Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying an image from a QAbstractTableModel

Tags:

qt

qt4

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);
}
like image 600
David Doria Avatar asked Nov 02 '11 22:11

David Doria


1 Answers

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.

like image 123
alexisdm Avatar answered Oct 13 '22 16:10

alexisdm