第十七章电子商城系统

一、功能需求分析

1、登录功能

用户需要输入用户名和口令登录商城系统,口令用密码形式保护,口令不正确重新输入。

第十七章电子商城系统_第1张图片

界面主要用label、LineEdit、pushbutton等控件组成

 

2、商城系统功能

2.1新品入库功能

实现新的产品的入库,卖完和不卖的产品的清仓,并对数据库中的商品的库存、进价、售价、名称、类别和样品照片的显示。

第十七章电子商城系统_第2张图片

 界面主要用label、LineEdit、pushbutton和TableView等控件组成

2.2预售订单功能

提供预售商品功能,可以选择商品类别、名称、数量、库存、售价并计算总共金额。

第十七章电子商城系统_第3张图片

界面主要用label、LineEdit、pushbutton和 ListWidget等控件组成

二、开发环境

win10+QT5.9_MinGW+MySQL5.7

三、实现细节

1、工程结构

第十七章电子商城系统_第4张图片

 

2、登录功能实现

全部实现代码在logindialog类中,继承Qdialog

主要函数包括登录按钮单击事件和退出登录事件

登录按钮单击事件:通过用户名查询数据库中的口令,再与口令框中的口令进行比较,相同验证通过,不相同弹出消息框提示失败,重新输入口令

退出登录事件:直接调用QDialog::reject()函数,退出登录界面。

logindialog.h

#ifndef LOGINDIALOG_H
#define LOGINDIALOG_H

#include 
#include           //查询Mysql的库
#include 
#include //包含MD5算法库

namespace Ui {
class LoginDialog;
}

class LoginDialog : public QDialog
{
    Q_OBJECT

public:
    explicit LoginDialog(QWidget *parent = 0);
    ~LoginDialog();
    QString strToMd5(QString str);   //将口令字符串转换为MD5加密

private slots:
    void on_loginPushButton_clicked();//登录按钮单击事件槽
    void on_exitPushButton_clicked();  //退出按钮单击事件槽

private:
    Ui::LoginDialog *ui;
};

#endif // LOGINDIALOG_H

logindialog.cpp

#include "logindialog.h"
#include "ui_logindialog.h"

LoginDialog::LoginDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::LoginDialog)
{
    ui->setupUi(this);
    setFixedSize(400,300);         //登录对话框固定大小
    ui->pwdLineEdit->setFocus();   //口令框置焦点
}

LoginDialog::~LoginDialog()
{
    delete ui;
}


void LoginDialog::on_loginPushButton_clicked()
{
    if(!ui->pwdLineEdit->text().isEmpty())
    {
        QSqlDatabase d = QSqlDatabase::addDatabase("QMYSQL");
        d.setHostName("localhost");
        d.setDatabaseName("emarket");
        d.setUserName("root");
        d.setPassword("123456");
        bool ok = d.open();
        if(!ok)
        {
            QMessageBox::critical(0,QObject::tr("数据库连接失败"),"无法创建连接!请检查排除故障后重启程序。",QMessageBox::Cancel);
        }

        QSqlQuery query(d);

        QString admin = ui->adminLineEdit->text();
        query.exec("select PassWord from member where MemberID='" + admin + "'");//从数据库中查询出口令密码字段
        query.next();
        QString pwdMd5 = ui->pwdLineEdit->text();
        QString pwd = query.value(0).toString();
        if( pwd == pwdMd5)
        {
            QDialog::accept();//验证通过
        }
        else
        {
            QMessageBox::warning(this,tr("口令错误"),tr("请输入正确的口令!"),QMessageBox::Ok);
            ui->pwdLineEdit->clear();
            ui->pwdLineEdit->setFocus();
        }
    }
    else
    {
        ui->pwdLineEdit->setFocus();
    }
}

void LoginDialog::on_exitPushButton_clicked()
{
    QDialog::reject();//退出登录框
}

