3

在 QLineEdit 对象中,我可以像这样设置 RegExp 验证器:

validator = QtGui.QRegExpValidator(QtCore.QRegExp("\d{11}"), lineedit)
lineedit.setValidator(validator)

在 QTableView 上编辑单元格时如何设置类似的验证器?

4

1 回答 1

5

通过继承 QStyledItemDelegate 并重新实现 createEditor 方法:

class ValidatedItemDelegate(QtGui.QStyledItemDelegate):
    def createEditor(self, widget, option, index):
        if not index.isValid():
            return 0
        if index.column() == 0: #only on the cells in the first column
            editor = QtGui.QLineEdit(widget)
            validator = QtGui.QRegExpValidator(QtCore.QRegExp("\d{11}"), editor)
            editor.setValidator(validator)
            return editor
        return super(ValidatedItemDelegate, self).createEditor(widget, option, index)

然后你可以像这样设置验证器:

tableview.setItemDelegate(ValidatedItemDelegate())
于 2012-11-19T08:21:41.507 回答