c++ - QTableWidget 到多个文件

标签 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 中的形状不在表中,则会创建一个空文件。

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

最佳答案

你可以这样写。

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();
}

关于c++ - QTableWidget 到多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52515020/

相关文章:

c++ - 您将如何嵌套结构?

c++ - Lambda 中的参数列表

c++ - iostream 或 C++ 中的其他地方是否有称为时间的东西?

c++ - OpenCV2.2 cvCaptureFromCAM 问题...只返回绿屏。 (罗技 C260 摄像头)

c++ - nmake 无法工作 - Qt

c++ - Qt 和 C++ 类给我一个错误

c++ - 编译器对析构函数省略的自由度是多少?

c++ - 参数或返回类型隐式转换在 C++ 中优先吗?

c++ - 提交对 SQLite 数据库的更改,这可以在 QTab 之间看到

c++ - Qt 5 构建错误 : extra characters after test expression