Compile qt5 on windows

Содержание
  1. Compile qt5 on windows
  2. Установка QT под Windows и правильные Helloworld’ы 🙂
  3. Qt Documentation
  4. Contents
  5. Supported Configurations
  6. Deployment and Other Issues
  7. Where to Go from Here
  8. Visual Studio Tools
  9. Qt Documentation
  10. Contents
  11. Step 1: Install the License File (Commercially Licensed Qt Only)
  12. Step 2: Unpack the Archive
  13. Step 3: Set the Environment Variables
  14. Step 4: Build the Qt Library
  15. Parallel Builds
  16. Step 5: Build the Qt Documentation
  17. Building Qt 5 from Git
  18. Contents
  19. System Requirements
  20. All desktop platforms
  21. Documentation (optional)
  22. SSL (optional)
  23. Linux/X11
  24. apt-get build-dep
  25. Convenience packages (Ubuntu 11.10 — 12.10 only)
  26. Build essentials
  27. Libxcb
  28. OpenGL support
  29. Accessibility
  30. Qt WebKit
  31. Qt WebEngine
  32. Qt Multimedia
  33. QDoc Documentation Generator Tool
  34. macOS
  35. Windows
  36. Windows Graphics Drivers
  37. ANGLE dependencies
  38. Supported Compilers on Windows
  39. Windows Build environment
  40. Configuring Visual Studio 2013 on Windows 8, 8.1 & 10
  41. Configuring MinGW on Windows 8, 8.1 & 10
  42. ICU on Windows
  43. Getting the source code
  44. Getting the Qt 5.15 LTS Commercial source code
  45. Cloning all the Qt submodules
  46. Cloning specific Qt submodule
  47. Getting the submodule source code
  48. Configuring and Building
  49. Building Qt WebKit
  50. Windows
  51. Installing (Linux / OS X)
  52. Cleaning
  53. Getting updates
  54. Using latest branches in the submodules
  55. Issues
  56. Linux
  57. configure fails with «No QPA platform plugin enabled!» (Linux)
  58. configure fails with errors like «cannot stat file . «
  59. configure fails to enable qdoc on Debian
  60. qmlscene segfaults «Cannot create platform GL context, none of GLX, EGL, DRI2 is enabled» (Linux)
  61. WebKit doesn’t compile, missing ICU
  62. on Ubuntu/Debian:
  63. on Fedora:
  64. Qt D-Bus fails to build due to «inconsistent user-defined literal suffixes»
  65. cc1: fatal error: .pch/release-shared/QtGui: No such file or directory
  66. (void_(QQmlDataLoaderThread::)(QQmlDataBlob),_QQmlDataBlob*_const&)’_isn’t_defined»> ld: hidden symbol `void QQmlThread::postMethodToThread (void (QQmlDataLoaderThread::)(QQmlDataBlob), QQmlDataBlob* const&)’ isn’t defined
  67. Windows
  68. Debugging OpenGL issues (Windows)
  69. Questions and comments

Compile qt5 on windows

БлогNot. Установка QT под Windows и правильные Helloworld’ы 🙂

Установка QT под Windows и правильные Helloworld’ы 🙂

QT — ещё один мегаглючный популярный инструмент для разработки на C++. Во всяком случае, если Вы заглянете в тематический раздел Киберфорума, Вы увидите, что вместе с Visual C++ (Studio) и Builder именно Qt образует «большую тройку» современных сред разработки для C++. К тому же, сторонники Qt говорят, что только он изначально соблюдает концепцию ООП и весь из себя кроссплатформенный 🙂 Мдя, ну и бесплатный open source, конечно.

Как нам поставить и настроить это чудо под обычную 32- (64-) разрядную Windows? Смотрим официальный сайт, не ленимся нажать Show downloads.

Онлайн-сборки инсталлятора могут называться вроде

Увы, они будут докачивать порядка 800 Мб при установке и, по статистике, чаще становятся криво.

Офлайн-сборки (нажать Show Downloads на странице загрузок) могут называться, например

Это значит что они — с собственным компилятором MinGW и под 32-разрядную Windows. Есть еще сборки, предназначенные для работы с компилятором Visual Studio, тогда в имени сборки есть «studio». Не советую их, даже если установлен полный Visual Studio.

Скачать, установить. Актуальная версия 5.2.1 включает в себя IDE под названием Qt Creator, ставшее более-менее полноценным, во всяком случае, после пары ухищрений заработала отладка.

Запускаем установщик, по умолчанию будет предложен путь установки C:\Qt\Qt5.2.1 , не стоит его менять. Включаем компоненты Qt, MinGW, Qt Creator, Sources — необязательно.

Возможные проблемы при запуске QT Creator:

1. Ошибки при запуске (отсутствует libstdc++-6.dll и т.п.)

В чём дело: в переменных окружения не определена библиотека Qt и не прописан путь к компилятору. Исправляем ситуацию – создаем в переменных среды переменную QTDIR , содержащую значение

Кроме того, в системную переменную Path через точку с запятой прописываем пути

Как это сделать:
Windows XP: Мой компьютер, Свойства, Дополнительно, Переменные среды, Path, Изменить
Windows 7: Мой компьютер, Свойства, Дополнительные параметры системы, Переменные среды, Системные переменные, Path, Изменить

Это необходимо сделать также для того, чтобы собранные Вами приложения могли запускаться из проводника Windows или другого файл-менеджера.

2. Запускается, но присутствуют сообщения об ошибках (например, «Точка входа в процедуру __gxx_personality_v0 не найдена в библиотеке libstdc++-6.dll«).

В чём дело: кривые сборки Qt Creator. Собирайте компилятор MinGW вручную (в инете об этом есть) или поставьте QT Creator 3.0.1, основанный на сборке Qt 5.2.1 (файл qt-opensource-windows-x86-mingw48_opengl-5.2.1.exe ), в нём такого бага не наблюдалось.

3. На работает отладка и т.п. Не исключено, что по умолчанию вообще работает только подсветка кода 🙂

В чём дело: кривизна-с. В меню Инструменты, Параметры, на вкладке Сборка и запуск, Профили Qt проверяем, что имеется автоопределённая связка Qt 5.2.1 + MinGW 32bit, это добавляет Qt Creator. На вкладке Сборка и запуск, Комплекты (в немного более ранних сборках — Инструментарии) должна быть автоопределенная связка инструментов Desktop Qt 5.2.1 MinGW 32bit, эту связку также добавляет Qt Creator, но в ней может быть указан неправильный отладчик, а редактированию она не поддается. У меня помогло просто создание новой связки с помощью кнопки Добавить, ей присваиваем какое-либо другое имя, например, Desktop QT 5.2.1 MinGW Patched, нажимаем кнопку Сделать по умолчанию. В нижней части окна для новой связки необходимо выбрать такие же параметры как и для автоопределенной (Desktop, Локальный ПК (по умолчанию для Desktop), MinGW (x86 32bit) — если желаете, можно и через Visual Studio компилировать, будет ещё медленнее), но указать другой отладчик, воспользовавшись кнопкой Управление, Добавить, Обзор. В открывшемся окне указываем путь к отладчику вида C:\Qt\Qt5.2.1\Tools\mingw48_32\bin\gdb.exe и нажимаем Применить.

4. Что ещё проверить и настроить перед созданием первого проекта.

Запускаем Qt Creator, выбираем пункт главного меню Инструменты, Параметры. на вкладке Текстовый редактор, Шрифт и цвета устанавливаем понравившийся шрифт (Courier New или другой моноширинный шрифт для листингов — рулит), на вкладке Текстовый редактор, Поведение выбираем кодировку файлов, по умолчанию Юникод (UTF-8). На вкладке Сборка и запуск, Основное указываем папку проектов, например, C:\Qt\Projects (эту папку надо предварительно создать; в пути к ней, как и к другим папкам Qt , не должно быть символов кириллицы и/или пробелов; имя пользователя в системе — тоже латиницей).

Теперь два главных действия должно быть легко выполнить:

  • меню Отладка, Начать отладку, Начать отладку или клавиша F5
  • меню Сборка, Запустить или комбинация клавиш Ctrl+R

Можно попробовать. Сначала консольное приложение: меню Файл, Новый файл или проект, Приложения, Консольное приложение Qt. Только встроенный код ничего не делает, а в инете и книгах обычно неработающие «Hello, world». Напишем работающий main.cpp 🙂

Теперь попробуем «приложение с интерфейсом»: меню Файл, Новый файл или проект, создать приложение QT Widgets. Текст модуля main.cpp :

Жмём Файл, Закрыть все документы и проекты — и вернёмся к начальному окну, готовые к новым подвигам 🙂

P.S. Ну и проблема ещё в том, что в инете и книгах большинство примеров — по QT4, а в QT5 есть заметные отличия, самое очевидное —

Подробнее здесь. А вот тут — много примеров с исходниками именно по QT5.

Ниже можно скачать оффлайн-сборку QT 5.2.1 с QT Creator и компилятором MinGW. При полной установке она обеспечивает нормальную работу приложения и не лезет в инет за дополнительными компонентами.

Скачать оффлайн-сборку QT 5.2.1 с QT Creator и компилятором MinGW в файле .exe, 634 Мб

Как слинковать приложение QT статически для работы на другом компьютере? DLL Collector

Как сделать Windows-инсталлятор для приложения на QT? InnoSetup

Qt Documentation

Contents

Qt’s support for different Windows platforms is extensive and mature.

Before you get started, ensure that your development environment fulfills the requirements.

To download and install Qt for Windows, follow the instructions on the Getting Started with Qt page.

Supported Configurations

The following configurations are supported.

Operating System Architecture Compiler Notes
Windows 10 x86 and x86_64 MSVC 2019, MSVC 2017, MSVC 2015, MinGW 8.1
Windows 8.1 x86 and x86_64 MSVC 2019, MSVC 2017, MinGW 8.1
Windows 7 x86 and x86_64 MSVC 2019, MSVC 2017, MinGW 8.1 MinGW-builds GCC 8.1.0 (x86)

Deployment and Other Issues

The pages below covers specific issues and recommendations for creating Windows applications.

Where to Go from Here

We invite you to explore the rest of Qt. We prepared overviews which help you decide which APIs to use and our examples demonstrate how to use our API.

  • Qt Overviews — list of topics about application development
  • Examples and Tutorials — code samples and tutorials
  • Qt Reference Pages — a listing of C++ and QML APIs
  • ActiveX in Qt

Qt’s vibrant and active community site, http://qt.io houses a wiki, a forum, and additional learning guides and presentations.

Visual Studio Tools

The Qt VS Tools allows programmers to create, build, debug and run Qt applications from within non-Express versions of Microsoft Visual Studio 2013 and later. The add-in contains project wizards, Qt project import/export support, integrated Qt resource manager and automated build setup for the Qt Meta-Object Compiler, User Interface Compiler, and Resource Compiler.

В© 2021 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.

Qt Documentation

Contents

This page describes the process of configuring and building Qt for Windows. Before building, there are some requirements that are given in more detail in the Qt for Windows — Requirements document.

You can download the Qt 5 sources from the Downloads page. For more information, visit the Getting Started with Qt page.

Step 1: Install the License File (Commercially Licensed Qt Only)

If you use Qt with a commercial license, the Qt tools look for a local license file. If you are using a binary installer or the commercial Qt Creator, your licenses are automatically fetched and stored in your local user profile ( %USERPROFILE%\AppData\Roaming\Qt\qtlicenses.ini file).

If you do not use any binary installer or Qt Creator, you can download the respective license file from your Qt Account Web portal and save it to your user profile as %USERPROFILE%\.qt-license . If you prefer a different location or file name, you need to set the QT_LICENSE_FILE environment variable to the respective file path.

Step 2: Unpack the Archive

Uncompress the files into the directory you want Qt installed; e.g. C:\Qt\%VERSION% .

Note: The install path must not contain any spaces or Windows specific file system characters.

Step 3: Set the Environment Variables

We recommend creating a desktop link that opens a command prompt with the environment set up similar to the Command Prompt menu entries provided by Visual Studio. This is done by creating an application link passing a .cmd file setting up the environment and the command line option /k (remain open) to cmd.exe .

Assuming the file is called qt5vars.cmd and the Qt folder is called Qt-5 and located under C:\Qt :

A desktop link can then be created by specifying the command %SystemRoot%\system32\cmd.exe /E:ON /V:ON /k C:\Qt\qt5vars.cmd as application and C:\Qt\Qt-5 as working directory.

Note: Setups for MinGW are similar; they differ only in that the bin folder of the installation should be added to the path instead of calling the Visual Studio setup script. For MinGW, please make sure that no sh.exe can be found in the path, as it affects mingw32-make .

Settings required by the additional libraries (see Qt for Windows — Requirements) should also go this file below the call to the Windows SDK setup script.

Step 4: Build the Qt Library

The default behavior of configure is to create an in-source build of Qt 5. If you want to install Qt 5 to a separate location, you need to specify the command line option -prefix . Alternatively, the command line option -developer-build creates an in-source build for developer usage.

To configure the Qt library for a debug build for your machine, type the following command in the command prompt:

The Configure Options page contains more information about the configure options.

To build Qt using jom, type:

If you do not have jom installed, type:

If an installation prefix was given, type jom install , nmake install or mingw32-make install .

Note: If you later need to reconfigure and rebuild Qt from the same location, ensure that all traces of the previous configuration are removed by entering the build directory and typing nmake distclean before running configure again.

Parallel Builds

jom is a replacement for nmake which makes use of all CPU cores and thus speeds up building.

Step 5: Build the Qt Documentation

For the Qt reference documentation to be available in Qt Assistant, you must build it separately:

This will build the documentation in the build folder. If you have installed Qt in a separate location, you will also need to install the documentation:

В© 2021 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.

Building Qt 5 from Git

En Ar Bg De El Es Fa Fi Fr Hi Hu It Ja Kn Ko Ms Nl Pl Pt Ru Sq Th Tr Uk Zh

This article provides hints for checking out and building the Qt 5 repositories. This is primarily for developers who want to contribute to the Qt library itself, or who want to try the latest unreleased code.

If you simply want to build a specific release of Qt from source to use the libraries in your own project, you can download the source code from the Official Releases page or the Archive. Alternatively, commercial customers can download the Source Packages via the Qt Account portal.

Contents

System Requirements

All desktop platforms

  • Git (>= 1.6.x)
  • Perl (>=5.14)
  • Python (>=2.6.x)
  • A working C++ compiler

For more detailed information, see Building Qt Sources

Documentation (optional)

SSL (optional)

For Windows, bison, flex and gperf are provided with the source code at c:\pathToQt\gnuwin32\bin. Get Ruby from http://rubyinstaller.org/. You can download the precompiled ICU packages from download.qt.io, or see Compiling-ICU to compile your own.

Linux/X11

apt-get build-dep

Ubuntu/Debian based systems have a convenient way of installing build-depends for any package:

RPM-based distros with yum offer a similar tool called yum-builddep.

Note: if you see the following error message while running the commands above on Ubuntu:

Then you will need to enable the «Source code» option in Software and Updates > Ubuntu Software under the «Downloadable from the Internet» section. This setting can also be found by running software-properties-gtk.

Convenience packages (Ubuntu 11.10 — 12.10 only)

For Ubuntu/Debian, Gabor Loki has provided a custom PPA with the sedkit-env-webkit meta package that installs all required dependencies for building Qt/Qt WebKit. You can add the PPA by calling:

For other distros, get the separate components below.

Build essentials

Ubuntu and/or Debian: sudo apt-get install build-essential perl python git
Fedora 30 su — -c «dnf install perl-version git gcc-c++ compat-openssl10-devel harfbuzz-devel double-conversion-devel libzstd-devel at-spi2-atk-devel dbus-devel mesa-libGL-devel»
OpenSUSE: sudo zypper install git-core gcc-c++ make

Libxcb

Libxcb is now the default window-system backend for platforms based on X11/Xorg, and you should therefore install libxcb and its accompanying packages. Qt5 should build with whatever libxcb version is available in your distro’s packages (but you may optionally wish to use v1.8 or higher to have threaded rendering support). The README lists the required packages.

Ubuntu/Debian: sudo apt-get install ‘^libxcb.*-dev’ libx11-xcb-dev libglu1-mesa-dev libxrender-dev libxi-dev libxkbcommon-dev libxkbcommon-x11-dev
Fedora 30: su — -c «dnf install libxcb libxcb-devel xcb-util xcb-util-devel xcb-util-*-devel libX11-devel libXrender-devel libxkbcommon-devel libxkbcommon-x11-devel libXi-devel libdrm-devel libXcursor-devel libXcomposite-devel»
OpenSUSE 12+: sudo zypper in xorg-x11-libxcb-devel xcb-util-devel xcb-util-image-devel xcb-util-keysyms-devel xcb-util-renderutil-devel xcb-util-wm-devel xorg-x11-devel libxkbcommon-x11-devel libxkbcommon-devel libXi-devel
ArchLinux/Manjaro: sudo pacman -S —needed libxcb xcb-proto xcb-util xcb-util-image xcb-util-wm libxi
Chakra Linux: Install the ArchLinux packages, plus xcb-util-keysyms. It’s available from CCR.
Mandriva/ROSA/Unity: urpmi ‘pkgconfig(xcb)’ ‘pkgconfig(xcb-icccm)’ ‘pkgconfig(xcb-image)’ ‘pkgconfig(xcb-renderutil)’ ‘pkgconfig(xcb-keysyms)’ ‘pkgconfig(xrender)’
Linux Mint: apt-get install libx11-xcb-dev libxcb-composite0-dev libxcb-cursor-dev libxcb-damage0-dev libxcb-dpms0-dev libxcb-dri2-0-dev libxcb-dri3-dev libxcb-glx0-dev libxcb-icccm4-dev libxcb-image0-dev libxcb-keysyms1-dev libxcb-present-dev libxcb-randr0-dev libxcb-render-util0-dev libxcb-render0-dev libxcb-shape0-dev libxcb-shm0-dev libxcb-sync-dev libxcb-util-dev libxcb-xfixes0-dev libxcb-xinerama0-dev libxcb-xkb-dev libxcb-xtest0-dev libxcb1-dev
Centos 5/6 Install missing Qt build dependencies:

Install Red Hat DevTools 1.1 for CentOS-5/6 x86_64, they are required due to outdated GCC shipped with default CentOS:

Initialise your newly installed dev tools:

For more info on preparing the environment on CentOS, see this thread.

Centos 7 Update to gcc 7:

Install missing Qt build dependencies (Qt 5.13):

OpenGL support

For Qt Quick 2, a graphics driver with native OpenGL 2.0 support is highly recommended.

Accessibility

It is recommended to build with accessibility enabled, install libatspi 2 and libdbus-1 development packages.

Qt WebKit

Ubuntu/Debian: sudo apt-get install flex bison gperf libicu-dev libxslt-dev ruby
Fedora 30: su — -c «dnf install flex bison gperf libicu-devel libxslt-devel ruby»
OpenSUSE: sudo zypper install flex bison gperf libicu-devel ruby
Mandriva/ROSA/Unity: urpmi gperf

Qt WebEngine

Ubuntu/Debian: sudo apt-get install libxcursor-dev libxcomposite-dev libxdamage-dev libxrandr-dev libxtst-dev libxss-dev libdbus-1-dev libevent-dev libfontconfig1-dev libcap-dev libpulse-dev libudev-dev libpci-dev libnss3-dev libasound2-dev libegl1-mesa-dev gperf bison nodejs
Fedora/RHEL: sudo dnf install freetype-devel fontconfig-devel pciutils-devel nss-devel nspr-devel ninja-build gperf cups-devel pulseaudio-libs-devel libcap-devel alsa-lib-devel bison libXrandr-devel libXcomposite-devel libXcursor-devel libXtst-devel dbus-devel fontconfig-devel alsa-lib-devel rh-nodejs12-nodejs rh-nodejs12-nodejs-devel
OpenSUSE: sudo zypper install alsa-devel dbus-1-devel libXcomposite-devel libXcursor-devel libXrandr-devel libXtst-devel mozilla-nspr-devel mozilla-nss-devel gperf bison nodejs10 nodejs10-devel

Qt Multimedia

You’ll need at least alsa-lib (>= 1.0.15) and gstreamer (>=0.10.24) with the base-plugins package.

QDoc Documentation Generator Tool

Ubuntu/Debian: sudo apt-get install libasound2-dev libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev libgstreamer-plugins-good1.0-dev libgstreamer-plugins-bad1.0-dev
Fedora 30:

macOS

Install the latest Xcode from the App Store. Verify that your Xcode install is properly set up for command line use:

This should give you eg:

You can verify that the right Xcode is being used by running:

If this points to /Developer you’re probably using an older Xcode version. Switch to the latest one by running:

Windows

Windows Graphics Drivers

The full feature set of Qt Quick 2 requires OpenGL 2.1 or higher or OpenGL ES 2.0 to work. Several options are available:

  1. Using the native OpenGL driver for your graphics card (Note: The stock Windows driver only supports OpenGL 1.1, which is insufficient).
  2. Using the ANGLE-library to translate OpenGL calls into DirectX. A copy of ANGLE is bundled in Qt 5.
  3. Using a software rasterizer shipped in the Qt SDK. See MesaLlvmpipe for instructions on how that is built.

Starting with Qt 5.8, many Qt Quick applications can also be run with the built-in software backend (previously known as the Qt Quick 2D Renderer). This is not the same as running through a full OpenGL software rasterizer, and is a lot more lightweight. See the documentation on how to request a specific backend.

Qt can be built to dynamically choose the OpenGL implementation (see Dynamically Loading Graphics Drivers) by passing the option -opengl dynamic to configure. To build Qt to always use the native OpenGL driver, pass -opengl desktop. To build Qt to always use ANGLE, pass -opengl es2.

ANGLE dependencies

  • MSVC
    • Qt .dll to be added to the PATH variable.
    • Qt >= 5.12: Qt needs at least a Windows 10 SDK in order to build ANGLE. No additional manual setup is needed
  • MinGW
    • Building ANGLE with Windows SDKs prior to Windows Kit 8 requires the DirectX SDK to be installed, and the path to the d3d_compiler .dll to be added to the PATH variable.

Any project that uses run-time shader compilation must have D3DCOMPILER_xx.DLL copied to the local executable path for the project. This DLL is available in this sub-directory of the Windows SDK installation under %ProgramFiles(x86)%\Windows Kits\ \Redist\D3D\ where is x86 and x64 (see [1]).

Supported Compilers on Windows

  • Visual Studio 2019
  • Visual Studio 2017 (might need a recent service pack, especially for QtWebEngine)
  • MinGW-w64 based compiler with g++ version 7.3 or higher (e.g. MinGW-builds, see also MinGW-64-bit).
  • Add the compiler to the PATH environment variable. Visual Studio usually ships .bat files named vcvarsall.bat or similar that can be called with a command line parameter for choosing the toolchain (/x86, /x64, etc) to set up the environment.
  • Windows SDK v6.0A/v7.0A contains the same compiler as Visual Studio 2008/2010.
  • Windows SDK 8.0 and later do not include a compiler.
  • As of 16.3.2012, if you wish to install both Visual Studio 2010 and the standalone SDK, you need to follow this order (see readme.html provided with the service pack):
    1. Install Visual Studio 2010
    2. Install Windows SDK 7.1. See also the Cannot Install Windows SDK page.
    3. Install Visual Studio 2010 SP1
    4. Install Visual C++ 2010 SP1 Compiler Update for the Windows SDK 7.1

Windows Build environment

We recommend creating a command prompt that provides the build environment (see the Qt Creator README ). In this environment, Python (e.g. Active Python 2.7 later) and Perl (e.g. StrawberryPerl 5.12 or later) should be in the PATH. Ruby is required for WebKit.

Hint: If you installed git with the non-recommended setting to add git's entire Unix environment to PATH, make sure that Perl is added to the path in front of git, since that ships an incompatible build of perl, which would cause the scripts to fail. Also, MinGW builds of Qt become Msys builds due to the presence of sh.exe; and those who've tried have had more success configuring and building for MinGW in MS's cmd.exe Command Prompt than in the Git Bash shell.

Multicore building: To speed up building when using nmake, the compiler can be instructed to use all available CPU cores in one of the following ways:

  • Pass the option -mp to Qt's configure
  • Set the environment variable CL (specifying Visual Studio compiler options) to /MP (On the command line: set CL=/MP)
  • Use the tool jom instead of nmake. (Using jom instead of nmake reduces compile time quite a bit)

Configuring Visual Studio 2013 on Windows 8, 8.1 & 10

Setting the environment variables to properly build Qt can be done by following the steps below:

  • Create a file called qt5vars.bat, paste the following inside it and save it

Complete the steps below after you have cloned Qt5 from Git

  • After having cloned Qt5 from Git (assuming it's at C:\Qt5), move qt5vars.bat to the Qt5 folder
  • Double-click on the script to run it. Once it runs the script, the command prompt will stay open to enter additional commands.
  • Navigate to C:\Qt5 in the command prompt

The working directory should be c:\Qt5.

All the required environment variables are now correctly set up and building Qt5 with nmake should work now. You have to run qt5vars.bat and use the command prompt every time you build Qt5 with nmake.

The above steps also work for setting up nmake to build jom.

Configuring MinGW on Windows 8, 8.1 & 10

The configuration process is similar to above except for a few minor changes in the qt5vars.bat script:

ICU on Windows

Qt 5 can make use of the ICU library for UNICODE and Localization support. This is required for building Qt WebKit. You can use pre-compiled versions of ICU with a Visual Studio 2010 dependency from the website, get pre-compiled versions for different compilers from download.qt.io, or compile ICU on your own.

The absolute paths of include and lib folders of the ICU installation must be passed with -I and -L option to Qt's configure. In addition, uic.exe needs to find the ICU DLLs during compilation, for which the lib folder of the ICU installation must be added to the PATH environment variable.

At run-time, the ICU DLLs need to be found. This can be achieved by copying the DLLs to the application folder or adding the lib folder of the ICU installation to the PATH environment variable.

Getting the source code

First clone the top-level Qt 5 git repository:

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

Then check out the target branch (see Branch Guidelines):

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. sign in to Gerrit with your Qt account (that has a valid commercial license): https://codereview.qt-project.org
  2. 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 ". For example, "tqtc-qtbase".
  3. 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):

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

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

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:

Getting the submodule source code

As described in the README.git, initialize the repository using the init-repository script, which clones the various sub-modules of Qt 5.

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 : 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.

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

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:

More information can be found in Get The Source.

Configuring and Building

The Qt5 build system should be fairly resilient against any "outside distractions" - it shouldn't matter whether you have other Qt versions in PATH, and QTDIR is entirely ignored. However, make sure that you have no qmake-specific environment variables like QMAKEPATH or QMAKEFEATURES set, and the qmake -query output does not refer to any other Qt versions ($HOME/.config/Qt/QMake.conf should be empty).

For more configure options, see Qt Configure Options.

Note: To build qdoc and Qt documentation in future you should set LLVM_INSTALL_DIR environment variable pointing to directory where LLVM is installed (it should be top level directory, the configuration scripts use relative path tracing from this directory). For example, in Linux with LLVM installed in isolated directory (/usr/llvm), at a bash prompt:

A build script called configure (or configure.bat for Windows) will be in the directory that you git cloned the source code into (

/qt5 if you followed the directions above). You will want to call that script from a different, parallel-level directory, because (unless you are using a Qt Autotest Environment) you do not want to build Qt in the directory that holds the source code. Instead, you should use a «shadow build,» meaning you should not build into the source directory.

For Linux / macOS, to install in

/qt5-build (an arbitrary name), assuming you are in

For Windows, again assuming you are in

The -developer-build option causes more symbols to be exported in order to allow more classes and functions to be unit tested than in a regular Qt build. It also defaults to a ‘debug’ build, and installs the binaries in the current directory, avoiding the need for ‘make install’. ‘-opensource’ sets the license to be GPL/LGPL. The -nomake examples and -nomake tests parameters make sure examples and tests aren’t compiled by default. You can always decide to compile them later by hand.

  1. You can add -confirm-license to get rid of the question whether you agree to the license.
  2. On Windows, you might not be able to build if sh.exe is in your PATH (for example due to a git or msys installation). Such an error is indicated by qt5-src\qtbase\bin\qmake.exe: command not found and alike. In this case, make sure that sh.exe is not in your path. You will have to re-configure if your installation is already configured.
  3. If you are planning to make contributions with git, it is advised to configure and build the source in a separate directory so the binaries are not seen by git. This can be done by navigating to the desired build directory and calling configure/make in that directory. (But shadow builds are discouraged in Qt Autotest Environment.)
    1. Note: If you do a shadow build, follow the instructions above for creating a build directory that is parallel to the source directory. Do NOT make the build directory a subdirectory of the source tree. The build will probably fail in weird ways if the build directory is not exactly parallel to the source directory.

Now trigger the build from within the build directory by running:

For Windows (MSVC), choose one of the following, depending on your setup/environment:

Or only build a specific module, e.g. declarative, and modules it depends on:

Building Qt WebKit

Windows

WebKit.org has instructions for building WebKit on Windows. ICU is required for building.

The tools bison, flex and gperf which are required for building are provided for convenience in the folder gnuwin32\bin. If you are using shadow builds, you must add this directory to your PATH, else no special actions need to be done manually in order to use them.

Installing (Linux / OS X)

  • Note: Installation is only needed if you haven’t used the configure options -developer-build or -prefix "%PWD%/qtbase". Otherwise, you can just use Qt from the build directory.

Cleaning

To get a really clean tree use:

since make confclean no longer works from the top-level of the repo.

Getting updates

To update both the qt5.git repo as well as the submodules to the list of revisions that are known to work, run

In addition, you should pass the same parameters to init-repository as you did in Getting the source code.

Unlike a «normal» git submodule update, this ensures that any changes to the module structure are automatically pulled as well.

If you are planning to do nightly builds, consider using the script qt5_tool that lives in qtrepotools/bin. It provides options for updating the repository, cleaning and building. For example, qt5_tool -u -c -b can be used to clean, update and build. qt5_tool -p -c -b would be used to pull all modules to the head of their master branches.

Depending upon what changed in the source since it was last updated you might have to run configure again. The safe thing to do is to always run config.status -recheck-all in the build directory after updating.

  • Hint1: The submodule update does a checkout in submodules, potentially hiding any local commits you’ve done. If the latter happened to you (and you haven’t been working with branches anyhow), git reflog is your friend.
  • Hint2: When creating scripts for updates on Windows, note that git clean often fails if some process locks a file or folder.

Using latest branches in the submodules

By default, the checkout will not contain the latest stable/dev branches of each individual submodule repository, but a combination of versions that are known to work together. If you want to get the absolute latest stuff you can do so on a per-module basis, e.g.

or tell init-repository to check out branches in all repositories:

Some Unix shell tricks for developing Qt can be useful when you are making or reviewing changes in multiple modules.

Issues

Linux

configure fails with «No QPA platform plugin enabled!» (Linux)

You should install the libxcb and it’s accompanying packages, see ‘System Requirements’.

configure fails with errors like «cannot stat file . «

Your perl version is too old, Qt 5 beta1 needs at least 5.14.

configure fails to enable qdoc on Debian

Debian allows parallel installs of libclang- -dev in /usr/lib/llvm- so LLVM_INSTALL_DIR should be /usr/lib/llvm- to build qdoc. Not /usr/llvm.

qmlscene segfaults «Cannot create platform GL context, none of GLX, EGL, DRI2 is enabled» (Linux)

Try installing the libx11-xcb-dev package:

afterwards you have to re-run configure and force qtbase/src/plugins/platforms/xcb to recompile.

WebKit doesn’t compile, missing ICU

Currently there is no configure time check for ICU, so install it through the package manager through

on Ubuntu/Debian:

on Fedora:

  • You can also compile Qt without Qt WebKit by deleting / renaming the qtwebkit, qtwebkit-examples-and-demos directories.
  • The —no-webkit option of configure added, see QTBUG-20577 issue.

Qt D-Bus fails to build due to «inconsistent user-defined literal suffixes»

This occurs when you attempt to build Qt 5 with GCC 4.7 while D-Bus . isNull is not defined (from qvariant_p.h)

C++11 support is detected while your GCC doesn’t properly support it. Fixed by passing -no-c11 to the configure options.

cc1: fatal error: .pch/release-shared/QtGui: No such file or directory

Currently unresolved bug with the build of assembly files, see discussion at http://comments.gmane.org/gmane.comp.lib.qt.devel/5933
Fixed by passing -no-pch to the configure options.

(void_(QQmlDataLoaderThread::)(QQmlDataBlob),_QQmlDataBlob*_const&)’_isn’t_defined»> ld: hidden symbol `void QQmlThread::postMethodToThread (void (QQmlDataLoaderThread::)(QQmlDataBlob), QQmlDataBlob* const&)’ isn’t defined

