Qt Create Slots

 
Qt Create Slots 3,6/5 1430 votes

The first example uses three separate handler functions, or slots, for each check box. The second example uses a single slot for all three check boxes. Follow the tutorial steps below to build the two QCheckBox example programs. Create a New Qt Widgets Application. Open Qt Creator and start a new Qt Widgets Application called checkbox. PyQt supports many type of signals, not just clicks. Example We can create a method (slot) that is connected to a widget. A slot is any callable function or method. Detailed Description. The QTimer class provides a high-level programming interface for timers. To use it, create a QTimer, connect its timeout signal to the appropriate slots, and call start. In order to use signals and slots, you need to have the QOBJECT macro in your class as well as identifying which functions should be the signals and the slots. Have a look at the documentation for a more in-depth explanation. After this, you need to set up the project file so that MOC can generate the necessary code.

In the following code snippet, we create two Counter objects and connect the first object's valueChanged signal to the second object's setValue slot using QObject::connect: Counter a, b; QObject:: connect( & a, SIGNAL(valueChanged( int )), & b, SLOT(setValue( int ))); a. SetValue( 12 ); // a.value 12, b.value 12 b. SetValue( 48 ); // a.value 12, b.value 48.

This tutorial is an introduction to Qt programming and will teach you how to create an application with Qt and C++. Full project and source code are provided.

Qt

Qt is a cross-platform framework and a collection of tools for creating applications which can run on desktop, embedded and mobile operating systems.

If you need to create an application with a GUI in C++ you should definitely consider Qt for it.

A simple example application

This tutorial will guide you through the creation of a basic window with a menu bar, a menu and a status bar. The final result while look like this:

Nothing too fancy, but these are the basic elements of most desktop applications and you can use this code as starting template for your projects.

When working with Qt, especially when developing cross-platform software, it’s recommended to use Qt Creator as IDE. The main reason is that Qt Creator is the official Qt IDE and it offers full integration with the framework and all the other development tools. Using other IDEs is possible, but I don’t recommend it and for this tutorial I will use Qt Creator.

Creating a new Qt project

The first step is to create a new project in Qt Creator from one of the available templates:

For a graphical application you want to select the Qt Widgets Application template.

The second step is selecting a name for your project and a location where to save it. For my project I decided to use “BasicApplication” for the name, but obviously you can use anything you want.

The third step is selecting the kit(s) for building your application.

Qt Creator kits are groups of settings used for building and running projects for different platforms.

Create

I am developing on Linux so I am going for the kit Desktop Qt 5.7.0 GCC 64bit, but you might see different kits if developing on/for different platforms.

The fourth step is defining the details of the initial main window class that will be generated by the template.

You can leave everything as it is, but make sure to uncheck the Generate form field. The form file is used by the integrated visual interface editor Qt Designer. We won’t need it because we will be coding the GUI from scratch.

In the final step of the project creation you will get a summary of what defined in the previous steps.

Here it’s also possible to set a version control system to use for the project, but feel free to not set any for now.

Clicking on the button Finish will create the project and generate 3 C++ files (main.cpp, MainWindow.h and MainWindow.cpp) and a project file used by Qt Creator and qmake (the Qt building tool) to build the project.

The main

The main function initialises the application, then creates and opens the main window:

The last line of code launches the Qt application and waits for it to return an exit code before terminating the program.

The main window class

The main window is defined in the header file MainWindow.h and it inherits from QMainWindow:

It’s important to include the Q_OBJECT macro in all the classes that are inheriting from QObject.

In this simple example the constructor is the only public function:

Finally some private slots are declared:

Slots are handlers used to do something when an event happens. They will be explained in more detail later.

The main window implementation

All the MainWindow methods, including the slots, are implemented in MainWindow.cpp.

Most of the code will be placed in the constructor because it’s there where the elements of the window are created.

Window settings

We can start with some basic settings:

The function setWindowTitle sets the title of the window, whereas setMinimumSize sets the minimum size allowed when resizing it.

