dipesh
dipesh

Reputation: 45

Qt QGraphicsScene slow adding items

I have been trying to use QGraphicsScene to create editable grid using following code:

int w = 5;
int h = 5;
//QRect r(0, 0, w*1680, h*800);
//scene->setSceneRect(r);
//scene->setBspTreeDepth(5);
//scene->setItemIndexMethod(QGraphicsScene::NoIndex);
QTime t;
for(long i = 0; i < 800; ++i) {
    t.restart();
    for(long j = 0; j < 1680; ++j) {
        QGraphicsItem *item = scene->addRect(j*w, i*h, w, h, pen, brush);
        item->setFlag(QGraphicsItem::ItemIsSelectable, true);
    }
    qDebug() << "Elapsed Time: " << t.elapsed();
}
//scene->setItemIndexMethod(QGraphicsScene::BspTreeIndex);
setScene(scene);
//setSceneRect(0, 0, 200, 200);

As can be seen from the code, there are approximately 1 million rectangle in the scene. Time to add new item seems to increase polynomially rather than logarithmically as described in the Qt documentation. Am I doing something obviously wrong?

Upvotes: 2

Views: 2662

Answers (2)

Alexander Kondratskiy
Alexander Kondratskiy

Reputation: 4275

This answer is directed to the particular problem mentioned in the comments below the question- A static grid where various grid cells can be "selected".

The key idea here is that the grid is not deformable, and the selection of a cell is a "rare" occurance. An idea that comes to mind is to define the backgroundBrush property of the QGraphicsScene to draw the static grid for you, perhaps using a simple tile-able QPixmap. This is efficient as it is just a background to the scene and involves no dynamic objects.

To make cells selectable is to watch for mouse events in the scene, and when a user clicks somewhere in the scene, you can create a rectangle of your desired color in the appropriate location. This allows you to essentially have an infinite grid where any cell can be selected.

To watch mouse events, subclass QGraphicsScene and reimplement the eventFilter method where you will handle some of the mouse events for dealing with selections. You can now install this filter by calling the installEventFilter method of your scene.

Inside your eventFilter method, you will essentially look out for mouse events, and depending on their position create new colored rectangles at the appropriate location in the scene.

Hope this makes sense.

Upvotes: 4

Stephen Chu
Stephen Chu

Reputation: 12832

Setting itemIndexMethod to noIndex helps the item insertion performance. See: For QGraphicsScene using setZValue on a QGraphicsItem causes major slowdown

Upvotes: 1

Related Questions