QtQuick2: Handle onWheel event inside of a ScrollV

2019-06-02 20:04发布

问题:

I have to put component X inside of a ScrollView. Component X has to handle mouse wheel event, but ScrollView handles it. So, following example (simplified) doesn't work.

How to let Rectangle's mouse area handle OnWheel event?

import QtQuick 2.1
import QtQuick.Controls 1.0
import QtQuick.Window 2.0
import QtQuick.Layouts 1.0

ApplicationWindow {
    width: 640
    height: 480

    ScrollView {
        height: 100
        width: 100

        ColumnLayout{
            Rectangle {
                color: "red"
                width: 50
                height: 50
                MouseArea {
                    anchors.fill: parent
                    onWheel: {
                        console.log("onWheel"); // it doesn't work
                    }
                    onClicked: {
                        console.log("onClicked"); // it works
                    }
                }
            }
        }
    }
}

回答1:

I find a way to solve it, but I can't properly explain it. :(

This document illustrates the concept of visual parent and object parent, but it dosen't tell how they affect the event propagation.

Hope someone would give a clear explaination.

ApplicationWindow {
    width: 640
    height: 480

    ScrollView {
        id: scroll   // add an id
        height: 100
        width: 100

        ColumnLayout{
            Rectangle {
                id: rect   // add an id
                color: "red"
                width: 50
                height: 50
                MouseArea {
                    parent: scroll      // specify the `visual parent`
                    anchors.fill: rect       // fill `object parent` 
                    onWheel: {
                        console.log("onWheel"); // now it works
                    }
                    onClicked: {
                        console.log("onClicked"); // it works
                    }
                }
            }
            Repeater {
                model: 30
                Text{ text: index }
            }
        }
    }  
}


回答2:

This as actually a bug in Qt:

  • https://bugreports.qt.io/browse/QTBUG-38083

This is being resolved in:

  • https://codereview.qt-project.org/#change,82572
  • https://codereview.qt-project.org/#change,82576


标签: qt qml qtquick2