سؤال

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?

هل كانت مفيدة؟

المحلول

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

painter = QPainter(self.viewport())
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top