Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
integratingjs.qdoc
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
3/*!
4\page qtquick-usecase-integratingjs.html
5\meta {keywords} {qmltopic}
6\title Integrating JavaScript in QML
7\keyword Use Case - Integrating JavaScript in QML
8\brief Example of how to integrate JavaScript code in QML views
9
10JavaScript code can be easily integrated into QML to provide UI logic,
11imperative control, or other benefits.
12
13\section1 Using JavaScript expressions for property values
14
15JavaScript expressions can be used in QML as bindings. For example:
16\code
17Item {
18 width: Math.random()
19 height: width < 100 ? 100 : (width + 50) / 2
20}
21\endcode
22
23Note that function calls, like Math.random(), will not be reevaluated unless
24their arguments change. So binding to Math.random() will be one random number
25and not reevaluated, but if the width is changed in some other manner, the
26height binding will be reevaluated to take that into account.
27
28\section1 Adding JavaScript functions in QML
29
30JavaScript functions can be declared on QML items, like in the below example.
31This allows you to call the method using the item id.
32
33\snippet qmlapp/usecases/integratingjs-inline.qml 0
34
35\section1 Using JavaScript files
36
37JavaScript files can be used for abstracting out logic from QML files. To do
38this, first place your functions inside a .js file like in the example shown.
39
40\snippet qmlapp/usecases/myscript.js 0
41
42Then import the file into any .qml file that needs to use the functions, like
43the example QML file below.
44
45\snippet qmlapp/usecases/integratingjs.qml 0
46
47\image qmlapp/qml-uses-integratingjs.png
48
49For further details on the JavaScript engine used by QML, as well as the
50difference from browser JS, see the full documentation on \l {JavaScript
51Expressions in QML Documents}.
52
53*/