如何通过 QTimer 定期检查变量

How to check a variable periodically by QTimer

我在我的 qt 项目的 cpp 文件中设置了一个全局变量。我想每 100 毫秒检查一次这个变量,持续 5 秒,如果变量在 5 秒后为 0,我想创建一个消息框。这是我的代码示例:

db.cpp:

if(case){
  g_clickedObj.readFlag = 1 ;
}
else{
g_clickedObj.readFlag = 0 ;
    }

mainwindow.cpp

this->tmr = new QTimer();

connect(this->tmr,SIGNAL(timeout()),this,SLOT(callSearchMachine()));

tmr->start(5000); 

这对你有用吗?我没有看到需要每 100 毫秒检查一次,如果 readFlag 没有在 5 秒内设置为 1,您将输出一条错误消息,否则什么也不会发生。

    // where you want to start the 5 second count down...
    QTimer::singleShot(5000, this, SLOT(maybePrintAnErrorMsg()));
    . . .

    // the slot:
    void MyClass::maybePrintAnErrorMsg()
    {
      if (readFlag != 1) {
        // show a QMessageBox;
      }
    }

    . . . somewhere else in your code, when you set readFlag to 1:

    if (case) {
      // when the timer goes off, we won't print an error message
      readFlag = 1;
    }

方案一:使用一个100ms间隔的timer来检测全局变量,保存一个成员变量来统计timer slot调用了多少次。当插槽调用 5000/100=50 次时,停止计时器并在必要时创建消息框。

void MyClass::onTimeout(){
    // check variable
    // increment counter
    // check if counter reached 5000/100
    // if so stop timer and create message box
}

选项 2: 使用两个具有两个不同时隙的计数器(一个间隔 100 毫秒,另一个间隔 5000 毫秒)。同时启动两个计数器。让 100ms 定时器的槽检查全局变量,让 5000ms 定时器的槽停止两个定时器并检查全局变量,必要时创建消息框。