天天看點

Qt+sqlite3實作單機登入管理資訊的簡單應用程式

Qt5.9.2+vs2013

軟體截圖:

1.登入

Qt+sqlite3實作單機登入管理資訊的簡單應用程式

2.首頁面

a)【使用者管理】頁面是為了更好管理使用者,擁有最高權限的使用者可看到所有使用者以及密碼,普通使用者隻可以看見自己的密碼,其他使用者密碼均顯示***,另外點選右上角使用者名可實作切換使用者。

Qt+sqlite3實作單機登入管理資訊的簡單應用程式

b)【客戶管理】頁面是為了讓使用者更好的管理客戶的聯系資訊,可實作增删改查以及導出成表格。然後就是按照檢索類型進行實時顯示資料。

Qt+sqlite3實作單機登入管理資訊的簡單應用程式

c)【商品管理】按照檢索類型顯示不同的資料以及将商品資訊導出到excel中。

Qt+sqlite3實作單機登入管理資訊的簡單應用程式

源碼簡介:

主函數部分 main.cpp:

#include "StewardSoft.h"
#include <QtWidgets/QApplication>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <qDebug>

int main(int argc, char *argv[])
{
	QApplication a(argc, argv);
	StewardSoft w;
	loginPage *m_loginPage = new loginPage;
	m_loginPage->exec();
	if (m_loginPage->login_flag == true) //login_flag判斷是否登入了
	{
		m_loginPage->close();
		w.username = m_loginPage->m_userName;
		w.userPrivilege = m_loginPage->m_privilege;
		UserManageChangeInfo::getInstance()->currentUserPrivilege = m_loginPage->m_privilege;
		qDebug() << "current user is: " << m_loginPage->m_userName;
		qDebug() << "current user privilege is: " << UserManageChangeInfo::getInstance()->currentUserPrivilege;
		//w.ui.menuadmin->setTitle(m_loginPage->m_userName);
		w.ui.loginUserBtn->setText(m_loginPage->m_userName);
		//w.show();
		return a.exec();
	}
	if (m_loginPage->login_flag == false && m_loginPage->close_flag == true)
	{
		a.quit();
	}
	
}
           

2.登入後首頁面 StewardSoft.cpp

#include "StewardSoft.h"
#include <QList>
#include <QTableWidgetItem>
#include <QSqlRecord>
#include <QTableWidget>
#include <QMessageBox>
#include <QDesktopWidget>
#include <QClipboard>
#include <QTableView>
#include <QTime>

#include "delegate.h"

#define tr QString::fromLocal8Bit

extern struct TableInfo;

StewardSoft* StewardSoft::instance = NULL;

StewardSoft::StewardSoft(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);
	//無邊框
	setWindowFlags(Qt::FramelessWindowHint);
	mLocation = this->geometry();
	mIsMax = false;
	mDrag = false;
	
	ui.mainTtile->installEventFilter(this);
	QIcon icon;
	icon.addFile("./img/appico.png");
	this->setWindowIcon(icon);
	//@test
	this->setMouseTracking(true);
	_isleftpressed = false;
	_curpos = 0;//标記滑鼠左擊時的位置
	//this->setMinimumSize(900, 600);//設定最小尺寸
	//@end
	
	ui.user_manage_privilege_LE->setValidator(new QIntValidator(1, 5, this));

	ui.userManageTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); //平均配置設定列寬
	ui.customerManageTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); //平均配置設定列寬
	ui.commodityManageTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); //平均配置設定列寬

	userManageChangeInfo = new UserManageChangeInfo; //使用者管理
	customerChangeInfo = new ChangeContent;  //客戶管理
	commmodityManagechangeInfo = new commmodityManageChangeInfo; //商品管理

	//添加登入使用者到menu上
	exitAction = new QAction;
	exitAction->setText(tr("切換使用者"));
	/*QAction *changePwd = new QAction;
	changePwd->setText(tr("修改密碼"));*/
	menu = new QMenu;
	//menu->setTitle("123");
	menu->addAction(exitAction);
	//menu->setFixedWidth(40);
	//menu->setMaximumWidth(50);
	//menu->addAction(changePwd);
	
	QString menuStyle = "\
						QMenu{\
							background-color: rgb(0,97,136); /* sets background of the menu 設定整個菜單區域的背景色,我用的是白色:white*/\
							border: 1px solid rgb(0,97,136);/*整個菜單區域的邊框粗細、樣式、顔色*/\
							color: #F0F0F0;\
						}\
						QMenuBar{\
							background-color: #F0F0F0; /* sets background of the menu 設定整個菜單區域的背景色,我用的是白色:white*/\
							border: 1px solid  rgb(0,97,136);\
						}\
						QMenuBar::item:selected{\
							background-color: rgb(0, 115, 168);\
							color:#F0F0F0;\
							font-size:12px;\
						}\
						QMenu::item{\
							background-color: rgb(0,97,136);\
							padding:8px 18px;/*設定菜單項文字上下和左右的内邊距,效果就是菜單中的條目左右上下有了間隔*/\
							margin:0px 0px;/*設定菜單項的外邊距*/\
							border-bottom:1px solid rgb(0,97,136);/*為菜單項之間添加橫線間隔*/\
						}\
						QMenu::item:selected{\
							color: white;\
							background-color: qlineargradient(spread : pad, x1 : 0, y1 : 1, x2 : 0, y2 : 0, stop : 0 rgb(25, 134, 199, 0), stop : 1 #5CACEE);/*這一句是設定菜單項滑鼠經過選中的樣式*/\
							font-size:12px;\
						}";
	menu->setStyleSheet(menuStyle);
	ui.loginUserBtn->setMenu(menu);

	if (username != NULL)
	{
		//ui.menuadmin->setTitle(username);
		ui.loginUserBtn->setText(username);
	}
	// 建立菜單項
	action_delete = new QAction(this);
	action_modification = new QAction(this);
	action_copy = new QAction(this);
	action_add = new QAction(this);
	//model測試
	//ui.tableView->setEditTriggers(QAbstractItemView::AllEditTriggers);
	CheckBoxDelegate *pCheckItem = new CheckBoxDelegate(this);
	myModel = new MyModel(20, 4, this);
	ui.tableView->setItemDelegateForColumn(3, pCheckItem);	
	QStringList headList;
	headList << "name" << "dsname" << "do" << "check";	
	myModel->setHeaderData(headList);
	ui.tableView->setModel(myModel);
	ui.tableView->horizontalHeader()->setStretchLastSection(true);
	//@end
	actions();
	connect(action_delete, SIGNAL(triggered(bool)), this, SLOT(actionDeleteClick())); //右鍵動作槽
	connect(action_modification, SIGNAL(triggered(bool)), this, SLOT(actionModificationClick())); //右鍵動作槽
	connect(action_copy, SIGNAL(triggered(bool)), this, SLOT(actionCopyClick())); //右鍵動作槽
	connect(action_add, SIGNAL(triggered(bool)), this, SLOT(actionAddClick())); //右鍵動作槽

	connect(userManageChangeInfo, SIGNAL(UpdateUserManageTable()), this, SLOT(UpdateUserManageInfo()));//更新資訊
	connect(customerChangeInfo, SIGNAL(UpdateCustomerManageTable()), this, SLOT(UpdateUserManageInfo()));
	connect(commmodityManagechangeInfo, SIGNAL(UpdatecommodityManageTable()), this, SLOT(UpdateUserManageInfo()));

	connect(ui.customerManageEXportDataBtn, SIGNAL(clicked()), this, SLOT(exportDataToExcel()));//導出資訊到excel表格
	connect(ui.searchContentExportDataBtn, SIGNAL(clicked()), this, SLOT(exportDataToExcel()));

	connect(ui.addDataBtn, SIGNAL(clicked()), this, SLOT(on_addDataBtn_clicked()));
	
	connect(exitAction, SIGNAL(triggered()), this, SLOT(exitCurrentUser()));

	if (ui.commodityManageTable != NULL)
	{
		TableInit("commodity", ui.commodityManageTable);
	}
	if (ui.userManageTable)
	{
		TableInit("user", ui.userManageTable);
	}
	if (ui.customerManageTable)
	{
		TableInit("customer", ui.customerManageTable);
	}
	qDebug() << tr("目前使用者權限等級:") << loginPage::getInstance()->m_privilege;
	//@處理滑鼠移動行的顔色變化
	lastRowBKColor = QColor(0x00, 0xff, 0x00, 0x00);//透明顔色
	previousColorRow = -1;
	connect(ui.userManageTable, SIGNAL(cellEntered(int, int)), this, SLOT(mycellEntered(int, int)));
	connect(ui.customerManageTable, SIGNAL(cellEntered(int, int)), this, SLOT(mycellEntered(int, int)));
	//@end
} 


StewardSoft::~StewardSoft()
{

}

