开发者

PyQt 4 - save all data in window to file on app close [duplicate]

开发者 https://www.devze.com 2023-02-10 13:10 出处:网络
This question already has answers here: 开发者_开发知识库How to remember last geometry of PyQt application?
This question already has answers here: 开发者_开发知识库 How to remember last geometry of PyQt application? (4 answers) Closed 4 years ago.

Is there a fast python way to save all data in all widgets to file before app is close? And of course read it and restore after app is re-run?


QWidget.saveGeometry saves the geometry of an widget.
QMainWindow.saveState saves the window's toolbars and dockwidgets.
To save other things you can use pickle.


Based on the question How to remember last geometry of PyQt application? and completing @Artur Gaspar answer, this is a full working example:

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

class myApp(QMainWindow):

    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
        windowScreenGeometry = self.settings.value( "windowScreenGeometry" )
        windowScreenState = self.settings.value( "windowScreenState" )

        if windowScreenGeometry:
            self.restoreGeometry( windowScreenGeometry )

        else:
            self.resize( 600, 400 )

        if windowScreenState:
            self.restoreState( windowScreenState )

    def closeEvent(self, e):
        # Write window size and position to config file
        self.settings.setValue( "windowScreenGeometry", self.saveGeometry() )
        self.settings.setValue( "windowScreenState", self.saveState() )
        e.accept()

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号