Access a StackView from a different QML file
-
I'm building an app that's using a
QQmlApplicationEnginefor the root view (don't know if that's of any help). It's aStackViewbased interface (generated by Qt Creator). Therefore, theStackViewis in one file (MainWindow.qml, in my case) and the home page is in another (HomePage.qml). I'd like to be able to push an item to theStackViewwhen the user clicks a button inHomePage.qml. Some skeleton code of what I'm trying to do is below.MainWindow.qml:
import QtQuick 2.12 import QtQuick.Controls 2.5 ApplicationWindow { id: root visible: true width: 1024 height: 768 title: qsTr("Hello world") header: ToolBar { contentHeight: toolButton.implicitHeight ToolButton { id: toolButton text: stackView.depth > 1 ? "\u25C0" : "\u2630" font.pixelSize: Qt.application.font.pixelSize * 1.6 onClicked: { if (stackView.depth > 1) { stackView.pop() } else { drawer.open() } } } Label { text: stackView.currentItem.title anchors.centerIn: parent } } Drawer { id: drawer width: window.width * 0.66 height: window.height Column { anchors.fill: parent } ItemDelegate { text: qsTr("Settings") width: parent.width onClicked: { stackView.push("SettingsPage.qml") drawer.close() } } } } StackView { id: stackView initialItem: "HomePage.qml" anchors.fill: parent } }HomePage.qml:
import QtQuick 2.12 import QtQuick.Controls 2.12 Page { id: pageRoot title: qsTr("Home") Button { anchors.centerIn: parent onClicked: ; // MainWindow.stackView.push("myQmlFile.qml"); }Is this even possible or will I need to invent some new kludgery to achieve this effect?
I'm using Qt 5.12.8, although I can test on 5.15.1 and 6.0.0 if needed.
-
ApplicationWindow'sidis in scope in the whole application, so it should be possible to do this:onClicked: root.stackView.push("myQmlFile.qml");You may need to expose
stackViewas a property, like this:ApplicationWindow { id: root property alias stack: stackViewIf this approach fails, you can always add a signal in
HomePageand react to it elsewhere:Page { id: pageRoot signal buttonClicked(string path) Button { onClicked: pageRoot.buttonClicked("myQmlFile.qml") -
ApplicationWindow'sidis in scope in the whole application, so it should be possible to do this:onClicked: root.stackView.push("myQmlFile.qml");You may need to expose
stackViewas a property, like this:ApplicationWindow { id: root property alias stack: stackViewIf this approach fails, you can always add a signal in
HomePageand react to it elsewhere:Page { id: pageRoot signal buttonClicked(string path) Button { onClicked: pageRoot.buttonClicked("myQmlFile.qml")