QTableWidget

  1. 单元格添加checkBox,并居中对齐
QCheckBox* checkItem = new QCheckBox(ui->tableWidget);
checkItem->setCheckState(Qt::Unchecked);
QWidget *widgetSet = new QWidget();
QHBoxLayout *tmp_layout = new QHBoxLayout(widgetSet);
tmp_layout->addWidget(checkItem);
tmp_layout->setAlignment(checkItem, Qt::AlignCenter);
ui->m_tableWidget_XZQDM->setCellWidget(nRow, nCol, widgetSet);
ui->m_tableWidget_XZQDM->setColumnWidth(0, 70);
  1. 上面这种情况下,遍历得到checkBox
QWidget *w = (QWidget*)ui->tableWidget->cellWidget(row, 0);
QList<QCheckBox*> checkBoxList = w->findChildren<QCheckBox*>();
QCheckBox* checkItem = checkBoxList.at(0);
checkItem->setCheckState((Qt::CheckState)selectState);
  1. 单元格设置宽度,高度
ui->tableWidget->setColumnWidth(nCol, 70);
  1. 清除当前网格的内容
ui->tableWidget->clearContents();
  1. 设置网格的第一列那个序号表头不显示
ui->tableWidget->verticalHeader()->setVisible(false);
  1. 设置行列的数量
ui->tableWidget->setColumnCount(3);
ui->tableWidget->setRowCount(4);
  1. 显示行表头的显示内容
QStringList qheadLables;
qheadLables << tr("checkState") << tr("名称1") << tr("名称2");
ui->tableWidget->setHorizontalHeaderLabels(qheadLables);
  1. 设置网格的单元格处于不可编辑状态
QTableWidgetItem* pWidgetItem = new QTableWidgetItem("22");
pWidgetItem->setFlags(pWidgetItem->flags() & (~Qt::ItemIsEditable));
ui->tableWidget->setItem(nRow, nCol, pWidgetItem);
  1. 设置单元格灰掉
QTableWidget* pTableWidget = ui->tableWidget;
QTableWidgetItem* pItemDM = (QTableWidgetItem*)pTableWidget->item(row, nCol);
pItemDM->setFlags(pItemDM->flags() & (~Qt::ItemIsEnabled));
pTableWidget->setItem(row, nCol, pItemDM);
  1. 合并单元格
ui->tableWidget->setSpan(nRowIndex, nColIndex, nRowCount, nColCount); 
ui->tableWidget->setSpan(0, 1, 2, 3); //表示序号为0的行,序号为1的列的这个单元格开始,包含自己,向下共选择两行;包含自己,向右供选择3列,然后合并
上一篇:QTableWidget如何设置只能选中一行?


下一篇:QTableWidget 使用