Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Loading component from other QML file



  • Hello everyone, I am trying to load a component from an auxiliary qml file and I can't find the correct way to do it. I know it's a very basic question, but I'm really a beginner with QML.

    The relevant part of my code is

    StackView {
        // Stuff
        initialItem: ListView {
            // Stuff
            delegate: ItemDelegate
            {
                // Stuff
                contentItem: Rectangle
                {
                    // Stuff
                }
    

    Now, I want to move the Rectangle to a separate file and replace its implementation in the code above with a suitable "call".

    I tried to naïvely copy-paste the Rectangle {} part to a new file myItem.qml and then replace it, in the code above, with contentItem: "myItem.qml" but I get the error

    Invalid property assignment: unsupported type "QQuickItem*"
    

    I tried various [pointless] things such as wrapping everything inside an Item {} [same error] or calling contentItem: "myItem" [yields ReferenceError for object not defined] but to no avail.

    Can anybody point me in the right direction? I feel I should be pretty close since it's a dumb task.

    Thank you!



  • Hi there, I have a question.

    • the myItem.qml is in same prefix of main.qml ? (relative of resource.qrc file)


  • Hi! My qml files are in a qml/ subfolder. My qml.qrc file reads

    <RCC>
        <qresource prefix="/">
            <file>qml/main.qml</file>
            <file>qml/buysItem.qml</file>
        </qresource>
    </RCC>
    

    the project file contains

    RESOURCES += qml.qrc
    

    and in the code I actually wrote contentItem: "qml/myItem.qml". Does it help?



  • Sorry for delay.
    To solve this problem, you need to do:

    • Change the first letter of your component to Uppercase (because Qt Name Rules), so, you need to rename the file buysItem.qml to BuysItem.qml.

    • Replace contentItem: "qml/myItem.qml" to contentItem: BuysItem{}

    Obs: All variables begin with lowercase letter and components with uppercase letter.

    Read More:
    http://doc.qt.io/qt-5/qtqml-syntax-directoryimports.html
    http://doc.qt.io/archives/qt-4.8/qmlreusablecomponents.html



  • Ah, that fixed it! Thank you very much :D


  • Lifetime Qt Champion

    @mleoni Then please close this topic as SOLVED (button Topic Tools below your first post). Thanks



  • Done, thanks for reminding me!


Log in to reply