Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onClicked and onDoubleClicked both happen in QML

Tags:

qt

qml

qtquick2

I have added onClick and onDoubleClick handlers to an item in QML, but both of the events get executed when I double click on the area. I don't know if it has something to do with checking if the clicks were generated by right mouse button. Also the order of placing the code does not affect the problem.

MouseArea {
    id: idModuleMouseDebug;
    parent: repeaterDelegate;
    anchors.fill: parent;
    acceptedButtons: Qt.LeftButton | Qt.RightButton

    onDoubleClicked: {
        if(mouse.button == Qt.RightButton) {

            console.log("Double Click");
        }
    }

    onClicked: {
        if(mouse.button == Qt.RightButton) {
            console.log("Single Click");
        }
    }
}
like image 517
Saeid Yazdani Avatar asked Sep 17 '15 21:09

Saeid Yazdani


2 Answers

You should use threshold for single click, like that:

{
    function singleClick(){
        print("Single click")
    }
    function dblClick(){
        print("Double Click")
    }
    MouseArea {
        id: idModuleMouseDebug;
        parent: repeaterDelegate;
        anchors.fill: parent;
        acceptedButtons: Qt.LeftButton | Qt.RightButton
        Timer{
            id:timer
            interval: 200
            onTriggered: singleClick()
        }
        onClicked: {
            if(mouse.button == Qt.RightButton) {
                if(timer.running)
                {
                    dblClick()
                    timer.stop()
                }
                else
                    timer.restart()
            }
        }
    }
}
like image 137
Razieru Avatar answered Nov 20 '22 10:11

Razieru


As @cdonts said, this is the expected behaviour, in the widgets world as well:

#include <QtWidgets>

class Widget : public QWidget
{
public:
    Widget() {}

protected:
    void mousePressEvent(QMouseEvent *) {
        qDebug() << "press";
    }

    void mouseReleaseEvent(QMouseEvent *) {
        qDebug() << "release";
    }

    void mouseDoubleClickEvent(QMouseEvent *) {
        qDebug() << "double click";
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();
    return a.exec();
}

Output:

press
release
double click
release

Think about how your expected behaviour would be implemented. In order to not emit the single click if it was eventually a double click, you'd need to hold off on emitting the single click until the double click delay/threshold had elapsed, and if no second click came, you'd have to artificially send the single click event late. It would be a mess.

like image 3
Mitch Avatar answered Nov 20 '22 10:11

Mitch