我有QWidget
持有QGraphicsScene
个项目。其中一些项目是QGraphicsRectItem
和子类QGraphicsItem
。当在场景中只有QGraphicsRectItem
时,应用程序的性能很好,处理器使用率正常,在0%到10%之间。但是当我向场景中添加QGraphicsItem
时,始终会调用paint事件,这会使处理器使用率提高到50% - 70%,有时应用程序会被冻结。
当我将QGraphicsView viewUpdateMode设置为QGraphicsView :: NoViewportUpdate时,处理器的使用情况很好,包括QGraphicsItems和QGraphicsRectItems,但是当viewUpdateMode设置为QGraphicsView :: FullViewportUpdate时,QGraphicsView :: MinimalViewportUpdate或QGraphicsView :: BoundingRectViewportUpdate然后即使在场景中没有修改,QGraphicsItem中的paint事件也会在循环中调用。
这是我创建QGraphicsScene的方式,而QGrpahicsView就是这样。
scene = new QGraphicsScene();
scene->setItemIndexMethod(QGraphicsScene::NoIndex);
scene->setSceneRect(0, 0, 470, 720);
view = new QGraphicsView(scene);
view->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::TextAntialiasing);
view->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
view->setMouseTracking(true);
子类化的QGraphicsItem是这样的:
MyItem::MyItem(QGraphicsItem *parent)
: QGraphicsItem(parent),
mIsHover(false), mIsSelected(false)
{
pixmapItem1 = new QGraphicsPixmapItem(this);
pixmapItem2 = new QGraphicsPixmapItem(this);
textItem = new QGraphicsTextItem(this);
pixmapItem1->setParentItem(this);
pixmapItem2->setParentItem(this);
textItem->setParentItem(this);
textItem->setTextWidth(60);
this->setAcceptTouchEvents(true);
this->setAcceptDrops(true);
this->setAcceptHoverEvents(true);
this->setAcceptedMouseButtons(Qt::LeftButton);
this->setFlag(QGraphicsItem::ItemIsSelectable);
this->setFlag(QGraphicsItem::ItemIsMovable);
this->setFlag(QGraphicsItem::ItemSendsGeometryChanges);
this->setFlag(QGraphicsItem::ItemSendsScenePositionChanges);
}
QRectF MyItem::boundingRect() const
{
QRectF rect = this->childrenBoundingRect();
return rect;
}
void MyItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* opt,QWidget* wdgt)
{
qDebug() << "-> MyItem::pain()";
painter->setClipRect(this->boundingRect());
if(this->mIsHover || this->mIsSelected){
painter->setBrush(QColor(Qt::green));
painter->setPen(Qt::black);
painter->drawRect(this->boundingRect());
}else{
painter->setBrush(Qt::transparent);
painter->setPen(Qt::NoPen);
painter->drawRect(this->boundingRect());
}
}
void MyItem::hoverEnterEvent(QGraphicsSceneHoverEvent*)
{
qDebug() << Q_FUNC_INFO;
this->mIsHover = true;
this->update();
}
void MyItem::hoverLeaveEvent(QGraphicsSceneHoverEvent*)
{
qDebug() << Q_FUNC_INFO;
this->mIsHover = false;
this->update();
}
所以问题是,如何在场景中或场景中的任何对象中进行任何修改并且不让QGraphicsScene始终调用QGraphicsItem绘制事件时,如何调用paint事件? ?
答案 0 :(得分:0)
您可以使用caching:
// Put this in the constructor of your QGraphicsItem
setCacheMode( QGraphicsItem::DeviceCoordinateCache );
// or
setCacheMode( QGraphicsItem::ItemCoordinateCache);