Qt实现系统托盘消息

实现思路

  1. 创建主应用程序:使用 QApplication 作为应用程序的基础。
  2. 创建系统托盘图标:使用 QSystemTrayIcon 来显示图标在系统托盘中。
  3. 添加右键菜单:为托盘图标添加右键菜单,允许用户选择退出应用程序。
  4. 显示新消息:使用 QTimer 定期触发显示消息,模拟新消息到达的情况。
  5. 处理槽函数:定义槽函数来响应特定事件,例如定时器超时时显示托盘消息。

1.包含必要的头文件

#include <QApplication>
#include <QSystemTrayIcon>
#include <QMenu>
#include <QAction>
#include <QWidget>
#include <QTimer>
#include <QIcon>
#include <QMessageBox>
#include <QDebug>

2.定义托盘应用程序类

  • 创建一个名为 TrayApp 的类,继承自 QWidget
  • 在构造函数中,初始化系统托盘图标、菜单和定时器。
class TrayApp : public QWidget {
public:
    TrayApp() {
        trayIcon = new QSystemTrayIcon(QIcon(":/Image/QQ图标.png"), this);
        // 创建菜单
        QMenu *menu = new QMenu();
        QAction *exitAction = menu->addAction("Exit");
        connect(exitAction, &QAction::triggered, qApp, &QApplication::quit);
        trayIcon->setContextMenu(menu);
        trayIcon->show();

3.设置定时器

  • 使用 QTimer 来定时触发消息显示。
  • 连接定时器的超时信号到槽函数。
        QTimer *timer = new QTimer(this);
        connect(timer, &QTimer::timeout, this, &TrayApp::simulateNewMessage);
        timer->start(3000); // 每3秒发送一次消息
    }

4.定义槽函数

  • 在私有槽中定义 simulateNewMessage 函数,该函数用于显示系统托盘消息。
private slots:
    void simulateNewMessage() {
        trayIcon->showMessage("新消息", "您有一条新消息!", QSystemTrayIcon::Information);
    }

5.main 函数中创建应用程序实例

  • 创建 QApplication 对象并设置退出行为。
  • 创建 TrayApp 的实例,启动事件循环。
int main(int argc, char *argv[]) {
    QApplication app(argc, argv);
    app.setQuitOnLastWindowClosed(false);

    TrayApp trayApp; // 创建托盘应用实例
    return app.exec();
}

完整代码

#include <QApplication>
#include <QSystemTrayIcon>
#include <QMenu>
#include <QAction>
#include <QWidget>
#include <QTimer>
#include <QIcon>
#include <QMessageBox>
#include <QDebug>

class TrayApp : public QWidget {
public:
    TrayApp() {
        trayIcon = new QSystemTrayIcon(QIcon(":/Image/QQ图标.png"), this);

        // 创建菜单
        QMenu *menu = new QMenu();
        QAction *exitAction = menu->addAction("Exit");
        connect(exitAction, &QAction::triggered, qApp, &QApplication::quit);
        trayIcon->setContextMenu(menu);

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

        // 定时器,模拟新消息
        QTimer *timer = new QTimer(this);
        connect(timer, &QTimer::timeout, this, &TrayApp::simulateNewMessage);
        timer->start(3000); // 每3秒发送一次消息
    }

private slots:
    void simulateNewMessage() {
        trayIcon->showMessage("新消息", "您有一条新消息!", QSystemTrayIcon::Information);
    }

private:
    QSystemTrayIcon *trayIcon; // 使用指针类型以动态创建
};

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);
    app.setQuitOnLastWindowClosed(false);

    TrayApp trayApp; // 创建托盘应用实例
    return app.exec();
}

总结

  • 这个代码实现了一个简单的系统托盘应用,能在托盘中显示图标,并定期显示消息。
  • 用户可以通过右键菜单退出应用程序。
  • 通过使用 Qt 的信号和槽机制,代码结构清晰、易于维护与扩展。
posted @ 2024-11-25 10:27  王廷胡_白嫖帝  阅读(513)  评论(0)    收藏  举报