How to define a custom function in QAbstractItemModel child class which could be called? [duplicate]

  c++, qabstractitemmodel, qml, qt, qtquick2

I created a tree model class which is derived from QAbstractItemModel and want to call the function from a qml file, but I get the following error message:

qrc:/TabIMTree/IMTree.qml:135: TypeError: Property 'getIndexByValue' of object IMTreeModel(0x555c381bec90) is not a function

My soure code is as follows

IMTreeModel.h

class IMTreeModel : public QAbstractItemModel
{
    Q_OBJECT

    Q_ENUMS(ItemRoles) 
    
public:
    enum ItemRoles {
        NAME = Qt::UserRole + 1,
        TYPE,
        VALUE
    };
    
    IMTreeModel(QObject *parent = NULL);
    ~IMTreeModel();
  
    void appendChild(const QModelIndex& index);
    bool removeRows(int row, int count, QModelIndex parent);
    QModelIndex parent(const QModelIndex &index) const;
    Qt::ItemFlags flags(const QModelIndex &index) const;
    QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    int columnCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role) const;
    bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole);//It's NOT permitted to define a new function to change data, override setData ONLY!
    QHash<int, QByteArray> roleNames() const;
    
    QModelIndex getIndexByValue(QVariant varValue) const;  //**HERE IS THE PROBLEM!!!**
}

IMTreeModel.cpp

QModelIndex IMTreeModel::getIndexByValue(QVariant varValue) const
{
    std::wcout << L"==getIndexByValue==== "<< varValue.toString().toStdWString()<<endl;
    return QModelIndex();
}

IMTree.qml

import QtQuick 2.0
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
import QtQuick.Controls.Styles 1.4
import QtQml.Models 2.2

import IMTreeModel 1.0  // which is registered in main.cpp   
                        // qmlRegisterType<IMTreeModel>("IMTreeModel", 1, 0, "IMTreeModel");
Rectangle{ 
  IMTreeModel{
      id: treeModel
  }

  TextField{
      id:fldFilter
  }

  Button{
    id:btnApplyFilter
    onClicked:{
        treeModel.getIndexByValue(fldFilter.text)
    }   
}

When I clicked the button btnApplyFilter I got the error message. But I have call the function data() and setData() of IMTreeModel successfully from IMTree.qml as following:

 treeModel.data(index, IMTreeModel.VALUE).toString()
 treeModel.setData(treeView.currentIndex, fldValue.text)

I know both successful functions are built-in functions in class QAbstractItemModel.
But why the function getIndexByValue defined by myself can’t be called?

What’s wrong?

Source: Windows Questions C++

LEAVE A COMMENT