Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QSortFilterProxyModel sub-class registration and instantiation issue.



  • Hi everyone!
    I have a problem with instantiating of an QSortFilterProxyModel derived class instance directly in QML.
    For e.g. I defined a class

    class FilterModel: public QSortFilterProxyModel {
    	Q_OBJECT
    public:
    	bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override;
    };
    

    Then I register the class:

    static void registerQmlTypes()
    {
    	qmlRegisterType<FilterModel>("com.mycompany.app", 1, 0, "FilterModel");
    }
    Q_COREAPP_STARTUP_FUNCTION(registerQmlTy
    

    And use it:

    import QtQuick 2.12
    import QtQuick.Controls 2.12
    import com.mycompany.app 1.0 as App
    ListView {
    	model: App.FilterModel {
    		sourceModel: App.someModel
    	}
        delegate: Item { /** */ }
    }
    

    The problem is that it's sometimes can't load the qml file on process start and terminates. Error message:

    Cannot assign object of type "App.FilterModel" to property of type "QAbstractItemModel*" as the former is neither the same as the latter nor a sub-class of it.
    

    And this issue isn't persistent. Sometimes it occurs and sometimes not.
    Anybody have any idea how can I fix it? I know that I can instantiate the model in C++ part and then pass to the QML, but I think it is an awkward solution.



  • Maybe it will help someone. This code fixed the issue:

    #if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
    	qmlRegisterAnonymousType<QAbstractItemModel>(uri, 1);
    #else
    	qmlRegisterType<QAbstractItemModel>();
    #endif
    

Log in to reply