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

一个人想着一个人 提交于 2019-12-11 10:46:18

问题


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.



来源:https://stackoverflow.com/questions/49667771/c-qquickitem-how-to-trigger-a-function-on-item-size-change

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!