Overriding QPaintEvents in PyQt

I am trying to create a TextEdit widget with a dividing line. In the beginning, I created a class MyTextEdit(as a subclass QTextEdit) and redefined its method paintEvent():

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?

+5
source share
1 answer

If the widget has a viewport , you must pass this to the constructor QPainter:

painter = QPainter(self.viewport())
+7
source

All Articles