Custom QLineEdit to store NULL with QDataWidgetMapper
I have a QLineEdit which is mapped to a table column using a QDataWidgetMapper.
Code:
CREATE TABLE mytable (EMP_REF varchar(10) NOT NULL, EMP_NAME varchar(40));
Code:
model = new QSQLRelationalTableModel(this)
model->setTable("mytable");
model->select();
mapper->setModel(model);
mapper->addMapping(ui->empRefEdit, 1);
The problem is that if the user does not enter a reference, the mapper simply populates the field with an empty string "" instead of a NULL and the database referential integrity is defeated.
I read another post suggesting that QLineEdit should be subclassed and a SQLText property added, but I haven't been able to work out a good way to update this property.
The QDataWidgetMapper appears not to use the text() getter method, but accesses the text property directly (I guess it has to!).
Is the only way to create a shadow SQLText property to override the event handler and update it on every keypress event? This seems a little clumsy.
Many thanks for help.
Re: Custom QLineEdit to store NULL with QDataWidgetMapper
You need to employ a custom delegate for the widget mapper to map between the widget and the model.
Re: Custom QLineEdit to store NULL with QDataWidgetMapper
Thanks for pointing me in the right direction. For anyone who is interested, this is my final solution to the problem:
Code:
model->setTable("mytable");
model->select();
mapper->setModel(model);
mapper->setItemDelegate(new NullDelegate);
mapper->addMapping(ui->empRefEdit, 1);
And the delegate:
Code:
{
Q_OBJECT
public:
NullDelegate
(QObject *parent
= 0);
};
{
model->setData(index, editor->property("text") == "" ?
editor->property("text"));
}
{
editor->setProperty("text", index.data());
}
Now, the next problem..... what if I need to use a QSqlRelationalDelegate as well to populate some combo boxes?
Re: Custom QLineEdit to store NULL with QDataWidgetMapper
Make your delegate a subclass of QSqlRelationalDelegate.