Solved How custom draw?
-
My trial
void ColoredTextEdit::paintEvent(QPaintEvent *event) { QPainter painter(viewport()); QColor col; col.setRgb(255,255,0); col.setAlpha(128); QPen pen; pen.setStyle(Qt::PenStyle::NoPen); painter.setPen(pen); painter.setBrush(QBrush(col)); int h = document()->size().height(); painter.drawRect(0,2*h,viewport()->maximumWidth()-1,4*h); QTextEdit::paintEvent(event); }
I can't change pen and brush attributes before QTextEdit::paintEvent(event), I can' t also draw with brush; only if is empty editor. I can only draw with brush after paintEvent with alpha channel, but in this case colors are ugly.
-
Since you're in the
paintEvent
of the text edit you should only paint on the text edit i.e.QPainter painter(this)
. Qt will call 'paintEvent' on all of its children so whatever you draw will be overdrawn. Also drawing on a widget outside of its paint event is not recommended.If you want to draw on the viewport you need to implement the
paintEvent
in the viewport, not in the text edit.
If you don't want to replace the default viewport you can installEventFilter() on it and check for theQEvent::Paint
.Also, calling the default implementation after you're done is not recommended (unless that's what you really want) - it will overdraw anything you paint. You should call it before you start painting or not at all.
-
I do:
bool MainWindow::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::Paint) { bool ret = QObject::eventFilter(obj, event); QWidget* viewport = static_cast<QWidget*>(obj); QPainter painter(viewport); //the same QTextEdit *editor = static_cast<QTextEdit *>(viewport->parent()); QColor col; col.setRgb(255,255,0); //col.setAlpha(128); QPen pen; pen.setStyle(Qt::PenStyle::NoPen); painter.setPen(pen); painter.setBrush(QBrush(col)); auto size = editor->document()->size(); int h = editor->document()->size().height(); //painter.drawRect(0,2*h,viewport()->maximumWidth()-1,4*h); painter.drawRect(0,2*h,500,8*h); return ret; } else { // standard event processing return QObject::eventFilter(obj, event); } } editor->viewport()->installEventFilter(this);
Nearly works, but I can't get information about text height from editor object - height is above 14000. Ok - height is probably height of document, not line.