QTableWidget:只允许数字 [英] QTableWidget: Only numbers permitted
问题描述
有什么办法可以禁止 QTableWidget 中除数字 (0-9) 以外的任何字符?对于 QLineEdits,我使用的是 RegEx 验证器,但这不适用于 QTableWidgets.我想将 QLineEdits 作为 CellWidgets 插入表中,但后来我不得不在我的代码中重写大量函数.那么,有没有其他(直接)方法可以做到这一点?
Is there any way to disallow any characters except numbers (0-9) in a QTableWidget? For QLineEdits I'm using a RegEx validator, but this is not available for QTableWidgets. I thought of inserting QLineEdits in as CellWidgets into the table, but then I had to rewrite an extreme large amount of functions in my code. So, is there any other (direct) way to do so?
推荐答案
我建议为您的表格小部件使用项目委托来处理可能的用户输入.下面是一个简化的解决方案.
I would suggest using an item delegate for your table widget to handle the possible user input. Below is a simplified solution.
item委托的实现:
class Delegate : public QItemDelegate
{
public:
QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem & option,
const QModelIndex & index) const
{
QLineEdit *lineEdit = new QLineEdit(parent);
// Set validator
QIntValidator *validator = new QIntValidator(0, 9, lineEdit);
lineEdit->setValidator(validator);
return lineEdit;
}
};
使用自定义项目委托实现简单表格小部件:
Implementation of the simple table widget with the custom item delegate:
QTableWidget tw;
tw.setItemDelegate(new Delegate);
// Add table cells...
tw.show();
这篇关于QTableWidget:只允许数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!