首页 > 解决方案 > 从 Listview 拖动到放置区域

问题描述

我在此处遵循此示例使用 ListView 拖放来创建库存 UI。但是,我已将组件分解为主要部分、Listview 和 droparea。一切正常,除了我无法获得ReferenceError: listView is not defined. 请帮忙

主要区域

import QtQuick 2.15
import QtQuick.Controls 2.15

Page{
    id:dragRect

    Rectangle {
        id: root
        width: 400
        height: 400

        ListViewElem{
        }

        DropAreaElem{}
    }

}

ListViewElem

import QtQuick 2.15

ListViewElem {
    id: listView
    width: parent.width / 2
    height: parent.height

    property int dragItemIndex: -1

    model: ListModel {
        Component.onCompleted: {
            for (var i = 0; i < 10; ++i) {
                append({value: i});
            }
        }
    }

    delegate: Item {
        id: delegateItem
        width: listView.width
        height: 50

        Rectangle {
            id: dragRect2
            width: listView.width
            height: 50
            anchors.horizontalCenter: parent.horizontalCenter
            anchors.verticalCenter: parent.verticalCenter
            color: "salmon"
            border.color: Qt.darker(color)

            Text {
                anchors.centerIn: parent
                text: modelData
            }

            MouseArea {
                id: mouseArea
                anchors.fill: parent
                drag.target: dragRect2

                drag.onActiveChanged: {
                    if (mouseArea.drag.active) {
                        listView.dragItemIndex = index;
                    }
                    dragRect2.Drag.drop();
                }
            }

            states: [
                State {
                    when: dragRect2.Drag.active
                    ParentChange {
                        target: dragRect2
                        parent: root
                    }

                    AnchorChanges {
                        target: dragRect2
                        anchors.horizontalCenter: undefined
                        anchors.verticalCenter: undefined
                    }
                }
            ]

            Drag.active: mouseArea.drag.active
            Drag.hotSpot.x: dragRect2.width / 2
            Drag.hotSpot.y: dragRect2.height / 2
        }
    }
}

DropAreaElem

import QtQuick 2.15


Rectangle {
    width: parent.width / 2
    height: parent.height
    anchors.right: parent.right
    color: "#aaff0011"

    DropArea {
        id: dropArea
        anchors.fill: parent
        onDropped: {
            listView.model.remove(listView.dragItemIndex);
            listView.dragItemIndex = -1;
        }
    }
}


标签: qtqml

解决方案


您应该id向您的组件提供

import QtQuick 2.15
import QtQuick.Controls 2.15

Page{
    id:dragRect

    Rectangle {
        id: root
        width: 400
        height: 400

        ListViewElem{
          id: listView
        }

        DropAreaElem{
          id: dropArea
        }
    }

}

推荐阅读