也许我的问题不清楚,但我希望通过代码我的问题变得更清楚。我创建了这两个结构,并在 FormModel 类中使用它们:
struct Tile
{
QString name;
QString color;
}; Q_DECLARE_METATYPE(Tile)
struct Form
{
QString nameForm;
Tile grid[9] ; // i want for each form 4 tile that in qml are 4 rectangles
}; Q_DECLARE_METATYPE(Form)
class FormModel : public QAbstractListModel
{
Q_OBJECT
public:
explicit FormModel(QObject *parent = 0);
~FormModel();
enum dashBoardRoles {
NameForm=Qt::UserRole+1,
Grid,
};
int rowCount(const QModelIndex &parent=QModelIndex()) const;
QVariant data(const QModelIndex &index, int role) const;
Q_INVOKABLE bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()) Q_DECL_OVERRIDE;
Q_INVOKABLE bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) Q_DECL_OVERRIDE;
QHash<int, QByteArray> roleNames() const;
signals:
public slots:
private:
QList<Form> dashboard;
};
这是 QAbstractListModel 的数据方法:
QVariant FormModel::data(const QModelIndex &index, int role) const
{
if(index.row()>0 && index.row() >= dashboard.count())
return QVariant();
Form dashTemp = dashboard[index.row()];
if(role== NameForm)
return dashTemp.nameForm;
if(role== Grid)
{
QVariant gridVect = QVariant::fromValue(dashTemp.grid);
return gridVect;
}
return QVariant();
}
QHash<int, QByteArray> FormModel::roleNames() const
{
QHash <int,QByteArray> roles;
roles [NameForm]="nameForm";
roles [Grid]="grid";
return roles;
}
这是qml代码:
Window {
id:app
visible: true
width: 480
height: 800
title: qsTr("Hello World")
ListView {
model: myForms // i have defined the name in main.cpp
anchors.fill: parent
delegate: ColumnLayout{
spacing: 30
// nome Form
Text{
text: nameForm
font.pointSize:20
color: "red"
font.capitalization: Font.Capitalize
}
// grigla mattonelle
GridView {
id:grid
width: 300; height: 300
cellWidth: 100 ; cellHeight: 100
model: 9
delegate: Item{
width : grid.cellWidth
height: grid.cellHeight
Rectangle{
anchors.centerIn: parent
width:parent.width-10
height: parent.height-10
color: grid[index].color
}
}
}
}
}
}
如何从角色网格的数据中获取颜色?我在 qml 中调用 grid[index].color....