Moving the mouse cursor yourself

Last edited on

Overview

Sometimes it may be useful to move (animate) the mouse cursor yourself, to perform a fluent or slower mouse movement, or to ensure that a certain path gets used.

Squish has the following mouseMove() functions which can be used to implement the desired functionality yourself. In addition, you can use the QCursor.setPos() function in your test script to achieve the same (but the resulting solution will be limited to Qt applications).

import os
import os.path
import sys

import names

def main():
    aut = "addressbook"
    path = os.environ["SQUISH_PREFIX"] + "/examples/qt/addressbook"
    registerAUT(aut, path)
    startApplication('"' + aut + '"')

    #mouseClick(waitForObject(names.AddressBook_New_QToolButton), 5, 5)
    my_qt_mouseClick(waitForObject(names.AddressBook_New_QToolButton), 5, 5)

def my_qt_mouseClick(objectOrName, x=0, y=0, modifierState=None, button=None):
    if modifierState is None:
        modifierState=Qt.NoModifier
    if button is None:
        button=Qt.LeftButton
    pos = QCursor.pos()
    start_x = pos.x
    start_y = pos.y

    pos = objectOrName.mapToGlobal(QPoint(x, y))
    end_x = pos.x
    end_y = pos.y

    # Increase to slow down
    step = 1

    x = start_x
    y = start_y
    while True:
        if x > end_x:
            x -= step
            if x < end_x:
                x = end_x
        elif x < end_x:
            x += step
            if x > end_x:
                x = end_x
        if y > end_y:
            y -= step
            if y < end_y:
                y = end_y
        elif y < end_y:
            y += step
            if y > end_y:
                y = end_y

        mouseMove(x, y)
        # Alternative:
        # QCursor.setPos(x, y)

        # Enable and possibly increase to slow down
        #snooze(0.0)

        if x == end_x and y == end_y:
            break
    mouseClick(objectOrName, x, y, modifierState, button)

def registerAUT(aut, path, squishserver_host=None, squishserver_port=None):
    s = '"' + os.environ["SQUISH_PREFIX"] + '/bin/squishrunner"'
    if squishserver_host is not None:
        s += ' --host ' + squishserver_host
    if squishserver_port is not None:
        s += ' port=' + str(squishserver_port)
    s += ' --config addAUT "' + aut + '" "' + path + '"'
    if sys.platform == "win32" and s.endswith('"'):
        s = '"' + s
    os.system(s)
test.py