Как настроить проект в qt creator
Одной из популярных сред разработки под С++ является среда Qt Creator. Qt Creator является кроссплатформенным, может работать на Windows, Linux и macOS и позволяет разрабатывать широкий диапазон приложений — десктопные и мобильные приложения, а также приложения для встроенных платформ. Рассмотрим, как создать простейшую программу на С++ в Qt Creator.
Загрузим программу установки. Для этого перейдем на страницу https://www.qt.io/download-qt-installer
Сайт автоматически определяет текущую операционную систему и предлагает для нее загрузить онлайн-установщик. Для загрузки нажмем на кнопку Download:

Регистрация программы установки
После загрузки запустим программу установки:

Вначале программа установки предложит осуществить вход с логином и паролем от учетной записи QT. Однако если у вас нет учетной записи QT, то необходимо зарегистрироваться. Для этого нажмем на ссылку «Зарегистрироваться». И в поля ввода введем логин-электронный адрес и пароль:

Нажмем на кнопку «Далее». После этого на указанный электронный адрес придет ссылка, по которой надо перейти для завершения регистрации.

После этого в программе установки QT снова нажмем на кнопку «Далее»

Установка
Затем отметим пару флажков и нажмем на кнопку «Далее»:

И после этого мы перейдем непосредственно к установке затем отметим пару флажков и нажмем на кнопку «Далее»:

Затем нам будет предложено выбрать, надо ли отправлять отчет :

Далее надо будет указать каталог для установки (можно оставить каталог по умолчанию), а также тип установки:

В качестве типа установки можно указать «Выборочная установка», тогда на следующем шаге необходимо будет указать устанавливаемые компоненты:

В данном случае я выбрал для установки последнюю на данный момент версию Qt — Qt 6.2.3 за исключением двух пакетов (MSVC 2019). При установке для Windows прежде всего стоит отметить пункт компилятора MinGW — на данный момент это MinGW 11.2.0. 64-bit . Остальные компоненты можно устанавливать при необходимости. При установки следует учитывать свободное место на жестком диске, так как некоторые компоненты занимают довольно многом места.
В зависимости от текущей операционной системы набор компонентов может отличаться. Например, набор компонентов для Qt 6.2.3 для MacOS:

Затем надо принять лицензионное соглашение и настроить ярлык для меню Пуск. И далее нажмем на кнопку «Установить»:

Создание проекта С++ в Qt Creator
После завершения установки запустим Qt Creator. На стартовом экране выберем вкладку Projects (Проекты), на которой нажмем на кнопку New (Создать):

В окне создания нового проекта в качестве шаблона проекта выберем Plain C++ Application :

Далее надо будет задать имя проекта и каталог, где он будет располагаться:

На следующих шагах оставим все значения по умолчанию. И на последнем шаге нажмем на кнопку Finish для создания проекта:

И нам откроется проект с некоторым содержимым по умолчанию:

Проект будет иметь один файл — main.cpp , и в центральной части — текстовом редакторе будет открыт его код:
Запустим его, нажав на зеленую стрелку в нижнем левом углу Qt Creator. И в нижней части Qt Creator откроется окно Application Output с результатами работы скомпилированной программы
3. Qt Creator IDE¶
Qt Creator is the default integrated development environment for Qt. It’s written by Qt developers for Qt developers. The IDE is available on all major desktop platforms, e.g. Windows/Mac/Linux. We have already seen customers using Qt Creator on an embedded device. Qt Creator has a lean efficient user interface and it really shines in making the developer productive. Qt Creator can be used to run your Qt Quick user interface but also to compile c++ code and this for your host system or for another device using a cross-compiler.

The source code of this chapter can be found in the assets folder.
3.1. The User Interface¶
When starting Qt Creator you are greeted by the Welcome screen. There you will find the most important hints on how to continue inside Qt Creator and your recently used projects. You will also see the sessions list, which might be empty for you. A session is a collection of projects stored for your reference. This comes really handy when you have several customers with larger projects.
On the left side, you will see the mode-selector. The mode selectors contain typical steps from your workflow.
- Welcome mode: For your orientation.
- Edit mode: Focus on the code
- Design mode: Focus on the UI design
- Debug mode: Retrieve information about a running application
- Projects mode: Modify your projects run and build configuration
- Analyze mode: For detecting memory leaks and profiling
- Help mode: Easy access to the Qt documentation
Below the mode-selectors, you will find the actual project-configuration selector and the run/debug

