Qt 如何使用qml主文件中的函数将不同视图推送到堆栈视图

Qt 如何使用qml主文件中的函数将不同视图推送到堆栈视图,qt,qml,Qt,Qml,使用qml作为接口处理应用程序。我在主qml文件中有一个堆栈视图,它将qml文件推送到堆栈视图中,qml文件将是一个页面。因为这些页面中有多个页面和按钮,单击这些页面时可能会将不同的页面推到堆栈视图上,所以我在主qml文件中创建了一个函数,当单击按钮时,我将从页面调用该函数。包含许多不同页面的pages文件夹是main.qml文件夹的子目录。该函数用于将页面推送到堆栈视图。但是,单击按钮时,satck视图不会推送新页面 这是下面的代码 主qml文件 import QtQuick 2.15 imp

使用qml作为接口处理应用程序。我在主qml文件中有一个堆栈视图,它将qml文件推送到堆栈视图中,qml文件将是一个页面。因为这些页面中有多个页面和按钮,单击这些页面时可能会将不同的页面推到堆栈视图上,所以我在主qml文件中创建了一个函数,当单击按钮时,我将从页面调用该函数。包含许多不同页面的pages文件夹是main.qml文件夹的子目录。该函数用于将页面推送到堆栈视图。但是,单击按钮时,satck视图不会推送新页面

这是下面的代码

主qml文件

import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
import "pages"



Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    property url source: ""

    function changeView(source){
        stackView.push(Qt.resolvedUrl(source))
    }

    Rectangle {
        id: rectangle
        color: "#391199"
        anchors.fill: parent

        StackView {
            id: stackView
            anchors.fill: parent
            initialItem: Qt.resolvedUrl("pages/homepage.qml")
        }
    }
}

/*##^##
Designer {
    D{i:0;formeditorZoom:0.75}
}
##^##*/
homePage.qml

import QtQuick 2.0
import QtQuick.Controls 2.15
import "qrc:../main.qml" as Main

Item {
    Rectangle {
        id: rectangle
        color: "#08630f"
        anchors.fill: parent

        Button {
            id: button
            x: 478
            y: 255
            text: qsTr("Change ")
            anchors.right: parent.right
            anchors.bottom: parent.bottom
            anchors.rightMargin: 10
            anchors.bottomMargin: 10
            onClicked: {
                source = "pages/nextPage.qml"
                Main.changeView(source)
            }
        }
    }

}
nextPage.qml

import QtQuick 2.0
import QtQuick.Controls 2.15
import "../main.qml" as Main

Item {
    Rectangle {
        id: rectangle
        color: "#08404b"
        anchors.fill: parent

        Button {
            id: button
            x: 478
            y: 255
            text: qsTr("Change ")
            anchors.right: parent.right
            anchors.bottom: parent.bottom
            anchors.rightMargin: 10
            anchors.bottomMargin: 10
            onClicked: {
                Main.changeView("pages/homePage.qml")
            }
        }
    }

}
我怀疑问题来自函数的调用,但我在qml方面有点专业知识。我得到了这个错误:对象[object object]的属性'changeView'不是一个函数

您需要在实际的主窗口上调用changeView函数,而不是在导入时调用

这涉及到一点魔力,你可以给主窗口一个id,它在它的所有子窗口中都是可用的,因为如果你看一个页面文件,你会想知道这个id在那里做什么。因此,请确保选择一个不会与其他id冲突的明智名称,即root将非常糟糕

//main.qml
Window {
    id: main_window

    function changeView(source) { ... }
}

//homePage.qml
Item {
    ...

    Button {
        ...
        onClicked: main_window.changeView("pages/nextPage.qml")
    }
}