如何使用Qtimer添加1秒延迟 [英] how to add a 1 second delay using Qtimer
问题描述
我目前有一个方法如下
void SomeMethod(int a)
{
//Delay for one sec.
timer->start(1000);
//After one sec
SomeOtherFunction(a);
}
此方法实际上是附加到信号的插槽。我想添加一个延迟1秒使用Qtimer.However我不知道如何完成这个。由于定时器在其完成时触发信号,并且信号将需要附接到不接受任何参数的另一方法。任何建议,如何我可以完成这项任务。
This method is actually a slot that is attached to a signal. I would like to add a delay of one sec using Qtimer.However I am not sure on how to accomplish this. Since the timer triggers a signal when its finished and the signal would need to be attached to another method that does not take in any parameters. Any suggestion on how I could accomplish this task.?
更新:
信号将在一秒钟内多次调用,延迟时间为1秒。我的问题是传递参数到附加到定时器的timeout()信号的插槽。
我的最后一种方法是将值存储在一个类的memeber变量,然后使用互斥体保护它在使用变量时不被更改.how我在这里寻找更简单的方法。
Update : The signal will be called multiple times in a second and the delay will be for a second. My issue here is passing a parameter to the slot attached to timeout() signal of a timer. My last approach would be to store the value in a memeber variable of a class and then use a mutex to protect it from being changed while the variable is being used .however I am looking for simpler methods here.
推荐答案
我有点困惑的方式你的问题,但如果你问如何获取定时器的超时信号调用带有参数的函数,然后可以创建一个单独的插槽来接收超时,然后调用所需的函数。类似这样: -
I'm a bit confused by the way you phrase your question, but if you're asking how to get the timer's timeout() signal to call a function with a parameter, then you can create a separate slot to receive the timeout and then call the function you want. Something like this: -
class MyClass : public QObject
{
Q_OBJECT
public:
MyClass(QObject* parent);
public slots:
void TimerHandlerFunction();
void SomeMethod(int a);
private:
int m_a;
QTimer m_timer;
};
实施: -
MyClass::MyClass(QObject* parent)
:QObject(parent)
{
// connect the timer's timeout to our TimerHandlerFunction
connect(&m_timer, SIGNAL(timout()), this, SLOT(TimerHandlerFunction()));
}
void MyClass::SomeMethod(int a)
{
m_a = a; // store the value to pass later
m_timer.setSingleShot(true); // if you only want it to fire once
m_timer.start(1000);
}
void MyClass::TimerHandlerFunction()
{
SomeOtherFunction(m_a);
}
注意QObject类实际上有一个定时器,你可以通过调用startTimer (),所以你实际上不需要在这里使用一个单独的QTimer对象。它包含在这里尝试保持示例代码接近的问题。
Note that the QObject class actually has a timer that you can use by calling startTimer(), so you don't actually need to use a separate QTimer object here. It is included here to try to keep the example code close to the question.
这篇关于如何使用Qtimer添加1秒延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!