tableView表格重写表头增加全选功能和实现翻页(读写excel和读ini)

一:重写表头文件
HeaderView.h

#pragma once
#ifndef HEADERVIEW_H
#define HEADERVIEW_H

#include <QObject>
#include <QHeaderView>
#include <QPainter>
#include <qcheckbox.h>
#include <QMouseEvent>

class HeaderView : public QHeaderView
{
	Q_OBJECT

public:
	explicit HeaderView(Qt::Orientation orientation, QWidget* parent = 0);
	bool isOn; //checkbox的开启或关闭状态
signals:
	void checkStatusChange(bool);
protected:	
	void paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const;
	void mousePressEvent(QMouseEvent* event);

private:
	
};


#endif // HEADERVIEW_H

HeaderView.cpp

#include "headerview.h"
#include <QDebug>

HeaderView::HeaderView(Qt::Orientation orientation, QWidget*  parent)
	: QHeaderView(orientation, parent)
	,isOn(false)
{
		
}

void HeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
{
	painter->save();
	QHeaderView::paintSection(painter, rect, logicalIndex);
	painter->restore();

	if (logicalIndex == 1)
	{	
		QStyleOptionButton option;
		option.iconSize = QSize(5, 5);
		option.rect = rect;

		if (isOn)
			option.state = QStyle::State_On;
		else
			option.state = QStyle::State_Off;
		//this->style()->drawPrimitive(QStyle::PE_IndicatorCheckBox, &option, painter);
		this->style()->drawControl(QStyle::CE_CheckBox, &option, painter);
	}
}


void HeaderView::mousePressEvent( QMouseEvent *event)
{
	if (isEnabled() && logicalIndexAt(event->pos()) == 1)
	{
		isOn = !isOn;		
		updateSection(isOn);
		emit checkStatusChange(isOn);
	}
	else
	{
		QHeaderView::mousePressEvent(event);
	}
}

二:TableView界面显示与翻页功能
Test.h

#pragma once
#ifndef TEST_H
#define TEST_H
#include "ui_Test.h"
#include "HeaderView.h"

#include <QSlider>
#include <QWidget>
#include <QScrollBar>
#include <QHeaderView>
#include <QStandardItemModel>
#include <QTableView>
#include <QPushButton>
#include <QLabel>
#include <QLineEdit>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QPalette>
#include <QFont>
#include <QDebug>
#include <qcheckbox.h>
#include <qformlayout.h>
#include <QMessageBox>
#include <qabstractitemview.h>
#include <Windows.h>

class Test : public QDialog
{
	Q_OBJECT
public:
	Test(QWidget *parent = Q_NULLPTR);
	~Test();

	QStandardItemModel* model;
	HeaderView* myHeader;
	void updateTableView(bool); //刷新同步项目checkbox测试选择状态
private:
	Ui::Dialog ui;

	void lastBtn_click();
	void nextBtn_click();
	void pageTo();
	void verticalScrollMove(int value);
};
#endif

Test.cpp

#include "Test.h"
#include<ActiveQt\qaxobject.h>

