Chapter 53 Detailed Explanation of Qt Quick Project

Introduction

Earlier we created a Qt Quick project together and briefly explained the files inside. Although this is just a HelloWorld program, this project is still a bit complicated for students who have no Qt Quick programming experience. In this article, we will start with the simplest QML file, and then gradually enrich the project content to help you learn from shallow to deep, and further understand the composition of the Qt Quick project.

Environment: Windows 7 + Qt 5.5.0 + Qt Creator 3.4.2

Table of contents

  • 1. Create an empty project
  • 2. Add QML file
  • 3. Run the program
  • 4. Extend the QML program
  • 5. Add C++ code
  • 6. Use resource files

text

1. Create an empty project

1. First open Qt Creator, then select the "New File or Project" menu item, select "Empty qmake Project" in the "Other Projects" category on the template selection page, let's create an empty project first, and then gradually add files to it . Click the "choose" button to confirm the selection, as shown in the figure below.

 

2. On the project location page, change the project name to myqml, and then select the creation path. As shown below.

 

3. The following steps can directly use the default settings.

2. Add QML file

1. The created empty project has only one .proproject file, and the content inside is also empty now. Let's leave that alone and add files to the project. Right-click on myqmlthe folder and select "Add New File" from the pop-up menu, as shown in the figure below.

 

2. In the pop-up new file dialog box, select "QML File (Qt Quick 2)" in the Qt category. As shown below. (Explanation: Here you need to add a QML file. The template can choose Qt Quick 1, Qt Quick 2 and QtQuickUI File. Qt Quick 1 will import the QtQuick 1.1 module, and the content inside is from the Qt 4 era; while QtQuick 2 imports It is a QtQuick 2.0 module, which is a new version in Qt 5; after the QtQuick UI file is generated, the designer will be used by default, because we will directly talk about the code in this section and do not involve the content of the designer, so this template is not selected. In fact, which one to use The templates are all the same, because you can directly modify the import module statement in the file, beginners should not be entangled here.)

 

3. Set the name of the file below to main, and keep the default path. The current path is the project source code path. Then click the "Next" button, as shown in the figure below.

 

4. Finally, there is the project management page. You can see that the newly created file is added to myqml.prothe project by default. Just click the "Finish" button to complete the addition and construction of the file, as shown in the figure below.

 

3. Run the program

1. You can see that the added file is main.qml, the suffix .qmlindicates that the file is a QML file, and its content is as follows.

 

import QtQuick 2.0
Rectangle {
    width: 100
    height: 62
}

This is the simplest QML file, it will display a rectangle with a width of 100 pixels and a height of 62 pixels. The statement here importhas been mentioned in the previous section, it will import the corresponding module, for example, the QtQuick 2.0 module is imported here. The following Rectangleis a rectangle object, which is used to define a rectangle item (the item is similar to a window or widget in C++), and the properties of widthand heightare Rectangleused to set rectangle-related parameters.

2. The QML file is different from the C++ file. It does not need to be compiled and can be run directly. In Qt, two tools for running QML files, qmlviewer and qmlscene, are provided. The former is a product of the Qt 4 era and is mainly used to display QML files imported from the QtQuick 1.1 module, while qmlscene is used to display QML imported from QtQuick 2.0 and later. document. Select the "Tools→External→QtQuick→Qt Quick 2Preview" menu item to display the content of the now opened QML document in qmlscene. As shown below.

 

The running effect is shown in the figure below.

 

4. Extend the QML program

1. Add text display

You can see that the current program is a blank window with nothing. Let's extend the program and main.qmlchange the contents of the file as follows:

import QtQuick 2.0
Rectangle {
    width: 100
    height: 62
    Text {
       text: "hello World"
    }
}

An object is added here Text, which is used to display a piece of text, and its textproperties are used to specify the text content to be displayed. Next, press Ctrl+Sthe shortcut key to save the file, and then check the display effect in qmlscene, as shown in the figure below.

 

2. Use anchor layout

We see that the hello world text can be displayed now, but the text is displayed in the upper left corner by default, we hope it can be displayed in the middle of the window, continue to add code below:

Text {
       text: "hello World"
       anchors.centerIn: parent
    }

