marmistrz
marmistrz

Reputation: 6384

Detect press and hold of a Button in QML

I'd like to open a context menu when a user presses and holds a Button (I use Button for convenience).

If I do:

Button
{
    text: model.ualabel

    MouseArea
    {
        preventStealing: true
        anchors.fill: parent
        onPressAndHold: uaContextMenu.open()
    }

    ContextMenu
    {
        id: uaContextMenu
        MenuLayout { MenuItem { /**/ } }
    }
}

Then the MouseArea responsible for pressAndHold steals all gestures, and the Button cannot be clicked.

What am I doing wrong?

I'm using Qt 4.7 and importing QtQuick 1.1 and com.nokia.meego 1.0.

Upvotes: 4

Views: 16385

Answers (3)

rsht
rsht

Reputation: 1582

Press-and-hold can be simulated in QML's Button like this:

Button {
    id: button

    signal pressAndHold()

    Timer {
        id: longPressTimer

        interval: 2000 //your press-and-hold interval here
        repeat: false
        running: false

        onTriggered: {
            button.pressAndHold()
        }
    }


    onPressedChanged: {
        if ( pressed ) {
            longPressTimer.running = true;
        } else {
            longPressTimer.running = false;
        }
    }
}

Upvotes: 6

Deadron
Deadron

Reputation: 5279

The problem is your mouse area is competing with the Button's mouse area to receive mouse events. Try setting propogateComposedEvents: true on your mouse area, and this should allow events to propagate downwards in the visual stack to the button's mouse area.

Refer to QML MouseArea — propagateComposedEvents for more details.


Another suggestion is to manually propagate the clicked signal in your mouseArea to the button. This should be doable by calling buttonId.clicked(), which will manually emit the clicked signal on your button.

Upvotes: 2

ArmX
ArmX

Reputation: 429

QML Button has its own pressAndHold() signal, so you can use it.

Button {
    text: model.ualabel

    ContextMenu
    {
        id: uaContextMenu

        MenuLayout { MenuItem { /**/ } }
    }

    onPressAndHold: uaContextMenu.open()
}

Upvotes: 2

Related Questions