Filling some QTableWidgetItems with QString from f

2019-09-19 07:07发布

I'm trying to fill a QTableWidget from a file that was exported by my program, but when I try to set text to the table cells they just ignore me, nothing happens.

void MainWindow::on_actionOpen_Project_triggered()
{
    QString line, fileName;
    fileName = QFileDialog::getOpenFileName(this,tr("Open Project"), "", tr("Project Files (*.project)"));

    if(!fileName.isEmpty()){

        QFile file(fileName);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return;
        QTextStream in(&file);

        for(int i=0;i<ui->code->rowCount();i++){ // goes through table rows
            for(int j=0;j<ui->code->columnCount();j++){ // through table columns

                ui->code->setCurrentCell(i,j);
                QTableWidgetItem *cell = ui->code->currentItem();
                in >> line;

                if(!line.isEmpty()){
                    cell = new QTableWidgetItem(line); // relates the pointer to a new object, because the table is empty.
                    ui->errorlog->append(line); // just for checking if the string is correct visually.
                }
            }
        }
        file.close();
    }
}

The errorlog object shows on the screen the correct values opened from the file, however the table is not filled. Any problems found?

1条回答
Emotional °昔
2楼-- · 2019-09-19 07:24

This line:

cell = new QTableWidgetItem(line); 

doesn't do what you think it does. Assigning the cell doesn't change anything in the table – cell is just a local variable, overwriting it doesn't have any effect elsewhere.

You (probably) want to do something like this instead:

cell->setText(line);

Or (if you don't really need to change the current item):

ui->code->item(i,j)->setText(line);

If those give you a segfault, it's that you haven't set the table's widget items yet. In that case, you should do something like:

QTableWidgetItem *cell = ui->code->item(i,j);
if (!cell) {
  cell = new QTableWidgetItem;
  ui->code->setItem(i,j,cell);
}

if (!line.isEmpty()) {
  cell->setText(line);
}

This will populate all the cells with QTableWidgetItems the first time this function is called, and reuse them subsequently.

查看更多
登录 后发表回答