首页 文章

从控件访问QML StackView

提问于
浏览
0

很抱歉可能是一个愚蠢的问题 - 我对QML很新 .

我的StackView的一个页面:

Page
{
    id : root

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

BackButton代码:

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

我已经尝试过parent.StackView了 . 没运气 . 获得:

TypeError: Cannot call method 'pop' of null

有解决方案吗?

2 回答

  • 1

    我建议这样的事情 .

    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()
    }
    

    这样,您不依赖于组件外部的 id . 相反,您传入了希望BackButton操作的实例 - 这在将来重构时不那么脆弱 .

  • 2
    • 在Qt或Visual Studio 2015中存在某种错误 . 通常在对QML进行一些修改后需要完全重建 .

    • root.StackView.view.pop()是正确的 .

相关问题