简体   繁体   中英

How to check a variable periodically by QTimer

I have a global variable that i set on a cpp file on my qt project. I want to check this variable in every 100ms for 5 second and if the variable is 0 after 5 seconds I want to create a message box. Here is the sample of my code:

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); 

Does this work for you? I didn't see a need to check every 100ms, if readFlag doesn't get set to 1 in 5 seconds, you'll output an error message, otherwise nothing happens.

    // 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;
    }

Option 1: Use a timer with 100ms interval to check global variable, hold a member variable for counting how many times timer slot called. When slot called 5000/100=50 times, stop timer and create message box if necessary.

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

Option 2: Use two counters(one with 100ms interval, other with 5000ms) which has two different slots. Start both counters at same time. Let 100ms timer's slot check global variable, let 5000ms timer's slot stop both timers and check global variable, create message box if necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM