c++ - 如何访问 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>。
我该如何解决这个问题?
解决方案
您还需要注册您的类和向量以在 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
}
}
推荐阅读
- python - JSON 加载返回字符串
- c# - 设置 ErrorProvider 后无法单击任何位置
- verilog - 如何在 Verilog 运行时捕获键盘输入?
- azure - 如何使用 .Net Fluent SDK 设置 Azure 容器实例托管服务标识参数
- reactjs -
所以这段代码之前可以工作,但我不得不使用 npm 重新安装 react-stripe-elements,之后我开始收到错误。当我删除 . 该代码再次起作用。任何想法为什么?
- mysql - Select rows with duration calculation in the where clause
- react-native - FormData 是一个具有数组数组的对象
- postgresql - 何为 Google Cloud SQL Postgresql 实例建立连接 URL
- django - 如何将我的 sqlite 数据传递给 django 并制作图表?
- javascript - 从外部脚本访问 React DOM 元素