QTableView with icons in rows

kasper360 picture kasper360 · Apr 4, 2011 · Viewed 13.5k times · Source

I have a QTableView showing rows of a database table. In this table I have a column called data type and I have icon images for each type. How can I add these icons in front of each data type?

Here's a part of my code as requested by justanothercoder.

QString msgQueryString = "select MESSAGE_ID, DATA_TYPE from SER_MESSAGES where MESSAGE_ID > 500 ";
serendibMsgTableModel->setQuery(msgQueryString, *database);
serendibMsgTableModel->setHeaderData(0, Qt::Horizontal, tr("Message ID"));
serendibMsgTableModel->setHeaderData(1, Qt::Horizontal, tr("Data Type"));

serendibMsgProxyModel->setSourceModel(serendibMsgTableModel);
serendibMsgView->setModel(serendibMsgProxyModel);

"serendibMsgTableModel" is a QSqlQueryModel and "serendibMsgProxyModel" is a customized QSortFilterProxyModel. "serendibMsgView" is the QTableView I need the icons to be displayed, in the Data Type column.

Hope this helps for your answer.

Answer

0xbaadf00d picture 0xbaadf00d · Apr 4, 2011

Set the DecorationRole of your items to the QPixmap you want and it should work.

edit:

I guess that the icon depends on the value in the data type column.

int rowCount = serendibMsgTableModel->rowCount();

for(int row = 0; row < rowCount; row++)
{
    QModelIndex index = serendibMsgTableModel->index(row, 1);
    QVariant value = serendibMsgTableModel->data(index);
    static QPixmap s_invalidIcon(PATH_TO_INVALID_ICON);
    static QPixmap s_type1Icon(PATH_TO_TYPE1_ICON);
    static QPixmap s_type2Icon(PATH_TO_TYPE2_ICON);

    QPixmap icon(s_invalidIcon);

    if(value.toString() == "type1")
    {
        icon = s_type1Icon;
    }
    else if(value.toString() == "type2")
    {
        icon = s_type2Icon;
    }
    serendibMsgTableModel->setData(index, icon, Qt::DecorationRole);
}

Something like this should work. Set the values before setModel.

I haven't tested it, but I think you should get the idea from this.