Qt List of Callbacks
I am trying to make a real-time data collection application that has timed task. Each task can have a different or the same update period. I would like to store the task with the common update period in a list where I can iterate through it and call the function that I registered in the list. How would I go about adding callbacks to a data structu开发者_开发百科re like a list or vector? Can I store slots in them?
You can add callback functions in the form of boost::function into a data structure such as list or vector.
However, if you are having timed tasks and would like these tasks to repeat at certain intervals, you can simply store a list of QTimer
QList<QTimer> timed_tasks;
In your setup, you will connect the correct timer to the correct slot functions. Then start your Qt event loop.
If you are running a very tight collection program (i.e. many long tasks but needs to perform in real time), you should have your slot functions on separate threads. That way your main event loop can still run (and fire off tasks). Otherwise, tasks that take too long will starve other tasks since the event loop doesn't return in time to fire the other due tasks.
You can also implement these tasks in term of QRunnable and provide a QThreadPool which will run them. I suggest you check out http://doc.qt.io/archives/4.6/threads.html if you are going down this road.
UPDATE: The solution suggested above will handle multiple timers that fire at the same time. In order to give the user control over which timer to fire (i.e. which value to collect), you can use QObject::killTimer and QObject::startTimer. This does not require any extra storage space for bit tables or some other mechanism to store which timer is currently active.
精彩评论