使用发射与调用信号,就好像它是 Qt 中的常规函数​​一样 [英] Using emit vs calling a signal as if it's a regular function in Qt

查看:48
本文介绍了使用发射与调用信号,就好像它是 Qt 中的常规函数​​一样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个信号:

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);

像这样调用它们似乎可行,并且所有连接的插槽都会执行,所以使用emit 关键字会导致不同的行为,还是只是语法糖?

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.

魔术"发生在信号发射函数的生成代码中,您可以通过检查由 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();被预处理为简单的foo();

And the code emit foo(); is pre-processed to simply foo();

emitQt/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.)

这篇关于使用发射与调用信号,就好像它是 Qt 中的常规函数​​一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