1

Is it possible to declare a C++ class to QJSEngine (the engine for QML) so objects of that class can be instantiated from javascript?

The only solution I can come up so far is to create a factory method with Q_INVOKABLE that returns an object using QJSEngine ::newQObject()

Thanks!

Jay
  • 13,803
  • 4
  • 42
  • 69

1 Answers1

0

How about using Qt.createQmlObject()? The problem is you need to supply a parent item when creating an object. The other being unable to call non-default constructor.

// C++ class (from http://doc.qt.io/qt-5/qtqml-cppintegration-definetypes.html)
class Message : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QString author READ author WRITE setAuthor NOTIFY authorChanged)
    Q_PROPERTY(QDateTime creationDate READ creationDate WRITE setCreationDate NOTIFY creationDateChanged)
public:
    // ...
};

// Register the C++ class to be used by QML
qmlRegisterType<Message>("com.mycompany.messaging", 1, 0, "Message");

// Create C++ object from QML JavaScript
var msg = Qt.createQmlObject('import com.mycompany.messaging 1.0; Message {}', parentItem);
msg.author = "Kate";
fxam
  • 3,874
  • 1
  • 22
  • 32
  • I thought about doing that. The dynamic creation of a runtime qml object isn't simple and my intended use is from run time users scripts in javascript. It's a lot of hoops to jump through. So far it seems much easier and more efficient to create a Q_INVOKABLE method that does the work. Good thought though – Jay Feb 25 '15 at 13:23