読者です 読者をやめる 読者になる 読者になる

アヤチノオト

覚書のこと

QSettingsでツールバーの状態とウィンドウの位置&サイズを保存したり読み込んだり

from PySide.QtGui import QMainWindow, QApplication, QPushButton, QToolBar
from PySide.QtCore import QSettings


class MainWin(QMainWindow):
    
    def __init__(self):
        super(MainWin, self).__init__()
        writeSettingsButton = QPushButton('save state')
        writeSettingsButton.clicked.connect(self.writeSettings)
        readSettingsButton = QPushButton('restore state')
        readSettingsButton.clicked.connect(self.readSettings)
        toolBar = QToolBar('test', self)
        toolBar.addWidget(writeSettingsButton)
        toolBar.addWidget(readSettingsButton)
        toolBar.setObjectName('test')
        self.addToolBar(toolBar)

    def writeSettings(self):
        self.settings = QSettings("/home/tetsuroh/testsetting.dat",
                                  QSettings.IniFormat)
        self.settings.beginGroup("MainWindow")
        self.settings.setValue("geometry", self.saveGeometry())
        self.settings.setValue("state", self.saveState())
        self.settings.endGroup()


    def readSettings(self):
        self.settings = QSettings("/home/ayachi/testsetting.ini",
                                  QSettings.IniFormat)
        self.settings.beginGroup("MainWindow")
        state = self.settings.value('state')
        if state != None:
            self.restoreState(state)
        geometry = self.settings.value('geometry')
        if geometry != None:
            self.restoreGeometry(geometry)
        self.settings.endGroup()

def main():
    import sys
    app = QApplication(sys.argv)
    win = MainWin()
    win.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()