How to use a validator with QTableWidgetItem?

大城市里の小女人 提交于 2019-12-07 08:03:58

问题


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!


回答1:


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.




回答2:


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




回答3:


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);
    }


来源:https://stackoverflow.com/questions/18309715/how-to-use-a-validator-with-qtablewidgetitem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!