Important: Please read the Qt Code of Conduct -

qml How to simulate mouse events

  • i want to send a mouse event to the MouseArea of a qml object ,How do you implement this feature? anyone any idea

  • @jimfar given that MouseEvent and TouchEvent are equivalent from QML MouseArea point of view per this, I'd use the TouchEventSequence QML Type from the Qt Quick Test module.

  • i am desktop app , is this way to work out this problem

  • TouchEventSequence must apparently be created by TestCase.touchEvent().
    Is there a way to use TouchEventSequence in a normal QML application that is not in unit testing mode?
    Thank you.

  • @jimfar said in qml How to simulate mouse events:

    How do you implement this feature?

    Like this:

    #include <QGuiApplication>
    #include <QQmlApplicationEngine>
    #include <QQmlContext>
    #include <QMouseEvent>
    class GenMouseEvent : public QObject
        GenMouseEvent(QObject* parent=nullptr)
            : QObject(parent)
    public slots:
        void sendMouseEvent(QObject* object, QPointF pos, int button){
            Qt::MouseButton type = Qt::MouseButton(button);
            auto down = new QMouseEvent(QMouseEvent::Type::MouseButtonPress, pos, type, type, Qt::KeyboardModifier::NoModifier);
            auto up = new QMouseEvent(QMouseEvent::Type::MouseButtonRelease, pos, type, type, Qt::KeyboardModifier::NoModifier);
            QCoreApplication::postEvent(object, down);
            QCoreApplication::postEvent(object, up);
    int main(int argc, char *argv[])
        QGuiApplication app(argc, argv);
        QQmlApplicationEngine engine;
        GenMouseEvent gme;
        auto context = engine.rootContext();
        const QUrl url(QStringLiteral("qrc:/main.qml"));
        QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                         &app, [url](QObject *obj, const QUrl &objUrl) {
            if (!obj && url == objUrl)
        }, Qt::QueuedConnection);
        return app.exec();
    #include "main.moc"


    import QtQuick 2.12
    import QtQuick.Controls 2.12
    import QtQuick.Window 2.12
    Window {
        visible: true
        width: 640
        height: 480
        title: qsTr("Simulate MouseEvent")
        Button {
            id: button
            text: "Test Button"
            onClicked: {
        MouseArea {
            id: mousearea
            acceptedButtons: Qt.LeftButton | Qt.RightButton
            onClicked: {
                if(mouse.button === Qt.LeftButton){
                    console.log("ma clicked left")
                if(mouse.button === Qt.RightButton){
                    console.log("ma clicked right")
        Component.onCompleted: {
            sendMouseEvent(button, Qt.point(0,0), Qt.LeftButton)
            sendMouseEvent(button, Qt.point(0,0), Qt.RightButton)
            sendMouseEvent(mousearea, Qt.point(0,0), Qt.LeftButton)
            sendMouseEvent(mousearea, Qt.point(0,0), Qt.RightButton)

Log in to reply