Qt 6 allows us to easily design our program’s user interface through a method 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 Sheet.
In this chapter, we’re going to cover the following recipes:
The technical requirements for this chapter include having Qt 6.1.1 MinGW 64-bit and Qt Creator 12.0.2. The code that’s used in this chapter can be downloaded from this book’s GitHub repository: https://github.com/PacktPublishing/QT6-C-GUI-Programming-Cookbook---Third-Edition-/tree/main/Chapter01.
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), something that’s used by web designers to decorate their websites.
Let’s get started by learning how to create a new project and get ourselves familiar with Qt Designer:
mainwindow.ui
, because we are about to start designing the program’s UI.mainwindow.ui
file; you will see an entirely different interface appear out of nowhere. Qt Creator helped you 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.mainwindow.ui
file. This is 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 (the green arrow button) at the bottom of the mode selector panel; you will see an empty window pop up once the compilation is complete.color: rgb(255, 0, 0);
Let’s take a bit of time to get familiar with Qt Designer’s interface before we start learning how to design our own UI:
Figure 1.1 – Overview of Qt Designer’s interface
The explanation for the preceding screenshot is as follows:
.ui
file. All the widgets are arranged according to their parent-child relationship in the hierarchy. You can select a widget from the Object Inspector area to display its properties in the Property Editor area.In this recipe, we discussed how to apply style sheets to Qt widgets through C++ coding. Although that method works well, most of the time, the person who is in charge of designing the program’s UI is not the programmer, but rather a UI designer who specializes in designing user-friendly UI. In this case, it’s better to let the UI designer design the program’s layout and style sheet with a different tool and not mess around with the code. Qt provides an all-in-one editor called Qt Creator.
Qt Creator consists of several different tools, such as a script editor, compiler, debugger, profiler, and UI editor. The UI editor, which is also called Qt Designer, is the perfect tool for designers to design their program’s UI without writing any code. This is because Qt Designer adopted the what you see is what you get approach by providing an accurate visual representation of the final result, which means whatever you design with Qt Designer will turn out the same visually when the program is compiled and run.
The similarities between Qt Style Sheets and CSS are as follows:
h1 { color: red; background-color: white;}
QLineEdit { color: red; background-color: white;}
As you can see, both of them contain a selector and a declaration block. Each declaration contains a property and a value, separated by a colon. In Qt, a style sheet can be applied to a single widget by calling the QObject::setStyleSheet()
function in C++ code.
Consider the following, for example:
myPushButton->setStyleSheet("color : blue");
The preceding code will turn the text of a button with the myPushButton
variable name to blue. You can achieve the same result by writing the declaration in the style sheet property field in Qt Designer. We will discuss Qt Designer more in the Customizing basic style sheets recipe.
Qt Style Sheets also supports all the different types of selectors defined in the CSS2 standard, including the universal selector, type selector, class selector, and ID selector, which allows us to apply styling to a very specific individual widget or group of widgets. For instance, if we want to change the background color of a specific line-edit widget with the usernameEdit
object name, we can do this by using an ID selector to refer to it:
QLineEdit#usernameEdit { background-color: blue }
Note
To learn about all the selectors available in CSS2 (which are also supported by Qt Style Sheets), please refer to this document: http://www.w3.org/TR/REC-CSS2/selector.html.
In the previous recipe, 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 changing 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; instead, 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 the long run.
In the following example, we will format different types of widgets on the canvas and add some code to the style sheet to change its appearance:
PushButton
by selecting it and clicking the small arrow button beside the styleSheet property. This button will revert the property to its default value, which in this case is the empty style sheet.Figure 1.2 – Dragging and dropping some widgets onto the form editor
border: 2px solid gray; border-radius: 10px; padding: 0 8px; background: yellow;
QPushButton { border: 2px solid gray; border-radius: 10px; padding: 0 8px; background: yellow; }
Figure 1.3 – Changing the push buttons to yellow
QPushButton
class. We can also apply the style to just one of the push buttons by mentioning its name in the style sheet, as shown in the following code:QPushButton#pushButton_3 { border: 2px solid gray; border-radius: 10px; padding: 0 8px; background: yellow; }
QPushButton { color: red; border: 0px; padding: 0 8px; background: white; } QPushButton#pushButton_2 { border: 1px solid red; border-radius: 10px; }
pushButton_2
button. We keep the style sheet of pushButton_3
as-is. Now, the buttons will look like this:Figure 1.4 – Applying a different style to each button
QPushButton
type to a white rectangular button with no border and red text. The second set of style sheets only changes 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 sheets, hence it will return to the style described in the first set of style sheets since it applies to all the QPushButton
widgets. 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 sheets.* { 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; }
rgb
function (rgb(255, 255, 255)
) or hex code (#ffffff
) to describe the color value.Figure 1.5 – Applying a gradient background to all the other widgets
If you are ever involved in web development using HTML and CSS, Qt’s style sheets work the same way as CSS. Style sheets provide the definitions to describe 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. If you specify the name of the widget to the style sheet, it will change the style of the particular PushButton
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 from either the form editor or the Object Inspector area and change the objectName property in the property window. If you 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.
Next, we will learn how to put all the knowledge we learned in the previous recipe together and create a fake graphical login screen for an imaginary operating system. Style sheets are not the only thing you need to master to design a good UI. You will also need to learn how to arrange the widgets neatly using the layout system in Qt Designer.
Let’s get started by following these steps:
Figure 1.6 – A simple drawing depicting the login screen
400
and 300
to 800
and 600
, respectively – we’ll need a bigger space in which to place all the widgets.currentDateTime
and change its text property to the current date and time for display purposes – for example, Wednesday, 25-10-2023
3:14 PM
.PushButton
under the Buttons category to the form editor. Repeat this process once more because we have two buttons on the top panel. Rename the two buttons restartButton
and shutdownButton
.55 x 55
. Set the text property of the buttons to empty, as we will be using icons instead of text. We will learn how to place an icon in the button widgets in the Using resources in style sheets recipe.Figure 1.7 – Pushing apart the text and buttons using a horizontal spacer
Next, we will be adding the logo. Follow these steps:
logo
. We will learn more about how to insert an image into the label to use it as a logo in the Using resources in style sheets recipe. For now, just empty out the text property and set both its Horizontal Policy and Vertical Policy properties to Fixed. Set the minimumSize property to 150
x 150
.border: 1px solid;
Your UI should look similar to this:
Figure 1.8 – Putting the placeholder logo in the middle
Now, let’s create the login form:
100
) so that you can add a widget to it more easily.20
) so that we can place widgets in it.QWidget
object, it will automatically inherit all the properties from the widget class, which means we can now adjust its size to suit our needs.QWidget
object, which we just converted from the layout, loginForm
and change both its Horizontal Policy and Vertical Policy properties to Fixed. Set the minimumSize parameter to 350
x 200
.loginForm
widget inside Horizontal Layout, we can set its layoutTopMargin property back to zero.loginForm
widget to make it visible temporarily. However, this time, we need to add an ID selector in front so that it will only apply the style to loginForm
and not its children widgets:#loginForm { border: 1px solid; }
Your UI should look something like this:
Figure 1.9 – Constructing the frame for the login form
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:
Username:
and the one beneath to Password:
. Rename the two line edits to username
and password
, respectively.Login
. Rename it loginButton
.Login
button to distance them slightly. After the Vertical Spacer widget has been placed, change its sizeType property to Fixed and change its Height property to 5
.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.Username
, Password
, and loginButton
widgets to 25
so that they don’t look so cramped.Your UI should look something like this:
Figure 1.10 – Adding widgets to the login form
Note
Alternatively, you can use a grid layout for the Username and Password fields to keep their sizes uniform.
We’re not done yet! As you can see, the login form and the logo are both sticking to the top of the main window due to the Vertical Spacer widget beneath them. The logo and the login form should be placed at the center of the main window instead of the top. To fix this problem, follow these steps:
10
.topPanel
. The layout must be converted into QWidget because we cannot apply style sheets to a layout. This is because a layout doesn’t have any properties other than margins.Figure 1.11 – We’re done with the layout – for now
#centralWidget { background: rgba(32, 80, 96, 100); }
#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)); }
border-radius
property:#loginForm { background: rgba(0, 0, 0, 80); border-radius: 8px; }
QLabel { color: white; } QLineEdit { border-radius: 3px; }
QPushButton { color: white; background-color: #27a9e3; border-width: 0px; border-radius: 3px; }
hover
keyword:QPushButton:hover { background-color: #66c011; }
Figure 1.12 – Applying colors and styles to the widgets
This example focused more on the layout system of Qt. Qt’s layout system allows our application GUI to automatically arrange itself within the given space by arranging the children objects of each widget. The spacer items that we used in this recipe help push the widgets contained in a layout outward to create spacing along the width of the spacer item.
To locate a widget in the middle of the layout, we must put two spacer items into the layout: one on the left-hand side of the widget and one on the right-hand side of the widget. The widget will then be pushed to the middle of the layout by the two spacers.
Qt provides us with a platform-independent resource system that allows us to store any type of file 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.
The resource system is really useful for embedding resource files (such as icons and translation files) into the executable so that it can be accessed by the application at any time. To achieve this, we must tell Qt which files we want to add to its resource system in the .qrc
file; Qt will handle the rest during the build process.
To add a new .qrc
file to our project, go to File | New File. 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 now be created and automatically opened by Qt Creator. You don’t have to edit the .qrc
file directly in XML format as Qt Creator provides you with the user interface to manage your resources.
To add images and icons to your project, 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 the Add Prefix button. The prefix is used to categorize your resources so that they can be better managed when you have a ton of resources in your project:
/icons
./images
./icon
prefix and click Add, followed by Add Files./images
prefix and click the Add button, followed by the Add Files button. The file-selection window will pop up again; this time, we will select the background image./images
prefix. Don’t forget to save once you’re done by pressing Ctrl + S. Your .qrc
file should now look like this:Figure 1.13 – Showing the structure of the resource file
mainwindow.ui
file; let’s make use of the resources we have just added to our project. Select the restart button located on the top panel. Scroll down the Property Editor area until you see the icon property. Click the little button with a drop-down arrow icon and click Choose Resources from its menu.16 x 16
. Change the iconSize property to 50 x 50
; you will see that the icon appears bigger. Repeat the preceding steps for the shutdown button, except this time, choose the shutdown icon instead.Figure 1.14 – Applying icons to the push buttons
border-image: url(:/images/logo.png);
Figure 1.15 – The logo is now appearing at the top of the login form
border-image
property in a style sheet. Right-click the main window and select Change styleSheet... to open the Edit Style Sheet window. We will add a new line under the style sheet of the centralWidget widget:#centralWidget { background: rgba(32, 80, 96, 100); border-image: url(:/images/login_bg.png); }
Figure 1.16 – The final result looks neat
The resource system in Qt stores binary files, such as images and translation files, 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 in 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 that contains them. The listed resource files must be located in the same directory as the .qrc
file, or one of its subdirectories.
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 for our widgets and use them to switch between different styles.
Follow these steps to customize widget properties and sub-controls:
Figure 1.17 – Basic user interface with three tabs and buttons
QPushButton { color: white; background-color: #27a9e3; border-width: 0px; border-radius: 3px; }
QPushButton:hover { color: white; background-color: #66c011; border-width: 0px; border-radius: 3px; }
hover
separated from the QPushButton
class by a colon. Every widget has a set of generic pseudo-states, such as active, disabled, and enabled, and also a set of pseudo-states that apply 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; }
QPushButton[pagematches=true] { color: white; background-color: red; border-width: 0px; border-radius: 3px; }
pagematches
property returns true. This property does not exist in the QPushButton
class. However, we can add it to our buttons using QObject::setProperty()
: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.
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);
mainwindow.cpp
; 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 (0 == index) 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); }
pagematches
properties of all three buttons to false when Tab Widget switches its current page. Be sure to reset everything before we decide which button should change to red.index
variable supplied by the event signal; this 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.polish()
. You may also want to add the following header to mainwindow.h
:#include <QStyle>
Figure 1.18 – The final result looks like this
Qt provides users the freedom to add 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, whereas 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 Tab Widget is currently showing, 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 gives us a method to add our own properties to the widgets, which uses 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. Often, a widget is not just a single object, but a combination of more than one object or control, used to form a more complex widget. These 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 sub-control using a style sheet if we want 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 to a spin box, I can write my style sheet as follows:
QSpinBox::down-button { image: url(:/images/spindown.png); subcontrol-origin: padding; subcontrol-position: right bottom; }
This 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 subcontrols in Qt: http://doc.qt.io/qt-6/stylesheet-reference.html.
Qt Meta Language or Qt Modeling Language (QML) is a JavaScript-inspired user interface markup language that’s used by Qt to design 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 provided in this recipe.
Follow these steps to learn about styling in QML:
Figure 1.19 – Creating a new QML project in Qt Design Studio
App.qml
file inside the project resource. This .qml
file is the UI description file that’s written using the QML markup language. If you double-click the main.qml
file, Qt Creator will open the script editor and you will see something like this:import QtQuick 6.2 import QtQuick.Window 6.2 import MyProject Window { width: mainScreen.width height: mainScreen.height visible: true title: "MyProject" Screen01 { id: mainScreen } }
main.cpp
file located in the scr
folder in your project, you will see the following line of code:QQmlApplicationEngine engine; const QUrl url(u"qrc:Main/main.qml"_qs);
main.qml
file when the program starts. If you want to load the other .qml
file, you know where to look for the code. The src
folder is hidden from your Qt Design Studio project; you can look for it inside your project directory.Figure 1.20 – Your first Qt Quick program
Figure 1.21 - Creating a new Qt Quick UI file
Figure 1.22 – Giving your Qt Quick component a meaningful name
Main.ui.qml
has been added to your project resources. Try to open the Main.ui.qml
file by double-clicking on it, if it hasn’t been automatically opened by Qt Design Studio upon creation. You will see a completely different UI editor compared to what we had for the C++ project in the previous recipes.App.qml
and replace Screen01 with Main, like so:Main { id: mainScreen }
App.qml
is loaded by the QML engine, it will also import Main.ui.qml
into the UI since Main
is now being called in the App.qml
file. Qt will check whether Main
is a valid UI by searching for its .qml
file based on the naming convention. This concept is similar to the C++ project we completed in all our previous recipes; the App.qml
file acts like the main.cpp
file and Main.ui.qml
acts like the MainWindow
class. You can also create other UI templates and use them in App.qml
. Hopefully, this comparison will make it easier to understand how QML works.Main.ui.qml
. You should see only one item listed in the Navigator window: Item. This is the base layout of the window, which shouldn’t be deleted. It is similar to centralWidget, which we used in the previous recipe.Figure 1.23 – Dragging and dropping a mouse area and text items onto the canvas
Figure 1.24 – Rearranging the parent-child relationship between items
Note
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.
800 x 600
as we’re going to need a bigger space for the widgets.Figure 1.25 – Selecting the fill anchor button to make the item follow the size of its parent object
#805bcce9
and the second color to #80000000
. This will create a half-transparent panel with a blue gradient.Wednesday, 25-10-2023 3:14 PM
) for display purposes. Then, set the text color to white.50 x 50
. Then, make it a child of the top panel by dragging it on top of the top panel in the Navigator window.#27a9e3
) and set its radius to 2
to make its corners slightly rounded. Enable the top anchor and right anchor to make it stick to the top-right corner of the window. Set the top anchor’s margin to 8
and the right anchor’s margin to 10
to create some space.Figure 1.26 – Be cautious about the parent-child relationship between items
Figure 1.27 – Completing the top banner design
360 x 200
and set its radius to 15
.#80000000
; this will change it to black with 50% transparency.100
so that it moves slightly lower to the bottom. This will ensure we have the space to place the logo. The following screenshot illustrates the settings for Anchors:Figure 1.28 – Setting the alignment and margin
Username:
and Password:
. 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.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.#27a9e3
) and enable the fill anchor so that it fits nicely with the mouse area.Login
. Finally, enable the horizontal center anchor and the vertical center anchor so that they align with the center of the button.Figure 1.29 – Final design of the login form
512
x 200
.Figure 1.30 – The final result
The Qt Quick editor uses a very different approach for placing widgets in the application compared to the form editor. The user can decide which method is best suited to their purposes. The following screenshot shows what the Qt Quick Designer looks like:
Figure 1.31 – Overview of Qt Design Studio’s user interface
Let’s look at the various elements of the editor’s UI:
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, or changing its size. Qt’s QML engine allows you to register your QML objects to C++ types, which automatically exposes all its properties.
We want to create a label in QML and change its text occasionally. To expose the label object to C++, we can do the following:
MyLabel
that extends from the QObject
class in 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); }
mylabel.cpp
source file, define a function called SetMyObject()
to save the object pointer. This function will later be called in QML in mylabel.cpp
:void MyLabel::SetMyObject(QObject* obj) { // Set the object pointer myObject = obj; }
main.cpp
, include the MyLabel
header and register it to the QML engine using the qmlRegisterType()
function:include "mylabel.h" int main(int argc, char *argv[]) { // Register your class to QML qmlRegisterType<MyLabel>("MyLabelLib", 1, 0, "MyLabel"); }
qmlRegisterType()
. Besides declaring your class name (MyLabel
), you also need to declare your library name (MyLabelLib
) and its version (1.0
). This will be used to import your class into QML.import MyLabelLib 1.0
in our QML file. Notice that the library name and its version number have to match the one you declared in main.cpp
; otherwise, it will throw 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 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); } } }
SetMyObject()
function within Component.onCompleted
and not in any other functions or event callbacks. Now that the QML label has been exposed to C/C++, we can change any of its properties by calling the 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!"));
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();
invokedMethod()
function with only two parameters if we do not expect any values to be returned from it:QMetaObject::invokeMethod(myObject, "myQMLFunction");
QML is designed in such a way that it can be expanded through C++ code. The classes in the Qt QML module permit QML objects to be used and operate from C++, and the capability of the QML engine united with Qt’s meta-object system allows C++ functionality to be called directly from QML. To add some C++ data or usage to QML, it should come forward from a QObject-derived class. QML object types could be instituted from C++ and supervised to access their properties, appeal their methods, and get their signal alerts. This is possible because all QML object types are executed using QObject-derived classes, allowing the QML engine to forcibly load and inspect objects through the Qt meta-object system.
Qt 6 comes with two different types of GUI kits – Qt Widgets and Qt Quick. Both have their strengths and advantages over the other, giving programmers the ability and freedom to design their application’s interface without having to worry about feature constraints and performance issues.
Qt 6 allows you to pick the best method and programming language that suits your working style and requirements for your project. By going through this chapter, you will be able to create a good-looking and functional cross-platform application using Qt 6 in no time.
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:
If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:
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.
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.