在C++ QT中使用QTableWidget显示 access表中 数据
时间: 2024-06-13 17:06:08 浏览: 16
以下是在C++ QT中使用QTableWidget显示access表中数据的示例代码:
```cpp
// 首先需要包含QTableWidget和QTableWidgetItem的头文件
#include <QTableWidget>
#include <QTableWidgetItem>
// 创建QTableWidget对象
QTableWidget *tableWidget = new QTableWidget(this);
// 打开access数据库
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
db.setDatabaseName("DRIVER={Microsoft Access Driver (*.mdb)};FIL={MS Access};DBQ=your_database_path");
if (!db.open()) {
qDebug() << "Failed to open database.";
return;
}
// 执行SQL查询语句
QSqlQuery query;
query.exec("SELECT * FROM your_table_name");
// 设置表格行数和列数
tableWidget->setRowCount(query.size());
tableWidget->setColumnCount(query.record().count());
// 遍历查询结果,将数据添加到表格中
int row = 0;
while (query.next()) {
for (int column = 0; column < query.record().count(); column++) {
QTableWidgetItem *item = new QTableWidgetItem(query.value(column).toString());
tableWidget->setItem(row, column, item);
}
row++;
}
// 显示表格
tableWidget->show();
```
需要注意的是,这里使用了QSqlDatabase和QSqlQuery来连接和查询access数据库,因此需要在.pro文件中添加以下语句:
```
QT += sql
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)