Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert QIcon to QPixmap

Tags:

c++

qt

qt4

qt3

I have following code and I have to change it with Qt4 code.

QIcon icon;
QPixmap pixmap = icon.pixmap();    // Qt3 code

for replacing Qt3 code with Qt4, I have to replace pixmap() with one of following methods provided by the Qt4.

QPixmap QIcon::pixmap ( const QSize & size, Mode mode = Normal, State state = Off ) const  
QPixmap QIcon::pixmap ( int w, int h, Mode mode = Normal, State state = Off ) const
QPixmap QIcon::pixmap ( int extent, Mode mode = Normal, State state = Off ) const

Since I don't know what size or dimension it is using in this call of pixmap(void). So I need to find out alternative which can eliminate this code without asking explicitly size.

What I understand from this code segment. It is taking size of icon. So I try to find out size of icon. But again I do not find any method to get size of icon.

like image 239
Jai Avatar asked Nov 20 '14 07:11

Jai


1 Answers

QIcon may contain multiple images with different sizes, a generic icon.pixmap() is too much arbitrary (which size will be used to build QPixmap?). pixmap() method is still available but you have to specify which size you want.

If you know size then you can simply use:

QPixmap pixmap = icon.pixmap(requiredImageSize);

If you don't (as in your case) then you have some alternatives. First you may ask for an image with a specified size (or less) using QIcon::actualSize() method.

QPixmap pixmap = icon.pixmap(icon.actualSize(QSize(32, 32)));

Suppsing icon contains 16x16, 24x24 and 64x64 then it'll return 24x24 (biggest image smaller than what you specified).

Second alternative is to pick biggest available image (assuming width and height are always equal) querying sizes using QIcon::availableSizes():

QList<QSize> sizes = icon.availableSizes();
int maximum = sizes[0].width();
for (int i=1; i < sizes.size(); ++i)
    maximum = qMax(maximum, sizes[i].width());

QPixmap pixmap = icon.pixmap(QSize(maximum, maximum));

Note that if you use first method and you specify a value big enough then you'll have same result:

QPixmap pixmap = icon.pixmap(icon.actualSize(QSize(1024, 1024)));

Of course you may also simply pick first/last available size:

QPixmap pixmap = icon.pixmap(icon.availableSizes().first());
QPixmap pixmap = icon.pixmap(icon.availableSizes().last());
like image 123
Adriano Repetti Avatar answered Oct 23 '22 01:10

Adriano Repetti