Problem:
I have a function void myFunc(data)
I am reading data from database using QSqlQuery:
QSqlQuery qry;
if (qry.exec("SELECT data, interval from table"))
{
while(qry.next())
{
// Somehow create and call function: myFunc(int data) periodically with interval = interval
}
}
As far as I understand I could use a timer like that:
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(myFunc()));
timer->start(interval); //time specified in ms
but how can I pass argument data to myFunc when I create this timer?
If you use C++11, you can connect your timer to a lambda function in which you capture your data value.
Example (untested):
int interval = 500;
int data = 42;
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, [data] {
/* Implement your logic here */
});
One more option: have a QObject-derived class that runs the function calling QObject::startTimer. In this same class, use a QMap<int, int> where each pair has the timer id as key and the data as value.
A simple implementation:
#include <QObject>
#include <QMap>
class TimedExecution : QObject
{
Q_OBJECT
public:
TimedExecution() : QObject(0){}
void addFunction(int data, int interval);
protected:
void timerEvent(QTimerEvent *event);
private:
QMap<int, int> map;
};
Use the addFunction method to create a new timed execution task (the passed interval is assumed to be expressed in seconds, here):
void TimedExecution::addFunction(int data, int interval)
{
map.insert(startTimer(interval * 1000), data);
}
Start the same function in the overridden timerEvent method, passing the data retrieved from the map, using the timer id retrieved from the timer event as the map key:
void TimedExecution::timerEvent(QTimerEvent *event)
{
myFunc( map[event->timerId()] );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With