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
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
void SystemTray::createPlayAction()
{
// 菜单总控件
play_widget = new QWidget();
play_widget_action = new QWidgetAction(pop_menu);

play_button = new QPushButton();
backward_button = new QPushButton();
forward_button = new QPushButton();

// 正在播放的音乐名字
music_name_label = new QLabel();
music_name_label->setFixedWidth(MUSIC_NAME_WIDTH);
music_name_label->setAlignment(Qt::AlignCenter);
music_name_label->setText('player');
music_name_label->setEnabled(false);

// 暂停按钮
QPixmap play_pixmap(':/action/pause');
play_button->setIcon(play_pixmap);
play_button->setIconSize(play_pixmap.size());
play_button->setObjectName('transparentButton');

// 上一曲按钮
QPixmap backward_pixmap(':/action/backward');
backward_button->setIcon(backward_pixmap);
backward_button->setIconSize(backward_pixmap.size());
backward_button->setObjectName('transparentButton');

// 下一曲按钮
QPixmap forward_pixmap(':/action/forward');
forward_button->setIcon(forward_pixmap);
forward_button->setIconSize(forward_pixmap.size());
forward_button->setObjectName('transparentButton');

// 设置鼠标
backward_button->setCursor(Qt::PointingHandCursor);
play_button->setCursor(Qt::PointingHandCursor);
forward_button->setCursor(Qt::PointingHandCursor);

// 播放控件布局(横向)
QHBoxLayout *layout = new QHBoxLayout();
layout->addWidget(backward_button);
layout->addWidget(play_button);
layout->addWidget(forward_button);
layout->setSpacing(0);
layout->setContentsMargins(20, 0, 20, 0);

// 总体布局(纵向)
QVBoxLayout *layout2 = new QVBoxLayout();
layout2->addLayout(layout);
layout2->addWidget(music_name_label, 0, Qt::AlignCenter);
layout2->setSpacing(5);
layout2->setContentsMargins(0, 0, 0, 5);

play_widget->setLayout(layout2);
play_widget_action->setDefaultWidget(play_widget);

connect(play_button, &QPushButton::clicked, this, &SystemTray::play);
connect(backward_button, &QPushButton::clicked, this, &SystemTray::skipBackward);
connect(forward_button, &QPushButton::clicked, this, &SystemTray::skipForward);
}