The Wayback Machine - https://web.archive.org/web/20241126193345/https://www.geeksforgeeks.org/cpp-gui-programming/
Open In App

Introduction to GUI Programming in C++

Last Updated : 02 Jan, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C++, Graphical User Interface (GUI) programming is important in modern application development where users have nice graphics for them to work with. Although C++ is commonly linked with system programming and game writing, it can be an excellent alternative to GUI writing. In this article, we will discuss GUI programming in C++, some popular GUI libraries for C++, and how to create a basic GUI application in C++.

Introduction-to-GUI-Programming-in-Cpp

Prerequisites: Fundamentals of C++, C++ OOPs, Some GUI Library.

What is GUI (Graphical User Interface)?

The Graphical User Interface (GUI) is a visual application interface that is provided using graphics like windows, text boxes, and buttons through which users can communicate with the software. GUI offers an interactive and easy-to-use platform as compared to the Command Line Interface (CLI) as users can use the mouse or other input devices such as a touchscreen, etc. without relying only on the keyboard.

Main Concepts of GUI Programming

A graphical user interface (GUI) involves designing windows, dialogs, buttons, etc which are all interactive user interface components. Then we control these widgets using event handlers like onClick, onHover, etc.

The main concepts of GUI Programming are:

Widgets

A graphical user interface (GUI) is made up of widgets. For example, these include buttons, textboxes, labels, etc. Properties and behaviors of each widget can be customized in accordance with the specific needs of an application. There are generally the following widgets in a GUI library:

  1. Window: A top level window frame that host other widgets inside itself.
  2. Button: A clickable button that have some event associated with its click.
  3. Label: Simple read-only text
  4. Checkbox: Box that provide the options to be on or off.
  5. Radio Button: Box that provide the options to be on or off but we can only choose one radio button in a group.
  6. Dropdown/Combo Box: Opens a dropdown menu when clicked. Only one item can be displayed in the non-opened form.
  7. Textbox: Editable Text area.
  8. Listbox: The box with multiple items and a scroll bar to go through all of them.
  9. Slider: A navigation widget used to move around the application.
  10. Menu: Shown at the top, menu provides different options to the application user.
  11. Dialog Box: A box that is displayed on the top of a window. Sometimes to display the notification.
  12. Grid: Used for the Layout Management of the UI.

Layout Management

The GUI applications must be optimised for various screens of different sizes, resolutions etc which seeks to keep an attractive but effective user interface with the various widgets organized onto the screen.

Event Handling

In GUI programming, the events like button clicks or key presses are critical. These events are handled by the app in order that it could follow the user actions. There are different events associated with different widgets. For example, for a clickable button, the associated events are:

  1. Click Event
  2. Mouse Move Event
  3. Focus In Event
  4. Focus Out Event

Popular GUI Libraries for C++

C++ have many platform independent GUI libraries that can be used to develop a GUI application. Some of the popular ones are:

  1. gtkmm
  2. Qt
  3. wxWidgets
  4. Dear ImuGui

Example of C++ GUI Application

We will be using the following tools for the below programs:

  1. Qt Library: The GUI library for our program.
  2. Qt Designer: An interactive GUI template designer for Qt.
  3. Qt Creator: IDE for Qt GUI Applications

Now, we will look at real cases for GUI programming with C++ and Qt. We are going to develop a basic “Hello World” application a button and when the button is clicked, a dialog box will appear with "Hello World" text written on it. We will implement it using these steps:

Step 1: Creating a Qt Project

We will open the Qt Creator and create a new project of type "Qt Widget Application". Enter the name, select the location and you are good to go. The Qt creator will create the project with all the required files.

creating-project

Step 2: Designing the Window

We will then open the file mainWindow.ui. This file contains the UI of the application. We will add one text label using the designer that just opened.


designing-ui

Now our files will contain the following code:

mainWindow.h

C++
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
  Q_OBJECT

public:
  MainWindow(QWidget *parent = nullptr);
  ~MainWindow();

