Import Qt function to QML file?

650 Views Asked by At

How do you call for example QFile::exists(path) inside a QML file in 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'
    }

}

I've seen some examples on how to import your custom Qt functions, but how do you call built-in Qt functions in QML?

1

There are 1 best solutions below

0
eyllanesc On

You cannot directly import a C ++ function, in these cases the approach is to create a QObject that exposes the method through a 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

backend.cpp

#include "backend.h"

#include <QFile>

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

main.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 backend.exists(source)
        ? preprocessor.getFilePath(source)
        : theme.example + 'placeholder.png'
}
// ...