PDA

View Full Version : Return image from custom model depending on selected state



MrGentleman
30th August 2017, 06:55
Hello folks,

I am using Qt 4.8 and I am wondering if it possible to return an image from a custom model's QAbstractItemModel::data()-implementation based on a 'selected' row state.

I have implemented the method data() following, where MyTreeModel is derived from QAbstractItemModel


QVariant MyTreeModel::data(const QModelIndex &index, int role) const {

if (!index.isValid()) return QVariant();

// Handle some other roles...

if (role == Qt::DecorationRole && index.column() == GEARS_COLUMN) {
// Is there any way to determine whether index.row() is selected in the view
// in order to return an other image, e.g.
// return IS_ROW_SELECTED(index) ? QImage(":/icons/gears_selected") : QImage(":/icons/gears_unselected");
//
return QImage(":/icons/gears_selected");
}

return QVariant();
}

Thanks in advance and best regards,
michael


By playing around I finally figured out the solution - just return a QIcon instead of a QPixmap :)



QVariant MyTreeModel::data(const QModelIndex &index, int role) const {

if (!index.isValid()) return QVariant();

// Handle some other roles...

if (role == Qt::DecorationRole && index.column() == GEARS_COLUMN) {
// Simply return an icon with pixmaps for different modes, then the QTreeView will decide
// which icon to render. In order to have ensured that the icon has a defined size, call QTreeView::setIconSize()

QIcon icon;
icon.addPixmap(QPixmap(":/icons/gears_unselected"), QIcon::Normal);
icon.addPixmap(QPixmap(":/icons/gears_selected"), QIcon::Selected);
return icon;
}

return QVariant();
}


Regards, michael

wysota
30th August 2017, 06:57
There are two approaches. First you can have two separate roles each returning a single image and then use a custom delegate to pick the one that should be drawn.
The second approach is to return QIcon instead of QImage so that you can set multiple pixmaps for different conditions.


QIcon icon;
icon.addFile(":/icons/gears");
icon.addFile(":/icons/gears_selected", QSize(), QIcon::Selected);