5

我正在尝试创建一个具有分隔线的 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_())

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

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
...

我究竟做错了什么?

4

1 回答 1

7

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

painter = QPainter(self.viewport())
于 2012-09-01T16:07:40.817 回答