QML绘图指令大全
时间: 2025-05-18 15:51:20 浏览: 14
### QML绘图指令与方法
QML 提供了一组丰富的绘图功能,允许开发者通过简单的声明式语法实现复杂的视觉效果。以下是 QML 中常用的绘图指令和方法:
#### 1. 基础绘图组件
- **Rectangle**: 创建矩形形状,支持填充颜色、边框样式等属性。
```qml
Rectangle {
width: 100
height: 50
color: "blue"
border.width: 2
border.color: "black"
}
```
- **Image**: 加载并显示图像资源。
```qml
Image {
source: "image.png"
fillMode: Image.PreserveAspectFit
}
```
- **Text**: 显示文本内容,支持字体大小、颜色和其他样式调整。
```qml
Text {
text: "Hello, QML!"
font.pixelSize: 20
color: "white"
}
```
#### 2. 高级绘图 API
对于更复杂的需求,可以使用 `Canvas` 或者基于 Qt Quick Shapes 的模块。
##### Canvas 绘图
`Canvas` 是 QML 中的核心绘图工具之一,它提供了 JavaScript 接口来进行低级别的绘制操作[^2]。
```qml
Canvas {
id: canvas
width: 200
height: 200
onPaint: {
var ctx = canvas.getContext('2d');
ctx.fillStyle = Qt.rgba(1, 0, 0, 1);
ctx.fillRect(0, 0, 100, 100); // 绘制红色正方形
}
}
```
##### Shape 和 Path
Shape 类型允许定义路径 (Path),从而轻松创建矢量图形[^3]。
```qml
import QtQuick.Shapes 1.15
Shape {
ShapePath {
strokeWidth: 4
strokeColor: "green"
fillColor: "lightGreen"
startX: 20; startY: 20
PathLine { x: 80; y: 20 }
PathLine { x: 80; y: 80 }
PathLine { x: 20; y: 80 }
PathLine { x: 20; y: 20 }
}
}
```
#### 3. 动画与变换
动画可以通过 `NumberAnimation`, `PropertyAnimation` 等类型实现,而变换则由 `Rotation`, `Scale`, `Translate` 控件完成[^1]。
```qml
Rectangle {
width: 100
height: 100
color: "red"
NumberAnimation on x {
from: 0
to: parent.width - width
duration: 2000
loops: Animation.Infinite
}
Rotation {
origin.x: 50
origin.y: 50
angle: 45
}
}
```
#### 4. 数据可视化
为了更好地呈现数据,通常会结合模型视图架构以及自定义的图表控件。
```qml
ListView {
model: ListModel {
ListElement { name: "Item 1"; value: 10 }
ListElement { name: "Item 2"; value: 20 }
}
delegate: Row {
Text { text: name }
ProgressBar { value: value / 100; width: 100 }
}
}
```
---
###
阅读全文
相关推荐


















