How to handle mouse right click on QSystemTrayIcon?

990 Views Asked by At

I have connected QSystemTrayIcon::ActivationReason to my 'handleClick' slot as below

connect(tray,SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this,SLOT(handleClick(QSystemTrayIcon::ActivationReason)));

mywindow::handleClick(QSystemTrayIcon::ActivationReason reason)
{
    switch (reason)
    {
    case QSystemTrayIcon::Trigger:
    case QSystemTrayIcon::DoubleClick:
        handleLeftClickOnTray();
        break;
    case QSystemTrayIcon::MiddleClick:
        break;
    default:;
    }
}

I have another function called 'handleRightClickOnSystemTray()' which should be called when mouse right button clicked over system tray icon. This function creates a QDialog box and display it. How to handle right click mouse events on system tray ?

2

There are 2 best solutions below

5
On

You can use QSystemTrayIcon::Trigger which will be invoked when you left click. QSystemTrayIcon::DoubleClick will not trigger when a menu is in place.

 case QSystemTrayIcon::Trigger:
    qDebug() << "Left clicked";
 break;

If that's not working for you, then you have to reimplement bool QSystemTrayIcon::event(QEvent *e) and install an event filter to check which button was pressed.

The new signal and slot syntax is

connect(tray, &QSystemTrayIcoon::activated, this, &MainWindow::handleClick /* assuming it's MainWindow */);

or the lamba version

connect(tray, &QSystemTrayIcoon::activated, [](QSystemTrayIcon::ActivationReason reason) { switch(reason) { /* .. */ } });
0
On

There's a workaround if you don't need The context menu of your system tray icon.

You can use QMenu's signal void QMenu::aboutToShow(), it detects right clicks, but you have to keep your menu without actions so that it does not actually show, you'll just be using its mouse event without displaying it.

This basically will make it as if your QSystemTrayIcon handled your right click mouse event.

Here's an example:

QSystemTrayIcon TrayIcon( QIcon("favicon.png") );
QMenu menu;

TrayIcon.show();
TrayIcon.setContextMenu(&menu);
QObject::connect(&menu,&QMenu::aboutToShow,some_function);