Most of the time you will be in the edit mode with the code-editor in the central panel. From time to time, you will visit the Projects mode when you need to configure your project. And then you press Run . Qt Creator is smart enough to ensure your project is fully built before running it.
In the bottom are the output panes for issues, application messages, compile messages, and other messages.
3.2. Registering your Qt Kit¶
The Qt Kit is probably the most difficult aspect when it comes to working with Qt Creator initially. A Qt Kit is a set of a Qt version, compiler and device and some other settings. It is used to uniquely identify the combination of tools for your project build. A typical kit for the desktop would contain a GCC compiler and a Qt version (e.g. Qt 5.12.0) and a device (“Desktop”). After you have created a project you need to assign a kit to a project before qt creator can build the project. Before you are able to create a kit first you need to have a compiler installed and have a Qt version registered. A Qt version is registered by specifying the path to the qmake executable. Qt Creator then queries qmake for information required to identify the Qt version.
Adding a kit and registering a Qt version is done in the Settings ‣ Build & Run entry. There you can also see which compilers are registered.
Please first check if your Qt Creator has already the correct Qt version registered and then ensure a Kit for your combination of compiler and Qt and device is specified. You can not build a project without a kit.
3.3. Managing Projects¶
Qt Creator manages your source code in projects. You can create a new project by using File ‣ New File or Project . When you create a project you have many choices of application templates. Qt Creator is capable of creating desktop, mobile applications. An application which uses Widgets or Qt Quick or Qt Quick and controls or even bare-bone projects. Also, a project for HTML5 and Python are supported. For a beginner, it is difficult to choose, so we pick three project types for you.
- Applications / Qt Quick 2.0 UI: This will create a QML/JS only project for you, without any C++ code. Take this if you want to sketch a new user interface or plan to create a modern UI application where the native parts are delivered by plug-ins.
- Libraries / Qt Quick 2.0 Extension Plug-in: Use this wizard to create a stub for a plug-in for your Qt Quick UI. A plug-in is used to extend Qt Quick with native elements.
- Other Project / Empty Qt Project: A bare-bones empty project. Take this if you want to code your application with c++ from scratch. Be aware you need to know what you are doing here.
During the first parts of the book, we will mainly use the Qt Quick 2.0 UI project type. Later to describe some c++ aspects we will use the Empty-Qt-Project type or something similar. For extending Qt Quick with our own native plug-ins we will use the Qt Quick 2.0 Extension Plug-in wizard type.
3.4. Using the Editor¶
When you open a project or you just created a new project Qt Creator will switch to the edit mode. You should see on the left of your project files and in the center area the code editor. Selecting files on the left will open them in the editor. The editor provides syntax highlighting, code-completion, and quick-fixes. Also, it supports several commands for code refactoring. When working with the editor you will have the feeling that everything reacts immediately. This is thanks to the developers of Qt Creator which made the tool feel really snappy.

3.5. Locator¶
The locator is a central component inside Qt Creator. It allows developers to navigate fast to specific locations inside the source code or inside the help. To open the locator press Ctrl+K .

A pop-up is coming from the bottom left and shows a list of options. If you just search a file inside your project just hit the first letter from the file name. The locator also accepts wild-cards, so *main.qml will also work. Otherwise, you can also prefix your search to search for the specific content type.

