views:

177

answers:

2

I am creating a small PyQt application and got stuck up in MouseOver effect.

I have a QMainWindow which has three buttons named createProfileButton, downloadPackagesButton and installPackagesButton. All these are of type QPushButton

Now I have created a Label which will hold the text when someone hovers the mouse over any of these button. I checked the documentation and came to know that it can be handled using over-riding

  • focusInEvent(self, QFocusEvent)
  • focusOutEvent(self, QFocusEvent)

methods of the button. Now this means that I have to extend QPushButton for each of the three buttons and each one of them have to an object for one class. I tried hunting for the signal which is emitted when mouse is hovered or taken away from the button, but in vain. All help I got on the net was to implement these two methods.

Isnt extending a class and creating one of each an overkill? A signal would be neat, unfortunately, I couldn't find any signal.

So I checked the whole inheritance hierarchy and found no signal for FocusIn and FocusOut

+4  A: 

As you stated, no signals exist for this functionality. You have two basic options.

Option 1 - Subclass:

class FocusEmittingButton(QPushButton):
    #...
    def focusInEvent(self, event):
        # emit your signal

You can then connect to that signal in your client code. Also, if necessary, you can use designer's Promote To feature to promote each button to the FocusEmittingButton type. You'll only need to subclass once, and then make sure the different buttons are all of the same type.

Option 2 - Use QApplication.focusChanged

You can also leverage QApplication.focusChanged(oldQWidget, newQWidget). By doing so, you won't need to subclass and override the focus events. Instead, you connect to the QApplication.focusChanged signal and then respond in a handler.

Kaleb Pederson
I meant that this is the only way I could add Focus events. I again said that I wanted to use signals and not Event methods. I don't want to subclass one class for each button.
Manish Sinha
There is no signal for focus as you stated yourself, you have to either subclass QPushButton (once not one for each instance) to send a signal when it gets focus, or use QApplication.focusChanged as Kaleb said.
Adam W
@Manish - I see what you're getting at. I've edited my answer to clarify how you would subclass. If option 2 isn't clear enough, let me know.
Kaleb Pederson
Thanks Kaleb, now the explanation is more clear. I will try out and tell you in ASAP
Manish Sinha
A: 

There is another way to receive focus signals in a parent widget. You can add an event filter:

class MyParent(QWidget):
    def __init__(self):
        ...
        self.mybutton.installEventFilter()

    def eventFilter(self, obj, event):
        if obj is self.mybutton and event.type() == qt4.QEvent.FocusOut:
           ...
        return qt4.QWidget.eventFilter(self, obj, event)
xioxox