【发布时间】:2019-08-03 06:24:55
【问题描述】:
我想从 QML 调用 C++ 方法,并将参数传递给它。据我了解,我应该用宏Q_OBJECT 标记类,并用Q_INVOKABLE 标记所需的公共功能。
虽然我做到了,但我仍然遇到运行时错误
qrc:/main.qml:42: TypeError: Property 'addFile' of object QObject(0xf20e90) is not a function
这是我的.hpp 和.cpp 类文件:
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 }
我想要的是调用函数addFile() 来构造file_manager 成员然后它需要对新文件进行排序。
为什么会发生这个错误?我做错了什么?
【问题讨论】: