Qt5 Interface/ru

From Free Pascal wiki
Jump to navigationJump to search

English (en) русский (ru)

Qt logo 2013.svg

Эта статья относится только к Qt5 widgetset.

См. также: Multiplatform Programming Guide

Введение

Этот интерфейс основан на Qt 5 (тестируется Qt 5.6.2). Для получения документации, исправлений и загрузки перейдите на Project (установщик доступен на странице загрузки 5.6.2). Lazarus с интерфейсом Qt5 (qt5-lcl) можно использовать в Windows 32/64, Linux x32/x64/arm, macOS x64 (Cocoa). Наборы виджетов Qt5 были доступны в Lazarus, начиная со стабильной версии 1.8.

Light bulb  Примечание: С недавних пор российские IP стали баниться. Такова печальная реальность. Поэтому лучше используйте прокси и скачивайте оффлайн инсталлятор. Устанавливать с него необходимо при отключенном интернете и именно по той же причине

Большинство современных дистрибутивов Linux имеют подходящий Qt5 в своих стандартных репозиториях, однако выпуски с долгосрочной поддержкой имеют проблемы из-за их возраста. Ubuntu 16.04 имеет слишком старый QT5.5, а 18.04 содержит проблемную версию libQt5Pas, которую необходимо заменить, см. ниже.


Также подробнее об установке "с нуля" под Windows и Linux можно почитать здесь (подойдет также для qt6)


Windows

Бинарный файл Q5Pas1.dll доступен здесь

а вот готовой 64-битной версии нет.

Сборка основана на MinGW, поэтому вы можете использовать библиотеку MinGW Qt (например, qt-opensource-windows-x86-mingw492-5.6.2.exe).

Если вам нужно собрать проект cbindings, вам понадобится MinGW. Вы можете использовать MinGW из пакета Qt (qt-opensource-windows-x86-mingw492-5.6.2.exe) — это необязательный компонент установки пакета Qt.

Запуск и развертывание

Проект должен быть развернут с использованием Q5Pas1.dll.

Файлы .dll Qt5, которые необходимо развернуть, см. в руководствах по Qt5: https://doc.qt.io/qt-5/windows-deployment.html.

Для пакета на основе MinGW потребуется следующий набор библиотек DLL для запуска одного проекта FORM.

Эти библиотеки DLL поставляются с пакетом Qt5 (можно найти в C:\QtQt5.6.2\5.6\mingw49_32\bin).

Qt5Core.dll
Qt5PrintSupport.dll
Qt5Widgets.dll
Qt5Gui.dll
Qt5Network.dll
libstdc++-6.dll
libwinpthread-1.dll
libgcc_s_dw2-1.dll

Для сборок, основанных на MSVC, а не на MinGW, может потребоваться другой набор dll(не Qt5). Обратите внимание, что Qt5Pas1.dll собран для Qt5-5.6.2, но Qt5Pas1.dll можно использовать с любым Qt5 > 5.6.2.

Linux

Lazarus

Image of Qt5 selected

Lazarus «из коробки» в Linux использует и создает приложения для GTK2. Он не помечен как имеющий зависимость от Qt5, поэтому, если вы хотите создавать приложения Qt5 или собирать версию Lazarus для Qt5, вам, вероятно, потребуется установить «libQt5Pas-dev», используя репозиторий вашего дистрибутива:

  • Fedora, Mageia - sudo dnf install qt5pas-devel <enter>
  • Ubuntu, Debian — sudo apt install libqt5pas-dev <enter>

это добавит необходимые библиотеки Qt5 в качестве зависимостей, обычно около 50 МБ в системе, в которой нет существующих потребностей Qt5. Если вы хотите использовать версию Lazarus для Qt5, выполните сборку из исходного кода с помощью такой команды, как

 make bigide LCL_PLATFORM=qt5 <enter>

но обратите внимание, что по умолчанию GTK2 Lazarus с удовольствием создаст для вас приложения Qt5.

В Lazarus, чтобы выбрать сборку приложения Qt5, сделайте так: Projects --> ProjectOptions --> Additions and Overrides, нажмите Set "LCLWidgetType" и выберите Qt5 для текущего режима сборки. А еще лучше добавить специальный режим сборки для Qt5, может быть, релиз и отладку.

