Search code examples
c++qtqwidgetqtcoreqt-signals

List of available signals at runtime


I need to get list of available signals from particular QWidget at runtime.

For example, the QWidget is QPushButton and I'd like to get this list:

"clicked()"
"pressed()"
"released()"
"toggled()"
"destroyed()"
...

Can you give me a hint how to do that? Thank you


Solution

  • This is the code to get all the signals in the inheritance tree. It would be easy to adjust to your needs should you not need all of them:

    main.cpp

    #include <QStringList>
    #include <QApplication>
    #include <QPushButton>
    #include <QMetaObject>
    #include <QMetaMethod>
    #include <QDebug>
    
    int main(int argc, char **argv)
    {
        QApplication application(argc, argv);
        QPushButton pushButton;
        const QMetaObject* metaObject = pushButton.metaObject();
        do {
            for (int i = metaObject->methodOffset(); i < metaObject->methodCount(); ++i) {
                QMetaMethod metaMethod = metaObject->method(i);
                if (metaMethod.methodType() == QMetaMethod::Signal)
                    qDebug() << metaMethod.methodSignature();
            }
        } while ((metaObject = metaObject->superClass()));
        return application.exec();
    }
    

    main.pro

    TEMPLATE = app
    TARGET = main
    QT += widgets
    SOURCES += main.cpp
    

    Build and Run

    qmake && make && ./main
    

    Output

    "pressed()"
    "released()"
    "clicked(bool)"
    "clicked()"
    "toggled(bool)"
    "windowTitleChanged(QString)"
    "windowIconChanged(QIcon)"
    "windowIconTextChanged(QString)"
    "customContextMenuRequested(QPoint)"
    "destroyed(QObject*)"
    "destroyed()"
    "objectNameChanged(QString)"