QObject的集合,例如ListModel

时间:2019-04-09 06:54:40

标签: qt qml qobject

我想创建一个ShortcutItem列表作为QObject,并将ShortcutItem添加到其中。例如,我有这个:

#include <QObject>

class ShortcutItem : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QString title READ title WRITE setTitle NOTIFY titleChanged)
    Q_PROPERTY(QString action READ action WRITE setAction NOTIFY actionChanged)
    Q_PROPERTY(QString icon READ icon WRITE setIcon NOTIFY iconChanged)
    Q_PROPERTY(QString font READ font WRITE setFont NOTIFY fontChanged)
    Q_PROPERTY(int size READ size WRITE setSize NOTIFY sizeChanged )
public:
    explicit ShortcutItem(QObject *parent = nullptr);
    QString title() const;
    QString action() const;
    QString icon() const;
    QString font() const;
    int size() const;
    void setTitle(const QString &title);
    void setAction(const QString &action);
    void setIcon(const QString &icon);
    void setFont(const QString &font);
    void setSize(const int &size);
private:
    QString _title;
    QString _action;
    QString _icon;
    QString _font;
    int _size;
signals:
    void titleChanged(QString title);
    void actionChanged(QString action);
    void iconChanged(QString icon);
    void fontChanged(QString font);
    void sizeChanged(int size);
public slots:
};

我可以在QML中这样使用:

U.Shortcut{
     title: "title"
     icon: "\uf015"
     font: "fontawesome"
     action: "open"
     size: 1
}

但是我想创建一个快捷方式列表(类似于其中包含ListElements的ListModel之类的东西):

U.Shortcuts {
    U.Shortcut {

    }
    U.Shortcut {

    }
}

如何创建它?

1 个答案:

答案 0 :(得分:3)

您必须创建一个QObject本身为Q_PROPERTYQQmlListProperty<ShortcutItem>DefaultProperty的{​​{1}}:

shortcutcollection.h

Q_PROPERTY

shortcutcollection.cpp

#ifndef SHORTCUTCOLLECTION_H
#define SHORTCUTCOLLECTION_H

#include <QObject>
#include <QVector>
#include <QQmlListProperty>
#include "shortcutitem.h"

class ShortcutCollection: public QObject
{
    Q_OBJECT
    Q_PROPERTY(QQmlListProperty<ShortcutItem> items READ items)
    Q_CLASSINFO("DefaultProperty", "items")
public:
    ShortcutCollection(QObject *parent=nullptr);
    QQmlListProperty<ShortcutItem> items();
    int itemsCount() const;
    ShortcutItem *item(int) const;
private:
    QList<ShortcutItem*> m_items;
};

#endif // SHORTCUTCOLLECTION_H

然后您注册它:

#include "shortcutcollection.h"

ShortcutCollection::ShortcutCollection(QObject *parent):
    QObject(parent)
{
}

QQmlListProperty<ShortcutItem> ShortcutCollection::items()
{
    return QQmlListProperty<ShortcutItem>(this, m_items);
}

int ShortcutCollection::itemsCount() const
{
    return m_items.count();
}

ShortcutItem *ShortcutCollection::item(int index) const
{
    return m_items.at(index);
}

*。qml

qmlRegisterType<ShortcutCollection>("FooModule", 1,0, "Shortcuts");
qmlRegisterType<ShortcutItem>("FooModule", 1,0, "Shortcut");

找到完整的示例here