脱离Qt的绘图系统(paint system)绘制图形

使用GDI在Qt窗口绘制

在Qt 5.11上测试通过,代码很少,自己看,特地写个博客,希望可以帮到你。

ReplayWidget.h

#pragma once

#include 

class ReplayWidget : public QWidget
{
    Q_OBJECT

public:
    ReplayWidget();
    ~ReplayWidget();
protected:
    typedef QWidget base;
    virtual QPaintEngine * paintEngine() const override;
    virtual bool event(QEvent * event) override;
    void paint();
};

ReplayWidget.cpp

#include 
#include 

#include 
#include 

#include "ReplayWidget.h"


ReplayWidget::ReplayWidget()
{
    setAutoFillBackground(false);
    //setAttribute(Qt::WA_NativeWindow);
    setAttribute(Qt::WA_PaintOnScreen);
}


ReplayWidget::~ReplayWidget()
{
}

QPaintEngine * ReplayWidget::paintEngine() const
{
    return nullptr;
}

bool ReplayWidget::event(QEvent * event) {
    //if (event->type() == QEvent::Paint) {
    //  bool result = base::event(event);
    //  paint();
    //  return result;
    //}
    if (event->type() == QEvent::UpdateRequest) {
        bool result = base::event(event);
        paint();
        return result;
    }
    return base::event(event);
}

void ReplayWidget::paint()
{
    WId handle = winId();
    HDC hdc = GetDC((HWND)handle);
    Gdiplus::Graphics g(hdc);
    auto blueBrush = new Gdiplus::SolidBrush(Gdiplus::Color::Blue);
    RECT rect;
    GetClientRect((HWND)handle, &rect);
    g.FillRectangle(blueBrush, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top);
    delete blueBrush; blueBrush = nullptr;
    auto redPen = new Gdiplus::Pen(Gdiplus::Color::Red, 2);
    g.DrawArc(redPen, 10, 10, 50, 50, 0, 360);
    SwapBuffers(hdc);
}

参考链接
显示结果
脱离Qt的绘图系统(paint system)绘制图形_第1张图片

你可能感兴趣的:(c++,Qt,GDI,GDI+)