Qt creator windows deploy

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

NOTE: The recommended way to deploy your application is to use the official deployment tool (windeployqt). Try that first! Continue reading this guide only if windeployqt doesn’t quite work for you.

The windeployqt tool will gather files from a few different locations. Here is an example of an app that uses Qt Quick to display a picture (PACKAGE-SPECIFIC DLLS ARE NOT SHOWN):

Qt Deployment Structure Windows.png

Sometimes, your app might be missing some functionality after deployment. Perhaps a window is blank, an image doesn’t show, or a music file won’t play. If this happens, windeployqt has probably forgotten to include a file that is only loaded at runtime (like a plug-in DLL).

Here is a systematic (albeit brute-force) way to identify the missing files. This guide is written for Qt 5 and assumes that:

  • The release version of your app works correctly when you build + run it from Qt Creator
  • Your (dynamically-linked) copy of Qt is installed in C:\Qt\5.2.1\mingw48_32\

Initial deployment (Quick and dirty)

  1. Close Qt Creator.
  2. Copy the following into C:\Deployment\
    1. The release version of MyApp.exe
    2. All the .dll files from C:\Qt\5.2.1\mingw48_32\bin\
    3. All the folders from C:\Qt\5.2.1\mingw48_32\plugins\
    4. (If you used QML) All the folders from C:\Qt\5.2.1\mingw48_32\qml\
  3. Rename C:\Qt\ to C:\QtHidden\ (This turns your PC into a clean environment, just like one that doesn’t have Qt installed).
  4. Launch C:\Deployment\MyApp.exe.

If your app worked correctly, congratulations! You are almost ready for deployment. You don’t want to ship a 1.5GB package though, so it’s time to clean up unused files.

If it didn’t work correctly, ask for help (see the Appendix)

Final deployment (Cleaned up)

Do the deletion steps below in C:\Deployment\ and all of its subdirectories. After each deletion, launch C:\Deployment\MyApp.exe and test it. If it stops working, restore the files you just deleted.

  1. Launch MyApp.exe. While it is running, try to delete all DLLs. The DLLs that aren’t used will go to the recycle bin, leaving behind only the DLLs that you need. (This trick doesn’t work for .qml and qmldir files, however).
  2. (If you used QML) Delete a few .qml files and try relaunching MyApp.exe. Repeat until you try all .qml files.
  3. (If you used QML) Delete qmldir files from the folders that have no more DLLs or .qml files

When you have removed all the files that you don’t need,

  1. Rename C:\QtHidden\ back to C:\Qt\ to restore your installation.
  2. Distribute your app.

Appendix 1: How to ask for help

If you still get stuck,

  1. Start a new post in the Qt Project forum
  2. Say that you followed this guide. Say which attempts passed, and which attempts failed.
  3. Describe how it fails, and provide any error messages that you see.
  4. Provide a screenshot of the contents in C:\Deployment\

Remember: The more info you provide, the better your chances of getting a solution!

Appendix 2: Alternative tools

  • windeployqt — The official deployment tool for Windows by the Qt Project
  • CQtDeployer — A cross-platform deployment tool by QuasarApp

Appendix 3: Some notes about windeployqt.exe

For example, if you have installed Qt lib 5.9.9 in the default location, it would be installed in C:\Qt\5.9.9

  • If you have chosen to install the MS VC 2013 x64 toolchain during the installation of Qt Creator, there will be a folder named msvc2013_64.
    • The file windeployqt.exe would be located in C:\Qt\5.9.9\msvc2013_64\bin.
  • If you have chosen to install the MS VC 2015 x86 toolchain during the installation of Qt Creator, there will be a folder named msvc2015.
    • The file windeployqt.exe would be located in C:\Qt\5.9.9\msvc2015\bin.
  • If you have chosen to install the MS VC 2015 x64 toolchain during the installation of Qt Creator, there will be a folder named msvc2015_64.
    • The file windeployqt.exe would be located in C:\Qt\5.9.9\msvc2015_64\bin.

Do not move windeployqt.exe to another folder.

Create a folder and place your program (your EXE file) into it. Then, you will need to run windeployqt.exe.

For example, from the command line, run C:\Qt\5.9.9\msvc2013_64\bin\windeployqt.exe C:\MyFolder\MyProgram.exe

MyFolder is now ready. You can copy it to any other PC and run your MyProgram.exe.

Публикация приложения

Публикация приложения на десктопных платформах

Последнее обновление: 15.01.2024

При запуске проекта Qt (например, в Qt Creator) фреймворк создает папку с бинарным файлом приложения. Однако создаваемый файл содержит много служебной информации, которая применяется для разработки и отладки,
но простому пользователю не нужна. Кроме того, для полноценной работы приложению нужны дополнительные файлы — различные библиотеки, которые применяются для его работы. В процессе отладки и запуска приложения
в Qt Creator такие файлы автоматически связываются с бинарным файлом. Однако в самой папке сгенерированного бинарного файла эти файлы могут отсутствовать, а бинарный файл при запуске может их не найти.
В связи с этим возникает необходимость создания выходного пакета приложения, которое можно просто скопировать на другой компьютер с определенной операционной системой и одним нажатием
на бинарный файл, запустить его. Рассмотрим, как собрать приложение на Qt в выходной пакет.

Настройка информации приложения

Перед сборкой мы можем добавить для приложения некоторые метаданные о приложении, в частности, имя, версию приложения, сведения о компании. Для этого
в файле main.cpp у класса QApplication (или QGuiApplication в случае с qml)
можно использовать несколько методов

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    app.setOrganizationName("MyCorp");              // имя компании
    app.setOrganizationDomain("metanit.com");       // домен компании
    app.setApplicationName("Test Application");     // имя приложения
    app.setApplicationVersion("1.0.0");             // версия приложения

    //  остальное содержимое файла

Построение приложения в режиме Release

Для создания релизной версии приложения для проекта надо в качестве режима построения указать Release

Публикация приложения Qt

Затем нажатию на пункт меню Build можно выбрать один из пунктов контекстного меню для построения проекта (например, на пункт Build Project/Rebuild)

Построение приложения Qt

Также для построения можно нажать на значок молоточка в левом нижнем углу Qt Creator.

Через пункт меню Edit -> Preferences можно перейти к окну настроек и далее выбрать пункт Build & Run для конфигурации ряд настроек построения.
В частности, мы можем задать выходной каталог для построения приложения

Настройка публикации приложения Qt

По умолчанию приложение создается в текущем каталоге проектов в папку, которая называется по шаблону build-{Имя_Проекта}-{инструментарий_построения}-{Имя_конфигурации}")

Например, в моем случае проект называется «QmlApp», инструментарий построения (Kit) — «Desktop_x86_windows_msvc2022_pe_64bit», а конфигурация — «Release», соответственно папка приложения называется build-QmlApp-Desktop_x86_windows_msvc2022_pe_64bit-Release.
Здесь я могу найти исполняемый файл построенного приложения, который по умолчанию называется по имени проекта:

Папка публикации приложения Qt

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

Ошибка публикации приложения Qt

Мы могли бы вручную попытаться скопировать все необходимые файлы в каталог приложения. Однако фреймворк Qt предоставляет ряд утилит для автоматизации публикации приложения.

Публикация на Windows

Для публикации приложения на Windows Qt предоставляет специальную утилиту windeployqt6, которая находится в папке фреймворка (для старых версий фреймворка — Qt 5 также поставляется
утилита windeployqt.exe — без цифры 6 в названии).

windeployqt и публикации приложения Qt на Windows

В общем случае ее применение имеет следующий синтаксис:

windeployqt6 [options] [files]

Если публикуется приложение на виджетах Qt, то этой утилите достаточно передать путь к приложению:

windeployqt6 C:\Users\eugen\Documents\QtProjects\build-QmlApp-Desktop_x86_windows_msvc2022_pe_64bit-Release\QmlApp.exe

Но если публикуется приложение, которое использует QML/Qt Quick, то этой утилите передается аргумент --qmldir, путь к папке qml-файлов и путь к файлу приложения:

windeployqt6 --qmldir путь_к_файлам_qml путь_к_приложению

Например, в моем случае папка проекта, где размещены файлы qml — «C:\Users\eugen\Documents\QtProjects\QmlApp», а путь к построенному приложению —
«C:\Users\eugen\Documents\QtProjects\build-QmlApp-Desktop_x86_windows_msvc2022_pe_64bit-Release\QmlApp.exe», поэтому в моем случае команда на публикаю выглядит так:

