0

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.

drescherjm
  • 10,365
  • 5
  • 44
  • 64
  • Why do you want to user a QWidget in QML? Have a look here https://stackoverflow.com/questions/13014415/qt5-embed-qwidget-object-in-qml – iam_peter Jan 18 '23 at 15:45
  • 3
    What is your use case? If you want to draw something in QML via `QPainter` you should derive from https://doc.qt.io/qt-6/qquickpainteditem.html – iam_peter Jan 18 '23 at 15:46
  • I wonder why you decided that it should work at all. you're trying to combine two completely different technologies. As said above, if you want to use a custom item in `QML` you have to derive from [QQuickItem](https://doc.qt.io/qt-6/qquickitem.html) / [QQuickPaintedItem](https://doc.qt.io/qt-6/qquickpainteditem.html). – folibis Jan 19 '23 at 08:47

0 Answers0