[英]Trigger a paint event inside the enter event in Qt
Q: I am trying to trigger a paint event inside the enter event in Qt but I am getting an error, basically can't call the painter inside the enter mouse event.问:我试图在 Qt 的 enter 事件中触发一个绘制事件,但是我得到一个错误,基本上不能在 enter mouse 事件中调用painter。 What I need is to darken the image(as button) as I hover the mouse.我需要的是在鼠标悬停时使图像变暗(作为按钮)。 Is this even possible?这甚至可能吗? Thank you.谢谢你。
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()
Ok, I solved the problem with underMouse()
within the paintEvent
.好的,我解决了paintEvent
中的underMouse()
的问题。 Not sure if it's the best solution but it's working now.不确定这是否是最好的解决方案,但它现在正在工作。 Just wish I was able to brighten the image instead of darkening.只希望我能够使图像变亮而不是变暗。
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.