testus
testus

Reputation: 183

Change last line in QTextBrowser

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.

Upvotes: 2

Views: 1519

Answers (1)

László Papp
László Papp

Reputation: 53173

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

Upvotes: 6

Related Questions