Qt 5 Hello World Tutorial using Qt Creator

A simple Qt 5 Hello World tutorial that demonstrates how to use Qt Creator to make a GUI application window. Create a window with two text labels and a button in this easy tutorial for beginners. Program the application in C++.

The image below shows the finished Qt GUI window application. When the button is clicked, the text “Hello, world!” is displayed in the first text label. Each time the button is clicked, the count in the second label is incremented.

Qt 5 Hello World Tutorial
Qt 5 Hello World Tutorial

Qt 5 Hello World Tutorial Steps

The following steps show how to create the Qt5 Hello World application using Qt Creator. Before continuing, be sure to install Qt Creator and other required software packages.

1. Start a New Qt Creator Project

Open the Qt Creator application and click the New Project button, or File → New File or Project … from the top menu.

Qt Creator New Project
Qt Creator New Project

In the New Project dialog box choose Qt Widgets Application and then click the Choose… button.

Qt Creator New Qt Widgets Application
Qt Creator New Qt Widgets Application

In the next dialog box enter the name of the project and choose the location to create the project in. Click the Next > button when done.

Qt Creator Project Name and Location
Qt Creator Project Name and Location

The Qt Kit can now be selected. If this is the first time using Qt Creator, you may be prompted to set up a kit. If a kit is already selected, it can be modified by hovering the mouse cursor over the kit name and then clicking the Manage… button that appears after hovering the mouse cursor, e.g. over Desktop in the below image.

Qt Creator Kit Selection
Qt Creator Kit Selection

Click the Next > button and leave the class information at the default values.

Qt Creator Class Information
Qt Creator Class Information

Click the Next > button and then the Finish button.

Qt Creator Summary Dialog Box
Qt Creator Summary Dialog Box

At this stage the Run button can be clicked to build and run the new Qt Creator application (or use Ctrl + R on the keyboard to run). When the application runs, a window will appear that can be resized and closed.

Qt Creator Project
Qt Creator Project

2. Edit the Application Window Graphically

To start editing the new application window in Qt Creator, expand the Forms folder at the top left of Qt Creator. Double-click the mainwindow.ui file that appears. Qt Creator will now change to Design mode allowing the hello application window to be edited.

Open the Main Window Form for Editing in Qt Creator
Open the Main Window Form for Editing in Qt Creator

2.1 Delete Unneeded Widgets from the Main Window

The default Qt Creator application window has a menu bar, tool bar and status bar. These widgets are not needed in this simple Hello World application, so they can be deleted. Each widget in the main window form has corresponding text at the top right of Qt Creator. This makes it easy to delete these widgets as they are difficult to see on the window form when they are empty.

Default Qt Application Window and Widgets
Default Qt Application Window and Widgets

Right-click the text for each widget at the right of Qt Creator and then click Remove on the menu that pops up to delete the widget from the window form.

2.2 Add Text Labels

Drag and drop two Label widgets from the pane at the left of the window form, under Display Widgets. Drop the labels onto the form.

Placing a Text Label in Qt Creator
Placing a Text Label in Qt Creator

2.3 Size the Text Labels

Click one of the text labels on the form, then hold down the Ctrl key and click the second label to select both of them. Now click the Lay Out Vertically button on the toolbar above the form or press Ctrl + L on the keyboard. This will allow both text labels to be resized at the same time while keeping them aligned. Resize the text labels making them longer by dragging on one of the square handles around the labels. The labels can also be moved to the desired position on the window form.

Resizing Labels in Qt Creator
Resizing Labels in Qt Creator

2.4 Middle Align the Label Text

Text in both labels can be aligned to the middle of the label box by first selecting both labels. Be sure to click one label, hold down the Ctrl key and then click the other label. This is different than selecting the vertical layout box added for aligning and sizing the text boxes in the previous step.

In the bottom right pane of Qt Creator, scroll down to find alignment under QLabel. If the alignment property is not expanded, expand it by clicking the arrow at the left of it. Now click in the value field to the right of Horizontal and select AlignHCenter. Both text labels will now be center aligned.

