C++ QQuickItem:如何在项目大小更改时触发函数
C++ QQuickItem: How to trigger a function on item size change
我在 C++ 中有一个 QQuickItem,它在 QML 应用程序中实例化。如果我的 QQuickItem 的宽度 属性 发生变化,我想在 C++ 端触发一个自定义函数。
在 QML 中,我会执行 onWidthChanged: { my code}。我如何在 C++ 端执行此操作?
如果您想响应自定义 QQuickItem
中的尺寸变化,请为每个项目重新实现 geometryChanged()
function. This has the benefit of not creating extra signal-slot connections,如果您要连接到 widthChanged()
/ heightChanged()
个信号。
Here是在 Qt Quick Controls 2 中重新实现的示例。
width
是具有 widthChanged
信号的 qproperty
,因此您可以将该信号连接到某个插槽。
class FooItem : public QQuickItem
{
Q_OBJECT
public:
FooItem(QQuickItem *parent=Q_NULLPTR): QQuickItem(parent){
connect(this, &FooItem::widthChanged, this, &FooItem::onWidthChanged);
}
Q_SLOT void onWidthChanged(){
qDebug()<<width();
}
};
我在 C++ 中有一个 QQuickItem,它在 QML 应用程序中实例化。如果我的 QQuickItem 的宽度 属性 发生变化,我想在 C++ 端触发一个自定义函数。
在 QML 中,我会执行 onWidthChanged: { my code}。我如何在 C++ 端执行此操作?
如果您想响应自定义 QQuickItem
中的尺寸变化,请为每个项目重新实现 geometryChanged()
function. This has the benefit of not creating extra signal-slot connections,如果您要连接到 widthChanged()
/ heightChanged()
个信号。
Here是在 Qt Quick Controls 2 中重新实现的示例。
width
是具有 widthChanged
信号的 qproperty
,因此您可以将该信号连接到某个插槽。
class FooItem : public QQuickItem
{
Q_OBJECT
public:
FooItem(QQuickItem *parent=Q_NULLPTR): QQuickItem(parent){
connect(this, &FooItem::widthChanged, this, &FooItem::onWidthChanged);
}
Q_SLOT void onWidthChanged(){
qDebug()<<width();
}
};