En esta página

Qt Quick Guías prácticas

El objetivo de esta página es ofrecer una referencia útil y fácil de consultar que muestre la forma más sencilla y adecuada de realizar tareas específicas en Qt Quick. Cada solución incluye fragmentos de código QML y/o C++ cuando procede, y Qt comprueba automáticamente cada fragmento para garantizar que siga funcionando correctamente.

¿Cómo puedo:

Llamar a una función de C++ desde QML al pulsar un botón

Suponiendo que el tipo de C++ deba estar disponible globalmente para los archivos QML de la aplicación, la forma más sencilla es convertirlo en un singleton de QML con QML_SINGLETON. Por ejemplo, en el archivo de cabecera backend.h:

#include <QObject>
#include <QQmlEngine>

class Backend : public QObject
{
    Q_OBJECT
    QML_ELEMENT
    QML_SINGLETON

public:
    Q_INVOKABLE void doStuff();
};

backend.cpp:

#include "backend.h"

#include <QDebug>

void Backend::doStuff()
{
    qDebug() << "Did stuff!";
}

A continuación, puedes llamar a esa función desde cualquier archivo QML:

import QtQuick.Controls

import MyModule

ApplicationWindow {
    width: 400
    height: 400
    title: qsTr("C++ Button example")

    Button {
        text: qsTr("Click me")
        onClicked: Backend.doStuff()
    }
}

Si el tipo de C++ solo tiene que estar disponible para un pequeño conjunto de archivos QML, plantéate utilizar ` QML_ELEMENT`. Para conocer más formas de exponer tipos de C++ a QML, consulta «Elegir el método de integración correcto entre C++ y QML».

Este ejemplo da por hecho que el tipo « Backend » está disponible en un módulo QML. Con CMake, esto se hace mediante «qt_add_qml_module». Para ver un ejemplo que lo ilustra con detalle, consulta «Compilación de una aplicación QML».

Ver qué elemento tiene el foco activo

Escribe un controlador de señal de cambio de propiedad para la propiedad ` activeFocusItem ` de la ventana:

import QtQuick
import QtQuick.Controls

ApplicationWindow {
    width: 400
    height: 400
    visible: true
    title: qsTr("Active focus debugging example")

    onActiveFocusItemChanged: print("activeFocusItem: " + activeFocusItem)

    Row {
        TextField {
            objectName: "textField1"
        }
        TextField {
            objectName: "textField2"
        }
    }
}

Esto mostrará en la consola el elemento que tiene el foco activo en ese momento. Para garantizar que la salida sea útil, asigna a cada elemento un valor descriptivo para la propiedad ` objectName`.

Crea un selector de hora similar al TimePickerDialog de Android.

Hemos preparado un ejemplo que consta de varios archivos QML que muestran cómo hacerlo. Se pueden utilizar en tu aplicación de la siguiente manera:

import QtQuick
import QtQuick.Layouts
import QtQuick.Controls.Material

ApplicationWindow {
    id: window
    width: 600
    height: 600
    visible: true
    title: qsTr("Time Picker Example")

    Material.theme: darkThemeSwitch.checked ? Material.Dark : Material.Light

    // Shows the selected time and opens the dialog.
    TimeComponentLabel {
        id: openDialogLabel
        width: parent.width - 80
        anchors.centerIn: parent
        font.pixelSize: Qt.application.font.pixelSize * 8
        renderTypeQuality: Text.VeryHighRenderTypeQuality
        interactive: !timePickerDialog.opened

        text: Qt.formatTime(new Date(1970, 1, 1, timePickerDialog.hours, timePickerDialog.minutes), "hh:mm")

        onTapped: timePickerDialog.openWithMode(TimePicker.Mode.Hours)
    }

    ColumnLayout {
        // We always want the openDialogLabel to be centered in the window, not us.
        // For that reason, we use anchors rather than putting the root items into a ColumnLayout.
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.top: openDialogLabel.bottom
        anchors.topMargin: 24
        spacing: 12

        Switch {
            id: is24HourSwitch
            text: qsTr("24 Hour")
            checked: timePickerDialog.is24Hour
        }
        Switch {
            id: darkThemeSwitch
            text: qsTr("Dark")
        }
    }

    TimePickerDialog {
        id: timePickerDialog
        anchors.centerIn: parent
        is24Hour: is24HourSwitch.checked

        onTimeAccepted: print("A time was chosen - do something here!")
    }
}

Cuadro de diálogo de selección de hora con selector circular en tema claro

TimePickerDialog con su tema claro.

Cuadro de diálogo de selección de hora con selector circular en tema oscuro

TimePickerDialog con su tema oscuro.

Usar una enumeración de C++ en JavaScript

Para hacer que una enumeración de C++ sea visible desde JavaScript (es decir, QJSEngine, no QQmlEngine ni QQmlApplicationEngine), utiliza newQMetaObject() y registerModule():

    QJSEngine engine;
    engine.installExtensions(QJSEngine::AllExtensions);

    QJSValue metaObjects = engine.newObject();
    const QJSValue backendJsMetaObject = engine.newQMetaObject(&Backend::staticMetaObject);
    metaObjects.setProperty("Backend", backendJsMetaObject);
    // Repeat the two lines above for other types as needed.
    engine.registerModule("MyApp", metaObjects);

    Backend backend(&engine);
    const bool loaded = backend.load();

A continuación, la enumeración se puede utilizar desde JavaScript:

export function backendStatusUpdate(backendStatus) {
    if (backendStatus === Backend.Error) {
        console.warn("Error!")
        return
    }

    console.log("Backend loaded successfully")
}

Si utilizas QQmlEngine o QQmlApplicationEngine, existen opciones más sencillas; consulta «Cómo elegir el método de integración adecuado entre C++ y QML» para obtener más información.

backend.h:

#include <QObject>
#include <QJSEngine>

class Backend : public QObject
{
    Q_OBJECT

public:
    Backend(QJSEngine *engine);

    enum Status {
        Unknown,
        Error,
        Loading,
        Loaded
    };

    Q_ENUM(Status)

    bool load();

private:
    QJSEngine *mEngine = nullptr;
};

backend.cpp:

#include "backend.h"

Backend::Backend(QJSEngine*engine) :
    mEngine(engine)
{
}

bool Backend::load()
{
    // Realizar aquí alguna operación de carga...

    const QJSValue module = mEngine->importModule(":/script.mjs");
    if (module.isError()) {
        qWarning() << "Error loading script.mjs:" << module.toString();
       return false;
    }

    const QJSValue function = module.property("backendStatusUpdate");
    if (!function.isCallable()) {
        qWarning() << "backendStatusUpdate script function is not callable!";
       return false;
    }

    const QJSValue resultadoDeFunción = function.call(QJSValueList() << Loaded);
    if (functionResult.isError()) {
        qWarning() << "backendStatusUpdate script function had errors:" << functionResult.toString();
       return false;
    }

    return true;
}

Para obtener más información, consulta QObject Integration.

Crear un indicador

Hemos preparado un ejemplo compuesto por varios archivos C++ y QML que muestran cómo hacerlo. Se pueden utilizar en su aplicación de la siguiente manera:

import QtQuick.Controls

import GaugeHowTo

ApplicationWindow {
    width: 400
    height: 400
    title: qsTr("Gauge example")

    Gauge {
        minimumValue: 0
        value: 75
        maximumValue: 100
    }
}

Indicador vertical con el valor fijado en 75 en una escala de 0 a 100

© 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.