事件:
有一個輸入框(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}}}}
}