QML如何不使用Canvas实现单侧带圆角且带边框的Rectangle组件
QML单侧圆角带边框Rectangle实现方案(无需Canvas)
方案1:使用Shape组件(推荐,最简洁)
Qt 5.10及以上版本自带QtQuick.Shapes模块,无需依赖Canvas,可直接绘制自定义圆角路径,边框一次性渲染不会出现重叠问题,你可以自由调整路径来控制任意一侧的圆角属性:
import QtQuick 2.10 import QtQuick.Shapes 1.0 import QtQuick.Window 2.2 Window { width: 200 height: 200 visible: true Shape { width: 100 height: 50 anchors.centerIn: parent // 填充色设置 fillColor: "blue" // 边框全局设置,无重叠问题 strokeColor: "black" strokeWidth: 2 ShapePath { // 示例为左侧带圆角、右侧直角的路径,可按需调整圆弧位置修改圆角侧 startX: 10; startY: 0 Line { x: 100; y: 0 } Line { x: 100; y: 50 } Line { x: 10; y: 50 } Arc { radiusX: 10; radiusY: 10 direction: Arc.Counterclockwise endX: 0; endY: 40 } Line { x:0; y:10 } Arc { radiusX:10; radiusY:10 direction: Arc.Counterclockwise endX:10; endY:0 } } } }
方案2:兼容低版本Qt的层叠优化方案
如果项目需要支持Qt 5.10以下版本,无法使用Shape组件,可以优化你原来的层叠逻辑,把边框和填充拆分实现,仅在最外层绘制一次边框,即可解决重叠问题:
import QtQuick 2.5 import QtQuick.Window 2.2 Window { width: 200 height: 200 visible: true // 外层仅负责绘制边框 Rectangle { width: 100 height: 50 color: "transparent" border.color: "black" border.width: 2 anchors.centerIn: parent // 裁切内部超出边框的内容 clip: true // 内部绘制单侧圆角填充 Item { anchors.fill: parent layer.enabled: true opacity: 0.5 Rectangle { color: "blue" radius: 10 anchors.fill: parent } Rectangle { color: "blue" anchors.fill: parent anchors.leftMargin: 10 } } } }
内容的提问来源于stack exchange,提问作者User7723337
相关产品推荐
相关产品推荐

