My app uses both c++ and QML.
I\'ve defined several objects in C++ part to access SQL etc.
It looks like:
Here is an example with an imagined 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(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 bit more complicated than necessary. It is supposed to create multiple types. Now that we have the factory class in place, we need to tell the QML/QJSEngine what to do when calling the operator new for 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 instanciate our TextFile
as desired, even with parameters:
var myFile = new TextFile("/path/to/file", TextFile.ReadWrite);
Credits go to the author of this answer.