Solved Custom QObject derived class as a parent in constructor definition
-
I have a class constructor like this(expecting MainWindow as a parent and deriving from QObject)
class ActionManager : public QObject { Q_OBJECT public: ActionManager(MainWindow *mainWindow, Settings *settings);
ActionManager::ActionManager(MainWindow *mainWindow, Settings *settings) : QObject(mainWindow)
This however, shows an error:
error: C2664: 'QObject::QObject(const QObject &)': cannot convert argument 1 from 'MainWindow *' to 'QObject *'
Should I
reinterpret_cast
this or it's a wrong way of doing this? -
@enemyofthedawn It's the wrong way to do it. Typically your constructor would take either a
QWidget *
or aQObject *
depending on your needs. SinceQMainWindow
is derived from both of those you can go either way (I would usually do QWidget for a widget since it's derived from QObject).So here is how it would normally be:
// .h ActionManager(Settings *settings, QWidget *parent=nullptr); // .cpp ActionManager::ActionManager(Settings *settings, QWidget *parent) : QWidget(parent) { }
Optionally if you need
MainWindow*
somewhere else in your ActionManager class (i.e. you are going to store it) then you can go ahead and use a qobject_cast<QWidget*> to pass it to QWidget's constructor. -
@ambershark Thanks!