Filling a table widget from a text file in Qt

I am new to Qt and need help with the following:

I would like to create a graphical interface containing a table widget that is populated with information coming from a tab delimited text file. In my GUI, the user first looks at the text file and then displays the contents in the table widgets. I did part of the review, but how to load data from a text file into a table widget?

+5
source share
2 answers

These are two steps, analyze the file and then paste it into the widget.

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

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

QTableWidgets . . , GUI- Qt Creator, .

GUI , examples... .

+8

...

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

All Articles