如何使用Qtimer添加1秒延迟

Raj*_*war 15 c++ qt qtimer

我目前有一个方法如下

void SomeMethod(int a)
{

     //Delay for one sec.
     timer->start(1000);

     //After one sec
     SomeOtherFunction(a);
}
Run Code Online (Sandbox Code Playgroud)

该方法实际上是附加到信号的插槽.我想用Qtimer添加一秒的延迟.但是我不知道如何实现这一点.由于定时器在完成时触发信号,并且信号需要连接到另一个不接受任何参数的方法.关于如何完成这项任务的任何建议.

更新: 信号将在一秒钟内被多次调用,延迟将持续一秒钟.我的问题是将参数传递给附加到计时器的timeout()信号的插槽.我的最后一种方法是将值存储在类的memeber变量中,然后使用互斥锁来保护它在使用变量时不被更改.但是我在这里寻找更简单的方法.

Lin*_*lle 51

实际上,对于不需要成员变量或队列的问题,有一个更优雅的解决方案.使用Qt 5.4和C++ 11,您可以直接从该QTimer::singleShot(..)方法运行Lambda表达式!如果您使用的是Qt 5.0 - 5.3,则可以使用connect方法将QTimer的超时信号连接到Lambda表达式,该表达式将调用需要使用适当参数进行延迟的方法.

编辑:使用Qt 5.4版本,它只是一行代码!

Qt 5.4(及更高版本)

void MyClass::SomeMethod(int a) {
  QTimer::singleShot(1000, []() { SomeOtherFunction(a); } );
}
Run Code Online (Sandbox Code Playgroud)

Qt 5.0 - 5.3

void MyClass::SomeMethod(int a) {
  QTimer *timer = new QTimer(this);
  timer->setSingleShot(true);

  connect(timer, &QTimer::timeout, [=]() {
    SomeOtherFunction(a);
    timer->deleteLater();
  } );

  timer->start(1000);
}
Run Code Online (Sandbox Code Playgroud)

  • Qt 5.4将支持[QTimer :: singleShot()和lambdas](https://codereview.qt-project.org/#/c/66110/). (2认同)

The*_*ght 1

我对你提出问题的方式有点困惑,但是如果你问如何获取计时器的 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;
};
Run Code Online (Sandbox Code Playgroud)

执行: -

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);
}
Run Code Online (Sandbox Code Playgroud)

请注意,QObject 类实际上有一个计时器,您可以通过调用 startTimer() 来使用它,因此您实际上不需要在这里使用单独的 QTimer 对象。此处包含它是为了尝试使示例代码接近问题。