1

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?

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
Sotanaht
  • 167
  • 2
  • 8

3 Answers3

5

The getRect method returns a tuple of the values:

>>> widget.geometry().getRect()
(0, 0, 640, 480)
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
3

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.

alexisdm
  • 29,448
  • 6
  • 64
  • 99
  • I'm trying to make this application cross-platform, but mainly it has to work on Linux, so would this still be feasible? Would this have any advantage over saving the tuple returned from getRect() to a text file instead? – Sotanaht Mar 07 '12 at 03:44
  • 1
    The main advantage is that, if you set the `applicationName` and `organizationName` properties in you `QApplication` object, your configuration will be automatically stored at the [platform standard location](http://qt-project.org/doc/qt-4.8/qsettings.html#locations-where-application-settings-are-stored) for configuration data, so you don't have to write any platform specific code for that part. You have also type safety, concurrent access from multiple process, and you can store most of [the Qt value types supported by `QVariant`](http://qt-project.org/doc/qt-4.8/qvariant.html#Type-enum). – alexisdm Mar 07 '12 at 12:08
  • I think I might actually use this instead. Currently I have to store each number in the tuple as a separate variable, because ConfigParser reads the tuple as a string. – Sotanaht Mar 14 '12 at 04:03
1

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à!

ewerybody
  • 1,443
  • 16
  • 29