Align Label Center in Qt Creator
Align Label Center in Qt Creator

2.5 Change the Label Name and Text

Click the top label on the window form and then change the label name next to objectName under QObject in the right bottom pane. Change the label name to lblHello. Change the label text to next to text under QLabel.

Change Label Name and Text
Change Label Name and Text

Do the same for the second label, but change the label name to lblCount.

Change the Name and Text of the Second Label
Change the Name and Text of the Second Label

2.6 Add and Edit a Button Widget

Add a Push Button to the window form by dragging and dropping it from the left widget pane under Buttons.

Place Button in Qt Creator
Place Button in Qt Creator

Make sure that the button is selected on the form. Change the name of the button to btnHello and the text of the button to Hello in the same way as the labels were edited.

Changing Button Name and Text in Qt Creator
Changing Button Name and Text in Qt Creator

3. Connecting the Button to Code

We now want to connect the button to the code that will run when it is clicked. Right-click the button on the form and select Go to slot… on the menu that pops up. Choose clicked() in the dialog box that pops up and then click the OK button.

Adding a Button Click Handler in Qt
Adding a Button Click Handler in Qt

Qt Creator will now switch to the member function that will be called when the button is clicked.

4. Application Operational Code

The application code can now be written. The code writes “Hello, world!” to the first text label in the window and increments a count in the second text label every time that the button is clicked.

The code listing below shows the code added to the button click handler in the mainwindow.cpp file.

Static integer count holds the count value that is incremented on each button click. The first time that the application runs, both labels will contain the text … which will be replaced by the “Hello, world!” text message and the incrementing count.

Each label is accessed by its name that was set in the GUI editor. Widgets are all accessed as member pointers of the user interface object (ui) and so pointer notation is used, e.g. ui->widget name

5. Change Window Size and Text

To switch back to editing the window form, click mainwindow.ui at the bottom left of Qt Creator under Open Documents. Qt Creator will change back to Design mode.

Changing to Qt Creator Design Mode
Changing to Qt Creator Design Mode

5.1 Change Window Size

Click the main window form and use the sizing handles to size the window to the desired size. The window size can also be changed by selecting the window and changing the Width and Height under QWidget and geometry in the bottom right Qt Creator pane.

5.2 Change Window Title Text

With the window form selected in Qt Creator, find windowTitle under QWidget in the bottom right pane of Qt Creator. In the image below, the window title was changed to “Hello Application”. This text will now appear in the top title bar of the application window when it is run.

Change Window Title of Qt Creator Application
Change Window Title of Qt Creator Application

6. Build and Run the Application

Save changes to the project. This can be done using File → Save All from the top menu or Ctrl + Shift + S on the keyboard.

The Qt 5 Hello World Tutorial project can be built by clicking the hammer icon on the left toolbar of Qt Creator. The application can be run by clicking the green triangle icon on the left toolbar.

Qt Creator Build Project and Run Buttons
Qt Creator Build Project and Run Buttons

Qt 5 Hello World Tutorial Development Environment

This tutorial was developed on a Linux Mint 18 Mate 64-bit computer using Qt Creator 3.5.1 and Qt 5.5.1. Compiled with g++ compiler version 5.4.0.

 

How to Install Qt 5 Development Tools in Linux

When starting Qt 5 application development in Linux it is necessary to first install Qt 5 development tools. Qt Creator is the IDE used to develop Qt applications. In order for Qt Creator to be able to build Qt applications, library files, header files and a C++ compiler must be installed.

This article shows how to install the necessary packages for Qt 5 application development. It was tested on a Linux Mint 18 Mate 64-bit computer, but should work on other Debian based Linux distributions such as Ubuntu and other Linux Mint versions.

Install Qt Creator

Qt Creator is an IDE for Qt GUI and C++ code development. It is used to graphically lay out windows and widgets for GUI applications and to edit C++ code.

Qt Creator
Qt Creator

Install Qt Creator using the following command in a terminal window.

Install Qt 5 Libraries, Header Files and Tools

