简体   繁体   中英

QVariant to QIcon/QPixmap/QImage

I want to extract a QIcon I've stored in one of a QTreeWidget's columns, as Qt::DecorationRole.

QTreeWidgetItem *item = ui->treeWidget->topLevelItem(index);
const QIcon &icon = item->data(0, Qt::DecorationRole)._howToConvert_();

However, I can only get the data as QVariant, and I could not find a function to convert from a QVariant to QIcon. Is it possible to do it?

OK, found the answer in the docs for QVariant upon further inspection.

This works:

QImage image = variant.value<QImage>();

I didn't find it immediately because I searched for QIcon/QPixmap/QImage, and they are not mentioned at all, I should have searched for QColor instead :)

A Note on GUI Types

Because QVariant is part of the QtCore library, it cannot provide conversion functions to data types defined in QtGui, such as QColor , QImage , and QPixmap . In other words, there is no toColor() function. Instead, you can use the QVariant::value() or the qvariant_cast() template function. For example:

 QVariant variant; ... QColor color = variant.value<QColor>(); 

The inverse conversion (eg, from QColor to QVariant ) is automatic for all data types supported by QVariant , including GUI-related types:

 QColor color = palette().background().color(); QVariant variant = color; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM