因为经常需要将c++中数据传递到qml中使用,而c++中数据多是以Qlist
class Person : public QObject
{
Q_OBJECT
Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)
Q_PROPERTY(int shoeSize READ shoeSize WRITE setShoeSize NOTIFY shoeSizeChanged)
public:
Person(QObject *parent = 0);
~Person();
QString name()const;
void setName(const QString name);
int shoeSize()const;
void setShoeSize(const int shoeSize);
signals:
void nameChanged();
void shoeSizeChanged();
private:
QString m_name;
int m_shoeSize;
};
class BirthdayParty :public QObject
{
Q_OBJECT
Q_PROPERTY(QQmlListProperty<Person> guests READ guests)
public:
BirthdayParty(QObject *parent = 0);
~BirthdayParty();
QQmlListProperty<Person> guests();
Q_INVOKABLE void appendData();
Q_INVOKABLE int guestsCount()const;
private:
QList<Person*> m_guests;//宾客
};
2、在main文件中注册存储对象和数据对象
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
qmlRegisterType<BirthdayParty>("Birthday",1,0,"Birthday");
qmlRegisterType<Person>("Person",1,0,"Person");
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
3、在qml中的使用方式为
import QtQuick 2.6
import QtQuick.Window 2.2
import Birthday 1.0
import Person 1.0
Window {
id: root;
visible: true
width: 640
height: 480
title: qsTr("Hello World")
property int count: 0;
MouseArea {
anchors.fill: parent
onClicked: {
count = 0;
if(birthday.guests.length > 0)//这里主要测试是否可以修改该数组中的数据
{
console.debug("数据变了吗 name = ",birthday.guests[0].name,",大小 = ",birthday.guests[0].shoeSize);
}
birthday.appendData();
count = birthday.guestsCount();
}
}
Rectangle
{
width: 300;
height: 300;
color: "lightblue";
anchors.centerIn: parent;
ListView
{
id: list;
anchors.fill: parent;
model: root.count;
delegate: com;
}
}
Birthday
{
id:birthday;
}
Component
{
id:com;
Column
{
id:col;
width: list.width;
spacing: 10;
property Person person: null;
Component.onCompleted:
{
person = birthday.guests[index];
person.name = "李四";
person.shoeSize = 100;
nameTxt.text = person.name;
shoeSizeTxt.text = person.shoeSize;
}
Text
{
id:nameTxt;
}
Text
{
id:shoeSizeTxt;
}
}
}
}
4、至此,可以方便的使用数据了,ok~