Pyside,PyQt4:如何在QTableView中编辑单元格时设置验证器

时间:2012-11-19 08:21:42

标签: python pyqt4 pyside qtableview

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

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

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

1 个答案:

答案 0 :(得分:4)

通过继承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())