panofish
panofish

Reputation: 7889

How to save and restore checkbox properly in pyqt

I am saving my ui checkbox state on application close and restoring it on application open.

This is my call during the close event:

settings.setValue("checkBoxReplace", self.ui.checkBoxReplace.checkState());

This is my call during the ui initialize:

value = settings.value("checkBoxReplace").toInt()[0]   # ??? works, but is there a more proper way?
self.ui.checkBoxReplace.setCheckState(value)   # restore checkbox

The above calls work, but I wonder if I am reading the stored QVariant properly? I used toInt, but it returns 2 values.

Upvotes: 1

Views: 1483

Answers (1)

ekhumoro
ekhumoro

Reputation: 120638

As has already been pointed out, in PyQt QVariant.toInt returns a tuple of the value, plus a flag indicating whether the conversion was successful. So your code is perfectly correct as it is.

However, it's worth pointing out that you can eliminate these QVariant conversions altogether by adding the following at the start of your program:

import sip
sip.setapi('QVariant', 2)
from PyQt4 import QtCore, QtGui

With this in place, any Qt method that returns a QVariant will return a python type instead (this is only needed for python2; python3 has this behaviour by default). And it is also possible to eliminate QString in the same way - see the docs for more details.

PS: if you're going to go down this route, you should probably also take a look at the Support for QSettings section in the PyQt docs.

Upvotes: 1

Related Questions