How to use a validator with QTableWidgetItem?

女生的网名这么多〃 提交于 2019-12-05 18:00:45

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.

I can think of two different ways you can handle this. There may be other solutions as well.

You could subclass the QTableWidgetItem and reimplement the setData function. If you pick up an invalid value, you can emit an error message.

You could subclass QStyledItemDelegate and either add a QValidator to the editor QWidget by reimplementing createEditor or reimplement the setModelData and examine the user input there. Once again, you can emit an error message if there's invalid data.

Check the documentation of each to see which would be more appropriate for your project.

QTableWidgetItem

QStyledItemDelegate

I use this solution where you have a QLineEdit in each cell. the validator is for scientific numbers (e.g. 2e-17)

for(int trow=0; trow <= 2; trow++ )
{
    for(int tcolumn=0; tcolumn <= 3; tcolumn++ )
    {
        QLineEdit * tableline = new QLineEdit;
        tableline->setValidator( new QDoubleValidator(0, 100, 2, this) );
        ui->tableWidget->setCellWidget ( trow, tcolumn,  tableline);
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!