How to import a CSV file to a QTableWidget

和自甴很熟 提交于 2019-12-06 12:28:43

问题


I am student programmer and I am using Qt to develop a GUI interface for work and Im having trouble figuring out how I should make this this import function work. A bit of programmers writers block if you will. SO far I have this for code:

void InjectionLocationsDialogExpanded::importCSVFile()
{
    QString fileName = QFileDialog::getOpenFileName(this, ("Open File"), "/home", ("csv File(*.csv)"));
    QString data;
    QFile importedCSV(fileName);
    QStringList rowOfData;
    QStringList rowData;
    int tempint = 0;
    data.clear();
    rowOfData.clear();
    rowData.clear();
    if (importedCSV.open(QFile::ReadOnly))
    {
        data = importedCSV.readAll();
        rowOfData = data.split("\n");
        rowData = data.split(";");
        importedCSV.close();
    }
    qDebug() << data;
    for (int x = 0; x < rowOfData.size(); x++)
    {
        for (int y = 0; y < ui->tableWidgetInjectionLocationsExpandedDialog->columnCount(); y++)
        {
            ui->tableWidgetInjectionLocationsExpandedDialog->item(x,y)->setText(rowData[]);
        }
    }
}

The issue here is that I don't know how to get the settext of each item in the table to reference the next item in the rowData QStringList. I need to increment by one location but I cant use a int++ because that will eventually look for a item in the QStringList that doesn't exist and cause a segmentation fault. I also cant use a for loop to cap the number I need in the location field here because of the current for loops structure. I just cant think of a good strategy for to approach this on. Please only leave constructive comments as I am only interested in learning or accomplishing this task. Thanks for reading!


回答1:


First of all, you would need to take care of line endings. This means that your code might not be platform independent if you just check for "\n" in your CSV file.

If I get what you're trying to do, you would have to set the rowData within the for-loop. So, what I would do then :

rowOfData.clear();
rowData.clear();

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

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

I guess this should do it. Best regards.



来源:https://stackoverflow.com/questions/9165183/how-to-import-a-csv-file-to-a-qtablewidget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!