c++ - 使用任何 c++ 函数作为 Qt 插槽

标签 c++ qt signals-slots qwidget

有没有一种方法可以将任何 C++ 函数用作 Qt 槽,而无需其类继承自 QWidget?

最佳答案

你不能在 Qt 版本 < Qt 5.

为了使用信号/槽,必须调用元对象编译器。要做到这一点,您的类(class)应满足以下要求:

  • 继承自 QObject 或任何其他子类(例如 QWidgetQPushButton 等)
  • Q_OBJECT 宏应该定义在类的私有(private)部分,以便启用元对象特性,例如插槽
  • 使用 Qt 关键字 slotssignals 来声明元编译器应将哪些函数作为槽或信号处理<

有关更多详细信息,请查看有关 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/

相关文章:

c++ - 模板类和派生类

c++ - 如何移动一个 const 返回的对象?

c++ - QCheckBox 检测标签上的点击

c++ - 信号处理程序与虚函数和继承(事件处理)

c++ - 在派生的 QObject 构造函数中连接 Qt 信号和槽

c++ - ram 中的共享内存或命名管道?

c++ - 帮助在 Windows 上使用 g++ 构建

c++ - 看到对 `vtable for CollidingMice' 的 undefined reference

c++ - 从键码中获取键名(X11 XGrabKey)

c++ - 在 QtCreator 中错误使用未声明的标识符 'mainwindow' 语义问题