I'm trying to create a custom delegate so I can use Regex to verify the data that's being entered into the table but for some reason, my code keeps throwing errors, is there a good structured example?
These are the two errors I'm currently getting, and when I fix the AttributeError: 'QLineEdit' object has no attribute 'set'
by using QLineEdit.setText my regular expression doesn't work and it allows any value to be added in.
Traceback (most recent call last):
File "F:\Computing\Program V3\stockGui.py", line 23, in setEditorData
editor.set(text)
AttributeError: 'QLineEdit' object has no attribute 'set'
Traceback (most recent call last):
File "F:\Computing\Program V3\stockGui.py", line 29, in setModelData
model.setData(index, QVariant(editor.text()))
NameError: name 'QVariant' is not defined
class ProductDelegate(QtSql.QSqlRelationalDelegate):
def __init__(self):
super().__init__()
def createEditor(self, parent, option, index):
if index.column() == 1:
editor = QtGui.QLineEdit(parent)
regex = QtCore.QRegExp(r"(?:[A-Z|\s]+)")
validator = QtGui.QRegExpValidator(regex,parent)
editor.setValidator(validator)
return editor
else:
return QtSql.QSqlRelationalDelegate.createEditor(self, parent, option, index)
def setEditorData(self, editor, index):
if index.column() == 1:
text = index.model().data(index, QtCore.Qt.DisplayRole)
editor.set(text)
else:
QtSql.QSqlRelationalDelegate.setEditorData(self, editor,index)
def setModelData(self, editor, model, index):
if index.column() == 1:
model.setData(index, QVariant(editor.text()))
else:
QtSql.QSqlRelationalDelegate.setModelData(self, editor, model, index)
As you've discovered,
setText
doesn't do any validatation. So, instead, use insert:The other error is caused simply because you did not import
QVariant
, and so you can't use it. The easiest fix is to just omit it altogether (PyQt will automatically convert to arguments to aQVariant
wherever it's appropriate):(NB: if you're using Python 3, then, by default,
QVariant
is always automatically converted both to and from the equivalent Python types).The above solution did not work for me.
This solution worked for me: http://nullege.com/codes/show/src@p@y@PyQt4-HEAD@examples@tools@settingseditor@settingseditor.py/626/PyQt4.QtGui.QRegExpValidator