Display image from QAbstractTableModel

I am trying to display an image with a QAbstractTableModel . I tried to return QPixmap as QVariant from data() , but it only creates empty cells when I expect each cell in the second column to have a 20x20 black square.

This is my code:

 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); } 
+6
source share
1 answer

Only a QVariant that can be converted to a string can be returned for the Qt::DisplayRole role with a standard delegate.

You can show the image by returning it for the Qt::DecorationRole role

 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 make the picture yourself. See the QStyledItemDelegate Documentation for more details .

+5
source

Source: https://habr.com/ru/post/900648/


All Articles