tes*_*tus 1 c++ qt qtgui qtextbrowser qtextcursor
我有一个QTextBrowser显示行QString和Int.消息看起来像这样:
给柜台留言1
给柜台留言2
给柜台留言3
消息b计数器1
而不是总是为计数器的每个增量添加一个新行,我想只增加Int最后一条消息(最后一行).最有效的方法是什么?
我想出了这个代码,只删除了最后一行QTextBrowser:
ui->outputText->append(messageA + QString::number(counter));
ui->outputText->moveCursor( QTextCursor::End, QTextCursor::MoveAnchor );
ui->outputText->moveCursor( QTextCursor::StartOfLine, QTextCursor::MoveAnchor );
ui->outputText->moveCursor( QTextCursor::End, QTextCursor::KeepAnchor );
ui->outputText->textCursor().removeSelectedText();
ui->outputText->append(messageA + QString::number(++counter));
Run Code Online (Sandbox Code Playgroud)
不幸的是,在删除看起来非常丑陋的最后一行之后,这给我留下了空行.实现这一目标的最佳方法是什么,不涉及清除整体QTextBroswer并再次附加每一行.
这是我的解决方案,但请注意,它至少需要C++ 11和Qt 5.4来构建和运行.但是,您可以在不使用QTimer上述版本的情况下复制和粘贴概念:
#include <QApplication>
#include <QTextBrowser>
#include <QTextCursor>
#include <QTimer>
int main(int argc, char **argv)
{
QApplication application(argc, argv);
int count = 1;
QString string = QStringLiteral("Message a counter %1");
QTextBrowser *textBrowser = new QTextBrowser();
textBrowser->setText(string.arg(count));
QTimer::singleShot(2000, [textBrowser, string, &count](){
QTextCursor storeCursorPos = textBrowser->textCursor();
textBrowser->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor);
textBrowser->moveCursor(QTextCursor::StartOfLine, QTextCursor::MoveAnchor);
textBrowser->moveCursor(QTextCursor::End, QTextCursor::KeepAnchor);
textBrowser->textCursor().removeSelectedText();
textBrowser->textCursor().deletePreviousChar();
textBrowser->setTextCursor(storeCursorPos);
textBrowser->append(string.arg(++count));
});
textBrowser->show();
return application.exec();
}
Run Code Online (Sandbox Code Playgroud)
TEMPLATE = app
TARGET = main
QT += widgets
CONFIG += c++11
SOURCES += main.cpp
Run Code Online (Sandbox Code Playgroud)
qmake && make && ./main
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
689 次 |
| 最近记录: |