【问题标题】:What does `&ClassName::function` method of calling represent?`&ClassName::function` 的调用方法代表什么?
【发布时间】:2020-11-20 23:50:21
【问题描述】:

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

这里的 Two 是一个单独的类。它的对象已在 Controller 类中创建。它的信号必须连接到 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++ multithreading qt qthread


    【解决方案1】:

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

    这个:

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

    最后一个参数是默认的(Qt::ConnectionType type = Qt::AutoConnection),所以你没有明确指定它。 Link to docs

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

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


    但是如果你写:

    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)
    

    【讨论】:

      猜你喜欢
      • 2013-01-07
      • 1970-01-01
      • 1970-01-01
      • 2019-02-22
      • 2019-08-05
      • 1970-01-01
      • 1970-01-01
      • 2018-11-07
      • 2018-03-21
      相关资源
      最近更新 更多