My First Qt Application

Qt was started to becaome a nightmare for some of my friends. This tutorial is intended to give them some relief and take a good sound sleep after applying it.

This is the tutorial originally written by [sector at ynet dot sk] here. So, i would like to thank him for the wonderful tutorial.

If you are sluggish or facing some problem after following this tutorial or you don’t care to follow all the steps just the case you want to understand the stuff then you can download the complete source code here.

Ok we know Qt as a library for creating GUI programs. So what I think your first question might be: How do I create some GUI program with Qt? OK, let’s go to do it (The Qt Designer way).

Dialog creation


I am assuming that Qt4 Designer is installed in your PC. I am showing the screen shots in Linux(Ubuntu) however this process is equally valid for windows :( also.

First we need to create a main window of our application. Launch Qt4 Designer. “New Form” window will appear. Choose Widget and click Create. Go to Edit>Preferences. In the “User Interface Mode” choose “Docked Window”. This docks the Qt designer window into a single window which makes easy to handle things.
You window should look like this :

Qt4 Designer's Initial window

Qt4 Designer's Initial window

First thing you should do is change objectName of this widget to something reasonable, ie. TryDialog.

Then change by giving the window a title, put it in the windowTitle property in Property Editor (ie. MyFirstQtApp).Your task is to create some form like this:

This is how your final app should look like

This is how your final app should look like

We use Label, Combo Box, Text Edit, Spin Box, Check Box. Drag and drop appropriate widget from left menu to our form. We name (objectName) Browse button “pushButton_browse”, Do something button “pushButton_do”… We’ll need object names later when connecting with functions (slots).

To preview form, press Ctrl+R.

Final form: qtapp.ui. If you open it in a text editor you’ll see it’s XML.

Application Sources


If we are happy with our form, it’s time to create header file for this dialog. Open your favorite text editor and save the following lines as qtapp.h



#ifndef QTAPP_H
#define QTAPP_H

#include "ui_qtapp.h"

class QtApp : public QWidget, private Ui:: TryDialog
{
        Q_OBJECT

        public:
                QtApp(QWidget *parent = 0);

        public slots:
                void getPath();
                void doSomething();
                void clear();
                void about();
};
#endif


Let’s look at this code line by line.


#ifndef QTAPP_H
#define QTAPP_H

This macro says if MYQTAPP_H is not defined, then define it and process code. It ensures that we define class only once even if this header is included from multiple sources in our application.

#include "ui_qtapp.h"

This line is particularly important to understand. Our form created in designer is called qtapp.ui. Forms in .ui (XML) format are converted during build process into C++ header files by UIC (User Interface Compiler). As Qt documentation says in the UIC documentation: The UIC reads an XML format user interface definition (.ui) file as generated by Qt Designer and creates a corresponding C++ header file.

If your form filename is myform.ui, uic generates ui_myform.h. No matter what name of your class (objectName) is.

It’s actually a C++ definition of your dialog. To modify this header file makes no sense because it is recreated during the build process and any changes are lost.

class QtApp : public QWidget, private Ui :: TryDialog

QtApp is name of our class. TryDialog is class name of the form we created in Designer. This line says our class inherit from QWidget (We have chosen QWidget then creating form. For a dialog based form, QDialog would go here.) and also private from Ui:: TryDialog. This is actually our form included from ui_qtapp.h. It means we can access widgets in our form from member functions of QtApp class. This is called The Multiple Inheritance Approach in Qt documentation.
There is also an alternative to this approach called The Single Inheritance Approach. Have a look, you may find it more convenient than multiple inheritance approach (but I don’t believe it) ;)

Q_OBJECT

This macro expands to some definitions which are needed for signals/slots mechanism.


	public:
                QtApp(QWidget *parent = 0);

