Skip to content Skip to sidebar Skip to footer

Pyside, PyQt4: How To Set A Validator When Editing A Cell In A QTableView

In QLineEdit objects I can set a RegExp validator like this: validator = QtGui.QRegExpValidator(QtCore.QRegExp('\d{11}'), lineedit) lineedit.setValidator(validator) How can I set

Solution 1:

By subclassing QStyledItemDelegate and reimplementing the createEditor method:

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)

Then you can set the validator like this:

tableview.setItemDelegate(ValidatedItemDelegate())

Post a Comment for "Pyside, PyQt4: How To Set A Validator When Editing A Cell In A QTableView"