鼠标悬停、点击检测
先自定义控件IndicatorButton.qml,该控件可以实现当鼠标悬停于该控件上方时可以给出提示信息,离开时相关消息消失,鼠标点击该控件时实现可以实现控件文本的更改。Qt如何添加自定义控件,请参考QML插件扩展
import QtQuick 2.0
import QtQuick.Controls 1.0
Rectangle{
signal clicked()
property string actionName: "unknown"
property string hoverColor: "yellow"
property string sourceImage
property string promptName
property bool checked: false
id: _indicator
width: 100
height: 30
color: "lightblue"
border.color: "gray"
border.width: 2
radius: 4
Text {
anchors.fill: parent
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
text: actionName
}
Image {
id: _indicatorImage
source: sourceImage
}
MouseArea{
anchors.fill: parent
hoverEnabled: true
onClicked: {
checked = !checked
_indicator.clicked()
}
onEntered: {
_indicator.color = hoverColor
_indicatorName.visible = true
}
onExited: {
_indicator.color = "lightblue"
_indicatorName.visible = false
}
}
Label{
id: _indicatorName
anchors.top: _indicator.bottom
anchors.left: _indicator.left
width: _indicator.width
height: _indicator.height
color: "green"
text: promptName
wrapMode: Text.Wrap
visible: false
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
}
}
功能测试代码
IndicatorButton{
id: _tester
promptName: "Mouse is hovering"
actionName: "Tester"
onClicked:{
_tester.actionName = _tester.checked ? "Checked" : "Unchecked"
}
}
长按
property bool isLongHold: false
Timer{
id: timer
interval: 3000
repeat: true
running: true
onTriggered: isLongHold = true
}
MouseArea {
onPressAndHold: {
timer.start()
try{
if(isLongHold){
/*检测到长按,do something*/
}
}
catch(e){
console.log(e.toString())
}
}
onReleased: {
isLongHold = false
}
}