Qt 5.4/Qml:防止绑定循环 [英] Qt 5.4/Qml: Prevent binding loop

查看:1119
本文介绍了Qt 5.4/Qml:防止绑定循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个全局单例"Settings",其中包含应用程序设置.当我尝试运行以下代码时,我得到一个QML CheckBox: Binding loop detected for property "checked":

I have a global singleton "Settings" which holds application settings. When I try to run the following code I get a QML CheckBox: Binding loop detected for property "checked":

CheckBox {
    checked: Settings.someSetting                         
    onCheckedChanged: {
        Settings.someSetting = checked;
    }
}

很明显为什么会发生此错误,但是如何在没有绑定循环的情况下正确实现此功能呢?例如.我想将复选框的当前选中状态保存在设置单例中.

It is obvious why this error occurs, but how can I correctly implement this functionality without a binding loop? E.g. I want to save the current checked state of the checkbox in the settings singleton.

我正在使用Qt 5.4和Qml Quick2.

I am using Qt 5.4 and Qml Quick 2.

此致

推荐答案

不要绑定它.因为该复选框不完全依赖Setting.someSetting.

Don't bind it. Because the check box does not fully depend on Setting.someSetting.

当用户单击复选框时,CheckBox.checked会自行更改.同时,属性绑定不再有效.用户单击Settings.someSetting后,不能修改CheckBox.因此,checked: Settings.someSetting绑定是错误的.

When a user clicked the checkbox, the CheckBox.checked is changed by itself. At the same time, the property binding is no longer valid. Settings.someSetting cannot modify the CheckBox after it is clicked by user. Therefore, the checked: Settings.someSetting binding is wrong.

如果要在组件准备就绪时为复选框分配初始值,请使用Component.onCompleted进行分配:

If you want to assign an initial value to the check box when the component is ready, use Component.onCompleted to assign it:

CheckBox {
    id: someSettingCheckBox 

    Component.onCompleted: checked = Settings.someSetting
    onCheckedChanged: Settings.someSetting = checked; 
}

如果您要处理的是更复杂的场景,则在运行时可能会通过其他某些方式更改Setting.someSetting,并且需要同时更改复选框的状态.捕获onSomeSettingChanged信号并显式更改复选框.仅在程序/小部件/对话框/xxx完成后,才将someSettingCheckBox的值提交给Settings.

If you are working on a more complex scenario, the Setting.someSetting may be changed by some other things during runtime and the state of the check box is required to be changed simultaneously. Catch onSomeSettingChanged signal and explicitly changed the check box. Submit the value of someSettingCheckBox to Settings only when the program/widget/dialog/xxx finished.

CheckBox { id: someSettingCheckBox }

//within the Settings, or Connection, or somewhere that can get the signal.
onSomeSettingChanged: someSettingCheckBox.checked = someSetting

这篇关于Qt 5.4/Qml:防止绑定循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