Compiling your first Qt Program in Ubuntu
Qt is a free, open source, and cross-platform application development framework for desktop, embedded and mobile. It supports various platforms such as Linux, OS X, Windows, VxWorks, QNX, Android, iOS, BlackBerry, Sailfish OS, and others. More than a programming language. Qt is a framework written in C++. A preprocessor, Meta-Object Compiler is used to extend the C++ language with features like signals and slots. Before the compilation step, the MOC parses the source files written in Qt-extended C++ and generates standard compliant C++ sources from them. Thus the framework itself and applications/libraries using it can be compiled by any standard compliant C++ compiler like Clang, GCC, ICC, MinGW, and MSVC.
- The Command line
- The Qt Compiler GUI
We have run the commands and procedures mentioned in this article on a Ubuntu 18.04 LTS system.
Installing Qt Creator
Let us first start by installing the Build Essential that is a meta package that lets you install and use c++ tools in Ubuntu.
Open the Ubuntu command line, the Terminal, either through the Application Launcher search bar or the Ctrl+Alt +T shortcut.
Then run the following command as sudo in order to update your local repository index with that of the Internet:
This command lets you install the latest available software packages available on the Internet.
Now, run the following command as sudo in order to install the Build Essential package:

Please note that only an authorized user can add, remove, update, and configure software on Ubuntu. Please provide your password and enter Y when the system prompts you with a choice to continue the installation.
Next, run the following command as sudo in order to install the Qt Creator package that contains both the UI and command line tools for Qt project creation and execution.

Please enter Y when the system prompts you with a choice to continue the installation.
If you want Qt 5 to be used as the default Qt Creator version, then run the following command:

Please enter Y when the system prompts you with a choice to continue the installation.
- qt5-doc: This package contains the Qt 5 API Documentation.
- qtbase5-examples: This package contains the Qt Base 5 examples.
- qtbase5-doc-html: This package contains the HTML documentation for the Qt 5 Base libraries.

Please enter Y when the system prompts you with a choice to continue the installation.
You are now ready to use the Qt Creator command line and UI tools!
Your first Qt Program; Written and compiled from the Terminal
A Terminal-savvy person like me is always on a look out for finding solutions for all the programming problems within the Terminal itself. It is after all, very simple to write and compile Qt programs from the Ubuntu command line. Please follow these steps in order to write and execute a simple program Qt program from the Terminal.
Step 1: Create a Project Directory
Let us first create a working directory that will later serve as a project directory for our Qt project.
You can, of course, choose project and file names according to your own wishes. Just be consistent and careful with them as you follow the steps of this tutorial.

Step 2: Create a .cpp file in the project directory
Move to the newly created project directory through the following command:
Then, create a main .cpp file in this directory through the nano editor as follows:
You can, of course, use any of your favorite text editors for this purpose.

In the blank file, copy this Qt program whose sole purpose is to print a line of sentence on a window with the title “My First Qt Program”.
Tip: You can copy this code by selecting it from here, and then paste it in the file by using the Ctrl+Shift +V shortcut. Alternatively, you can paste the selected text by using the Paste option from the right-click menu in the File.

Quit the file by using the Ctrl+X shortcut and then save it by entering Y, and then hitting Enter.
Step 3: Create the Qt project file
After saving the file, run the following command in order to create a Qt Project file:

Running the ls command will display that the above command has created a file by the name of SampleProject.pro in the project directory. This project file is the basic skeleton file for Qt projects and it can be edited for complex purposes.
Step 4: A little configuration to the Qt project file
Open the SampleProject.pro file in the nano editor as follows:

Add the above-mentioned line and Save the file by hitting Ctrl+X, and then by entering Y and hitting Enter.
Step 5: Run qmake to make the project platform-specific
To make the .pro file platform specific, you need to run the following command on the project file:

This will create a file by the name of “Makefile” in the project directory. You can verify this by running the ls command, just as I did.
Step 6: Create and Executable Qt File for the project
The following make command will help you in compiling the Makefile into an executable program.

Providing that there are no errors in your project, this command should create an executable program in your working directory. You can verify this by running the ls command, just as I did.
The SampleProject file, in green color, is my executable Qt file.
Step 7: Run the Executable file
Finally, we are ready to run the executable file we created in the last step through the Terminal. Run the following command to do so:
Here is the output of the program:

A window with a title and label that we provided in the code!
Your first Qt Program, compiled from the Qt Creator UI
If you are interested in executing the same program from the Qt Creator UI, please follow this procedure:
Launch Qt Creator
Launch the Qt Creator application either through the system Application Launcher search as follows, or directly through the Applications listing.

You can even launch it by entering the following command in your Terminal:
Create a Qt Project
The application will open in the following view.
Create a new project by Clicking on the New Project button in the following Projects view:

This will open the New File or Project view as follows:

We will be choosing a template for our project here. Click on the Application option from the Project panel and select Qt Widgets Application as a template. This template creates a Qt application for the desktop. It includes a Qt Designer-based main window. Click on the Choose button after making your selections; this will open the following Qt Widgets Application view:

Enter the name of your Qt project and specify the location where you want to create it. Then click Next; it will open the following view for you to make a Kit Selection:

Make sure that Desktop is selected as the kit, and then click Next. You will then be presented with the Class Information as follows:

You can, of course, change the class names according to your will but for your first Qt program, we prefer you use the default file names. Click Next and you will be presented with the following Project Management details:

