Qt: QPainter + GDI in the same widget?

对着背影说爱祢 提交于 2020-03-16 07:36:08

问题


I'm trying to use the method described here to use a QPainter and GDI calls on the same widget.
Unfortunately this tutorial seem to have been written on an earlier version of Qt and now it does not work.

I set the WA_PaintOnScreen flag and reimplement paintEngine() to return NULL.

Then on the paintEvent() I create a QPainter, use it and then use some GDI calls to paint a bitmap. The GDI calls work fine but the QPainter does nothing. I get the following error on the console:

QPainter::begin: Paint device returned engine == 0, type: 1

Is this simply not supported anymore? how can I do it?

I've also tried creating an additional widget on top of the GDI-painting widget but that didn't go well as well since the top widget appears black and blocks the GDI widget.


回答1:


I got this working in QT 4.7-beta 2 as follows

  1. In the constructor call setAttribute(Qt::WA_PaintOnScreen,true);
  2. Do NOT reimplement paintEngine() to return NULL;
  3. Use the following code in the paintEvent();

    QPainter painter(this);
    HDC hdc = painter.paintEngine()->getDC();   // THIS IS THE CRITICAL STEP! 
    HWND hwnd = winID();
    
       // From this point on it is all regular GDI 
    QString text("Test GDI Paint");
    RECT rect;
    GetClientRect(hwnd, &rect);
    
    HBRUSH hbrRed = CreateSolidBrush(RGB(255,0,0));
    FillRect(hdc, &rect, hbrRed);
    HBRUSH hbrBlue = CreateSolidBrush(RGB(40,40,255));
    HPEN bpenGreen = CreatePen(PS_SOLID, 4, RGB(0,255,0));
    SelectObject(hdc,bpenGreen);
    SelectObject(hdc,hbrBlue);
    
    Ellipse(hdc,10,10,rect.right-20,rect.bottom-20);
    SetTextAlign(hdc, TA_CENTER | TA_BASELINE);
    TextOutW(hdc, width() / 2, height() / 2, text.utf16(), text.size());
    ReleaseDC(hwnd, hdc);
    



回答2:


This worked with Qt 4.0 and 4.1, but stopped working in either 4.2 or 4.3, when Trolltech reimplemented the Windows paint engine. In the second edition of the Qt 4 book, we added the sentence:

"For this to work, we must also reimplement QPaintDevice::paintEngine() to return a null pointer and set the Qt::WA_PaintOnScreen attribute in the widget's constructor."

I haven't tested it using later versions of Qt (I'm no longer at Trolltech/Nokia and have no Windows machine) but I hope it will still work.



来源:https://stackoverflow.com/questions/2616349/qt-qpainter-gdi-in-the-same-widget

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!