You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让QML Window从全屏状态直接切换至最大化?

QML全屏转最大化异常的修复

问题原因

Qt的Window组件默认会监听Esc键,将全屏状态自动切换为普通窗口状态,且这个默认处理逻辑的优先级高于自定义按键事件。导致第一次按下Esc时,系统先把窗口切换为普通状态,我们设置的Maximized被覆盖,需要再次按键才能触发自定义逻辑。

解决方案

在自定义的Esc按键处理代码中,添加event.accepted = true,阻止事件继续向上传递给Window的默认处理逻辑,这样就能直接执行最大化设置,无需按两次Esc。

修改后的代码

import QtQuick 2.15
import QtQuick.Window 2.15

Window {
    id: topLevelWindow

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

    visibility: Window.FullScreen

    Rectangle {
        id: rect

        anchors.fill: parent
        color: "lightBlue"

        focus: true
        Keys.onPressed: {
            if (event.key === Qt.Key_Escape) {
                rect.color = "lightGreen"
                topLevelWindow.visibility = Window.Maximized
                event.accepted = true // 阻止事件传递,禁用系统默认的全屏退出逻辑
            }
        }
    }
}

说明

添加event.accepted = true后,Esc键的事件会被自定义逻辑完全处理,不会再触发Window默认的全屏转普通窗口行为,按下一次Esc就能直接切换到最大化状态。

内容的提问来源于stack exchange,提问作者maldata

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 23:51:18