Qt隐藏QTableView中的列

时间:2013-09-25 10:04:57

标签: c++ qt qtableview

我想隐藏ID中的QtableView列,但我无法在我的实施中执行此操作。任何人都可以帮助我吗?

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++;
}

}

2 个答案:

答案 0 :(得分:16)

您使用ui->tableView->setColumnHidden(6, true);,但没有索引为6的列。您应该改为编写ui->tableView->setColumnHidden(5, true);,因为ID列号比 5 而不是6。

<强>更新

在将模型设置为视图后,您还需要隐藏列,即:

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

答案 1 :(得分:1)

另一种方法是将指定列的宽度设置为零:ui->tableView->setColumnWidth(col,0); ui->tableWidget->setColumnWidth(col,0);