这是跟着网上黑马视频的qt练手项目 ,主要涉及ui界面设计,数据库操作,xml生成与应用
ui界面如下,采用栈容器,抽屉容器等进行设计,点击确定可以实时显示售卖信息并跟新数据库和xml文件
以下为sqlite数据库表格(事先生成,由navicat进行调试)
以下为生成记录的xml文件
以下为详细代码
pro
#-------------------------------------------------
#
# Project created by QtCreator 2019-04-03T13:39:42
#
#-------------------------------------------------
QT += core gui sql xml
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = carManage
TEMPLATE = app
# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
mainwindow.cpp \
domxml.cpp
HEADERS += \
mainwindow.h \
domxml.h
FORMS += \
mainwindow.ui
domxml.h
#ifndef DOMXML_H
#define DOMXML_H
#include
#include
#include
#include
class DomXML
{
public:
DomXML();
static void createXML(const QString path);
static void appendXML(QString filePath,QStringList list);
static void writeXML(QDomDocument &doc,QDomElement &root,QStringList &list);
static void readXML(QString filePath,QStringList &fList,
QStringList &bList,
QStringList &pList,
QStringList &nList,
QStringList &tList
);
};
#endif // DOMXML_H
domxml.cpp
#include "domxml.h"
#include
#include
#include //格式头部
#include
#include
#include
#include //文本流
#include
DomXML::DomXML()
{
}
void DomXML::createXML(const QString path) //创建xml空文件
{
QFile file(path);
if(true == file.exists())//如果文件存在则不进行创建
{
//QMessageBox::warning(NULL,"错误","xml文件已经存在");
qDebug()<<"文件已经存在";
return;
}
else
{
bool isOK = file.open (QIODevice::WriteOnly);//如果不存在只写方式打开文件
if(isOK) //若成功
{
//创建xml文件对象
QDomDocument doc;
//创建xml文件头部格式
QDomProcessingInstruction ins;
ins =doc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"utf-8\"");
doc.appendChild(ins); //追加元素
//根节点元素
QDomElement root =doc.createElement("日销售清单");
doc.appendChild(root);
//保存
QTextStream stream(&file); //文本关联文件
doc.save(stream,4); //4个字符缩进
file.close();
}
else
{
QMessageBox::warning(NULL,"错误","打开失败");
//qDebug()<<"打开失败";
}
}
}
//list.at(0)为厂家 如一汽 添加xml文件
void DomXML::appendXML(QString filePath, QStringList list)
{
QFile file(filePath);
bool isOk =file.open(QIODevice::ReadOnly);
if (true == isOk)
{
//file和xml文档对象关联
QDomDocument doc;
bool isOK_1=doc.setContent(&file);
if(isOK_1) //如果关联成功
{
file.close();//已经关联,可以关闭文件
//获取根节点元素
QDomElement root =doc.documentElement();
//获取当前时间
QDateTime date = QDateTime::currentDateTime();
QString dateStr = date.toString("yyyy-MM-dd");
//判断当前根节点有没有子节点
if(root.hasChildNodes()) //若有子节点查找最后一个子节点元素
{
//QMessageBox::warning(NULL,"错误","当前有子节点");
// return;
//查找最后一个子节点并看是否为当天日期
QDomElement lastEmt = root.lastChildElement();
if(lastEmt.attribute("date")==dateStr)
{//有当天日期,直接写入
writeXML(doc,lastEmt,list);
}
else{ //如果不是当天日期,则创建一些预先的日期格式
//创建日期子节点元素
QDomElement dateEmt = doc.createElement("日期");
//创建日期属性
QDomAttr dateAttr = doc.createAttribute("date");
//创建属性的值
dateAttr.setNodeValue(dateStr);
//关联日期属性和结点
dateEmt.setAttributeNode(dateAttr);
//把日期节点添加到根节点
root.appendChild(dateEmt);
//写入文件内容
writeXML(doc,dateEmt,list);
}
}
else //没有子节点
{
//创建日期子节点元素
QDomElement dateEmt = doc.createElement("日期");
//创建日期属性
QDomAttr dateAttr = doc.createAttribute("date");
//创建属性的值
dateAttr.setNodeValue(dateStr);
//关联日期属性和结点
dateEmt.setAttributeNode(dateAttr);
//把日期节点添加到根节点
root.appendChild(dateEmt);
//写入文件内容
writeXML(doc,dateEmt,list);
}
//保存下
bool isOK_2 =file.open(QIODevice::WriteOnly);
if(isOK_2)
{
QTextStream stream(&file);
doc.save(stream,4);
file.close();
}
}
else {
QMessageBox::warning(NULL,"错误","xml关联失败");
}
}
else {
QMessageBox::warning(NULL,"错误","打开已存在的xml错误");
}
}
void DomXML::writeXML(QDomDocument &doc, QDomElement &root, QStringList &list)
{
//获取当前时间
QDateTime time = QDateTime::currentDateTime();
QString timeStr = time.toString("hh-mm-ss"); //时分秒
//创建日期子节点元素
QDomElement timeEmt = doc.createElement("时间");
//创建日期属性
QDomAttr timeAttr = doc.createAttribute("time");
//创建属性的值
timeAttr.setNodeValue(timeStr);
//关联日期属性和结点
timeEmt.setAttributeNode(timeAttr);
//把日期节点添加到根节点
root.appendChild(timeEmt);
QDomElement factory = doc.createElement("厂家");
QDomElement brand = doc.createElement("品牌");
QDomElement price = doc.createElement("报价");
QDomElement number = doc.createElement("数量");
QDomElement total = doc.createElement("金额");
//依次添加传入的信息
QDomText text =doc.createTextNode(list.at(0));
factory.appendChild(text);
text =doc.createTextNode(list.at(1));
brand.appendChild(text);
text =doc.createTextNode(list.at(2));
price.appendChild(text);
text =doc.createTextNode(list.at(3));
number.appendChild(text);
text =doc.createTextNode(list.at(4));
total.appendChild(text);
//添加到时间结点下
timeEmt.appendChild(factory);
timeEmt.appendChild(brand);
timeEmt.appendChild(price);
timeEmt.appendChild(number);
timeEmt.appendChild(total);
}
void DomXML::readXML(QString filePath, QStringList &fList, QStringList &bList, QStringList &pList, QStringList &nList, QStringList &tList)
{
QFile file(filePath);
bool isOk =file.open(QIODevice::ReadOnly);
if (true == isOk)
{
//file和xml文档对象关联
QDomDocument doc;
bool isOK_1=doc.setContent(&file);
if(isOK_1) //如果关联成功
{
//获取根节点
QDomElement root =doc.documentElement();
file.close();
QDateTime date = QDateTime::currentDateTime();
QString dateStr = date.toString("yyyy-MM-dd");
if(root.hasChildNodes()) //如果有子节点
{
//找最后一个节点元素
QDomElement lastEmt =root.lastChildElement() ;
if(lastEmt.attribute("date")==dateStr)
{
//找出当前日期下的所有时间子节点
QDomNodeList list =lastEmt.childNodes();
for(int i =0;i
mainwindow
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
void connectDb();
void initDate();
~MainWindow();
private slots:
void on_actioncar_triggered();
void on_actioncalc_triggered();
void on_comboBoxFactory_currentIndexChanged(const QString &arg1);
void on_comboBoxBrand_currentIndexChanged(const QString &arg1);
void on_spinBox_valueChanged(int arg1);
void on_pushButtonCal_clicked();
void on_pushButtonSure_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "domxml.h"
#include
#include
#include
#include
#include
#include
#include
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
on_actioncar_triggered();//显示车辆管理页面
connectDb(); //连接数据库
initDate();
DomXML::createXML("./demo.xml"); //创建xml文件
// QStringList list;
// list<<"十年来"<<"毕加索"<<"11"<<"33"<<"11";
// DomXML::appendXML("./demo.xml",list);
}
//连接数据库
void MainWindow::connectDb()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("car.db");
if(!db.open())
{
QMessageBox::warning(this,"数据库的错误",db.lastError().text());
return;
}
}
void MainWindow::initDate() //初始数据
{
QSqlQueryModel *queryModel = new QSqlQueryModel;
ui->toolBox->setCurrentIndex(0);
queryModel->setQuery("select name from factory"); //用模型来进行数据存储
ui->comboBoxFactory->setModel(queryModel); //初始化下拉框数据
ui->labelLast->setText("0"); //初始化剩余车辆
ui->lineEditTotal->setEnabled(false); //将总数设置为只读
ui->lineEditPrice->setEnabled(false);
ui->pushButtonSure->setEnabled(false);
}
MainWindow::~MainWindow()
{
delete ui;
}
//设置车辆管理的菜单
void MainWindow::on_actioncar_triggered()
{
ui->stackedWidget->setCurrentIndex(0);
ui->label->setText("车辆管理");
}
//设置车辆统计的菜单
void MainWindow::on_actioncalc_triggered()
{
ui->stackedWidget->setCurrentIndex(1);
ui->label->setText("销售统计");
}
//厂家切换时对应的变换槽函数
void MainWindow::on_comboBoxFactory_currentIndexChanged(const QString &arg1)
{
if(arg1 =="请选择厂家")
{
ui->comboBoxBrand->clear(); //品牌下拉框清空
ui->lineEditPrice->clear(); //报价栏清空
ui->labelLast->setText("0");
ui->lineEditTotal->clear();
ui->spinBox->setValue(0);
ui->spinBox->setEnabled(false); //微调框禁止使用
}
else
{
ui->comboBoxBrand->clear(); //每次操作前进行清空 不然会叠加的
ui->spinBox->setEnabled(true);
QSqlQuery query;
QString sql =QString("select name from brand where factory= '%1'").arg(arg1);
query.exec(sql); //执行查找语句
while (query.next()) {
QString name = query.value(0).toString();
ui->comboBoxBrand->addItem(name);
}
}
}
//设置剩余以及价格随下拉框的改变而改变
void MainWindow::on_comboBoxBrand_currentIndexChanged(const QString &arg1)
{
QSqlQuery query;
QString sql =QString("select price,last from brand where name= '%1'").arg(arg1);
query.exec(sql); //执行查找语句
while (query.next()) {
QString price = query.value(0).toString();
QString last =query.value("last").toString();
ui->lineEditPrice->setText(price); //设置单辆车报价
ui->labelLast->setText(last); //设置剩余车的数目
}
}
//微调框槽函数
void MainWindow::on_spinBox_valueChanged(int arg1)
{
ui->pushButtonSure->setEnabled(true); //激活确定按钮
//更新剩余数量
QSqlQuery query;
QString sql =QString("select last from brand where name= '%1'").
arg(ui->comboBoxBrand->currentText());//查找当前品牌名
query.exec(sql); //执行查找语句
int last;
while (query.next()) {
last =query.value("last").toInt();
int tempNum =last-arg1;
//qDebug()<last)
{
ui->spinBox->setValue(last);
return; //如果选定数目大于剩余 则终止
}
ui->labelLast->setText(QString::number(tempNum)); //绑定设置剩余数和微调框
}
//更新车价的总体金额数目
int price =ui->lineEditPrice->text().toInt();
int num = ui->spinBox->text().toInt();
int total = price*num;
ui->lineEditTotal->setText(QString::number(total));
}
void MainWindow::on_pushButtonCal_clicked() //点击取消按钮,不进行数据库操作
{
on_comboBoxFactory_currentIndexChanged("请选择厂家");//进行回退初始化
ui->comboBoxFactory->setCurrentText("请选择厂家"); //初始化选择框
}
void MainWindow::on_pushButtonSure_clicked() //点击确定按钮
{
int num = ui->spinBox->text().toInt(); //获取销售数量
int last = ui->labelLast->text().toInt(); //获取剩余数量
//获取数据库中的销量
QSqlQuery query;
QString sql = QString("select sell from brand where name = '%1'").
arg(ui->comboBoxBrand->currentText());
int sell; //销售的数量
query.exec(sql);
while (query.next()) {
sell = query.value("sell").toInt();
}
//更新数据库中的销售量和剩余量
sell = sell + num;
QString sq = QString("update brand set sell = %1,last =%2 where name ="
" '%3'").arg(sell).arg(last)
.arg(ui->comboBoxBrand->currentText());
query.exec(sq);
//把确认后的数据跟新到xml中
QStringList list;
list<comboBoxFactory->currentText()
<comboBoxBrand->currentText()
<lineEditPrice->text()
<lineEditTotal->text();
DomXML::appendXML("./demo.xml",list);
QStringList fList;
QStringList bList;
QStringList pList;
QStringList nList;
QStringList tList;
DomXML::readXML("./demo.xml",fList,bList,pList,nList,tList);
int i=fList.size()-1;
//for(int i=0;itextEdit->append(str);
// }
//按完确定后进行界面初始化
on_comboBoxFactory_currentIndexChanged("请选择厂家");//进行回退初始化
ui->comboBoxFactory->setCurrentText("请选择厂家"); //初始化选择框
ui->pushButtonSure->setEnabled(false); //淹没确定按钮
//on_pushButtonCal_clicked() 或者直接调用这个函数
}
main
#include "mainwindow.h"
#include
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}