如何将QMenu设置保存到外部配置文件以及如何在以后重新应用它们

时间:2015-01-14 00:45:33

标签: python qt pyqt qmainwindow

以下代码在每个应用程序的开始和退出时保存,读取和重新应用配置设置。 除了主窗口的大小,我希望能够保存QMenu状态。

enter image description here

from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.iniFile=os.path.join( os.path.expanduser('~'), 'gui.ini')
        self.settings=QSettings(self.iniFile, QSettings.IniFormat)
        self.onStart()  
    def closeEvent(self, e):
        result = QMessageBox.question(self,"Confirm window","Are you sure you want to close the window?",QMessageBox.Yes | QMessageBox.No,QMessageBox.No)
        if result == QMessageBox.Yes:
            self.onExit()
            self.destroy(True)
            sys.exit()
        else:
            e.ignore()

    def onExit(self):
        self.settings.setValue("WindowGeometry", self.saveGeometry())
        self.settings.setValue("WindowState", self.saveState())
        print "Success: gui.ini was saved as %s"%self.iniFile

    def onStart(self):    
        windowGeometry=self.settings.value("WindowGeometry")
        if windowGeometry:
            windowGeometry=windowGeometry.toByteArray()
            if windowGeometry:
                self.restoreGeometry(windowGeometry) 
        else:
            self.resize(200,50)

        windowState=self.settings.value("WindowState")
        if windowState:
            windowState=windowState.toByteArray()
            if windowState:
                self.restoreState(windowState) 

class Window(MainWindow):
    def __init__(self):
        super(Window, self).__init__()        
        menu=QMenu()
        menu1=menu.addAction("Menu01")     
        menu2=menu.addAction("Menu02")
        menu1.triggered.connect(self.onTrigger)
        menu2.triggered.connect(self.onTrigger)
        menu1.setCheckable(True)
        menu2.setCheckable(True)

        button=QToolButton(self)
        button.setText('Click Here')

        button.setPopupMode(button.InstantPopup)
        button.setMenu(menu)

    def onTrigger(self, arg):
        print arg, type(arg)

app=QApplication(sys.argv)
view=Window() 
view.show()
sys.exit(app.exec_())

0 个答案:

没有答案