Test::Test(QWidget *parent)
{
	ui.setupUi(this);

	//当前最大化不可用,主界面设置好后,控件无需跟随
	this->setWindowFlags(windowFlags()&~Qt::WindowMaximizeButtonHint);
	this->setFixedSize(this->width(), this->height());
	this->setWindowTitle(QString::fromLocal8Bit("点检"));

	QPalette pe;   //调色板
	QFont font;    //字体
	pe.setColor(QPalette::WindowText, Qt::black);
	font.setBold(true);
	font.setPointSize(11);

	model = new QStandardItemModel();
	QStringList labels;
	labels.append(QString::fromLocal8Bit("序号"));
	labels.append(QString::fromLocal8Bit(""));
	labels.append(QString::fromLocal8Bit("名称"));
	model->setHorizontalHeaderLabels(labels);
	//定义item
	QStandardItem* item = 0;
	//写tableView表格内容,此处省略
	item = new QStandardItem(QString("%1").arg(1));
	item->setEditable(false);
	model->setItem(nIndex, 0, item);
	//选择勾选列
	item = new QStandardItem();
	item->setCheckable(true);
	item->setCheckState(Qt::Unchecked);
	item->setEditable(false);
	model->setItem(0, 1, item);
	//名称
	item = new QStandardItem(m_vecConfig.at(i).strTestItem);
	item->setEditable(false);
	model->setItem(0, 2, item);
	//填充单元格背景颜色		
	//model->item(0, 2)->setBackground(QColor(144, 238, 144));
	//固定表格大小
	//ui.tableView->setFixedSize(1280, 670);
	ui.tableView->setShowGrid(true);
	ui.tableView->setGridStyle(Qt::SolidLine);
	ui.tableView->setModel(model);
	ui.tableView->setSelectionBehavior(QAbstractItemView::SelectRows);  //select a line
//把重新写的表头加到tableview里
	myHeader = new HeaderView(Qt::Horizontal, ui.tableView);
	//HeaderView* myHeader = new HeaderView(Qt::Horizontal, ui.tableView);
	ui.tableView->setHorizontalHeader(myHeader);

	//设置tableView水平滚动和自适应宽度
	ui.tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
	ui.tableView->horizontalHeader()->setStretchLastSection(false);
	ui.tableView->horizontalHeader()->setHighlightSections(false);
	ui.tableView->verticalHeader()->setVisible(false);
	ui.tableView->setStyleSheet("QHeaderView::section { background-color:green; color:white};");
	int totalRow = ui.tableView->model()->rowCount(); //the total row
	int totalPage = 1;
	if (totalRow > 0)  
	{
		int rowHeight = ui.tableView->rowHeight(0);           //the row's height
		int tableViewHeight = ui.tableView->height();                //every row's height
		int row1page = tableViewHeight / rowHeight - 1;
		totalPage = totalRow / row1page;
		if (totalRow%row1page != 0)
		{
			totalPage++;
		}
	}
	//翻页键的设置
	ui.pushButtonlast->setFixedSize(80, 30);
	ui.pushButtonlast->setPalette(pe);
	ui.pushButtonlast->setFont(font);
	connect(ui.pushButtonlast, &QPushButton::clicked, this, &Test::lastBtn_click);

	ui.lineEditPage->setFixedSize(50, 30);
	ui.lineEditPage->setPalette(pe);
	ui.lineEditPage->setFont(font);
	connect(ui.lineEditPage, &QLineEdit::editingFinished, this, &Test::pageTo);

	ui.labelPage->setText("/" + QString::number(totalPage));
	ui.labelPage->setFixedSize(50, 30);
	ui.labelPage->setPalette(pe);
	ui.labelPage->setFont(font);

	ui.pushButtonNext->setFixedSize(80, 30);
	ui.pushButtonNext->setPalette(pe);
	ui.pushButtonNext->setFont(font);
	connect(ui.pushButtonNext, &QPushButton::clicked, this, &Test::nextBtn_click);

	QHBoxLayout *second_layout = new QHBoxLayout();
	second_layout->setSpacing(3);
	second_layout->addStretch(1);
	second_layout->addWidget(ui.pushButtonlast);
	second_layout->addWidget(ui.lineEditPage);
	second_layout->addWidget(ui.labelPage);
	second_layout->addWidget(ui.pushButtonNext);
	second_layout->addStretch(1);

	QVBoxLayout *mainSec_layout = new QVBoxLayout();
	mainSec_layout->addStretch(2);
	mainSec_layout->addLayout(second_layout);
	mainSec_layout->addSpacing(2);
	this->setLayout(mainSec_layout);

	QScrollBar *scrollBar = (QScrollBar *)ui.tableView->verticalScrollBar();
	connect(scrollBar, SIGNAL(valueChanged(int)), this, SLOT(verticalScrollMove(int)));

	ui.lineEditPage->setText("1");
	ui.pushButtonTest->setParent(this);  //设置到对象树
	ui.pushButtonTest->setStyleSheet("background-color: rgb(0, 255, 0);");//设置按钮背景颜色
																		  //跟随表头全选复选框状态,刷新tableview表checkbox
	connect(myHeader, &HeaderView::checkStatusChange, this, &Test::updateTableView);
}

//Dialg类时,加了析构
Test::~Test()
{
}
//读ini文件 法1.QTextStream数据流形式。法2.头文件加QSetting
/*int Test::readTestConfig()
{
	QString line = "";
	QString strFile = "D:\\MyProject\\Test.ini";
	QFile defaultFile(strFile);
	if (defaultFile.exists())
	{
		QFile file(strFile);
		if (file.open(QIODevice::ReadOnly | QIODevice::Text))
		{
		//法1
			QTextStream in(&file);
			qDebug() << line;
			while (!line.isNull())
			{
				line = in.readLine();
				qDebug() << line;
			}
		}
		file.close();
		
		//法2
		/*QSettings *syssetting = new QSettings(strFile, QSettings::IniFormat);
		if (syssetting == nullptr)
		{
			QMessageBox::critical(NULL, QString::fromLocal8Bit("错误"), QString::fromLocal8Bit("文件寻找失败!"), QMessageBox::Ok);
			return -1;
		}
		syssetting->setIniCodec("GBK"); //处理中文,键key不能为中文,值可以为中文
		QString strTmp = "";
		QString strItem = "";
		for (int i = 0; i < ; i++)
		{
			strItem = "Item/" + QString::number(i);
			strTmp = syssetting->value(strItem).toString();
		}
		delete syssetting;
		syssetting = nullptr;*/
		return 0;
	}
	else
	{
		QMessageBox::critical(NULL, QString::fromLocal8Bit("错误"), strFile + QString::fromLocal8Bit(":路径不存在文件"), QMessageBox::Ok);
		return -1;
	}
}
*/

