用例 - QML中的视觉元素¶
如何在QML应用程序中显示视觉项目类型的示例
矩形类型¶
对于最基本的视觉效果,Qt Quick 提供了一个 Rectangle 类型来绘制矩形。这些矩形可以用颜色或垂直渐变来填充。Rectangle 类型还可以在矩形上绘制边框。
要绘制矩形以外的自定义形状,请参阅Canvas类型或使用Image类型显示预渲染的图像。
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 提供了一个 Image 类型,可用于显示图像。Image 类型有一个 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多媒体模块。
不透明度和可见性¶
Qt Quick 提供的 QML 对象类型内置了对不透明度的支持。不透明度可以动画化,以实现平滑过渡到或从透明状态。可见性也可以通过 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属性。