一半君的总结纸

听话只听一半君

如何使用QSettings保存pyqt gui的设置

如果想保存上次运行时的信息如窗口大小位置或者用户设置,可以用QSettings class, 这和maya的optionvar有点像

下面这个例子使用的是api v2,所以self.settings.value(‘size’, QtCore.QSize(270, 225)) 在找不到到保存的size的时候,返回的是None,此时会自动使用QtCore.QSize(270, 225)作为返回值,如果你不用api v2 那么找不到size的时候,返回的是QVariant,那这行就要改一改了

linux下 NativeFormat 和 IniFormat 都是存在 $HOME/.config 里, windows下前者存在注册表里,后者存在%APPDATA%或者%COMMON_APPDATA%文件夹里

from sip import setapi
setapi("QVariant", 2)

from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import QTabWidget, QApplication
from PyQt4.QtCore import QSettings

class AbcApp(QTabWidget):
    def __init__(self):
        super(AbcApp, self).__init__()

        self.settings = QSettings('settings.ini', QSettings.IniFormat)
        self.settings.setFallbacksEnabled(False)    # File only, no fallback to registry or or.

        # Initial window size/pos last saved if available
        self.resize(self.settings.value('size', QtCore.QSize(270, 225)))
        self.move(self.settings.value('pos', QtCore.QPoint(50, 50)))

        self.tab = QtGui.QWidget()
        self.textEdit = QtGui.QTextEdit(self.tab)
        self.textEdit.setHtml('<font color=grey>[QTextEdit area]</font><p><center><font color=blue size=4><b>Allo Woyld</b></font></center>')
        self.addTab(self.tab, 'tab1')

    def closeEvent(self, e):
        self.settings.setValue('size', self.size())
        self.settings.setValue('pos', self.pos())
        e.accept()

if __name__ == '__main__':
    app = QApplication([])
    frame = AbcApp()
    frame.show()
    app.exec_()

参考:
QSettings(): How to save to current working directory
QSettings Class Reference

Advertisements

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s

%d 博主赞过: