|
不论处于什么理由,往往程序运行时喜欢在状态栏处显示图标,并且经常可以看到最小化或者关闭时隐藏至状态栏图标功能。在QT中实现相当简单,给类加入几个私有成员函数和私有SLOT,而后在类的构造函数里创建联接监听关系,并重载退出函数closeEvent()函数就可以很轻松实现。废话少说,且看代码:
netsharer.h部分源码
------------------------------
class netsharer:public QDialog,public Ui::netsharer
{
Q_OBJECT
public:
netsharer(QWidget *parent=0);
protected:
void closeEvent ( QCloseEvent * event );
private:
......
void createActions();
void createTrayIcon();
QAction *minimizeAction;
QAction *maximizeAction;
QAction *restoreAction;
QAction *quitAction;
QSystemTrayIcon *trayIcon;
QMenu *trayIconMenu;
private slots:
......
void iconActivated(QSystemTrayIcon::ActivationReason reason);
void quitaction();
};
netsharer.cpp部分源码:
-------------------------------
netsharer::netsharer(QWidget *parent)
:QDialog(parent)
{
......
createActions();
createTrayIcon();
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
QIcon icon = QIcon(":/images/icon.png");
trayIcon->setIcon(icon);
setWindowIcon(icon);
trayIcon->setToolTip("Net Sharer 0.4.2");
trayIcon->show();
}
void netsharer::closeEvent ( QCloseEvent * event )
{
QMessageBox::information(this, tr("Net Sharer"),
tr("The program will keep running in the "
"system tray. To terminate the program, "
"choose <b>Quit</b> in the context menu "
"that pops up when clicking this program's "
"entry in the system tray."));
hide();
event->ignore();
}
void netsharer::createActions()
{
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(show()));
quitAction = new QAction(tr("&Quit"), this);
connect(quitAction, SIGNAL(triggered()), this, SLOT(quitaction()));
}
void netsharer::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);
}
void netsharer::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
switch (reason) {
//case QSystemTrayIcon::Trigger:
case QSystemTrayIcon::DoubleClick:
setVisible(isHidden());
break;
//case QSystemTrayIcon::MiddleClick:
//showMessage();
//break;
default:
;
}
}
void netsharer::quitaction()
{
if (runbutton->isEnabled())
{
qApp->quit();
}
int r=QMessageBox::warning(this,tr("NetSharer"),QString::fromLocal8Bit("服务正在运行中\n是否立刻退出?"),QMessageBox::Yes|QMessageBox::Default,QMessageBox:: Cancel|QMessageBox::Escape);
if (r==QMessageBox::Yes)
{
stopsharer();
qApp->quit();
}
}
其实最重要的就是黑体部分。
代码简单,不必细说,只用加到相应位置即可。 |
|