1, Functional requirements analysis
1. Login function
The user needs to enter the user name and password to log in to the mall system. The password is protected in the form of password. If the password is incorrect, re-enter it.
The interface is mainly composed of label, LineEdit, pushbutton and other controls
2. Mall system function
2.1 new product warehousing function
Realize the warehousing of new products, the clearance of sold and unsold products, and display the inventory, purchase price, selling price, name, category and sample photos of commodities in the database.
The interface is mainly composed of label, LineEdit, pushbutton, TableView and other controls
2.2 pre sale order function
It provides the function of pre-sale goods. You can select commodity category, name, quantity, inventory and sales price, and calculate the total amount.
The interface mainly uses label, LineEdit, pushbutton and ListWidget and other controls
2, Development environment
win10+QT5.9_MinGW+MySQL5.7
3, Implementation details
1. Engineering structure
2. Implementation of login function
All the implementation codes are in the logindialog class and inherit Qdialog
The main functions include login button click event and exit login event
Login button click event: query the password in the database through the user name, and then compare it with the password in the password box. The same verification passes, but the different message box pops up indicating failure, and re-enter the password
Exit login event: directly call the QDialog::reject() function to exit the login interface.
logindialog.h
#ifndef LOGINDIALOG_H #define LOGINDIALOG_H #include <QDialog> #Include < qsqlquery > / / query the Mysql database #include <QMessageBox> #Include < qcryptographichash > / / including MD5 algorithm library namespace Ui { class LoginDialog; } class LoginDialog : public QDialog { Q_OBJECT public: explicit LoginDialog(QWidget *parent = 0); ~LoginDialog(); QString strToMd5(QString str); //Convert password string to MD5 encryption private slots: void on_loginPushButton_clicked();//Login button click the event slot void on_exitPushButton_clicked(); //Exit button click the event slot 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); //Login dialog fixed size ui->pwdLineEdit->setFocus(); //Password frame focus } 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("Database connection failed"),"Unable to create connection! Please check and restart the program after troubleshooting.",QMessageBox::Cancel); } QSqlQuery query(d); QString admin = ui->adminLineEdit->text(); query.exec("select PassWord from member where MemberID='" + admin + "'");//Query the export order password field from the database query.next(); QString pwdMd5 = ui->pwdLineEdit->text(); QString pwd = query.value(0).toString(); if( pwd == pwdMd5) { QDialog::accept();//Verification passed } else { QMessageBox::warning(this,tr("password error"),tr("Please enter the correct password!"),QMessageBox::Ok); ui->pwdLineEdit->clear(); ui->pwdLineEdit->setFocus(); } } else { ui->pwdLineEdit->setFocus(); } } void LoginDialog::on_exitPushButton_clicked() { QDialog::reject();//Exit login box } QString LoginDialog::strToMd5(QString str) { QString strMd5; QByteArray qba; qba = QCryptographicHash::hash(str.toLatin1(),QCryptographicHash::Md5); strMd5.append(qba.toHex()); return strMd5; }
3. Function realization of mall system
The function of mall system is realized in mainwindow class
3.1 interface initialization function
Initialize the information displayed on the interface
Display the new product warehousing page in the front
Import product categories into drop-down options
void MainWindow::initMainWindow() { ui->stackedWidget->setCurrentIndex(1); ui->toolBox->setCurrentIndex(0); QSqlQueryModel *categoryModel = new QSqlQueryModel(this);//Commodity category model data categoryModel->setQuery("select Name from category"); ui->newCategoryComboBox->setModel(categoryModel);//Loading commodity category list (new product warehousing page) commodity_model = new QSqlTableModel(this);//Product information view commodity_model->setTable("commodity_inf"); commodity_model->select(); ui->commodityTableView->setModel(commodity_model);//Inventory commodity record data grid information loading (new product warehousing page) ui->preCategoryComboBox->setModel(categoryModel);//Product category list loading (pre-sale order page) loadPreCommodity();//Load product information on the pre-sale order page myMemberID = "b02020622"; //myOrdered = false; myOrdered = true; //myOrderID = 0; myOrderID = 4; myPaySum = 0; QListWidgetItem *title = new QListWidgetItem; title->setText(QString("Current order [No.] %1 ]").arg(myOrderID)); title->setTextAlignment(Qt::AlignCenter); //ui->sellListWidget->addItem(title); }
3.2 new product warehousing function
Warehousing operation
//Warehousing operation void MainWindow::on_newPutinStorePushButton_clicked() { QSqlQuery query; query.exec(QString("select CategoryID from category where Name='%1'"). arg(ui->newCategoryComboBox->currentText()));//Query category ID by category alias query.next(); int categoryid = query.value(0).toInt();//Commodity category to be warehoused QString name = ui->newNameLineEdit->text();//Trade name float inputprice = ui->newInputPriceLineEdit->text().toFloat();//Purchase price float outputprice = ui->newOutputPriceLineEdit->text().toFloat();//price int count = ui->newCountSpinBox->value();//Stock in quantity 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));//Insert new incoming goods record //Insert photo QByteArray picdata; QBuffer buffer(&picdata); buffer.open(QIODevice::WriteOnly); myPicImg.save(&buffer, "JPG");//Use the QImage object to store the photo data to be written to the database QVariant var(picdata); QString sqlstr = "update commodity set Picture=? where Name='" + name + "'"; query.prepare(sqlstr); query.addBindValue(var);//Bind the photo data as a parameter and pass it to the location if(!query.exec()) { QMessageBox::information(0, QObject::tr("Tips"), "Photo writing failed"); } //Refresh grid information commodity_model->setTable("commodity_inf"); commodity_model->select(); ui->commodityTableView->setModel(commodity_model);//Refresh data grid (new product warehousing page) }
Sample selection photo
void MainWindow::on_newUploadPushButton_clicked() { QString picturename = QFileDialog::getOpenFileName(this, "Select product picture", ".", "Image File(*.png *.jpg *.jpeg *.bmp)"); if (picturename.isEmpty()) return; myPicImg.load(picturename); ui->newPictureLabel->setPixmap(QPixmap::fromImage(myPicImg)); }
Clearing operation
//Clearing operation void MainWindow::on_newClearancePushButton_clicked() { QSqlQuery query; query.exec(QString("delete from commodity where Name='%1'").arg(ui->newNameLineEdit->text()));//Delete product record //Refresh interface 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);//Refresh data grid (new product warehousing page) }
3.3 pre sale order function
Sale of goods
//Sale of goods 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(); } //Let's start pre-sale query.exec(QString("select CommodityID from commodity where Name='%1'").arg(ui->preNameComboBox->currentText())); query.next(); int commodityid = query.value(0).toInt();//Item no. of this pre-sale int count = ui->preCountSpinBox->value();//Pre sale volume int amount = ui->preCountSpinBox->maximum() - count;//Remaining inventory QSqlDatabase::database().transaction();//Start a transaction bool insOk = query.exec(QString("insert into orderitems(OrderID, CommodityID, Count) values(%1, %2, %3)").arg(myOrderID).arg(commodityid).arg(count));//Add order item bool uptOk = query.exec(QString("update commodity set Amount=%1 where CommodityID=%2").arg(amount).arg(commodityid));//Update inventory if (insOk && uptOk) { QSqlDatabase::database().commit(); onPreNameComboBoxChange(); //Show pre-sale list 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 + " " + "Sold:" + curname + "\r\n number:" + curcount + ";Unit Price:" + curoutprice + "¥;Total price:" + 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("Tips"), "Order added!"); } else { QSqlDatabase::database().rollback(); } }
Place an order
//Place an order void MainWindow::on_prePlaceOrderPushButton_clicked() { QSqlQuery query; QString otime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"); QSqlDatabase::database().transaction();//Start a transaction bool ordOk = query.exec(QString("update orders set PaySum=%1, OTime='%2' where OrderID=%3").arg(myPaySum).arg(otime).arg(myOrderID));//Place an order bool uptOk = query.exec(QString("update orderitems set Affirm=1, SendGoods=1 where OrderID=%1").arg(myOrderID));//Confirm shipment if (ordOk && uptOk) { QSqlDatabase::database().commit(); ui->prePlaceOrderPushButton->setEnabled(false); //Display order record QString order_record = "Date:" + otime + "\r\n order number:" + QString(" %1 ").arg(myOrderID) + "\r\n Total payables:" + QString(" %1¥").arg(myPaySum) + "\r\n Order successfully!"; 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("Tips"), "Order successfully!"); commodity_model->setTable("commodity_inf"); commodity_model->select(); ui->commodityTableView->setModel(commodity_model);//Refresh data grid (new product warehousing page) } else { QSqlDatabase::database().rollback(); } }
3.4 complete code
mainwidow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QMessageBox> #include <QFileDialog> #include <QBuffer> //#include "opencv2/opencv.hpp" #Include < QSqlDatabase > / / MySQL database class #Include < qsqltablemodel > / / MySQL table model library #Include < qsqlquery > / / MySQL query class library #include <QTime> #Include < qpixmap > / / image processing class library //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); //Commodity information data grid and form linkage void showCommodityPhoto(); //Display sample photos void loadPreCommodity(); //Load the list of product names on the pre-sale order page void onPreNameComboBoxChange(); //Pre sale order page commodity name and form linkage private slots: void on_commodityTableView_clicked(const QModelIndex& index);//Commodity information data grid click event slot void on_newPutinStorePushButton_clicked();//Stock in button event Click event slot void on_preCategoryComboBox_currentIndexChanged(int index);//Category and commodity name list linkage information slot void on_preNameComboBox_currentIndexChanged(int index);//Reselect trade name information slot void on_preCountSpinBox_valueChanged(int arg1);//Number of goods sold change information slot void on_preSellPushButton_clicked();//Sell button click event void on_prePlaceOrderPushButton_clicked();//Order button click event void on_newUploadPushButton_clicked();//Upload button event Click event slot void on_newClearancePushButton_clicked();//Clearance button event Click event slot private: Ui::MainWindow *ui; QImage myPicImg; //Save commodity sample photo (interface display) QSqlTableModel *commodity_model; //Model for accessing database commodity information view QString myMemberID; //Member account bool myOrdered; //Are you purchasing (the order has been written to the database) int myOrderID; //Order No float myPaySum; //Cumulative total amount to be paid for the current order }; /**Static method for accessing MySQL database*/ static bool createMySqlConn() { QSqlDatabase sqldb = QSqlDatabase::addDatabase("QMYSQL"); sqldb.setHostName("localhost"); sqldb.setDatabaseName("emarket");//Database name sqldb.setUserName("root"); //Database user name sqldb.setPassword("123456"); //Login password if (!sqldb.open()) { QMessageBox::critical(0, QObject::tr("Background database connection failed"), "Unable to create connection! Please check and restart the program after troubleshooting.", QMessageBox::Cancel); return false; } //QMessageBox::information(0, QObject::tr("background database started and running..."), "database connection succeeded! Application will be started soon.); //Insert photos into the database /*QSqlQuery query(sqldb); QString photoPath = "D:\\Qt\\imgproc\\21.jpg";//Photos cannot be greater than 60K QFile photoFile(photoPath); if (photoFile.exists()) { //Stored in database 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("Prompt ")," photo writing failed "); } else{ QMessageBox::information(0, QObject::tr("Prompt ")," photos have been written to the database "); } } 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);//Commodity category model data categoryModel->setQuery("select Name from category"); ui->newCategoryComboBox->setModel(categoryModel);//Loading commodity category list (new product warehousing page) commodity_model = new QSqlTableModel(this);//Product information view commodity_model->setTable("commodity_inf"); commodity_model->select(); ui->commodityTableView->setModel(commodity_model);//Inventory commodity record data grid information loading (new product warehousing page) ui->preCategoryComboBox->setModel(categoryModel);//Product category list loading (pre-sale order page) loadPreCommodity();//Load product information on the pre-sale order page myMemberID = "b02020622"; //myOrdered = false; myOrdered = true; //myOrderID = 0; myOrderID = 4; myPaySum = 0; QListWidgetItem *title = new QListWidgetItem; title->setText(QString("Current order [No.] %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); //name ui->newNameLineEdit->setText(commodity_model->data(index).toString()); index = commodity_model->index(r, 1); //Purchase price ui->newInputPriceLineEdit->setText(commodity_model->data(index).toString()); index = commodity_model->index(r, 2); //price ui->newOutputPriceLineEdit->setText(commodity_model->data(index).toString()); showCommodityPhoto(); //Commodity sample photo 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());//Category linkage } void MainWindow::showCommodityPhoto() { QPixmap photo; QModelIndex index; QSqlQueryModel *pictureModel = new QSqlQueryModel(this);//Commodity sample model data 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);//Commodity name model data commodityNameModel->setQuery(QString("select Name from commodity where CategoryID=(select CategoryID from category where Name='%1')").arg(ui->preCategoryComboBox->currentText())); ui->preNameComboBox->setModel(commodityNameModel);//Product name list loading (pre-sale order page) onPreNameComboBoxChange(); } void MainWindow::onPreNameComboBoxChange() { QSqlQueryModel *preCommodityModel = new QSqlQueryModel(this);//Commodity table model data QString name = ui->preNameComboBox->currentText(); preCommodityModel->setQuery("select OutputPrice, Amount, Picture from commodity where Name='" + name + "'"); QModelIndex index; index = preCommodityModel->index(0, 0); //Unit Price ui->preOutputPriceLabel->setText(preCommodityModel->data(index).toString()); index = preCommodityModel->index(0, 1); //stock ui->preAmountLabel->setText(preCommodityModel->data(index).toString()); ui->preCountSpinBox->setMaximum(ui->preAmountLabel->text().toInt()); //Let's start getting and showing photos QPixmap photo; index = preCommodityModel->index(0, 2); photo.loadFromData(preCommodityModel->data(index).toByteArray(), "JPG"); ui->prePictureLabel->setPixmap(photo); //Calculate total price 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)); } //Sale of goods 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(); } //Let's start pre-sale query.exec(QString("select CommodityID from commodity where Name='%1'").arg(ui->preNameComboBox->currentText())); query.next(); int commodityid = query.value(0).toInt();//Item no. of this pre-sale int count = ui->preCountSpinBox->value();//Pre sale volume int amount = ui->preCountSpinBox->maximum() - count;//Remaining inventory QSqlDatabase::database().transaction();//Start a transaction bool insOk = query.exec(QString("insert into orderitems(OrderID, CommodityID, Count) values(%1, %2, %3)").arg(myOrderID).arg(commodityid).arg(count));//Add order item bool uptOk = query.exec(QString("update commodity set Amount=%1 where CommodityID=%2").arg(amount).arg(commodityid));//Update inventory if (insOk && uptOk) { QSqlDatabase::database().commit(); onPreNameComboBoxChange(); //Show pre-sale list 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 + " " + "Sold:" + curname + "\r\n number:" + curcount + ";Unit Price:" + curoutprice + "¥;Total price:" + 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("Tips"), "Order added!"); } else { QSqlDatabase::database().rollback(); } } //Place an order void MainWindow::on_prePlaceOrderPushButton_clicked() { QSqlQuery query; QString otime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"); QSqlDatabase::database().transaction();//Start a transaction bool ordOk = query.exec(QString("update orders set PaySum=%1, OTime='%2' where OrderID=%3").arg(myPaySum).arg(otime).arg(myOrderID));//Place an order bool uptOk = query.exec(QString("update orderitems set Affirm=1, SendGoods=1 where OrderID=%1").arg(myOrderID));//Confirm shipment if (ordOk && uptOk) { QSqlDatabase::database().commit(); ui->prePlaceOrderPushButton->setEnabled(false); //Display order record QString order_record = "Date:" + otime + "\r\n order number:" + QString(" %1 ").arg(myOrderID) + "\r\n Total payables:" + QString(" %1¥").arg(myPaySum) + "\r\n Order successfully!"; 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("Tips"), "Order successfully!"); commodity_model->setTable("commodity_inf"); commodity_model->select(); ui->commodityTableView->setModel(commodity_model);//Refresh data grid (new product warehousing page) } else { QSqlDatabase::database().rollback(); } } //Sample selection photo void MainWindow::on_newUploadPushButton_clicked() { QString picturename = QFileDialog::getOpenFileName(this, "Select product picture", ".", "Image File(*.png *.jpg *.jpeg *.bmp)"); if (picturename.isEmpty()) return; myPicImg.load(picturename); ui->newPictureLabel->setPixmap(QPixmap::fromImage(myPicImg)); } //Warehousing operation void MainWindow::on_newPutinStorePushButton_clicked() { QSqlQuery query; query.exec(QString("select CategoryID from category where Name='%1'"). arg(ui->newCategoryComboBox->currentText()));//Query category ID by category alias query.next(); int categoryid = query.value(0).toInt();//Commodity category to be warehoused QString name = ui->newNameLineEdit->text();//Trade name float inputprice = ui->newInputPriceLineEdit->text().toFloat();//Purchase price float outputprice = ui->newOutputPriceLineEdit->text().toFloat();//price int count = ui->newCountSpinBox->value();//Stock in quantity 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));//Insert new incoming goods record //Insert photo QByteArray picdata; QBuffer buffer(&picdata); buffer.open(QIODevice::WriteOnly); myPicImg.save(&buffer, "JPG");//Use the QImage object to store the photo data to be written to the database QVariant var(picdata); QString sqlstr = "update commodity set Picture=? where Name='" + name + "'"; query.prepare(sqlstr); query.addBindValue(var);//Bind the photo data as a parameter and pass it to the location if(!query.exec()) { QMessageBox::information(0, QObject::tr("Tips"), "Photo writing failed"); } //Refresh grid information commodity_model->setTable("commodity_inf"); commodity_model->select(); ui->commodityTableView->setModel(commodity_model);//Refresh data grid (new product warehousing page) } //Clearing operation void MainWindow::on_newClearancePushButton_clicked() { QSqlQuery query; query.exec(QString("delete from commodity where Name='%1'").arg(ui->newNameLineEdit->text()));//Delete product record //Refresh interface 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);//Refresh data grid (new product warehousing page) }
main.cpp
#include "mainwindow.h" #include <QApplication> #include "logindialog.h" #Include < qpprocess > / / Qt process module int main(int argc, char *argv[]) { QApplication a(argc, argv); if(!createMySqlConn()) { //If the initial attempt to connect is unsuccessful, start the MySQL service process in code mode instead QProcess process; process.start("C:/Program Files/MySQL/MySQL Server 5.6/bin/mysqld.exe"); //Second attempt to connect 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
4, Summary of knowledge points
1. Interface design
Use of controls and layouts
2. Database operation
2.1 QSqlQueryModel is a database query model and belongs to the model view structure
QSqlQueryModel Is the parent class of QSqlTableModel. Qsqlquerymodel encapsulates the function of executing SELECT statements to query data from the database, but qsqlquerymodel can only be used as a read-only data source and cannot edit data.
QSqlQueryModel *categoryModel = new QSqlQueryModel(this);// A product category table model is created to communicate with the product category table
categoryModel->setQuery();// Execute SQL statement operation
ui->newCategoryComboBox->setModel(categoryModel);// Load the query results as a list of commodity categories (new product warehousing page)
QSqlQueryModel *categoryModel = new QSqlQueryModel(this);//Commodity category model data categoryModel->setQuery("select Name from category"); ui->newCategoryComboBox->setModel(categoryModel);//Loading commodity category list (new product warehousing page)
2.2 image query and label display in the database
QPixmap photo; QModelIndex index; QSqlQueryModel *pictureModel = new QSqlQueryModel(this);//Commodity sample model data 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 inserting pictures into database
//Insert photo QByteArray picdata; QBuffer buffer(&picdata); buffer.open(QIODevice::WriteOnly); myPicImg.save(&buffer, "JPG");//Use the QImage object to store the photo data to be written to the database QVariant var(picdata); QString sqlstr = "update commodity set Picture=? where Name='" + name + "'"; query.prepare(sqlstr); query.addBindValue(var);//Bind photo data as a parameter to? place if(!query.exec()) { QMessageBox::information(0, QObject::tr("Tips"), "Photo writing failed"); }
2.4 common database functions
1 QSqlQuery::next() looks down from the beginning of the database. If data is saved in a row, it returns 1. If it is an empty row, it returns 0 2 QSqlQuery::value(0) if the data stored in the database is 00 11, the printed result is QVariant(QString, "00111111") converted to string type QSqlQuery::value(0).toString(), and the printed result is 00 11 3. Qsqlquery:: value (1). Tostring() prints "" 4. If there are many pieces of data stored in the qsqlquery:: size() database, the value is the same.