Save window position in Settings - handle multiple monitors



  • This example suggests saving the position of the window in settings, and I have seen it being used a lot. This seems to work fine in most cases. But on Windows with multiple monitors, if the app is closed on the secondary monitor, and then restarted with only the primary monitor, the application seems to spawn outside the the visible space.

    What is the recommended way to avoid this behaviour on Windows?


  • Lifetime Qt Champion

    Hi,

    A quick idea: store also the monitor then load and apply it it first then apply the position settings.

    Hope it helps



  • Thanks for the suggestion. Do you think this would be possible in QML or does it need to be done in the C++ code?




  • Lifetime Qt Champion

    You'll likely have to do that by hand. AFAIK, there's no equivalent to the QMainWindow state in the ApplicationWindow class.



  • I ended up saving the saving the available desktop layout on destruction using Screen and Settings, then when the application was re-spawned, moving the window to the middle if the layout wasn't the same anymore.

    Full code example:

    import QtQuick 2.5
    import QtQuick.Layouts 1.1
    import QtQuick.Controls 1.4
    import Qt.labs.settings 1.0
    import QtQuick.Window 2.2
    
    ApplicationWindow {
        id: window
        Component.onCompleted: ensureValidWindowPosition()
        Component.onDestruction: saveScreenLayout()
    
        Settings {
            id: settings
    
            property alias x: window.x
            property alias y: window.y
    
            property var desktopAvailableWidth
            property var desktopAvailableHeight
        }
    
        function saveScreenLayout() {
            settings.desktopAvailableWidth = Screen.desktopAvailableWidth
            settings.desktopAvailableHeight = Screen.desktopAvailableHeight
        }
    
        function ensureValidWindowPosition() {
            var savedScreenLayout = (settings.desktopAvailableWidth === Screen.desktopAvailableWidth)
                    && (settings.desktopAvailableHeight === Screen.desktopAvailableHeight)
            window.x = (savedScreenLayout) ? settings.x : Screen.width / 2 - window.width / 2
            window.y = (savedScreenLayout) ? settings.y : Screen.height / 2 - window.height / 2
        }
    }
    

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.