QML视觉元素类型
- 一、概述
- 一、图像类型
- 三、共享视觉属性
- 1. 不透明度和可见性
- 2. 转换(转置)
一、概述
对于最基本的视觉效果,Qt Quick提供了一个 Rectangle 类型来绘制矩形。这些矩形可以用颜色或垂直渐变来着色。 Rectangle 还可以在矩形上绘制边框。通过设置border属性,当然可以绘制圆角的,很多QQuick Ctrol 都是用这些rectangle来做的,自定义一些属性也是的。若要绘制矩形以外的自定义形状,请参阅“Canvas”类型 或 使用“Image”类型显示预渲染图像。Canvas 其实就是类似 Qt C++ 里面的 QPainter,可以自定义的绘制一些样式。也是自定义控件或者绘图会使用到的。
import QtQuick 2.3Item {width: 320height: 480Rectangle {color: "#272822"width: 320height: 480}// This element displays a rectangle with a gradient and a borderRectangle {x: 160y: 20width: 100height: 100radius: 8 // This gives rounded corners to the Rectanglegradient: Gradient { // This sets a vertical gradient fillGradientStop { 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 borderRectangle {x: 40y: 20width: 100height: 100color: "red"}}
简单的效果如下图:
一、图像类型
Qt Quick提供了一个Image类型,可以用来显示图像。Image类型有一个source属性,其值可以是远程URL或本地URL,也可以是嵌入在已编译资源文件中的图像文件的URL。
//该元素显示一个图像。因为源是在线的,所以可能需要一些时间来获取
// This element displays an image. Because the source is online, it may take some time to fetchImage {x: 40y: 20width: 61height: 73source: "http://codereview.qt-project.org/static/logo_qt.png"}
对于更复杂的图像,还有其他类似于Image的类型。BorderImage使用网格缩放绘制图像,适用于用作边界的图像。AnimatedImage播放gif和mng动画图像。AnimatedSprite和SpriteSequence播放由多个相邻存储的非动画图像格式的帧组成的动画。
要显示视频文件和相机上数据,请参阅Qt多媒体模块。
三、共享视觉属性
Qt Quick提供的所有可视项都基于Item类型,该类型为可视项提供了一组公共属性,包括不透明度和转换属性。
1. 不透明度和可见性
Qt Quick提供的QML对象类型内置了对不透明度的支持。opacity 可以被动画化,以允许平滑过渡到或从透明状态。可见性也可以更有效地使用 visible 属性进行管理,但代价是不能对其进行动画化。可见性只有两个状态,不具备中间转换状态。
import QtQuick 2.3Item {width: 320height: 480Rectangle {color: "#272822"width: 320height: 480}Item {x: 20y: 270width: 200height: 200MouseArea {anchors.fill: parentonClicked: topRect.visible = !topRect.visible}Rectangle {x: 20y: 20width: 100height: 100color: "red"}Rectangle {id: topRectopacity: 0.5x: 100y: 100width: 100height: 100color: "blue"}}}
2. 转换(转置)
Qt Quick类型有内置的转换支持。如果您希望旋转或缩放可视内容,可以设置 Item::rotation 或 Item::scale 属性。这些也可以被动画化。
import QtQuick 2.3Item {width: 320height: 480Rectangle {color: "#272822"width: 320height: 480}Rectangle {rotation: 45 // This rotates the Rectangle by 45 degreesx: 20y: 160width: 100height: 100color: "blue"}Rectangle {scale: 0.8 // This scales the Rectangle down to 80% sizex: 160y: 160width: 100height: 100color: "green"}}