How to make qml window retain its position and size in qt5
-
I am trying to make my application window which is written in qml to retain its size and position once i close the application. I came across using Settings to do the same, but my application is not able to retain its position and size after i reopen it. Below is snippet of code i have written
import QtQuick 2.12
import QtQuick.Controls 2.5
import QtQuick.Shapes 1.12
import QtQuick.Window 2.12
import QtQuick.Layouts 1.14
import Qt.labs.settings 1.0Window {
id: rootWindow
visible: falseminimumWidth: 975//screenInfo.availableWidth * 0.7 minimumHeight: 440//screenInfo.availableHeight * 0.7 //Default Windowed size width: 1463 height: 660 title: "" color: "transparent" //property bool enableCustomTitleBar: (Qt.platform.os == "windows") property bool enableCustomTitleBar: true property string lastSaveAsDialogTextFieldEdited: "fileNameTextField" property bool venueNameChangedFromFileName: false property bool venueNameEdited : false property bool progressDialogVisibility : false property int groupBy: 0 // Property to store window position and size property var windowGeometry: null // Declare the Settings component at the root level to store window properties Settings { id: appSettings category: "WindowGeometry" property string organizationName : "abc" property string organizationDomain : "abc.com" property string windowState: 'maximized' property int windowLeft: 0 property int windowTop: 0 property int windowWidth: 1200 property int windowHeight: 720 } Component.onCompleted: { flags = enableCustomTitleBar ? (flags | Qt.CustomizeWindowHint | Qt.FramelessWindowHint | Qt.WindowMinimizeButtonHint) : flags // Load the window properties if they were previously saved if (appSettings.windowState === 'maximized') { rootWindow.visibility = Qt.WindowMaximized } else { rootWindow.x = appSettings.windowLeft rootWindow.y = appSettings.windowTop rootWindow.width = appSettings.windowWidth rootWindow.height = appSettings.windowHeight } visible = true }
onClosing :
{
console.info("Quit is invoked from means other than TitleBar ")
if (rootWindow.visibility === Qt.WindowMaximized) {appSettings.windowState = 'maximized' } else { appSettings.windowState = 'normal' appSettings.windowLeft = rootWindow.x appSettings.windowTop = rootWindow.y appSettings.windowWidth = rootWindow.width appSettings.windowHeight = rootWindow.height } if(rootWindow.visibility == Window.Minimized) { rootWindow.requestActivate() rootWindow.visibility = Window.Maximized }
where am i going wrong ?
-
@supratik123 The problem is that you overwrite the Settings properties with your default values.
The easiest way would be to do alias properties in your Settings object (
property alias windowLeft: rootWindow.x
) and set your default in your Window.