ARTICLE AD BOX
I'm developing an app using QSqlQueryModel and QListView. The below is a much simplified example for purpose of explaining my problem. When I run this, the ListView shows the correct number of items (4) but they're all blank, the print()'s in the data() method all show the values as None. Using the column numbers instead of the names gives the same result. Adding in a print(self.record(r).count()) shows the expected number of columns (3). If I open the database file in my database browser app, all the values are there. What am I doing wrong here?
I realised my example is more suited to QSqlTableModel so I changed the code to use that, but I get the same result.
from PyQt6.QtCore import Qt from PyQt6.QtWidgets import QApplication, QMainWindow, QListView from PyQt6.QtSql import QSqlDatabase, QSqlQuery, QSqlQueryModel, QSqlTableModel class ListModel(QSqlQueryModel): def __init__(self): super().__init__() self.setQuery("SELECT id, name, age FROM people") def data(self, index, role): r = index.row() if role == Qt.ItemDataRole.DisplayRole: v = self.record(r).value("name") print("row " + str(r) + " displayrole = " + str(v)) return v elif role == Qt.ItemDataRole.ToolTipRole: v = self.record(r).value("age") print("row " + str(r) + " tooltiprole = " + str(v)) return v class ListView(QListView): def __init__(self): super().__init__() self.model = ListModel() self.setModel(self.model) class ListWindow(QMainWindow): def __init__(self): super().__init__() self.resize(300,300) self.list = ListView() self.setCentralWidget(self.list) if __name__ == "__main__": con = QSqlDatabase.addDatabase("QSQLITE") con.setDatabaseName("test.db") con.open() query = QSqlQuery() query.exec("CREATE TABLE IF NOT EXISTS people (id INTEGER, name TEXT, age INTEGER, PRIMARY KEY(id AUTOINCREMENT))") query.exec("DELETE FROM people") query.exec("INSERT INTO people (name, age) VALUES ('Bob', 42), ('Sue', 38), ('Steve', 21), ('Wendy', 50)") app = QApplication([]) win = ListWindow() win.show() app.exec()If I comment out the data() method and add self.setModelColumn(1) to the ListView.__init__, the list is populated with the names, so my database and connection do work (but I can't get the tooltips and do the other stuff I'm doing in my real code).
I originally wrote the data() method as below:
def data(self, index, role): r = index.row() rec = self.record(r) if role == Qt.ItemDataRole.DisplayRole: v = rec.value("name") print("row " + str(r) + " displayrole = " + str(v)) return v elif role == Qt.ItemDataRole.ToolTipRole: v = rec.value("age") print("row " + str(r) + " tooltiprole = " + str(v)) return vbut when I ran this I got endless repeating RecursionError's. Why is this?
