Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Qt5 C++ GUI Programming Cookbook
Qt5 C++ GUI Programming Cookbook

Qt5 C++ GUI Programming Cookbook: Design and build a functional, appealing, and user-friendly graphical user interface

eBook
€26.99 €29.99
Paperback
€36.99
Hardcover
€32.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Qt5 C++ GUI Programming Cookbook

Chapter 1. Look and Feel Customization

In this chapter we will cover the following recipes:

  • Using style sheets with Qt Designer
  • Basic style sheet customization
  • Creating a login screen using style sheets
  • Using resources in style sheets
  • Customizing properties and sub-controls
  • Styling in QML
  • Exposing QML object pointer to C++

Introduction

Qt allows us to easily design our program's user interface through a method that most people are familiar with. Qt not only provides us with a powerful user interface toolkit called Qt Designer, which enables us to design our user interface without writing a single line of code, but it also allows advanced users to customize their user interface components through a simple scripting language called Qt Style Sheets.

Use style sheets with Qt Designer

In this example, we will learn how to change the look and feel of our program and make it look more professional by using style sheets and resources. Qt allows you to decorate your Graphical User Interfaces (GUIs) using a style sheet language called Qt Style Sheets, which is very similar to Cascading Style Sheets (CSS) used by web designers to decorate their websites.

How to do it…

  1. The first thing we need to do is open up Qt Creator and create a new project. If this is the first time you have used Qt Creator, you can either click the big button that says New Project with a + sign, or simply go to File | New File or New Project.
  2. Then, select Application under the Project window and select Qt Widgets Application.
  3. After that, click the Choose button at the bottom. A window will then pop out and ask you to insert the project name and its location.
  4. Once you're done with that, click Next several times and click the Finish button to create the project. We will just stick to all the default settings for now. Once the project has been created, the first thing you will see is the panel with tons of big icons on the left side of the window that is called the Mode Selector panel; we will discuss this more later in the How it works... section.
  5. Then, you will also see all your source files listed on the Side Bar panel which is located right next to the Mode Selector panel. This is where you can select which file you want to edit, which, in this case, is mainwindow.ui because we are about to start designing the program's UI!
  6. Double-click mainwindow.ui and you will see an entirely different interface appearing out of nowhere. Qt Creator actually helped you to switch from the script editor to the UI editor (Qt Designer) because it detected the .ui extension on the file you're trying to open.
  7. You will also notice that the highlighted button on the Mode Selector panel has changed from the Edit button to the Design button. You can switch back to the script editor or change to any other tools by clicking one of the buttons located in the upper half of the Mode Selector panel.
  8. Let's go back to the Qt Designer and look at the mainwindow.ui file. This is basically the main window of our program (as the filename implies) and it's empty by default, without any widget on it. You can try to compile and run the program by pressing the Run button (green arrow button) at the bottom of the Mode Selector panel, and you will see an empty window popping up once the compilation is complete:
    How to do it…
  9. Now, let's add a push button to our program's UI by clicking on the Push Button item in the widget box (under the Buttons category) and dragging it to your main window in the form editor. Then, keep the push button selected, and now you will see all the properties of this button inside the property editor on the right side of your window. Scroll down to somewhere around the middle and look for a property called styleSheet. This is where you apply styles to your widget, which may or may not inherit to its children or grandchildren recursively depending on how you set your style sheet. Alternatively, you can also right-click on any widget in your UI at the form editor and select Change Style Sheet from the pop-up menu.
  10. You can click on the input field of the styleSheet property to directly write the style sheet code, or click on the button besides the input field to open up the Edit Style Sheet window which has a bigger space for writing longer style sheet code. At the top of the window you can find several buttons, such as Add Resource, Add Gradient, Add Color, and Add Font, that can help you to kick-start your coding if you can't remember the properties' names.

    Let's try to do some simple styling with the Edit Style Sheet window.

  11. Click Add Color and choose color.
  12. Pick a random color from the color picker window, let's say, a pure red color. Then click OK.
  13. Now, you will see a line of code has been added to the text field on the Edit Style Sheet window, which in my case is as follows:

    color: rgb(255, 0, 0);

  14. Click the OK button and now you will see the text on your push button has changed to a red color.

How it works...

Let's take a bit of time to get ourselves familiar with Qt Designer's interface before we start learning how to design our own UI:

Basic style sheet customization

In the previous example, you learned how to apply a style sheet to a widget with Qt Designer. Let's go crazy and push things further by creating a few other types of widgets and change their style properties to something bizarre for the sake of learning. This time, however, we will not apply the style to every single widget one by one, but we will learn to apply the style sheet to the main window and let it inherit down the hierarchy to all the other widgets so that the style sheet is easier to manage and maintain in long run.

