diff --git a/core/include/Variable/VariableModel.h b/core/include/Variable/VariableModel.h index 2e891ee..adbcd1d 100644 --- a/core/include/Variable/VariableModel.h +++ b/core/include/Variable/VariableModel.h @@ -36,6 +36,13 @@ public: void addVariable(std::shared_ptr variable) noexcept; /** + * Checks that a variable is contained in the model + * @param variable the variable to check + * @return true if the variable is in the model, false otherwise + */ + bool containsVariable(std::shared_ptr variable) const noexcept; + + /** * Creates a new variable in the model * @param name the name of the new variable * @param dateTime the dateTime of the new variable diff --git a/core/src/Variable/VariableController.cpp b/core/src/Variable/VariableController.cpp index 5951f28..f639a57 100644 --- a/core/src/Variable/VariableController.cpp +++ b/core/src/Variable/VariableController.cpp @@ -191,13 +191,21 @@ void VariableController::setTimeController(TimeController *timeController) noexc std::shared_ptr VariableController::cloneVariable(std::shared_ptr variable) noexcept { - // Clones variable - auto duplicate = variable->clone(); + if (impl->m_VariableModel->containsVariable(variable)) { + // Clones variable + auto duplicate = variable->clone(); - // Adds clone to model - impl->m_VariableModel->addVariable(duplicate); + // Adds clone to model + impl->m_VariableModel->addVariable(duplicate); - return duplicate; + return duplicate; + } + else { + qCCritical(LOG_VariableController()) + << tr("Can't create duplicate of variable %1: variable not registered in the model") + .arg(variable->name()); + return nullptr; + } } void VariableController::deleteVariable(std::shared_ptr variable) noexcept diff --git a/core/src/Variable/VariableModel.cpp b/core/src/Variable/VariableModel.cpp index 1ba3792..ad88e27 100644 --- a/core/src/Variable/VariableModel.cpp +++ b/core/src/Variable/VariableModel.cpp @@ -88,6 +88,12 @@ void VariableModel::addVariable(std::shared_ptr variable) noexcept endInsertRows(); } +bool VariableModel::containsVariable(std::shared_ptr variable) const noexcept +{ + auto end = impl->m_Variables.cend(); + return std::find(impl->m_Variables.cbegin(), end, variable) != end; +} + std::shared_ptr VariableModel::createVariable(const QString &name, const SqpRange &dateTime, const QVariantHash &metadata) noexcept