枪械管理系统

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

#include <QTextCodec>
#include <QDebug>
#include <QSqlDatabase>
#include <QMessageBox>
#include <QSqlQuery>
#include <QString>
#include <QPoint>
#include <QSqlError>
#include <QDataWidgetMapper>
#include <QWidget>
#include <QJsonParseError>
#include <QJsonDocument>
#include <QJsonObject>
#include <QFile>
#include <QList>
#include <QVariant>
#include <QMap>
#include <QStringList>

#include "logindialog.h"
#include "addweaponsdialog.h"
#include "addweapondialog.h"
#include "modifydialog.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("枪械管理系统"); //设置mainWindow窗口的标题
    this->setWindowIcon(QIcon("/home/class/qt/Equipment_System/jpg/system.jpg")); //设置dialog窗口的图标

    initTree();

    //ui->treeWidget->setHeaderHidden(true);//隐藏树的标题栏
    ui->treeWidget->setContextMenuPolicy(Qt::CustomContextMenu);//右键 不可少否则右键无反应
    connect(ui->treeWidget,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(showrightMenu(QPoint)));

    popMenu = new QMenu(this);
    addParent = new QAction("增加父类",this);
    addChild = new QAction("增加子类",this);
    remove = new QAction("删除",this);
    modify = new QAction("修改",this);
    connect(addParent,SIGNAL(triggered(bool)),this,SLOT(onAddParentActionTriggered()));
    connect(addChild,SIGNAL(triggered(bool)),this,SLOT(onAddChildActionTriggered()));
    connect(remove,SIGNAL(triggered(bool)),this,SLOT(onRemoveActionTriggered()));
    connect(modify,SIGNAL(triggered(bool)),this,SLOT(onModifyActionTriggered()));

    connect(ui->treeWidget,SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),
                this,SLOT(showAtti())); //连接对应槽函数(鼠标双击事件)

    connect(ui->editButton,SIGNAL(clicked(bool)),this,SLOT(onEditButtonclicked()));
    connect(ui->finishButton,SIGNAL(clicked(bool)),this,SLOT(onFinishButtonclicked()));

}

MainWindow::~MainWindow()
{
    //new了就需要delete
    delete popMenu;
    delete addParent;
    delete addChild;
    delete remove;
    delete modify;
    delete ui;
}

void MainWindow::initTree()
{
    // header
    QStringList ls ;
    ls << "枪械管理系统";//放tree头
    ui->treeWidget->setHeaderLabels(ls);

    QSqlDatabase db=QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("127.0.0.1");
    db.setDatabaseName("weapon");//自己建数据库名
    db.setUserName("root");
    db.setPassword("123456");
    db.exec("set NAMES UTF8");   //加上这一行,可以正常显示中文
    bool ok=db.open();
    if( ok ){
        QSqlQuery query;

        bool ok = query.exec("select * from model;");//按照id的正序排序,从第1条开始取1条数据  "
        if(!ok)
            qDebug() << "+++++++++++++>" << db.lastError();
        while(query.next())
        {
            QString name = query.value(1).toString();//取第i条记录第1个字段(从0开始计数)的结果
            QString type = query.value(2).toString();

            QTreeWidgetItem *it= new QTreeWidgetItem;
            it->setText(0, name);
            ui->treeWidget->addTopLevelItem(it);

            //任老师修改
            QString s("select * from device where model='%2'");
            s = s.arg(type);
            qDebug() << s;
            QSqlQuery query1(db);
            bool ok1 = query1.exec(s);
            //if(!ok1)
            //    qDebug() << db.lastError();
            while(query1.next()) {
                QString childname = query1.value(1).toString();
                qDebug() << childname;
                QTreeWidgetItem *child= new QTreeWidgetItem;
                child->setText(0, childname);
                it->addChild(child);
            }
        }


    }else{
        qDebug()<<"QSqlQuery open error";
    }
}


void MainWindow::showrightMenu(QPoint point)
{
    popMenu->clear();//清除原有菜单
    popMenu->addAction(addParent);//如果放这是全局都有的右键
    popMenu->addAction(addChild);
    popMenu->addAction(remove);
    popMenu->addAction(modify);
    //QTreeWidgetItem *item = tree->itemAt(point); //可得到右键条目
    //QTreeWidgetItem* curItem=treeWidget->currentItem(); //获取当前被点击的节点
    m_currentItem = ui->treeWidget->currentItem();
    popMenu->exec(QCursor::pos());//在当前鼠标位置显示
}

