从委托中的 C++ 模型获取数据
Getting data from C++ model inside delegate
我在 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 是 integer 而不是 QModelIndex,所以
我想要类似
的东西
Text {
text:model.getDescription(currentlyPaintedModelIndex)
font.pixelSize: 14
}
或者我应该在整数和树 QModelIndex 之间建立映射吗?
好的,我自己想出来了
模型中:
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
}
我在 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 是 integer 而不是 QModelIndex,所以 我想要类似
的东西Text {
text:model.getDescription(currentlyPaintedModelIndex)
font.pixelSize: 14
}
或者我应该在整数和树 QModelIndex 之间建立映射吗?
好的,我自己想出来了
模型中:
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
}