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\title Integrating JavaScript in QML
6\keyword Use Case - Integrating JavaScript in QML
7\brief Example of how to integrate JavaScript code in QML views
8
9JavaScript code can be easily integrated into QML to provide UI logic,
10imperative control, or other benefits.
11
12\section1 Using JavaScript expressions for property values
13
14JavaScript expressions can be used in QML as bindings. For example:
15\code
16Item {
17 width: Math.random()
18 height: width < 100 ? 100 : (width + 50) / 2
19}
20\endcode
21
22Note that function calls, like Math.random(), will not be reevaluated unless
23their arguments change. So binding to Math.random() will be one random number
24and not reevaluated, but if the width is changed in some other manner, the
25height binding will be reevaluated to take that into account.
26
27\section1 Adding JavaScript functions in QML
28
29JavaScript functions can be declared on QML items, like in the below example.
30This allows you to call the method using the item id.
31
32\snippet qmlapp/usecases/integratingjs-inline.qml 0
33
34\section1 Using JavaScript files
35
36JavaScript files can be used for abstracting out logic from QML files. To do
37this, first place your functions inside a .js file like in the example shown.
38
39\snippet qmlapp/usecases/myscript.js 0
40
41Then import the file into any .qml file that needs to use the functions, like
42the example QML file below.
43
44\snippet qmlapp/usecases/integratingjs.qml 0
45
46\image qmlapp/qml-uses-integratingjs.png
47
48For further details on the JavaScript engine used by QML, as well as the
49difference from browser JS, see the full documentation on \l {JavaScript
50Expressions in QML Documents}.
51
52*/