Question

I'm currently writing an application in PySide, and I want it to save the window dimensions upon exiting. The geometry() method retuns something like PySide.QtCore.QRect(300, 300, 550, 150) but all I want is (300, 300, 550, 150). I could find a way to parse it, but I want a cleaner method. Any suggestions?

Was it helpful?

Solution

The cleaner way, without any parsing, would be to use QSettings to store and retrieve the QRect returned by geometry to/from the native application settings storage (Windows registry, .ini file, .plist file...).

For example:

settings = QSettings(...);    
settings.setValue("lastGeometry", self.geometry())

# and to retrieve the value
lastGeometry = settings.value("lastGeometry")
if lastGeometry.isValid():
    self.setGeometry(lastGeometry)

You can also binary serialize or deserialize a QRect with QDataStream to a 16 byte array representing the 4 32-bit integers.

OTHER TIPS

The getRect method returns a tuple of the values:

>>> widget.geometry().getRect()
(0, 0, 640, 480)

Considering OP has accepted the one from @alexisdm this might be interesting:

I was looking into using restoreGeometry() as it handles recovering outside of screen windows and ones that are out of the top border. BUT: it needs a QByteArray and I can only save plain Python data in my case. So I tried to turn the byte array into a string:

encoded = str(self.saveGeometry().toPercentEncoding())
print('encoded: %s' % encoded)
>>> encoded: %01%D9%D0%CB%00%01%00%00%FF%F...

geometry = QtCore.QByteArray().fromPercentEncoding(encoded)
self.restoreGeometry(geometry)

Voilà!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top