简体   繁体   English

如何检查它是否是由 QMetaType::create() 创建的有效 QObject 指针

[英]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.

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