Hi @SGaist,
I had some problems to adapt the wiki article to PySide6.
I endet up with following model implementation:
class SqlQueryModel(QSqlQueryModel):
def __init__(self, parent=None):
super().__init__(parent)
self._roleNames = {}
def setQuery(self, query: str, db: QSqlDatabase):
super().setQuery(query, db)
self.generateRoleNames()
def generateRoleNames(self):
self._roleNames = {}
for i in range(super().record().count()):
self._roleNames[QtCore.Qt.UserRole + i + 1] = super().record().fieldName(i)
print(f"generateRoleNames produced: {self._roleNames =}")
def data(self, index:QModelIndex, role: int = ...):
print(f"data called with {index = }, {role = }")
if role < QtCore.Qt.UserRole:
print("if here")
if not self.query().exec():
print("Error while executing", self.query().lastError().text())
i: int =0
while self.query().next():
data = self.query().value(index.column())
if i == index.row(): break
i +=1
else:
print("else here")
columnIdx = role - QtCore.Qt.UserRole - 1
modelIndex = self.index(index.row(), columnIdx)
data = super().data(modelIndex, QtCore.Qt.DisplayRole)
print(f"fetched data: {data =} ")
return data
I have to say, that I still see no data in my ListView. But since the data function is not called when my StackLayout loads the view the issue might not necessary related to QSqlQueryModel.
My connect method from controller:
def connect(self, db_name, user, password):
if any([db_name == "", user == "", password == ""]):
self.loginSuccess.emit(False)
return
db_file = Path(__file__).resolve().parent.parent / 'data' / f"{db_name}.sqlite"
connection: QSqlDatabase = QSqlDatabase.addDatabase("QSQLITE", db_name)
connection.setDatabaseName(str(db_file))
if not connection.open(user, password):
print("Error:", connection.lastError().text())
self.loginSuccess.emit(False)
return
if connection.isOpen():
self.db_name = db_name
self._topicmodel.setQuery(query="SELECT * FROM topics", db=connection)
self._topicmodel.query().prepare("SELECT * FROM topics")
print("0; 0: ", self._topicmodel.data(self._topicmodel.index(0,0), QtCore.Qt.DisplayRole))
print("0; 0: ", self._topicmodel.data(self._topicmodel.index(0,1), QtCore.Qt.DisplayRole))
self._topicmodel.setHeaderData(0, QtCore.Qt.Horizontal, "id")
self._topicmodel.setHeaderData(1, QtCore.Qt.Horizontal, "topic")
self.loginSuccess.emit(True)
else:
self.loginSuccess.emit(False)
If I don't call prepare() the return value of data is always None and exec(), isValid(), next(), result() are returning False.
I found this by trying each method of QSqlQuery().
I find this odd and would like you to ask how this could be refactored....