【问题标题】:How to display the content of a database into a QListWidget如何将数据库的内容显示到 QListWidget
【发布时间】:2021-01-09 02:59:30
【问题描述】:

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

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

【问题讨论】:

    标签: c++ sqlite qt


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2019-01-08
      • 1970-01-01
      • 2019-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多