//添加父类
void MainWindow::onAddParentActionTriggered()
{
    QSqlDatabase db=QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("127.0.0.1");
    db.setDatabaseName("weapon");//自己建数据库名
    db.setUserName("root");
    db.setPassword("123456");
    db.exec("set NAMES UTF8");   //加上这一行,可以正常显示中文
    bool ok=db.open();
    if( ok ){
        addweaponSDialog addweapon;
        int ret = addweapon.exec();
        QString message1 = addweapon.Name();
        QString message2 = addweapon.Type();

        QString getname = ui->treeWidget->currentItem()->text(0); //获取被点击的根目录名称
        qDebug() << getname;

        if( message1.isEmpty() || message2.isEmpty() ){ //如果添加的信息其中一个为空返回
            QMessageBox mbox;
            mbox.setWindowTitle("OK!");
            mbox.setText("请输入完整信息!");
            mbox.setStandardButtons(QMessageBox::Yes);
            mbox.exec();
            mbox.close();
            return ;
        }

        QTreeWidgetItem *it = new QTreeWidgetItem;
        it->setText(0,message1);
        ui->treeWidget->addTopLevelItem( it );

        QSqlQuery query;
        QString newname;
        QString mtr = QString("select * from model where name='%1';");//
        query.exec(mtr);
        while(query.next()){
            newname = query.value(1).toString();//取第i条记录第1个字段(从0开始计数)的结果 数据库表有id占用0计数
        }if(NULL != newname){
            QMessageBox mbox;
            mbox.setWindowTitle("Error");
            mbox.setText("信息已存在!");
            mbox.setStandardButtons(QMessageBox::Yes);
            mbox.exec();
        }else if(NULL == newname){
                QString str = QString("insert into model(name,type)values('%1','%2');").arg(message1).arg(message2);
                qDebug()<<str;
                if(query.exec(str)){//在数据库里成功插入一条信息
                    QMessageBox mbox1;
                    mbox1.setWindowTitle("OK!");
                    mbox1.setText("添加成功!");
                    mbox1.setStandardButtons(QMessageBox::Yes);
                    mbox1.exec();
                }
        }

        db.close();

    }


    qDebug() << "open secon";
    db.close();
}

//添加子类
void MainWindow::onAddChildActionTriggered()
{   
    QSqlDatabase db=QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("127.0.0.1");
    db.setDatabaseName("weapon");//自己建数据库名
    db.setUserName("root");
    db.setPassword("123456");
    db.exec("set NAMES UTF8");   //加上这一行,可以正常显示中文
    bool ok=db.open();
    if( ok ){
        addweaponDialog addweapon;
        int ret = addweapon.exec();
        QString message1 = addweapon.Name();
        QString message2 = addweapon.Type();
        QString message3 = addweapon.Model();
        QString message4 = addweapon.Atti();

        ui->textEdit->setText(message4); //添加枪械属性到textEdit

        if( message1.isEmpty() || message2.isEmpty() || message3.isEmpty() ){ //如果添加的信息其中一个为空返回
            QMessageBox mbox;
            mbox.setWindowTitle("OK!");
            mbox.setText("请输入完整信息!");
            mbox.setStandardButtons(QMessageBox::Yes);
            mbox.exec();
            mbox.close();
            return ;
        }

        QTreeWidgetItem *cit = new QTreeWidgetItem;
        cit->setText(0,message1);
        m_currentItem->addChild( cit ); //m_currentItem点击选中为父类

        QSqlQuery query;
        QString newname;
        QString mtr = QString("select * from device where name='%1';").arg(message1);
        query.exec(mtr);
        while(query.next()){
            newname = query.value(1).toString();//取第i条记录第1个字段(从0开始计数)的结果 数据库表有id占用0计数
        }if(NULL != newname){
            QMessageBox mbox;
            mbox.setWindowTitle("Error");
            mbox.setText("信息已存在!");
            mbox.setStandardButtons(QMessageBox::Yes);
            mbox.exec();
        }else if(NULL == newname){
                QString str = QString("insert into device(name,type,model,atti)values('%1','%2','%3','%4');").arg(message1).arg(message2).arg(message3).arg(message4);
                qDebug()<<str;
                if(query.exec(str)){//在数据库里成功插入一条信息
                    QMessageBox mbox1;
                    mbox1.setWindowTitle("OK!");
                    mbox1.setText("添加成功!");
                    mbox1.setStandardButtons(QMessageBox::Yes);
                    mbox1.exec();
                }
        }
    }

}

