纯虚函数
[pure virtual] QRectF QGraphicsItem::boundingRect() const
的作用:
它是一个矩形框,这个框框是QGraphicsItem的外边框,打个比方,假如QGraphicsItem是一个人像,boundingRect()返回的就是相框边缘的矩形。
如下图(抱歉网上随便搜的一幅图,如有侵权请联系删除),黄色的框框表示这个boundingRect()返回的矩形,而方框里面的人物,景色,则为QGraphicsItem的内容,这个内容可以是多边形,矩形,三角形,直线等等
boundingRect()返回的这个矩形框的作用,是为了刷新里面的内容。
我们新建一个继承于QGraphicsItem的类,加到Qgraphicscene中去后,假如我们随意设置boundingRect()返回值,如0,0,100,100。 则只会刷新该固定区域。此时,如果我们的实际位置是其他,则很可能无法刷新。因此,很有必要将boundingRect()返回调整成实际物体所在位置的包含区域。
使用一个QPainterPath举例:
QRectF MyItem::boundingRect() const
{
qDebug()<<“boundingRect”;
return thisQRectF;
}
void MyItem::thisQRectF_init()
{
// quint32 rand_value = QRandomGenerator::global()->generate();
// thisQRectF= QRectF(rand_value%500, rand_value%800,rand_value%150, rand_value%180);
qreal startX,startY;
qreal maxX,maxY;
qreal tempPosX,tempPosY;
startX=100;
startY=100;
thisQPainterPath.moveTo(startX,startY);
maxX=startX;
maxY=startY;
tempPosX=150;
tempPosY=150;
thisQPainterPath.lineTo(tempPosX,tempPosY);
if(maxX<tempPosX)
{
maxX=tempPosX;
}
if(maxY<tempPosY)
{
maxY=tempPosY;
}
// thisQPainterPath.lineTo(750,250);
tempPosX=750;
tempPosY=250;
thisQPainterPath.lineTo(tempPosX,tempPosY);
if(maxX<tempPosX)
{
maxX=tempPosX;
}
if(maxY<tempPosY)
{
maxY=tempPosY;
}
// thisQPainterPath.lineTo(950,1250);
tempPosX=950;
tempPosY=1250;
thisQPainterPath.lineTo(tempPosX,tempPosY);
if(maxX<tempPosX)
{
maxX=tempPosX;
}
if(maxY<tempPosY)
{
maxY=tempPosY;
}
tempPosX=1150;
tempPosY=350;
thisQPainterPath.lineTo(tempPosX,tempPosY);
if(maxX<tempPosX)
{
maxX=tempPosX;
}
if(maxY<tempPosY)
{
maxY=tempPosY;
}
// thisQPainterPath.lineTo(140,250);
tempPosX=140;
tempPosY=250;
thisQPainterPath.lineTo(tempPosX,tempPosY);
if(maxX<tempPosX)
{
maxX=tempPosX;
}
if(maxY<tempPosY)
{
maxY=tempPosY;
}
// thisQPainterPath.lineTo(100,100);
thisQRectF= QRectF(startX,startY,maxX-startX,maxY-startY);
}
可以看到,当窗口移动后,所画的线条会随之刷新;
而当我们将boundingRect()返回调整到一个其他区域的矩形后,移动窗口,发现黄色线条随着窗口移动会逐渐不见!