Skip to content

Instantly share code, notes, and snippets.

@meramsey
Forked from dgovil/windowPositions.py
Last active June 12, 2020 22:20
Show Gist options
  • Save meramsey/2867e163946e180eaba81ee56dfa1315 to your computer and use it in GitHub Desktop.
Save meramsey/2867e163946e180eaba81ee56dfa1315 to your computer and use it in GitHub Desktop.
Saving Window Positions in PyQt or PySide
# First lets import the two modules we'll need from Qt
from Qt import QtWidgets, QtCore
# Then we create our Window class, in this case from a QDialog
class MyWindow(QtWidgets.QDialog):
def __init__(self):
# We use the __init__ method to initialize it
# The super function gets the class we are inheriting from (in this case QDialog) and calls its' __init__ as well
super(MyWindow, self).__init__()
# We set a title
self.setWindowTitle('Demo of Saving Preferences')
# Then we create a QSettings for our tool. Qt stores this using your company name and your application name
# This setting is then saved in the correct place for your user and their operating system
# Qt takes care of that for you, so you don't need to worry about handling it on different operating systems etc..
# Your company name can be just your name but should remain consistent between your tools.
# Your tool name should however be unique to each tool or application you create.
self.settings = QtCore.QSettings('ImaginaryCompany', 'ToolName')
# Then we look at our settings to see if there is a setting called geometry saved. Otherwise we default to an empty string
geometry = self.settings.value('geometry', bytes('', 'utf-8'))
# Then we call a Qt built in function called restoreGeometry that will restore whatever values we give it.
# In this case we give it the values from the settings file.
self.restoreGeometry(geometry)
def closeEvent(self, event):
# Now we define the closeEvent
# This is called whenever a window is closed.
# It is passed an event which we can choose to accept or reject, but in this case we'll just pass it on after we're done.
# First we need to get the current size and position of the window.
# This can be fetchesd using the built in saveGeometry() method.
# This is got back as a byte array. It won't really make sense to a human directly, but it makes sense to Qt.
geometry = self.saveGeometry()
# Once we know the geometry we can save it in our settings under geometry
self.settings.setValue('geometry', geometry)
# Finally we pass the event to the class we inherit from. It can choose to accept or reject the event, but we don't need to deal with it ourselves
super(MyWindow, self).closeEvent(event)
# Now lets create an instance of our window
win = MyWindow()
# and then show it.
win.show()
# Now move and resize the UI
# Then close it
# When you reopen it, it will restore its position
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment