THE DOCTOR
THE DOCTOR

Reputation: 4555

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?

Upvotes: 6

Views: 7141

Answers (2)

user2976791
user2976791

Reputation: 1

Sorry...

void squidlogreader_::process_line(QString line)
{
    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++;

}
void squidlogreader_::on_pushButton_clicked()
{
    QFile file("in.txt");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

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

Upvotes: -2

phyatt
phyatt

Reputation: 19102

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.

Upvotes: 8

Related Questions