【问题标题】:QML MouseArea: how to propagate mouse events to other mouse areas?QML MouseArea:如何将鼠标事件传播到其他鼠标区域?
【发布时间】:2020-03-20 04:58:17
【问题描述】:

我有一个复杂的对话框,其中包含许多复杂布局中的控件。我需要添加一个光标标记:在此对话框上方绘制的垂直线,应该跟随鼠标光标。 我不明白如何实现这一点。 简化示例代码:

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12

Window {
    visible: true
    width: 640
    height: 480

    Button {
        anchors.centerIn: parent
        width: 100
        height: 50
        text: "Button"
        highlighted:  hovered
    }

    Rectangle {
        id: cursorMarker
        width: 1
        color: "black"
        anchors.top: parent.top
        anchors.bottom: parent.bottom
    }

    MouseArea {
        anchors.fill: parent
        hoverEnabled: true

        onPositionChanged: {
            cursorMarker.x = mouse.x
        }

    }
}

在此示例中,MouseArea 位于按钮上方并拦截所有鼠标消息。因此,当鼠标光标移到按钮上方时,按钮不会突出显示。如果将 MouseArea 放置在按钮下方,则当鼠标移到按钮上时光标标记未正确定位。 但我需要两者:光标标记正确定位在整个对话框上方,并且按钮正常工作。 如何解决这个问题?

【问题讨论】:

  • Reading propagateComposedEvents 我认为这是不可能的,因为传播只针对 clicked、doubleClicked 和 pressAndHold 事件进行
  • 也许有另一种方法可以实现此功能,无需事件传播。
  • 可能你可以通过将cursorShape设置为带有垂直线的普通鼠标指针来到达某个地方

标签: qt qml qtquick2


【解决方案1】:
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12

Window {
visible: true
width: 640
height: 480

property int mousePosX : 0
property int mousePosY : 0

Button {
    anchors.centerIn: parent
    width: 100
    height: 50
    text: "Button"
    // Test if the mouse is within the Button
    highlighted:  mousePosX > x && mousePosX > y && mousePosX < x + width && mousePosY < y + height
}

Rectangle {
    id: cursorMarker
    x: mousePosX
    width: 1
    color: "black"
    anchors.top: parent.top
    anchors.bottom: parent.bottom
}

MouseArea {
    id: mouse
    anchors.fill: parent
    hoverEnabled: true

    onPositionChanged: {
        mousePosX = mouse.x
        mousePosY = mouse.y
    }
}
}

我提出以下建议(不完全是您的要求,而是实现相同的另一种方法):

  1. 将鼠标位置存储在一些变量中。
  2. 然后检查当前鼠标位置是否在按钮对象内(通过查看它是否位于该按钮的边界框内)

【讨论】:

  • 这看起来像是一种解决方法,但似乎这是唯一的解决方案。而且这个解决方案很不方便:实际上我在这个对话框中有很多控件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-10
  • 2020-06-14
相关资源
最近更新 更多