I'm trying to get my table to display a QCheckBox for a column that is boolean (actually int) from a QSqlQueryModel.
I've implemented a delegate so when the field is clicked a check box appears and this works fine, but I can't work out what code to implement to get the column to display a check box instead of a 0 or 1.
I've read in another post:
You can reimplement QAbstractItemModel::flags() to return Qt::ItemIsUserCheckable together with other flags for the checkable column. But notice that you must also handle Qt::CheckStateRole in data() and setData().
With this in mind, I reimplemented flags() which seems to work
Qt::ItemFlags PurchaseOrdersRequests::flags(
{
flags |= Qt::ItemIsEditable;
if (index.column() == 6)
{
flags |= Qt::ItemIsUserCheckable;
}
return flags;
}
Qt::ItemFlags PurchaseOrdersRequests::flags(
const QModelIndex &index) const
{
Qt::ItemFlags flags = QSqlQueryModel::flags(index);
flags |= Qt::ItemIsEditable;
if (index.column() == 6)
{
flags |= Qt::ItemIsUserCheckable;
}
return flags;
}
To copy to clipboard, switch view to plain text mode
...but data() is totally wrong.
{
if (!index.isValid())
// if (role == Qt::ItemIsUserCheckable) // NEVER happens !
// qDebug() << " ItemIsUserCheckable";
if (role == Qt::DisplayRole)
{
QString val
= rec.
value(index.
column()).
toString();
return val; // ALWAYS returns an empty string :-(
}
else
}
QVariant PurchaseOrdersRequests::data ( const QModelIndex & index, int role ) const
{
if (!index.isValid())
return QVariant();
// if (role == Qt::ItemIsUserCheckable) // NEVER happens !
// qDebug() << " ItemIsUserCheckable";
if (role == Qt::DisplayRole)
{
QSqlRecord rec = record(index.row());
QString val = rec.value(index.column()).toString();
return val; // ALWAYS returns an empty string :-(
}
else
return QVariant();
}
To copy to clipboard, switch view to plain text mode
Problems are:
1) record() is returning empty values.
2) ItemIsUserCheckable returns false, I thought flags() would be called here where I set it (?)
3) I don't know what to do with CheckStateRole so there's nothing in my code to return a checkbox for display.
Bookmarks