【问题标题】:Use createComponent in qml but the status is always error在 qml 中使用 createComponent 但状态总是错误
【发布时间】:2015-09-15 17:07:02
【问题描述】:

当我使用Qt.createComponent动态创建组件时,状态总是Component.error,但我不明白原因。

我是这样用的:

Rectangle{
    function loadTest(){
        function finishCreation() {
            if (component.status === Component.Ready) {
                console.log("ready")
            } else if (component.status === Component.Error) {
                // Error Handling
                console.log("Error loading component:", component.errorString());
            }
        }

        var component = Qt.createComponent("MyPage.qml");
        console.log(component.status)
        console.log("Error loading component:", component.errorString());
        component.statusChanged.connect(finishCreation);

        if (component.status === Component.Ready) {
            var button = component.createObject(container);
            console.log("ready")
        }
    }

    Component.onCompleted: {
        console.log("Completed Running!")
        loadTest()
    }
}

如果MyPage.qmlqrc文件中不存在,则错误为

qrc:/MyPage.qml:-1 找不到文件”

如果我设置MyPage.qml 的完整路径,我会得到Network error

当我将SeriesSelectionPage.qml 文件添加到资源文件时,它可以工作。但它不应该是动态的吗?

我只是想找一个QML文件,在应用执行的时候动态加载,这样应用就可以根据用户操作加载不同的QML。

有人知道怎么做吗?我要疯了。

【问题讨论】:

    标签: qt qml qtquick2 qqmlcomponent


    【解决方案1】:

    Qt.createComponent()url 作为其第一个参数。来自url documentation

    url 类型指的是资源定位器(例如文件名)。它可以是绝对的,例如“http://qt-project.org”,或相对的,例如“图片/标志.png”。相对 URL 是相对于包含组件的 URL 解析的。

    因此,只要您在从 QRC 文件加载的文件中使用相对 URL,您就需要使用 qrc 方案:

    var component = Qt.createComponent("qrc:/MyPage.qml");
    

    【讨论】:

    • 最好将QML文件添加到资源中并在URL中使用“qrc:/”协议。
    • 我的印象是 OP 希望最终用户能够选择 QML 文件......我猜我看错了。
    • 是的,你是对的。看起来你的第一个版本的答案更正确:) 抱歉
    • 不,我认为你是对的,我只是看错了问题!哈哈。 :)
    • 谢谢大家。很抱歉我的英语太弱,无法表达清楚。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-14
    • 2021-02-05
    • 2018-09-12
    • 2010-11-15
    • 2015-10-04
    • 1970-01-01
    • 2019-04-05
    相关资源
    最近更新 更多