How can I find from which key the timeout signal sent from Qtimer objects in Qmap comes from?

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();
 QMap<QString,QTimer*> job;

I create QMap value and key with Qtimer. SQL.cpp

void SQL::experiment()
  QTimer *timer=new Qtimer();

  QTimer *timer1=new Qtimer();




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?

1 answer

  • answered 2022-04-21 06:54 hyde

    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]() { 
            // 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.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum