Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > C/C++ программирование > Qt и кроссплатформенное программирование С/С++
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 13.09.2023, 09:09   #1
Mitzzz
Пользователь
 
Регистрация: 27.05.2009
Сообщений: 17
По умолчанию Сохранение данных в файл XML в виде истории

Добрый день! Возник такой вопрос.

Необходимо сохранить xml-файл так, чтобы данные не перезаписывались на новые, а сохранялись в виде истории.

Вот код для сохранения в xml-файл необходимых данных, где данные при нажатии на кнопку "Сохранить в файл" (на данный момент) перезаписываются на новые:
Mitzzz вне форума Ответить с цитированием
Старый 13.09.2023, 09:34   #2
Mitzzz
Пользователь
 
Регистрация: 27.05.2009
Сообщений: 17
По умолчанию

Действие кнопки "Сохранить в файл" (для всех разделов) (начало):

Код:
void MainWindow::saveToFile()
{
    QDir dir(QDir::currentPath() + "/настройка");
    if (!dir.exists())
        dir.mkdir(QDir::currentPath() + "/настройка");
    if(ui->stackedWidget->currentIndex() == 2) //вкладка градуировка
    {
        if ((ui->edPipNumber_1->text() == "") || (ui->edVipNumber_1->text() == ""))
        {
            QMessageBox::warning(this, "Ошибка", "Введите номера ВИП и ПИП!");
            return;
        }
        QString fileName = QDir::currentPath() + "/настройка/X999_ПИП№" + ui->edPipNumber_1->text() + "_ВИП№" + \
                    ui->edVipNumber_1->text() + "_настройка.xml";
        //////////////////////////////////////////////////////////////////////////////////////////////////
        static QList<OneCalibration> cl;
        static OneCalibration oc;
        static int ang = 0, u1 = 0, u2 = 0, dU = 0;
        static QString temp = "";
        //Создаем список градуировок из данных видимой таблички
        for(int i = 0; i < 21; i++)
        {
            ang = 0; u1 = 0; u2 = 0; dU = 0;
            temp = ui->gradTableWidget_2->verticalHeaderItem(i)->text().right(4).left(3);
            if(temp != "")
                ang = temp.toInt();
            temp = ui->gradTableWidget_2->item(i, 0)->text();
            if(temp != "")
                u1 = temp.toInt();
            temp = ui->gradTableWidget_2->item(i, 1)->text();
            if(temp != "")
                u2 = temp.toInt();
            temp = ui->gradTableWidget_2->item(i, 2)->text();
            if(temp != "")
                dU = temp.toInt();
            oc.ReadOneCalibration(ang, u1, u2, dU);
            cl.append(oc);
        }
        myXml = new XmlMainClass(fileName, cl, ui->edPipNumber_1->text(), ui->edVipNumber_1->text());
        myXml->WriteAllFile(0);
        if(myXml->GetIsFileOk())
        {
            QString info = "Результаты настройки сохранены в файл:\n" + fileName;
            QMessageBox::information(this, "Сохранение файла", info.toUtf8().data());
        }
        else QMessageBox::warning(this, "Ошибка", "Ошибка открытия файла");
        cl.clear();
        delete myXml;
        //////////////////////////////////////////////////////////////////////////////////////////////////
    }
    if(ui->stackedWidget->currentIndex() == 3)
    {
        if ((ui->edPipNumber_2->text() == "") || (ui->edVipNumber_2->text() == ""))
        {
            QMessageBox::warning(this, "Ошибка", "Введите номера ВИП и ПИП!");
            return;
        }
        QString fileName = QDir::currentPath() + "/настройка/X999_ПИП№" + ui->edPipNumber_2->text() + "_ВИП№" + \
                    ui->edVipNumber_2->text() + "_настройка.xml";
        //////////////////////////////////////////////////////////////////////////////////////////////////
        static QList<OneTemperature> tl;
        static OneTemperature ot;
        static int ang = 0, tem = 0, u1 = 0, u2 = 0, du = 0, ra = 0;
        static QString temp = "", pointDate = "";
        //Создаем список градуировок из данных видимой таблички
        for(int i = 0; i < 6; i++)
        {												//
            ang = 0; tem = 0; u1 = 0; u2 = 0; du = 0; ra = 0;
            temp = ui->tempTableWidget_1->verticalHeaderItem(i)->text();
            if(temp != "")
            {
                int t = temp.indexOf(',');
                ang = temp.mid(t-4, 3).toInt();
                tem = temp.right(5).left(3).toInt();
            }
            pointDate = ui->tempTableWidget_1->item(i, 0)->text();

           // pointDate.remove(pointDate.indexOf('\n'),2);
            temp = ui->tempTableWidget_1->item(i, 1)->text();
            if(temp != "")
                u1 = temp.toInt();
            temp = ui->tempTableWidget_1->item(i, 2)->text();
            if(temp != "")
                u2 = temp.toInt();
            temp = ui->tempTableWidget_1->item(i, 3)->text();
            if(temp != "")
                du = temp.toInt();
            temp = ui->tempTableWidget_1->item(i, 4)->text();
            if(temp != "")
                ra = temp.toInt();
            ot.ReadOneTemperature(ang, tem, pointDate, u1, u2, du, ra);
            tl.append(ot);
        }

        myXml = new XmlMainClass(fileName, tl, ui->edPipNumber_2->text(), ui->edVipNumber_2->text());
        myXml->WriteAllFile(1);
        if(myXml->GetIsFileOk())
        {
            QString info = "Результаты настройки сохранены в файл:\n" + fileName;
            QMessageBox::information(this, "Сохранение файла", info.toUtf8().data());
        }
        else QMessageBox::warning(this, "Ошибка", "Ошибка открытия файла");
        tl.clear();
        delete myXml;
        //////////////////////////////////////////////////////////////////////////////////////////////////
    }
    if(ui->stackedWidget->currentIndex() == 7)   //вкладка проверка погрешности
    {
        if ((ui->edPipNumber_8->text() == "") || (ui->edVipNumber_8->text() == ""))
        {
            QMessageBox::warning(this, "Ошибка", "Введите номера ВИП и ПИП!");
            return;
        }
        static QList<OneCalibCheck> ccl;
        static OneCalibCheck occ;
        static int ang = 0, p1 = 0, p2 = 0, o1 = 0, o2 = 0;
        static QString temp = "";
        for(int i = 0; i < 12; i++)
        {
            ang = 0; p1 = 0; p2 = 0; o1 = 0; o2 = 0;
            temp = ui->gradTableWidget_8->verticalHeaderItem(i)->text().right(4).left(3);
            if(temp != "")  ang = temp.toInt();
            temp = ui->gradTableWidget_8->item(i, 1)->text();
            if(temp != "") p1 = temp.toInt();
                      else p1 = -10000000;
            temp = ui->gradTableWidget_8->item(i, 2)->text();
            if(temp != "") o1 = temp.toInt();
                      else o1 = -10000000;
            temp = ui->gradTableWidget_8->item(i, 3)->text();
            if(temp != "") p2 = temp.toInt();
                      else p2 = -10000000;
            temp = ui->gradTableWidget_8->item(i, 4)->text();
            if(temp != "") o2 = temp.toInt();
                      else o2 = -10000000;
            occ.ReadOneCalibCheck(ang, p1, o1, p2, o2);
            ccl.append(occ);
        }
        myXml = new XmlMainClass(ui->edPipNumber_8->text(), ui->edVipNumber_8->text(), ccl);
        myXml->WriteCheckFile(1);
        if(myXml->GetIsFileOk())
        {
            QString info = "Результаты настройки сохранены в файл:\n" + QDir::currentPath() + "/настройка/X999_ПИП№" + \
                           ui->edPipNumber_8->text() + "_ВИП№" + \
                           ui->edVipNumber_8->text() + "_проверка_градуировка.xml";
            QMessageBox::information(this, "Сохранение файла", info.toUtf8().data());
        }
        else QMessageBox::warning(this, "Ошибка", "Ошибка открытия файла");
        ccl.clear();
        delete myXml;
    }
Mitzzz вне форума Ответить с цитированием
Старый 13.09.2023, 09:34   #3
Mitzzz
Пользователь
 
Регистрация: 27.05.2009
Сообщений: 17
По умолчанию

Действие кнопки "Сохранить в файл" (для всех разделов) (продолжение):

Код:
    if(ui->stackedWidget->currentIndex() == 8)
    {
        if ((ui->edPipNumber_9->text() == "") || (ui->edVipNumber_9->text() == ""))
        {
            QMessageBox::warning(this, "Ошибка", "Введите номера ВИП и ПИП!");
            return;
        }
        static QList<OneTempCheck> tcl;
        static OneTempCheck otc;
        static int ang = 0, tem = 0, u1 = 0, u2 = 0, du = 0, ktu = 0, nt = 0, np = 0;
        static QString temp = "", pointDate = "";
        for(int i = 0; i < 6; i++)
        {
            ang = 0; tem = 0; u1 = 0; u2 = 0; du = 0; ktu = 0; nt = 0; np = 0;
           // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Что это
            temp = ui->tempTableWidget_9->verticalHeaderItem(i)->text();
            if(temp != "")
            {
                int t = temp.indexOf(',');
                ang = temp.mid(t-4, 3).toInt();
                tem = temp.right(5).left(3).toInt();
            }
            pointDate = ui->tempTableWidget_9->item(i, 0)->text();
            temp = ui->tempTableWidget_9->item(i, 1)->text();
            if(temp != "")
                u1 = temp.toInt();
            temp = ui->tempTableWidget_9->item(i, 2)->text();
            if(temp != "")
                u2 = temp.toInt();
            temp = ui->tempTableWidget_9->item(i, 3)->text();
            if(temp != "")
                du = temp.toInt();
            temp = ui->tempTableWidget_9->item(i, 4)->text();
            if(temp != "")
                ktu = temp.toInt();
            temp = ui->tempTableWidget_9->item(i, 5)->text();
            if(temp != "")
                nt = temp.toInt();
            temp = ui->tempTableWidget_9->item(i, 6)->text();
            if(temp != "")
                np = temp.toInt();
            otc.ReadOneTemperCheck(ang, tem, pointDate, u1, u2, du, ktu, nt, np);
            tcl.append(otc);
        }
        myXml = new XmlMainClass(ui->edPipNumber_9->text(), ui->edVipNumber_9->text(), tcl);
        myXml->WriteCheckFile(2);
        if(myXml->GetIsFileOk())
        {
            QString info = "Результаты настройки сохранены в файл:\n" + QDir::currentPath() + "/настройка/X999_ПИП№" + \
                           ui->edPipNumber_9->text() + "_ВИП№" + \
                           ui->edVipNumber_9->text() + "_проверка_температура.xml";
            QMessageBox::information(this, "Сохранение файла", info.toUtf8().data());
        }
        else QMessageBox::warning(this, "Ошибка", "Ошибка открытия файла");
        tcl.clear();
        delete myXml;
    }
    if(ui->stackedWidget->currentIndex() == 4)
    {
        if ((ui->edPipNumber->text() == "") || (ui->edVipNumber->text() == ""))
        {
            QMessageBox::warning(this, "Ошибка", "Введите номера ВИП и ПИП!");
            return;
        }

        QString curDate = QDate::currentDate().toString("ddMMyyyy");
        QString curTime = QTime::currentTime().toString("hhmmss");

        QString fileName = QDir::currentPath() + "/расчет/X999_ПИП№" + ui->edPipNumber->text() + "_ВИП№" + \
                    ui->edVipNumber->text() + "_" + curDate + "_" + curTime + "_расчет.xml";

        QStringList title, value;

        for(int i = 0; i < ui->parametrTableWidget->rowCount(); i++)
        {
            title.append(ui->parametrTableWidget->verticalHeaderItem(i)->text());
            if(ui->parametrTableWidget->item(i, 0) == 0)
            {
                value.append("");
            }
            else
            {
                value.append(ui->parametrTableWidget->item(i, 0)->text());
            }
        }

        myXml = new XmlMainClass(fileName, title, value);
        myXml->writeCalcFile(title, value);

        if(myXml->GetIsFileOk())
        {
            QString info = "Результаты настройки сохранены в файл:\n" + fileName;
            QMessageBox::information(this, "Сохранение файла", info.toUtf8().data());
        }
        else QMessageBox::warning(this, "Ошибка", "Ошибка открытия файла");
        delete myXml;
        //////////////////////////////////////////////////////////////////////////////////////////////////
    }

}
Mitzzz вне форума Ответить с цитированием
Старый 13.09.2023, 09:35   #4
Mitzzz
Пользователь
 
