Qt中QTableview的使用方法
数据模型类为QStandardItemModel
插入的数据类型为QStandardItem
可定全局变量数据模型类和插入的数据类型
QItemSelectionModel *theSelection
QStandardItemModel *theModel;
QStandardItem *Item;
1.确定行列数
QWidget *window = new QWidget;
theModel = new QStandardItemModel(15,13,window);//确定行列数
theSelection = new QItemSelectionModel(theModel);//选中模型类
2.设置表头
QStringList headerList;
headerList<<"类别"
<<"真空井1"<<"真空井2"<<"真空井3"<<"真空井4"<<"真空井5"
<<"真空井6"<<"真空井7"<<"真空井8"<<"真空井9"<<"真空井10"
<<"真空井11"<<"真空井12";
theModel->setHorizontalHeaderLabels(headerList);//设置表头文字
3.设置各项数据
Item = new QStandItnem("数据n");
theModel->setItem(i,j,Item);//学生列设置Item
Item->setTextAlignment(Qt::AlignCenter);//使数据处于中心位置
4…设置
tableView->setModel(theModel);
tableView->setSelectionModel(theSelection);//设置选中模型
5.插入一行数据
QList<QStandardItem*> ItemList;//列表类
QStandardItem *Item;
for(int i = 0;i<ColumnCount-1;i++)
{
Item = new QStandardItem("0");//创建Item
ItemList<<Item;//输出到列表
}
//获取当前选中的行
QModelIndex index = ui->tableView->selectionModel()->currentIndex();//返回当前选中的的模型项的索引
int count = index.row();
theModel->insertRow(count,ItemList);//插入
6.删除一行数据
QModelIndex index = ui->tableView->selectionModel()->currentIndex();//返回当前选中的的模型项的索引
int count = index.row();
theModel->removeRow(count);//删除
7.数据左对齐
QModelIndexList index = theSelection->selectedIndexes();//所有选中行的索引
for(int i = 0;i<index.count();i++)
{
QModelIndex count = index.at(i);//选中行的每一行的索引值
QStandardItem* Item = theModel->itemFromIndex(count);//获取每项数据。itemFromIndex:与给定索引相关联的指针
Item->setTextAlignment(Qt::AlignLeft);//左对齐
}
8.粗体、颜色设置类似
QModelIndexList index = theSelection->selectedIndexes();//所有选中行的索引
for(int i = 0;i<index.count();i++)
{
QModelIndex count = index.at(i);//选中行的每一行的索引值
QStandardItem* Item = theModel->itemFromIndex(count);//获取每项数据。itemFromIndex:与给定索引相关联的指针
QFont font = Item->font();
font.setBold(Qt::Checked);//粗体设置为被选中状态
//font.setBold(true);//粗体设置为被选中状态
Item->setFont(font);
}
9.斜体
QModelIndexList index = theSelection->selectedIndexes();
for(int i = 0;i<index.count();i++)
{
QModelIndex count = index.at(i);//选中行的索引值
QStandardItem* Item = theModel->itemFromIndex(count);//获取每项数据。itemFromIndex:与给定索引相关联的指针
QFont font = Item->font();
font.setItalic(Qt::Checked);//斜体设置为被选中状态
//font.setBold(true);//粗体设置为被选中状态
Item->setFont(font);
}