QPlainTextEdit truncate history linewise
Asked Answered
D

2

15

I have a GUI application whose main part is a QPlainTextEdit. It is used to display a log of the application, and as such the associated text grows line by line ad infinitum.

As the application is intended to run very long, I need to limit the memory that will be allocated for this log. Therefore I want to have some maxNumLines or maxNumCharacters parameter that will make sure the history will be truncated when reached, i.e. the head lines will be removed as new lines are appended (a.k.a. log rotation).

To achieve this I found the functions

// get the associated text
QString toPlainText () const

// set the associated text
void setPlainText ( const QString & text )

Therefore something like this untested code would probably do the trick:

QString &tmp = pte.toPlainText();
while (tmp.size() > maxNumCharacters) {
  // remove lines from the head of the string until the desired size is reached
  // removes nothing if "\n" could not be found
  tmp.remove(0, tmp.indexOf("\n")+1);
}
pte.setPlainText( tmp );

Is this the way to go to remove the first line(s) from the QPlainTextEdit? Are there probably other Qt Text GUI elements that would better fit to this task (set a maximum number of lines and truncate at the head of the list), e.g. somehow display a QStringList in which I could store the lines (s.t. I could easily erase(0))?

Or does the QPlainTextEdit eventually implement such upper bound for the size of the associated QString after all?

Demerit answered 19/6, 2012 at 9:14 Comment(0)
D
20

Apparantly the property maximumBlockCount is exactly what I need:

If you want to limit the total number of paragraphs in a QPlainTextEdit, as it is for example useful in a log viewer, then you can use the maximumBlockCount property. The combination of setMaximumBlockCount() and appendPlainText() turns QPlainTextEdit into an efficient viewer for log text.

For reference:

Demerit answered 20/6, 2012 at 9:33 Comment(1)
Thanks for sharing. I was previously using cursor based insertion, but I discovered that append* methods will provide much higher performances.Blubber
Y
9

I had exactly the same problem a months back, and I ended up using a QListView. Although using the model/view/delegate architecture is a bit more fiddly, it scales much better in the long run. For example once the basic architecture is in place, adding a filter that displays only error or warning entries becomes trivial, or creating a delegate so that the background of error entries are painted red is also straightforward.

Yovonnda answered 19/6, 2012 at 9:24 Comment(1)
see also: QListWidgetTetragram

© 2022 - 2024 — McMap. All rights reserved.