Defines public construtor, every class must have this. QWidget *parent = 0 is an optional argument (QtApp() constructor would also work). You may wonder what it is good for. Actually this is a customary form of widget constructor. Usually main windows and dialogs have no parent (i.e. parent == 0 ), but if somebody has a dialog that is used frequently (for example a “Find” dialog), he might want to create it once and then he might give it a parent, so that it will be destroyed automatically by Qt.


	public slots:
                void getPath();
                void doSomething();
                void clear();
                void about();

Defines some member functions of class called slots. Signals can be connected to these slots (function). When a signal is emitted, the function connected to it will trigger. We will see that later.

Ok, now let’s create qtapp.cpp file (implementation of our class defined in qtapp.h).


#include <QtGui>
#include "qtapp.h"

// if we include <QtGui> there is no need to include every
// class used: <QString>, <QFileDialog>,...

QtApp::QtApp(QWidget *parent)
{
    setupUi(this); // this sets up GUI

    // signals/slots mechanism in action
    connect( pushButton_browse, SIGNAL( clicked() ), this, SLOT( getPath() ) );
    connect( pushButton_do, SIGNAL( clicked() ), this, SLOT( doSomething() ) );
    connect( pushButton_clear, SIGNAL( clicked() ), this, SLOT( clear() ) );
    connect( pushButton_about, SIGNAL( clicked() ), this, SLOT( about() ) );
}

void QtApp::getPath()
{
    QString path;

    path = QFileDialog::getOpenFileName(
        this,
        "Choose a file to open",
        QString::null,
        QString::null);

    lineEdit->setText( path );
}

void QtApp::doSomething()
{
    int value1, value2;
    Qt::CheckState state;
    QString str;

    textEdit->append( "Path to file: " + lineEdit->text() );

    value1 = spinBox1->value();
    value2 = spinBox2->value();

    textEdit->append( "Number 1 value: " + QString::number(value1) );
    textEdit->append( "Number 2 value: " + QString::number(value2) );

    state = checkBox->checkState();

    str = "Checkbox says: ";
    if ( state == Qt::Checked ) str += "yes";
    else str += "no";
    textEdit->append( str );

    textEdit->append( "ComboBox current text: " + comboBox->currentText() );
    textEdit->append( "ComboBox current item: " +
				QString::number(comboBox->currentIndex()) );
}

void QtApp::clear()
{
    textEdit->clear();
}

void QtApp::about()
{
    QMessageBox::about(this,"About QtApp",
                "This app was coded for telling you guys Qt isn't difficult.\n"
                "Number 1 is: " + QString::number(spinBox1->value()) + "\n\n"
                "Bye.\n");
}

We need to create main.cpp


#include <QApplication>

#include "qtapp.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QtApp *dialog = new QtApp;

    dialog->show();
    return app.exec();
}

Now we have all we need to create the project file qtapp.pro


TEMPLATE = app
TARGET =
DEPENDPATH += .
INCLUDEPATH += .

# Input
HEADERS += qtapp.h
FORMS += qtapp.ui
SOURCES += main.cpp qtapp.cpp

It is possible to generate the .pro file automaticly with qmake -project command.

Compilation


Press Alt + F2 (in ubuntu) and type gnome-terminal OR for windows :( in Run dialog box type cmd, go to the directory with application sources and type:


qmake
make

After successful compilation and linking, MyFirstQtApp will be created in Sources folder(in ubuntu) and in windows MyQtApp.exe will be created in “debug” folder.

Final working app

Final working app


Congratulations, you have done your first Qt GUI application!

Category: QT  Tags:
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
5 Responses
  1. Vubhor says:

    Nicely written

  2. Thanks and i have tried each code and its working perfectly and i hope your .ui problem is now solved :)

  3. ankit goyal says:

    Thats preety well it works great

  4. Vibhor says:

    Sir I Need Those Commands Which Are Needed To Be Put Into Qt Command Prompt For Configure In Windows

    Please Reply With Those Commands

    I Can’t Progress Until I Got That…………

    Please Reply

  5. Kelly Brown says:

    The best information i have found exactly here. Keep going Thank you

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>