Important: Please read the Qt Code of Conduct -

Call a slot whenever a QObject is created

  • Hi,

    I'm not so great at C++, so maybe I'm taking the wrong approach here, but I'm trying to make a garbage collector in QT. I've got most of it worked out, but I want to connect all instances of the onCreate() signal to a slot on said garbage collector, including those that haven't yet been made.

    Is this possible? Is there a better approach?

    Below is my header, for context. The idea is that it's a singleton which will be called whenever a page is pop()'d off my main StackView (at which point it will clear all items associated with said view).

    #include <QObject>
    #include <QList>
    class garbageCollector : public QObject
        explicit garbageCollector(QObject *parent = nullptr);
        garbageCollector* instance;
        QList<QObject*>* objectList;
        garbageCollector* getInstance();
    public slots:
        void cleanup();
        void addItem();

  • Moderators

    Why do you need it? QML already contains a garbage collector. And all Q_OBJECT instances are additionally managed by parent-child hierarchy.

    If you need some additional collecting, I'd rather recommend using QSharedPointer - it will automatically remove the object when needed, without any garbage collection class.

  • Oh! Someone comes from Java development!

  • Lifetime Qt Champion

    There is already a system in place. as @sierdzio says

    So in most cases, ownership and clean up is handled by Qt.

  • I do indeed come from Java :p
    Or rather, python -> java -> now trying C++ and Rust.

    So just to clarify, I'm in a situation where I might have several long-lived objects created by views in my stackview (C++ objects, that is). Despite that, by popping a view off said stackview, all the objects created by that view will be cleaned up, even if they're C++ objects (still derived from QObject)?

Log in to reply