Как правильно создавать Dialog?

168
07 октября 2018, 13:00

У меня аварийно завершается программа после того как я открываю диалог повторно. Почему так происходить ? Может это быть из-за пустого Деструктор? : EditLog::~EditLog() {} Сам код диалога : editlog.h

#ifndef EDITLOG_H
#define EDITLOG_H
#include <QDialog>
#include <QObject>
//#include <QSharedPointer>
#include <QGridLayout>
#include <QComboBox>
#include <QPushButton>
#include <QLabel>
#include <QTextEdit>
#include <QLineEdit>
#include "Sources/ColorWheel/colorwheel.h"
//#include <Sources/qtdbconn/src/qtdatabase.h>
#include <QMessageBox>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlError>
#include <QStack>
#include <login.h>
//#include <Sources/common/src/pkoristrcont.h>
//#include <Sources/common/src/pkoriutils.h>
#include <QDoubleSpinBox>
#include <QDateTimeEdit>
#include <QGroupBox>
class EditLog: public QDialog
{
    Q_OBJECT
public:
    explicit EditLog(QDialog *parent = nullptr);
    ~EditLog();
    QGridLayout *layout = new QGridLayout;
    QComboBox *LogComBox = new QComboBox;
    QLineEdit *NameLineEdit = new QLineEdit (this);
    QTextEdit *CommentTextEdit = new QTextEdit (this);
    QLineEdit *ColorLineEdit = new QLineEdit(this);
    QWidget *windowColorWheel = new QWidget();
    ColorWheel *ColorW = new ColorWheel(this);
    QVBoxLayout *layoutColorWheel = new QVBoxLayout;
    QPushButton *ButtonColorW = new QPushButton(tr("Выбрать"));
    QDateTimeEdit *BeginDateTimeEdit = new QDateTimeEdit;
    QDateTimeEdit *EndDateTimeEdit = new QDateTimeEdit;
    QDoubleSpinBox *LatitudeSpinBox = new QDoubleSpinBox;
    QDoubleSpinBox *LongitudeSpinBox = new QDoubleSpinBox;
    QDoubleSpinBox *AirTemperatureSpinBox = new QDoubleSpinBox;
    QDoubleSpinBox *WaterTemperatureSpinBox = new QDoubleSpinBox;
    QDoubleSpinBox *WindSpeedSpinBox = new QDoubleSpinBox;
    QDoubleSpinBox *FlowSpeedSpinBox = new QDoubleSpinBox;
    QSpinBox *DirectionWindSpinBox = new QSpinBox;
    QSpinBox *DirectionFlowSpinBox = new QSpinBox;
    QMessageBox msgBox;
public slots:
    void LogComBoxBuilding();
private slots:
    void SelectLog();
    bool eventFilter(QObject *watched, QEvent *event);
    void showColorWheel();
    void GetColor();
    void SaveLog();
    void DeleteLog();
    //QSharedPointer<pkori::db::qtconnect::QtDBConn> m_qtdbConn;
    //QString m_connectionName;
};
#endif // EDITLOG_H

editlog.cpp:

