QTableView with row icons

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

Here is part of my code at the request of 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 the QSqlQueryModel , and "serendibMsgProxyModel" is the custom QSortFilterProxyModel . "serendibMsgView" is a QTableView I need the icons that will be displayed in the "Data Type" column.

Hope this helps you answer.

+4
source share
2 answers

Set the DecorationRole of your items in the QPixmap that you want, and it should work.

edit:

I think 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 have not tested it, but I think you should get this idea.

+4
source

I saw that you have already chosen the answer, but since you are learning Qt, I will add a few things.

Looking at the excellent Qt documentation, I suggest you rewrite this in your model:

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

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

Qt :: ItemDataRole enumeration : Each model element has a set of data elements associated with it, each with its own role. Roles are used to indicate to the model which data type it needs. custom models should return data in these types.

Qt :: DecorationRole : data to be made as decoration in the form of an icon. (QColor, QIcon or QPixmap)

So you need to return QIcon or QPixmap to the data () function for DisplayRole.

Another approach that might be more appropriate is to use delegates : for example, ColorListEditor

+3
source

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


All Articles