Qt hide column in QTableView

laura picture laura · Sep 25, 2013 · Viewed 28.6k times · Source

I want to hide the ID column in the QtableView and i can't do that on my implementation. Can anyone help me?

void MainWindow::on_actionClear_Search_triggered()
{
model = new QStandardItemModel(cars.size(),6,this);
//create header
createHeader(model);
//set data to the table view
populate(cars);

ui->tableView->setColumnHidden(6,true);
ui->tableView->setModel(model);


}

void MainWindow::createHeader(QStandardItemModel *model){


model->setHorizontalHeaderItem(0,new QStandardItem("Car"));
model->setHorizontalHeaderItem(1, new QStandardItem("Type"));
model->setHorizontalHeaderItem(2, new QStandardItem("Mileage"));
model->setHorizontalHeaderItem(3, new QStandardItem("Year"));
model->setHorizontalHeaderItem(4, new QStandardItem("Is registered"));
model->setHorizontalHeaderItem(5, new QStandardItem("ID"));
}

void MainWindow::populate(const QList<Vehicle> &vehicles)
{
int j = 0;
QList<Vehicle>::ConstIterator iter;
for( iter= vehicles.begin(); iter != vehicles.end(); iter++){
    const Vehicle& car = *iter;
    //set car
    QString makeAndModel = car.getGeneralData().getMake() + car.getGeneralData().getModel();
    QStandardItem *mAndM = new QStandardItem(QString(makeAndModel));
    mAndM->setEditable(false);
    model->setItem(j,0,mAndM);

    //set type
    QStandardItem *type = new QStandardItem(QString(car.getGeneralData().getType()));
    type->setEditable(false);
    model->setItem(j,1,type);

    //set mileage
    QString mileageString = QString::number(car.getGeneralData().getMileage());
    QStandardItem *mileage = new QStandardItem(QString(mileageString));
    mileage->setEditable(false);
    model->setItem(j,2,mileage);

    //set year
    QString yearString = QString::number(car.getGeneralData().getYear());
    QStandardItem *year = new QStandardItem(QString(yearString));
    year->setEditable(false);
    model->setItem(j,3,year);

    //set registration
    QString regString = VehicleHelper::convertBoolToString(car.getRegistration().isRegistered());
    QStandardItem *regDate = new QStandardItem(QString(regString));
    regDate->setEditable(false);
    model->setItem(j,4,regDate);


    //set ID column
    QStandardItem *idNumber = new QStandardItem(QString(car.getVehicleID().getID()));
    idNumber->setEditable(false);
    model->setItem(j,5,idNumber);
    j++;
}

}

Answer

vahancho picture vahancho · Sep 25, 2013

You use ui->tableView->setColumnHidden(6, true);, but there is no column with index 6. You should write ui->tableView->setColumnHidden(5, true); instead, because ID column number is rather 5 than 6.

UPDATE:

You also need to hide column(s) after you set the model to the view, i.e:

ui->tableView->setModel(model);
ui->tableView->setColumnHidden(5, true);