I am trying to display an image from a QAbstractTableModel
. I tried returning a QPixmap
as the QVariant
of data()
, but it only produces empty cells, when I would expect every cell in the second column to have a 20x20 black square.
This is my code currently:
QVariant MySqlTableModel::data(const QModelIndex &idx, int role = Qt::DisplayRole) const
{
if (role == Qt::DisplayRole && idx.column() == 1) {
QPixmap pixmap(20,20);
QColor black(0,0,0);
pixmap.fill(black);
return pixmap;
}
return QSqlTableModel::data(idx, role);
}
Only QVariant
s that can be converted to string can be returned for the role Qt::DisplayRole
with the standard delegate.
You can show the image by returning it for the role Qt::DecorationRole
QVariant MySqlTableModel::data(const QModelIndex &idx, int role = Qt::DisplayRole) const
{
if (idx.column() == 1) {
if (role == Qt::DecorationRole) {
QPixmap pixmap(20,20);
QColor black(0,0,0);
pixmap.fill(black);
return pixmap;
} else if (role == Qt::DisplayRole) {
// For Qt::DisplayRole return an empty string, otherwise
// you will have *both* text and image displayed.
return "";
}
}
return QSqlTableModel::data(idx, role);
}
Or write your own delegate to do the painting yourself. See QStyledItemDelegate documentation for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With