QTableView
model提供数据 view提供视图 view用来显示model的数据 必须将model绑定到某个view中才能显示
QStandardItemModel* model = new QStandardItemModel(); QStringList labels = QObject::trUtf8("频率,功率,误差").simplified().split(","); model->setHorizontalHeaderLabels(labels); //定义item QStandardItem* item = 0; for(int i = 0;i < 10;i++){ item = new QStandardItem(QString("%1").arg(i)); model->setItem(i,0,item); item = new QStandardItem(QString("%1").arg(i*2)); model->setItem(i,1,item); item = new QStandardItem(QString("%1").arg(i*3)); model->setItem(i,2,item); } ui->tableView->setModel(model); ui->tableView->show();
QTableWidget
//三列,只设置前两列宽度,剩下一列自适应到最大宽度 ui->tableWidget->setColumnWidth(0, 150); ui->tableWidget->setColumnWidth(1, 150); ui->tableWidget->horizontalHeader()->setStretchLastSection(true); ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); ui->tableWidget->setSelectionMode( QAbstractItemView::SingleSelection);