【问题标题】:Qt Model within a model?模型中的 Qt 模型?
【发布时间】:2012-12-31 15:34:54
【问题描述】:

我有一个 Qt 模型,它很可能是 QAbstractListModel。每个“行”代表我存储在QList 中的一个对象。我在QMLListView 中显示这个。但是,每个对象都有一个属性,恰好是一个字符串数组。我想在显示该行的委托中将其显示为ListView。但我不知道如何将该模型(对于对象的字符串数组属性)公开给QML。我不能通过数据函数公开它,因为模型是QObjects,不能是QVariants。我想改用QAbstractItemModel,但我仍然不知道如何为我的ListView 获取模型。以防万一,我使用的是Qt 5.0.0 版本。

【问题讨论】:

    标签: c++ qt model qml


    【解决方案1】:

    您可以从主 QAbstractListModel 返回 QVariantList,然后可以将其作为模型分配给您在代表。我添加了一个小例子,它有一个非常简单的单行模型,以内部模型为例。

    c++模型类:

    class TestModel : public QAbstractListModel
    {
      public:
    
      enum EventRoles {
        StringRole = Qt::UserRole + 1
      };
    
      TestModel()
      {
        m_roles[ StringRole] = "stringList";
        setRoleNames(m_roles);
      }
    
      int rowCount(const QModelIndex & = QModelIndex()) const
      {
        return 1;
      }
    
      QVariant data(const QModelIndex &index, int role) const
      {
        if(role == StringRole)
        {
          QVariantList list;
          list.append("string1");
          list.append("string2");
          return list;
        }
      }
    
      QHash<int, QByteArray> m_roles;
    };
    

    现在您可以将此模型设置为 QML 并像这样使用它:

    ListView {
      anchors.fill: parent
      model: theModel //this is your main model
    
      delegate:
        Rectangle {
          height: 100
          width: 100
          color: "red"
    
          ListView {
            anchors.fill: parent
            model: stringList //the internal QVariantList
            delegate: Rectangle {
              width: 50
              height: 50
              color: "green"
              border.color: "black"
              Text {
                text: modelData //role to get data from internal model
              }
            }
          }
        }
    }
    

    【讨论】:

    • 谢谢。事实证明,您可以将模型公开为QVariantQVariant::fromValue&lt;QObject*&gt;(myModelInstancePointer);
    猜你喜欢
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多