是“公共插槽:” Qt5中还需要哪些部分? [英] Are "public slots:" sections still necessary in Qt5?

查看:50
本文介绍了是“公共插槽:” Qt5中还需要哪些部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于Qt5中新的 signal / slot 语法的一个简单问题:

A simple question regarding the new signal/slot syntax in Qt5:


  • 对于一个 Q_OBJECT 派生的类具有个公共位置:节已声明?

  • Are there still benefits for a Q_OBJECT-derived class to have public slots:sections declared?

注意:使用新语法,您可以将信号连接到类的任何公共函数或直接实现C ++ 11 lambda(

Note: With the new syntax you're able to connect a signal to any public function of a class or directly implement a C++11 lambda (which can also call some member functions itself).

Qt的新功能信号/插槽语法

推荐答案

vahancho和TheDarkKnight的答案是有效的:插槽对于连接不是必需的,但是它使意图更清晰并允许自省。我想我应该列出一些确实需要插槽的用例。

While the answers by vahancho and TheDarkKnight are valid: slots is not required for connections, but it makes the intent clearer and allows introspection. I think I should list some use cases where you do need slots.

首先请注意,您可以使用插槽 Q_SLOTS Q_SLOT Q_INVOKABLE 可使元对象(自省)系统知道该函数。 Q_INVOKABLE 的优点是可以在构造函数上使用。

First please note that you can use slots, Q_SLOTS, Q_SLOT or Q_INVOKABLE to make a function known to the meta object (introspection) system. Q_INVOKABLE has the advantage that it can be used on constructors.

以下是不分先后的用例:

And here are the use cases in no particular order:


  • 使您的代码与Qt 4兼容。即使未维护Qt 4,我也认为一些大公司仍在使用它,并且使库与Qt 5和Qt 4兼容非常容易。

  • 使该功能在QML(和Qt Quick)中可用

  • 使该功能可在javascript中使用(Qt脚本,Qt WebEngine等)

  • 使用 QMetaObject :: invokeMethod()调用该函数。 在Qt 5.10中将提供接受函子的重载。

  • 使用 QMetaObject :: connectSlotsByName() 。请注意,不应使用此功能 会受到对象名称冲突的影响,但是Qt小部件设计器仍然是连接其创建的插槽的方式。

  • 使用 QMetaObject :: newInstance()

  • 以及需要运行时自省的所有其他用例

  • Make your code works with Qt 4. Even if Qt 4 is not maintained I think some big company are still using it and it is fairly easy to make a library works with Qt 5 and Qt 4.
  • Make the function available in QML (and Qt Quick)
  • Make the function available in javascript (Qt Script, Qt WebEngine, etc.)
  • Make the function callable with QMetaObject::invokeMethod(). An overload that accepts functors will be available in Qt 5.10.
  • Make use of QMetaObject::connectSlotsByName(). Note that this function should not be used as it can be affected by object name collisions, but it is still the way the Qt widget designer connects the slots it creates.
  • Make your class instantiatable with QMetaObject::newInstance().
  • And every other use case that requires run-time introspection

这篇关于是“公共插槽:” Qt5中还需要哪些部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