Home > Enterprise >  Access mouse.button variable in QML
Access mouse.button variable in QML

Time:03-22

I was trying something to strengthen my experience with C and QML.

I have a MouseArea item. I want to pass the "onPressed" , "onReleased" and "onPositionChanged" events to the backend side that I am trying to write in C . Actually I want this for clean and simple code. I can do whatever I want by writing in QML.

The problem is that I couldn't define "mouse.button" variable of MouseArea in C side. I am getting error like:

qrc:/main.qml:58: Error: Unknown method parameter type: Qt::MouseButton

My QML script:

.
.
Item{
    id: item
    anchors.fill: parent

    Viewer{
        id: viewer
    }

    MouseArea{
        id: viewerMouseArea
        anchors.fill: parent
        hoverEnabled: true
        acceptedButtons: Qt.RightButton | Qt.LeftButton | Qt.MiddleButton

        onPressed: {
            //console.log("Mouse buttons in mouse area pressed.");
            viewer.mousePressEvent(mouseX, mouseY, mouse.button);
        }

        onReleased:{
            //console.log("Mouse buttons in mouse area released.")
            viewer.mouseReleaseEvent(mouseX, mouseY, mouse.button);
        }

        onPositionChanged:{
            //console.log("Position of cursor in mouse area changed.")
            //viewer.mouseMoveEvent(x, mouseY);
        }
    }
}
.
.

My C backend code:

.
.
void Viewer::mousePressEvent(double x, double y, Qt::MouseButton button) {
    qDebug() << "Viewer::mousePressEvent()";
}

void Viewer::mouseReleaseEvent(double x, double y, Qt::MouseButton button) {
    qDebug() << "Viewer::mouseReleaseEvent()";
}

void Viewer::mouseMoveEvent(double x, double y) {
    qDebug() << "Viewer::mouseMoveEvent()";
}
.
.

How can I access mouse.button variable in QML in C ?

CodePudding user response:

I looked at the documentation here. https://doc.qt.io/qt-6/qt.html#MouseButton-enum I solved it by working directly with the unsigned integer.

void Viewer::mousePressEvent(double x, double y, quint32 button) {
    qDebug() << "Viewer::mousePressEvent()";

    qDebug() << "x: " << x << " y: " << y << " button: " << button;
}

void Viewer::mouseReleaseEvent(double x, double y, quint32 button) {
    qDebug() << "Viewer::mouseReleaseEvent()";

    qDebug() << "x: " << x << " y: " << y << " button: " << button;
}

void Viewer::mouseMoveEvent(double x, double y) {
    qDebug() << "Viewer::mouseMoveEvent()";
}

If you have a better solution suggestion, please let me know. I would be very grateful.

Console output:

Viewer::mousePressEvent()
x:  243  y:  161  button:  2
Viewer::mouseReleaseEvent()
Viewer::mousePressEvent()
x:  282  y:  183  button:  1
Viewer::mouseReleaseEvent()
Viewer::mousePressEvent()
x:  277  y:  138  button:  4
Viewer::mouseReleaseEvent()
  • Related