基本使用
(详见官方博文:https://www.qt.io/blog/all-about-property-bindings-in-qt-6.2)
在 QML 中,我们可以通过属性绑定使得关联的属性自动更新。如下的代码片段使得 height 绑定到 width,当 wdith 值变化时,height 的值也能根据绑定的表达式重新计算:
import QtQuick 2.15
Rectangle {
width: 10
height: width
}
在 Qt6 中,属性绑定这一机制也被引入到了 Qt C++,将上面 QML 代码转化为 C++ 逻辑就是:
class Rectangle {
public:
QProperty width{10};
QProperty height;
Rectangle() {
height.setBinding([this]() {
return width.value();
});
}
};
在 QML 中,属性值修改时会触发 onXXXChanged 信号,如:
onWidthChanged: { /**/ }
onHeightChanged: { /**/ }
QProperty 也提供了三个对应的接口:
//值变更时回调
template
QPropertyChangeHandler QProperty::onValueChanged(Functor f)
//绑定,以及值变更时回调
template
QPropertyChangeHandler QProperty::subscribe(Functor f)
//值变更时回调,返回的不是模板更容易存储,可作为类成员
template
QPropertyNotifier QProperty::addNotifier(Functor f)
Rectangle rect;
QPropertyChangeHandler cb1=rect.height.onValueChanged([&]{
qDebug()
关注
打赏