Friday, June 8, 2012

A Basic QT LCD Number Component Example

In this small example, we demonstrate how to use Qt's LCD Number component with consequent images and codes.

Since Qt is known to be a good GUI library, it has got a collection of classes for general purpose programming on networking, databases and other things.

In our simple example, we have one lcd number component and two buttons for increasing and decreasing the value on it. Events are handling using slots and signals as usual in Qt. First, follow these images.


















The C++ code for main.cpp, mainwindow.cpp and mainwindow.h is shown below:


main.cpp
#include <QtGui/QApplication>
#include "mainwindow.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    
    return a.exec();
}


mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->connect(this->ui->pushButton, SIGNAL(clicked()), this,SLOT(button_Plus_click()));
    this->connect(this->ui->pushButton_2, SIGNAL(clicked()), this,SLOT(button_Minus_click()));
    this->counter=10;
    this->ui->lcdNumber->display(counter);
}

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

void MainWindow::button_Minus_click(){
    counter--;
    this->ui->lcdNumber->display(counter);
}

void MainWindow::button_Plus_click(){
    counter++;
    this->ui->lcdNumber->display(counter);
}



mainwindow.h
#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();

    
private:
    Ui::MainWindow *ui;
    int counter;

private slots:
    void button_Plus_click();
    void button_Minus_click();
};

#endif // MAINWINDOW_H



Good luck!

1 comment:

  1. Very new to this ..
    Is there a way to have say buttons 1 to 9 and when you press these the number appears on the screen instead of minus and plus .So you press the button labeled 1 and the number one is shown etc ?
    Thanks

    ReplyDelete

Thanks