Qt 重写QSqlTableModel类定义UserRole在qml 的 tableview中显示数据
要在QML的TableView中显示QSqlTableModel中的数据,你需要在QML文件中使用一个QAbstractItemModel来连接到QSqlTableModel,并将其设置为TableView的model。
下面是一个示例代码,演示如何在QML的TableView中显示QSqlTableModel的数据:
- 创建一个自定义的QAbstractItemModel类,让它继承自QSqlTableModel,并重新实现data()、rowCount()和columnCount()方法:
class UserModel : public QSqlTableModel
{
Q_OBJECT
public:
explicit UserModel(QObject *parent = nullptr, QSqlDatabase db = QSqlDatabase());
QVariant data(const QModelIndex &index, int role) const override;
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const override;
};
- 在实现文件中,重新实现这些方法:
UserModel::UserModel(QObject *parent, QSqlDatabase db)
: QSqlTableModel(parent, db)
{
setTable("users"); // 设置表名
select(); // 选择数据
}
QVariant UserModel::data(const QModelIndex &index, int role) const
{
if (role == Qt::DisplayRole) {
// 返回数据
return QSqlTableModel::data(index, role);
}
return QVariant();
}
int UserModel::rowCount(const QModelIndex &parent) const
{
// 返回行数
return QSqlTableModel::rowCount(parent);
}
int UserModel::columnCount(const QModelIndex &parent) const
{
// 返回列数
return QSqlTableModel::columnCount(parent);
}
- 在QML文件中,创建一个TableView,并将其model属性设置为我们刚刚创建的Model:
import QtQuick 2.15
import QtQuick.Controls 2.15
TableView {
id: tableView
anchors.fill: parent
model: userModel
TableViewColumn {
role: "username"
title: "Username"
width: tableView.width / 3
}
TableViewColumn {
role: "password"
title: "Password"
width: tableView.width / 3
}
TableViewColumn {
role: "role"
title: "Role"
width: tableView.width / 3
}
}
- 在C++代码中,创建一个QGuiApplication,并在其main函数中创建一个QQmlApplicationEngine,将QAbstractItemModel作为上下文属性传递给QML引擎:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QSqlDatabase>
#include <QSqlTableModel>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
// 连接到数据库
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("path/to/database.db");
db.open();
// 创建Model
UserModel userModel;
// 创建引擎
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("userModel", &userModel);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
这样就可以在QML的TableView中显示QSqlTableModel中的数据了。你可以根据需要调整Model和QML中的列定义和样式
原文地址: http://www.cveoy.top/t/topic/hWJM 著作权归作者所有。请勿转载和采集!