Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/155.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 模型中的Qt模型?_C++_Qt_Model_Qml - Fatal编程技术网

C++ 模型中的Qt模型?

C++ 模型中的Qt模型?,c++,qt,model,qml,C++,Qt,Model,Qml,我有一个Qt模型,它很可能是一个QAbstractListModel。每个“行”表示我存储在QList中的对象。我正在QML的列表视图中显示这个。但是,每个对象都有一个属性,恰好是字符串数组。我想在显示该行的代理内将其显示为列表视图。但是我不知道如何将该模型(对象的字符串数组属性)公开给QML。我无法通过数据函数公开它,因为模型是QObjects,不能是QVariants。我想改用qabstractemmodel,但我仍然不知道如何为我的ListView获取模型。如果有问题,我使用的是Qt5.0

我有一个Qt模型,它很可能是一个
QAbstractListModel
。每个“行”表示我存储在
QList
中的对象。我正在
QML
列表视图中显示这个。但是,每个对象都有一个属性,恰好是字符串数组。我想在显示该行的代理内将其显示为
列表视图
。但是我不知道如何将该模型(对象的字符串数组属性)公开给
QML
。我无法通过数据函数公开它,因为模型是
QObjects
,不能是
QVariants
。我想改用
qabstractemmodel
,但我仍然不知道如何为我的
ListView
获取模型。如果有问题,我使用的是
Qt
5.0.0版本。

您可以从主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;
};

谢谢还可以使用以下命令将模型公开为
QVariant
QVariant::fromValue(myModelInstancePointer)
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
          }
        }
      }
    }
}