17 Mart 2014 Pazartesi

Basic Qt Applications: QLCDNumber Application

Our first application was a basic QTimer application in which it is aimed to show the way of doing a certain task periodically by using a timer.

In this application, QTimer, QLCDNumber and QTime classes are used to implement a digital clock using an lcd digital format.

For this purpose, a display widget "LCD number" is inserted to the centralWidget as shown in figure.

By default Qt names the QLCDNumber object as "lcdNumber". Thus, we do not need to create a new
QLCDNumber object again.

Since we want to implement a digital clock we must include the <QTime> class and create a QTime object to access currentTime() function. The currentTime() function is used to get the current system time. However, in order to implement a digital clock we must access and display the current time periodically for every second. Thus, we will create a timer as in the QTimer application and call the myFunc() function as a slot to display the current time in the lcdNumber object.

mainwindow.h and mainwindow.cpp files are given below.

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTime>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void myFunc();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H
 
 
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTimer>
#include <QLCDNumber>
#include <QTime>

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

    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(myFunc()));
    timer->start(1000);
}

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


void MainWindow::myFunc()
{
    QTime t;
    ui->lcdNumber->setDigitCount(8);
    ui->lcdNumber->setSegmentStyle(QLCDNumber::Flat);

    ui->lcdNumber->setStyleSheet("color: green;"
                                 "background-color: white");

    ui->lcdNumber->display(t.currentTime().toString());

}

Some lcdNumber parameters such as text color and background color are set in myFunc() by using the following code pair. In order to view digital clock properly, lcdNumber digit count number must also be set to 8 for hh:mm:ss form.

    ui->lcdNumber->setDigitCount(8);
    ui->lcdNumber->setSegmentStyle(QLCDNumber::Flat);
    ui->lcdNumber->setStyleSheet("color: green;"
                                 "background-color: white");

Program output can be seen from the figure below.

Hiç yorum yok:

Yorum Gönder