void StewardSoft::Table2ExcelByHtml(QTableWidget *table, QString title)
{
	qDebug() << "-------this is: " << title << " ," << table->rowCount();
	QString fileName = QFileDialog::getSaveFileName(table, "儲存", QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation), tr("Excel 檔案(*.xls *.xlsx)"));
	if (fileName != "")
	{
		QAxObject *excel = new QAxObject;
		if (excel->setControl("Excel.Application")) //連接配接Excel控件
		{
			excel->dynamicCall("SetVisible (bool Visible)", "false");//不顯示窗體
			excel->setProperty("DisplayAlerts", false);//不顯示任何警告資訊。如果為true那麼在關閉是會出現類似“檔案已修改,是否儲存”的提示
			QAxObject *workbooks = excel->querySubObject("WorkBooks");//擷取工作簿集合
			workbooks->dynamicCall("Add");//建立一個工作簿
			QAxObject *workbook = excel->querySubObject("ActiveWorkBook");//擷取目前工作簿
			QAxObject *worksheet = workbook->querySubObject("Worksheets(int)", 1);

			int i, j;
			//QTablewidget 擷取資料的列數
			int colcount = table->columnCount();
			//QTablewidget 擷取資料的行數
			int rowscount = table->rowCount();

			//QTableView 擷取列數
			//int colount=ui->tableview->model->columnCount();
			//QTableView 擷取行數
			//int rowcount=ui->tableview->model->rowCount();

			QAxObject *cell, *col;
			//标題行
			cell = worksheet->querySubObject("Cells(int,int)", 1, 1);
			cell->dynamicCall("SetValue(const QString&)", title);
			cell->querySubObject("Font")->setProperty("Size", 18);
			//調整行高
			worksheet->querySubObject("Range(const QString&)", "1:1")->setProperty("RowHeight", 30);
			//合并标題行
			QString cellTitle;
			cellTitle.append("A1:");
			cellTitle.append(QChar(colcount - 1 + 'A'));
			cellTitle.append(QString::number(1));
			QAxObject *range = worksheet->querySubObject("Range(const QString&)", cellTitle);
			range->setProperty("WrapText", true);
			range->setProperty("MergeCells", true);
			range->setProperty("HorizontalAlignment", -4108);//xlCenter
			range->setProperty("VerticalAlignment", -4108);//xlCenter
			//列标題
			for (i = 0; i < colcount; i++)
			{
				QString columnName;
				columnName.append(QChar(i + 'A'));
				columnName.append(":");
				columnName.append(QChar(i + 'A'));
				col = worksheet->querySubObject("Columns(const QString&)", columnName);
				col->setProperty("ColumnWidth", table->columnWidth(i) / 6);
				cell = worksheet->querySubObject("Cells(int,int)", 2, i + 1);
				//QTableWidget 擷取表格頭部文字資訊
				columnName = table->horizontalHeaderItem(i)->text();
				//QTableView 擷取表格頭部文字資訊
				// columnName=ui->tableView_right->model()->headerData(i,Qt::Horizontal,Qt::DisplayRole).toString();
				cell->dynamicCall("SetValue(const QString&)", columnName);
				cell->querySubObject("Font")->setProperty("Bold", true);
				cell->querySubObject("Interior")->setProperty("Color", QColor(191, 191, 191));
				cell->setProperty("HorizontalAlignment", -4108);//xlCenter
				cell->setProperty("VerticalAlignment", -4108);//xlCenter
			}

			//資料區

			//QTableWidget 擷取表格資料部分
			for (i = 0; i < rowscount; i++)
			{
				for (j = 0; j < colcount; j++)
				{
					worksheet->querySubObject("Cells(int,int)", i + 3, j + 1)->dynamicCall("SetValue(const QString&)", table->item(i, j) ? table->item(i, j)->text() : "");
				}
			}

			//QTableView 擷取表格資料部分
			//  for(i=0;i<rowcount;i++) //行數
			//     {
			//         for (j=0;j<colcount;j++)   //列數
			//         {
			//             QModelIndex index = ui->tableView_right->model()->index(i, j);
			//             QString strdata=ui->tableView_right->model()->data(index).toString();
			//             worksheet->querySubObject("Cells(int,int)", i+3, j+1)->dynamicCall("SetValue(const QString&)", strdata);
			//         }
			//     }

			//畫框線
			QString lrange;
			lrange.append("A2:");
			lrange.append(colcount - 1 + 'A');
			lrange.append(QString::number(table->rowCount() + 2));
			range = worksheet->querySubObject("Range(const QString&)", lrange);
			range->querySubObject("Borders")->setProperty("LineStyle", QString::number(1));
			range->querySubObject("Borders")->setProperty("Color", QColor(0, 0, 0));
			//調整資料區行高
			QString rowsName;
			rowsName.append("2:");
			rowsName.append(QString::number(table->rowCount() + 2));
			range = worksheet->querySubObject("Range(const QString&)", rowsName);
			range->setProperty("RowHeight", 20);
			workbook->dynamicCall("SaveAs(const QString&)", QDir::toNativeSeparators(fileName));//儲存至fileName
			workbook->dynamicCall("Close()");//關閉工作簿
			excel->dynamicCall("Quit()");//關閉excel
			delete excel;
			excel = NULL;
			if (QMessageBox::question(NULL, tr("完成"), tr("檔案已經導出,是否現在打開?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)
			{
				QDesktopServices::openUrl(QUrl("file:///" + QDir::toNativeSeparators(fileName)));
			}
		}
		else
		{
			QMessageBox::warning(NULL, tr("錯誤"), tr("未能建立 Excel 對象,請安裝 Microsoft Excel。"), QMessageBox::Apply);
		}
	}
}

StewardSoft* StewardSoft::getInstance()
{
	if (instance == NULL)
	{
		instance = new StewardSoft();
	}
	return instance;
}

//menubar監聽
void StewardSoft::on_menuBar_triggered(QAction *action)
{
	qDebug() << QString::fromLocal8Bit("menubar目前點選的是:") << action->text();
	if (action->text().toStdString().compare("exit") == 0)
	{	
		loginPage *m_loginPage = new loginPage;
		m_loginPage->show();
		this->close();
		qDebug() << "mainWindow is visible: " << this->isVisible();
	}
}

void StewardSoft::exitCurrentUser()
{
	qDebug() << "退出目前使用者";
	loginPage *m_loginPage = new loginPage;
	m_loginPage->show();
	this->close();
	qDebug() << "mainWindow is visible: " << this->isVisible();
}

void StewardSoft::on_userManageAddBtn_clicked()
{
	qDebug() << tr("新增的使用者賦予的:") << ui.user_manage_privilege_LE->text().toInt();
	
	QString msg = tr("您輸入的權限必須小于等于登陸者權限!\n登陸者權限為:") + QString::number(userPrivilege);
	qDebug() << tr("登入使用者權限:") << msg;
	if (ui.user_manage_privilege_LE->text().toInt() < userPrivilege)
	{
		QToolTip::showText(ui.user_manage_privilege_LE->mapToGlobal(QPoint(100, 0)), msg);
		return;
	}
	if (ui.user_manage_username_LE->text() == "")
	{
		QToolTip::showText(ui.user_manage_username_LE->mapToGlobal(QPoint(100, 0)), tr("您輸入的賬戶為空!"));
		return;
	}
	if (ui.user_manage_pwd_LE->text() == "")
	{
		QToolTip::showText(ui.user_manage_pwd_LE->mapToGlobal(QPoint(100, 0)), tr("您輸入的密碼為空!"));
		return;
	}
	if (ui.user_manage_privilege_LE->text() == "")
	{
		QToolTip::showText(ui.user_manage_privilege_LE->mapToGlobal(QPoint(100, 0)), tr("您輸入的權限等級為空!"));
		return;
	}
	QString currentTableName = ui.mainTab->tabText(ui.mainTab->currentIndex());
	if (currentTableName == tr("使用者管理"))
	{
		currentTableName = "user";
	}
	QString user_manage_username = ui.user_manage_username_LE->text();
	QString user_manage_pwd = ui.user_manage_pwd_LE->text();
	QString user_manage_privilege = ui.user_manage_privilege_LE->text();
	QString creator = ui.loginUserBtn->text();

	qDebug() << "user name:" << user_manage_username << "pwd:" << user_manage_pwd;
	QList<QString> valueList;
	valueList.append(user_manage_username);
	valueList.append(user_manage_pwd);
	valueList.append(user_manage_privilege);
	valueList.append(creator);
	TableInsert(currentTableName, valueList);
}

//客戶管理按鈕添加新客戶資訊
void StewardSoft::on_customerManageAddBtn_clicked()
{
	
	QString currentTableName = ui.mainTab->tabText(ui.mainTab->currentIndex());
	if (currentTableName == tr("客戶管理"))
	{
		currentTableName = "customer";
	}
	QString customerName = ui.customerManageNameLE->text();
	QString customerContact = ui.customerManageContactLE->text();
	QString customerArea = ui.customerManageAreaLE->text();
	QString customerElseInfo = ui.customerManageElseInfoTE->toPlainText();
	qDebug() << "currentTableName:" << currentTableName << ",customerName:" << customerName << ",customerContact:" << customerContact << ",customerArea:" << customerArea << ",customerElseInfo:" << customerElseInfo;
	if (customerName == "" || customerContact == "")
	{
		QMessageBox::warning(NULL, tr("警告"), tr("客戶姓名為空或聯系方式為空!"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
		return;
	}
	QList<QString> valueList;
	valueList.append(customerName);
	valueList.append(customerContact);
	valueList.append(customerArea);
	valueList.append(customerElseInfo);
	TableInsert(currentTableName, valueList);
}
//表查詢
void StewardSoft::TableQuery(QTableWidget *tablewidget, QString queryType, QString tableName, QString condition)
{
	//建立并打開資料庫
	QSqlDatabase database;
	database = QSqlDatabase::addDatabase("QSQLITE");
	database.setDatabaseName("MyDataBase.db");
	if (!database.open())
	{
		qDebug() << "Error: Failed to connect database." << database.lastError();
	}
	else
	{
		qDebug() << "Succeed to connect database.";
	}
	QSqlQuery sql_query(database);
	int newTableRowCount = 0;
	int sqlResultCount = 0;
	//查詢所有資料
	sql_query.prepare("select * from " + tableName + " where " + queryType + " like '" + condition + "%'");
	if (!sql_query.exec())
	{
		qDebug() << sql_query.lastError();
	}
	else
	{
		newTableRowCount = queryRowCount(sql_query);
		qDebug() << "sql_query size: " << newTableRowCount;
		tablewidget->setRowCount(newTableRowCount);
		while (sql_query.next())
		{
			QString userName = sql_query.value(0).toString();
			QString userPwd = sql_query.value(1).toString();
			QString privilege = sql_query.value(2).toString();
			QString creator = sql_query.value(3).toString();
			qDebug() << QString("name:%1    password:%2    privilege:%3     creator:%4").arg(userName).arg(userPwd).arg(privilege).arg(creator);
			QList<QString> *list = new QList<QString>;
			list->append(userName);
			list->append(userPwd);
			list->append(privilege);
			list->append(creator);
			for (int i = 0; i < list->size(); i++)
			{
				QTableWidgetItem *item = new QTableWidgetItem();
				item->setTextAlignment(Qt::AlignCenter);
				item->setText(list->at(i));

				//if (i == 1)
				//{
				//	/*qDebug() << "sqlResultCount: " << sqlResultCount << " ,i : " << i;
				//	QPushButton *showPwd = new QPushButton;
				//	showPwd->setText(tr("顯示密碼"));
				//	ui.user_manage_table->setCellWidget(sqlResultCount, 1, showPwd);*/
				//	item->setText("******");
				//	ui.user_manage_table->setItem(sqlResultCount, i, item);
				//}
				//else
				//{
				//	ui.user_manage_table->setItem(sqlResultCount, i, item);
				//}
				tablewidget->setItem(sqlResultCount, i, item);
			}
			sqlResultCount++;
		}
	}
	//關閉資料庫
	database.close();
}

//商品管理檢索
void StewardSoft::on_searchContentSerchBtn_clicked()
{
	QString serachTypeComboBoxText = ui.commodityManageserachTypeCB->currentText();
	QTableWidget *currentTableWidget = ui.commodityManageTable;
	QString condition = ui.searchContentLE->text();
	qDebug() << tr("目前檢索類型:") << serachTypeComboBoxText;
	if (serachTypeComboBoxText.compare(tr("名稱")) == 0)
	{
		serachTypeComboBoxText = "commodityName";
		
	}
	if (serachTypeComboBoxText.compare(tr("裝置号")) == 0)
	{
		serachTypeComboBoxText = "commodityEquitmentNumber";
	}
	if (serachTypeComboBoxText.compare(tr("屬性")) == 0)
	{
		serachTypeComboBoxText = "commodityProperty";
	}
	if (serachTypeComboBoxText.compare(tr("備注")) == 0)
	{
		serachTypeComboBoxText = "commodityElseInfo";
	}
	TableQuery(currentTableWidget, serachTypeComboBoxText, "commodity", condition);

}

//檢索内容輸入内容監聽
void StewardSoft::on_searchContentLE_textChanged(const QString &text)
{
	qDebug() << tr("目前輸入的條件是:") << text;
	on_searchContentSerchBtn_clicked();
}
//檢索類型變化監聽
void StewardSoft::on_commodityManageserachTypeCB_currentTextChanged(const QString &text)
{
	qDebug() << tr("目前輸入的條件是:") << text;
	on_searchContentSerchBtn_clicked();
}

void StewardSoft::on_customerManageSearchTypeCB_currentTextChanged(const QString &text)
{
	qDebug() << tr("目前輸入的條件是:") << text;
	on_customerManageSearchBtn_clicked();
}

void StewardSoft::on_customerManageSearchContent_textChanged(const QString &text)
{
	qDebug() << tr("目前輸入的條件是:") << text;
	on_customerManageSearchBtn_clicked();
}

void StewardSoft::on_customerManageSearchBtn_clicked()
{
	QString serachTypeComboBoxText = ui.customerManageSearchTypeCB->currentText();
	QTableWidget *currentTableWidget = ui.customerManageTable;
	QString condition = ui.customerManageSearchContent->text();
	qDebug() << tr("目前檢索類型:") << serachTypeComboBoxText;
	if (serachTypeComboBoxText.compare(tr("姓名")) == 0)
	{
		serachTypeComboBoxText = "CustomerName";

	}
	if (serachTypeComboBoxText.compare(tr("聯系方式")) == 0)
	{
		serachTypeComboBoxText = "CustomerPhone";
	}
	if (serachTypeComboBoxText.compare(tr("地區")) == 0)
	{
		serachTypeComboBoxText = "Area";
	}
	if (serachTypeComboBoxText.compare(tr("備注")) == 0)
	{
		serachTypeComboBoxText = "ElseInfo";
	}
	TableQuery(currentTableWidget, serachTypeComboBoxText, "customer", condition);
}

void StewardSoft::on_mainTab_tabBarClicked(int index)
{
	//qDebug() << "current tab is : " << index << "tab name: " << ui.mainTab->tabText(index) << ui.mainTab->tabText(index).compare(QString::fromLocal8Bit("客戶管理"));
	if (ui.mainTab->tabText(index).compare(QString::fromLocal8Bit("使用者管理")) == 0)
	{
		TableInit("user", ui.userManageTable);
	}
	if (ui.mainTab->tabText(index).compare(QString::fromLocal8Bit("客戶管理")) == 0)
	{
		TableInit("customer",ui.customerManageTable);
	}
	if (ui.mainTab->tabText(index).compare(QString::fromLocal8Bit("商品管理")) == 0)
	{
		TableInit("commodity", ui.commodityManageTable);
	}
}

void StewardSoft::findTableNullLine()
{
	ui.userManageTable->rowCount();
}

//擷取列
int StewardSoft::queryColumnCount(QSqlQuery query)
{
	QSqlRecord sqlRecord = query.record();
	return sqlRecord.count();
}

//擷取行
int StewardSoft::queryRowCount(QSqlQuery query)
{
	int initialPos = query.at();
	// Very strange but for no records .at() returns -2
	int pos = 0;
	if (query.last()){
		pos = query.at() + 1;
	}
	else{
		pos = 0;
	}
	// Important to restore initial pos
	query.seek(initialPos);
	return pos;
}

void StewardSoft::TableInit(QString tableName ,QTableWidget *tabWidget)
{
	//建立并打開資料庫
	QSqlDatabase database;
	database = QSqlDatabase::addDatabase("QSQLITE");
	database.setDatabaseName("MyDataBase.db");
	if (!database.open())
	{
		qDebug() << "Error: Failed to connect database." << database.lastError();
	}
	else
	{
		qDebug() << "Succeed to connect database.";
	}
	QSqlQuery sql_query(database);
	int newTableRowCount = 0;
	int sqlResultCount = 0;
	//查詢所有資料
	sql_query.prepare("select * from " + tableName);
	if (!sql_query.exec())
	{
		qDebug() << sql_query.lastError();
	}
	else
	{
		newTableRowCount = queryRowCount(sql_query);
		qDebug() << "sql_query size: " << newTableRowCount;
		tabWidget->setRowCount(newTableRowCount);
		while (sql_query.next())
		{
			QString userName = sql_query.value(0).toString();
			QString userPwd = sql_query.value(1).toString();
			QString privilege = sql_query.value(2).toString();
			QString creator = sql_query.value(3).toString();
			qDebug() << QString("one:%1    two:%2    three:%3     four:%4").arg(userName).arg(userPwd).arg(privilege).arg(creator);
			QList<QString> *list = new QList<QString>;
			list->append(userName);			
			if (userPrivilege == 1 && tableName.compare("user") == 0)
			{
				list->append(userPwd);
			}
			else if (userPrivilege != 1 && tableName.compare("user") == 0)
			{
				list->append("****");
			}
			else
			{
				list->append(userPwd);
			}
			list->append(privilege);
			list->append(creator);
			for (int i = 0; i < list->size(); i++)
			{
				QTableWidgetItem *item = new QTableWidgetItem();
				item->setTextAlignment(Qt::AlignCenter);
				item->setText(list->at(i));
			
				//if (i == 1)
				//{
				//	/*qDebug() << "sqlResultCount: " << sqlResultCount << " ,i : " << i;
				//	QPushButton *showPwd = new QPushButton;
				//	showPwd->setText(tr("顯示密碼"));
				//	ui.user_manage_table->setCellWidget(sqlResultCount, 1, showPwd);*/
				//	item->setText("******");
				//	ui.user_manage_table->setItem(sqlResultCount, i, item);
				//}
				//else
				//{
				//	ui.user_manage_table->setItem(sqlResultCount, i, item);
				//}
				tabWidget->setItem(sqlResultCount, i, item);
			}
			sqlResultCount++;
		}
	 }
	//關閉資料庫
	database.close();
}

//customer表和user表的添加
void StewardSoft::TableInsert(QString tableName, QList<QString> valueList)
{
	qDebug() << tr("表名:") << tableName << tr("内容個數:") << valueList.size();
	for (QString value : valueList)
	{
		qDebug() << tr("值:") << value;
	}
	//建立并打開資料庫
	QSqlDatabase database;
	database = QSqlDatabase::addDatabase("QSQLITE");
	database.setDatabaseName("MyDataBase.db");
	if (!database.open())
	{
		qDebug() << "Error: Failed to connect database." << database.lastError();
	}
	else
	{
		qDebug() << "Succeed to connect database.";
	}
	QSqlQuery sql_query(database);
	

	//插入資料
	QString s = "insert into " + tableName +" values (?,?,?,?)";
	qDebug() << "sql query:" << s;
	sql_query.prepare(s);
	for (QString value : valueList)
	{
		qDebug() << "---" << value;
		sql_query.addBindValue(value);
	}
	if (!sql_query.exec())
	{
		qDebug() << sql_query.lastError();
		QMessageBox::warning(NULL, tr("警告"), tr("資訊重複,請檢查添加資訊唯一性"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
	}
	else
	{
		qDebug() << "insert success";
		//查詢所有資料
		if (tableName == "user")
		{
			TableInit(tableName, ui.userManageTable);
		}
		if (tableName == "customer")
		{
			TableInit(tableName, ui.customerManageTable);
		}
		
	}

	if (sql_query.next() == false)
	{
		qDebug() << "return null:" << sql_query.next();

	}
	//關閉資料庫
	database.close();
}



void StewardSoft::update_menuBar_value(QString name)
{
	username = name;
	qDebug() << "--- user name : " << name;
	if (username != NULL)
	{
		//ui.menuadmin->setTitle(username);
		ui.loginUserBtn->setText(username);
		menu->setTitle(username);
	}
}

void StewardSoft::createActions()
{
	//設定快捷鍵
	action_flush->setShortcut(QKeySequence::Refresh);
}


void StewardSoft::contextMenuEvent(QContextMenuEvent *event)
{
	//目前點選的表格
	QString currentTableName = ui.mainTab->tabText(ui.mainTab->currentIndex());
	QPoint manageTablePos;
	QRect rect;
	qDebug() << tr("目前表名:") << currentTableName;
	if (currentTableName.compare(tr("使用者管理")) == 0)
	{
		manageTablePos = ui.userManageTable->mapFromGlobal(event->globalPos());
		QRect rect1(QPoint(0, 0), ui.userManageTable->size());
		rect = rect1;
	}
	if (currentTableName.compare(tr("客戶管理")) == 0)
	{
		manageTablePos = ui.customerManageTable->mapFromGlobal(event->globalPos());
		QRect rect1(QPoint(0, 0), ui.customerManageTable->size());
		rect = rect1;
	}
	if (currentTableName.compare(tr("商品管理")) == 0)
	{
		manageTablePos = ui.commodityManageTable->mapFromGlobal(event->globalPos());
		QRect rect1(QPoint(0, 0), ui.commodityManageTable->size());
		rect = rect1;
	}
	qDebug() << "manageTablePos is NULL?:" << (manageTablePos.isNull()) << "rect is NULL?: " << rect.isNull();
	if (!rect.contains(manageTablePos))
	{
		return;
	}

	qDebug() << tr("進來了");
	QPoint point = event->pos(); //得到視窗坐标
	qDebug() << tr("table is ") << ui.mainTab->tabText(ui.mainTab->currentIndex());
	//qDebug() << event->
	pop_menu->clear(); //清除原有菜單
	pop_menu->addAction(action_add);//添加
	pop_menu->addAction(action_copy);//複制
	pop_menu->addSeparator();
	pop_menu->addAction(action_delete); //删除
	pop_menu->addAction(action_modification);//修改
	
	//菜單出現的位置為目前滑鼠的位置
	pop_menu->exec(QCursor::pos());
	event->accept();

}

//添加動作
void StewardSoft::actions()
{
	pop_menu = new QMenu(); //建立菜單項
	action_delete->setText(tr("删除"));
	action_modification->setText(tr("修改"));
	action_copy->setText(tr("複制"));
	action_add->setText(tr("添加"));
}

int StewardSoft::deleteDate(QString tableName, QString name, QTableWidget *tableWidget)
{
	qDebug() << tr("要删除資料了,看下删除者的權限: ") << userPrivilege;

	if (userPrivilege != 1)
	{
		QMessageBox::warning(NULL, tr("删除警告"), tr("您的權限不夠,無法删除資料!"), QMessageBox::Yes | QMessageBox::No);
		return -1;
	}
	//建立并打開資料庫
	QSqlDatabase database;
	database = QSqlDatabase::addDatabase("QSQLITE");
	database.setDatabaseName("MyDataBase.db");
	if (!database.open())
	{
		qDebug() << "Error: Failed to connect database." << database.lastError();
	}
	else
	{
		qDebug() << "Succeed to connect database.";
	}
	QSqlQuery sql_query(database);

	//删除資料
	if (tableName == "user")
	{
		sql_query.prepare("delete from " + tableName + " where	name= '" + name + "'");
	}
	if (tableName == "customer")
	{
		sql_query.prepare("delete from " + tableName + " where	CustomerName= '" + name + "'");
	}
	if (tableName == "commodity")
	{
		sql_query.prepare("delete from " + tableName + " where	commodityEquitmentNumber= '" + name + "'");
	}
	
	if (!sql_query.exec())
	{
		qDebug() << sql_query.lastError();
	}
	else
	{
		qDebug() << tr("登入賬戶删除成功!");
		QMessageBox::information(NULL, tr("結果"), name + tr("删除成功"), QMessageBox::Ok);
	
		//關閉資料庫
		database.close();
		//查詢所有資料
		TableInit(tableName, tableWidget);
		return 1;
	}
	//關閉資料庫
	database.close();
	return -1;
}

//右鍵動作被按下
void StewardSoft::actionClick()
{
	qDebug() << "actionClick here";
}

//排序,從大到小
bool Comp(const int &a, const int  &b)
{
	return a > b;
}
//删除
void StewardSoft::actionDeleteClick()
{
	qDebug() << tr("目前登陸者權限為:") << userPrivilege;
	if (userPrivilege != 1)
	{
		QMessageBox::about(NULL, tr("警告"), tr("目前登陸者權限不可删除資料"));
		return;
	}
	//TODO: 在退出視窗之前,實作希望做的操作 
	QMessageBox::StandardButton r = QMessageBox::question(this, tr("删除提示"), tr("确定删除資料?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
	if (r == QMessageBox::No)
	{
		return;
	}
	else if(r == QMessageBox::Yes)
	{
		qDebug() << tr("删除資料");
		QString currentTab = ui.mainTab->tabText(ui.mainTab->currentIndex());
		if (currentTab == tr("使用者管理"))
		{
			QList<QTableWidgetSelectionRange>ranges = ui.userManageTable->selectedRanges();
			int count = ranges.count();
			QVector<int> vec;
			for (int i = 0; i < count; i++)
			{
				int topRow = ranges.at(i).topRow();
				int bottomRow = ranges.at(i).bottomRow();
				for (int j = topRow; j <= bottomRow; j++)
				{
					qDebug() << "selectRow:" << j;
					vec.push_back(j);
				}
			}
			std::sort(vec.begin(), vec.end(), Comp);
			for (int k = 0; k < vec.size(); k++)
			{
				qDebug() << "從大到小:" << vec[k];
				QString needDeleteUser = ui.userManageTable->item(vec[k], 0)->text();
				qDebug() << tr("目前要删除的使用者: ") << needDeleteUser;
				deleteDate("user", needDeleteUser, ui.userManageTable);
			}
			
			/*QTableWidgetItem *currentItem = ui.userManageTable->currentItem();
			QString needDeleteUser = ui.userManageTable->item(currentItem->row(), 0)->text();
			qDebug() << tr("目前要删除的使用者: ") << ui.userManageTable->item(currentItem->row(), 0)->text();
			deleteDate("user", needDeleteUser, ui.userManageTable);*/
		}
		if (currentTab == tr("客戶管理"))
		{
			QTableWidgetItem *currentItem = ui.customerManageTable->currentItem();
			QString needDeleteUser = ui.customerManageTable->item(currentItem->row(), 0)->text();
			qDebug() << tr("目前要删除的客戶: ") << ui.customerManageTable->item(currentItem->row(), 0)->text();
			deleteDate("customer", needDeleteUser, ui.customerManageTable);
		}
		if (currentTab == tr("商品管理"))
		{
			QTableWidgetItem *currentItem = ui.commodityManageTable->currentItem();
			QString needDeleteUser = ui.commodityManageTable->item(currentItem->row(), 1)->text();
			qDebug() << tr("目前要删除的商品: ") << ui.commodityManageTable->item(currentItem->row(), 0)->text();
			deleteDate("commodity", needDeleteUser, ui.commodityManageTable);
		}
	}
}

//修改
void StewardSoft::actionModificationClick()
{
	QString currentTabName = ui.mainTab->tabText(ui.mainTab->currentIndex());
	qDebug() << "actionModificationClick here " << currentTabName;
	qDebug() << tr("目前登陸者權限為:") << userPrivilege;
	if (currentTabName == tr("使用者管理"))
	{
		qDebug() << tr("修改使用者管理");
		
		int row = ui.userManageTable->currentItem()->row();
		qDebug() << tr("要修改的使用者權限等級:") << ui.userManageTable->item(row, 2)->text().toInt();
		if (userPrivilege == 1)
		{
			userManageChangeInfo->ui.userManageChangeInfoNameLE->setText(ui.userManageTable->item(row, 0)->text()); //賬戶
			userManageChangeInfo->ui.userManageChangeInfoPwdLE->setText(ui.userManageTable->item(row, 1)->text()); //密碼
			userManageChangeInfo->ui.userManageChangeInfoPrivilegeLE->setText(ui.userManageTable->item(row, 2)->text()); //權限等級
			//userManageChangeInfo->ui.userManageChangeInfoCreatorLE->setText(ui.menuadmin->title()); //建立人
			userManageChangeInfo->ui.userManageChangeInfoCreatorLE->setText(ui.loginUserBtn->text()); //建立人
			userManageChangeInfo->ui.userManageChangeInfoNameLE->setEnabled(false);
			userManageChangeInfo->isAddNewData = false;
			userManageChangeInfo->currentUserPrivilege = userPrivilege;
			userManageChangeInfo->exec();
		}
		else
		{
			QMessageBox::information(NULL, tr("提示"), tr("目前使用者不可更改登入表資訊"), QMessageBox::Ok);
		}
		
	}
	if (currentTabName == tr("客戶管理"))
	{
		qDebug() << tr("修改客戶管理");
		int row = ui.customerManageTable->currentItem()->row();
		customerChangeInfo->ui.changeContentNameLE->setText(ui.customerManageTable->item(row, 0)->text()); //客戶姓名
		customerChangeInfo->ui.changeContentPhoneLE->setText(ui.customerManageTable->item(row, 1)->text()); //客戶聯系方式
		customerChangeInfo->ui.changeContentAreaLE->setText(ui.customerManageTable->item(row, 2)->text()); //地區
		customerChangeInfo->ui.changeContentElseTE->setText(ui.customerManageTable->item(row, 3)->text()); //備注資訊
		customerChangeInfo->ischangeFlag = true;
		customerChangeInfo->ui.changeContentNameLE->setEnabled(false);
		customerChangeInfo->exec();
	}
	
	if (currentTabName == tr("商品管理"))
	{
		qDebug() << tr("修改商品管理");
		int row = ui.commodityManageTable->currentItem()->row();
		commmodityManagechangeInfo->ui.commmodityManageChangeInfoNameLE->setText(ui.commodityManageTable->item(row, 0)->text()); //商品名稱
		commmodityManagechangeInfo->ui.commmodityManageChangeInfoEquitmentLE->setText(ui.commodityManageTable->item(row, 1)->text()); //裝置号
		commmodityManagechangeInfo->ui.commmodityManageChangeInfoPropertyLE->setText(ui.commodityManageTable->item(row, 2)->text()); //屬性
		commmodityManagechangeInfo->ui.commmodityManageChangeInfoElseTE->setText(ui.commodityManageTable->item(row, 3)->text()); //備注資訊
		commmodityManagechangeInfo->ui.commmodityManageChangeInfoEquitmentLE->setEnabled(false);
		commmodityManagechangeInfo->isChangeFlag = true;
		commmodityManagechangeInfo->exec();
	}
}

//複制
void StewardSoft::actionCopyClick()
{
	qDebug() << "actionCopyClick here";
	QString currentTabName = ui.mainTab->tabText(ui.mainTab->currentIndex());
	int tableCurrentRow = 0;
	QString copyContent = "";
	if (currentTabName.compare(tr("使用者管理")) == 0)
	{
		tableCurrentRow = ui.userManageTable->currentRow();
		copyContent =tr("使用者名:") + ui.userManageTable->item(tableCurrentRow, 0)->text();  //使用者名:admin
	}
	if (currentTabName.compare(tr("客戶管理")) == 0) 
	{
		tableCurrentRow = ui.customerManageTable->currentRow();
		QString name = ui.customerManageTable->item(tableCurrentRow, 0)->text();
		QString phoneNum = ui.customerManageTable->item(tableCurrentRow, 1)->text();
		QString area = ui.customerManageTable->item(tableCurrentRow, 2)->text();
		QString elseInfo = ui.customerManageTable->item(tableCurrentRow, 3)->text();
		copyContent = tr("客戶姓名:") + name + tr(" 聯系方式:") + phoneNum + tr(" 客戶所在地區:") + area + tr(" 備注資訊:") + elseInfo;
	}
	if (currentTabName.compare(tr("商品管理")) == 0) 
	{
		tableCurrentRow = ui.commodityManageTable->currentRow();
		QString name = ui.commodityManageTable->item(tableCurrentRow, 0)->text();
		QString equipmentNum = ui.commodityManageTable->item(tableCurrentRow, 1)->text();
		QString commodityProperty = ui.commodityManageTable->item(tableCurrentRow, 2)->text();
		QString elseInfo = ui.commodityManageTable->item(tableCurrentRow, 3)->text();
		copyContent = tr("商品名稱:") + name + tr(" 商品裝置号:") + equipmentNum + tr(" 商品屬性:") + commodityProperty + tr(" 備注資訊:") + elseInfo;
	}
	QClipboard *clipboard = QApplication::clipboard();   //擷取系統剪貼闆指針
	QString originalText = clipboard->text();         //擷取剪貼闆上文本資訊
	clipboard->setText(copyContent);                     //設定剪貼闆内容</span>
	QMessageBox::about(NULL, tr("複制資訊"), tr("内容已複制到剪切闆,\n按ctrl + v即可粘貼文本或滑鼠右鍵也可粘貼。")); 
}

//添加
void StewardSoft::actionAddClick()
{
	qDebug() << tr("添加菜單,目前頁卡是:") << ui.mainTab->tabText(ui.mainTab->currentIndex());
	if (ui.mainTab->tabText(ui.mainTab->currentIndex()).compare(tr("使用者管理")) == 0)
	{
		qDebug() << tr("彈出使用者管理添加小界面 start");
		//userManageChangeInfo = new UserManageChangeInfo(this);
		connect(userManageChangeInfo, SIGNAL(AddNew()), this, SLOT(AddNewSlot()));
		//userManageChangeInfo->ui.userManageChangeInfoCreatorLE->setText(ui.menuadmin->title()); //建立人
		userManageChangeInfo->ui.userManageChangeInfoCreatorLE->setText(ui.loginUserBtn->text()); //建立人
		userManageChangeInfo->isAddNewData = true;
		userManageChangeInfo->ui.userManageChangeInfoNameLE->setText("");
		userManageChangeInfo->ui.userManageChangeInfoPwdLE->setText("");
		userManageChangeInfo->ui.userManageChangeInfoPrivilegeLE->setText("");
		userManageChangeInfo->exec();
		qDebug() << tr("彈出使用者管理添加小界面 end");
	}
	if (ui.mainTab->tabText(ui.mainTab->currentIndex()).compare(tr("客戶管理")) == 0)
	{
		qDebug() << tr("客戶管理");
		customerChangeInfo->ui.changeContentNameLE->setText("");
		customerChangeInfo->ui.changeContentPhoneLE->setText("");
		customerChangeInfo->ui.changeContentAreaLE->setText("");
		customerChangeInfo->ui.changeContentElseTE->setText("");
		customerChangeInfo->ischangeFlag = false;
		customerChangeInfo->ui.changeContentNameLE->setEnabled(true);
		customerChangeInfo->exec();
	}
	if (ui.mainTab->tabText(ui.mainTab->currentIndex()).compare(tr("商品管理")) == 0)
	{
		qDebug() << tr("商品管理");
		commmodityManagechangeInfo->ui.commmodityManageChangeInfoNameLE->setText("");
		commmodityManagechangeInfo->ui.commmodityManageChangeInfoEquitmentLE->setText("");
		commmodityManagechangeInfo->ui.commmodityManageChangeInfoPropertyLE->setText("");
		commmodityManagechangeInfo->ui.commmodityManageChangeInfoElseTE->setText("");
		commmodityManagechangeInfo->isChangeFlag = false;
		commmodityManagechangeInfo->ui.commmodityManageChangeInfoEquitmentLE->setEnabled(true);
		commmodityManagechangeInfo->exec();
	}
}

void StewardSoft::AddNewSlot()
{

	//查詢所有資料
	TableInit("user", ui.userManageTable);
	qDebug() << "ui.userManageTable->rowCount(): " << ui.userManageTable->rowCount();
	ui.userManageTable->selectRow(ui.userManageTable->rowCount());
	qDebug() << tr("添加成功");
}

//導出資料到excel
void StewardSoft::exportDataToExcel()
{
	QString currentTableName = ui.mainTab->tabText(ui.mainTab->currentIndex());
	QString tableName = "";
	QTableWidget *currentTable;
	if (currentTableName.compare(tr("使用者管理")) == 0)
	{
		tableName = "user";
		currentTable = ui.userManageTable;
	}
	if (currentTableName.compare(tr("客戶管理")) == 0)
	{
		tableName = "customer";
		currentTable = ui.customerManageTable;
	}
	if (currentTableName.compare(tr("商品管理")) == 0)
	{
		tableName = "commodity";
		currentTable = ui.commodityManageTable;
	}
	qDebug() << tr("目前表名:") << tableName;
	Table2ExcelByHtml(currentTable, currentTableName);
}



void StewardSoft::on_userManageTable_currentItemChanged(QTableWidgetItem *current, QTableWidgetItem *previous)
{
	//qDebug() << tr("目前item是:") << current->text() << tr("行:") << current->row() << tr("列:") << current->column();
	
}

void StewardSoft::UpdateUserManageInfo()
{
	//查詢所有資料
	if ((ui.mainTab->tabText(ui.mainTab->currentIndex())).compare(tr("使用者管理")) == 0)
	{
		TableInit("user", ui.userManageTable);
		ui.userManageTable->selectRow(ui.userManageTable->rowCount());
	}
	if ((ui.mainTab->tabText(ui.mainTab->currentIndex())).compare(tr("客戶管理")) == 0)
	{
		TableInit("customer", ui.customerManageTable);
		ui.customerManageTable->selectRow(ui.customerManageTable->rowCount());
	}
	if ((ui.mainTab->tabText(ui.mainTab->currentIndex())).compare(tr("商品管理")) == 0)
	{
		TableInit("commodity", ui.commodityManageTable);
		ui.commodityManageTable->selectRow(ui.commodityManageTable->rowCount());
	}
	
}

bool StewardSoft::eventFilter(QObject *obj, QEvent *e)
{
	if (obj == ui.mainTtile)
	{
		if (e->type() == QEvent::MouseButtonDblClick)
		{
			on_mainBtnMax_clicked();
			return true;
		}
	}
	return QObject::eventFilter(obj, e);
}

void StewardSoft::mousePressEvent(QMouseEvent *event)
{
	/*if (e->button() == Qt::LeftButton)
	{
		mDrag = true;
		mDragPos = e->globalPos() - pos();
		e->accept();
	}*/
	if (event->button() == Qt::LeftButton)
	{
		this->_isleftpressed = true;
		QPoint temp = event->globalPos();
		_plast = temp;
		_curpos = countFlag(event->pos(), countRow(event->pos()));
		event->ignore();
	}
}

void StewardSoft::mouseMoveEvent(QMouseEvent *event)
{
	if (mDrag && (event->buttons() && Qt::LeftButton))
	{
		move(event->globalPos() - mDragPos);
		event->accept();
	}
	int poss = countFlag(event->pos(), countRow(event->pos()));
	setCursorType(poss);
	if (_isleftpressed)//是否左擊
	{
		QPoint ptemp = event->globalPos();
		ptemp = ptemp - _plast;
		if (_curpos == 22)//移動視窗
		{
			ptemp = ptemp + pos();
			move(ptemp);
		}
		else
		{
			QRect wid = geometry();
			switch (_curpos)//改變視窗的大小
			{

			case 11:wid.setTopLeft(wid.topLeft() + ptemp); break;//左上角
			case 13:wid.setTopRight(wid.topRight() + ptemp); break;//右上角
			case 31:wid.setBottomLeft(wid.bottomLeft() + ptemp); break;//左下角
			case 33:wid.setBottomRight(wid.bottomRight() + ptemp); break;//右下角
			case 12:wid.setTop(wid.top() + ptemp.y()); break;//中上角
			case 21:wid.setLeft(wid.left() + ptemp.x()); break;//中左角
			case 23:wid.setRight(wid.right() + ptemp.x()); break;//中右角
			case 32:wid.setBottom(wid.bottom() + ptemp.y()); break;//中下角
			}
			setGeometry(wid);
		}

		_plast = event->globalPos();//更新位置
	}
	event->ignore();
}

void StewardSoft::mouseReleaseEvent(QMouseEvent *event)
{
	/*mDrag = false;*/
	if (_isleftpressed)
		_isleftpressed = false;
	setCursor(Qt::ArrowCursor);
	event->ignore();
}

void StewardSoft::mouseDoubleClickEvent(QMouseEvent *event)
{
	if (event->button() == Qt::LeftButton)
	{
		if (windowState() != Qt::WindowFullScreen)
			setWindowState(Qt::WindowFullScreen);
		else setWindowState(Qt::WindowNoState);//恢複正常模式
	}
	event->ignore();
}

int StewardSoft::countFlag(QPoint p, int row)//計算滑鼠在哪一列和哪一行
{
	if (p.y()<MARGIN)
		return 10 + row;
	else if (p.y()>this->height() - MARGIN)
		return 30 + row;
	else
		return 20 + row;
}

void StewardSoft::setCursorType(int flag)//根據滑鼠所在位置改變滑鼠指針形狀
{
	Qt::CursorShape cursor;
	switch (flag)
	{
	case 11:
	case 33:
		cursor = Qt::SizeFDiagCursor; break;
	case 13:
	case 31:
		cursor = Qt::SizeBDiagCursor; break;
	case 21:
	case 23:
		cursor = Qt::SizeHorCursor; break;
	case 12:
	case 32:
		cursor = Qt::SizeVerCursor; break;
	case 22:
		//cursor = Qt::OpenHandCursor; break;
		cursor = Qt::ArrowCursor; break;
	default:
		cursor = Qt::ArrowCursor; break;
		break;

	}
	setCursor(cursor);
}

int StewardSoft::countRow(QPoint p)//計算在哪一列
{
	
	return (p.x()<MARGIN) ? 1 : (p.x()>(this->width() - MARGIN) ? 3 : 2);
}

void StewardSoft::on_mainBtnMin_clicked()
{
	showMinimized();
}

void StewardSoft::on_mainBtnMax_clicked()
{
	if (mIsMax)
	{
		setGeometry(mLocation);
		ui.mainBtnMax->setIcon(QIcon("./img/max1.png"));
		ui.mainBtnMax->setToolTip(QStringLiteral("最大化"));
	}
	else
	{
		mLocation = geometry();
		setGeometry(qApp->desktop()->availableGeometry());
		ui.mainBtnMax->setIcon(QIcon("./img/max2.png"));
		ui.mainBtnMax->setToolTip(QStringLiteral("還原"));
	}
	mIsMax = !mIsMax;
}

void StewardSoft::on_mainBtnClose_clicked()
{
	QMessageBox::StandardButton r = QMessageBox::question(this, tr("提示"), tr("确定退出?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
	if (r == QMessageBox::Yes) 
	{
		qApp->exit();
	}
}

/**
* @func:    on_addDataBtn_clicked
* @brief:   用于測試Model添加資料用
* @author:  xxx  
* @param:   void
* @return:  void
*/
void StewardSoft::on_addDataBtn_clicked()
{
	QTime t;
	qDebug() << t.currentTime().toString("hh:mm:ss:zzz");

	QVector<TableInfo> vec;
	for (int i = 0; i < 100; i++)
	{
		TableInfo info;
		info.szName = "name,name1,name2,name3,name4" + QString::number(i);
		info.szdsName = "dsname,dsname1,dsname2,dsname3,dsname4,dsname5" + QString::number(i);
		info.szdo = "do,do1,do2,do3,do4,do5" + QString::number(i);
		info.check = 0;
		vec.push_back(info);
		qApp->processEvents();
	}
	myModel->setInputData(vec);
	QTime t1;
	qDebug() << t1.currentTime().toString("hh:mm:ss:zzz");
}

void StewardSoft::leaveEvent(QEvent* event)
{
	QTableWidgetItem *item = 0;
	if (ui.mainTab->tabText(ui.mainTab->currentIndex()).compare(tr("使用者管理")) == 0)
	{
		//還原上一行的顔色
		item = ui.userManageTable->item(previousColorRow, 0);
		if (item != 0)
		{
			this->setRowColor(previousColorRow, lastRowBKColor);
		}
	}
	if (ui.mainTab->tabText(ui.mainTab->currentIndex()).compare(tr("客戶管理")) == 0)
	{
		//還原上一行的顔色
		item = ui.customerManageTable->item(previousColorRow, 0);
		if (item != 0)
		{
			this->setRowColor(previousColorRow, lastRowBKColor);
		}
	}
	if (ui.mainTab->tabText(ui.mainTab->currentIndex()).compare(tr("商品管理")) == 0)
	{
		//還原上一行的顔色
		item = ui.commodityManageTable->item(previousColorRow, 0);
		if (item != 0)
		{
			this->setRowColor(previousColorRow, lastRowBKColor);
		}
	}
	
}

void StewardSoft::mycellEntered(int row, int column)
{
	QTableWidgetItem *item = 0;
	QTableWidget *currentTableWidget;
	if (ui.mainTab->tabText(ui.mainTab->currentIndex()).compare(tr("使用者管理")) == 0)
	{
		//還原上一行的顔色
		item = ui.userManageTable->item(previousColorRow, 0);
		currentTableWidget = ui.userManageTable;
		if (item != 0)
		{
			this->setRowColor(previousColorRow, lastRowBKColor);
		}
	}
	if (ui.mainTab->tabText(ui.mainTab->currentIndex()).compare(tr("客戶管理")) == 0)
	{
		//還原上一行的顔色
		item = ui.customerManageTable->item(previousColorRow, 0);
		currentTableWidget = ui.customerManageTable;
		if (item != 0)
		{
			this->setRowColor(previousColorRow, lastRowBKColor);
		}
	}
	if (ui.mainTab->tabText(ui.mainTab->currentIndex()).compare(tr("商品管理")) == 0)
	{
		//還原上一行的顔色
		item = ui.commodityManageTable->item(previousColorRow, 0);
		currentTableWidget = ui.commodityManageTable;
		if (item != 0)
		{
			this->setRowColor(previousColorRow, lastRowBKColor);
		}
	}

	//設定目前行的顔色
	item = currentTableWidget->item(row, column);
	if (item != 0 && !item->isSelected())
	{
		this->setRowColor(row, QColor(193, 210, 240));
	}

	//設定行的索引
	previousColorRow = row;
}

void StewardSoft::setRowColor(int row, QColor color)
{
	QTableWidget *currentTableWidget;
	if (ui.mainTab->tabText(ui.mainTab->currentIndex()).compare(tr("使用者管理")) == 0)
	{		
		currentTableWidget = ui.userManageTable;		
	}
	if (ui.mainTab->tabText(ui.mainTab->currentIndex()).compare(tr("客戶管理")) == 0)
	{		
		currentTableWidget = ui.customerManageTable;		
	}
	if (ui.mainTab->tabText(ui.mainTab->currentIndex()).compare(tr("商品管理")) == 0)
	{		
		currentTableWidget = ui.commodityManageTable;
	}
	if (currentTableWidget == NULL)
	{
		return;
	}
	for (int col = 0; col < currentTableWidget->columnCount(); col++)
	{
		QTableWidgetItem *item = currentTableWidget->item(row, col);
		item->setBackgroundColor(color);
	}
}

           

3.修改内容的彈窗 ChangeContent.cpp

#include "ChangeContent.h"
#include <QToolTip>

#define tr QString::fromLocal8Bit

ChangeContent::ChangeContent(QWidget *parent)
	: QDialog(parent)
{
	Qt::WindowFlags flags = Qt::Dialog;
	flags |= Qt::WindowCloseButtonHint;
	setWindowFlags(flags);
	// 取消邊框
	setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
	ui.setupUi(this);
	ui.changeContentNameLE->setText("");
	ui.changeContentPhoneLE->setText("");
	ui.changeContentAreaLE->setText("");
	ui.changeContentElseTE->setText("");
	connect(ui.changeContentElseTE, SIGNAL(returnPressed()), ui.changeContentSureBtn, SIGNAL(clicked()), Qt::UniqueConnection);
}

ChangeContent::~ChangeContent()
{
	delete& ui;
}


void ChangeContent::Table2ExcelByHtml(QTableWidget *table, QString title)
{
	QString fileName = QFileDialog::getSaveFileName(table, "儲存", QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation), "Excel 檔案(*.xls *.xlsx)");
	if (fileName != "")
	{
		QAxObject *excel = new QAxObject;
		if (excel->setControl("Excel.Application")) //連接配接Excel控件
		{
			excel->dynamicCall("SetVisible (bool Visible)", "false");//不顯示窗體
			excel->setProperty("DisplayAlerts", false);//不顯示任何警告資訊。如果為true那麼在關閉是會出現類似“檔案已修改,是否儲存”的提示
			QAxObject *workbooks = excel->querySubObject("WorkBooks");//擷取工作簿集合
			workbooks->dynamicCall("Add");//建立一個工作簿
			QAxObject *workbook = excel->querySubObject("ActiveWorkBook");//擷取目前工作簿
			QAxObject *worksheet = workbook->querySubObject("Worksheets(int)", 1);

			int i, j;
			//QTablewidget 擷取資料的列數
			int colcount = table->columnCount();
			//QTablewidget 擷取資料的行數
			int rowscount = table->rowCount();

				//QTableView 擷取列數
				//int colount=ui->tableview->model->columnCount();
				//QTableView 擷取行數
				//int rowcount=ui->tableview->model->rowCount();

				QAxObject *cell, *col;
			//标題行
			cell = worksheet->querySubObject("Cells(int,int)", 1, 1);
			cell->dynamicCall("SetValue(const QString&)", title);
			cell->querySubObject("Font")->setProperty("Size", 18);
			//調整行高
			worksheet->querySubObject("Range(const QString&)", "1:1")->setProperty("RowHeight", 30);
			//合并标題行
			QString cellTitle;
			cellTitle.append("A1:");
			cellTitle.append(QChar(colcount - 1 + 'A'));
			cellTitle.append(QString::number(1));
			QAxObject *range = worksheet->querySubObject("Range(const QString&)", cellTitle);
			range->setProperty("WrapText", true);
			range->setProperty("MergeCells", true);
			range->setProperty("HorizontalAlignment", -4108);//xlCenter
			range->setProperty("VerticalAlignment", -4108);//xlCenter
			//列标題
			for (i = 0; i < colcount; i++)
			{
				QString columnName;
				columnName.append(QChar(i + 'A'));
				columnName.append(":");
				columnName.append(QChar(i + 'A'));
				col = worksheet->querySubObject("Columns(const QString&)", columnName);
				col->setProperty("ColumnWidth", table->columnWidth(i) / 6);
				cell = worksheet->querySubObject("Cells(int,int)", 2, i + 1);
				//QTableWidget 擷取表格頭部文字資訊
				columnName = table->horizontalHeaderItem(i)->text();
				//QTableView 擷取表格頭部文字資訊
				// columnName=ui->tableView_right->model()->headerData(i,Qt::Horizontal,Qt::DisplayRole).toString();
				cell->dynamicCall("SetValue(const QString&)", columnName);
				cell->querySubObject("Font")->setProperty("Bold", true);
				cell->querySubObject("Interior")->setProperty("Color", QColor(191, 191, 191));
				cell->setProperty("HorizontalAlignment", -4108);//xlCenter
				cell->setProperty("VerticalAlignment", -4108);//xlCenter
			}

			//資料區

			//QTableWidget 擷取表格資料部分
			for (i = 0; i < rowscount; i++){
				for (j = 0; j < colcount; j++)
				{
					worksheet->querySubObject("Cells(int,int)", i + 3, j + 1)->dynamicCall("SetValue(const QString&)", table->item(i, j) ? table->item(i, j)->text() : "");
				}
			}
			//QTableView 擷取表格資料部分
			//  for(i=0;i<rowcount;i++) //行數
			//     {
			//         for (j=0;j<colcount;j++)   //列數
			//         {
			//             QModelIndex index = ui->tableView_right->model()->index(i, j);
			//             QString strdata=ui->tableView_right->model()->data(index).toString();
			//             worksheet->querySubObject("Cells(int,int)", i+3, j+1)->dynamicCall("SetValue(const QString&)", strdata);
			//         }
			//     }


			//畫框線
			QString lrange;
			lrange.append("A2:");
			lrange.append(colcount - 1 + 'A');
			lrange.append(QString::number(table->rowCount() + 2));
			range = worksheet->querySubObject("Range(const QString&)", lrange);
			range->querySubObject("Borders")->setProperty("LineStyle", QString::number(1));
			range->querySubObject("Borders")->setProperty("Color", QColor(0, 0, 0));
			//調整資料區行高
			QString rowsName;
			rowsName.append("2:");
			rowsName.append(QString::number(table->rowCount() + 2));
			range = worksheet->querySubObject("Range(const QString&)", rowsName);
			range->setProperty("RowHeight", 20);
			workbook->dynamicCall("SaveAs(const QString&)", QDir::toNativeSeparators(fileName));//儲存至fileName
			workbook->dynamicCall("Close()");//關閉工作簿
			excel->dynamicCall("Quit()");//關閉excel
			delete excel;
			excel = NULL;
			if (QMessageBox::question(NULL, "完成", "檔案已經導出,是否現在打開?", QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)
			{
				QDesktopServices::openUrl(QUrl("file:///" + QDir::toNativeSeparators(fileName)));
			}
		}
		else
		{
			QMessageBox::warning(NULL, "錯誤", "未能建立 Excel 對象,請安裝 Microsoft Excel。", QMessageBox::Apply);
		}
	}
}

void ChangeContent::closeEvent(QCloseEvent *event)
{

	if (ui.changeContentBtnClose->isDefault())
	{
		//TODO: 在退出視窗之前,實作希望做的操作 
		QMessageBox::StandardButton r = QMessageBox::question(this, tr("提示"), tr("确定退出?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
		if (r == QMessageBox::Yes)
		{
			event->accept();
		}
		else
		{
			event->ignore();
		}
	}
	else
	{
		return;
	}
}

void ChangeContent::mousePressEvent(QMouseEvent *e)
{
	if (e->button() == Qt::LeftButton)
	{
		mDrag = true;
		mDragPos = e->globalPos() - pos();
		e->accept();
	}
}

void ChangeContent::mouseMoveEvent(QMouseEvent *e)
{
	if (mDrag && (e->buttons() && Qt::LeftButton))
	{
		move(e->globalPos() - mDragPos);
		e->accept();
	}
}

void ChangeContent::mouseReleaseEvent(QMouseEvent *event)
{
	mDrag = false;
}

void ChangeContent::on_changeContentBtnMin_clicked()
{
	showMinimized();
}

void ChangeContent::on_changeContentBtnClose_clicked()
{
	this->close();
}

void ChangeContent::on_changeContentSureBtn_clicked()
{
	qDebug() << "clicked login_btn";
	if (ui.changeContentNameLE->text() == "" || ui.changeContentPhoneLE->text() == "")
	{
		if (ui.changeContentNameLE->text() == "")
		{
			QToolTip::showText(ui.changeContentNameLE->mapToGlobal(QPoint(100, 0)), tr("您輸入的賬戶為空,請重新輸入!"));
		}
		if (ui.changeContentPhoneLE->text() == "")
		{
			QToolTip::showText(ui.changeContentPhoneLE->mapToGlobal(QPoint(100, 0)), tr("您輸入的客戶電話為空,請重新輸入!"));
		}
		return;
	}
	else
	{
		QString customerName = ui.changeContentNameLE->text();
		QString customerPhone = ui.changeContentPhoneLE->text();
		QString customerArea = ui.changeContentAreaLE->text();
		QString customerElseInfo = ui.changeContentElseTE->toPlainText();
		//建立并打開資料庫
		QSqlDatabase database;
		database = QSqlDatabase::addDatabase("QSQLITE");
		database.setDatabaseName("MyDataBase.db");
		if (!database.open())
		{
			qDebug() << "Error: Failed to connect database." << database.lastError();
		}
		else
		{
			qDebug() << "Succeed to connect database.";
		}
		QSqlQuery sql_query(database);
		//查詢資料
		if (ischangeFlag)
		{
			sql_query.prepare("update  customer set CustomerName ='" + customerName + "', " + "CustomerPhone='" + customerPhone + "',Area='" + customerArea + "',ElseInfo='" + customerElseInfo + "' where CustomerName='" + customerName + "'");
		}
		else
		{
			sql_query.prepare("insert into customer values ('" + customerName + "','" + customerPhone + "','" + customerArea + "','" + customerElseInfo + "')");
		}
		//qDebug() << sql_query.exec();
		if (!sql_query.exec())
		{
			qDebug() << sql_query.lastError();
			//錯誤提示
			QToolTip::showText(ui.changeContentNameLE->mapToGlobal(QPoint(0, 0)), QString::fromLocal8Bit("客戶資訊已存在!"));
		}
		else
		{
			qDebug() << tr("添加成功");
			emit UpdateCustomerManageTable();
			this->close();
		}
		
		//關閉資料庫
		database.close();
	}
	ui.changeContentNameLE->setEnabled(true);
	return;
}

void ChangeContent::on_changeContentCancleBtn_clicked()
{
	this->close();
}

//導出資料到excel
void ChangeContent::on_customerManageEXportDataBtn_clicked()
{
	qDebug() << "導出資料到excel!";
	
}

           

4.商品資訊修改頁面 commodityManageChangeInfo.cpp

#include "commmodityManageChangeInfo.h"

#define tr QString::fromLocal8Bit

commmodityManageChangeInfo::commmodityManageChangeInfo(QWidget *parent)
	: QDialog(parent)
{
	ui.setupUi(this);
	// 取消邊框
	setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
	ui.commmodityManageChangeInfoNameLE->setText("");
	ui.commmodityManageChangeInfoEquitmentLE->setText("");
	ui.commmodityManageChangeInfoPropertyLE->setText("");
	ui.commmodityManageChangeInfoElseTE->setText("");
}

commmodityManageChangeInfo::~commmodityManageChangeInfo()
{
	delete &ui;
}

void commmodityManageChangeInfo::closeEvent(QCloseEvent *event)
{

	if (ui.commmodityManageChangeInfoBtnClose->isDefault())
	{
		//TODO: 在退出視窗之前,實作希望做的操作 
		QMessageBox::StandardButton r = QMessageBox::question(this, tr("提示"), tr("确定退出?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
		if (r == QMessageBox::Yes)
		{
			event->accept();
		}
		else
		{
			event->ignore();
		}
	}
	else
	{
		return;
	}
}

void commmodityManageChangeInfo::on_commmodityManageChangeInfoSureBtn_clicked()
{
	qDebug() << "clicked login_btn";
	if (ui.commmodityManageChangeInfoNameLE->text() == "" || ui.commmodityManageChangeInfoEquitmentLE->text() == "")
	{
		if (ui.commmodityManageChangeInfoNameLE->text() == "")
		{
			QToolTip::showText(ui.commmodityManageChangeInfoNameLE->mapToGlobal(QPoint(100, 0)), tr("您輸入的商品名稱為空,請重新輸入!"));
		}
		if (ui.commmodityManageChangeInfoEquitmentLE->text() == "")
		{
			QToolTip::showText(ui.commmodityManageChangeInfoEquitmentLE->mapToGlobal(QPoint(100, 0)), tr("您輸入的商品裝置号為空,請重新輸入!"));
		}
		return;
	}
	else
	{
		QString commodityName = ui.commmodityManageChangeInfoNameLE->text();
		QString commodityEquitmentNumber = ui.commmodityManageChangeInfoEquitmentLE->text();
		QString commodityProperty = ui.commmodityManageChangeInfoPropertyLE->text();
		QString commodityElseInfo = ui.commmodityManageChangeInfoElseTE->toPlainText();
		//建立并打開資料庫
		QSqlDatabase database;
		database = QSqlDatabase::addDatabase("QSQLITE");
		database.setDatabaseName("MyDataBase.db");
		if (!database.open())
		{
			qDebug() << "Error: Failed to connect database." << database.lastError();
		}
		else
		{
			qDebug() << "Succeed to connect database.";
		}
		QSqlQuery sql_query(database);
		//查詢資料
		
		if (isChangeFlag)
		{
			sql_query.prepare("update  commodity set commodityName ='" + commodityName + "', " + "commodityProperty='" + commodityProperty + "',commodityElseInfo='" + commodityElseInfo + "' where commodityEquitmentNumber='" + commodityEquitmentNumber + "'");
		}
		else
		{
			sql_query.prepare("insert into commodity values ('" + commodityName + "','" + commodityEquitmentNumber + "','" + commodityProperty + "','" + commodityElseInfo + "')");
		}
		//qDebug() << sql_query.exec();
		if (!sql_query.exec())
		{
			qDebug() << sql_query.lastError();
			//錯誤提示
			QToolTip::showText(ui.commmodityManageChangeInfoEquitmentLE->mapToGlobal(QPoint(0, 0)), QString::fromLocal8Bit("裝置号重複,請重新輸入!"));
		}
		else
		{
			qDebug() << tr("添加商品資訊成功");
			emit UpdatecommodityManageTable();
			this->close();
		}

		//關閉資料庫
		database.close();
	}
	return;
}

void commmodityManageChangeInfo::mousePressEvent(QMouseEvent *e)
{
	if (e->button() == Qt::LeftButton)
	{
		mDrag = true;
		mDragPos = e->globalPos() - pos();
		e->accept();
	}
}

void commmodityManageChangeInfo::mouseMoveEvent(QMouseEvent *e)
{
	if (mDrag && (e->buttons() && Qt::LeftButton))
	{
		move(e->globalPos() - mDragPos);
		e->accept();
	}
}

void commmodityManageChangeInfo::mouseReleaseEvent(QMouseEvent *event)
{
	mDrag = false;
}

void commmodityManageChangeInfo::on_commmodityManageChangeInfoBtnMin_clicked()
{
	showMinimized();
}

void commmodityManageChangeInfo::on_commmodityManageChangeInfoBtnClose_clicked()
{
	this->close();
}

void commmodityManageChangeInfo::on_commmodityManageChangeInfoCancleBtn_clicked()
{
	this->close();
}
           

源碼:https://download.csdn.net/download/sinat_33419023/12713592