[英]How to check if it's a valid QObject pointer, created by QMetaType::create()
I need to convert QVariant
to other user custom classes.我需要将
QVariant
转换为其他用户自定义类。
All classes have to be derived from QObject
.所有类都必须从
QObject
派生。
I can check at compilation time the destination type because it's a template but the source is a QVariant
so, it cannot be checked.我可以在编译时检查目标类型,因为它是模板但源是
QVariant
,因此无法检查。
My method:我的方法:
template<class T, typename = std::enable_if_t<std::is_base_of<QObject, T>::value> > static bool canConvert(const QVariant& var)
calls this:称之为:
QObject* from = reinterpret_cast<QObject*>(QMetaType::create(var.userType()));
from
is never null but, if userType
is not of a QObject
base class, from
is not a valid QObject
pointer and the call crashes when calling: from
永远不会为空,但是,如果userType
不是QObject
基类,则from
不是有效的QObject
指针并且调用时调用崩溃:
from->metaObject();
I cannot do dynamic_cast
of a void*
from QMetaType::create()
我不能从
QMetaType::create()
做一个void*
dynamic_cast
I tried qobject_cast
of from
but it does not fail if it's not valid我试过
qobject_cast
of from
但如果它无效,它不会失败
How do I know if QObject* from
is a valid pointer to a QObject
derived class?我如何知道
QObject* from
是否是指向QObject
派生类的有效指针?
I've found a solution.我找到了解决办法。
If the type is, for example MyType
, it's pointer type has to be registered.如果类型是,例如
MyType
,则必须注册它的指针类型。
qRegisterMetaType<MyType*>();
So, here a rudimental method to check if it's derived from QObject:所以,这里有一个基本的方法来检查它是否是从 QObject 派生的:
static bool isClassDerivedFromQObject(const QVariant& var)
{
QString className(QMetaType::typeName(var.userType()));
className.append("*"); // create a pointer of the name
const auto id = QMetaType::type(className.toLatin1().data());
const auto metaObject = QMetaType::metaObjectForType(id);
return metaObject != nullptr;
}
This can be called before QMetaType::create(var.userType())
这可以在
QMetaType::create(var.userType())
之前调用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.