Tomas Tintera
Tomas Tintera

Reputation: 829

QML: Buble event to parent

How can component inform parents when certain action happens? I mean something like event.buble in JavaScript. https://www.w3docs.com/learn-javascript/bubbling-and-capturing.html

For example some elements in dialog can send a "Ok" or "Cancel" action. Parent item does not know all the child items items in advance. I would add something like:

Widget {
   signal cancel
   signal ok
   ...
}


ParentItem {
  id: myParentItem

  onCancel { ... }
  onOk { ... }

  Widget {
    id: first
  }
  Widget {
    id: second
  }

  // no connection section needed. Auto-connect signals by name.
}

}

Edit: Note: adding separate Widget and then connection is a bit impractical. Some one can forget to add one or other, moreover when deleting and renaming one can remove only one part or rename one part incorrectly.

Calling parent.functionName is impractival too because then such Widget can be used only in parents having functionName.

Upvotes: 0

Views: 146

Answers (1)

JarMan
JarMan

Reputation: 8277

One idea is to search through all the children and check their type. If they are the Widget type, then connect their signals to some ParentItem function. I haven't tested this code, but something like it should work.

ParentItem {
  id: myParentItem

  function doCancel() { ... }
  function doOk() { ... }

  Component.onCompleted: {
    for (var i = 0; i < children.length; i++) {
      if (children[i] instanceOf Widget) {
        children[i].onOk.connect(doOk);
        children[i].onCancel.connect(doCancel);
      }
    }
  }

  Widget {
    id: first
  }
  Widget {
    id: second
  }
}

Upvotes: 1

Related Questions