Here is an example with a suggested TextFile class. First of all, we need a factory class, as already suggested:
// Factory class class Creator : public QObject { Q_OBJECT public: Q_INVOKABLE QObject* createObject(const QString& typeName, const QVariantMap& arguments); }; QObject* Creator::createObject(const QString& typeName, const QVariantMap& arguments) { if (typeName == "TextFile") { QString filePath = arguments.value("filePath").toString(); TextFile::OpenMode openMode = qvariant_cast<TextFile::OpenMode>(arguments.value("openMode", TextFile::ReadWrite)); QString codec = arguments.value("codec", "UTF-8").toString(); return new TextFile(qmlEngine(this), filePath, openMode, codec); } Q_ASSERT(false); return nullptr; }
Note. This class is a little more complicated than necessary. It is supposed to create several types. Now that we have the factory class, we need to tell QML / QJSEngine what to do if you call the new operator on the TextFile .
QJSValue creator = engine.newQObject(new Creator()); engine.globalObject().setProperty("_creator", creator); engine.evaluate("function TextFile(path, mode) { return _creator.createObject(\"TextFile\", { filePath: path, openMode: mode }); }");
Now we can customize our TextFile as desired, even with options:
var myFile = new TextFile("/path/to/file", TextFile.ReadWrite);
Credits go to the author for this answer .
Richard W
source share