c++ - 如何将枚举的 Qlist 从 C++ 公开到 QML?

标签 c++ qt enums qml qqmllistproperty

我有一个 C++ 错误列表,我想将它公开给 QML。枚举使用 Q_ENUM 注册,属性使用 Q_PROPERTY 注册。您可以在下面查看详细信息:

class MyClass : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QList<LoginErrorCode> loginErrors READ getLoginErrors NOTIFY loginErrorsChanged)
    ...

public:
    ...
    enum LoginErrorCode {
        UsernameOrPassIsNotValid
    };
    Q_ENUM(LoginErrorCode)
    enum GetUserInfoErrorCode {
        GetUserInfoError_TokenIsNotValid
    };
    Q_ENUM(GetUserInfoErrorCode)

    QList<LoginErrorCode> getLoginErrors() const;
    ...
signals:
    ...
    void loginFailed();
    ...
    void loginErrorsChanged();
    ...
private:
    QList<LoginErrorCode> m_loginErrors;
};

我在 main.cpp 中使用以下行注册了 MyClass:

qmlRegisterType<MyClass>("ir.MyComponents", 1, 0, "MyClass");

在 QML 中我使用了这个类:

MyClass {
    id: myClass
    Component.onCompleted: login("irani", "iravani");
    onLoginFailed: console.log("Login failed with errors count: "+loginErrors.length);
}

输出为:

QMetaProperty::read: Unable to handle unregistered datatype 'QList<LoginErrorCode>' for property 'MyClass::loginErrors'
qrc:/main.qml:46: TypeError: Cannot read property 'length' of undefined

有什么问题?!
如何将我的枚举列表公开给 qml?

对于 QQmlListProperty 文档说:

Note: QQmlListProperty can only be used for lists of QObject-derived object pointers.

最佳答案

如你所见from the documentation , QList仅支持一组有限的类型( intqreal 等)。有关详细信息,请参阅JavaScript 数组的序列类型部分。
你应该使用 QVariantList为了您的目的。它直接映射到 JavaScript Array .有关详细信息,请参阅QVariantList 和 QVariantMap 到 JavaScript 数组和对象部分。
另请注意明确提及:

Other sequence types are not supported transparently, and instead an instance of any other sequence type will be passed between QML and C++ as an opaque QVariantList.

当然,你仍然可以使用 QList<LoginErrorCode>在内部,但转换为 QVariantList每当您想在 QML 环境中返回它时,它都是必需的。

关于c++ - 如何将枚举的 Qlist 从 C++ 公开到 QML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42314799/

相关文章:

c++ - 智能指针/编码模式的名称

c++ - 无法将 QGraphicsView 坐标映射到 QGraphicsScene

Qt moc.exe无法生成* .moc文件

来自字符串输入的 C++ 枚举值

mysql - 数据模型: Having separate table for a field vs having it as a column in the main table

c++ - 规范运算符重载?

c++ - glGenerateMipmap 中的 GL_INVALID_OPERATION(不完整的立方体贴图)

c++ - 图可排序性 C++

unit-testing - Qt、单元测试和模拟对象

c# - WCF 枚举,如果我不将成员标记为 EnumMember 会怎样?