我看过如何验证类型为QVariant::UserType的QVariant是预期类型?我知道如何判断MyType类的对象已存储在QVariant对象中。我已经阅读了QVariant::convert((的文档,但我不知道如何为我作为QVariant接收的对象调用MyType中定义的成员函数。
假设我有
class MyType
{
public:
void myFunction;
.
.
.
};
Q_DELCARE_METATYPE(MyType)
MyType m;
QVariant var (QVariant::fromValue (m));
如何为保存在var中的MyType对象调用MyType::myFunction?
根据注释,可以使用QVariant::value
获取QVariant
所持有对象的副本。所以在这种特殊的情况下。。。
/*
* Check that the conversion is possible.
*/
if (var.canConvert<MyType>()) {
/*
* Obtain a copy of the MyType held.
*/
auto m = var.value<MyType>();
/*
* Use as per normal.
*/
m.myFunction();
}