// Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only /*! \page qtquick-usecase-integratingjs.html \title Use Case - Integrating JavaScript in QML \brief Example of how to integrate JavaScript code in QML applications JavaScript code can be easily integrated into QML to provide UI logic, imperative control, or other benefits. \section1 Using JavaScript Expressions for Property Values JavaScript expressions can be used in QML as bindings. For example: \code Item { width: Math.random() height: width < 100 ? 100 : (width + 50) / 2 } \endcode Note that function calls, like Math.random(), will not be reevaluated unless their arguments change. So binding to Math.random() will be one random number and not reevaluated, but if the width is changed in some other manner, the height binding will be reevaluated to take that into account. \section1 Adding JavaScript Functions in QML JavaScript functions can be declared on QML items, like in the below example. This allows you to call the method using the item id. \snippet qmlapp/usecases/integratingjs-inline.qml 0 \section1 Using JavaScript Files JavaScript files can be used for abstracting out logic from QML files. To do this, first place your functions inside a .js file like in the example shown. \snippet qmlapp/usecases/myscript.js 0 Then import the file into any .qml file that needs to use the functions, like the example QML file below. \snippet qmlapp/usecases/integratingjs.qml 0 \image qmlapp/qml-uses-integratingjs.png For further details on the JavaScript engine used by QML, as well as the difference from browser JS, see the full documentation on \l {JavaScript Expressions in QML Documents}. */