Use Case - Visual Elements In QML
The Rectangle Type
对于最基本的视觉效果,Qt Quick提供了一个Rectangle类型来绘制矩形。这些矩形可以用颜色或垂直渐变着色。Rectangle类型也可以在矩形上绘制边框。
要绘制超出矩形的自定义形状,请参阅Canvas类型或使用Image类型显示预渲染图像。
import QtQuick 2.3 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" } }
The Image Type
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 Multimedia模块。
Shared Visual Properties
Qt Quick提供的所有可视项目均基于项目类型,该类型为视觉项目提供了一组通用属性,包括不透明度和变换属性。
Opacity and Visibility
Qt Quick提供的QML对象类型内置支持不透明度。可以对不透明度进行动画处理以允许平滑过渡到透明状态或从透明状态过渡。还可以使用visible属性更有效地管理可见性,但代价是无法为其设置动画。
import QtQuick 2.3 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" } } }
Transforms
Qt Quick类型内置了对转换的支持。如果希望旋转或缩放可视内容,可以设置Item :: rotation或Item :: scale属性。这些也可以动画。
import QtQuick 2.3 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属性。