C++/qt: пора валить?

Creating Qt Quick Based Python Applications

The Qt for Python — Qt Quick Application — Empty wizard enables you to create a Python project that contains a main QML file. Specify the minimum PySide version to run the application.

The wizard adds the following imports to the source file to provide access to QGuiApplication and QQmlApplicationEngine:

import sys
import os

from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine

The wizard also adds a main function, where it creates a QGuiApplication instance and passes system arguments to the QGuiApplication object:

if __name__ == "__main__":
    app = QGuiApplication(sys.argv)
...

The following lines in the main class create a QQmlApplicationEngine instance and load the generated QML file to the engine object:

engine = QQmlApplicationEngine()
engine.load(os.path.join(os.path.dirname(__file__), "main.qml"))

Finally, the wizard adds code that checks whether the file was successfully loaded. If loading the file fails, the application exits with an error code. If loading succeeds, the wizard calls the method to enter the Qt main loop and start executing the Qt code:

if not engine.rootObjects():
    sys.exit(-1)
sys.exit(app.exec_())

Open the .qml file in the Design mode to design a Qt Quick UI in Qt Quick Designer.

Questions about New Features

Will a requested feature be implemented?

If it is a scheduled feature, you can see this in the task tracker. If a feature already has been implemented, it is mentioned in the changes file for the upcoming release.

Why does Qt Creator not use tabs for editors?

This question comes up from time to time, so we have considered it carefully. Here are our main reasons for not using tabs:

  • Tabs do not scale. They work fine if you have 5 to 6 editors open, they become cumbersome with 10, and if you need more horizontal space than the tab bar, the interface does not work at all.
  • Tabs do not adapt to your working set.
  • The common solution is to give the user the ability to reorder tabs. Now user has to manage tabs instead of writing code.
  • Tabs force you to limit the amount of open editors, because otherwise you get confused.

Consider the following use case: Developers want to switch editors.

In fact, developers do not want to switch editors, but might have to do so to accomplish their tasks. We need to figure out what the tasks are to provide developers with better ways to navigate while performing the tasks.

One common factor in many use cases is switching editors while working on a set of open files. While working on files A and B, users sometimes need to look at file C. They can press Ctrl+Tab to move between the files and have the files open in the correct editor according to file type. The list is sorted by last used.

Typically, users also work on multiple classes or functions that are related, even though they are defined or declared in different files. Qt Creator provides two shortcuts for that: F2 to follow the symbol under cursor and Ctrl+Shift+U to find references to it.

In addition, developers can:

  • Press F4 to switch between header and source.
  • Press Alt+Left to move backwards in the navigation history.
  • Use the locator (Ctrl+K) to simply tell Qt Creator where to go.

The locator can be used to open files, but opening files is also just a step on the way to accomplish a task. For example, consider the following use case: Fix AFunction in SomeClass which comes from someclass.cpp/someclass.h.

With a tabbed user interface, developers would search for someclass.cpp in the tab bar, and then search for , only to find out that the function is not located in that file. They would then search for someclass.h in the tab bar, find our that the function is inline, fix the problem, and forget where they came from.

With Qt Creator, developers can type to find the function. Typically, they only need to type 3 to 4 characters of the function name. They can then fix the problem and press Alt+Back to go back to where they were.

Other locator filters include for classes, for all symbols, and (thanks to a community contribution) for symbols in the current file.

Установка Qt Creator в Linux

На этих уроках используется операционная система Linux (Debian 9.x 64-bit), поэтому мы скачиваем , но вы также можете использовать соответствующие файлы Qt для Windows или macOS:

После окончания загрузки переходим в папку с необходимым нам файлом, нажимаем на него правой кнопкой мыши и выбираем . На вкладке видим , , , а также наименование родительской папки:

Переходим на вкладку и ставим галочку возле пункта :

Закрываем и запускаем программу.

Шаг №2: На следующем этапе установщик сообщает, что нам предоставлена версия с открытым исходным кодом Qt 5.13.0. Дальнейшая установка Qt предполагает регистрацию в Qt и создание Qt Account, который предоставляет доступ ко всем возможностям Qt. Кроме того, данное действие необходимо для проверки лицензии (коммерческая/некоммерческая). Если у вас уже есть учетная запись в Qt Account, то используйте кнопку .

