八、系统托盘与配置面板

发布于:2025-02-10 ⋅ 阅读:(25) ⋅ 点赞:(0)

没有人会把你变得越来越好,时间和经历只是陪衬。

支撑你变得越来越好的,是你自己坚强的意志、修养、品行、以及不断的反思和经验。

人生最好的贵人,就是努力向上的自己。

一、系统托盘

1、资源文件夹

新建资源文件夹,我们需要把图片相关资源都放到这里,

这里我们新建一个 icon 文件夹,并且放入一个 cloud.png 图片作为系统托盘图标。

2、代码实现

我们使用 QMenu  来创建系统托盘菜单,使用 QAction 来定义菜单项,并且绑定对应的菜单触发事件,具体代码如下: 

void MainWindow::initSysTrayIcon(){
    ptrSysTrayIcon = new QSystemTrayIcon(QIcon(":/icon/cloud.png"), this);
    // 创建托盘菜单
    QMenu *trayMenu = new QMenu();

    // 添加设置菜单项
    QAction *settingsAction = new QAction("设置", this);
    QObject::connect(settingsAction, &QAction::triggered, this, &MainWindow::openSettingsWindow);
    trayMenu->addAction(settingsAction);

    // 添加退出菜单项
    QAction *exitAction = new QAction("退出", this);
    QObject::connect(exitAction, &QAction::triggered, this, &QCoreApplication::quit);
    trayMenu->addAction(exitAction);

    // 将菜单关联到托盘图标
    ptrSysTrayIcon->setContextMenu(trayMenu);

    // 显示托盘图标
    ptrSysTrayIcon->show();
}

3、显示托盘

在主窗口构造方法设置系统托盘,

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    initWindowSettings();
    initSysTrayIcon();
}

void MainWindow::initSysTrayIcon(){
    ptrSysTrayIcon = new QSystemTrayIcon(QIcon(":/icon/cloud.png"), this);
    // 创建托盘菜单
    QMenu *trayMenu = new QMenu();

    // 添加设置菜单项
    QAction *settingsAction = new QAction("设置", this);
    QObject::connect(settingsAction, &QAction::triggered, this, &MainWindow::openSettingsWindow);
    trayMenu->addAction(settingsAction);

    // 添加退出菜单项
    QAction *exitAction = new QAction("退出", this);
    QObject::connect(exitAction, &QAction::triggered, this, &QCoreApplication::quit);
    trayMenu->addAction(exitAction);

    // 将菜单关联到托盘图标
  

网站公告

今日签到

点亮在社区的每一天
去签到