开发者

QSqlTableModel::setData() always returns false for bool column

I am trying to replace true and false values with checkboxes in QSqlTableModel for a database column with bool type.

The following code appears to be work. QSqlTableModel::setData() does post data to back end and returns true for columns other than the bool column.

The problem I encounter is that QSqlTableModel::setData() always returns false for checkbox field.

After checking the checkbox, database log does not show the SQL updating the bool column. This, if I am right, indicates that the problem is in my Qt code, not in table, column, or data type in database.

Helps will be much appreciated.

//-------------

class CheckboxTableModel : public QSqlTableModel
{
public:
    CheckboxTableModel(QObject * parent=0,QSqlDatabase db=QSqlDatabase());
    QVariant data( const QModelIndex& idx, int role) const;
    Qt::ItemFlags flags(const QModelIndex&) const;
    bool setData( const QModelIndex& idx, const QVariant&, int);
};
//-------------
CheckboxTableModel::CheckboxTableModel(QObject *parent,QSqlDatabase db)
    : QSqlTableModel(parent,db)
{
}
//-------------
#define BOOLEAN_COLUMN_INDEX 7 //index of the boolean field

QVariant CheckboxTableModel::data(const QModelIndex& idx,int role) const
{
    QVariant v=QSqlTableModel::data(idx,role);
    if(idx.column() == BOOLEAN_COLUMN_INDEX && (role == Qt::CheckStateRole || role == Qt::EditRole))
        return v.toBool() ? Qt::Checked : Qt::Unchecked;
    else
        return v;
}

Qt::ItemFlags CheckboxTableModel::flags(const QModelIndex& idx) const
{
    if(idx.row() < 0 || idx.row() >= rowCount() || idx.column() < 0 || idx.column() >= columnCount())
        return 0;
    if(idx.column() == B开发者_运维问答OOLEAN_COLUMN_INDEX)
        return Qt::ItemIsUserCheckable | Qt::ItemIsSelectable | Qt::ItemIsEnabled;
    return Qt::ItemIsEditable | Qt::ItemIsSelectable | Qt::ItemIsEnabled;
}

bool CheckboxTableModel::setData(const QModelIndex& idx,const QVariant& value,int role)
{
    if(idx.row() < 0 || idx.row() >= rowCount() || idx.column() < 0 || idx.column() >= columnCount())
        return false;
    QVariant v;
    if(role == Qt::CheckStateRole && idx.column() == BOOLEAN_COLUMN_INDEX)
        v = value.toInt() == Qt::Checked ? true : false;
    else
        v=value;
    bool r= QSqlTableModel::setData(idx,v,role);
qDebug() << (r ? "Y":"N"); //Always returns "false" for checkbox column. Why? How do I fix this?
    return r;
}

edit strategy:

CheckboxTableModel *model=new CheckboxTableModel(this);
model->setEditStrategy(QSqlTableModel::OnFieldChange);


When calling bool r= QSqlTableModel::setData(idx,v,role); instead of passing the role try calling with Qt::EditRole as below.

bool r= QSqlTableModel::setData(idx,v,Qt::EditRole);

I haven't tried it but i guess that this should make it work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