PDA

View Full Version : Custom QLineEdit to store NULL with QDataWidgetMapper



certqt
9th November 2010, 11:09
I have a QLineEdit which is mapped to a table column using a QDataWidgetMapper.


CREATE TABLE mytable (EMP_REF varchar(10) NOT NULL, EMP_NAME varchar(40));



model = new QSQLRelationalTableModel(this)
model->setTable("mytable");
model->select();

mapper = new QDataWidgetMapper(this);
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.

wysota
9th November 2010, 11:15
You need to employ a custom delegate for the widget mapper to map between the widget and the model.

certqt
9th November 2010, 12:42
Thanks for pointing me in the right direction. For anyone who is interested, this is my final solution to the problem:



model = new QSqlRelationalTableModel(this);
model->setTable("mytable");
model->select();

mapper = new QDataWidgetMapper(this);
mapper->setModel(model);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
mapper->setItemDelegate(new NullDelegate);
mapper->addMapping(ui->empRefEdit, 1);


And the delegate:


class NullDelegate : public QItemDelegate
{
Q_OBJECT
public:
NullDelegate (QObject *parent = 0);
void setEditorData(QWidget *editor, const QModelIndex &index) const;
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const;
};

void NullDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
model->setData(index, editor->property("text") == "" ?
QVariant() :
editor->property("text"));
}

void NullDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
editor->setProperty("text", index.data());
}

Now, the next problem..... what if I need to use a QSqlRelationalDelegate as well to populate some combo boxes?

wysota
9th November 2010, 13:15
Make your delegate a subclass of QSqlRelationalDelegate.