在 PyQt 中覆盖 QPaintEvents [英] Overriding QPaintEvents in PyQt

查看:69
本文介绍了在 PyQt 中覆盖 QPaintEvents的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个带有分隔线的 TextEdit 小部件.首先,我创建了一个 MyTextEdit 类(作为 QTextEdit 的子类)并覆盖了它的 paintEvent() 方法:

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

我做错了什么?

推荐答案

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

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

painter = QPainter(self.viewport())

这篇关于在 PyQt 中覆盖 QPaintEvents的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