简体   繁体   English

与QVariant的多态性

[英]Polymorphism with QVariant

I have two classes like this : 我有两个这样的课程:

 class Foo { public: Foo(int i) : _i(i) {} int _i; }; Q_DECLARE_METATYPE(Foo*) 
class Bar : public Foo
{
public:
   Bar(int i, int j) : Foo(i), _j(j) {}
   int _j;
};
Q_DECLARE_METATYPE(Bar*)

My bench is like this : 我的板凳是这样的:

 int main(int argc, char *argv[]) { QApplication a(argc, argv); Bar* bar = new Bar(10,11); QVariant var = QVariant::fromValue(bar); Foo * foo = var.value<Foo*>(); // foo IS NULL QPushButton * b = new QPushButton(); QVariant v = QVariant::fromValue(b); QObject * object = v.value<QObject*>(); // object IS NOT NULL return a.exec(); } 

Why is foo null ? 为什么foo null? QVariant lets the polymorphism since I have no problem with object QVariant允许多态,因为我对object没有问题

Because Foo is not derived from QObject and QVariant only supports polymorphism for QObject -derived types. 因为Foo不是从QObject派生的,所以QVariant仅支持QObject派生类型的多态性。

From the QVariant::value documentation : 来自QVariant :: value文档

If the QVariant contains a pointer to a type derived from QObject then T may be any QObject type. 如果QVariant包含指向从QObject派生的类型的指针,则T可以是任何QObject类型。 If the pointer stored in the QVariant can be qobject_cast to T, then that result is returned. 如果存储在QVariant中的指针可以是qobject_cast到T,则返回该结果。 Otherwise a null pointer is returned. 否则返回空指针。 Note that this only works for QObject subclasses which use the Q_OBJECT macro. 请注意,这仅适用于使用Q_OBJECT宏的QObject子类。

(Emphasis mine). (强调我的)。 This is rehashed in the part about QVariant::canConvert that is referenced further down, and there is nothing else about pointer conversions. 关于QVariant::canConvert的部分重新进行了更深入的参考,并且没有关于指针转换的其他内容。 QVariant simply does not support your scenario. QVariant根本不支持您的方案。

The upside is that if you make Foo a subclass of QObject , you do not have to bother with Q_DECLARE_METATYPE anymore. 好处是,如果你让Foo成为QObject的子类,你就不必再为Q_DECLARE_METATYPE而烦恼了。

Problem is that there is no meta data about inheritance and no virtual table, so QVariant has no data about inheritance. 问题是没有关于继承的元数据而没有虚拟表,因此QVariant没有关于继承的数据。 You can try add some virtual method to base class (destructor would be best), it might help (in such case there will be some run time data about inheritance) but I don't think it is enough. 您可以尝试向基类添加一些虚方法(析构函数最好),它可能会有所帮助(在这种情况下会有一些关于继承的运行时数据),但我认为这还不够。
Like in other answer this feature will work for sure for QObject s. 与其他答案一样,此功能对QObject来说肯定会起作用。

You can also try add Q_GADGET macro to provide meta data, but I doubt it will solve the problem. 您也可以尝试添加Q_GADGET宏来提供元数据,但我怀疑它会解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM