在.h里面定义
QImage *image;//先画到image上面,然后再贴上去
bool painterok = false;//判断是否是第一次绘图,第一次绘图完毕,下次painterok为true,不在绘图,只是贴image;
.cpp
重载paint函数
void RoboPointItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
// Q_UNUSED(widget)
Q_UNUSED(option);
if(painterok)//判断 boundingRect是你自己规定的大小
{
painter->setRenderHint(QPainter::Antialiasing, true);
painter->drawImage(static_cast<int>( boundingRect().x()),
static_cast<int>( boundingRect().y()),*image);
return;
}
//你的第一次绘图的内容 begin
QPainter paint(image);
paint.setRenderHint(QPainter::Antialiasing, true);
paint.setPen(pen);
foreach (auto item,MapAllPoint)
{
paint.drawPoint(QPointF(item.x,item.y));
}
paint.setPen(MapPen);
paint.setBrush(MapBrush);
paint.drawRect(BoundingRect.adjusted(-20, -20, 20, 20));
paint.fillRect(BoundingRect.adjusted(-20, -20, 20, 20), QColor(15, 15, 15, 35));
//你的第一次绘图内容 end
// image->save("a.png");
// painter->drawPixmap(static_cast<int>( boundingRect().x()),
// static_cast<int>( boundingRect().y()),*pixmap);
painterok = true;
}
注意几个坑:
1:可能回一直报 Painter not active
这个时候看看你的image在构造函数定义的时候有给初始值的大小吗?类是这样
image = new QImage(static_cast<int>(boundingRect().width()),static_cast<int>(boundingRect().height()), QImage::Format::Format_RGB32);
2:还有我为啥在painter里面又定义了一个paint,因为之前我直接用参数列表里面的painter去画在image上面,不管是用begin(),end()函数,还是其他的都不行,第一次画的好好的,第二次就不显示了,后来我保存了image,一看,根本就没画上去。后来才想着定义一个画好了之后,再用参数里面的painter去贴image.
3.这种直接在paint函数里面进行双缓冲绘制的,前提是你的这个对象是临时变量,用的时候就会new,然后给新的数据,不然如果是全局的变量,那就不行了,只能采用放在外面写,需要刷新的时候先调用那个函数,将新的数据画上去,然后再update();就好了