try to add a context menu to QSystemTrayIcon



  • I use this code to make the QSystemTeayIcon and add a menu

      trayicon = new QSystemTrayIcon(this);
      trayicon->setIcon(QIcon(":/images/a.ico"));
      trayicon->setVisible(true);
      QMenu menue;
      menue.addAction("Exit",this,SLOT(close()));
      trayicon->setContextMenu(&menue);
      connect(trayicon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),this,SLOT(Actived(QSystemTrayIcon::ActivationReason)));
    

    here the slot code of activation reason

    void MainWindow::Actived(QSystemTrayIcon::ActivationReason reason)
    {
      switch (reason) {
      case QSystemTrayIcon::DoubleClick:
      qDebug() << "Double click";
      break;
      case QSystemTrayIcon::Trigger:
      qDebug() << "Drag";
      break;
      default:
      break;
      }
    }
    
    

    what should i do to make menu appeare when i press right click on my app tray icon
    Thanks in advance



  • i solve it by add this to slot function

    void MainWindow::Actived(QSystemTrayIcon::ActivationReason reason)
    {
        switch (reason) {
        case QSystemTrayIcon::DoubleClick:
            this->show();
            break;
        case QSystemTrayIcon::Context:
            coustemContextMenu(QCursor::pos()); // here send position of the click
            break;
        default:
            break;
        }
    }
    

    here the coustemContextMenu function

    void MainWindow::coustemContextMenu(QPoint point)
    {
        QMenu menue;
        menue.setContextMenuPolicy(Qt::CustomContextMenu);
        menue.addAction("Exit",this,SLOT(close()));
        menue.exec(point); // to show menu on this point
    }
    

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.