Files
kontor/gui/table_model.py
T
2025-01-07 01:48:03 +01:00

86 lines
3.2 KiB
Python

from datetime import datetime
from PySide6.QtCore import QAbstractTableModel, QModelIndex
from PySide6.QtGui import Qt
from model_config import KontorModelConfig
class KontorTableModel(QAbstractTableModel):
def __init__(self, model_config: KontorModelConfig):
super().__init__()
self._main_window = model_config.main_window
self._config = model_config
self._data = None
def refresh(self):
data = []
cursor = self._config.db_conn.cursor()
cursor.execute(self._config.get_statement())
rows = cursor.fetchall()
# print(len(rows))
if len(rows) > 0:
self.beginResetModel()
for row in rows:
data.append(list(row))
self._data = data
self.endResetModel()
else:
self._data = None
self.layoutChanged.emit()
self._main_window.statusBar.showMessage(f"{len(rows)} Einträge geladen", 3000)
def rowCount(self, parent=QModelIndex()):
# The length of the outer list.
if self._data is None:
return 0
return len(self._data)
def headerData(self, col, orientation, role=Qt.ItemDataRole.DisplayRole):
if orientation == Qt.Orientation.Horizontal and role == Qt.ItemDataRole.DisplayRole:
return self._config.header[col]['column']
if orientation == Qt.Orientation.Vertical and role == Qt.ItemDataRole.DisplayRole:
return str(col+1)
def data(self, index, role=Qt.ItemDataRole.DisplayRole):
if self._data is None:
return None
value = self._data[index.row()][index.column()]
if role == Qt.ItemDataRole.DisplayRole:
# print('{}: {}'.format(value, type(value)))
if isinstance(value, datetime):
return value.strftime("%Y-%m-%d %M:%M:%S")
if isinstance(value, str):
return value
if isinstance(value, bytes):
if value == b'\x01':
return self._main_window.tick
else:
return self._main_window.cross
return str(value)
if role == Qt.ItemDataRole.DecorationRole:
if isinstance(value, bytes):
# print('{}: {}'.format(value, type(value)))
if value == b'\x01':
return self._main_window.tick
else:
return self._main_window.cross
def columnCount(self, index=QModelIndex()):
# The following takes the first sub-list, and returns
# the length (only works if all rows are an equal length)
# print(f"Header count: {len(self._config.get_header())}")
return len(self._config.header)
def setData(self, index, value, role=Qt.ItemDataRole.EditRole):
if role == Qt.ItemDataRole.EditRole:
self._data[index.row()][index.column()] = value
if role == Qt.ItemDataRole.CheckStateRole:
checked = value == Qt.CheckState.Checked
self._data[index.row()][index.column()] = checked
return True
def flags(self, index):
return Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsEditable | Qt.ItemFlag.ItemIsUserTristate