如何使用验证器与QTableWidgetItem? [英] How to use a validator with QTableWidgetItem?
问题描述
假设我有一个QTableWidgetItem项目,我只想验证用户输入的数据。例如,用户只在该项目中输入一个数字,否则程序将显示一个警告对话框。
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.
我也搜索该文档页面,但我没有找到类似的功能与 setValidator()函数。
I also search on that document page but I didn’t find similar function with setValidator() function.
如何使用QTableWidgetItem项目的验证器?
How can I use a validator for that QTableWidgetItem item?
谢谢!
推荐答案
假设你真正想要的是有 QValidate
可用单元格,你可以填充单元格与 QLineEdit
实例。这里有一个使用 QDoubleValidator
的示例,但任何 QValidator
都可以工作:
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);
默认情况下, QLineEdit
并用框架绘制。为了保持表的外观,可以通过先验调用以下函数来关闭框架:
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
以便随后访问每个单元格中的QLineEdit实例,这意味着您还必须将指针转换为 QLineEdit *
。 (参见 qobject_cast()
)。这是一个有点冗长,但可行。
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.
这篇关于如何使用验证器与QTableWidgetItem?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!