Qt – Why can’t I set a QObject parent in a class of which QObject is only an indirect base

parent-childqobjectqt

I have a class BatchItem that inherits QObject, plus several classes that inherit from BatchItem:

#ifndef BATCHITEM_H
#define BATCHITEM_H

#include <QObject>

class BatchItem : public QObject
{
    Q_OBJECT
public:
    virtual void start() = 0;
    virtual void stop() = 0;

signals:
    /* ... some signals ... */

};

#endif // BATCHITEM_H

Example of a class that inherits from BatchItem:

#ifndef VIDEOBATCHITEM_H
#define VIDEOBATCHITEM_H

#include "batchprocessing/batchitem.h"

#include <QtCore/QObject>

class VideoBatchItem : public BatchItem
{
    Q_OBJECT
public:
    explicit VideoBatchItem(/* ... */, QObject *parent = 0);

    void start();
    void stop();

private:
    /* ... some private member variables ... */
};

#endif // VIDEOBATCHITEM_H

And this is the corresponding .cpp:

#include "videobatchitem.h"

VideoBatchItem::VideoBatchItem(/* ... */,
                               QObject *parent) :
    /* ... */,
    QObject(parent)
{
    /* ... */
}

/* ... */

But when I try to compile, I get the following error:

error: type ‘QObject’ is not a direct base of ‘VideoBatchItem’

Of course I see that this is correct, as QObject is only an indirect base of VideoBatchItem. But why is that a problem?
Isn't that also the case for e.g. QAbstractScrollArea, which inherits from QFrame, which in turn inherits from QWidget? They all take a QWidget as their parent, although QAbstractScrollArea only indirectly inherits from QWidget.
Unfortunately I couldn't find an answer to that in neither the documentation nor the .cpp files of the named widget classes.

Since I cannot pass a QObject parent, is there still a way to use Qt's parent-child system for the destruction of my derived batch items?

Best Answer

You can't call QObject base constructor. It doesn't matter about type of parent parameter but call of QObject(QObject * parent). You should call in this case BatchItem() without parameter and call setParent(parent) in constructor body, or overload BatchItem(QObject *) constructor.

Related Topic