对于一款可以直接从闪存/笔式驱动器/USB/跳马盘运行的应用程序,为了在不同机器之间实现可移植性,将用户设置存储在内存棒中与从中运行程序的相同目录中(而不是每台机器的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_()
由于我目前正在Windows上运行,因此创建了此.ini文件: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_()