Question

What do you consider best practice for designing signal/slot interaction for updating member values in a class?

For instance, consider a member variable that is represented on a UI. The user alters the value in the UI. A signal/slot relationship exists to automatically update the member variable via a member variable update function.

We also want changes to the member variable to be automatically updated on the UI, so there is a signal/slot relationship the other way. On updating the member variable via the update function, a signal triggers the UI to be updated.

How do you prevent these becoming circular? Is it as simple as checking the new value against the current value when the member variable update function is called, and only sending a signal to update the UI if there is a difference?

Or...is there a more elegant way of doing this?

Était-ce utile?

La solution

How do you prevent these becoming circular? Is it as simple as checking the new value against the current value when the member variable update function is called, and only sending a signal to update the UI if there is a difference?

Yes.

Pragmatically speaking, this allows you to connect, say, a QDial, a QSpinBox and a QSlider and make them stay in sync, without requiring you to do extra magic to prevent infinite loops.

Semantically speaking, have you noticed that the typical signal when a value changes is called valueChanged?

void myClass::setValue(int value) {
    if (m_value != value) {
        m_value = value;
        emit valueChanged(value); // YES, THE VALUE *DID* CHANGE!
    }
}

It means that the signal shouldn't be emitted if there's no change of the value, which is what happens if you try to set the value to the current one -- either by setting it directly, or via a signal/slot invokation.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top