Integração de JavaScript no QML
O código JavaScript pode ser facilmente integrado ao QML para fornecer lógica de interface do usuário, controle imperativo ou outros benefícios.
Usando expressões JavaScript para valores de propriedades
Expressões JavaScript podem ser usadas no QML como ligações. Por exemplo:
Item {
width: Math.random()
height: width < 100 ? 100 : (width + 50) / 2
}Observe que chamadas de função, como Math.random(), não serão reavaliadas a menos que seus argumentos sejam alterados. Portanto, a ligação a Math.random() resultará em um número aleatório e não será reavaliada; porém, se a largura for alterada de alguma outra forma, a ligação de altura será reavaliada para levar isso em conta.
Adicionando funções JavaScript no QML
Funções JavaScript podem ser declaradas em itens QML, como no exemplo abaixo. Isso permite que você chame o método usando o ID do item.
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 } }
}
}Usando arquivos JavaScript
Arquivos JavaScript podem ser usados para abstrair a lógica dos arquivos QML. Para fazer isso, primeiro coloque suas funções dentro de um arquivo .js, como no exemplo mostrado.
// myscript.js
function getRandom(previousValue) {
return Math.floor(previousValue + Math.random() * 90) % 360;
}Em seguida, importe o arquivo para qualquer arquivo .qml que precise usar as funções, como no arquivo QML de exemplo abaixo.
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 mais detalhes sobre o mecanismo de JavaScript usado pelo QML, bem como a diferença em relação ao JavaScript dos navegadores, consulte a documentação completa sobre Expressões JavaScript em 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.