简体   繁体   中英

how to paint outside of paintEvent()? Qt, C++

I am trying to draw rectangle outside of paintEvent().

If users click and drag the screen with their mouse, application should draw 'Selecting Area'.

But it seems impossible painting outside of paintEvent().

I already solved this problem on MFC with ReleaseDC().

Here is My Code on MFC:

void DrawingPaper::DrawSelectingArea() {
    CDC *dc = this->GetDC();
    CPen pen;
    CPen *oldPen;

    dc->SetROP2(R2_NOTXORPEN);

    pen.CreatePen(PS_DOT, 1, RGB(166, 166, 166));

    oldPen = dc->SelectObject(&pen);

    dc->Rectangle(this->startX, this->startY, this->currentX, this->currentY);

    dc->SelectObject(oldPen);
    this->ReleaseDC(dc);

    DeleteObject(pen);
}

it works well although the code is not in OnPaint().

But on Qt, how?

here is my code on Qt:

void DrawingPaper::DrawSelectingArea() {
    QPainter painter(this);

    QRect drawRect(this->startX, this->startY, this->currentX, this->currentY);
    painter.drawRect(drawRect);

    //this->ReleaseDC(dc);
}

it does not work because painter that draw rectangle will be removed by other QPainter in paintEvent().

Is there any solution like ReleaseDC()?

I am on Qt 5.12.6.

Thanks for your help.

The short answer is, you can't — Qt does not work that way. If you're outside of paintEvent() and you want to repaint your widget, what you need to do is call update() instead. That will cause paintEvent() to be called ASAP, and then your code inside paintEvent() can do the actual painting.

That said, if you absolutely must do your painting elsewhere, you can create a QPixmap object that is the same width and height as your widget, and pass a pointer to that QPixmap to the constructor of your QPainter object, and paint into the QPixmap. Then when you are done, call update(), which will cause paintEvent() to be called ASAP, and in the paintEvent() call you can call drawPixmap() with that QPixmap as an argument, to copy the pixels from the QPixmap to the widget's on-screen buffer. Note that this is less efficient than just doing the original painting directly inside paintEvent(), though, since this approach requires the pixels to be copied an additional time (and possibly also causes the image to be drawn more often than is necessary)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM