pythonpyqtfocussignals-slotsqpushbutton

QPushButton tab highlight signal


I'm using PyQt to design an app. For accessibility reasons, I want to speak the name of a button when it is highlighted (using navigation by tab key.)

I have the speech down okay using Windows Speech API. Now I want to use signals and slots, but QPushButton doesn't seem to have a signal for when it is highlighted. The ones I have found are clicked, destroyed, pressed, released, toggled. None of them work.

Is there any way to set up a custom signal that will be emitted when the button is highlighted by tab?


Solution

  • The QApplication is responsible for managing widget focus, so you could connect to its focusChanged signal:

        QtGui.qApp.focusChanged.connect(self.handleFocusChanged)
    

    The signal sends references to the previous/current widget that has lost/received the focus (by whatever means), so the handler might look like this:

        def handleFocusChanged(self, old, new):
            if old is not None and new is not None:
                if isinstance(new, QtGui.QPushButton):
                    print('Button:', new.text())
                elif isinstance(new, QtGui.QLineEdit):
                    print('Line Edit:', new.objectName())
                # and so forth...
    

    You can also get the widget that currently has the focus using:

        widget = QtGui.qApp.focusWidget()