PDA

View Full Version : Using images in QComboBox



jonks
8th December 2009, 06:22
Hi,

What is the correct way to get a combobox to display images?
(The images are 120x90)

Do I need to create an ItemModel (derived from QAbstractItemModel) and then use QComboBox::setModel() ?

Or is there an easier way?

Thanks

spirit
8th December 2009, 06:31
you can try to create your own delegate.

spirit
8th December 2009, 06:48
so, you should get something like this


void PixmapDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
const QPixmap pixmap = qVariantValue<QPixmap>(index.data(Qt::UserRole));
painter->drawPixmap(option.rect, pixmap);
QItemDelegate::paint(painter, option, index);
}

QSize PixmapDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
Q_UNUSED(option);
const QPixmap pixmap = qVariantValue<QPixmap>(index.data(Qt::UserRole));
return pixmap.size();
}
...
QComboBox *cb = new QComboBox();
cb->setItemDelegate(new PixmaDelegate(cb));
for (int i = 0; i < 10; ++i) {
QPixmap pixmap(100, 100);
pixmap.fill(QColor(qrand() % 255, qrand() % 255, qrand() % 255));
cb->addItem(QString("item%1").arg(i), pixmap);
}
QVBoxLayout *vbl = new QVBoxLayout(this);
vbl->addWidget(cb);
...

jonks
8th December 2009, 13:17
Thanks - I tried that but it does no give me the exact effect I need because when using it the current selection is not rendered as an image.

However, using:-

1) QAbstractItemModel and calling QComboBox::setIconSize to ensure the images are not scaled.

and 2) QItemDelegate for the drop list, I get the exact effect I need

spirit
8th December 2009, 17:57
reimplement QItemDelegate::drawFocus. you need write something like this


void PixmapDelegate::drawFocus ( QPainter * painter, const QStyleOptionViewItem & option, const QRect & rect ) const
{
Q_UNUSED(painter);
Q_UNUSED(option);
Q_UNUSED(rect);
//nothig to do
}

IMHO, you don't need any custom model for this task.