Filling some QTableWidgetItems with QString from file

99封情书 提交于 2019-12-25 17:34:15

问题


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:


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.



来源:https://stackoverflow.com/questions/10453343/filling-some-qtablewidgetitems-with-qstring-from-file

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