Qt формат файла pro
При использовании Qt мы часто выполняем ряд утомительных настроек pro. Для облегчения понимания и поиска мы организуем часто используемые конфигурации.
| Заявление об авторском праве: одна поездка, две или три мили не могут быть воспроизведены без разрешения блоггера.
банкнота
CONFIG
Укажите параметры компилятора и конфигурацию проекта. Значения внутренне распознаются qmake и имеют особое значение.
Следующие значения конфигурации управляют флагами компиляции:
При использовании параметров отладки и выпуска (по умолчанию в Windows) проект будет обрабатываться три раза: один «мета» Makefile генерируется одновременно, а два других генерируются Makefile.Debug и Makefile.Release.
Позднее build_pass и соответствующая отладка или выпуск добавляются к опции CONFIG. Это позволяет ему выполнять специфичные для сборки задачи.
DEFINES
qmake добавляет значение этой переменной как макрос препроцессора C компилятора (опция -D).
Тогда вы можете использовать его в своем коде:
Часто можно указать специальные версии проекта (например, официальную версию, пробную версию), ограничения для некоторых специальных функциональных модулей (например, ключ) и так далее.
DEPENDPATH
Указывает на просмотр списка каталогов, которые разрешают зависимости, и используется при включении файлов.
DESTDIR
Укажите, где разместить целевой файл.
FORMS
Указанный файл пользовательского интерфейса (ссылка: Руководство по Qt Designer) обрабатывается uic перед компиляцией. Все зависимости, заголовочные файлы и исходные файлы, необходимые для создания этих файлов пользовательского интерфейса, автоматически добавляются в проект.
HEADERS
Укажите все заголовочные файлы в проекте.
qmake автоматически определит, нужен ли moc в классе заголовочных файлов, и добавит в проект соответствующие зависимости и файлы для генерации и связывания файлов moc.
INCLUDEPATH
Если путь содержит пробелы, его необходимо заключить в кавычки.
LIBS
Определяет список библиотек, связанных с проектом. Если вы используете флаги Unix -l (библиотека) и -L (путь к библиотеке), qmake правильно обрабатывает библиотеку в Windows (то есть передает полный путь к библиотеке компоновщику), библиотека должна существовать, и qmake ищет спецификацию -l Каталог, в котором находится библиотека.
Если путь содержит пробелы, вы должны включить путь в кавычки.
MOC_DIR
Укажите каталог, в котором находятся все промежуточные файлы из moc (заголовочный файл, содержащий макрос Q_OBJECT, преобразуется в стандартный каталог хранения файлов .h)
OBJECTS_DIR
Указывает каталог, в котором находятся все промежуточные файлы .o (.obj).
QT
Укажите модули, которые используют Qt в проекте. QT включает в себя ядро и графический интерфейс по умолчанию, чтобы гарантировать возможность создания стандартных приложений с графическим интерфейсом без дальнейшей настройки.
Если вы хотите построить проект, который не включает модуль Qt GUI, вы можете использовать оператор «- =».
Следующая строка создаст небольшой проект Qt:
Если вы хотите создать интерфейс, который использует XML и сетевые классы, вам необходимо включить следующие модули:
Если ваш проект является плагином Qt Designer, используйте значение uiplugin, чтобы указать, что проект встроен в библиотеку, но для конкретной поддержки плагина Qt Designer, пожалуйста, обратитесь к разделу: Сборка и установка плагина.
RCC_DIR
Укажите каталог выходного файла компилятора ресурсов Qt (файл .qrc преобразуется в каталог, где хранятся файлы qrc _ *. H).
RESOURCES
Укажите имя файла ресурсов (qrc), обратитесь к:Система ресурсов Qt
RC_FILE
Укажите имя файла ресурса приложения. Значение этой переменной обычно обрабатывается qmake или qmake.conf и редко нуждается в изменении.
RC_ICONS
Только для Windows, указанный значок должен быть включен в сгенерированный файл .rc. Это доступно только если не установлены ни переменные RC_FILE, ни RES_FILE.
SOURCES
Укажите все исходные файлы в проекте.
TARGET
Укажите имя файла назначения. Базовое имя файла проекта включено по умолчанию.
Вышеупомянутый проект сгенерирует исполняемый файл, myapp.exe под Windows и myapp под Unix.
TEMPLATE
Переменные шаблона сообщают qmake, какой make-файл сгенерировать для этого приложения.
TRANSLATIONS
Задает список файлов перевода (.ts), содержащих переведенный текст для пользовательского интерфейса.
UI_DIR
Укажите каталог, в который помещены все промежуточные файлы из uic (каталог, в который файлы .ui конвертируются в файлы ui _ *. H)
This chapter describes how to set up qmake project files for three common project types that are based on Qt: application, library, and plugin. Although all project types use many of the same variables, each of them uses project-specific variables to customize output files.
Platform-specific variables are not described here. For more information, see Qt for Windows - Deployment and Qt for macOS.
Building an Application
The app template tells qmake to generate a Makefile that will build an application. With this template, the type of application can be specified by adding one of the following options to the CONFIG variable definition:
Option | Description |
---|---|
windows | The application is a Windows GUI application. |
console | app template only: the application is a Windows console application. |
testcase | The application is an automated test. |
When using this template, the following qmake system variables are recognized. You should use these in your .pro file to specify information about your application. For additional platform-dependent system variables, you could have a look at the Platform Notes.
-
- A list of header files for the application. - A list of C++ source files for the application. - A list of UI files for the application (created using Qt Designer). - A list of Lex source files for the application. - A list of Yacc source files for the application. - Name of the executable for the application. This defaults to the name of the project file. (The extension, if any, is added automatically). - The directory in which the target executable is placed. - A list of any additional pre-processor defines needed for the application. - A list of any additional include paths needed for the application. - The dependency search path for the application. - The search path to find supplied files. - Windows only: A .def file to be linked against for the application.
You only need to use the system variables that you have values for. For example, if you do not have any extra INCLUDEPATHs then you do not need to specify any. qmake will add the necessary default values. An example project file might look like this:
Building a Testcase
A testcase project is an app project intended to be run as an automated test. Any app may be marked as a testcase by adding the value testcase to the CONFIG variable.
For testcase projects, qmake will insert a check target into the generated Makefile. This target will run the application. The test is considered to pass if it terminates with an exit code equal to zero.
The check target automatically recurses through SUBDIRS projects. This means it is possible to issue a make check command from within a SUBDIRS project to run an entire test suite.
Variable | Description |
---|---|
TESTRUNNER | A command or shell fragment prepended to each test command. An example use-case is a "timeout" script which will terminate a test if it does not complete within a specified time. |
TESTARGS | Additional arguments appended to each test command. For example, it may be useful to pass additional arguments to set the output file and format from the test (such as the -o filename,format option supported by QTestLib). |
Note: The variables must be set while invoking the make tool, not in the .pro file. Most make tools support the setting of Makefile variables directly on the command-line:
Testcase projects may be further customized with the following CONFIG options:
Option | Description |
---|---|
insignificant_test | The exit code of the test will be ignored during make check . |
Test cases will often be written with QTest or TestCase , but it is not a requirement to make use of CONFIG+=testcase and make check . The only primary requirement is that the test program exit with a zero exit code on success, and a non-zero exit code on failure.
Building a Library
The lib template tells qmake to generate a Makefile that will build a library. When using this template, the VERSION variable is supported, in addition to the system variables that the app template supports. Use the variables in your .pro file to specify information about the library.
When using the lib template, the following options can be added to the CONFIG variable to determine the type of library that is built:
Option | Description |
---|---|
dll | The library is a shared library (dll). |
staticlib | The library is a static library. |
plugin | The library is a plugin. |
The following option can also be defined to provide additional information about the library.
- VERSION - The version number of the target library. For example, 2.3.1.
The target file name for the library is platform-dependent. For example, on X11, macOS, and iOS, the library name will be prefixed by lib . On Windows, no prefix is added to the file name.
Building a Plugin
Plugins are built using the lib template, as described in the previous section. This tells qmake to generate a Makefile for the project that will build a plugin in a suitable form for each platform, usually in the form of a library. As with ordinary libraries, the VERSION variable is used to specify information about the plugin.
- VERSION - The version number of the target library. For example, 2.3.1.
Building a Qt Designer Plugin
Qt Designer plugins are built using a specific set of configuration settings that depend on the way Qt was configured for your system. For convenience, these settings can be enabled by adding designer to the QT variable. For example:
See the Qt Designer Examples for more examples of plugin-based projects.
Building and Installing in Debug and Release Modes
Sometimes, it is necessary to build a project in both debug and release modes. Although the CONFIG variable can hold both debug and release options, only the option that is specified last is applied.
Building in Both Modes
To enable a project to be built in both modes, you must add the debug_and_release option to the CONFIG variable:
The scope in the above snippet modifies the build target in each mode to ensure that the resulting targets have different names. Providing different names for targets ensures that one will not overwrite the other.
When qmake processes the project file, it will generate a Makefile rule to allow the project to be built in both modes. This can be invoked in the following way:
The build_all option can be added to the CONFIG variable in the project file to ensure that the project is built in both modes by default:
This allows the Makefile to be processed using the default rule:
Installing in Both Modes
The build_all option also ensures that both versions of the target will be installed when the installation rule is invoked:
It is possible to customize the names of the build targets depending on the target platform. For example, a library or plugin may be named using a different convention on Windows from the one used on Unix platforms:
The default behavior in the above snippet is to modify the name used for the build target when building in debug mode. An else clause could be added to the scope to do the same for release mode. Left as it is, the target name remains unmodified.
© 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.
Project files contain all the information required by qmake to build your application, library, or plugin. Generally, you use a series of declarations to specify the resources in the project, but support for simple programming constructs enables you to describe different build processes for different platforms and environments.
Project File Elements
The project file format used by qmake can be used to support both simple and fairly complex build systems. Simple project files use a straightforward declarative style, defining standard variables to indicate the source and header files that are used in the project. Complex projects may use control flow structures to fine-tune the build process.
The following sections describe the different types of elements used in project files.
Variables
In a project file, variables are used to hold lists of strings. In the simplest projects, these variables inform qmake about the configuration options to use, or supply filenames and paths to use in the build process.
qmake looks for certain variables in each project file, and it uses the contents of these to determine what it should write to a Makefile. For example, the lists of values in the HEADERS and SOURCES variables are used to tell qmake about header and source files in the same directory as the project file.
Variables can also be used internally to store temporary lists of values, and existing lists of values can be overwritten or extended with new values.
The following snippet illustrates how lists of values are assigned to variables:
The list of values in a variable is extended in the following way:
Note: The first assignment only includes values that are specified on the same line as the HEADERS variable. The second assignment splits the values in the SOURCES variable across lines by using a backslash (\).
The CONFIG variable is another special variable that qmake uses when generating a Makefile. It is discussed in General Configuration. In the snippet above, console is added to the list of existing values contained in CONFIG .
The following table lists some frequently used variables and describes their contents. For a full list of variables and their descriptions, see Variables.
Variable | Contents |
---|---|
CONFIG | General project configuration options. |
DESTDIR | The directory in which the executable or binary file will be placed. |
FORMS | A list of UI files to be processed by the user interface compiler (uic). |
HEADERS | A list of filenames of header (.h) files used when building the project. |
QT | A list of Qt modules used in the project. |
RESOURCES | A list of resource (.qrc) files to be included in the final project. See the The Qt Resource System for more information about these files. |
SOURCES | A list of source code files to be used when building the project. |
TEMPLATE | The template to use for the project. This determines whether the output of the build process will be an application, a library, or a plugin. |
The contents of a variable can be read by prepending the variable name with $$ . This can be used to assign the contents of one variable to another:
The $$ operator is used extensively with built-in functions that operate on strings and lists of values. For more information, see qmake Language.
Whitespace
Usually, whitespace separates values in variable assignments. To specify values that contain spaces, you must enclose the values in double quotes:
The quoted text is treated as a single item in the list of values held by the variable. A similar approach is used to deal with paths that contain spaces, particularly when defining the INCLUDEPATH and LIBS variables for the Windows platform:
Comments
Built-in Functions and Control Flow
qmake provides a number of built-in functions to enable the contents of variables to be processed. The most commonly used function in simple project files is the include() function which takes a filename as an argument. The contents of the given file are included in the project file at the place where the include function is used. The include function is most commonly used to include other project files:
Support for conditional structures is made available via scopes that behave like if statements in programming languages:
The assignments inside the braces are only made if the condition is true. In this case, the win32 CONFIG option must be set. This happens automatically on Windows. The opening brace must stand on the same line as the condition.
More complex operations on variables that would usually require loops are provided by built-in functions such as find(), unique(), and count(). These functions, and many others are provided to manipulate strings and paths, support user input, and call external tools. For more information about using the functions, see qmake Language. For lists of all functions and their descriptions, see Replace Functions and Test Functions.
Project Templates
The TEMPLATE variable is used to define the type of project that will be built. If this is not declared in the project file, qmake assumes that an application should be built, and will generate an appropriate Makefile (or equivalent file) for the purpose.
The following table summarizes the types of projects available and describes the files that qmake will generate for each of them:
Template | qmake Output |
---|---|
app (default) | Makefile to build an application. |
lib | Makefile to build a library. |
aux | Makefile to build nothing. Use this if no compiler needs to be invoked to create the target, for instance because your project is written in an interpreted language. |
Note: This template type is only available for Makefile-based generators. In particular, it will not work with the vcxproj and Xcode generators.
See Building Common Project Types for advice on writing project files for projects that use the app and lib templates.
When the subdirs template is used, qmake generates a Makefile to examine each specified subdirectory, process any project file it finds there, and run the platform's make tool on the newly-created Makefile. The SUBDIRS variable is used to contain a list of all the subdirectories to be processed.
General Configuration
The CONFIG variable specifies the options and features that the project should be configured with.
The project can be built in release mode or debug mode, or both. If debug and release are both specified, the last one takes effect. If you specify the debug_and_release option to build both the debug and release versions of a project, the Makefile that qmake generates includes a rule that builds both versions. This can be invoked in the following way:
Adding the build_all option to the CONFIG variable makes this rule the default when building the project.
Note: Each of the options specified in the CONFIG variable can also be used as a scope condition. You can test for the presence of certain configuration options by using the built-in CONFIG() function. For example, the following lines show the function as the condition in a scope to test whether only the opengl option is in use:
This enables different configurations to be defined for release and debug builds. For more information, see Using Scopes.
The following options define the type of project to be built.
Note: Some of these options only take effect when used on the relevant platform.
Option | Description |
---|---|
qt | The project is a Qt application and should link against the Qt library. You can use the QT variable to control any additional Qt modules that are required by your application. This value is added by default, but you can remove it to use qmake for a non-Qt project. |
x11 | The project is an X11 application or library. This value is not needed if the target uses Qt. |
The application and library project templates provide you with more specialized configuration options to fine tune the build process. The options are explained in detail in Building Common Project Types.
For example, if your application uses the Qt library and you want to build it in debug mode, your project file will contain the following line:
Declaring Qt Libraries
If the CONFIG variable contains the qt value, qmake's support for Qt applications is enabled. This makes it possible to fine-tune which of the Qt modules are used by your application. This is achieved with the QT variable which can be used to declare the required extension modules. For example, we can enable the XML and network modules in the following way:
Note: QT includes the core and gui modules by default, so the above declaration adds the network and XML modules to this default list. The following assignment omits the default modules, and will lead to errors when the application's source code is being compiled:
If you want to build a project without the gui module, you need to exclude it with the "- pre">
For a list of Qt modules that you can add to the QT variable, see QT.
Configuration Features
qmake can be set up with extra configuration features that are specified in feature (.prf) files. These extra features often provide support for custom tools that are used during the build process. To add a feature to the build process, append the feature name (the stem of the feature filename) to the CONFIG variable.
For example, qmake can configure the build process to take advantage of external libraries that are supported by pkg-config, such as the D-Bus and ogg libraries, with the following lines:
For more information about adding features, see Adding New Configuration Features.
Declaring Other Libraries
If you are using other libraries in your project in addition to those supplied with Qt, you need to specify them in your project file.
The paths that qmake searches for libraries and the specific libraries to link against can be added to the list of values in the LIBS variable. You can specify the paths to the libraries or use the Unix-style notation for specifying libraries and paths.
For example, the following lines show how a library can be specified:
The paths containing header files can also be specified in a similar way using the INCLUDEPATH variable.
For example, to add several paths to be searched for header files:
© 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.
.PRO файл является проектом QT дляУправление файлами кода, файлы ресурсов и т. Д. Файлы конфигурации。
QMKAE для файлов .PRO может генерировать файл makefile и компиляцию компиляции через makefile для завершения всего проекта.
.PRO файл пример кода
Выходной терминал
QT Creator предоставляет клемму печати для файла .pro. То есть «Synject Information», каждый раз, когда вы изменяете файл .PRO, нажмите «Сохранить», «Информация о профиле» печатает информационную подсказку в файле .pro.
Примечание
Суждение Qt версия
Пример: судействуя, соответствует ли текущая версия QT, она не соответствует версии версии для компиляции;
Как видно из вышеуказанного кода:
Ключевое слово | Интерпретация |
---|---|
QT_MAJOR_VERSION | Qt Основная версия номер |
QT_MINOR_VERSION | Qt версии номер |
QT_PATCH_VERSION | Qt Patch Version номер |
Тип печати информации
Ключевое слово | Интерпретация |
---|---|
message("This is a message.") | [Совет] Печать |
warning("This is a warning.") | [Предупреждение] Печать |
error("This is a error.") | [Неправильно] печатать |
Примечание: call. error() После этого Pro файл заканчивает это, error() Ни одно из последующих заявлений не будет сделано.
Значение других ключевых слов
Ключевое слово | Интерпретация |
---|---|
QT | Определяет модуль QT для использования (по умолчанию является CORE GUI, соответствует модулю QTCORE и QTGUI) |
TARGET | Укажите базовое имя файла исполняемого или библиотеки, которая не содержит никаких расширений, префиксов или номеров версий (по умолчанию - текущее имя каталога); |
TEMPLATE | Указывает, какой makefile генерируется для этого приложения; |
DEFINES | Список дополнительных программ для предварительной обработки, необходимых для приложений; |
SOURCES | Список всех исходных файлов в приложении; |
HEADERS | Файл заголовка C ++ (.h) в приложении; |
FORMS | Все файлы .ui в приложении (сгенерировано qt designer); |
DESTDIR | Поместите каталог цели исполняемой программы; |
INCLUDEPATH | Дополнительный список необходимых приложений |
DEPENDPATH | Путь поиска полагается на приложение |
CONFIG | Переменная конфигурации определяет параметры, которые вы хотите использовать, и библиотека, которую вы хотите подключиться к компилятору. |
VPATH | Найти путь поиска для дополнительных файлов |
DEF_FILE | Только нужно Windows: приложение, к которому подключено приложение. Def file |
RC_FILE | Только Windows требует: файл ресурсов приложения |
RES_FILE | Только нужно Windows: файл ресурса, который должен быть подключен приложением |
Ключевое слово Template имеет следующий тип
Шаблон ключевого слова Содержание | Интерпретация |
---|---|
app | Установите Makefile App. Это значение по умолчанию, поэтому, если шаблон не указан, это будет использоваться. |
lib | Создайте библиотеку Makefile. При использовании этого шаблона, помимо системной переменной в шаблоне «Приложение», также поддерживается версия. Вам необходимо использовать их в файле .pro, который определяет конкретную информацию для библиотеки. Версия - номер версии целевой библиотеки, например, 2.3.1. |
vcapp | Установите файл проекта Visual Studio для приложения. |
vclib | Создайте файл проекта Visual Studio библиотеки. |
subdirs | Это специальный шаблон, который создает makefile, который входит в определенный каталог и генерирует makefile для файла проекта и вызовов. Можно идентифицировать только одну системную переменную поддразти в этом шаблоне. Эта переменная содержит список подкаталогов, которые содержат файлы проекта, которые будут обработаны. Название этого файла проекта является то же имя, что и поддиректор, поэтому qmake может его найти. Например, если подслуги - «MyApp», файл проекта в этом каталоге должен быть называется myapp.pro. |
Ключевые слова Config имеют следующие типы
Настройка переменных Укажите параметры, которые вы хотите использовать с помощью компилятора, и библиотекой, которую вы хотите подключиться. В переменной конфигурации можно добавить в переменной конфигурации, но только следующие параметры могут быть идентифицированы QMake.
QT Учитесь при выполнении 1. Файлы управления проектами (.pro) и подробные объяснения их функций.
QT Учитесь при выполнении 1. Файлы управления проектами (.pro) и подробные объяснения их функций.
Общая версия проекта QT будет содержать следующие типы файлов
- Файл управления проектом samp2_1.pro, файл, в котором хранятся настройки проекта.
- Основной файл записи программы main.cpp, программный файл, реализующий функцию main ().
- Файл интерфейса окна widget.ui - это файл компонентов и их расположение в окне, хранящийся в формате XML.
- widget.h - файл заголовка созданного класса формы,
- widget.cpp - это файл реализации, который определяет класс в widget.h. В C ++ любая форма или компонент интерфейса инкапсулируется классом.Класс обычно имеет файл заголовка (файл .h) и исходный файл (файл .cpp).
Я не понимал .pro, когда работал над проектом, и было тяжело двигаться Это мой кровный урок. В этом разделе будет использоваться .pro, который я использовал в процессе работы над проектом.
Информация о файле обобщается и передается вам.
Файл с суффиксом «.pro» - это файл управления проектом, а имя файла - это имя проекта, например samp2_1.pro в этом проекте. Ниже приводится содержимое файла samp2_1.pro.
Общий код
Файл управления проектом используется для записи некоторых настроек проекта, а также для организации и управления включенными в проект файлами.
«Qt + = core gui» означает, что в проект добавлен модуль core gui. Core gui - это модуль библиотеки классов, используемый Qt для разработки графического интерфейса пользователя.Если вы создаете консольное приложение, вам не нужно добавлять основной графический интерфейс.
Библиотека классов Qt организует классы различных функций в виде модулей и добавляет в проект соответствующую поддержку модуля библиотеки классов в соответствии с функциональными требованиями, задействованными в проекте. Например, если в проекте используется класс, связанный с операциями с базой данных, необходимо использовать модуль sql, а в файл pro необходимо добавить следующую строку:
«TARGET = samp2_1» представляет имя сгенерированного целевого исполняемого файла, то есть исполняемого файла, сгенерированного после компиляции, является samp2_1.exe.
«TEMPLATE = app» означает, что в проекте используется шаблон app, который является общим приложением.
Следующие ниже ИСТОЧНИКИ, ЗАГОЛОВКИ, ФОРМЫ записывают имена исходных программных файлов, файлов заголовков и файлов форм (файлов .ui), содержащихся в проекте. Эти списки файлов автоматически добавляются в файлы управления проектом Qt Creator, и пользователям не нужно изменять их вручную. При добавлении файла в проект или удалении файла из проекта запись в файле управления проектом будет автоматически изменена.
Вторая строка в samp2_1.pro:
Это оператор условного выполнения, что означает, что, когда основная версия Qt больше 4, будет добавлен модуль виджетов.
Мой часто используемый код
Изменить каталог файлов
Когда имеется много файлов .cpp и .h, необходимо поместить их в разные папки для облегчения управления. Я обычно помещаю файл .h в папку include, а файл .cpp - в папку src.
Здесь мы расскажем вам о методах, которые необходимо изменить в .pro.
$$ PWD представляет текущий путь, то есть путь, по которому находится файл .pro
others
Когда проект становится больше, компиляция QT происходит очень медленно, и обязательно увеличивать скорость компиляции. Это застряло у меня надолго. Я нашел в Интернете учебные пособия и попробовал их на своем компьютере, но всегда компилировал их. Чтобы завершить это, потребовалось много времени. В следующий раз я напишу блог о том, как ускорить компиляцию, чтобы поделиться с вами.
Читайте также: