QPlainTextEdit truncate history linewise
-
15-06-2021 - |
Question
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?
Solution
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 themaximumBlockCount
property. The combination ofsetMaximumBlockCount()
andappendPlainText()
turnsQPlainTextEdit
into an efficient viewer for log text.
For reference:
OTHER TIPS
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.