Skip to content

Instantly share code, notes, and snippets.

@bootchk
Last active May 1, 2022 16:26
Show Gist options
  • Save bootchk/5330231 to your computer and use it in GitHub Desktop.
Save bootchk/5330231 to your computer and use it in GitHub Desktop.
Python, PySide, Qt implementation of saving/restoring window attributes (size, position, etc.) as settings (preferences) for an application. Mixin: make your custom subclass of QMainWindow multiply inherit this, and call these methods from appropriate places.
'''
Copyright 2013 Lloyd Konneker
License: LGPL
'''
from PySide.QtCore import QSettings
class WindowSettable(object):
'''
Mixin behavior for MainWindow: window attributes persist as Settings
See Qt Application Example, where these are called readSettings() and writeSettings().
Assert that QSettings have been established on app startup:
QCoreApplication.setOrganizationName("Foo")
QCoreApplication.setOrganizationDomain("foo.com")
QCoreApplication.setApplicationName("Bar")
'''
def _readAndApplyWindowAttributeSettings(self):
'''
Read window attributes from settings,
using current attributes as defaults (if settings not exist.)
Called at QMainWindow initialization, before show().
'''
qsettings = QSettings()
qsettings.beginGroup( "mainWindow" )
# No need for toPoint, etc. : PySide converts types
self.restoreGeometry(qsettings.value( "geometry", self.saveGeometry()))
self.restoreState(qsettings.value( "saveState", self.saveState()))
self.move(qsettings.value( "pos", self.pos()))
self.resize(qsettings.value( "size", self.size()))
if qsettings.value( "maximized", self.isMaximized()) :
self.showMaximized()
qsettings.endGroup()
def _writeWindowAttributeSettings(self):
'''
Save window attributes as settings.
Called when window moved, resized, or closed.
'''
qsettings = QSettings()
qsettings.beginGroup( "mainWindow" )
qsettings.setValue( "geometry", self.saveGeometry() )
qsettings.setValue( "saveState", self.saveState() )
qsettings.setValue( "maximized", self.isMaximized() )
if not self.isMaximized() == True :
qsettings.setValue( "pos", self.pos() )
qsettings.setValue( "size", self.size() )
qsettings.endGroup()
@giumas
Copy link

giumas commented May 3, 2015

Is this code snippet portable if qsettings.value( "maximized", self.isMaximized()):?

pyside/PySide#124 (comment)

@nate-h
Copy link

nate-h commented Oct 30, 2016

note: qsettings.value( "maximized") read as a lowercase false string for me which registered as true for the if statement.
My way around this was:

def str2bool(self, strBool):
if type(strBool) == type(True):
return strBool
return strBool.lower() in ("yes", "true", "t", "1")

...

   maximized = qsettings.value("maximized", self.isMaximized())

    # apply settings
    self.restoreGeometry(qsettings.value("geometry", self.saveGeometry()))
    self.restoreState(qsettings.value("saveState", self.saveState()))
    self.move(qsettings.value( "pos", self.pos()))
    self.resize(qsettings.value( "size", self.size()))
    if self.str2bool(maximized) :
        self.showMaximized()

....

@tisaconundrum2
Copy link

Here's my iteration, for the sake of knowledge and anyone who was having a bunch of trouble with maximizing.

    def _writeWindowAttributeSettings(self):
        '''
        Save window attributes as settings.

        Called when window moved, resized, or closed.
        '''
        self.settings.beginGroup("mainWindow")
        self.settings.setValue("pos", self.MainWindow.pos())
        self.settings.setValue("maximized", self.MainWindow.isMaximized())
        if not self.MainWindow.isMaximized():
            self.settings.setValue("size", self.MainWindow.size())

        self.settings.endGroup()

    def _readAndApplyWindowAttributeSettings(self):
        '''
        Read window attributes from settings,
        using current attributes as defaults (if settings not exist.)

        Called at QMainWindow initialization, before show().
        '''
        self.settings.beginGroup("mainWindow")
        # No need for toPoint, etc. : PySide converts types
        try:
            self.MainWindow.move(self.settings.value("pos"))
            if self.settings.value("maximized") in 'true':
                self.MainWindow.showMaximized()
            else:
                self.MainWindow.resize(self.settings.value("size"))
        except:
            pass
        self.settings.endGroup()

You'll notice I'm using self.MainWindow. change that as necessary for your code

@excalamus
Copy link

It's worth mentioning that this all needs to happen after the widgets have been made. Obvious in hindsight; not so clear when trying to debug. Thanks @bootchk for putting all this info in one spot.

FWIW, here's where in the docs this stuff is mentioned: https://doc.qt.io/qtforpython-5/PySide2/QtCore/QSettings.html?highlight=qsettings#restoring-the-state-of-a-gui-application

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment