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_()
精彩评论