无法将动态创建的对象数组从qml发送到c ++作为方法参数

时间:2018-08-08 13:27:41

标签: c++ qt qml qt5

我正在创建已注册的qml对象,并将其存储在javascript数组中。我想将它们作为B方法参数发送给c ++。下面是代码。但是,QVariantList方法的第一个指令不打印尺寸。奇怪的是,它只打印“ ze”,其他都没有,就像线程被中断了一样。我究竟做错了什么?您也可以建议实现我想要的另一种方式。

main.cpp

Backend::sendItems

custom_class.h

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "backend.h"
#include "custom_class.h"

void register_Qml_types() {
  qmlRegisterType<Backend>("customApi", 1, 0, "Backend");
  qmlRegisterType<CustomClass>("customApi", 1, 0, "CustomClass");
}

int main(int argc, char **argv)
{
  QGuiApplication app(argc, argv);

  register_Qml_types();
  QQmlApplicationEngine engine;
  engine.load(QUrl("qrc:/main.qml"));

  return app.exec();
}

后端。h

#ifndef CUSTOM_H
#define CUSTOM_H

#include <QString>
#include <QObject>

class CustomClass : public QObject
{
  Q_OBJECT
  Q_PROPERTY(QString name READ name WRITE setName)

public:
  CustomClass(QObject* parent = 0)
    : QObject(parent)
  {}

  CustomClass(QString name) {
    name_ = name;
  }

  CustomClass(const CustomClass& item) {
    name_ = item.name_;
  }

  QString name() const {
    return name_;
  }

  void setName(QString name) {
    name_ = name;
  }

private:
  QString name_;
};

Q_DECLARE_METATYPE(CustomClass)

#endif

main.qml

#ifndef BACKEND_H
#define BACKEND_H

#include <iostream>
#include <typeinfo>
#include <QObject>
#include <QList>
#include <QVariant>
#include "custom_class.h"

class Backend : public QObject
{
  Q_OBJECT

public:
  Backend(QObject* parent = nullptr)
    : QObject(parent)
  {}

  Q_INVOKABLE void sendItems(const QVariantList& list) {
    std::cout << "size " + list.size() << std::endl;
    list_.clear();
    for(const QVariant& variant : list) {
      if(variant.canConvert<CustomClass>()) {
        CustomClass* custom = new CustomClass(variant.value<CustomClass>());
        list_.append(custom);
        std::cout << "converted" << std::endl;
      }
    }

  }

private:
    QList<CustomClass*> list_;
};

#endif

1 个答案:

答案 0 :(得分:0)

我看到你正在打印:

std::cout << "size " + list.size() << std::endl;

但是必须将其分开,因为它可能会将size()视为char。

std::cout << "size "<< list.size() << std::endl;

另一方面,QObject被存储为指针,即:CustomClass *,并且您还创建了其他CustomClass *而不是QML中的那些{我假设您想视图中有相同的项目)

下一个解决方案是

Q_INVOKABLE void sendItems(const QVariantList& list) {
    std::cout << "size "<< list.size() << std::endl;
    list_.clear();
    for(const QVariant& variant : list) {
        if(variant.canConvert<CustomClass *>()) {
            CustomClass* custom = variant.value<CustomClass*>();
            list_.append(custom);
            std::cout << "converted " << custom->name().toStdString() << std::endl;
        }
    }
}

您可以在以下link

中找到测试项目