Search code examples
pythonpyqt4pysideqtableview

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 a similar validator when I edit a cell on a QTableView?


Solution

  • 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())