repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/skills/qml/references/javascript.md

Raw

JavaScript in QML

Every QML expression is JavaScript. You can write property int x: 1 + 2, run a loop in a function, or import a full .js file.

Inline expressions

Item {
    property int doubled: count * 2
    visible: name.length > 0
    color: enabled ? "red" : "gray"
    text: `Hello, ${name}!`         // template literal
}

Most expressions are JS. Multi-line:

property var result: {
    const x = compute(x)
    const y = compute(y)
    return x + y
}

Functions

Item {
    function square(x: int): int { return x * x }
    function notify(msg: string): void { console.log(msg) }

    Component.onCompleted: notify("x² = " + square(5))
}

Type annotations (int, string, void) are optional. The function body is full JS.

Lambdas

Item {
    property var adder: (a, b) => a + b
    property var doubler: (x) => x * 2

    Button {
        onClicked: (mouse) => console.log("at", mouse.x, mouse.y)
    }
}

Lambdas (arrow functions) work anywhere a function is expected. The most common use: signal handler with arguments.

Property aliases to functions

You can't property alias a function, but you can wrap it:

// MyButton.qml
Button {
    property var onActivate: () => {}
    onClicked: onActivate()
}

Imports

// helpers.js
.pragma library

function format(n) { return n.toFixed(2) }
function greet(name) { return `Hello, ${name}` }
// Consumer
import "helpers.js" as Helpers

Item {
    Text { text: Helpers.greet("world") }
    Text { text: Helpers.format(3.14159) }
}

.pragma library (in the .js file) makes the file a stateless library — its top-level state is shared across all importers, not per-importer.

Captures

QML objects can be captured by id and used inside JS:

Item {
    id: root
    property int count: 0
    Timer {
        interval: 1000; running: true; repeat: true
        onTriggered: root.count++    // bind through id, not closure
    }
}

Capturing root (by id) is the canonical way. Closures over local variables work but are less reliable across re-instantiation.

Qt.* helpers

Qt.formatDate(date, "yyyy-MM-dd")
Qt.formatTime(date, "HH:mm:ss")
Qt.formatDateTime(date, "yyyy-MM-dd HH:mm")
Qt.rgba(0.5, 0, 0, 1)
Qt.hsva(h, s, v, a)
Qt.lighter(color, factor)
Qt.darker(color, factor)
Qt.tint(baseColor, tintColor)
Qt.callLater(fn, ...args)            // schedule fn for next event loop tick
Qt.application.name
Qt.application.version
Qt.platform.os                       // "linux", "windows", "osx", "android", "ios"
Qt.platform.osVersion
Qt.inputMethod                       // IM state
Qt.styleHints                       // UI style hints

Qt.callLater is the right way to defer work to the next event-loop iteration (without a Timer).

Object literals

QML objects are JS objects with type semantics. You can construct them in JS:

property var point: Qt.point(10, 20)
property var size: Qt.size(100, 50)
property var rect: Qt.rect(0, 0, 100, 50)
property var list: ["a", "b", "c"]
property var map: ({ a: 1, b: 2 })

Mutating a var doesn't trigger binding updates (the binding tracks property reads, not deep changes). For observable state, use Q_PROPERTY on a C++ object, or a ListModel.

Async work

QML doesn't have native promises but has some workarounds:

Item {
    Timer {
        interval: 100
        running: true
        onTriggered: doDeferredWork()
    }
}

// Or chain with Qt.callLater
function doChain() {
    step1()
    Qt.callLater(() => { step2(); Qt.callLater(step3) })
}

For real async, use a WorkerScript (deprecated in Qt 6) or a C++ QObject with Q_INVOKABLE methods that return a QFuture (Qt 6+).

Iterating

property var items: [1, 2, 3, 4, 5]

// for-of
for (const x of items) console.log(x)

// for-in (over keys, for plain objects)
for (const k in ({a: 1, b: 2})) console.log(k, ":", this[k])

// map
const doubled = items.map(x => x * 2)

// filter
const evens = items.filter(x => x % 2 === 0)

// reduce
const sum = items.reduce((acc, x) => acc + x, 0)

JS array methods work as expected. Note: the result is a plain JS array, not a model — bindings to it won't reactively update.

Strings

property var s: "Hello, World"

s.length                          // 12
s.indexOf("World")                // 7
s.toUpperCase()                   // "HELLO, WORLD"
s.split(", ")                     // ["Hello", "World"]
s.startsWith("Hello")             // true
s.includes("World")               // true
s.replace("World", "QML")         // "Hello, QML"
s.padStart(20, "-")               // "-------Hello, World"

Number.toFixed(2), Date.toISOString(), Math.PI, JSON.parse, JSON.stringify all work.

Common mistakes

When to use JS vs C++

Use JS for Use C++ for
Property expressions High-performance loops over millions of items
Small algorithms (sort, filter) Database access
UI glue (toggle, format) Image processing
One-time setup Heavy data models
Validation Network I/O

For anything CPU-bound or data-heavy, push it to C++ via Q_INVOKABLE and Q_PROPERTY and bind to the result.

Markdown source
File outline
# JavaScript in QML

Every QML expression is JavaScript. You can write `property int x: 1 + 2`, run a loop in a function, or import a full `.js` file.

## Inline expressions

```qml
Item {
    property int doubled: count * 2
    visible: name.length > 0
    color: enabled ? "red" : "gray"
    text: `Hello, ${name}!`         // template literal
}
```

Most expressions are JS. Multi-line:

```qml
property var result: {
    const x = compute(x)
    const y = compute(y)
    return x + y
}
```

## Functions

