Импортировать функцию Qt в файл QML? - PullRequest
1 голос
/ 13 января 2020

Как вы вызываете, например, QFile::exists(path) внутри файла QML в Qt 5.5?

MyFile.qml

import QtQuick 2.5

// These are some various things I've tried, with the error message they 
// give related to the row where I call QFile::exists()

#include <QFile>      // Expected token `{'
import QtQml 2.5      // Expected token `;'
import io.qt          // Expected token `;'
import io.qt.QFile    // Expected token `;'

Item {
    id: root
    property string imageSource

    Image {
        id: test
        source: fileOrFallback(root.imageSource)
    }

    function fileOrFallback (source) {
        return QFile::exists(source)
            ? preprocessor.getFilePath(source)
            : theme.example + 'placeholder.png'
    }

}

Я видел несколько примеров о том, как импортировать ваши пользовательские функции Qt, но как вы вызываете встроенные функции Qt в QML?

1 Ответ

3 голосов
/ 13 января 2020

Вы не можете напрямую импортировать функцию C ++, в этих случаях подход заключается в создании объекта QObject, который предоставляет метод через Q_INVOKABLE:

backend.h

#ifndef BACKEND_H
#define BACKEND_H

#include <QObject>

class Backend : public QObject
{
    Q_OBJECT
public:
    using QObject::QObject;
    Q_INVOKABLE bool exists(const QString &fileName);

};

#endif // BACKEND_H

бэкэнд. cpp

#include "backend.h"

#include <QFile>

bool Backend::exists(const QString &fileName){
    return QFile::exists(fileName);
}

основной. cpp

#include "backend.h"

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    Backend backend;
    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("backend", &backend);
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    return app.exec();
}

* .qml

// ...
function fileOrFallback (source) {
    return <b>backend.exists(source)</b>
        ? preprocessor.getFilePath(source)
        : theme.example + 'placeholder.png'
}
// ...
...