Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

qt

qt-quick

qml

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");
like image 344
Alex P. Avatar asked Oct 21 '25 05:10

Alex P.


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.

like image 183
Silvano Cerza Avatar answered Oct 22 '25 17:10

Silvano Cerza