Qml仅从后端更新Ui

时间:2019-02-24 16:01:33

标签: c++ qt qml

如何防止切换ui元素(如switch或复选框)直接更新其外观? 出现以下情况:用户可以通过开关(开/关)设置选项。然后,该请求由应用程序的后端处理。如果请求可以被执行,则开关应切换其视觉状态,否则将保持原样。 将“ checked”属性绑定到后端的状态不起作用。

修改 不起作用(!)示例:

C ++

class Backend: public QObject
{
    Q_OBJECT
    Q_PROPERTY(bool state READ state WRITE setState NOTIFY stateChanged)
public:
    explicit Backend(QObject* parent = nullptr);

    bool state() { return m_state; }
    void setState(bool state) {
        // process state transition 
        emit stateChanged();
    }

signals:
    void stateChanged();

private:
    bool m_state{ false};
};

QML:

Item {
    Backend {
        id: myBackend
    }

    Switch {
        id: mySwitch
        // what to do here?
        // switch needs to update the backend, but also be able to represent the actual state, provided by the backend
        checked: myBackend.state 

        onClicked: myBackend.state = checked
    }
}

1 个答案:

答案 0 :(得分:0)

您可以在Switch内声明一个MouseArea,然后像这样在onClick函数中更改状态; <​​/ p>

Switch {
  checked: myBackend.state 

  MouseArea {
    anchors.fill: parent

    onClick: {
      myBackend.state = !myBackend.state
    }
  }
}

这样做,Switch的选中属性将仅绑定到您的state属性。