```qml
Item {
    function square(x: int): int { return x * x }
    function notify(msg: string): void { console.log(msg) }

    Component.onCompleted: notify("x² = " + square(5))
}
```

Type annotations (`int`, `string`, `void`) are optional. The function body is full JS.

## Lambdas

```qml
Item {
    property var adder: (a, b) => a + b
    property var doubler: (x) => x * 2

    Button {
        onClicked: (mouse) => console.log("at", mouse.x, mouse.y)
    }
}
```

Lambdas (arrow functions) work anywhere a function is expected. The most common use: signal handler with arguments.

## Property aliases to functions

You can't `property alias` a function, but you can wrap it:

```qml
// MyButton.qml
Button {
    property var onActivate: () => {}
    onClicked: onActivate()
}
```

## Imports

```qml
// helpers.js
.pragma library

function format(n) { return n.toFixed(2) }
function greet(name) { return `Hello, ${name}` }
```

```qml
// Consumer
import "helpers.js" as Helpers

Item {
    Text { text: Helpers.greet("world") }
    Text { text: Helpers.format(3.14159) }
}
```

`.pragma library` (in the .js file) makes the file a stateless library — its top-level state is shared across all importers, not per-importer.

## Captures

QML objects can be captured by id and used inside JS:

```qml
Item {
    id: root
    property int count: 0
    Timer {
        interval: 1000; running: true; repeat: true
        onTriggered: root.count++    // bind through id, not closure
    }
}
```

Capturing `root` (by id) is the canonical way. Closures over local variables work but are less reliable across re-instantiation.

## `Qt.*` helpers

```qml
Qt.formatDate(date, "yyyy-MM-dd")
Qt.formatTime(date, "HH:mm:ss")
Qt.formatDateTime(date, "yyyy-MM-dd HH:mm")
Qt.rgba(0.5, 0, 0, 1)
Qt.hsva(h, s, v, a)
Qt.lighter(color, factor)
Qt.darker(color, factor)
Qt.tint(baseColor, tintColor)
Qt.callLater(fn, ...args)            // schedule fn for next event loop tick
Qt.application.name
Qt.application.version
Qt.platform.os                       // "linux", "windows", "osx", "android", "ios"
Qt.platform.osVersion
Qt.inputMethod                       // IM state
Qt.styleHints                       // UI style hints
```

`Qt.callLater` is the right way to defer work to the next event-loop iteration (without a `Timer`).

## Object literals

QML objects are JS objects with type semantics. You can construct them in JS:

```qml
property var point: Qt.point(10, 20)
property var size: Qt.size(100, 50)
property var rect: Qt.rect(0, 0, 100, 50)
property var list: ["a", "b", "c"]
property var map: ({ a: 1, b: 2 })
```

Mutating a `var` doesn't trigger binding updates (the binding tracks property reads, not deep changes). For observable state, use `Q_PROPERTY` on a C++ object, or a ListModel.

## Async work

QML doesn't have native promises but has some workarounds:

```qml
Item {
    Timer {
        interval: 100
        running: true
        onTriggered: doDeferredWork()
    }
}

// Or chain with Qt.callLater
function doChain() {
    step1()
    Qt.callLater(() => { step2(); Qt.callLater(step3) })
}
```

For real async, use a `WorkerScript` (deprecated in Qt 6) or a C++ QObject with `Q_INVOKABLE` methods that return a `QFuture` (Qt 6+).

## Iterating

```qml
property var items: [1, 2, 3, 4, 5]

// for-of
for (const x of items) console.log(x)

// for-in (over keys, for plain objects)
for (const k in ({a: 1, b: 2})) console.log(k, ":", this[k])

// map
const doubled = items.map(x => x * 2)

// filter
const evens = items.filter(x => x % 2 === 0)

// reduce
const sum = items.reduce((acc, x) => acc + x, 0)
```

JS array methods work as expected. Note: the result is a plain JS array, not a model — bindings to it won't reactively update.

## Strings

```qml
property var s: "Hello, World"

s.length                          // 12
s.indexOf("World")                // 7
s.toUpperCase()                   // "HELLO, WORLD"
s.split(", ")                     // ["Hello", "World"]
s.startsWith("Hello")             // true
s.includes("World")               // true
s.replace("World", "QML")         // "Hello, QML"
s.padStart(20, "-")               // "-------Hello, World"
```

`Number.toFixed(2)`, `Date.toISOString()`, `Math.PI`, `JSON.parse`, `JSON.stringify` all work.

## Common mistakes

- **Heavy work in a binding** — bindings re-evaluate on every dependency change. Long-running JS in a binding blocks the UI. Use a function called from a `Timer` instead.
- **Mutating a `var` property** — the binding doesn't re-evaluate. Use a real `Q_PROPERTY` or replace the whole var.
- **Using `this` in a delegate** — `this` refers to the delegate context, which can be confusing. Bind by id or by the model role.
- **Forgetting `Qt.callLater` for cross-binding side-effects** — if a binding changes a property that another binding depends on, you can get a binding loop. Defer with `Qt.callLater`.
- **Capturing local variables in a long-lived closure** — they don't update. Bind to a property instead.

## When to use JS vs C++

| Use JS for                      | Use C++ for                                   |
| ------------------------------- | --------------------------------------------- |
| Property expressions            | High-performance loops over millions of items |
| Small algorithms (sort, filter) | Database access                               |
| UI glue (toggle, format)        | Image processing                              |
| One-time setup                  | Heavy data models                             |
| Validation                      | Network I/O                                   |

For anything CPU-bound or data-heavy, push it to C++ via `Q_INVOKABLE` and `Q_PROPERTY` and bind to the result.