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

2019-07-23 12:20发布

问题:

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?

回答1:

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.



回答2:

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.



标签: qt qml qtquick2