Если учетной записи в Qt Account у вас еще нет, то её можно создать сейчас: для этого перейдите по соответствующей ссылке в установщике, и вы будете перенаправлены на сайт qt.io в соответствующий раздел, или просто используйте кнопку — вы сможете это сделать на следующем шаге:

Шаг №3: Здесь необходимо ввести логин и пароль от Qt Account или создать Qt Account, если его у вас еще нет. Кнопка переводит нас на следующий этап:

 Добро пожаловать в настройки Qt 5.13.0! Для перехода к следующему шагу нажимаем :

Шаг №4: Выбираем каталог для установки Qt 5.13.0

Обратите внимание, адрес каталога указывается латинскими буквами (без кириллицы) и без пробелов! После того, как выбрали каталог, нажимаем :

Шаг №5: Выбираем компоненты, которые хотим установить. Если на данном этапе у вас нет уверенности в выборе конкретных компонентов, то добавление и удаление можно будет сделать позже, после установки программы:

Шаг №6: Принимаем лицензионное соглашение:

И нажимаем на кнопку :

Для завершения установки нажимаем . После завершения установки Qt Creator запустится самостоятельно (для этого необходимо поставить галочку возле пункта ):

Вот примерно следующее вы должны увидеть при запуске Qt Creator:

Поздравляем! Qt Creator установлен.

Настройка Qt Creator

После окончания установки перезагрузите компьютер и запустите Qt Creator. Перейдите в меню «Инструменты» -> «Параметры».

Здесь следует рассмотреть несколько вкладок.

1. Среда — это настройка внешнего вида самой IDE, а также изменение сочетаний клавиш и управление внешними утилитами.

2. Текстовый редактор — здесь идет настройка внешнего вида, шрифтов и расцветки редактора.

3. C++ — подсветка синтаксиса, работа с расширениями файлов и UI (т. е. формами).

4. Android — здесь собраны пути к необходимым инструментам, а также в этом меню настраиваются подключаемые или виртуальные устройства.

The Windows Deployment Tool

The Windows deployment tool is designed to automate the process of creating a deployable folder containing the -related dependencies (libraries, QML imports, plugins, and translations) required to run the application from that folder. It creates a sandbox for Universal Windows Platform (UWP) or an installation tree for Windows desktop applications, which can be easily bundled into an installation package.

The tool can be found in . It needs to be run within the build environment in order to function correctly. When using Qt Installer, the script should be used to set it up.

takes an file or a directory that contains an file as an argument, and scans the executable for dependencies. If a directory is passed with the argument, uses the tool to scan QML files inside the directory for QML import dependencies. Identified dependencies are then copied to the executable’s directory.

In case Qt was built with the configure switch turned off, replaces the hardcoded local paths in Qt5Core.dll by relative ones.

For Windows desktop applications, the required runtime files for the compiler are also copied to the deployable folder by default (unless the option is specified). In the case of release builds using Microsoft Visual C++, these consist of the Visual C++ Redistributable Packages, which are intended for recursive installation by the application’s installer on the target machine. Otherwise, the shared libraries of the compiler runtime are used.

The application may require additional 3rd-party libraries (for example, database libraries), which are not taken into account by windeployqt.

Additional arguments are described in the tools’ help output:

Usage: windeployqt  
Qt Deploy Tool 5.14.1

The simplest way to use windeployqt is to add the bin directory of your Qt
installation (e.g. <QT_DIR\bin>) to the PATH variable and then run:
  windeployqt <path-to-app-binary>
If ICU, ANGLE, etc. are not in the bin directory, they need to be in the PATH
variable. If your application uses Qt Quick, run:
  windeployqt --qmldir <path-to-app-qml-files> <path-to-app-binary>