//删除treewidget节点
void MainWindow::onRemoveActionTriggered()
{
    QSqlDatabase db=QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("127.0.0.1");
    db.setDatabaseName("weapon");//自己建数据库名
    db.setUserName("root");
    db.setPassword("123456");
    db.exec("set NAMES UTF8");   //加上这一行,可以正常显示中文
    bool ok=db.open();
    if( ok ){
        QSqlQuery query;

        if(m_currentItem->parent() == 0){ //被点击的是父节点,删除父节点

            QString getname = ui->treeWidget->currentItem()->text(0); //获取被点击的根目录名称
            qDebug() << getname;
            QString str = QString("delete from model where name = '%1';").arg(getname); //把 用.arg()将字符串father 组成字符串传给'%1'去执行删除命令
            query.exec(str);

            int i = ui->treeWidget->indexOfTopLevelItem(m_currentItem);//index指的是QList中的序号
            m_currentItem->takeChildren();
            ui->treeWidget->takeTopLevelItem(i);

            QMessageBox mbox1;
            mbox1.setWindowTitle("OK!");
            mbox1.setText("删除成功!");
            mbox1.setStandardButtons(QMessageBox::Yes);
            mbox1.exec();

        }else{ //被点击的子节点,删除子结点

            QString child = ui->treeWidget->currentItem()->text(0); //获取被点击的子目录名称
            qDebug() << child;
            QString str = QString("delete from device where name = '%1';").arg(child); //把 用.arg()将字符串father 组成字符串传给'%1'去执行删除命令
            query.exec(str);

            m_currentItem->parent()->removeChild(m_currentItem);

            QMessageBox mbox1;
            mbox1.setWindowTitle("OK!");
            mbox1.setText("删除成功!");
            mbox1.setStandardButtons(QMessageBox::Yes);
            mbox1.exec();
        }
    }
}

//修改treewidget节点
void MainWindow::onModifyActionTriggered()
{
    QString getname = ui->treeWidget->currentItem()->text(0); //获取被点击的根目录名称
    qDebug() << getname;

    modifyDialog mod;
    int ret = mod.exec();
    QString newname = mod.Name(); //获取modifyDialog中写入的名称

    QTreeWidgetItem * currentItem = ui->treeWidget->currentItem(); //取得当前的item

    if( newname.isEmpty() ){ //如果添加的信息其中一个为空返回
        QMessageBox mbox;
        mbox.setWindowTitle("OK!");
        mbox.setText("修改信息不能为空!");
        mbox.setStandardButtons(QMessageBox::Yes);
        mbox.exec();
        mbox.close();
        return ;
    }

    //修改界面目录
    if(currentItem==Q_NULLPTR){
        return;
    }
    for(int i=0;i<currentItem->columnCount();i++){
            currentItem->setText(i,newname );
    }

    QSqlDatabase db=QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("127.0.0.1");
    db.setDatabaseName("weapon");//自己建数据库名
    db.setUserName("root");
    db.setPassword("123456");
    db.exec("set NAMES UTF8");   //加上这一行,可以正常显示中文
    bool ok=db.open();
    if( ok ){

        QSqlQuery query;
        QString name = mod.Name();
        qDebug() << name;

        //根据name去修改名称
        QString str = QString("update device set name = '%1' where name = '%2';").arg(name).arg(getname); //把 用.arg()将字符串father 组成字符串传给'%1'去执行删除命令
        query.exec(str);
    }

}

