PDA

View Full Version : Load CSV file into QTableWidget



thecml
24th May 2015, 14:11
Hi all.

I've been using Qt for a few days now and having trouble populating a QTableWidget with data from an CSV file. My code is as follows:

Input text file:


Test1
Heyheyhey25

Code for inserting the file into QTableWidget:


{
QFile file("filename");

// QString fileName = QFileDialog::getOpenFileName(this, ("Open File"), "/home", ("csv File(*.csv)"));
// QFile file(fileName);

QString data;
QStringList rowOfData;
QStringList rowData;
data.clear();
rowOfData.clear();
rowData.clear();

if (file.open(QFile::ReadOnly))
{
data = file.readAll();
rowOfData = data.split("\n");
file.close();
}

qDebug()<<rowOfData;

for (int x = 0; x < rowOfData.size(); x++)
{
rowData = rowOfData.at(x).split(";");
qDebug()<<rowData;
for (int y = 0; y < rowData.size(); y++)
{
ui->tableWidgetScenarios->item(x,y)->setText(rowData[y]);
}
}
}

It crashes whenever I try to insert my data into the tablewidget. Here's the debugger output and error message:


Debugging starts
("Test1", "Heyheyhey25")
("Test1")

qtablewidget.h:181: error: Exception at 0x646e55e3, code: 0xc0000005: read access violation at: 0x0, flags=0x0 (first chance)

I've tried with multiple files, same result. Do I need to initialize the widget in some way or what am I doing wrong? :)

Thanks in advance, regards.

anda_skoa
24th May 2015, 17:06
for (int x = 0; x < rowOfData.size(); x++)
{
rowData = rowOfData.at(x).split(";");
qDebug()<<rowData;
for (int y = 0; y < rowData.size(); y++)
{
ui->tableWidgetScenarios->item(x,y)->setText(rowData[y]);
}
}
}

It crashes whenever I try to insert my data into the tablewidget. Here's the debugger output and error message:


Assuming you don't have code elsewhere that creates table widget items, then


ui->tableWidgetScenarios->item(x,y)->setText(rowData[y]);

tries to access an item that does not exist. I.e. item(x, y) returns 0 and you are then calling a method on a null pointer.

See QTableWidget::setItem().

Cheers,
_