【问题标题】:QML not getting property from singleton in another fileQML 没有从另一个文件中的单例获取属性
【发布时间】:2020-03-30 22:33:40
【问题描述】:

我创建了一个将一些 QML 放入插件的项目,以及一个使用 Qt 的 QPluginLoader 的应用程序。

应用程序的 QML 然后可以使用插件的 QML,但有一个明显的问题。从插件的一个 QML 文件中,我无法在另一个 QML 文件中读取单例的属性。如果您查看文件 hello.qml,有一个 Text 项试图从 MySingleton 获取他的文本,但该文本没有显示出来。当我替换字符串文字(注释掉的行)时,文本显示得很好。

我的项目在这里:https://github.com/rhvonlehe/qmlplugin

项目本身非常基础,但代表了我无法分享但存在相同问题的大型项目中发生的许多相同事情。

按原样输出:

在蓝色矩形中应该有“singleton Text”字样

【问题讨论】:

    标签: qt qml


    【解决方案1】:

    QtCompany 提供了答案,我可以在这里分享。

    长话短说,为了在插件中获得 QML 所期望的全部功能,我需要使用 QQmlExtensionPlugin。以下是更新后的文件以使事情正常运行(Plugin.h 和 hello.qml)

    hello.qml

    import QtQuick 2.0
    import org.example.PluginInterface 1.0
    import "."
    
    Rectangle {
        id: page
        width: 320; height: 240
        color: "lightgray"
    
        Text {
            id: helloText
            text: "Hello world!"
            y: 30
            anchors.horizontalCenter: page.horizontalCenter
            font.pointSize: 24; font.bold: true
        }
    
        Rectangle {
            id: innerPage
            width: 300; height: 30
            anchors.horizontalCenter: page.horizontalCenter
            color: "blue"
    
            Text {
                id: nextOne
                color: "white"
    //            text: "literal Text"
                text: MySingleton.getTheText()
                anchors.verticalCenter: innerPage.verticalCenter
                anchors.horizontalCenter: innerPage.horizontalCenter
                font.pointSize: 18; font.bold: false
            }
        }
    
        OtherThing {
            id: myOtherThing
            x: 20; y: 150
        }
    
    }
    

    插件.h

    #ifndef PLUGIN_H
    #define PLUGIN_H
    
    #include <PluginIf.h>
    #include <QQmlExtensionPlugin>
    #include <QQmlEngine>
    
    class Q_DECL_EXPORT Plugin : public QQmlExtensionPlugin, PluginInterface
    {
        Q_OBJECT
        Q_PLUGIN_METADATA(IID QQmlExtensionInterface_iid)
        Q_INTERFACES(PluginInterface)
    public:
        void init() override;
        void registerTypes(const char *uri) override
        {
            qmlRegisterSingletonType(QUrl("qrc:/MySingleton.qml"), uri, 1, 0, "MySingleton");
        }
    };
    
    #endif // PLUGIN_H
    

    【讨论】:

    • FWIW,它也可以仅使用原始 PluginInterface 并在 init() 函数中调用 qmlRegisterSingletonType。这假设消费者将始终调用 init。
    猜你喜欢
    • 1970-01-01
    • 2017-02-27
    • 2022-06-15
    • 2022-12-05
    • 2014-04-05
    • 2019-05-25
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多