I have a QDialog, and when the user closes the QDialog, and reopens it later, I want to remember the location and open the window at the exact same spot. How would I exactly remember that location?
I have a QDialog, and when the user closes the QDialog, and reopens it later, I want to remember the location and open the window at the exact same spot. How would I exactly remember that location?
For that, you can use the saveState()
, saveGeometry()
resize()
and move()
methods, in conjunction with the closeEvent() and QSettings mentioned by the other answers. Here is some example, to get the idea:
class MyWindow(QMainWindow):def __init__(self, parent):QMainWindow.__init__(self, parent)self.settings = QSettings("MyCompany", "MyApp")self.restoreGeometry(self.settings.value("geometry", ""))self.restoreState(self.settings.value("windowState", ""))def closeEvent(self, event):self.settings.setValue("geometry", self.saveGeometry())self.settings.setValue("windowState", self.saveState())QMainWindow.closeEvent(self, event)
EDIT:
Updated answer to use PyQt API v2. If using API v1, you have to manually cast the result of settings.value()
to a ByteArray like
self.restoreState(self.settings.value("windowState").toByteArray())
I also used the window's own size()
and pos()
, since I'm already loading the windows from a .ui
file. You may set it to defaults before those lines if coding the window from scratch. For the state, I'm defaulting to an empty string, which the function happily accepts as an empty ByteArray and does nothing on the first run.