Light bulb  Примечание: если вы устанавливаете Lazarus, используя версию Lazarus вашего дистрибутива, вам может потребоваться специально запросить компоненты Qt5 LCL. Если вы устанавливаете из исходного кода, вы получите намного больше с самого начала.

Не забудьте, что при релизе вашего приложения оно должно быть помечено как зависимое от libqt5pas1.

libqt5pas

libqt5pas — это библиотека, связывающая Qt5 и ваше приложение Lazarus. Более новые дистрибутивы (U20.04, Debian Buster и т.д.) имеют рабочие версии, доступные в их репозиториях. Отметьте свое приложение как зависимое от libqt5pas1 и все будет в порядке. Вам, как разработчику, использующему Qt5, также понадобится libqt5pas-dev, как упоминалось выше.

Light bulb  Примечание: если вы используете версию Lazarus более позднюю, чем 2.2.0, вам (и вашим конечным пользователям) потребуется libQt5Pas выше или равной 1.2.10. Дистрибутивам потребуется некоторое время, чтобы обновить версию, которую они распространяют, поэтому либо создайте свою собственную, либо используйте неофициальные https://github.com/davidbannon/libqt5pas/releases/latest debs и rpms, как указано ниже. Помните, что вашим конечным пользователям тоже нужна версия 1.2.10!

Использование вашего репозитория дистрибутивов -

  • Fedora, Mageia - sudo dnf install qt5pas<enter>
  • Ubuntu, Debian - sudo apt install libqt5pas1 <enter>


Проблема с версией?

Версия libQt5Pas вызовет проблемы у следующих людей, помните, что это влияет на вас, как на разработчика, и на ваших конечных пользователей.

  • Пользователи очень старых дистрибутивов Linux, таких как Ubuntu 16.04 - жаль, нет решения, не используйте Qt5, если вам нужна поддержка таких операционных систем.
  • Старые дистрибутивы Linux, такие как U18.04, официально поддерживаются до 2023 года, но используют неподходящий libQt5Pas. Вы увидите сбой, если ваше приложение использует TMemo. Замените существующий libQt5Pas.
  • Текущие дистрибутивы LTS, такие как 20.04 (и, возможно, 22.04, Debian Bullseye и т. д.), будут иметь libQt5Pas более ранней, чем 1.2.10, и это проблема, если вы используете версию Lazarus более позднюю, чем 2.2.0. Опять же, вы можете заменить существующий libQt5Pas

Заменить свой libQt5Pas?

Два варианта: используйте Deb- или RPM-пакеты из https://github.com/davidbannon/libqt5pas/releases/latest — вы должны убедиться, что ваш менеджер пакетов не возражает, или даже заменить ваш новый сияющий файл другим из предпочитаемого дистрибутива. Пишите на форуме, если вам нужно что-то кроме 64-битных Deb и RPM (Signing, 32bit, Pacman и т.д.). Установите, например, с помощью

 sudo apt install ./libqt5pas1_2.10-0_amd64.deb <enter> 

Как разработчику, вам также понадобится dev-пакет, удалите существующий, если он есть.

Secondly, the Lazarus source has the code to build your own, you will need gcc and a few other things, documented in the README.txt. Then copy the new library over top of your existing libQt5Pas1 (as root of course)

Note 1 that these two deb packages are made for Ubuntu 18.04 (or later), they will not help at all on Ubuntu 16.04 as its main Qt5 libraries are too old.

Note 2 Ubuntu will constantly overwrite this pair of updated packages via it's 'unattended update' tool. You must blacklist the packages to force the unattended update tool from undoing your good work.

Systems using Wayland

Some distributions us Wayland by default (eg the default Fedora with a GNOME desktop) and QT5 does not work with Wayland. You will receive a message like:

QSocketNotifier: Can only be used with threads started with QThread
[FORMS.PP] ExceptionOccurred
....

Logout, from the login screen click the small gear symbol, select "GNOME on XOrg". Log back in again.

There is, apparently a Wayland plugin for Qt5, for the brave - https://wayland.freedesktop.org/qt5.html

Qt5 Colours

