QT中,实现读取txt文件的每一行,并存放在一个QStringList中,知道读取完全部的行
时间: 2024-03-11 15:49:42 浏览: 63
您可以使用以下代码实现:
```cpp
QStringList lines;
QFile file("file.txt");
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream stream(&file);
while (!stream.atEnd()) {
QString line = stream.readLine();
lines.append(line);
}
file.close();
}
```
以上代码将会打开名为“file.txt”的文件。然后,使用QTextStream读取每一行,并将其添加到QStringList中。最后,关闭文件。
相关问题
Qt中读取txt文件的每一行,用来实时更新QLineEdit中的内容
可以使用QFile和QTextStream来读取txt文件的每一行,并且在读取时更新QLineEdit中的内容。
下面是一个示例代码:
```cpp
QFile file("example.txt");
if(file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream stream(&file);
while(!stream.atEnd()) {
QString line = stream.readLine();
// 更新QLineEdit中的内容
ui->lineEdit->setText(line);
QCoreApplication::processEvents(); // 更新UI界面
}
file.close();
}
```
在这个示例代码中,我们首先打开一个名为“example.txt”的文件,并使用QTextStream读取每一行。
每读取一行,我们就将该行的内容更新到QLineEdit中,并通过QCoreApplication::processEvents()函数来实时更新UI界面。
需要注意的是,如果txt文件比较大,这种实时更新的方式可能会导致程序变慢,因此需要根据实际情况进行优化。
QT实现读取tablewidget中的每一行数据
可以使用以下代码实现读取 QTableWidget 中的每一行数据:
```cpp
int rowCount = tableWidget->rowCount();
for(int i=0; i<rowCount; i++){
QStringList rowData;
for(int j=0; j<tableWidget->columnCount(); j++){
QTableWidgetItem *item = tableWidget->item(i, j);
if(item){
QString text = item->text();
rowData.append(text);
}
}
// do something with the rowData, such as print it out or save it to a file
}
```
这里的 `tableWidget` 是 QTableWidget 对象,可以通过 `rowCount()` 方法获取表格的行数。然后在一个外层循环中遍历每一行,使用一个 QStringList 对象 `rowData` 存储当前行的数据。在一个内层循环中遍历当前行的每一列,获取单元格中的文本,然后将其添加到 `rowData` 中。最后可以对 `rowData` 进行处理,例如打印出来或者保存到文件中。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)