[使用pyinstaller构建一个文件后,QSettings不起作用

问题描述 投票:0回答:1

[在构建脚本的pyinstaller onefile版本时遇到问题,但我的复选框状态没有保存,但是另一方面,当pyinstaller用文件构建普通exe时,复选框状态已保存并且可以正常工作。

请注意,我正在使用resources(package)> __init__.py来存储我的图标和config.ini,并且图标在onefile或常规构建中均适用。

项目文件图片

“”

__init__.py contents

from pathlib import Path

resources = Path(__file__).parent

config_ini = resources / "config.ini"

My PyQt5 Gui.

import sys

from PyQt5.QtCore import QSettings

import resources

import PyQt5.QtCore
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *



settings = QSettings(str(resources.config_ini), QSettings.IniFormat)


class Window(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.main_ui()
        self.buttons()
        self.layout()
        self.show()
        settings.sync()


    def main_ui(self):
        self.setWindowTitle("Files Organizer")

    def buttons(self):
        self.checkbox_startup = QCheckBox("Run on start up")

        self.checkbox_startup.setChecked(False)
        self.checkbox_startup.setChecked(settings.value("startup_state", type=bool))

        self.checkbox_startup.toggled.connect(self.startup_settings)

    def layout(self):
        self.horizontalGroupBox_options = QGroupBox("Options", self)
        verticalbox_options = QVBoxLayout()
        verticalbox_options.addWidget(self.checkbox_startup)
        self.horizontalGroupBox_options.setLayout(verticalbox_options)
        self.horizontalGroupBox_options.resize(360, 80)
        self.horizontalGroupBox_options.move(20, 110)

    def startup_settings(self):
        startup_state = self.checkbox_startup.isChecked()
        settings.setValue("startup_state", startup_state)
        print("startup state is ", settings.value("startup_state", type=bool))


if __name__ == "__main__":
    app = QApplication(sys.argv)
    screen = Window()
    screen.show()
    app.exec()

python pyqt pyqt5 pyinstaller qsettings
1个回答
0
投票

onefile的工作原理是将其内容提取到一个临时目录中,该目录具有存储在sys._MEIPASS中的路径。所以你在设置值resources.config_ini仅更改提取的文件,该文件已删除关闭程序后

qt在QtCore.QStandardPaths.writableLocation下有一堆路径那可能是您想要存储配置的地方,例如QtCore.QStandardPaths.writableLocation(QtCore.QStandardPaths.AppConfigLocation)返回.../appdata/local/{org}/{app}

这些行是在GUI的开头添加的。

# This return .../appdata/local local_path = QStandardPaths.writableLocation(QStandardPaths.AppConfigLocation) # Make directory for my program os.makedirs(local_path + "\\" + "FilesOrganizer", exist_ok=True) # Making config.ini file. config_path = local_path + "\\" + "FilesOrganizer" + "\\" + "config.ini" settings = QSettings(config_path, QSettings.IniFormat)

© www.soinside.com 2019 - 2024. All rights reserved.