繁体   English   中英

在 Qt 的 enter 事件中触发绘制事件

[英]Trigger a paint event inside the enter event in Qt

问:我试图在 Qt 的 enter 事件中触发一个绘制事件,但是我得到一个错误,基本上不能在 enter mouse 事件中调用painter。 我需要的是在鼠标悬停时使图像变暗(作为按钮)。 这甚至可能吗? 谢谢你。

from PySide2 import QtWidgets
from PySide2 import QtGui
from PySide2 import QtCore

class PicButton(QtWidgets.QAbstractButton):
    def __init__(self, pixmap, parent=None):
        super(PicButton, self).__init__(parent)
        self.pixmap = pixmap

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.drawPixmap(event.rect(), self.pixmap)
        
        painter.fillRect(event.rect(), QtGui.QBrush(QtGui.QColor (0,0,0,0)))  
        
    def enterEvent(self, event):
        #error with the line below: 'PySide2.QtGui.QEnterEvent' object has no attribute 'rect'
        #painter.fillRect(event.rect(), QtGui.QBrush(QtGui.QColor (0,0,0,128)))  
        
        print('hovering')

    def sizeHint(self):
        return self.pixmap.size()

window_wid = QtWidgets.QWidget()
vlayout_wid = QtWidgets.QVBoxLayout()

myPixmap = QtGui.QPixmap("image.jpg")

my_button = PicButton(myPixmap)
my_button.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
my_button.setMaximumSize(200,100)


vlayout_wid.addWidget(my_button)

window_wid.setLayout(vlayout_wid)
window_wid.show()

在此处输入图像描述

好的,我解决了paintEvent中的underMouse()的问题。 不确定这是否是最好的解决方案,但它现在正在工作。 只希望我能够使图像变亮而不是变暗。

from PySide2 import QtWidgets
from PySide2 import QtGui
from PySide2 import QtCore

class PicButton(QtWidgets.QAbstractButton):
    def __init__(self, pixmap,  parent=None):
        super(PicButton, self).__init__(parent)
        self.pixmap = pixmap

        self.pressed.connect(self.update)
        self.released.connect(self.update)

    def paintEvent(self, event):
        #pix = self.pixmap_hover if self.underMouse() else self.pixmap

        painter = QtGui.QPainter(self)
        
        painter.drawPixmap(event.rect(), self.pixmap)
        
        
        pix = painter.fillRect(event.rect(), QtGui.QBrush(QtGui.QColor (0,0,0,128)))  if self.underMouse() else self.pixmap

    def enterEvent(self, event):
        self.update()
        
    def leaveEvent(self, event):
        self.update()
                
    def sizeHint(self):
        return QtCore.QSize(200, 100)

        
window_wid = QtWidgets.QWidget()
vlayout_wid = QtWidgets.QVBoxLayout()

pixmap = QtGui.QPixmap("image.jpg")

my_button = PicButton(pixmap)
my_button.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
#my_button.setMaximumSize(200,100)


vlayout_wid.addWidget(my_button)

window_wid.setLayout(vlayout_wid)
window_wid.show()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM