“绑定"两个QML CheckBox在一起,确保它们的状态始终相同 [英] "Bind" two QML CheckBoxes together, ensuring their states are always identical

查看:262
本文介绍了“绑定"两个QML CheckBox在一起,确保它们的状态始终相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在GUI的不同页面上创建两个复选框,以使它们在语义上是相同"复选框-相同的标签,相同的效果. (在两个页面上都放置它们只是为了方便用户.)

I'd like to create two checkboxes on different pages of a GUI such that they are semantically the "same" checkbox -- same label, same effect. (Having them on both pages is just for the user's convenience.)

这需要将两个CheckBox QML元素绑定"在一起,以便一个状态始终由另一个状态反映,反之亦然.

This requires "binding" two CheckBox QML elements together such that the state of one is always reflected by the other, and vice-versa.

这是等同于此处的要求,除了我使用的是QML/JS而不是JS/JQuery.

This is equivalent to what's being asked here, except I'm using QML/JS instead of JS/JQuery.

我认为将每个复选框的checked状态绑定到某些全局持久属性的幼稚实现会起作用:

I thought that a naive implementation of binding the checked state of each checkbox to some global persistent property would work:

// Global shared state object
pragma Singleton
MySharedState {
    my_feature_on: false
}

然后,在两个不同的页面上,完全相同的CheckBox实例化:

Then, on two separate pages, the exact same CheckBox instantiation:

// Checkbox implementation (on both pages
CheckBox {
    checked: MySharedState.my_feature_on
    onClicked: MySharedState.my_feature_on = checked
}

但是,这不起作用,因为单击复选框时,它会破坏初始的checked绑定.这是预期的行为,而不是错误.

However, this doesn't work, because when a checkbox is clicked, it breaks the initial checked binding. This is the intended behavior, not a bug.

那么如何确保两个复选框始终共享相同的已选中"状态?

So how can I ensure that two checkboxes always share the same "checked" state?

编辑:根据下面的评论,以上实现无需修改即可随Qt 5.7发行的Qt Quick Controls 2一起使用,因此该问题仅适用于以前的Qt版本(包括5.6,这是长期支持"版本.

According to a comment bellow, the above implementation will work without modification in Qt Quick Controls 2, which was released with Qt 5.7, so this question only applies to prior versions of Qt (including 5.6, which is a "long-term support" release).

推荐答案

单击复选框后,其'checked属性将被更改,原始的checked: MySharedState.my_feature_on绑定也将被删除. 您需要创建属性绑定从Javascript 还原到原始绑定,如JP Nurmi在您链接的错误报告中所述.

When a checkbox is clicked its' checked property is changed and the original checked: MySharedState.my_feature_on binding is removed. You need to create a property binding from Javascript to restore the original binding as explained by J-P Nurmi in the bug report you linked.

为此,您必须使用 Qt.binding() .

For that you have to use Qt.binding().

CheckBox {
    checked: MySharedState.my_feature_on
    onClicked: { // the checked binding is removed since checked has been changed externally to the binding
        MySharedState.my_feature_on = checked
        checked = Qt.binding(function() {return MySharedState.my_feature_on}); //we restore the checked binding
    }
}

这篇关于“绑定"两个QML CheckBox在一起,确保它们的状态始终相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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