从委托中的C ++模型获取数据

时间:2015-04-20 12:36:43

标签: c++ qt treeview qml

我在C ++端和树视图上有一个模型

TreeView {
            id: view
            itemDelegate: Rectangle{
                property int indexOfThisDelegate: model.index
                Text {
                text:???
                    font.pixelSize: 14
                }
            }
            model: myModel
            onCurrentIndexChanged: console.log("current index", currentIndex)
            TableViewColumn {
                title: "Name"
                role: "type"
                resizable: true
            }

            onClicked: console.log("clicked", index)
            onDoubleClicked: isExpanded(index) ? collapse(index) : expand(index)
    }

如何从TreeItem获取数据?问题是 indexOfThisDelegate 整数而不是QModelIndex,所以 我想要像

这样的东西
Text {
    text:model.getDescription(currentlyPaintedModelIndex)
    font.pixelSize: 14
}

或者我应该在整数和树之间有映射QModelIndex吗?

1 个答案:

答案 0 :(得分:1)

好的,自己想通了

在模型中:

QHash<int, QByteArray> MenuTreeModel::roleNames() const
{
    QHash<int, QByteArray> roles;
    roles[TitleRole] = "Title";
    return roles;
}

// of course it could me more complex with many roles
QVariant MenuTreeModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
    {
        return QVariant();
    }

    MenuTreeItem *item = itemForIndex(index);

    if (role != TitleRole)
    {
        return QVariant();
    }
    QString str = item->data(index.column()).toString();
    return item->data(index.column());
}

我们的自定义树项目(例如):

class MenuTreeItem
{
    // item data, contains title
    QList<QVariant> m_itemData; 
};

在qml中:

TreeView {
        id: view
        itemDelegate: Rectangle{
            Text {
            text:model.Title 
                font.pixelSize: 14
            }
        }
        model: myModel
}