c++ 传结构体到qml
时间: 2023-09-01 09:11:28 浏览: 230
在Qt中,可以通过将结构体作为属性添加到QObject派生类中,然后将该对象传递到QML中。
例如,假设我们有以下结构体:
```cpp
struct Person {
QString name;
int age;
};
```
我们可以创建一个QObject派生类,将Person结构体作为其属性之一:
```cpp
class PersonObject : public QObject
{
Q_OBJECT
Q_PROPERTY(QString name READ getName WRITE setName NOTIFY nameChanged)
Q_PROPERTY(int age READ getAge WRITE setAge NOTIFY ageChanged)
public:
explicit PersonObject(QObject *parent = nullptr) : QObject(parent) {}
QString getName() const { return m_person.name; }
void setName(const QString &name) {
if (m_person.name != name) {
m_person.name = name;
emit nameChanged();
}
}
int getAge() const { return m_person.age; }
void setAge(int age) {
if (m_person.age != age) {
m_person.age = age;
emit ageChanged();
}
}
Q_INVOKABLE QVariantMap toVariantMap() const {
return QVariantMap{{"name", m_person.name}, {"age", m_person.age}};
}
signals:
void nameChanged();
void ageChanged();
private:
Person m_person;
};
```
然后,在main函数中,我们可以创建一个PersonObject对象,并将其添加到QML Engine中:
```cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "personobject.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
// Create a PersonObject and add it to the QML engine
PersonObject person;
person.setName("John");
person.setAge(30);
engine.rootContext()->setContextProperty("person", &person);
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
```
最后,在QML中,我们可以访问PersonObject对象的属性和方法:
```qml
import QtQuick 2.14
import QtQuick.Controls 2.14
ApplicationWindow {
visible: true
width: 640
height: 480
title: "Person Example"
Column {
spacing: 10
Label {
text: "Name:"
}
TextField {
text: person.name
onTextChanged: person.name = text
}
Label {
text: "Age:"
}
TextField {
text: person.age.toString()
onTextChanged: person.age = parseInt(text)
}
Button {
text: "Print Person"
onClicked: console.log(person.toVariantMap())
}
}
}
```
这里,我们将PersonObject对象命名为“person”,并使用其属性和方法来更新和显示界面中的数据。我们还可以调用toVariantMap方法,将Person对象转换为QVariantMap对象,并在QML中打印出来。
阅读全文