在这个学期的专业实习结课时,和几位同学一同编写了一个局域网通信软件:子曰USay。采用基于服务器转发的通信模式,服务器是使用Python编写,客户端采用Qt实现。界面和功能基本上是模仿腾讯的QQ。由于我只负责前端设计这方面,所以就将这个项目的前端实现总结一下。
在我们的子曰USay局域网聊天室中,客户端登陆成功之后,会显示子曰的主界面,并且会在计算机右下角创建一个托盘图标,这一篇文章说明如何在Qt中创建托盘程序。
一个HelloWorld程序更容易看懂托盘的具体实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
#include <QtGui>
class
myclass:
public
QWidget
{
public
:
myclass();
private
:
QSystemTrayIcon *trayIcon;
};
myclass::myclass()
{
QIcon icon = QIcon(
":/logo.png"
);
trayIcon =
new
QSystemTrayIcon(
this
);
trayIcon->setIcon(icon);
trayIcon->setToolTip(tr(
"子曰USay"
));
QString titlec=tr(
"子曰USay"
);
QString textc=tr(
"子曰USay:给你神一般的体验"
);
trayIcon->show();
trayIcon->showMessage(titlec,textc,QSystemTrayIcon::Information,5000);
}
int
main(
int
argc,
char
**argv)
{
QApplication testc(argc,argv);
myclass newc;
newc.show();
return
testc.exec();
}
|
接下来,添加一些代码,使托盘能够响应鼠标的单机双击时间,并且用鼠标右键单击托盘图标时,能够弹出操作菜单,并执行相应的操作,效果如下:
![](https://i-blog.csdnimg.cn/blog_migrate/547df4e6c2b6799a57401df0574da8f6.png)
Qt实现托盘程序
实现起来非常简单,main函数没有什么变化,myclass类如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
class
myclass:
public
QWidget
{
public
:
myclass();
private
:
QSystemTrayIcon *trayIcon;
QAction *minimizeAction;
QAction *restoreAction;
QAction *quitAction;
QMenu *trayIconMenu;
private
slots:
void
trayiconActivated(QSystemTrayIcon::ActivationReason reason);
};
myclass::myclass()
{
//创建托盘图标
QIcon icon = QIcon(
":/logo.png"
);
trayIcon =
new
QSystemTrayIcon(
this
);
trayIcon->setIcon(icon);
trayIcon->setToolTip(tr(
"子曰USay"
));
QString titlec=tr(
"子曰USay"
);
QString textc=tr(
"子曰USay:给你神一般的体验"
);
trayIcon->show();
//弹出气泡提示
trayIcon->showMessage(titlec,textc,QSystemTrayIcon::Information,5000);
//添加单/双击鼠标相应
connect(trayIcon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this
,SLOT(trayiconActivated(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
myclass::trayiconActivated(QSystemTrayIcon::ActivationReason reason)
{
switch
(reason)
{
case
QSystemTrayIcon::Trigger:
//单击托盘图标
case
QSystemTrayIcon::DoubleClick:
//双击托盘图标
this
->showNormal();
this
->
raise
();
break
;
default
:
break
;
}
}
|
至此,大功告成。