您可以对模型进行子类化,这样data
将为 NULL 返回一个特殊值,然后setData
检查该特殊值并替换为 NULL。
代码示例草图:
class MyModel : public QSqlTableModel
{
Q_OBJECT
public:
MyModel();
virtual QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
virtual bool setData(const QModelIndex &index, const QVariant &value, int role);
};
QVariant MyModel::data(const QModelIndex& idx, int role)
{
QVariant var = QSqlTableModel::data(idx, role);
if (var.isNull())
var = QVariant(QString("NULL"));
return var;
}
bool MyModel::setData(const QModelIndex& idx, const QVariant& value, int role)
{
QVariant var(value);
if (var == QString("NULL"))
var == QVariant(record().field(idx.column()).type());
return QSqlTableModel::setData(idx, var, role);
}