QString LoginDialog::strToMd5(QString str)
{
    QString strMd5;
    QByteArray qba;
    qba = QCryptographicHash::hash(str.toLatin1(),QCryptographicHash::Md5);
    strMd5.append(qba.toHex());
    return strMd5;
}

3、商城系统功能实现

商城系统功能在mainwindow类中实现

3.1界面初始化功能

对界面显示的信息进行初始化

将新品入库页显示在前

将商品类别导入到下拉框选项中

void MainWindow::initMainWindow()
{
    ui->stackedWidget->setCurrentIndex(1);
    ui->toolBox->setCurrentIndex(0);
    QSqlQueryModel *categoryModel = new QSqlQueryModel(this);//商品类别模型数据
    categoryModel->setQuery("select Name from category");
    ui->newCategoryComboBox->setModel(categoryModel);//商品类别列表加载(新品入库页)
    commodity_model = new QSqlTableModel(this);//商品信息视图
    commodity_model->setTable("commodity_inf");
    commodity_model->select();
    ui->commodityTableView->setModel(commodity_model);//库存商品记录数据网格信息加载(新品入库页)
    ui->preCategoryComboBox->setModel(categoryModel);//商品类别列表加载(预售订单页)
    loadPreCommodity();//在预售订单页加载商品信息
    myMemberID = "b02020622";
    //myOrdered = false;
    myOrdered = true;
    //myOrderID = 0;
    myOrderID = 4;
    myPaySum = 0;
    QListWidgetItem *title = new QListWidgetItem;
    title->setText(QString("当 前 订 单 【 编号 %1 】").arg(myOrderID));
    title->setTextAlignment(Qt::AlignCenter);
    //ui->sellListWidget->addItem(title);
}

3.2新品入库功能

入库操作

//入库操作
void MainWindow::on_newPutinStorePushButton_clicked()
{
    QSqlQuery query;
    query.exec(QString("select CategoryID from category where Name='%1'").
               arg(ui->newCategoryComboBox->currentText()));//根据类别名查询类别ID
    query.next();
    int categoryid = query.value(0).toInt();//将要入库的商品类别
    QString name = ui->newNameLineEdit->text();//商品名称
    float inputprice = ui->newInputPriceLineEdit->text().toFloat();//进价
    float outputprice = ui->newOutputPriceLineEdit->text().toFloat();//售价
    int count = ui->newCountSpinBox->value();//入库量
    query.exec(QString("insert into commodity(CategoryID, Name, Picture, InputPrice, OutputPrice, Amount) values(%1, '%2', NULL, %3, %4, %5)").
               arg(categoryid).arg(name).arg(inputprice).arg(outputprice).arg(count));//插入新入库的商品记录
    //插入照片
    QByteArray picdata;
    QBuffer buffer(&picdata);
    buffer.open(QIODevice::WriteOnly);
    myPicImg.save(&buffer, "JPG");//用QImage对象储存要写入数据库的照片数据
    QVariant var(picdata);
    QString sqlstr = "update commodity set Picture=? where Name='" + name + "'";
    query.prepare(sqlstr);
    query.addBindValue(var);//绑定照片数据作为参数传给?处
    if(!query.exec())
    {
        QMessageBox::information(0, QObject::tr("提示"), "照片写入失败");
    }
    //刷新网格信息
    commodity_model->setTable("commodity_inf");
    commodity_model->select();
    ui->commodityTableView->setModel(commodity_model);//刷新数据网格(新品入库页)
}

选样照

void MainWindow::on_newUploadPushButton_clicked()
{
    QString picturename = QFileDialog::getOpenFileName(this, "选择商品图片", ".", "Image File(*.png *.jpg *.jpeg *.bmp)");
    if (picturename.isEmpty()) return;
    myPicImg.load(picturename);
    ui->newPictureLabel->setPixmap(QPixmap::fromImage(myPicImg));
}

清仓操作