Here, the concept of anchors is used anchorfor layout. In QML, each item has a set of invisible anchors, respectively at top, bottom, left, right, center, etc., which can define the relative position of the item itself and other items. For example, here centerInrefers to Textthe project in parentthe center of the project, and here parentrefers Textto the parent project Rectangle. anchorGenerally, other items are specified later . idIf it is a parent-child item, it can also be specified as it is now parent.

Next, save the code first (you need to save it for each modification in the future, and you will not be reminded later), and then run it in qmlscene, the effect is shown in the figure below.

 

3. Add mouse interaction.

The previous code has completed a simple Hello World interface. Next, we add code to realize the effect of clicking the interface to exit the program:

import QtQuick 2.0
Rectangle {
    width: 100
    height: 62
    Text {
       text: "hello World"
       anchors.centerIn: parent
    }
    MouseArea {
       anchors.fill: parent
       onClicked: {
           Qt.quit()
       }
    }
}

We Rectangleadded another MouseAreasub-object in , which literally translates to the mouse area, which is an invisible item, that is to say, we cannot see its existence on the window, and mouse interaction can be realized through this object. anchors.fillIt is to fill, here is to cover the entire Rectanglewindow with the mouse area. onClickedIn fact, it is the signal processing function in Qt C++, which is generally called a signal processor, and its syntax is, on<Signal>so here is Clickedthe processing of the click signal. When the mouse is clicked on the window, Qt.quit()the function will be executed. This is a global function. The execution result is Make the program exit.

You can run the program in qmlscene, and then click the mouse on the window to see the running effect.

4. Use components

The file created earlier main.qmlis intended to be the main file and the entry point of the program. But if the current practice is followed, the program will become more and more complicated, and main.qmlthe content will become more and more chaotic. In order to avoid main.qmladding too much code in , we generally put the specific implementation code in a separate file.

Next, first add a new file in the QML directory, as shown in the figure below.

 

The template still selects QML File (QtQuick 2) in the Qt category, and the file name is set to MyHelloWorld, please note that the first letter should be capitalized, as shown in the figure below.

 

After the addition is complete, main.qmlcopy and paste all the content in the file, as shown in the figure below.

Next, we modify main.qmlthe content of the file as follows:

import QtQuick 2.0
Item {
    MyHelloWorld {
       anchors.fill: parent
    }
}

A QML snippet like this in a separate document defines an object type, also called a component, whose file name must start with a capital letter. For example, a type is created here MyHelloWorld, and the custom object type in the same directory can be directly used in other QML files, so we main.qmldirectly create MyHelloWorldthe object in . Here the root object is used Item. In Qt Quick, all visual items are inherited from Item, because main.qmlwe only need to create a window in Qt Quick and do not need to set the content, so it can be used generally Item. Of course, if you want to use it, Rectangleit is also possible. .

In addition to simplifying the code, using components can be reused. If the same component or function needs to be used multiple times in a code, it is unnecessary to write the same code multiple times by using them as components. You can save the file and run the program in qmlscene to view the effect.

5. idAttributes and attribute aliases

The attribute mentioned earlier idis actually the name of an object to uniquely identify an object, which can be referenced in other objects id. Let's MyHelloWorld.qmlchange the contents of the file as follows:

import QtQuick 2.0
Rectangle {
    width: 100
    height: 62
    property alias mArea: mouseArea
    Text {
       text: "hello World"
       anchors.centerIn: parent
    }
    MouseArea {
       id: mouseArea
       anchors.fill: parent
    }
}

Here we first changed MouseAreathe object, set it idto mouseArea, so that the object can be accessed Rectangleby passing in . In order to be able to access the sub-object inside the file, we need to customize the property in the file, and the property needs to be the property alias of the sub-object. For example, here we declare a property , indicating that it is an alias, so that it can be passed outside the file. It's time to manipulate the object.mouseAreaMouseAreaMyHelloWorld.qmlRectangleRectanglemAreaaliasmAreamouseAreaMyHelloWorld.qmlmAreaMouseArea

Let's modify the file below main.qml:

import QtQuick 2.0
Item {
    MyHelloWorld {
       anchors.fill: parent

       mArea.onClicked: {
           Qt.quit()
       }
    }
}

