在PyQt中重写QPaintEvents

在PyQt中重写QPaintEvents,qt,qt4,pyqt,pyqt4,qtgui,Qt,Qt4,Pyqt,Pyqt4,Qtgui,我正在尝试创建一个文本编辑小部件,它将有一个分隔线。首先,我创建了一个MyTextEdit类(作为QTextEdit的子类),并重写了它的paintEvent()方法: import sys from PyQt4.QtGui import QApplication, QTextEdit, QPainter class MyTextEdit(QTextEdit): """A TextEdit widget derived from QTextEdit and implementing i

我正在尝试创建一个文本编辑小部件,它将有一个分隔线。首先,我创建了一个
MyTextEdit
类(作为
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_())
尝试执行此代码时,我收到大量以下错误:

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
...
我做错了什么?

如果一个小部件有一个

painter = QPainter(self.viewport())

有趣的是,我不明白为什么那不起作用。那个视口总是把我搞砸。谢谢