覆盖PyQt中的QPaintEvents

Dmi*_*nev 5 qt qt4 pyqt pyqt4 qtgui

我正在尝试创建一个具有分隔符行的TextEdit小部件.首先,我创建了一个MyTextEdit类(作为a的子类QTextEdit)并重写了它的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_())
Run Code Online (Sandbox Code Playgroud)

尝试执行此代码,我收到了很多以下错误:

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
...
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

ekh*_*oro 7

如果窗口小部件有视口,则必须将其传递给QPainter构造函数:

painter = QPainter(self.viewport())
Run Code Online (Sandbox Code Playgroud)