我目前有一种方法如下
void SomeMethod(int a)
{
//Delay for one sec.
timer->start(1000);
//After one sec
SomeOtherFunction(a);
}
该方法实际上是连接到信号的插槽。我想使用Qtimer添加一秒的延迟,但是我不确定如何实现这一点。由于计时器在完成时会触发信号,因此该信号将需要附加到不带任何参数的另一种方法上。关于如何完成此任务的任何建议。
更新:该信号将在一秒钟内被多次调用,并且延迟将持续一秒钟。我的问题是将参数传递给附加到计时器timeout()信号的插槽。我的最后一种方法是将值存储在类的成员变量中,然后在使用该变量时使用互斥来保护它不被更改。但是我在这里寻找更简单的方法。
我对您的问题表达方式有些困惑,但是如果您要询问如何获取计时器的timeout()信号以调用带有参数的函数,则可以创建一个单独的插槽来接收超时,然后调用您想要的函数。像这样的东西:
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(timeout()), 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对象。它包含在此处以使示例代码更贴近问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句