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).

    #ifndef GARBAGECOLLECTOR_H
    #define GARBAGECOLLECTOR_H
    
    #include <QObject>
    #include <QList>
    
    class garbageCollector : public QObject
    {
        Q_OBJECT
    private:
        explicit garbageCollector(QObject *parent = nullptr);
        garbageCollector* instance;
        QList<QObject*>* objectList;
    
    public:
        garbageCollector* getInstance();
    
    signals:
    
    public slots:
        void cleanup();
        void addItem();
    };
    
    #endif // GARBAGECOLLECTOR_H
    

  • 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

    Hi
    There is already a system in place. as @sierdzio says
    https://doc.qt.io/qt-5/objecttrees.html

    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)?


 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.