83 lines
3.3 KiB
Python
83 lines
3.3 KiB
Python
#modifie the QSqlQueryModel to be editable and sets them to the database
|
|
from PySide6.QtSql import QSqlQueryModel, QSqlQuery
|
|
from PySide6.QtCore import Qt
|
|
#credits to :
|
|
#https://stackoverflow.com/questions/49752388/editable-qtableview-of-complex-sql-query
|
|
|
|
|
|
class SqlQueryModel_editable(QSqlQueryModel):
|
|
"""a subclass of QSqlQueryModel where individual columns can be defined as editable
|
|
"""
|
|
def __init__(self, editables):
|
|
"""editables should be a dict of format:
|
|
{INT editable_column_nr : (STR update query to be performed when changes are made on this column
|
|
INT model's column number for the filter-column (used in the where-clause),
|
|
)}
|
|
"""
|
|
super().__init__()
|
|
self.editables = editables
|
|
self.updatelist = []
|
|
|
|
def flags(self, index):
|
|
fl = QSqlQueryModel.flags(self, index)
|
|
if index.column() in self.editables:
|
|
fl |= Qt.ItemIsEditable
|
|
return fl
|
|
|
|
def setData(self, index, value, role=Qt.EditRole):
|
|
print("role: ",role)
|
|
if role == Qt.EditRole:
|
|
mycolumn = index.column()
|
|
if mycolumn in self.editables:
|
|
(query, filter_col) = self.editables[mycolumn]
|
|
filter_value = self.index(index.row(), filter_col).data()
|
|
q = QSqlQuery(query.format(value, filter_value))
|
|
result = q.exec_()
|
|
if result:
|
|
self.query().exec_()
|
|
# print("filter_value:",filter_value)
|
|
print("setdata query: ",query.format(value, filter_value))
|
|
print("index.row:",index.row(), "filter_col:",filter_col)
|
|
else:
|
|
print(self.query().lastError().text())
|
|
return result
|
|
elif role == 1001:
|
|
result = 0
|
|
self.updatelist.append(value)
|
|
print(self.updatelist)
|
|
if len(self.updatelist) >= 5:
|
|
for x in self.updatelist:
|
|
print("Atempt flaging view")
|
|
q = QSqlQuery("UPDATE jobs SET viewed = '1' WHERE hash = {}".format(x))
|
|
print("QSQLQuery: ", "UPDATE jobs SET viewed = '1' WHERE hash = {}".format(x))
|
|
result = q.exec_()
|
|
if result:
|
|
self.query().exec_()
|
|
else:
|
|
print("Error:", self.query().lastError().text())
|
|
return result
|
|
self.updatelist = []
|
|
return result
|
|
self.dataChanged.emit(index-100,index+100)
|
|
self.layoutChanged.emit()
|
|
return QSqlQueryModel.setData(self, index, value, role)
|
|
|
|
|
|
# view = QTableView()
|
|
#
|
|
# editables = {1 : ("UPDATE Manufacturers SET Country = '{}' WHERE Company = '{}'", 2)}
|
|
# model = SqlQueryModel_editable(editables)
|
|
# query = '''
|
|
# SELECT (comp.company || " " || cars.model) as Car,
|
|
# comp.Country,
|
|
# cars.company,
|
|
# (CASE WHEN cars.Year > 2000 THEN 'yes' ELSE 'no' END) as this_century
|
|
# from manufacturers comp left join cars
|
|
# on comp.company = cars.company
|
|
# '''
|
|
# q = QSqlQuery(query)
|
|
# model.setQuery(q)
|
|
# model.setFilter("cars.Company = 'VW'")
|
|
# view.setModel(model)
|
|
# view.hideColumn(2)
|