Options:
  -?, -h, --help            Displays help on commandline options.
  --help-all                Displays help including Qt specific options.
  -v, --version             Displays version information.
  --dir <directory>         Use directory instead of binary directory.
  --libdir <path>           Copy libraries to path.
  --plugindir <path>        Copy plugins to path.
  --debug                   Assume debug binaries.
  --release                 Assume release binaries.
  --pdb                     Deploy .pdb files (MSVC).
  --force                   Force updating files.
  --dry-run                 Simulation mode. Behave normally, but do not
                            copy/update any files.
  --no-patchqt              Do not patch the Qt5Core library.
  --no-plugins              Skip plugin deployment.
  --no-libraries            Skip library deployment.
  --qmldir <directory>      Scan for QML-imports starting from directory.
  --qmlimport <directory>   Add the given path to the QML module search
                            locations.
  --no-quick-import         Skip deployment of Qt Quick imports.
  --no-translations         Skip deployment of translations.
  --no-system-d3d-compiler  Skip deployment of the system D3D compiler.
  --compiler-runtime        Deploy compiler runtime (Desktop only).
  --no-virtualkeyboard      Disable deployment of the Virtual Keyboard.
  --no-compiler-runtime     Do not deploy compiler runtime (Desktop only).
  --webkit2                 Deployment of WebKit2 (web process).
  --no-webkit2              Skip deployment of WebKit2.
  --json                    Print to stdout in JSON format.
  --angle                   Force deployment of ANGLE.
  --no-angle                Disable deployment of ANGLE.
  --no-opengl-sw            Do not deploy the software rasterizer library.
  --list <option>           Print only the names of the files copied.
                            Available options:
                             source:   absolute path of the source files
                             target:   absolute path of the target files
                             relative: paths of the target files, relative
                                       to the target directory
                             mapping:  outputs the source and the relative
                                       target, suitable for use within an
                                       Appx mapping file
  --verbose <level>         Verbose level (0-2).

Qt libraries can be added by passing their name (-xml) or removed by passing
the name prepended by --no- (--no-xml). Available libraries:
bluetooth concurrent core declarative designer designercomponents enginio
gamepad gui qthelp multimedia multimediawidgets multimediaquick network nfc
opengl positioning printsupport qml qmltooling quick quickparticles quickwidgets
script scripttools sensors serialport sql svg test webkit webkitwidgets
websockets widgets winextras xml xmlpatterns webenginecore webengine
webenginewidgets 3dcore 3drenderer 3dquick 3dquickrenderer 3dinput 3danimation
3dextras geoservices webchannel texttospeech serialbus webview

Arguments:
                     Binaries or directory containing the binary.

Filling in the Missing Pieces

Begin by designing the user interface and then move on to filling in the missing code. Finally, add the find functionality.

Designing the User Interface

  1. In the Editor mode, double-click the textfinder.ui file in the Projects view to launch the integrated Qt Designer.
  2. Drag and drop the following widgets to the form:
    • Label (QLabel)
    • Line Edit (QLineEdit)
    • Push Button (QPushButton)

    Note: To easily locate the widgets, use the search box at the top of the Sidebar. For example, to find the Label widget, start typing the word label.

  3. Double-click the Label widget and enter the text Keyword.
  4. Double-click the Push Button widget and enter the text Find.
  5. In the Properties view, change the objectName to findButton.
  6. Press Ctrl+A (or Cmd+A) to select the widgets and select Lay out Horizontally (or press Ctrl+H on Linux or Windows or Ctrl+Shift+H on macOS) to apply a horizontal layout (QHBoxLayout).
  7. Drag and drop a Text Edit widget (QTextEdit) to the form.
  8. Select the screen area, and then select Lay out Vertically (or press Ctrl+L) to apply a vertical layout (QVBoxLayout).

    Applying the horizontal and vertical layouts ensures that the application UI scales to different screen sizes.

  9. To call a find function when users select the Find button, you use the Qt signals and slots mechanism. A signal is emitted when a particular event occurs and a slot is a function that is called in response to a particular signal. Qt widgets have predefined signals and slots that you can use directly from Qt Designer. To add a slot for the find function:
    • Right-click the Find button to open a context-menu.
    • Select Go to Slot > clicked(), and then select OK.

      A private slot, , is added to the header file, textfinder.h and a private function, , is added to the source file, textfinder.cpp.

  10. Press Ctrl+S (or Cmd+S) to save your changes.

