我對 QML 很陌生,我想制作一個基本應用程式,它由一個包含 20-30 段(披薩片)的分段圓和一個計數器組成。計數器上的數字是突出顯示的段數。我找到了一些在其他問題中制作分段圓圈的方法,但不幸的是,它們似乎都不適用于我的作業。
我現在看到的唯一方法是每次更改計數器時重新繪制所有段,并更改所需段的顏色。那么有沒有最佳的方法來實作呢?
uj5u.com熱心網友回復:
為了降低復雜性,讓我們通過一個簡化版本的問題來解決:
- 假設有 6 件
- 假設我們要繪制第 2 塊
- 假設我們想把它放在一個 300x300 的矩形中
這是數學:
- 每片將占據 60 度(即 360 / 6)
- 塊 2 將占據從 120 到 180 的角度
要渲染這幅作品,繪圖將是:
- 從中心點 (150, 150)
- 然后 (150 150 * cos(120), 150 150 * sin(120))
- 然后 (150 150 * cos(180), 150 150 * sin(180))
- 然后回到中心點 (150, 150)
我們想在點 2 和點 3 之間畫一條曲線,而不是一條直線。
要渲染它,我們可以使用Shape、ShapePath、PathLine和PathArc。
為了概括,我們可以用 20 代替 6 并相應地概括所有公式。要繪制 20 個切片,我們可以使用中繼器,例如
Repeater {
model: 20
PizzaPiece {
piece: index
}
}
為了完善它,我添加了一個Slider,這樣您就可以互動式地從 0-20 更改您想要的件數并將顏色設定為"orange",否則它將是淺黃色"#ffe"。
Repeater {
model: 20
PizzaPiece {
piece: index
fillColor: index < slider.value ? "orange" : "#ffe"
}
}
Slider {
id: slider
from: 0
to: 20
stepSize: 1
}
作為額外的獎勵,我添加了一個TapHandler,以便每個部分都是可點擊的。如果您一直按住滑鼠,則該棋子將顯示為“紅色”,直到您松開滑鼠。
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
Page {
id: page
property int pieces: 20
Rectangle {
anchors.centerIn: parent
width: 300
height: 300
border.color: "grey"
Repeater {
model: pieces
PizzaPiece {
anchors.fill: parent
anchors.margins: 10
pieces: page.pieces
piece: index
fillColor: pressed ? "red" : index < slider.value ? "orange" : "#ffe"
onClicked: {
slider.value = index 1;
}
}
}
}
footer: Frame {
RowLayout {
width: parent.width
Label {
text: slider.value
}
Slider {
id: slider
Layout.fillWidth: true
from: 0
to: pieces
value: 3
stepSize: 1
}
}
}
}
//PizzaPiece.qml
import QtQuick
import QtQuick.Shapes
Shape {
id: pizzaPiece
property int pieces: 20
property int piece: 0
property real from: piece * (360 / pieces)
property real to: (piece 1) * (360 / pieces)
property real centerX: width / 2
property real centerY: height / 2
property alias fillColor: shapePath.fillColor
property alias strokeColor: shapePath.strokeColor
property alias pressed: tapHandler.pressed
property real fromX: centerX centerX * Math.cos(from * Math.PI / 180)
property real fromY: centerY centerY * Math.sin(from * Math.PI / 180)
property real toX: centerX centerX * Math.cos(to * Math.PI / 180)
property real toY: centerY centerY * Math.sin(to * Math.PI / 180)
signal clicked()
containsMode: Shape.FillContains
ShapePath {
id: shapePath
fillColor: "#ffe"
strokeColor: "grey"
startX: centerX; startY: centerY
PathLine { x: fromX; y: fromY }
PathArc {
radiusX: centerX; radiusY: centerY
x: toX; y: toY
}
PathLine { x: centerX; y: centerY }
}
TapHandler {
id: tapHandler
onTapped: pizzaPiece.clicked()
}
}
您可以在線試用!
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/531680.html
標籤:qt制作qml形状
