Search code examples
c++qtqmlqt-quickqt4.8

Propagating onPositionChanged events to background items in QtQuick 1.1


Background.qml

import QtQuick 1.1

Item {
    MouseArea {
        id: backgroundMouseArea
        anchors.fill: parent
        hoverEnabled: true

        onPositionChanged: {
            console.log("Background")
        }
    }
}

Foreground.qml

import QtQuick 1.1

Item {
    Background {
        width: 1920
        height: 1080
    }

    MouseArea {
        anchors.fill: parent
        hoverEnabled: true

        onPositionChanged: {
            console.log("Foreground")
            [mouse.accepted = false] - Not working (as the docs say)
            [backgroundMouseArea.onPositionChanged(mouse)] - Not working
        }
    }
}

I need to execute onPositionChanged event on both background and foreground items.

F.ex. for onPressed I would do it by setting mouse.accepted = false in the foreground item.

Can I call onPositionChanged of the background item manually? If yes, how do I do it?


Solution

  • I am not completely sure what you are trying to achieve here. A MouseArea is meant to grab mouse events from hardware. If you really want to propagate mouse events to background from a different MouseArea, maybe what you actually want to do is give Background a simple property mousePosition instead of the MouseArea, and then set that position from the Foreground onPositionChanged handler.

    Also, your Foreground code relies on an internal id parameter inside of Background. This smells really bad. It is often more useful to think about the "Public API" of the Background and Foreground "classes". If what I described above is really what you want to do, this is what it should look like IMHO:

    // Background.qml
    import QtQuick 1.1
    Rectangle {
        // an object with just x and y properties
        // or the complete mouseevent, whatever you want
        // Use variant for QtQuick 1/Qt4, var for QtQuick 2.0 / Qt5
        property variant mousePosition
        onMousePositionChanged: console.log(
          "Background " + mousePosition.x + " " + mousePosition.y
        )
    }
    
    //Foreground.qml
    import QtQuick 1.1
    Item {
      // use only ids defined in the same file
      // else, someone might change it and not know you use it
      Background { id: background }
      MouseArea {
        anchors.fill: parent
        hoverEnabled: true
    
        onPositionChanged: {
           console.log("Foreground")
           background.mousePosition = {x: mouse.x, y: mouse.y}
        }
      }
    }
    

    ...........