qtsignalsslotqobject

How to pass QObject as argument from signal to slot in Qt connect


My original code passed a QStringList from the signal to the slot and then returned a QList .
Everything worked fine but I needed to change both the QStringList and QList into 2 different subclassed QObjects. Since then I have been receiving errors like "synthesized method first required here" or it simply crashes without any error message.

I understand that qt copies all arguments passed in a queued connection and a QObject cannot be copied. So instead of returning a QObject I thought I would create both QObjects prior to emitting the signal.
Then I would pass references to each object, modify one of them in the slot function and void the return value.

Unfortunately the app still crashes no matter how I code the signal and slot functions.

How can I code the signal/slot functions and connect them to either pass both qobjects as arguments or return a qobject?

MyQObject1 obj1("a","b","c");
MyQObject2 obj2();
emit sendSignal(&obj1, &obj2);
// or
MyQObject2 obj2 = emit sendSignal(&obj1);

connect(someObj, SIGNAL(sendSignal(const QObject&)), this, SLOT(receiveSignal(const QObject&)));

The receiveSignal() function does not directly create or modify any QObject.
It has to pass the QObjects to another function first which then either modifies obj2 or creates and returns it.
Any code examples would be greatly appreciated.


Solution

  • Usually QObject is passed by pointer, not by reference (note that QObject cannot be copied and cannot be passed by value). QObject* is registered as a meta type by default. So creating a signal and a slot with QObject* argument is enough to get them work:

    private slots:
      void test_slot(QObject* object);
    
    signals:
      void test_signal(QObject* object);
    

    Initialization:

    connect(this, SIGNAL(test_signal(QObject*)), this, SLOT(test_slot(QObject*)));
    

    Emitting:

    QObject* object = new QObject();
    emit test_signal(object);
    

    Of course the signal and the slot could be in different classes.