【qml】如何在将c++中的Qlist 注册到qml中并使用

因为经常需要将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 guests READ guests)
public:
BirthdayParty(QObject *parent = 0);
~BirthdayParty();
QQmlListProperty 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(“Birthday”,1,0,“Birthday”);
qmlRegisterType(“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;
        }
    }
}

}

原文:https://blog.csdn.net/wei375653972/article/details/77986870

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

草丛中的蝈蝈

您的鼓励是我最大的动力....

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值