In a function, how to understand the signal sent from Qtimer objects that I created in Qmap, how to find from which object the signal comes from in the slot function.
I created Qmap above code SQL.h
public slots:
void experiment();
void run();
private:
QMap<QString,QTimer*> job;
I create QMap value and key with Qtimer. SQL.cpp
void SQL::experiment()
{
QTimer *timer=new Qtimer();
job.insert("dd",timer);
QTimer *timer1=new Qtimer();
job.insert("ss",timer1);
job.value("dd")->start();
job.value("dd")->setInterval)(5000);
job.value("ss")->start();
job.value("ss")->setInterval)(10000);
connect(job.value("dd"),SIGNAL(timeout()),this,SLOT(run()));
connect(job.value("ss"),SIGNAL(timeout()),this,SLOT(run()));
}
In this slot, how can I understand which of the Qtimer in the Qmap receives a signal at that time?
void SQL::run()
{
//job.value(key) // how to understand key
}
I thought I could use sender() with Qmapiterator, but I couldn't find out how. can you help?
Old way is using QSignalMapper
. You could also set the key as dynamic property of the timer object, so you could access it through QObject::sender()
. But, today you should probably just use a lambda.
First, change the run slot to take any parameters you want:
void SQL::run(const QString &key)
{
QTimer *timer = job.value(key);
}
Then, just use lambda to easily pass the required parameters
QString name="ff";
connect(job.value(name), &QTimer::timeout, this, [this, name]() {
run(name);
});
// name is capture by value above,
// so changing name variable later does not
// affect the value captured by the lambda
As a side note, you shouldn't use the old SIGNAL()
and SLOT()
macros unless you really have to for some reason. Use the "new" (10 years old) connect syntax.