Home > Enterprise >  How to automatically make a calculation in a cell in the same row using the data of another cell tha
How to automatically make a calculation in a cell in the same row using the data of another cell tha

Time:04-26

Basically I have a table widget. 2 columns in that table contain Diameters and Area repsectively.

I basically want when I enter the diameter the area get calculated in the corresponding cell. And if I enter the area, the diameter is similarly calculated.

I made the connect function that sends a signal when a cell is changed, this is used to detect the row and column to know which cell exactly and the SLOT is the function where the calculations happen. So this:

    QObject::connect(TabUI.tableWidget, &QTableWidget::itemChanged, this, &Pressurator::CalculateArea);

And this:

void Pressurator::CalculateArea(QTableWidgetItem *item)
{

//        QTableWidgetItem * item = new QTableWidgetItem;
//        double area = 0;
//        QDoubleSpinBox * diameter_SB =  static_cast<QDoubleSpinBox*>(TabUI.tableWidget->cellWidget(item->row(),0));
//        QDoubleSpinBox * area_SB =  static_cast<QDoubleSpinBox*>(TabUI.tableWidget->cellWidget(item->row(),1));

//        area = M_PI * qPow(diameter_SB->value()/2, 2);
//        area_SB->setValue(area);


    row = item->row();
    column = item->column();

    qDebug()<<"DETECTED--->"<<row<<" | "<<column;
if(column == 0){
    diameter = TabUI.tableWidget->item(row,0)->text().toDouble();
    qDebug()<<"Diameter: "<<diameter<<Qt::endl;
    area = M_PI * qPow(diameter/2, 2);
    qDebug()<<"Area: "<<area<<Qt::endl;
    TabUI.tableWidget->item(row,1)->setText(QString::number(area, 'f', 6));
}else if(column == 1){
    area = TabUI.tableWidget->item(row,1)->text().toDouble();
    diameter = qSqrt((4* area)/M_PI);
    TabUI.tableWidget->item(row,0)->setText(QString::number(diameter, 'f', 6));
}

My app keeps crashing after I enter data in one of the cells, so I don't really know how to proceed or the reason for the crash.

CodePudding user response:

I just defined my tableWidget when constructing my form (not at the CalculateArea function) as below and it worked:

QTableWidget* tableWidget = new QTableWidget();
tableWidget->setRowCount(1);
tableWidget->setColumnCount(2);
QTableWidgetItem* item = new QTableWidgetItem("1.0");
QTableWidgetItem* item2 = new QTableWidgetItem("0.785398");
tableWidget->setItem(0, 0, item);
tableWidget->setItem(0, 1, item2);
tableWidget->show();

In QTableWidget class, the signal "itemChanged" is emitted whenever the data of item has changed. In the definition of "CalculateArea" slot, you are trying set the data which causes to emit another signal. So it will be stuck in stack overflow. You can block the signal before you are trying set the data.

row = item->row();
column = item->column();
TabUI.tableWidget->blockSignals(true);
.
. // Set your data (if / else if) ...
.
TabUI.tableWidget->blockSignals(false);
  • Related