Регистрация: 27.05.2009
Сообщений: 17
По умолчанию

Формирование XML-файла (Градуировка):

Код:
bool XmlMainClass::WriteAllFile(int type)
{
    QIODevice::OpenMode modeFile = QFile::WriteOnly | QFile::Text;
    xmlFile = new QFile(xmlFileName);
    if(!xmlFile->open(modeFile))
    {
        delete xmlFile;
        isFileOpened = false;
        return false;
    }

    OneCalibration oc;
    OneTemperature ot;

    writer = new QXmlStreamWriter(xmlFile);
    writer->setAutoFormatting(true);
    writer->writeStartDocument();
    writer->writeStartElement("data");
    writer->writeTextElement("PIP_Number", pip_Num);
    writer->writeTextElement("VIP_Number", vip_Num);
    writer->writeStartElement("Calibration");
    if (type==0) writer->writeTextElement("C_Date", QDateTime::currentDateTime().toString("dd.MM.yyyy hh:mm"));
    else  writer->writeTextElement("C_Date", calibDate);
    for(int i = 0; i < 21; i++)
    {
        oc = calib->at(i);
        oc.WriteOneCalibration(writer);
    }
    writer->writeEndElement();
    writer->writeStartElement("Temperature");
    for(int i = 0; i < 6; i++)
    {
        ot = temper->at(i);
        ot.WriteOneTemperature(writer);
    }
    writer->writeEndElement();
    writer->writeEndElement();
    xmlFile->close();
    delete xmlFile;
    isFileOpened = true;
    return true;
}




