Search code examples
qtqtablewidgetqtablewidgetitem

QT :how to check if there Empty cell in qt table widget


i have table widget with specific row and column ,

my function is as follow

get value from the first column and second column

compare between them and return result in the third column

Ex: first column :1 2 3 Second column 2 2 3 Result column No Yes Yes

I make sure that my code work by using the qDebug, however when I compile and run it the mainwindow stopped and crash.

I use for loop to go throw all rows for(int row=0;rowtableWidget->rowCount();row++)

I think this line rowtableWidget->rowCount() coz when it read empty cells the app Freeze and stop working .

how can I void that to happen

void MainWindow::GenerateRes() {
    QString Result;
    for(int row = 0; row < ui->tableWidget->rowCount(); row++) {
        QString R1 = ui->tableWidget->item(row, 0)->text();

        QString R2 = ui->tableWidget->item(row, 1)->text();

        if(R1 == R2) {
           Result = "P" ;
        } else {
           Result = "F" ;
        }

        QTableWidgetItem *Item = new QTableWidgetItem(Result);
        ui->tableWidget->setItem(row, 2, Item); 
        qDebug() << Item;
    }
}

Solution

  • maybe you should check the values returned from tableWidget::item(), because the functions can return 0 if no item is asigned to the provided coordinates, and in that case you're trying to call a method (QTableWidgetItem::text()) on a zero pointer. Try something like:

    QString R1;
    QTableWidgetItem *item1(ui->tableWidget->item(row,0));
    if (item1) {
        R1 = item1->text();
    }
    
    // and so on...
    

    Your code looks strange anyway, the 5th line (ui->tableWidget->rowCount()) doesn't make sense, you shouldn't be able to compile that (at least you're missing a semicolon).