前言

QML中有时候需要实现一些特殊定制化页面,比如不同的圆角矩形,如果直接用Rectangle控件定义radius圆角属性,会将四个角统一设置成一样的圆角,但是如果仅仅只想实现两个圆角效果,另外两个直角,或者圆角的弧度不同,这时候就不能直接用现有的Rectangle去做了,有两种方法, 一种是直接用Canvas进行绘制,一种是通过Shape组件来实现。
两种方法均可,区别是前者稍微复杂一点,代码量会多一些,后者相对简单点,而且便于封装,多处使用。

本文主要使用Shape来封装一个任意圆角的矩形,方便满足不同需求实现。

先看效果:

QML Shape实现任意圆角Rectangle矩形_圆角


其中第一张是带边框效果,其他几个的圆角大小也是不同的。

正文

话不多说,为了方便在不同的地方使用,直接封装成自定义控件,提供相应的属性便于设置。

上代码:

import QtQuick 2.13
import QtQuick.Controls 2.13
import QtQuick.Shapes 1.13

Shape {
id: shape
property var cornersRadius
property color color
property color borderColor:"transparent"
property int borderWidth: 1
layer.enabled: true
layer.samples: 4
layer.smooth: true


ShapePath {
startX: 0
startY: cornersRadius[0]
fillColor: color
strokeColor: borderColor
strokeWidth: borderWidth
PathQuad { x: cornersRadius[0]; y: 0; controlX: 0; controlY: 0 }
PathLine { x: shape.width - cornersRadius[1]; y: 0 }
PathQuad { x: shape.width; y: cornersRadius[1]; controlX: shape.width; controlY: 0 }
PathLine { x: shape.width; y: shape.height - cornersRadius[2] }
PathQuad { x: shape.width - cornersRadius[2]; y: shape.height; controlX: shape.width; controlY: shape.height }
PathLine { x: cornersRadius[3]; y: shape.height }
PathQuad { x: 0; y: shape.height - cornersRadius[3]; controlX: 0; controlY: shape.height }
PathLine { x: 0; y: cornersRadius[0] }
}
}

test代码

import QtQuick 2.13
import QtQuick.Window 2.13

Window {
width: 740
height: 480
visible: true
title: qsTr("Curved Rectangle Demo")


Row{
spacing: 20
anchors.centerIn: parent

CurvedRectangle{
width: 160
height: 160
color: "cyan"
cornersRadius: [20,0,20,0]
borderWidth:1
borderColor:"grey"
}
CurvedRectangle{
width: 160
height: 160
color: "green"
cornersRadius: [30,50,40,0]

}
CurvedRectangle{
width: 160
height: 160
color: "blue"
cornersRadius: [30,0,0,30]
}
CurvedRectangle{
width: 160
height: 160
color: "red"
cornersRadius: [0,20,20,0]
}
}
}

直接通过cornersRadius属性,指定四个角的圆角大小。若要使用边框,可以设置borderColor和borderWidth, 不设置就默认没有边框。

代码不复杂,不做过多解释,仅此分享。

Enjoy~