Important: Please read the Qt Code of Conduct -

Dynamic Columns in TableView

  • I am using a TableView and giving it a list model from C++. However, I am finding that TableView is looking for roles that would correspond to each column (I think, not sure). I cannot get the TableView to display data from my model for some reason. But if I feed a QML ListModel to the same TableView I can get it to display. The QML ListModel seems to use roles very explicitly.

    So, I started wondering about dynamic views that might need a dynamic set of columns. Is there a way to do this with a QML TableView using a C++ model for the data? I would like to be able to query the number of columns returned from a database query and display the results of all columns without defining explicit roles, if possible.

    It may be that I am just not seeing the forest for the trees right now.

  • So, I looked at the source for QAbstractListModel and QAbstractItemModel and it looks like roleNames is a virtual function that is never defined. That means there are no default roles at all? I guess the default roles are only in QML types like ListView? This is really interesting and explains why I have been struggling with this.

  • I "think" I found something that should work:

    It seems to show all the parts needed for dynamic roles.

  • Can role name strings used in the interface to C++ be strings of numbers? example: "256"
    I have found that the code I am working on in using numbers to represent the roles. So that the roleNames function returns a list of number/string pairs that look like this:


    However, the TableView only seems to be requesting role number 256 when calling the data() function on our QAbstractListModel. I cannot find the page that talks about roleNames in the model view programming docs pages for Qt.

  • Painful...
    I changed the rolenames to this:


    Now everything seems to work.

Log in to reply