Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Trying to dynamically create objects and have them send to a slot in MainWindow.



  • Hello,

    I've created an object lets just say it's called TestObject it's just a QFrame with a button inside of it.

    in MainWindow I can create this object and everything is good to go. I've been able to create a signal/slot in both TestObject (the emiter) and in MainWindow(the slot). In MainWindow I have code as such:

    *TestObject ObjectA = new TestObject(this, Qpoint(20, 20));

    This creates a new TestObject and is visible in MainWindow.

    I've then have a function which sets text in a label.

    void MainWindow::RxText()
    {
    label->setText("TestObject button signal Rx'd");
    }

    I then can change that text via a call to connect as such

    connect(ObjectA, &TestObject::TxText, this, MainWindow::RxText); // (This is in the MainWindow Constructor)

    This works beautifully. However my next step I would like to do is create a line of code that will respond to the signal of any button from any TestObject I create.

    for instance something like this would be handy.

    connect(TestObject <anytestobject>, &TestObject::TxText, this, MainWIndow::RxText);
    Would anyone know of a good way to do this? I can't seem to figure this part out.


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    You can build a list of these objects and then use a loop to connect each of them to the slot you want.


  • Qt Champions 2017

    connect(ObjectA, &TestObject::TxText, this, MainWindow::RxText);

    What is the meaning of anytestobject ? Are you creating the multiple objects ? if yes, are you strong them somewhere ? You have already connected the single object. Signal/slot is object to object. Connect statement takes individual object as argument. You make connect the moment object is created or build list of object, iterate through & then connect as @SGaist suggested.

    if this is not the case, you need to tell what do you mean by anytestobject.



  • Thank you SGaist and Dheerendra - that was sufficent info. Still getting the hang of C++.



  • @dheerendra Hi I'm just toying with Object creation with GUI objects/QObjects.

    With QObjects the main thing I've learned here is that you need to use a pointers when using a QList or anyother container.

    QList<TestObject> TObjectList;*


  • Qt Champions 2017

    Any qobject type instances to be stored in qlist shoud be dynamically created objects only. Data types in containers should be assignable I.e they shud have copy constructor and assignment operator. Both are disabled for qobject types. Hence objects should be pointer types.



  • Dheerendra, I did not know this, thank you very much. I'm still very much a noob to C++, Qt and programming in general. Thanks again!


Log in to reply