void MainWindow::showAtti()
{
    QSqlDatabase db=QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("127.0.0.1");
    db.setDatabaseName("weapon");//自己建数据库名
    db.setUserName("root");
    db.setPassword("123456");
    db.exec("set NAMES UTF8");   //加上这一行,可以正常显示中文
    bool ok=db.open();
    if( ok ){
        QSqlQuery query;
        QString message;

        QString getname = ui->treeWidget->currentItem()->text(0); //获取被点击的根目录名称
        qDebug() << getname;

        QString mstr = QString("select * from device where name='%1';").arg(getname);
        query.exec( mstr );
        while ( query.next() ) {
          message = query.value(4).toString(); //获取数据库表atti枪械属性
        }

        //先把在数据库读到枪械的属性用Qjson解析出来再放到textEdit显示
        QFile jsonfile("/home/class/qt/Equipment_System/testFile.json"); //创建//.json文件
        if ( !jsonfile.open(QFile::ReadWrite | QFile::Text) ) {
            qDebug() << "jsonfile open error!";
            return ;
        }
        QTextStream in( &jsonfile );
        in << message ; //将在数据库读到枪械的属性存到.json文件
       // jsonfile.close();


//            if (!jsonfile.open(QIODevice::ReadOnly | QIODevice::Text))
//              return ;
//            QByteArray str = jsonfile.readAll ();
//            qDebug() << str.constData();
//            bool ok;
//            QList<QVariant> result = Qtjson::parse(str, ok).toList ();
//            for ( int i = 0 ; i < result.size () ; i ++ )
//            {
//                QVariant tmp = result.at (i);
//                QMap<QString, QVariant> result = tmp.toMap ();
//                qDebug () << result.keys ()<< result.values ();
//            }
//            jsonfile.close ();

        QByteArray byte_array = jsonfile.readAll();
        jsonfile.resize(0);

        qDebug() << byte_array.constData();
        QJsonParseError json_error;
        QJsonDocument parse_doucment = QJsonDocument::fromJson(byte_array, &json_error);

        if(json_error.error == QJsonParseError::NoError)
        {
            if(parse_doucment.isObject())
            {
                QString name;

                ui->textEdit->clear(); //每次点击新的枪械先清空原有的属性,再显示点击后的枪械属性

                QJsonObject obj = parse_doucment.object();
                //输出所有key,这一步是非必须的
                QStringList keys = obj.keys();
                for(int i = 0; i < keys.size(); i++)
                {
                    qDebug() << "key" << i << " is:" << keys.at(i);
                    QString k = keys.at(i);
                    QJsonValue name_value = obj.take(keys.at(i)); //如果列表里面有相应的key,key有相对应的value就解析出来
                    if( name_value.isString() ){
                        name = name_value.toString();
                    }
                    qDebug() <<  k << "::" << name;

                    ui->textEdit->append( k ); //append()为换行追加
                    ui->textEdit->insertPlainText(":"); //在 k 的后面插入 :
                    ui->textEdit->insertPlainText( name ); //在 : 的后面插入字符串name
                }
                ui->textEdit->setReadOnly(true); //设置textEdit为只读模式
                ui->textEdit->setFont(QFont(tr("Consolas"), 14)); //设置textEdit文字大小

            }
        }
        jsonfile.resize(0); // 清空文件中的原有内容
        jsonfile.close();
    }
}

void MainWindow::onEditButtonclicked()
{
    ui->textEdit->setReadOnly(false); //设置textEdit取消只读模式
}

void MainWindow::onFinishButtonclicked()
{
    ui->textEdit->setReadOnly(true); //设置textEdit为只读模式

    //把textEdit的文本生成josn
    QString getmessage = ui->textEdit->toPlainText(); //获取textEdit上的普通文本
    qDebug() << getmessage;
    QStringList list = getmessage.split("\n");

    qDebug() << "++++++++++++++++++++" << list.size(); //textEdit文本行数
    QString key, value;
    QJsonObject json; //生成json

    for(int i = 0;i < list.size();i++){
        key = list.at( i ).split(":").at(0); //将具体名称等属性截断出来 这里.at(0)得name:AK-47,再以":"截断.at(1)得到AK-47
        value = list.at( i ).split(":").at(1);
        json.insert(key, value); //生成json
        qDebug() << key;
        qDebug() << value ;
    }

    QJsonDocument document;
    document.setObject(json);
    QByteArray byte_array = document.toJson(QJsonDocument::Compact);
    QString json_str(byte_array);
    qDebug() << json_str;

    QSqlDatabase db=QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("127.0.0.1");
    db.setDatabaseName("weapon");//自己建数据库名
    db.setUserName("root");
    db.setPassword("123456");
    db.exec("set NAMES UTF8");   //加上这一行,可以正常显示中文
    bool ok=db.open();
    if( ok ){
        QSqlQuery query;

        QString getname = ui->treeWidget->currentItem()->text(0); //获取被点击的根目录名称
        qDebug() << getname;

        //根据name去修改atti
        QString str = QString("update device set atti = '%1' where name = '%2';").arg(json_str).arg(getname); //把 用.arg()将字符串father 组成字符串传给'%1'去执行删除命令
        query.exec(str);
    }
    db.close();
}

 

 

发布了12 篇原创文章 · 获赞 3 · 访问量 1445
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览