QML 鼠标穿透
事件:
有一个输入框(TextField),需要实现鼠标悬浮时改变边框颜色,鼠标移出后恢复原来边框颜色;
这时如果需要实现此功能,就得使用到MouseArea,鼠标操作区域填充满整个TextField。
然后实现鼠标移入移入出的修改边框颜色的效果,具体实现代码:
TextField {id: pwdTextFieldwidth: 400height: 40font.pixelSize: height / 2placeholderText: "请输入密码" // 背景提示文本placeholderTextColor: "#303037" // 提示文本颜色verticalAlignment: Text.AlignVCenter // 文本垂直居中anchors.centerIn: parentbackground: Rectangle {anchors.fill: parentradius: pwdTextField.height / 2color: "#CCFFFF"border.width: 1border.color: pwdTextField.focus ? "#FF66FF" : "#222"MouseArea {anchors.fill: parent // 鼠标区域填充满整个TextFieldhoverEnabled: true // 启用鼠标悬浮追踪onEntered: { // 鼠标进入parent.border.color = "#FF66FF"}onExited: { // 鼠标移出parent.border.color = pwdTextField.focus ? "#FF66FF" : "#222"}}}
}
但是,此时就出现问题了,鼠标区域会覆盖TextField,使得TextField无法输入文本了
鼠标移入实现边框颜色改变,移出恢复功能确实已经实现了,但是,输入框无法输入文本了…
原因就是设置MouseArea时将TextField给遮住了;
解决问题的方案就是鼠标穿透!将MouseArea的点击事件穿透传给父控件,即TextField;
在MouseArea加入两行代码:
propagateComposedEvents: true
onPressed: { mouse.accepted = false }
代码加上后,运行TextField可以正常输入文本了!
最后再优化一下,鼠标指针进入后,修改一下:
Window {id: rootvisible: truewidth: 600height: 400title: qsTr("Hello World")TextField {id: pwdTextFieldwidth: 400height: 40font.pixelSize: height / 2placeholderText: "请输入密码" // 背景提示文本placeholderTextColor: "#303037" // 提示文本颜色verticalAlignment: Text.AlignVCenter // 文本垂直居中anchors.centerIn: parentbackground: Rectangle {anchors.fill: parentradius: pwdTextField.height / 2color: "#CCFFFF"border.width: 1border.color: pwdTextField.focus ? "#FF66FF" : "#222"MouseArea {anchors.fill: parent // 填充满父控件hoverEnabled: true// 鼠标穿透,按下事件不接收,传递给父控件propagateComposedEvents: trueonPressed: {mouse.accepted = false}onEntered: {parent.border.color = "#FF66FF"cursorShape = Qt.IBeamCursor}onExited: {parent.border.color = pwdTextField.focus ? "#FF66FF" : "#222"cursorShape = Qt.ArrowCursor}}}}
}