Qt World Summit: Submit your Presentation

Need to store custom class objects in a list/vector/etc

  • Hi, I'm very new to C++ and even newer to Qt. I am trying to teach myself the language by diving into the fire (this usually works very well for me.) Here is my problem, I am trying to store custom QWidget class objects in a list or a vector, etc... here in lies the problem. I have need to be able to spawn and destroy the widget (basically, a timer), the method that destroys the widget is IN the widget, but here in lies the rub: once I destroy the widget, how do I remove the reference to it in the list? I tried using a signal/slot, but the signal will trigger the removal of ALL the widgets. So I introduced a QSignalMapper. This will let me associate a specific int to the instance, and have it passed back to the post destroyed function in the window where the reference can then be removed, However. I can not insure that the instance will still be where I left it, because other instances could have been created/destroyed in such a way that they move the instance being destroyed to another index. So yea, that won't work.

    So QVector then? well, problem there is that the object becomes const when inserted into the Vector, so then I can't change the object.

    I guess I am hoping that one of you has a clue of what the best array type object would be for this? Sorry if my terminology isn't right, again. I am really green.

  • Moderators

    You said:

    I am trying to store custom QWidget class objects in a list or a vector

    You can't put QObject derived classes in containers. Puting them in is making a copy and QObejct derived classes are not copyable. Usually you store pointers to objects, not objects themselves.

    So you want to have a container of pointers to QObject derived classes, add some pointers to it and remove them when the objects are destroyed. Is that about right?

    Here's an example. A type of container doesn't matter. I'll just use a QVector, but it can be anything really - vector, list, set from Qt, std or anything else.

    void addToVector(QVector<QObject*>* v, QObject* obj)
        QObject::connect(obj, &QObject::destroyed, [=]{ v->removeOne(obj); });

    The connect part will remove the object from the container when it is destroyed. You would use it like this:

    QObject* obj = ... // construct the object somehow
    QVector<QObject*> v;
    addToVector(&v, obj);
    //later on:
    delete obj; //this will delete the object and emit destroyed() signal, which will remove it from the container

Log in to reply