On Linux, sometimes Qt5 apps will inherit the colours it uses from the Desktop/OS. However this does not always work and appears to be Distribution / Desktop dependent. With the current fad of Dark Themes, a more reliable approach is to use qt5ct. qt5ct appears to be in most distribution's repository and is a quick and easy install. When you run it, it opens on the "Appearance" tab, for a Dark Theme, choose Palette = Custom, Color Scheme = Darker. Click "Apply" and "OK" to close the app.

qt5ct dark.png

Did you note the message across the top, "The application is not configured correctly" ? What it is worried about is that you have not added the environment variable setting that will tell your app to use the colours you just set. You can set it for just one application by setting it in the application's command line :

QT_QPA_PLATFORMTHEME=qt5ct myapplication

That may be added to the app's Desktop file or maybe you edit the menu entry. The alternative is to add it /etc/environment (obviously without the application's name) so it is automatically set for all apps, you need to logout and back in again. Adding an entry into your own .bashrc is not quite appropriate in that GUI apps started from the menu for example will not be told about it. Note: On Debian installing qt5ct automatically add QT_QPA_PLATFORMTHEME to environment variables.

Why Qt5 instead of GTK ?

Good question ! Most Linux Lazarus applications are built using the default GTK2. The various Linux distributions are delivering fewer and fewer GTK2 apps, generally 'upgrading' to GTK3. However, the Lazarus GTK3 interface still needs some work and its not ready for production systems yet. Until late 2019, this has not mattered much, GTK2 works fine. But Ubuntu19.10 does not have GTK2 libraries installed by default and Xfce has announced its next release will be GTK2 free, apparently many distributions are looking to drop GTK2 from their default kits. While you can still install GTK2, its pretty big....

Qt5 is an obvious solution, its already installed on distros like Fedora 30 plus, its a relatively lightweight addition to Ubuntu, only 48Meg compared with GTK2's 445Meg. If you mark your application dependent on libqt5pas then it will be installed at the same time, bringing along the other qt5 files if necessary. Manually installing libqt5pas with your package manager (as long as it resolves dependencies!) will also work.

Clearly, Qt based distributions, ones using Plasma or KDE as a desktop will require only libqt5pas.

macOS (64-bit)

The following steps have been tested with macOS 10.13.6 (High Sierra), Xcode command line tools 10.0.0 (no Xcode required), Lazarus 1.8.4 and minimum Qt 5.6.2 (Qt 5.12.xx works without problems too).

After installing Qt 5.6.2 (see above), open up a terminal window and run these commands (paths may vary):

export LazarusDir=/Developer/Lazarus
export QtDir=~/Qt5.6.2
cd $LazarusDir/lcl/interfaces/qt5/cbindings
export PATH=$QtDir/5.6/clang_64/bin:$PATH
qmake

If qmake fails with the following error:

xcode-select: error: tool 'xcodebuild' requires Xcode, but active developer directory '/Library/Developer/CommandLineTools' is a command line tools instance

it does not mean that you have to install Xcode. See Qt without Xcode for a workaround and try running qmake again. (The Xcode dependency seems to be fixed in Qt 5.9.4 or maybe earlier.)

Proceed the build process with the following commands:

make
make install

It may be helpful to add symlinks to the Qt5Pas.framework and other *.framework files (so no modifications to the path are required):

cd /Library/Frameworks/
sudo ln -s $QtDir/5.6/clang_64/lib/*.framework .

Remember that Qt5 is 64 bit, so in Lazarus under Tools - Options - Environment, you need to change Compiler Executable from /usr/local/bin/ppc386 to /usr/local/bin/ppcx64 . With ppc386, you would later get the following errors when compiling your Lazarus projects:

Error: linker: Undefined symbols for architecture i386:
Error: linker: "_QAbstractButton_click", referenced from:
[...]
ld: symbol(s) not found for architecture i386

Finally, create a new Lazarus project (or open an existing one), open Project - Project options - Compiler options - Additions and overrides, set LCLWidgetType:=qt5 . You should now be able to compile your project with the Qt5 widget set.

Example Project

See First Steps with Lazarus Qt5 interface for an example project for Win32, Win64, macOS (64 bit) and Linux (64 bit).

Other Interfaces

Platform specific Tips

Interface Development Articles