信号与Qt中的SLOT宏:它们是做什么的? [英] SIGNAL & SLOT macros in Qt : what do they do?
问题描述
我是Qt的初学者,试图了解SIGNAL
和SLOT
宏.当我学习使用connect
方法绑定信号和插槽时,我发现Qt官方参考页上的教程使用:
connect(obj1, SIGNAL(signal(int)), obj2, SLOT(slot()))
但是,这也很好用:
connect(obj1, &Obj1::signal, obj2, &Obj2::slot)
那么宏SIGNAL
和SLOT
到底是做什么的呢?他们只是在对象所属的类中寻找信号并返回其地址吗?
那为什么大多数程序员为什么不使用&Obj1::signal
而使用这些宏,因为后者似乎更简单,并且如果信号函数的参数发生变化,则不需要更改代码?
在Qt 5之前,使用SIGNAL
和SLOT
宏曾经是建立连接的唯一方法.需要在标头中标记信号和插槽.例如:
Class MyClass : public QObject
{
Q_OBJECT
signals:
void Signal();
slots:
void ASlotFunction();
};
信号和插槽机制是Qt提供的C ++扩展的一部分,并利用了元对象编译器(moc).
这解释了信号和时隙使用moc的原因. /p>
第二个connect方法有了很大的改进,因为指定的功能可以在编译时而不是运行时进行检查.此外,通过使用函数的地址,您可以引用任何类函数,而不仅限于标记为 slots:
的部分中的那些.此外,还有一篇有关Qt 4 connect运作的好博客文章这里和Qt 5 这里.
I'm a beginner in Qt and trying to understand the SIGNAL
and SLOT
macros. When I'm learning to use the connect
method to bind the signal and slot, I found the tutorials on Qt's official reference page uses:
connect(obj1, SIGNAL(signal(int)), obj2, SLOT(slot()))
However, this also works very well:
connect(obj1, &Obj1::signal, obj2, &Obj2::slot)
So what exactly do the macros SIGNAL
and SLOT
do? Do they just look for the signal in the class the object belongs to and return the address of it?
Then why do most programmers use these macros instead of using &Obj1::signal
since the latter appears to be simpler and you don't need to change the code if the parameters of the signal function change?
The use of the SIGNAL
and SLOT
macros used to be the only way to make connections, before Qt 5. The connection is made at runtime and require signal and slots to be marked in the header. For example:
Class MyClass : public QObject
{
Q_OBJECT
signals:
void Signal();
slots:
void ASlotFunction();
};
To avoid repetition, the way in which it works is described in the QT 4 documentation.
The signal and slot mechanism is part of the C++ extensions that are provided by Qt and make use of the Meta Object Compiler (moc).
This explains why signals and slots use the moc.
The second connect method is much improved as the functions specified can be checked at the time of compilation, not runtime. In addition, by using the address of a function, you can refer to any class function, not just those in the section marked slots:
The documentation was updated for Qt 5.
In addition, there's a good blog post about the Qt 4 connect workings here and Qt 5 here.
这篇关于信号与Qt中的SLOT宏:它们是做什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!