jiateng_ws/widgets/settings_widget.py

314 lines
13 KiB
Python
Raw Normal View History

from PySide6.QtWidgets import QMessageBox, QVBoxLayout
2025-06-07 10:45:09 +08:00
import logging
2025-06-13 17:14:03 +08:00
import json
import os
2025-06-07 10:45:09 +08:00
from ui.settings_ui import SettingsUI
from utils.sql_utils import SQLUtils
from widgets.inspection_settings_widget import InspectionSettingsWidget
from widgets.pallet_type_settings_widget import PalletTypeSettingsWidget
2025-06-13 17:14:03 +08:00
from utils.config_loader import ConfigLoader
2025-06-07 10:45:09 +08:00
class SettingsWidget(SettingsUI):
def __init__(self, parent=None):
super().__init__(parent)
self.parent = parent
logging.info("正在初始化SettingsWidget")
# 创建检验设置部件
logging.info("创建InspectionSettingsWidget实例")
self.inspection_settings = InspectionSettingsWidget()
# 移除临时占位符标签并添加检验设置部件
if hasattr(self, 'inspection_placeholder'):
logging.info("移除临时占位符")
self.inspection_layout.removeWidget(self.inspection_placeholder)
self.inspection_placeholder.hide()
self.inspection_placeholder.deleteLater()
else:
logging.warning("未找到临时占位符标签")
# 检查布局是否可用
if hasattr(self, 'inspection_layout'):
logging.info("添加检验设置部件到布局")
self.inspection_layout.addWidget(self.inspection_settings)
else:
logging.error("无法找到inspection_layout布局")
# 创建托盘类型设置部件
logging.info("创建PalletTypeSettingsWidget实例")
self.pallet_type_settings = PalletTypeSettingsWidget()
# 移除临时占位符标签并添加托盘类型设置部件
if hasattr(self, 'pallet_type_placeholder'):
logging.info("移除托盘类型临时占位符")
self.pallet_type_layout.removeWidget(self.pallet_type_placeholder)
self.pallet_type_placeholder.hide()
self.pallet_type_placeholder.deleteLater()
else:
logging.warning("未找到托盘类型临时占位符标签")
# 检查布局是否可用
if hasattr(self, 'pallet_type_layout'):
logging.info("添加托盘类型设置部件到布局")
self.pallet_type_layout.addWidget(self.pallet_type_settings)
else:
logging.error("无法找到pallet_type_layout布局")
2025-06-13 17:14:03 +08:00
# 加载配置文件
self.config_loader = ConfigLoader.get_instance()
2025-06-07 10:45:09 +08:00
# 连接信号和槽
self.connect_signals()
# 初始化数据库类型UI状态
2025-06-13 17:14:03 +08:00
self.load_db_config()
2025-06-07 10:45:09 +08:00
logging.info("SettingsWidget初始化完成")
2025-06-07 10:45:09 +08:00
def connect_signals(self):
# 数据库类型选择
2025-06-13 17:14:03 +08:00
self.db_type_combo.currentTextChanged.connect(self.update_db_ui_state)
# 更新当前使用的数据源
self.current_source_combo.currentTextChanged.connect(self.update_default_source)
2025-06-07 10:45:09 +08:00
# 按钮动作
self.test_conn_button.clicked.connect(self.test_connection)
self.save_db_button.clicked.connect(self.save_db_settings)
# 检验配置变更信号
self.inspection_settings.signal_configs_changed.connect(self.handle_inspection_configs_changed)
# 托盘类型配置变更信号
self.pallet_type_settings.signal_pallet_types_changed.connect(self.handle_pallet_types_changed)
# 返回按钮
if hasattr(self, 'back_button'):
self.back_button.clicked.connect(self.back_to_main)
2025-06-07 10:45:09 +08:00
2025-06-13 17:14:03 +08:00
def load_db_config(self):
"""加载数据库配置"""
try:
# 获取默认数据源
default_source = self.config_loader.get_value('database.default', 'sqlite').lower()
# 设置当前使用的数据源组合框
self._update_source_combo_items() # 更新组合框项目
index = self.current_source_combo.findText(default_source.capitalize(), Qt.MatchFixedString)
if index >= 0:
self.current_source_combo.setCurrentIndex(index)
# 默认选择当前使用的数据源类型
index = self.db_type_combo.findText(default_source.capitalize(), Qt.MatchFixedString)
if index >= 0:
self.db_type_combo.setCurrentIndex(index)
# 更新UI状态
self.update_db_ui_state()
except Exception as e:
logging.error(f"加载数据库配置失败: {e}")
def _update_source_combo_items(self):
"""更新数据源下拉框项目"""
try:
# 清空当前项目
self.current_source_combo.clear()
# 获取所有配置的数据源
sources = self.config_loader.get_value('database.sources', {})
# 添加数据源到下拉框
for source_name in sources.keys():
# 处理特殊情况postgresql显示为PostgreSQL
display_name = source_name.capitalize()
self.current_source_combo.addItem(display_name, source_name)
except Exception as e:
logging.error(f"更新数据源下拉框失败: {e}")
# 添加默认项
self.current_source_combo.addItem("SQLite", "sqlite")
2025-06-07 10:45:09 +08:00
def update_db_ui_state(self):
"""根据选择的数据库类型更新UI状态"""
2025-06-13 17:14:03 +08:00
db_type = self.db_type_combo.currentText().lower()
# 处理特殊情况PostgreSQL对应postgresql
if db_type == "postgresql":
db_type = "postgresql"
# 加载选定类型的数据源配置
config_path = f"database.sources.{db_type}"
db_config = {}
if db_type == "sqlite":
# SQLite模式下只需要数据库文件路径和说明
path = self.config_loader.get_value(f"{config_path}.path", "db/jtDB.db")
description = self.config_loader.get_value(f"{config_path}.description", "")
2025-06-07 10:45:09 +08:00
self.host_input.setEnabled(False)
self.host_input.setText("")
self.user_input.setEnabled(False)
self.user_input.setText("")
self.password_input.setEnabled(False)
self.password_input.setText("")
self.port_input.setEnabled(False)
self.port_input.setText("")
self.database_input.setEnabled(True)
2025-06-13 17:14:03 +08:00
self.database_input.setText(path)
self.desc_input.setText(description)
elif db_type == "postgresql":
2025-06-07 10:45:09 +08:00
# PostgreSQL模式下需要完整的连接信息
2025-06-13 17:14:03 +08:00
host = self.config_loader.get_value(f"{config_path}.host", "localhost")
port = self.config_loader.get_value(f"{config_path}.port", "5432")
user = self.config_loader.get_value(f"{config_path}.user", "postgres")
password = self.config_loader.get_value(f"{config_path}.password", "")
name = self.config_loader.get_value(f"{config_path}.name", "jtDB")
description = self.config_loader.get_value(f"{config_path}.description", "")
2025-06-07 10:45:09 +08:00
self.host_input.setEnabled(True)
2025-06-13 17:14:03 +08:00
self.host_input.setText(host)
2025-06-07 10:45:09 +08:00
self.user_input.setEnabled(True)
2025-06-13 17:14:03 +08:00
self.user_input.setText(user)
2025-06-07 10:45:09 +08:00
self.password_input.setEnabled(True)
2025-06-13 17:14:03 +08:00
self.password_input.setText(password)
2025-06-07 10:45:09 +08:00
self.port_input.setEnabled(True)
2025-06-13 17:14:03 +08:00
self.port_input.setText(port)
2025-06-07 10:45:09 +08:00
self.database_input.setEnabled(True)
2025-06-13 17:14:03 +08:00
self.database_input.setText(name)
self.desc_input.setText(description)
elif db_type == "mysql":
2025-06-07 10:45:09 +08:00
# MySQL模式下需要完整的连接信息
2025-06-13 17:14:03 +08:00
host = self.config_loader.get_value(f"{config_path}.host", "localhost")
port = self.config_loader.get_value(f"{config_path}.port", "3306")
user = self.config_loader.get_value(f"{config_path}.user", "root")
password = self.config_loader.get_value(f"{config_path}.password", "")
name = self.config_loader.get_value(f"{config_path}.name", "jtDB")
description = self.config_loader.get_value(f"{config_path}.description", "")
2025-06-07 10:45:09 +08:00
self.host_input.setEnabled(True)
2025-06-13 17:14:03 +08:00
self.host_input.setText(host)
2025-06-07 10:45:09 +08:00
self.user_input.setEnabled(True)
2025-06-13 17:14:03 +08:00
self.user_input.setText(user)
2025-06-07 10:45:09 +08:00
self.password_input.setEnabled(True)
2025-06-13 17:14:03 +08:00
self.password_input.setText(password)
2025-06-07 10:45:09 +08:00
self.port_input.setEnabled(True)
2025-06-13 17:14:03 +08:00
self.port_input.setText(port)
2025-06-07 10:45:09 +08:00
self.database_input.setEnabled(True)
2025-06-13 17:14:03 +08:00
self.database_input.setText(name)
self.desc_input.setText(description)
def update_default_source(self):
"""更新默认使用的数据源"""
default_source = self.current_source_combo.currentText().lower()
self.config_loader.set_value('database.default', default_source)
logging.info(f"已更新默认使用的数据源为: {default_source}")
2025-06-07 10:45:09 +08:00
def get_db_type(self):
"""获取当前选择的数据库类型"""
2025-06-13 17:14:03 +08:00
return self.db_type_combo.currentText().lower()
2025-06-07 10:45:09 +08:00
def get_connection_params(self):
"""获取数据库连接参数"""
db_type = self.get_db_type()
params = {
"database": self.database_input.text().strip()
}
if db_type != "sqlite":
params.update({
"host": self.host_input.text().strip(),
"user": self.user_input.text().strip(),
"password": self.password_input.text().strip(),
"port": self.port_input.text().strip()
})
return db_type, params
def test_connection(self):
"""测试数据库连接"""
db_type, params = self.get_connection_params()
try:
# 创建数据库连接
db = SQLUtils(db_type, **params)
# 测试连接
db.cursor.execute("SELECT 1")
2025-06-07 10:45:09 +08:00
# 关闭连接
2025-06-07 10:45:09 +08:00
db.close()
# 显示成功消息
QMessageBox.information(self, "连接成功", "数据库连接测试成功!")
logging.info(f"数据库连接测试成功,类型: {db_type}")
2025-06-07 10:45:09 +08:00
except Exception as e:
# 显示错误消息
QMessageBox.critical(self, "连接失败", f"数据库连接测试失败!\n\n错误: {str(e)}")
2025-06-07 10:45:09 +08:00
logging.error(f"数据库连接测试失败,类型: {db_type}, 错误: {str(e)}")
def save_db_settings(self):
"""保存数据库设置"""
db_type = self.get_db_type()
params = self.get_connection_params()[1]
desc = self.desc_input.text().strip()
2025-06-13 17:14:03 +08:00
try:
# 构建要保存的配置数据
config_path = f"database.sources.{db_type}"
if db_type == "sqlite":
self.config_loader.set_value(f"{config_path}.path", params["database"])
self.config_loader.set_value(f"{config_path}.description", desc)
2025-06-07 10:45:09 +08:00
else:
2025-06-13 17:14:03 +08:00
self.config_loader.set_value(f"{config_path}.host", params["host"])
self.config_loader.set_value(f"{config_path}.port", params["port"])
self.config_loader.set_value(f"{config_path}.user", params["user"])
self.config_loader.set_value(f"{config_path}.password", params["password"])
self.config_loader.set_value(f"{config_path}.name", params["database"])
self.config_loader.set_value(f"{config_path}.description", desc)
# 更新数据源下拉框
self._update_source_combo_items()
# 构建要显示的消息
settings_info = f"数据库类型: {db_type}\n"
for key, value in params.items():
if key != "password":
settings_info += f"{key}: {value}\n"
else:
settings_info += f"{key}: {'*' * len(value)}\n"
settings_info += f"说明: {desc}"
# 显示成功消息
QMessageBox.information(self, "设置已保存", f"数据库设置已保存!\n\n{settings_info}")
logging.info(f"数据库设置已保存,类型: {db_type}")
except Exception as e:
# 显示错误消息
QMessageBox.critical(self, "保存失败", f"保存数据库设置失败!\n\n错误: {str(e)}")
logging.error(f"保存数据库设置失败: {str(e)}")
def handle_inspection_configs_changed(self):
"""处理检验配置变更"""
logging.info("检验配置已更新")
# 如果有父窗口,通知父窗口更新检验配置
if self.parent and hasattr(self.parent, 'update_inspection_columns'):
self.parent.update_inspection_columns()
def handle_pallet_types_changed(self):
"""处理托盘类型配置变更"""
logging.info("托盘类型配置已更新")
# 如果有父窗口,通知父窗口更新托盘类型
if self.parent and hasattr(self.parent, 'update_pallet_types'):
self.parent.update_pallet_types()
def back_to_main(self):
"""返回主页"""
if self.parent and hasattr(self.parent, 'show_main_page'):
self.parent.show_main_page()