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.
更多推荐
发布评论