//读excel文件
/*int Test::readtExcelFile()
{	
	//读最新测试文件,记录数据
	QString strPath = "D:\\MyProject\\Test.xlsx";

	//连接Excel控件
	QAxObject* excel = new QAxObject(this);
	if (!excel->setControl("Excel.Application"))  //office //WPS
	{
		if (!excel->setControl("ket.Application"))
		{
			QMessageBox::critical(NULL, QString::fromLocal8Bit("错误"), QString::fromLocal8Bit("电脑未安装可以读写Excle的Office和WPS软件!"), QMessageBox::Ok);
			return -1;
		}
	}
	
	excel->dynamicCall("Visible", false); // 不显示窗体
	excel->setProperty("DisplayAlerts", false);  // 不显示任何警告信息。如果为true, 那么关闭时会出现类似"文件已修改,是否保存"的提示
	QAxObject* workbooks = excel->querySubObject("WorkBooks");  //获取工作簿集合
	workbooks->dynamicCall("Open(const QString&)", strPath); //打开打开已存在的工作簿
	QAxObject* workbook = excel->querySubObject("ActiveWorkBook"); //获取当前工作簿 
	QAxObject* sheets = workbook->querySubObject("Sheets");  //获取工作表集合,Sheets也可换用WorkSheets
	QAxObject* sheet = workbook->querySubObject("WorkSheets(int)", 1);//获取工作表集合的工作表1,即sheet1
	QAxObject* range = sheet->querySubObject("UsedRange"); //获取该sheet的使用范围对象
	QAxObject* columns = range->querySubObject("Columns");
	int nCol = columns->property("Count").toInt(); //获取列数,可能会多读的空列,需自己处理
	QVariant var = range->dynamicCall("Value");
	delete range;
	QVariantList varRows = var.toList();  //得到表格中的所有数据
	if (varRows.isEmpty())
	{
		return -1;
	}
		
	const int rowCount = varRows.size(); 
	QStringList temList;
	for (int i = 0; i < rowCount; ++i)   //
	{
		temList.clear();
		QVariantList rowData = varRows[i].toList();
		temList << rowData[j].toString();  //每行数据
	}
     
	workbook->dynamicCall("Close()");  //关闭文件
	excel->dynamicCall("Quit()");//关闭excel  如果电脑安装有福昕阅读器,excel进程关闭失效,多次操作会打开多个进程
	delete excel;
	excel = nullptr;	
	return 0;
}
*/
//上一页
void Test::lastBtn_click()
{
	int page = ui.lineEditPage->text().toInt();
	if (page <= 1) return;

	int rowHeight = ui.tableView->rowHeight(0);           //the row's height
	int tableViewHeight = ui.tableView->height();                //every row's height
	int row1page = tableViewHeight / rowHeight - 1;
	ui.tableView->verticalScrollBar()->setSliderPosition((page - 2)*row1page);
	ui.lineEditPage->setText(QString::number(page - 1));
}
//下一页
void Test::nextBtn_click()
{
	int page = ui.lineEditPage->text().toInt();
	int totalRow = ui.tableView->model()->rowCount();    //the total row
	int rowHeight = ui.tableView->rowHeight(0);           //the row's height
	int tableViewHeight = ui.tableView->height();                //every row's height
	int row1page = tableViewHeight / rowHeight - 1;
	int totalPage = totalRow / row1page;
	if (totalRow%row1page != 0)
	{
		totalPage++;
	}

	ui.tableView->verticalScrollBar()->setSliderPosition((page + 1)*row1page);
	if (page + 1 <= totalPage)
	{
		ui.lineEditPage->setText(QString::number(page + 1));
	}
}

