Inheritance with QObject (parent?)
-
Hello,
I would like to know what it necessary to proper inherit from QObject.
I have two example classes. Class A which is my base class derived from QObject and Class B which is derived from Class A.I already found out that I am only allowed to inherit from QObject with the first class. But how do I need to modify the constructors that the parent system is working?
Here is a minimal not working example which tells me that the constructor implementation of B has QObject not as an element and not as Base.
What do I need to do?
Thank you very much!
a.h:
#ifndef A_H #define A_H #include <QObject> class A : public QObject { Q_OBJECT public: explicit A(QObject *parent = nullptr); }; #endif // A_H
a.cpp:
#include "a.h" A::A(QObject *parent) : QObject(parent) { }
b.h:
#ifndef B_H #define B_H #include <QObject> #include "a.h" class B : protected A { Q_OBJECT public: explicit B(QObject *parent = nullptr); }; #endif // B_H
b.cpp:
#include "b.h" B::B(QObject *parent): QObject(parent) { }
main:
#include <QCoreApplication> #include <b.h> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); B myclass; return a.exec(); }
-
Hi,
@robro said in Inheritance with QObject (parent?):
B::B(QObject *parent): QObject(parent)
This is wrong, your B object is of A type, therefore:
B::B(QObject *parent): A(parent)
-
Thank you very much :-)
It worked, but now I got another error.
In reality I use the class B togehter with QML.So I use the following lines:
#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include "b.h" int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); qmlRegisterType<B>("com.br.classes", 1, 0, "b"); B b QQmlApplicationEngine engine; engine.rootContext()->setContextProperty("b", &b); //Throws the error engine.load(QUrl(QLatin1String("qrc:/main.qml"))); return app.exec();
This leads to the following error: "Conversion from B* to QObject* is already existing but it cannot be accesed"
How can I solve that?
-
@robro said in Inheritance with QObject (parent?):
This leads to the following error: "Conversion from B* to QObject* is already existing but it cannot be accesed"
How can I solve that?you declared the base class protected:
class B : protected A
And therefore can't be accessed from outside the class, I would change that.