How to create and use C++ objects in QML Javascript

前端 未结 4 582
北海茫月
北海茫月 2021-02-05 21:43

My app uses both c++ and QML.

I\'ve defined several objects in C++ part to access SQL etc.

It looks like:



        
4条回答
  •  被撕碎了的回忆
    2021-02-05 22:25

    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.

提交回复
热议问题