如何从类名中找到 Qt 元对象实例?
有没有办法在给定类名的情况下找到类的 QMetaObject 实例?我喜欢做的是从磁盘加载对象,但为了实现这一点,我需要一种使用类名检索 QMetaObject 实例的方法,以便使用 QMetaObject 创建实例。
Is there a way to find the QMetaObject instance of a class, given the class name? what I like to do is to load objects from disk, but for this to happen, I need a way to retrieve a QMetaObject instance using the name of a class, in order to use the QMetaObject to create an instance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您应该能够使用 QMetaType 来完成此操作。您可能需要
Q_DECLARE_META_TYPE()
和/或qRegisterMetaType()
来让您的类型为人所知。然后它应该大致像链接中的示例一样工作:You should be able to do this with QMetaType. You might need
Q_DECLARE_META_TYPE()
and/orqRegisterMetaType()
to make your types known. Then it should work roughly like in this example from the link:我最近也面临着同样的问题。我需要元对象而不必创建类本身的实例。我能做的最好的事情就是创建一个全局/静态函数来检索给定类名的 qmetaobject 。我通过使用 QObject::staticMetaObject 实现了这一点。
请参阅:http://doc.qt.io/qt-5/qobject .html#staticMetaObject-var
如果有人有更好的选择,请分享!
I have been facing the same problem recently. I needed the metaobject without having to create an instance of the class itself. Best I could do is to create a global / static function that retrieves the qmetaobject given the class name. I achieved this by using QObject::staticMetaObject.
See : http://doc.qt.io/qt-5/qobject.html#staticMetaObject-var
If somebody has a better option, please share !
您可以将所需的 MetaClass 实例存储在哈希或映射中,然后通过存储它们的任何名称检索它们
You can store the MetaClass instances you will need in a Hash or Map, and then retrieve them via whatever name you stored them under
对于您的情况,适当的解决方案可以使用 Qt 插件机制。它提供了轻松加载共享/动态库并检查它是否包含某些所需接口的实现的功能,如果是,则创建实例。详细信息可以在这里找到:如何创建 Qt 插件
For your case the appropriate solution can be using Qt plugin mechanism. It offers functionality to easily load shared/dynamic library and check if it contains implementation of some desired interface, if so - create the instance. Details can be found here: How to Create Qt Plugins
您还可以查看该函数:
QMetaType::metaObjectForType
其中
:这是我的代码,它按类名创建一个类。 (请注意,该类必须使用 qRegisterMetaType 注册(或者是 QObject 基类)
更新 2: 我忘记说了。Yout 类的构造函数必须标记为 Q_INVOKABLE
You can also take a look at the function:
QMetaType::metaObjectForType
whichUpdate: That's my code, it create a class by class name. (Note that the class must be registered with qRegisterMetaType (or is QObject base)
Update 2: I have forgot to say. Yout class's constructor must be marked as Q_INVOKABLE