0

I have a QTableWidget that is made up of two columns: Diameters and Areas

I inserted QDoubleSpinBoxes into every cell. When I enter data into one, I want to be able to detect that and automatically generate the area using the value I inserted in the corresponding cell.

So how exactly do I send a signal when I changed the value of a diameter at a certain row, to the function to calculate the area using that diameter and then update the cell right next to it in the Area column on the same row with that value calculated?

 QObject::connect(TabUI.tableWidget,SIGNAL(cellChanged()), this, SLOT(CalculateArea()));

    void Pressurator::CalculateArea()
{

//        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);
    qDebug()<<"DETECTED";
}

This is where the QTableWidget is generated:

 void Pressurator::NozzleCount()
{
 int nozzleCount = TabUI.nozzlesNum_SB->value();
// QDoubleSpinBox * nozzleD_A_SB = new QDoubleSpinBox;
// nozzleD_A_SB->setRange(0,10000);
 TabUI.tableWidget->setColumnCount(3);
 TabUI.tableWidget->setRowCount(nozzleCount);

QStringList labels = {"Diameter","Area","Type"};
 TabUI.tableWidget->setHorizontalHeaderLabels(labels);

// QHeaderView* header = TabUI.tableWidget->horizontalHeader();
// header->setSectionResizeMode(QHeaderView::Stretch);

 for(int i=0 ; i< nozzleCount; i++)
 {

 QDoubleSpinBox * ND_SB = new QDoubleSpinBox;
 QDoubleSpinBox * NA_SB = new QDoubleSpinBox;
 QComboBox * nozzleType = new QComboBox;

 ND_SB->setDecimals(5);ND_SB->setRange(0,500);
 NA_SB->setDecimals(5);NA_SB->setRange(0,500);
 nozzleType->addItems(nozzleTypesList);


 TabUI.tableWidget->setCellWidget(i,0, ND_SB);
 TabUI.tableWidget->setCellWidget(i,1, NA_SB);
 TabUI.tableWidget->setCellWidget(i,2, nozzleType);
 }

}

1 Answers1

0

If you call setCellWidget, you won't get cellChanged signal from QTableWidget. You have to connect the QDoubleSpinBoxes's valueChanged signal. If you have bigger and dynamic table using ItemDelegates will better.

Also Qt has an example for QSpinBox delegate and it has a disadvantage if you use the code out of the box. The disadvantage is If you change the spinbox's value, the QTableWidget's cellChanged signal won't emit until press enter or click other cell.

If you want emit signal immediately you have to add this connection into createEditor function before return statement:

connect(editor, QOverload<decltype(editor->value())>::of(&QSpinBox::valueChanged), [=](auto val){
        auto ptr = const_cast<SpinBoxDelegate*>(this);
       emit ptr->commitData(editor);
    });
M. Galib Uludag
  • 369
  • 2
  • 8