2

I have a QTextBrowser that displays lines of QString and an Int. The messages looks something like this:

Message a counter 1

Message a counter 2

Message a counter 3

Message b counter 1

Instead of always appending a new line for each incrementation of the counter I want to just increment the Int in the last message (the last line). What is the most efficient way to do this?

I came up with this code to remove only the last line in the 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));

Unfortunately this leaves me with an empty line after removing the last line which looks very ugly. What is the best way to achieve this that doesn't involve clearing the whole QTextBroswerand appending each line again.

Community
  • 1
  • 1
testus
  • 183
  • 2
  • 21
  • Would you be OK with deleting the last line and reappending? I can give you code for that if that is okay... – László Papp Dec 29 '14 at 13:39
  • Yes thats what I am trying to do. The way I did it in my example I am left with an empty line after deleting the last line which doesn't look nice. – testus Dec 29 '14 at 13:44

1 Answers1

6

Here is my solution, but mind you that it requires C++11 and Qt 5.4 at least to build and run. However, the concept is there that you can copy and paste out without using QTimer requiring those versions above:

main.cpp

#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();
}

main.pro

TEMPLATE = app
TARGET = main
QT += widgets
CONFIG += c++11
SOURCES += main.cpp

Build and Run

qmake && make && ./main
László Papp
  • 51,870
  • 39
  • 111
  • 135