numberCruncher
numberCruncher

Reputation: 645

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

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?

Upvotes: 1

Views: 1766

Answers (2)

Mitch
Mitch

Reputation: 24416

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.

Upvotes: 5

eyllanesc
eyllanesc

Reputation: 244202

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.

Upvotes: 1

Related Questions