问题
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