QTableWidget 初始化
一段代码:
void InitSpeedSystemTable(int row) { ui->tableSpeedSystem->clear(); ui->tableSpeedSystem->horizontalHeader()->setVisible(true); ui->tableSpeedSystem->setEditTriggers(QAbstractItemView::NoEditTriggers);//禁止编辑 ui->tableSpeedSystem->setSelectionBehavior(QAbstractItemView::SelectRows);//选择整行 ui->tableSpeedSystem->setColumnCount(8); ui->tableSpeedSystem->setRowCount(row); ui->tableSpeedSystem->setColumnWidth(0, 150); ui->tableSpeedSystem->setColumnWidth(1, 98); ui->tableSpeedSystem->setColumnWidth(2, 98); ui->tableSpeedSystem->setColumnWidth(3, 108); ui->tableSpeedSystem->setColumnWidth(4, 90); ui->tableSpeedSystem->setColumnWidth(5, 98); ui->tableSpeedSystem->setColumnWidth(6, 98); ui->tableSpeedSystem->setColumnWidth(7, 80); //设置表头动态 QStringList header; header << tr("时间") << tr("分类") << tr("对象") << tr("项目") << tr("描述") << tr("状态") << tr("码")<< tr("名称"); ui->tableSpeedSystem->horizontalHeader()->setStyleSheet("QHeaderView::section{border:0px solid rgb(218, 222, 226);background-color: rgb(204, 217, 230);font: 11pt '微软雅黑'}"); ui->tableSpeedSystem->setHorizontalHeaderLabels(header); ui->tableSpeedSystem->setSelectionBehavior(QAbstractItemView::SelectRows); ui->tableSpeedSystem->setSelectionMode(QAbstractItemView::SingleSelection); ui->tableSpeedSystem->verticalHeader()->setVisible(false); ui->tableSpeedSystem->horizontalHeader()->setMinimumHeight(40); ui->tableSpeedSystem->horizontalHeader()->setStretchLastSection(true); QHeaderView* headerView = ui->tableSpeedSystem->horizontalHeader(); headerView->setDefaultAlignment(Qt::AlignLeft | Qt::AlignVCenter); for(int i = 0; i < row; i++){ ui->tableSpeedSystem->setRowHeight(i, 50); } }
item 复选框
item(单元格)可编辑
void MainWindow::setTableItemText(int row, int column, const QString &text, bool checkable) { QTableWidgetItem* item = ui->tableWidget->item(row, column); if(item == nullptr) { item = new QTableWidgetItem(); ui->tableWidget->setItem(row, column, item); } item->setText(text); if(checkable) { //item->setTextAlignment(Qt::AlignCenter); item->setFlags(item->flags() | Qt::ItemIsUserCheckable); item->setCheckState(Qt::Unchecked); } if(column == 3){ item->setFlags(item->flags() & ~Qt::ItemIsEditable); } }