在 Qt 6 中将 HICON 转换为 QIcon
Convert HICON to QIcon in Qt 6
我正在尝试将 HICON 转换为 Qt6 中的 QIcon/QPixmap。在旧的 Qt 版本中,曾经有一个 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;
但是,我一定是搞砸了。图像只是一些随机噪声,有时应用程序也会崩溃。
Displayed image
附加信息:图标是这样获取的:
HICON icon = (HICON)GetClassLong(hwnd, -14);
在 QT 6 中,QtWin::fromHICON() 的实现(减去到 QPixmap 的转换)已经转移到 QImage 的静态函数中。
所以现在你只需要。
QPixmap pixmap = QPixmap::fromImage(QImage::fromHICON(icon));
我正在尝试将 HICON 转换为 Qt6 中的 QIcon/QPixmap。在旧的 Qt 版本中,曾经有一个 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;
但是,我一定是搞砸了。图像只是一些随机噪声,有时应用程序也会崩溃。
Displayed image
附加信息:图标是这样获取的:
HICON icon = (HICON)GetClassLong(hwnd, -14);
在 QT 6 中,QtWin::fromHICON() 的实现(减去到 QPixmap 的转换)已经转移到 QImage 的静态函数中。 所以现在你只需要。
QPixmap pixmap = QPixmap::fromImage(QImage::fromHICON(icon));