I have a QTextEdit
where the user can edit QTextDocument
s.
I want to set the default color and font for the document, however, the format is discarded when there is no text in the doucment.
Here's my code:
QTextDocument *d = new QTextDocument;
QTextCursor cur(d);
cur.select(QTextCursor::Document);
QTextBlockFormat f1;
f1.setBackground(Qt::black);
f1.setForeground(Qt::yellow);
cur.setBlockFormat(f1);
QTextCharFormat f2;
f2.setForeground(Qt::yellow);
QFont font("Times New Roman", 12);
f2.setFont(font);
cur.setBlockCharFormat(f2);
editor->setDocument(d);
When the editor is displayed, I see a line with black background, with a certain height. So it seems that this worked.
However, as soon as I start typing, the line size is decreased and I don't see any text. When selecting the entered text, I can see that is written black (on black background), and it's font is changed.
When I insert some non-empty text using the cursor, everything works, and the format is not changed on editing:
// Same as above...
cur.insertText("A");
editor->setDocument(d);
Is there a way that the editor keeps the format, without inserting dummy text?
I cannot use a stylesheet, or palette on the editor, as mentioned in other questions to this topic. All has to be done direclty using QTextFormat
s
I have finally found the solution by myself.
The problem was that the editor's cursor did not have the required style information, and was inserting text with the default style. The editor's cursor has to be updated.
The solution is simply to move the cursor to the beginning of the document, where it will fetch the style:
// Build document as required...
editor->setDocument(d);
// This fixes the problem:
QTextCursor editorCursor = editor->textCursor();
editorCursor.movePosition(QTextCursor::Start);
editor->setTextCursor(editorCursor);