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

Distinguish between the models 'id' and the local/view 'id'.



  • Hi all,

    I am trying to use the id field of my model in the views delegate.
    I can't seem to find how to make the distinguishment between the models 'id' and the local 'id'.
    How would i go about that?
    See below.

    QHash<int, QByteArray> MyModel::roleNames() const
    {
    	static const QHash<int, QByteArray> roles {
    		{NameRole, "name"},
    		{IdRole, "id"},
    		{ChildCountRole, "childCount"},
    		{Active, "active"},
    	};
    	return roles;
    }
    
    ItemDelegate {
        id: delegate
    
        contentItem: ListButton {
            id: id // <= I want the buttons id to be the models id ...
            caption: name // <= ... just like how the models name field is assigned to the caption of the button.
        }
    }
    

  • Qt Champions 2018

    That doesn't really make sense.

    The QML id is not a property and is not modifiable at runtime.
    It is fixed at compile time and is used as the identifier in the current context. A single object can have multiple id in different contexts..

    What are you trying to do? Why do you want a dynamic id?

    If the question were for a different role, says you had a caption role, you could differentiate them by prefixing the role with model. :

    caption: model.caption
    


  • @javs I don't know if I am missing something, but couldn't you just give it a different name?



  • I have run into serious problems when I shadow names of features or properties in Item or derived from Item. It is better to just name it something that cannot clash.

    static const QHash<int, QByteArray> roles {
    		{NameRole, "nameRole"},
    		{IdRole, "idRole"},
    		{ChildCountRole, "childCountRole"},
    		{ActiveRole, "activeRole"},
    	};
    

    Putting role in the name automatically documents this is coming from the model.

    Using simple names that have a chance to clash just opens you up to failing later because something is added to an object later. Analogous to using i, j, and k in every loop. It is a pain to diagnose. It is a bad habit that will cost you time months from now. Text is cheap, descriptive names don't cost you anything, but can cost you hours if you collide with other names. Search and replace is a thing. Autocomplete is a thing. Use them to supplement having to type in long variable names.


Log in to reply