private:
  Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H


main.cpp

C++
#include "mainwindow.h"

#include <QApplication>

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


mainWindow.cpp

C++
#include "mainwindow.h"
#include "./ui_mainwindow.h"

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

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


mainWindow.ui

XML
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>800</width>
    <height>600</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <widget class="QLabel" name="label">
    <property name="geometry">
     <rect>
      <x>260</x>
      <y>140</y>
      <width>81</width>
      <height>71</height>
     </rect>
    </property>
    <property name="text">
     <string>Hello World</string>
    </property>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>800</width>
     <height>22</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>


Notice that mainWindow.ui is written in XML. It is because Qt writes its UI files in XML.

Step 4: Build and Run

We can build and run the Qt project in Qt creator using a single click.


build-and-run

Output


hello_world


Advantages of GUI Applications

GUI applications offers several advantages, contributing to a better user experience and streamlined development:

  • User-Friendly Interface: The use of graphical user interfaces (GUIs) provides a simple and easy-to-use approach towards software applications compared to other approaches that would take more time.
  • Enhanced Interactivity: It encompasses interactive features like buttons, drop-down menus, checkbox, and slider that give users power over their experiences.
  • Cross-Platform Compatibility: The languages such as Qt enable creation of GUI application for windows, macOS, Linux with C++.
  • Rapid Prototyping: The presence of many GUI builders and design tools in GUI frameworks promotes quick prototyping of interfaces, making the entire development process faster.

Previous Article
Next Article

Similar Reads