Click the Finish button and you are ready to work on your first Qt project.
Your First Qt Program
The Qt Creator will open your mainwindow.cpp file by default. Click on the main.cpp file from the Project hierarchy presented in the left-most panel. In the main.cpp file, replace the existing code with the following one:
This is how your project window should look like:

Save the file by using the Ctrl+S shortcut or by selecting Save from the File menu.
Running the Program
Finally, Run the project by using the Ctrl+R shortcut or by selecting Run from the Build menu.
Your program will be compiled and run, and you will be able to see the following output:

A window with our specified title and label! Do not forget to build the project before running it, the next time you make any changes to the code.
So, this was all you needed to know in order to write, compile, and run your first Qt program. You can choose if the command line or the UI method suits you more, depending on your project needs and personal preferences.
Karim Buzdar
About the Author: Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications. As an IT engineer and technical author, he writes for various web sites. You can reach Karim on LinkedIn
Advertisement
report this ad
Как установить Qt 5 на Linux Ubuntu

В этой статье вы прочитаете как установить Qt creator Ubuntu 20.04, если вы интересуетесь разработкой под Linux, то вам сюда.
Ещё посмотрите статью «Аналоги программ Windows на Linux», если вы интересуетесь Linux.
Как установить Qt на Linux Ubuntu 20.04:
В начале, перед установкой нужно зайти на официальный сайт, и грубо говоря скачать установщик, хотя он потом всё равно будет всё погружает из интернета, зайдите по этой ссылке.

Там нажимаете «Download», после этого надо будет опять нажать на кнопку «Download», после этого у вас скачивается файл с расширением «.run».
Этому файлу вам нужно добавить права доступа, чтобы его потом запустить через терминал, для этого откройте загрузки в терминале и выполните эту команду:
Установка Qt в Ubuntu
Qt — это кроссплатформенный инструмент с открытым исходным кодом для разработки программ на языке программирования С++. Инструмент и набор библиотек были основаны в 1996 году, а сейчас их используют тысячи успешных проектов. Среди них одно из популярных окружений рабочего стола для Linux — KDE, браузер Opera, и множества других программ.
Операционная система Ubuntu не использует Qt в элементах своего интерфейса, вместо этого она работает на GTK. Если вы хотите использовать Qt в своей системе, или даже писать свои программы с помощью этой библиотеки, вам придется установить ее вручную. В этой статье будет рассмотрена установка Qt в Ubuntu 20.04.
Что такое Qt?
Qt используется в качестве кроссплатформенной основы для разработки различного прикладного программного обеспечения, которое можно запускать на множестве аппаратных платформ без изменений исходного кода программы. Обычно Qt используется для разработки графических приложений, но библиотека поддерживает и создание программ без графического интерфейса.
Важно заметить, что Qt — это не язык программирования. Библиотека написана на C++ и поставляется со своей средой программирования Qt Creator. Она может работать в Linux, Windows и MacOS и здесь есть автоматическое завершение кода, подсветка синтаксиса, интегрирован отладчик, профилировщик, система управления версиями, а также есть поддержка визуального проектирования интерфейсов.
Установка Qt из репозитория
В официальных репозиториях Ubuntu уже есть версия Qt 5. Правда это не самая новая версия, но во многих случаях этого будет вполне достаточно.
Сначала обновите список пакетов:
sudo apt update
Теперь, чтобы установить Qt Ubuntu выполните:
sudo apt install qt5-default

Если вам также нужна установка Qt Creator Ubuntu 20.04, то это сделать тоже не так сложно:
sudo apt install qtcreator
И установите примеры программ на qt5 если это нужно:
sudo apt install qtbase5-examples qtdeclarative5-examples
Готово. Установка Qt завершена и вы можете писать с ее использованием программы. Запустить QtCreator можно из главного меню.

Установка самой новой версии Qt
Естественно, в репозиториях находится не самая новая версия. Если вы хотите именно новую, то придется качать пакет из официального сайта. вы можете скачать установочный пакет на этой странице. Сайт автоматически определит вашу систему и битность. Просто нажмите кнопку Download:

Это онлайн-установщик, который позволит вам установить самую последнюю версию Qt 5 и среду разработки QtCreator. Когда загрузка файла будет завершена нужно дать ему права на выполнения. Для этого перейдите в папку, куда он был загружен, например, загрузки:
chmod u+x qt-unified-linux-x64-2.0.3-1-online.run
Теперь, чтобы запустить установочный скрипт вам будет достаточно выполнить:
Для установки не нужны права администратора и программа установит выбранную вами версию Qt в домашнюю папку. Вам осталось пройти несколько шагов мастера и несколько раз принять лицензионное соглашение. Я опишу не все шаги, а только самые интересные. Сначала вам нужно авторизоваться в своем аккаунте Qt или создать новый:

Примите лицензию и отметьте, что не будете использовать платформу в для компании:

Выберите компоненты, которые необходимо установить и дождитесь завершения установки:

Когда установка qt Ubuntu 20.04 будет завершена, вы сможете использовать самую новую версию этой библиотеки.
Выводы
Вот и все. Теперь вы знаете как установить Qt в Ubuntu 20.04. Это очень просто. Устанавливать самую новую версию немного сложнее чем версию из официальных репозиториев, но зато вы можете получить самое свежее программное обеспечение. Если у вас остались вопросы, спрашивайте в комментариях!