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.sortByColumn(0);
view.setSortingEnabled(true);
view.setAutoScroll
view->horizontalHeader()->setHighlightSections(false);
view.horizontalHeader()->setResizeMode(QHeaderView::Fixed); view.verticalHeader()->setResizeMode(QHeaderView::Fixed);
view.setSelectionMode(QAbstractItemView::NoSelection);
view.verticalHeader()->hide();
view.setSelectionMode(QAbstractItemView::SingleSelection);
//设置选择模式,表示只能选中单个
view.setSelectionBehavior(QAbstractItemView::SelectRows);
//设置选择行为,表示只能选择一行(也可以设置为列,或者单个Item项目)
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(); //更据当前内容自动调整列距
view.setFocusPolicy(Qt::NoFocus);
qDebug()<<view.currentIndex().row(); //获取行号,如果为-1,表示无效
qDebug()<<view.currentIndex().column();//获取列号,如果为-1,表示无效
文章来源:https://www.cnblogs.com/lifexy/p/9155708.html