windeployqt6 --qmldir C:\Users\eugen\Documents\QtProjects\QmlApp C:\Users\eugen\Documents\QtProjects\build-QmlApp-Desktop_x86_windows_msvc2022_pe_64bit-Release\QmlApp.exe

В результате windeployqt6 скопирует все необходимые файлы в папку приложения. В дальнейшем мы сможем переносить папку приложения с компьютера на компьютер с той же ОC и запускать приложение.

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

Публикация на Linux

Qt не предоставляет для дистрибутивов Linux готовых инструментов, аналогичных windeployqt. Возможно, это связано с большим количеством разновидностей Linux.
Но есть аналогичный неофициальный инструмент с открытым исходным кодом под названием linuxdeployqt. Он также принимает скомпилированный файл приложения
в качестве параметра и превращает его в автономный пакет путем репликации ресурсов проекта в пакет. Пользователи могут получить сгенерированный пакет. linuxdeployqt
может упаковывать определенные библиотеки и компоненты, необходимые для запуска приложения на основе Qt. Загрузить инструмент можно по ссылке
https://github.com/probonopd/linuxdeployqt/releases

Публикация для macOS

Для публикации приложения для MacOS Qt предоставляет инструмент macdeployqt, который аналогичен windeployqt и который можно найти в папке Qt в каталоге «bin».
Так, этой утилите передается путь к приложению. Для приложения Qt Quick также передается параметр -qmldir с путем к файлам QML:

macdeployqt /Users/foo/myapp-build/MyApp.app -qmldir=/Users/foo/myapp/qml -dmg

Время на прочтение6 мин

Количество просмотров100K

Вступление

Добрый день, уважаемые читатели! Совсем недавно я завершил разработку одного своего приложения на Qt, и мне захотелось создать профессиональную программу установки, чтобы всё было «как у взрослых». Как оказалось, сделать это непросто, учитывая, что на официальном сайте инструментария информации по развёртыванию почти нет. В данной статье рассмотрены некоторые этапы подготовки программ на Qt версии 5.2 или выше для распространения на компьютеры других пользователей. Итак, вот план руководства:

  1. Подготовка проекта Qt к развёртыванию
  2. Компоновка дистрибутива программы
  3. Подписание кода и создание установщика

Не будем терять времени и приступим к работе.

1. Подготовка проекта Qt к развёртыванию

Для того, чтобы было проще следовать инструкциям, создадим простой проект Qt Widgets. Все последующие операции будут относиться к этому проекту. Ниже приведено содержимое исходных файлов приложения:

HelloWorld.pro

QT          += core gui widgets
TARGET      = HelloWorld
TEMPLATE    = app
SOURCES     += main.cpp

main.cpp

#include <QApplication>
#include <QLabel>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QLabel label("Hello, world!");
    label.setAlignment(Qt::AlignCenter);
    label.resize(200, 50);
    label.show();
    return a.exec();
}

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

Добавить подобную информацию можно с помощью файла ресурсов. Файл ресурсов имеет расширение .rc и несёт в себе текстовый код, описывающий используемые в приложении ресурсы. Подобные скрипты используются в проектах Visual Studio, основанных на WinAPI, и содержат различные дескрипторы иконок, строк, идентификаторов и прочего. В проектах Qt всё это имеет мало смысла, однако включение общей информации о программе всё же необходимо. Ниже приведены исходный код файла ресурсов и содержимое файла проекта, который также потребуется изменить:

resources.rc

IDI_ICON1 ICON "icon.ico"

#include <windows.h>

#define VER_FILEVERSION             1,0,0,0
#define VER_FILEVERSION_STR         "1.0.0.0\0"
#define VER_PRODUCTVERSION          1,0,0
#define VER_PRODUCTVERSION_STR      "1.0.0\0"
#define VER_FILEDESCRIPTION_STR     "HelloWorld"
#define VER_INTERNALNAME_STR        "Sensor"
#define VER_LEGALCOPYRIGHT_STR      "Copyright (C) 2015, MyCompany"
#define VER_ORIGINALFILENAME_STR    "HelloWorld.exe"
#define VER_PRODUCTNAME_STR         "Hello World"

