首页 > 解决方案 > `&ClassName::function` 的调用方法代表什么?

问题描述

connect( &objTwo, &Two::emitThisSignal, this, &Controller::mySlot );

这里的二是一个单独的类。它的对象已在 Controller 类中创建。它的信号必须连接到控制器类的插槽。

连接的签名是:

connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type)
connect(const QObject *sender, const char *signal, const char *method, Qt::ConnectionType type) const
connect(const QObject *sender, PointerToMemberFunction signal, const QObject *receiver, PointerToMemberFunction method, Qt::ConnectionType type)
connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
connect(const QObject *sender, PointerToMemberFunction signal, const QObject *context, Functor functor, Qt::ConnectionType type)

我的连接调用代表上面的哪个签名?

为什么我不能简单地写:connect( &objTwo, objTwo.emitThisSignal, this, this->mySlot );

标签: c++multithreadingqtqthread

解决方案


我的连接调用代表上面的哪个签名?

这个:

connect(const QObject *sender, PointerToMemberFunction signal, 
       const QObject *receiver, PointerToMemberFunction method, Qt::ConnectionType type)

最后一个参数是 default( Qt::ConnectionType type = Qt::AutoConnection),因此您没有明确指定它。链接到文档

为什么我不能简单地写:connect( &objTwo, objTwo.emitThisSignal, this, this->mySlot );?

因为如果你想传递一个指向成员函数的指针,那是无效的 C++ 语法。objTwo.emitThisSignal在 C++ 语法中意味着,访问内部的数据成员,而函数需要一个指向成员函数的指针。emitThisSignalobjTwo


但是,如果你写:

connect( &objTwo, SIGNAL(objTwo.emitThisSignal), this, SLOT(this->mySlot) );

您的代码可能会编译,但不会按预期工作。其原因可以通过查看第一个connect签名来理解:

connect(const QObject *sender, const char *signal, 
        const QObject *receiver, const char *method, Qt::ConnectionType type)

它将指针char*作为第二个和第四个参数。所以任何语法都会被编译。宏SIGNAL()并将SLOT()它们转换为字符串,然后 Qt 在运行时使用它们在发出信号时调用正确的插槽。上述语法甚至可能不会导致崩溃或任何警告。我知道这听起来很可怕,但这就是 Qt 5 出现之前 Qt 的状态。

这些天来,强烈建议您使用这三个签名:

connect(const QObject *sender, PointerToMemberFunction signal, const QObject *receiver, PointerToMemberFunction method, Qt::ConnectionType type)
connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
connect(const QObject *sender, PointerToMemberFunction signal, const QObject *context, Functor functor, Qt::ConnectionType type)

推荐阅读