David Doria
David Doria

Reputation: 10273

Displaying an image from a QAbstractTableModel

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);
}

Upvotes: 7

Views: 3730

Answers (1)

alexisdm
alexisdm

Reputation: 29896

Only QVariants 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.

Upvotes: 8

Related Questions