import sys
import os
import json
import requests
import pickle
import subprocess
from datetime import datetime
import webbrowser
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel,
QPushButton, QScrollArea, QFrame, QInputDialog,
QGridLayout, QGraphicsDropShadowEffect, QLineEdit,
QTextEdit, QMessageBox, QTextBrowser, QSlider, QFileDialog)
from PyQt5.QtGui import QFont, QIcon, QPixmap, QFontDatabase, QColor, QBrush, QPalette, QPainter, QFontMetrics
from PyQt5.QtCore import Qt, QSize, QPoint, QRect, QTimer, QUrl
from PyQt5.QtMultimedia import QMediaPlayer, QMediaPlaylist
SAVE_DIR = "./saves/players"
CONFIG_DIR = "./config/software/"
ELEMENT_COLOR_FILE = os.path.join(CONFIG_DIR, "elementcolor.json")
PATHS_MAPPING_FILE = os.path.join(CONFIG_DIR, "pathsmapping.json")
加载元素颜色配置
def load_element_colors():
if not os.path.exists(ELEMENT_COLOR_FILE):
return {}
with open(ELEMENT_COLOR_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
加载路径映射配置
def load_paths_mapping():
if not os.path.exists(PATHS_MAPPING_FILE):
return {}
with open(PATHS_MAPPING_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
class CharacterDetailWindow(QWidget):
def init (self, character, element_colors, paths_mapping):
super().init ()
self.character = character
self.element_colors = element_colors
self.paths_mapping = paths_mapping
self.rarity_colors = self.load_rarity_colors()
self.affix_mapping = self.load_affix_mapping()
self.initUI()
code Copy code
def load_affix_mapping(self):
file_path = os.path.join("config", "software", "affixmapping.json")
if os.path.exists(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
return json.load(file)
return {}
def load_rarity_colors(self):
file_path = os.path.join("config", "software", "raritycoloring.json")
if os.path.exists(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
return json.load(file)
return {}
def get_gradient_style(self, rarity):
colors = self.rarity_colors
if str(rarity) in colors:
start = colors[str(rarity)]['start']
end = colors[str(rarity)]['end']
return f"background: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 {start}, stop:1 {end});"
return ""
def initUI(self):
self.setWindowTitle(f"{self.character['name']} - 详细信息")
self.showMaximized()
self.set_background()
main_layout = QVBoxLayout(self)
self.setLayout(main_layout)
main_layout.setContentsMargins(0, 0, 0, 0)
scroll_area = QScrollArea(self)
scroll_area.setWidgetResizable(True)
scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
main_layout.addWidget(scroll_area)
container = QWidget()
scroll_area.setWidget(container)
layout = QVBoxLayout(container)
layout.setContentsMargins(50, 50, 50, 50)
# 添加角色立绘
splashart_path = f"image/splashart/{self.character['id']}.png"
splashart_pixmap = QPixmap(splashart_path).scaled(768, 768, Qt.KeepAspectRatio, Qt.SmoothTransformation)
splashart_label = QLabel(container)
splashart_label.setPixmap(splashart_pixmap)
layout.addWidget(splashart_label, alignment=Qt.AlignLeft | Qt.AlignTop)
path_name = self.character['path']['name'].lower()
path_icon_key = self.paths_mapping.get(path_name, None)
if path_icon_key:
path_icon_path = f"image/path/{path_icon_key}.png"
path_pixmap = QPixmap(path_icon_path).scaled(128, 128, Qt.KeepAspectRatio, Qt.SmoothTransformation)
path_icon_label = QLabel(splashart_label)
path_icon_label.setPixmap(path_pixmap)
path_icon_label.move(10, 10)
# 整个光锥和信息的表格
light_cone_frame = LightConeFrame(self.character, self.affix_mapping, container)
light_cone_frame.setFixedSize(896, 576)
layout.addWidget(light_cone_frame, alignment=Qt.AlignTop)
light_cone_layout = QVBoxLayout(light_cone_frame)
light_cone_layout.setContentsMargins(0, 0, 0, 0)
# 上部信息部分
top_section = QWidget(light_cone_frame)
top_section.setFixedHeight(192)
top_layout = QHBoxLayout(top_section)
top_layout.setContentsMargins(0, 0, 0, 0)
# 左侧光锥图片和渐变背景
light_cone = self.character.get('light_cone')
if light_cone:
rarity = light_cone['rarity']
cone_id = light_cone['id']
gradient_style = self.get_gradient_style(rarity)
cone_name = light_cone['name']
cone_level = light_cone['level']
cone_rank = light_cone['rank']
else:
rarity = 0
cone_id = 'unequip'
gradient_style = "background-color: #444444;"
cone_name = "未佩戴光锥"
cone_level = "N/A"
cone_rank = "N/A"
gradient_section = QWidget(top_section)
gradient_section.setFixedSize(192, 192)
gradient_section.setStyleSheet(gradient_style + "border-top-left-radius: 15px;")
# 在渐变背景中居中显示光锥图
gradient_layout = QVBoxLayout(gradient_section)
gradient_layout.setContentsMargins(0, 0, 0, 0)
lightcone_pixmap = QPixmap(f"image/lightcone/{cone_id}.png").scaled(180, 180, Qt.KeepAspectRatio, Qt.SmoothTransformation)
lightcone_label = QLabel()
lightcone_label.setPixmap(lightcone_pixmap)
lightcone_label.setAlignment(Qt.AlignCenter)
gradient_layout.addWidget(lightcone_label)
top_layout.addWidget(gradient_section)
# 右侧信息区域
right_section = QWidget(top_section)
right_layout = QVBoxLayout(right_section)
right_layout.setContentsMargins(0, 0, 0, 0)
# 光锥名称
colors = self.rarity_colors.get(str(rarity), {})
end_color = colors.get("end", "#ffffff")
name_label = QLabel(cone_name, right_section)
name_label.setFixedHeight(72)
name_label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
name_label.setStyleSheet(f"color: {end_color}; font-size: 36px; font-weight: bold; padding: 0px 2px;")
right_layout.addWidget(name_label)
# 第二行: 光锥命途图标、等级、叠影数量
second_row = QWidget(right_section)
second_row.setFixedHeight(64)
second_row_layout = QHBoxLayout(second_row)
second_row_layout.setContentsMargins(0, 0, 0, 0)
# 设置布局的对齐方式为左对齐
second_row_layout.setAlignment(Qt.AlignLeft)
path_icon_label = QLabel(second_row)
path_icon_label.setPixmap(QPixmap(path_icon_path).scaled(64, 64, Qt.KeepAspectRatio))
path_icon_label.setFixedSize(64, 64)
second_row_layout.addWidget(path_icon_label)
level_label = QLabel(f"等级 {cone_level}", second_row)
level_label.setFixedSize(128, 64)
level_label.setAlignment(Qt.AlignCenter)
level_label.setStyleSheet("color: white; font-size: 32px; font-weight: bold;")
second_row_layout.addWidget(level_label)
rank_roman = ["Ⅰ", "Ⅱ", "Ⅲ", "Ⅳ", "Ⅴ"]
rank_label = QLabel(rank_roman[int(cone_rank) - 1] if cone_rank != "N/A" else "N/A", second_row)
rank_label.setFixedSize(64, 64)
rank_label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
rank_label.setStyleSheet("color: white; font-size: 32px; font-weight: bold;")
second_row_layout.addWidget(rank_label)
right_layout.addWidget(second_row)
# 稀有度一行
font_id = QFontDatabase.addApplicationFont("fonts/hsr-icon.ttf")
font_family = QFontDatabase.applicationFontFamilies(font_id)[0]
star_label = QLabel("b" * rarity, right_section)
star_label.setFixedHeight(66)
star_label.setAlignment(Qt.AlignLeft)
custom_font = QFont(font_family, 16)
star_label.setFont(custom_font)
star_label.setStyleSheet(
f"color: {end_color}; font-weight: bold; "
f"margin: 0px 0px 0px 0px;"
)
right_layout.addWidget(star_label)
top_layout.addWidget(right_section)
light_cone_layout.addWidget(top_section)
# 下方滚动区域
bottom_section = QScrollArea(light_cone_frame)
bottom_section.setMinimumHeight(384)
bottom_section.setWidgetResizable(True)
bottom_section.setStyleSheet("background-color: transparent; border: none;")
bottom_section.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
bottom_section.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
bottom_content = QWidget()
bottom_layout = QVBoxLayout(bottom_content)
if light_cone:
lightcone_data = self.load_lightcone_data(cone_id)
if lightcone_data:
description_browser = QTextBrowser(bottom_content)
description_browser.setStyleSheet("background-color: transparent; color: white; font-weight: bold;")
self.populate_lightcone_description(description_browser, lightcone_data)
bottom_layout.addWidget(description_browser)
else:
description_browser = QTextBrowser(bottom_content)
description_browser.setStyleSheet("color: white; font-weight: bold;")
description_browser.append("未佩戴光锥")
bottom_layout.addWidget(description_browser)
bottom_section.setWidget(bottom_content)
light_cone_layout.addWidget(bottom_section)
def load_lightcone_data(self, lightcone_id):
file_path = os.path.join("config", "lightcone", f"{lightcone_id}.json")
if os.path.exists(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
return json.load(file)
return None
def populate_lightcone_description(self, text_browser, data):
rarity = self.character['light_cone']['rank']
skill_description = data.get("combined_skill_description", "").replace("\n", "<br>")
light_cone_description = data.get("light_cone_description", "").replace("\n", "<br>")
text_browser.clear()
# Skill name and rarity level line
skill_name = data.get("skill_name", "")
text_browser.append(f"{skill_name} - 等级 {rarity}")
# Skill description with highlighting
skill_text = ""
start_marker = '[['
end_marker = ']]'
start = skill_description.find(start_marker)
while start != -1:
end = skill_description.find(end_marker, start)
if end != -1:
actual_start = start + len(start_marker)
actual_end = end
skill_text += skill_description[:start]
# Highlight the number according to rarity
numbers_str = skill_description[actual_start:actual_end].split(',')
if 1 <= rarity <= len(numbers_str):
number_to_highlight = numbers_str[rarity - 1].strip()
skill_text += f"<span style='color:orange;'>{number_to_highlight}</span>"
skill_description = skill_description[end + len(end_marker):]
start = skill_description.find(start_marker)
else:
break
skill_text += skill_description
text_browser.append(skill_text)
# 添加空行
text_browser.append("<br>")
# Light cone description in gray
text_browser.append(f"<div style='color:grey;'>{light_cone_description}</div>")
def set_background(self):
palette = self.palette()
background_pixmap = QPixmap("image/gui/background.jpeg").scaled(self.size(), Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
palette.setBrush(QPalette.Window, QBrush(background_pixmap))
self.setPalette(palette)
def resizeEvent(self, event):
self.set_background()
super().resizeEvent(event)
class LightConeFrame(QWidget):
def init (self, character, affix_mapping, parent=None, bg_color="#262634"):
super().init (parent)
self.bg_color = bg_color
self.character = character
self.affix_mapping = affix_mapping
class MusicPlayerWidget(QWidget):
def init (self, parent=None):
super().init (parent)
self.setWindowTitle("Music Player")
self.setFixedSize(400, 200)
code Copy code
# 创建播放器和播放列表
self.player = QMediaPlayer(self)
self.playlist = QMediaPlaylist(self)
self.player.setPlaylist(self.playlist)
# 设置UI布局
layout = QVBoxLayout(self)
# 显示音乐名称的标签
self.song_label = QLabel("选择一首乐曲", self)
self.song_label.setStyleSheet("color: white; font-size: 18px;")
self.song_label.setAlignment(Qt.AlignCenter)
layout.addWidget(self.song_label)
# 播放进度条
self.progress_slider = QSlider(Qt.Horizontal, self)
self.progress_slider.setStyleSheet("QSlider::groove:horizontal {background: white;} QSlider::handle:horizontal {background: lightblue;}")
layout.addWidget(self.progress_slider)
# 添加按钮
buttonLayout = QVBoxLayout()
self.play_button = QPushButton("▶", self)
self.play_button.setStyleSheet("background-color: transparent; color: white; font-size: 24px;")
self.play_button.clicked.connect(self.toggle_play)
buttonLayout.addWidget(self.play_button)
self.browse_button = QPushButton("选择音乐文件", self)
self.browse_button.setStyleSheet("background-color: transparent; color: white;")
self.browse_button.clicked.connect(self.browse_files)
buttonLayout.addWidget(self.browse_button)
layout.addLayout(buttonLayout)
# 设置透明背景
self.setAttribute(Qt.WA_TranslucentBackground)
self.setStyleSheet("background-color: rgba(0, 0, 0, 150); border-radius: 15px;")
# 连接信号和槽
self.player.durationChanged.connect(self.update_duration)
self.player.positionChanged.connect(self.update_position)
self.progress_slider.sliderMoved.connect(self.set_position)
def toggle_play(self):
if self.player.state() == QMediaPlayer.PlayingState:
self.player.pause()
self.play_button.setText("▶")
else:
self.player.play()
self.play_button.setText("⏸")
def browse_files(self):
file_name, _ = QFileDialog.getOpenFileName(self, "选择音乐文件", "./music", "Music Files (*.mp3 *.ogg *.wav *.flac *.mid)")
if file_name:
self.playlist.clear()
self.playlist.addMedia(QUrl.fromLocalFile(file_name))
self.song_label.setText(file_name.split("/")[-1])
self.player.play()
self.play_button.setText("⏸")
def update_duration(self, duration):
self.progress_slider.setRange(0, duration)
def update_position(self, position):
if not self.progress_slider.isSliderDown():
self.progress_slider.setValue(position)
def set_position(self, position):
self.player.setPosition(position)
class HSRToolApp(QWidget):
def init (self):
super().init ()
self.current_data = None
self.current_player = None
self.element_colors = load_element_colors()
self.paths_mapping = load_paths_mapping()
self.detail_windows = []
self.initUI()
class GoldTicketWindow(QWidget):
def init (self):
super().init ()
self.setWindowTitle("期望计算")
self.setGeometry(100, 100, 400, 300)
code Copy code
layout = QVBoxLayout()
self.role_count_input = QLineEdit(self)
self.role_count_input.setPlaceholderText("你想要多少限定角色?")
layout.addWidget(self.role_count_input)
self.weapon_count_input = QLineEdit(self)
self.weapon_count_input.setPlaceholderText("你想要多少限定光锥?")
layout.addWidget(self.weapon_count_input)
self.simulate_button = QPushButton("开始模拟", self)
self.simulate_button.clicked.connect(self.simulate)
layout.addWidget(self.simulate_button)
self.result_display = QTextEdit(self)
self.result_display.setPlaceholderText("模拟结果")
layout.addWidget(self.result_display)
self.setLayout(layout)
def simulate(self):
role_count = self.role_count_input.text().strip()
weapon_count = self.weapon_count_input.text().strip()
if not all(x.isdigit() for x in [role_count, weapon_count]):
QMessageBox.critical(self, "输入无效", "请确保所有输入都是有效数字。")
return
command = (f"expansions\\ratecalc.exe -average {role_count} {weapon_count} ")
try:
output = "期望抽数 " + subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True, text=True)
self.result_display.setPlainText(output)
except subprocess.CalledProcessError as e:
QMessageBox.critical(self, "调用失败", f"错误信息:\n{e.output}")
class SilverTicketWindow(QWidget):
def init (self):
super().init ()
self.setWindowTitle("概率计算")
self.setGeometry(100, 100, 400, 300)
code Copy code
layout = QVBoxLayout()
self.role_count_input = QLineEdit(self)
self.role_count_input.setPlaceholderText("你要抽多少限定角色?")
layout.addWidget(self.role_count_input)
self.weapon_count_input = QLineEdit(self)
self.weapon_count_input.setPlaceholderText("你要抽多少限定光锥?")
layout.addWidget(self.weapon_count_input)
self.items_input = QLineEdit(self)
self.items_input.setPlaceholderText("你还有多少抽?(需要折合你的星琼数)")
layout.addWidget(self.items_input)
self.initial_role_pulls_input = QLineEdit(self)
self.initial_role_pulls_input.setPlaceholderText("角色池已垫抽数")
layout.addWidget(self.initial_role_pulls_input)
self.initial_weapon_pulls_input = QLineEdit(self)
self.initial_weapon_pulls_input.setPlaceholderText("光锥池已垫抽数")
layout.addWidget(self.initial_weapon_pulls_input)
self.major_pity_role_input = QLineEdit(self)
self.major_pity_role_input.setPlaceholderText("角色池大保底 (1=是, 0=否)")
layout.addWidget(self.major_pity_role_input)
self.major_pity_weapon_input = QLineEdit(self)
self.major_pity_weapon_input.setPlaceholderText("武器池大保底 (1=是, 0=否)")
layout.addWidget(self.major_pity_weapon_input)
self.simulate_button = QPushButton("开始模拟", self)
self.simulate_button.clicked.connect(self.simulate)
layout.addWidget(self.simulate_button)
self.result_display = QTextEdit(self)
self.result_display.setPlaceholderText("模拟结果")
layout.addWidget(self.result_display)
self.setLayout(layout)
def simulate(self):
role_count = self.role_count_input.text().strip()
weapon_count = self.weapon_count_input.text().strip()
items = self.items_input.text().strip()
initial_role_pulls = self.initial_role_pulls_input.text().strip()
initial_weapon_pulls = self.initial_weapon_pulls_input.text().strip()
major_pity_role = self.major_pity_role_input.text().strip()
major_pity_weapon = self.major_pity_weapon_input.text().strip()
if (not all(x.isdigit() for x in [role_count, weapon_count, items,
initial_role_pulls, initial_weapon_pulls]) or
major_pity_role not in ["0", "1"] or major_pity_weapon not in ["0", "1"]):
QMessageBox.critical(self, "输入无效", "请确保所有输入都是有效数字。")
return
command = (f"expansions\\ratecalc.exe -simulate {role_count} {weapon_count} {items} "
f"{initial_role_pulls} {initial_weapon_pulls} {major_pity_role} {major_pity_weapon}")
try:
output = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True, text=True)
self.result_display.setPlainText(output)
except subprocess.CalledProcessError as e:
QMessageBox.critical(self, "调用失败", f"错误信息:\n{e.output}")
if name == "main ":
app = QApplication(sys.argv)
app.setWindowIcon(QIcon("image/gui/icon.ico"))
window = HSRToolApp()
window.show()
sys.exit(app.exec_())我希望内置的播放器在主页右侧下方占据全部位置,淡灰色背景,半透明,附着在角色列表底部,黑色加粗字体,字体库不变
Show full message · 988 lines Assistant2024-11-20 13:12 UTC Copy response
要实现你所描述的效果,可以对 MusicPlayerWidget 进行一些调整。我们将调整其布局、样式和与角色列表的关系。以下是你需要做的更改:
你理解错了,不要调整我上半部分的布局,你可以理解为附着一个单独的半透明组件
Assistant2024-11-20 13:14 UTC Copy response
谢谢你的澄清。你想要的是在角色列表的底部附加一个独立的、半透明的音乐播放器组件。我们可以通过在你的应用程序中添加一个新的 QWidget 来实现。其中包含 MusicPlayerWidget,并设置其样式以达到所需的外观。
以下是实现这种效果的完整代码修改:
只告诉我要更改哪些,在什么位置,重复的内容不要输出
Assistant2024-11-20 13:15 UTC Copy response
好的,这里是针对你代码的具体修改建议:
1. 创建 MusicPlayerContainer 类
在类定义的区域中,增加以下代码:
python Copy code
class MusicPlayerContainer(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
# 设置布局
layout = QVBoxLayout(self)
layout.setContentsMargins(10, 10, 10, 10) # 控制边距
# 添加音乐播放器
self.music_player_widget = MusicPlayerWidget(self)
layout.addWidget(self.music_player_widget)
# 设置背景样式
self.setAttribute(Qt.WA_StyledBackground, True)
self.setStyleSheet("background-color: rgba(211, 211, 211, 0.7); border-radius: 15px;")
2. 在 initUI() 方法中,将音乐播放器容器组件添加到布局中
在 HSRToolApp 类的 initUI() 方法中,找到 self.right_layout.addWidget(self.scroll_area) 后面,添加以下内容:
python Copy code
# 添加音乐播放器容器
self.music_player_container = MusicPlayerContainer(self)
self.right_layout.addWidget(self.music_player_container)
通过这样的修改,你可以确保音乐播放器组件作为一个独立部分存在于用户界面的右侧布局中。
import sys
import os
import json
import requests
import pickle
import subprocess
from datetime import datetime
import webbrowser
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel,
QPushButton, QScrollArea, QFrame, QInputDialog,
QGridLayout, QGraphicsDropShadowEffect, QLineEdit,
QTextEdit, QMessageBox, QTextBrowser, QSlider, QFileDialog)
from PyQt5.QtGui import QFont, QIcon, QPixmap, QFontDatabase, QColor, QBrush, QPalette, QPainter, QFontMetrics
from PyQt5.QtCore import Qt, QSize, QPoint, QRect, QTimer, QUrl
from PyQt5.QtMultimedia import QMediaPlayer, QMediaPlaylist
SAVE_DIR = "./saves/players"
CONFIG_DIR = "./config/software/"
ELEMENT_COLOR_FILE = os.path.join(CONFIG_DIR, "elementcolor.json")
PATHS_MAPPING_FILE = os.path.join(CONFIG_DIR, "pathsmapping.json")
加载元素颜色配置
def load_element_colors():
if not os.path.exists(ELEMENT_COLOR_FILE):
return {}
with open(ELEMENT_COLOR_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
加载路径映射配置
def load_paths_mapping():
if not os.path.exists(PATHS_MAPPING_FILE):
return {}
with open(PATHS_MAPPING_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
class CharacterDetailWindow(QWidget):
def init (self, character, element_colors, paths_mapping):
super().init ()
self.character = character
self.element_colors = element_colors
self.paths_mapping = paths_mapping
self.rarity_colors = self.load_rarity_colors()
self.affix_mapping = self.load_affix_mapping()
self.initUI()
Show full message · 1,008 lines Assistant2024-11-20 13:17 UTC Copy response
从你提供的代码和错误信息来看,MusicPlayerContainer 类在使用之前没有定义导致 NameError。这个问题通常是因为类定义的位置不正确或者代码文件中存在其他错误。
以下是检查和处理此问题的步骤:
检查类定义位置:
确保 MusicPlayerContainer 类在 HSRToolApp 类使用之前定义。通常情况下,定义顺序应该是从上到下。
确保以下顺序的代码:
python Copy code
# MusicPlayerContainer 类
class MusicPlayerContainer(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
# 设置布局
layout = QVBoxLayout(self)
layout.setContentsMargins(10, 10, 10, 10) # 控制边距
# 添加音乐播放器
self.music_player_widget = MusicPlayerWidget(self)
layout.addWidget(self.music_player_widget)
# 设置背景样式
self.setAttribute(Qt.WA_StyledBackground, True)
self.setStyleSheet("background-color: rgba(211, 211, 211, 0.7); border-radius: 15px;")
# HSRToolApp 类
class HSRToolApp(QWidget):
def __init__(self):
super().__init__()
self.current_data = None
self.current_player = None
self.element_colors = load_element_colors()
self.paths_mapping = load_paths_mapping()
self.detail_windows = []
self.initUI()
确保所有依赖类定义完毕后再用到它们:
尤其是 MusicPlayerWidget 和 MusicPlayerContainer 需要在 HSRToolApp 使用之前定义。
重新检查 import 语句:
如果你在不同的文件中定义了类,需要确保正确的 import。
通过这些检查来确保编译和执行时有完整的类和函数可用。完成这些步骤后,再次运行程序即可看到一些可能造成错误的遗漏或设置问题,并加以修复。
Assistant2024-11-20 13:18 UTC Copy response
出现这种情况可能是由于布局设置或其他代码逻辑的问题导致的。以下是几项需要检查和修正的地方,请按照下面的步骤来排查和修复问题:
1. 检查布局设置
确保在主窗口的布局中正确添加了所有需要的组件。在 HSRToolApp 的 initUI 方法中检查以下几点:
确保 self.scroll_area 正确地设置其 widget。
确保 MusicPlayerContainer 也被正确添加到 right_layout。
python Copy code
def initUI(self):
...
self.left_frame.setLayout(self.left_layout)
layout.addWidget(self.left_frame, stretch=22)
self.right_frame = QFrame()
self.right_layout = QVBoxLayout()
self.right_layout.setAlignment(Qt.AlignTop)
self.scroll_area = QScrollArea()
self.scroll_area.setWidgetResizable(True)
self.scroll_widget = QWidget()
self.scroll_layout = QVBoxLayout(self.scroll_widget)
self.scroll_layout.setAlignment(Qt.AlignTop)
self.scroll_area.setWidget(self.scroll_widget)
self.right_layout.addWidget(self.scroll_area)
# 添加音乐播放器容器
self.music_player_container = MusicPlayerContainer(self)
self.right_layout.addWidget(self.music_player_container)
self.right_frame.setLayout(self.right_layout)
layout.addWidget(self.right_frame, stretch=78)
...
2. 确认 display_player_data 方法
确保 display_player_data 方法中所有 component 都添加到 scroll_layout:
Assistant2024-11-20 13:19 UTC Copy response
由于篇幅限制,很难完整显示900多行代码。建议先了解以下几个关键步骤来检测和修正代码问题,如有需要可以分段通过消息请求:
结构检查 :
请确保所有类和方法的定义顺序正确。一般来说,底层工具类和函数在前,应用类和主逻辑在后。
布局和组件的完整性 :
确保所有组件都被正确添加到布局中。如果某个组件没有显示,确认它是否被正确实例化并添加到了布局中。
错误和日志输出 :
在调试时加入打印或日志输出,确认程序的执行流程和数据状态正常,可以帮助找出错误。
逐步测试 :
根据已有的功能实现逐一启用,确认各个组件的功能在剥离其他复杂依赖的情况下是正常的。
示例:关键布局代码
python Copy code
# 在类 HSRToolApp 中的 initUI 方法里,确保布局的增加
def initUI(self):
layout = QHBoxLayout(self)
self.left_frame = QFrame()
self.left_layout = QVBoxLayout()
self.left_layout.setAlignment(Qt.AlignTop)
# 省略部分代码:设置添加玩家数据按钮和其他工具按钮布局
self.left_frame.setLayout(self.left_layout)
layout.addWidget(self.left_frame, stretch=22)
self.right_frame = QFrame()
self.right_layout = QVBoxLayout()
self.right_layout.setAlignment(Qt.AlignTop)
self.scroll_area = QScrollArea()
self.scroll_area.setWidgetResizable(True)
self.scroll_widget = QWidget()
self.scroll_layout = QVBoxLayout()
self.scroll_layout.setAlignment(Qt.AlignTop)
self.scroll_widget.setLayout(self.scroll_layout)
self.scroll_area.setWidget(self.scroll_widget)
self.right_layout.addWidget(self.scroll_area)
# 确认音乐播放器容器的设置
self.music_player_container = MusicPlayerContainer(self)
self.right_layout.addWidget(self.music_player_container)
self.right_frame.setLayout(self.right_layout)
layout.addWidget(self.right_frame, stretch=78)
self.setLayout(layout)
通过这些检查步骤,你可以调试并更好地理解问题所在。稍等可以将代码逐渐拆分或列出有关疑问的具体部分,以便更高效地解决问题。
请你直接给我完整代码,不要更改其他模块,让我直接复制
Assistant2024-11-20 13:22 UTC Copy response
当然可以。我会给你提供修改后的完整代码块,其中包括音乐播放器的设置在角色列表底部的相关修改。请确保将以下代码块直接替换到你的项目中:
Show full message · 1,011 lines Traceback (most recent call last):
File "c:\Users\surface\Desktop\srtool\srtool.pyw", line 469, in browse_files
self.playlist.addMedia(QUrl.fromLocalFile(file_name))
TypeError: arguments did not match any overloaded call:
addMedia(self, content: QMediaContent): argument 1 has unexpected type 'QUrl'
addMedia(self, items: Iterable[QMediaContent]): argument 1 has unexpected type 'QUrl'告诉我要改的地方
Assistant2024-11-20 13:27 UTC Copy response
这个错误是由于向 QMediaPlaylist 的 addMedia() 方法传递了一个 QUrl 类型的参数,而该方法实际上期望接受的是 QMediaContent 类型的参数。
你可以通过将 QUrl 包装成 QMediaContent 来解决这个问题。以下是需要修改的代码片段:
修改 browse_files 方法:
python Copy code
def browse_files(self):
file_name, _ = QFileDialog.getOpenFileName(self, "选择音乐文件", "./music", "Music Files (*.mp3 *.ogg *.wav *.flac *.mid)")
if file_name:
self.playlist.clear()
# 创建 QMediaContent
media_content = QMediaContent(QUrl.fromLocalFile(file_name))
self.playlist.addMedia(media_content)
self.song_label.setText(file_name.split("/")[-1])
self.player.play()
self.play_button.setText("⏸")
解释:
使用 QMediaContent(QUrl.fromLocalFile(file_name)) 将本地文件路径的 QUrl 封装成 QMediaContent,然后再添加到播放列表中。
修改后,这应该可以解决你的问题,因为它符合 addMedia() 方法的正确参数类型要求。确保在使用任何 API 时都遵循其期待的参数类型和格式。
还是理解错了,要类似于现代的播放ui,左侧三个图标:上一首,开始/暂停,下一首,然后歌名和进度条,进度条可以拖动,然后要自动读取同目录music文件夹里的音乐播放,只告诉我需要改的地方
Assistant2024-11-20 13:34 UTC Copy response
根据你的需求,我将提供如何修改 MusicPlayerWidget 类以满足以下要求:
添加播放控制按钮:上一首、播放/暂停、下一首。
自动读取和播放 ./music 目录下的所有音乐文件。
更新 UI 布局以实现现代化外观。
需要修改的地方:
File "c:\Users\surface\Desktop\srtool\srtool.pyw", line 1003, in
window = HSRToolApp()
^^^^^^^^^^^^
File "c:\Users\surface\Desktop\srtool\srtool.pyw", line 514, in init
self.initUI()
File "c:\Users\surface\Desktop\srtool\srtool.pyw", line 614, in initUI
self.music_player_container = MusicPlayerContainer(self)
^^^^^^^^^^^^^^^^^^^^
NameError: name 'MusicPlayerContainer' is not defined
Assistant2024-11-20 13:36 UTC Copy response
根据你的错误信息,NameError: name 'MusicPlayerContainer' is not defined 表示在调用 MusicPlayerContainer 类时,该类还未定义。为了确保每个类在使用前都被正确定义,尝试以下步骤:
确保 MusicPlayerContainer 在 HSRToolApp 之前定义
确保 MusicPlayerContainer 类的定义在 HSRToolApp 类之前。在代码中,类定义的顺序非常重要,因为 Python 是按顺序执行的。
确保 MusicPlayerContainer 的完整性
以下是 MusicPlayerContainer 类定义示例,请将其放置在 HSRToolApp 类之前并检查是否匹配:
python Copy code
class MusicPlayerContainer(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
# 设置布局
layout = QVBoxLayout(self)
layout.setContentsMargins(10, 10, 10, 10) # 控制边距
# 添加音乐播放器
self.music_player_widget = MusicPlayerWidget(self)
layout.addWidget(self.music_player_widget)
# 设置背景样式
self.setAttribute(Qt.WA_StyledBackground, True)
self.setStyleSheet("background-color: rgba(211, 211, 211, 0.7); border-radius: 15px;")
类定义的顺序
确保定义顺序如下:
MusicPlayerWidget
MusicPlayerContainer
HSRToolApp
这样可以确保在实例化 HSRToolApp 时,MusicPlayerContainer 已经被正确定义。
附加检查
确保没有拼写错误。
确保加载模块的正确顺序。
检查导入的内容是否正确。
修改后,请重新运行代码,错误应当得到解决。如果仍有问题,请检查其他可能导致错误的代码段或结构。
那三个按钮应和进度条在同一排,进度条要可拖动,而且现在没显示
Assistant2024-11-20 13:41 UTC Copy response
为了解决您的问题,我们需要调整 MusicPlayerWidget 的布局,使进度条和播放控制按钮(上一首、播放/暂停、下一首)在同一行显示,并确保进度条是可拖动的。以下是具体如何调整代码的建议:
修改 MusicPlayerWidget 类:
mid flac ogg 播不出来,然后你还没显示可拖动的进度条
Assistant2024-11-20 13:46 UTC Copy response
了解。我将以下问题修正:
支持格式 :QMediaPlayer 的具体编解码器支持可能会因平台而异,部分格式(如 .mid, .flac, 和 .ogg)可能不被默认支持。通常 .mp3 和 .wav 具有更好的支持性。
进度条的拖动 :确保进度条在被拖动时能够控制播放位置。
以下是更新后的代码,只考虑 .mp3 和 .wav 格式,为了确保以最广泛的支持性,并确保进度条可以拖动:
更新 MusicPlayerWidget 类:
Not yet included in a published release.
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
rect = self.rect()
# 填充背景色
painter.fillRect(rect, QColor(self.bg_color))
# 绘制右侧分割线
pen = painter.pen()
pen.setWidth(2)
pen.setColor(QColor('#444444'))
painter.setPen(pen)
# 计算分割线的起始和终止点位置
x_position = rect.width() - 320
y_end = 192
painter.drawLine(x_position, 0, x_position, y_end)
# 绘制表格框线
pen.setWidth(5)
pen.setColor(QColor('#444444'))
painter.setPen(pen)
painter.drawRoundedRect(rect.adjusted(1, 1, -1, -1), 30, 30)
# 绘制水平分割线
horizontal_line_y_position = 192
painter.drawLine(0, horizontal_line_y_position, rect.width(), horizontal_line_y_position)
# 在这里添加检测光锥是否存在并绘制属性图标、名称及数值
light_cone = self.character.get('light_cone')
attributes = light_cone.get('attributes', []) if light_cone else []
for idx, attribute in enumerate(attributes):
attr_name = attribute['name']
attr_value = float(attribute['value'])
attr_display = f"{attr_value:.3f}"
icon_file = self.affix_mapping.get(attr_name, None)
if icon_file:
icon_path = f"image/buffdata/{icon_file}.png"
if os.path.exists(icon_path):
icon_pixmap = QPixmap(icon_path).scaled(64, 64, Qt.KeepAspectRatio, Qt.SmoothTransformation)
# 下调图标1px
icon_y = (idx * 64) - 4 + 1
# 绘制图标:与框线对齐
painter.drawPixmap(x_position + 10, icon_y, icon_pixmap)
# 设置淡灰色
light_gray = QColor(169, 169, 169)
painter.setPen(light_gray)
# 绘制属性名称,向下移动1像素
font = painter.font()
font.setBold(True)
font.setPointSize(10)
painter.setFont(font)
# 设置属性名称的位置(向下移动1像素)
name_x = x_position + 80
name_y = (idx * 64) + (64 + self.fontMetrics().height()) // 2 + 1
attr_abbr = self.affix_mapping.get(attr_name, attr_name)
painter.drawText(QRect(name_x, (idx * 64) + 1, 150, 64), Qt.AlignVCenter | Qt.AlignLeft, attr_abbr)
# 计算数字的宽度并调整位置
font.setBold(True)
font.setPointSize(11)
painter.setFont(font)
int_width = self.fontMetrics().width(str(int(attr_value)))
# 设置小数部分的颜色和字体
darker_gray = QColor(105, 105, 105)
decimal_font = QFont(font)
decimal_font.setPointSize(8)
decimal_width = QFontMetrics(decimal_font).width(f".{attr_display.split('.')[1]}")
total_width = int_width + decimal_width
text_x = rect.width() - total_width - 19
# 将所有数字上移6像素
int_y = icon_y + (64 + self.fontMetrics().height()) // 2 - 6
# 绘制整数部分,右移一些
offset = 2
painter.drawText(QPoint(text_x + offset, int_y), str(int(attr_value)))
# 绘制小数部分
painter.setFont(decimal_font)
painter.setPen(darker_gray)
painter.drawText(QPoint(text_x + int_width + offset, int_y), f".{attr_display.split('.')[1]}")
super().paintEvent(event)
def initUI(self):
self.setWindowTitle("HSR Toolkit")
self.setWindowIcon(QIcon("image/gui/icon.ico"))
self.setGeometry(0, 0, 800, 600)
self.showMaximized()
layout = QHBoxLayout(self)
self.left_frame = QFrame()
self.left_layout = QVBoxLayout()
self.left_layout.setAlignment(Qt.AlignTop)
self.add_player_button = QPushButton("添加玩家数据")
self.add_player_button.setIcon(QIcon("image/gui/add.svg"))
self.add_player_button.setIconSize(QSize(24, 24))
self.add_player_button.setFixedWidth(600)
self.add_player_button.setStyleSheet("""
QPushButton {
border: 2px solid black;
border-radius: 10px;
color: gray;
background-color: white;
padding: 8px;
font-weight: bold;
}
QPushButton:hover {
background-color: lightblue;
color: black;
}
""")
self.add_player_button.setToolTip("点击添加玩家数据")
self.add_player_button.clicked.connect(self.prompt_for_uid)
self.left_layout.addWidget(self.add_player_button, alignment=Qt.AlignTop)
self.player_buttons_frame = QVBoxLayout()
self.player_buttons_frame.setAlignment(Qt.AlignTop)
self.left_layout.addLayout(self.player_buttons_frame)
self.cmd_button = QPushButton()
self.gold_ticket_button = QPushButton()
self.silver_ticket_button = QPushButton()
cmd_pixmap = QPixmap("image/gui/cmd.png").scaled(80, 80, Qt.KeepAspectRatio)
gold_ticket_pixmap = QPixmap("image/gui/GoldTicket.png").scaled(80, 80, Qt.KeepAspectRatio)
silver_ticket_pixmap = QPixmap("image/gui/SilverTicket.png").scaled(80, 80, Qt.KeepAspectRatio)
self.cmd_button.setIcon(QIcon(cmd_pixmap))
self.cmd_button.setIconSize(cmd_pixmap.size())
self.cmd_button.setFixedSize(80, 80)
self.gold_ticket_button.setIcon(QIcon(gold_ticket_pixmap))
self.gold_ticket_button.setIconSize(gold_ticket_pixmap.size())
self.gold_ticket_button.setFixedSize(80, 80)
self.silver_ticket_button.setIcon(QIcon(silver_ticket_pixmap))
self.silver_ticket_button.setIconSize(silver_ticket_pixmap.size())
self.silver_ticket_button.setFixedSize(80, 80)
self.cmd_button.clicked.connect(self.open_cmd)
self.gold_ticket_button.clicked.connect(self.open_gold_ticket_simulator)
self.silver_ticket_button.clicked.connect(self.open_silver_ticket_simulator)
bottom_layout = QHBoxLayout()
bottom_layout.addWidget(self.cmd_button)
bottom_layout.addWidget(self.gold_ticket_button)
bottom_layout.addWidget(self.silver_ticket_button)
self.stellar_jade_button = QPushButton()
stellar_jade_pixmap = QPixmap("image/gui/stellarjade.png").scaled(80, 80, Qt.KeepAspectRatio)
self.stellar_jade_button.setIcon(QIcon(stellar_jade_pixmap))
self.stellar_jade_button.setIconSize(stellar_jade_pixmap.size())
self.stellar_jade_button.setFixedSize(80, 80)
self.stellar_jade_button.clicked.connect(self.open_stellar_jade_website)
bottom_layout.addWidget(self.stellar_jade_button)
self.left_layout.addStretch()
self.left_layout.addLayout(bottom_layout)
self.left_frame.setLayout(self.left_layout)
layout.addWidget(self.left_frame, stretch=22)
self.right_frame = QFrame()
self.right_layout = QVBoxLayout()
self.right_layout.setAlignment(Qt.AlignTop)
self.scroll_area = QScrollArea()
self.scroll_area.setWidgetResizable(True)
self.scroll_widget = QWidget()
self.scroll_layout = QVBoxLayout()
self.scroll_layout.setAlignment(Qt.AlignTop)
self.scroll_widget.setLayout(self.scroll_layout)
self.scroll_area.setWidget(self.scroll_widget)
self.right_layout.addWidget(self.scroll_area)
# 添加音乐播放器
self.music_player = MusicPlayerWidget(self)
self.right_layout.addWidget(self.music_player)
self.right_frame.setLayout(self.right_layout)
layout.addWidget(self.right_frame, stretch=78)
self.setLayout(layout)
font_path = "fonts/SDK_SC_Web65.ttf"
if os.path.exists(font_path):
font_id = QFontDatabase.addApplicationFont(font_path)
font_family = QFontDatabase.applicationFontFamilies(font_id)[0]
QApplication.setFont(QFont(font_family))
self.load_player_list()
def load_player_list(self):
for i in reversed(range(self.player_buttons_frame.count())):
widget = self.player_buttons_frame.itemAt(i).widget()
if widget is not None:
widget.deleteLater()
if os.path.exists(SAVE_DIR):
for uid in os.listdir(SAVE_DIR):
player_dir = os.path.join(SAVE_DIR, uid)
if os.path.isdir(player_dir):
with open(os.path.join(player_dir, "player_data.json"), 'r', encoding='utf-8') as f:
data = json.load(f)
player_name = data['player']['nickname']
player_level = data['player']['level']
player_widget = QFrame()
player_layout = QHBoxLayout(player_widget)
player_button = QPushButton(f"{player_name} Lv.{player_level}")
player_button.setFixedWidth(350)
player_button.setFixedHeight(80)
player_button.setStyleSheet("""
QPushButton {
border: 1px solid black;
border-radius: 10px;
padding: 8px;
background-color: white;
font-weight: bold;
}
QPushButton:hover {
background-color: lightgray;
}
""")
view_icon = QIcon("image/gui/open.png")
player_button.setIcon(view_icon)
player_button.setIconSize(QSize(40, 40))
player_button.clicked.connect(lambda _, uid=uid: self.load_player_data(uid))
refresh_button = QPushButton()
refresh_button.setIcon(QIcon("image/gui/update.png"))
refresh_button.setIconSize(QSize(40, 40))
refresh_button.setFixedSize(60, 60)
refresh_button.setContentsMargins(5, 0, 5, 0)
refresh_button.clicked.connect(lambda _, uid=uid: self.refresh_player_data(uid))
refresh_button.setStyleSheet("""
QPushButton {
border: none;
background-color: transparent;
padding: 0px;
}
QPushButton:hover {
background-color: rgba(0, 0, 255, 0.3);
}
""")
delete_button = QPushButton()
delete_button.setIcon(QIcon("image/gui/delete.png"))
delete_button.setIconSize(QSize(40, 40))
delete_button.setFixedSize(60, 60)
delete_button.setContentsMargins(5, 0, 5, 0)
delete_button.setStyleSheet("""
QPushButton {
border: none;
background-color: transparent;
padding: 0px;
}
QPushButton:hover {
background-color: rgba(255, 0, 0, 0.3);
}
""")
delete_button.clicked.connect(lambda _, uid=uid: self.delete_player_data(uid))
player_layout.addWidget(player_button)
player_layout.addWidget(refresh_button)
player_layout.addWidget(delete_button)
self.player_buttons_frame.addWidget(player_widget)
def load_player_data(self, uid):
player_dir = os.path.join(SAVE_DIR, uid)
if os.path.exists(player_dir):
self.current_data = []
for file_name in os.listdir(player_dir):
if file_name.endswith('.pkl'):
with open(os.path.join(player_dir, file_name), 'rb') as f:
character_data = pickle.load(f)
self.current_data.append(character_data)
with open(os.path.join(player_dir, "player_data.json"), 'r', encoding='utf-8') as f:
self.current_player = json.load(f)['player']
self.display_player_data(self.current_data)
def refresh_player_data(self, uid):
self.fetch_data(uid)
self.load_player_data(uid)
def clear_right_layout(self):
while self.scroll_layout.count():
item = self.scroll_layout.takeAt(0)
widget = item.widget()
if widget:
widget.deleteLater()
else:
sub_layout = item.layout()
if sub_layout:
while sub_layout.count():
sub_item = sub_layout.takeAt(0)
sub_widget = sub_item.widget()
if sub_widget:
sub_widget.deleteLater()
sub_layout.deleteLater()
def delete_player_data(self, uid):
player_dir = os.path.join(SAVE_DIR, uid)
if os.path.exists(player_dir):
import shutil
shutil.rmtree(player_dir)
self.load_player_list()
def prompt_for_uid(self):
uid, ok = QInputDialog.getText(self, "输入 UID", "请输入玩家 UID:")
if ok and uid:
self.fetch_data(uid.strip())
def fetch_data(self, uid):
if len(uid) != 9 or not uid.isdigit() or uid.startswith('0'):
QMessageBox.critical(self, "Invalid UID", "<b>UID必须是9位数字且不能以 '0' 开头。请重试。</b>")
return
url = f"https://api.mihomo.me/sr_info_parsed/{uid}?lang=cn"
try:
response = requests.get(url)
response.raise_for_status()
data = response.json()
self.save_data(uid, data)
self.load_player_list()
except requests.RequestException:
QMessageBox.critical(self, "Fetch Failed", "<b>无法获取数据,请检查UID或网络连接。</b>")
def save_data(self, uid, data):
player_dir = os.path.join(SAVE_DIR, uid)
os.makedirs(player_dir, exist_ok=True)
for character in data['characters']:
char_file_path = os.path.join(player_dir, f"{character['id']}.pkl")
with open(char_file_path, 'wb') as f:
pickle.dump(character, f)
with open(os.path.join(player_dir, "player_data.json"), 'w', encoding='utf-8') as f:
json.dump(data, f)
software_data = {
"last_updated": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
software_file_path = os.path.join(player_dir, "software.json")
with open(software_file_path, "w", encoding='utf-8') as f:
json.dump(software_data, f)
def load_software_data(self, uid):
software_file_path = os.path.join(SAVE_DIR, uid, "software.json")
if os.path.exists(software_file_path):
with open(software_file_path, 'r', encoding='utf-8') as f:
software_data = json.load(f)
return software_data.get('last_updated', '未更新')
return '未更新'
def display_player_data(self, characters):
self.clear_right_layout()
if self.current_player:
last_updated_time = self.load_software_data(self.current_player['uid'])
player_info = QLabel(f"<b style='font-size:48px;'>{self.current_player['nickname']}</b><br>"
f"<b style='font-size:26px; font-weight:bold;'>UID:</b> "
f"<b style='font-size:35px; font-weight:bold;'>{self.current_player['uid']}</b><br>"
f"<b style='font-size:26px; font-weight:bold;'>上次刷新时间:</b> "
f"<b style='font-size:26px; font-weight:bold;'>{last_updated_time}</b><br><br>")
self.scroll_layout.addWidget(player_info)
grid_layout = QGridLayout()
spacing = 20
grid_layout.setSpacing(spacing)
button_width = 280
image_width = 280
image_height = 384
available_width = self.scroll_area.width() - (spacing * 2)
buttons_per_row = max(1, available_width // (button_width + spacing))
for index, character in enumerate(characters):
char_button = QPushButton()
char_pixmap = QPixmap(f"image/avataricon/{character['id']}.png").scaled(image_width, image_height, Qt.KeepAspectRatio)
char_button.setIcon(QIcon(char_pixmap))
char_button.setIconSize(QSize(image_width, image_height))
char_button.setFixedSize(image_width, image_height)
element = character['element']['name']
border_color = self.element_colors.get(element, '#000000')
shadow = QGraphicsDropShadowEffect(self)
shadow.setBlurRadius(15)
shadow.setColor(QColor(border_color))
shadow.setOffset(0, 0)
char_button.setGraphicsEffect(shadow)
char_button.setStyleSheet(f"""
QPushButton {{
border: 5px solid {border_color};
border-radius: 15px;
background-color: transparent;
}}
QPushButton:hover {{
background-color: rgba(0, 0, 0, 0.1);
}}
""")
char_button.clicked.connect(lambda _, char=character: self.show_character_details(char))
row = index // buttons_per_row
column = index % buttons_per_row
grid_layout.addWidget(char_button, row, column)
self.scroll_layout.addLayout(grid_layout)
def show_character_details(self, character):
detail_window = CharacterDetailWindow(character, self.element_colors, self.paths_mapping)
self.detail_windows.append(detail_window)
detail_window.show()
def open_cmd(self):
os.system("start cmd")
def open_gold_ticket_simulator(self):
self.gold_window = GoldTicketWindow()
self.gold_window.show()
def open_silver_ticket_simulator(self):
self.silver_window = SilverTicketWindow()
self.silver_window.show()
def open_stellar_jade_website(self):
reply = QMessageBox.question(self, "即将打开第三方抽卡模拟网站",
"本网站和工具箱作者无关,是否确定要打开网站?",
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
webbrowser.open("https://hsr.wishsimulator.app")
def resizeEvent(self, event):
super().resizeEvent(event)
if self.current_data:
self.display_player_data(self.current_data)
class MusicPlayerWidget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("音乐播放器")
# 创建播放器和播放列表
self.player = QMediaPlayer(self)
self.playlist = QMediaPlaylist(self)
self.player.setPlaylist(self.playlist)
# 设置UI布局
layout = QVBoxLayout(self)
# 显示音乐名称的标签
self.song_label = QLabel("选择一首乐曲", self)
self.song_label.setStyleSheet("color: black; font-size: 18px; font-weight: bold;")
self.song_label.setAlignment(Qt.AlignCenter)
layout.addWidget(self.song_label)
# 播放进度条
self.progress_slider = QSlider(Qt.Horizontal, self)
self.progress_slider.setStyleSheet(
"QSlider::groove:horizontal {background: #d3d3d3;} QSlider::handle:horizontal {background: lightblue;}")
layout.addWidget(self.progress_slider)
# 添加按钮布局
buttonLayout = QHBoxLayout() # 改变为水平布局
self.play_button = QPushButton("▶", self)
self.play_button.setStyleSheet("background-color: transparent; color: black; font-size: 24px; font-weight: bold;")
self.play_button.clicked.connect(self.toggle_play)
buttonLayout.addWidget(self.play_button)
self.browse_button = QPushButton("选择音乐文件", self)
self.browse_button.setStyleSheet("background-color: transparent; color: black; font-weight: bold;")
self.browse_button.clicked.connect(self.browse_files)
buttonLayout.addWidget(self.browse_button)
layout.addLayout(buttonLayout)
# 添加颜色和秀背景
self.setAttribute(Qt.WA_StyledBackground, True)
self.setStyleSheet("background-color: rgba(211, 211, 211, 0.7); border-radius: 15px;")
# 连接信号和槽
self.player.durationChanged.connect(self.update_duration)
self.player.positionChanged.connect(self.update_position)
self.progress_slider.sliderMoved.connect(self.set_position)
def toggle_play(self):
if self.player.state() == QMediaPlayer.PlayingState:
self.player.pause()
self.play_button.setText("▶")
else:
self.player.play()
self.play_button.setText("⏸")
def browse_files(self):
file_name, _ = QFileDialog.getOpenFileName(self, "选择音乐文件", "./music", "Music Files (*.mp3 *.ogg *.wav *.flac *.mid)")
if file_name:
self.playlist.clear()
self.playlist.addMedia(QUrl.fromLocalFile(file_name))
self.song_label.setText(file_name.split("/")[-1])
self.player.play()
self.play_button.setText("⏸")
def update_duration(self, duration):
self.progress_slider.setRange(0, duration)
def update_position(self, position):
if not self.progress_slider.isSliderDown():
self.progress_slider.setValue(position)
def set_position(self, position):
self.player.setPosition(position)
# 在HSRToolApp的initUI方法中调整音乐播放器的布局
def initUI(self):
...
# 添加音乐播放器
self.music_player = MusicPlayerWidget(self)
self.right_layout.addStretch()
self.right_layout.addWidget(self.music_player)
...
改动说明:
背景和文字样式:
调整播放器背景为半透明淡灰色(rgba(211, 211, 211, 0.7))。
标签和按钮的文字颜色变为黑色并加粗。
播放器布局:
在播放器UI布局中,按钮使用水平布局 (QHBoxLayout) 以确保播放和选择文件按钮能够自然展示。
播放器位置:
将播放器加在 right_layout 的底部,通过 addStretch() 确保其在整个应用的末尾。
以上内容将会使得音乐播放器始终与角色列表在right_layout中保持一个固定的、占据全宽的位置,并在其背景上应用半透明,确保它在视觉上和整个应用程序中的其他部分协调一致。
class MusicPlayerContainer(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
# 设置布局
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
# 添加音乐播放器
self.music_player_widget = MusicPlayerWidget(self)
layout.addWidget(self.music_player_widget)
# 设置背景样式
self.setAttribute(Qt.WA_StyledBackground, True)
self.setStyleSheet("background-color: rgba(211, 211, 211, 0.7); border-radius: 15px;")
class HSRToolApp(QWidget):
def __init__(self):
super().__init__()
self.current_data = None
self.current_player = None
self.element_colors = load_element_colors()
self.paths_mapping = load_paths_mapping()
self.detail_windows = []
self.initUI()
def initUI(self):
self.setWindowTitle("HSR Toolkit")
self.setWindowIcon(QIcon("image/gui/icon.ico"))
self.setGeometry(0, 0, 800, 600)
self.showMaximized()
layout = QVBoxLayout(self)
self.left_frame = QFrame()
self.left_layout = QVBoxLayout()
self.left_layout.setAlignment(Qt.AlignTop)
self.add_player_button = QPushButton("添加玩家数据")
self.add_player_button.setIcon(QIcon("image/gui/add.svg"))
self.add_player_button.setIconSize(QSize(24, 24))
self.add_player_button.setFixedWidth(600)
self.add_player_button.setStyleSheet("""
QPushButton {
border: 2px solid black;
border-radius: 10px;
color: gray;
background-color: white;
padding: 8px;
font-weight: bold;
}
QPushButton:hover {
background-color: lightblue;
color: black;
}
""")
self.add_player_button.setToolTip("点击添加玩家数据")
self.add_player_button.clicked.connect(self.prompt_for_uid)
self.left_layout.addWidget(self.add_player_button, alignment=Qt.AlignTop)
self.player_buttons_frame = QVBoxLayout()
self.player_buttons_frame.setAlignment(Qt.AlignTop)
self.left_layout.addLayout(self.player_buttons_frame)
self.cmd_button = QPushButton()
self.gold_ticket_button = QPushButton()
self.silver_ticket_button = QPushButton()
cmd_pixmap = QPixmap("image/gui/cmd.png").scaled(80, 80, Qt.KeepAspectRatio)
gold_ticket_pixmap = QPixmap("image/gui/GoldTicket.png").scaled(80, 80, Qt.KeepAspectRatio)
silver_ticket_pixmap = QPixmap("image/gui/SilverTicket.png").scaled(80, 80, Qt.KeepAspectRatio)
self.cmd_button.setIcon(QIcon(cmd_pixmap))
self.cmd_button.setIconSize(cmd_pixmap.size())
self.cmd_button.setFixedSize(80, 80)
self.gold_ticket_button.setIcon(QIcon(gold_ticket_pixmap))
self.gold_ticket_button.setIconSize(gold_ticket_pixmap.size())
self.gold_ticket_button.setFixedSize(80, 80)
self.silver_ticket_button.setIcon(QIcon(silver_ticket_pixmap))
self.silver_ticket_button.setIconSize(silver_ticket_pixmap.size())
self.silver_ticket_button.setFixedSize(80, 80)
self.cmd_button.clicked.connect(self.open_cmd)
self.gold_ticket_button.clicked.connect(self.open_gold_ticket_simulator)
self.silver_ticket_button.clicked.connect(self.open_silver_ticket_simulator)
bottom_layout = QHBoxLayout()
bottom_layout.addWidget(self.cmd_button)
bottom_layout.addWidget(self.gold_ticket_button)
bottom_layout.addWidget(self.silver_ticket_button)
self.stellar_jade_button = QPushButton()
stellar_jade_pixmap = QPixmap("image/gui/stellarjade.png").scaled(80, 80, Qt.KeepAspectRatio)
self.stellar_jade_button.setIcon(QIcon(stellar_jade_pixmap))
self.stellar_jade_button.setIconSize(stellar_jade_pixmap.size())
self.stellar_jade_button.setFixedSize(80, 80)
self.stellar_jade_button.clicked.connect(self.open_stellar_jade_website)
bottom_layout.addWidget(self.stellar_jade_button)
self.left_layout.addStretch()
self.left_layout.addLayout(bottom_layout)
self.left_frame.setLayout(self.left_layout)
layout.addWidget(self.left_frame, stretch=22)
self.right_frame = QFrame()
self.right_layout = QVBoxLayout()
self.right_layout.setAlignment(Qt.AlignTop)
self.scroll_area = QScrollArea()
self.scroll_area.setWidgetResizable(True)
self.scroll_widget = QWidget()
self.scroll_layout = QVBoxLayout()
self.scroll_layout.setAlignment(Qt.AlignTop)
self.scroll_widget.setLayout(self.scroll_layout)
self.scroll_area.setWidget(self.scroll_widget)
self.right_layout.addWidget(self.scroll_area)
# 添加音乐播放器容器
self.music_player_container = MusicPlayerContainer(self)
self.right_layout.addWidget(self.music_player_container)
self.right_frame.setLayout(self.right_layout)
layout.addWidget(self.right_frame, stretch=78)
self.setLayout(layout)
font_path = "fonts/SDK_SC_Web65.ttf"
if os.path.exists(font_path):
font_id = QFontDatabase.addApplicationFont(font_path)
font_family = QFontDatabase.applicationFontFamilies(font_id)[0]
QApplication.setFont(QFont(font_family))
self.load_player_list()
说明:
MusicPlayerContainer : 我们创建了一个 MusicPlayerContainer 类来封装 MusicPlayerWidget,这个类有一个设置好的背景风格。
布局调整 : 在主应用中,MusicPlayerContainer 被添加到 right_layout 的末尾,确保播放器与角色列表靠近,并且在底部加载。
样式 : MusicPlayerContainer 继承了原本播放器的半透明淡灰色背景样式。
这样一来,你的播放器将位于角色列表的底部,并呈现为一个独立的半透明 UI 组件。
def load_affix_mapping(self):
file_path = os.path.join("config", "software", "affixmapping.json")
if os.path.exists(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
return json.load(file)
return {}
def load_rarity_colors(self):
file_path = os.path.join("config", "software", "raritycoloring.json")
if os.path.exists(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
return json.load(file)
return {}
def get_gradient_style(self, rarity):
colors = self.rarity_colors
if str(rarity) in colors:
start = colors[str(rarity)]['start']
end = colors[str(rarity)]['end']
return f"background: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 {start}, stop:1 {end});"
return ""
def initUI(self):
self.setWindowTitle(f"{self.character['name']} - 详细信息")
self.showMaximized()
self.set_background()
main_layout = QVBoxLayout(self)
self.setLayout(main_layout)
main_layout.setContentsMargins(0, 0, 0, 0)
scroll_area = QScrollArea(self)
scroll_area.setWidgetResizable(True)
scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
main_layout.addWidget(scroll_area)
container = QWidget()
scroll_area.setWidget(container)
layout = QVBoxLayout(container)
layout.setContentsMargins(50, 50, 50, 50)
# 添加角色立绘
splashart_path = f"image/splashart/{self.character['id']}.png"
splashart_pixmap = QPixmap(splashart_path).scaled(768, 768, Qt.KeepAspectRatio, Qt.SmoothTransformation)
splashart_label = QLabel(container)
splashart_label.setPixmap(splashart_pixmap)
layout.addWidget(splashart_label, alignment=Qt.AlignLeft | Qt.AlignTop)
path_name = self.character['path']['name'].lower()
path_icon_key = self.paths_mapping.get(path_name, None)
if path_icon_key:
path_icon_path = f"image/path/{path_icon_key}.png"
path_pixmap = QPixmap(path_icon_path).scaled(128, 128, Qt.KeepAspectRatio, Qt.SmoothTransformation)
path_icon_label = QLabel(splashart_label)
path_icon_label.setPixmap(path_pixmap)
path_icon_label.move(10, 10)
# 整个光锥和信息的表格
light_cone_frame = LightConeFrame(self.character, self.affix_mapping, container)
light_cone_frame.setFixedSize(896, 576)
layout.addWidget(light_cone_frame, alignment=Qt.AlignTop)
light_cone_layout = QVBoxLayout(light_cone_frame)
light_cone_layout.setContentsMargins(0, 0, 0, 0)
# 上部信息部分
top_section = QWidget(light_cone_frame)
top_section.setFixedHeight(192)
top_layout = QHBoxLayout(top_section)
top_layout.setContentsMargins(0, 0, 0, 0)
# 左侧光锥图片和渐变背景
light_cone = self.character.get('light_cone')
if light_cone:
rarity = light_cone['rarity']
cone_id = light_cone['id']
gradient_style = self.get_gradient_style(rarity)
cone_name = light_cone['name']
cone_level = light_cone['level']
cone_rank = light_cone['rank']
else:
rarity = 0
cone_id = 'unequip'
gradient_style = "background-color: #444444;"
cone_name = "未佩戴光锥"
cone_level = "N/A"
cone_rank = "N/A"
gradient_section = QWidget(top_section)
gradient_section.setFixedSize(192, 192)
gradient_section.setStyleSheet(gradient_style + "border-top-left-radius: 15px;")
# 在渐变背景中居中显示光锥图
gradient_layout = QVBoxLayout(gradient_section)
gradient_layout.setContentsMargins(0, 0, 0, 0)
lightcone_pixmap = QPixmap(f"image/lightcone/{cone_id}.png").scaled(180, 180, Qt.KeepAspectRatio, Qt.SmoothTransformation)
lightcone_label = QLabel()
lightcone_label.setPixmap(lightcone_pixmap)
lightcone_label.setAlignment(Qt.AlignCenter)
gradient_layout.addWidget(lightcone_label)
top_layout.addWidget(gradient_section)
# 右侧信息区域
right_section = QWidget(top_section)
right_layout = QVBoxLayout(right_section)
right_layout.setContentsMargins(0, 0, 0, 0)
# 光锥名称
colors = self.rarity_colors.get(str(rarity), {})
end_color = colors.get("end", "#ffffff")
name_label = QLabel(cone_name, right_section)
name_label.setFixedHeight(72)
name_label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
name_label.setStyleSheet(f"color: {end_color}; font-size: 36px; font-weight: bold; padding: 0px 2px;")
right_layout.addWidget(name_label)
# 第二行: 光锥命途图标、等级、叠影数量
second_row = QWidget(right_section)
second_row.setFixedHeight(64)
second_row_layout = QHBoxLayout(second_row)
second_row_layout.setContentsMargins(0, 0, 0, 0)
# 设置布局的对齐方式为左对齐
second_row_layout.setAlignment(Qt.AlignLeft)
path_icon_label = QLabel(second_row)
path_icon_label.setPixmap(QPixmap(path_icon_path).scaled(64, 64, Qt.KeepAspectRatio))
path_icon_label.setFixedSize(64, 64)
second_row_layout.addWidget(path_icon_label)
level_label = QLabel(f"等级 {cone_level}", second_row)
level_label.setFixedSize(128, 64)
level_label.setAlignment(Qt.AlignCenter)
level_label.setStyleSheet("color: white; font-size: 32px; font-weight: bold;")
second_row_layout.addWidget(level_label)
rank_roman = ["Ⅰ", "Ⅱ", "Ⅲ", "Ⅳ", "Ⅴ"]
rank_label = QLabel(rank_roman[int(cone_rank) - 1] if cone_rank != "N/A" else "N/A", second_row)
rank_label.setFixedSize(64, 64)
rank_label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
rank_label.setStyleSheet("color: white; font-size: 32px; font-weight: bold;")
second_row_layout.addWidget(rank_label)
right_layout.addWidget(second_row)
# 稀有度一行
font_id = QFontDatabase.addApplicationFont("fonts/hsr-icon.ttf")
font_family = QFontDatabase.applicationFontFamilies(font_id)[0]
star_label = QLabel("b" * rarity, right_section)
star_label.setFixedHeight(66)
star_label.setAlignment(Qt.AlignLeft)
custom_font = QFont(font_family, 16)
star_label.setFont(custom_font)
star_label.setStyleSheet(
f"color: {end_color}; font-weight: bold; "
f"margin: 0px 0px 0px 0px;"
)
right_layout.addWidget(star_label)
top_layout.addWidget(right_section)
light_cone_layout.addWidget(top_section)
# 下方滚动区域
bottom_section = QScrollArea(light_cone_frame)
bottom_section.setMinimumHeight(384)
bottom_section.setWidgetResizable(True)
bottom_section.setStyleSheet("background-color: transparent; border: none;")
bottom_section.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
bottom_section.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
bottom_content = QWidget()
bottom_layout = QVBoxLayout(bottom_content)
if light_cone:
lightcone_data = self.load_lightcone_data(cone_id)
if lightcone_data:
description_browser = QTextBrowser(bottom_content)
description_browser.setStyleSheet("background-color: transparent; color: white; font-weight: bold;")
self.populate_lightcone_description(description_browser, lightcone_data)
bottom_layout.addWidget(description_browser)
else:
description_browser = QTextBrowser(bottom_content)
description_browser.setStyleSheet("color: white; font-weight: bold;")
description_browser.append("未佩戴光锥")
bottom_layout.addWidget(description_browser)
bottom_section.setWidget(bottom_content)
light_cone_layout.addWidget(bottom_section)
def load_lightcone_data(self, lightcone_id):
file_path = os.path.join("config", "lightcone", f"{lightcone_id}.json")
if os.path.exists(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
return json.load(file)
return None
def populate_lightcone_description(self, text_browser, data):
rarity = self.character['light_cone']['rank']
skill_description = data.get("combined_skill_description", "").replace("\n", "<br>")
light_cone_description = data.get("light_cone_description", "").replace("\n", "<br>")
text_browser.clear()
# Skill name and rarity level line
skill_name = data.get("skill_name", "")
text_browser.append(f"{skill_name} - 等级 {rarity}")
# Skill description with highlighting
skill_text = ""
start_marker = '[['
end_marker = ']]'
start = skill_description.find(start_marker)
while start != -1:
end = skill_description.find(end_marker, start)
if end != -1:
actual_start = start + len(start_marker)
actual_end = end
skill_text += skill_description[:start]
# Highlight the number according to rarity
numbers_str = skill_description[actual_start:actual_end].split(',')
if 1 <= rarity <= len(numbers_str):
number_to_highlight = numbers_str[rarity - 1].strip()
skill_text += f"<span style='color:orange;'>{number_to_highlight}</span>"
skill_description = skill_description[end + len(end_marker):]
start = skill_description.find(start_marker)
else:
break
skill_text += skill_description
text_browser.append(skill_text)
# 添加空行
text_browser.append("<br>")
# Light cone description in gray
text_browser.append(f"<div style='color:grey;'>{light_cone_description}</div>")
def set_background(self):
palette = self.palette()
background_pixmap = QPixmap("image/gui/background.jpeg").scaled(self.size(), Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
palette.setBrush(QPalette.Window, QBrush(background_pixmap))
self.setPalette(palette)
def resizeEvent(self, event):
self.set_background()
super().resizeEvent(event)
class LightConeFrame(QWidget):
def init (self, character, affix_mapping, parent=None, bg_color="#262634"):
super().init (parent)
self.bg_color = bg_color
self.character = character
self.affix_mapping = affix_mapping
code Copy code
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
rect = self.rect()
# 填充背景色
painter.fillRect(rect, QColor(self.bg_color))
# 绘制右侧分割线
pen = painter.pen()
pen.setWidth(2)
pen.setColor(QColor('#444444'))
painter.setPen(pen)
# 计算分割线的起始和终止点位置
x_position = rect.width() - 320
y_end = 192
painter.drawLine(x_position, 0, x_position, y_end)
# 绘制表格框线
pen.setWidth(5)
pen.setColor(QColor('#444444'))
painter.setPen(pen)
painter.drawRoundedRect(rect.adjusted(1, 1, -1, -1), 30, 30)
# 绘制水平分割线
horizontal_line_y_position = 192
painter.drawLine(0, horizontal_line_y_position, rect.width(), horizontal_line_y_position)
# 在这里添加检测光锥是否存在并绘制属性图标、名称及数值
light_cone = self.character.get('light_cone')
attributes = light_cone.get('attributes', []) if light_cone else []
for idx, attribute in enumerate(attributes):
attr_name = attribute['name']
attr_value = float(attribute['value'])
attr_display = f"{attr_value:.3f}"
icon_file = self.affix_mapping.get(attr_name, None)
if icon_file:
icon_path = f"image/buffdata/{icon_file}.png"
if os.path.exists(icon_path):
icon_pixmap = QPixmap(icon_path).scaled(64, 64, Qt.KeepAspectRatio, Qt.SmoothTransformation)
# 下调图标1px
icon_y = (idx * 64) - 4 + 1
# 绘制图标:与框线对齐
painter.drawPixmap(x_position + 10, icon_y, icon_pixmap)
# 设置淡灰色
light_gray = QColor(169, 169, 169)
painter.setPen(light_gray)
# 绘制属性名称,向下移动1像素
font = painter.font()
font.setBold(True)
font.setPointSize(10)
painter.setFont(font)
# 设置属性名称的位置(向下移动1像素)
name_x = x_position + 80
name_y = (idx * 64) + (64 + self.fontMetrics().height()) // 2 + 1
attr_abbr = self.affix_mapping.get(attr_name, attr_name)
painter.drawText(QRect(name_x, (idx * 64) + 1, 150, 64), Qt.AlignVCenter | Qt.AlignLeft, attr_abbr)
# 计算数字的宽度并调整位置
font.setBold(True)
font.setPointSize(11)
painter.setFont(font)
int_width = self.fontMetrics().width(str(int(attr_value)))
# 设置小数部分的颜色和字体
darker_gray = QColor(105, 105, 105)
decimal_font = QFont(font)
decimal_font.setPointSize(8)
decimal_width = QFontMetrics(decimal_font).width(f".{attr_display.split('.')[1]}")
total_width = int_width + decimal_width
text_x = rect.width() - total_width - 19
# 将所有数字上移6像素
int_y = icon_y + (64 + self.fontMetrics().height()) // 2 - 6
# 绘制整数部分,右移一些
offset = 2
painter.drawText(QPoint(text_x + offset, int_y), str(int(attr_value)))
# 绘制小数部分
painter.setFont(decimal_font)
painter.setPen(darker_gray)
painter.drawText(QPoint(text_x + int_width + offset, int_y), f".{attr_display.split('.')[1]}")
super().paintEvent(event)
class MusicPlayerWidget(QWidget):
def init (self, parent=None):
super().init (parent)
self.setWindowTitle("音乐播放器")
code Copy code
# 创建播放器和播放列表
self.player = QMediaPlayer(self)
self.playlist = QMediaPlaylist(self)
self.player.setPlaylist(self.playlist)
# 设置UI布局
layout = QVBoxLayout(self)
# 显示音乐名称的标签
self.song_label = QLabel("选择一首乐曲", self)
self.song_label.setStyleSheet("color: black; font-size: 18px; font-weight: bold;")
self.song_label.setAlignment(Qt.AlignCenter)
layout.addWidget(self.song_label)
# 播放进度条
self.progress_slider = QSlider(Qt.Horizontal, self)
self.progress_slider.setStyleSheet(
"QSlider::groove:horizontal {background: #d3d3d3;} QSlider::handle:horizontal {background: lightblue;}")
layout.addWidget(self.progress_slider)
# 添加按钮布局
buttonLayout = QHBoxLayout() # 改变为水平布局
self.play_button = QPushButton("▶", self)
self.play_button.setStyleSheet("background-color: transparent; color: black; font-size: 24px; font-weight: bold;")
self.play_button.clicked.connect(self.toggle_play)
buttonLayout.addWidget(self.play_button)
self.browse_button = QPushButton("选择音乐文件", self)
self.browse_button.setStyleSheet("background-color: transparent; color: black; font-weight: bold;")
self.browse_button.clicked.connect(self.browse_files)
buttonLayout.addWidget(self.browse_button)
layout.addLayout(buttonLayout)
# 添加颜色和秀背景
self.setAttribute(Qt.WA_StyledBackground, True)
self.setStyleSheet("background-color: rgba(211, 211, 211, 0.7); border-radius: 15px;")
# 连接信号和槽
self.player.durationChanged.connect(self.update_duration)
self.player.positionChanged.connect(self.update_position)
self.progress_slider.sliderMoved.connect(self.set_position)
def toggle_play(self):
if self.player.state() == QMediaPlayer.PlayingState:
self.player.pause()
self.play_button.setText("▶")
else:
self.player.play()
self.play_button.setText("⏸")
def browse_files(self):
file_name, _ = QFileDialog.getOpenFileName(self, "选择音乐文件", "./music", "Music Files (*.mp3 *.ogg *.wav *.flac *.mid)")
if file_name:
self.playlist.clear()
self.playlist.addMedia(QUrl.fromLocalFile(file_name))
self.song_label.setText(file_name.split("/")[-1])
self.player.play()
self.play_button.setText("⏸")
def update_duration(self, duration):
self.progress_slider.setRange(0, duration)
def update_position(self, position):
if not self.progress_slider.isSliderDown():
self.progress_slider.setValue(position)
def set_position(self, position):
self.player.setPosition(position)
class MusicPlayerContainer(QWidget):
def init (self, parent=None):
super().init (parent)
code Copy code
# 设置布局
layout = QVBoxLayout(self)
layout.setContentsMargins(10, 10, 10, 10) # 控制边距
# 添加音乐播放器
self.music_player_widget = MusicPlayerWidget(self)
layout.addWidget(self.music_player_widget)
# 设置背景样式
self.setAttribute(Qt.WA_StyledBackground, True)
self.setStyleSheet("background-color: rgba(211, 211, 211, 0.7); border-radius: 15px;")
class HSRToolApp(QWidget):
def init (self):
super().init ()
self.current_data = None
self.current_player = None
self.element_colors = load_element_colors()
self.paths_mapping = load_paths_mapping()
self.detail_windows = []
self.initUI()
code Copy code
def initUI(self):
self.setWindowTitle("HSR Toolkit")
self.setWindowIcon(QIcon("image/gui/icon.ico"))
self.setGeometry(0, 0, 800, 600)
self.showMaximized()
layout = QHBoxLayout(self)
self.left_frame = QFrame()
self.left_layout = QVBoxLayout()
self.left_layout.setAlignment(Qt.AlignTop)
self.add_player_button = QPushButton("添加玩家数据")
self.add_player_button.setIcon(QIcon("image/gui/add.svg"))
self.add_player_button.setIconSize(QSize(24, 24))
self.add_player_button.setFixedWidth(600)
self.add_player_button.setStyleSheet("""
QPushButton {
border: 2px solid black;
border-radius: 10px;
color: gray;
background-color: white;
padding: 8px;
font-weight: bold;
}
QPushButton:hover {
background-color: lightblue;
color: black;
}
""")
self.add_player_button.setToolTip("点击添加玩家数据")
self.add_player_button.clicked.connect(self.prompt_for_uid)
self.left_layout.addWidget(self.add_player_button, alignment=Qt.AlignTop)
self.player_buttons_frame = QVBoxLayout()
self.player_buttons_frame.setAlignment(Qt.AlignTop)
self.left_layout.addLayout(self.player_buttons_frame)
self.cmd_button = QPushButton()
self.gold_ticket_button = QPushButton()
self.silver_ticket_button = QPushButton()
cmd_pixmap = QPixmap("image/gui/cmd.png").scaled(80, 80, Qt.KeepAspectRatio)
gold_ticket_pixmap = QPixmap("image/gui/GoldTicket.png").scaled(80, 80, Qt.KeepAspectRatio)
silver_ticket_pixmap = QPixmap("image/gui/SilverTicket.png").scaled(80, 80, Qt.KeepAspectRatio)
self.cmd_button.setIcon(QIcon(cmd_pixmap))
self.cmd_button.setIconSize(cmd_pixmap.size())
self.cmd_button.setFixedSize(80, 80)
self.gold_ticket_button.setIcon(QIcon(gold_ticket_pixmap))
self.gold_ticket_button.setIconSize(gold_ticket_pixmap.size())
self.gold_ticket_button.setFixedSize(80, 80)
self.silver_ticket_button.setIcon(QIcon(silver_ticket_pixmap))
self.silver_ticket_button.setIconSize(silver_ticket_pixmap.size())
self.silver_ticket_button.setFixedSize(80, 80)
self.cmd_button.clicked.connect(self.open_cmd)
self.gold_ticket_button.clicked.connect(self.open_gold_ticket_simulator)
self.silver_ticket_button.clicked.connect(self.open_silver_ticket_simulator)
bottom_layout = QHBoxLayout()
bottom_layout.addWidget(self.cmd_button)
bottom_layout.addWidget(self.gold_ticket_button)
bottom_layout.addWidget(self.silver_ticket_button)
self.stellar_jade_button = QPushButton()
stellar_jade_pixmap = QPixmap("image/gui/stellarjade.png").scaled(80, 80, Qt.KeepAspectRatio)
self.stellar_jade_button.setIcon(QIcon(stellar_jade_pixmap))
self.stellar_jade_button.setIconSize(stellar_jade_pixmap.size())
self.stellar_jade_button.setFixedSize(80, 80)
self.stellar_jade_button.clicked.connect(self.open_stellar_jade_website)
bottom_layout.addWidget(self.stellar_jade_button)
self.left_layout.addStretch()
self.left_layout.addLayout(bottom_layout)
self.left_frame.setLayout(self.left_layout)
layout.addWidget(self.left_frame, stretch=22)
self.right_frame = QFrame()
self.right_layout = QVBoxLayout()
self.right_layout.setAlignment(Qt.AlignTop)
self.scroll_area = QScrollArea()
self.scroll_area.setWidgetResizable(True)
self.scroll_widget = QWidget()
self.scroll_layout = QVBoxLayout()
self.scroll_layout.setAlignment(Qt.AlignTop)
self.scroll_widget.setLayout(self.scroll_layout)
self.scroll_area.setWidget(self.scroll_widget)
self.right_layout.addWidget(self.scroll_area)
# 添加音乐播放器容器
self.music_player_container = MusicPlayerContainer(self)
self.right_layout.addWidget(self.music_player_container)
layout.addWidget(self.right_frame, stretch=78)
self.setLayout(layout)
font_path = "fonts/SDK_SC_Web65.ttf"
if os.path.exists(font_path):
font_id = QFontDatabase.addApplicationFont(font_path)
font_family = QFontDatabase.applicationFontFamilies(font_id)[0]
QApplication.setFont(QFont(font_family))
self.load_player_list()
def load_player_list(self):
for i in reversed(range(self.player_buttons_frame.count())):
widget = self.player_buttons_frame.itemAt(i).widget()
if widget is not None:
widget.deleteLater()
if os.path.exists(SAVE_DIR):
for uid in os.listdir(SAVE_DIR):
player_dir = os.path.join(SAVE_DIR, uid)
if os.path.isdir(player_dir):
with open(os.path.join(player_dir, "player_data.json"), 'r', encoding='utf-8') as f:
data = json.load(f)
player_name = data['player']['nickname']
player_level = data['player']['level']
player_widget = QFrame()
player_layout = QHBoxLayout(player_widget)
player_button = QPushButton(f"{player_name} Lv.{player_level}")
player_button.setFixedWidth(350)
player_button.setFixedHeight(80)
player_button.setStyleSheet("""
QPushButton {
border: 1px solid black;
border-radius: 10px;
padding: 8px;
background-color: white;
font-weight: bold;
}
QPushButton:hover {
background-color: lightgray;
}
""")
view_icon = QIcon("image/gui/open.png")
player_button.setIcon(view_icon)
player_button.setIconSize(QSize(40, 40))
player_button.clicked.connect(lambda _, uid=uid: self.load_player_data(uid))
refresh_button = QPushButton()
refresh_button.setIcon(QIcon("image/gui/update.png"))
refresh_button.setIconSize(QSize(40, 40))
refresh_button.setFixedSize(60, 60)
refresh_button.setContentsMargins(5, 0, 5, 0)
refresh_button.clicked.connect(lambda _, uid=uid: self.refresh_player_data(uid))
refresh_button.setStyleSheet("""
QPushButton {
border: none;
background-color: transparent;
padding: 0px;
}
QPushButton:hover {
background-color: rgba(0, 0, 255, 0.3);
}
""")
delete_button = QPushButton()
delete_button.setIcon(QIcon("image/gui/delete.png"))
delete_button.setIconSize(QSize(40, 40))
delete_button.setFixedSize(60, 60)
delete_button.setContentsMargins(5, 0, 5, 0)
delete_button.setStyleSheet("""
QPushButton {
border: none;
background-color: transparent;
padding: 0px;
}
QPushButton:hover {
background-color: rgba(255, 0, 0, 0.3);
}
""")
delete_button.clicked.connect(lambda _, uid=uid: self.delete_player_data(uid))
player_layout.addWidget(player_button)
player_layout.addWidget(refresh_button)
player_layout.addWidget(delete_button)
self.player_buttons_frame.addWidget(player_widget)
def load_player_data(self, uid):
player_dir = os.path.join(SAVE_DIR, uid)
if os.path.exists(player_dir):
self.current_data = []
for file_name in os.listdir(player_dir):
if file_name.endswith('.pkl'):
with open(os.path.join(player_dir, file_name), 'rb') as f:
character_data = pickle.load(f)
self.current_data.append(character_data)
with open(os.path.join(player_dir, "player_data.json"), 'r', encoding='utf-8') as f:
self.current_player = json.load(f)['player']
self.display_player_data(self.current_data)
def refresh_player_data(self, uid):
self.fetch_data(uid)
self.load_player_data(uid)
def clear_right_layout(self):
while self.scroll_layout.count():
item = self.scroll_layout.takeAt(0)
widget = item.widget()
if widget:
widget.deleteLater()
else:
sub_layout = item.layout()
if sub_layout:
while sub_layout.count():
sub_item = sub_layout.takeAt(0)
sub_widget = sub_item.widget()
if sub_widget:
sub_widget.deleteLater()
sub_layout.deleteLater()
def delete_player_data(self, uid):
player_dir = os.path.join(SAVE_DIR, uid)
if os.path.exists(player_dir):
import shutil
shutil.rmtree(player_dir)
self.load_player_list()
def prompt_for_uid(self):
uid, ok = QInputDialog.getText(self, "输入 UID", "请输入玩家 UID:")
if ok and uid:
self.fetch_data(uid.strip())
def fetch_data(self, uid):
if len(uid) != 9 or not uid.isdigit() or uid.startswith('0'):
QMessageBox.critical(self, "Invalid UID", "<b>UID必须是9位数字且不能以 '0' 开头。请重试。</b>")
return
url = f"https://api.mihomo.me/sr_info_parsed/{uid}?lang=cn"
try:
response = requests.get(url)
response.raise_for_status()
data = response.json()
self.save_data(uid, data)
self.load_player_list()
except requests.RequestException:
QMessageBox.critical(self, "Fetch Failed", "<b>无法获取数据,请检查UID或网络连接。</b>")
def save_data(self, uid, data):
player_dir = os.path.join(SAVE_DIR, uid)
os.makedirs(player_dir, exist_ok=True)
for character in data['characters']:
char_file_path = os.path.join(player_dir, f"{character['id']}.pkl")
with open(char_file_path, 'wb') as f:
pickle.dump(character, f)
with open(os.path.join(player_dir, "player_data.json"), 'w', encoding='utf-8') as f:
json.dump(data, f)
software_data = {
"last_updated": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
software_file_path = os.path.join(player_dir, "software.json")
with open(software_file_path, "w", encoding='utf-8') as f:
json.dump(software_data, f)
def load_software_data(self, uid):
software_file_path = os.path.join(SAVE_DIR, uid, "software.json")
if os.path.exists(software_file_path):
with open(software_file_path, 'r', encoding='utf-8') as f:
software_data = json.load(f)
return software_data.get('last_updated', '未更新')
return '未更新'
def display_player_data(self, characters):
self.clear_right_layout()
if self.current_player:
last_updated_time = self.load_software_data(self.current_player['uid'])
player_info = QLabel(f"<b style='font-size:48px;'>{self.current_player['nickname']}</b><br>"
f"<b style='font-size:26px; font-weight:bold;'>UID:</b> "
f"<b style='font-size:35px; font-weight:bold;'>{self.current_player['uid']}</b><br>"
f"<b style='font-size:26px; font-weight:bold;'>上次刷新时间:</b> "
f"<b style='font-size:26px; font-weight:bold;'>{last_updated_time}</b><br><br>")
self.scroll_layout.addWidget(player_info)
grid_layout = QGridLayout()
spacing = 20
grid_layout.setSpacing(spacing)
button_width = 280
image_width = 280
image_height = 384
available_width = self.scroll_area.width() - (spacing * 2)
buttons_per_row = max(1, available_width // (button_width + spacing))
for index, character in enumerate(characters):
char_button = QPushButton()
char_pixmap = QPixmap(f"image/avataricon/{character['id']}.png").scaled(image_width, image_height, Qt.KeepAspectRatio)
char_button.setIcon(QIcon(char_pixmap))
char_button.setIconSize(QSize(image_width, image_height))
char_button.setFixedSize(image_width, image_height)
element = character['element']['name']
border_color = self.element_colors.get(element, '#000000')
shadow = QGraphicsDropShadowEffect(self)
shadow.setBlurRadius(15)
shadow.setColor(QColor(border_color))
shadow.setOffset(0, 0)
char_button.setGraphicsEffect(shadow)
char_button.setStyleSheet(f"""
QPushButton {{
border: 5px solid {border_color};
border-radius: 15px;
background-color: transparent;
}}
QPushButton:hover {{
background-color: rgba(0, 0, 0, 0.1);
}}
""")
char_button.clicked.connect(lambda _, char=character: self.show_character_details(char))
row = index // buttons_per_row
column = index % buttons_per_row
grid_layout.addWidget(char_button, row, column)
self.scroll_layout.addLayout(grid_layout)
def show_character_details(self, character):
detail_window = CharacterDetailWindow(character, self.element_colors, self.paths_mapping)
self.detail_windows.append(detail_window)
detail_window.show()
def open_cmd(self):
os.system("start cmd")
def open_gold_ticket_simulator(self):
self.gold_window = GoldTicketWindow()
self.gold_window.show()
def open_silver_ticket_simulator(self):
self.silver_window = SilverTicketWindow()
self.silver_window.show()
def open_stellar_jade_website(self):
reply = QMessageBox.question(self, "即将打开第三方抽卡模拟网站",
"本网站和工具箱作者无关,是否确定要打开网站?",
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
webbrowser.open("https://hsr.wishsimulator.app")
def resizeEvent(self, event):
super().resizeEvent(event)
if self.current_data:
self.display_player_data(self.current_data)
class GoldTicketWindow(QWidget):
def init (self):
super().init ()
self.setWindowTitle("期望计算")
self.setGeometry(100, 100, 400, 300)
code Copy code
layout = QVBoxLayout()
self.role_count_input = QLineEdit(self)
self.role_count_input.setPlaceholderText("你想要多少限定角色?")
layout.addWidget(self.role_count_input)
self.weapon_count_input = QLineEdit(self)
self.weapon_count_input.setPlaceholderText("你想要多少限定光锥?")
layout.addWidget(self.weapon_count_input)
self.simulate_button = QPushButton("开始模拟", self)
self.simulate_button.clicked.connect(self.simulate)
layout.addWidget(self.simulate_button)
self.result_display = QTextEdit(self)
self.result_display.setPlaceholderText("模拟结果")
layout.addWidget(self.result_display)
self.setLayout(layout)
def simulate(self):
role_count = self.role_count_input.text().strip()
weapon_count = self.weapon_count_input.text().strip()
if not all(x.isdigit() for x in [role_count, weapon_count]):
QMessageBox.critical(self, "输入无效", "请确保所有输入都是有效数字。")
return
command = (f"expansions\\ratecalc.exe -average {role_count} {weapon_count} ")
try:
output = "期望抽数 " + subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True, text=True)
self.result_display.setPlainText(output)
except subprocess.CalledProcessError as e:
QMessageBox.critical(self, "调用失败", f"错误信息:\n{e.output}")
class SilverTicketWindow(QWidget):
def init (self):
super().init ()
self.setWindowTitle("概率计算")
self.setGeometry(100, 100, 400, 300)
code Copy code
layout = QVBoxLayout()
self.role_count_input = QLineEdit(self)
self.role_count_input.setPlaceholderText("你要抽多少限定角色?")
layout.addWidget(self.role_count_input)
self.weapon_count_input = QLineEdit(self)
self.weapon_count_input.setPlaceholderText("你要抽多少限定光锥?")
layout.addWidget(self.weapon_count_input)
self.items_input = QLineEdit(self)
self.items_input.setPlaceholderText("你还有多少抽?(需要折合你的星琼数)")
layout.addWidget(self.items_input)
self.initial_role_pulls_input = QLineEdit(self)
self.initial_role_pulls_input.setPlaceholderText("角色池已垫抽数")
layout.addWidget(self.initial_role_pulls_input)
self.initial_weapon_pulls_input = QLineEdit(self)
self.initial_weapon_pulls_input.setPlaceholderText("光锥池已垫抽数")
layout.addWidget(self.initial_weapon_pulls_input)
self.major_pity_role_input = QLineEdit(self)
self.major_pity_role_input.setPlaceholderText("角色池大保底 (1=是, 0=否)")
layout.addWidget(self.major_pity_role_input)
self.major_pity_weapon_input = QLineEdit(self)
self.major_pity_weapon_input.setPlaceholderText("武器池大保底 (1=是, 0=否)")
layout.addWidget(self.major_pity_weapon_input)
self.simulate_button = QPushButton("开始模拟", self)
self.simulate_button.clicked.connect(self.simulate)
layout.addWidget(self.simulate_button)
self.result_display = QTextEdit(self)
self.result_display.setPlaceholderText("模拟结果")
layout.addWidget(self.result_display)
self.setLayout(layout)
def simulate(self):
role_count = self.role_count_input.text().strip()
weapon_count = self.weapon_count_input.text().strip()
items = self.items_input.text().strip()
initial_role_pulls = self.initial_role_pulls_input.text().strip()
initial_weapon_pulls = self.initial_weapon_pulls_input.text().strip()
major_pity_role = self.major_pity_role_input.text().strip()
major_pity_weapon = self.major_pity_weapon_input.text().strip()
if (not all(x.isdigit() for x in [role_count, weapon_count, items,
initial_role_pulls, initial_weapon_pulls]) or
major_pity_role not in ["0", "1"] or major_pity_weapon not in ["0", "1"]):
QMessageBox.critical(self, "输入无效", "请确保所有输入都是有效数字。")
return
command = (f"expansions\\ratecalc.exe -simulate {role_count} {weapon_count} {items} "
f"{initial_role_pulls} {initial_weapon_pulls} {major_pity_role} {major_pity_weapon}")
try:
output = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True, text=True)
self.result_display.setPlainText(output)
except subprocess.CalledProcessError as e:
QMessageBox.critical(self, "调用失败", f"错误信息:\n{e.output}")
if name == "main ":
app = QApplication(sys.argv)
app.setWindowIcon(QIcon("image/gui/icon.ico"))
window = HSRToolApp()
window.show()
sys.exit(app.exec_())Traceback (most recent call last):
File "c:\Users\surface\Desktop\srtool\srtool.pyw", line 984, in
^^^^^^^^^^^^
File "c:\Users\surface\Desktop\srtool\srtool.pyw", line 495, in init
self.initUI()
File "c:\Users\surface\Desktop\srtool\srtool.pyw", line 596, in initUI
self.music_player_container = MusicPlayerContainer(self)
^^^^^^^^^^^^^^^^^^^^
NameError: name 'MusicPlayerContainer' is not defined
def display_player_data(self, characters):
self.clear_right_layout()
if self.current_player:
last_updated_time = self.load_software_data(self.current_player['uid'])
player_info = QLabel(f"<b style='font-size:48px;'>{self.current_player['nickname']}</b><br>"
f"<b style='font-size:26px; font-weight:bold;'>UID:</b> "
f"<b style='font-size:35px; font-weight:bold;'>{self.current_player['uid']}</b><br>"
f"<b style='font-size:26px; font-weight:bold;'>上次刷新时间:</b> "
f"<b style='font-size:26px; font-weight:bold;'>{last_updated_time}</b><br><br>")
self.scroll_layout.addWidget(player_info)
grid_layout = QGridLayout()
spacing = 20
grid_layout.setSpacing(spacing)
button_width = 280
image_width = 280
image_height = 384
available_width = self.scroll_area.width() - (spacing * 2)
buttons_per_row = max(1, available_width // (button_width + spacing))
for index, character in enumerate(characters):
char_button = QPushButton()
char_pixmap = QPixmap(f"image/avataricon/{character['id']}.png").scaled(image_width, image_height, Qt.KeepAspectRatio)
char_button.setIcon(QIcon(char_pixmap))
char_button.setIconSize(QSize(image_width, image_height))
char_button.setFixedSize(image_width, image_height)
element = character['element']['name']
border_color = self.element_colors.get(element, '#000000')
shadow = QGraphicsDropShadowEffect(self)
shadow.setBlurRadius(15)
shadow.setColor(QColor(border_color))
shadow.setOffset(0, 0)
char_button.setGraphicsEffect(shadow)
char_button.setStyleSheet(f"""
QPushButton {{
border: 5px solid {border_color};
border-radius: 15px;
background-color: transparent;
}}
QPushButton:hover {{
background-color: rgba(0, 0, 0, 0.1);
}}
""")
char_button.clicked.connect(lambda _, char=character: self.show_character_details(char))
row = index // buttons_per_row
column = index % buttons_per_row
grid_layout.addWidget(char_button, row, column)
self.scroll_layout.addLayout(grid_layout)
3. 确认背景和透明度设置 确保任何时候设置背景颜色或透明度的样式表,不要影响其子组件的可见性。
通过这些检查和修改,希望能帮助你解决角色列表和音乐播放器不显示的问题。如果仍然无法解决,建议检查控制台输出,查看有无错误信息提示进一步排查。
import sys
import os
import json
import requests
import pickle
import subprocess
from datetime import datetime
import webbrowser
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel,
QPushButton, QScrollArea, QFrame, QInputDialog,
QGridLayout, QGraphicsDropShadowEffect, QLineEdit,
QTextEdit, QMessageBox, QTextBrowser, QSlider, QFileDialog)
from PyQt5.QtGui import QFont, QIcon, QPixmap, QFontDatabase, QColor, QBrush, QPalette, QPainter, QFontMetrics
from PyQt5.QtCore import Qt, QSize, QPoint, QRect, QUrl
from PyQt5.QtMultimedia import QMediaPlayer, QMediaPlaylist
SAVE_DIR = "./saves/players"
CONFIG_DIR = "./config/software/"
ELEMENT_COLOR_FILE = os.path.join(CONFIG_DIR, "elementcolor.json")
PATHS_MAPPING_FILE = os.path.join(CONFIG_DIR, "pathsmapping.json")
def load_element_colors():
if not os.path.exists(ELEMENT_COLOR_FILE):
return {}
with open(ELEMENT_COLOR_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
def load_paths_mapping():
if not os.path.exists(PATHS_MAPPING_FILE):
return {}
with open(PATHS_MAPPING_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
class CharacterDetailWindow(QWidget):
def __init__(self, character, element_colors, paths_mapping):
super().__init__()
self.character = character
self.element_colors = element_colors
self.paths_mapping = paths_mapping
self.rarity_colors = self.load_rarity_colors()
self.affix_mapping = self.load_affix_mapping()
self.initUI()
def load_affix_mapping(self):
file_path = os.path.join("config", "software", "affixmapping.json")
if os.path.exists(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
return json.load(file)
return {}
def load_rarity_colors(self):
file_path = os.path.join("config", "software", "raritycoloring.json")
if os.path.exists(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
return json.load(file)
return {}
def get_gradient_style(self, rarity):
colors = self.rarity_colors
if str(rarity) in colors:
start = colors[str(rarity)]['start']
end = colors[str(rarity)]['end']
return f"background: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 {start}, stop:1 {end});"
return ""
def initUI(self):
self.setWindowTitle(f"{self.character['name']} - 详细信息")
self.showMaximized()
self.set_background()
main_layout = QVBoxLayout(self)
self.setLayout(main_layout)
main_layout.setContentsMargins(0, 0, 0, 0)
scroll_area = QScrollArea(self)
scroll_area.setWidgetResizable(True)
scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
main_layout.addWidget(scroll_area)
container = QWidget()
scroll_area.setWidget(container)
layout = QVBoxLayout(container)
layout.setContentsMargins(50, 50, 50, 50)
# 添加角色立绘
splashart_path = f"image/splashart/{self.character['id']}.png"
splashart_pixmap = QPixmap(splashart_path).scaled(768, 768, Qt.KeepAspectRatio, Qt.SmoothTransformation)
splashart_label = QLabel(container)
splashart_label.setPixmap(splashart_pixmap)
layout.addWidget(splashart_label, alignment=Qt.AlignLeft | Qt.AlignTop)
path_name = self.character['path']['name'].lower()
path_icon_key = self.paths_mapping.get(path_name, None)
if path_icon_key:
path_icon_path = f"image/path/{path_icon_key}.png"
path_pixmap = QPixmap(path_icon_path).scaled(128, 128, Qt.KeepAspectRatio, Qt.SmoothTransformation)
path_icon_label = QLabel(splashart_label)
path_icon_label.setPixmap(path_pixmap)
path_icon_label.move(10, 10)
# 整个光锥和信息的表格
light_cone_frame = LightConeFrame(self.character, self.affix_mapping, container)
light_cone_frame.setFixedSize(896, 576)
layout.addWidget(light_cone_frame, alignment=Qt.AlignTop)
light_cone_layout = QVBoxLayout(light_cone_frame)
light_cone_layout.setContentsMargins(0, 0, 0, 0)
# 上部信息部分
top_section = QWidget(light_cone_frame)
top_section.setFixedHeight(192)
top_layout = QHBoxLayout(top_section)
top_layout.setContentsMargins(0, 0, 0, 0)
# 左侧光锥图片和渐变背景
light_cone = self.character.get('light_cone')
if light_cone:
rarity = light_cone['rarity']
cone_id = light_cone['id']
gradient_style = self.get_gradient_style(rarity)
cone_name = light_cone['name']
cone_level = light_cone['level']
cone_rank = light_cone['rank']
else:
rarity = 0
cone_id = 'unequip'
gradient_style = "background-color: #444444;"
cone_name = "未佩戴光锥"
cone_level = "N/A"
cone_rank = "N/A"
gradient_section = QWidget(top_section)
gradient_section.setFixedSize(192, 192)
gradient_section.setStyleSheet(gradient_style + "border-top-left-radius: 15px;")
# 在渐变背景中居中显示光锥图
gradient_layout = QVBoxLayout(gradient_section)
gradient_layout.setContentsMargins(0, 0, 0, 0)
lightcone_pixmap = QPixmap(f"image/lightcone/{cone_id}.png").scaled(180, 180, Qt.KeepAspectRatio, Qt.SmoothTransformation)
lightcone_label = QLabel()
lightcone_label.setPixmap(lightcone_pixmap)
lightcone_label.setAlignment(Qt.AlignCenter)
gradient_layout.addWidget(lightcone_label)
top_layout.addWidget(gradient_section)
# 右侧信息区域
right_section = QWidget(top_section)
right_layout = QVBoxLayout(right_section)
right_layout.setContentsMargins(0, 0, 0, 0)
# 光锥名称
colors = self.rarity_colors.get(str(rarity), {})
end_color = colors.get("end", "#ffffff")
name_label = QLabel(cone_name, right_section)
name_label.setFixedHeight(72)
name_label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
name_label.setStyleSheet(f"color: {end_color}; font-size: 36px; font-weight: bold; padding: 0px 2px;")
right_layout.addWidget(name_label)
# 第二行: 光锥命途图标、等级、叠影数量
second_row = QWidget(right_section)
second_row.setFixedHeight(64)
second_row_layout = QHBoxLayout(second_row)
second_row_layout.setContentsMargins(0, 0, 0, 0)
# 设置布局的对齐方式为左对齐
second_row_layout.setAlignment(Qt.AlignLeft)
path_icon_label = QLabel(second_row)
path_icon_label.setPixmap(QPixmap(path_icon_path).scaled(64, 64, Qt.KeepAspectRatio))
path_icon_label.setFixedSize(64, 64)
second_row_layout.addWidget(path_icon_label)
level_label = QLabel(f"等级 {cone_level}", second_row)
level_label.setFixedSize(128, 64)
level_label.setAlignment(Qt.AlignCenter)
level_label.setStyleSheet("color: white; font-size: 32px; font-weight: bold;")
second_row_layout.addWidget(level_label)
rank_roman = ["Ⅰ", "Ⅱ", "Ⅲ", "Ⅳ", "Ⅴ"]
rank_label = QLabel(rank_roman[int(cone_rank) - 1] if cone_rank != "N/A" else "N/A", second_row)
rank_label.setFixedSize(64, 64)
rank_label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
rank_label.setStyleSheet("color: white; font-size: 32px; font-weight: bold;")
second_row_layout.addWidget(rank_label)
right_layout.addWidget(second_row)
# 稀有度一行
font_id = QFontDatabase.addApplicationFont("fonts/hsr-icon.ttf")
font_family = QFontDatabase.applicationFontFamilies(font_id)[0]
star_label = QLabel("b" * rarity, right_section)
star_label.setFixedHeight(66)
star_label.setAlignment(Qt.AlignLeft)
custom_font = QFont(font_family, 16)
star_label.setFont(custom_font)
star_label.setStyleSheet(
f"color: {end_color}; font-weight: bold; "
f"margin: 0px 0px 0px 0px;"
)
right_layout.addWidget(star_label)
top_layout.addWidget(right_section)
light_cone_layout.addWidget(top_section)
# 下方滚动区域
bottom_section = QScrollArea(light_cone_frame)
bottom_section.setMinimumHeight(384)
bottom_section.setWidgetResizable(True)
bottom_section.setStyleSheet("background-color: transparent; border: none;")
bottom_section.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
bottom_section.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
bottom_content = QWidget()
bottom_layout = QVBoxLayout(bottom_content)
if light_cone:
lightcone_data = self.load_lightcone_data(cone_id)
if lightcone_data:
description_browser = QTextBrowser(bottom_content)
description_browser.setStyleSheet("background-color: transparent; color: white; font-weight: bold;")
self.populate_lightcone_description(description_browser, lightcone_data)
bottom_layout.addWidget(description_browser)
else:
description_browser = QTextBrowser(bottom_content)
description_browser.setStyleSheet("color: white; font-weight: bold;")
description_browser.append("未佩戴光锥")
bottom_layout.addWidget(description_browser)
bottom_section.setWidget(bottom_content)
light_cone_layout.addWidget(bottom_section)
def load_lightcone_data(self, lightcone_id):
file_path = os.path.join("config", "lightcone", f"{lightcone_id}.json")
if os.path.exists(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
return json.load(file)
return None
def populate_lightcone_description(self, text_browser, data):
rarity = self.character['light_cone']['rank']
skill_description = data.get("combined_skill_description", "").replace("\n", "<br>")
light_cone_description = data.get("light_cone_description", "").replace("\n", "<br>")
text_browser.clear()
# Skill name and rarity level line
skill_name = data.get("skill_name", "")
text_browser.append(f"{skill_name} - 等级 {rarity}")
# Skill description with highlighting
skill_text = ""
start_marker = '[['
end_marker = ']]'
start = skill_description.find(start_marker)
while start != -1:
end = skill_description.find(end_marker, start)
if end != -1:
actual_start = start + len(start_marker)
actual_end = end
skill_text += skill_description[:start]
# Highlight the number according to rarity
numbers_str = skill_description[actual_start:actual_end].split(',')
if 1 <= rarity <= len(numbers_str):
number_to_highlight = numbers_str[rarity - 1].strip()
skill_text += f"<span style='color:orange;'>{number_to_highlight}</span>"
skill_description = skill_description[end + len(end_marker):]
start = skill_description.find(start_marker)
else:
break
skill_text += skill_description
text_browser.append(skill_text)
# 添加空行
text_browser.append("<br>")
# Light cone description in gray
text_browser.append(f"<div style='color:grey;'>{light_cone_description}</div>")
def set_background(self):
palette = self.palette()
background_pixmap = QPixmap("image/gui/background.jpeg").scaled(self.size(), Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
palette.setBrush(QPalette.Window, QBrush(background_pixmap))
self.setPalette(palette)
def resizeEvent(self, event):
self.set_background()
super().resizeEvent(event)
class LightConeFrame(QWidget):
def __init__(self, character, affix_mapping, parent=None, bg_color="#262634"):
super().__init__(parent)
self.bg_color = bg_color
self.character = character
self.affix_mapping = affix_mapping
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
rect = self.rect()
# 填充背景色
painter.fillRect(rect, QColor(self.bg_color))
# 绘制右侧分割线
pen = painter.pen()
pen.setWidth(2)
pen.setColor(QColor('#444444'))
painter.setPen(pen)
# 计算分割线的起始和终止点位置
x_position = rect.width() - 320
y_end = 192
painter.drawLine(x_position, 0, x_position, y_end)
# 绘制表格框线
pen.setWidth(5)
pen.setColor(QColor('#444444'))
painter.setPen(pen)
painter.drawRoundedRect(rect.adjusted(1, 1, -1, -1), 30, 30)
# 绘制水平分割线
horizontal_line_y_position = 192
painter.drawLine(0, horizontal_line_y_position, rect.width(), horizontal_line_y_position)
# 在这里添加检测光锥是否存在并绘制属性图标、名称及数值
light_cone = self.character.get('light_cone')
attributes = light_cone.get('attributes', []) if light_cone else []
for idx, attribute in enumerate(attributes):
attr_name = attribute['name']
attr_value = float(attribute['value'])
attr_display = f"{attr_value:.3f}"
icon_file = self.affix_mapping.get(attr_name, None)
if icon_file:
icon_path = f"image/buffdata/{icon_file}.png"
if os.path.exists(icon_path):
icon_pixmap = QPixmap(icon_path).scaled(64, 64, Qt.KeepAspectRatio, Qt.SmoothTransformation)
# 下调图标1px
icon_y = (idx * 64) - 4 + 1
# 绘制图标:与框线对齐
painter.drawPixmap(x_position + 10, icon_y, icon_pixmap)
# 设置淡灰色
light_gray = QColor(169, 169, 169)
painter.setPen(light_gray)
# 绘制属性名称,向下移动1像素
font = painter.font()
font.setBold(True)
font.setPointSize(10)
painter.setFont(font)
# 设置属性名称的位置(向下移动1像素)
name_x = x_position + 80
name_y = (idx * 64) + (64 + self.fontMetrics().height()) // 2 + 1
attr_abbr = self.affix_mapping.get(attr_name, attr_name)
painter.drawText(QRect(name_x, (idx * 64) + 1, 150, 64), Qt.AlignVCenter | Qt.AlignLeft, attr_abbr)
# 计算数字的宽度并调整位置
font.setBold(True)
font.setPointSize(11)
painter.setFont(font)
int_width = self.fontMetrics().width(str(int(attr_value)))
# 设置小数部分的颜色和字体
darker_gray = QColor(105, 105, 105)
decimal_font = QFont(font)
decimal_font.setPointSize(8)
decimal_width = QFontMetrics(decimal_font).width(f".{attr_display.split('.')[1]}")
total_width = int_width + decimal_width
text_x = rect.width() - total_width - 19
# 将所有数字上移6像素
int_y = icon_y + (64 + self.fontMetrics().height()) // 2 - 6
# 绘制整数部分,右移一些
offset = 2
painter.drawText(QPoint(text_x + offset, int_y), str(int(attr_value)))
# 绘制小数部分
painter.setFont(decimal_font)
painter.setPen(darker_gray)
painter.drawText(QPoint(text_x + int_width + offset, int_y), f".{attr_display.split('.')[1]}")
super().paintEvent(event)
class MusicPlayerWidget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("音乐播放器")
# 创建播放器和播放列表
self.player = QMediaPlayer(self)
self.playlist = QMediaPlaylist(self)
self.player.setPlaylist(self.playlist)
# 设置UI布局
layout = QVBoxLayout(self)
# 显示音乐名称的标签
self.song_label = QLabel("选择一首乐曲", self)
self.song_label.setStyleSheet("color: black; font-size: 18px; font-weight: bold;")
self.song_label.setAlignment(Qt.AlignCenter)
layout.addWidget(self.song_label)
# 播放进度条
self.progress_slider = QSlider(Qt.Horizontal, self)
self.progress_slider.setStyleSheet(
"QSlider::groove:horizontal {background: #d3d3d3;} QSlider::handle:horizontal {background: lightblue;}")
layout.addWidget(self.progress_slider)
# 添加按钮布局
buttonLayout = QHBoxLayout() # 改为水平布局
self.play_button = QPushButton("▶", self)
self.play_button.setStyleSheet("background-color: transparent; color: black; font-size: 24px; font-weight: bold;")
self.play_button.clicked.connect(self.toggle_play)
buttonLayout.addWidget(self.play_button)
self.browse_button = QPushButton("选择音乐文件", self)
self.browse_button.setStyleSheet("background-color: transparent; color: black; font-weight: bold;")
self.browse_button.clicked.connect(self.browse_files)
buttonLayout.addWidget(self.browse_button)
layout.addLayout(buttonLayout)
# 添加背景
self.setAttribute(Qt.WA_StyledBackground, True)
self.setStyleSheet("background-color: rgba(211, 211, 211, 0.7); border-radius: 15px;")
# 连接信号和槽
self.player.durationChanged.connect(self.update_duration)
self.player.positionChanged.connect(self.update_position)
self.progress_slider.sliderMoved.connect(self.set_position)
def toggle_play(self):
if self.player.state() == QMediaPlayer.PlayingState:
self.player.pause()
self.play_button.setText("▶")
else:
self.player.play()
self.play_button.setText("⏸")
def browse_files(self):
file_name, _ = QFileDialog.getOpenFileName(self, "选择音乐文件", "./music", "Music Files (*.mp3 *.ogg *.wav *.flac *.mid)")
if file_name:
self.playlist.clear()
self.playlist.addMedia(QUrl.fromLocalFile(file_name))
self.song_label.setText(file_name.split("/")[-1])
self.player.play()
self.play_button.setText("⏸")
def update_duration(self, duration):
self.progress_slider.setRange(0, duration)
def update_position(self, position):
if not self.progress_slider.isSliderDown():
self.progress_slider.setValue(position)
def set_position(self, position):
self.player.setPosition(position)
class MusicPlayerContainer(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
# 设置布局
layout = QVBoxLayout(self)
layout.setContentsMargins(10, 10, 10, 10) # 控制边距
# 添加音乐播放器
self.music_player_widget = MusicPlayerWidget(self)
layout.addWidget(self.music_player_widget)
# 设置背景样式
self.setAttribute(Qt.WA_StyledBackground, True)
self.setStyleSheet("background-color: rgba(211, 211, 211, 0.7); border-radius: 15px;")
class HSRToolApp(QWidget):
def __init__(self):
super().__init__()
self.current_data = None
self.current_player = None
self.element_colors = load_element_colors()
self.paths_mapping = load_paths_mapping()
self.detail_windows = []
self.initUI()
def initUI(self):
self.setWindowTitle("HSR Toolkit")
self.setWindowIcon(QIcon("image/gui/icon.ico"))
self.setGeometry(0, 0, 800, 600)
self.showMaximized()
layout = QHBoxLayout(self)
self.left_frame = QFrame()
self.left_layout = QVBoxLayout()
self.left_layout.setAlignment(Qt.AlignTop)
self.add_player_button = QPushButton("添加玩家数据")
self.add_player_button.setIcon(QIcon("image/gui/add.svg"))
self.add_player_button.setIconSize(QSize(24, 24))
self.add_player_button.setFixedWidth(600)
self.add_player_button.setStyleSheet("""
QPushButton {
border: 2px solid black;
border-radius: 10px;
color: gray;
background-color: white;
padding: 8px;
font-weight: bold;
}
QPushButton:hover {
background-color: lightblue;
color: black;
}
""")
self.add_player_button.setToolTip("点击添加玩家数据")
self.add_player_button.clicked.connect(self.prompt_for_uid)
self.left_layout.addWidget(self.add_player_button, alignment=Qt.AlignTop)
self.player_buttons_frame = QVBoxLayout()
self.player_buttons_frame.setAlignment(Qt.AlignTop)
self.left_layout.addLayout(self.player_buttons_frame)
self.cmd_button = QPushButton()
self.gold_ticket_button = QPushButton()
self.silver_ticket_button = QPushButton()
cmd_pixmap = QPixmap("image/gui/cmd.png").scaled(80, 80, Qt.KeepAspectRatio)
gold_ticket_pixmap = QPixmap("image/gui/GoldTicket.png").scaled(80, 80, Qt.KeepAspectRatio)
silver_ticket_pixmap = QPixmap("image/gui/SilverTicket.png").scaled(80, 80, Qt.KeepAspectRatio)
self.cmd_button.setIcon(QIcon(cmd_pixmap))
self.cmd_button.setIconSize(cmd_pixmap.size())
self.cmd_button.setFixedSize(80, 80)
self.gold_ticket_button.setIcon(QIcon(gold_ticket_pixmap))
self.gold_ticket_button.setIconSize(gold_ticket_pixmap.size())
self.gold_ticket_button.setFixedSize(80, 80)
self.silver_ticket_button.setIcon(QIcon(silver_ticket_pixmap))
self.silver_ticket_button.setIconSize(silver_ticket_pixmap.size())
self.silver_ticket_button.setFixedSize(80, 80)
self.cmd_button.clicked.connect(self.open_cmd)
self.gold_ticket_button.clicked.connect(self.open_gold_ticket_simulator)
self.silver_ticket_button.clicked.connect(self.open_silver_ticket_simulator)
bottom_layout = QHBoxLayout()
bottom_layout.addWidget(self.cmd_button)
bottom_layout.addWidget(self.gold_ticket_button)
bottom_layout.addWidget(self.silver_ticket_button)
self.stellar_jade_button = QPushButton()
stellar_jade_pixmap = QPixmap("image/gui/stellarjade.png").scaled(80, 80, Qt.KeepAspectRatio)
self.stellar_jade_button.setIcon(QIcon(stellar_jade_pixmap))
self.stellar_jade_button.setIconSize(stellar_jade_pixmap.size())
self.stellar_jade_button.setFixedSize(80, 80)
self.stellar_jade_button.clicked.connect(self.open_stellar_jade_website)
bottom_layout.addWidget(self.stellar_jade_button)
self.left_layout.addStretch()
self.left_layout.addLayout(bottom_layout)
self.left_frame.setLayout(self.left_layout)
layout.addWidget(self.left_frame, stretch=22)
self.right_frame = QFrame()
self.right_layout = QVBoxLayout()
self.right_layout.setAlignment(Qt.AlignTop)
self.scroll_area = QScrollArea()
self.scroll_area.setWidgetResizable(True)
self.scroll_widget = QWidget()
self.scroll_layout = QVBoxLayout(self.scroll_widget)
self.scroll_layout.setAlignment(Qt.AlignTop)
self.scroll_area.setWidget(self.scroll_widget)
self.right_layout.addWidget(self.scroll_area)
# 添加音乐播放器容器
self.music_player_container = MusicPlayerContainer(self)
self.right_layout.addWidget(self.music_player_container)
self.right_frame.setLayout(self.right_layout)
layout.addWidget(self.right_frame, stretch=78)
self.setLayout(layout)
font_path = "fonts/SDK_SC_Web65.ttf"
if os.path.exists(font_path):
font_id = QFontDatabase.addApplicationFont(font_path)
font_family = QFontDatabase.applicationFontFamilies(font_id)[0]
QApplication.setFont(QFont(font_family))
self.load_player_list()
def load_player_list(self):
for i in reversed(range(self.player_buttons_frame.count())):
widget = self.player_buttons_frame.itemAt(i).widget()
if widget is not None:
widget.deleteLater()
if os.path.exists(SAVE_DIR):
for uid in os.listdir(SAVE_DIR):
player_dir = os.path.join(SAVE_DIR, uid)
if os.path.isdir(player_dir):
with open(os.path.join(player_dir, "player_data.json"), 'r', encoding='utf-8') as f:
data = json.load(f)
player_name = data['player']['nickname']
player_level = data['player']['level']
player_widget = QFrame()
player_layout = QHBoxLayout(player_widget)
player_button = QPushButton(f"{player_name} Lv.{player_level}")
player_button.setFixedWidth(350)
player_button.setFixedHeight(80)
player_button.setStyleSheet("""
QPushButton {
border: 1px solid black;
border-radius: 10px;
padding: 8px;
background-color: white;
font-weight: bold;
}
QPushButton:hover {
background-color: lightgray;
}
""")
view_icon = QIcon("image/gui/open.png")
player_button.setIcon(view_icon)
player_button.setIconSize(QSize(40, 40))
player_button.clicked.connect(lambda _, uid=uid: self.load_player_data(uid))
refresh_button = QPushButton()
refresh_button.setIcon(QIcon("image/gui/update.png"))
refresh_button.setIconSize(QSize(40, 40))
refresh_button.setFixedSize(60, 60)
refresh_button.setContentsMargins(5, 0, 5, 0)
refresh_button.clicked.connect(lambda _, uid=uid: self.refresh_player_data(uid))
refresh_button.setStyleSheet("""
QPushButton {
border: none;
background-color: transparent;
padding: 0px;
}
QPushButton:hover {
background-color: rgba(0, 0, 255, 0.3);
}
""")
delete_button = QPushButton()
delete_button.setIcon(QIcon("image/gui/delete.png"))
delete_button.setIconSize(QSize(40, 40))
delete_button.setFixedSize(60, 60)
delete_button.setContentsMargins(5, 0, 5, 0)
delete_button.setStyleSheet("""
QPushButton {
border: none;
background-color: transparent;
padding: 0px;
}
QPushButton:hover {
background-color: rgba(255, 0, 0, 0.3);
}
""")
delete_button.clicked.connect(lambda _, uid=uid: self.delete_player_data(uid))
player_layout.addWidget(player_button)
player_layout.addWidget(refresh_button)
player_layout.addWidget(delete_button)
self.player_buttons_frame.addWidget(player_widget)
def load_player_data(self, uid):
player_dir = os.path.join(SAVE_DIR, uid)
if os.path.exists(player_dir):
self.current_data = []
for file_name in os.listdir(player_dir):
if file_name.endswith('.pkl'):
with open(os.path.join(player_dir, file_name), 'rb') as f:
character_data = pickle.load(f)
self.current_data.append(character_data)
with open(os.path.join(player_dir, "player_data.json"), 'r', encoding='utf-8') as f:
self.current_player = json.load(f)['player']
self.display_player_data(self.current_data)
def refresh_player_data(self, uid):
self.fetch_data(uid)
self.load_player_data(uid)
def clear_right_layout(self):
while self.scroll_layout.count():
item = self.scroll_layout.takeAt(0)
widget = item.widget()
if widget:
widget.deleteLater()
else:
sub_layout = item.layout()
if sub_layout:
while sub_layout.count():
sub_item = sub_layout.takeAt(0)
sub_widget = sub_item.widget()
if sub_widget:
sub_widget.deleteLater()
sub_layout.deleteLater()
def delete_player_data(self, uid):
player_dir = os.path.join(SAVE_DIR, uid)
if os.path.exists(player_dir):
import shutil
shutil.rmtree(player_dir)
self.load_player_list()
def prompt_for_uid(self):
uid, ok = QInputDialog.getText(self, "输入 UID", "请输入玩家 UID:")
if ok and uid:
self.fetch_data(uid.strip())
def fetch_data(self, uid):
if len(uid) != 9 or not uid.isdigit() or uid.startswith('0'):
QMessageBox.critical(self, "Invalid UID", "<b>UID必须是9位数字且不能以 '0' 开头。请重试。</b>")
return
url = f"https://api.mihomo.me/sr_info_parsed/{uid}?lang=cn"
try:
response = requests.get(url)
response.raise_for_status()
data = response.json()
self.save_data(uid, data)
self.load_player_list()
except requests.RequestException:
QMessageBox.critical(self, "Fetch Failed", "<b>无法获取数据,请检查UID或网络连接。</b>")
def save_data(self, uid, data):
player_dir = os.path.join(SAVE_DIR, uid)
os.makedirs(player_dir, exist_ok=True)
for character in data['characters']:
char_file_path = os.path.join(player_dir, f"{character['id']}.pkl")
with open(char_file_path, 'wb') as f:
pickle.dump(character, f)
with open(os.path.join(player_dir, "player_data.json"), 'w', encoding='utf-8') as f:
json.dump(data, f)
software_data = {
"last_updated": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
software_file_path = os.path.join(player_dir, "software.json")
with open(software_file_path, "w", encoding='utf-8') as f:
json.dump(software_data, f)
def load_software_data(self, uid):
software_file_path = os.path.join(SAVE_DIR, uid, "software.json")
if os.path.exists(software_file_path):
with open(software_file_path, 'r', encoding='utf-8') as f:
software_data = json.load(f)
return software_data.get('last_updated', '未更新')
return '未更新'
def display_player_data(self, characters):
self.clear_right_layout()
if self.current_player:
last_updated_time = self.load_software_data(self.current_player['uid'])
player_info = QLabel(f"<b style='font-size:48px;'>{self.current_player['nickname']}</b><br>"
f"<b style='font-size:26px; font-weight:bold;'>UID:</b> "
f"<b style='font-size:35px; font-weight:bold;'>{self.current_player['uid']}</b><br>"
f"<b style='font-size:26px; font-weight:bold;'>上次刷新时间:</b> "
f"<b style='font-size:26px; font-weight:bold;'>{last_updated_time}</b><br><br>")
self.scroll_layout.addWidget(player_info)
grid_layout = QGridLayout()
spacing = 20
grid_layout.setSpacing(spacing)
button_width = 280
image_width = 280
image_height = 384
available_width = self.scroll_area.width() - (spacing * 2)
buttons_per_row = max(1, available_width // (button_width + spacing))
for index, character in enumerate(characters):
char_button = QPushButton()
char_pixmap = QPixmap(f"image/avataricon/{character['id']}.png").scaled(image_width, image_height, Qt.KeepAspectRatio)
char_button.setIcon(QIcon(char_pixmap))
char_button.setIconSize(QSize(image_width, image_height))
char_button.setFixedSize(image_width, image_height)
element = character['element']['name']
border_color = self.element_colors.get(element, '#000000')
shadow = QGraphicsDropShadowEffect(self)
shadow.setBlurRadius(15)
shadow.setColor(QColor(border_color))
shadow.setOffset(0, 0)
char_button.setGraphicsEffect(shadow)
char_button.setStyleSheet(f"""
QPushButton {{
border: 5px solid {border_color};
border-radius: 15px;
background-color: transparent;
}}
QPushButton:hover {{
background-color: rgba(0, 0, 0, 0.1);
}}
""")
char_button.clicked.connect(lambda _, char=character: self.show_character_details(char))
row = index // buttons_per_row
column = index % buttons_per_row
grid_layout.addWidget(char_button, row, column)
self.scroll_layout.addLayout(grid_layout)
def show_character_details(self, character):
detail_window = CharacterDetailWindow(character, self.element_colors, self.paths_mapping)
self.detail_windows.append(detail_window)
detail_window.show()
def open_cmd(self):
os.system("start cmd")
def open_gold_ticket_simulator(self):
self.gold_window = GoldTicketWindow()
self.gold_window.show()
def open_silver_ticket_simulator(self):
self.silver_window = SilverTicketWindow()
self.silver_window.show()
def open_stellar_jade_website(self):
reply = QMessageBox.question(self, "即将打开第三方抽卡模拟网站",
"本网站和工具箱作者无关,是否确定要打开网站?",
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
webbrowser.open("https://hsr.wishsimulator.app")
def resizeEvent(self, event):
super().resizeEvent(event)
if self.current_data:
self.display_player_data(self.current_data)
class GoldTicketWindow(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("期望计算")
self.setGeometry(100, 100, 400, 300)
layout = QVBoxLayout()
self.role_count_input = QLineEdit(self)
self.role_count_input.setPlaceholderText("你想要多少限定角色?")
layout.addWidget(self.role_count_input)
self.weapon_count_input = QLineEdit(self)
self.weapon_count_input.setPlaceholderText("你想要多少限定光锥?")
layout.addWidget(self.weapon_count_input)
self.simulate_button = QPushButton("开始模拟", self)
self.simulate_button.clicked.connect(self.simulate)
layout.addWidget(self.simulate_button)
self.result_display = QTextEdit(self)
self.result_display.setPlaceholderText("模拟结果")
layout.addWidget(self.result_display)
self.setLayout(layout)
def simulate(self):
role_count = self.role_count_input.text().strip()
weapon_count = self.weapon_count_input.text().strip()
if not all(x.isdigit() for x in [role_count, weapon_count]):
QMessageBox.critical(self, "输入无效", "请确保所有输入都是有效数字。")
return
command = (f"expansions\\ratecalc.exe -average {role_count} {weapon_count} ")
try:
output = "期望抽数 " + subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True, text=True)
self.result_display.setPlainText(output)
except subprocess.CalledProcessError as e:
QMessageBox.critical(self, "调用失败", f"错误信息:\n{e.output}")
class SilverTicketWindow(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("概率计算")
self.setGeometry(100, 100, 400, 300)
layout = QVBoxLayout()
self.role_count_input = QLineEdit(self)
self.role_count_input.setPlaceholderText("你要抽多少限定角色?")
layout.addWidget(self.role_count_input)
self.weapon_count_input = QLineEdit(self)
self.weapon_count_input.setPlaceholderText("你要抽多少限定光锥?")
layout.addWidget(self.weapon_count_input)
self.items_input = QLineEdit(self)
self.items_input.setPlaceholderText("你还有多少抽?(需要折合你的星琼数)")
layout.addWidget(self.items_input)
self.initial_role_pulls_input = QLineEdit(self)
self.initial_role_pulls_input.setPlaceholderText("角色池已垫抽数")
layout.addWidget(self.initial_role_pulls_input)
self.initial_weapon_pulls_input = QLineEdit(self)
self.initial_weapon_pulls_input.setPlaceholderText("光锥池已垫抽数")
layout.addWidget(self.initial_weapon_pulls_input)
self.major_pity_role_input = QLineEdit(self)
self.major_pity_role_input.setPlaceholderText("角色池大保底 (1=是, 0=否)")
layout.addWidget(self.major_pity_role_input)
self.major_pity_weapon_input = QLineEdit(self)
self.major_pity_weapon_input.setPlaceholderText("武器池大保底 (1=是, 0=否)")
layout.addWidget(self.major_pity_weapon_input)
self.simulate_button = QPushButton("开始模拟", self)
self.simulate_button.clicked.connect(self.simulate)
layout.addWidget(self.simulate_button)
self.result_display = QTextEdit(self)
self.result_display.setPlaceholderText("模拟结果")
layout.addWidget(self.result_display)
self.setLayout(layout)
def simulate(self):
role_count = self.role_count_input.text().strip()
weapon_count = self.weapon_count_input.text().strip()
items = self.items_input.text().strip()
initial_role_pulls = self.initial_role_pulls_input.text().strip()
initial_weapon_pulls = self.initial_weapon_pulls_input.text().strip()
major_pity_role = self.major_pity_role_input.text().strip()
major_pity_weapon = self.major_pity_weapon_input.text().strip()
if (not all(x.isdigit() for x in [role_count, weapon_count, items,
initial_role_pulls, initial_weapon_pulls]) or
major_pity_role not in ["0", "1"] or major_pity_weapon not in ["0", "1"]):
QMessageBox.critical(self, "输入无效", "请确保所有输入都是有效数字。")
return
command = (f"expansions\\ratecalc.exe -simulate {role_count} {weapon_count} {items} "
f"{initial_role_pulls} {initial_weapon_pulls} {major_pity_role} {major_pity_weapon}")
try:
output = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True, text=True)
self.result_display.setPlainText(output)
except subprocess.CalledProcessError as e:
QMessageBox.critical(self, "调用失败", f"错误信息:\n{e.output}")
if __name__ == "__main__":
app = QApplication(sys.argv)
app.setWindowIcon(QIcon("image/gui/icon.ico"))
window = HSRToolApp()
window.show()
sys.exit(app.exec_())
关键点:
确保所有类的定义都在使用之前。
MusicPlayerContainer 作为独立组件,包含 MusicPlayerWidget。
在 HSRToolApp 的 initUI() 中,正确设置布局。
确保所有资源路径、字体路径有效。
粘贴代码时请注意缩进和路径的正确性以保证程序正常执行。
class MusicPlayerWidget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("音乐播放器")
# 创建播放器和播放列表
self.player = QMediaPlayer(self)
self.playlist = QMediaPlaylist(self)
self.player.setPlaylist(self.playlist)
self.load_music_files()
# 设置UI布局
layout = QVBoxLayout(self)
# 顶部显示音乐名称的标签
self.song_label = QLabel("选择一首乐曲", self)
self.song_label.setStyleSheet("color: black; font-size: 18px; font-weight: bold;")
self.song_label.setAlignment(Qt.AlignCenter)
layout.addWidget(self.song_label)
# 添加播放进度条
self.progress_slider = QSlider(Qt.Horizontal, self)
self.progress_slider.setStyleSheet(
"QSlider::groove:horizontal {background: #d3d3d3;} QSlider::handle:horizontal {background: lightblue;}")
self.progress_slider.sliderMoved.connect(self.set_position)
layout.addWidget(self.progress_slider)
# 添加按钮布局
buttonLayout = QHBoxLayout()
self.previous_button = QPushButton("⏮", self)
self.previous_button.setStyleSheet("background-color: transparent; color: black; font-size: 24px; font-weight: bold;")
self.previous_button.clicked.connect(self.previous_song)
buttonLayout.addWidget(self.previous_button)
self.play_button = QPushButton("▶", self)
self.play_button.setStyleSheet("background-color: transparent; color: black; font-size: 24px; font-weight: bold;")
self.play_button.clicked.connect(self.toggle_play)
buttonLayout.addWidget(self.play_button)
self.next_button = QPushButton("⏭", self)
self.next_button.setStyleSheet("background-color: transparent; color: black; font-size: 24px; font-weight: bold;")
self.next_button.clicked.connect(self.next_song)
buttonLayout.addWidget(self.next_button)
layout.addLayout(buttonLayout)
# 添加背景
self.setAttribute(Qt.WA_StyledBackground, True)
self.setStyleSheet("background-color: rgba(211, 211, 211, 0.7); border-radius: 15px;")
# 连接信号和槽
self.player.durationChanged.connect(self.update_duration)
self.player.positionChanged.connect(self.update_position)
def load_music_files(self):
music_directory = './music'
if not os.path.exists(music_directory):
os.makedirs(music_directory)
for file_name in os.listdir(music_directory):
if file_name.endswith(('.mp3', '.ogg', '.wav', '.flac', '.mid')):
file_path = os.path.join(music_directory, file_name)
media_content = QMediaContent(QUrl.fromLocalFile(file_path))
self.playlist.addMedia(media_content)
self.playlist.setCurrentIndex(0) # 设置当前播放为第一首
def toggle_play(self):
if self.player.state() == QMediaPlayer.PlayingState:
self.player.pause()
self.play_button.setText("▶")
else:
self.player.play()
self.play_button.setText("⏸")
def next_song(self):
self.playlist.next()
def previous_song(self):
self.playlist.previous()
def update_duration(self, duration):
self.progress_slider.setRange(0, duration)
def update_position(self, position):
if not self.progress_slider.isSliderDown():
self.progress_slider.setValue(position)
index = self.playlist.currentIndex()
if index >= 0:
current_media = self.playlist.media(index)
current_url = current_media.canonicalUrl().toLocalFile()
song_name = os.path.basename(current_url)
self.song_label.setText(song_name)
def set_position(self, position):
self.player.setPosition(position)
主要改动:
自动加载音乐文件: 使用 load_music_files(self) 方法自动读取 ./music 目录下的所有音乐文件。
添加控制按钮: 在按钮布局中添加了“上一首”和“下一首”按钮,并与播放列表的 next() 和 previous() 方法绑定。
更新标签: 音乐文件变化时更新标签,以显示当前正在播放的歌曲名称。
这些更改使播放器具有读取目录、简单播放列表控制,以及更现代化的 UI 控制所需的元素。
class MusicPlayerWidget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("音乐播放器")
# 创建播放器和播放列表
self.player = QMediaPlayer(self)
self.playlist = QMediaPlaylist(self)
self.player.setPlaylist(self.playlist)
self.load_music_files()
# 设置UI布局
layout = QVBoxLayout(self)
# 顶部显示音乐名称的标签
self.song_label = QLabel("选择一首乐曲", self)
self.song_label.setStyleSheet("color: black; font-size: 18px; font-weight: bold;")
self.song_label.setAlignment(Qt.AlignCenter)
layout.addWidget(self.song_label)
# 添加进度条和控制按钮布局
controls_layout = QHBoxLayout()
self.previous_button = QPushButton("⏮", self)
self.previous_button.setStyleSheet("background-color: transparent; color: black; font-size: 24px; font-weight: bold;")
self.previous_button.clicked.connect(self.previous_song)
controls_layout.addWidget(self.previous_button)
self.play_button = QPushButton("▶", self)
self.play_button.setStyleSheet("background-color: transparent; color: black; font-size: 24px; font-weight: bold;")
self.play_button.clicked.connect(self.toggle_play)
controls_layout.addWidget(self.play_button)
self.next_button = QPushButton("⏭", self)
self.next_button.setStyleSheet("background-color: transparent; color: black; font-size: 24px; font-weight: bold;")
self.next_button.clicked.connect(self.next_song)
controls_layout.addWidget(self.next_button)
# 添加播放进度条
self.progress_slider = QSlider(Qt.Horizontal, self)
self.progress_slider.setStyleSheet(
"QSlider::groove:horizontal {background: #d3d3d3;} QSlider::handle:horizontal {background: lightblue;}")
self.progress_slider.sliderMoved.connect(self.set_position)
controls_layout.addWidget(self.progress_slider)
layout.addLayout(controls_layout)
# 添加背景
self.setAttribute(Qt.WA_StyledBackground, True)
self.setStyleSheet("background-color: rgba(211, 211, 211, 0.7); border-radius: 15px;")
# 连接信号和槽
self.player.durationChanged.connect(self.update_duration)
self.player.positionChanged.connect(self.update_position)
def load_music_files(self):
music_directory = './music'
if not os.path.exists(music_directory):
os.makedirs(music_directory)
for file_name in os.listdir(music_directory):
if file_name.endswith(('.mp3', '.ogg', '.wav', '.flac', '.mid')):
file_path = os.path.join(music_directory, file_name)
media_content = QMediaContent(QUrl.fromLocalFile(file_path))
self.playlist.addMedia(media_content)
self.playlist.setCurrentIndex(0) # 设置当前播放为第一首
def toggle_play(self):
if self.player.state() == QMediaPlayer.PlayingState:
self.player.pause()
self.play_button.setText("▶")
else:
self.player.play()
self.play_button.setText("⏸")
def next_song(self):
self.playlist.next()
def previous_song(self):
self.playlist.previous()
def update_duration(self, duration):
self.progress_slider.setRange(0, duration)
def update_position(self, position):
if not self.progress_slider.isSliderDown():
self.progress_slider.setValue(position)
index = self.playlist.currentIndex()
if index >= 0:
current_media = self.playlist.media(index)
current_url = current_media.canonicalUrl().toLocalFile()
song_name = os.path.basename(current_url)
self.song_label.setText(song_name)
def set_position(self, position):
self.player.setPosition(position)
主要变化:
控制的布局调整: 创建了一个新的 QHBoxLayout(命名为 controls_layout),并将播放控制按钮和进度条添加到此布局。
进度条位置: 将进度条移动到与播放控制按钮(上一首、播放/暂停、下一首)同一行。
更新样式表: 确保进度条和按钮的样式表设置了正确的视觉风格。
修改完成后,播放器界面将更现代化,且符合你要求的布局样式。如果问题还没解决,或者有新的问题,请随时告知。
class MusicPlayerWidget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("音乐播放器")
# 创建播放器和播放列表
self.player = QMediaPlayer(self)
self.playlist = QMediaPlaylist(self)
self.player.setPlaylist(self.playlist)
self.load_music_files()
# 设置UI布局
layout = QVBoxLayout(self)
# 顶部显示音乐名称的标签
self.song_label = QLabel("选择一首乐曲", self)
self.song_label.setStyleSheet("color: black; font-size: 18px; font-weight: bold;")
self.song_label.setAlignment(Qt.AlignCenter)
layout.addWidget(self.song_label)
# 添加进度条和控制按钮布局
controls_layout = QHBoxLayout()
self.previous_button = QPushButton("⏮", self)
self.previous_button.setStyleSheet("background-color: transparent; color: black; font-size: 24px; font-weight: bold;")
self.previous_button.clicked.connect(self.previous_song)
controls_layout.addWidget(self.previous_button)
self.play_button = QPushButton("▶", self)
self.play_button.setStyleSheet("background-color: transparent; color: black; font-size: 24px; font-weight: bold;")
self.play_button.clicked.connect(self.toggle_play)
controls_layout.addWidget(self.play_button)
self.next_button = QPushButton("⏭", self)
self.next_button.setStyleSheet("background-color: transparent; color: black; font-size: 24px; font-weight: bold;")
self.next_button.clicked.connect(self.next_song)
controls_layout.addWidget(self.next_button)
# 添加播放进度条
self.progress_slider = QSlider(Qt.Horizontal, self)
self.progress_slider.setStyleSheet(
"QSlider::groove:horizontal {background: #d3d3d3;} QSlider::handle:horizontal {background: lightblue;}")
self.progress_slider.sliderMoved.connect(self.set_position)
self.progress_slider.sliderPressed.connect(self.pause_while_sliding)
self.progress_slider.sliderReleased.connect(self.resume_after_sliding)
controls_layout.addWidget(self.progress_slider)
layout.addLayout(controls_layout)
# 添加背景
self.setAttribute(Qt.WA_StyledBackground, True)
self.setStyleSheet("background-color: rgba(211, 211, 211, 0.7); border-radius: 15px;")
# 连接信号和槽
self.player.durationChanged.connect(self.update_duration)
self.player.positionChanged.connect(self.update_position)
def load_music_files(self):
music_directory = './music'
if not os.path.exists(music_directory):
os.makedirs(music_directory)
for file_name in os.listdir(music_directory):
if file_name.endswith(('.mp3', '.wav')): # 仅加载 MP3 和 WAV 文件
file_path = os.path.join(music_directory, file_name)
media_content = QMediaContent(QUrl.fromLocalFile(file_path))
self.playlist.addMedia(media_content)
self.playlist.setCurrentIndex(0) # 设置当前播放为第一首
def toggle_play(self):
if self.player.state() == QMediaPlayer.PlayingState:
self.player.pause()
self.play_button.setText("▶")
else:
self.player.play()
self.play_button.setText("⏸")
def next_song(self):
self.playlist.next()
def previous_song(self):
self.playlist.previous()
def update_duration(self, duration):
self.progress_slider.setRange(0, duration)
def update_position(self, position):
if not self.progress_slider.isSliderDown():
self.progress_slider.setValue(position)
index = self.playlist.currentIndex()
if index >= 0:
current_media = self.playlist.media(index)
current_url = current_media.canonicalUrl().toLocalFile()
song_name = os.path.basename(current_url)
self.song_label.setText(song_name)
def set_position(self, position):
self.player.setPosition(position)
def pause_while_sliding(self):
if self.player.state() == QMediaPlayer.PlayingState:
self.was_playing = True
self.player.pause()
else:
self.was_playing = False
def resume_after_sliding(self):
if self.was_playing:
self.player.play()
更改和注意事项:
支持格式: 由于 QMediaPlayer 的局限性,仅支持 .mp3 和 .wav 格式,以确保大多数平台下良好的兼容性。
进度条可拖动: 将 QSlider 的拖动事件设置为在拖动过程中暂停播放,松开后继续播放。
代码逻辑: 增加了 pause_while_sliding() 和 resume_after_sliding() 方法以处理进度条拖动时的播放状态控制。
请确保安装了所有必要的编解码器,尤其是对于 Windows 系统,默认支持可能较有限。如果仍需要播放其他格式,通常需要通过安装第三方编解码器。