C++图形用户界面开发框架Qt 6.x入门级教程:用例 – 在QML中集成JavaScript

JavaScript 代码可以很容易地集成到 QML 中,以提供 UI 逻辑、命令式控制或其他。

对属性值使用 JavaScript 表达式

JavaScript 表达式可以在 QML 中用作绑定,例如:

Item {width: Math.random()height: width < 100 100 : (width + 50) / 2}

请注意,函数调用,如 Math.random(),不会被重新评估,除非它们的参数发生变化。 所以绑定到 Math.random() 将是一个随机数并且不会重新计算,但如果宽度以其他方式改变,高度绑定将被重新计算以考虑到这一点。

在QML中添加JavaScript函数

可以在QML项目上声明JavaScript函数,如下例所示,这允许您使用项目ID调用该方法。

import QtQuickItem {id: containerwidth: 320height: 480function randomNumber() {return Math.random() * 360;}function getNumber() {return container.randomNumber();}TapHandler {// This line uses the JS function from the itemonTapped: rectangle.rotation = container.getNumber();}Rectangle {color: "#272822"width: 320height: 480}Rectangle {id: rectangleanchors.centerIn: parentwidth: 160height: 160color: "green"Behavior on rotation { RotationAnimation { direction: RotationAnimation.Clockwise } }}}
使用 JavaScript 文件

JavaScript 文件可用于从 QML 文件中抽象出逻辑。 为此,首先将您的函数放入 .js 文件中,如示例所示。

// myscript.jsfunction getRandom(previousValue) {return Math.floor(previousValue + Math.random() * 90) % 360;}

然后将该文件导入到任何需要使用这些函数的 .qml 文件中,例如下面的示例 QML 文件。

import QtQuickimport "myscript.js" as LogicItem {width: 320height: 480Rectangle {color: "#272822"width: 320height: 480}TapHandler {// This line uses the JS function from the separate JS fileonTapped: rectangle.rotation = Logic.getRandom(rectangle.rotation);}Rectangle {id: rectangleanchors.centerIn: parentwidth: 160height: 160color: "green"Behavior on rotation { RotationAnimation { direction: RotationAnimation.Clockwise } }}}

C++图形用户界面开发框架Qt 6.x入门级教程:用例 - 在QML中集成JavaScript
Qt商用组件推荐
  • QtitanRibbon – Ribbon UI组件:是一款遵循Microsoft Ribbon UI Paradigm for Qt技术的Ribbon UI组件,QtitanRibbon致力于为Windows、Linux和Mac OS X提供功能完整的Ribbon组件。
  • QtitanChart – Qt类图表组件:是一个C ++库,代表一组控件,这些控件使您可以快速地为应用程序提供漂亮而丰富的图表。
  • QtitanNavigation:QtitanNavigationDesignUI 组件是一组 GUI 控件,它实现了菜单、导航框、命令栏等导航界面,并让您以更少的滚动和点击次数有效地查看所有实体(工作区、 格或其他项目)。
  • QtitanDocking:允许您像 Visual Studio 一样为您的伟大应用程序配备可停靠面板和可停靠工具栏。黑色、白色、蓝色调色板完全支持 Visual Studio 2019 主题!

Qt技术交流群:166830288      欢迎一起进群讨论

更多Qt产品教程、下载、正版授权资讯,请点击获取

标签:

声明:本站部分文章及图片源自用户投稿,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!

上一篇 2022年1月18日
下一篇 2022年1月18日

相关推荐

发表回复

登录后才能评论