Frage

I am self-learner and new to qt(I just want to learn to write program). Trying to load the csv file to qtablewidget but it overriding all columns and row with same data. I tried to follow How to import a CSV file to a QTableWidget but i did not get it correctly.

Code:

QFile file("testData.txt");
QTextStream in(&file);
QStringList setDataInrow;
QStringList rowNumbers;
QString allLine;

if(file.open(QIODevice::ReadOnly)){
    allLine=in.readAll();
    rowNumbers=allLine.split("\n");
    file.close();

}

QTableWidget *myTable=new QTableWidget();
myTable->setRowCount(rowNumbers.size());


for(int row=0;row<rowNumbers.count();row++)
{
    setDataInrow=allLine.split(";");


    for(int column=0;column<setDataInrow.count();column++){
        myTable->setColumnCount(setDataInrow.size());
        //myTable->item(row,column)->setText(setDataInrow[column]);
        QTableWidgetItem *item=new QTableWidgetItem(setDataInrow[column]);
        myTable->setItem(row,column,item);


    }
}


qDebug()<<"Numbers of row needed:"<<"\n"<<rowNumbers<<"\n";
qDebug()<<"Set following data to each column as per row:"<<"\n"<<setDataInrow<<setDataInrow.size();

window->setCentralWidget(myTable);
window->show();
return app.exec();

}

i am trying to load :

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

It should be loaded within 3 rows and 5 columns but it is setting 13 columns . Perhaps i am not able think this correctly. I need your help with some code example so that i can study about it more.

Since my English is not good(Sucks like my codes :)) I have taken an screenshot of the current program which is not working as expected:

http://imageshack.us/a/img801/1601/le59.png

War es hilfreich?

Lösung

setDataInrow=allLine.split(";");

You do this once for each line. But you don't split the line, as you intended, but each time the whole file content.

Edit: Don't split allLine. You have already a QStringList, which contains your lines: rowNumbers.

This you must split.

for(int row=0;row<rowNumbers.count();row++){
  QStringList rowCells = rowNumbers.at(row).split(";");
  .....
}

I hope this gives you the idea. No guarantee for details.

Edit 2:

When you do

setDataInrow=allLine.split(";");

your stringlist contains:

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

This is the whole text in your file. The line breaks do not matter. They are just another character. You add all this in one row. And you do it three times.

What you want is first split the text into lines. You already do this here: rowNumbers=allLine.split("\n");

With your example data the rowNumbers stringlist contains three entries. Each entry one line from your file. These lines you have to split.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top