首页 > 解决方案 > 如何在 ScrollView 和 Flow 中使用 MouseArea

问题描述

我确实想使用 MouseArea 在 ScrollView 中显示 Flow 中的可点击按钮。这种结构的原因是对象是从用户动态创建的,所以我想将它们放在 Flow 中以确保垂直放置,并在 ScrollView 中以确保在变成多个对象时滚动。

    ScrollView {
            clip: true
            id: shiftsScrollView
    
            wheelEnabled: true
            //ScrollBar.vertical.policy: ScrollBar.AlwaysOn
    
            height: 100
            width: 300
            anchors.left: shiftsTitle.left
            anchors.top: shiftsTitle.bottom
            //spacing: 0
            anchors.leftMargin: 0
            anchors.topMargin: 20
    
            Flow {
                id: scrollableFlow
                layoutDirection: Qt.RightToLeft
                flow: Flow.TopToBottom

// Objects will be filled in here at runtime
    
            }
    
    
        }

这是在 js 函数中创建对象的方式:

for (let i=0; i<amountOfShifts; i++) {
            var myShift = Qt.createQmlObject(
                        'ShiftListElement {
                        width: 300;
                        height: 25;
                        shiftText: "'+splittedShifts[i]+'";
                        shiftName: "'+shiftNames[i]+'";

                        }',
                        scrollableFlow,
                        "shiftElement");
            shiftListObjects.push(myShift);
            shiftsScrollView.contentHeight = amountOfShifts * 25
        }

请注意,ID 'scrollableFlow' 是 ScrollView 中的 ID,您可以直观地看到它有效。对象在以前彼此不认识的情况下按顺序垂直放置。

包含非工作 MouseArea 的 QML 对象:

    Item {
        id: item1
    
        property string shiftText: "shift";
        property string shiftName: "name";
    
        width: 200
        height: 100
    
        Text {
            id: text1
            text: item1.shiftText
            anchors.verticalCenter: parent.verticalCenter
            font.pixelSize: 12
            anchors.horizontalCenterOffset: -30
            anchors.horizontalCenter: parent.horizontalCenter
        }
    
        Button {
            id: button
            width: 20
            height: 20
            text: qsTr("X")
            anchors.verticalCenter: text1.verticalCenter
            anchors.left: text1.right
            anchors.leftMargin: 20
            MouseArea {
                id: buttonCommitShiftMouseArea
                anchors.fill: parent
                preventStealing: true
                onClicked:
                {
    
                   console.log("I work!");
    
                }
            }
        }
    
    }

我找到了一些推荐属性“preventStealing”的答案,但在这种情况下似乎没有效果。我还尝试删除 Flow,这似乎也没有什么不同。它在常规项目中的 ScrollView 之外确实有效,这让我认为 ScrollView 窃取了其中的所有 MouseEvents。ScrollView 可根据需要滚动并以所需大小显示。

我错过了什么?谢谢您的帮助。

标签: qmlqt5mousearea

解决方案


推荐阅读