VS_VERSION_INFO VERSIONINFO
FILEVERSION     VER_FILEVERSION
PRODUCTVERSION  VER_PRODUCTVERSION
BEGIN
    BLOCK "StringFileInfo"
    BEGIN
        BLOCK "040904E4"
        BEGIN
            VALUE "FileDescription",    VER_FILEDESCRIPTION_STR
            VALUE "FileVersion",        VER_FILEVERSION_STR
            VALUE "InternalName",       VER_INTERNALNAME_STR
            VALUE "LegalCopyright",     VER_LEGALCOPYRIGHT_STR
            VALUE "OriginalFilename",   VER_ORIGINALFILENAME_STR
            VALUE "ProductName",        VER_PRODUCTNAME_STR
            VALUE "ProductVersion",     VER_PRODUCTVERSION_STR
        END
    END

    BLOCK "VarFileInfo"
    BEGIN
        VALUE "Translation", 0x409, 1252
    END
END

HelloWorld.pro

QT          += core gui widgets
TARGET      = HelloWorld
TEMPLATE    = app
SOURCES     += main.cpp
RC_FILE     = resources.rc

В данном примере важно не забыть добавить файлы resources.rc и icon.ico в папку с исходными файлами проекта. На рисунке ниже показано окно свойств программы после сборки:

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

HelloWorld.pro

QT          += core gui widgets
TARGET      = HelloWorld
TEMPLATE    = app
SOURCES     += main.cpp
RC_FILE     = resources.rc

win32
{
    CONFIG += embed_manifest_exe
    QMAKE_LFLAGS_WINDOWS += /MANIFESTUAC:"level='requireAdministrator'"
}

Следует отметить, что все указанные выше инструкции будут гарантированно работать только при использовании комплекта сборки Visual Studio. Подробную информацию о файлах ресурсов можно найти на портале MSDN в разделе «About Resource Files».

2. Компоновка дистрибутива программы

Создание дистрибутива приложения с учётом всех его файлов, которые должны устанавливаться на компьютерах пользователей, вероятно, является самым сложным этапом развёртывания. Требуется тщательно проанализировать исполняемый файл программы на наличие зависимостей, позаботиться о файлах переводов, не забыть про ресурсы приложения. Решить часть этих проблем поможет утилита

windeployqt.exe

, которая поставляется вместе с комплектом сборки. Данный инструмент работает в командной строке и поддерживает некоторые параметры конфигурации. На рисунке ниже показано окно командной строки с запущенной утилитой:

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

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

Следует отметить, что перед использованием windeployqt.exe необходимо добавить путь к этому файлу в переменную среды PATH, в противном случае данный инструмент работать не будет.

3. Подписание кода и создание установщика

После компоновки дистрибутива программы попробуем запустить приложение от имени администратора. На рисунке ниже показано сообщение системной службы User Account Control (UAC) с предупреждением о запуске приложения неизвестного издателя:

Данное предупреждение отпугивает пользователей и создаёт приложению плохую репутацию. Чтобы исправить ситуацию, нужно подписать файлы программы с помощью специального сертификата. Разработчики, подписывая свои программы, как бы дают дополнительные гарантии надёжности приложений с точки зрения информационной безопасности. Разработчики программного обеспечения с открытым исходным кодом могут получить сертификаты для своих проектов бесплатно, к примеру, на сайте Certum. Для использования сертификата понадобиться специальная программа, которая подпишет файлы приложения. Для этого можно использовать удобный инструмент DigiCert Certificate Utility. На рисунке ниже показано окно данной программы со списком сертификатов для подписания кода:

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

После проделанной работы пришло время задуматься над выбором системы создания установщика для подготовленного приложения. Существуют как платные, так и бесплатные продукты для выполнения данной задачи. В таблице ниже перечислены некоторые инструменты для создания программ установки:

Сложно дать какие-либо рекомендации по поводу выбора той или иной системы. Разработчики ПО с открытым исходным кодом, вероятно, выберут бесплатные инструменты, в то же время платные продукты часто используются коммерческими компаниями.

Заключение

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

Developing a C++ program with a graphical user interface can readily be achieved using the Qt Creator integrated development environment. In addition Qt Creator is cross-platform and is available for both Linux and Windows. However, once an application has been built on a given computer, deploying the software to another machine, even one running the same operating system, is not necessarily straightforward. Essentially this is because Qt Creator produces dynamically-linked software so the resulting executable file must be accompanied by a suite of dynamic-link library (DLL) files in order to be able to run.

Deploying a Linux executable

