Qt之数据表头增加控件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zl_95520/article/details/86573671

QTableView中不重写QHeadView,增加控件


1、实现效果

直接看实现的结果是否满足需求,再来干货!
在这里插入图片描述

2、添加控件

以本次演示为例进行代码讲解,其中各个变量由自己定义的去改变
代码最终实现的效果需要自己去设计样式!

	//初始化表一的model
    m_model = new QStandardItemModel();

    //初始化表头属性,后面有需要可设计不同表头属性
    strHeader<<QString::fromLocal8Bit("等级")<<QString::fromLocal8Bit("时间")
            <<QString::fromLocal8Bit("类型")<<QString::fromLocal8Bit("内容");
            
    //将表头属性插入model中
    m_model->setHorizontalHeaderLabels(strHeader);
    
    //数据表设置model
    ui->tableView->setModel(m_model);
    
	//将数据表的表头对象传过来
    _headView = ui->tableView->horizontalHeader();

    //表头第一个属性单独设置一下,增加事件功能
    //QToolButton 的父类设置为QHeadView,这样就在表头插入QToolButton了
    _headButton  = new QToolButton(_headView);
    
    //这边指定位置,(0,0)就是表头的第一个属性了
    _headView->setIndexWidget(m_model->index(0,0),_headButton);
    
	//这边我根据表头的第一个单元格的大小,先初始化控件的大小进行填充
    _headButton->resize(80,20);

	//改变控件移上去的鼠标样式
    _headButton->setCursor(Qt::ArrowCursor);

    //设置一下控件菜单,这个由个人需求设计添加
    _headButton->setPopupMode(QToolButton::InstantPopup);
    _headButton->setMenu(_tableHeadMenu);
    
    //这边链接表头的事件,如果表头的列宽改变了,控件大小也要改变,不然会很奇怪
    connect(_headView,SIGNAL(sectionResized(int,int,int)),this,SLOT(onModelIndexResize(int,int,int)));

3、控件事件

//表头控件重置大小-功能
void MyEye::onModelIndexResize(int logicalIndex, int oldSize, int newSize)
{
    //只对表头第一个单元格的控件进行改变,所以判断一下下标
    if(logicalIndex == 0)
    {
    	//控件的大小可由自己设计
         _headButton->resize(newSize,20);
    }

}

猜你喜欢

转载自blog.csdn.net/zl_95520/article/details/86573671