从 Qt 中的文本文件填充表格小部件 [英] Populating Table Widget from Text File in Qt

查看:14
本文介绍了从 Qt 中的文本文件填充表格小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Qt 新手,需要以下方面的帮助:

I'm new to Qt and need some help with the following:

我想创建一个包含表格小部件的 GUI,该小部件由制表符分隔的文本文件中的信息填充.在我的 GUI 中,用户将首先浏览文本文件,然后在 Table Widget 中显示内容.我已经完成了浏览部分,但是如何将文本文件中的数据加载到 Table Widget 中?

I would like to create a GUI containing a Table Widget that is populated by information coming from a tab delimited text file. In my GUI, the user would first browse for the text file and then it would then show the contents in the Table Widget. I've done the browse part, but how do I load the data from the text file into the Table Widget?

推荐答案

分两步,解析文件,然后push到widget中.

It's two steps, parse the file, and then push it into the widget.

我从 QFile 文档中获取了这些行.

I grabbed these lines from the QFile documentation.

 QFile file("in.txt");
 if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
     return;

 while (!file.atEnd()) {
     QByteArray line = file.readLine();
     process_line(line);
 }

您的 process_line 函数应如下所示:

Your process_line function should look like this:

static int row = 0;
QStringList ss = line.split('	');

if(ui->tableWidget->rowCount() < row + 1)
    ui->tableWidget->setRowCount(row + 1);
if(ui->tableWidget->columnCount() < ss.size())
    ui->tableWidget->setColumnCount( ss.size() );

for( int column = 0; column < ss.size(); column++)
{
    QTableWidgetItem *newItem = new QTableWidgetItem( ss.at(column) );
    ui->tableWidget->setItem(row, column, newItem);
}

row++;

有关操作 QTableWidgets 的更多信息,请查看文档.对于使用 Qt Creator 中的 GUI 构建器的新用户,一开始很难弄清楚.

For more information about manipulating QTableWidgets, check the documentation. For new users using the GUI builder in Qt Creator, it is tricky figuring it out at first.

最终我会建议切换到构建 GUI,就像他们在所有 示例...通过在代码中手动添加所有内容而不是拖放.

Eventually I would recommend to switching to building the GUI the way they do in all their examples... by adding everything by hand in the code instead of dragging and dropping.

这篇关于从 Qt 中的文本文件填充表格小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