Last active
May 1, 2022 16:26
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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