Qt Quick 中实现一个无边框窗口阴影效果的中心思想是将 Window 容器背景设置为透明的,在 Windows 容器中添加一个填满窗口的容器(如 Page、Rectangle 等),然后将这个容器设置一些边距,再给这个容器附加一个阴影效果,实现的效果如下: 注意:本文所描述的方案会有严重的性能损耗,尤其是在 2k 4k 显示器上性能损耗严重、帧率极低,如非特殊需求,建议不使用类似方案。

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12
import QtGraphicalEffects 1.0

Window {
id: mainWindow
visible: true
width: 640
height: 480
title: qsTr("Hello World")
// 无边框窗口
flags: Qt.Window Qt.FramelessWindowHint
// 设置窗口背景色为透明
color: "#00000000"

Rectangle {
id: mainLayout
// 一个填满窗口的容器,Page、Rectangle 都可以
anchors.fill: parent
// 当窗口全屏时,设置边距为 0,则不显示阴影,窗口化时设置边距为 10 就可以看到阴影了
anchors.margins: mainWindow.visibility === Window.Maximized ? 0 : 10
}

DropShadow {
anchors.fill: mainLayout
horizontalOffset: 1
verticalOffset: 1
radius: 8
samples: 16
source: mainLayout
color: "#33333F"
Behavior on radius { PropertyAnimation { duration: 100 } }
}
}

这样设置后可以看到窗口阴影的效果,但是还是有一些缺点的, 当你使用一些 Dialog、Popup 控件时,并设置 modal 为 true 的情况下,Dialog 这类浮层窗口会显示一个黑色背景,此时黑色背景的边缘是以 Window 为基础的,而不是我们放到 Window 中的容器。