我如何与扩展的 QQuickItem 中的模型交互?

How do I interact with a model in an extended QQuickItem?

在 Qt 文档中有很多关于处理模型和视图的好资源,例如:http://doc.qt.io/qt-5/model-view-programming.html, but I can't seem to find any that link to dealing with models in QtQuick. There are some basic chapters on extending qml with c++, like in http://doc.qt.io/qt-5/qtqml-tutorials-extending-qml-example.html, and on using models: http://doc-snapshots.qt.io/qt5-5.11/qtquick-modelviewsdata-modelview.html,但我找不到在扩展 qml 中使用实际模型的方法。

目前我有这个型号:

class LayoutModel : public QAbstractItemModel {
  Q_OBJECT

public:
  explicit LayoutModel(const QString &data, QObject *parent = 0);
  ~LayoutModel();

  QVariant data(const QModelIndex &index, int role) const override;
  Qt::ItemFlags flags(const QModelIndex &index) const override;
  QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
  QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override;
  QModelIndex parent(const QModelIndex &index) const override;
  int rowCount(const QModelIndex &parent = QModelIndex()) const override;
  int columnCount(const QModelIndex &parent = QModelIndex()) const override;

private:
  void setupModelData(const QStringList &lines, LayoutItem *parent);

  LayoutItem *rootItem;
};

我正在尝试从这个视图访问它 class:

class Layout : public QQuickItem
{
    Q_OBJECT
    Q_PROPERTY(LayoutModel model READ model WRITE setModel NOTIFY modelChanged)

   private:
    LayoutModel & m_model;

   public:
    explicit Layout(QQuickItem * parent = nullptr);

    LayoutModel & model() const;
    void setModel(const LayoutModel & model);

    void itemChange(QQuickItem::ItemChange change, const QQuickItem::ItemChangeData & value) override;
    void geometryChanged(const QRectF & newGeometry, const QRectF & oldGeometry) override;

   signals:
    void modelChanged();
};

但我找不到实际使用该模型的方法。我什至无法正确设置模型的读写,因为 QAbstractItemModels(和一般 Qt 中的模型)删除了它们的复制构造函数以强制实体奇点。这是我当前损坏的实现:

Layout::Layout(QQuickItem * parent) : QQuickItem(parent) {}

LayoutList & Layout::model() const
{
    return m_model;
}

void Layout::setModel(const LayoutList & model)
{
    if (m_model == model)
        return;

    m_model = model;
    emit modelChanged();
}

那么,我怎样才能将这个扩展的 qml class 与我的 LayoutModel 一起使用?

QObject没有拷贝构造函数,所以必须使用指针:

*.h

class Layout : public QQuickItem
{
    Q_OBJECT
    Q_PROPERTY(LayoutModel *model READ model WRITE setModel NOTIFY modelChanged)

   private:
    LayoutModel *m_model;

   public:
    explicit Layout(QQuickItem * parent = nullptr);

    LayoutModel *model();
    void setModel(LayoutModel * model);
    ...
   signals:
    void modelChanged();
};

*.cpp

...

LayoutModel  *Layout::model() 
{
    return m_model;
}

void Layout::setModel(LayoutModel *model)
{
    if (m_model == model)
        return;
    m_model = model;
    emit modelChanged();
}