Qt项目中经常用到表格,在项目中使用统一封装的接口,进行表格的初始化和数据插入;
//初始化所有TableWidget,参数headerList为表头数据,使用逗号分隔的表头数据字符串
void initTableWidget(QTableWidget *tableWidget, QString headerList){
tableWidget->horizontalHeader()->setStyleSheet("QHeaderView::section{height:22px;color:black;background:#ffffff;padding:0 0 0 5px;border-right:1px solid #dcdcdc;border-bottom:1px solid #dcdcdc;border-left:none;border-top:none; font-weight:bold;}");
tableWidget->setColumnCount(headerList.split(",").count());
tableWidget->setHorizontalHeaderLabels(headerList.split(","));
tableWidget->verticalHeader()->hide();
tableWidget->horizontalHeader()->setStretchLastSection(true);
tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
tableWidget->setWordWrap(true);
tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
}
//TableWidget单元格中插入数据,只针对文本数据,如果要插入控件,需要单独实现
void inserTabletWidgetItem(QTableWidget *tableWidget, int row, int column, QString text, int alignment){
QTableWidgetItem * item = new QTableWidgetItem();
item->setText(text);
item->setToolTip(text);
switch (alignment) {
case 0: //居中显示
item->setTextAlignment(Qt::AlignCenter);
break;
case 1: //靠左显示
item->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
break;
case 2: //靠右显示
item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
break;
default:
break;
}
tableWidget->setItem(row, column, item);
}
调用示例:
//表格初始化
initTableWidget(ui->tableWidgetXXX, "序号,接收时间,文件名称,接收状态");
//数据插入 inserTabletWidgetItem(ui->tableWidgetXXX, rowIndex, columnIndex, “插入的数据信息”);
以上两个函数,一定程度上方便了代码的开发,减少重复工作量。