[PyQt] QT save state example

David Cortesi davecortesi at gmail.com
Tue Oct 8 02:22:41 BST 2013


> I'm trying to understand how does save state works using QT...
> ... I only found C++ examples which I cant read,

Being able to mentally translate the C++ code in
the Qt doc into Python is a very useful skill!
It really isn't too hard. Turn :: into dot and add
"self." everywhere.

The first thing to know is how to get control when
the app is quitting and what to do then.
There is an example here:

http://qt-project.org/doc/qt-5.0/qtwidgets/qmainwindow.html#saveState

What this is trying to say is: your main window subclass
(what you called MyWindow in your sample code)
needs to define its own method closeEvent().

What does this method do? You look up to the top
of the QMainWindow page and there is no definition
for closeEvent. This tells you it is inherited.

So you click the link at the top, "List of all
members, including inherited members"
and see closeEvent in the list, click it, and
you are now on the QWidget page. So this is where
QMainWindow inherits closeEvent from.

On that page you get the details of what closeEvent
does and when it is called. Read it.

Now go back to the QMainWindow::saveState link above.

So when your main window is being closed, Qt will
call its closeEvent method. If you do not define
one, nothing is saved at close time. So add
some code to your class like:

   def closeEvent(self, event):
      ...something…

In that method you can use a QSettings object
to save the window size and position ("Geometry").
Maybe back in the __init__ you did this:

      self.settings = QSettings("MyCompany","MyAppname")

Read about the QSettings object here:

http://qt-project.org/doc/qt-5.0/qtcore/qsettings.html

Now in the closeEvent you can do this (not tested!)

      self.settings.setValue("geometry", self.saveGeometry())
      self.settings.setValue("statebytes", self.saveState())

Then, up in your __init__ method, you can use
the settings object to recover the geometry
and the state bytearray from the last time the
program ended. See this link:

http://qt-project.org/doc/qt-5.0/qtwidgets/qmainwindow.html#restoreState

for a very similar example.

In short:

* During shutdown your closeEvent() is called

* in it, you save everything in QSettings

* During __init__ you get everything back by
querying the settings object.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.riverbankcomputing.com/pipermail/pyqt/attachments/20131007/b168bdab/attachment.html>


More information about the PyQt mailing list