En esta página

Integración de JavaScript en QML

El código JavaScript puede integrarse 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 pueden utilizarse en QML como vinculaciones. Por ejemplo:

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

Tenga en cuenta que las llamadas a funciones, como Math.random(), no se reevaluarán a menos que cambien sus argumentos. Por tanto, la vinculación a Math.random() será un número aleatorio y no se reevaluará, pero si la anchura cambia de alguna otra forma, la vinculación de la altura se reevaluará para tenerlo en cuenta.

Añadir funciones JavaScript en QML

Las funciones JavaScript pueden declararse en elementos QML, como en el ejemplo siguiente. Esto permite llamar al método utilizando el id 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 pueden utilizarse para abstraer la lógica de los archivos QML. Para ello, coloque primero las funciones en un archivo .js, como en el ejemplo.

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

A continuación, importe el archivo en cualquier archivo .qml que necesite utilizar las funciones, como el archivo QML de ejemplo que se muestra 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 } }
    }

}

Para más detalles sobre el motor JavaScript utilizado por QML, así como la diferencia con el JS del navegador, consulte 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.