问题描述
假设我有这个信号:
signals:
void progressNotification(int progress);
我最近才了解到Qt中的emit关键字。到现在为止,我只是像普通函数一样调用它们来执行信号。而不是:
I only recently learned about the emit keyword in Qt. Until now, I used to execute signals by just calling them like a regular function. So instead of:
emit progressNotification(1000 * seconds);
我会写:
progressNotification(1000 * seconds);
像这样调用他们似乎工作,所有连接的插槽都会执行,关键字导致不同的行为,还是只是语法糖?
Calling them like that seemed to work, and all the connected slots would execute, so does using the emit keyword cause a different behaviour, or is it just syntactic sugar?
推荐答案
emit
只是语法糖。如果你看看发出信号的函数的预处理输出,你会看到 emit
刚刚走了。
emit
is just syntactic sugar. If you look at the pre-processed output of function that emits a signal, you'll see emit
is just gone.
magic发生在信号发射函数的生成代码中,您可以通过检查moc生成的C ++代码来查看。
The "magic" happens in the generated code for the signal emitting function, which you can look at by inspecting the C++ code generated by moc.
例如 foo
没有参数的信号生成此成员函数:
For example a foo
signal with no parameters generates this member function:
void W::foo()
{
QMetaObject::activate(this, &staticMetaObject, 0, 0);
}
而代码 emit foo code>被预处理为简单的
foo();
emit
在 Qt / qobjectdefs.h
中定义(在源的开源风格中),如下所示:
emit
is defined in Qt/qobjectdefs.h
(in the open-source flavor of the source anyway), like this:
#ifndef QT_NO_EMIT
# define emit
#endif
(定义保护是允许你通过 no_keywords
QMake配置选项使用Qt与其他具有冲突名称的框架。)
(The define guard is to allow you to use Qt with other frameworks that have colliding names via the no_keywords
QMake config option.)
这篇关于使用emit和调用信号,就像它是Qt中的常规函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!