//清仓操作
void MainWindow::on_newClearancePushButton_clicked()
{
    QSqlQuery query;
    query.exec(QString("delete from commodity where Name='%1'").arg(ui->newNameLineEdit->text()));//删除商品记录
    //刷新界面
    ui->newNameLineEdit->setText("");
    ui->newInputPriceLineEdit->setText("");
    ui->newOutputPriceLineEdit->setText("");
    ui->newCountSpinBox->setValue(1);
    ui->newPictureLabel->clear();
    commodity_model->setTable("commodity_inf");
    commodity_model->select();
    ui->commodityTableView->setModel(commodity_model);//刷新数据网格(新品入库页)
}

3.3预售订单功能

商品出售

//商品出售
void MainWindow::on_preSellPushButton_clicked()
{
    QSqlQuery query;
    if (!myOrdered)
    {
        query.exec(QString("insert into orders(MemberID, PaySum, PayWay, OTime) values('%1', NULL, NULL, NULL)").arg(myMemberID));
        myOrdered = true;
        query.exec(QString("select OrderID from orders where OTime IS NULL"));
        query.next();
        myOrderID = query.value(0).toInt();
    }
    //下面开始预售
    query.exec(QString("select CommodityID from commodity where Name='%1'").arg(ui->preNameComboBox->currentText()));
    query.next();
    int commodityid = query.value(0).toInt();//本次预售商品编号
    int count = ui->preCountSpinBox->value();//预售量
    int amount = ui->preCountSpinBox->maximum() - count;//剩余库存量
    QSqlDatabase::database().transaction();//开始一个事务
    bool insOk = query.exec(QString("insert into orderitems(OrderID, CommodityID, Count) values(%1, %2, %3)").arg(myOrderID).arg(commodityid).arg(count));//新增订单项
    bool uptOk = query.exec(QString("update commodity set Amount=%1 where CommodityID=%2").arg(amount).arg(commodityid));//更新库存
    if (insOk && uptOk)
    {
        QSqlDatabase::database().commit();
        onPreNameComboBoxChange();
        //显示预售清单
        QString curtime = QTime::currentTime().toString("hh:mm:ss");
        QString curname = ui->preNameComboBox->currentText();
        QString curcount = QString::number(count, 10);
        QString curoutprice = ui->preOutputPriceLabel->text();
        QString curtotal = ui->preTotalLabel->text();
        myPaySum += curtotal.toFloat();
        QString sell_record = curtime + " " + "售出:" + curname + "\r\n              数量:" + curcount + ";单价:" + curoutprice + "¥;总价:" + curtotal + "¥";
        QListWidgetItem *split = new QListWidgetItem;
        split->setText("——.——.——.——.——.——.——.——.——.——.——.——.——.——.——");
        split->setTextAlignment(Qt::AlignCenter);
        ui->sellListWidget->addItem(split);
        ui->sellListWidget->addItem(sell_record);
        ui->prePlaceOrderPushButton->setEnabled(true);
        QMessageBox::information(0, QObject::tr("提示"), "已加入订单!");
    } else {
        QSqlDatabase::database().rollback();
    }
}

下订单

//下订单
void MainWindow::on_prePlaceOrderPushButton_clicked()
{
    QSqlQuery query;
    QString otime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    QSqlDatabase::database().transaction();//开始一个事务
    bool ordOk = query.exec(QString("update orders set PaySum=%1, OTime='%2' where OrderID=%3").arg(myPaySum).arg(otime).arg(myOrderID));//下订单
    bool uptOk = query.exec(QString("update orderitems set Affirm=1, SendGoods=1 where OrderID=%1").arg(myOrderID));//确认发货
    if (ordOk && uptOk)
    {
        QSqlDatabase::database().commit();
        ui->prePlaceOrderPushButton->setEnabled(false);
        //显示下单记录
        QString order_record = "日 期:" + otime + "\r\n订 单 号:" + QString(" %1 ").arg(myOrderID) + "\r\n应付款总额:" + QString(" %1¥").arg(myPaySum) + "\r\n下 单 成 功!";
        QListWidgetItem *split = new QListWidgetItem;
        split->setText("***.***.***.***.***.***.***.***.***.***.***.***.***.***.***.***.***.***");
        split->setTextAlignment(Qt::AlignCenter);
        ui->sellListWidget->addItem(split);
        ui->sellListWidget->addItem(order_record);
        myPaySum = 0;
        QMessageBox::information(0, QObject::tr("提示"), "下单成功!");
        commodity_model->setTable("commodity_inf");
        commodity_model->select();
        ui->commodityTableView->setModel(commodity_model);//刷新数据网格(新品入库页)
    } else {
        QSqlDatabase::database().rollback();
    }
}

