简体   繁体   English

当QDeclarativeItem上的X,Y不为0时,QPainter :: drawImage()剪辑QImage

[英]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 . 我正在基于此示例代码在C ++中开发一个新的QML元素。 My class inherits from QDeclarativeItem and it's paint() method is responsible to draw a QImage to the screen: 我的类继承自QDeclarativeItem ,它的paint()方法负责将QImage绘制到屏幕:

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. 小部件大小为800x480,图像为400x240。 The code below works perfectly as long as the drawing starts at (0, 0) , as you can see below: 只要绘图从(0,0)开始,下面的代码就可以完美地工作 ,如下所示:

The problem I'm facing is that drawing at an arbitrary coordinate such as(200, 0), seems to clip the drawing. 我面临的问题是在任意坐标(如(200,0))上绘图似乎会剪切绘图。 It looks like QPainter only updates the screen starting from (0, 0): 看起来QPainter只从(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() . 我目前的解决方法是在paint()的末尾调用widget->update() 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. 我目前正在Windows上使用Qt 5.2。

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. 我发现在这些情况下你需要调用prepareGeometryChange()让父母知道你的小部件的大小/位置已经改变,并且它需要查询新几何以便能够正确地将它绘制到屏幕上。

This will make the parent invoke boundingRect() on your widget, so it's your responsibility to implement it: 这将使 boundingRect()在您的窗口小部件上调用boundingRect() ,因此您有责任实现它:

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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