qt - 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.
解决方案
干得好:
Page {
id: homePage
Connections {
target: window
onKeyReceived: {
}
}
}
这将起作用的原因是它在运行时使用 QML 上下文链接StackView
直到Window
解析window
id 引用。
您的第一种方法不起作用的原因是对当前类型之上的信号处理程序的引用不是静态可解析的。即 QML 不知道谁将成为Page
运行时的父级,因此它无法解析的类型,window
因此无法解析信号的类型和参数keyReceived
。这些类型的引用仅适用于当前类型以及在其下静态定义的所有子类型。
因此,每当您需要连接到 QML 无法确定静态定义的类型时(如上下文链上的引用),您必须使用一个Connections
对象,该对象将在运行时解决所有这些问题。
推荐阅读
- javascript - ChartJS 中的条形颜色未更新
- spring-boot - 升级到Spring-boot 2.3.1.RELEASE和kafka,找不到kafka.utils.TestUtils
- java - 在 JOptionPane 内的 JScrollPane 上方添加文本
- javascript - 无法从“App.js”解析“@react-navigation/stack”
- c# - LINQ to Entities 无法识别 System.String
- css - 第一次连接提供了不受支持的 MIME 类型,但在浏览器刷新后工作正常吗?
- ffmpeg - 如何将带有ffmpeg的流保存到块中,但是在临时名称中并将名称更改为const
- android - UnsatisfiedLinkError: dlopen failed: library "libm.so.6" not found - Android Studio 4.0
- graphql - 有没有办法用动态变量调用 useQuery ?
- python - 将 CSV 解析为多个单独的字典