PDA

View Full Version : Null Handling with QDataMapper and QSqlTableModel



FinancialStudent
22nd December 2010, 09:23
I've been working on this for days now and done a lot of searching, and while I've piece together some code, I can't get it to do what I want. I'm trying to create a simple table editor, but I can't seem to get the program to handle nulls properly. Ignoring null dates for the time being, which seems to be a separate issue altogether.

I noticed when I was scrolling through the records that any null numeric fields would just display the last non-null value that they previously displayed. Also, if the field was empty, the database would complain about a '' being written to a numeric field. I was able to fix both these problems by adding a custom delegator, but that caused some new problems.



void NullDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
if (editor->inherits("QLineEdit"))
{
QLineEdit *e = static_cast<QLineEdit*>(editor);
QVariant editorValue;
if (!(e->text().isEmpty())) {
editorValue = e->text();
}
model->setData(index, editorValue);
}
else {
QItemDelegate::setModelData(editor, model, index);
}
}

void NullDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
if (editor->inherits("QLineEdit"))
{
QLineEdit *e = static_cast<QLineEdit*>(editor);

if (index.data().isNull()) {
e->clear();
}
else {
e->setText(index.data(Qt::DisplayRole).toString());
}
}
else {
QItemDelegate::setEditorData(editor, index);
}
}

NullDelegate::NullDelegate(QObject *parent)
: QItemDelegate(parent)
{
}


Problem #1: This affects strings and numerics and I'm not sure how to distinguish between the two. I'm OK, with storing '' for strings, but I'd prefer to store nulls for numerics when the text is ''.

Problem #2: If I try and set the value back to '', it just re-displays the last non-null value.

It seems to me that the setData is not accepting nulls, but maybe I'm doing something wrong here.

Any help would be greatly appreciated. I'm fairly new to both Qt and forums, so let me know what other information I need to provide.