Before I attempt to write my own Python PyQt4 module functions... I wanted to ask if anyone has such a function to share.
In many of my python programs where I have a GUI built using PyQt4 and qtDesigner, I use the QSettings method to save and restore UI states and values of all widgets during close and startup.
This example shows how I save and restore some lineEdit, checkBox, and radioButton fields.
Does anyone have a function that can traverse the UI and find ALL widgets/controls and their states and save them (e.g. guisave()) and another function that can restore them (e.g. guirestore())?
My closeEvent looks something like this:
#---------------------------------------------
# close by x OR call to self.close
#---------------------------------------------
def closeEvent(self, event): # user clicked the x or pressed alt-F4...
UI_VERSION = 1 # increment this whenever the UI changes significantly
programname = os.path.basename(__file__)
programbase, ext = os.path.splitext(programname) # extract basename and ext from filename
settings = QtCore.QSettings("company", programbase)
settings.setValue("geometry", self.saveGeometry()) # save window geometry
settings.setValue("state", self.saveState(UI_VERSION)) # save settings (UI_VERSION is a constant you should increment when your UI changes significantly to prevent attempts to restore an invalid state.)
# save ui values, so they can be restored next time
settings.setValue("lineEditUser", self.lineEditUser.text());
settings.setValue("lineEditPass", self.lineEditPass.text());
settings.setValue("checkBoxReplace", self.checkBoxReplace.checkState());
settings.setValue("checkBoxFirst", self.checkBoxFirst.checkState());
settings.setValue("radioButton1", self.radioButton1.isChecked());
sys.exit() # prevents second call
My MainWindow init looks something like this:
def __init__(self, parent = None):
# initialization of the superclass
super(QtDesignerMainWindow, self).__init__(parent)
# setup the GUI --> function generated by pyuic4
self.setupUi(self)
#---------------------------------------------
# restore gui position and restore fields
#---------------------------------------------
UI_VERSION = 1
settings = QtCore.QSettings("company", programbase) # http://pyqt.sourceforge.net/Docs/PyQt4/pyqt_qsettings.html
self.restoreGeometry(settings.value("geometry"))
self.restoreState(settings.value("state"),UI_VERSION)
self.lineEditUser.setText(str(settings.value("lineEditUser"))) # restore lineEditFile
self.lineEditPass.setText(str(settings.value("lineEditPass"))) # restore lineEditFile
if settings.value("checkBoxReplace") != None:
self.checkBoxReplace.setCheckState(settings.value("checkBoxReplace")) # restore checkbox
if settings.value("checkBoxFirst") != None:
self.checkBoxFirst.setCheckState(settings.value("checkBoxFirst")) # restore checkbox
value = settings.value("radioButton1").toBool()
self.ui.radioButton1.setChecked(value)