如何从这些元素之一向listView的所有元素发送信号

时间:2017-05-16 12:10:38

标签: qt listview qml qtquick2

我使用了ListView,我尝试向signal的所有Elements发送ListView

Signal必须由ListView's Element 之一发送。

我试过这个,但只有发送Element才能抓住Signal

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0

ApplicationWindow {
    id: window
    visible: true
    width: 640
    height: 480

    ListModel {
        id: modelList
        ListElement {
            name: "Bill Smith"
        }
        ListElement {
            name: "John Brown"    
        }
        ListElement {
            name: "Sam Wise"
        }
    }

    ListView {
        width: window.width
        height: window.height    
        model: modelList
        delegate: Rectangle {
            id:elem
            signal activated()    
            width: window.width
            height: window.height/10
            color: "red"    
            Button {
                text: name
                anchors{
                    right: parent.right
                    top: parent.top
                    bottom: parent.bottom
                    margins: 10
                }
                onClicked: {
                    elem.activated()
                }
            }
            onActivated: {
                console.log("test")
            }
        }
    }
}

我认为我误解了这个文档,但是我很难找到一个很好的例子,对于这个案例,有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您可以在ListView的父级(例如ApplicationWindow)中定义信号,并在委托中编写信号处理程序并将其连接到父级中定义的信号

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0

ApplicationWindow {
    id: window
    visible: true
    width: 640
    height: 480

    signal someSignal(int arg);

    ListModel {
        id: modelList
        ListElement {
            name: "Bill Smith"
        }
        ListElement {
            name: "John Brown"    
        }
        ListElement {
            name: "Sam Wise"
        }
    }

    ListView {
        width: window.width
        height: window.height    
        model: modelList
        delegate: Rectangle {
            id:elem
            signal activated()    
            width: window.width
            height: window.height/10
            color: "red"
            Connections{
                target: window
                onSomeSignal: {
                     console.log("Argument: " + arg);
                }
            } 
            Button {
                text: name
                anchors{
                    right: parent.right
                    top: parent.top
                    bottom: parent.bottom
                    margins: 10
                }
                onClicked: {
                    window.someSignal(1);
                }
            }
            onActivated: {
                console.log("test")
            }
        }
    }
}