For more information about designing forms with Qt Designer, see the Qt Designer Manual.

Completing the Header File

The textfinder.h file already has the necessary #includes, a constructor, a destructor, and the object. You need to add a private function, , to read and display the contents of the input text file in the QTextEdit.

  1. In the Projects view in the Edit view, double-click the file to open it for editing.
  2. Add a private function to the section, after the pointer, as illustrated by the following code snippet:
    private slots:
        void on_findButton_clicked();
    
    private:
        Ui::TextFinder *ui;
        void loadTextFile();

Completing the Source File

Now that the header file is complete, move on to the source file, textfinder.cpp.

  1. In the Projects view in the Edit view, double-click the textfinder.cpp file to open it for editing.
  2. Add code to load a text file using QFile, read it with QTextStream, and then display it on with (). This is illustrated by the following code snippet:
    void TextFinder::loadTextFile()
    {
        QFile inputFile(":/input.txt");
        inputFile.open(QIODevice::ReadOnly);
    
        QTextStream in(&inputFile);
        QString line = in.readAll();
        inputFile.close();
    
        ui->textEdit->setPlainText(line);
        QTextCursor cursor = ui->textEdit->textCursor();
        cursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor, 1);
    }
  3. To use QFile and QTextStream, add the following #includes to textfinder.cpp:
    #include <QFile>
    #include <QTextStream>
  4. For the slot, add code to extract the search string and use the () function to look for the search string within the text file. This is illustrated by the following code snippet:
    void TextFinder::on_findButton_clicked()
    {
        QString searchString = ui->lineEdit->text();
        ui->textEdit->find(searchString, QTextDocument::FindWholeWords);
    }
  5. Once both of these functions are complete, add a line to call in the constructor, as illustrated by the following code snippet:
    TextFinder::TextFinder(QWidget *parent)
        : QWidget(parent), ui(new Ui::TextFinder)
    {
        ui->setupUi(this);
        loadTextFile();
    }

The slot is called automatically in the uic generated ui_textfinder.h file by this line of code:

QMetaObject::connectSlotsByName(TextFinder);

Creating a Resource File

You need a resource file (.qrc) within which you embed the input text file. The input file can be any .txt file with a paragraph of text. Create a text file called input.txt and store it in the textfinder folder.

To add a resource file:

  1. Select File > New File or Project > Qt > Qt Resource File > Choose.

    The Choose the Location dialog opens.

  2. In the Name field, enter textfinder.
  3. In the Path field, enter , and select Next or Continue.

    The Project Management dialog opens.

  4. In the Add to project field, select TextFinder.pro and select Finish or Done to open the file in the code editor.
  5. Select Add > Add Prefix.
  6. In the Prefix field, replace the default prefix with a slash (/).
  7. Select Add > Add Files, to locate and add input.txt.

Managing Plugins

Qt Creator comes with a set of plugins, some of which are disabled by default. You can enable disabled plugins if you need them and disable plugins you don’t need.

You can also install additional plugins that you downloaded from Qt Marketplace or some other source, such as GitHub.

Enabling and Disabling Plugins

New Qt Creator plugins are often introduced as experimental plugins to let you try them out before they are fully supported. Experimental plugins are disabled by default and you must enable them for them to become visible after you restart Qt Creator. By default, all the plugins that the plugin depends on are also enabled.

You can also disable plugins that you do not use, to streamline Qt Creator. By default, all the plugins that depend on the plugin are also disabled.

To enable and disable plugins, select Help > About Plugins.

Installing Plugins

Qt Marketplace contains links to Qt Creator plugins that you can download and install either for free or for a price set by their publisher. You can browse the available plugins in the Marketplace tab in the Welcome mode.

Note: You can install only plugins that are supported by your Qt Creator version.

To install plugins:

  1. Select Help > About Plugins > Install Plugins.
  2. In the Source dialog, enter the path to the archive or library that contains the plugin.
  3. In the Install Location dialog, select User plugins to make the plugin available for the current user in all compatible Qt Creator instances or Qt Creator installation to make the plugin available for all users of a particular Qt Creator instance.
  4. In the Summary dialog, select Finish to install the plugin.
  5. Select Restart Now to restart Qt Creator and load the plugin.

