Overriding QPaintEvents in PyQt

2019-02-17 18:10发布

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?

1条回答
啃猪蹄的小仙女
2楼-- · 2019-02-17 19:00

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

painter = QPainter(self.viewport())
查看更多
登录 后发表回答