4

When I use Qt.createComponent to create component dynamically, the stutas is always Component.error but I cannot understand the reason.

I used it like that:

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()
    }
}

If the MyPage.qml does not exist in the qrc file, the error is

qrc:/MyPage.qml:-1 File not found"

If I set the full path of MyPage.qml, I get a Network error.

When I add the SeriesSelectionPage.qml file to the resource file, it works. But it shouldn't be dynamic?

I just want to find a QML file and load it dynamically when the application executes so that the application can load different QML according to user operations.

Anyone knows how to do that? I'm going crazy.

1 Answer 1

5

Qt.createComponent() takes a url as its first argument. From the url documentation:

The url type refers to a resource locator (like a file name, for example). It can be either absolute, e.g. "http://qt-project.org", or relative, e.g. "pics/logo.png". A relative URL is resolved relative to the URL of the containing component.

So, as long as you're using relative URLs from within a file that is loaded from a QRC file, you'll need to use the qrc scheme:

var component = Qt.createComponent("qrc:/MyPage.qml");
Sign up to request clarification or add additional context in comments.

9 Comments

It will be better just add the QML file into resources and use "qrc:/" protocol in URL.
I was under the impression that OP wanted the end user to be able to choose a QML file... guess I misread.
Yes, you are right. looks like your first version of answer is more correct :) Sorry
No, I think you're right and I just read the question incorrectly! Haha. :)
Thank you all. I'm so sorry that my English is too weak to express clearly.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.