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?
This 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:
Or (if you don't really need to change the current item):
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:
This will populate all the cells with
QTableWidgetItem
s the first time this function is called, and reuse them subsequently.