Search code examples
pyqt5qt5pyside2signals-slotsqobject

How to obtain the set of all signals for a given widget?


I am looking through the Qt documentation. Is there a quick and dirty way to get a list of all signals that a widget can emit.

For example (withPyQt):

allSignalsList = thisWidget.getSignals()

Alternatively, is there is a nice place on the new Qt5 API that shows all the signals for a given QObject?


Solution

  • There's no built-in method for listing signals, but normal python object introspection will get the information fairly easily:

    from PyQt5 import QtCore, QtWidgets
    
    def get_signals(source):
        cls = source if isinstance(source, type) else type(source)
        signal = type(QtCore.pyqtSignal())
        for subcls in cls.mro():
            clsname = f'{subcls.__module__}.{subcls.__name__}'
            for key, value in sorted(vars(subcls).items()):
                if isinstance(value, signal):
                    print(f'{key} [{clsname}]')
    
    get_signals(QtWidgets.QPushButton)
    

    Output:

    clicked [PyQt5.QtWidgets.QAbstractButton]
    pressed [PyQt5.QtWidgets.QAbstractButton]
    released [PyQt5.QtWidgets.QAbstractButton]
    toggled [PyQt5.QtWidgets.QAbstractButton]
    customContextMenuRequested [PyQt5.QtWidgets.QWidget]
    windowIconChanged [PyQt5.QtWidgets.QWidget]
    windowIconTextChanged [PyQt5.QtWidgets.QWidget]
    windowTitleChanged [PyQt5.QtWidgets.QWidget]
    destroyed [PyQt5.QtCore.QObject]
    objectNameChanged [PyQt5.QtCore.QObject]
    

    However, it's probably better to learn to use the Qt Documentation. If you go to the page for a Qt class, there's a Contents sidebar on the top-right which has links for the main member types. This usually includes a section for signals, but if it doesn't, you can drill down through the inherited classes until you find one.

    So for example, the QPushButton page doesn't show a signals section, but it inherits QAbstractButton, which does have one.