PDA

View Full Version : Loading csv data to tablewideget (I am completely stuck!)



qtgraphical
24th August 2013, 18:55
Hello guys,

I am very new to Qt. Trying to load csv data to my simple tablewideget. Here is

Data.csv:

John Kl;34;1335532;CA;0444344
Kuma jo;54;44432;NY;0322355
Lebal ho;24;44022;NY;0110004

Here is what i am trying:


#include <QApplication>
#include <QMainWindow>
#include <QTableWidget>
#include <QTableWidgetItem>
#include <QFile>
#include <QString>
#include <QStringList>
#include <QMessageBox>
#include <QTextStream>
#include <QDebug>

int main(int argc, char **argv)
{
QApplication app(argc, argv);
QMainWindow *window = new QMainWindow();
QMessageBox msg;

QFile file("Data.txt");
if(!file.open(QIODevice::ReadOnly))
msg.information(0,"Error!","Error opening file!",0);

QTextStream in(&file);
QStringList loadCsv;

QTableWidget *myTable=new QTableWidget();



while(!file.atEnd()){

loadCsv<<in.readLine().split(";");

myTable->setColumnCount(loadCsv.size());
for(int row=0;row<in.readLine().size();++row){
myTable->setRowCount(loadCsv.size()); //It reading only first line.
for(int col=0;col<loadCsv.size();++col){

myTable->setColumnCount(loadCsv.size());
QTableWidgetItem *Items= new QTableWidgetItem(loadCsv[col]);
myTable->setItem(row,col,Items);

}
}
}
qDebug()<<loadCsv;
window->setCentralWidget(myTable);
window->show();
return app.exec();
}


I know this code is not okay as it is not working at all and i don't know how to fix it, I guess i am doing something wrong with the loop. but I just don't get an easy way to make this work. If someone can help me to load the csv to load in the QTableWideget then it will be a greate resource for me to study.

Santosh Reddy
26th August 2013, 09:14
If someone can help me to load the csv to load in the QTableWideget then it will be a greate resource for me to study.
Ok, study this and find you at least 5 differences from the your code. :)



int main(int argc, char **argv)
{
QApplication app(argc, argv);
QMainWindow *window = new QMainWindow();
QMessageBox msg;

QFile file("Data.txt");
if(!file.open(QIODevice::ReadOnly|QIODevice::Text) )
msg.information(0,"Error!","Error opening file!",0);
else
{
QTextStream in(&file);
QStringList loadCsv;

QTableWidget *myTable=new QTableWidget();
myTable->setColumnCount(5);
int row=0;

while(!in.atEnd()){
loadCsv<<in.readLine().split(";");

if(!loadCsv.isEmpty())
{
myTable->insertRow(myTable->rowCount());

for(int col=0;col<5;++col){
if(col < loadCsv.size())
{
QTableWidgetItem *Items= new QTableWidgetItem(loadCsv[col]);
myTable->setItem(row,col,Items);
}
}
row++;
loadCsv.clear();
}
}
file.close();
window->setCentralWidget(myTable);
}
window->show();
return app.exec();
}