I'm trying to display data from a MySQL database in a table with the help of TableView
component of QML.
Initially I tried making a QSqlQueryModel
object from a QSqlQuery
object and pass it to QML context as a property. But I came to know from Qt documentation that I must implement roleNames()
to supply column to role mapping to TableView
, so I subclassed QSqlQueryModel
like so
import sys
from PyQt5.QtCore import QUrl, Qt
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQuick import QQuickView
from PyQt5.QtSql import QSqlDatabase, QSqlQuery, QSqlQueryModel
class QtTabModel(QSqlQueryModel):
def __init__(self):
super(QtTabModel, self).__init__()
@staticmethod
def roleNames():
roles = {
Qt.UserRole + 1 : "id",
Qt.UserRole + 2 : "name"
}
return roles
app = QGuiApplication(sys.argv)
view = QQuickView()
db = QSqlDatabase.addDatabase("QMYSQL")
db.setHostName("localhost")
db.setDatabaseName("qtdb")
db.setUserName("abc")
db.setPassword("xyz")
qry = QSqlQuery()
if db.open():
qry = db.exec("SELECT id, name FROM qttab")
tabmodel = QtTabModel()
tabmodel.setQuery(qry)
ctx = view.rootContext()
ctx.setContextProperty("tabmodel", tabmodel)
view.setSource(QUrl.fromLocalFile("sqltabletest.qml"))
view.show()
app.exec()
and my QML is
import QtQuick 2.2
import QtQuick.Controls 1.1
TableView {
width: 200
height: 300
model: tabmodel
}
but it's showing nothing, just a blank window
I can see my QSqlQuery
is working as I can print data from database using value(n)
method from that query. I've also checked with making rolenames()
member function, but the end result is same.
def roleNames(self):
roles = {
Qt.UserRole + 1 : "id",
Qt.UserRole + 2 : "name"
}
return roles
Update:
QSqlQueryModel
works with widget classes, I've tested it with QTableView
widget. But I need to make it work with QML.
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QTableView
from PyQt5.QtSql import QSqlDatabase, QSqlQuery, QSqlQueryModel
app = QApplication(sys.argv)
db = QSqlDatabase.addDatabase("QMYSQL")
db.setHostName("localhost")
db.setDatabaseName("qtdb")
db.setUserName("abc")
db.setPassword("xyz")
qry = QSqlQuery()
if db.open():
qry = db.exec("SELECT id, name FROM qttab")
tabmodel = QSqlQueryModel()
tabmodel.setQuery(qry)
tabmodel.setHeaderData(0, Qt.Horizontal, "ID")
tabmodel.setHeaderData(1, Qt.Horizontal, "Name")
tabview = QTableView()
tabview.setModel(tabmodel)
tabview.show()
db.close()
app.exec()
Can anyone please help me to resolve this issue? Thanks in advance.