3.4完整代码

mainwidow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include 
#include 
#include 
#include 
//#include "opencv2/opencv.hpp"
#include     //MySQL数据库类
#include   //MySQL表模型库
#include        //MySQL查询类库
#include 
#include          //图像处理类库

//using namespace cv;

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    void initMainWindow();
    void onTableSelectChange(int row);  //商品信息数据网格与表单联动
    void showCommodityPhoto();           //显示商品样照
    void loadPreCommodity();             //加载预售订单页商品名称列表
    void onPreNameComboBoxChange();      //预售订单页商品名与表单联动
    
    

private slots:
    void on_commodityTableView_clicked(const QModelIndex& index);//商品信息数据网格单击事件槽
    void on_newPutinStorePushButton_clicked();//入库按钮事件单击事件槽
    void on_preCategoryComboBox_currentIndexChanged(int index);//类别与商品名列表联动信息槽
    void on_preNameComboBox_currentIndexChanged(int index);//改选商品名信息槽
    void on_preCountSpinBox_valueChanged(int arg1);//售出商品数改变信息槽
    void on_preSellPushButton_clicked();//"出售"按钮单击事件
    void on_prePlaceOrderPushButton_clicked();//下单按钮单击事件
    void on_newUploadPushButton_clicked();//上传按钮事件单击事件槽

    void on_newClearancePushButton_clicked();//清仓按钮事件单击事件槽

    

private:
    Ui::MainWindow *ui;
    QImage myPicImg;                          //保存商品样照(界面显示)
    QSqlTableModel *commodity_model;          //访问数据库商品信息视图的模型
    QString myMemberID;                       //会员帐号
    bool myOrdered;                           //是否正在购买(订单已写入数据库)
    int myOrderID;                            //订单编号
    float myPaySum;                           //当前订单累计需要付款的总金额
};

/**访问MySQL数据库的静态方法*/
static bool createMySqlConn()
{
    QSqlDatabase sqldb = QSqlDatabase::addDatabase("QMYSQL");
    sqldb.setHostName("localhost");
    sqldb.setDatabaseName("emarket");//数据库名称
    sqldb.setUserName("root");      //数据库用户名
    sqldb.setPassword("123456");    //登录密码
    if (!sqldb.open()) {
        QMessageBox::critical(0, QObject::tr("后台数据库连接失败"), "无法创建连接!请检查排除故障后重启程序。", QMessageBox::Cancel);
        return false;
    }
    //QMessageBox::information(0, QObject::tr("后台数据库已启动、正在运行……"), "数据库连接成功!即将启动应用程序。");
    //向数据库中插入照片

    /*QSqlQuery query(sqldb);
    QString photoPath = "D:\\Qt\\imgproc\\21.jpg";//照片不能大于60K
    QFile photoFile(photoPath);
    if (photoFile.exists())
    {
        //存入数据库
        QByteArray picdata;
        photoFile.open(QIODevice::ReadOnly);
        picdata = photoFile.readAll();
        photoFile.close();
        QVariant var(picdata);
        QString sqlstr = "update commodity set Picture=? where CommodityID=6";
        query.prepare(sqlstr);
        query.addBindValue(var);
        if(!query.exec())
        {
            QMessageBox::information(0, QObject::tr("提示"), "照片写入失败");
        } else{
            QMessageBox::information(0, QObject::tr("提示"), "照片已写入数据库");
        }
    }
    sqldb.close();*/

    return true;
}