We start with the release version of an application built using Qt Creator. For Linux, this provides an executable file with the name of the application. As an example, we are going to use an app named UpdateContacts, that is designed to consolidate the address books (personal and collected addresses) for the Thunderbird E-mail client. If we now copy this file to another Linux system and run (double-click) the program, nothing will happen. If we run the program in a terminal window (./UpdateContacts), we will see the error message:

./UpdateContacts: error while loading shared libraries: 
libQt6Widgets.so.6: cannot open shared object file: 
No such file or directory

This error message describes the issue – Linux can’t locate the dynamic-link library files necessary to run the program. Searching the Internet for a solution identifies several possible options. The fix that I adopted was to use the linuxdeploy AppDir maintenance tool and the associated plugin, linuxdeploy-plugin-qt. These two packages work in tandem to build an AppDir folder that contains the executable file and all of the associated DLL files for a Qt project.

The files linuxdeploy-x86_64.AppImage and linuxdeploy-plugin-qt-x86_64.AppImage are downloaded and their permissions modified (Properties – Permissions – Allow executing file as a program) to allow execution. The two files can then be copied to the folder in which the release version of the application has been built. An AppDir folder can then be produced, using Terminal, by switching to the release folder and running the command:

./linuxdeploy-x86_64.AppImage --appdir=AppDir 
--executable UpdateContacts --plugin qt

This initially results in an error:

[qt/stderr] linuxdeploy-plugin-qt version 1-alpha 
(git commit ID 52d9a4c), GitHub actions build 130 built on 
2024-01-09 16:47:36 UTC
[qt/stdout] ERROR: Could not find qmake, please install or 
provide path using $QMAKE 
ERROR: Failed to run plugin: qt (exit code: 1)

The problem is that the process requires a path to qmake. This can be established temporarily by including the location where the Qt Creator package is installed using, for my system, the command:

export PATH=/home/toaster/Qt/6.6.1/gcc_64/bin:$PATH

Re-running the command to build the AppDir is now successful; however, the following warning is produced:

WARNING: Could not find desktop file in AppDir, cannot create
links for AppRun, desktop file and icon in AppDir root

This results from the fact that AppDir files are normally used to create AppImages, which are used to distribute applications in a single executable file. AppImages typically have desktop and icon files that are associated with the application but we have not provided any such files. Nevertheless, the resulting AppDir contains the executable UpdateContacts file and the associated DLL files that are required for the application to run.

The contents of the AppDir folder include the following files and folders:

apprun-hooks
usr – bin
    – lib
    – plugins
    – share
    – translations

The contents of the bin folder include the executable UpdateContacts file while the lib and plugins folders essentially contain the required DLL files (including the “missing” libQt6Widgets.so.6).

The entire AppDir folder can now be copied to a second computer running Linux Mint and the application started by double-clicking on the file AppDir/usr/bin/UpdateContacts.

Deploying a Windows executable

In Windows, building the release version of the program produces the file UpdateContacts.exe. However, copying this file to a second machine and attempting to run the program will produce a series of pop-up error messages in the form:

System Error

Each of the error messages relates to a missing DLL file. The solution is to identify all of the required DLL files and copy these to a Release folder together with a copy of the executable file, UpdateContacts.exe.

In order to identify the missing DLL’s we can use the Dependencies package, an open-source version of an older program named Dependency Walker. In particular, we run the program DependenciesGui.exe and use this to open the file UpdateContacts.exe. The output of the program is as shown below:

Dependencies

Note that three of the DLL’s (kernel32.dll, MSVCRT.dll, and SHELL32.dll) are Windows system components. These should be present in any Windows installation and so no specific action is required with regard to these files.

Note that my specific application, in both Linux and Windows, uses SQLite to access Thunderbird’s address database files and so the SQLite module is installed for both operating systems for use in the software development process using Qt Creator. The file sqlite3.dll is available in C:\sqlite which is the folder in which the SQLite module has been installed under Windows. This file can be copied to the release folder. Note that this DLL is required by the current application but will not be listed for software that does not use SQLite.

The five remaining DLL files, tagged with a pink question-mark icon are part of the Qt Creator system and must be retrieved from the relevant storage location(s). A search for the DLL filenames on my system identifies their locations as:

C:\Qt\6.5.2\mingw_64\bin:
   Qt6Core.dll
   Qt6Gui.dll
   Qt6Widgets.dll

