本页内容

Qt Quick 示例 - 窗口和屏幕

本示例演示了 QML 中的 Window 和 Screen 类型。

包含可见性按钮和屏幕属性的控制窗口,以及一个辅助的测试窗口

“窗口”和“屏幕”展示了如何:

  • 在 QML 中创建窗口
  • 控制其visibility
  • 在应用程序启动时显示启动画面
  • 访问窗口的属性Screen

此外,本章节还演示了如何将 QML 打包为资源并提供图标,以创建一个独立的 QML 桌面应用程序。

运行示例

您可以通过以下方式运行该示例:

窗口实现

可通过Qt.SplashScreen 标志创建启动画面,并应将其ApplicationModal ,以防止与主窗口发生交互。如果启动窗口也是透明的,并且显示部分透明的图像,那么它看起来就像一个异形窗口。

Window {
    id: splash
    color: "transparent"
    title: "Splash Window"
    modality: Qt.ApplicationModal
    flags: Qt.SplashScreen
    property int timeoutInterval: 2000
    signal timeout

在此示例中,Timer 会自动关闭启动画面,但在实际应用中,您可能需要连接到应用程序逻辑发出的信号,以便在初始化完成后隐藏启动画面。

Timer {
    interval: splash.timeoutInterval; running: splash.visible; repeat: false
    onTriggered: splash.exit()
}

本示例中的主窗口是控制窗口,包含一些按钮和复选框,用于控制次级窗口的状态并提供状态反馈。每个复选框都与它所显示状态对应的属性建立了绑定,同时还具有一个 onClicked 处理程序来更改该状态。这是建立双向绑定同时避免绑定循环的典型模式。

CheckBox {
    text: "Windowed"
    height: showButton.height
    width: col.cellWidth
    Binding on checked { value: root.testWindow.visibility === Window.Windowed }
    onClicked: root.testWindow.visibility = Window.Windowed
}

Screen 拥有若干属性,这些属性通常对以下应用非常有用:当屏幕方向改变时需要旋转某些内容、在屏幕上定位窗口,或者将实际单位转换为逻辑像素单位。 CurrentScreen.qml(该文件在 window.qml 中内联显示,也可通过qml 工具单独运行)仅用于显示属性值,而启动画面则利用这些值将窗口居中显示在屏幕上。

    x: (Screen.width - splashImage.width) / 2
    y: (Screen.height - splashImage.height) / 2

如果将 `Window ` 嵌套在 `Item ` 或其他窗口内部,则内层窗口对外层窗口而言将成为瞬态窗口(更多说明请参阅Window )。但若需将多个顶级窗口作为互不相关的对等窗口创建,可像本示例所示,将其置于非视觉的 `QtObject ` 根项中。

示例项目 @ code.qt.io

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.