refactor(packaging): PyInstaller资源路径统一适配get_resource_path

This commit is contained in:
DXC
2026-05-10 18:02:59 +08:00
parent 5a55be286f
commit 2a4a7ec7be
4 changed files with 74 additions and 47 deletions

View File

@ -32,6 +32,18 @@ from PyQt5.QtGui import QIcon, QFont, QTextCursor, QPalette, QColor, QPixmap
import sys
import traceback
def get_resource_path(relative_path: str) -> str:
"""获取资源的绝对路径,适配 PyInstaller 打包环境。
打包后资源位于 sys._MEIPASS解压临时目录开发环境则基于 __file__ 向上三级。
"""
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS, relative_path)
return os.path.abspath(
os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), relative_path)
)
def global_exception_handler(exc_type, exc_value, exc_traceback):
print("\n" + "="*50)
print("【严重错误拦截 - PyQt 崩溃死因】")
@ -1398,19 +1410,8 @@ class WaterQualityGUI(QMainWindow):
}
def get_icon_path(self, icon_filename):
"""
获取图标文件的完整路径
在开发环境中从../data/icons/获取在打包后从data/icons/获取
"""
if hasattr(sys, '_MEIPASS'):
# 打包后的环境
icon_dir = os.path.join(sys._MEIPASS, 'data', 'icons')
else:
# 开发环境
current_dir = os.path.dirname(os.path.abspath(__file__))
icon_dir = os.path.join(current_dir, '..', '..', 'data', 'icons')
return os.path.join(icon_dir, icon_filename)
"""获取图标文件的完整路径(统一使用 get_resource_path"""
return get_resource_path(f"data/icons/{icon_filename}")
def _disable_wheel_for_all_spinboxes(self):
"""
@ -1554,12 +1555,8 @@ class WaterQualityGUI(QMainWindow):
}
""")
# 设置Logo图片路径 - 使用相对路径(打包兼容)
from pathlib import Path
if hasattr(sys, '_MEIPASS'):
logo_path = os.path.join(sys._MEIPASS, 'data', 'icons', 'logo.png')
else:
logo_path = str(Path(__file__).parent.parent.parent / "data" / "icons" / "logo.png")
# 设置Logo图片路径
logo_path = get_resource_path("data/icons/logo.png")
logo_pixmap = QPixmap(logo_path)
if not logo_pixmap.isNull():
@ -1692,10 +1689,7 @@ class WaterQualityGUI(QMainWindow):
banner_widget.setStyleSheet("margin: 0px; padding: 0px; border: none;")
# 纯净底图路径(无水印文字)
if hasattr(sys, '_MEIPASS'):
banner_path = os.path.join(sys._MEIPASS, 'data', 'icons', 'Mega Water 1.0.jpg')
else:
banner_path = str(Path(__file__).parent.parent.parent / "data" / "icons" / "Mega Water 1.0.jpg")
banner_path = get_resource_path("data/icons/Mega Water 1.0.jpg")
self.banner_pixmap = QPixmap(banner_path)
if not self.banner_pixmap.isNull():
@ -1822,14 +1816,14 @@ class WaterQualityGUI(QMainWindow):
self.step_list.addItem(stage_item)
# 添加该阶段的所有步骤
HIDDEN_STEP_IDS = {"step6_5", "step6_75", "step8_5", "step8_75"}
for step_id, step_display in steps:
if step_id in HIDDEN_STEP_IDS:
continue
item = QListWidgetItem(f" └─ {step_display}")
item.setData(Qt.UserRole, step_id)
# 隐藏4个冗余回归步骤树节点
if step_id in ("step6_5", "step6_75", "step8_5", "step8_75"):
item.setHidden(True)
self.step_name_map[step_display] = step_id
# 设置步骤项的样式