gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:03:57 26 4
gpt4 key购买 nike

我有一个基本的自定义按钮,使用带有 radius: width/2 的矩形.现在我添加一个 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
}
}
}

round mouse area gif

关于qt - 如何在 QML 中创建圆形鼠标区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38164074/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com