Thanush Ganesh
Thanush Ganesh

Reputation: 23

QTableWidget with setItem cannot access the data in the tablewidget

void IdListForTrain::SetListIdInList(QStringList IdList) {

QTableWidgetItem *item=nullptr;
for(int index=0;index<IdList.count();index++)
{
    ui->Id_tableWidget->insertRow(index);
    for(qint32 columnIndex=0;columnIndex<=1;columnIndex++)
    {
        item = new QTableWidgetItem;
        if(columnIndex==0)
        {
            ui->Id_tableWidget->setItem(index,columnIndex,item);
            item->setText("00:00:00");
        }
        if(columnIndex==1)
        {
            ui->Id_tableWidget->setItem(index,columnIndex,item);
            item->setText(IdList.at(index));
        }

        QString tmp1 = ui->Id_tableWidget->item(index,1)->text();
        QString tmp = item->text();

    }
}

}

Hi! I am new to Qt and I'm facing a problem. I was asked to create a tablewidget with the effective date of train Ids in one column and the names of the trains in another column,I did this code to the best of my knowledge but I can't set or access the data in the widget in the line eventhough the code doesnt give any errors but it crashes everytime I open the application window at this line,

QString tmp1 = ui->Id_tableWidget->item(index,1)->text();

I'm not sure what the reason is.

Upvotes: 0

Views: 190

Answers (1)

Alexey
Alexey

Reputation: 2479

Let look at first iteration - index=0 and columnIndex=0.

  1. You go through if(columnIndex==0) condition and set item to QTableWidget's row = 0 (index) and column = 0 (columnIndex)
  2. Second condition skipped
  3. You try to access item at row = 0 (index) and column = 1 with code QString tmp1 = ui->Id_tableWidget->item(index,1)->text();. But at this time you have no item assigned to that column

That's all!

Upvotes: 1

Related Questions