#include "editlog.h"
#include "spoiler.h"
EditLog::EditLog(QDialog *parent) :
    QDialog(parent)
{
    EditLog::setWindowTitle(tr("Редактирование/Удаление журнала"));
    layout->setSpacing(10);
    layout->setMargin(15);
    EditLog::LogComBoxBuilding();
    QPushButton *SelectLogButton = new QPushButton(tr("Выбрать журнал для редактирования"));
    connect(SelectLogButton, &QPushButton::clicked, this, [=] () { SelectLog(); });
    layout->addWidget(SelectLogButton,0,1);
    QPushButton *DeleteLogButton = new QPushButton(tr("Удалить журнал"));
    connect(DeleteLogButton, &QPushButton::clicked, this, [=] () { DeleteLog(); });
    layout->addWidget(DeleteLogButton,0,2);
    Login conn;
    conn.connOpen();
    QSqlQuery *queryColorComboBox = new QSqlQuery(conn.mydb);
    bool CheckBoxBool = true;
    queryColorComboBox->exec("SELECT \"Цвет\" FROM \"SchemeObservationLog\".settingslog WHERE id = 1 ");
    while (queryColorComboBox->next()) {
       CheckBoxBool = queryColorComboBox->value(0).toBool();
    }
    conn.connClose();
    QLabel *NameLabel = new QLabel("Название журнала.");
    QLabel *CommentLabel = new QLabel("Коментарий к журналу.");
    if (CheckBoxBool == true) {
        QLabel *ColorLabel = new QLabel("Выбери цвет журнала.");
        layout->addWidget(ColorLabel,3,0);
        layout->addWidget(ColorLineEdit,3,1,1,2);
    } else {
        ColorLineEdit->setText("#ffffff");
    }

    NameLineEdit->setEnabled(false);
    CommentTextEdit->setEnabled(false);   
    ColorLineEdit->setEnabled(false);
    AirTemperatureSpinBox->setEnabled(false);
    WaterTemperatureSpinBox->setEnabled(false);
    WindSpeedSpinBox->setEnabled(false);
    FlowSpeedSpinBox->setEnabled(false);
    DirectionWindSpinBox->setEnabled(false);
    DirectionFlowSpinBox->setEnabled(false);
    BeginDateTimeEdit->setEnabled(false);
    EndDateTimeEdit->setEnabled(false);
    LatitudeSpinBox->setEnabled(false);
    LongitudeSpinBox->setEnabled(false);
    ColorLineEdit->installEventFilter(this);

    Spoiler* OptionalField = new Spoiler("Геоинформационные данные",900,this);
    QGridLayout *SpoilerLayout = new QGridLayout();

    QLabel *BeginDateLabel = new QLabel("Время начала операции:");
    QLabel *EndDateLabel = new QLabel("Время окончания операции:");
    QGroupBox *TimeGroupBox = new QGroupBox("Время");
    QGridLayout *GridLayoutTime = new QGridLayout;
    GridLayoutTime->addWidget(BeginDateLabel,0,0);
    GridLayoutTime->addWidget(BeginDateTimeEdit,0,1);
    GridLayoutTime->addWidget(EndDateLabel,1,0);
    GridLayoutTime->addWidget(EndDateTimeEdit,1,1);
    TimeGroupBox->setLayout(GridLayoutTime);
    QGroupBox *CoordinatesGB = new QGroupBox("Координаты");
    QGridLayout *GridLayoutCoordinates = new QGridLayout;
    QLabel *LatitudeLabel = new QLabel ("Широта:");
    QLabel *LongitudeLabel = new QLabel ("Долгота:");
    QGroupBox *MeteorologicalSituation = new QGroupBox("Метеорологическая обстановка");
    QGridLayout *GridLayoutMS = new QGridLayout;
    QLabel *AirTemperatureLabel = new QLabel ("Температура_воздуха(°C):");
    QLabel *WaterTemperatureLabel = new QLabel ("Температура_воды(°C):");
    QLabel *WindSpeedLabel = new QLabel ("Скорость_ветра(м/с):");
    QLabel *FlowSpeedLabel = new QLabel ("Скорость_течения(м/с):");
    QLabel *DirectionWindLabel = new QLabel ("Направление_ветра(0°-360°):");
    QLabel *DirectionFlowLabel = new QLabel ("Направление_течения(0°-360°):");
    LatitudeSpinBox->setDecimals(6);
    LongitudeSpinBox->setDecimals(6);
    AirTemperatureSpinBox->setRange(-50,60);
    AirTemperatureSpinBox->setDecimals(1);
    AirTemperatureSpinBox->setSingleStep(0.5);
    WaterTemperatureSpinBox->setRange(-5,50);
    WaterTemperatureSpinBox->setDecimals(1);
    WaterTemperatureSpinBox->setSingleStep(0.5);
    WindSpeedSpinBox->setRange(0,35);
    WindSpeedSpinBox->setDecimals(1);
    WindSpeedSpinBox->setSingleStep(0.1);
    FlowSpeedSpinBox->setRange(0,3);
    FlowSpeedSpinBox->setDecimals(2);
    FlowSpeedSpinBox->setSingleStep(0.01);
    DirectionWindSpinBox->setRange(0,360);
    DirectionWindSpinBox->setSingleStep(1);
    DirectionFlowSpinBox->setRange(0,360);
    DirectionFlowSpinBox->setSingleStep(1);
    QPushButton *SaveLogButton = new QPushButton(tr("СОХРАНИТЬ ОТРЕДАКТИРОВАННЫЙ ЖУРНАЛ"));
    connect(SaveLogButton, &QPushButton::clicked, this, [=] () { SaveLog(); });
    layout->addWidget(NameLabel,1,0);
    layout->addWidget(NameLineEdit,1,1,1,2);
    layout->addWidget(CommentLabel,2,0);
    layout->addWidget(CommentTextEdit,2,1,1,2);
    GridLayoutCoordinates->addWidget(LatitudeLabel,0,0);
    GridLayoutCoordinates->addWidget(LatitudeSpinBox,0,1);
    GridLayoutCoordinates->addWidget(LongitudeLabel,1,0);
    GridLayoutCoordinates->addWidget(LongitudeSpinBox,1,1);
    CoordinatesGB->setLayout(GridLayoutCoordinates);
    GridLayoutMS->addWidget(AirTemperatureLabel,0,0);
    GridLayoutMS->addWidget(AirTemperatureSpinBox,0,1);
    GridLayoutMS->addWidget(WaterTemperatureLabel,1,0);
    GridLayoutMS->addWidget(WaterTemperatureSpinBox,1,1);
    GridLayoutMS->addWidget(WindSpeedLabel,2,0);
    GridLayoutMS->addWidget(WindSpeedSpinBox,2,1);
    GridLayoutMS->addWidget(FlowSpeedLabel,3,0);
    GridLayoutMS->addWidget(FlowSpeedSpinBox,3,1);
    GridLayoutMS->addWidget(DirectionWindLabel,4,0);
    GridLayoutMS->addWidget(DirectionWindSpinBox,4,1);
    GridLayoutMS->addWidget(DirectionFlowLabel,5,0);
    GridLayoutMS->addWidget(DirectionFlowSpinBox,5,1);
    MeteorologicalSituation->setLayout(GridLayoutMS);

    SpoilerLayout->addWidget(TimeGroupBox,0,0);
    SpoilerLayout->addWidget(CoordinatesGB,0,1);
    SpoilerLayout->addWidget(MeteorologicalSituation,1,0,1,2);
    OptionalField->setContentLayout(*SpoilerLayout);
    layout->addWidget(OptionalField,4,0,1,3);
    layout->addWidget(SaveLogButton,5,0,1,3);
    this->setLayout(layout);
}
EditLog::~EditLog()
{
}
void EditLog::LogComBoxBuilding() {
    LogComBox->clear();
    Login conn;
    conn.connOpen();
    QSqlError dbError;
    QSqlQuery *query = new QSqlQuery(conn.mydb);
    bool queryRes = query->exec("SELECT * FROM \"SchemeObservationLog\".log");
    if (queryRes) {
        int ItemComBox = 0;
        while (query->next()) {
            LogComBox->addItem(query->value(1).toString(), QVariant(query->value(0).toInt()));
            LogComBox->setItemData( ItemComBox, QColor( query->value(3).toString()), Qt::BackgroundRole );
            ItemComBox++;
        }
        LogComBox->setCurrentIndex(-1);
    }else{
        dbError = conn.mydb.lastError();
        QMessageBox::critical(this, "Ошибка", dbError.text(), QMessageBox::Close);
    }
    layout->addWidget(LogComBox,0,0);
    conn.connClose();
    return;
}
void EditLog::SelectLog()
{
    if (!LogComBox->currentData().isNull()) {
        Login conn;
        conn.connOpen();
        QSqlQuery* querySelectLog = new QSqlQuery(conn.mydb);
        if (querySelectLog->exec("SELECT * FROM \"SchemeObservationLog\".log  WHERE id ="+LogComBox->currentData().toString())) {
            while (querySelectLog->next()) {
                NameLineEdit->setText(querySelectLog->value(1).toString());
                CommentTextEdit->setText(querySelectLog->value(2).toString());
                ColorLineEdit->setText(querySelectLog->value(3).toString());
                ColorLineEdit->setStyleSheet("QLineEdit { background:"+querySelectLog->value(3).toString()+" }");
                AirTemperatureSpinBox->setValue(querySelectLog->value(4).toDouble());
                WaterTemperatureSpinBox->setValue(querySelectLog->value(5).toDouble());
                WindSpeedSpinBox->setValue(querySelectLog->value(6).toDouble());
                FlowSpeedSpinBox->setValue(querySelectLog->value(7).toDouble());
                DirectionWindSpinBox->setValue(querySelectLog->value(8).toInt());
                DirectionFlowSpinBox->setValue(querySelectLog->value(9).toInt());
                BeginDateTimeEdit->setDateTime(querySelectLog->value(10).toDateTime());
                EndDateTimeEdit->setDateTime(querySelectLog->value(11).toDateTime());
                LatitudeSpinBox->setValue(querySelectLog->value(13).toDouble());
                LongitudeSpinBox->setValue(querySelectLog->value(14).toDouble());
                if (querySelectLog->value(15).toBool() == false) {
                    NameLineEdit->setEnabled(false);
                    CommentTextEdit->setEnabled(false);
                    AirTemperatureSpinBox->setEnabled(false);
                    WaterTemperatureSpinBox->setEnabled(false);
                    WindSpeedSpinBox->setEnabled(false);
                    FlowSpeedSpinBox->setEnabled(false);
                    DirectionWindSpinBox->setEnabled(false);
                    DirectionFlowSpinBox->setEnabled(false);
                    BeginDateTimeEdit->setEnabled(false);
                    EndDateTimeEdit->setEnabled(false);
                    LatitudeSpinBox->setEnabled(false);
                    LongitudeSpinBox->setEnabled(false);
                } else if (querySelectLog->value(15).toBool() == true) {
                    NameLineEdit->setEnabled(true);
                    CommentTextEdit->setEnabled(true);
                    AirTemperatureSpinBox->setEnabled(true);
                    WaterTemperatureSpinBox->setEnabled(true);
                    WindSpeedSpinBox->setEnabled(true);
                    FlowSpeedSpinBox->setEnabled(true);
                    DirectionWindSpinBox->setEnabled(true);
                    DirectionFlowSpinBox->setEnabled(true);
                    BeginDateTimeEdit->setEnabled(true);
                    EndDateTimeEdit->setEnabled(true);
                    LatitudeSpinBox->setEnabled(true);
                    LongitudeSpinBox->setEnabled(true);
                }
            }
            conn.connClose();
        } else {
            QMessageBox::warning(this, tr("Ошибка базы данных"),querySelectLog->lastError().text());
        }
    } else {
        msgBox.setText("Выберите журнал в ComboBox, слева!");
        msgBox.exec();
        return;
    }
    return;
}
bool EditLog::eventFilter(QObject *obj, QEvent *event)
{
    if (obj == ColorLineEdit) {
        if (event->type() == QEvent::MouseButtonPress) {
            EditLog::showColorWheel();
            return true;
        } else {
            return false;
        }
    } else {
        // pass the event on to the parent class
        return EditLog::eventFilter(obj, event);
    }
}
void EditLog::showColorWheel()
{
    if (!LogComBox->currentData().isNull()) {
        connect(ButtonColorW,SIGNAL(clicked(bool)),SLOT(GetColor()));
        layoutColorWheel->addWidget(ColorW);
        layoutColorWheel->addWidget(ButtonColorW);
        windowColorWheel->setLayout(layoutColorWheel);
        windowColorWheel->show();
    } else {
        msgBox.setText("Выберите журнал в ComboBox, слева!");
        msgBox.exec();
        return;
    }
    return;
}
void EditLog::GetColor() {
    QColor Col = ColorW->color();
    ColorLineEdit->setText(Col.name());
    ColorLineEdit->setStyleSheet("QLineEdit { background:"+Col.name()+" }");
    windowColorWheel->close();
    return;
}
void EditLog::SaveLog()
{
    if(!NameLineEdit->text().isEmpty() && !CommentTextEdit->toPlainText().isEmpty() && !ColorLineEdit->text().isEmpty()) {
        Login conn;
        conn.connOpen();
        QSqlQuery* queryAddLog = new QSqlQuery(conn.mydb);
        if (queryAddLog->prepare(QString("UPDATE \"SchemeObservationLog\".log "
                                     "SET \"Название\" = '%1', \"Комментарий\" = '%2', \"Цвет\" = '%3',"
                                     "\"Температура_воздуха(°C)\" = '%4',\"Температура_воды(°C)\" = '%5', \"Скорость_ветра(м/с)\" = '%6',"
                                     "\"Скорость_течения(м/с)\" = '%7',\"Направление_ветра(0°-360°)\" = '%8', \"Направление_течения(0°-360°)\" = '%9',"
                                     "\"Время_начала_операции\" = '%10', \"Время_окончания_операции\" = '%11',"
                                     "\"Широта\" = '%12', \"Долгота\" = '%13'"
                                     " WHERE id ="+LogComBox->currentData().toString())
                                        .arg(NameLineEdit->text())
                                        .arg(CommentTextEdit->toPlainText())
                                        .arg(ColorLineEdit->text())
                                        .arg(AirTemperatureSpinBox->text().replace(",","."))
                                        .arg(WaterTemperatureSpinBox->text().replace(",","."))
                                        .arg(WindSpeedSpinBox->text().replace(",","."))
                                        .arg(FlowSpeedSpinBox->text().replace(",","."))
                                        .arg(DirectionWindSpinBox->text())
                                        .arg(DirectionFlowSpinBox->text())
                                        .arg(BeginDateTimeEdit->text())
                                        .arg(EndDateTimeEdit->text())
                                        .arg(LatitudeSpinBox->text().replace(",","."))
                                        .arg(LongitudeSpinBox->text().replace(",",".")))) {
                    queryAddLog->exec();
                    NameLineEdit->clear();
                    CommentTextEdit->clear();
                    ColorLineEdit->clear();
                    AirTemperatureSpinBox->setValue(0);
                    WaterTemperatureSpinBox->setValue(0);
                    WindSpeedSpinBox->setValue(0);
                    FlowSpeedSpinBox->setValue(0);
                    DirectionWindSpinBox->setValue(0);
                    DirectionFlowSpinBox->setValue(0);
                    LatitudeSpinBox->setValue(0);
                    LongitudeSpinBox->setValue(0);
                    BeginDateTimeEdit->setDate(QDate::currentDate());
                    EndDateTimeEdit->setDate(QDate::currentDate());
                    LogComBoxBuilding();
                    msgBox.setText("Информация обнавлена.");
                    msgBox.exec();
        } else {
            QMessageBox::warning(this, tr("Ошибка базы данных"),queryAddLog->lastError().text());
        }
        conn.connClose();
    } else {
        if(NameLineEdit->text().isEmpty()) {
            msgBox.setText("Назови журнал.");
            msgBox.exec();
            return;
        } else if (CommentTextEdit->toPlainText().isEmpty()) {
            msgBox.setText("Напиши о журнале.");
            msgBox.exec();
            return;
        } else if (ColorLineEdit->text().isEmpty()) {
            msgBox.setText("Задай цвет.");
            msgBox.exec();
            return;
        }
    }
    return;
}
void EditLog::DeleteLog()
{    
    if(!LogComBox->currentData().isNull()) {
        Login conn;
        conn.connOpen();
        QSqlQuery* queryLog = new QSqlQuery(conn.mydb);
        QSqlQuery* queryAnalysis = new QSqlQuery(conn.mydb);
        QSqlQuery* queryDeleteLog = new QSqlQuery(conn.mydb);
        queryLog->exec("SELECT id_log FROM \"SchemeObservationLog\".data");
        while (queryLog->next()) {
            if(LogComBox->currentData().toString() == queryLog->value(0).toString()) {
                msgBox.setText("УДАЛЕНИЕ НЕВОЗМОЖНО!!! Выбранный журнал используется в таблице 'data'.");
                msgBox.exec();
                conn.connClose();
                return;
            }
        }
        queryAnalysis->exec("SELECT id_log FROM \"SchemeObservationLog\".analysis");
        while (queryAnalysis->next()) {
            if(LogComBox->currentData().toString() == queryAnalysis->value(0).toString()) {
                msgBox.setText("УДАЛЕНИЕ НЕВОЗМОЖНО!!! Выбранный журнал используется в таблице 'analysis'.");
                msgBox.exec();
                return;
            }
        }
        QString LOGname = LogComBox->currentText();
        queryDeleteLog->prepare(QString("DELETE FROM \"SchemeObservationLog\".log WHERE id ='"+LogComBox->currentData().toString()+"'"));
        queryDeleteLog->exec();
        msgBox.setText("УДАЛЁН ЖУРНАЛ - "+LOGname+".");
        msgBox.exec();
        conn.connClose();
        EditLog::LogComBoxBuilding();
    } else {
        msgBox.setText("Выберите журнал в ComboBox, слева!");
        msgBox.exec();
    }
    return;
}

Открытие диалога :

void MainWindow::EditLogDialog() {
    //LogEditDialog->setAttribute(Qt::WA_DeleteOnClose); //если убрать этот атрибут не вылетает
    LogEditDialog->show();
    connect(LogEditDialog, SIGNAL(destroyed(QObject*)), this, SLOT(ComboBoxBuilding(int)));
}
READ ALSO
C++ delete и delete[]

C++ delete и delete[]

Ясное дело, что по Стандарту вызовы malloc()/free()*, **new/delete и new[]/delete[] должны быть строго парными, иначе неопределенное поведение

149
В чем смысл использования auto?

В чем смысл использования auto?

В сети нашел статьи, например такиую: статья

150
C++, избавление объекта от квалификатора const

C++, избавление объекта от квалификатора const

Хорошим тоном в C/C++ считается использование const везде, где можно

165
Значения с С++ в QML

Значения с С++ в QML

С СОМ порта мне приходят данные, например: 19999932

144