C++ Q_INVOKABLE不向QML公开方法
我想从QML调用C++方法,将参数传递给它。据我所知,我应该用宏C++ Q_INVOKABLE不向QML公开方法,c++,qt,qml,qt5,C++,Qt,Qml,Qt5,我想从QML调用C++方法,将参数传递给它。据我所知,我应该用宏Q\u对象标记类,用Q\u可调用标记所需的公共函数 虽然我做到了,但我仍然遇到运行时错误 qrc:/main.qml:42: TypeError: Property 'addFile' of object QObject(0xf20e90) is not a function 这是我的.hpp和.cpp类文件: lib_controller.hpp main.cpp 我想要的是调用函数addFile()来构造文件管理器成员,然后它
Q\u对象
标记类,用Q\u可调用
标记所需的公共函数
虽然我做到了,但我仍然遇到运行时错误
qrc:/main.qml:42: TypeError: Property 'addFile' of object QObject(0xf20e90) is not a function
这是我的.hpp
和.cpp
类文件:
lib_controller.hpp
main.cpp
我想要的是调用函数addFile()
来构造文件管理器
成员,然后它需要对新文件进行排序
为什么会发生这种错误?我做错了什么?我认为您在main.qml中缺少一个组件实例化
LibController{id:LibController}
。我认为您缺少一个组件实例化LibController{id:LibController}
在main.qml中。在libcontroller构造函数中删除私有成员而不是初始化它。在libcontroller构造函数中删除私有成员而不是初始化它。根据,<代码>文件> <代码>属性>文件IDEAL < /COD>返回一个等价于C++类型而不是qStand的类型。因此,您可以:
-
<> >编辑你的C++方法,取两个代码> qURL < /代码> S.< /P>
- 或者在QML过程中
.fileUrl.toString()
根据
-
<> >编辑你的C++方法,取两个代码> qURL < /代码> S.< /P>
- 或者在QML过程中
.fileUrl.toString()
#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);
...
};
#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());
}
...
#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();
}
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 }