首页 > 解决方案 > 如何访问 std::vector在qml?

问题描述

c++的TestMethod在qml中调用。

C++

class Test : public QObject {

    Q_OBJECT
public:

    enum TestEnum
    {
       RED = 0,
       BLACK = 0x1,
       YELLOW = 0x2,
       PINK = 0x4,
    };

    Q_ENUM(TestEnum)

    Q_INVOKABLE std::vector<TestEnum> testMethod();
};

Q_DECLARE_METATYPE(std::vector<Test::TestEnum>)

qml

    Test{
        id: test
    }


onClicked: {
  var result = test.testMethod();
}

是返回错误。
qml:384:错误:未知方法返回类型:std::vector<Test::TestEnum>。

我该如何解决这个问题?

标签: c++qtqml

解决方案


您还需要注册您的类和向量以在 QML 中使用它们

class Test : public QObject {

    Q_OBJECT
public:

    enum TestEnum
    {
       RED = 0,
       BLACK = 0x1,
       YELLOW = 0x2,
       PINK = 0x4,
    };

    Q_ENUM(TestEnum)

    Q_INVOKABLE std::vector<Test::TestEnum> testMethod();
};

Q_DECLARE_METATYPE(std::vector<Test::TestEnum>)

主要:

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    qmlRegisterType<Test>("org.mytest.test", 1, 0, "Test");
    qRegisterMetaType<std::vector<Test::TestEnum>>();
    ....

在 qml 中:

import org.mytest.test 1.0

Page {
    width: 600
    height: 400

    Test {
        id: test
    }

    title: qsTr("Page 1")

    Label {
        text: test.testMethod() == Test.RED?"RED":"not red";
        anchors.centerIn: parent
    }
}

推荐阅读