Using any c++ function as a Qt slot

后端 未结 5 1188
太阳男子
太阳男子 2021-01-17 11:54

Is there a way to use any C++ function as a Qt slot, without having its class inheriting from QWidget?

5条回答
  •  情深已故
    2021-01-17 12:25

    Since Qt 5, functors and lambda expressions can be used as slot (as previously mentioned, here: http://qt-project.org/wiki/New_Signal_Slot_Syntax).

    As I could not find example code, I added the following:

    This example uses boost::function for a class member ClassName::classMember() without parameters.

        boost::function f= boost::bind(&ClassName::classMember, classInstance);
        connect(QObjectInstance, &QObject::signalName, f);
    

    When the Qt signal and class member have parameters (for instance ClassName::classMember(int)), the boost function should be adapted as follows:

        boost::function f= boost::bind(&ClassName::classMember, classInstance, _1);
    

    More information on boost::bind can be found in the documentation: http://www.boost.org/doc/libs/1_55_0/libs/bind/bind.html

提交回复
热议问题