效果
????????每次打開Pyqt5打包后的程序,默認顯示的是上一次的結果
例如下圖的 文件路徑、表名、類型等
????????
大致的思路
????????Pyqt5自帶的方法QSettings實現保存上一次的設置,其思路是讀取ini文件,如果不存在就是程序的初始狀態,如果存在則可以讀取ini文件里面的內容,開發者可將讀取的內容綁定至具體的控件上,實現每一次運行程序,都是加載上一次的狀態
? ? ? ? 關鍵在于:需要開發者選擇將哪些狀態進行保存和加載
?
用法
????????導入包?
? ? ? ? ? ? ? ? from PyQt5.QtCore import QSettings
????????初始化
????????????????QSettings('myapp.ini', QSettings.IniFormat)
class MyMainForm(QMainWindow, Ui_DownloadImages):def __init__(self, parent=None):super(MyMainForm, self).__init__(parent)self.setupUi(self)self.settings = QSettings('myapp.ini', QSettings.IniFormat)
????????保存結果
????????????????self.settings.setValue(key, value)
input_data = {"file_path": "具體的數據","new_dir_path": "具體的數據","col_list": "具體的數據","sheet_name": "具體的數據",'img_width': "具體的數據",'img_height': "具體的數據","write_to_excel": "具體的數據","write_to_dir": "具體的數據","use_agent": "具體的數據",
}
for key, value in input_data.items():self.settings.setValue(key, value)
????????????????程序會在py文件的同級目錄下生一個ini文件,執行上面的代碼時,就會將對應數據寫入這個ini文件
????????加載文件
????????????????self."具體的控件".setText(self.settings.value(key, value))
# 初始化信息
def init_info(self):# 加載上一次的結果self."具體的控件".setText(self.settings.value('sheet_name', ""))self."具體的控件"t.setText(self.settings.value('file_path', ""))self."具體的控件".setText(self.settings.value('new_dir_path', ""))self."具體的控件".setText(self.settings.value('img_width', "75"))self."具體的控件".setText(self.settings.value('img_height', "75"))col_list = self.settings.value('col_list', [])
????????????????通常會使用一個函數實現加載上一次結果的功能,在程序運行時,執行這個函數即可
補充
????????這里給出幾個比較常用的控件綁定方式
????????復選框
? ? ? ? ????????由于復選框的值,在后端接收的True或False,但是寫入文件確實字符串格式的true或false,所以需要進行格式轉化,將字符串轉為對應的值
write_to_excel = self.settings.value('write_to_excel', True)
write_to_excel = True if write_to_excel == 'true' or write_to_excel != "false" else False
self.writeExcelCheckBox.setChecked(write_to_excel)
????????listWidget
? ? ? ? ? ? ? ? listwidget對象其是一個一個item,所有通過列表的方式,將每一個值都添加進listwidget中
col_list = self.settings.value('col_list', [])
for col_name in col_list:self.listWidget.addItem(col_name)