0

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?

Alexander Dyagilev
  • 1,139
  • 1
  • 15
  • 43
  • For future reference, please take a look at the instructions about how to create a minimal example over at https://stackoverflow.com/help/mcve - in the current form, your example is not at all complete (it doesn't include imports, and does not show a StackView at all). – Robin Burchell Jan 14 '17 at 20:39

2 Answers2

2

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.

Robin Burchell
  • 871
  • 5
  • 9
1
  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.
Alexander Dyagilev
  • 1,139
  • 1
  • 15
  • 43