Qt Creator needs Qt 5 libraries, header files and software utility tools to be installed. Without these packages Qt applications would not be able to be compiled. All the necessary packages can be installed by running the following command in a terminal window.

Install a C++ Compiler

Finally a C++ compiler must be installed on the system. Qt development is done in C++ in Qt Creator. Applications will not be able to be compiled without a C++ compiler installed. Run the following command to install the g++ C++ compiler

 

With the above packages installed, you are ready to begin developing Qt 5 applications using Qt Creator. You may like to try the Qt 5 Hello World tutorial to start learning how to use Qt Creator to make a simple GUI application.

Compiling GLib C Programs

GLib is a utility library required by GTK+, but which can also be used independently in non-GUI applications. This article shows how to compile C programs that use GLib in Linux. It also shows how to install the correct documentation for the version of GLib installed on the system and how to find the version number of the currently installed GLib library.

Commands and libraries used in this article were tested on Linux Mint 18, but should work on all Debian based Linux distributions including Ubuntu. Before compiling a program, make sure that the GLib development library is installed on your system:

Compiling a Simple GLib C Program

The example program below is a simple “Hello World” C program written using a GLib function. Instructions on compiling the program in Linux are shown below the code listing.

Use the following at the command line to compile the above program:

In the above line use back-ticks (`) and not single quotes (‘) to enclose pkg-config and its options. Or use:

The compiled program called hello can be run from the command line as follows:

Installing GLib Help

Install the GLib help documentation for the version of  GLib installed on your system.

The help files can be viewed in Devhelp. Install Devhelp using the following command:

Devhelp can be found on the Linux Mint 18 Mate menu under Menu → Programming → Devhelp. The image below shows the GLib Reference Manual opened in Devhelp.

The GLib Reference Manual in Devhelp
The GLib Reference Manual in Devhelp

Finding the Version Number of GLib

Clicking GLib Reference Manual in the left pane of Devhelp should show the version number of the documentation which should correspond to the version number of the installed library. There are two other ways to determine the installed version of the library — using pkg-config and programmatically as described below.

Using pkg-config

Entering the following command in a terminal window will display the currently installed version of GLib.

Programmatically

When the following program is compiled and run it will display the current version of GLib.

Compile using:

Or:

Run:

GLib C Coin Toss Example Program

An additional GLib C program which simulates a coin toss. When the program is run it will print either Heads or Tails to the terminal window. Heads or tails for the coin toss is determined by the g_random_boolean() function.

Compile using:

Or:

Run:

 

Configure PHP for Local Web Development

When developing PHP on a local computer it is usual to configure PHP to display error and warning messages. Enabling errors and warnings in PHP helps during software development to find bugs and detect potential problems.

This article explains how to enable PHP error and warning messages for local web development on a LAMP stack. Linux Mint is used as an example, but other Debian Linux computers such as Ubuntu should follow the same procedure.

First install a LAMP stack and then configure Apache web server for local web development.

Create a Test PHP File

Create a PHP file that contains an error. When PHP error and warning reporting is not enabled, and the PHP script is executed, no error or warning messages are displayed in the web browser.

Here is an example of a PHP script that contains an error.

Save this script to a file, e.g. php_error.php and copy it to a local web server. Use a web browser to surf to the script. If you configured a test website as explained in the article on configuring Apache for local web development, then you can copy the test file to your test folder. Use a web browser to surf to http://test/php_error.php

PHP File with Errors Displays as Blank Page
A PHP File with an Error Shows as a Blank Page when PHP Error and Warning Display is Switched Off

When the script is run, a blank page is appears in the web browser as shown in the above image.

Configure PHP to Display Errors and Warnings

After configuring PHP to display errors and warnings, the same test script created above will be used to verify that error reporting has been switched on.

Enable PHP Error and Warning Messages

First locate the php.ini configuration file in the file system. This file is located in /etc/php/7.0/apache2/ in Linux Mint 18. In older versions of Linux Mint it was located in /etc/php5/apache2/ If you can’t find php.ini, do a search for it in the /etc/ directory.

Open the php.ini file in an editor with superuser privileges by either starting file manager as root or using sudo from the command line. Choose one of the options below to open and edit php.ini

Open File Manager as Root

Press Alt + F2 to open the Run Application dialog box. Enter gksudo caja in the Run Application dialog box and press enter. Enter your password when prompted and an instance of the Caja file manager will open (Linux Mint Mate). If you are using a different distribution of Linux, substitute the name of your file manager for caja.

Use the file manager opened as root to navigate to the php.ini file, e.g. to /etc/php/7.0/apache2/ in Linux Mint 18. Double click the php.ini file to open it for editing.

Edit php.ini from the Command Line

Instead of using a file manager opened as root, php.ini can be opened from the command line. Start a terminal window (Ctrl + Alt + t). Now open the php.ini file in the nano file editor using the following command:

Change the path to php.ini in the above line if necessary.

Edit php.ini

With php.ini opened in an editor with root privileges, PHP error and warning messages can be enabled.

Scroll down the php.ini file to find the “Error handling and logging” section as shown below, or search for “Error handling and logging”.

PHP Error Handling and Logging
PHP Error Handling and Logging

Scroll down to find what error_reporting is set to. By default this value is set as follows on a Linux Mint 18 system.

For the strictest error reporting, and to report the use of deprecated PHP code, change this value to the following.

Scroll a bit further down the file and change the value of display_errors to On.

This will enable all PHP errors and warnings to be displayed when they occur.

Save the file and exit the editing program. (use Ctrl + o to save the file and then Ctrl + x to exit the application if using the nano editor).

Restart Apache Server

For the above changes to take effect, the Apache web server must be restarted. Enter the following at the command line.

Testing that Error and Warning Reporting is Enabled

Use the same php_error.php file from above to test that the error in this file is reported. Use a browser to navigate to the file as done previously. An error should now be displayed in the browser as shown below.

Web Page Displaying a PHP Error
Web Page Displaying a PHP Error

When to Configure PHP to Display Errors and Warnings

PHP should only be configured to display errors and warnings on a local test sever. A live or production server should not display PHP error and warning messages. Code should first be tested and debugged on a local server. When it is error free it can be moved to the live production server.

Configure Apache for Local Web Development

How to configure Apache 2 web server on a local Linux computer for local web development. Configure Apache to host multiple local web sites for web development on Linux Mint or Ubuntu.

The previous blog post describes how to set up a LAMP stack on a local Linux computer. This post shows how to set up multiple web sites on a single local LAMP server. Having copies of websites on a local computer allows PHP code and WordPress plugins or themes to be developed and tested on a local computer. After testing the PHP code or plugins, they can be uploaded to the live version of the website.

Apache Settings for Local Web Development

Be sure to install a local LAMP stack before continuing with this tutorial.

Choose the Websites Location

Make a folder that contains your local websites. This should be in your home directory or folder. As an example, you could create a folder called websites in your home directory. The full path to the folder would then be:

/home/<user name>/websites/

Create a Folder for Each Website

Create a new folder for each local website that you want. Create these folders inside the main folder that you created in the previous step. Two folders are created as examples for this tutorial. The first folder is called test and the second site as shown below.

/home/<user name>/websites/test/
/home/<user name>/websites/site/

More folders for additional websites can be added at any time.

Write a PHP script called index.php for each of the websites that will uniquely identify them. For example, print the name of each website so that it can be viewed in a browser. Save the scripts to their respective website folders created above.

Example index.php script for the test website:

Make a similar PHP file for the site website, but substitute Site in the file for Test in two places.

Configure Apache 2 Web Server

A configuration file for each local website must be created by copying an existing file in the Linux file system. Open file manager as root to edit the file system files. Alternatively use the command line and a text editor such as nano.

Opening the File Manager as Root

Press Alt + F2 to open the Run Application dialog box. In Linux Mint Mate, type gksudo caja in the dialog box and hit the Enter key. Caja is the file manager in Linux Mint Mate. Substitute the file manager name for your Linux distribution in the run box.

Run Application Dialog Box
Run Application Dialog Box

After pressing Enter, you will be prompted for your Linux password. Enter your password and the file manager will start with root privileges.

Caution: With the file manager opened as root it is possible to edit or delete any file in the file system. Use the file manager with great care when it is opened as root and close it immediately after all the file system files have been edited.

Create the Apache 2 Configuration Files

Use the file manager to navigate to:

/etc/apache2/sites-available/
Apache Sites Available Folder
Apache Sites Available Folder

Make a copy of 000-default.conf for each website that will be configured. Drag this file in file manager and hold down the Ctrl key before dropping it in the same folder to make copies of this file. Rename each new file to the name of the folders being used, i.e. test and site for this example. The image below shows the two new files created by copying 000-default.conf in the file manager. The files are renamed next.

Copying the Apache Configuration File
Copying the Apache Configuration File

To rename a file in file manager, click the file to select it and then press F2 to edit it. Now type the new name and press the Enter key. The result of renaming the two files is shown below. You should now have two files called test.conf and site.conf which are copies of 000-default.conf.

Renaming the Apache Configuration Files
Renaming the Apache Configuration Files

Editing the Apache Configuration Files

Each of the configuration files must now be edited. Double-click test.conf to open it for editing (this must be done in the file manager opened as root or else it will not be able to be saved). Add the following lines to the file. First change the server name at the top of the file. Modify the paths in the below text to suit your user name and website name. The sever name and paths are marked in bold in the next code listing.

ServerName test

ServerAdmin webmaster@localhost
DocumentRoot /home/user/websites/test/
<Directory /home/user/websites/test/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Require all granted
</Directory>

The complete file looks as follows:

<VirtualHost *:80>
    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless.
    # However, you must set it for any further virtual host explicitly.
    ServerName test

    ServerAdmin webmaster@localhost
    DocumentRoot /home/user/websites/test/
    <Directory /home/user/websites/test/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Require all granted
    </Directory>
    
    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

It is important to modify the lines above marked in bold. These lines will be different for each website and must contain the name of the web server and path to each website’s folder.

Save and close these files after editing.

Activate the New Local Websites

Right-click in the file manager that was opened as root and should have the /etc/apache2/sites-available/ folder open. In the menu that pops up click Open in Terminal to open this folder in a terminal window.

In the terminal window, type a2ensite followed by the site name(s), e.g.:

a2ensite test site

The terminal window is shown below after running the command.

Enabling Apache Websites for Local Web Development
Enabling Apache Websites for Local Web Development

The terminal window can now be closed.

Configure Host

In the file manager that was opened as root, navigate two folders back. This will be the /etc/ folder. Open the hosts file for editing (/etc/hosts).

Add the names of the new sites next to the IP address of 127.0.0.1. The edited file is shown below.

127.0.0.1    localhost
127.0.1.1    toshi
127.0.0.1    test
127.0.0.1    site

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

Save and close the file.

Open a terminal window and enter the following to restart the Apache server so that the changes can take effect.

sudo service apache2 restart

Modify File and Folder Permissions

The new websites are now configured, but Apache does not have permission to access your local website folders. Before continuing, close the file manager that you opened as root.

Open a normal file manager (not as root) and navigate to your website folders. Select the website folders (test and site for this example) and right click them. In the menu that pops up, click Properties. In the Properties dialog box, click the Permissions tab. Change the permissions for Group and Others to Access Files and Read-only as shown below. Click the Apply Permissions to Enclosed Files button and then the Close button.

Changing File Permissions
Changing File Permissions

In the file manager, move one level back and using the same method, change the permissions for the websites folder to Access files for the Folder access options for Group and Others. Do the same for your home folder.

Access the Local Websites

The local websites used as examples in this tutorial can now be accessed from a browser. Type http://test in the browser address bar to access the test website and http://site to access the site website. You can now use the new websites for local web development of PHP and WordPress sites or other sites or applications that use a LAMP stack.

Test Website after Apache Configuration
Test Website after Apache Configuration

Further Configuration

You may also want to configure PHP to display error and warning messages during software development on the local LAMP stack. Enabling error and warning messages to be displayed helps with debugging PHP code locally before moving it to a live production server.