为什么这个 Qt 示例使用地址而不是对象和函数本身?没有 SLOT/SIGNAL 个关键词?

Why does this Qt example work with addresses instead of the objects and functions themselves? And no SLOT/SIGNAL keywords?

我在 Qt 文档中遇到过这段代码:

Counter a, b;

QObject::connect(&a, &Counter::valueChanged,

                 &b, &Counter::setValue);

a.setValue(12);     // a.value() == 12, b.value() == 12
b.setValue(48);     // a.value() == 12, b.value() == 48

为什么a和b之前以及函数之前有&? a 是发射对象(提供信号),b 是接收对象(有插槽),那么为什么他们的地址在这里而不是仅仅使用对象本身(如果我不是,则获取对象的地址错误)?在其他 Qt 示例中,它不是这样的(不使用地址,对象本身)

我不太确定函数调用(即 Counter::valueChanged 和 Counter::setValue)之前的 & 是如何工作的...我认为它通过引用迫使它们 return,但我不确定这在这里有多重要。

最后,为什么没有SLOT和SIGNAL关键词呢?不应该是 SIGNAL(Counter::valueChanged) 和 SLOT(Counter::setValue) 吗?同样,这就是我在 QObject:connect 的其他示例中看到的,这个示例对我来说没有意义。

感谢任何帮助!

看看这个:

Counter a, b; // objects created on the stack, they are not pointers

// get the addresses of the objects and assign them as pointers.
Counter *aPointer = &a;
Counter *bPointer = &b;

以下将无法编译,因为 a 和 b 不是指针,并且 QObject connect 需要指向继承自 QObject 的 classes 实例的指针。

QObject::connect(a, &Counter::valueChanged, b, &Counter::setValue);

以下将编译,因为您提供了指针:

QObject::connect(aPointer, &Counter::valueChanged, bPointer, &Counter::setValue);

同样这也有效,因为你获取了对象的地址(又名指针):

QObject::connect(&a, &Counter::valueChanged, &b, &Counter::setValue);

这有望解释对象之前的 &。然后是函数名前的&'s。这是指向成员函数的指针的语法:

&Counter::valueChanged 

class名称(Counter),附加::和成员函数名称(valueChanged),前面加上&

在本例中,它是作为第一个参数提供的指针的成员。这称为信号。在引擎盖下,Qt 将它们组合在一起。

QObject *sender = &a;
std::function<void()> signal = std::bind(&Counter::valueChanged,sender);
...
signal(); // the function is called here

广告位也是如此。

最后,使用了 SIGNAL() 和 SLOT() 宏 < Qt 5.0。所以它已被弃用,不应再使用。在极少数情况下,您仍然应该使用它,因为没有其他选择,例如与 QtDBus 但这是另一个话题。

我希望这能解决你的一些问题。