PyQt 4 - 将窗口中的所有数据保存到app close文件中

时间:2011-02-11 18:01:12

标签: python pyqt

有没有一种快速的python方法可以在app关闭之前将所有小部件中的所有数据保存到文件中? 当然,阅读它并在应用程序重新运行后恢复?

2 个答案:

答案 0 :(得分:4)

QWidget.saveGeometry保存小部件的几何图形 QMainWindow.saveState保存窗口的工具栏和dockwidgets 为了保存其他东西,你可以使用泡菜。

答案 1 :(得分:1)

根据问题How to remember last geometry of PyQt application?并完成@Artur Gaspar的回答,这是一个完整的示例:

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_()