我正在将C ++类注册为QML单例,并尝试从JS调用此单例的方法。我收到此错误消息:
TypeError:对象[object Object]的属性'readAll'不是函数
我的代码:
main.cpp (只需注册单身,由书籍完成):
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "fileio.h"
static QObject* fileIOSingletonTypeProvider(QQmlEngine *engine, QJSEngine *scriptEngine)
{
Q_UNUSED(engine)
Q_UNUSED(scriptEngine)
FileIO* example = new FileIO();
return example;
}
static void registerQmlTypes()
{
qmlRegisterSingletonType<FileIO>("FileIO", 1, 0, "FileIO", fileIOSingletonTypeProvider);
}
int main(int argc, char *argv[])
{
registerQmlTypes();
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
fileio.cpp :
#include "fileio.h"
FileIO::FileIO(QObject *parent) :
QObject(parent)
{
}
void FileIO::readAll()
{
}
fileio.h :
#ifndef FILEIO_H
#define FILEIO_H
#include <QObject>
class FileIO : public QObject
{
Q_OBJECT
public:
explicit FileIO(QObject *parent = 0);
Q_INVOKABLE void readAll();
};
#endif // FILEIO_H
main.qml :
import QtQuick 2.5
import QtQuick.Window 2.2
import "test.js" as Code
Window {
visible: true
Component.onCompleted: {
Code.func();
}
}
test.js :
.import FileIO 1.0 as FileIO
function func() {
FileIO.readAll();
}
答案 0 :(得分:1)
我找到了答案here。虽然它们指的是从QML导入而我指的是从JS导入,但解决方案是相同的,即:
将方法调用为FileIO.FileIO.readAll()
或从as FileIO
语句中删除.import
。
docs并未明显提及需要加倍FileIO
限定符,也未提及删除as FileIO
的可能性。{p>我reported a documentation bug to Qt。