23

我想隐藏其中的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++;
}

}
4

2 回答 2

34

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

更新:

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

ui->tableView->setModel(model);
ui->tableView->setColumnHidden(5, true);
于 2013-09-25T10:12:20.737 回答
2

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

于 2021-07-13T09:36:30.233 回答