Qt:如何获得特定类的子类的所有类(Qt : How to get all the classes that are children of a specific class)

编程入门 行业动态 更新时间:2024-10-25 16:19:48
Qt:如何获得特定类的子类的所有类(Qt : How to get all the classes that are children of a specific class)

Qt的Meta Object系统允许很多有趣的内省。 但我的问题如下:假设我编写了一个class MyClass : public QObject 。 我想在我的GUI中有一个按钮来创建MyClass的实例。 但我决定创建MySubClass : public MyClass并创建另一个按钮来创建MySubClass的实例。

现在一位同事也创建了自己的子类。 有没有办法自动找出扩展MyClass所有类(并自动添加相关按钮)?

我可以看到一些解决方法,比如拥有一个MetaObject数组,以便我可以在每个上调用QMetaObject::newInstance() ,但是每次将新子类添加到代码库时,它都需要我手动添加子类。

有自动方式吗? 如果需要,我可以将自己限制在实现特定Q_INTERFACE类中,如果它有任何区别的话。

Qt's Meta Object system allows a lot of interesting introspection. But my problem is the following : let's suppose I have coded a class MyClass : public QObject. I want to have a button in my GUI to create an instance of MyClass. But I decide to create MySubClass : public MyClass and I create another button to create an instance of MySubClass.

Now a colleague also creates his own subclass. Is there a way to automatically find out all the classes that extend MyClass (and add automatically a relevant button)?

I can see some workaround like having an array of MetaObject so that I can call QMetaObject::newInstance() on each of them, but it requires me to add manually the subclass everytime a new sublass is added to the codebase.

Is there an automatic way to do it? If need be I can restrict myself to classes that implement a specific Q_INTERFACE if it makes any difference.

最满意答案

不,没有自动的方法,因为类没有在任何地方注册 - Q_OBJECT宏只将成员直接添加到类中,但不注册类。

你可以做的是添加一个项目范围的定义,修改Q_OBJECT以通过成员添加工厂注册,例如:

// this declaration added to `Q_OBJECT`: Factory::Registration q_obj_reg{this};

鉴于:

class Factory { public: class Registration { public: template <typename T> Registration(T*); ... };

};

这将至少在第一次使用时自动注册所有QObject类。

No, there's no automatic way to do it, because the classes are not registered anywhere - a Q_OBJECT macro only adds members directly to the class but doesn't register the class.

What you could do is add a project-wide define that modifies Q_OBJECT to add a factory registration via a member, e.g.:

// this declaration added to `Q_OBJECT`: Factory::Registration q_obj_reg{this};

Given:

class Factory { public: class Registration { public: template <typename T> Registration(T*); ... };

};

This would automagically register all QObject classes on first use at least.

更多推荐

本文发布于:2023-08-03 16:57:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1393535.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:子类   如何获得   Qt   classes   class

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!