Here the handler is called directly MyHelloWorldin the object . Now save the file and run the program to see the effect.mAreaonClickedqmlscene

So far we have basically restored qmlthe content of the files in the Qt Quick application created in the previous article, starting from the simplest program and gradually enriching the code. Now everyone should have a certain understanding of QML programs. Next, we continue to enrich the program to make it a project that can be compiled and run.

5. Add C++ code

1. Add main.cppfiles. First, myqmlright-click on the directory and select "Add New File", as shown in the figure below. In the pop-up dialog box, select "C++Source File" in the C++ category.

2. Set the file name to main, as shown in the figure below.

3. After the addition is complete, main.cppmodify the content of the file to:

#include <QGuiApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("../myqml/main.qml")));
    return app.exec();
}

This is mainly an ordinary Qt C++ main()function, the key is that an object is created QQmlApplicationEngineto load a QML file, which is a fixed usage. Because the local directory for compiling and running the program is an automatically generated directory, it myqmlis at the same level as the source code directory, so main.qmla relative path needs to be specified for loading files.

2. Change the project file. Now that myqml.prosome code has been automatically added to the file, we just need to add a line of code at the end:

QT += quick qml

This indicates that QtQuickthe and QtQmlmodules are used in the project.

3. Modify main.qmlthe file. To load a QML file in a C++ program QQmlApplicationEngine, the top-level window is required to use Windowthe project, that is, main.qmlthe root object in it uses Windowthe object instead of Itemthe object, because Windowit is not displayed by default, so there is also a setting visiblefor its property true, this is also a fixed usage, everyone in the future Just follow along. The modified main.qmlfile is as follows:

import QtQuick 2.0
import QtQuick.Window 2.0
Window {
    visible: true
    MyHelloWorld {
       anchors.fill: parent
       mArea.onClicked: {
           Qt.quit()
       }
    }
}

2.0 is also imported here QtQuick.Windowbecause the module contains Windowtypes. Now we can press Ctrl+Rthe shortcut key to compile and run the program, the effect is shown in the figure below.

6. Use resource files

Because QML files are ordinary text files, but these files need to be used to create interfaces when the program is running, it is not safe to put them directly outside the program, so our approach is to put QML files in resource files.

1. Add resource files. Continue to right-click on the myqml directory, select Add New File, and select "Qt Resource File" in the Qt category as a template, as shown in the figure below.

Then set the file name as "qml" as shown in the image below.

2. After the file is created, it will be opened automatically. Here we first click the "Add" button and select "Add Prefix", as shown in the figure below.

Here the prefix is ​​set to /, as shown in the figure below. (In fact, you can use any prefix. For simplicity, only slashes are kept here.)

3. Click the "Add" button again, this time select "Add File", as shown in the figure below.

In the pop-up dialog box, select all the QML files in the source code directory, as shown in the figure below. Ctrl+SClick Save Resource File when finished .

4. After adding, you can see the resource file in the file list on the left. As shown below.

5. Because the QML file has been added to the resource file, the previous QML file in the project is no longer needed. Double-click myqml.prothe file to open it, and put the:

DISTFILES += \
    main.qml \
    MyHelloWorld.qml

Delete the code and click Ctrl+SSave Project File. At this time, the list of files in the project is shown in the figure below.

6. Finally modify main.cppthe file. Because the resource file is now used, to change main.cppthe path to the QML file in the file, modify it to:

engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

At this point, the entire project has been modified, and you can run the program to see the effect. This project will serve as our template, and the following chapters will be modified on the basis of this project to explain, and the process of creating the project will not be repeated.

summary

In this article, we will disassemble and analyze the Qt Quick project explained in the previous article. From the perspective of beginners, starting from the simplest few lines of code, enriching the program a little bit, analyzing and explaining step by step, and finally restoring the entire program . The content of this section allows you to fundamentally grasp the construction of Qt Quick programs, and also provides a method of learning, a method of analyzing large and complex programs, which is the so-called profiling method. I hope you will go through it carefully for future Learn to lay a good foundation.

Guess you like

Origin blog.csdn.net/qq_21137441/article/details/128301882