Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

python - How to remember last geometry of PyQt application?

I am using PyQt5 5.5.1 (64-bit) with Python 3.4.0 (64-bit) on Windows 8.1 64-bit.

I am having trouble restoring the position and size (geometry) of my very simple PyQt app.

Here is minimal working application:

import sys
from PyQt5.QtWidgets import QApplication, QWidget

class myApp(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()


    def initUI(self):
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    view = myApp()
    sys.exit(app.exec())

What I read online is that this is the default behavior and we need to use QSettings to save and retrieve settings from Windows registry, which is stored in

\HKEY_CURRENT_USERSoftware{CompanyName}{AppName}

Here are some of the links I read.

I could have followed those tutorials but those tutorials/docs were written for C++ users.

C++ is not my glass of beer, and converting those codes are impossible to me.


Related:

QSettings(): How to save to current working directory

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This should do.

import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtCore import QSettings, QPoint, QSize

class myApp(QWidget):
    def __init__(self):
        super(myApp, self).__init__()

        self.settings = QSettings( 'My company', 'myApp')     

        # Initial window size/pos last saved. Use default values for first time
        self.resize(self.settings.value("size", QSize(270, 225)))
        self.move(self.settings.value("pos", QPoint(50, 50)))

    def closeEvent(self, e):
        # Write window size and position to config file
        self.settings.setValue("size", self.size())
        self.settings.setValue("pos", self.pos())

        e.accept()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    frame = myApp()
    frame.show()
    app.exec_()

I simplified this example: QSettings(): How to save to current working directory


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...