Adding a menu bar

Most applications have a menu bar with menus. Creating one in Qt is pretty simple:

Once the menu bar is created you need to set it for the main window calling the setMenuBar function.

After creating and setting the menu bar it’s time to create a first menu:

The “&” before “File” will enable the keyboard shortcut ALT+F to open the menu.

Now that we have a menu we can populate it with entries, which are QAction objects:

As you can see creating an entry and adding it to a menu is pretty straightforward.

What’s more interesting is connecting menu entries to functions so that something happens when they are clicked. This is achieved using the Qt function connect which in its standard format takes 4 parameters:

  1. sender – the element generating an event
  2. signal – the event generated by the sender
  3. receiver – the element receiving the event
  4. slot – the handler to execute when an event is received

In the case of the first menu entry we have the following scenario

  1. sender : action (the menu entry)
  2. signal : &QAction::triggered (a menu entry has been clicked)
  3. receiver : this (the event is handled by the MainWindow)
  4. slot : &MainWindow::OnFileNew (when the menu entry is clicked this function is called)

When building a menu it’s also possible to add a horizontal line to to separate logic blocks. It only takes one line of code:

The final entry of the File menu is going to be one to exit from the application:

This entry is connected to the function close defined in QMainWindow which, as expected, will close the window when the menu entry is clicked.

Adding a status bar

A status bar is useful to show messages to the user. Creating one is pretty simple:

As for the menu bar, it’s important to remember to set the active status bar calling the setStatusBar function.

Implementing the slots

In this simple example all the slot functions do is setting a message to show in the status bar like in the following code:

Obviously this is just an example and a real application will do something more useful with them.

Adding content to the window

Once the basic elements of the window have been created it’s time to add some content.

This is done by calling the function setCentralWidget and passing it a QWidget which contains the graphic elements the application needs to show and handle.

I decided to not add any central widget in my code to keep this example as simple as possible, but obviously you’ll need to do that in your application.

Source code

The full source code of this tutorial is available on GitHub and released under the Unlicense license.

References

All the Qt widgets discussed in this tutorial are documented in detail in the Qt Widgets C++ Classes section of the Qt documentation.

To learn more about Qt Creator check out the online manual.

Conclusion

This was a simple tutorial to teach you how to create an application with Qt and C++. If you have any question about the code explained here feel free to leave a comment.

If you found it helpful please feel free to share it on social media using the share buttons below.

Subscribe

Don’t forget to subscribe to the blog newsletter to get notified of future posts.

You can also get updates following me on Google+, LinkedIn and Twitter.

The Raspberry pi is a mini computer which is designed in a single board with all the essential components required for running an operating system. The Raspberry pi board runs on the Broadcom controller chip which is a SoC (System on Chip). This powerful processor and the controller having the peripherals like timers, interrupt controller, GPIO, PCM / I2S, DMA controller, I2C, SPI slave, PWM, UART, USB, graphical processing unit (GPU) which includes VideoCore, MPEG-2 and MPEG-4 and a 512 MB SDRAM makes it a mini-computer. The board is provided with a RCA connector which can be used to connect it directly to a TV screen which is based on PAL and NTSC standard. The board also has a HDMI connector output which can be used to connect the board to a HD TV.

The Raspberrypi board is powerful enough to run large operating systems like Linux, Mac and Windows. Linux operating systems especially Ubuntu is preferred for all kind of programming and development. Since the board capable of generating graphics on standard display screen needs a perfect application using which the programmers can exploit that capability. The ‘QT’ is a widely used platform for creating GUIs in Linux environment. The ‘QT’ is a widely used platform for creating GUIs in Linux environment. Qt is an application which helps in developing the UI framework using the Qt IDE. Qt uses standard C++ but it also supports support many compilers, including the GCC C++ compiler and the Visual Studio suite.

The GUI or graphical user interface makes it easy for the user to control or communicate with the applications which are connected to that particular GUI. The most unavoidable components of a GUI window are ‘buttons’ and this article discusses how to create a button and use it with the help of QT.

