简体   繁体   中英

QPainter::drawImage() clips QImage when X, Y are not 0 on a QDeclarativeItem

I'm developing a new QML element in C++ based on this sample code . My class inherits from QDeclarativeItem and it's paint() method is responsible to draw a QImage to the screen:

void NewQMLitem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    // image is QImage* that was loaded at the constructor of the class
    painter->drawImage(0, 0, *image);
}

The widget size is 800x480 and the image is 400x240. The code below works perfectly as long as the drawing starts at (0, 0) , as you can see below:

The problem I'm facing is that drawing at an arbitrary coordinate such as(200, 0), seems to clip the drawing. It looks like QPainter only updates the screen starting from (0, 0):

void NewQMLitem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    painter->drawImage(200, 0, *image);
}

And the following is the result:

My current workaround involves calling widget->update() at the end of the paint() . Of course, this is terrible because it makes the widget be painted twice.

What is the proper way to handle this? I'm currently using Qt 5.2 on Windows.

I found out that in these situations you need to call prepareGeometryChange() to let the parent know that the size/position of your widget has changed, and that it needs to query the new geometry to be able to paint it correctly to the screen.

This will make the parent invoke boundingRect() on your widget, so it's your responsibility to implement it:

void NewQMLitem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    prepareGeometryChange()
    painter->drawImage(200, 0, *image);
}

QRectF NewQMLitem::boundingRect() const
{
    return QRectF(m_x, m_y, m_width, m_height);
}

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