There is a program that adds an OrCAD project. The main code of the program is main.py The program has an “Editing” section, which changes the project by adding or removing indexes by the user. The section has a “Cancel” button, which deletes the index added or adds the index deleted by the user. The function only works on the added one, but not on the deleted one. Everything is done through RAWData.py. Here’s the code.
def addRecord(self):
selection_model = self.tree_view.selectionModel()
selected_indexes = selection_model.selectedIndexes()
# Определяем родительскую группу выделенной строки
parent_index = selected_indexes[0].parent()
# Создаем пустую строку для отображения в TreeView
empty_row = [QStandardItem('-') for _ in range(5)] # Определение переменной empty_row
parent_item = self.tree_model.itemFromIndex(parent_index)
row_position = selected_indexes[0].row() + 1
# Проверяем, есть ли уже такие элементы в дереве
existing_items = [parent_item.child(i) for i in range(parent_item.rowCount())]
if empty_row not in existing_items:
if row_position <= parent_item.rowCount(): # Проверяем, что позиция вставки превышает количество элементов в родительском элементе
parent_item.insertRow(row_position, empty_row)
# Сохраняем информацию о последней добавленной записи
self.last_added_index = (parent_item, row_position)
# Обновляем представление (TreeView) с новой строкой
self.tree_view.setModel(self.tree_model)
# Если операция добавления прошла успешно, добавляем действие в стек отмены
self.undo_stack.append(('add', parent_item, row_position, empty_row.copy())) # Создаем копию empty_row
else:
print("Ошибка: Позиция вставки превышает количество элементов в родительском элементе.")
else:
print("Ошибка: Пустая строка уже существует в данной группе.")
class_part = parent_item.text()
if self.query.exec(f"INSERT INTO RAWDATA (ClassPart, PartReference, ManufacturerPartNumber, Manufacturer, Quantity, Description) VALUES ('{class_part}', '-', '-', '-', '-', '-')"):
print("Data add successfully")
if self.query.exec(
f"UPDATE RAWDATA SET PartReference = '-', ManufacturerPartNumber = '-', Manufacturer = '-', Quantity = '-', Description = '-' WHERE ClassPart = '{class_part}' AND PartReference = '-' AND ManufacturerPartNumber = '-'"):
print("Data updated successfully")
else:
print("Ошибка выполнения запроса:", self.query.lastError().text())
else:
print("Ошибка выполнения запроса:", self.query.lastError().text())
def delRecord(self):
selection_model = self.tree_view.selectionModel()
selected_indexes = selection_model.selectedIndexes()
rows_to_remove = []
values_to_remove = []
parent_values = []
for index in selected_indexes:
row = index.row()
if row not in rows_to_remove:
rows_to_remove.append(row)
item = self.tree_model.itemFromIndex(index)
value = item.text()
if index.column() < 2:
values_to_remove.append(value)
print(value)
for row in sorted(rows_to_remove, reverse=True):
parent_index = selected_indexes[0].parent()
parent_item = self.tree_model.itemFromIndex(parent_index)
parent_text = parent_item.text()
parent_values.append(parent_text)
self.tree_model.removeRow(row, parent_index)
print(parent_text)
print(row)
x = 0
for i in range((len(values_to_remove))//2):
print(temp_value)
if temp_value == 'product1':
if self.query.exec(f"DELETE FROM RAWDATA WHERE PartReference = '{values_to_remove[x]}' AND ManufacturerPartNumber = '{values_to_remove[x+1]}'"):
print("Data updated successfully")
else:
print("Ошибка выполнения запроса:", self.query.lastError().text())
elif temp_value == 'product2':
if self.query.exec(f"DELETE FROM RAWDATA WHERE ClassPart = '{values_to_remove[x]}' AND ManufacturerPartNumber = '{values_to_remove[x + 1]}' AND PartReference = '{parent_values[(x//2)]}'"):
print("Data updated successfully")
else:
print("Ошибка выполнения запроса:", self.query.lastError().text())
elif temp_value == 'product4':
if self.query.exec(f"DELETE FROM RAWDATA WHERE ClassPart = '{values_to_remove[x]}' AND PartReference = '{values_to_remove[x + 1]}'"):
print("Data updated successfully")
else:
print("Ошибка выполнения запроса:", self.query.lastError().text())
x = x + 2
self.tree_model.submit()
self.tree_view.setModel(self.tree_model)
def Cancel(self):
try:
if hasattr(self, 'undo_stack') and self.undo_stack:
# Получаем все действия из стека отмены
actions_to_undo = list(reversed(self.undo_stack))
print("Действия для отмены:", actions_to_undo) # Выводим содержимое стека отмены для отладки
for action, parent_item, row_position, removed_row in actions_to_undo:
if action == 'add':
parent_item.removeRow(row_position)
print("Добавление элемента отменено.")
elif action == 'del':
# Получаем родительский индекс и вставляем удаленную строку
self.tree_model.insertRow(row_position, removed_row)
print("Удаление элемента отменено.")
print("Содержимое стека отмены перед очисткой:", self.undo_stack)
self.undo_stack.clear() # Очищаем стек отмены
self.tree_model.layoutChanged.emit()
else:
print("Отмененное действие не найдено в стеке отмены.")
except Exception as e:
print("Ошибка при отмене:", e)
I kindly ask you to help me with this problem. It is necessary that the “Cancel” button cancels all actions performed by the user.