Introduction to Parallel Programming with OpenMP in C++
Parallel programming is the process of breaking down a large task into smaller sub-tasks that can be executed simultaneously, thus utilizing the available computing resources more efficiently. OpenMP is a widely used API for parallel programming in C++. It allows developers to write parallel code easily and efficiently by adding simple compiler dir
5 min read
Introduction to C++ Programming Language
C++ is a general-purpose programming language that was developed as an enhancement of the C language to include object-oriented paradigm. It is an imperative and a compiled language. C++ is a high-level, general-purpose programming language designed for system and application programming. It was developed by Bjarne Stroustrup at Bell Labs in 1983 a
7 min read
Comparison of Java with other programming languages
Java is one of the most popular and widely used programming language and platform. A platform is an environment that helps to develop and run programs written in any programming language. Java is fast, reliable and secure. From desktop to web applications, scientific supercomputers to gaming consoles, cell phones to the Internet, Java is used in ev
4 min read
Web Programming in C++
CGI(COMMON GATEWAY INTERFACE) may be a set of standards that outline however data is changed from the online server, passing the online user’s request to Associate in Nursing application and to receive data back to the user. When any user requests for a web page, the server sends back the requested page. The Web server typically passes the form inf
5 min read
Hello World Program : First program while learning Programming
In this article, I'll show you how to create your first Hello World computer program in various languages. Along with the program, comments are provided to help you better understand the terms and keywords used in theLearning program. Programming can be simplified as follows: Write the program in a text editor and save it with the correct extension
6 min read
Importance of Testing In Competitive Programming
Many times while solving problems, we face issues like time limit exceeds, wrong solution, runtime error, and memory limit exceeds because after designing algorithm we don't test algorithm efficiency, correctness, time complexity and running the algorithm on a large set of inputs for testing purpose. This is where stress testing comes for rescue. S
3 min read
Comparison of Python with Other Programming Languages
Python is an easily adaptable programming language that offers a lot of features. Its concise syntax and open-source nature promote readability and implementation of programs which makes it the fastest-growing programming language in current times. Python has various other advantages which give it an edge over other popular programming languages su
3 min read
Writing code faster during Competitive Programming in C++
This article focuses on how to implement your solutions and implement them fast while doing competitive programming. Setup Please refer Setting up a C++ Competitive Programming Environment Snippets Snippet is a programming term for a small region of re-usable source Code. A lot of modern text editors like Sublime provide you a functionality to auto
3 min read
Top 10 Programming Languages for Blockchain Development
Do you ever wonder about the sudden emergence and popularity of Blockchain? What is it? Well, Blockchain is literally a chain of blocks as the name suggests! It’s just that the “blocks” in this context are digital information that is connected using cryptography. Each of these blocks contains a cryptographic hash function linking to the previous bl
7 min read
Why Java Language is Slower Than CPP for Competitive Programming?
Choosing the appropriate language while starting competitive programming is the most important factor. Generally, we choose that language that has short syntax and executes very fast or which is familiar to us, and we know all the working patterns of that particular whether it is Java or C++. Most of the programmers use C++ for competitive programm
5 min read
How to Use int as long long int for Competitive Programming?
Most of the time, input constraints in Competitive programming questions are bigger than the limits of int. Therefore, there is a need to use long int or even long long int. Here let us take two cases so that if a naive user writes correct logic still input is not getting accepted can get to know where the rectification is required. Case 1: Big int
3 min read
Different Ways to Setting Up Environment For C++ Programming in Mac
Xcode is an IDE developed by Apple themselves to develop apps for macOS and iOS or all other Operating Systems that Apple develops. It also has support for C/C++ built-in. Here, finding a C++ IDE for a macOS system is quite easy. To run a program in C++ in Mac we have to install Xcode or command-line tools for Xcode. Ways: Hence, there are two opti
3 min read
Most Critical Mistakes & Tips in Competitive Programming
The moment a beginner hears this word, an image pops up in one's mind where students are sitting in a room full of Computers and coding some out of the world stuff, We'll to be honest it's nothing too hard to grasp so we will be proposing tips that help a programmer to level up faster. So let's begin with the most underrated points on each topic wh
15+ min read
Setting up Sublime Text For Competitive Programming (C++) Using Fast Olympic Coding Plugin
Competitive Programming is a mind sport where time matters the most. For that, a fast and easy-to-use tool is required for writing code. Sublime text along with the CppFastOlympicCoding plugin provides the same. Sublime text is popular for its fast performance and aesthetic UI. The CppFastOlympicCoding plugin offers features such as: TestManager: W
4 min read
C++ Programming Examples
Writing C++ programs yourself is the best way to learn the C++ language. C++ programs are also asked in the interviews. This article covers the top practice problems for basic C++ programs on topics like control flow, patterns, and functions to complex ones like pointers, arrays, and strings. C++ Tutorial C++ Recent Articles Topics: Basic Programs
9 min read
Which C++ libraries are useful for competitive programming?
C++ is one of the most recommended languages in competitive programming (please refer our previous article for the reason) C++ STL contains lots of containers which are useful for different purposes. In this article, we are going to focus on the most important containers from competitive programming and interview preparation point of view. vector :
3 min read
Tips and Tricks for Competitive Programmers | Set 2 (Language to be used for Competitive Programming)
This is a question asked quite often as in which language should be preferred to be efficient in competitive programming. It is something one should not worry about as what matters is the logic, not the language. Most of the languages are more or less same, but till now the most preferred language is C++, and here are the reasons. Python Simple and
5 min read
getchar_unlocked() – Faster Input in C/C++ For Competitive Programming
getchar_unlocked() is similar to getchar() with the exception that it is not thread-safe. This function can be securely used in a multi-threaded program if and only if they are invoked when the invoking thread possesses the (FILE*) object, as is the situation after calling flockfile() or ftrylockfile(). Syntax: int getchar_unlocked(void); Example:
2 min read
Bitwise Hacks for Competitive Programming
Prerequisite: It is recommended to refer Interesting facts about Bitwise Operators How to set a bit in the number 'num': If we want to set a bit at nth position in the number 'num', it can be done using the 'OR' operator( | ). First, we left shift '1' to n position via (1<<n)Then, use the 'OR' operator to set the bit at that position. 'OR' op
14 min read
Writing C/C++ code efficiently in Competitive programming
First of all you need to know about Template, Macros and Vectors before moving on the next phase! Templates are the foundation of generic programming, which involve writing code in a way that is independent of any particular type.A Macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of
6 min read
C++ tricks for competitive programming (for C++ 11)
We have discussed some tricks in the below post. In this post, some more tricks are discussed. Writing C/C++ code efficiently in Competitive programming Although, practice is the only way that ensures increased performance in programming contests but having some tricks up your sleeve ensures an upper edge and fast debugging. 1) Checking if the numb
5 min read
Common mistakes to be avoided in Competitive Programming in C++ | Beginners
Not using of 1LL or 1ll when needed // A program shows problem if we // don't use 1ll or 1LL #include <iostream> using namespace std; int main() { int x = 1000000; int y = 1000000; // This causes overflow even // if z is long long int long long int z = x*y; cout << z; return 0; } Output: -727379968 You might get some other negative valu
7 min read
Programming puzzle (Assign value without any control statement)
Given four integers 'a', 'b', 'y' and 'x', where 'x' can only be either zero or one. Your task is as follows: If 'x' is zero assign value 'a' to the variable 'y'If 'x' is one assign value 'b' to the variable 'y'. It is not allowed to use any conditional operator (including the ternary operator). Examples : Input : a = 3, b = 7, x = 1 Output : y = 7
6 min read
How to Setup VSCode with C, C++ and Python for Competitive Programming
VSCode is a Text editor that provides support for development operations and version control systems. It provides tools for a user to build hassle-free codes. VSCode can be downloaded and installed from visualstudio.com This article will show you how to, fetch test cases directly from the browser without copy-pasting and run them in VSCode with jus
5 min read
C++ Programming and STL Facts
C++ is widely used for competitive programming. It is preferred because of its reliability, efficient execution, short snippets, etc. It has become adaptive by most coders as it also provides the benefits of Standard Template Library(STL). C++ STL is the backbone of programming. The inbuilt functions reduce a code snippet to even a single line some
5 min read
Implement Secure Hashing Algorithm - 512 ( SHA-512 ) as Functional Programming Paradigm
Given a string S of length N, the task is to find the SHA-512 Hash Value of the given string S. Examples: Input: S = "GeeksforGeeks"Output: acc10c4e0b38617f59e88e49215e2e894afaee5ec948c2af6f44039f03c9fe47a9210e01d5cd926c142bdc9179c2ad30f927a8faf69421ff60a5eaddcf8cb9c Input: S = "hello world"Output:309ecc489c12d6eb4cc40f50c902f2b4d0ed77ee511a7c7a9bc
15 min read
10 C++ Programming Tricks That You Should Know
C++ Programming Language is a powerful, versatile, and compiled language, which means the source code is converted into machine language before the execution. In order to make your code as efficient and effective as possible, you should be aware of the following tricks and techniques. Hence, it's better to know some C++ tricks and tips to reduce a
10 min read
Customized Debugging in Sublime Text using C++ for Competitive Programming
Competitive Programming is a mental sport that enables us to code a given problem under provided constraints. The purpose of this article is to guide every individual on how they can debug their code efficiently during a contest.Prerequisite: Setting up Sublime Text for C++ Competitive Programming Environment Time is something that is precious and
15+ min read
Socket Programming in C/C++: Handling multiple clients on server without multi threading
This tutorial assumes you have a basic knowledge of socket programming, i.e you are familiar with basic server and client model. In the basic model, server handles only one client at a time, which is a big assumption if you want to develop any scalable server model. The simple way to handle multiple clients would be to spawn new thread for every ne
9 min read
Role of SemiColon in various Programming Languages
Semicolon is a punctuation mark (;) indicating a pause, typically between two main clauses, that is more pronounced than that indicated by a comma. In programming, Semicolon symbol plays a vital role. It is used to show the termination of instruction in various programming languages as well, like C, C++, Java, JavaScript and Python. In this article
5 min read
Practice Tags :
three90RightbarBannerImg