0
votes

I want to call C++ method from QML, passing parameters to it. As i understood, i should mark class with macro Q_OBJECT and desired public functions with Q_INVOKABLE.

Although i did it, i still get in runtime error

qrc:/main.qml:42: TypeError: Property 'addFile' of object QObject(0xf20e90) is not a function

Here is my .hpp and .cpp files of the class:

lib_controller.hpp

#include <QObject>
#include <QString>
...

class LibController : public QObject{
    Q_OBJECT
    Q_PROPERTY(decltype(getProgress) progress READ getProgress NOTIFY ProgressChanged)
    public:
        ...

        Q_INVOKABLE
        void addFile(QString from_name, QString to_name);
        ...
};

lib_controller.cpp

#include "lib_controller.hpp"
...
void LibController::addFile(QString from_name, QString to_name){
    file_manager = new FileManager(from_name.toUtf8().constData(),
                                   to_name.toUtf8().constData());
}

...

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlComponent>

#include "lib_controller.hpp"

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    // Registration of custom type
    qmlRegisterType<LibController>("com.sort.controller", 0, 1, "LibController");

    ...

    return app.exec();
}

main.qml

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.0
import QtQuick.Dialogs 1.2
import com.sort.controller 0.1

...

     FileDialog {
        id: fileDialog_for_load
        title: "Load file"
        onAccepted: {
           fileDialog_for_save.open()
        }
    }
    FileDialog {
        id: fileDialog_for_save
        title: "Save file"
        onAccepted: {
            var loadPath = fileDialog_for_load.fileUrl.toString();
            loadPath = loadPath.replace(/^(file:\/{2})/,"");

            var savePath = fileDialog_for_save.fileUrl.toString();
            savePath = savePath.replace(/^(file:\/{2})/,"");

            console.log("Save Path:" + savePath)
            libController.addFile(loadPath, savePath)
        }
    }

LibController { id: libController }

What i want, is to call function addFile() to construct file_manager member then it needs to sort new file.

Why is this error happenning? What am I doing wrong?

3

3 Answers

1
votes

According to the docs, fileUrl property of FileDialog returns a url type which is equivalent to C++ type QUrl not QString. So you can either:

  • Edit your C++ method to take two QUrls.

  • Or in your QML pass .fileUrl.toString().

1
votes

in your libcontroller constructor you delete your private member instead of initializing it.

0
votes

I think you are missing a component instancing LibController { id:libController } in your main.qml.