Skip to content

Instantly share code, notes, and snippets.

@eyllanesc
Last active June 26, 2022 20:11
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eyllanesc/be8a476bb7038c7579c58609d7d0f031 to your computer and use it in GitHub Desktop.
Save eyllanesc/be8a476bb7038c7579c58609d7d0f031 to your computer and use it in GitHub Desktop.
Functions to save and restore Widgets in PyQt.
import sys
from PyQt5.QtCore import QFileInfo, QSettings
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import qApp, QApplication, QMainWindow, QFormLayout, QLineEdit, QTabWidget, QWidget, QAction
def restore(settings):
finfo = QFileInfo(settings.fileName())
if finfo.exists() and finfo.isFile():
for w in qApp.allWidgets():
mo = w.metaObject()
if w.objectName() != "":
for i in range(mo.propertyCount()):
name = mo.property(i).name()
val = settings.value("{}/{}".format(w.objectName(), name), w.property(name))
w.setProperty(name, val)
def save(settings):
for w in qApp.allWidgets():
mo = w.metaObject()
if w.objectName() != "":
for i in range(mo.propertyCount()):
name = mo.property(i).name()
settings.setValue("{}/{}".format(w.objectName(), name), w.property(name))
class mainwindow(QMainWindow):
settings = QSettings("gui.ini", QSettings.IniFormat)
def __init__(self, parent=None):
super(mainwindow, self).__init__(parent)
self.setObjectName("MainWindow")
self.initUI()
restore(self.settings)
def initUI(self):
exitAction = QAction(QIcon('icon\\exit.png'), 'Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.triggered.connect(self.close)
self.toolbar = self.addToolBar('Exit')
self.toolbar.setMovable(False)
self.toolbar.addAction(exitAction)
self.tab_widget = QTabWidget(self) # add tab
self.tab_widget.setObjectName("tabWidget")
self.tab2 = QWidget()
self.tab2.setObjectName("tab2")
self.tab_widget.addTab(self.tab2, "Tab_2")
self.tab2UI()
self.setCentralWidget(self.tab_widget)
def tab2UI(self):
self.layout = QFormLayout()
nameLe = QLineEdit(self)
nameLe.setObjectName("nameLe")
self.layout.addRow("Name", nameLe)
addressLe = QLineEdit()
addressLe.setObjectName("addressLe")
self.layout.addRow("Address", addressLe)
self.tab2.setLayout(self.layout)
def closeEvent(self, event):
save(self.settings)
QMainWindow.closeEvent(self, event)
def main():
app = QApplication(sys.argv)
ex = mainwindow()
ex.setGeometry(100, 100, 1000, 600)
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
from PyQt5.QtCore import QFileInfo
from PyQt5.QtWidgets import qApp
def restore(settings):
finfo = QFileInfo(settings.fileName())
if finfo.exists() and finfo.isFile():
for w in qApp.allWidgets():
mo = w.metaObject()
if w.objectName() != "":
for i in range(mo.propertyCount()):
name = mo.property(i).name()
val = settings.value("{}/{}".format(w.objectName(), name), w.property(name))
w.setProperty(name, val)
def save(settings):
for w in qApp.allWidgets():
mo = w.metaObject()
if w.objectName() != "":
for i in range(mo.propertyCount()):
name = mo.property(i).name()
settings.setValue("{}/{}".format(w.objectName(), name), w.property(name))
@Sibiriak
Copy link

Sibiriak commented Aug 5, 2019

As a beginner I faced a problem to store settings of my GUI such as last opened tabs in QTabWidget, checked states of QCheckBoxes, QRadioButtons etc. So I used your functions to save and restore settings of widgets. It works just partly for me, when I restore settings from *.ini file it displays not all QLabels on the last opened tab and all other tabs appear to be empty.

@vaasu070
Copy link

Hi elly,

I am running the exact code which you have shared above. But why I am getting following error ??

Traceback (most recent call last):
File "/home/vaasu/PycharmProjects/smartcabin/saveLoad.py", line 90, in
main()
File "/home/vaasu/PycharmProjects/smartcabin/saveLoad.py", line 83, in main
ex = mainwindow()
File "/home/vaasu/PycharmProjects/smartcabin/saveLoad.py", line 43, in init
restore(self.settings)
File "/home/vaasu/PycharmProjects/smartcabin/saveLoad.py", line 20, in restore
val = settings.value("{}/{}".format(w.objectName(), name),w.property(name))
EOFError: Ran out of input

@eyllanesc
Copy link
Author

eyllanesc commented Dec 11, 2019

@vaasu070 You could also run your code in the console/CMD since pycharm often does not provide the complete error message.

@LCJebe
Copy link

LCJebe commented Dec 14, 2019

Hi elly,

I am running the exact code which you have shared above. But why I am getting following error ??

Traceback (most recent call last):
File "/home/vaasu/PycharmProjects/smartcabin/saveLoad.py", line 90, in
main()
File "/home/vaasu/PycharmProjects/smartcabin/saveLoad.py", line 83, in main
ex = mainwindow()
File "/home/vaasu/PycharmProjects/smartcabin/saveLoad.py", line 43, in init
restore(self.settings)
File "/home/vaasu/PycharmProjects/smartcabin/saveLoad.py", line 20, in restore
val = settings.value("{}/{}".format(w.objectName(), name),w.property(name))
EOFError: Ran out of input

I'm getting the same error (using PySide2). Any ideas?

@eyllanesc
Copy link
Author

@LCJebe You could also run your code in the console/CMD since pycharm often does not provide the complete error message.

@flaviodelgrosso
Copy link

flaviodelgrosso commented Apr 17, 2020

It should be usefull insert a way to save and reload items from QListWidget @eyllanesc

@Zythyr
Copy link

Zythyr commented Oct 2, 2020

@eyllanesc
Using your example save/restore functions, I was having issues restoring QLabel. When restoring the QLabel would disappear. You posted a revised updated solution here, https://stackoverflow.com/a/60028282/4988010. I want to confirm if the revised solution it the best and universal approach to saving/restoring instead of the this gist?

@houssamfarag
Copy link

I tried using with pyside2 but qApp Is not available for it
Tried to run with QApplication and getting pickle errors

@eyllanesc
Copy link
Author

@houssamfarag try change qApp to QApplication.instance()

@houssamfarag
Copy link

still giving pickle error with these objects
"inputMethodHints",
"alignment",
"textInteractionFlags"
during save if i use this it can save
if name not in ("inputMethodHints", "alignment", "textInteractionFlags"):

@masoudr
Copy link

masoudr commented Dec 4, 2021

I have two QSpinBox but sometimes when settings restored it get wrong values.

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