QTableView view(this); QStandardItemModel model(this); /*设置表头水平标题*/ model.setHorizontalHeaderItem(0,new QStandardItem("Name")); model.setHorizontalHeaderItem(1,new QStandardItem("Sex")); model.setHorizontalHeaderItem(2,new QStandardItem("Age")); model.horizontalHeaderItem(0)->setFont(QFont("Helvetica",20,50)); //设置标题字体 /*设置表头垂直标题*/ model.setVerticalHeaderItem(0,new QStandardItem("No.1")); model.setVerticalHeaderItem(1,new QStandardItem("No.2")); model.setVerticalHeaderItem(2,new QStandardItem("No.3")); /*设置列表条目数据*/ QPixmap pix(":user.png"); pix = pix.scaled(24,24,Qt::KeepAspectRatio); QStandardItem *itemA=new QStandardItem(); itemA->setData(pix,Qt::DecorationRole); //设置条目图标 itemA->setData("A",Qt::DisplayRole); itemA->setData("A:tooltip",Qt::ToolTipRole); itemA->setData(QFont("宋体",12,QFont::Bold,true),Qt::FontRole); //设置条目字体 itemA->setData(Qt::AlignCenter,Qt::TextAlignmentRole); //设置条目中心对齐 QLinearGradient linearGradient(0,0,100,20); linearGradient.setColorAt(0.2, Qt::white); linearGradient.setColorAt(0.6, Qt::green); linearGradient.setColorAt(1.0, Qt::black); itemA->setData(QBrush(linearGradient),Qt::BackgroundRole); //设置条目背景色(为渐变色) model.setItem(0,0,itemA); model.setItem(0,1,new QStandardItem("B")); model.setItem(1,0,new QStandardItem("C")); model.item(0,1)->setTextAlignment(Qt::AlignCenter); //设置条目居中对齐 /*将数据模型的第一列进行下降排序(从大到小)*/ model.sort(0,Qt::DescendingOrder); /*设置列宽不可变动*/ view.horizontalHeader()->setResizeMode(QHeaderView::Fixed); /*设置行宽不可变动*/ view.verticalHeader()->setResizeMode(QHeaderView::Fixed);
/*设置用户不能选择表格*/
view.setSelectionMode(QAbstractItemView::NoSelection);
/*设置表格不可编辑*/ view.setEditTriggers(QAbstractItemView::NoEditTriggers); /*设置表头的显示与隐藏*/ view.horizontalHeader()->setVisible(false); view.verticalHeader()->setVisible(false); /*禁止显示网格线*/ view.setShowGrid(false); /*禁止显示滚动条*/ view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); /*设置行列的高宽*/ view.setColumnWidth(0,50); //设置column0(第1列)的宽度为50 view.setRowHeight(0,30); //设置row0(第1行)的高度为30 view.resizeRowsToContents(); //更据当前内容自动调整行距 view.resizeColumnsToContents(); //更据当前内容自动调整列距
/*禁止焦点(取消QTableView选中后的虚线框)*/
view.setFocusPolicy(Qt::NoFocus);
原文地址:https://www.cnblogs.com/lifexy/p/9155708.html
时间: 2024-10-11 07:32:49