thilomller
thilomller

Reputation: 23

Convert HICON to QIcon in Qt 6

I'm trying to convert a HICON to a QIcon/QPixmap in Qt6. In older Qt versions there used to be a fromHICON function that made this conversion very easy. Unfortunately, they removed it in Qt6 so I tried to do it myself following this answer:

HDC hdc = GetDC(hwnd);
HBITMAP hbitmap = CreateCompatibleBitmap(hdc, 32, 32);
hdc = CreateCompatibleDC(hdc);
SelectObject(hdc, hbitmap);

// Calculate size of buffer
BITMAP BitmapInfo = {0};
DWORD BitmapImageSize = BitmapInfo.bmHeight * BitmapInfo.bmWidth * (BitmapInfo.bmBitsPixel / 8);

// Allocate memory
BYTE *pBitmapData = new BYTE[BitmapImageSize];
ZeroMemory(pBitmapData, BitmapImageSize);

// Get Bitmap data
GetBitmapBits(hbitmap, BitmapImageSize, pBitmapData);

QImage image = QImage(pBitmapData, 32, 32, QImage::Format_ARGB32_Premultiplied);

ui->label->setPixmap(QPixmap::fromImage(image));
ui->label->setScaledContents(true);

// delete data
delete[] pBitmapData;

However, I must have messed something up. The image is just some random noise and sometimes the application also crashes.

Displayed image

Additional info: The icon is aquired like this:

HICON icon = (HICON)GetClassLong(hwnd, -14);

Upvotes: 2

Views: 1107

Answers (1)

Make that 4
Make that 4

Reputation: 256

In QT 6, the implementation (minus a convert to QPixmap) for QtWin::fromHICON() has moved into a static function for QImage. So now you just need to.

  QPixmap pixmap = QPixmap::fromImage(QImage::fromHICON(icon));

Upvotes: 6

Related Questions