Last active
March 6, 2017 08:11
-
-
Save GaryLee/7f069e96bb5753495058 to your computer and use it in GitHub Desktop.
Use QML application in tray icon
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <QApplication> | |
#include <QQmlApplicationEngine> | |
#include <QMessageBox> | |
#include <QAction> | |
#include <QMenu> | |
#include <QSystemTrayIcon> | |
int init_trayicon_app() | |
{ | |
if (!QSystemTrayIcon::isSystemTrayAvailable()) { | |
QMessageBox::critical(0, QObject::tr("Systray"), | |
QObject::tr("No systray was found.")); | |
return 1; | |
} | |
QApplication::setQuitOnLastWindowClosed(false); | |
return 0; | |
} | |
void init_trayicon() | |
{ | |
QObject *root = 0; | |
if (engine.rootObjects().size() > 0) | |
{ | |
root = engine.rootObjects().at(0); | |
QAction *minimizeAction = new QAction(QObject::tr("Mi&nimize"), root); | |
root->connect(minimizeAction, SIGNAL(triggered()), root, SLOT(hide())); | |
QAction *maximizeAction = new QAction(QObject::tr("Ma&ximize"), root); | |
root->connect(maximizeAction, SIGNAL(triggered()), root, SLOT(showMaximized())); | |
QAction *restoreAction = new QAction(QObject::tr("&Restore"), root); | |
root->connect(restoreAction, SIGNAL(triggered()), root, SLOT(showNormal())); | |
QAction *quitAction = new QAction(QObject::tr("&Quit"), root); | |
root->connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); | |
QMenu *trayIconMenu = new QMenu(); | |
trayIconMenu->addAction(minimizeAction); | |
trayIconMenu->addAction(maximizeAction); | |
trayIconMenu->addAction(restoreAction); | |
trayIconMenu->addSeparator(); | |
trayIconMenu->addAction(quitAction); | |
QSystemTrayIcon *trayIcon = new QSystemTrayIcon(root); | |
trayIcon->setContextMenu(trayIconMenu); | |
trayIcon->setIcon(QIcon(":/trayicon.png")); | |
trayIcon->show(); | |
} | |
} | |
int main(int argc, char *argv[]) | |
{ | |
QApplication app(argc, argv); | |
init_trayicon_app(); | |
QQmlApplicationEngine engine; | |
engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); | |
init_trayicon(); | |
return app.exec(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This will crash with Qt5.4