使用任何C ++函数作为Qt插槽 [英] Using any c++ function as a Qt slot
问题描述
有没有一种方法可以将任何C ++函数用作Qt插槽,而不必让其类继承自QWidget?
Is there a way to use any C++ function as a Qt slot, without having its class inheriting from QWidget?
推荐答案
您不能在Qt版本中<Qt 5.
为了使用信号/插槽,必须调用元对象编译器.为此,您的课程应满足以下要求:
In order to use signals/slots the meta object compiler has to be invoked. To make this happen your class should meet the following requirements:
- 继承自
QObject
或任何其他子类(例如QWidget
,QPushButton
等) -
Q_OBJECT
宏应在类的私有部分中定义,以启用诸如插槽之类的元对象功能 - 使用
Qt
关键字slots
和signals
来声明元编译器应将哪些函数作为插槽或信号进行处理
- Inherit from
QObject
or any other subclass (egQWidget
,QPushButton
etc) - The
Q_OBJECT
macro should be defined in the private section of the class in order to enable meta-object features such as slots - Use the
Qt
keywordsslots
andsignals
in order to declare which functions should be handles by the meta compiler as slots or signals
For more details check the corresponding documentation pages about the meta-object system and the signals & slots
还要检查 QObject
文档:
Also check the QObject
documentation:
请注意,
Q_OBJECT
宏对于实现信号,插槽或属性的任何对象都是必需的.源文件上的元对象编译器.我们强烈建议使用QObject的所有子类中此宏的大小,无论是否他们不实际使用信号,插槽和属性,因为这样做可能导致某些功能表现出奇怪的行为.
Notice that the
Q_OBJECT
macro is mandatory for any object that implements signals, slots or properties. You also need to run the Meta Object Compiler on the source file. We strongly recommend the use of this macro in all subclasses of QObject regardless of whether or not they actually use signals, slots and properties, since failure to do so may lead certain functions to exhibit strange behavior.
从Qt 5开始,函子和lambda表达式可用作插槽.参见 Qt 5中的新信号槽语法
这篇关于使用任何C ++函数作为Qt插槽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!