I made the gui in Qt Designer and then converted it into python using pyuic4. Now i want to capture the mouseover event on the buttons.
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;")
I put the mouseMoveEvent
method on the widget and I want to detect which button on the Dialog sent the mouseOver event. I tried source.name()
but it throws me this error
print source.name()
AttributeError: 'NoneType' object has no attribute 'name'
Any suggestion.
sender()
is only useful for signals but the mouse hovering is an event not a signal (actually 2 events: QEvent.Enter
and QEvent.Leave
).
And to be able to handle events outside the buttons that received them, you need to install your window_b
instance as an event filter for each button.
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)
If you only need to change the style, you can simply use the pseudo-state ":hover" in a stylesheet (from the designer, or in the constructor with self.setStyleSheet
):
QPushButton {
border: 1px solid black;
padding: 5px;
}
QPushButton:hover {
border: 1px solid black;
border-radius: 5px;
background-color:#66c0ff;
}