4

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?

4

1 回答 1

6

你如何防止这些变成圆形?是否像调用成员变量更新函数时检查新值与当前值一样简单,如果有差异则只发送信号更新UI?

是的。

务实地说,这允许您连接,例如,QDial、QSpinBox 和 QSlider,并使它们保持同步,而不需要您做额外的魔法来防止无限循环。

从语义上讲,您是否注意到值更改时的典型信号称为value Changed

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

这意味着如果值没有变化,则不应发出信号,如果您尝试将值设置为当前值,则会发生这种情况 - 通过直接设置或通过信号/插槽调用。

于 2013-08-15T09:52:18.440 回答