Search code examples
qtqmlqlayout

How to add element to the top of an existing layout in QML


I have an existing ColumnLayout and I want to add a new element on top of it without changing the existing ColumnLayout. I'm using an alias to reference the existing ColumnLayout but when I add the new element, it goes to the bottom of the layout. How can I add it to the top?

BaseColumn.qml

import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15

Rectangle {
    property alias content: content
    anchors.fill: parent
    ColumnLayout {
        id: content
        Text {
            id: name
            text: qsTr("World")
        }
    }
}

Now in another file ChildColumn.qml I'm doing this but this adds this text at the bottom of the ColumnLayout and not the top.

BaseColumn {
    content.data [
        Text {
            id: name
            text: qsTr("Hello")
        }
    ]
}

Solution

  • You can have two ColumnLayout so that user customizations will always go in front of yours, e.g.

    import QtQuick
    import QtQuick.Controls
    import QtQuick.Layouts
    Page {
        BaseColumn {
            Text {
                text: qsTr("Hello")
            }
        }
    }
    
    // BaseColumn.qml
    import QtQuick 2.15
    import QtQuick.Controls 2.15
    import QtQuick.Layouts 1.15
    Frame {
        default property alias __content: topColumnLayout.data
        ColumnLayout {
            ColumnLayout {
                id: topColumnLayout
            }
            Text {
                id: name
                text: qsTr("World")
            }
        }
    }
    

    However, having said that, your requirement maybe simpler implemented with the Page footer property, e.g.

    // BaseColumn.qml
    import QtQuick 2.15
    import QtQuick.Controls 2.15
    import QtQuick.Layouts 1.15
    Page {
        default property alias __content: topColumnLayout.data
        ColumnLayout {
            id: topColumnLayout
        }
        footer: Text {
            id: name
            text: qsTr("World")
        }
    }