#endif // MAINWINDOW_H

mainwidow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    initMainWindow();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::initMainWindow()
{
    ui->stackedWidget->setCurrentIndex(1);
    ui->toolBox->setCurrentIndex(0);
    QSqlQueryModel *categoryModel = new QSqlQueryModel(this);//商品类别模型数据
    categoryModel->setQuery("select Name from category");
    ui->newCategoryComboBox->setModel(categoryModel);//商品类别列表加载(新品入库页)
    commodity_model = new QSqlTableModel(this);//商品信息视图
    commodity_model->setTable("commodity_inf");
    commodity_model->select();
    ui->commodityTableView->setModel(commodity_model);//库存商品记录数据网格信息加载(新品入库页)
    ui->preCategoryComboBox->setModel(categoryModel);//商品类别列表加载(预售订单页)
    loadPreCommodity();//在预售订单页加载商品信息
    myMemberID = "b02020622";
    //myOrdered = false;
    myOrdered = true;
    //myOrderID = 0;
    myOrderID = 4;
    myPaySum = 0;
    QListWidgetItem *title = new QListWidgetItem;
    title->setText(QString("当 前 订 单 【 编号 %1 】").arg(myOrderID));
    title->setTextAlignment(Qt::AlignCenter);
    //ui->sellListWidget->addItem(title);
}

void MainWindow::onTableSelectChange(int row)
{
    int r = 1;
    if(row != 0) r = ui->commodityTableView->currentIndex().row();
    QModelIndex index;
    index = commodity_model->index(r, 0);                   //名称
    ui->newNameLineEdit->setText(commodity_model->data(index).toString());
    index = commodity_model->index(r, 1);                   //进价
    ui->newInputPriceLineEdit->setText(commodity_model->data(index).toString());
    index = commodity_model->index(r, 2);                   //售价
    ui->newOutputPriceLineEdit->setText(commodity_model->data(index).toString());
    showCommodityPhoto();                                   //商品样照
    QSqlQuery query;
    query.exec(QString("select Name from category where CategoryID=(select CategoryID from commodity where Name='%1')").arg(ui->newNameLineEdit->text()));
    query.next();
    ui->newCategoryComboBox->setCurrentText(query.value(0).toString());//类别联动
}

void MainWindow::showCommodityPhoto()
{
    QPixmap photo;
    QModelIndex index;
    QSqlQueryModel *pictureModel = new QSqlQueryModel(this);//商品样照模型数据
    QString name = ui->newNameLineEdit->text();
    pictureModel->setQuery("select Picture from commodity where Name='" + name + "'");
    index = pictureModel->index(0, 0);
    photo.loadFromData(pictureModel->data(index).toByteArray(), "JPG");
    ui->newPictureLabel->setPixmap(photo);
}

void MainWindow::loadPreCommodity()
{
    QSqlQueryModel *commodityNameModel = new QSqlQueryModel(this);//商品名称模型数据
    commodityNameModel->setQuery(QString("select Name from commodity where CategoryID=(select CategoryID from category where Name='%1')").arg(ui->preCategoryComboBox->currentText()));
    ui->preNameComboBox->setModel(commodityNameModel);//商品名称列表加载(预售订单页)
    onPreNameComboBoxChange();
}

