Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating Table Widget from Text File in Qt

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

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?

like image 901
THE DOCTOR Avatar asked May 15 '12 20:05

THE DOCTOR


1 Answers

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

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);
 }

Your process_line function should look like this:

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

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++;

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.

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.

like image 181
phyatt Avatar answered Sep 23 '22 16:09

phyatt