View Full Version : qtablewidget edit only numbers

14th January 2020, 10:22
I use tablewidget to presenet data and in one column user can input data but i dont know how to limit user to enter only numbers and of course on end i must get imputed values trought loop.

while (query1.next()) {
ui->tableWidget->setItem(i, 0, new QTableWidgetItem(query1.value(0).toString()));
ui->tableWidget->setItem(i, 1, new QTableWidgetItem(QString::number(query1.value(1).t oDouble(), 'f', 2)));
ui->tableWidget->setItem(i, 2, new QTableWidgetItem(""));
ui->tableWidget->item(i,0)->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled );
ui->tableWidget->item(i,1)->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled );
QLineEdit * tableline = new QLineEdit;
tableline->setValidator( new QDoubleValidator(0, 100, 2, this) );
ui->tableWidget->setCellWidget (i, 2, tableline);
qDebug() << ui->tableWidget->cellWidget(i,2)->

14th January 2020, 20:36
The usual way to do this is to create a custom QStyledItemDelegate and install it on the column using QTableView::setItemDelegateForColumn(). In the createEditor() method for your delegate, you would create a QLineEdit -and- install the QDoubleValidator on that.

Here is a good tutorial (https://www.bogotobogo.com/Qt/Qt5_QTableView_QItemDelegate_ModelView_MVC.php) on how to do that (by creating a QSpinBox as the custom editor). Beware of the typos. You should find it pretty easy to implement your own delegate from this example.