【问题标题】:Import Qt function to QML file?将 Qt 函数导入 QML 文件?
【发布时间】:2020-01-13 15:37:55
【问题描述】:

您如何在 Qt 5.5 的 QML 文件中调用例如 QFile::exists(path)

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 函数的示例,但是如何在 QML 中调用内置 Qt 函数?

【问题讨论】:

    标签: qt qml qfile qt5.5


    【解决方案1】:

    您不能直接导入 C++ 函数,在这些情况下,方法是创建一个通过 Q_INVOKABLE 公开该方法的 QObject:

    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);
    }
    

    ma​​in.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'
    }
    // ...

    【讨论】:

      猜你喜欢
      • 2015-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-28
      • 2021-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多