首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >QML/Javascript中的QVector

QML/Javascript中的QVector
EN

Stack Overflow用户
提问于 2012-07-30 20:10:28
回答 3查看 4.9K关注 0票数 4

如何在QML/Javascript中使用QVector?示例:

C++:

我在QML中使用的自定义类。该类包含返回已注册ElementTypeQVector的函数

代码语言:javascript
复制
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类型。

代码语言:javascript
复制
//.......
function(){
    var elements = custom.getElements()
    elements[0].property   //?
}
EN

回答 3

Stack Overflow用户

发布于 2012-07-30 21:57:16

QML可访问的列表属性需要用QDeclarativeListProperty来构造。这适用于所有列表形状的对象,也适用于向量。请听This part of the Qt documentation的详细报道。

票数 1
EN

Stack Overflow用户

发布于 2012-08-01 23:01:24

在您的示例中,您只需要从Q_INVOKABLE函数返回QObject*QList。请注意,以这种方式返回的所有对象都将拥有JavaScript所有权,并且在JavaScript函数返回时将被垃圾回收。若要防止此行为,请在将对象推入QList集合之前使用setObjectOwnership。有关在QML中使用集合的更多信息,请参见QML Data Models

票数 0
EN

Stack Overflow用户

发布于 2020-03-31 00:40:49

我回答这个问题已经晚了几年了,但是,现在开始吧。这是一个要解决的简单问题。只需在C++代码中使用Qt QVariantList类型,而不是QVector。Qt的QVariantList本质上是一个包含QVariant元素的QVector。一旦你知道自己在做什么,QVariants就可以接近任何东西。此外,QML会自动将C++ QVariant转换为QML等效项。因此,如果您在main.cpp中执行此操作:

代码语言:javascript
复制
#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中执行以下操作:

代码语言:javascript
复制
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()

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11721268

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档