void MainWindow::onPreNameComboBoxChange()
{
    QSqlQueryModel *preCommodityModel = new QSqlQueryModel(this);//商品表模型数据
    QString name = ui->preNameComboBox->currentText();
    preCommodityModel->setQuery("select OutputPrice, Amount, Picture from commodity where Name='" + name + "'");
    QModelIndex index;
    index = preCommodityModel->index(0, 0);                   //单价
    ui->preOutputPriceLabel->setText(preCommodityModel->data(index).toString());
    index = preCommodityModel->index(0, 1);                   //库存
    ui->preAmountLabel->setText(preCommodityModel->data(index).toString());
    ui->preCountSpinBox->setMaximum(ui->preAmountLabel->text().toInt());
    //下面开始获取和展示照片
    QPixmap photo;
    index = preCommodityModel->index(0, 2);
    photo.loadFromData(preCommodityModel->data(index).toByteArray(), "JPG");
    ui->prePictureLabel->setPixmap(photo);
    //计算总价
    ui->preTotalLabel->setText(QString::number(ui->preOutputPriceLabel->text().toFloat() * ui->preCountSpinBox->value()));
}

void MainWindow::on_commodityTableView_clicked(const QModelIndex &index)
{
    onTableSelectChange(1);
}

void MainWindow::on_preCategoryComboBox_currentIndexChanged(int index)
{
    loadPreCommodity();
}

void MainWindow::on_preNameComboBox_currentIndexChanged(int index)
{
    onPreNameComboBoxChange();
}

