Question

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;
    }
}
Was it helpful?

Solution 2

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).

OTHER TIPS

To check whether the cell(i,j) in QTableWidget is empty or not, use isNull() or isEmpty(). Example:

for(int i=0; i < ui->tableWidget->rowCount(); i++)
{
    for(int j=0; j < ui->tableWidget->columnCount(); j++)
    {
        bool flag = ui->tableWidget->item(i,j)->text().isNull();

        if (!flag) /* the cell is not empty */
        {
            // do stuff 
        }
        else /* the cell is empty */
        {
            // do stuff
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top