gpt4 book ai didi

c++ - 如何填充数据库sqlite tablewidget

转载 作者:行者123 更新时间:2023-11-30 05:33:43 26 4
gpt4 key购买 nike

我正在编写“SQLite”数据库并且我创建了这样的数据库表:

void MainWindow::createdata()
{
QSqlQuery query;
query.exec("DROP TABLE messages");
query.exec("CREATE TABLE messages("
"id INTEGER PRIMARY KEY AUTOINCREMENT,"
"IPAddress VARCHAR(20),"
"date VARCHAR(10),"
"message VARCHAR(30))");

query.prepare("INSERT INTO messages(IPAddress, date, message) values(?,?,?)");
query.addBindValue("192.168.1.1");
query.addBindValue("jun 3 2016");
query.addBindValue("hello");

if (query.exec()) {
qDebug() << "ok!";
}
else
{
qDebug() << query.executedQuery();
qDebug() << query.lastError();
}
}

然后我像这样创建“qtablewidget”:

 QTableWidget* table = new QTableWidget();

table->setRowCount(10);
table->setColumnCount(4);
table->setWindowTitle("Received Message");
table->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
table->setHorizontalHeaderLabels(QString("ID;HostAddress;Date;Message").split(";"));
table->setStyleSheet("QTableView {selection-background-color: blue;}");
table->setEditTriggers(QAbstractItemView::NoEditTriggers);
table->setSelectionBehavior(QAbstractItemView::SelectRows);
table->setSelectionMode(QAbstractItemView::SingleSelection);


QSqlQuery query("SELECT * FROM messages");

但我不知道应该如何填充“tablewidget”以显示查询。谁能帮帮我?谢谢

最佳答案

您应该使用QTableView(基于模型的 TableView 版本),然后使用QSqlQueryModel,您可以填充您的表。

QSqlQueryModel *model = new QSqlQueryModel();
model->setQuery(query);
tableView->setModel(model);

要将 QSqlQueryModelQTableWidget 一起使用,您应该逐行遍历 QSqlQueryModel 并将它们添加到您的 QTableWidget.

QSqlQueryModel *model = new QSqlQueryModel();
model->setQuery(query);

int i;
QSqlRecord row
for(i = 0, row = model->record(i); !row.isEmpty(); i++, row = model->record(i)){
// Get each field using `value` method of variabale 'row'
// and insert this fields to its corresponding cell in QTableWidget
}

相关问题:

Setting the model to a QTableWidget

关于c++ - 如何填充数据库sqlite tablewidget,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34607288/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com