Skip to content

Instantly share code, notes, and snippets.

@eyllanesc
Last active June 26, 2022 20:11
Show Gist options
  • 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))
@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