首页 > 解决方案 > Qt/QML MainWindow and StackView page communication using signal or global variables

问题描述

I would like to implement key handlers for different pages of a StackView. The problem with StackView is that it uses "item" attribute to display a qml page. Therefore, what's declared inside a StackView page (e.g. HomePage.qml), since it is not instantiated explicitly, is not visible to main.qml.

In order to overcome this problem, I am trying to declare a signal at window and place its callback in StackView page (it's dumb, but please suggest what else to do). Here is how it roughly looks:

main.qml
-----------
Window {
    id: window

    signal keyReceived();
    property var key;

    StackView {
        id:stackView
        initialItem: "HomePage.qml"
    }
}

HomePage.qml
-------------
Page {
    id: homePage
    window.onKeyReceived:{
         // Here "window" is not recognized, since this type of use does not exist?
    }
}

All in all, I want to be able to declare a global variable that is visible in both main.qml and HomePage.qml, and be able to notified by the changes to that variable. Be it with signals or other things, does not matter. Any help is greatly appreciated.

标签: qtqml

解决方案


干得好:

Page {
    id: homePage
    Connections {
        target: window
        onKeyReceived: {
        }
    }
}

这将起作用的原因是它在运行时使用 QML 上下文链接StackView直到Window解析windowid 引用。

您的第一种方法不起作用的原因是对当前类型之上的信号处理程序的引用不是静态可解析的。即 QML 不知道谁将成为Page运行时的父级,因此它无法解析的类型,window因此无法解析信号的类型和参数keyReceived。这些类型的引用仅适用于当前类型以及在其下静态定义的所有子类型。

因此,每当您需要连接到 QML 无法确定静态定义的类型时(如上下文链上的引用),您必须使用一个Connections对象,该对象将在运行时解决所有这些问题。


推荐阅读