Qt4.8.2 托盘

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include 
#include 

class Widget : public QWidget
{
    Q_OBJECT
    
public:
    Widget(QWidget *parent = 0);
    ~Widget();

private:
    QSystemTrayIcon *trayIcon;

    QMenu * CreateTrayMenu();

private slots:
    void iconActived(QSystemTrayIcon::ActivationReason);

};

#endif // WIDGET_H

widget.cpp

#include "widget.h"
#include 
#include 
#include 
#include 

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    trayIcon=new QSystemTrayIcon(QIcon(":/img/tray.png"),this);
    //鼠标移至托盘的消息提示
    trayIcon->setToolTip(tr("这是一个Qt托盘测试程序"));
    //右击托盘图标的弹出菜单
    trayIcon->setContextMenu(CreateTrayMenu());
    //设置托盘可见
    trayIcon->setVisible(true);
    //添加托盘的鼠标事件
    connect(trayIcon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),this,SLOT(iconActived(QSystemTrayIcon::ActivationReason)));
}

Widget::~Widget()
{
    
}
QMenu *Widget::CreateTrayMenu()
{
    QMenu *menu=new QMenu;
    QAction *actionMinSize=new QAction(tr("最小化"),this);
    connect(actionMinSize,SIGNAL(triggered()),this,SLOT(showMinimized()));
    QAction *actionMaxSize=new QAction(tr("最大化"),this);
    connect(actionMaxSize,SIGNAL(triggered()),this,SLOT(showMaximized()));
    QAction *actionRestore=new QAction(tr("还原"),this);
    connect(actionRestore,SIGNAL(triggered()),this,SLOT(showNormal()));
    QAction *actionQuit=new QAction(tr("退出"),this);
    /*
      gui中qApp等同于QApplication::instance()
      非gui中qApp等同于QCoreapplication::instance()

      使用qApp需加头文件QApplication/QCoreapplication
    */
    connect(actionQuit,SIGNAL(triggered()),qApp,SLOT(quit()));

    menu->addAction(actionMinSize);
    menu->addAction(actionMaxSize);
    menu->addAction(actionRestore);
    menu->addSeparator();
    menu->addAction(actionQuit);

    return menu;
}

void Widget::iconActived(QSystemTrayIcon::ActivationReason reason)
{
    switch(reason)
    {
    case QSystemTrayIcon::DoubleClick:
        QMessageBox::information(this,tr("托盘消息"),tr("双击"));
        break;
    case QSystemTrayIcon::Trigger:
        QMessageBox::information(this,tr("托盘消息"),tr("单击"));
        break;
    case QSystemTrayIcon::MiddleClick:
        QMessageBox::information(this,tr("托盘消息"),tr("鼠标中键"));
        break;
    }
}

main.cpp

#include 
#include "widget.h"
#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QTextCodec::setCodecForTr(QTextCodec::codecForLocale());

    //设置点击关闭时不退出
    QApplication::setQuitOnLastWindowClosed(false);

    Widget w;
    w.show();
    
    return a.exec();
}


你可能感兴趣的:(Qt4)