[Qt-interest] update qgraphicsscene

Murphy, Sean M. sean.murphy at gd-ais.com
Mon May 24 21:58:27 CEST 2010


> I have the need to update a QGraphicsView widget with a new QImage everytime I call a certain function 
> ("populateScene"). Currently I create  a new QGraphicsScene instance everytime I call this function, is 
> there some better way to update the scene without creating a new instance of QGraphicsScene every time? 
> (I am assuming this would slow things down and also I will not be able to delete the QGraphicsScene 
> pointer at the end since this would clear the image from the viewport).  My code below-
>
> void populateScene(QImage* image)
> {
>   QGraphicsScene* scene = new QGraphicsScene;
>   QPixmap np = QPixmap::fromImage(*image);
>   
>   qGraphicsItem->setPixmap(np);
>   scene->addItem(qGraphicsItem); 
>
>   qgraphicsView->setPixmap(np);
>   
> }

It looks like what you've got above is pseudo code since a few of your lines won't compile.  QGraphicsItem doesn't have setPixmap(), that's QGraphicsPixmapItem, and QGraphicsView also doesn't have a setPixmap() function.

> qGraphicsItem: QGraphicsItem, initialized in the constructor
> qgraphicsView: QGRaphicsView, initialized in constructor

Anyways, what you want to do is move your scene initialization to the constructor, as well as your QGraphicsPixmapItem initialization.  From what you've told us, you'll only need one of each for the lifetime of the application.

The just make populateScene be:

void populateScene(QImage* image)
{
  qGraphicsPixmapItem->setPixmap(QPixmap::fromImage(*image));
  scene->setSceneRect(0,0,image->width(), image->height());
}

You could add a qgraphicsView->centerOn(x,y) if you want to guarantee the new image is centered.
Sean




More information about the Qt-interest-old mailing list