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,或者是嵌入在已编译资源文件中的图像文件的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提供的所有视觉项目均基于Item类型,该类型为视觉项目提供了一组通用属性,包括不透明度和变换属性。
不透明度和可见性
Qt Quick提供的QML对象类型具有对opacity的内置支持。 可以对不透明度进行动画处理,以实现与透明状态之间的平滑过渡。 还可以通过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属性。