void MainWindow::on_preCountSpinBox_valueChanged(int arg1)
{
    ui->preTotalLabel->setText(QString::number(ui->preOutputPriceLabel->text().toFloat() * arg1));
}
//商品出售
void MainWindow::on_preSellPushButton_clicked()
{
    QSqlQuery query;
    if (!myOrdered)
    {
        query.exec(QString("insert into orders(MemberID, PaySum, PayWay, OTime) values('%1', NULL, NULL, NULL)").arg(myMemberID));
        myOrdered = true;
        query.exec(QString("select OrderID from orders where OTime IS NULL"));
        query.next();
        myOrderID = query.value(0).toInt();
    }
    //下面开始预售
    query.exec(QString("select CommodityID from commodity where Name='%1'").arg(ui->preNameComboBox->currentText()));
    query.next();
    int commodityid = query.value(0).toInt();//本次预售商品编号
    int count = ui->preCountSpinBox->value();//预售量
    int amount = ui->preCountSpinBox->maximum() - count;//剩余库存量
    QSqlDatabase::database().transaction();//开始一个事务
    bool insOk = query.exec(QString("insert into orderitems(OrderID, CommodityID, Count) values(%1, %2, %3)").arg(myOrderID).arg(commodityid).arg(count));//新增订单项
    bool uptOk = query.exec(QString("update commodity set Amount=%1 where CommodityID=%2").arg(amount).arg(commodityid));//更新库存
    if (insOk && uptOk)
    {
        QSqlDatabase::database().commit();
        onPreNameComboBoxChange();
        //显示预售清单
        QString curtime = QTime::currentTime().toString("hh:mm:ss");
        QString curname = ui->preNameComboBox->currentText();
        QString curcount = QString::number(count, 10);
        QString curoutprice = ui->preOutputPriceLabel->text();
        QString curtotal = ui->preTotalLabel->text();
        myPaySum += curtotal.toFloat();
        QString sell_record = curtime + " " + "售出:" + curname + "\r\n              数量:" + curcount + ";单价:" + curoutprice + "¥;总价:" + curtotal + "¥";
        QListWidgetItem *split = new QListWidgetItem;
        split->setText("——.——.——.——.——.——.——.——.——.——.——.——.——.——.——");
        split->setTextAlignment(Qt::AlignCenter);
        ui->sellListWidget->addItem(split);
        ui->sellListWidget->addItem(sell_record);
        ui->prePlaceOrderPushButton->setEnabled(true);
        QMessageBox::information(0, QObject::tr("提示"), "已加入订单!");
    } else {
        QSqlDatabase::database().rollback();
    }
}
//下订单
void MainWindow::on_prePlaceOrderPushButton_clicked()
{
    QSqlQuery query;
    QString otime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    QSqlDatabase::database().transaction();//开始一个事务
    bool ordOk = query.exec(QString("update orders set PaySum=%1, OTime='%2' where OrderID=%3").arg(myPaySum).arg(otime).arg(myOrderID));//下订单
    bool uptOk = query.exec(QString("update orderitems set Affirm=1, SendGoods=1 where OrderID=%1").arg(myOrderID));//确认发货
    if (ordOk && uptOk)
    {
        QSqlDatabase::database().commit();
        ui->prePlaceOrderPushButton->setEnabled(false);
        //显示下单记录
        QString order_record = "日 期:" + otime + "\r\n订 单 号:" + QString(" %1 ").arg(myOrderID) + "\r\n应付款总额:" + QString(" %1¥").arg(myPaySum) + "\r\n下 单 成 功!";
        QListWidgetItem *split = new QListWidgetItem;
        split->setText("***.***.***.***.***.***.***.***.***.***.***.***.***.***.***.***.***.***");
        split->setTextAlignment(Qt::AlignCenter);
        ui->sellListWidget->addItem(split);
        ui->sellListWidget->addItem(order_record);
        myPaySum = 0;
        QMessageBox::information(0, QObject::tr("提示"), "下单成功!");
        commodity_model->setTable("commodity_inf");
        commodity_model->select();
        ui->commodityTableView->setModel(commodity_model);//刷新数据网格(新品入库页)
    } else {
        QSqlDatabase::database().rollback();
    }
}
//选样照
void MainWindow::on_newUploadPushButton_clicked()
{
    QString picturename = QFileDialog::getOpenFileName(this, "选择商品图片", ".", "Image File(*.png *.jpg *.jpeg *.bmp)");
    if (picturename.isEmpty()) return;
    myPicImg.load(picturename);
    ui->newPictureLabel->setPixmap(QPixmap::fromImage(myPicImg));
}
//入库操作
void MainWindow::on_newPutinStorePushButton_clicked()
{
    QSqlQuery query;
    query.exec(QString("select CategoryID from category where Name='%1'").
               arg(ui->newCategoryComboBox->currentText()));//根据类别名查询类别ID
    query.next();
    int categoryid = query.value(0).toInt();//将要入库的商品类别
    QString name = ui->newNameLineEdit->text();//商品名称
    float inputprice = ui->newInputPriceLineEdit->text().toFloat();//进价
    float outputprice = ui->newOutputPriceLineEdit->text().toFloat();//售价
    int count = ui->newCountSpinBox->value();//入库量
    query.exec(QString("insert into commodity(CategoryID, Name, Picture, InputPrice, OutputPrice, Amount) values(%1, '%2', NULL, %3, %4, %5)").
               arg(categoryid).arg(name).arg(inputprice).arg(outputprice).arg(count));//插入新入库的商品记录
    //插入照片
    QByteArray picdata;
    QBuffer buffer(&picdata);
    buffer.open(QIODevice::WriteOnly);
    myPicImg.save(&buffer, "JPG");//用QImage对象储存要写入数据库的照片数据
    QVariant var(picdata);
    QString sqlstr = "update commodity set Picture=? where Name='" + name + "'";
    query.prepare(sqlstr);
    query.addBindValue(var);//绑定照片数据作为参数传给?处
    if(!query.exec())
    {
        QMessageBox::information(0, QObject::tr("提示"), "照片写入失败");
    }
    //刷新网格信息
    commodity_model->setTable("commodity_inf");
    commodity_model->select();
    ui->commodityTableView->setModel(commodity_model);//刷新数据网格(新品入库页)
}
//清仓操作
void MainWindow::on_newClearancePushButton_clicked()
{
    QSqlQuery query;
    query.exec(QString("delete from commodity where Name='%1'").arg(ui->newNameLineEdit->text()));//删除商品记录
    //刷新界面
    ui->newNameLineEdit->setText("");
    ui->newInputPriceLineEdit->setText("");
    ui->newOutputPriceLineEdit->setText("");
    ui->newCountSpinBox->setValue(1);
    ui->newPictureLabel->clear();
    commodity_model->setTable("commodity_inf");
    commodity_model->select();
    ui->commodityTableView->setModel(commodity_model);//刷新数据网格(新品入库页)
}

