Hiding a column in QTableView based on the column name

  • This is how I fill in my QTableView (not sure it's a good way).

    QStandardItemModel *model = new QStandardItemModel;

    QList<QStringList> *rows = Cars::find("something");

    model->setHorizontalHeaderLabels(QStringList() << "id" << "col1" << "col2" << "col2" << "col3" << "col4" << "col5");

    foreach (QStringList row, *rows) {
    QList<QStandardItem *> items;

            foreach (QString text, row)
                items.append(new QStandardItem(text));


    // Hide columns

    My question is, how do I hide the column based on the header label, something like this

    @model = new QSqlRelationalTableModel(ui.bookTable);
    ui.bookTable->setColumnHidden(model->fieldIndex("id"), true);@

  • Is there a reason you would not know which column you wanted to hide? The fieldIndex is used for the field name. You are placing the naming the headerLabel which is maintained by the model, they are not the same. There are a couple of ways. Since you are explicitly setting the column name, you could test for the column name in an if statement and set a variable to the proper column number. Or if you want to explicitly test for the text in the headerLable you would have to use something like this:
    for (i=0; i<model()->columnCount(); i++)
    if (model->headerData ( i, Qt::Horizontal, Qt::DisplayRole)=="id")
    ui.bookTable->setColumnHidden(i, true);

  • I was hoping to do it like that so that in the future I don't have to keep track which column is "col1" or which column is "col2". I gues that's one way to do it, I'll just make a function out of it. BTW, you need to put true or false parameter in setColumnHidden. Thanks for the suggestion.

  • If you are testing for a certain column name, then why would you not know what column it is? Another trick to make it easier is to use an enumeration to identify the columns by a name rather than a column number. Something like:
    then in your code you can refer to a meaningful name as opposed to a number that has no meaning. Like:
    @ui.bookTable->setColumnHidden(COL1, true);
    ui.bookTable->setColumnHidden(COL3, true);@

    I am not sure if this will help but if you are having concerns with keeping track of column numbers this can be a good tool.

  • The column order list might change in the future, but not the column name, that's why I'm asking if it's possible to get the column location based on the name. However, your alternate solution is good enough, better than using #define (that's what I've thought before). Thanks a lot.

Log in to reply

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