26/11/2019 20

QTimer with QT GUI C++

Hello everyone, in this article we are going to talk about How can we use QTimer in QT GUI with C++.

Now let's get started

First we create a QWidget project named QTimer_example.
Create a QWidget App - Thecodeprogram Firstly, we have to be make sure we have added core library in QT pro file:

QT       += core 

And then we need to include QTimer library in header file of the form which we will use. I will use it in MainWindow and I need to include it in mainwindow.h file:

#include <QTimer> Also We need to define a variable to QTimer in our header file:

private:
    Ui::MainWindow *ui;
    QTimer *tmr_counter;

Now we need to create a function to use when the QTimer time ended. And after that we need to connect the QTimer to related function via Sıgnal Slot method.

Related header file

private:
    Ui::MainWindow *ui;
    QTimer *tmr_counter;
    
private slots:
    void fnc_checkValues();
and related CPP file:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(tmr_counter, SIGNAL(timeout()), this, SLOT(fnc_checkValues())); 
   //fire fnc_checkValues when tmr_counter timeout
}

//this function will work with QTimer
void MainWindow::fnc_checkValues()
{
     //Here you can do whatever you want
}

You can make your GUI updates with QTimer with an individual thread and it will not affect the main thread. You can also use the continuous while loop and make some updates on GUI without disturb the main thread. QTimer works with a seperate thread. It is not exactly multithread bu it is a little bit.

That is all in this article.

Have a good timing.

Burak Hamdi TUFAN


Tags

Share this Post



Post a Comment

Success! Your comment sent to post. It will be showed after confirmation.
Error! There was an error sending your comment.

Comments

    There is no comment. Be the owner of first comment...