前言
通过QML的QtGraphicalEffects模块实现的透明,可以使用FastBlur或GaussianBlur。
一、效果
二、代码
1.模块代码
//Rect_blur.qml
import QtQuick 2.0
import QtGraphicalEffects 1.14
Rectangle {
property Item m_source
property bool m_dragable: true //未使用
property color border_color: "transparent"
property int border_radius: 10
property int blur_radius: 32
id:blur_rect
width: 100
height: 100
radius: border_radius
clip: true
MouseArea {
anchors.fill: parent
drag.target: parent
drag.axis: Drag.XAndYAxis
}
Rectangle{
id:blur_1
anchors.fill: parent
clip: true
visible:false
FastBlur{
id:blur
width: m_source.width
height: m_source.height
source:m_source
x:-blur_rect.x
y:-blur_rect.y
radius: blur_radius
}
}
Rectangle{//遮罩
id:mask
anchors.centerIn: parent
width: parent.width+2//+2 去掉边缘遮罩层边缘漏色,不知道为啥??
height: parent.height+2
color: "red"
radius: border_radius
visible: false
}
OpacityMask {
anchors.fill: mask
source:blur_1
maskSource:mask
}
Rectangle{//边框
anchors.fill: parent
border.color: border_color
border.width: 1
color: "transparent"
radius: border_radius
}
}
2.简单使用
代码如下(示例):
Rect_blur{
m_source: image_bg
width: 100
height: 100
}
3.例子中的使用
//main.qml
import QtQuick 2.6
import QtQuick.Window 2.2
import QtQuick.Controls 2.12
import QtGraphicalEffects 1.14
Window {
id:wind
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Item {
id:topcontent
anchors.fill: parent
//底部菜单之外的部分
Item {
id: content
anchors.fill: parent
z : 1
Image {//背景图片
id:image_bg
anchors.fill: parent
source: "qrc:/icon/nunzio-guerrera-x5mTFgOD6M8-unsplash.jpg"
}
Rect_blur{
m_source: image_bg
x:500; y:200
width: 100; height: 100
border_color: "red"
}
Rectangle{
width: 100; height: 100
x:100; y:200
MouseArea {
anchors.fill: parent
drag.target: parent
drag.axis: Drag.XAndYAxis
}
}
}
//底部菜单
Rect_blur{
m_source: content
height: 60
width: parent.width-60
z : 2
anchors.bottom: parent.bottom
anchors.bottomMargin: 20
anchors.horizontalCenter: parent.horizontalCenter
blur_radius: 40
border_radius: 20
ListView{
anchors.fill: parent
orientation: Qt.Horizontal
model:10
delegate: Button{
anchors.verticalCenter: parent.verticalCenter
icon.source:"qrc:/icon/icons8_lol_480px.png"
icon.color: "transparent"
background: Rectangle{
color: "transparent"
}
onClicked: {
popup.open()
}
}
}
}
}
//弹出菜单
Popup{
id:popup
anchors.centerIn: parent
width: 200; height: 200
modal:true; dim:true
Text {
anchors.centerIn: parent
text: qsTr("Popup")
}
Overlay.modal: Rect_blur{
m_source:topcontent
blur_radius: 20
opacity:0.6
}
}
}
总结
OpacityMask 的makesource使用rectangle时,如果设置rectangle圆角,圆角处会漏出rectangle的底色,目前是加宽了rectangle的大小解决