90 lines
3.3 KiB
Python
90 lines
3.3 KiB
Python
from datetime import datetime
|
|
|
|
import mariadb
|
|
from PySide6.QtCore import QAbstractTableModel, QModelIndex, Qt
|
|
from PySide6.QtGui import QColor
|
|
|
|
|
|
class ComicTableModel(QAbstractTableModel):
|
|
|
|
def __init__(self, db_config, main_window):
|
|
super().__init__()
|
|
self.main_window = main_window
|
|
self._data = []
|
|
self.status_bar = main_window.statusBar
|
|
self.mariadb_conn = mariadb.connect(
|
|
host=db_config['mariadb']['host'],
|
|
port=db_config['mariadb']['port'],
|
|
user=db_config['mariadb']['user'],
|
|
password=db_config['mariadb']['password'],
|
|
database=db_config['mariadb']['database']
|
|
)
|
|
self.refresh()
|
|
|
|
def refresh(self):
|
|
data = []
|
|
cursor = self.mariadb_conn.cursor()
|
|
cursor.execute("SELECT id, created_date, last_modified_date, title, publisher_id FROM comic")
|
|
rows = cursor.fetchall()
|
|
for row in rows:
|
|
data.append(list(row))
|
|
self.status_bar.showMessage(f"{len(rows)} Einträge geladen", 3000)
|
|
self._data = data
|
|
|
|
def rowCount(self, parent=QModelIndex()):
|
|
# The length of the outer list.
|
|
return len(self._data)
|
|
|
|
def headerData(self, col, orientation, role=Qt.ItemDataRole.DisplayRole):
|
|
if orientation == Qt.Orientation.Horizontal and role == Qt.ItemDataRole.DisplayRole:
|
|
match col:
|
|
case 0:
|
|
return "ID"
|
|
case 1:
|
|
return "Created"
|
|
case 2:
|
|
return "Updated"
|
|
case 3:
|
|
return "Title"
|
|
case 4:
|
|
return "Verlag"
|
|
if orientation == Qt.Orientation.Vertical and role == Qt.ItemDataRole.DisplayRole:
|
|
return str(col + 1)
|
|
|
|
def data(self, index, role=Qt.ItemDataRole.DisplayRole):
|
|
value = self._data[index.row()][index.column()]
|
|
if role == Qt.ItemDataRole.DisplayRole:
|
|
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 "True"
|
|
return "False"
|
|
return 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)
|
|
return len(self._data[0])
|
|
|
|
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
|