首页 > 解决方案 > 如何将数据库的内容显示到 QListWidget

问题描述

我想知道如何将标题和 ID 从数据库显示到 QListWidget 中。该 ID 将不可见,但当单击该项目时,它必须能够使用该 ID 搜索数据库以获取更多信息。

{我在 Qt 和 SQLite3 中使用 c++ 作为数据库。}

标签: c++sqliteqt

解决方案


建议使用 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();
}

推荐阅读