Is it possible to connect a signal to a static slot without a receiver instance?

前端 未结 3 1420
天命终不由人
天命终不由人 2020-12-01 17:44

Is it possible to connect a signal to static slot without receiver instance?

Like this: connect(&object, SIGNAL(some()), STATIC_SLOT(staticFooMember()));

相关标签:
3条回答
  • 2020-12-01 18:20

    In earlier versions of Qt, although you cannot do so as mentioned by @UmNyobe but you can do something like this if you really want to call that static slot :

    connect(&object, SIGNAL(some()), this, SLOT(foo()));
    
    void foo()
    {
        .... //call your static function here.
    }
    
    0 讨论(0)
  • 2020-12-01 18:29

    Update for QT5: Yes you can

    static void someFunction() {
        qDebug() << "pressed";
    }
    // ... somewhere else
    QObject::connect(button, &QPushButton::clicked, someFunction);
    

    In QT4 you can't:

    No it is not allowed. Rather, it is allowed to use a slot which is a static function, but to be able to connect it you need an instance.

    In their example,

    connect(exitAct, SIGNAL(triggered()), qApp, SLOT(closeAllWindows()));
    

    means than they previously called

    QApplication* qApp = QApplication::instance();
    

    Edit:

    The only interface for connecting object is the function

    bool QObject::connect ( const QObject * sender, const QMetaMethod & signal, const QObject * receiver, const QMetaMethod & method, Qt::ConnectionType type = Qt::AutoConnection )
    

    How are you going to get rid of const QObject * receiver?

    Check the moc files in your project, it speaks by itself.

    0 讨论(0)
  • 2020-12-01 18:31

    It is. (With Qt5)

    #include <QApplication>
    #include <QDebug>
    
    void foo(){
        qDebug() << "focusChanged";
    }
    
    
    int main(int argc, char *argv[]) {
        QApplication app(argc, argv);
        QObject::connect(&app, &QApplication::focusChanged, foo);
        return app.exec();
    }
    
    0 讨论(0)
提交回复
热议问题