在悬停事件时激活QPainter

时间:2017-02-09 19:10:39

标签: python qt user-interface pyqt pyqt4

以下是一些说明我问题的代码:

import sys
from PyQt4 import QtGui, QtCore


class CustomButton(QtGui.QAbstractButton):
    def __init__(self, *__args):
        super().__init__(*__args)
        self.setFixedSize(190, 50)
        self.installEventFilter(self)

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.setBrush(QtGui.QColor(136, 212, 78))
        painter.setPen(QtCore.Qt.NoPen)
        painter.drawRect(QtCore.QRect(0, 0, 100, 48))

    def eventFilter(self, object, event):
        if event.type() == QtCore.QEvent.HoverMove:
            painter = QtGui.QPainter(self)
            painter.begin(self)
            painter.drawRect(QtCore.QRect(0, 0, 100, 48))
            painter.end()
            return True
        return False

app = QtGui.QApplication(sys.argv)
window = QtGui.QWidget()
layout = QtGui.QGridLayout(window)

button = CustomButton()
layout.addWidget(button, 0, 0)

window.show()
sys.exit(app.exec_())

目标是使用QPainter创建一个按钮,可以在检测到HoverMove事件时修改该按钮。但是,我在悬停时遇到以下错误:

QPainter::begin: Paint device returned engine == 0, type: 1
QPainter::begin: Paint device returned engine == 0, type: 1
QPainter::drawRects: Painter not active
QPainter::end: Painter not active, aborted

根据我对文档(here)的理解,我可以使用.begin()来激活QPainter;但是,因为错误消息显示不是这种情况,并且不会绘制第二个矩形。我应该如何使用QPainter来实现所需的输出?

2 个答案:

答案 0 :(得分:1)

您需要检测paintEvent内的悬停并采取相应措施:

    def paintEvent(self, event):
        option = QtGui.QStyleOptionButton()
        option.initFrom(self)
        painter = QtGui.QPainter(self)
        if option.state & QtGui.QStyle.State_MouseOver:
            # do hover stuff ...
        else:
            # do normal stuff ...

QStyleOption及其子类包含QStyle函数绘制图形元素所需的所有信息。 QPaintEvent仅包含有关需要更新的区域的信息。

答案 1 :(得分:0)

@ekhumoro's answer above可以使用QWidget::underMouse()更简单地重写。 the docs

    def paintEvent(self, event):
        if underMouse():
            # do hover stuff ...
        else:
            # do normal stuff ...