main.cpp

#include "mainwindow.h"
#include 
#include "logindialog.h"
#include     //Qt进程模块

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    if(!createMySqlConn())
    {
        //若初次尝试连接不成功,就转而用代码方式启动MySQL服务进程
        QProcess process;
        process.start("C:/Program Files/MySQL/MySQL Server 5.6/bin/mysqld.exe");
        //第二次尝试连接
        if(!createMySqlConn()) return 1;
    }

    LoginDialog logindlg;


    if(logindlg.exec() == QDialog::Accepted)
    {
        MainWindow w;
        w.show();
        return a.exec();
    }
    else
    {
        return 0;
    }
    

    
}

eMarket.pro

#-------------------------------------------------
#
# Project created by QtCreator 2021-09-13T20:26:29
#
#-------------------------------------------------

QT       += core gui
QT       += sql

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = eMarket
TEMPLATE = app

# The following define makes your compiler emit warnings if you use
# any feature of Qt which as 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 \
    logindialog.cpp

HEADERS += \
        mainwindow.h \
    logindialog.h

FORMS += \
        mainwindow.ui \
    logindialog.ui

四、知识点总结

1、界面设计

控件、布局的使用

2、数据库操作

2.1 QSqlQueryModel 是数据库查询模型,属于模型视图结构

 QSqlQueryModel 是 QSqlTableModel 的父类。QSqlQueryModel 封装了执行 SELECT 语句从数据库查询数据的功能,但是 QSqlQueryModel 只能作为只读数据源使用,不可以编辑数据 。

QSqlQueryModel *categoryModel = new QSqlQueryModel(this);//创建了一个商品类别表模型,与商品类别表通信
categoryModel->setQuery();//执行SQL语句操作
ui->newCategoryComboBox->setModel(categoryModel);//将查询的结果当作商品类别列表加载(新品入库页)
QSqlQueryModel *categoryModel = new QSqlQueryModel(this);//商品类别模型数据
categoryModel->setQuery("select Name from category");
ui->newCategoryComboBox->setModel(categoryModel);//商品类别列表加载(新品入库页)

2.2数据库中图片查询,label显示

    QPixmap photo;
    QModelIndex index;
    QSqlQueryModel *pictureModel = new QSqlQueryModel(this);//商品样照模型数据
    QString name = ui->newNameLineEdit->text();
    pictureModel->setQuery("select Picture from commodity where Name='" + name + "'");
    index = pictureModel->index(0, 0);
    photo.loadFromData(pictureModel->data(index).toByteArray(), "JPG");
    ui->newPictureLabel->setPixmap(photo);

2.3数据库插入图片

//插入照片
    QByteArray picdata;
    QBuffer buffer(&picdata);
    buffer.open(QIODevice::WriteOnly);
    myPicImg.save(&buffer, "JPG");//用QImage对象储存要写入数据库的照片数据
    QVariant var(picdata);
    QString sqlstr = "update commodity set Picture=? where Name='" + name + "'";
    query.prepare(sqlstr);
    query.addBindValue(var);//绑定照片数据作为参数传给?处
    if(!query.exec())
    {
        QMessageBox::information(0, QObject::tr("提示"), "照片写入失败");
    }

2.4数据库常用函数

1 QSqlQuery::next() 从数据库的开头一直往下找,如果某一行存了数据则返回1,如果是1个空行,则返回0
2 QSqlQuery::value(0) 如果存入数据库的数据是00 11 11 11 11 则打印出来的是QVariant(QString, "00111111") 转成字符串类型 QSqlQuery::value(0).toString()则打印出来的结果为 00 11 11 11 11
3 QSqlQuery::value(1).toString() 打印出来的则是""
4 QSqlQuery::size() 数据库中如果存了多少条数据,这个值就是多少。

你可能感兴趣的:(qt,c++)