Код:
XmlMainClass::XmlMainClass(QString fileName, QList<OneCalibration> calibList, QString pip, QString vip)
{
    xmlFileName = fileName;
    pip_Num = pip;
    vip_Num = vip;
    QDir dir;
    dir.setPath(xmlFileName);
    if(!dir.exists(xmlFileName))
    {
        CreateNewDataStruct();
        WriteAllFile(0);
    }
    ReadAllFile();
    OneCalibration oc;
    for(int i = 0; i < 21; i++)
    {
        oc = calibList.at(i);
        if(!oc.IsEmpty())
            calib->replace(i, oc);
    }
}




Формирование XML-файла (Температурная настройка):

Код:
bool XmlMainClass::WriteAllFile(int type)
{
    QIODevice::OpenMode modeFile = QFile::WriteOnly | QFile::Text;
    xmlFile = new QFile(xmlFileName);
    if(!xmlFile->open(modeFile))
    {
        delete xmlFile;
        isFileOpened = false;
        return false;
    }

    OneCalibration oc;
    OneTemperature ot;

    writer = new QXmlStreamWriter(xmlFile);
    writer->setAutoFormatting(true);
    writer->writeStartDocument();
    writer->writeStartElement("data");
    writer->writeTextElement("PIP_Number", pip_Num);
    writer->writeTextElement("VIP_Number", vip_Num);
    writer->writeStartElement("Calibration");
    if (type==0) writer->writeTextElement("C_Date", QDateTime::currentDateTime().toString("dd.MM.yyyy hh:mm"));
    else  writer->writeTextElement("C_Date", calibDate);
    for(int i = 0; i < 21; i++)
    {
        oc = calib->at(i);
        oc.WriteOneCalibration(writer);
    }
    writer->writeEndElement();
    writer->writeStartElement("Temperature");
    for(int i = 0; i < 6; i++)
    {
        ot = temper->at(i);
        ot.WriteOneTemperature(writer);
    }
    writer->writeEndElement();
    writer->writeEndElement();
    xmlFile->close();
    delete xmlFile;
    isFileOpened = true;
    return true;
}




Код:
XmlMainClass::XmlMainClass(QString fileName, QList<OneTemperature> temperList, QString pip, QString vip)
{
    xmlFileName = fileName;
    pip_Num = pip;
    vip_Num = vip;
    QDir dir;
    dir.setPath(xmlFileName);
    if(!dir.exists(xmlFileName))
    {
        CreateNewDataStruct();
        WriteAllFile(1);
    }
    ReadAllFile();
    OneTemperature ot;
    for(int i = 0; i < 6; i++)
    {
        ot = temperList.at(i);
        if(!ot.IsEmpty()) temper->replace(i, ot);
    }
}
Mitzzz вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Запись истории результата вычислений (по формуле) в виде примечания Vasilii78 Microsoft Office Excel 0 16.01.2018 18:56
при сохранение данных в файл данные сохранились в скрытый файл ini alman12 Общие вопросы Delphi 27 25.05.2015 07:53
StringGrid Сохранение в файл в виде таблицы. werrey Общие вопросы Delphi 11 23.04.2012 12:39
Экспорт данных в Excel и сохранение истории изменения значений ячеек Asblue Microsoft Office Excel 7 13.12.2011 16:47
построчное сохранение данных в табличном виде kvs Microsoft Office Excel 4 26.04.2010 19:26