I am trying to create a class in QT C++ that is a subclass of QWidget. However when I add it to my QML the program crashes. Before it chrashes "Constructed" is printed by QDebug. Any suggestions on how to fix this is wellcome.
MyClass.h
#ifndef MYCLASS_H
#define MYCLASS_H
#include <QObject>
#include <QWidget>
class MyClass : public QWidget
{
private:
Q_OBJECT
public:
MyClass(QWidget *parent = nullptr);
~MyClass();
};
#endif // MYCLASS_H
MyClass.cpp
#include "myclass.h"
#include <QDebug>
MyClass::MyClass(QWidget *parent): QWidget(parent)
{
qDebug() << "Constructed";
}
MyClass::~MyClass()
{
qDebug() << "Deconstructed";
}
main.cpp
#include <QApplication>
#include <QQmlApplicationEngine>
#include "myclass.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
qmlRegisterType <MyClass> ("MyImport", 1, 0, "MyObject");
QQmlApplicationEngine engine;
const QUrl url(u"qrc:/RectTest/main.qml"_qs);
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
main.qml
import QtQuick
import MyImport 1.0
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
MyObject {
id: obj
}
}
When I try the exact same code but instead of subclassing QWidget I subclass QObject it works fine.