dimanche 18 août 2019

The Qt Tray application closes by itself after performing any action in the menu

I'm new in QT and I ran into a problem.

I decided to try writing a small application using Qt and QSystemTrayIcon. To start, I decided to reproduce the example from the official site of Qt. https://doc.qt.io/qt-5/qtwidgets-desktop-systray-example.html?

I redefined the necessary functions, such as:

 void MyTray::trayIconActivated(QSystemTrayIcon::ActivationReason reason) {
switch (reason) {
    case QSystemTrayIcon::Trigger:
    case QSystemTrayIcon::DoubleClick:
        this->trayActionExecute();
        break;
    default:
        break;
}
}

 void MyTray::setTrayIconActions() {
    launchAction = new QAction("Go!", this);       
    quitAction = new QAction("Exit", this);

     connect (launchAction, SIGNAL(triggered()), this, SLOT(start()));
    connect (quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));      

    // Setting system tray's icon menu
    trayIconMenu = new QMenu(this);
    trayIconMenu->addAction (launchAction);      
    trayIconMenu -> addAction (quitAction);
}

 void MyTray::changeEvent(QEvent *event) {
QMainWindow::changeEvent(event);
if (event->type() == QEvent::WindowStateChange) {
    if (isMinimized()) {
        this->hide();
    }
}
}

 void MyTray::closeEvent(QCloseEvent *event) {
  #ifdef Q_OS_OSX
  if (!event->spontaneous() || !isVisible()) {
    return;
}
#endif
if (trayIcon->isVisible()) {
    QMessageBox::information(this, tr("Systray"),
                             tr("Hello!"));
     hide();
     event->ignore();
 }
 }

When I perform any action in the context menu, the application simply closes. What can be wrong?

Thanks.

Aucun commentaire:

Enregistrer un commentaire