我正在创建注册的QML对象并将其存储在JavaScript数组中。我想把它们作为
QVariantList
方法参数为C++。下面是代码。然而,首先
Backend::sendItems
方法不打印大小。奇怪的是,它只会打印“ze”,而其他任何东西都不会像线程那样中途中断。我做错什么了?你也可以建议另一种方法来实现我想要的。
主.cpp
#include
#include
#include "backend.h"
#include "custom_class.h"
void register_Qml_types() {
qmlRegisterType("customApi", 1, 0, "Backend");
qmlRegisterType("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();
}
自定义\u类.h
#ifndef CUSTOM_H
#define CUSTOM_H
#include
#include
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
后端.h
#ifndef BACKEND_H
#define BACKEND_H
#include
#include
#include
#include
#include
#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* custom = new CustomClass(variant.value());
list_.append(custom);
std::cout << "converted" << std::endl;
}
}
}
private:
QList list_;
};
#endif
主.qml
import QtQuick.Window 2.11
import QtQuick.Controls 1.4
import QtQuick 2.11
import customApi 1.0
Window {
id: root
visible: true
width: 500
height: 500
property var items: []
Backend {
id: backend
}
Row {
Button {
text: "button1"
onClicked: {
var item1 = Qt.createQmlObject("import customApi 1.0; CustomClass { name: \"first-name\" }", root);
var item2 = Qt.createQmlObject("import customApi 1.0; CustomClass { name: \"second-name\" }", root);
items.push(item1);
items.push(item2);
}
}
Button {
text: "button2"
onClicked: {
backend.sendItems(items);
}
}
}
}