Na primeira parte da série vimos como configurar o ambiente e gerar uma distribuição Linux Embarcado com Qt5 para Raspberry Pi 2 usando aceleração gráfica por hardware com o Yocto Project.
Agora vamos aprender como gerar e configurar as ferramentas necessárias para o desenvolvimento de aplicações Qt que serão executadas no nosso target, a Raspberry Pi 2. Basicamente precisaremos de uma toolchain contendo os utilitários e bibliotecas para podermos “cross-compilar” as aplicações desenvolvidas através da IDE Qt Creator.
Gerando a Toolchain para Qt5
É importante que você tenha realizado todos passos descritos no primeiro artigo da série.
Para gerarmos a toolchain devemos carregar as variáveis de ambiente do Yocto e instruí-lo a construir a toolchain para o Qt5.
cd ~/yocto . poky-fido/oe-init-build-env build-fido bitbake meta-toolchain-qt5
O instalador da toolchain gerado está disponível em: ~/yocto/build-fido/tmp/deploy/sdk/
e serve tanto para construção de aplicações Qt5 quanto para aplicações Linux que não utilizam o Qt.
Instalando a Toolchain
Vamos executar o script com a opção de instalação no caminho padrão sugerido.
# Para Host Linux 64bits ~/yocto/build-fido/tmp/deploy/sdk/poky-glibc-x86_64-meta-toolchain-qt5-cortexa7hf-vfp-vfpv4-neon-toolchain-1.8.sh # Para Host Linux 32bits ~/yocto/build-fido/tmp/deploy/sdk/poky-glibc-i686-meta-toolchain-qt5-cortexa7hf-vfp-vfpv4-neon-toolchain-1.8.sh
Após a instalação nossa toolchain estará disponível em: /opt/poky/1.8/ .
Instalando o Qt Creator
Vamos baixar a versão 3.4.0 e instala-lá utilizando as opções padrão sugeridas:
# Para Host Linux 64bits: wget https://download.qt.io/official_releases/qtcreator/3.4/3.4.0/qt-creator-opensource-linux-x86_64-3.4.0.run -P ~/Downloads # Para Host Linux 32bits: wget https://download.qt.io/official_releases/qtcreator/3.4/3.4.0/qt-creator-opensource-linux-x86-3.4.0.run -P ~/Downloads # Executando o Instalador # Host 64bits chmod +x ~/Downloads/qt-creator-opensource-linux-x86_64-3.4.0.run ~/Downloads/qt-creator-opensource-linux-x86_64-3.4.0.run # Host 32bits chmod +x ~/Downloads/qt-creator-opensource-linux-x86-3.4.0.run ~/Downloads/qt-creator-opensource-linux-x86-3.4.0.run
Configurando o Qt Creator
Vamos realizar as configurações necessárias para que o Qt Creator utilize a toolchain que geramos. Feche o programa caso ele esteja aberto.
A primeira coisa a ser feita é adicionar as variáveis de ambiente da toolchain no script de inicialização do Qt Creator. Para isso adicione o conteúdo abaixo na primeira linha do arquivo ~/qtcreator-3.4.0/bin/qtcreator.sh:
source /opt/poky/1.8/environment-setup-cortexa7hf-vfp-vfpv4-neon-poky-linux-gnueabi
O resultado final do arquivo ~/qtcreator-3.4.0/bin/qtcreator.sh. deve ser:
source /opt/poky/1.8/environment-setup-cortexa7hf-vfp-vfpv4-neon-poky-linux-gnueabi
#! /bin/sh
makeAbsolute() {
case $1 in
/*)
# already absolute, return it
echo "$1"
;;
*)
# relative, prepend $2 made absolute
echo `makeAbsolute "$2" "$PWD"`/"$1" | sed 's,/\.$,,'
;;
esac
}
me=`which "$0"` # Search $PATH if necessary
if test -L "$me"; then
# Try readlink(1)
readlink=`type readlink 2>/dev/null` || readlink=
if test -n "$readlink"; then
# We have readlink(1), so we can use it. Assuming GNU readlink (for -f).
me=`readlink -nf "$me"`
else
# No readlink(1), so let's try ls -l
me=`ls -l "$me" | sed 's/^.*-> //'`
base=`dirname "$me"`
me=`makeAbsolute "$me" "$base"`
fi
fi
bindir=`dirname "$me"`
libdir=`cd "$bindir/../lib" ; pwd`
LD_LIBRARY_PATH=$libdir:$libdir/qtcreator${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
export LD_LIBRARY_PATH
exec "$bindir/qtcreator" ${1+"$@"}
Agora vamos executar o Qt Creator. É importante dizer que SEMPRE que formos abrir o programa utilizaremos o comando abaixo, caso contrário o Qt Creator não funcionará corretamente com a toolchain gerada:
~/qtcreator-3.4.4/bin/qtcreator.sh
A figura abaixo mostra a tela inicial do aplicativo:
Agora vamos criar um Kit contendo as informações do nosso target (Raspberry Pi 2) e da nossa toolchain. Siga os passos descritos abaixo:
1) Menu "Tools"-> Submenu "Options" 2) Opção "Build & Run" -> Aba "Compilers" ->Botão "Add" -> Opção "GCC" Name: Poky G++ -> Apply Compiler path: /opt/poky/1.8/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-g++ Botão "Apply" 3) Opção "Build & Run" -> Aba "Debuggers" -> Botão "Add" Name: Poky GDB Path: opt/poky/1.8/sysroots/x86_64-pokysdk-linux/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-gdb Botão "Apply" 4) Opção "Build & Run" -> Aba "Qt Versions" -> Botão "Add" Filename: /opt/poky/1.8/sysroots/x86_64-pokysdk-linux/usr/bin/qt5/qmake Version Name: Qt 5.4.1 (qt5) Botão "Apply" 5) Opção "Build & Run" -> Aba "Kits" -> Botão "Add" Name: Rpi2 Device Type: Generic Linux Device Sysroot: /opt/poky/1.8/sysroots/cortexa7hf-vfp-vfpv4-neon-poky-linux-gnueabi Compiler: Poky G++ Debugger: Poky GDB Qt Version: Qt 5.4.1 (qt5) Botão "Make Default" Botão "OK"
Ao final desses procedimentos devemos ter a tela de configuração das opções “Build & Run” semelhante a essa:
Compilando uma aplicação
Como não poderia deixar de ser, vamos criar uma aplicação “Hello World”. Execute os seguintes comandos no shell:
mkdir ~/qt5-helloworld
echo -e 'TEMPLATE = app\nTARGET = hello\nDEPENDPATH += .\nINCLUDEPATH += .\n\nQT += widgets\n\nSOURCES += hello.cpp' > ~/qt5-helloworld/helloworld.pro
echo -e '#include <QApplication>\n#include <QLabel>\n\nint main(int argc, char *argv[])\n{\n QApplication app(argc, argv);\n QLabel *label = new QLabel("Hello Qt!");\n label->show();\n return app.exec();\n}
' > ~/qt5-helloworld/hello.cpp
Teremos um arquivo de projeto ~/qt5-helloworld/helloworld.pro:
TEMPLATE = app TARGET = hello DEPENDPATH += . INCLUDEPATH += . QT += widgets SOURCES += hello.cpp
E um código fonte da aplicação ~/qt5-helloworld/hello.cpp:
#include <QApplication>
#include <QLabel>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QLabel *label = new QLabel("Hello Qt!");
label->show();
return app.exec();
}
Vamos importar nosso projeto para dentro do Qt Creator. Para isso, vá em “File” -> “Open File or Project”, e selecione o arquivo ~/qt5-helloworld/helloworld.pro.
Na próxima tela aparecerá qual Kit deverá ser utilizado, se você marcou o Kit Rpi2 como default (“Make Default”) na seção anterior ele já estará selecionado. Para finalizar clique em “Configure Project”.
Agora vamos construir a aplicação em “Build” -> “Build Project helloworld”
Testando a aplicação
Copie o binário gerado pelo Qt Creator em ~/qt5-helloworld/build-qt5-helloworld-Rpi2-Debug/hello para a raíz de um pendrive ou envie via scp para a placa.
Insira o pendrive na Raspberry Pi 2, plugue um cabo conversor USB Serial e abra uma conexão serial.
Insira o microSD card gerado na primeira parte dessa série, conecte a Rpi 2 a uma TV através de uma cabo HDMI, conecte o pendrive com o binário gerado e energize a placa, logue como root e execute os seguintes comandos:
mount /dev/sda1 /media /media/hello -platform eglfs
Note que rodamos a aplicação com os parâmetros “-platform eglfs”, isso indica ao Qt que ele deve rodar utilizando o plugin de plataforma EGLFS.
A TV ficará com a seguinte imagem:
Notem que está escrito no canto esquerdo da tela a frase: “Hello Qt!“
Conclusão
Com ambas as partes desse tutorial é possível gerar uma distribuição Linux embarcado customizado usando o Qt5 com aceleração gráfica por hardware para a Raspberry Pi 2 e desenvolver aplicações sem muitas complicações.
Se você é novato no mundo de programação Qt, sugiro que dê uma lida no material Qt for beginners.






Olá Diego,
Realizei passo a passo deste tutorial, mas durante a compilação, o Qt apresenta o seguinte erro:
c: command not found
Ao que me parece, o compilador não está configurado, mas está. Fui lá em Tools, options, build & run e configurei o compiler, debuggers, Qt version e Kits, mesmo assim, o erro não desaparece.
Sabe o que pode estar acontecendo?
Ola Atila,
Eu tive esse mesmo problema, ai descobri que o caminho da variável environment-setup-cortexa7hf-vfp-vfpv4-neon-poky-linux-gnueabi estava incorreto. Depois de colocar o caminho correto, funcionou.
Ola vinifr,
O arquivo environment-setup-cortexa7hf-vfp-vfpv4-neon-poky-linux-gnueabi se encontra na pasta /opt/poky/1.8.
Em qual arquivo ou onde consigo editar o caminho desta variável para que fique correto?
;D
Dentro do arquivo qtcreator.sh. No meu caso, no artigo estava /opt/poky/1.6.2, mas a versão que instalei era 1.6.3. Mas isso na Raspberry B: https://embarcados.com.br/raspberry-pi-qt5-yocto-parte-2/
Muito obrigado! Consegui resolver o problema com a sua ajuda!
Abraços!
In Figura 2 in the Device field, I don’t have any options. Do I need to add a device clicking Manage… or will it be unnecessary?
Click on manage and create a new one.
It’s nit this tutorial but you can configure extra settings do connect to the board and perform remote debugging, for example.
Until I figure out the
meta-toolchain-qt5build issue, I would like to try out Wayland see if how it does withQtWebEngine.So now I have
DISTRO_FEATURES_remove = "x11"in my~/yocto/build/conf/local.confand I addedqtwaylandmodule to the image. Well Is that the correct way to do it? (it’s compiling so far).Looks I may need to do something else to add the Wayland plugin for Qt. Any pointers?
Joel,
As far as I know there isn’t any support for wayland on Rpi.
I don’t have knowledge on Wayland, sorry.
I think I remember trying some test image a couple of months ago. Nevermind, this is really not critical for me. I was just interested, but I think you are right.
FYI here a link about Weston Wayland
https://wayland.freedesktop.org/raspberrypi.html
**Part 1** seems to have succeeded well with QtWebEngine + QML plugin. I will test again now. I still got a problem with toolchain. I hope I haven’t missed something this time. I have bitbake meta-toolchain-qt5 ERROR: Unable to install packages. Command '/home/otto/yocto/build/tmp/sysroots/x86_64-linux/usr/bin/opkg-cl -f /home/otto/yocto/build/tmp/work/cortexa7hf-vfp-vfpv4-neon-poky-linux-gnueabi/meta-toolchain-qt5/1.0-r0/opkg.conf -o /home/otto/yocto/build/tmp/work/cortexa7hf-vfp-vfpv4-neon-poky-linux-gnueabi/meta-toolchain-qt5/1.0-r0/sdk/image/opt/poky/1.8/sysroots/cortexa7hf-vfp-vfpv4-neon-poky-linux-gnueabi --force_postinstall --prefer-arch-to-version install packagegroup-core-standalone-sdk-target-dbg packagegroup-core-standalone-sdk-target packagegroup-qt5-toolchain-target' returned 255: Installing packagegroup-core-standalone-sdk-target-dbg (1.0-r8) on root. ... ... Configuring packagegroup-core-standalone-sdk-target. Collected errors: * satisfy_dependencies_for: Cannot satisfy the following dependencies for packagegroup-qt5-toolchain-target: * libx11-6 (>= 1.6.2) * libxcb1 (>= 1.11) * libxau6 (>= 1.0.8) * libxdmcp6 (>= 1.1.1) * * opkg_install_cmd: Cannot install package packagegroup-qt5-toolchain-target. ERROR: Function… Leia mais »
Do you have added this line to local.conf?
DISTRO_FEATURES_remove = “x11 wayland”
Yeah I did, this is what I added at the top of the default file … but my “default” has a lot more line that I didn’t touch … may be that’s the issue
otto@Marcus Vinícius Martins Meneses:~/yocto/build/conf$ ls -al local.conf
-rw-r--r-- 1 otto otto 10259 Jun 11 06:39 local.conf
MACHINE = "raspberrypi2"
LICENSE_FLAGS_WHITELIST="commercial license"
DISTRO = "poky"
DL_DIR = "${TOPDIR}/../dl"
PACKAGE_CLASSES = "package_ipk"
DISTRO_FEATURES_remove = "x11 wayland"
# Set Rpi GPU Memory to 128MB
GPU_MEM = "128"
still fighting this issue (even on a Sunday), I am guessing that it should have been straight forward. At the top of the log I found this additional message that may be relevant, but it didn’t raise a hint on my side. May be it does on yours. otto@Marcus Vinícius Martins Meneses:~/yocto/build$ bitbake meta-toolchain-qt5 Loading cache: 100% |##############################################################################################################################################################################################| ETA: 00:00:00 Loaded 2025 entries from dependency cache. NOTE: Resolving any missing task queue dependencies Build Configuration: BB_VERSION = "1.26.0" BUILD_SYS = "x86_64-linux" NATIVELSBSTRING = "Debian-7.8" TARGET_SYS = "arm-poky-linux-gnueabi" MACHINE = "raspberrypi2" DISTRO = "poky" DISTRO_VERSION = "1.8" TUNE_FEATURES = "arm armv7a… Leia mais »
OK my 2 cents is that your Ubuntu 14.04 environment has the correct version of
libx11-6 i.e. >= 1.6.2, I think it mysteriously needs it even if removed from the distro. I hope this is not a completely silly diagnose.Do you mind running this command on your machine?
$ apt-cache policy libx11-6
Here it is:
apt-cache policy libx11-6
libx11-6:
Installed: 2:1.6.2-1ubuntu2
I’ve added this package installation on the part 1 of this series.
Ok I have now found out why my build is failing. Debian 7.8 won’t install
libx11-6 >= 1.6.2, I think I will upgrade my build machine to Jessie or find another computer. Thanks!Upgraded to Debian 8.1 Jessie, deleted my tmp, and started over. The RPi2 image built fine (Tutorial Part 1), but the I am getting the same message when bitbake meta-toolchain-qt5. Collected errors: * satisfy_dependencies_for: Cannot satisfy the following dependencies for packagegroup-qt5-toolchain-target: * libx11-6 (>= 1.6.2) * libxcb1 (>= 1.11) * libxau6 (>= 1.0.8) * libxdmcp6 (>= 1.1.1) * * opkg_install_cmd: Cannot install package packagegroup-qt5-toolchain-target. libx11-6, libxau6, libxdmcp6 satisfy the dependency rules, but not libxcb1. otto@Marcus Vinícius Martins Meneses:~/yocto/build$ apt-cache policy libxcb1 libxcb1: Installed: 1.10-3+b1 Candidate: 1.10-3+b1 Version table: *** 1.10-3+b1 0 500 https://ftp.us.debian.org/debian/ jessie/main amd64 Packages 500 https://http.debian.net/debian/ jessie/main amd64… Leia mais »
Sorry,
But I don’t use Debian.
No worries. May be someone else here can help. I am going to try Ubuntu 14.04! 😉 Cheers mate
BTW Would you know I list I could post my
meta-qt5question? It puzzles me that I can’t get to build my toolchain on Debian 8.1. Nevermind.This one:
https://lists.openembedded.org/mailman/listinfo/openembedded-core
Did you tried on Ubuntu 14.04?
not yet, actually we are buying a machine for that purpose. Hence trying lists, just in case there is a hack. Cheers
On Ubuntu 14.04 the toolchain took about 4 hours to build, got a few WARNINGs … hopefully nothing critical. Thx joel@linux-Lenovo-G50-70:~/yocto/build-fido$ bitbake meta-toolchain-qt5 Loading cache: 100% |######################################################################################################################################################| ETA: 00:00:00 Loaded 2025 entries from dependency cache. Parsing recipes: 100% |####################################################################################################################################################| Time: 00:00:00 Parsing of 1547 .bb files complete (1545 cached, 2 parsed). 2024 targets, 280 skipped, 0 masked, 0 errors. NOTE: Resolving any missing task queue dependencies Build Configuration: BB_VERSION = "1.26.0" BUILD_SYS = "x86_64-linux" NATIVELSBSTRING = "Ubuntu-14.04" TARGET_SYS = "arm-poky-linux-gnueabi" MACHINE = "raspberrypi2" DISTRO = "poky" DISTRO_VERSION = "1.8" TUNE_FEATURES = "arm armv7a vfp thumb neon callconvention-hard vfpv4 cortexa7" TARGET_FPU… Leia mais »