from PyQt5 import QtWidgets from PyQt5.QtCore import Qt import db.tasks import gui.tasks.signal import gui.tasks.table.menu import gui.tasks.table.model import gui.tasks.dialog from model.task import Task, ValidTaskForm class Widget(QtWidgets.QTableView): def __init__(self, database, parent, add_task_signal): super().__init__(parent) self._database = database self._update_task_signal = gui.tasks.signal.UpdateTask() tasks = db.tasks.get(self._database.cursor()) table_model = gui.tasks.table.model.TableModel(tasks) self.setModel(table_model) self.sortByColumn( gui.tasks.table.model.default_sort[0], gui.tasks.table.model.default_sort[1]) self.setSortingEnabled(True) self.setSelectionBehavior(QtWidgets.QTableView.SelectRows) self.horizontalHeader().setStretchLastSection(True) self.resizeColumns() self.doubleClicked.connect(lambda index: self.on_double_click(index.row())) # Menu self.setContextMenuPolicy(Qt.CustomContextMenu) self.customContextMenuRequested.connect(lambda position: gui.tasks.table.menu.open(self._database, self, self._update_task_signal, position)) add_task_signal.get().connect(lambda task: self.insert(task)) self._update_task_signal.get().connect(lambda row, task: self.update(row, task)) def insert(self, task): self.model().insert_task(self.horizontalHeader(), task) self.resizeColumns() def update(self, row, task): row = self.model().update_task(self.horizontalHeader(), row, task) self.selectRow(row) self.resizeColumns() def resizeColumns(self): for column in range(gui.tasks.table.model.columns): self.resizeColumnToContents(column) def keyPressEvent(self, event): super().keyPressEvent(event) if event.key() in (Qt.Key_Return, Qt.Key_Enter): rows = self.get_selected_rows() if len(rows) == 1: row = rows[0] task = self.model().get_at(row) gui.tasks.dialog.update( self._database, self, self._update_task_signal, row, task).exec_() elif event.key() == Qt.Key_Delete: rows = self.get_selected_rows() gui.tasks.dialog.show_delete(self._database, self, rows) def get_selected_rows(self): return list(set([index.row() for index in self.selectedIndexes()])) def on_double_click(self, row: int): task = self.model().get_at(row) gui.tasks.dialog.update(self._database, self, self._update_task_signal, row, task).exec_()