Работа с Qt Creator — первый проект

Ну что же, час пробил! Установка Qt Creator завершена. Пора сделать свое первое кроссплатформенное приложение на Linux, а затем скомпилировать его на Windows. Пусть это будет… программа, выводящая иконку Qt, кнопку и надпись, на которую по нажатию кнопки будет выводиться случайная фраза. Проект несложный, и, конечно же, кроссплатформенный!

Для начала откроем среду разработки. Нажмем «Файл» -> «Создать файл или проект…». Выберем приложение Qt Widgets — его быстро и удобно сделать. А название ему — «Cross-Platphorm». Вот как!

Комплект — по умолчанию. Главное окно тоже оставляем без изменений. Создаем проект.

Для начала необходимо настроить форму — главное окно приложения. По умолчанию оно пустое, но это не останется надолго.

Перейдем в папку «Формы» -> «mainwindow.ui». Откроется окно Qt Designer:

Удаляем панель меню и панель инструментов на форму, нажав правой кнопкой мыши и выбрав соответствующий пункт. Теперь перетаскиваем элементы Graphics View, Push Button и Label таким образом:

Чтобы изменить текст, дважды кликните по элементу. В свойствах Label (справа) выбираем расположение текста по вертикали и по горизонтали — вертикальное.

Теперь пора разобраться с выводом иконки. Перейдем в редактор, слева кликнем по любой папке правой кнопкой мыши и выберем «Добавить новый…». Теперь нажимаем «Qt» -> «Qt Resource File». Имя — res. В открывшемся окне нажимаем «Добавить» -> «Добавить префикс», а после добавления — «Добавить файлы». Выбираем файл, а в появившемся окне «Неверное размещение файла» кликаем «Копировать».

Получилось! Сохраняем все. Снова открываем форму. Кликаем правой кнопкой мыши по Graphics View, выбираем «styleSheet…» -> «Добавить ресурс» -> «background-image». В левой части появившегося окна выбираем prefix1, а в правой — нашу картинку. Нажимаем «ОК». Настраиваем длину и ширину.

Все! Теперь можно приступать к коду.  Клик правой кнопкой мыши по кнопке открывает контекстное меню, теперь надо нажать «Перейти к слоту…» -> «clicked()». В окне набираем следующий код:

Creating the Text Finder Project

  1. Select File > New File or Project > Application (Qt) > Qt Widgets Application > Choose.

    The Introduction and Project Location dialog opens.

  2. In the Name field, type TextFinder.
  3. In the Create in field, enter the path for the project files. For example, , and then select Next (on Windows and Linux) or Continue (on macOS).

    The Define Build System dialog opens.

  4. In the Build system field, select the build system to use for building and running the project: qmake, CMake, or Qbs.

    The Class Information dialog opens.

  5. In the Class name field, type TextFinder as the class name.
  6. In the Base class list, select QWidget as the base class type.

    Note: The Header file, Source file and Form file fields are automatically updated to match the name of the class.

    The Kit Selection dialog opens.

  7. Select build and run for your project, and select Next or Continue.
  8. Select Next or Continue.

    The Project Management dialog opens.

  9. Review the project settings, and select Finish (on Windows and Linux) or Done (on macOS) to create the project.

Note: The project opens in the Edit mode, and these instructions are hidden. To return to these instructions, open the Help mode.

The TextFinder project now contains the following files:

  • main.cpp
  • textfinder.h
  • textfinder.cpp
  • textfinder.ui
  • textfinder.pro

The .h and .cpp files come with the necessary boiler plate code. The .pro file is complete.

Code documentation and status

Doxygen Plugin

Generates doxygen comments from source code and can launch doxywizard for editing doxygen config file. See Doxygen Plugin for QtCreator for more info.

Status: Works with Qt Creator 4.3+. Binaries provided for Linux and Windows.

Jenkins Status plugin

Shows the status of Jenkins on the left site. This Plugin is based on the CruiseControl-Plugin.

