PDA

View Full Version : QTextDocument background colour



Ruud v A
16th May 2010, 17:21
Hello everyone,

I am writing a syntax highlighter with QPlainTextEdit, QSyntaxHighlighter and QTextDocument. I want to set the background colour of the editor. I successfully managed to set the background colour of the QPlainTextEdit, and I can set the background colour of individual text blocks with syntax highlighting. However, QTextDocument seems to render a little margin around the text. It renders a white border around the document. Also setting the background colour explicitly every time when highlighting seems unnecessary, it would be better to set the background colour of the entire document. I have tried to use setDefaultStyleSheet but that doesn't work. So how do I set the background colour of a QTextDocument?

Qt 4.6, Windows at the moment but should also apply to other platforms

Thanks in advance,

Ruud

elcuco
17th May 2010, 20:13
This needs to be done in a class which derives QTextEdit or QPlainTextEdit. Do this each time the cursor moves:



QTextCharFormat format;
format.setBackground(QColor(0xc0,0xff,0xc0,0x80));

QTextEdit::ExtraSelection selection;
selection.format.setProperty(QTextFormat::FullWidt hSelection, true);
selection.format = format;
selection.cursor = textCursor();
selection.cursor.clearSelection();

QList<QTextEdit::ExtraSelection> selections;
selections.append( selection );

setExtraSelections(selections);

The trick is QTextEdit::setExtraSelections() . Download the code of QtCreator for some more hidden gems.

Ruud v A
17th May 2010, 21:24
Thanks for the reply! Unfortunately it didn't work. I did find the solution myself after trying some more. The solution was quite simple actually. Instead of setting the default stylesheet for the document, setting the stylesheet of the QPlainTextEdit works:


textEdit->setStyleSheet("background-color: "+colour.name()+";");

Lykurg
17th May 2010, 21:44
You could also try to set a proper palette (QPalette::Base). Which is normally a lighter way compared to using style sheets.

Ruud v A
17th May 2010, 22:02
I did already set the palette, but that changed only the background colour of the area where there is no text (everything below the last line). The background of the text did not change.

Lykurg
17th May 2010, 22:30
Hm, a quick test in designer works for me. But if you are fine with the style sheets, no reason to dig deeper.

Ruud v A
18th May 2010, 14:30
It's probably the combination of a QPlainTextEdit with a QSyntaxHightlighter that causes the problem, but you are right, no need to search any further.