Qt使用GDI绘图关键在于获取HDC,对于Qt5来说,以前有两种方法。
1、使用gui-private
pro或pri文件中增加
QT += gui-private
代码:
#include
QPlatformNativeInterface *fooPlatformNativeInterface= QGuiApplication::platformNativeInterface();
QBackingStore *fooBackingStore = this->topLevelWidget()->backingStore();
HDC fooNRFWGetDC = static_cast(fooPlatformNativeInterface->nativeResourceForBackingStore(QByteArrayLiteral("getDC"), fooBackingStore));
这个方法不需要releaseDC
此方法使用了Qt官方不推荐使用的 gui-private,并且在整个窗口绘图,没有限制。
2、强行使用GetDC
pro或pri文件中增加
LIB += libgdi32
代码
#include
HWND hwnd = (HWND)this->window()->winId();
HDC hdc = GetDC(hwnd);
ReleaseDC(hwnd, dhc);
方法2只适用于顶层窗体。
此方法在整个窗口绘图,没有限制。
在Qt5.2中,新增了命名空间QtWin,这让我们有了方法3
3、使用QtWin
pro或pri文件中增加
QT += winextras代码
#include
HDC hdcScreen = GetDC(NULL);
HDC hdc = CreateCompatibleDC(hdcScreen);
HBITMAP hbm = CreateCompatibleBitmap(hdcScreen, rectForMap.width(), rectForMap.height());
SelectObject(hdc, hbm);
QImage img = QtWin::imageFromHBITMAP(hdc, hbm, rectForMap.width(), rectForMap.height());
//释放GDI资源
DeleteObject(hbm);
DeleteDC(hdc);
ReleaseDC(nullptr, hdcScreen);
此方法可以限制GDI的绘图范围。