I create a table with two rows and two columns:
The second column contains spinBoxes as elements. The code is the following:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
myTable = ui->tableWidget;
for( int i = 0; i < myTable->rowCount(); i++ )
{
QDoubleSpinBox *spinBox = new QDoubleSpinBox(this);
spinBox->setValue( i + 1 );
myTable->setCellWidget( i, 1, spinBox );
}
}
myTable
is declared as a member of MainWindow
.
Normally, values of just SpinBoxes
are accessed via:
ui->spinBox->value();
But this is not working here.
How do I access the values of SpinBoxes
use them as items in a QTableWidget
?
I want to access the SpinBoxes
by an iteration, hence using a for loop for looping through all Spin Boxes.
A table widget works with items
. Each cell represents one item (in your case 2 rows x 2 columns = 4 cells = 4 items). As you already did you can set a specific widget for one of the items by calling setCellWidget(int row, int column, QWidget* widget)
. Now, with the corresponding call cellWidget(int row, int column)
it will return that pointer to the QWidget you set before.
The only thing left then is to cast
the QWidget
back to its derived class.
double val = static_cast<QDoubleSpinBox*>(myTable->cellWidget(0,1))->value();
As you asked for an explanation, here is the code in single lines with comments:
QWidget* some_cell_widget = myTable->cellWidget(0,1); // retrieve widget from cell
QDoubleSpinBox* dbl_spin_box = static_cast<QDoubleSpinBox*>(some_cell_widget); // cast widget to double spin box
double val = dbl_spin_box->value(); // get value from spinbox