Status: works with Qt Creator 2.5

SpellChecker plugin

Configurable SpellCheck plugin that checks the spelling of comments as well as string literal. Interaction made possible using an output pane, navigation widget and other menus and commands.
The spell checking is done using the Hunspell spell checker. Implemented and tested for English but might work for other languages.

Status: Actively maintained. Latest binaries provided for Qt Creator 4.10. (Linux and Windows)

Using the Editor Toolbar

The editor toolbar is located at the top of the editor view. The editor toolbar is context sensitive and shows items relevant to the file currently open in the editor.

Navigating Between Open Files and Symbols

Use the toolbar, Window menu items, or to navigate between open files and symbols in use.

To browse backward or forward through your location history, click (Go Back) and (Go Forward).

To return to the last location where you made a change, select Window > Go to Last Edit.

To go to any open file, select it from the Open files drop-down menu (1). To open a context menu that contains commands for managing open files, right-click the file name or icon on the toolbar. In addition to the commands also available in the File menu, you can copy the path and name of the current file and the number of the line where the cursor is currently located to the clipboard by selecting Copy Full Path, Copy File Name, or Copy Path and Line Number.

To jump to any symbol used in the current file, select it from the Symbols drop-down menu (2). By default, the symbols are displayed in the order in which they appear in the file. Right-click the menu title and select Sort Alphabetically to arrange the symbols in alphabetic order.

To jump to a line and column in the current file, select the line and column indicator (3) or press Ctrl+K (or Cmd+K on macOS) to open the locator. Enter the line number and column number in the locator, separated by a colon (:).

Note: Other convenient ways of navigating in Qt Creator are provided by the sidebars.

Selecting Parse Context

Code might be interpreted differently in different contexts. A file can be used by different projects or subprojects with different defines, or it can be included in the context of C, C++, Objective-C, or Objective-C++. To change the active parse context, select an available parse context in the Active Parse Context menu (4). The menu is visible only when several parse contexts are available. To reset the parse context, right-click on the menu to open a context menu, and then select Clear Preferred Parse Context. If the information needed for parsing the project is still incomplete or incorrect, select Additional Preprocessor Directives to add preprocessor directives.

Changing Text Encoding

To show the file encoding of the current file on the editor toolbar (5), select Tools > Options > Text Editor > Display > Display file encoding.

To change the text encoding, click it on the toolbar and select new encoding in the Text Encoding dialog:

To reload the file with the selected encoding, select Reload with Encoding. To save the file with the new encoding, select Save with Encoding.

Selecting Line Ending Style

To switch between Windows line endings (CRLF) and Unix line endings (LF), select the ending style on the editor toolbar (6).

To set the line endings to use for all projects by default, select Tools > Options > Text Editor > Behavior, and then select the ending style in the Default line endings field.

To set the line endings to use for a project, select Projects > Project Settings > Editor. For more information, see Specifying Editor Settings.

Moving to Symbol Definition or Declaration

You can move directly to the definition or the declaration of a symbol in the Edit mode by holding the Ctrl key and clicking the symbol. If you have multiple splits opened, you can open the link in the next split by holding Ctrl and Alt while clicking the symbol.

To enable this moving function, select Tools > Options > Text Editor > Behavior > Enable mouse navigation.

There are several additional ways of moving between symbol definitions and declarations. All the functions described below are also available from the Tools > C++ menu. The functions supported for QML and JavaScript code are available from the Tools > QML/JS menu.

You can select the symbol and press F2, or right-click the symbol and select Follow Symbol Under Cursor to move to its definition or declaration. To follow the symbol in the next split, select Follow Symbol Under Cursor in Next Split. Following symbols is supported for namespaces, classes, functions, variables, include statements, and macros.

To switch between the definition and declaration of a function, place the cursor on either and press Shift+F2 or right-click and select Switch Between Function Declaration/Definition or Open Function Declaration/Definition in Next Split. For example, this allows you to navigate from anywhere within a function body directly to the function declaration.

