En esta página

Integración de JavaScript en QML

El código JavaScript se puede integrar fácilmente en QML para proporcionar lógica de interfaz de usuario, control imperativo u otras ventajas.

Uso de expresiones JavaScript para valores de propiedades

Las expresiones de JavaScript se pueden utilizar en QML como enlaces. Por ejemplo:

Item {
    width: Math.random()
    height: width < 100 ? 100 : (width + 50) /  2
}

Ten en cuenta que las llamadas a funciones, como Math.random(), no se volverán a evaluar a menos que cambien sus argumentos. Por lo tanto, el enlace a Math.random() dará como resultado un número aleatorio y no se volverá a evaluar, pero si se modifica el ancho de alguna otra forma, el enlace de la altura se volverá a evaluar para tenerlo en cuenta.

Añadir funciones de JavaScript en QML

Las funciones de JavaScript se pueden declarar en elementos QML, como en el ejemplo siguiente. Esto permite llamar al método utilizando el identificador del elemento.

import QtQuick

Item {
    id: container
    width: 320
    height: 480

    function randomNumber() {
        return Math.random() * 360;
    }

    function getNumber() {
        return container.randomNumber();
    }

    TapHandler {
        // This line uses the JS function from the item
        onTapped: rectangle.rotation = container.getNumber();
    }

    Rectangle {
        color: "#272822"
        width: 320
        height: 480
    }

    Rectangle {
        id: rectangle
        anchors.centerIn: parent
        width: 160
        height: 160
        color: "green"
        Behavior on rotation { RotationAnimation { direction: RotationAnimation.Clockwise } }
    }

}

Uso de archivos JavaScript

Los archivos JavaScript se pueden utilizar para abstraer la lógica de los archivos QML. Para ello, primero coloca tus funciones dentro de un archivo .js, tal y como se muestra en el ejemplo.

// myscript.js
function getRandom(previousValue) {
    return Math.floor(previousValue + Math.random() * 90) % 360;
}

A continuación, importa el archivo a cualquier archivo .qml que necesite utilizar las funciones, tal y como se muestra en el archivo QML de ejemplo que aparece a continuación.

import QtQuick
import "myscript.js" as Logic

Item {
    width: 320
    height: 480

    Rectangle {
        color: "#272822"
        width: 320
        height: 480
    }

    TapHandler {
        // This line uses the JS function from the separate JS file
        onTapped: rectangle.rotation = Logic.getRandom(rectangle.rotation);
    }

    Rectangle {
        id: rectangle
        anchors.centerIn: parent
        width: 160
        height: 160
        color: "green"
        Behavior on rotation { RotationAnimation { direction: RotationAnimation.Clockwise } }
    }

}

Cuadrado verde girado un ángulo calculado por JavaScript

Para obtener más detalles sobre el motor de JavaScript utilizado por QML, así como sobre las diferencias con respecto al JavaScript de los navegadores, consulta la documentación completa sobre expresiones JavaScript en documentos QML.

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