QtQuick CircularGauge实现指针后动态背景mask裁切问题求解
实现方案
核心用OpacityMask配合动态扇形遮罩实现,确保遮罩与蓝色背景图尺寸、位置完全对齐,避免裁切问题,修改后完整代码如下:
import QtQuick 2.7 import QtQuick.Controls 2.0 import QtQuick.Window 2.15 import QtQuick.Controls.Styles 1.4 import QtQuick.Extras 1.4 import QtQuick.Extras.Private 1.0 import QtGraphicalEffects 1.0 import QtQuick.Shapes 1.0 // 新增Shape模块用于绘制动态扇形遮罩 Window { width: 1280 height: 480 visible: true title: qsTr("Hello World") color: "#000" CircularGauge { id:gauge property bool accelerating width: 377 height: 377 anchors.top: parent.top anchors.horizontalCenter: parent.horizontalCenter anchors.topMargin: 101 maximumValue:8 value: accelerating ? maximumValue : 0 Component.onCompleted: forceActiveFocus() Behavior on value { NumberAnimation { duration: 1500 }} Keys.onSpacePressed: accelerating = true Keys.onReleased: { if (event.key === Qt.Key_Space) { accelerating = false; event.accepted = true; } } style: CircularGaugeStyle { labelStepSize: 1 labelInset: outerRadius / 6 minimumValueAngle: -110 maximumValueAngle: 110 // 总可转动角度 readonly property real totalAngle: maximumValueAngle - minimumValueAngle background: Rectangle { id: bgRect implicitHeight: gauge.height implicitWidth: gauge.width color:"Transparent" anchors.centerIn: parent radius: 360 // 动态蓝色背景层 OpacityMask { anchors.fill: blueBg source: blueBg maskSource: progressMask } // 原始蓝色背景图,位置尺寸保持原配置 Image { id: blueBg width: 417 height: 287 anchors.top: parent.top source: "Blue_bg.png" anchors.topMargin: -23 anchors.horizontalCenter: parent.horizontalCenter asynchronous: true } // 动态扇形遮罩,和背景图完全同尺寸同位置,避免裁切 Shape { id: progressMask anchors.fill: blueBg // 把坐标原点移到遮罩中心,和仪表盘中心对齐 transform: Translate { x: progressMask.width / 2 y: progressMask.height / 2 } ShapePath { fillColor: "white" startX: 0 startY: -outerRadius PathAngleArc { centerX: 0 centerY: 0 radius: outerRadius + 50 // 半径比仪表盘大,覆盖完整背景图 // 起始角度和仪表盘一致,修正角度偏移匹配仪表盘逻辑 startAngle: styleData.minimumValueAngle - 90 // 扫过角度随当前值动态计算 sweepAngle: (gauge.value / gauge.maximumValue) * styleData.totalAngle moveToStart: false } PathLine { x: 0 y: 0 } } } } foreground: Item { Text { id: speedLabel anchors.centerIn: parent anchors.verticalCenterOffset: -20 text: "126" font.pixelSize:76 color: "white" antialiasing: true } } tickmarkLabel: Text { font.italic: true font.bold: true text: styleData.value font.pixelSize: 30 color: styleData.value <= gauge.value ? "white" : "#ffffff" antialiasing: true } } } }
关键说明
- 遮罩层
progressMask和蓝色背景图blueBg完全同尺寸同定位,不会限制在仪表盘的圆形边界内,解决了之前的裁切问题 - 扇形遮罩的角度范围和仪表盘角度配置完全同步,进度和指针转动逻辑一致
- 遮罩半径设置大于仪表盘外半径,确保完整覆盖背景图所有区域
内容的提问来源于stack exchange,提问作者Антон Антонов
相关产品推荐
相关产品推荐

