Assigning roles to QSqlRelationalTable in QT5

  • I am using "this tutorial": to access a SQLite table and make it available in QML. The populates a number of empty rows, but I cannot get any of the fields (or roles) to display. Any idea what I could be missing?

    My qml code is something like this, where "STRING" is a field, and a valid role that I can observe in the C++ object with the debugger:

    TableView {
    model: myModel

    TableViewColumn {
    role: "STRING"
    title: "STRING"
    width: 160

    EDIT: See my own comment trails below, but I believe the question here boils down to: How can I assign roles to QSqlRelationalTableModel when "setRoleNames()": has been deprecated?

  • I notice that when I inspect my QLSqlTableModel with the debugger, the roles have been updated. However, when I inspect the roles using the roleNames() method, I observe the six default role names (toolTip, display, edit, etc.)

    Here's my code used to generate the role names. Notice I commented out the setRoleNames in the #ifndef QT5 directive. It was throwing a compiler error, and I was hoping that since I'm using QT5 it would be okay.

    void QLSqlTableModel::generateRoleNames()
    int nbCols = this->columnCount();
    for (int i = 0; i < nbCols; i++) {
    roles[Qt::UserRole + i + 1] = QVariant(this->headerData(i, Qt::Horizontal).toString()).toByteArray();


    #ifndef HAVE_QT5
    // setRoleNames(roles);

  • I overloaded roleNames() to return roles, so now the returned roles of that method are my 11 column names, rather than the 6 default roles. However, my data still does not show up in TableView. If I change the role name to one of the 6 default values, say "edit", then TableView is populated with a bunch of int values.

  • Ah, I think I see the problem. Roles is defined in the derived class, not QSQLRelationalTableModel class. So when I generatRoleNames, I'm not really doing anything. How then can I assign roleNames in the base class? "setRoleNames()": function has been deprecated.

  • I ended up just overriding the roleNames() method.

    @QHash<int, QByteArray> QLSqlTableModel::roleNames() const{
    return roles;

Log in to reply

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