C:\Qt\Tools\mingw1120_64\bin
   libgcc_s_seh-1.dll
   libstdc++-6.dll

With all of these files copied to the release folder, running the executable still fails. This time, the error message indicates that libwinpthread-1.dll was not found. This DLL file is also located in C:\Qt\Tools\mingw1120_64\bin and so can be copied to the release folder.

We now appear to have all the required DLL files available in the release folder; however, running the executable file produces a new error:

Platform error

The solution for this is to copy the platforms folder (C:\Qt\6.5.2\mingw_64\plugins\platforms) to the release folder so that the final content of this folder is:

Release folder

and the platforms folder contains yet more DLL’s:

Platforms folder

Now, all of the required DLL’s are in place and, from a copy of the release folder, the executable file, UpdateContacts.exe, will run on a different Windows computer.

Wrap-Up

The process for deploying a Qt application on either Linux or Windows is not straightforward, and related information available on the Internet is not always clear or accurate. The methods described here worked for my specific application and I hope they will at least provide useful guidelines for other users.

References:

Qt Creator – An IDE for C++
https://opcug.ca/Reviews/QtCreator.pdf

Qt Creator
https://www.qt.io/product/development-tools

AppDir specification
https://docs.appimage.org/reference/appdir.html

linuxdeploy
https://github.com/linuxdeploy/linuxdeploy

linuxdeploy-plugin-qt
https://github.com/linuxdeploy/linuxdeploy-plugin-qt

AppImage
https://appimage.org

lucasg/Dependencies
https://github.com/lucasg/Dependencies

What is the best way to deploy my application in linux?
https://forum.qt.io/topic/144085/what-is-the-best-way-to-deploy-my-application-in-linux/11

How to deploy to a Linux server without a Qt install ?
https://forum.qt.io/topic/150319/how-to-deploy-to-a-linux-server-without-a-qt-install

Deploy an Application on Windows
https://wiki.qt.io/Deploy_an_Application_on_Windows

This article shows how to deploy and create an offline installation script for a Qt application for Microsoft Windows.
The basis for this article is a Youtube video tutorial by Duarte Corporation (in Spanish).

Deployment without installation

This step will provide us with the necessary dynamic libraries (DLLs) that need to accompany the executable. This step needs to be performed
regardless of whether we deploy the application with or without an installation script.

  1. Open your project in Qt Creator and compile it in the Release mode.
  2. Go to the release folder and delete everything except for the executable.
  3. In Qt Creator right click on the .pro file of your project and click on Open Command Prompt Here.
  4. Go to the release folder with the command cd release.
  5. Run the win deployment tool, this should be something similar to:

    C:\Qt\5.6\mingw49_32\bin\windeployqt.exe

  6. The release folder should now contain most of the necessary DLLs.
  7. Additionally (if you are using MinGW/gcc), copy the following dlls from the location of your compiler (C:\Qt\5.6\mingw49_32\bin) into the release folder: libgcc_s_dw2-1.dll, libwinpthread-1.dll, libstdc++-6.dll.
  8. Try to run the executable directly from the release folder, make sure it does not complain about any missing libraries.

Installation script

This section shows how to prepare the installation script for the release folder containing all the necessary DLLs.

Installing Qt Installation Framework

  1. Go to the following url: https://download.qt.io/official_releases/qt-installer-framework/ and download the latest edition release of the Qt Installer Framework for MS Windows, in our case 2.0.5/QtInstallerFramework-win-x86.exe.
  2. Install the framework. If the installation was successful, you should find an executable binarycreator.exe in the folder C:\Qt\QtIFW2.0.5\bin.

Optional: To add help for Qt Installer Framework into Qt Creator:

  1. In Qt Creator go to Tools -> Options -> Help.
  2. Click on the tab Documentation.
  3. Add the following file: C:\Qt\QtIFW2.0.5\doc\ifw.qch. An item org.qt-project.ifw.205 should appear in the list. You should now be able to call help for Qt the Installer Framework via the Help option in Qt Creator.

Configuring the installer via config.xml