void Test::pageTo()
{
	if (ui.lineEditPage->text().isEmpty()) return;

	int totalRow = ui.tableView->model()->rowCount();    //the total row
	int rowHeight = ui.tableView->rowHeight(0);           //the row's height
	int tableViewHeight = ui.tableView->height();                //every row's height
	int row1page = tableViewHeight / rowHeight - 1;
	int totalPage = totalRow / row1page;
	if (totalRow%row1page != 0)
	{
		totalPage++;
	}

	int page = ui.lineEditPage->text().toInt();
	if (page <= 0)
	{
		page = 1;
	}
	else if (page > totalPage)
	{
		page = totalPage;
	}
	ui.lineEditPage->setText(QString::number(page));
	ui.tableView->verticalScrollBar()->setSliderPosition(row1page * (page - 1));
}
//垂直进度条跟随翻页时移动
void Test::verticalScrollMove(int)
{
	int totalRow = ui.tableView->model()->rowCount();    //the total row
	int rowHeight = ui.tableView->rowHeight(0);           //the row's height
	int tableViewHeight = ui.tableView->height();                //every row's height
	int row1page = tableViewHeight / rowHeight - 1;
	int totalPage = totalRow / row1page;
	if (totalRow%row1page != 0)
	{
		totalPage++;
	}

	int last = 0;
	int current = ui.tableView->verticalScrollBar()->value();
	int next = row1page;
	for (int page = 1; page <= totalPage; page++)
	{
		if (current > last && current < next)
		{
			ui.lineEditPage->setText(QString::number(page));
			break;
		}
		last += row1page;
		next += row1page;
	}
	if (current >= row1page*(totalPage - 1))
	{
		ui.lineEditPage->setText(QString::number(totalPage));
	}
}

void Test::updateTableView(bool)
{
	if (myHeader->isOn)
	{
		for (int i = 0; i < model->rowCount(); i++)
		{
			model->item(i, 1)->setCheckState(Qt::Checked);			
		}
	}
	else
	{
		for (int i = 0; i < model->rowCount(); i++)
		//for (int i = 0; i < m_vecConfig.size(); i++)
		{
			model->item(i, 1)->setCheckState(Qt::Unchecked);
		}
	}
}

/*int Test::WriteExeclFile()
{
	QString strPath = "D:\\MyProject\\SpotTest.xlsx";
	QDateTime currTime = QDateTime::currentDateTime();
	
	//连接Excel控件
	QAxObject* excel = new QAxObject(this);
	if (!excel->setControl("Excel.Application"))  //office //WPS
	{
		if (!excel->setControl("ket.Application"))
		{
			QMessageBox::critical(NULL, QString::fromLocal8Bit("错误"), QString::fromLocal8Bit("电脑未安装可以读写Excle的Office和WPS软件!"), QMessageBox::Ok);
			return -1;
		}
	}

	excel->dynamicCall("Visible", false); // 不显示窗体
	excel->setProperty("DisplayAlerts", false);  // 不显示任何警告信息。如果为true, 那么关闭时会出现类似"文件已修改,是否保存"的提示
	QAxObject* workbooks = excel->querySubObject("WorkBooks");  //获取工作簿集合
	workbooks->dynamicCall("Open(const QString&)", strPath); //打开打开已存在的工作簿
	QAxObject* workbook = excel->querySubObject("ActiveWorkBook"); //获取当前工作簿 
	QAxObject* sheets = workbook->querySubObject("Sheets");  //获取工作表集合,Sheets也可换用WorkSheets
	int sheet_count = sheets->property("Count").toInt();
	
	QAxObject* sheet = workbook->querySubObject("WorkSheets(int)", 1);//获取工作表集合的工作表1,即sheet1
	QAxObject* range = sheet->querySubObject("UsedRange"); //获取该sheet的使用范围对象
	//workbooks->dynamicCall("Add");	
	if (NULL == range || range->isNull())
	{
		return -1;
	}
	//QList<QVariant> datalist;
	//range->dynamicCall("SetValue(const QVariant&", QVariant(datalist));

	 注意一定要用QDir::toNativeSeparators, 将路径中的"/"转换为"\", 不然一定保存不了
	//QAxObject* workbook = workbooks->querySubObject("Open(const QString&)", QDir::toNativeSeparators(strPath));
	
	//excel->setProperty("Caption", "Qt Excel");      //标题为Qt Excel
	//QAxObject *work_book = excel->querySubObject("ActiveWorkBook");
	//QAxObject *worksheets = workbook->querySubObject("Sheets");  //当前工作簿
	//int sheetCount = worksheets->property("Count").toInt();
	//QAxObject *worksheet = workbook->querySubObject("Sheets(int)", 1);     //获取表单1   WorkSheets(int)
	
	int rew = 2;
	int col =3;
	strValue = "aabb";
	QAxObject *cell = sheet->querySubObject("Cells(int,int)", row, col);
	if (cell->isNull() || cell == NULL) 
	{
		return -1;
	}
		cell->setProperty("Value", strValue);
		sheet->querySubObject("Cells(int,int)", row, 1)->setProperty("Value", "sddfd");
		//字体颜色
		QAxObject *font = cell->querySubObject("Font");
		font->setProperty("Color", QColor(74, 51, 255));
	}
	
	workbook->dynamicCall("Save()");
	workbook->dynamicCall("Close()");  //关闭文件
	excel->dynamicCall("Quit()");//关闭excel
	delete excel;
	excel = nullptr;
	return 0;
}
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值