Use QML ToolTip with Label

2019-03-05 18:59发布

问题:

I'm using a ToolTip with a TextField. This works properly.

RowLayout {
    property string toolTipText

    TextField {
        hoverEnabled: true
        ToolTip.visible: tooltipText ? hovered : false
        ToolTip.text: tooltipText 
    }
}

But with a Label it wont work properly. hoverEnabled is not available in the Label Component. So i've tried it with a MouseArea

RowLayout {
    property string toolTipText

    Label {
        MouseArea { 
            anchors.fill: parent
            hoverEnabled: true
            ToolTip.visible: tooltipText ? hovered : false
            ToolTip.text: tooltipText 
        }
    }
}

The ToolTip will be shown, but not when mouseover the Label. It actually shows when entering the Window.

Is there any solution for this?

回答1:

MouseArea does not have the ToolTip but the Label, so that you must move it and activate it using the containsMouse property of MouseArea:

RowLayout {

    Label {
        text: "label"
        property string toolTipText: "message"
        ToolTip.text: toolTipText
        ToolTip.visible: toolTipText ? ma.containsMouse : false
        MouseArea {
            id: ma
            anchors.fill: parent
            hoverEnabled: true
        }
    }
}