Links are opened in the same split by default. To open links in the next split, prepend Ctrl+E to the shortcut. For example, press Ctrl+E,F2 to follow the symbol in the next split. If necessary, the view is automatically split. To change the default behavior, select Tools > Options > Text Editor > Display > Always open links in another split. Additional symbols are displayed and switching between definition and declaration is done in another split. If you change the default behavior, the shortcuts for opening link targets in the next split are used to open them in the current split.

To switch between C++ header and source files, right-click anywhere in a file and select Switch Header/Source or Open Corresponding Header/Source in Next Split. You can also press F4 or Ctrl+E,F4, respectively.

Using Bookmarks

To insert or delete a bookmark in the Edit mode:

  • Right-click the line number and select Toggle Bookmark.
  • Press Shift and click the left margin at a line.
  • Press Ctrl+M when the cursor is on a line.

Adding Notes to Bookmarks

To add a note to a bookmark:

  • Select Tools > Bookmarks > Edit Bookmark.
  • Press Ctrl+Shift+M.
  • Right-click a bookmark and select Edit Bookmark in the context menu.

To view the note, move the mouse pointer over the bookmark or open the Bookmarks view in the sidebar.

Navigating Bookmarks

To go to the previous bookmark in the current session, select Tools > Bookmarks > Previous Bookmark or press Ctrl+,.

To go to the next bookmark in the current session, select Tools > Bookmarks > Previous Bookmark or press Ctrl+..

To use the locator to go to a bookmark, press Ctrl+K (or Cmd+K on macOS) to open the locator. Enter b and a space to display a list of bookmarks. To filter the bookmarks by line number or a text string, enter the number or string after the space. Double-click a bookmark in the list to go to it in the editor.

Viewing Bookmarks

Bookmarks are listed in the Bookmarks view in the sidebar. To move between bookmarks, select the Previous Bookmark or Next Bookmark button or use the keyboard shortcuts.

Creating Qt Quick UI Projects

Qt Quick UI Prototype projects are useful for testing or prototyping user interfaces, or for setting up a separate project just for QML editing, for example. You cannot use them for application development, because they do not contain:

  • C++ code
  • Resource files (.qrc)
  • Code needed for deploying applications to

For more information about how to turn Qt Quick UI Prototype projects into Qt Quick Application projects, see Converting UI Projects to Applications.

To create a Qt Quick UI Prototype project:

  1. Select File > New File or Project > Other Project > Qt Quick UI Prototype.
  2. Select Choose to open the Project Location dialog.
  3. In the Name field, enter a name for the application.
  4. In the Create in field, enter the path for the project files. Select the Use as default project location check box to create new projects in this folder by default.
  5. Select Next (or Continue on macOS) to open the Define Project Details dialog.
  6. In the Minimal required Qt version field, select the Qt version to develop with. The Qt version determines the Qt Quick imports that are used in the QML files.

    You can add imports later to combine Qt Quick basic types with Qt Quick Controls, Qt Quick Dialogs, and Qt Quick Layouts (available since Qt 5.1).

  7. Select the Use Qt Virtual Keyboard check box to add support for Qt Virtual Keyboard to the application.

    Note: If you have not installed the Qt Virtual Keyboard module when you installed Qt, an error message will appear when you try to open the main.qml in the Form Editor in the Design mode. You can use the to install Qt Virtual Keyboard.

  8. Select Next to open the Kit Selection dialog.
  9. Select for the platforms that you want to build the application for.

    Note: Kits are listed if they have been specified in Tools > Options > Kits (on Windows and Linux) or in Qt Creator > Preferences > Kits (on macOS). For more information, see Adding Kits.

  10. Select Next to open the Project Management dialog.
  11. Review the project settings, and select Finish (on Windows and Linux) or Done (on macOS) to create the project.

Qt Creator creates the following files:

  • .qmlproject project file defines that all QML, JavaScript, and image files in the project folder belong to the project. Therefore, you do not need to individually list all the files in the project.
  • .qml file defines a UI item, such as a component or the whole application UI.
  • ui.qml file defines a form for the application UI. This file is created if you selected the With .ui.qml file check box.

To use JavaScript and image files in the application, copy them to the project folder.

Getting the source code

