How to use C++ enum in Qt .js file?

Viewed 406

I need to create a file with several shared functions for multiple QML files.

I tried to create a .js file, but seems like C++ enums don't work here. FileSystemModel.TYPE_DIR is undefined here, while in QML it works fine after import FileSystemModel 1.0

.pragma library

.import FileSystemModel 1.0 as FileSystemModel

function fsItemTypeToImage(type) {
    console.log(FileSystemModel.TYPE_DIR)
    switch (type) {
    case FileSystemModel.TYPE_DIR:
        return "/img/dir.png"
    case FileSystemModel.TYPE_FILE:
        return "/img/file.png" 
    }
    return null
}

FileSystemModel.h:

class FileSystemModel : public QAbstractListModel {
    Q_OBJECT 
public:
    enum Roles { NameRole = Qt::UserRole + 1, SizeRole, DateRole, TypeRole };

    enum ItemType {
        TYPE_UNKNOWN = 0,
        TYPE_FILE,
        TYPE_DIR, 
    };
    Q_ENUM(ItemType)

registration in main.cpp:

qmlRegisterType<FileSystemModel>("FileSystemModel", 1, 0, "FileSystemModel");
1 Answers

When you call qmlRegisterType<FileSystemModel>("FileSystemModel", 1, 0, "FileSystemModel") you're registering a FileSystemModel QML module that contains a FileSystemModel type, so in your js when you write .import FileSystemModel 1.0 as FileSystemModel you're not actually importing your type but the QML module, that's why it's not working.

In your js file try changing FileSystemModel.TYPE_DIR to FileSystemModel.FileSystemModel.TYPE_DIR, that should do the trick.

Related