对于可以直接从 flash/pen/usb/jump/thumb 驱动器运行的应用程序,为了从一台机器移动到另一台机器的可移植性,将用户设置存储在与程序正在从(而不是 Windows/Mac/Linux 用户或每台机器的系统目录)运行。
QSettings() 很方便,但是,可以告诉它使用当前工作目录吗?
这是一个小示例程序,它使用 QSettings() 保持其屏幕位置从运行到运行:
from PySide import QtGui, QtCore
from PySide.QtGui import QTabWidget, QApplication
from PySide.QtCore import QSettings
class AbcApp(QTabWidget):
def __init__(self):
super(AbcApp, self).__init__()
self.settings = QSettings(QSettings.IniFormat,QSettings.SystemScope, '__MyBiz', '__settings')
self.settings.setFallbacksEnabled(False) # File only, not registry or or.
# setPath() to try to save to current working directory
self.settings.setPath(QSettings.IniFormat,QSettings.SystemScope, './__settings.ini')
# Initial window size/pos last saved
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):
# Write window size and position to config file
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_()
这个 .ini 文件是因为我现在恰好在 Windows 上运行而创建的:C:\Documents and Settings\All Users\Application Data__MyBiz__settings.ini。
UserScope 而不是 SystemScope 没有帮助。
'.'
而不是'./__settings.ini'
没有工作, setPath() 基本上没有效果。
也试过这个无济于事:
filepath = os.getcwd() + '/__settings.ini'
self.settings.setPath(QSettings.IniFormat,QSettings.SystemScope, filepath)
参考:https ://doc.qt.io/archives/qt-4.8/qsettings.html http://www.pyside.org/docs/pyside/PySide/QtCore/QSettings.html
虽然我不知道如何适应 PySide,但很有希望:
http ://www.qtcentre.org/archive/index.php/t-35287.html
更新:来自 alexisdm 的答案有效,所以现在是更新的代码:
from PySide import QtGui, QtCore
from PySide.QtGui import QTabWidget, QApplication
from PySide.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_()