Qt Quick per i progetti Android Studio

Qt Quick Gli esempi dell'API per Android sono progetti Android Studio
Gli esempi dell'API Qt Quick per Android sono forniti come progetti Android Studio. Le cartelle dei progetti si trovano nella directory di installazione di Qt.
Ad esempio, nel percorso di installazione predefinito di Windows, si trovano qui:
C:\Qt\Examples\Qt-<patch-release-number>\platforms\android\<example-name>Questi progetti sono già configurati per utilizzare una versione del plugin Gradle di Qt compatibile con questa versione di Qt.
Panoramica
Questo esempio contiene un progetto Qml che è possibile importare in Android Studio tramite il plugin Qt Tools for Android Studio. Sono presenti progetti Java e Kotlin che utilizzano il progetto Qml come vista (View) tramite l’API QtQuickView.
Per ulteriori informazioni sul funzionamento di QML, consultare Qt Qml. Questa documentazione si concentra su come un componente QML viene incorporato nelle applicazioni Android utilizzando Java o Kotlin.
Le modifiche in main() sono richieste dalle API di Qt Quick per Android
Il file main.cpp di una tipica applicazione " Qt Quick " si presenta così:
#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();
}In main() non è necessario creare un motore QML né caricare alcun codice QML che verrà gestito in seguito dalle API di visualizzazione di Qt Quick. Tutto ciò di cui abbiamo bisogno in main() è:
#include <QGuiApplication>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
return app.exec();
}Configurazione del layout
Sia per i progetti Java che per quelli Kotlin, dobbiamo configurare il layout per le QtQuickViewin app/src/main/res/layout/activity_main.xml.
All’interno di LinearLayout, configuriamo due FrameLayout per ogni 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>Il file ` id ` è quello a cui si fa riferimento nella `MainActivity` scritta in Kotlin o Java.
Importazione delle classi Java dei tipi QML generate automaticamente
Le classi Java relative ai nostri tipi QML vengono generate durante la compilazione del progetto Qt Quick. Queste devono essere importate prima di poterle utilizzare nella nostra 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: per ulteriori informazioni sulla generazione di codice Java dei componenti QML,consultare la variabile CMake QT_ANDROID_GENERATE_JAVA_QTQUICKVIEW_CONTENTS.
Metodo onCreate() di MainActivity
Per prima cosa, esaminiamo il metodo onCreate() di ` MainActivity` nei progetti 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() }
}Nota: nel progetto Kotlin utilizziamo il View binding per accedere ai componenti dell'interfaccia utente dell'applicazione:
m_binding = ActivityMainBinding.inflate(layoutInflater)
val view = m_binding.root
setContentView(view)All'interno del metodo ` onCreate() `, le variabili dichiarate in precedenza vengono inizializzate con nuove istanze di `QtQuickView`. Queste istanze ricevono come argomenti l'Context e dell'attività Java/Kotlin.
QtQuickView m_firstQuickView = new QtQuickView(this);
QtQuickView m_secondQuickView = new QtQuickView(this);val firstQtQuickView = QtQuickView(this)
val secondQtQuickView = QtQuickView(this)Le istanze di QtQuickView vengono aggiunte al layout Android con i parametri di layout appropriati.
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)Le classi Java ` Main ` e ` Second ` ereditano dalla classe `QtQuickViewContent `. Queste classi vengono generate dal progetto QML che abbiamo importato.
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()Il contenuto di ` Qt Quick ` viene caricato tramite il metodo ` QtQuickView.loadContent() `, che accetta come argomento un oggetto ` QtQuickViewContent `.
m_firstQuickView.loadContent(m_firstQmlContent);
m_secondQuickView.loadContent(m_secondQmlContent);firstQtQuickView.loadContent(m_firstQmlContent)
secondQtQuickView.loadContent(m_secondQmlContent)Interazione con i componenti QML
Per interagire con i componenti QML incorporati, implementiamo l'interfaccia QtQmlStatusChangeListener e sovrascriviamo il metodo ` onStatusChanged ` per ottenere lo stato di caricamento del ` QtQuickViewContent ` attualmente in fase di caricamento all'interno del ` QtQuickView`.
public class MainActivity extends AppCompatActivity implements
QtQmlStatusChangeListener {
...
}class MainActivity : AppCompatActivity(), QtQmlStatusChangeListener {
...
}L'implementazione di ` 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()
)
)
}
}
}
}L'MainActivity e viene impostato come statusChangeListener dei siti m_mainQmlContent e m_secondQmlContent tramite il metodo QtQuickViewContent.setStatusChangeListener.
m_firstQmlContent.setStatusChangeListener(this);
m_secondQmlContent.setStatusChangeListener(this);m_firstQmlContent.setStatusChangeListener(this)
m_secondQmlContent.setStatusChangeListener(this)La funzione di callback sovrascritta ` onStatusChanged() ` riceve un segnal StatusChanged() ` contenente lo stato attuale, un enum `QtQmlStatus`, del caricamento dell'QtQuickViewContent corrente nella ` QtQuickView`. Se si conferma che questo ` QtQmlStatus ` è ` QtQmlStatus.READY`, è possibile iniziare a interagire con la vista QML.
Ottenere e impostare i valori delle proprietà dei componenti QML
Il recupero e l’impostazione dei valori delle proprietà dei componenti QML avvengono tramite i metodi descritti nella classe ` Main.java `. In questo caso utilizziamo i metodi ` m_mainQmlContent.setColorStringProperty() ` e ` m_mainQmlContent.getColorStringProperty() `. Questi metodi vengono generati in base alle proprietà incluse nel 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 il metodo ` m_mainQmlContent.setColorStringProperty() ` impostiamo il valore della proprietà ` colorStringFormat ` dell'oggetto ` m_mainQmlContent ` su un valore di colore casuale recuperato dalla classe ` Colors.java ` (o ` Colors.kt`).
Il metodo m_mainQmlContent.getColorStringProperty() viene utilizzato in questo caso per recuperare il colore di sfondo corrente dell’oggetto radice di m_mainQmlContent e quindi mostrarlo all’utente sul lato Java/Kotlin Android dell’applicazione.
m_secondQmlContent Esiste un componente QML denominato ` Grid ` che possiamo ruotare dal lato Java tramite il metodo ` m_secondQmlContent.setGridRotation() ` generato.
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
}
}Ascoltatori di segnali
La classe ` QtQuickViewContent ` offre i metodi ` connectSignalListener() ` e ` disconnectSignalListener() `, utilizzati per collegare e scollegare i listener di segnale dai segnali dichiarati nell'oggetto radice del componente QML. Il metodo ` QtQuickViewContent.connectSignalListener() ` restituisce un ID univoco del listener di segnale, che viene memorizzato e utilizzato in seguito per identificare e scollegare il listener.
Qui colleghiamo un listener al segnale ` 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()
)
)
}
}Il segnale ` onClicked() ` viene emesso ogni volta che si fa clic sul pulsante del componente QML. Questo listener riceve quindi tale segnale e il colore di sfondo del layout che contiene la parte Android dell’applicazione viene impostato su un valore di colore casuale prelevato dalla classe ` Colors.java `.
Successivamente, il listener del segnale viene disconnesso utilizzando il metodo ` QtQuickViewContent.disconnectSignalListener() `, specificandone l’ID univoco.
m_firstQmlContent.disconnectSignalListener(m_qmlButtonSignalListenerId);m_firstQmlContent.disconnectSignalListener(m_qmlButtonSignalListenerId)Se non l’avete ancora fatto, date un’occhiata al corso “Qt Academy: Integrazione dei contenuti di Qt Quick 3D in un’app Android”, che illustra gli strumenti e le API citati in questo esempio.
© 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.