Unable to use drawContents inside a QTextEdit
-
I have a class that include a reference to a QTextEdit and a QPainter object initialized as following:
class MyClass : QObject { QWidget &parent; Ui::MainWindow &ui; QPaint painter; ... } MyClass::MyClass() : painter(ui.textEdit) { connect(ui.textEdit, &QTextEdit::cursorPositionChanged, this, &MyClass::cursorPositionChanged); painter.setPen(Qt::yellow); }
And this is the slot connected to the signal:
void MyClass::cursorPositionChanged() { QRect cursorRect = ui.textEdit->cursorRect(); painter.drawRect(cursorRect); ui.textEdit->document()->drawContents(&painter); }
Once I move the cursor inside the QTextEdit document the output is:
QPainter::drawRects: Painter not active QPainter::save: Painter not active QPainter::pen: Painter not active QPainter::setPen: Painter not active QPainter::pen: Painter not active QPainter::setPen: Painter not active QPainter::pen: Painter not active QPainter::setPen: Painter not active QPainter::setPen: Painter not active QPainter::setPen: Painter not active QPainter::restore: Unbalanced save/restore
and it doesn't paint anything in the document. What I'm missing?
-
Hi,
You can't paint on a widget in an arbitrary manner like you do. And you can't paint on a widget from an arbitrary source either.
What exactly do you want to achieve ?
-
I need to paint the current cursor in the document
-
[EDITED]
A QPainter must bebegin()
ed / constructed with a QPaintDevice to use.
And if the device is a widget, then it need to bebegin()
ed / constructed and used only in its paintEvent.
So ifdrawContents
is not called in a widget's paintEvent, it is usually used to draw the document to another QPaintDevice, like an image or a pdf.
Here I even don't know what do you want to paint on since you never set any QPaintDevice to the painter. -
@anphetamina said in Unable to use drawContents inside a QTextEdit:
I need to paint the current cursor in the document
QTextEdit already draws the cursor where it is so that's a bit strange. Can you give more details ?
-
What do you mean by on demands ?
What kind of line ? -
@anphetamina said in Unable to use drawContents inside a QTextEdit:
but I need to draw more lines on demand, is that possible?
Then draw more lines in paintEvent() ...