Qt插件无法使用qobject_cast进行投射

时间:2015-04-30 22:13:50

标签: c++ qt plugins qml

这是我的插件文件:

#include <QQmlExtensionPlugin>

class VersionInterface
{
public:
    virtual const QString version() const = 0;
    virtual ~VersionInterface() {}
};

#define VersionInterface_iid "com.fx.VersionInterface/1.0"
Q_DECLARE_INTERFACE(VersionInterface, "com.fx.VersionInterface")

class FXQLLauncherPlugin : public QQmlExtensionPlugin, public VersionInterface
{
    Q_OBJECT
    Q_INTERFACES(VersionInterface)
    Q_PLUGIN_METADATA(IID "com.fx.QLLauncherPlugin")

    public:
        void registerTypes(const char *uri);
        void initializeEngine(QQmlEngine *engine, const char *uri);

        const QString version() const final override;
};

它汇编得很好。

但是在我尝试加载和转换对象qobject_cast的应用程序中,返回nullptr

qmlPlugin.load();
if (qmlPlugin.isLoaded()) {
    QObject *rootObject = qmlPlugin.instance();
    // rootObject is valid object
    qDebug() << rootObject->inherits("QQmlExtensionPlugin");
    // outputs: true
    qDebug() << rootObject->inherits("VersionInterface");
    // outputs: false
    VersionInterface* plugin = qobject_cast<VersionInterface*>(rootObject);
    // plugin == nullptr
}

MOC文件生成有效代码: 的 moc_plugin.cpp

void *FXQLLauncherPlugin::qt_metacast(const char *_clname)
{
    if (!_clname) return Q_NULLPTR;
    if (!strcmp(_clname, qt_meta_stringdata_FXQLLauncherPlugin.stringdata))
        return static_cast<void*>(const_cast< FXQLLauncherPlugin*>(this));
    if (!strcmp(_clname, "VersionInterface"))
        return static_cast< VersionInterface*>(const_cast< FXQLLauncherPlugin*>(this));
    if (!strcmp(_clname, "com.fx.VersionInterface"))
        return static_cast< VersionInterface*>(const_cast< FXQLLauncherPlugin*>(this));
    return QQmlExtensionPlugin::qt_metacast(_clname);
}

请解释为什么qobject_cast在这里不起作用?

0 个答案:

没有答案