有没有一种方法可以将任何 C++ 函数用作 Qt 槽,而无需其类继承自 QWidget?
最佳答案
你不能在 Qt 版本 < Qt 5.
为了使用信号/槽,必须调用元对象编译器。要做到这一点,您的类(class)应满足以下要求:
- 继承自
QObject
或任何其他子类(例如QWidget
、QPushButton
等) Q_OBJECT
宏应该定义在类的私有(private)部分,以便启用元对象特性,例如插槽- 使用
Qt
关键字slots
和signals
来声明元编译器应将哪些函数作为槽或信号处理<
有关更多详细信息,请查看有关 meta-object system 的相应文档页面和 signals & slots
同时检查 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 表达式可以用作槽。参见 New Signal Slot Syntax in Qt 5
关于c++ - 使用任何 c++ 函数作为 Qt 插槽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44376408/