In this project the Raspberrypi board is loaded with Ubuntu and is remotely accessed using VNC. The Raspberrypi board is also connected to the internet. Downloading and installing the fourth version, QT4 using commands are already discussed in a previous article. There is another article which discusses about how to start with programming in QT, a hello world program using QT.

Once the installation is complete the user can find them listed under the installed programs for ‘Programming’ as shown in the following image;

Fig. 2: QT Listed In Installed Programs

The list includes “Qt 4 Assistant”, “Qt 4 Designer”, “Qt 4 Linguist” and “Qt Creator”. The “Qt 4 Assistant” is basically provides help in the form of documentations related to the topics in QT. “Qt 4 Designer” is where the user can create a design and save it as a ‘.ui’ file which can then be used in QT projects. The “Qt 4 Linguist” provides a language view of the design created. The “Qt Creator” is where all these things can be done in the same IDE which helps in creating a GUI using QT.

Click on the “Qt Creator” and the following window opens up which includes options for creating a project as explained in the article hello world program using QT.

As soon as a new project is created the “Edit” window of the Qt Creator will open up. Expand the “Forms” where the “mainwindow.ui” can be seen listed. Now double click on the “mainwindow.ui” and the Qt Creator’s “Design” window opens up:

Fig. 3: Drag And Drop ‘Push Button’ QT Creator Window In Ubuntu

Drag and drop a ‘Push Button’ from the list of ‘Buttons’ into the dialogue box as shown in the above image. Right click on the ‘Push Button’ and the text displayed on the button can be modified by selecting the “Change text” option.

Fig. 4: Editing Text of Push Button In QT Creator Window For GUI In Raspberry Pi

Every component in the designer is represented as an object in the code in the editor and every object has a specific default name also. It is possible to change the name of the object as per the convenience of the user, necessary when using many numbers of buttons or other components. Right click on the ‘Push Button’ and the object name of the button can be modified by selecting the “Change object name” option.

Fig. 5: Changing Object Name And Text In QT Creator Window

Here the object name is modified to “button_1” and the text displayed on the button is changed to “Say hello”. As soon as the object name is changed the same change can be visible as marked in the following image:

Fig. 6: Push Button Name Changed To Say Hello

Qt creator slots and signals

In the following steps how to assign a particular function to the button is discussed. There are terms called ‘Signals’ and ‘Slots’. Slots are basically functions which are associated with an object and the Signals are send to execute those functions whenever the object is enabled. For example whenever the user clicks on a button a Signal will be send to the corresponding Slot function.

To create a Slot and Signal corresponding to an object just right click on the button and select the option “Go to Slot”.

Fig. 7: Creating Slot For Object Button To Assign Function With QT

The user will be provided with a list of Signals corresponding to that Push Button type object. Since the button is commonly used for clicking, here the signal ‘clicked ()’ has been selected.

Fig. 8: Creating Signal For Object Button To Execute Function With QT

Once clicked on the “OK” button it will instantly direct the user to the Editor window where the corresponding Slot can be visible in the code, here “_on_button_1_clicked ()”

Fig. 9: Slot Visible In Code Of Editor Window

This function will be called whenever the button object named “button_1 is clicked. Just to test it the user can write a simple printf () statement as shown in the following image, don’t forget to add the <stdio.h> header file.

Fig. 10: Testing The Code With Print f Command

The coding is finished with that and now save the project using “File >> Save All”.

Fig. 11: Saving The Project Using File From QT Creator Tool Bar

Qt Create Slots Poker

Build the code and run it as explained in the articlehello world program using QT.

Fig. 12: Build Code And Run Using QT

Qt Create Slots Free

As the GUI runs it prints the string “HELLO WORLD” each and every time the button “Say Hello” is clicked.

Qt Creator Slots

Fig. 13: “HELLO WORLD” Printed As GUI Executes Command