开发者

QTableView with icons in rows

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(serendib开发者_如何学PythonMsgTableModel);
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.


I saw that you've already picked an answer but since you are learning Qt I'll add a few things.

Taking a look at the excellent Qt documentation I suggest you overwrite this in your model:

QVariant QSqlTableModel::data ( 
            const QModelIndex & index,
            int role = Qt::DisplayRole ) const   [virtual]

There are various roles (int role = Qt::DisplayRole):

enum Qt::ItemDataRole : Each item in the model has a set of data elements associated with it, each with its own role. The roles are used by the view to indicate to the model which type of data it needs. Custom models should return data in these types.

Qt::DecorationRole : The data to be rendered as a decoration in the form of an icon. (QColor, QIcon or Qpixmap)

Thus, what you need to do is return a QIcon or QPixmap in the data() function for the DisplayRole.

Another approach which might be more appropriate is to make use of delegates: For example ColorListEditor


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