Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt: Call a function with arguments periodically

Tags:

c++

qt

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?

like image 747
John Davis Avatar asked Jun 05 '26 21:06

John Davis


2 Answers

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 */
});
like image 187
epsilon Avatar answered Jun 07 '26 11:06

epsilon


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()] );
}
like image 25
p-a-o-l-o Avatar answered Jun 07 '26 12:06

p-a-o-l-o



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!