关闭

Qt系统托盘程序

779人阅读 评论(0) 收藏 举报
分类:

1:首先在程序的main函数中添加:

void main()

{

QApplication a(argc, argv); 


if ( !QSystemTrayIcon::isSystemTrayAvailable() ) 

              MessageBoxQt(“没有检测到系统托盘”);

return 1;

}


QApplication::setQuitOnLastWindowClosed(false);


            。。。

}


2:在指定窗口中(一般是主窗口),添加相应代码:



class trayWindow : public QMainWindow

{

public slots:

void slot_create_tray() //创建系统托盘;
{
createActions();  
createTrayIcon();
 
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));


QIcon icon("G:\\t.png");
trayIcon->setIcon(icon);  //设置托盘图标;
 
trayIcon->show(); //显示托盘;
}




public:
QAction *minimizeAction;
QAction *maximizeAction;
QAction *restoreAction;
QAction *quitAction;


QSystemTrayIcon *trayIcon;
QMenu *trayIconMenu; 
 

void createActions()  //创建添加菜单QAction;
{
minimizeAction = new QAction(tr("Mi&nimize"), this);
connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide()));


maximizeAction = new QAction(tr("Ma&ximize"), this);
connect(maximizeAction, SIGNAL(triggered()), this, SLOT(showMaximized()));


restoreAction = new QAction(tr("&Restore"), this);
connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal()));


quitAction = new QAction(tr("&Quit"), this);
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); 
}


void createTrayIcon() //创建托盘,添加菜单;
{
trayIconMenu = new QMenu(this);
  trayIconMenu->addAction(minimizeAction);
  trayIconMenu->addAction(maximizeAction);
  trayIconMenu->addAction(restoreAction);
   trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);


trayIcon = new QSystemTrayIcon(this);
trayIcon->setContextMenu(trayIconMenu);
}


public slots:
void iconActivated(QSystemTrayIcon::ActivationReason reason) //托盘图标响应鼠标消息
{
switch (reason) 
{
case QSystemTrayIcon::Trigger:
case QSystemTrayIcon::DoubleClick:
break;
case QSystemTrayIcon::MiddleClick:
break;
default:
;
}
}


}


通过上述方法就可以制作一个简单的托盘应用程序; 

这里简单讲托盘程序的编写过程将清楚;

如果想查看更多托盘程序应用,可以参考Qt安装包中的例子: Qt\Qt5.1.1\5.1.1\msvc2010\examples\widgets\desktop\systray ;

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1557112次
    • 积分:16781
    • 等级:
    • 排名:第592名
    • 原创:309篇
    • 转载:283篇
    • 译文:5篇
    • 评论:153条
    最新评论