c++ - 如何将数据库的内容显示到 QListWidget
问题描述
我想知道如何将标题和 ID 从数据库显示到 QListWidget 中。该 ID 将不可见,但当单击该项目时,它必须能够使用该 ID 搜索数据库以获取更多信息。
{我在 Qt 和 SQLite3 中使用 c++ 作为数据库。}
解决方案
建议使用 QListView 和 QSqlTableModel 而不是使用 QListWidget,您可以使用 setModelColumn 方法指示要显示的列“标题”并使用 QSqlRecord 访问“id”:
#include <QtSql>
#include <QtWidgets>
static bool createConnection()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(":memory:");
if (!db.open()) {
QMessageBox::critical(nullptr, QObject::tr("Cannot open database"),
QObject::tr("Unable to establish a database connection.\n"
"This example needs SQLite support. Please read "
"the Qt SQL driver documentation for information how "
"to build it.\n\n"
"Click Cancel to exit."), QMessageBox::Cancel);
return false;
}
QSqlQuery query;
query.exec("CREATE TABLE mytable (id INTEGER PRIMARY KEY AUTOINCREMENT, title VARCHAR(20))");
query.exec("INSERT INTO mytable(title) VALUES('Title1')");
query.exec("INSERT INTO mytable(title) VALUES('Title2')");
query.exec("INSERT INTO mytable(title) VALUES('Title3')");
query.exec("INSERT INTO mytable(title) VALUES('Title4')");
query.exec("INSERT INTO mytable(title) VALUES('Title5')");
return true;
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
if(!createConnection())
return -1;
QSqlTableModel model;
model.setTable("mytable");
model.select();
QListView view;
view.setModel(&model);
view.setModelColumn(model.record().indexOf("title"));
QObject::connect(&view, &QAbstractItemView::clicked, [&model](const QModelIndex & index){
QSqlRecord rec = model.record(index.row());
qDebug() << rec.value("id").toInt();
});
view.resize(640, 480);
view.show();
return a.exec();
}
推荐阅读
- java - csv 文件在其中一个字段中有一个单双引号。例如:- 数据“列表
- c# - 使用 ado.net 实现 ODATA
- c# - 使用 FluentValidation 将 lambda 表达式作为方法参数传递
- r - 在服务器中使用 switchInput
- neo4j - 一个节点可以有两次属性吗?
- node.js - $size 在 MongoDB 中的条件
- java - 如何在 Java 中为 TreeMap 编写自定义比较器?
- javascript - 如何让 2d 字符在 JavaScript 中运行和跳跃
- ruby-on-rails - 遵循教程时不会显示 Link_to “Read Me”
- r - How to pass an input parameter for a UDF to sapply