PDA

View Full Version : QGraphicsView/QGraphicsScene/QGraphicsItem slow pos updating



ben1996123
21st October 2013, 17:35
I have a lot of items in a QGraphicsScene (about 10000), and I need to update the position of every one of them, but when I do this it can take over 1 minute, so how can I (if possible) make it faster?

Here's the position update code:


void Dialog::updateAllPositions(){
int x,y,z,x2,y2;
for(int aa=0;aa<size.x()*size.y();aa++){
x=aa%size.x();
y=aa/size.x();
z=tiles[y][x];
if(z==0) continue;
x2=(z-1)%size.x();
y2=(z-1)/size.x();
scene->items()[size.x()*size.y()-1-z]->setPos(ssize*x+sgap*x-sgap+(ssize-fontMetric.width(QString::number(z)))/2, ssize*y+sgap*y-sgap+(ssize-fontMetric.height())/2);
scene->items()[2*size.x()*size.y()-2-z]->setPos((x-x2)*ssize+(x-x2)*sgap, (y-y2)*ssize+(y-y2)*sgap);
}
}

ssize and sgap are constants. Even if I disable viewport updating it still takes just as long. Any ideas?

ben1996123
22nd October 2013, 01:18
fixed

for anyone who has the same problem, heres what I did (even though tbh I dont really understand completely how it works)

I made a QList<QGraphicsItem*> q and set it equal to scene->items(), then instead of doing scene->items()[stuff]->setPos, do q[stuff]->setPos and it works a lot faster (I dont really understand why it works because scene->items is a const function and I never had to tell the scene that its items had changed, just change them in q)


void Dialog::updateAllPositions(){
int x,y,z,x2,y2;
QList<QGraphicsItem*> q=scene->items();
for(int aa=0;aa<size.x()*size.y();aa++){
x=aa%size.x();
y=aa/size.x();
z=tiles[y][x];
if(z==0) continue;
x2=(z-1)%size.x();
y2=(z-1)/size.x();
q[size.x()*size.y()-1-z]->setPos(ssize*x+sgap*x-sgap+(ssize-fontMetric.width(QString::number(z)))/2, ssize*y+sgap*y-sgap+(ssize-fontMetric.height())/2);
q[2*size.x()*size.y()-2-z]->setPos((x-x2)*ssize+(x-x2)*sgap, (y-y2)*ssize+(y-y2)*sgap);
}
}

its faster because it doesnt have to call scene->items thousands of times (each time returning a huge qlist). with 20k items, it only took 0.15 seconds intead of 12 minutes :p

spirit
22nd October 2013, 08:24
Well, QGraphicsView::items is declared with const, but it returns a list of pointer to non-const items. So, you are fine. ;)

ben1996123
24th October 2013, 02:16
Well, QGraphicsView::items is declared with const, but it returns a list of pointer to non-const items. So, you are fine. ;)

ah, that makes sense, thanks