Please try it out. For example to open the help for the QML element Rectangle open the locator and type ? rectangle . While you type the locator will update the suggestions until you found the reference you are looking for.
3.6. Debugging¶
Qt Creator comes with C++ and QML debugging support.
Hmm, I just realized I have not used debugging a lot. I hope this is a good sign. Need to ask someone to help me out here. In the meantime have a look at the Qt Creator documentation.
3.7. Shortcuts¶
Shortcuts are the difference between a nice-to-use editor and a professional editor. As a professional you spend hundreds of hours in front of your application. Each shortcut which makes your work-flow faster counts. Luckily the developers of Qt Creator think the same and have added literally hundreds of shortcuts to the application.
To get started we have collection some basic shortcuts (in Windows notation):
- Ctrl+B — Build project
- Ctrl+R — Run Project
- Ctrl+Tab — Switch between open documents
- Ctrl+K — Open Locator
- Esc — Go back (hit several times and you are back in the editor)
- F2 — Follow Symbol under cursor
- F4 — Switch between header and source (only useful for c++ code)
List of Qt Creator shortcuts from the documentation.
You can edit the shortcuts from inside creator using the settings dialog.

© Copyright 2012-2018 Jürgen Bocklage-Ryannel and Johan Thelin. This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.
Last updated on Dec 07, 2020.
Установка и настройка Qt Creator
С каждым годом становится все больше операционных систем, и потому разработчикам все труднее удовлетворять потребности пользователей. Три самые популярные компьютерные платформы — Windows, Linux и Mac OS, а также три мобильные — Android, iOS и Windows Mobile — продолжают активно бороться между собой. А это значит, что качественное приложение должно работать на всех основных платформах.
Справиться с этой проблемой помогает кроссплатформенная разработка. Об одной из самых популярных кроссплатформенных сред разработки — Qt Creator — и пойдёт речь в этой статье. Мы рассмотрим как выполняется установка и настройка Qt Creator, а также как работать в Qt Creator.
Что такое Qt Creator
Qt Creator (не так давно имевший название Greenhouse) — это одна из самых распространенных кроссплатформенных IDE. Ее плюсы — удобство, быстрота работы, а также — свободность, так как это ПО с открытым исходным кодом. Поддерживаются такие языки, как C, С++, QML.
Программа была написана компанией под названием Trolltech, которая в полной мере выполнила цель создания среды — работу с графическим фреймворком Qt. Удобный графический интерфейс с поддержкой Qt Widgets и QML, а также большое число поддерживаемых компиляторов позволяют быстро и удобно создать свое кроссплатформенное приложение.
Главная задача этой IDE — обеспечить наиболее быструю кроссплатформенную разработку, используя собственный фреймворк. Благодаря этому разработчики получают прекрасную возможность не писать приложения нативно (т. е. отдельно под каждую платформу), а создать общий код, и, возможно, подогнать его под особенности используемых ОС.
Qt Creator также включает в себя утилиту Qt Designer, что позволяет обработать внешний вид окна приложения, добавляя и перетаскивая элементы (аналогично Windows Forms в Visual Studio). В качестве систем сборки используются qmake, cmake и autotools.
Установка Qt Creator
Итак, пора рассмотреть как установить Qt Creator. Если для Windows разработчики позаботились и сделали оффлайн-установщик, то в Linux 32-bit этой возможности не предусмотрено. Поэтому во время установки вам может потребоваться стабильное интернет-соединение (
20-30 минут). Для начала скачаем установщик:
-
Linux 32-bit (нажимаем » View other options»). Linux 64-bit.
После окончания загрузки переходим в папку с файлом, нажимаем правой кнопкой мыши и выбираем пункт «Свойства».

Теперь перейдем на вкладку «Права» и поставим галочку «Разрешить запуск этого файла в качестве программы».


Теперь нажимаем «Next».

Здесь необходимо выбрать существующий аккаунт или создать его. Данное действие необходимо для проверки лицензии (коммерческой или некоммерческой).

Нажимаем «Next».

Выбираем директорию, в которой будет находиться Qt. Важно, чтобы в пути не было кириллицы и пробелов!

В этом меню находится выбор компонентов. К примеру, можно выбрать установку инструментов для разработки на Android, или же исходных компонентов (это нужно для статической сборки, если кому-то это нужно — напишите в комментариях, и я напишу отдельную статью). Если Вы не уверены, нужны Вам эти компоненты или нет, оставьте их пока так — даже после установки Qt будет возможным удаление и добавление элементов.

