在尝试QSQLITE
在 QML 中显示表中的数据时,TableView
我偶然发现了这个答案并试图跟进它。我理解重新实施的必要性,data()
但是roleNames()
当涉及到QVariant
PySide2 中不存在的问题时,我遇到了问题。我明白了NameError: name 'QVariant' is not defined
。我已经测试了从数据库读取数据,它的工作。是否有任何数据类型可以代替QVariant
PySide2 使用?我的计划是拥有来自不同表的多个数据源。这个例子使用setContextProperty
,在这种情况下使用是更好的做法qmlRegisterType
吗?
文件夹结构
├── ViewModel
│ └── QCond.py
├── Qml
│ └── Modellist.qml
└── qmlengine.py
qmlengine.py
import os
import sys
from PySide2.QtCore import QUrl, QStringListModel, QCoreApplication, Qt
from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine, qmlRegisterType
from PySide2.QtSql import QSqlDatabase, QSqlQuery, QSqlQueryModel
from ViewModel.QCond import *
if __name__ == "__main__":
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
db = QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName("C:\\Users\\terao\\Documents\\ctmd\\CatData.db")
db.open()
qry = QSqlQuery()
qry=db.exec_("SELECT tip,s FROM uzad")
tabmodel = QtCond()
tabmodel.setQuery(qry)
engine.rootContext().setContextProperty("tabmodel", tabmodel)
engine.load(QUrl.fromLocalFile('Qml/Modellist.qml'))
if not engine.rootObjects():
sys.exit(-2)
sys.exit(app.exec_())
QCond.py
import sys
from PySide2 import QtCore, QtGui, QtQml
from PySide2.QtCore import QObject, Qt,Signal, Slot, QUrl, QStringListModel, QCoreApplication
import sqlite3
from PySide2.QtSql import QSqlDatabase, QSqlQuery, QSqlQueryModel
class QtCond(QSqlQueryModel):
def __init__(self):
super(QtCond, self).__init__()
def roleNames(self):
roles = {
Qt.UserRole + 1 : 'tip',
Qt.UserRole + 2 : 's'
}
return roles
def data(self, index, role):
if role < Qt.UserRole:
# caller requests non-UserRole data, just pass to papa
return super(QtTabModel, self).data(index, role)
任何帮助表示赞赏。提前致谢。
MMTTMM
相关分类