繁体   English   中英

如何在QML中捕获信号?

[英]How to capture a signal in QML?

我如何从一个qml组件发送信号到另一个?

以下是一个例子:

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"
}

如何捕获其他组件中的信号?

你应该使用组件信号的connect()方法(信号本身就是对象)。

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

请参阅http://developer.qt.nokia.com/doc/qt-4.8/qmlevents.html

在其他物体,只需添加一个on字,接着由信号名称。 例如:

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

(点击有点令人困惑的信号名称,因为它很常见。但是如果你把你的信号称为orange ,那么你就可以在onOrange:进行绑定onOrange:

你可以使用QML连接元素

 Connections {
 target: yourQmlObject 
 onClicked: foo(...)
 }

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)
      }
    }
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM