Home > Enterprise >  QML share one instance of a component in different pages in a stackview
QML share one instance of a component in different pages in a stackview

Time:12-28

In QML, I have one instance of a Component (id: sharedComponent) which I would like to use in two QML Pages that are managed in a StackView. However, the sharedComponent is only visible when page1 is active in StackView, i.e., the blue rectangle disappears as soon as page2 is pushed on the StackView.

How can I share/use/see an instance of a component in multiple pages in QML?

MyPage.qml

Page {
    default property alias mainContent: mainContent.data

    Item {
        id: mainContent
        anchors.fill: parent
    }
}

main.qml

ApplicationWindow {
    id: window
    width: 640
    height: 480
    visible: true

    Rectangle {
        id: sharedComponent
        anchors.fill: parent
        color: "blue"
        // in my actual software, this shared component would contain a Scene3D here
    }

    MyPage {
        id: page1
        mainContent: sharedComponent
    }
    MyPage {
        id: page2
        mainContent: sharedComponent
    }

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

    Button {
        text: "Switch Page"
        anchors.centerIn: parent
        onClicked: {
            if(stackView.depth>1) {
                stackView.pop()
            } else {
                stackView.push(page2)
            }
        }
    }
}

CodePudding user response:

In order to share an object, the shared object needs to be re-parented. When a different MyPage instance becomes visible, it needs to become the parent of the sharedObject. So start the pages with visible set to false.

MyPage.qml:

Page {
    property Item mainContent

    Item {
        id: container
        anchors.fill: parent
    }

    onVisibleChanged: {
        if (visible) {
            // Take ownership of the shared object
            mainContent.parent = container
        }
    }
}

main.qml:

ApplicationWindow {
    ...

    Rectangle {
        id: sharedComponent
        anchors.fill: parent
        color: "blue"
    }

    MyPage {
        id: page1
        mainContent: sharedComponent

        // When visible becomes true, page1 becomes the parent
        visible: false
    }
    MyPage {
        id: page2
        mainContent: sharedComponent

        // When visible becomes true, page2 becomes the parent
        visible: false
    }
}
  • Related