Adding Items to a layout of a custom component

2019-05-07 06:24发布

I have a custom Footer Component which I would like to reuse in different place in my QML App:

Rectangle {
    color: "gold"
    height: 50
    anchors {
        bottom: parent.bottom
        left: parent.left
        right: parent.right
    }

    RowLayout {
        anchors.fill: parent
        anchors.margins: 10

        Button {
            text: "quit"
        }
    }
}

The use of this is easy:

Window {
    visible: true

    Footer {
    }
}

But now I would like to add a "ButtonA" to the RowLayout of my Footer in one view and a "ButtonB" in another view.

How can I achieve that?

标签: qt qml qtquick2
1条回答
ら.Afraid
2楼-- · 2019-05-07 07:03

See this answer.

You have to declare a default property in Footer.qml:

import QtQuick 2.0
import QtQuick.Controls 1.2
import QtQuick.Layouts 1.1

Rectangle {
    color: "gold"
    height: 50

    default property alias content: rowLayout.children

    anchors {
        bottom: parent.bottom
        left: parent.left
        right: parent.right
    }

    RowLayout {
        id: rowLayout
        anchors.fill: parent
        anchors.margins: 10

        Button {
            text: "quit"
        }
    }
}

This ensures that any items declared as children of Footer instances will be added to its RowLayout.

main.qml:

import QtQuick 2.4
import QtQuick.Controls 1.3

ApplicationWindow {
    width: 640
    height: 480
    visible: true

    StackView {
        id: stackView
        anchors.fill: parent
        initialItem: viewAComponent
    }

    Component {
        id: viewAComponent

        Rectangle {
            id: viewA
            color: "salmon"

            Footer {
                id: footerA

                Button {
                    text: "Go to next view"
                    onClicked: stackView.push(viewBComponent)
                }
            }
        }
    }

    Component {
        id: viewBComponent

        Rectangle {
            id: viewB
            color: "lightblue"

            Footer {
                id: footerB

                Button {
                    text: "Go to previous view"
                    onClicked: stackView.pop()
                }
            }
        }
    }
}

I used StackView as a convenient way of navigating between the views.

查看更多
登录 后发表回答