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.

    CPP:

    TreeViewTest::TreeViewTest() : m_treeViewModel(0){
    	QFile file(":/default.txt");
    	if(file.open(QIODevice::ReadOnly)){
    		m_treeViewModel = new TreeModel(file.readAll());
    		file.close();
    	}
    	m_qmlEngine.rootContext()->setContextProperty("myTreeView", this);
    	m_qmlEngine.load(QUrl(QStringLiteral("qrc:/qml/mainWindow.qml")));
    }
    TreeViewTest::~TreeViewTest(){
    	delete m_treeViewModel;
    }
    

    Header:

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

    QML:

    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
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.