問題描述
假設我有這個信號:
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 中的常規函數??一樣的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!