我有一个基本的自定义按钮,使用带有radius: width/2的Rectangle。现在,我将MouseArea添加到我的按钮中。但是,MouseArea具有正方形的形状。这意味着当我在圆形按钮外面稍微单击时,即在圆形按钮周围的假想正方形的角上单击时,也会触发单击事件。我可以以某种方式也进行MouseArea循环吗?

  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";
              }
          }

      }
  }

最佳答案

PieMenu窃取代码,这是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()
    }
}

您可以像这样使用它:
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
        }
    }
}

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

09-19 16:37