How to capture a signal in QML?

2019-03-18 21:15发布

How I can send s signal from one qml component to another?

Below is an example:

Rectangle {
    id: main
    width: 360; height: 360
    signal clicked()

    Text {
        id: testStr
        anchors.centerIn: parent
        text: "Hello World"
    }
    MouseArea {
        id: mouseArea
        anchors.fill: parent
        onClicked: { Qt.quit(); }
    }

    Component.onCompleted: clicked()
    onClicked:  testStr.text = "Demo"
}

How do I capture the signal in other Component?

标签: qt qml
4条回答
▲ chillily
2楼-- · 2019-03-18 21:25

QML

Button{
  id: btn_add_pq
  text: "Add"
  onClicked: {
    var component = Qt.createComponent("add_pq.qml")
    var dialog    = component.createObject(root)
    dialog.open()

    dialog.accepted.connect(function(){
      console.log("ID     :" + window.in_id)
      console.log("Name   :" + window.in_name)
      console.log("Comment:" + window.in_comment)
    })
  }
}

add_pq.qml

Dialog {
  id:dialog
  ...
  property alias in_id: txtID.text
  property alias in_comment: txtComment.text
  property alias in_name: txtName.text
  ...
  contentItem: GridLayout{
    ...
    TextField{
      id: txtComment
      Layout.alignment: Qt.AlignRight
    }
    Button{
      Layout.columnSpan: 2
      text: "Add"
      Layout.alignment: Qt.AlignRight
      onClicked: {
        dialog.click(StandardButton.Save)
      }
    }
  }
查看更多
贪生不怕死
3楼-- · 2019-03-18 21:33

You should use connect() method of component's signals (signals themselves are objects).

function clickHandler() {
    console.log('main clicked')
}
Component.onCompleted: {
    main.clicked.connect(clickHandler)
}

See http://developer.qt.nokia.com/doc/qt-4.8/qmlevents.html

查看更多
再贱就再见
4楼-- · 2019-03-18 21:36

In the other object, you simply add a on word followed by the signal name. EG:

Rectangle {
  YourQmlObject {
    onClicked: { ... }
  }
}

(clicked is somewhat a confusing signal name because it's common. But if you had called your signal orange, you'd make the binding onOrange:)

查看更多
迷人小祖宗
5楼-- · 2019-03-18 21:43

you can use QML connection element

 Connections {
 target: yourQmlObject 
 onClicked: foo(...)
 }
查看更多
登录 后发表回答