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?
The entire text can be selected using selectAll(). QPlainTextEdit holds a QTextDocument object which can be retrieved using the document() method. You can also set your own document object using setDocument().
If you want to set a selection in QPlainTextEdit just create one on a QTextCursor object and then make that cursor the visible cursor using setCursor() . The selection can be copied to the clipboard with copy() , or cut to the clipboard with cut() . The entire text can be selected using selectAll() .
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With