How to enter and read an Icon image into/from a ListWidget data model with a Delegate
-
Hi,
I am using a Delegate to retrieve data from a ListWidget data model to be able to control how I display the data in the ListWidgetItem items. My code compiles fine but when I debug the Delegate I can see that the retrieved Icon points to "null". So it seems that the Icon is not being found in the model. I wonder if someone can tell what the problem is. Here are the snippets of the code that are revelant. Thank you!In MainWindow construtor: I enter the Icon into the data model of ListWidget
@
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
QVBoxLayout *hlayout = new QVBoxLayout();
QListWidget *myListWidget = new QListWidget();
// Setting Delegate
myListWidget->setItemDelegate(new ListDelegate(myListWidget));QListWidgetItem *item = new QListWidgetItem();
QPixmap pixmap(":/images/arrow.png");
QIcon ic(pixmap);
QVariant v(QMetaType::QIcon, &ic);//Add Icon to model with custom role
item->setData(Qt::UserRole + 3, v);// Add strings
item->setData(Qt::DisplayRole, "Wine");
//item->setData(Qt::UserRole + 1, "Description");
myListWidget->addItem(item);// BEER QListWidgetItem *item2 = new QListWidgetItem(); item2->setData(Qt::DisplayRole, "Beer"); myListWidget->addItem(item2); myListWidget->setLayout(hlayout); setCentralWidget(myListWidget);
@
In the Delegate: Read Icon and display in ListWidget--
@
void ListDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QRect r = option.rect; //rectangle of listitem// THE FOLLOWING FUNCTION RETURNS A NULL POINTER for ic
QIcon ic = QIcon(qvariant_cast<QPixmap>(index.data(Qt::UserRole + 3)));
r = option.rect.adjusted(5, 10, -10, -10);
ic.paint(painter, r, Qt::AlignVCenter|Qt::AlignRight);
}@
-
That is so funny, how just telling others about your bug, helps you find the solution. I fiddled some more and realized what you just said so I fixed it. Thanks Gerolf for confirming.
So I replaced this line in the Delegate:
@
QIcon ic = QIcon(qvariant_cast<QPixmap>(index.data(Qt::UserRole + 3)));
@With:
@QVariant v = index.data(Qt::UserRole + 3);
QIcon ic = v.value<QIcon>();@