To prepare the basic version of the installation script we are going to use an example provided by the Qt Installation Framework called startmenu. Firstly, we are going to configure the installer.

  1. Go to the folder C:\Qt\QtIFW2.0.5\examples, copy the directory startmenu into one of your working folders, e.g. Desktop or Documents.
  2. Open your copy of the folder startmenu and go to startmenu -> config -> config.xml.
  3. Open config.xml in any text editor and modify the text to match your project. The images below show how our input appears in the installer.
    <?xml version="1.0" encoding="UTF-8"?>
    <Installer>
        <Name>Reverse Polish Notation Calculator</Name>
        <Version>1.0</Version>
        <Title>Reverse Polish Notation Calculator</Title>
        <Publisher>Walletfox.com</Publisher>
        <StartMenuDir>RPN Calculator</StartMenuDir>
        <TargetDir>@HomeDir@/RPNCalculator</TargetDir>
    </Installer>
    
    <Name> application name that is added to the page name and introduction text
    <Version> application version number
    <Title> installer name displayed on the title bar
    <StartMenuDir> name of the default program group for the product in the Windows Start menu
    <TargetDir> default target directory
config.xml Title and Name

config.xml TargetDir

config.xml StartMenuDir

Providing data and creating package information file package.xml

In the next step, we are going to modify the installer package information file (package.xml) that specifies the components that are available for installation.

  1. Go to the folder startmenu -> packages -> org.qtproject.ifw.example -> data.
  2. Delete README.txt from the data folder.
  3. Move all the contents from your project release folder into this data folder.
  4. Go to the folder startmenu -> packages -> org.qtproject.ifw.example -> meta -> package.xml.
  5. Open package.xml in any text editor and modify the text to match your project data. In our case:
    <?xml version="1.0" encoding="UTF-8"?>
    <Package>
        <DisplayName>RPN</DisplayName>
        <Description>Calculator based on the Reverse Polish Notation</Description>
        <Version>1.0</Version>
        <ReleaseDate>2017-04-27</ReleaseDate>
        <Default>true</Default>
        <Script>installscript.qs</Script>
    </Package>
    
    <DisplayName> human-readable name of the component
    <Description> human-readable description of the component
    <Version> version number of the component
    <ReleaseDate> date when this component version was released
    <Default> true if it preselects the component in the installer
    <Script> the file name of the JavaScript file that is loaded to perform operations
package.xml Description, DisplayName and Default

Adding entries to the Start Menu via installscript.qs

  1. Go startmenu -> packages -> org.qtproject.ifw.example -> meta and open installscript.qs in Qt Creator.
  2. Modify the installscript.qs in the following manner: Change «@TargetDir@/README.txt» to @TargetDir@/ + the name of your executable (in this case, rpn_calculator.exe).
  3. Change «@StartMenuDir@/README.lnk» to @@StartMenuDir@/ + whatever you would like to appear in the Start Menu of MS Windows(in this case, RPN Calculator.lnk)
  4. Remove the keywords which handle icons, i.e. «iconPath=%SystemRoot%/system32/SHELL32.dll», «iconId=2».
  5. function Component()
    {
        // default constructor
    }
    
    Component.prototype.createOperations = function()
    {
        // call default implementation to actually install README.txt!
        component.createOperations();
    
        if (systemInfo.productType === "windows") {
            component.addOperation("CreateShortcut", "@TargetDir@/rpn_calculator.exe", "@StartMenuDir@/RPN Calculator.lnk",
                "workingDirectory=@TargetDir@");
        }
    }
    

Generating the installer

  1. In the command prompt go to the folder startmenu.
  2. Paste the following line into the command prompt:

    C:\Qt\QtIFW2.0.5\bin\binarycreator.exe —offline-only -c config/config.xml -p packages installer.exe

    Executable of the installer should now appear in the startmenu project folder.

  3. Try to run the installer. After a successful installation, you should find the application
    shortcut in the start menu of Windows. You should also find the executable and DLLs in the folder where you installed the application.
  4. You can uninstall the application via the Control Panel of MS Windows or via maintenancetool.exe that can be found in the folder where you installed the application.

Note: If you do not see the application icon in the Start menu of MS Windows, check that the line below appears in the .pro file of your project and that the application icon is of type .ico. This problem has nothing to do with the installation script.

win32:RC_ICONS += rpn_calculator.ico

Tagged: Qt

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Ldap windows server 2012 настройка
  • Windows прозрачный прокси сервер windows
  • Windows 11 поддержка процессоров ryzen
  • Windows terminal preview download
  • Как сделать монитор основным дисплеем на windows 10