Untitled conversation
Jump to turn (7)
- User
# combine_split_manager.py
import json, os, subprocess, pypinyin
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt, QTimer, pyqtSignal, QAbstractTableModel, QModelIndex
from PyQt5.QtGui import QColor
from bs4 import BeautifulSoup
class FormulaTableModel(QAbstractTableModel):
def __init__(self, data, parent=None):
super().__init__(parent)
self._data = data
self.checked_rows = set()
def rowCount(self, parent=QModelIndex()):
return len(self._data)
def columnCount(self, parent=QModelIndex()):
return 1 if self._data else 0
def data(self, index, role=Qt.DisplayRole):
if role == Qt.DisplayRole:
row = index.row()
col = index.column()
if col == 0:
return self._data[row][1] # 返回药方名称
elif col == 1:
return None # 第二列不显示文字,只显示复选框
elif role == Qt.CheckStateRole and index.column() == 1:
row = index.row()
if row in self.checked_rows:
return Qt.Checked
else:
return Qt.Unchecked
return None
def headerData(self, section, orientation, role=Qt.DisplayRole):
if role == Qt.DisplayRole and orientation == Qt.Horizontal:
if section == 0:
return "药方名称"
elif section == 1:
return "选择"
return None
def flags(self, index):
if index.column() == 1:
return Qt.ItemIsEnabled | Qt.ItemIsUserCheckable
return Qt.ItemIsEnabled
def setData(self, index, value, role=Qt.EditRole):
if index.column() == 1 and role == Qt.CheckStateRole:
row = index.row()
if value == Qt.Checked:
self.checked_rows.add(row)
else:
self.checked_rows.discard(row)
self.dataChanged.emit(index, index)
return True
return False
class MaterialTableModel(QAbstractTableModel):
def __init__(self, data, parent=None):
super().__init__(parent)
self._data = data
self.checked_rows = set()
def rowCount(self, parent=QModelIndex()):
return len(self._data)
def columnCount(self, parent=QModelIndex()):
return 2 if self._data else 0
def data(self, index, role=Qt.DisplayRole):
if role == Qt.DisplayRole:
row = index.row()
col = index.column()
if col == 0:
return self._data[row][1] # 返回药材名称
elif col == 1:
return None # 第二列不显示文字,只显示复选框
elif role == Qt.CheckStateRole and index.column() == 1:
row = index.row()
if row in self.checked_rows:
return Qt.Checked
else:
return Qt.Unchecked
return None
def headerData(self, section, orientation, role=Qt.DisplayRole):
if role == Qt.DisplayRole and orientation == Qt.Horizontal:
if section == 0:
return "药材名称"
elif section == 1:
return "选择"
return None
def flags(self, index):
if index.column() == 1:
return Qt.ItemIsEnabled | Qt.ItemIsUserCheckable
return Qt.ItemIsEnabled
def setData(self, index, value, role=Qt.EditRole):
if index.column() == 1 and role == Qt.CheckStateRole:
row = index.row()
if value == Qt.Checked:
self.checked_rows.add(row)
else:
self.checked_rows.discard(row)
self.dataChanged.emit(index, index)
return True
return False
class CombineSplitManager(QWidget):
def __init__(self, db, formula_manager, material_manager):
super().__init__()
self.db = db
self.formula_manager = formula_manager
self.material_manager = material_manager
self.selected_materials = set()
self.selected_formulas = set()
self.combined_ingredients = {}
# 缓存药方药材和名称信息
self.formula_data = {}
self.material_names = {}
self.init_ui()
self.material_manager.material_changed.connect(self.load_materials_to_table)
self.formula_manager.formula_changed.connect(self.load_all_formulas)
def init_ui(self):
layout = QVBoxLayout()
self.search_input = QLineEdit(placeholderText="输入药方或药材的名称,支持拼音或缩写快速搜索")
self.search_input.textChanged.connect(self.on_search_input_changed)
layout.addWidget(self.search_input)
# 药方表格
self.formula_table = QTableView()
self.formula_table.verticalHeader().setVisible(False)
self.formula_table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.formula_table.clicked.connect(self.on_formula_table_clicked)
layout.addWidget(self.formula_table)
# 药材表格
self.combine_split_material_table = QTableView()
self.combine_split_material_table.verticalHeader().setVisible(False)
self.combine_split_material_table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.combine_split_material_table.clicked.connect(self.on_material_table_clicked)
layout.addWidget(self.combine_split_material_table)
self.result_text = QTextEdit(readOnly=True, acceptRichText=True)
layout.addWidget(self.result_text)
btn_layout = QHBoxLayout()
self.save_button = QPushButton("保存结果", clicked=self.save_results)
self.clear_button = QPushButton("全部清除", clicked=self.clear_all_selections)
btn_layout.addStretch(1)
btn_layout.addWidget(self.save_button)
btn_layout.addWidget(self.clear_button)
layout.addLayout(btn_layout)
self.notification_label = QLabel('')
self.notification_label.setStyleSheet('color: red; padding: 5px; border: 1px solid #ddd; border-radius: 3px;')
self.notification_label.setAlignment(Qt.AlignCenter)
self.notification_label.setFixedHeight(30)
layout.addWidget(self.notification_label)
self.setLayout(layout)
self.load_all_formulas()
self.load_materials_to_table()
def save_results(self):
text = BeautifulSoup(self.result_text.toHtml(), 'html.parser').get_text()
if not text.strip():
self.show_warning("没有可保存的结果")
return
file_name, _ = QFileDialog.getSaveFileName(self, "保存结果", "", "文本文件 (*.txt);;所有文件 (*)")
if not file_name:
return
if not file_name.endswith('.txt'):
file_name += '.txt'
try:
with open(file_name, 'w', encoding='utf-8') as f:
f.write(text)
self.show_warning(f"结果已保存到 {os.path.basename(file_name)}", is_warning=False)
self.open_file_location(file_name)
except Exception as e:
self.show_warning(f"保存失败: {str(e)}")
def open_file_location(self, file_path):
folder_path = os.path.dirname(file_path)
if os.name == 'nt':
os.startfile(folder_path)
elif os.name == 'posix':
subprocess.call(['open', folder_path])
def on_search_input_changed(self, text):
keywords = text.strip().lower().split()
# 缓存拼音结果
pinyin_cache = {}
keywords = set(keywords + [''.join(pinyin_cache.setdefault(k, pypinyin.lazy_pinyin(k))[0] for k in keywords)])
self.update_table_visibility(self.formula_table, keywords, pinyin_cache)
self.update_table_visibility(self.combine_split_material_table, keywords, pinyin_cache)
def update_table_visibility(self, table, keywords, pinyin_cache):
model = table.model()
for row in range(model.rowCount()):
text = model.data(model.index(row, 0)).lower()
pinyin_text = ''.join(pinyin_cache.setdefault(text, pypinyin.lazy_pinyin(text)))
pinyin_initials = ''.join(p[0] for p in pinyin_cache.setdefault(text, pypinyin.lazy_pinyin(text)))
match = any(k in text or k in pinyin_text or k in pinyin_initials for k in keywords)
table.setRowHidden(row, not match)
def load_all_formulas(self):
self.formula_data.clear()
self.formula_data = {
formula_id: {
'name': formula_name,
'materials': {ing[0] for ing in json.loads(ingredients)},
'ingredients': json.loads(ingredients)
}
for formula_id, formula_name, ingredients in self.db.fetch_all('SELECT id, name, ingredients FROM Formulas ORDER BY id')
}
# 将 formula_id 添加到 FormulaTableModel 的数据中
self.formula_table_model = FormulaTableModel([(formula_id, data['name']) for formula_id, data in self.formula_data.items()], self)
self.formula_table.setModel(self.formula_table_model)
self.formula_table.setColumnWidth(0, 200)
self.formula_table.setColumnWidth(1, 50)
def clear_all_selections(self):
self.selected_formulas.clear()
self.selected_materials.clear()
self.combined_ingredients.clear()
self.reset_table_selections(self.formula_table)
self.reset_table_selections(self.combine_split_material_table)
self.result_text.setText('')
self.show_warning("已清除所有选择")
def on_formula_table_clicked(self, index):
row = index.row()
formula_id = list(self.formula_data.keys())[row]
if row in self.formula_table_model.checked_rows:
self.select_formula(formula_id)
else:
self.deselect_formula(formula_id)
def select_formula(self, formula_id):
if formula_id in self.selected_formulas or any(self.is_subset(formula_id, f) for f in self.selected_formulas):
return True if formula_id in self.selected_formulas else (self.show_warning("该药方是已选药方的子集,无法添加。") or False)
new_selected_formulas = self.selected_formulas - {f for f in self.selected_formulas if self.is_subset(f, formula_id)} | {formula_id}
new_selected_materials = self.selected_materials | self.get_formula_materials(formula_id)
self.selected_formulas = new_selected_formulas
self.selected_materials = new_selected_materials
self.update_combined_ingredients_from_formulas(new_selected_formulas)
self.update_formula_selections()
self.update_table_selections(self.combine_split_material_table, new_selected_materials, True, False)
self.update_results()
return True
def update_table_selections(self, table, items_to_update, checked=True, force=True):
model = table.model()
for row in range(model.rowCount()):
# 直接从 model._data 中获取 item_id
item_id = model._data[row][0]
if item_id in items_to_update:
# 使用 Qt.CheckStateRole 设置复选框状态
model.setData(model.index(row, 1), Qt.Checked if checked else Qt.Unchecked, Qt.CheckStateRole)
def deselect_formula(self, formula_id):
if formula_id not in self.selected_formulas:
return True
supersets = [f for f in self.selected_formulas if self.is_subset(formula_id, f)]
if supersets:
return self.show_warning(f"无法取消该药方,因为它是以下药方的子集:{', '.join(self.get_formula_name(f) for f in supersets)}") or False
formula_materials = self.get_formula_materials(formula_id)
subsets = [f for f in self.selected_formulas if self.is_subset(f, formula_id)]
subset_materials = set().union(*(self.get_formula_materials(f) for f in subsets))
if subset_materials == formula_materials:
formulas_to_remove = set(subsets) | {formula_id}
materials_to_remove = formula_materials
else:
formulas_to_remove = {formula_id}
materials_to_remove = formula_materials - subset_materials
self.selected_formulas -= formulas_to_remove
self.selected_materials -= {m for m in materials_to_remove if m not in self.get_materials_from_formulas(self.selected_formulas)}
self.update_combined_ingredients_from_formulas(self.selected_formulas)
self.update_formula_selections()
self.update_table_selections(self.combine_split_material_table, materials_to_remove, False)
self.update_results()
return True
def update_formula_selections(self):
# 首先重置所有行的隐藏状态
for row in range(self.formula_table_model.rowCount()):
self.formula_table.setRowHidden(row, False)
# 然后根据选择状态和子集关系设置隐藏状态
for row, (formula_id, _) in enumerate(self.formula_data.items()):
is_selected = formula_id in self.selected_formulas
is_subset = any(self.is_subset(formula_id, f) for f in self.selected_formulas if f != formula_id)
self.formula_table_model.setData(self.formula_table_model.index(row, 1), Qt.Checked if is_selected else Qt.Unchecked, Qt.CheckStateRole)
# 仅当药方是子集且未被选中时才隐藏
self.formula_table.setRowHidden(row, is_subset and not is_selected)
def on_material_table_clicked(self, index):
row = index.row()
material_id = list(self.material_names.keys())[row]
if row in self.combine_split_material_table.model().checked_rows:
self.select_material(material_id)
else:
self.deselect_material(material_id)
def select_material(self, material_id):
self.selected_materials.add(material_id)
new_selected_formulas = self.get_formulas_from_materials(self.selected_materials)
self.update_table_selections(self.formula_table, new_selected_formulas - self.selected_formulas, True)
self.selected_formulas = new_selected_formulas
self.update_combined_ingredients_from_formulas(self.selected_formulas)
self.update_results()
def deselect_material(self, material_id):
self.selected_materials.discard(material_id)
new_selected_formulas = self.get_formulas_from_materials(self.selected_materials)
self.update_table_selections(self.formula_table, self.selected_formulas - new_selected_formulas, False)
self.selected_formulas = new_selected_formulas
self.update_combined_ingredients_from_formulas(self.selected_formulas)
self.update_results()
def load_materials_to_table(self):
self.material_names.clear()
self.material_names = {
material_id: material_name
for material_id, material_name in self.db.fetch_all('SELECT id, name FROM Materials ORDER BY id')
}
self.material_table_model = MaterialTableModel(list(self.material_names.items()), self)
self.combine_split_material_table.setModel(self.material_table_model)
self.combine_split_material_table.setColumnWidth(0, 200)
self.combine_split_material_table.setColumnWidth(1, 50)
def reset_table_selections(self, table):
model = table.model()
model.checked_rows.clear()
model.dataChanged.emit(model.index(0, 0), model.index(model.rowCount() - 1, model.columnCount() - 1))
def get_formula_materials(self, formula_id):
return self.formula_data.get(formula_id, {}).get('materials', set())
def get_formula_ingredients(self, formula_id):
return self.formula_data.get(formula_id, {}).get('ingredients', [])
def get_materials_from_formulas(self, formula_ids):
return set().union(*(self.get_formula_materials(formula_id) for formula_id in formula_ids))
def get_formulas_from_materials(self, material_ids):
return {formula_id for formula_id, formula_data in self.formula_data.items() if formula_data['materials'].issubset(material_ids)}
def update_combined_ingredients(self, new_ingredients):
for ing_id, dosage in new_ingredients:
self.combined_ingredients[ing_id] = max(self.combined_ingredients.get(ing_id, 0), float(dosage))
def update_combined_ingredients_from_formulas(self, formula_ids):
self.combined_ingredients = {}
for formula_id in formula_ids:
if not any(self.is_subset(formula_id, other_id) for other_id in formula_ids if other_id != formula_id):
self.update_combined_ingredients(self.get_formula_ingredients(formula_id))
def is_subset(self, formula_id1, formula_id2):
materials1 = self.get_formula_materials(formula_id1)
materials2 = self.get_formula_materials(formula_id2)
return materials1.issubset(materials2) and materials1 != materials2
def show_warning(self, message, is_warning=True):
self.notification_label.setText(message)
self.notification_label.setStyleSheet(f'color: {"red" if is_warning else "green"}; padding: 5px; border: 1px solid #ddd; border-radius: 3px;')
QTimer.singleShot(5000, self.clear_warning)
def clear_warning(self):
self.notification_label.clear()
def update_results(self):
selected_materials = [(mid, self.material_names.get(mid, "未知药材")) for mid in self.selected_materials]
self.update_combined_ingredients_from_formulas(self.selected_formulas)
matching_formulas = self.find_matching_formulas(self.selected_materials)
result = self.format_results(selected_materials, self.combined_ingredients, matching_formulas, self.selected_formulas)
self.result_text.setHtml(result)
self.save_button.setEnabled(bool(result.strip()))
def find_matching_formulas(self, selected_material_ids):
return [(formula_id, formula_data['name'], json.dumps(formula_data['ingredients']))
for formula_id, formula_data in self.formula_data.items()
if formula_data['materials'].issubset(selected_material_ids)]
def format_results(self, selected_materials, combined_ingredients, matching_formulas, selected_formulas):
result = "<p>您选择的药材共计 {} 味:".format(len(selected_materials))
combined_material_ids = set(combined_ingredients.keys())
in_result = ['<span style="color: green;">{}</span>'.format(material_name) for material_id, material_name in selected_materials if material_id in combined_material_ids]
not_in_result = ['<span style="color: red;">{}</span>'.format(material_name) for material_id, material_name in selected_materials if material_id not in combined_material_ids]
result += ' '.join(in_result)
if not_in_result:
result += ' ({})'.format('、'.join(not_in_result))
result += '</p><p><small>(上方括号中的药材未在合方中。)</small></p>'
result += "<p>包含的药方组合共计 {} 个:</p>".format(len(matching_formulas))
for formula_id, formula_name, ingredients in matching_formulas:
is_subset = any(self.is_subset(formula_id, other_id) for other_id in selected_formulas if other_id != formula_id)
result += "<p>{}{}: ".format(formula_name, " (子集)" if is_subset else "")
ingredients = json.loads(ingredients)
for ing_id, dosage in ingredients:
result += '{}: {} '.format(self.material_names.get(ing_id, "未知药材"), dosage)
result += "</p>"
result += "<p>合方结果:</p>"
total_ingredients = len(combined_ingredients)
result += "<p>共计 {} 味:".format(total_ingredients)
result += ' '.join(['<span style="color: green;">{}</span>: <span style="color: orange;">{}</span>'.format(self.material_names.get(material_id, "未知药材"), dosage) for material_id, dosage in combined_ingredients.items()]) + "</p>"
subset_formulas = {formula_id for formula_id in selected_formulas if any(self.is_subset(formula_id, other_id) for other_id in selected_formulas if other_id != formula_id)}
if subset_formulas:
result += "<p><small>注意:以下药方是其他药方的子集,其药材未参与最终合方结果的计算:</small></p>"
for formula_id in subset_formulas:
result += f"<p><small>- {self.get_formula_name(formula_id)}</small></p>"
return result
def get_formula_name(self, formula_id):
return self.formula_data.get(formula_id, {}).get('name', "未知药方")
以上程序中药方和药材的表格修改为多列,让屏幕上一次显示更多的药方或药材。
要将药方和药材的表格修改为多列,以便在屏幕上同时显示更多的药方或药材,你可以通过以下步骤进行修改:
调整 FormulaTableModel 和 MaterialTableModel 的 columnCount 方法:
修改 data 方法:
调整表格的布局:
FormulaTableModel 和 MaterialTableModel 的 columnCount 方法class FormulaTableModel(QAbstractTableModel):
def __init__(self, data, parent=None):
super().__init__(parent)
self._data = data
self.checked_rows = set()
self.columns_per_row = 3 # 每行显示3个药方
def rowCount(self, parent=QModelIndex()):
return (len(self._data) + self.columns_per_row - 1) // self.columns_per_row
def columnCount(self, parent=QModelIndex()):
return self.columns_per_row
# MaterialTableModel 类也进行相同的修改
data 方法,调整根据行列获取数据的逻辑class FormulaTableModel(QAbstractTableModel):
def data(self, index, role=Qt.DisplayRole):
if role == Qt.DisplayRole:
row = index.row()
col = index.column()
data_index = row * self.columns_per_row + col
if data_index < len(self._data):
return self._data[data_index][1] # 返回药方名称
elif role == Qt.CheckStateRole:
row = index.row()
col = index.column()
data_index = row * self.columns_per_row + col
if data_index < len(self._data) and data_index in self.checked_rows:
return Qt.Checked
elif data_index < len(self._data):
return Qt.Unchecked
return None
# MaterialTableModel 类也进行相同的修改
还有很多逻辑要修改,比如现在的程序只有第二列才能勾选,其他列不能勾选。
在现有代码结构中,勾选功能仅限于表格的第二列。要将勾选功能扩展到多列并适应多列布局,需要对代码中涉及勾选操作的逻辑进行较大调整。以下是具体的修改步骤。
flags 方法,允许所有列勾选首先,修改 FormulaTableModel 和 MaterialTableModel 中的 flags 方法,使所有列都可以勾选,而不仅仅是第二列。
class FormulaTableModel(QAbstractTableModel):
def flags(self, index):
if index.isValid():
return Qt.ItemIsEnabled | Qt.ItemIsUserCheckable
return Qt.ItemIsEnabled
# MaterialTableModel 类也进行相同的修改
setData 方法,处理多列勾选需要修改 setData 方法,以支持各列的勾选操作:
class FormulaTableModel(QAbstractTableModel):
def setData(self, index, value, role=Qt.EditRole):
if role == Qt.CheckStateRole:
row = index.row()
col = index.column()
data_index = row * self.columns_per_row + col
if data_index < len(self._data):
if value == Qt.Checked:
self.checked_rows.add(data_index)
else:
self.checked_rows.discard(data_index)
self.dataChanged.emit(index, index)
return True
return False
# MaterialTableModel 类也进行相同的修改
data 方法,处理多列勾选状态修改 data 方法,使其在所有列上正确显示勾选状态:
class FormulaTableModel(QAbstractTableModel):
def data(self, index, role=Qt.DisplayRole):
row = index.row()
col = index.column()
data_index = row * self.columns_per_row + col
if data_index >= len(self._data):
return None
if role == Qt.DisplayRole:
return self._data[data_index][1] # 返回药方名称
elif role == Qt.CheckStateRole:
return Qt.Checked if data_index in self.checked_rows else Qt.Unchecked
return None
# MaterialTableModel 类也进行相同的修改
修改为点击名称也可以勾选或取消复选框。
要让用户在点击名称时也能勾选或取消复选框,我们需要在点击名称的单元格时手动触发复选框状态的切换。以下是具体的步骤:
on_formula_table_clicked 和 on_material_table_clicked 方法我们需要在点击名称时手动切换复选框的状态。可以在 on_formula_table_clicked 和 on_material_table_clicked 方法中实现这一点。
class CombineSplitManager(QWidget):
def on_formula_table_clicked(self, index):
row = index.row()
col = index.column()
data_index = row * self.formula_table_model.columns_per_row + col
if data_index < len(self.formula_table_model._data):
# 获取 formula_id
formula_id = self.formula_table_model._data[data_index][0]
# 手动切换复选框状态
if data_index in self.formula_table_model.checked_rows:
self.formula_table_model.setData(index, Qt.Unchecked, Qt.CheckStateRole)
self.deselect_formula(formula_id)
else:
self.formula_table_model.setData(index, Qt.Checked, Qt.CheckStateRole)
self.select_formula(formula_id)
def on_material_table_clicked(self, index):
row = index.row()
col = index.column()
data_index = row * self.material_table_model.columns_per_row + col
if data_index < len(self.material_table_model._data):
# 获取 material_id
material_id = self.material_table_model._data[data_index][0]
# 手动切换复选框状态
if data_index in self.material_table_model.checked_rows:
self.material_table_model.setData(index, Qt.Unchecked, Qt.CheckStateRole)
self.deselect_material(material_id)
else:
self.material_table_model.setData(index, Qt.Checked, Qt.CheckStateRole)
self.select_material(material_id)
在上面的代码中,我们手动切换了复选框的状态。当用户点击任意列时,都会触发 on_formula_table_clicked 或 on_material_table_clicked 方法,然后根据当前状态自动切换复选框的状态。
如果你希望点击任意列都能切换复选框状态,可以将列号的判断逻辑去掉,直接对 on_formula_table_clicked 和 on_material_table_clicked 方法进行修改。
经过上述修改后,当用户点击药方或药材的名称时,复选框的状态也会自动切换。这将为用户提供更直观的操作体验。
通过上述修改,你可以实现点击表格中的名称时也能勾选或取消复选框的功能,这样用户体验会更加友好。所有涉及勾选的逻辑都被统一处理,无论用户点击的是复选框还是名称,都能触发相同的勾选操作。
表格宽度自动撑满
要让表格宽度自动撑满窗口宽度,无论表格的列数如何,都需要进行以下调整:
设置表格的自动调整模式:通过设置表格的 horizontalHeader().setSectionResizeMode(),可以自动调整列宽,使其填满整个表格宽度。
监听窗口大小的变化:确保窗口大小改变时,表格也会自动调整列宽。
在 CombineSplitManager 的 init_ui 方法中,对 formula_table 和 combine_split_material_table 设置自动调整列宽。
def init_ui(self):
layout = QVBoxLayout()
self.search_input = QLineEdit(placeholderText="输入药方或药材的名称,支持拼音或缩写快速搜索")
self.search_input.textChanged.connect(self.on_search_input_changed)
layout.addWidget(self.search_input)
# 药方表格
self.formula_table = QTableView()
self.formula_table.verticalHeader().setVisible(False)
self.formula_table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.formula_table.clicked.connect(self.on_formula_table_clicked)
self.formula_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) # 自动调整列宽
layout.addWidget(self.formula_table)
# 药材表格
self.combine_split_material_table = QTableView()
self.combine_split_material_table.verticalHeader().setVisible(False)
self.combine_split_material_table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.combine_split_material_table.clicked.connect(self.on_material_table_clicked)
self.combine_split_material_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) # 自动调整列宽
layout.addWidget(self.combine_split_material_table)
self.result_text = QTextEdit(readOnly=True, acceptRichText=True)
layout.addWidget(self.result_text)
btn_layout = QHBoxLayout()
self.save_button = QPushButton("保存结果", clicked=self.save_results)
self.clear_button = QPushButton("全部清除", clicked=self.clear_all_selections)
btn_layout.addStretch(1)
btn_layout.addWidget(self.save_button)
btn_layout.addWidget(self.clear_button)
layout.addLayout(btn_layout)
self.notification_label = QLabel('')
self.notification_label.setStyleSheet('color: red; padding: 5px; border: 1px solid #ddd; border-radius: 3px;')
self.notification_label.setAlignment(Qt.AlignCenter)
self.notification_label.setFixedHeight(30)
layout.addWidget(self.notification_label)
self.setLayout(layout)
self.load_all_formulas()
self.load_materials_to_table()
# 调整窗口大小时自动调整列宽
self.resizeEvent = self.on_resize
def on_resize(self, event):
# 重新调整列宽
self.formula_table.resizeColumnsToContents()
self.combine_split_material_table.resizeColumnsToContents()
这个表头没有用处,请取消
如果表头没有用处,你可以直接隐藏表格的表头,以简化界面。以下是如何隐藏表头的步骤:
在 CombineSplitManager 类的 init_ui 方法中,可以通过设置 setVisible(False) 来隐藏水平和垂直表头。
def init_ui(self):
layout = QVBoxLayout()
self.search_input = QLineEdit(placeholderText="输入药方或药材的名称,支持拼音或缩写快速搜索")
self.search_input.textChanged.connect(self.on_search_input_changed)
layout.addWidget(self.search_input)
# 药方表格
self.formula_table = QTableView()
self.formula_table.verticalHeader().setVisible(False)
self.formula_table.horizontalHeader().setVisible(False) # 隐藏水平表头
self.formula_table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.formula_table.clicked.connect(self.on_formula_table_clicked)
self.formula_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) # 自动调整列宽
layout.addWidget(self.formula_table)
# 药材表格
self.combine_split_material_table = QTableView()
self.combine_split_material_table.verticalHeader().setVisible(False)
self.combine_split_material_table.horizontalHeader().setVisible(False) # 隐藏水平表头
self.combine_split_material_table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.combine_split_material_table.clicked.connect(self.on_material_table_clicked)
self.combine_split_material_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) # 自动调整列宽
layout.addWidget(self.combine_split_material_table)
self.result_text = QTextEdit(readOnly=True, acceptRichText=True)
layout.addWidget(self.result_text)
btn_layout = QHBoxLayout()
self.save_button = QPushButton("保存结果", clicked=self.save_results)
self.clear_button = QPushButton("全部清除", clicked=self.clear_all_selections)
btn_layout.addStretch(1)
btn_layout.addWidget(self.save_button)
btn_layout.addWidget(self.clear_button)
layout.addLayout(btn_layout)
self.notification_label = QLabel('')
self.notification_label.setStyleSheet('color: red; padding: 5px; border: 1px solid #ddd; border-radius: 3px;')
self.notification_label.setAlignment(Qt.AlignCenter)
self.notification_label.setFixedHeight(30)
layout.addWidget(self.notification_label)
self.setLayout(layout)
self.load_all_formulas()
self.load_materials_to_table()
# 调整窗口大小时自动调整列宽
self.resizeEvent = self.on_resize
def on_resize(self, event):
# 重新调整列宽
self.formula_table.resizeColumnsToContents()
self.combine_split_material_table.resizeColumnsToContents()
隐藏表格线
要隐藏表格的网格线,使表格看起来更加简洁和平滑,可以通过设置 QTableView 的 showGrid 属性为 False 来实现。以下是具体的步骤:
在 CombineSplitManager 类的 init_ui 方法中,设置 showGrid(False) 来隐藏表格线。
def init_ui(self):
layout = QVBoxLayout()
self.search_input = QLineEdit(placeholderText="输入药方或药材的名称,支持拼音或缩写快速搜索")
self.search_input.textChanged.connect(self.on_search_input_changed)
layout.addWidget(self.search_input)
# 药方表格
self.formula_table = QTableView()
self.formula_table.verticalHeader().setVisible(False)
self.formula_table.horizontalHeader().setVisible(False) # 隐藏水平表头
self.formula_table.setShowGrid(False) # 隐藏表格线
self.formula_table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.formula_table.clicked.connect(self.on_formula_table_clicked)
self.formula_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) # 自动调整列宽
layout.addWidget(self.formula_table)
# 药材表格
self.combine_split_material_table = QTableView()
self.combine_split_material_table.verticalHeader().setVisible(False)
self.combine_split_material_table.horizontalHeader().setVisible(False) # 隐藏水平表头
self.combine_split_material_table.setShowGrid(False) # 隐藏表格线
self.combine_split_material_table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.combine_split_material_table.clicked.connect(self.on_material_table_clicked)
self.combine_split_material_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) # 自动调整列宽
layout.addWidget(self.combine_split_material_table)
self.result_text = QTextEdit(readOnly=True, acceptRichText=True)
layout.addWidget(self.result_text)
btn_layout = QHBoxLayout()
self.save_button = QPushButton("保存结果", clicked=self.save_results)
self.clear_button = QPushButton("全部清除", clicked=self.clear_all_selections)
btn_layout.addStretch(1)
btn_layout.addWidget(self.save_button)
btn_layout.addWidget(self.clear_button)
layout.addLayout(btn_layout)
self.notification_label = QLabel('')
self.notification_label.setStyleSheet('color: red; padding: 5px; border: 1px solid #ddd; border-radius: 3px;')
self.notification_label.setAlignment(Qt.AlignCenter)
self.notification_label.setFixedHeight(30)
layout.addWidget(self.notification_label)
self.setLayout(layout)
self.load_all_formulas()
self.load_materials_to_table()
# 调整窗口大小时自动调整列宽
self.resizeEvent = self.on_resize
def on_resize(self, event):
# 重新调整列宽
self.formula_table.resizeColumnsToContents()
self.combine_split_material_table.resizeColumnsToContents()
当选择一个药方时,他的子集没有被选中,也没有被锁定。
要实现选择一个药方时,其子集药方既不被选中也不被锁定(即不自动勾选和不隐藏),只保留用户手动选择的控制权,可以对现有逻辑进行以下调整:
select_formula 方法当前的 select_formula 方法中,当选择一个药方时,它会检查并移除其子集药方,以避免冲突。我们需要调整这个逻辑,使得子集药方不受影响。
def select_formula(self, formula_id):
# 检查被选中的药方是否已经在选中列表中,或是其他选中的药方的子集
if formula_id in self.selected_formulas or any(self.is_subset(formula_id, f) for f in self.selected_formulas):
return True if formula_id in self.selected_formulas else (self.show_warning("该药方是已选药方的子集,无法添加。") or False)
# 将当前选中的药方添加到已选列表中,而不移除其子集药方
self.selected_formulas.add(formula_id)
self.selected_materials |= self.get_formula_materials(formula_id)
# 更新组合的药材和 UI
self.update_combined_ingredients_from_formulas(self.selected_formulas)
self.update_formula_selections()
self.update_table_selections(self.combine_split_material_table, self.selected_materials, True, False)
self.update_results()
return True
deselect_formula 方法同样,取消选择一个药方时,也不需要检查和影响其子集药方。
def deselect_formula(self, formula_id):
if formula_id not in self.selected_formulas:
return True
# 直接从已选列表中移除当前药方,并更新相关数据
self.selected_formulas.discard(formula_id)
self.selected_materials = self.get_materials_from_formulas(self.selected_formulas)
self.update_combined_ingredients_from_formulas(self.selected_formulas)
self.update_formula_selections()
self.update_table_selections(self.combine_split_material_table, self.selected_materials, True, False)
self.update_results()
return True
update_formula_selections 方法Not yet included in a published release.
setData 方法,调整根据行列设置数据的逻辑class FormulaTableModel(QAbstractTableModel):
def setData(self, index, value, role=Qt.EditRole):
if role == Qt.CheckStateRole:
row = index.row()
col = index.column()
data_index = row * self.columns_per_row + col
if data_index < len(self._data):
if value == Qt.Checked:
self.checked_rows.add(data_index)
else:
self.checked_rows.discard(data_index)
self.dataChanged.emit(index, index)
return True
return False
# MaterialTableModel 类也进行相同的修改
在 CombineSplitManager 的 init_ui 方法中,调整表格的列宽:
def init_ui(self):
# 其他代码保持不变...
# 药方表格
self.formula_table = QTableView()
self.formula_table.verticalHeader().setVisible(False)
self.formula_table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.formula_table.clicked.connect(self.on_formula_table_clicked)
layout.addWidget(self.formula_table)
self.formula_table.setColumnWidth(0, 150) # 调整列宽
self.formula_table.setColumnWidth(1, 150)
self.formula_table.setColumnWidth(2, 150)
# 药材表格
self.combine_split_material_table = QTableView()
self.combine_split_material_table.verticalHeader().setVisible(False)
self.combine_split_material_table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.combine_split_material_table.clicked.connect(self.on_material_table_clicked)
layout.addWidget(self.combine_split_material_table)
self.combine_split_material_table.setColumnWidth(0, 150) # 调整列宽
self.combine_split_material_table.setColumnWidth(1, 150)
self.combine_split_material_table.setColumnWidth(2, 150)
# 其他代码保持不变...
update_table_selections 方法的逻辑,考虑多列布局def update_table_selections(self, table, items_to_update, checked=True, force=True):
model = table.model()
for row in range(model.rowCount()):
for col in range(model.columnCount()):
data_index = row * model.columns_per_row + col
if data_index < len(model._data):
item_id = model._data[data_index][0]
if item_id in items_to_update:
model.setData(model.index(row, col), Qt.Checked if checked else Qt.Unchecked, Qt.CheckStateRole)
经过这些更改后,药方和药材将以多列形式显示在表格中,并且每行显示的药方或药材将增加,从而一次能够在屏幕上显示更多内容。
注意:你可以根据实际需求调整每行显示的列数(columns_per_row),调整列宽等参数以达到理想的显示效果。
on_formula_table_clicked 和 on_material_table_clicked 方法在 CombineSplitManager 类中,修改 on_formula_table_clicked 和 on_material_table_clicked 方法,以支持多列布局的勾选操作:
class CombineSplitManager(QWidget):
def on_formula_table_clicked(self, index):
row = index.row()
col = index.column()
data_index = row * self.formula_table_model.columns_per_row + col
if data_index < len(self.formula_table_model._data):
formula_id = self.formula_table_model._data[data_index][0]
if data_index in self.formula_table_model.checked_rows:
self.select_formula(formula_id)
else:
self.deselect_formula(formula_id)
def on_material_table_clicked(self, index):
row = index.row()
col = index.column()
data_index = row * self.material_table_model.columns_per_row + col
if data_index < len(self.material_table_model._data):
material_id = self.material_table_model._data[data_index][0]
if data_index in self.material_table_model.checked_rows:
self.select_material(material_id)
else:
self.deselect_material(material_id)
update_table_selections 方法该方法需要适应多列布局,确保在多列布局下正确设置勾选状态:
class CombineSplitManager(QWidget):
def update_table_selections(self, table, items_to_update, checked=True, force=True):
model = table.model()
for row in range(model.rowCount()):
for col in range(model.columnCount()):
data_index = row * model.columns_per_row + col
if data_index < len(model._data):
item_id = model._data[data_index][0]
if item_id in items_to_update:
model.setData(model.index(row, col), Qt.Checked if checked else Qt.Unchecked, Qt.CheckStateRole)
reset_table_selections 方法在 CombineSplitManager 类中,修改 reset_table_selections 方法,以适应多列布局:
class CombineSplitManager(QWidget):
def reset_table_selections(self, table):
model = table.model()
model.checked_rows.clear()
model.dataChanged.emit(
model.index(0, 0),
model.index(model.rowCount() - 1, model.columnCount() - 1)
)
update_formula_selections 方法此方法也需要修改,以确保在多列布局下正确显示药方的选择状态:
class CombineSplitManager(QWidget):
def update_formula_selections(self):
# 首先重置所有行的隐藏状态
for row in range(self.formula_table_model.rowCount()):
self.formula_table.setRowHidden(row, False)
# 然后根据选择状态和子集关系设置隐藏状态
for row in range(self.formula_table_model.rowCount()):
for col in range(self.formula_table_model.columnCount()):
data_index = row * self.formula_table_model.columns_per_row + col
if data_index >= len(self.formula_data):
continue
formula_id = list(self.formula_data.keys())[data_index]
is_selected = formula_id in self.selected_formulas
is_subset = any(self.is_subset(formula_id, f) for f in self.selected_formulas if f != formula_id)
self.formula_table_model.setData(
self.formula_table_model.index(row, col),
Qt.Checked if is_selected else Qt.Unchecked,
Qt.CheckStateRole
)
# 仅当药方是子集且未被选中时才隐藏
self.formula_table.setRowHidden(row, is_subset and not is_selected)
最后,确保界面布局适应多列显示,可能需要调整列宽和行高:
def init_ui(self):
# 其他代码保持不变...
# 药方表格
self.formula_table = QTableView()
self.formula_table.verticalHeader().setVisible(False)
self.formula_table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.formula_table.clicked.connect(self.on_formula_table_clicked)
layout.addWidget(self.formula_table)
for i in range(3): # 假设3列
self.formula_table.setColumnWidth(i, 150) # 调整列宽
# 药材表格
self.combine_split_material_table = QTableView()
self.combine_split_material_table.verticalHeader().setVisible(False)
self.combine_split_material_table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.combine_split_material_table.clicked.connect(self.on_material_table_clicked)
layout.addWidget(self.combine_split_material_table)
for i in range(3): # 假设3列
self.combine_split_material_table.setColumnWidth(i, 150) # 调整列宽
# 其他代码保持不变...
通过上述修改,你可以将药方和药材的表格改为多列形式,并且每列都支持勾选操作,从而一次能够在屏幕上显示更多内容。所有涉及勾选的逻辑都适应了多列布局,并且在操作时能够正确处理每一列的勾选状态。
这些改动涉及的代码较多,请在实际应用中逐步测试和调整,以确保所有功能正常运作。
已经在上述代码中通过重写 resizeEvent 将表格的列宽自动调整为适应窗口大小:
def on_resize(self, event):
# 重新调整列宽
self.formula_table.resizeColumnsToContents()
self.combine_split_material_table.resizeColumnsToContents()
通过 horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) 设置所有列的宽度均匀分布。
如果你希望列宽的调整更加灵活,你可以使用 QHeaderView.Interactive 模式,这样用户可以手动调整列宽。
self.formula_table.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)
self.combine_split_material_table.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)
通过这种方式,你可以确保表格的宽度自动撑满窗口宽度,增强用户体验。
这样设置后,表格的水平和垂直表头将被隐藏,界面看起来更加简洁。用户将只看到药方和药材的名称以及对应的复选框,没有多余的表头占用空间。
通过隐藏表头,你可以简化用户界面,使其更加直观和简洁,尤其是在表头信息不必要的情况下。这种方式对于想要最大化利用屏幕空间的应用程序特别有用。
经过上述设置,表格中的网格线将被隐藏。这样可以让表格看起来更加简洁、平滑,用户的视觉焦点将集中在内容本身,而不是表格的线条上。
通过隐藏表格线,你可以进一步简化用户界面,使表格看起来更加现代和干净。结合隐藏表头的设置,这种方式特别适合需要最大化内容展示空间的应用程序。
# combine_split_manager.py
import json, os, subprocess, pypinyin
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt, QTimer, pyqtSignal, QAbstractTableModel, QModelIndex
from PyQt5.QtGui import QColor
from bs4 import BeautifulSoup
class FormulaTableModel(QAbstractTableModel):
def __init__(self, data, parent=None):
super().__init__(parent)
self._data = data
self.checked_rows = set()
self.columns_per_row = 10 # 每行显示10个药方
def rowCount(self, parent=QModelIndex()):
return (len(self._data) + self.columns_per_row - 1) // self.columns_per_row
def columnCount(self, parent=QModelIndex()):
return self.columns_per_row
def data(self, index, role=Qt.DisplayRole):
row = index.row()
col = index.column()
data_index = row * self.columns_per_row + col
if data_index >= len(self._data):
return None
if role == Qt.DisplayRole:
return self._data[data_index][1] # 返回药方名称
elif role == Qt.CheckStateRole:
return Qt.Checked if data_index in self.checked_rows else Qt.Unchecked
return None
def flags(self, index):
if index.isValid():
return Qt.ItemIsEnabled | Qt.ItemIsUserCheckable
return Qt.ItemIsEnabled
def setData(self, index, value, role=Qt.EditRole):
if role == Qt.CheckStateRole:
row = index.row()
col = index.column()
data_index = row * self.columns_per_row + col
if data_index < len(self._data):
if value == Qt.Checked:
self.checked_rows.add(data_index)
else:
self.checked_rows.discard(data_index)
self.dataChanged.emit(index, index)
return True
return False
class MaterialTableModel(QAbstractTableModel):
def __init__(self, data, parent=None):
super().__init__(parent)
self._data = data
self.checked_rows = set()
self.columns_per_row = 20 # 每行显示20个药材
def rowCount(self, parent=QModelIndex()):
return (len(self._data) + self.columns_per_row - 1) // self.columns_per_row
def columnCount(self, parent=QModelIndex()):
return self.columns_per_row
def data(self, index, role=Qt.DisplayRole):
row = index.row()
col = index.column()
data_index = row * self.columns_per_row + col
if data_index >= len(self._data):
return None
if role == Qt.DisplayRole:
return self._data[data_index][1] # 返回药材名称
elif role == Qt.CheckStateRole:
return Qt.Checked if data_index in self.checked_rows else Qt.Unchecked
return None
def flags(self, index):
if index.isValid():
return Qt.ItemIsEnabled | Qt.ItemIsUserCheckable
return Qt.ItemIsEnabled
def setData(self, index, value, role=Qt.EditRole):
if role == Qt.CheckStateRole:
row = index.row()
col = index.column()
data_index = row * self.columns_per_row + col
if data_index < len(self._data):
if value == Qt.Checked:
self.checked_rows.add(data_index)
else:
self.checked_rows.discard(data_index)
self.dataChanged.emit(index, index)
return True
return False
class CombineSplitManager(QWidget):
def __init__(self, db, formula_manager, material_manager):
super().__init__()
self.db = db
self.formula_manager = formula_manager
self.material_manager = material_manager
self.selected_materials = set()
self.selected_formulas = set()
self.combined_ingredients = {}
# 缓存药方药材和名称信息
self.formula_data = {}
self.material_names = {}
self.init_ui()
self.material_manager.material_changed.connect(self.load_materials_to_table)
self.formula_manager.formula_changed.connect(self.load_all_formulas)
def init_ui(self):
layout = QVBoxLayout()
self.search_input = QLineEdit(placeholderText="输入药方或药材的名称,支持拼音或缩写快速搜索")
self.search_input.textChanged.connect(self.on_search_input_changed)
layout.addWidget(self.search_input)
# 药方表格
self.formula_table = QTableView()
self.formula_table.verticalHeader().setVisible(False)
self.formula_table.horizontalHeader().setVisible(False)
self.formula_table.setShowGrid(False)
self.formula_table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.formula_table.clicked.connect(self.on_formula_table_clicked)
self.formula_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
layout.addWidget(self.formula_table)
# 药材表格
self.combine_split_material_table = QTableView()
self.combine_split_material_table.verticalHeader().setVisible(False)
self.combine_split_material_table.horizontalHeader().setVisible(False)
self.combine_split_material_table.setShowGrid(False)
self.combine_split_material_table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.combine_split_material_table.clicked.connect(self.on_material_table_clicked)
self.combine_split_material_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
layout.addWidget(self.combine_split_material_table)
self.result_text = QTextEdit(readOnly=True, acceptRichText=True)
layout.addWidget(self.result_text)
btn_layout = QHBoxLayout()
self.save_button = QPushButton("保存结果", clicked=self.save_results)
self.clear_button = QPushButton("全部清除", clicked=self.clear_all_selections)
btn_layout.addStretch(1)
btn_layout.addWidget(self.save_button)
btn_layout.addWidget(self.clear_button)
layout.addLayout(btn_layout)
self.notification_label = QLabel('')
self.notification_label.setStyleSheet('color: red; padding: 5px; border: 1px solid #ddd; border-radius: 3px;')
self.notification_label.setAlignment(Qt.AlignCenter)
self.notification_label.setFixedHeight(30)
layout.addWidget(self.notification_label)
self.setLayout(layout)
self.load_all_formulas()
self.load_materials_to_table()
self.resizeEvent = self.on_resize
def on_resize(self, event):
self.formula_table.resizeColumnsToContents()
self.combine_split_material_table.resizeColumnsToContents()
def save_results(self):
text = BeautifulSoup(self.result_text.toHtml(), 'html.parser').get_text()
if not text.strip():
self.show_warning("没有可保存的结果")
return
file_name, _ = QFileDialog.getSaveFileName(self, "保存结果", "", "文本文件 (*.txt);;所有文件 (*)")
if not file_name:
return
if not file_name.endswith('.txt'):
file_name += '.txt'
try:
with open(file_name, 'w', encoding='utf-8') as f:
f.write(text)
self.show_warning(f"结果已保存到 {os.path.basename(file_name)}", is_warning=False)
self.open_file_location(file_name)
except Exception as e:
self.show_warning(f"保存失败: {str(e)}")
def open_file_location(self, file_path):
folder_path = os.path.dirname(file_path)
if os.name == 'nt':
os.startfile(folder_path)
elif os.name == 'posix':
subprocess.call(['open', folder_path])
def on_search_input_changed(self, text):
keywords = text.strip().lower().split()
pinyin_cache = {}
keywords = set(keywords + [''.join(pinyin_cache.setdefault(k, pypinyin.lazy_pinyin(k))[0] for k in keywords)])
self.update_table_visibility(self.formula_table, keywords, pinyin_cache)
self.update_table_visibility(self.combine_split_material_table, keywords, pinyin_cache)
def update_table_visibility(self, table, keywords, pinyin_cache):
model = table.model()
for row in range(model.rowCount()):
text = model.data(model.index(row, 0)).lower()
pinyin_text = ''.join(pinyin_cache.setdefault(text, pypinyin.lazy_pinyin(text)))
pinyin_initials = ''.join(p[0] for p in pinyin_cache.setdefault(text, pypinyin.lazy_pinyin(text)))
match = any(k in text or k in pinyin_text or k in pinyin_initials for k in keywords)
table.setRowHidden(row, not match)
def load_all_formulas(self):
self.formula_data.clear()
self.formula_data = {
formula_id: {
'name': formula_name,
'materials': {ing[0] for ing in json.loads(ingredients)},
'ingredients': json.loads(ingredients)
}
for formula_id, formula_name, ingredients in self.db.fetch_all('SELECT id, name, ingredients FROM Formulas ORDER BY id')
}
self.formula_table_model = FormulaTableModel([(formula_id, data['name']) for formula_id, data in self.formula_data.items()], self)
self.formula_table.setModel(self.formula_table_model)
def clear_all_selections(self):
self.selected_formulas.clear()
self.selected_materials.clear()
self.combined_ingredients.clear()
self.reset_table_selections(self.formula_table)
self.reset_table_selections(self.combine_split_material_table)
self.result_text.setText('')
self.show_warning("已清除所有选择")
def on_formula_table_clicked(self, index):
row = index.row()
col = index.column()
data_index = row * self.formula_table_model.columns_per_row + col
if data_index < len(self.formula_table_model._data):
formula_id = self.formula_table_model._data[data_index][0]
if data_index in self.formula_table_model.checked_rows:
self.formula_table_model.setData(index, Qt.Unchecked, Qt.CheckStateRole)
self.deselect_formula(formula_id)
else:
self.formula_table_model.setData(index, Qt.Checked, Qt.CheckStateRole)
self.select_formula(formula_id)
def select_formula(self, formula_id):
if formula_id in self.selected_formulas or any(self.is_subset(formula_id, f) for f in self.selected_formulas):
return True if formula_id in self.selected_formulas else (self.show_warning("该药方是已选药方的子集,无法添加。") or False)
new_selected_formulas = self.selected_formulas - {f for f in self.selected_formulas if self.is_subset(f, formula_id)} | {formula_id}
new_selected_materials = self.selected_materials | self.get_formula_materials(formula_id)
self.selected_formulas = new_selected_formulas
self.selected_materials = new_selected_materials
self.update_combined_ingredients_from_formulas(new_selected_formulas)
self.update_formula_selections()
self.update_table_selections(self.combine_split_material_table, new_selected_materials, True, False)
self.update_results()
return True
def update_table_selections(self, table, items_to_update, checked=True, force=True):
model = table.model()
for row in range(model.rowCount()):
for col in range(model.columnCount()):
data_index = row * model.columns_per_row + col
if data_index < len(model._data):
item_id = model._data[data_index][0]
if item_id in items_to_update:
model.setData(model.index(row, col), Qt.Checked if checked else Qt.Unchecked, Qt.CheckStateRole)
def deselect_formula(self, formula_id):
if formula_id not in self.selected_formulas:
return True
supersets = [f for f in self.selected_formulas if self.is_subset(formula_id, f)]
if supersets:
return self.show_warning(f"无法取消该药方,因为它是以下药方的子集:{', '.join(self.get_formula_name(f) for f in supersets)}") or False
formula_materials = self.get_formula_materials(formula_id)
subsets = [f for f in self.selected_formulas if self.is_subset(f, formula_id)]
subset_materials = set().union(*(self.get_formula_materials(f) for f in subsets))
if subset_materials == formula_materials:
formulas_to_remove = set(subsets) | {formula_id}
materials_to_remove = formula_materials
else:
formulas_to_remove = {formula_id}
materials_to_remove = formula_materials - subset_materials
self.selected_formulas -= formulas_to_remove
self.selected_materials -= {m for m in materials_to_remove if m not in self.get_materials_from_formulas(self.selected_formulas)}
self.update_combined_ingredients_from_formulas(self.selected_formulas)
self.update_formula_selections()
self.update_table_selections(self.combine_split_material_table, materials_to_remove, False)
self.update_results()
return True
def update_formula_selections(self):
for row in range(self.formula_table_model.rowCount()):
self.formula_table.setRowHidden(row, False)
for row in range(self.formula_table_model.rowCount()):
for col in range(self.formula_table_model.columnCount()):
data_index = row * self.formula_table_model.columns_per_row + col
if data_index >= len(self.formula_data):
continue
formula_id = list(self.formula_data.keys())[data_index]
is_selected = formula_id in self.selected_formulas
is_subset = any(self.is_subset(formula_id, f) for f in self.selected_formulas if f != formula_id)
self.formula_table_model.setData(
self.formula_table_model.index(row, col),
Qt.Checked if is_selected else Qt.Unchecked,
Qt.CheckStateRole
)
self.formula_table.setRowHidden(row, is_subset and not is_selected)
def on_material_table_clicked(self, index):
row = index.row()
col = index.column()
data_index = row * self.material_table_model.columns_per_row + col
if data_index < len(self.material_table_model._data):
# 获取 material_id
material_id = self.material_table_model._data[data_index][0]
# 手动切换复选框状态
if data_index in self.material_table_model.checked_rows:
self.material_table_model.setData(index, Qt.Unchecked, Qt.CheckStateRole)
self.deselect_material(material_id)
else:
self.material_table_model.setData(index, Qt.Checked, Qt.CheckStateRole)
self.select_material(material_id)
def select_material(self, material_id):
self.selected_materials.add(material_id)
new_selected_formulas = self.get_formulas_from_materials(self.selected_materials)
self.update_table_selections(self.formula_table, new_selected_formulas - self.selected_formulas, True)
self.selected_formulas = new_selected_formulas
self.update_combined_ingredients_from_formulas(self.selected_formulas)
self.update_results()
def deselect_material(self, material_id):
self.selected_materials.discard(material_id)
new_selected_formulas = self.get_formulas_from_materials(self.selected_materials)
self.update_table_selections(self.formula_table, self.selected_formulas - new_selected_formulas, False)
self.selected_formulas = new_selected_formulas
self.update_combined_ingredients_from_formulas(self.selected_formulas)
self.update_results()
def load_materials_to_table(self):
self.material_names.clear()
self.material_names = {
material_id: material_name
for material_id, material_name in self.db.fetch_all('SELECT id, name FROM Materials ORDER BY id')
}
self.material_table_model = MaterialTableModel(list(self.material_names.items()), self)
self.combine_split_material_table.setModel(self.material_table_model)
def reset_table_selections(self, table):
model = table.model()
model.checked_rows.clear()
model.dataChanged.emit(
model.index(0, 0),
model.index(model.rowCount() - 1, model.columnCount() - 1)
)
def get_formula_materials(self, formula_id):
return self.formula_data.get(formula_id, {}).get('materials', set())
def get_formula_ingredients(self, formula_id):
return self.formula_data.get(formula_id, {}).get('ingredients', [])
def get_materials_from_formulas(self, formula_ids):
return set().union(*(self.get_formula_materials(formula_id) for formula_id in formula_ids))
def get_formulas_from_materials(self, material_ids):
return {formula_id for formula_id, formula_data in self.formula_data.items() if formula_data['materials'].issubset(material_ids)}
def update_combined_ingredients(self, new_ingredients):
for ing_id, dosage in new_ingredients:
self.combined_ingredients[ing_id] = max(self.combined_ingredients.get(ing_id, 0), float(dosage))
def update_combined_ingredients_from_formulas(self, formula_ids):
self.combined_ingredients = {}
for formula_id in formula_ids:
if not any(self.is_subset(formula_id, other_id) for other_id in formula_ids if other_id != formula_id):
self.update_combined_ingredients(self.get_formula_ingredients(formula_id))
def is_subset(self, formula_id1, formula_id2):
materials1 = self.get_formula_materials(formula_id1)
materials2 = self.get_formula_materials(formula_id2)
return materials1.issubset(materials2) and materials1 != materials2
def show_warning(self, message, is_warning=True):
self.notification_label.setText(message)
self.notification_label.setStyleSheet(f'color: {"red" if is_warning else "green"}; padding: 5px; border: 1px solid #ddd; border-radius: 3px;')
QTimer.singleShot(5000, self.clear_warning)
def clear_warning(self):
self.notification_label.clear()
def update_results(self):
selected_materials = [(mid, self.material_names.get(mid, "未知药材")) for mid in self.selected_materials]
self.update_combined_ingredients_from_formulas(self.selected_formulas)
matching_formulas = self.find_matching_formulas(self.selected_materials)
result = self.format_results(selected_materials, self.combined_ingredients, matching_formulas, self.selected_formulas)
self.result_text.setHtml(result)
self.save_button.setEnabled(bool(result.strip()))
def find_matching_formulas(self, selected_material_ids):
return [(formula_id, formula_data['name'], json.dumps(formula_data['ingredients']))
for formula_id, formula_data in self.formula_data.items()
if formula_data['materials'].issubset(selected_material_ids)]
def format_results(self, selected_materials, combined_ingredients, matching_formulas, selected_formulas):
result = "<p>您选择的药材共计 {} 味:".format(len(selected_materials))
combined_material_ids = set(combined_ingredients.keys())
in_result = ['<span style="color: green;">{}</span>'.format(material_name) for material_id, material_name in selected_materials if material_id in combined_material_ids]
not_in_result = ['<span style="color: red;">{}</span>'.format(material_name) for material_id, material_name in selected_materials if material_id not in combined_material_ids]
result += ' '.join(in_result)
if not_in_result:
result += ' ({})'.format('、'.join(not_in_result))
result += '</p><p><small>(上方括号中的药材未在合方中。)</small></p>'
result += "<p>包含的药方组合共计 {} 个:</p>".format(len(matching_formulas))
for formula_id, formula_name, ingredients in matching_formulas:
is_subset = any(self.is_subset(formula_id, other_id) for other_id in selected_formulas if other_id != formula_id)
result += "<p>{}{}: ".format(formula_name, " (子集)" if is_subset else "")
ingredients = json.loads(ingredients)
for ing_id, dosage in ingredients:
result += '{}: {} '.format(self.material_names.get(ing_id, "未知药材"), dosage)
result += "</p>"
result += "<p>合方结果:</p>"
total_ingredients = len(combined_ingredients)
result += "<p>共计 {} 味:".format(total_ingredients)
result += ' '.join(['<span style="color: green;">{}</span>: <span style="color: orange;">{}</span>'.format(self.material_names.get(material_id, "未知药材"), dosage) for material_id, dosage in combined_ingredients.items()]) + "</p>"
subset_formulas = {formula_id for formula_id in selected_formulas if any(self.is_subset(formula_id, other_id) for other_id in selected_formulas if other_id != formula_id)}
if subset_formulas:
result += "<p><small>注意:以下药方是其他药方的子集,其药材未参与最终合方结果的计算:</small></p>"
for formula_id in subset_formulas:
result += f"<p><small>- {self.get_formula_name(formula_id)}</small></p>"
return result
def get_formula_name(self, formula_id):
return self.formula_data.get(formula_id, {}).get('name', "未知药方")
在更新药方选择状态时,我们不再隐藏子集药方,所有药方均保持可见状态,且其勾选状态仅受用户手动操作影响。
def update_formula_selections(self):
# 确保所有行都显示
for row in range(self.formula_table_model.rowCount()):
self.formula_table.setRowHidden(row, False)
# 根据选择状态更新复选框
for row in range(self.formula_table_model.rowCount()):
for col in range(self.formula_table_model.columnCount()):
data_index = row * self.formula_table_model.columns_per_row + col
if data_index >= len(self.formula_data):
continue
formula_id = list(self.formula_data.keys())[data_index]
is_selected = formula_id in self.selected_formulas
self.formula_table_model.setData(
self.formula_table_model.index(row, col),
Qt.Checked if is_selected else Qt.Unchecked,
Qt.CheckStateRole
)
on_formula_table_clicked 方法这个方法已经处理了点击表格时的选择和取消选择操作,所以不需要进一步修改。
通过上述修改,选择一个药方时,其子集药方将保持原样,不会被自动勾选或隐藏。所有药方的选择或取消选择完全由用户手动控制。
所有药方都会显示在表格中,并且用户可以自由选择或取消选择任何药方,而不会因为选择父级药方而影响其子集药方的状态。
通过这些修改,您可以实现更灵活的药方选择逻辑,用户可以根据需要手动选择或取消选择药方,而不会因为选择一个药方而影响到其他药方的状态。这种方式提高了用户的控制能力,避免了因自动勾选子集药方而导致的困惑。