Qt Quick para projetos do Android Studio

Qt Quick Os exemplos da API para Android são projetos do Android Studio
Os exemplos da API Qt Quick para Android são fornecidos como projetos do Android Studio. As pastas dos projetos estão localizadas no diretório de instalação do Qt.
Por exemplo, no caminho padrão de instalação do Windows, elas estão localizadas aqui:
C:\Qt\Examples\Qt-<patch-release-number>\platforms\android\<example-name>Esses projetos já estão configurados para usar uma versão do Qt Gradle Plugin compatível com esta versão do Qt.
Visão geral
Este exemplo contém um projeto Qml que você pode importar para o Android Studio com o plug-in Qt Tools for Android Studio. Existem projetos em Java e Kotlin que utilizam o projeto Qml como uma View, por meio da API QtQuickView.
Para obter mais informações sobre como o QML funciona, consulte Qt Qml. Esta documentação enfoca como um componente QML é incorporado em aplicativos Android usando Java ou Kotlin.
Alterações no ` main() ` são exigidas pelas APIs do ` Qt Quick ` para Android
O arquivo main.cpp de um aplicativo típico do ` Qt Quick ` tem a seguinte aparência:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
QObject::connect(
&engine,
&QQmlApplicationEngine::objectCreationFailed,
&app,
[]() { QCoreApplication::exit(-1); },
Qt::QueuedConnection);
engine.loadFromModule("MyQtQuickProject", "Main");
return app.exec();
}No main(), não precisamos criar um QML Engine nem carregar nenhum QML que será tratado posteriormente pelas APIs de visualização do Qt Quick. Tudo o que precisamos no main() é:
#include <QGuiApplication>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
return app.exec();
}Configurando o layout
Tanto para projetos em Java quanto em Kotlin, precisamos configurar o layout para os QtQuickViewsem app/src/main/res/layout/activity_main.xml.
Dentro do ` LinearLayout`, configuramos dois `FrameLayouts` para cada ` QtQuickView`.
<FrameLayout
android:id="@+id/firstQmlFrame"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
</FrameLayout>
<FrameLayout
android:id="@+id/secondQmlFrame"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
</FrameLayout>O ` id ` é o arquivo ao qual se faz referência na `MainActivity` codificada em Kotlin ou Java.
Importando classes Java de tipos QML geradas automaticamente
As classes Java para nossos tipos QML são geradas quando o projeto ` Qt Quick ` é compilado. Elas devem ser importadas antes que possamos usá-las em nossa `MainActivity`.
import org.qtproject.example.qtquickview.QmlModule.Main;
import org.qtproject.example.qtquickview.QmlModule.Second;import org.qtproject.example.qtquickview.QmlModule.Main
import org.qtproject.example.qtquickview.QmlModule.SecondObservação: Consulte a variável CMake QT_ANDROID_GENERATE_JAVA_QTQUICKVIEW_CONTENTS para obter mais informações sobre a geração de código Java para componentes QML.
Método onCreate() da MainActivity
Primeiro, vamos examinar o método `onCreate()` da ` MainActivity` nos projetos Java e Kotlin.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m_qmlViewBackgroundText = findViewById(R.id.qmlViewBackgroundText);
m_qmlStatus = findViewById(R.id.qmlStatusText);
m_androidControlsLayout = findViewById(R.id.javaRelative);
m_colorBox = findViewById(R.id.qmlColorBox);
m_switch = findViewById(R.id.disconnectQmlListenerSwitch);
m_switch.setOnClickListener(view -> switchListener());
QtQuickView m_firstQuickView = new QtQuickView(this);
QtQuickView m_secondQuickView = new QtQuickView(this);
// Set status change listener for m_qmlView
// listener implemented below in OnStatusChanged
m_firstQmlContent.setStatusChangeListener(this);
m_secondQmlContent.setStatusChangeListener(this);
final ViewGroup.LayoutParams params = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
FrameLayout m_firstQmlFrameLayout = findViewById(R.id.firstQmlFrame);
m_firstQmlFrameLayout.addView(m_firstQuickView, params);
FrameLayout m_secondQmlFrameLayout = findViewById(R.id.secondQmlFrame);
m_secondQmlFrameLayout.addView(m_secondQuickView, params);
m_firstQuickView.loadContent(m_firstQmlContent);
m_secondQuickView.loadContent(m_secondQmlContent);
Button m_changeColorButton = findViewById(R.id.changeQmlColorButton);
m_changeColorButton.setOnClickListener(view -> onClickListener());
Button m_rotateQmlGridButton = findViewById(R.id.rotateQmlGridButton);
m_rotateQmlGridButton.setOnClickListener(view -> rotateQmlGrid());
}override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
m_binding = ActivityMainBinding.inflate(layoutInflater)
val view = m_binding.root
setContentView(view)
m_binding.disconnectQmlListenerSwitch.setOnCheckedChangeListener { button, checked ->
switchListener(
button,
checked
)
}
val firstQtQuickView = QtQuickView(this)
val secondQtQuickView = QtQuickView(this)
// Set status change listener for m_qmlView
// listener implemented below in OnStatusChanged
m_firstQmlContent.setStatusChangeListener(this)
m_secondQmlContent.setStatusChangeListener(this)
val params: ViewGroup.LayoutParams = FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
)
m_binding.firstQmlFrame.addView(firstQtQuickView, params)
m_binding.secondQmlFrame.addView(secondQtQuickView, params)
firstQtQuickView.loadContent(m_firstQmlContent)
secondQtQuickView.loadContent(m_secondQmlContent)
m_binding.changeQmlColorButton.setOnClickListener { onClickListener() }
m_binding.rotateQmlGridButton.setOnClickListener { rotateQmlGrid() }
}Observação: no projeto Kotlin, usamos o View binding para acessar os componentes da interface do usuário do aplicativo:
m_binding = ActivityMainBinding.inflate(layoutInflater)
val view = m_binding.root
setContentView(view)Dentro do método ` onCreate() `, as variáveis declaradas anteriormente são inicializadas com novas instâncias de `QtQuickView`. Essas instâncias recebem como argumentos o ` Context ` da `Activity` em Java/Kotlin.
QtQuickView m_firstQuickView = new QtQuickView(this);
QtQuickView m_secondQuickView = new QtQuickView(this);val firstQtQuickView = QtQuickView(this)
val secondQtQuickView = QtQuickView(this)As instâncias do QtQuickView são adicionadas ao layout do Android com os parâmetros de layout adequados.
final ViewGroup.LayoutParams params = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
FrameLayout m_firstQmlFrameLayout = findViewById(R.id.firstQmlFrame);
m_firstQmlFrameLayout.addView(m_firstQuickView, params);
FrameLayout m_secondQmlFrameLayout = findViewById(R.id.secondQmlFrame);
m_secondQmlFrameLayout.addView(m_secondQuickView, params);val params: ViewGroup.LayoutParams = FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
)
m_binding.firstQmlFrame.addView(firstQtQuickView, params)
m_binding.secondQmlFrame.addView(secondQtQuickView, params)As classes Java ` Main ` e ` Second ` herdam da classe ` QtQuickViewContent `. Essas classes são geradas a partir do projeto QML que importamos.
private final Main m_firstQmlContent = new Main();
private final Second m_secondQmlContent = new Second();private val m_firstQmlContent: Main = Main()
private val m_secondQmlContent: Second = Second()O conteúdo do ` Qt Quick ` é carregado por meio do método ` QtQuickView.loadContent() `, que recebe um ` QtQuickViewContent ` como argumento.
m_firstQuickView.loadContent(m_firstQmlContent);
m_secondQuickView.loadContent(m_secondQmlContent);firstQtQuickView.loadContent(m_firstQmlContent)
secondQtQuickView.loadContent(m_secondQmlContent)Interagindo com componentes QML
Para interagir com os componentes QML incorporados, implementamos a interface `QtQmlStatusChangeListener ` e sobrescrevemos o método ` onStatusChanged ` para obter o status de carregamento do ` QtQuickViewContent ` que está sendo carregado no momento no ` QtQuickView`.
public class MainActivity extends AppCompatActivity implements
QtQmlStatusChangeListener {
...
}class MainActivity : AppCompatActivity(), QtQmlStatusChangeListener {
...
}A implementação de ` onStatusChanged `:
@Override
public void onStatusChanged(QtQmlStatus qtQmlStatus, QtQuickViewContent content) {
Log.i(TAG, "Status of QtQuickView: " + qtQmlStatus);
// Show current QML View status in a textview
m_qmlStatus.setText(getString(R.string.qml_view_status, m_statusNames.get(qtQmlStatus)));
updateColorDisplay();
if (content == m_firstQmlContent) {
// Connect signal listener to "onClicked" signal from main.qml
// addSignalListener returns int which can be used later to identify the listener
if (qtQmlStatus == QtQmlStatus.READY && m_switch.isChecked()) {
m_qmlButtonSignalListenerId = m_firstQmlContent.connectOnClickedListener(
(String name, Void v) -> {
Log.i(TAG, "QML button clicked");
m_androidControlsLayout.setBackgroundColor(Color.parseColor(
m_colors.getColor()
));
});
}
}
}override fun onStatusChanged(status: QtQmlStatus?, content: QtQuickViewContent?) {
Log.v(TAG, "Status of QtQuickView: $status")
// Show current QML View status in a textview
m_binding.qmlStatusText.text = getString(R.string.qml_view_status, m_statusNames[status])
updateColorDisplay()
if (content == m_firstQmlContent) {
// Connect signal listener to "onClicked" signal from main.qml
// addSignalListener returns int which can be used later to identify the listener
if (status == QtQmlStatus.READY && m_binding.disconnectQmlListenerSwitch.isChecked) {
m_qmlButtonSignalListenerId =
m_firstQmlContent.connectOnClickedListener { _: String, _: Void? ->
Log.i(TAG, "QML button clicked")
m_binding.kotlinRelative.setBackgroundColor(
Color.parseColor(
m_colors.getColor()
)
)
}
}
}
}O objeto ` MainActivity ` é definido como o ` statusChangeListener ` do ` m_mainQmlContent ` e do ` m_secondQmlContent ` por meio do método ` QtQuickViewContent.setStatusChangeListener `.
m_firstQmlContent.setStatusChangeListener(this);
m_secondQmlContent.setStatusChangeListener(this);m_firstQmlContent.setStatusChangeListener(this)
m_secondQmlContent.setStatusChangeListener(this)A função de retorno de chamada sobrescrita ` onStatusChanged() ` recebe um sinal ` StatusChanged() ` contendo o status atual — uma enumeração `QtQmlStatus ` — do carregamento da ` QtQuickViewContent ` atual no ` QtQuickView`. Se for confirmado que esse ` QtQmlStatus ` está em ` QtQmlStatus.READY`, podemos começar a interagir com a visualização QML.
Obtenção e definição de valores de propriedades de componentes QML
A obtenção e a definição de valores de propriedades de componentes QML ocorrem por meio dos métodos descritos na classe ` Main.java `. Neste caso, utilizamos os métodos ` m_mainQmlContent.setColorStringProperty() ` e ` m_mainQmlContent.getColorStringProperty() `. Esses métodos são gerados de acordo com as propriedades que o componente QML inclui.
public void onClickListener() {
// Set the QML view root object property "colorStringFormat" value to
// color from Colors.getColor()
m_firstQmlContent.setColorStringFormat(m_colors.getColor());
updateColorDisplay();
}
private void updateColorDisplay() {
String qmlBackgroundColor = m_firstQmlContent.getColorStringFormat();
// Display the QML View background color code
m_qmlViewBackgroundText.setText(qmlBackgroundColor);
// Display the QML View background color in a view
// if qmlBackGroundColor is not null
if (qmlBackgroundColor != null) {
m_colorBox.setBackgroundColor(Color.parseColor(qmlBackgroundColor));
}
}private fun onClickListener() {
// Set the QML view root object property "colorStringFormat" value to
// color from Colors.getColor()
m_firstQmlContent.colorStringFormat = m_colors.getColor()
updateColorDisplay()
}
private fun updateColorDisplay() {
val qmlBackgroundColor = m_firstQmlContent.colorStringFormat
// Display the QML View background color code
m_binding.qmlViewBackgroundText.text = qmlBackgroundColor
// Display the QML View background color in a view
// if qmlBackgroundColor is not null
if (qmlBackgroundColor != null) {
m_binding.qmlColorBox.setBackgroundColor(Color.parseColor(qmlBackgroundColor))
}
}Com o método ` m_mainQmlContent.setColorStringProperty() `, definimos o valor da propriedade ` colorStringFormat ` do ` m_mainQmlContent ` como uma cor aleatória obtida a partir da classe ` Colors.java ` (ou ` Colors.kt`).
O método ` m_mainQmlContent.getColorStringProperty() ` é usado aqui para obter a cor de fundo atual do objeto raiz do `m_mainQmlContent` e, em seguida, exibi-la ao usuário no lado Java/Kotlin do aplicativo para Android.
m_secondQmlContent Existe um componente QML ` Grid `, que podemos girar a partir do lado Java com o método ` m_secondQmlContent.setGridRotation() ` gerado.
private void rotateQmlGrid() {
Integer previousGridRotation = m_secondQmlContent.getGridRotation();
if (previousGridRotation != null) {
m_secondQmlContent.setGridRotation(previousGridRotation + 45);
}
}private fun rotateQmlGrid() {
val previousGridRotation = m_secondQmlContent.gridRotation
if (previousGridRotation != null) {
m_secondQmlContent.gridRotation = previousGridRotation + 45
}
}Ouvintes de sinal
A classe ` QtQuickViewContent ` oferece os métodos ` connectSignalListener() ` e ` disconnectSignalListener() `, que são usados para conectar e desconectar ouvintes de sinal entre os sinais declarados no objeto raiz do componente QML. O método ` QtQuickViewContent.connectSignalListener() ` retorna um ID exclusivo do ouvinte de sinal, que armazenamos e usamos posteriormente para identificar e desconectar o ouvinte.
Aqui, conectamos um ouvinte de sinal ao sinal ` onClicked() ` do componente QML:
if (qtQmlStatus == QtQmlStatus.READY && m_switch.isChecked()) {
m_qmlButtonSignalListenerId = m_firstQmlContent.connectOnClickedListener(
(String name, Void v) -> {
Log.i(TAG, "QML button clicked");
m_androidControlsLayout.setBackgroundColor(Color.parseColor(
m_colors.getColor()
));
});
}if (status == QtQmlStatus.READY && m_binding.disconnectQmlListenerSwitch.isChecked) {
m_qmlButtonSignalListenerId =
m_firstQmlContent.connectOnClickedListener { _: String, _: Void? ->
Log.i(TAG, "QML button clicked")
m_binding.kotlinRelative.setBackgroundColor(
Color.parseColor(
m_colors.getColor()
)
)
}
}O sinal ` onClicked() ` é emitido toda vez que o botão no componente QML é clicado. Esse ouvinte, então, recebe esse sinal, e a cor de fundo do layout que contém a parte do aplicativo para Android é definida como um valor de cor aleatório obtido da classe ` Colors.java `.
Em seguida, o ouvinte de sinal é desconectado usando o método ` QtQuickViewContent.disconnectSignalListener() `, passando a ele o ID exclusivo do ouvinte de sinal.
m_firstQmlContent.disconnectSignalListener(m_qmlButtonSignalListenerId);m_firstQmlContent.disconnectSignalListener(m_qmlButtonSignalListenerId)Caso ainda não tenha feito isso, confira o curso “Qt Academy: Incorporando conteúdo 3D Qt Quick em um aplicativo Android”, que apresenta as ferramentas e APIs mencionadas neste exemplo.
© 2026 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.