В этом окне принимаем лицензию. Жмем «Next».

Если Вы готовы, начинайте установку. У Вас запросят пароль суперпользователя (sudo), после чего начнется скачивание и извлечение файлов. Альтернативный способ — установка через терминал. Для начала необходимо обновить список пакетов.
sudo apt update
Скачиваем и устанавливаем Qt:
sudo apt install qt5-default
Теперь установка Qt Creator:
sudo apt install qtcreator
И, если нужно, исходники.
sudo apt install qtbase5-examples qtdeclarative5-examples
Настройка Qt Creator
После окончания установки перезагрузите компьютер и запустите Qt Creator. Перейдите в меню «Инструменты» -> «Параметры».

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

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

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

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

Установка компонентов Qt Creator
Если вдруг так случилось, что Вы забыли установить какой-то компонент, или, наоборот, хотите его удалить, то на помощь придет Qt Maintenance Tool. Это инструмент, позволяющий управлять всеми компонентами Qt Creator.
Чтобы запустить его, перейдите в меню приложений, выберите пункт «Разработка» -> «Qt Maintenance Tool».

Выберите необходимый пункт (Удалить/добавить компоненты, обновить компоненты или удалить Qt). После выполните необходимые операции и закройте окно.
Работа с 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()». В окне набираем следующий код:

Или вы можете скачать полный проект на GitHub. Работа с Qt Creator завершена, нажимаем на значок зеленой стрелки слева, и ждем запуска программы (если стрелка серая, сначала нажмите на значок молотка). Запустилось! Ура!

Выводы
Установка и настройка Qt Creator завершена. Теперь вы сможете создавать свои программы под огромное число платформ, оставляя код нетронутым! Кстати, установив Qt на Windows, вы сможете скомпилировать этот проект и там. Удачи вам!
Creating a Qt Widget Based Application
This tutorial describes how to use Qt Creator to create a small Qt application, Text Finder. It is a simplified version of the Qt UI Tools Text Finder Example. We use Qt Designer to construct the application user interface from Qt widgets and the code editor to write the application logic in C++.

Creating the Text Finder Project
- Select File > New Project > Application (Qt) > Qt Widgets Application > Choose.

The Introduction and Project Location dialog opens.



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



Note: The project opens in the Edit mode, which hides these instructions. 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
- CMakeLists.txt

The .h and .cpp files come with the necessary boiler plate code.
If you selected CMake as the build system, Qt Creator created a CMakeLists.txt project file for you.
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

- In the Editor mode, double-click the textfinder.ui file in the Projects view to launch the integrated Qt Designer.
- 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.




Applying the horizontal and vertical layouts ensures that the application UI scales to different screen sizes.
- Right-click the Find button to open a context-menu.
- Select Go to Slot > clicked(), and then select OK.
This adds a private slot, on_findButton_clicked() , to the header file, textfinder.h and a private function, TextFinder::on_findButton_clicked() , to the source file, textfinder.cpp.
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 Ui object. You need to add a private function, loadTextFile() , to read and display the contents of the input text file in the QTextEdit.
- In the Projects view in the Edit view, double-click the textfinder.h file to open it for editing.
- Add a private function to the private section, after the Ui::TextFinder pointer:
Completing the Source File
Now that the header file is complete, move on to the source file, textfinder.cpp.
- In the Projects view in the Edit view, double-click the textfinder.cpp file to open it for editing.
- Add code to load a text file using QFile, read it with QTextStream, and then display it on textEdit with QTextEdit::setPlainText():
The following line of code automatically calls the on_findButton_clicked() slot in the uic generated ui_textfinder.h file:
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:
-
Select File > New File > Qt > Qt Resource File > Choose.

The Choose the Location dialog opens.

The Project Management dialog opens.



Adding Resources to Project File
For the text file to appear when you run the application, you must specify the resource file as a source file in the CMakeLists.txt file that the wizard created for you:
Compiling and Running Your Application
Now that you have all the necessary files, select the
button to compile and run your Application.
© 2022 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.