Automating Tray Icon (Qt)

Last edited on

Introduction

When recording a testscript that opens the systemtray context-menu you will get different recordings depending on the current operating system.

On Linux/X11:

import * as names from 'names.js'

function main() {
    startApplication("systray");
    sendEvent("QMouseEvent", waitForObject(names.QWidget), QEvent.MouseButtonPress, 15, 9, Qt.RightButton, 2, 0);
    activateItem(waitForObjectItem(names.Systray_QMenu, "Quit"));
}

On Windows:

import * as names from 'names.js'

function main() {
    startApplication("systray");
    mouseClick(waitForObject(names.Heart_Button), 11, 12, MouseButton.RightButton);
    activateItem(waitForObjectItem(name.Systray_QMenu, "Quit"));
}

The code interacting with the tray-icon is platform-dependant and works on different objects (“names.Heart_Button” vs “names.QWidget”), something which is undesirable for testing cross-platform applications.

Solution

Replace the sendEvent / mouseClick that opens the tray-icon context menu with something similar to the following:

function main() {
    startApplication("systray");

    // Fetch object:
    trayIcon = waitForObject({"type": "QSystemTrayIcon", "unnamed": 1});

    // Retrieve geometry:
    trayCenter = trayIcon.geometry().center();

    // Show context menu - variant #1:
    trayMenu = trayIcon.contextMenu();
    trayMenu.popup(trayCenter);

    // Show context menu - variant #2:
    //nativeMouseClick(trayCenter.x, trayCenter.y, MouseButton.RightButton);

    activateItem(waitForObjectItem(names.Systray_QMenu, "Quit"));
}

This example makes use of the QSystemTrayIcon API which is cross-platform. It first tries to lookup the first QSystemTrayIcon object in the application, fetches the context-menu assigned to the tray-icon followed by opening the context-menu at the current position of the tray-icon.

Alternatively you may use nativeMouseClick() to achieve a replay that is closer to what a real user would do at the expensive of possible test-instabilities in case the tray-icon unexpectedly changes its position (i.e. appearance of new tray-icons from other applications)

Limitations