DylanM
DylanM

Reputation: 343

How to append to QTextEdit without using the current paragraph style

When using myQTextEdit.append() the style of the inserted text is as follows (Qt 5.14 documentation):

"The new paragraph appended will have the same character format and block format as the current paragraph, determined by the position of the cursor."

However I would find it convenient to be able to append text with a neutral style.

What causes my problem is this: I have a log window in the form of a QTextEdit where I append text (mostly neutral but some element may be coloured, etc.). Since it's for log purposes, the QTextEdit is read-only and the text elements are always added at the end (append()). This is fine as long as the user never clicks on the text. When clicking on a part of the QTextEdit, the cursor position is changed. It's not an issue for the position since I use append() which inserts text at the end, even if the cursor is somewhere else. However, if the user clicked on something with a non-neutral style, the afterwards appended text will have this style as well, which is not desirable.

What would be interesting for me would be to either block the cursor so that the user can't tamper with the styles or to append without basing the style on the current paragraph.

Is there a way to change this behaviour, other than by subclassing QTextEdit?

As mentioned, I could check the cursor position before doing any append() (and set the cursor at the end of the document if it has been moved) but if it exists, I would prefer a more "global" solution.

Upvotes: 1

Views: 1684

Answers (1)

Scheff's Cat
Scheff's Cat

Reputation: 20141

I tried to reproduce in an MCVE what OP described:

// Qt header:
#include <QtWidgets>

// main application
int main(int argc, char **argv)
{
  qDebug() << "Qt Version:" << QT_VERSION_STR;
  QApplication app(argc, argv);
  // setup GUI
  QTextEdit qTextEdit;
  qTextEdit.show();
  // populate text editor
  qTextEdit.append(QString::fromUtf8(
    "<p>This is some text...</p>"
    "<p style='color: red'>...followed by more red text...</p>"
    "<p style='color: blue; font-weight: bold'>...followed by more fat blue text.</p>"));
  // test QTextEdit::append() like described by OP:
  qTextEdit.setTextCursor(QTextCursor(qTextEdit.document()->findBlockByNumber(1)));
  qTextEdit.append("TEST. (Reproduce what OP described.)");
  qTextEdit.append("<p>TEST. (A possible fix.)</p>");
  // runtime loop
  return app.exec();
}

Output:

snapshot of MCVE

So, a possible fix is to provide the text to append with mark-up.

If it's just raw text the simplest solution is to wrap it in "<p>" and "</p>".

Btw. if it's just raw text I would recommend some additional adjustments to make it proper HTML according to the Supported HTML Subset. Namely, I would search and replace the usual XML meta characters like I did it e.g. in my answer to SO: qt plaintextedit change message color.

Upvotes: 1

Related Questions