天天看點

QTableView相關操作

添加表頭
//需要先建立一個模型
QStandardItemModel *theModel = new QStandardItemModel();
//設定列數
theModel.setColumnCount(3);
//設定表頭資訊
theModel->setHeaderData(0,Qt::Horizontal,"序号");
theModel->setHeaderData(1,Qt::Horizontal, "檔案名稱");
theModel->setHeaderData(2, Qt::Horizontal, "建立時間");      
設定表格的屬性
在ui界面中插入一個QtableView的表格
ui->tableView->setModel(theModel);
//讓表頭資訊顯示居左
ui->tableView->horizontalHeader()->setDefaultAlignment(Qt::AlignLift);
//設定列的寬度不可以改變
//比如設定第一列的寬度不可以改變
ui->tableView->horizontalHeader()->setResizeMode(1,QHeaderView::fixed);
//設定第一列的寬度為100
ui->tableView->horizontalHeader()->setResizeMode(1,100);      
設定表格内容
theModel->setData(theModel->index(行号,列号),需要設定的内容));
theModel->index用來定位指定的行号和列号确定一個位置
//例如,在第1行第1列的位置處設定内容為小明
theModel->setData(theModel->index(1,1),"小明");      
删除
//删除所有的行除了表頭
theModel->clear();
//删除指定的行
//例如删除一行
theModel->removeRow(1);
//删除所有行
theModel->removeRows(0,theModel->count());      

繼續閱讀