Adding Items to a layout of a custom component

天涯浪子 提交于 2019-12-22 08:36:22

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/31612731/adding-items-to-a-layout-of-a-custom-component

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!