Qt中QTableview的使用方法

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);
    }
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值