qt托盘菜单半透明

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
QMenu#toptoolbarmenu {
padding: 10px 0;
border-radius: 15px;
background-color: rgba(38, 40, 42, 0.7);
}
QMenu#toptoolbarmenu::separator {
height: 2px;
margin: 6px 0;
background-color: rgba(255, 255, 255, 1);
}
QMenu#toptoolbarmenu::icon {
padding: 0 0 0 10px;
}
QMenu#toptoolbarmenu::item {
color: white;
padding: 3px 10px;
font-weight: bold;
background-color: transparent;
}
QMenu#toptoolbarmenu::item:hover,
QMenu#toptoolbarmenu::item:pressed,
QMenu#toptoolbarmenu::item:selected {
color: rgb(95, 174, 200);
border-radius: 15px;
}
QMenu#toptoolbarmenu::item QLabel {
color: rgb(145, 145, 145);
font-weight: bold;
padding-left: 7px;
margin-bottom: 5px;
background-color: transparent;
}

对话框构造函数

TrayDialog.h

1
2
3
4
5
6
7
8
9
10
11
12

class TrayDialog: public QDialog{
public:
...

// add
void activeTray(QSystemTrayIcon::ActivationReason reason);
private:
// add
struct TrayDialogImpl;
TrayDialogImpl* impl{ nullptr };
}

TrayDialog.cpp

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include "traydialog.h"

#include <QMenu>
#include <QList>
#include <QAction>
#include <QObject>
#include <QSystemTrayIcon>
#include <functional>
#include <QDebug>

struct TrayDialog::TrayDialogImpl
{
// 托盘
Menu* trayMenu{ nullptr };
QSystemTrayIcon* systemTray{ nullptr };
TrayDialogImpl()
{
}
};

TrayDialog::TrayDialog()
{
...

// add
impl->trayMenu = new Menu(this);
impl->systemTray = new QSystemTrayIcon(this);
// menu
impl->trayMenu->setObjectName("toptoolbarmenu");
impl->trayMenu->setProperty("class", "toptoolbarmenu");
impl->trayMenu->setWindowFlags(impl->trayMenu->windowFlags() | Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint);
impl->trayMenu->setAttribute(Qt::WA_TranslucentBackground);
// tray
impl->systemTray->setIcon(QIcon("icon.png"));
impl->systemTray->setToolTip("TrayDialog");
impl->systemTray->setContextMenu(impl->trayMenu);
impl->systemTray->show();
// connect
connect(impl->systemTray, &QSystemTrayIcon::activated, this, &TrayDialog::activeTray);//点击托盘,执行相应的动作

QAction* action = new QAction(QIcon(""), "123");
QObject::connect(action, &QAction::triggered, []() {
qDebug() << "123";
});
QAction* show = new QAction(QIcon(""), "show");
QObject::connect(show, &QAction::triggered, [&]() {
this->show();
});
impl->trayMenu->addAction(show);
impl->trayMenu->addAction(action);
}


void TrayDialog::activeTray(QSystemTrayIcon::ActivationReason reason)
{
switch (reason)
{
case QSystemTrayIcon::Context: // 已请求系统托盘条目的上下文菜单
{
;
}
break;
case QSystemTrayIcon::DoubleClick: // 双击
{
;
}
break;
case QSystemTrayIcon::Trigger: // 单击
{
;
}
break;
}
}

1