且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 QML 中创建圆形鼠标区域

更新时间:2023-01-04 16:07:37

I have a basic custom button using a Rectangle with radius: width/2. Now I add a MouseArea to my button. However the MouseArea has a squared shape. That means the click event is also triggered when I click slightly outside the round button, i.e. in the corners of the imaginary square around the round button. Can I somehow make also the MouseArea round?

  import QtQuick 2.7
  import QtQuick.Window 2.2

  Window {
      visible: true
      width: 640
      height: 480
      title: qsTr("TestApp")

      Rectangle {
          id: background
          anchors.fill: parent
          color: Qt.rgba(0.25, 0.25, 0.25, 1);


          Rectangle {
              id: button
              width: 64
              height: 64
              color: "transparent"
              anchors.centerIn: parent
              radius: 32
              border.width: 4
              border.color: "grey"

              MouseArea {
                  anchors.fill: parent
                  onPressed: button.color = "red";
                  onReleased: button.color = "transparent";
              }
          }

      }
  }

Stealing code from PieMenu, here's RoundMouseArea.qml:

import QtQuick 2.0

Item {
    id: roundMouseArea

    property alias mouseX: mouseArea.mouseX
    property alias mouseY: mouseArea.mouseY

    property bool containsMouse: {
        var x1 = width / 2;
        var y1 = height / 2;
        var x2 = mouseX;
        var y2 = mouseY;
        var distanceFromCenter = Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2);
        var radiusSquared = Math.pow(Math.min(width, height) / 2, 2);
        var isWithinOurRadius = distanceFromCenter < radiusSquared;
        return isWithinOurRadius;
    }

    readonly property bool pressed: containsMouse && mouseArea.pressed

    signal clicked

    MouseArea {
        id: mouseArea
        anchors.fill: parent
        hoverEnabled: true
        acceptedButtons: Qt.LeftButton | Qt.RightButton
        onClicked: if (roundMouseArea.containsMouse) roundMouseArea.clicked()
    }
}

You can use it like this:

import QtQuick 2.5
import QtQuick.Window 2.2

Window {
    width: 640
    height: 480
    visible: true

    RoundMouseArea {
        id: roundMouseArea
        width: 100
        height: 100
        anchors.centerIn: parent

        onClicked: print("clicked")

        // Show the boundary of the area and whether or not it's hovered.
        Rectangle {
            color: roundMouseArea.pressed ? "red" : (roundMouseArea.containsMouse ? "darkorange" : "transparent")
            border.color: "darkorange"
            radius: width / 2
            anchors.fill: parent
        }
    }
}