First, cd into the directory where you want the «qt5» directory to live. Then, clone the top-level Qt 5 git repository:

$ git clone git://code.qt.io/qt/qt5.git

or (if you’re behind a firewall and want to use the https protocol):

$ git clone https://code.qt.io/qt/qt5.git

This creates a local branch that tracks «origin/dev». If you plan to submit changes to Qt, stay on this branch. Otherwise, check out the target branch (see Branch Guidelines):

$ cd qt5
$ git checkout 5.12

Getting the Qt 5.15 LTS Commercial source code

The Qt 5.15 LTS Commercial source codes are available in the tqtc shadow repositories and their lts branches. The lts branches have a common prefix, «tqtc/lts-«. For example, «tqtc/lts-5.15».

You can get sources for all Qt submodules or just one specific Qt submodule. The clone commands are visible in the Gerrit as follows:

  1. In Browse > Repositories, type «tqtc-qt5» to Filter field to open the top-level Qt 5 shadow repository. If you like to open some submodule shadow repository, type «tqtc-qt<submodule>». For example, «tqtc-qtbase».
  2. Under the Download topic, you can see the clone commands for different protocols (anonymous HTTP, HTTP, SSH).

Cloning all the Qt submodules

First clone the top-level Qt 5 git repository (the anonymous HTTP clone command is used in the following example):

$ git clone "https://codereview.qt-project.org/qt/tqtc-qt5"

Then check out the target branch. Currently only the tqtc/lts-5.15 branch is available:

$ cd tqtc-qt5
$ git checkout tqtc/lts-5.15

Get the submodule source code (options are described in the next section):

$ perl init-repository

Cloning specific Qt submodule

Ypu can clone some specific Qt submodule, for example Qt Base (the anonymous HTTP clone command is used in the following example). The lts branch is the default branch that is cloned:

$ git clone "https://codereview.qt-project.org/qt/tqtc-qtbase"

Getting the submodule source code

Relevant options for init-repository:

  • --module-subset=default,-qtwebengine : Consider skipping the web module (Qt WebEngine) by passing this option. It is quite big and takes a long time to compile (and is often a source of compile errors), so it is recommended to only download it if you intend to use it. You can always re-run init-repository later on to add it.
  • --branch : Check out the branch tips instead of the SHA1s of the latest successful integration build.
  • --codereview-username <Jira/Gerrit username> : If you plan to contribute to Qt, you may specify your codereview username (pay attention to capitalization!) so that the git remotes are properly set up. Note that it is recommended to adjust your ssh configuration instead.
$ cd qt5
$ perl init-repository

In order to build a specific release of Qt, you can checkout the desired tag:

$ cd qt5
$ git checkout 5.12.0
$ perl init-repository

Note: init-repository is currently unable to initialize tags that are too old. An alternative way to build a specific release or branch of Qt5 (although without linking of the gerrit account for code reviewing) is to use git submodule update --init in place of the init-repository script. That translates to:

$ git clone https://code.qt.io/qt/qt5.git                     # cloning the repo
$ cd qt5
$ git checkout v5.8.0                                         # checking out the specific release or branch
$ git submodule update --init --recursive                     # updating each submodule to match the supermodule

More information can be found in Get The Source.

Будущие релизы

  • Qt 5.9 — текущий релиз (long term supported — 3 года)
  • Qt 5.9.2 — скоро
  • Qt 5.10 — скоро бета, релиз в ноябре
  • Qt 5.11 — май 2018
  • Qt 5.12 — ноябрь 2018 (возможный кандидат следующего long term supported)

Плановая работа

  • Улучшение производительности
  • Распознавание речи (цифровой помощник?)
  • AR/VR
  • Инструменты IDE (рефакторинг, workflow)

C++14 & 17

Мы используем C++11 в той мере, в которой позволяет VS2013. Мы бы хотели использовать:

  • if constexpr
  • Initializers в if/switch
  • Structured bindings
  • Overaligned data

Уже используем , , , . Добавили QStringView.

C++20

Мог бы стать очень интересным для Qt: концепты, модули, рефлексия (может быть даже удалось бы избавиться от moc когда-нибудь в будущем).

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector