简体   繁体   English

Qmap中的Qtimer对象发送的超时信号是从哪个key发出来的?

[英]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.在一个function中,如何理解我在Qmap中创建的Qtimer对象发送的信号,如何在槽function中找到信号来自哪个object。

I created Qmap above code SQL.h我在代码 SQL.h 上面创建了 Qmap

public slots:
 void experiment();
 void run();
private:
 QMap<QString,QTimer*> job;

I create QMap value and key with Qtimer.我使用 Qtimer 创建 QMap 值和键。 SQL.cpp 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?在这个slot中,我如何了解Qmap中的哪个Qtimer当时接收到信号?

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.我以为我可以将 sender() 与 Qmapiterator 一起使用,但我不知道如何使用。 can you help?你能帮我吗?

Old way is using QSignalMapper .旧方法是使用QSignalMapper You could also set the key as dynamic property of the timer object, so you could access it through QObject::sender() .您还可以将密钥设置为计时器 object 的动态属性,这样您就可以通过QObject::sender()访问它。 But, today you should probably just use a lambda.但是,今天你应该只使用 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然后,只需使用 lambda 即可轻松传递所需参数

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.作为旁注,您不应该使用旧的SIGNAL()SLOT()宏,除非您出于某种原因确实需要这样做。 Use the "new" (10 years old) connect syntax.使用“新”(10 岁)连接语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM