如何通过QTimer定期检查变量

问题描述

我在qt项目的cpp文件上设置了一个全局变量。我想每5秒钟每100毫秒检查一次此变量,如果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;
    }
,

选项1:使用间隔为100ms的计时器检查全局变量,并保存一个成员变量以计算计时器插槽被调用的次数。当插槽调用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计时器的插槽停止两个计时器并检查全局变量,并在必要时创建消息框。