Stop QTimer and Variable scope issue



  • Hi all,

    I want to have a QTimer keep running, but sometimes I need to stop and resume this timer.
    I have code as below:

    void MainWindow::on_pushButton_3_clicked()
    {
        QTimer *MainLoopTimer;
    
        MainLoopTimer = new QTimer();
        connect(MainLoopTimer, SIGNAL(timeout()), this, SLOT(timerUpDate()));
        MainLoopTimer->start(100);
    }
    
    void MainWindow::on_pushButton_7_pressed()
    {
         MainLoopTimer->stop();
    }
    

    As you can see, "MainLoopTimer" cannot been seen in "on_pushButton_7_pressed()", so I don't know how to stop this timer.

    Appreciate for any suggestion,
    Thanks,



  • @Hiloshi
    I think you can declare MainLoopTimer as MainWindow's member



  • Hi @Hiloshi ,

    As suggested by @Flotisable

    Your QTimer can a var member

    in your MainWindow.h

    .
    .
    .
    Private :
    QTimer *mTimer;
    

    In your MainWindow.cpp

    mTimer = new QTimer();
    .
    .
    .
    .
    
    void MainWindow::on_pushButton_7_pressed()
    {
         mTimer->stop();
    }
    .
    .
    .
    

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.