5

I have a Qt "Text Edit" widget in my Gui and this widget is used to log something. I add every line(s) this way:

QString str;
str = ...
widget.textEdit_console->append(str);

by this way the Text Edit height will increase more and more after each new line. I want it act like a terminal in this case, I mean after some number (that I set) of lines entered, for each new line the first line of Text Edit being deleted to prevent it being too big! should I use a counter with every new line entered and delete the first ones after counter reached it's top or there is better way that do this automatically after

widget.textEdit_console->append(str);

called ?

ildjarn
  • 62,044
  • 9
  • 127
  • 211
blackfox
  • 71
  • 1
  • 6
  • If you are creating a logger, you should use a `QListWidget` (or equivalent). That way each log entry is a discrete unit rather than the whole thing being a monolithic block of text. Adding functionality like what you want becomes very simple as well. – cmannett85 Apr 14 '13 at 10:23
  • @cmannett85: Now that you mention it, it's the obvious solution. – TonyK Apr 14 '13 at 10:30

3 Answers3

2

thank cmannett85 for your advise but for some reason I prefer 'Text Edit', I solved my problem this way:

void mainWindow::appendLog(const QString &str)
{
    LogLines++;
    if (LogLines > maxLogLines)
    {
        QTextCursor tc = widget.textEdit_console->textCursor();
        tc.movePosition(QTextCursor::Start);
        tc.select(QTextCursor::LineUnderCursor);
        tc.removeSelectedText(); // this remove whole first line but not that '\n'
        tc.deleteChar(); // this way the first line will completely being removed
        LogLines--;
    }
    widget.textEdit_console->append(str);
}

I still don't know is there any better more optimized way while using 'Text Edit'

Community
  • 1
  • 1
blackfox
  • 71
  • 1
  • 6
0

One simple way is to turn the vertical scroll-bar off:

 textEdit_console->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
s4eed
  • 7,173
  • 9
  • 67
  • 104
  • That won't automatically delete the first line, will it? The user will be able to bring it into view by simply cursoring up to it. – TonyK Apr 14 '13 at 10:26
  • @TonyK ~> You're right. But I said it's the simplest way :). I'll edit my answer. – s4eed Apr 14 '13 at 10:30
0

This code move cursor to the first line and then select it until end of line, next it will delete the line:

widget.textEdit->moveCursor(QTextCursor::Start, QTextCursor::MoveAnchor);
widget.textEdit->moveCursor(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
widget.textEdit->textCursor().deleteChar();
widget.textEdit->textCursor().deleteChar();
masoud
  • 55,379
  • 16
  • 141
  • 208