C++ QQuickItem: How to trigger a function on item

2019-07-23 11:45发布

I have a QQuickItem in C++ which is instantiated in a QML application. I want to trigger a custom function on the c++ side if the width property of my QQuickItem changes.

In QML I would do onWidthChanged: { my code}. How can I do this on the c++ side?

标签: qt qml qtquick2
2条回答
淡お忘
2楼-- · 2019-07-23 12:17

If you want to respond to size changes in a custom QQuickItem, reimplement the geometryChanged() function. This has the benefit of not creating extra signal-slot connections for each item, as would be necessary if you were to connect to the widthChanged()/heightChanged() signals.

Here's an example of it being reimplemented in Qt Quick Controls 2.

查看更多
Deceive 欺骗
3楼-- · 2019-07-23 12:23

width is qproperty that has the widthChanged signal, so you can connect that signal to some slot.

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();
    }
};

Similarly, the other properties such as height, x, y, z.

查看更多
登录 后发表回答