QTableWidget到多个文件

时间:2018-09-26 09:59:25

标签: c++ qt

我有QTableWidget,其中包含以下数据: table.png 该表只能包含QList中的名称:

QList<QString> shapes {  "Triangle", "Circle", "Trapeze", "Square", "Rectangle", "Diamond" };

在相邻单元格中具有随机的int值。

表格可以包含所有“形状”,也可以仅包含一部分(如示例中所示)。

我尝试为表格中的每个形状创建单独的文件,并为它们写下相应的int值。 为了达到这个目的,我写了这样的东西:

QList<QTableWidgetItem *> ItemList 
/.../
for(int i = 0; i < rows; ++i)
{
    for(int i = 0; i<columns; ++i)
    {
        foreach(QString itm, shapes )
        {
            ItemList = ui->tableWidget->findItems(itm, Qt::MatchExactly); 
            QFile mFile(itm + ".txt");

            if(mFile.open(QFile::ReadWrite))
            {
                for(int i = 0; i < ItemList.count(); ++i)
                {
                    int rowNR = ItemList.at(i)->row();
                    int columnNR = ItemList.at(i)->column();
                    out << "Values = " << ui->tableWidget->item(rowNR, columnNR+1)->text() << endl;
                }
            }   
        }
            mFile.flush();
            mFile.close();
    }
}

为QList中的每个项目创建文件-如果QList中的形状不在表格中,则会创建一个空文件。

如何仅根据表中的可用名称创建文件?

1 个答案:

答案 0 :(得分:2)

您可以这样写。

QList<QTableWidgetItem *> ItemList 
/.../

for(QString str : Shapes){
    ItemList = ui->tableWidget->findItems(itm, Qt::MatchExactly); // Get the matching list

    if(ItemList.isEmpty(){
        continue; // If shape does not exist in table skip the iteration
    }

    QFile mFile(str + ".txt");
    if(!mFile.open(QFile::ReadWrite){
        return; // This should not happen ; this is error
    }

    for(QTableWidgetItem *item : ItemList){
        int row = item->row(); 
        int col = item->column()+1; // since it is neighboring cell
        QString Value = ui->tableWidget->item(row,col)->text();
        mFile.write(Value.toUtf8()); // You can change the way in which values are written
    }

    mFile.flush();
    mFile.close();
}