PDA

View Full Version : QtSql.QSqlRelationalDelegate Validation



lukeQt
21st July 2015, 19:49
Hi Everyone,

I have subclassed both a QSqlRelationalTableModel and a QtSql.QSqlRelationalDelegate. My question is with validation when editing a cell.

I have a createEditor method where I specify a line edit and add a regular expression validator to the lineEdit. The user can double click the cell and then click a different cell in the model and then the editor closes.

This allows the user to not enter anything into the cell and skip the validator. Is this normal behavior? How would I prevent the editor from closing until the regular expression is met?

Do I need to subclass the method commitAndCloseEditor to get this to work?



def createEditor(self, parent, option, index):
"""
This creates the editors and returns the widget used to edit the item
specified by index for editing.

The parent widget and style option are used to control how the
editor widget appears.
"""

if index.column() == EVENT_ALIAS:
lineEdit = QtGui.QLineEdit(parent)
regex = QtCore.QRegExp(r"[a-zA-Z0-9_]{3,60}")
validator = QtGui.QRegExpValidator(regex, parent)
lineEdit.setValidator(validator)
return lineEdit

# Else return the base method createEditor.
else:
return super(Delegate, self).createEditor(parent, option, index)

lukeQt
22nd July 2015, 00:28
I think I found a workaround.

In the setModelData I make sure that the length is greater then 3 before calling setData.



def setModelData(self, editor, model, index):
"""
Gets data from the editor widget and stores it in the specified model
at the item index.

The default implementation gets the value to be stored in the data model
from the editor widget's user property.
"""

# Call the setData method and set the data to the editors text. This
# allows the user to write the edit text back to the model.
if index.column() in [2, 3]:
# Only set the data if the len of the text is greater then 3.
# This means the data will not be set if it is less then 3.
# this will force the validator to be met here.
if len(editor.text()) >3:
model.setData(index, QtCore.QVariant(editor.text()))