gpt4 book ai didi

c++ - Q_INVOKABLE 不向 QML 公开方法

转载 作者:行者123 更新时间:2023-11-28 01:19:16 25 4
gpt4 key购买 nike

我想从 QML 调用 C++ 方法,将参数传递给它。据我所知,我应该用宏 Q_OBJECT 标记类,用 Q_INVOKABLE 标记所需的公共(public)函数。

虽然我这样做了,但我仍然遇到运行时错误

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成员,然后它需要对新文件进行排序。

为什么会出现这个错误?我做错了什么?

最佳答案

根据docs , FileDialogfileUrl 属性返回 url等同于 C++ 类型的类型 QUrl不是 QString。所以你可以:

  • 编辑您的 C++ 方法以获取两个 QUrl

  • 或者在您的 QML 中传递 .fileUrl.toString()

关于c++ - Q_INVOKABLE 不向 QML 公开方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57335979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com