[Solved] Glitchy painting over QTextEdit
-
Hello.
I need to draw over QTextEdit. In the example below (Qt version is 5) I want to draw just single red line on fixed position:@
// main.cpp
#include "widget.h"
#include <QApplication>int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();return a.exec();
}
@@
// widget.h
#ifndef WIDGET_H
#define WIDGET_H#include <QTextEdit>
#include <QPainter>class Widget : public QTextEdit
{
Q_OBJECTpublic:
Widget(QWidget* parent = 0);
void paintEvent(QPaintEvent* event);
};#endif // WIDGET_H
@@
// widget.cpp
#include "widget.h"Widget::Widget(QWidget* parent)
: QTextEdit(parent)
{
setFixedSize(100,100);
setUndoRedoEnabled(false);
setReadOnly(true);
setLineWrapMode(QTextEdit::NoWrap);
setAttribute(Qt::WA_OpaquePaintEvent);for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) insertPlainText( QString("line %1 ").arg(i+1) ); insertPlainText("\n"); }
}
void Widget::paintEvent(QPaintEvent* event)
{
QTextEdit::paintEvent(event);
QPainter painter(viewport());
painter.setPen( QColor(255,0,0) );
painter.drawLine(10, 10, 30, 30);
}
@It seems to work good until I use scrollbars. Scrolling causes partial line drawing, multiple line drawing e.t.c. Maybe drawing over scroll area requires some special actions to do?
-
Yes you have to update your viewport. But this seems to be an windows only thing.
On OSX everthing looks fine.
Putting that line in your paint event solves the problem but that is no good idea.
@viewport()->update();@
In general you should not paint on other widgets in paintEvents.
-
Yes, I'm on windows (8.1 x64). Using "viewport()->update()" solves the problem but the program starts to eat a lot of CPU. So I need another solution.
-
As i mentioned above it is in general no good idea to draw on another widget in paint event.
In you code you do that !
To solve you problem you could either create an overlay widget, that you then put together with your QTextEdit in a QGridLayout.
Or you can set your own viewport widget.
I have not tested this but i think these are two possibilities that should work.
-
Got it. Thank you.
-
This code works: "overlay":http://developer.nokia.com/community/wiki/Archived:How_to_overlay_QWidget_on_top_of_another