[SOLVED] QML Row: How to extend qml containers (Row or Column) from other file

Issue

It seems should have a solution for sure.
Suppose I have a Test.qml file containing this:

import QtQuick 2.0

Rectangle {
    color: "green"

    Row {
        id: row
        spacing: 10
        anchors.fill: parent
        Rectangle {
            color: "red";
            width: 100;
            height: 100;
        }
        Rectangle {
            color: "red";
            width: 100;
            height: 100;
        }
        Rectangle {
            color: "red";
            width: 100;
            height: 100;
        }
    }
}

Now suppose we want to use this Test.qml within another file like main.qml:

import QtQuick 2.15
import QtQuick.Window 2.15

Window {
    id: window
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")


    Test {
        anchors.fill: parent;
        // I want to be able to add new items (rects) to the row inside Test.qml
    }
}

Now suppose we want to extend items to the row object in Test.qml, But we want to add from main.qml. How we can do that? is that even possible?

(FYI: The application of this feature would be to develop a placeholder form and fill the items in the other items so we can skip duplicate codes. )

Solution

You can do this without creating objects dynamically. You need to use a default property that is aliased to the contents of your Row. A default property means Items that get added to your object will actually be assigned to that property instead. In Test.qml, add this:

Rectangle {
    color: "green"
    default property alias contents: row.data

    Row {
        id: row
        ...
     }
}    

Now you can add other items to it from main.qml, like this:

    Test {
        anchors.fill: parent;
        
        // Automatically gets added to 'row'
        Rectangle {
            color: "blue"
            width: 100
            height: 100
        }
    }

Answered By – JarMan

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *