Reputation: 154
What is the best/most considrable way to queue fired connections in one thread to not freeze the gui?
E.g. I have a QGraphicsScene where I can freely move QGraphicsItem. I want to start a time consuming claculation with the current Item position. But one single calculation is fast enough to not recogize the gui freeze.
So, just connecting to itemChange()
afte doing setFlag(QGraphicsItem::ItemSendsScenePositionChanges, true);
is too expensive: the GUI freezes because of new calculations at every move.
I want to queue the connection to just fire, let's say every 500ms, not on every move. (Or after 500ms of no user input)
Upvotes: 5
Views: 263
Reputation: 30860
Create a timer with a 500ms timeout, set up to run expensiveCalculation
once and then stop.
QTimer *t = new QTimer(this);
t->setInterval(500);
QObject::connect(t, &QTimer::timeout, t, &QTimer::stop);
QObject::connect(t, &QTimer::timeout, this, &expensiveCalculation);
Now connect the itemChanged
signal to its start
slot. This will start or restart the timer every time the signal is fired. If no new events appear for 500ms, the timer goes off and does expensiveCalculation
.
QObject::connect(item, &QGraphicsItem::itemChanged, t, &QTimer::start);
Upvotes: 1