簡體   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