使用QML保存窗口状态

时间:2015-07-15 09:28:16

标签: qt window qml settings qtquick2

有没有一种很好的方法来记录QtQuick应用程序的窗口状态?该文档提供了以下方法:

Settings {
    property alias x: mainWindow.x
    property alias y: mainWindow.y
    property alias width: mainWindow.width
    property alias height: mainWindow.height

然而,这有三个缺陷:

  1. 调整窗口大小/移动时,它会连续写入设置文件。
  2. 它不记得窗口是否最大化(Notepad ++也受到这个恼人的缺陷btw)。
  3. 如果最大化窗口,则不会保存未最大化的几何体。
  4. 有没有人有更好的代码?

1 个答案:

答案 0 :(得分:0)

根据Timmmm的回答,但可能更适合。

import QtQuick 2.10
import QtQuick.Window 2.10
import QtQuick.Controls 2.3
import Qt.labs.settings 1.0

Item
{
    property Window window
    property string windowName: ""

    Settings
    {
        id: s
        category: windowName
        property int x
        property int y
        property int width
        property int height
        property int visibility
    }

    Component.onCompleted:
    {
        if (s.width && s.height)
        {
            window.x = s.x;
            window.y = s.y;
            window.width = s.width;
            window.height = s.height;
            window.visibility = s.visibility;
        }
    }

    Connections
    {
        target: window
        onXChanged: saveSettingsTimer.restart()
        onYChanged: saveSettingsTimer.restart()
        onWidthChanged: saveSettingsTimer.restart()
        onHeightChanged: saveSettingsTimer.restart()
        onVisibilityChanged: saveSettingsTimer.restart()
    }

    Timer
    {
        id: saveSettingsTimer
        interval: 1000
        repeat: false
        onTriggered: saveSettings()
    }

    function saveSettings()
    {
        switch(window.visibility)
        {
        case ApplicationWindow.Windowed:
            s.x = window.x;
            s.y = window.y;
            s.width = window.width;
            s.height = window.height;
            s.visibility = window.visibility;
            break;
        case ApplicationWindow.FullScreen:
            s.visibility = window.visibility;
            break;
        case ApplicationWindow.Maximized:
            s.visibility = window.visibility;
            break;
        }
    }
}

用法。像这样:

ApplicationWindow 
{
    id: mainWindow
    WindowStateSaver 
    {
        window: mainWindow
        windowName: "mainWindow"
    }
}