For a NOTIFY signal on a property, what difference does it make if I give it a parameter?

时光怂恿深爱的人放手 提交于 2019-12-11 08:41:47

问题


Suppose I have a class that looks like this:

class Something : QObject {
  Q_PROPERTY(int something READ getSomething NOTIFY somethingChanged)

  // ...

  signals:
    void somethingChanged();
}

According to the documentation, declaring somethingChanged as void somethingChanged() and void somethingChanged(int) (note the parameter) are both valid. Why would I want to do it one way over the other?


回答1:


Emitting the value allows you to use that value without having a reference to the object it is a property of. It is how things are usually done in the C++ API, this saves you from manually having to keep references to objects, so that you can read in the value upon a change notification. Note that even then, you can use QObject::sender() to find the sender object if necessary, but emitting the value is just more straightforward.

In QML what you end up using most of the time is bindings, which are very fast and powerful, and involve having references to the objects, and change notifications cause the binding expressions which reference the properties to automatically reevaluate. Thus it is not necessary to emit the actual value.

There is nothing stopping you from having the best of both worlds. A notification signal that emits the new value appears to work just fine with QML bindings. So if for some reason you need to emit a value, don't shy away from it, it will not jeopardize QML compatibility.



来源:https://stackoverflow.com/questions/42870182/for-a-notify-signal-on-a-property-what-difference-does-it-make-if-i-give-it-a-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!