How to do it…

  1. First of all, let's remove the style sheet from the push button by selecting it and clicking the small arrow button besides the styleSheet property. This button will revert the property to the default value, which in this case is the empty style sheet.
  2. Then, add a few more widgets to the UI by dragging them one by one from the widget box to the form editor. I've added a line edit, combo box, horizontal slider, radio button, and a check box.
  3. For the sake of simplicity, delete the menu bar, main toolbar, and the status bar from your UI by selecting them from the object inspector, right click, and choose Remove. Now your UI should look similar to this:
    How to do it…
  4. Select the main window either from the form editor or the object inspector, then right click and choose Change Stylesheet to open up the Edit Style Sheet.

    Insert the following style sheet:

    border: 2px solid gray;
    border-radius: 10px;
    padding: 0 8px;
    background: yellow;
  5. Now what you will see is a completely bizarre-looking UI with everything covered in yellow with a thick border. This is because the preceding style sheet does not have a selector, which means the style will apply to the children widgets of the main window all the way down the hierarchy. To change that, let's try something different:
    QPushButton
    {
      border: 2px solid gray;
      border-radius: 10px;
      padding: 0 8px;
      background: yellow;
    }
  6. This time, only the push button will get the style described in the preceding code, and all other widgets will return to the default styling. You can try to add a few more push buttons to your UI and they will all look the same:
    How to do it…
  7. This happens because we specifically tell the selector to apply the style to all the widgets with the class called QPushButton. We can also apply the style to just one of the push buttons by mentioning its name in the style sheet, like so:
    QPushButton#pushButton_3
    {
      border: 2px solid gray;
      border-radius: 10px;
      padding: 0 8px;
      background: yellow;
    }
  8. Once you understand this method, we can add the following code to the style sheet :
    QPushButton
    {
      color: red;
      border: 0px;
      padding: 0 8px;
      background: white;
    }
    
    QPushButton#pushButton_2
    {
      border: 1px solid red;
      border-radius: 10px;
    }
    
    QPushButton#pushButton_3
    {
      border: 2px solid gray;
      border-radius: 10px;
      padding: 0 8px;
      background: yellow;
    }
  9. What it does is basically change the style of all the push buttons as well as some properties of a specific button named pushButton_2. We keep the style sheet of pushButton_3 as it is. Now the buttons will look like this:
    How to do it…
  10. The first set of style sheet will change all widgets of QPushButton type to a white rectangular button with no border and red text. Then the second set of style sheet changes only the border of a specific QPushButton widget called pushButton_2. Notice that the background color and text color of pushButton_2 remain white and red respectively because we didn't override them in the second set of style sheet, hence it will return to the style described in the first set of style sheet since it's applicable to all QPushButton widgets. Do notice that the text of the third button has also changed to red because we didn't describe the color property in the third set of style sheet.
  11. After that, create another set of style using the universal selector, like so:
    *
    {
      background: qradialgradient(cx: 0.3, cy: -0.4, fx: 0.3, fy: -0.4, radius: 1.35, stop: 0 #fff, stop: 1 #888);
      color: rgb(255, 255, 255);
      border: 1px solid #ffffff;
    }
  12. The universal selector will affect all the widgets regardless of their type. Therefore, the preceding style sheet will apply a nice gradient color to all the widgets' background as well as setting their text as white and giving them a one-pixel solid outline which is also in white. Instead of writing the name of the color (that is, white), we can also use the rgb function (rgb(255, 255, 255)) or hex code (#ffffff) to describe the color value.
  13. Just as before, the preceding style sheet will not affect the push buttons because we have already given them their own styles which will override the general style described in the universal selector. Just remember that in Qt, the style that is more specific will ultimately be used when there is more than one style having influence on a widget. This is how the UI will look now:
    How to do it…

How it works...

If you are ever involved in web development using HTML and CSS, Qt's style sheet works exactly the same way as CSS. Style sheets provide the definitions for describing the presentation of the widgets – what the colors are for each element in the widget group, how thick the border should be, and so on and so forth.

If you specify the name of the widget to the style sheet, it will change the style of a particular push button widget with the name you provide. None of the other widgets will be affected and will remain as the default style.

To change the name of a widget, select the widget either from the form editor or the object inspector and change the property called objectName in the property window. If you have used the ID selector previously to change the style of the widget, changing its object name will break the style sheet and lose the style. To fix this problem, simply change the object name in the style sheet as well.

Creating a login screen using style sheets

Next, we will learn how to put all the knowledge we learned in the previous example together and create a fake graphical login screen for an imaginary operating system. Style sheets are not the only thing you need to master in order to design a good UI. You will also need to learn how to arrange the widgets neatly using the layout system in Qt Designer.

How to do it…

  1. The first thing we need to do is design the layout of the graphical login screen before we start doing anything. Planning is very important in order to produce good software. The following is a sample layout design I made to show you how I imagine the login screen will look. Just a simple line drawing like this is sufficient as long as it conveys the message clearly:
    How to do it…

We are not done with the login form yet. Now that we have created the container for the login form, it's time to put more widgets into the form:

  1. Place two horizontal layouts into the login form container. We need two layouts as one for the username field and another for the password field.
  2. Add a label and a line edit to each of the layouts you just added. Change the text property of the upper label to Username: and the one below as Password:. Then, rename the two line edits as username and password respectively.
  3. Add a push button below the password layout and change its text property to Login. After that, rename it as loginButton.
  4. You can add a vertical spacer between the password layout and the login button to distance them slightly. After the vertical spacer has been placed, change its sizeType property to Fixed and change the Height to 5.
  5. Now, select the loginForm container and set all its margins to 35. This is to make the login form look better by adding some space to all its sides.
  6. You can also set the Height property of the username, password, and loginButton widgets to 25 so that they don't look so cramped.
  7. Now your UI should look something like this:
    How to do it…
  8. After we've done the layout, it's time for us to add some fanciness to the UI using style sheets! Since all the important widgets have been given an object name, it's easier for us to apply the style sheets to it from the main window, since we will only write the style sheets to the main window and let them inherit down the hierarchy tree.
  9. Right click on MainWindow from the object inspector window and choose Change Stylesheet.
  10. Add the following code to the style sheet:
    #centralWidget { background: rgba(32, 80, 96, 100); }
  11. Now you will see that the background of the main window changes its color. We will learn how to use an image for the background in the next section, so the color is just temporary.
  12. In Qt, if you want to apply styles to the main window itself, you must apply it to its central widget instead of the main window itself because the window is just a container.
  13. Then, we will add a nice gradient color to the top panel:
    #topPanel { background-color: qlineargradient(spread:reflect, x1:0.5, y1:0, x2:0, y2:0, stop:0 rgba(91, 204, 233, 100), stop:1 rgba(32, 80, 96, 100)); }
  14. After that, we will apply black color to the login form and make it look semi-transparent. After that, we will also make the corners of the login form container slightly rounded by setting the border-radius property:
    #loginForm
    {
      background: rgba(0, 0, 0, 80);
      border-radius: 8px;
    }
  15. After we're done applying styles to the specific widgets, we will apply styles to the general types of widgets instead:
    QLabel { color: white; }
    QLineEdit { border-radius: 3px; }
  16. The preceding style sheets will change all the labels' texts to a white color, which includes the text on the widgets as well because, internally, Qt uses the same type of label on the widgets that have text on it. Also, we made the corners of the line edit widgets slightly rounded.
  17. Next, we will apply style sheets to all the push buttons on our UI:
    QPushButton
    {
      color: white;
      background-color: #27a9e3;
      border-width: 0px;
      border-radius: 3px;
    }
  18. The preceding style sheet changes the text of all the buttons to a white color, then sets its background color to blue, and makes its corners slightly rounded as well.
  19. To push things even further, we will change the color of the push buttons when we mouse-over it, using the keyword hover:
    QPushButton:hover { background-color: #66c011; }
  20. The preceding style sheet will change the background color of the push buttons to green when we mouse-over them. We will talk more about this in the following section.
  21. You can further adjust the size and margins of the widgets to make them look even better. Remember to remove the border line of the login form by removing the style sheet that we applied directly to it earlier.
  22. Now your login screen should look something like this:
    How to do it…

How it works...

This example focuses more on the layout system of Qt. The Qt layout system provides a simple and powerful way of automatically arranging child widgets within a widget to ensure that they make good use of the available space.

The spacer items used in the preceding example help to push the widgets contained in a layout outward to create spacing along the width of the spacer item. To locate a widget to the middle of the layout, put two spacer items to the layout, one on the left side of the widget and another on the right side of the widget. The widget will then be pushed to the middle of the layout by the two spacers.

Using resources in style sheets

Qt provides us with a platform-independent resource system which allows us to store any type of files in our program's executable for later use. There is no limit to the types of files we can store in our executable—images, audio, video HTML, XML, text files, binary files, and so on, are all permitted. This is useful if your application always needs a certain set of files (icons, translation files, and so on) and you don't want to run the risk of losing the files. To achieve this, we must tell Qt which files we want to add to its resource system in the .qrc file and Qt will handle the rest during the build process.

How to do it

To add a new .qrc file to our project, go to File | New File or Project. Then, select Qt under the Files and Classes category and select Qt Resources File. After that, give it a name (that is, resources) and click the Next button followed by the Finish button. The .qrc file will not be created and automatically opened by Qt Creator.

You don't have to edit the .qrc file directly in the XML format as Qt Creator provides you the user interface to manage your resources. To add images and icons to your project, first you need to make sure that the images and icons are being placed in your project's directory.

While the .qrc file is opened in Qt Creator, click the Add button followed by Add Prefix button. The prefix is used to categorize your resources so that it can be better managed when you have a ton of resources in your project:

  1. Rename the prefix you just created /icons.
  2. Then, create another prefix by clicking Add followed by Add Prefix.
  3. Rename the new prefix /images.
  4. After that, select the /icon prefix and click Add followed by Add Files.
  5. A file selection window will appear; use that to select all the icon files. You can select multiple files at a time by holding the Ctrl key on your keyboard while clicking on the files to select them. Click Open once you're done.
  6. Then, select the /images prefix and click the Add button followed by the Add Files button. The file selection window will pop up again, and this time we will select the background image.
  7. Repeat the preceding steps, but this time we will add the logo image to the /images prefix.

    Don't forget to save once you're done by pressing Ctrl + S. Your .qrc file should now look like this:

    How to do it
  8. Lastly, we will apply the wallpaper image to the background using a style sheet. Since the background dimension will change according to the window size, we cannot use pixmap in this case. Instead, we will use the border-image property in a style sheet to achieve this. Right click the main window and select Change styleSheet to open up the Edit Style Sheet window. We will add a new line under the style sheet of the central widget:
    #centralWidget
    {
      background: rgba(32, 80, 96, 100);
      border-image: url(:/images/login_bg.png);
    }
  9. It's really that simple and easy! Your login screen should now look like this:
    How to do it

How it works...

The resource system in Qt stores binary files, such as images, translation files, and so on, in the executable when it gets compiled. It reads the resource collection files (.qrc) in your project to locate the files that need to be stored in the executable and include them into the build process. A .qrc file looks something like this:

<!DOCTYPE RCC><RCC version="1.0">
  <qresource>
    <file>images/copy.png</file>
    <file>images/cut.png</file>
    <file>images/new.png</file>
    <file>images/open.png</file>
    <file>images/paste.png</file>
    <file>images/save.png</file>
  </qresource>
</RCC>

It uses XML format to store the paths of the resource files which are relative to the directory containing it. Do note that the listed resource files must be located in the same directory as the .qrc file, or one of its sub-directories.

Customizing properties and sub-controls

Qt's style sheet system enables us to create stunning and professional-looking UIs with ease. In this example, we will learn how to set custom properties to our widgets and use them to switch between different styles.

How to do it…

  1. Let's try out the scenario described in the preceding paragraph by creating a new Qt project. I have prepared the UI for this purpose. The UI contains three buttons on the left side and a tab widget with three pages located at the right side, as shown in the following screenshot:
    How to do it…
  2. The three buttons are blue in color because I've added the following style sheet to the main window (not to the individual button):
    QPushButton
    {
      color: white;
      background-color: #27a9e3;
      border-width: 0px;
      border-radius: 3px;
    }
  3. Next, I will explain to you what pseudo states are in Qt by adding the following style sheet to the main window, which you might be familiar with:
    QPushButton:hover
    {
      color: white;
      background-color: #66c011;
      border-width: 0px;
      border-radius: 3px;
    }
  4. We used the preceding style sheet in the previous tutorial to make the buttons change color when there is a mouse-over. This is made possible by Qt Style Sheet's pseudo state, which in this case is the word hover separated from the QPushButton class by a colon. Every widget has a set of generic pseudo states, such as active, disabled, enabled, and so on, and also a set of pseudo states which are applicable to their widget type. For example, states such as open and flat are available for QPushButton, but not for QLineEdit. Let's add the pressed pseudo state to change the buttons' color to yellow when the user clicks on it:
    QPushButton:pressed
    {
      color: white;
      background-color: yellow;
      border-width: 0px;
      border-radius: 3px;
    }
  5. Pseudo states allow the users to load a different set of style sheet based on the condition that applies to it. Qt pushes this concept further by implementing dynamic properties in Qt Style Sheets. This allows us to change the style sheet of a widget when a custom condition has been met. We can make use of this feature to change the style sheet of our buttons based on a custom condition that we can set using custom properties in Qt.

    First, we will add this style sheet to our main window:

    QPushButton[pagematches=true]
    {
      color: white;
      background-color: red;
      border-width: 0px;
      border-radius: 3px;
    }
  6. What it does is basically change the push button's background color to red if the property called pagematches returns true. Obviously, this property does not exist in the QPushButton class. However, we can add it to our buttons by using QObject::setProperty():
    • In your MainWindow.cpp source code, add the following code right after ui->setupUi(this);:
      ui->button1->setProperty("pagematches", true);
    • The preceding code will add a custom property called pagematches to the first button and set its value as true. This will make the first button turn red by default.
    • After that, right click on the tab widget and choose Go to slot. A window will then pop up; select the currentChanged(int) option from the list and click Ok. Qt will generate a slot function for you, which looks something like this:
      private slots:
      void on_tabWidget_currentChanged(int index);
    • The slot function will be called whenever we change page of the tab widget. We can then decide what we want it to do by adding our code into the slot function. To do that, open up mainwindow.cpp and you will see the function's declaration there. Let's add some code to the function:
      void MainWindow::on_tabWidget_currentChanged(int index)
      {
        / Set all buttons to false
        ui->button1->setProperty("pagematches", false);
        ui->button2->setProperty("pagematches", false);
        ui->button3->setProperty("pagematches", false);
      
        / Set one of the buttons to true
        if (index == 0)
          ui->button1->setProperty("pagematches", true);
        else if (index == 1)
          ui->button2->setProperty("pagematches", true);
        else
          ui->button3->setProperty("pagematches", true);
      
        / Update buttons style
        ui->button1->style()->polish(ui->button1);
        ui->button2->style()->polish(ui->button2);
        ui->button3->style()->polish(ui->button3);
      }
  7. The preceding code basically does this: when the tab widget switches its current page, it sets the pagematches properties of all three buttons to false. Just be sure to reset everything before we decide which button should change to red.
  8. Then, check the index variable supplied by the event signal, which will tell you the index number of the current page. Set the pagematches property of one of the buttons to true based on the index number.
  9. Lastly, refresh the style of all three buttons by calling polish().

    Then, build and run the project. You should now see the three buttons changing their color to red whenever you switch the tab widget to a different page. Also, the buttons will change color to green when there is a mouse-over, as well as change their color to yellow when you click on them:

    How to do it…

How it works...

Qt provides users the freedom of adding their own custom properties to any type of widget. Custom properties are very useful if you want to change a particular widget when a special condition is met, where Qt doesn't provide such a context by default. This allows the user to extend the usability of Qt and makes it a flexible tool for customized solutions.

For example, if we have a row of buttons on our main window and we need one of them to change its color depending on which page the tab widget is currently showing, then there is no way the buttons would know when they should change their color, because Qt itself has no built-in context for this type of situation. To solve this issue, Qt provides us a method to add our own properties to the widgets, which is using a generic function called QObject::setProperty(). To read the custom property, we can use another function called QObject::property().

Next, we will talk about sub-controls in Qt Style Sheets. It's actually quite self-explanatory by looking at the term sub-controls. Often, a widget is not just a single object but a combination of more than one object or control in order to form a more complex widget, and such objects are called sub-controls.

For example, a spin box widget contains an input field, a down button, an up button, an up arrow, and a down arrow, which is quite complicated compared to some other widgets. In this case, Qt grants us more flexibility by allowing us to change every single sub-control using a style sheet, if we wanted to. We can do so by specifying the name of the sub-control behind the widget's class name, separated by a double colon. For instance, if I want to change the image of the down button in a spin box, I can write my style sheet like this:

QSpinBox::down-button
{
  image: url(:/images/spindown.png);
  subcontrol-origin: padding;
  subcontrol-position: right bottom;
}

That will only apply the image to the down button of my spin box, and not to any other parts of the widget.

By combining custom properties, pseudo states, and sub-controls, Qt provides us with a very flexible method to customize our user interface.

Note

Visit the following link to learn more about pseudo states and sub-controls in Qt:

http://doc.qt.io/qt-4.8/stylesheet-reference.html

Styling in QML

Qt Meta Language or Qt Modeling Language (QML) is a Javascript-inspired user interface mark-up language used by Qt for designing user interfaces. Qt provides you with Qt Quick components (widgets powered by the QML technology) to easily design touch-friendly UI without C++ programming. We will learn more about how to use QML and Qt Quick components to design our program's UI by following the steps given in the following section.

How to do it…

  1. Create a new project by going to File | New File or Project. Select Application under Project category and choose Qt Quick Application.
  2. Press the Choose button, and that will bring you to the next window. Insert a name for your project and click the Next button again.
  3. Another window will now appear and ask you to choose a minimum required Qt version. Pick the latest version installed on your computer and click Next.
  4. After that, click Next again followed by Finish. Qt Creator will now create a new project for you.
  5. Once the project is being created, you will see there are some differences compare to a C++ Qt project. You will see two .qml files, namely main.qml and MainForm.ui.qml, inside the project resource. These two files are the UI description files using the QML mark-up language. If you double click main.qml file, Qt Creator will open up the script editor and you will see something like this:
    import QtQuick 2.5
    import QtQuick.Window 2.2
    
    Window {
      visible: true
      MainForm {
        anchors.fill: parent
        mouseArea.onClicked: {
          Qt.quit();
        }
      }
    }
  6. This file basically tells Qt to create a window and insert a set of UI called MainForm which is actually from the other .qml file called MainForm.ui.qml. It also tells Qt that when the user clicks on the mouseArea widget, the entire program should be terminated.
  7. Now, try to open the MainForm.ui.qml file by double-clicking on it. This time, Qt Designer (UI editor) will be opened instead, and you will see a completely different UI editor compared to the C++ project we did previously. This editor is also called the Qt Quick Designer, specially designed for editing QML-based UI only.
  8. If you open up the main.cpp file in your project, you will see this line of code:
    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
  9. The preceding code basically tells Qt's QML engine to load the main.qml file when the program starts. If you want to load the other .qml file instead of main.qml, you know where to look for the code.
  10. When main.qml is loaded by the QML engine, it will also import MainForm.ui.qml into the UI, since MainForm is being called in the main.qml file. Qt will check if MainForm is a valid UI by searching for its .qml file based on the naming convention. Basically the concept is similar to the C++ project we did in the previous section, whereby the main.qml file acts like the main.cpp file and MainForm.ui.qml acts like the MainWindow class. You can also create other UI templates and use them in main.qml. Hopefully this comparison will make it easier to understand how QML works.
  11. Now let's open up MainForm.ui.qml. You should see three items listed on the navigator window: Rectangle, mouseArea, and Text. When these items are interpreted by the QML engine, it produces the following result on the canvas:
    How to do it…
  12. We can also re-arrange them by using the arrow buttons located on top of the navigator window, as shown in the preceding screenshot. Anything that happens to the parent item will also affect all its children, such as moving the parent item, hide and show the parent item, and so on.

    Tip

    You can pan around the canvas view by holding the middle mouse button (or mouse scroll) while moving your mouse around. You can also zoom in and out by scrolling your mouse while holding the Ctrl key on your keyboard. By default, scrolling your mouse will move the canvas view up and down. However, if your mouse cursor is on top of the horizontal scroll bar of the canvas, scrolling the mouse will move the view to the left and right.

  13. Next, delete both the mouseArea and Text items as we will be learning how to create a user interface from scratch using QML and Qt Quick.
  14. After you've done, let's set the Rectangle item's size to 800x600, as we're going to need a bigger space for the widgets.
  15. Open up main.qml and remove these lines of code:
    mouseArea.onClicked: {
      Qt.quit();
    }

    This is because the mouseArea item no longer exists and it will cause an error when compiling.

  16. After that, remove the following code from MainForm.ui.qml:
    property alias mouseArea: mousearea
  17. This is removed for the same reason as the previous code, because the mouseArea item no longer exists.
  18. Then, copy the images we used in the previous C++ project over to the QML project's folder, because we are going re-create the same login screen, with QML!
  19. Add the images to the resource file so that we can use them for our UI.
  20. Once you're done with that, open up Qt Quick Designer again and switch to the resource window. Click and drag the background image directly to the canvas. Then, switch over to the Layout tab on the properties pane and click the fill anchor button marked in red circle. This will make the background image always stick to the window size:
    How to do it…
  21. Add the text widgets to the canvas. Make them the children of the login form (rectangle widget) and set their text property to Username: and Password: respectively. Then, change their text color to white and position them accordingly. We don't need to set a margin this time because they will follow the rectangle's position.
  22. Next, add two text input widgets to the canvas and place them next to the text widgets we created just now. Make sure the text inputs are also the children of the login form. Since the text inputs don't contain any background color property, we need to add two rectangles to the canvas to use as their background.
  23. Add two rectangles to the canvas and make each of them a child of one of the text inputs we created just now. Then, set the radius property to 5 to give them some rounded corners. After that, enable fill anchors on both of the rectangles so that they will follow the size of the text input widgets.
  24. After that, we're going to create the login button below the password field. First, add a mouse area to the canvas and make it a child of the login form. Then, resize it to your preferred dimension and move it into place.
  25. Since the mouse area also does not contain any background color property, we need to add a rectangle widget and make it a child of the mouse area. Set the color of the rectangle to blue (#27a9e3) and enable the fill anchor so that it fits nicely with the mouse area.
  26. Next, add a text widget to the canvas and make it a child of the login button. Change its text color to white and set its text property to Login. Finally, enable the horizontal center anchor and the vertical center anchor to align it to the center of the button.
  27. You will now get a login form that looks pretty similar to the one we made in the C++ project:
    How it works...

    We will now look at the various elements of the editor's UI:

    1. Navigator: The Navigator window displays the items in the current QML file as a tree structure. It's similar to the object operator window in the other Qt Designer we used in previous section.
    2. Library: The Library window displays all the Qt Quick Components or Qt Quick Controls available in QML. You can click and drag it to the canvas window to add to your UI. You can also create your own custom QML components and display it here.
    3. Resources: The Resources window displays all the resources in a list which can then be used in your UI design.
    4. Imports: The Imports window allows you to import different QML modules into your current QML file, such as a bluetooth module, webkit module, positioning module, and so on, to add additional functionality to your QML project.
    5. State pane: Stat pane displays the different states in the QML project which typically describe UI configurations, such as the UI controls, their properties and behavior, and the available actions.
    6. Properties pane: Similar to the property editor we used in previous section, this properties pane in QML Designer displays the properties of the selected item. You can also change the properties of the items in the code editor as well.
    7. Canvas: Canvas is the working area where you create QML components and design applications.

Exposing QML object pointer to C++

Sometimes we want to modify the properties of a QML object through C++ scripting, such as changing the text of a label, hiding/showing the widget, changing its size, and so on. Qt's QML engine allows you to register your QML objects to C++ types which automatically exposes all its properties.

How to do it…

We want to create a label in QML and change its text occasionally. In order to expose the label object to C++, we can do the following steps. First, create a C++ class called MyLabel that extends from QObject class:

mylabel.h:
class MyLabel : public QObject
{
  Q_OBJECT
  public:
    / Object pointer
    QObject* myObject;

    explicit MyLabel(QObject *parent = 0);

  / Must call Q_INVOKABLE so that this function can be used in QML
  Q_INVOKABLE void SetMyObject(QObject* obj);
}

In the mylabel.cpp source file, define a function called SetMyObject() to save the object pointer. This function will later be called in QML:

mylabel.cpp:
void MyLabel::SetMyObject(QObject* obj)
{
  / Set the object pointer
  myObject = obj;
}

After that, in main.cpp, include MyLabel header and register it to QML engine using the function qmlRegisterType():

#include "mylabel.h"
int main(int argc, char *argv[])
{
  / Register your class to QML
  qmlRegisterType<MyClass>("MyLabelLib", 1, 0, "MyLabel");
}

Notice that there are four parameters you need to declare in qmlRegisterType(). Besides declaring your class name (MyLabel), you also need to declare your library name (MyLabelLib) and its version (1.0), which will be used for importing your class to QML later on.

Now that the QML engine is fully aware of our custom label class, we can then map it to our label object in QML and import the class library we defined earlier by calling import MyLabelLib 1.0 in our QML file. Notice that the library name and its version number have to match with the one you declared in main.cpp, otherwise it will throw you an error.

After declaring MyLabel in QML and setting its ID as mylabels, call mylabel.SetMyObject(myLabel) to expose its pointer to C/C++ right after the label is being initialized:

import MyLabelLib 1.0

ApplicationWindow
{
  id: mainWindow
  width: 480
  height: 640

  MyLabel
  {
    id: mylabel
  }

  Label
  {
    id: helloWorldLabel
    text: qsTr("Hello World!")
    Component.onCompleted:
    {
      mylabel.SetMyObject(hellowWorldLabel);
    }
  }
}

Please be aware that you need to wait until the label is fully initiated before exposing its pointer to C/C++, otherwise you may cause the program to crash. To make sure it's fully initiated, call SetMyObject() within Component.onCompleted and not any other places.

Now that the QML label has been exposed to C/C++, we can change any of its properties by calling setProperty() function. For instance, we can set its visibility to true and change its text to Bye bye world!:

/ QVariant automatically detects your data type
myObject->setProperty("visible", QVariant(true));
myObject->setProperty("text", QVariant("Bye bye world!"));

Besides changing the properties, we can also call its functions by calling QMetaObject::invokeMethod():

QVariant returnedValue;
QVariant message = "Hello world!";

QMetaObject::invokeMethod(myObject, "myQMLFunction",
Q_RETURN_ARG(QVariant, returnedValue),
Q_ARG(QVariant, message));

qDebug() << "QML function returned:" << returnedValue.toString();

Or simply, we can call the invokedMethod() function with only two parameters if we do not expect any values to be returned from it:

QMetaObject::invokeMethod(myObject, "myQMLFunction");

How it works...

QML is designed to be easily extensible through C++ code. The classes in the Qt QML module enable QML objects to be loaded and manipulated from C++, and the nature of the QML engine's integration with Qt's meta object system enables C++ functionality to be invoked directly from QML. To provide some C++ data or functionality to QML, it must be made available from a QObject-derived class.

QML object types can be instantiated from C++ and inspected in order to access their properties, invoke their methods, and receive their signal notifications. This is possible due to the fact that all QML object types are implemented using QObject-derived classes, enabling the QML engine to dynamically load and introspect objects through the Qt meta object system.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Learn to make use of Qt5 to design and customize the look-and-feel of your application
  • Improve the visual quality of your application by utilizing the graphic rendering system and animation system provided by Qt5
  • A good balance of visual presentation and its contents will make an application appealing yet functional

Description

With the advancement of computer technology, the software market is exploding with tons of software choices for the user, making their expectations higher in terms of functionality and the look and feel of the application. Therefore, improving the visual quality of your application is vital in order to overcome the market competition and stand out from the crowd. This book will teach you how to develop functional and appealing software using Qt5 through multiple projects that are interesting and fun. This book covers a variety of topics such as look-and-feel customization, GUI animation, graphics rendering, implementing Google Maps, and more. You will learn tons of useful information, and enjoy the process of working on the creative projects provided in this book

Who is this book for?

This book intended for those who want to develop software using Qt5. If you want to improve the visual quality and content presentation of your software application, this book is best suited to you.

What you will learn

  • • Customize the look and feel of your application using the widget editor provided by Qt5
  • • Change the states of the GUI elements to make them appear in a different form
  • • Animating the GUI elements using the built-in animation system provided by Qt5
  • • Draw 3D graphics in your application by implementing OpenGL, an industry-standard graphical library, in your project
  • • Build a mobile app that supports touch events and export it to your device
  • • Parse and extract data from an XML file, then present it on your software's GUI
  • • Access MySQL and SQLite databases to retrieve data and display it on your software's GUI

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 29, 2016
Length: 300 pages
Edition : 1st
Language : English
ISBN-13 : 9781783280285
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jul 29, 2016
Length: 300 pages
Edition : 1st
Language : English
ISBN-13 : 9781783280285
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 115.97
Qt5 C++ GUI Programming Cookbook
€36.99
Mastering Qt 5
€36.99
QT5 Blueprints
€41.99
Total 115.97 Stars icon

Table of Contents

10 Chapters
1. Look and Feel Customization Chevron down icon Chevron up icon
2. States and Animations Chevron down icon Chevron up icon
3. QPainter and 2D Graphics Chevron down icon Chevron up icon
4. OpenGL Implementation Chevron down icon Chevron up icon
5. Building a Touch Screen Application with Qt5 Chevron down icon Chevron up icon
6. XML Parsing Made Easy Chevron down icon Chevron up icon
7. Conversion Library Chevron down icon Chevron up icon
8. Accessing Databases Chevron down icon Chevron up icon
9. Developing a Web Application Using Qt Web Engine Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.7
(17 Ratings)
5 star 41.2%
4 star 17.6%
3 star 17.6%
2 star 17.6%
1 star 5.9%
Filter icon Filter
Top Reviews

Filter reviews by




SY Aug 23, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Essential book to understand C++ GUI programming. Very detailed step by step learning process. I will rate this as MUST-BUY to those who are reading this.
Amazon Verified review Amazon
Robert F. Lebo Jun 26, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
On time. No problems.
Amazon Verified review Amazon
Harterly Boey Aug 24, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Good reference for C++ GUI programming. This would be helpful for programmer to use C++ to create program with attractive UI
Amazon Verified review Amazon
Kirk Nov 17, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Good
Amazon Verified review Amazon
anniw Aug 23, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great guide book! It is easy and straight forward just like a cookbook!
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.

Modal Close icon
Modal Close icon

Follow Lee on X/Twitter - Father, Husband, Serial builder creating AI, crypto, games & web tools. We are friends :) AI Will Come To Life!

Check out: eBank.nz (Art Generator) | Netwrck.com (AI Tools) | Text-Generator.io (AI API) | BitBank.nz (Crypto AI) | ReadingTime (Kids Reading) | RewordGame | BigMultiplayerChess | WebFiddle | How.nz | Helix AI Assistant