Search code examples
c++qmlsignalsqtquick2qobject

How to listen to the signal of a view while having a QObject instance of it?


I have created an attached object as described here.
This is my qml file in which I have used the attached object (Constraint.widthInParent):

 Window {
     id: root
     width: 640
     height: 480
     visible: true
     title: qsTr("Hello World")

     Rectangle {
         id: rect
         color: "black"
         height: width

         Constraint.widthInParent: 0.2
     }
}

In the above example, I have used the attached object in a Rectangle with the id rect and in this cpp file, I am getting the width of the Rectangle by using the QObject instance I have:

ConstraintAttached::ConstraintAttached(QObject *parent) : QObject(parent) {

    int viewWidth = parent->property("width").toInt();
}

Now I want to listen to the signals in this way...
My Rectangle has a signal that is widthChanged and now, I want to receive that signal through the QObject instance I have. So, how can I listen to a view signal (e.g widthChanged) through a QObject instance?


Solution

  • As you already have a valid pointer to a QObject* that lives inside the QML engine, you can simply do whatever you may do with any other QObject.

    So, the short answer is :

    connect(parent, SIGNAL(widthChanged()), this, SLOT(doSomething()));
    

    This is the older signal/slot syntax where you use the SIGNAL() and SLOT() macros instead of passing function pointers or lambda functions.

    But let's go further to get familiar with the Qt Meta Object system. You can run this code on the QObject* you have in hand, to get more information about its functions. Let's assume that you still have the QObject* parent:

        auto methodCount = parent->metaObject()->methodCount();
        for(int i = 0 ; i<methodCount ; ++i){
            auto method = parent->metaObject()->method(i);
            qDebug() << method.methodSignature();
        }
    
    

    This will list all methods of the QObject* parent. Read the documentation of QMetaObject and QMetaMethod, to see other possibilities. Actually the MOC, is generating a vast amount of information about a single QObject that is accessible runtime.

    Good Luck