Using emit vs calling a signal as if it#39;s a regular function in Qt(使用发射与调用信号,就好像它是 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();
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.)
这篇关于使用发射与调用信号,就好像它是 Qt 中的常规函数一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用发射与调用信号,就好像它是 Qt 中的常规函
基础教程推荐
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- c++ STL设置差异 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
