1. 程式人生 > >24.QTableView函數使用,右擊菜單實現

24.QTableView函數使用,右擊菜單實現

life target this mode ont 行為 display str gre

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

24.QTableView函數使用,右擊菜單實現