用例 - QML 中的可视化元素
矩形类型
用于最基本的视觉效果、 Qt Quick提供了一个Rectangle 类型来绘制矩形。这些矩形可以用颜色或垂直梯度着色。Rectangle 类型还能在矩形上绘制边框。
要绘制矩形以外的自定义形状,请参阅Canvas 类型,或使用图像类型显示预渲染图像。
import QtQuick Item { width: 320 height: 480 Rectangle { color: "#272822" width: 320 height: 480 } // This element displays a rectangle with a gradient and a border Rectangle { x: 160 y: 20 width: 100 height: 100 radius: 8 // This gives rounded corners to the Rectangle gradient: Gradient { // This sets a vertical gradient fill GradientStop { position: 0.0; color: "aqua" } GradientStop { position: 1.0; color: "teal" } } border { width: 3; color: "white" } // This sets a 3px wide black border to be drawn } // This rectangle is a plain color with no border Rectangle { x: 40 y: 20 width: 100 height: 100 color: "red" } }
图像类型
Qt Quick提供的图像类型可用于显示图像。图像类型有一个source 属性,其值可以是远程或本地 URL,也可以是嵌入在已编译资源文件中的图像文件的 URL。
// This element displays an image. Because the source is online, it may take some time to fetch Image { x: 40 y: 20 width: 61 height: 73 source: "http://codereview.qt-project.org/static/logo_qt.png" }
对于更复杂的图像,还有其他与Image 相似的类型。BorderImage 可绘制具有网格缩放功能的图像,适用于用作边框的图像。AnimatedImage 可播放 .gif 和 .mng 动画图片。AnimatedSprite 和SpriteSequence 可播放以非动画图像格式相邻存储的多帧动画。
要显示视频文件和摄像机数据,请参阅 Qt Multimedia模块。
共享可视化属性
由 Qt Quick提供的所有可视化项都基于项类型,该类型为可视化项提供了一组通用属性,包括不透明度和变换属性。
不透明度和可见性
Qt Quick 提供的 QML 对象类型内置了对opacity 的支持。不透明度可通过动画实现从透明状态到透明状态的平滑过渡。可见性也可以用visible 属性更有效地管理,但代价是不能动画化。
import QtQuick Item { width: 320 height: 480 Rectangle { color: "#272822" width: 320 height: 480 } Item { x: 20 y: 270 width: 200 height: 200 MouseArea { anchors.fill: parent onClicked: topRect.visible = !topRect.visible } Rectangle { x: 20 y: 20 width: 100 height: 100 color: "red" } Rectangle { id: topRect opacity: 0.5 x: 100 y: 100 width: 100 height: 100 color: "blue" } } }
变换
Qt Quick 类型内置了对变换的支持。如果希望旋转或缩放可视内容,可以设置 或 属性。这些属性也可以制作动画。Item::rotation Item::scale
import QtQuick Item { width: 320 height: 480 Rectangle { color: "#272822" width: 320 height: 480 } Rectangle { rotation: 45 // This rotates the Rectangle by 45 degrees x: 20 y: 160 width: 100 height: 100 color: "blue" } Rectangle { scale: 0.8 // This scales the Rectangle down to 80% size x: 160 y: 160 width: 100 height: 100 color: "green" } }
如需更复杂的变换,请参阅Item::transform 属性。
© 2025 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.