Qt Quick para proyectos de Android Studio

Qt Quick Los ejemplos de la API de Android son proyectos de Android Studio
Los ejemplos de la API « Qt Quick » para Android se proporcionan como proyectos de Android Studio. Las carpetas de los proyectos se encuentran en la ruta de instalación de Qt.
Por ejemplo, en la ruta de instalación predeterminada de Windows, se encuentran aquí:
C:\Qt\Examples\Qt-<patch-release-number>\platforms\android\<example-name>Estos proyectos ya están configurados para utilizar una versión del complemento Gradle de Qt compatible con esta versión de Qt.
Descripción general
Este ejemplo contiene un proyecto Qml que puedes importar a Android Studio con el complemento Qt Tools for Android Studio. Hay proyectos en Java y Kotlin que utilizan el proyecto Qml como vista mediante la API QtQuickView.
Para obtener más información sobre cómo funciona QML, consulta Qt Qml. Esta documentación se centra en cómo se integra un componente QML en aplicaciones de Android utilizando Java o Kotlin.
Qt Quick, para las API de Android, exige cambios en main()
El archivo main.cpp de una aplicación típica de « Qt Quick » tiene este aspecto:
#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();
}En main() no es necesario crear un motor QML ni cargar ningún archivo QML que luego vayan a gestionar las API de vista de Qt Quick. Todo lo que necesitamos en main() es:
#include <QGuiApplication>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
return app.exec();
}Configuración del diseño
Tanto para los proyectos en Java como en Kotlin, debemos configurar el diseño de los QtQuickViewsen app/src/main/res/layout/activity_main.xml.
Dentro de LinearLayout, configuramos dos 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>El archivo id es al que se hace referencia en la MainActivity codificada en Kotlin o Java.
Importación de clases Java de tipos QML generadas automáticamente
Las clases Java correspondientes a nuestros tipos QML se generan al compilar el proyecto « Qt Quick ». Es necesario importarlas antes de poder utilizarlas en nuestra 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.SecondNota: Consulta la variable CMake QT_ANDROID_GENERATE_JAVA_QTQUICKVIEW_CONTENTS para obtener más información sobre la generación de código Java de los componentes QML.
El método onCreate() de MainActivity
En primer lugar, analizaremos el método onCreate() de ` MainActivity` en los proyectos de Java y 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() }
}Nota: en el proyecto de Kotlin utilizamos el enlace de vistas (View binding) para acceder a los componentes de la interfaz de usuario de la aplicación:
m_binding = ActivityMainBinding.inflate(layoutInflater)
val view = m_binding.root
setContentView(view)Dentro del método ` onCreate() `, las variables declaradas previamente se inicializan con nuevas instancias de `QtQuickView`. Estas instancias toman como argumentos el ` Context ` de la actividad Java/Kotlin.
QtQuickView m_firstQuickView = new QtQuickView(this);
QtQuickView m_secondQuickView = new QtQuickView(this);val firstQtQuickView = QtQuickView(this)
val secondQtQuickView = QtQuickView(this)Las instancias de QtQuickView se añaden al diseño de Android con los parámetros de diseño adecuados.
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)Las clases Java ` Main ` y ` Second ` heredan de la clase `QtQuickViewContent`. Estas clases se generan a partir del proyecto QML que hemos importado.
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()El contenido de ` Qt Quick ` se carga mediante el método ` QtQuickView.loadContent() `, que toma un objeto ` QtQuickViewContent ` como argumento.
m_firstQuickView.loadContent(m_firstQmlContent);
m_secondQuickView.loadContent(m_secondQmlContent);firstQtQuickView.loadContent(m_firstQmlContent)
secondQtQuickView.loadContent(m_secondQmlContent)Interacción con los componentes QML
Para interactuar con los componentes QML integrados, implementamos la interfaz QtQmlStatusChangeListener y sobrescribimos el método onStatusChanged para obtener el estado de carga del QtQuickViewContent que se está cargando actualmente en el QtQuickView.
public class MainActivity extends AppCompatActivity implements
QtQmlStatusChangeListener {
...
}class MainActivity : AppCompatActivity(), QtQmlStatusChangeListener {
...
}La implementación 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()
)
)
}
}
}
}El objeto « MainActivity » se establece como el « statusChangeListener » de « m_mainQmlContent » y « m_secondQmlContent » mediante el método « QtQuickViewContent.setStatusChangeListener ».
m_firstQmlContent.setStatusChangeListener(this);
m_secondQmlContent.setStatusChangeListener(this);m_firstQmlContent.setStatusChangeListener(this)
m_secondQmlContent.setStatusChangeListener(this)La función de llamada de retorno sobrescrita ` onStatusChanged() ` recibe una señal ` StatusChanged() ` que contiene el estado actual —una enumeración `QtQmlStatus `— de la carga del ` QtQuickViewContent ` actual en el `QtQuickView`. Si se confirma que este ` QtQmlStatus ` es ` QtQmlStatus.READY`, podemos empezar a interactuar con la vista QML.
Obtención y configuración de los valores de las propiedades de los componentes QML
La obtención y el establecimiento de los valores de las propiedades de los componentes QML se realizan a través de los métodos descritos en la clase « Main.java ». En este caso, utilizamos los métodos « m_mainQmlContent.setColorStringProperty() » y « m_mainQmlContent.getColorStringProperty() ». Estos métodos se generan en función de las propiedades que incluya el componente QML.
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))
}
}Con el método ` m_mainQmlContent.setColorStringProperty() `, establecemos el valor de la propiedad ` colorStringFormat ` del objeto ` m_mainQmlContent ` con un valor de color aleatorio que se obtiene de la clase ` Colors.java ` (o ` Colors.kt`).
El método m_mainQmlContent.getColorStringProperty() se utiliza aquí para obtener el color de fondo actual del objeto raíz de `m_mainQmlContent` y, a continuación, mostrárselo al usuario en el lado Java/Kotlin de la aplicación para Android.
m_secondQmlContent Cuenta con un componente QML ` Grid ` que podemos rotar desde el lado de Java mediante el método generado ` m_secondQmlContent.setGridRotation() `.
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
}
}Escuchas de señales
La clase ` QtQuickViewContent ` ofrece los métodos ` connectSignalListener() ` y ` disconnectSignalListener() `, que se utilizan para conectar y desconectar escuchas de señales entre las señales declaradas en el objeto raíz del componente QML. El método ` QtQuickViewContent.connectSignalListener() ` devuelve un identificador único de la escucha de señal, que almacenamos y utilizamos posteriormente para identificar y desconectar la escucha.
Aquí conectamos un oyente de señal a la señal « onClicked() » del 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()
)
)
}
}La señal « onClicked() » se emite cada vez que se pulsa el botón del componente QML. A continuación, este oyente recibe dicha señal y el color de fondo del diseño que contiene la parte de la aplicación para Android se establece en un valor de color aleatorio obtenido de la clase « Colors.java ».
A continuación, el oyente de la señal se desconecta mediante el método QtQuickViewContent.disconnectSignalListener(), pasándole el identificador único del oyente de la señal.
m_firstQmlContent.disconnectSignalListener(m_qmlButtonSignalListenerId);m_firstQmlContent.disconnectSignalListener(m_qmlButtonSignalListenerId)Si aún no lo has hecho, echa un vistazo al curso «Qt Academy: Integración de contenido 3D de Qt Quick en una aplicación para Android», que presenta las herramientas y las API mencionadas en este ejemplo.
© 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.