qt引入txt文件,Qt——读入txt文件,写入到表格
时间: 2023-11-11 22:04:29 浏览: 70
首先需要使用Qt中的QFile类来打开文本文件,然后使用QTextStream类来读取文件内容。接着,我们可以将读取到的内容写入到Qt中的表格控件中。
以下是一个简单的示例代码:
```cpp
#include <QFile>
#include <QTextStream>
#include <QTableWidget>
void readTxtFile(QString filePath, QTableWidget *tableWidget)
{
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine();
QStringList fields = line.split('\t');
int row = tableWidget->rowCount();
tableWidget->insertRow(row);
for (int i = 0; i < fields.count(); ++i) {
QTableWidgetItem *item = new QTableWidgetItem(fields.at(i));
tableWidget->setItem(row, i, item);
}
}
file.close();
}
```
在上述代码中,我们将文本文件中的每一行作为一个字符串读入,并使用QStringList类的split()函数将其分割成字段。然后,我们使用QTableWidget类的insertRow()函数在表格中插入一行,并使用QTableWidgetItem类的构造函数创建每个单元格的内容。
使用该函数的示例代码如下:
```cpp
QString filePath = "path/to/your/file.txt";
QTableWidget *tableWidget = new QTableWidget();
readTxtFile(filePath, tableWidget);
```
这将打开名为“file.txt”的文本文件,并将其内容读入到一个新的QTableWidget对象中。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)