Important: Please read the Qt Code of Conduct -

Need help with populating QML TreeView

  • I'm trying to populate a TreeView in a QML file. I'm using the Simple Tree Model example as a guide. From the example, I'm using the same data file and TreeItem and TreeModel classes. The difference though is that my TreeView is instantiated in the QML as opposed to in C++.

    My problem is that the tree is empty, no data appears. I'm not getting an errors. I know that the data is correctly retrieved from the file and the property get function (getTreeViewModel) is called but TreeView doesn't seem to do anything with it.

    I don't know if I'm supposed to force some kind of update but I don't know how to do that.

    Any help would be appreciated. I've pasted some of the code below. I'm using Qt 5.5.1. Thanks.


    TreeViewTest::TreeViewTest() : m_treeViewModel(0){
    	QFile file(":/default.txt");
    		m_treeViewModel = new TreeModel(file.readAll());
    	m_qmlEngine.rootContext()->setContextProperty("myTreeView", this);
    	delete m_treeViewModel;


    class TreeViewTest : QObject {
    	Q_PROPERTY(QAbstractItemModel* treeViewModel READ getTreeViewModel)
    	explicit TreeViewTest();
    public slots:
    	QAbstractItemModel* getTreeViewModel() {return m_treeViewModel;}
    	QQmlApplicationEngine m_qmlEngine;
    	TreeModel* m_treeViewModel;


    Item {
    	id: item1
    	width: 640
    	height: 480
    	TreeView {
    		id: treeView1
    		width: 500
    		height: 450
    		model: myTreeView.getTreeViewModel()

  • Moderators

    Hi @infinicat You need to define role name too in case of accessing C++ models from QML. This can de done by re-implementing roleNames(). Have you implemented it in your model ? If not then, check this post.

  • Thank you. That worked.

Log in to reply