16 Mart 2014 Pazar

Basic Qt Applications: QTimer Application

This blog provides some application examples of Qt classes. As a first application "QTimer" class is used to show how to make a job peridocally by using a timer.

Examples are implemented in the Qt version of Qt 5.2.1 for Windows 32-bit (MinGW 4.8, OpenGL, 634 MB).  

QTimer Application

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
 
#include <QMainWindow>
 
namespace Ui {
class MainWindow;
}
 
class MainWindow : public QMainWindow
{
    Q_OBJECT
 
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    void callTimer();
 
private slots:
    void myFunc();
 
private:
    Ui::MainWindow *ui;
};
 
#endif // MAINWINDOW_H


#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTimer>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    callTimer();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::callTimer(){
    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(myFunc()));

    timer->start(1000);

}

void MainWindow::myFunc(){

    qDebug() << "Debugging is in progress...";
}



mainwindow.h and mainwindow.cpp files are respectively given above. Once a QTimer is created its timeout() signal should be connected to the appropriate slots. Slots can be considered as the functions that will be invoked after a timer call. Here, we define the myFunc() function as a slot which will be called periodically to perform some job. That's why in mainwindow.h file myFunc() is defined as a slot as shown above. 

In mainwindow.cpp file the callTimer() function is called in the constructor function of the MainWindow class. callTimer() function creates a timer object by using the following code pair.


QTimer *timer = new QTimer(this); 


To create a QTimer object in the mainwindow.cpp file the <QTimer> library must be included. Once a timer object created its timeout() signal is connected to the myFunc() function with the following code pair.
connect(timer, SIGNAL(timeout()), this, SLOT(myFunc()));

Here myFunc() can be any function that addresses your requirements. As an example, in this function a text is printed out by using another Qt class QDebug. Thus, it will be possible to observe if the timer is working properly or not. Please do not forget to add <QDebug> library to the mainwindow.cpp. Otherwise, qDebug() function will not be identified by the compiler.


timer is started by calling the start() function of QTimer class. The start() function asks the duration in milliseconds as a parameter from the user. Here, as it can be shown above, we passed start(1000) which makes 1 seconds. This means, the timer will call the myFunc() function periodically for every second.

Hiç yorum yok:

Yorum Gönder