Access QML StackView from a control

谁说我不能喝 提交于 2019-12-12 02:27:45

问题


Sorry for probably a stupid question - I'm very new to QML.

One of my StackView's pages:

Page
{
    id : root

    header: ToolBar
    {   
        BackButton
        {
            anchors.left: parent.left
        }
    }
}

BackButton code:

Button
{
    text: "<"
    font.pixelSize: 20
    width: 30
    onClicked: parent.root.StackView.view.pop()
}

I've tried parent.StackView also. No luck. Getting:

TypeError: Cannot call method 'pop' of null

Is there a solution?


回答1:


I'd suggest something like this.

main.qml:

import QtQuick 2.6
import QtQuick.Controls 2.0

StackView {
    id: stackView
    initialItem: Page {
        header: ToolBar {
            BackButton {
                anchors.left: parent.left
                view: stackView
            }
        }
    }
}

BackButton.qml:

import QtQuick 2.6
import QtQuick.Controls 2.0

Button {
    property StackView view
    text: "<"
    font.pixelSize: 20
    width: 30
    onClicked: view.pop()
}

This way, you are not relying on an id from outside the component. Instead, you pass in the instance you want the BackButton to operate on - this is much less fragile when refactoring in the future.




回答2:


  1. There is some sort of bug in Qt or Visual Studio 2015. Full rebuild is required generally after some modifications made to QML.
  2. root.StackView.view.pop() is the correct one.


来源:https://stackoverflow.com/questions/41652163/access-qml-stackview-from-a-control

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