Assuming I have a QTableWidgetItem item and I just wanna validate data that users enter. Example, users only enter a number into that item otherwise the program will show a warning dialog.
I also search on that document page but I didn’t find similar function with setValidator() function.
How can I use a validator for that QTableWidgetItem item?
Thanks!
Assuming what you really want is to have QValidate
-able cells, you could populate the cell with a QLineEdit
instance instead. Here's an example that uses QDoubleValidator
, but any QValidator
will work:
QLineEdit *edit = new QLineEdit(ui->myTable);
edit->setValidator(new QDoubleValidator(edit));
ui->myTable->setCellWidget(row, col, edit);
By default, QLineEdit
will fill the cell and is drawn with a frame. To preserve the appearance of the table, you can turn the frame off by calling the following function a priori:
QLineEdit::setFrame(false);
One annoying thing about this solution is that you'll have to call
QWidget* QTableWidget::cellWidget(row, col) const
to subsequently access the QLineEdit instance in each cell, which means you'll have to cast the pointer to QLineEdit*
also. (See qobject_cast()
). It's a bit verbose but workable.