Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding QPaintEvents in PyQt

I'm trying to create a TextEdit widget that will have a delimiter line. As a start, I've created a MyTextEdit class (as a subclass of a QTextEdit) and overridden its paintEvent() method:

import sys
from PyQt4.QtGui import QApplication, QTextEdit, QPainter

class MyTextEdit(QTextEdit):
    """A TextEdit widget derived from QTextEdit and implementing its
       own paintEvent"""

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.drawLine(0, 10, 10, 10)
        QTextEdit.paintEvent(self, event)

app = QApplication(sys.argv)
textEdit = MyTextEdit()
textEdit.show()

sys.exit(app.exec_())

Trying to execute this code, I get lots of the following errors:

QPainter::begin: Widget painting can only begin as a result of a paintEvent
QPainter::begin: Widget painting can only begin as a result of a paintEvent
...

What am I doing wrong?

like image 580
Dmitry Shachnev Avatar asked Sep 01 '12 10:09

Dmitry Shachnev


1 Answers

If a widget has a viewport, you have to pass that to the QPainter constructor:

painter = QPainter(self.viewport())
like image 118
ekhumoro Avatar answered Oct 17 '22 00:10

ekhumoro