|
代码如下:- #include<QtGui>
- #include<QTextCodec>
- #include<QCloseEvent>
- #include<QString>
- #include<QDebug>
- #include<QSystemTrayIcon>
- #include<QMainWindow>
- #include<QMenu>
- class myMainWindow: public QMainWindow
- {
- Q_OBJECT
- public:
- myMainWindow();
- private:
- QSystemTrayIcon *trayIcon;
- QAction *minimizeAction;
- QAction *restoreAction;
- QAction *quitAction;
- QMenu *trayIconMenu;
- private slots:
- // void trayiconActivated(QSystemTrayIcon::ActivationReason reason);
- void onSystemTrayIconClicked(QSystemTrayIcon::ActivationReason reason);
- protected:
- void closeEvent(QCloseEvent *event);
- };
- myMainWindow::myMainWindow()
- {
- //创建托盘图标
- QIcon icon = QIcon("D:/studytool/Qt/workspace/myTray1/tengweitw.jpg");
- trayIcon = new QSystemTrayIcon(this);
- trayIcon->setIcon(icon);
- trayIcon->setToolTip(tr("托盘测试"));
- trayIcon->show();
- //弹出气泡提示,但是运行时显示不了。
- trayIcon->showMessage(titlec,textc,QSystemTrayIcon::Information,5000);
- //添加单/双击鼠标相应
- connect(trayIcon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),this,SLOT(onSystemTrayIconClicked(QSystemTrayIcon::ActivationReason)));
- //创建监听行为
- minimizeAction = new QAction(tr("最小化 (&I)"), this);
- connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide()));
- restoreAction = new QAction(tr("还原 (&R)"), this);
- connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal()));
- quitAction = new QAction(tr("退出 (&Q)"), this);
- connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
- //创建右键弹出菜单
- trayIconMenu = new QMenu(this);
- trayIconMenu->addAction(minimizeAction);
- trayIconMenu->addAction(restoreAction);
- trayIconMenu->addSeparator();
- trayIconMenu->addAction(quitAction);
- trayIcon->setContextMenu(trayIconMenu);
- }
- void myMainWindow::onSystemTrayIconClicked(QSystemTrayIcon::ActivationReason reason)
- {
- switch (reason)
- {
- case QSystemTrayIcon::Trigger:
- //单击托盘图标
- case QSystemTrayIcon::DoubleClick:
- //双击托盘图标
- // this->showNormal();
- // this->raise();
- qDebug()<<"ok";
- this->setWindowState(Qt::WindowActive);
- this->show();
- break;
- default:
- break;
- }
- }
- void myMainWindow::closeEvent(QCloseEvent *event)
- {
- if(trayIcon->isVisible())
- {
- hide();
- event->ignore();
- }
- }
- int main(int argc, char *argv[])
- {
- QApplication a(argc, argv);
- QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
- myMainWindow w;
- w.show();
- return a.exec();
- }
- //#include "moc_MainWindow.cpp"
复制代码 |
|