I have a working treemodel, called myModel
(derived from QAbstractItemModel
) in C++ and I can show it in QML using the QML Treeview
control and the TreeViewDelegate
When the mouse is pressed on one treeview item, I want to pass a QModelIndex
(or parameters which I can use in C++ for constructing a QModelIndex
) back to C++ for further processing.
I can use the model.index
but this gives me the index in the view (which corresponds to the selected row), but not a useable QModelIndex
. Also I experiemented with the depth of the treeview. But I am stuck.
Has anyone a solution?
BTW: I am using Qt6.4. I found something for Qt5, which is now archived (QML: How to get the QModelIndex in a delegate inside a TreeView).
This is the code where I try to investigate the behaviour of the treeview (the call to _controller(...)
is the entry point back to C++:
TreeView {
id: garminDrives
Layout.fillHeight: true
Layout.fillWidth: true
Layout.preferredHeight: root.height
Layout.preferredWidth: root.width
delegate: TreeViewDelegate {
MouseArea {
anchors.fill: parent
onClicked: {
console.log("Tree item tapped. Model name = " + model.name
+ " Index to be passed back to C++ = " + model.index,
" Depth = " + garminDrives.depth(model.index) + " row = "
+ model.row + " col = " + model.column
+ " currentRow = " + garminDrives.currentRow
+ " currentCol = " + garminDrives.currentCol
)
_controller.getSelectedRow(model.index)
}
}
contentItem: Label {
id: delegatetext
text: model.name
}
}
model: myModel
}
Just simplified the QML
TreeView {
id: treeView
anchors.fill: parent
delegate: TreeViewDelegate {
id: treeDelegate
text: model.display
onClicked: {
var mi = treeDelegate.treeView.index(row, column)
console.log("model.index =", mi)
treeView.model.showQModelIndex(mi)
}
}
model: _model
}
}
The QModelIndex is simply treeDelegate.treeView.index(row, column).
You can find the complete example on Github: https://github.com/d029940/QmlTreeview