如何在 QML 的 ListView 中绑定到来自委托组件的信号 [英] How to bind to a signal from a delegate component within a ListView in QML

查看:27
本文介绍了如何在 QML 的 ListView 中绑定到来自委托组件的信号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 ListView 的可点击委托组件(或 GridViewRepeater).这些委托组件需要在触发时发出一个信号以及自定义数据,该信号可由 ListView 的父级拾取.如何实现这种信号绑定?

Let's say I have a ListView of clickable delegate components (or GridView or Repeater). These delegate components need to emit a signal along with custom data when triggered that can be picked up by the parent of the ListView. How can this signal binding be achieved?

例如以下代码是我的尝试,但我不知道如何将委托组件的 trigger 信号绑定到 root 中的 componentTriggered 信号项目?

e.g. The following code is my attempt but I don't know how to bind the trigger signal of the delegate component to the componentTriggered signal in the root item?

Item {
    id: root
    anchors.fill: parent

    signal componentTriggered(string name)

    onComponentTriggered: {
        console.log(name + ' component was triggered')
    }

    ListModel {
        id: myModel

        ListElement { name: "alpha" }
        ListElement { name: "beta" }
        ListElement { name: "gamma" }
        ListElement { name: "delta" }
    }

    ListView {
        id: myListView
        width: 100
        height: 600

        model: myModel
        delegate: TheDelegate { name: model.name }
    }
}

访问TheDelegate.qml

import QtQuick 2.0

Rectangle {
    id: root
    width: 100
    height: 50
    color: "steelblue"
    border.color: "white"
    border.width: 2

    property string name

    signal trigger(string name)

    Text {
        anchors.centerIn: parent
        text: model.name
    }

    MouseArea {
        anchors.fill: parent
        onClicked: {
            console.log(root.name + ' clicked')
            root.trigger(root.name)
        }
    }
}

推荐答案

您可以在 Component.onCompleted 处理程序中连接这两个信号.

You could connect both signals in the Component.onCompleted handler.

使用您的代码会是这样的:

Using your code it would be something like this:

ListView {
        id: myListView
        width: 100
        height: 600

        model: myModel
        delegate: TheDelegate {
            name: model.name
            Component.onCompleted: {
                trigger.connect(root.componentTriggered)
            }
        }
    }

除了调用信号 componentTriggered 您还可以实现一个函数,但这取决于您的要求.反正信号没问题.

Instead of calling the signal componentTriggered you could also implement a function, but it depends on your requirements. The signal is OK in any case.

这篇关于如何在 QML 的 ListView 中绑定到来自委托组件的信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