使用C ++对象Q_PROPERTY绑定复选框“checked”属性 [英] Binding Checkbox 'checked' property with a C++ object Q_PROPERTY

查看:293
本文介绍了使用C ++对象Q_PROPERTY绑定复选框“checked”属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习QtQuick,我正在使用C ++类和QML属性之间的数据绑定。

I'm learning QtQuick and I'm playing with data binding between C++ classes and QML properties.

在我的C ++对象模型中,我有两个属性: / p>

In my C++ object Model, I have two properties :

Q_PROPERTY(QString name READ getName WRITE setName NOTIFY nameChanged)
Q_PROPERTY(bool status READ getStatus WRITE setStatus NOTIFY statusChanged)

在我的.qml文件中:

And in my .qml file :

TextEdit {
    placeholderText: "Enter your name"
    text: user.name
}

Checkbox {
    checked: user.status
}

当我用 setName 从我的C ++代码,它会自动反映在视图中。
当我检查/取消选中复选框,或者当我从我的C ++代码调用 setStatus()时,没有任何反应。看起来属性检查的复选框与 TextEdit 组件的行为不同。

When I change the user name with setName from my C++ code, it is automatically reflected in the view. When I check/uncheck the checkbox, or when I call setStatus() from my C++ code, nothing happens. It seems the property checked of checkboxes haven't the same behavior as TextEdit components.

我不想以声明方式绑定我的属性。不是Qt Quick支持属性绑定?

I don't want to bind my properties in a declarative way. Doesn't Qt Quick support property binding ?

感谢您的帮助。

推荐答案

如leemes指出,用户单击复选框将打破您创建的绑定。所以,不要创建绑定,而是直接连接到更改信号来处理get情况。使用onClicked处理set大小写。此解决方案还需要您在Component.onCompleted()中初始化。例如...

As leemes points out, user clicking the check box breaks the binding you've created. So, don't create the binding, but instead connect to the change signal directly to handle the "get" case. Use "onClicked" to handle the "set" case. This solution requires you also initialize in Component.onCompleted(). For example...

CheckBox {
    id: myCheck
    onClicked: user.status = checked
    Component.onCompleted: checked = user.status
    Connections {
        target: user
        onStatusChanged: myCheck.checked = user.status
    }
}

这篇关于使用C ++对象Q_PROPERTY绑定复选框“checked”属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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