如何在QML/Javascript中使用QVector?示例:
C++:
我在QML中使用的自定义类。该类包含返回已注册ElementType的QVector的函数
class CustomType : public QObject
{
Q_OBJECT
public:
Q_INVOKABLE QVector<ElementType*> getElements();
//.....
}
//.........
qmlRegisterType<CustomType>("CustomComponents", 1, 0, "CustomType");
qmlRegisterType<ElementType>("CustomComponents", 1, 0, "ElementType");
qRegisterMetaType<ElementType*>("ElementType*");QML:
QML代码接收CustomType类的实例(自定义),并尝试获取元素的QVector<ElementType*>并读取其属性。但是QML不能识别QVector类型。
//.......
function(){
var elements = custom.getElements()
elements[0].property //?
}发布于 2012-07-30 21:57:16
QML可访问的列表属性需要用QDeclarativeListProperty来构造。这适用于所有列表形状的对象,也适用于向量。请听This part of the Qt documentation的详细报道。
发布于 2012-08-01 23:01:24
在您的示例中,您只需要从Q_INVOKABLE函数返回QObject*的QList。请注意,以这种方式返回的所有对象都将拥有JavaScript所有权,并且在JavaScript函数返回时将被垃圾回收。若要防止此行为,请在将对象推入QList集合之前使用setObjectOwnership。有关在QML中使用集合的更多信息,请参见QML Data Models
发布于 2020-03-31 00:40:49
我回答这个问题已经晚了几年了,但是,现在开始吧。这是一个要解决的简单问题。只需在C++代码中使用Qt QVariantList类型,而不是QVector。Qt的QVariantList本质上是一个包含QVariant元素的QVector。一旦你知道自己在做什么,QVariants就可以接近任何东西。此外,QML会自动将C++ QVariant转换为QML等效项。因此,如果您在main.cpp中执行此操作:
#include <QCoreApplication>
#include <QGuiApplication>
#include <QQmlContext>
#include <QQuickView>
int main(int argc, char *argv[])
{
// Prepare to enter the QML GUI world
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
// Create a QVariantList to be used instead of a QVector
QVariantList dataList;
dataList << "Item 1";
dataList << 2;
dataList << 3.3;
// Create QML UI
QQuickView view;
// make your QVariantList visible to QML
QQmlContext *ctxt = view.rootContext();
ctxt->setContextProperty("myModel",
QVariant::fromValue(dataList));
// show QML UI
view.setSource(QUrl("qrc:/main.qml"));
view.show();
return 1;
} // main()然后,您可以在您的main.qml中执行以下操作:
import QtQuick 2.12
import QtQuick.Window 2.12
Item
{
// Print contents of C++ QVariantList to console
function printMeBruh()
{
console.log("modelData contains:")
console.log("-------------------")
for (var i = 0; i < 3; i++)
{
console.log(myModel[i])
}
}
Component.onCompleted: printMeBruh()
}https://stackoverflow.com/questions/11721268
复制相似问题