Bug with GCC versions Touchscreen (or Wacom tablet) doesn’t work

Qt depends on having libxi (including development headers), supporting XInput protocol 2.2 or higher, available at build time in order to have multi-touch support. Otherwise configure will fall back to XInput 2.0 which does not support touchscreens. To prove that is the problem, try this:

and try your Qt application again. At startup, Qt will enumerate the input devices available, like this

If it does not say Qt supports 2.2 or greater, it means the headers weren’t available when Qt was built, so the support for touch was not included. If you do have 2.2 or greater but it doesn’t say it’s a touchscreen at the end, there may be some other problem such that the touchscreen is not recognized, and you may want to write up a bug, after verifying that touch works in other X11 applications.

Windows

Note that if you’re shadow-building Qt, the source directory and build directory must be on the same drive, nested equally deeply. Also, make sure there are no old build artifacts in the source directory.

Debugging OpenGL issues (Windows)

Set the environment variable QT_QPA_VERBOSE=gl:1 and run the application with DebugView installed. The log will show the requested vs obtained OpenGL version. If the log tells you that it only has OpenGL 1.1, Qt Quick 2 will not work. Note that qmlscene will not report errors about unsupported OpenGL versions.

Questions and comments

Please raise questions & comments about this article in this forum thread.

Читайте также:  При загрузке windows ошибка lsass exe
Оцените статью
Ubuntu/Debian: sudo apt install libclang-6.0-dev llvm-6.0
Fedora 30: