我在Qt Designer中创建了gui,然后使用pyuic4将其转换为python。现在我想在按钮上捕获鼠标悬停事件。
class window_b(QtGui.QDialog):
def __init__(self,parent=None):
super(window_b, self).__init__(parent)
window_a.setEnabled(False)
self.ui = Ui_Form_window_b()
self.ui.setupUi(self)
self.setFocusPolicy(QtCore.Qt.StrongFocus)
def mouseMoveEvent (self,event):
source= self.sender()
#print source.name()
# The action I want to do when the mouse is over the button:
source.setStyleSheet("background-color:#66c0ff;border-radius: 5px;")
我在窗口小部件上放了mouseMoveEvent
方法,我想检测Dialog上哪个按钮发送了mouseOver事件。我试过了source.name()
但它却抛出了这个错误
print source.name()
AttributeError: 'NoneType' object has no attribute 'name'
任何建议。
答案 0 :(得分:2)
sender()
仅对信号有用,但鼠标悬停是一个事件而非信号(实际上是2个事件:QEvent.Enter
和QEvent.Leave
)。
为了能够处理接收它们的按钮之外的事件,您需要将window_b
实例安装为每个按钮的事件过滤器。
class window_b(QtGui.QDialog):
def __init__(self,parent=None):
super(window_b, self).__init__(parent)
window_a.setEnabled(False)
self.ui = Ui_Form_window_b()
self.ui.setupUi(self)
self.setFocusPolicy(QtCore.Qt.StrongFocus)
# Get all the buttons (you probably don't want all of them)
buttons = self.findChildren(QtGui.QAbstractButton)
for button in buttons:
button.installEventFilter(self)
def eventFilter(self, obj, event):
if event.type() == QtCore.QEvent.Enter:
print("mouse entered %s" % obj.objectName())
elif event.type() == QtCore.QEvent.Leave:
print("mouse leaved %s" % obj.objectName())
return super(window_b, self).eventFilter(obj, event)
如果您只需要更改样式,则只需在样式表中使用伪状态“:hover”(来自设计器,或者使用self.setStyleSheet
的构造函数):
QPushButton {
border: 1px solid black;
padding: 5px;
}
QPushButton:hover {
border: 1px solid black;
border-radius: 5px;
background-color:#66c0ff;
}