diff --git a/qt6-after/qt6-migrated-legatus/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/CMakeLists.txt index 1a6a902ae..f23d4a52d 100755 --- a/qt6-after/qt6-migrated-legatus/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/CMakeLists.txt @@ -94,7 +94,12 @@ IF(WIN32) LIST(APPEND CMAKE_PROGRAM_PATH "${EXTERNAL_LIBRARY_DIR}/bin;${EXTERNAL_LIBRARY_DIR}/dev-utils/bin") ELSE() # Linux: ArcGIS SDK Pfad konfigurieren - SET(ARCGIS_SDK_DIR "/repo/external/ArcGIS/MapsSDK_Qt_300.0.0/ArcGIS_Maps_SDK_Qt_300.0.0/qt300.0.0/sdk" CACHE STRING "ArcGIS Runtime SDK for Qt directory") + # Use environment variable ARCGIS_ROOT if set, otherwise default to /repo/external/... + IF(DEFINED ENV{ARCGIS_ROOT}) + SET(ARCGIS_SDK_DIR "$ENV{ARCGIS_ROOT}" CACHE STRING "ArcGIS Runtime SDK for Qt directory") + ELSE() + SET(ARCGIS_SDK_DIR "/repo/external/ArcGIS/MapsSDK_Qt_300.0.0/ArcGIS_Maps_SDK_Qt_300.0.0/qt300.0.0/sdk" CACHE STRING "ArcGIS Runtime SDK for Qt directory") + ENDIF() IF(EXISTS "${ARCGIS_SDK_DIR}") LIST(APPEND CMAKE_PREFIX_PATH "${ARCGIS_SDK_DIR}") MESSAGE(STATUS "ArcGIS SDK found at: ${ARCGIS_SDK_DIR}") diff --git a/qt6-after/qt6-migrated-legatus/EXTERNAL_DEPS.md b/qt6-after/qt6-migrated-legatus/EXTERNAL_DEPS.md new file mode 100644 index 000000000..789f42763 --- /dev/null +++ b/qt6-after/qt6-migrated-legatus/EXTERNAL_DEPS.md @@ -0,0 +1,45 @@ +# Externe Dependencies - Fehlende Libraries + +## Nicht verfügbare externe Libraries + +Folgende Libraries werden im Build referenziert, sind aber nicht im migrierten Code verfügbar: + +### Services +- `svcPpmCommon` - Participant Management Service Common +- `svcExmCommon` - Exercise Management Service Common +- `svcGnaCommon` - Guez Nasat Common +- `svcAvmCommon` - Audio/Video Management Common (BUILD_RTI abhängig) +- `svcEemCommon` - Equipment Management Service Common + +### Plugin Interfaces +- `PpmGuiComboboxPluginInterface` - Participant Management GUI Combobox Interface +- `AsbDataPluginInterface` - ASB Data Plugin Interface +- `ExmDataPluginInterface` - Exercise Management Data Plugin Interface +- `advancedSymbologyGui` - Advanced Symbology GUI + +### svcPdmClient +- **Status**: Nicht vorhanden +- **Betroffene Module**: + - `Lts/Proxies/TrainingAreaBase/Plugins/AdlerJson/saaTelegrams` + - `Lts/Proxies/TrainingAreaBase/Plugins/AdlerJson/tabPluginAdler` +- **Lösung**: Dependency auskommentieren + +## Betroffene Module + +### Lts/Plugins/GuezNasat/Gui/Common (GnaCommon) +- Benötigt: PpmGuiComboboxPluginInterface, svcGnaCommon, svcExmCommon, svcPpmCommon + +### Lts/Plugins/ParticipantManagement/Gui/Common (PpmCommon) +- Benötigt: svcPpmCommon, AsbDataPluginInterface, ExmDataPluginInterface, advancedSymbologyGui + +### Lts/Plugins/AlarmManagement/Gui/Common (AlmCommon) +- Benötigt: svcGnaCommon (für logger.h), svcPpmCommon, svcAlmCommon, svcAesCommon, advancedSymbology, advancedSymbologyGui +- Status: Hinter BUILD_RTI Guard gesetzt (benötigt GuezNasat/RTI) + +## Lösung + +Diese Module benötigen die externen Dependencies für einen vollständigen Build. +Optionen: +1. Externe Dependencies als Submodule einbinden +2. Module暂时 deaktivieren bis Dependencies verfügbar +3. Stubs für Interfaces erstellen (nicht empfohlen per User-Anweisung) diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans.h index 436dab573..9febecd42 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans.h @@ -4,7 +4,7 @@ #include #include -#include +#include "ltscoordtrans_export.h" #include class QPointF; class QRectF; diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/CMakeLists.txt index 87d62dc6e..879ea304f 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/CMakeLists.txt @@ -11,17 +11,20 @@ NGL_ADD_LIBRARY2(WS SV HLA LtsElevation SHARED logger.h ) NGL_TARGET_INCLUDE_DIRECTORIES(LtsElevation - INTERFACE + PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../ - ${CMAKE_CURRENT_SOURCE_DIR}/../../Lts/Viewer/SituationMap + ${CMAKE_SOURCE_DIR}/Lts/Common + ${CMAKE_SOURCE_DIR}/Lts/Common/LtsUtils + ${CMAKE_SOURCE_DIR}/Lts/Viewer/SituationMap + ${CMAKE_SOURCE_DIR}/Lts/Viewer/SituationMap/Common ) NGL_TARGET_LINK_LIBRARIES(LtsElevation PRIVATE NGLLogger ## LtsSessionDataDds - ExmDataPluginInterface - situationMapCommon - situationMapElevationMap +## ExmDataPluginInterface # External dependency - missing +## situationMapCommon # External dependency - missing +## situationMapElevationMap # External dependency - missing PUBLIC LtsUtilsCoreHeaderOnly Qt6::Core diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/UnitTest_Elevation/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/UnitTest_Elevation/CMakeLists.txt index 19f570923..f42c3fc64 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/UnitTest_Elevation/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/UnitTest_Elevation/CMakeLists.txt @@ -18,8 +18,8 @@ TARGET_LINK_LIBRARIES(commenUnitTestElevation nglcoreapplication LtsElevation LtsCoordTrans - situationMapCommon - situationMapElevationMap +## situationMapCommon # External dependency - missing +## situationMapElevationMap # External dependency - missing Qt6::Core Qt6::Gui Qt6::Test) diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/lts_elevation_manager.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/lts_elevation_manager.cpp index c56ab759f..4f0327850 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/lts_elevation_manager.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/lts_elevation_manager.cpp @@ -5,14 +5,7 @@ #ifdef BUILD_RTI #include #include -#endif -#include -#include -#include -#include -#include #include -#include static_assert((int)SituationMap::ElevationMapManager::LineOfSight::LOS_UNDEFINED == (int)LtsElevation::LineOfSight::LOS_UNDEFINED, @@ -26,6 +19,7 @@ static_assert((int)SituationMap::ElevationMapManager::LineOfSight::LOS_VISIBLE = static_assert((int)SituationMap::ElevationMapManager::LineOfSight::LOS_INVISIBLE == (int)LtsElevation::LineOfSight::LOS_INVISIBLE, "LineOfSight mismatch"); +#endif namespace LtsElevation { @@ -62,16 +56,18 @@ class LtsElevationManager::Private ~Private() { +#ifdef BUILD_RTI delete m_elevationManager; +#endif } std::shared_ptr m_exmDtc; #ifdef BUILD_RTI std::shared_ptr m_asmDtc; + SituationMap::ElevationMapManager* m_elevationManager{nullptr}; #endif QStringList m_filePaths_rough_to_fine; - SituationMap::ElevationMapManager* m_elevationManager{nullptr}; }; LtsElevationManager::LtsElevationManager() @@ -335,6 +331,7 @@ QStringList LtsElevationManager::getFilenamesForTrainingArea(int /*trainingAreaI bool LtsElevationManager::init(const QStringList& filePaths_rough_to_fine) { +#ifdef BUILD_RTI delete d->m_elevationManager; d->m_elevationManager = new SituationMap::ElevationMapManager(); @@ -347,11 +344,14 @@ bool LtsElevationManager::init(const QStringList& filePaths_rough_to_fine) FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!"; FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!"; FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!"; - FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!"; - FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!"; return false; } return true; +#else + Q_UNUSED(filePaths_rough_to_fine); + ERROR_LOG(m_logger) << Q_FUNC_INFO << " BUILD_RTI=OFF, init not available"; + return false; +#endif } #ifdef BUILD_RTI @@ -403,28 +403,47 @@ int LtsElevationManager::exerciseIdToTrainingAreaId(int exerciseId, bool LtsElevationManager::waitForInitialization() { +#ifdef BUILD_RTI if (!d->m_elevationManager) return false; return d->m_elevationManager->waitForInitialization(); +#else + ERROR_LOG(m_logger) << Q_FUNC_INFO << " BUILD_RTI=OFF, waitForInitialization not available"; + return false; +#endif } bool LtsElevationManager::isValid() const { +#ifdef BUILD_RTI if (!d->m_elevationManager) return false; return d->m_elevationManager->isValid(); +#else + ERROR_LOG(m_logger) << Q_FUNC_INFO << " BUILD_RTI=OFF, isValid not available"; + return false; +#endif } double LtsElevationManager::elevation(double lon_rad, double lat_rad, double defaultValue, bool* bIsCovered) const { +#ifdef BUILD_RTI if (!d->m_elevationManager) return defaultValue; return d->m_elevationManager->elevation(lon_rad, lat_rad, defaultValue, bIsCovered); +#else + Q_UNUSED(lon_rad); + Q_UNUSED(lat_rad); + Q_UNUSED(bIsCovered); + ERROR_LOG(m_logger) << Q_FUNC_INFO << " BUILD_RTI=OFF, elevation not available"; + return defaultValue; +#endif } LineOfSight LtsElevationManager::lineOfSightCalculation(const LtsUtils::QPoint3D& startPointGeo_absZ, const LtsUtils::QPoint3D& endPointGeo_absZ) { +#ifdef BUILD_RTI TRACE_LOG(m_logger) << Q_FUNC_INFO << " START" << ", startPointGeo_absZ = " << startPointGeo_absZ << ", endPointGeo_absZ = " << endPointGeo_absZ; @@ -444,11 +463,18 @@ LineOfSight LtsElevationManager::lineOfSightCalculation(const LtsUtils::QPoint3D << ", startPointGeo = " << startPointGeo_absZ << ", endPointGeo = " << endPointGeo_absZ << " -> LineOfSight " << result; return result; +#else + Q_UNUSED(startPointGeo_absZ); + Q_UNUSED(endPointGeo_absZ); + ERROR_LOG(m_logger) << Q_FUNC_INFO << " BUILD_RTI=OFF, lineOfSightCalculation not available"; + return LineOfSight::LOS_ERROR; +#endif } LineOfSight LtsElevationManager::lineOfSightCalculation(const QPointF& startPointGeo, double startHat, const QPointF& endPointGeo, double endHat) { +#ifdef BUILD_RTI TRACE_LOG(m_logger) << Q_FUNC_INFO << " START" << ", startPointGeo = " << startPointGeo << ", startHat = " << startHat << ", endPointGeo = " << endPointGeo << ", endHat = " << endHat; @@ -463,6 +489,14 @@ LineOfSight LtsElevationManager::lineOfSightCalculation(const QPointF& startPoin << ", endPointGeo = " << endPointGeo << ", endHat = " << endHat << " -> LineOfSight " << static_cast(eleMapMgrResult); return result; +#else + Q_UNUSED(startPointGeo); + Q_UNUSED(startHat); + Q_UNUSED(endPointGeo); + Q_UNUSED(endHat); + ERROR_LOG(m_logger) << Q_FUNC_INFO << " BUILD_RTI=OFF, lineOfSightCalculation not available"; + return LineOfSight::LOS_ERROR; +#endif } const QString toString(const LineOfSight& value) diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/lts_elevation_manager.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/lts_elevation_manager.h index 0b996f24d..7701a4b3c 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/lts_elevation_manager.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/lts_elevation_manager.h @@ -7,6 +7,7 @@ #include #include +#include #include #include #include diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/CMakeLists.txt index e01884edc..8fa3b51ca 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/CMakeLists.txt @@ -33,12 +33,7 @@ NGL_ADD_LIBRARY2(WS LtsMultiMonitor SHARED ${LtsMultiMonitor_SRCS}) NGL_TARGET_INCLUDE_DIRECTORIES(LtsMultiMonitor PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../ -) - -NGL_TARGET_INCLUDE_DIRECTORIES(LtsMultiMonitor - PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/../ - ${PROJECT_SOURCE_DIR}/include/LtsUtilsGuiDds + ${CMAKE_SOURCE_DIR}/Lts/Common/LtsUtils ) NGL_TARGET_LINK_LIBRARIES(LtsMultiMonitor diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/CMakeLists.txt index 2942bfd05..f3e554b29 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/CMakeLists.txt @@ -19,8 +19,8 @@ SET(SRCS_hdr_only ADD_LIBRARY(LtsUtilsCoreHeaderOnly INTERFACE) TARGET_INCLUDE_DIRECTORIES(LtsUtilsCoreHeaderOnly INTERFACE - ${CMAKE_CURRENT_SOURCE_DIR}/.. - ${CMAKE_CURRENT_BINARY_DIR}/.. + ${CMAKE_CURRENT_SOURCE_DIR}/../.. + ${CMAKE_CURRENT_BINARY_DIR}/../.. ) TARGET_SOURCES(LtsUtilsCoreHeaderOnly INTERFACE ${SRCS_hdr_only}) @@ -39,8 +39,8 @@ SET(SRCS NGL_ADD_LIBRARY2(ALL LtsUtilsCore SHARED ${SRCS}) NGL_TARGET_INCLUDE_DIRECTORIES(LtsUtilsCore PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/.. - ${CMAKE_CURRENT_BINARY_DIR}/.. + ${CMAKE_CURRENT_SOURCE_DIR}/../.. + ${CMAKE_CURRENT_BINARY_DIR}/../.. ) NGL_TARGET_LINK_LIBRARIES(LtsUtilsCore PUBLIC diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/CMakeLists.txt index 95a3da073..d3e1c5884 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/CMakeLists.txt @@ -4,8 +4,6 @@ # $Author$ # -MESSAGE(STATUS "DEBUG LTSWIDGETS TOP: BUILD_RTI=${BUILD_RTI}") - # # Lts Widgets library # @@ -75,8 +73,8 @@ SET(ltswidgets_SRCS lts_image_editor.h lts_led_widget.cpp lts_led_widget.h - requirement_widget.cpp - requirement_widget.h + ui_requirement.cpp + ui_requirement.h #lts_widgets_export.h lts_picture_view.cpp lts_picture_view.h @@ -113,8 +111,6 @@ SET(ltswidgets_SRCS LtsImageCropper/lts_image_cropper.cpp ) -# requirement_widget.h renamed from ui_requirement.h to avoid AutoUIC scanning - #if (TABLET_MODE) # LIST(APPEND ltswidgets_SRCS @@ -146,27 +142,18 @@ NGL_WRAP_UI(ltswidgets_SRCS lts_text_editor.ui lts_notification_box.ui lts_angle_edit.ui - lts_date_time_edit_touch.ui +# lts_date_time_edit_touch.ui ) -MESSAGE(STATUS "DEBUG: After NGL_ADD_BIG_RESOURCES") +# ui_requirement.cpp/h sind normale C++ Dateien, keine UI-Dateien +# SKIP_AUTOUIC verhindert dass CMake nach requirement.ui sucht +set_source_files_properties(ui_requirement.cpp PROPERTIES SKIP_AUTOUIC ON) NGL_ADD_BIG_RESOURCES(ltswidgets_SRCS resources/lts_resources.qrc) +NGL_ADD_LIBRARY(WS TOOLSWS TOOLSSV LtsWidgets SHARED ${ltswidgets_SRCS}) -MESSAGE(STATUS "DEBUG: BUILD_RTI=${BUILD_RTI}, BUILD_WS=${BUILD_WS}, building LtsWidgets") - -# Define MAKE_LTSWIDGETS_LIB for proper symbol export -ADD_DEFINITIONS(-DMAKE_LTSWIDGETS_LIB) - -NGL_ADD_LIBRARY2(WS TOOLSWS TOOLSSV LtsWidgets SHARED ${ltswidgets_SRCS}) - -NGL_TARGET_INCLUDE_DIRECTORIES(LtsWidgets - PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/../ - ${CMAKE_BINARY_DIR}/Lts/Common/LtsUtils/LtsUtilsCore - ${CMAKE_CURRENT_BINARY_DIR} -) - +# Qt6 Dependencies immer setzen (auch wenn BUILD_RTI=OFF) +# Die Library wird gebaut, aber nur bei BUILD_RTI=ON installiert/verwendet NGL_TARGET_LINK_LIBRARIES(LtsWidgets PRIVATE Qt6::Network # for QHostInfo - for portability @@ -184,34 +171,42 @@ NGL_TARGET_LINK_LIBRARIES(LtsWidgets Qt6::Gui ) +IF(BUILD_RTI) + +NGL_TARGET_INCLUDE_DIRECTORIES(LtsWidgets + PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}/../ +) + NGL_INSTALL_TARGET(LtsWidgets) +ENDIF() # -# Designer-Plugin (RTI-dependent) +# Designer-Plugin # IF(BUILD_RTI) - SET(ltswidgetsplugin_SRCS ltswidgetsplugin.cpp ltswidgetsplugin.json) - NGL_ADD_LIBRARY(WS ltswidgetsplugin MODULE ${ltswidgetsplugin_SRCS}) - NGL_TARGET_LINK_LIBRARIES(ltswidgetsplugin LtsWidgets ltsCoordWidget LtsDataView LtsFileDialog LtsReportDisplay svcFlmCommon) - NGL_SET_TARGET_PROPERTIES(ltswidgetsplugin PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib/designer) - NGL_INSTALL_TARGET(ltswidgetsplugin DESTINATION lib/designer COMPONENT Devel) +SET(ltswidgetsplugin_SRCS ltswidgetsplugin.cpp ltswidgetsplugin.json) +NGL_ADD_LIBRARY(WS ltswidgetsplugin MODULE ${ltswidgetsplugin_SRCS}) +NGL_TARGET_LINK_LIBRARIES(ltswidgetsplugin LtsWidgets ltsCoordWidget LtsDataView LtsFileDialog LtsReportDisplay svcFlmCommon) +NGL_SET_TARGET_PROPERTIES(ltswidgetsplugin PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib/designer) +NGL_INSTALL_TARGET(ltswidgetsplugin DESTINATION lib/designer COMPONENT Devel) +ENDIF() + +IF(BUILD_TESTING) + # picture_editing_test + SET(pet_SRCS + tests/lts_picture_editing.cpp + tests/lts_picture_editing.h + tests/lts_picture_editing_main.cpp + ) + NGL_WRAP_UI(pet_SRCS + tests/lts_picture_editing.ui + ) + NGL_ADD_EXECUTABLE(WS NO_TRANSLATION picture_editing_test ${pet_SRCS}) + NGL_TARGET_LINK_LIBRARIES(picture_editing_test + LtsWidgets + ) - IF(BUILD_TESTING) - # picture_editing_test - SET(pet_SRCS - tests/lts_picture_editing.cpp - tests/lts_picture_editing.h - tests/lts_picture_editing_main.cpp - ) - NGL_WRAP_UI(pet_SRCS - tests/lts_picture_editing.ui - ) - NGL_ADD_EXECUTABLE(WS NO_TRANSLATION picture_editing_test ${pet_SRCS}) - NGL_TARGET_LINK_LIBRARIES(picture_editing_test - LtsWidgets - ) - ENDIF() -ENDIF(BUILD_RTI) # # LtsWidgetsTest # SET(src_test @@ -224,3 +219,4 @@ ENDIF(BUILD_RTI) # NGL_TARGET_LINK_LIBRARIES(LtsWidgetsTest # LtsWidgets # ) +ENDIF() diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/LtsImageCropper/lts_image_cropper.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/LtsImageCropper/lts_image_cropper.cpp index 73d8de27e..a11104eb6 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/LtsImageCropper/lts_image_cropper.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/LtsImageCropper/lts_image_cropper.cpp @@ -1,122 +1,137 @@ - +/* + * @RDE_HEADER@ + * graphicsview widget to resize qpixmaps/qimages with mouse drag and mwheel + * $Id$ + * $HeadURL$ + * $Author$ + * Created by Jens Heilmann, SLTE, 2020-10-14 + */ #include "lts_image_cropper.h" - -#include #include #include +#include namespace LtsWidgets { -LtsImageCropper::LtsImageCropper(QWidget* parent, const QSize& size, const QPixmap& pixmap) - : QGraphicsView(parent), m_scene(new QGraphicsScene(this)), m_maxScale(2.0f), m_multiplier(1.0f) +LtsImageCropper::LtsImageCropper(QWidget *parent, const QSize &size, const QPixmap &pixmap) + : QGraphicsView(parent) + , m_scene(new QGraphicsScene(this)) + , m_maxScale(2.0f) + , m_multiplier(1.0f) { - if (!size.isNull()) - setFixedSize(size); + if(!size.isNull()) + setFixedSize(size); - setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setFrameStyle(QFrame::NoFrame); - setDragMode(QGraphicsView::ScrollHandDrag); - setTransformationAnchor(QGraphicsView::AnchorViewCenter); + setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setFrameStyle(QFrame::NoFrame); + setDragMode(QGraphicsView::ScrollHandDrag); + setTransformationAnchor(QGraphicsView::AnchorViewCenter); - m_scene->setBackgroundBrush(Qt::Dense6Pattern); - setScene(m_scene); + m_scene->setBackgroundBrush(Qt::Dense6Pattern); + setScene(m_scene); - setPixmap(pixmap); + setPixmap(pixmap); } LtsImageCropper::~LtsImageCropper() { - delete m_pixmapItem; + delete m_pixmapItem; } -void LtsImageCropper::setPixmap(const QPixmap& pixmap) +void LtsImageCropper::setPixmap(const QPixmap &pixmap) { - if (pixmap.isNull()) - return; + if(pixmap.isNull()) + return; - delete m_pixmapItem; + delete m_pixmapItem; // delete previous pixmapitem - m_pixmapItem = new QGraphicsPixmapItem(pixmap); - m_scene->addItem(m_pixmapItem); + m_pixmapItem = new QGraphicsPixmapItem(pixmap); + m_scene->addItem(m_pixmapItem); - setTransform(QTransform()); - m_currentZoom = 1.0; + setTransform(QTransform()); // set a fresh transformation matrix + m_currentZoom = 1.0; // reset current zoom - double sx = static_cast(size().height()) / pixmap.height(); - double sy = static_cast(size().width()) / pixmap.width(); - if (sx > 1) - scale(sx, sx); - if (sy > 1) - scale(sy, sy); + //check if image size is min view, if not scale it + double sx = static_cast(size().height()) / pixmap.height(); + double sy = static_cast(size().width()) / pixmap.width(); + if(sx > 1 ) + scale(sx,sx); + if(sy > 1) + scale(sy,sy); - double ratioWidth = 1.0 * size().width() / pixmap.width(); - double ratioHeight = 1.0 * size().height() / pixmap.height(); - m_minScale = qMax(ratioHeight, ratioWidth); + // calculate min scale from qMin(width,height); + double ratioWidth = 1.0 * size().width() / pixmap.width(); + double ratioHeight = 1.0 * size().height() / pixmap.height(); + m_minScale = qMax(ratioHeight,ratioWidth); - calculateScaleStep(); + calculateScaleStep(); - m_scene->setSceneRect(pixmap.rect()); - centerOn(m_scene->sceneRect().center()); + // change scene boundaries to image rectangle and center scene on image center + m_scene->setSceneRect(pixmap.rect()); + centerOn(m_scene->sceneRect().center()); } -void LtsImageCropper::setImage(const QImage& image) +void LtsImageCropper::setImage(const QImage &image) { - setPixmap(QPixmap::fromImage(image)); + setPixmap(QPixmap::fromImage(image)); } void LtsImageCropper::setMultiplier(double multiplier) { - m_multiplier = multiplier; - calculateScaleStep(); + m_multiplier = multiplier; + calculateScaleStep(); } void LtsImageCropper::calculateScaleStep() { - m_stepScale = (m_maxScale - m_minScale) / 100.0; + m_stepScale = (m_maxScale - m_minScale) / 100.0; } QImage LtsImageCropper::image() { - return grab().toImage(); + return grab().toImage(); } -void LtsImageCropper::wheelEvent(QWheelEvent* event) +void LtsImageCropper::wheelEvent(QWheelEvent *event) { - if (!m_pixmapItem) - return; + if(!m_pixmapItem) + return; - auto value = event->pixelDelta(); - if (value.isNull()) - value = event->angleDelta() / 15.0; + auto value = event->pixelDelta(); + if(value.isNull()) + value = event->angleDelta() / 15.0; - double scrollZoom = m_stepScale * value.y() * m_multiplier / 8.0; + // calculate scrollZoom value to be added to the current zoom + double scrollZoom = m_stepScale * value.y() * m_multiplier / 8.0; - m_currentZoom += scrollZoom; + m_currentZoom += scrollZoom; - if (m_currentZoom > m_maxScale) - m_currentZoom = m_maxScale; - else if (m_currentZoom < m_minScale) - m_currentZoom = m_minScale; + if(m_currentZoom > m_maxScale) + m_currentZoom = m_maxScale; + else if (m_currentZoom < m_minScale) + m_currentZoom = m_minScale; - setTransform(QTransform(m_currentZoom, transform().m12(), transform().m13(), transform().m21(), m_currentZoom, - transform().m23(), transform().m31(), transform().m32(), 1)); + // scale the view + setTransform(QTransform(m_currentZoom, transform().m12(), transform().m13(), + transform().m21(), m_currentZoom, transform().m23(), + transform().m31(), transform().m32(), 1)); } -void LtsImageCropper::mousePressEvent(QMouseEvent* event) +void LtsImageCropper::mousePressEvent(QMouseEvent *event) { - QApplication::setOverrideCursor(Qt::DragMoveCursor); - update(); - QGraphicsView::mousePressEvent(event); + QApplication::setOverrideCursor(Qt::DragMoveCursor); + update(); + QGraphicsView::mousePressEvent(event); } -void LtsImageCropper::mouseReleaseEvent(QMouseEvent* event) +void LtsImageCropper::mouseReleaseEvent(QMouseEvent *event) { - QApplication::restoreOverrideCursor(); - update(); - QGraphicsView::mouseReleaseEvent(event); + QApplication::restoreOverrideCursor(); + update(); + QGraphicsView::mouseReleaseEvent(event); } -} // namespace LtsWidgets +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/LtsImageCropper/lts_image_cropper.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/LtsImageCropper/lts_image_cropper.h index 490b68181..29a31b9b4 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/LtsImageCropper/lts_image_cropper.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/LtsImageCropper/lts_image_cropper.h @@ -1,71 +1,108 @@ - +/* + * @RDE_HEADER@ + * graphicsview widget to resize qpixmaps/qimages with mouse drag and mwheel + * $Id$ + * $HeadURL$ + * $Author$ + * Created by Jens Heilmann, SLTE, 2020-10-14 + */ #pragma once -#include "ltswidgets_export.h" +#include "lts_widgets_export.h" #include -#include namespace LtsWidgets { +/** + * @brief The ImageCropper class provides a graphicsview widget to crop images with mouse drag and mwheel scroll. + * avatar() returns a pixmap of the current view (the cropped image). + */ class LTSWIDGETS_EXPORT LtsImageCropper : public QGraphicsView { - Q_OBJECT + Q_OBJECT - Q_PROPERTY(QPixmap pixMap READ pixmap WRITE setPixmap) - Q_PROPERTY(double multiplier READ multiplier WRITE setMultiplier) - Q_PROPERTY(double maxZoom READ maxZoom WRITE setMaxZoom) + Q_PROPERTY(QPixmap pixMap READ pixmap WRITE setPixmap) + Q_PROPERTY(double multiplier READ multiplier WRITE setMultiplier) + Q_PROPERTY(double maxZoom READ maxZoom WRITE setMaxZoom) - public: - LtsImageCropper(QWidget* parent = nullptr, const QSize& size = {}, const QPixmap& pixmap = {}); - ~LtsImageCropper(); +public: + /** + * @brief ImageCropper + * @param parent + * @param size specifies the size of the graphicsview widget, aswell as the size of the cropped image. + * @param image to crop + */ + LtsImageCropper(QWidget *parent = nullptr, const QSize &size = {} , const QPixmap &pixmap = {}); + ~LtsImageCropper(); - void setPixmap(const QPixmap& pixmap); + /** + * @brief setter for image + * @param image + */ + void setPixmap(const QPixmap &pixmap); - void setImage(const QImage& image); + /** + * @brief setter for image + * @param image + */ + void setImage(const QImage &image); - void setMultiplier(double multiplier); + /** + * @brief set the zoom mutliplier for mwheel scaling e.g. 1.03. + * @param multiplier + */ + void setMultiplier(double multiplier); - void setMaxZoom(double maxZoom) - { - m_maxScale = maxZoom; - } + /** + * @brief set the maximum zoom in scale e.g. 2.0 = 200% zoom in. + * @param maxZoom + */ + void setMaxZoom(double maxZoom) { m_maxScale = maxZoom; } - QPixmap pixmap() - { - return grab(); - } + /** + * @brief returns the current graphicsview view as a pixmap. + * @return qpixmap + */ + QPixmap pixmap() { return grab(); } - QImage image(); + /** + * @brief returns the current graphicsview view as qimage. + * @return qimage + */ + QImage image(); - double multiplier() const - { - return m_multiplier; - } + /** + * @brief returns the current multiplier + * @return double + */ + double multiplier() const { return m_multiplier; } - double maxZoom() const - { - return m_maxScale; - } + /** + * @brief returns the current max zoom value + * @return double + */ + double maxZoom() const { return m_maxScale; } - private: - QGraphicsScene* m_scene = nullptr; - QGraphicsPixmapItem* m_pixmapItem = nullptr; +private: + QGraphicsScene *m_scene = nullptr; + QGraphicsPixmapItem *m_pixmapItem = nullptr; - double m_currentZoom; - double m_minScale; - double m_maxScale; - double m_stepScale; - double m_multiplier; + double m_currentZoom; + double m_minScale; + double m_maxScale; + double m_stepScale; + double m_multiplier; - void calculateScaleStep(); + void calculateScaleStep(); + +protected: + void wheelEvent(QWheelEvent *event) override; + void mousePressEvent(QMouseEvent *event) override; + void mouseReleaseEvent(QMouseEvent *event) override; - protected: - void wheelEvent(QWheelEvent* event) override; - void mousePressEvent(QMouseEvent* event) override; - void mouseReleaseEvent(QMouseEvent* event) override; }; } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_abstract_sequence_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_abstract_sequence_widget.cpp index d32344cce..71b8ad136 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_abstract_sequence_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_abstract_sequence_widget.cpp @@ -1,22 +1,32 @@ - - +/** + * @RDE_HEADER@ + * ABC widget for creating custom views of sequences + * $Id$ + * $HeadURL$ + * $Author$ + * Created by Verena Eberlein, SPMO, 2023-08-03 + */ #include "lts_abstract_sequence_widget.h" -#include #include namespace LtsWidgets { -LtsAbstractSequenceWidget::LtsAbstractSequenceWidget(QWidget* parent, const bool& readOnly) - : QGroupBox(parent), m_readOnly(readOnly), m_pbAddMember(new QToolButton) +LtsAbstractSequenceWidget::LtsAbstractSequenceWidget(QWidget *parent, const bool &readOnly) + : QGroupBox(parent) + , m_readOnly(readOnly) + , m_pbAddMember(new QToolButton) { - m_pbAddMember->setIcon(QIcon(QLatin1String(":/icons/png/add.png"))); + m_pbAddMember->setIcon(QIcon(QLatin1String(":/icons/png/add.png"))); - connect(m_pbAddMember, &QToolButton::clicked, this, &LtsAbstractSequenceWidget::addMember); + connect(m_pbAddMember, &QToolButton::clicked, this, &LtsAbstractSequenceWidget::addMember); } -LtsAbstractSequenceWidget::~LtsAbstractSequenceWidget() {} +LtsAbstractSequenceWidget::~LtsAbstractSequenceWidget() +{ + +} void LtsAbstractSequenceWidget::addWidget(QWidget* widget, bool isReadOnly, bool isButtonVisible) { @@ -25,91 +35,92 @@ void LtsAbstractSequenceWidget::addWidget(QWidget* widget, bool isReadOnly, bool m_pbAddMember->setVisible(isButtonVisible); } -int LtsAbstractSequenceWidget::getMemberlistSize() -{ - return m_memberList.size(); +int LtsAbstractSequenceWidget::getMemberlistSize(){ + return m_memberList.size(); } -void LtsAbstractSequenceWidget::getValue(QWidget* data, const QString& findObjectName) const +void LtsAbstractSequenceWidget::getValue(QWidget *data, + const QString &findObjectName) const { - if (!findChild(findObjectName)) - return; + if(!findChild(findObjectName)) + return; - data = findChild(findObjectName); + data = findChild(findObjectName); } void LtsAbstractSequenceWidget::setMemberCount(int count) { - QWidget* child = nullptr; - do - { - child = findChild(getObjectName(++count)); - delete child; - } while (child); - m_memberList.removeAll(nullptr); + QWidget *child = nullptr; + do + { + child = findChild(getObjectName(++count)); + delete child; + } + while (child); + m_memberList.removeAll(nullptr); } uint32_t LtsAbstractSequenceWidget::getMemberCount() const { - int count = 0; - QWidget* child = findChild(getObjectName(count + 1)); - while (child) - { - count++; - child = findChild(getObjectName(count + 1)); - } - return count; + int count = 0; + QWidget *child = findChild(getObjectName(count+1)); + while(child) + { + count++; + child = findChild(getObjectName(count+1)); + } + return count; } -QToolButton* LtsAbstractSequenceWidget::pbAddMember() const +QToolButton *LtsAbstractSequenceWidget::pbAddMember() const { - return m_pbAddMember; + return m_pbAddMember; } QString LtsAbstractSequenceWidget::getObjectName(int index) const { - return QString::number(index); + return QString::number(index); } -void LtsAbstractSequenceWidget::addMemberWidget(QWidget* member, bool isReadOnly, bool isButtonVisible) +void LtsAbstractSequenceWidget::addMemberWidget(QWidget *member, bool isReadOnly, bool isButtonVisible) { - QToolButton* button = new QToolButton(); - button->setIcon(QIcon(QLatin1String(":/icons/png/remove.png"))); - button->setDisabled(isReadOnly); + QToolButton *button = new QToolButton(); + button->setIcon(QIcon(QLatin1String(":/icons/png/remove.png"))); + button->setDisabled(isReadOnly); - connect(button, &QToolButton::clicked, member, &QWidget::deleteLater); - connect(member, &QWidget::destroyed, this, &LtsAbstractSequenceWidget::deleteMemberWidget); - connect(member, &QWidget::destroyed, button, &QToolButton::deleteLater); + connect(button, &QToolButton::clicked, member, &QWidget::deleteLater); + connect(member, &QWidget::destroyed, this, &LtsAbstractSequenceWidget::deleteMemberWidget); + connect(member, &QWidget::destroyed, button, &QToolButton::deleteLater); - m_memberList.push_back(member); - setupMemberWidget(member, button, member->objectName(), isButtonVisible); + m_memberList.push_back(member); + setupMemberWidget(member, button, member->objectName(), isButtonVisible); } -void LtsAbstractSequenceWidget::deleteMemberWidget(QObject* member) +void LtsAbstractSequenceWidget::deleteMemberWidget(QObject *member) { - QWidget* w = qobject_cast(member); + QWidget *w = qobject_cast(member); - if (!w) - return; + if(!w) + return; - for (auto child : w->children()) - child->deleteLater(); + for(auto child : w->children()) // necessary? + child->deleteLater(); - m_memberList.removeAll(w); - for (int i = 0; i < m_memberList.size(); i++) + m_memberList.removeAll(w); + for(int i=0; isetObjectName(getObjectName(i + 1)); + + for(auto child : m_memberList[i]->children()) { - m_memberList[i]->setObjectName(getObjectName(i + 1)); + if(child->objectName().isEmpty()) + continue; - for (auto child : m_memberList[i]->children()) - { - if (child->objectName().isEmpty()) - continue; - - QString childName = child->objectName(); - QString newId = QString::number(i + 1); - child->setObjectName(childName.replace(QRegularExpression(QLatin1String("\\.([0-9]*)")), newId)); - } + QString childName = child->objectName(); + QString newId = QString::number(i + 1); + child->setObjectName(childName.replace(QRegExp(QLatin1String(".([0-9]*)")), newId)); } + } } } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_abstract_sequence_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_abstract_sequence_widget.h index 3927fb2d2..a2067d60e 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_abstract_sequence_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_abstract_sequence_widget.h @@ -1,59 +1,126 @@ #ifndef LTS_ABSTRACT_SEQUENCE_WIDGET_H #define LTS_ABSTRACT_SEQUENCE_WIDGET_H +/** + * @RDE_HEADER@ + * ABC for creating custom views of dds sequences + * $Id$ + * $HeadURL$ + * $Author$ + * Created by Verena Eberlein, SPMO, 2023-08-03 + */ + #pragma once -#include "lts_widgets_export.h" + #include #include -#include +#include "lts_widgets_export.h" class QToolButton; - namespace LtsWidgets { + class LTSWIDGETS_EXPORT LtsAbstractSequenceWidget : public QGroupBox { - Q_OBJECT - public: - explicit LtsAbstractSequenceWidget(QWidget* parent = nullptr, const bool& readOnly = false); + Q_OBJECT +public: + /** + * @brief LtsAbstractSequenceWidget inits pbAddMember and adds logic to it. + * @attention pbAddMember must be inserted into a layout + * @param readOnly if read only, disable all buttons on creation + * @param name + * @param contentType + * @param parent + */ - ~LtsAbstractSequenceWidget(); + explicit LtsAbstractSequenceWidget(QWidget *parent = nullptr, const bool &readOnly = false); - virtual void addWidget(QWidget* widget, bool isReadOnly, bool isButtonVisible = true); + ~LtsAbstractSequenceWidget(); - virtual void getValue(QWidget* contentType, const QString& findObjectName) const; + /** + * @brief adds a given QWidget + * @param widget + */ + virtual void addWidget(QWidget* widget, bool isReadOnly, bool isButtonVisible = true); + /** + * @brief getValue get widget by objectname + * @param contentType + * @param findObjectName + */ + virtual void getValue(QWidget *contentType, + const QString &findObjectName) const; - virtual void setMemberCount(int count); + /** + * @brief setMemberCount + * @param count + */ + virtual void setMemberCount(int count); - virtual uint32_t getMemberCount() const; + /** + * @brief getMemberCount by objectname + * @return count + */ + virtual uint32_t getMemberCount() const; - virtual int getMemberlistSize(); + /** + * @brief get the current memberlist size + * @return count + */ + virtual int getMemberlistSize(); - protected: - virtual QToolButton* pbAddMember() const; - virtual QString getObjectName(int index) const; +protected: - virtual void setupMemberWidget(QWidget* child, QToolButton* pbChild, const QString& objectName, - bool isButtonVisible = true) = 0; + /** + * @brief pbAddMember + * @return + */ + virtual QToolButton *pbAddMember() const; - signals: - void addMember(); + /** + * @brief getObjectName generates a valid object name given by index + * @param index + * @return + */ + virtual QString getObjectName(int index) const; - private slots: + /** + * @brief setupMemberWidget place child and button widget into a layout + * @param child + * @param pbChild + * @param objectName + */ + virtual void setupMemberWidget(QWidget *child, QToolButton *pbChild, const QString &objectName, bool isButtonVisible = true) = 0; - virtual void addMemberWidget(QWidget* member, bool isReadOnly, bool isButtonVisible = true); +signals: + /** + * @brief signal is send when ToolButton is pressed so we can add a member widget via addWidget + */ + void addMember(); + +private slots: + /** + * @brief addMemberWidget create a new button and connect to child + * @param member new child + */ + virtual void addMemberWidget(QWidget *member, bool isReadOnly, bool isButtonVisible = true); + + /** + * @brief deleteMemberWidget clean up child and reindex other children objectnames + * @param member deleted child + */ + virtual void deleteMemberWidget(QObject *member); + +private: + bool m_readOnly; + QToolButton *m_pbAddMember = nullptr; + QList m_memberList; - virtual void deleteMemberWidget(QObject* member); - private: - bool m_readOnly; - QToolButton* m_pbAddMember = nullptr; - QList m_memberList; }; -} // namespace LtsWidgets +} -#endif +#endif // LTS_ABSTRACT_SEQUENCE_WIDGET_H diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_abstract_table_model.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_abstract_table_model.h index d43eb3319..cfbaeff0e 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_abstract_table_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_abstract_table_model.h @@ -1,264 +1,293 @@ - +/** + * @RDE_HEADER@ + * + * $Id$ + * $HeadURL$ + * $Author$ + * Created by Philipp Last, SLSE, 2017-06-20 + */ #pragma once #include "lts_base.h" -#include -#include +#include + #include -#include +#include + #include +#include + namespace LtsWidgets { -template class LtsAbstractTableModel : public QAbstractTableModel +template +class LtsAbstractTableModel : public QAbstractTableModel { +public: + LtsAbstractTableModel(const QVector &header, QObject *parent) + : QAbstractTableModel(parent) + , m_vecColumns(header) + {} + + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override + { + if (role == Qt::DisplayRole && orientation == Qt::Horizontal && section>= 0 && section < m_vecColumns.size()) + return m_vecColumns[section]; + + return QAbstractTableModel::headerData(section, orientation, role); + } + + bool isEmpty(const QModelIndex &parent = QModelIndex()) + { + return parent.isValid() ? true : m_vecData.isEmpty(); + } + + int rowCount(const QModelIndex &parent = QModelIndex()) const override + { + return parent.isValid() ? 0 : m_vecData.size(); + } + + int columnCount(const QModelIndex &parent = QModelIndex()) const override + { + return parent.isValid() ? 0 : m_vecColumns.size(); + } + + void clear() + { + beginResetModel(); + m_vecData.clear(); + endResetModel(); + } + + bool indexIsValid(const QModelIndex &idx) const + { + if (!idx.isValid()) + return false; + if (idx.row() < 0 || idx.row() >= m_vecData.size()) + return false; + return true; + } + + virtual bool removeRow(int row) + { + return removeRows(row, 1); + } + + bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override + { + if (parent.isValid()) + return false; + + if (row < 0 || row >= m_vecData.size()) + return false; + + int range = std::min(row + count, m_vecData.size()); + + beginRemoveRows(QModelIndex(), row, range - 1); + m_vecData.erase(m_vecData.begin() + row, m_vecData.begin() + range); + endRemoveRows(); + + return true; + } + + virtual bool insertRow(const T &item) + { + if (isFiltered(item, DataModification::eAdded) || isDeletedInternal(item)) + return false; + beginInsertRows(QModelIndex(), m_vecData.size(), m_vecData.size()); + m_vecData.append(item); + endInsertRows(); + return true; + } + + template + void insertRows(const CONT &items) + { + if (items.isEmpty()) + return; + const int cntBefore = m_vecData.size(); + for (const auto &item : items) + { + if (isFiltered(item, DataModification::eAdded) || isDeletedInternal(item)) + continue; + m_vecData += item; + } + const int cntAfter = m_vecData.size(); + if (cntBefore == cntAfter) + return; + beginInsertRows(QModelIndex(), cntBefore, cntAfter - 1); + endInsertRows(); + } + + void setData(const QVector &vecData) + { + clear(); + insertRows(vecData); + } + + /* + * Emits Qt's signal dataChanged for the whole model data + */ + void update() + { + if (!m_vecData.isEmpty()) + emit dataChanged(index(0, 0), index(m_vecData.size() - 1, columnCount() - 1)); + } + + T getRowData(int row) const + { + if (row < 0 || row >= m_vecData.size()) + return T(); + return m_vecData.at(row); + } + + bool setRowData(int row, const T &data) + { + if (row < 0 || row >= m_vecData.size()) + return false; + + m_vecData[row] = data; + emit dataChanged(index(row, 0), index(row, columnCount() - 1)); + return true; + } + + QModelIndex findIndexForId(int id, int column = 0) const + { + const int row = findRowForId(id); + if (row < 0) + return QModelIndex(); + return index(row, column); + } + + int getId(const QModelIndex &mi) const + { + if (!indexIsValid(mi)) + return -1; + return getIdInternal(m_vecData.at(mi.row())); + } + +protected: + template + class HasId + { + template + static std::true_type testSignature(const int &(CLS::*)() const); + template + static std::true_type testSignature(int (CLS::*)() const); + + template + static decltype(testSignature(&CLS::id)) test(std::nullptr_t); + + template + static std::false_type test(...); + public: - LtsAbstractTableModel(const QVector& header, QObject* parent) - : QAbstractTableModel(parent), m_vecColumns(header) + using type = decltype(test(nullptr)); + static const bool value = type::value; + }; + + // enable getId() if there is a function F::id + template ::value, int>::type = 0> + int getIdInternal(const F &data) const + { + return data.id(); + } + // fallback, should assert since it does not return a valid value + // static_assert is not possible since virtual void onDataChanged() is instantiated (due to virtual) + virtual int getId(const T &data) const + { + Q_ASSERT(false); + Q_UNUSED(data); + return -1; + } + + template < typename F = T, typename std::enable_if < !HasId::value, int>::type = 0> + int getIdInternal(const F &data) const + { + return getId(data); + } + + template + class HasIsDeleted + { + template + static std::true_type testSignature(const bool &(CLS::*)() const); + template + static std::true_type testSignature(bool (CLS::*)() const); + + template + static decltype(testSignature(&CLS::isDeleted)) test(std::nullptr_t); + + template + static std::false_type test(...); + + public: + using type = decltype(test(nullptr)); + static const bool value = type::value; + }; + // if data.isDeleted() is available - return it's value + template ::value, int>::type = 0> + bool isDeletedInternal(const F &data) const + { + return data.isDeleted(); + } + // fallback + virtual int isDeleted(const T &data) const + { + Q_UNUSED(data); + return false; + } + template < typename F = T, typename std::enable_if < !HasIsDeleted::value, int>::type = 0> + bool isDeletedInternal(const F &data) const + { + return isDeleted(data); + } + + // virtual to allow overriding this function for special cases + virtual bool isFiltered(const T &data, DataModification modType) const + { + Q_UNUSED(data); + Q_UNUSED(modType); + return false; + } + + // virtual to allow overriding this function for special cases + virtual bool onDataChanged(const T &data, DataModification modType) + { + if (isFiltered(data, modType)) + return false; + + const int id = getIdInternal(data); + const int row = findRowForId(id); + + // isDeletedInternal -> T::isDeleted() == true + if (modType == DataModification::eRemoved || isDeletedInternal(data)) { + if (row >= 0) + return removeRow(row); + return false; } - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override - { - if (role == Qt::DisplayRole && orientation == Qt::Horizontal && section >= 0 && section < m_vecColumns.size()) - return m_vecColumns[section]; + if (modType == DataModification::eAdded && row < 0) + return insertRow(data); - return QAbstractTableModel::headerData(section, orientation, role); + return setRowData(row, data); + } + + int findRowForId(int id) const + { + for (int i = 0; i < m_vecData.size(); ++i) + { + if (getIdInternal(m_vecData.at(i)) == id) + return i; } + return -1; + } - bool isEmpty(const QModelIndex& parent = QModelIndex()) - { - return parent.isValid() ? true : m_vecData.isEmpty(); - } - - int rowCount(const QModelIndex& parent = QModelIndex()) const override - { - return parent.isValid() ? 0 : m_vecData.size(); - } - - int columnCount(const QModelIndex& parent = QModelIndex()) const override - { - return parent.isValid() ? 0 : m_vecColumns.size(); - } - - void clear() - { - beginResetModel(); - m_vecData.clear(); - endResetModel(); - } - - bool indexIsValid(const QModelIndex& idx) const - { - if (!idx.isValid()) - return false; - if (idx.row() < 0 || idx.row() >= m_vecData.size()) - return false; - return true; - } - - virtual bool removeRow(int row) - { - return removeRows(row, 1); - } - - bool removeRows(int row, int count, const QModelIndex& parent = QModelIndex()) override - { - if (parent.isValid()) - return false; - - if (row < 0 || row >= m_vecData.size()) - return false; - - qsizetype range = std::min(row + count, m_vecData.size()); - - beginRemoveRows(QModelIndex(), row, range - 1); - m_vecData.erase(m_vecData.begin() + row, m_vecData.begin() + range); - endRemoveRows(); - - return true; - } - - virtual bool insertRow(const T& item) - { - if (isFiltered(item, DataModification::eAdded) || isDeletedInternal(item)) - return false; - beginInsertRows(QModelIndex(), m_vecData.size(), m_vecData.size()); - m_vecData.append(item); - endInsertRows(); - return true; - } - - template void insertRows(const CONT& items) - { - if (items.isEmpty()) - return; - const int cntBefore = m_vecData.size(); - for (const auto& item : items) - { - if (isFiltered(item, DataModification::eAdded) || isDeletedInternal(item)) - continue; - m_vecData += item; - } - const int cntAfter = m_vecData.size(); - if (cntBefore == cntAfter) - return; - beginInsertRows(QModelIndex(), cntBefore, cntAfter - 1); - endInsertRows(); - } - - void setData(const QVector& vecData) - { - clear(); - insertRows(vecData); - } - - void update() - { - if (!m_vecData.isEmpty()) - emit dataChanged(index(0, 0), index(m_vecData.size() - 1, columnCount() - 1)); - } - - T getRowData(int row) const - { - if (row < 0 || row >= m_vecData.size()) - return T(); - return m_vecData.at(row); - } - - bool setRowData(int row, const T& data) - { - if (row < 0 || row >= m_vecData.size()) - return false; - - m_vecData[row] = data; - emit dataChanged(index(row, 0), index(row, columnCount() - 1)); - return true; - } - - QModelIndex findIndexForId(int id, int column = 0) const - { - const int row = findRowForId(id); - if (row < 0) - return QModelIndex(); - return index(row, column); - } - - int getId(const QModelIndex& mi) const - { - if (!indexIsValid(mi)) - return -1; - return getIdInternal(m_vecData.at(mi.row())); - } - - protected: - template class HasId - { - template static std::true_type testSignature(const int& (CLS::*)() const); - template static std::true_type testSignature(int (CLS::*)() const); - - template static decltype(testSignature(&CLS::id)) test(std::nullptr_t); - - template static std::false_type test(...); - - public: - using type = decltype(test(nullptr)); - static const bool value = type::value; - }; - - template ::value, int>::type = 0> - int getIdInternal(const F& data) const - { - return data.id(); - } - - virtual int getId(const T& data) const - { - Q_ASSERT(false); - Q_UNUSED(data); - return -1; - } - - template ::value, int>::type = 0> - int getIdInternal(const F& data) const - { - return getId(data); - } - - template class HasIsDeleted - { - template static std::true_type testSignature(const bool& (CLS::*)() const); - template static std::true_type testSignature(bool (CLS::*)() const); - - template static decltype(testSignature(&CLS::isDeleted)) test(std::nullptr_t); - - template static std::false_type test(...); - - public: - using type = decltype(test(nullptr)); - static const bool value = type::value; - }; - - template ::value, int>::type = 0> - bool isDeletedInternal(const F& data) const - { - return data.isDeleted(); - } - - virtual int isDeleted(const T& data) const - { - Q_UNUSED(data); - return false; - } - - template ::value, int>::type = 0> - bool isDeletedInternal(const F& data) const - { - return isDeleted(data); - } - - virtual bool isFiltered(const T& data, DataModification modType) const - { - Q_UNUSED(data); - Q_UNUSED(modType); - return false; - } - - virtual bool onDataChanged(const T& data, DataModification modType) - { - if (isFiltered(data, modType)) - return false; - - const int id = getIdInternal(data); - const int row = findRowForId(id); - - if (modType == DataModification::eRemoved || isDeletedInternal(data)) - { - if (row >= 0) - return removeRow(row); - return false; - } - - if (modType == DataModification::eAdded && row < 0) - return insertRow(data); - - return setRowData(row, data); - } - - int findRowForId(int id) const - { - for (int i = 0; i < m_vecData.size(); ++i) - { - if (getIdInternal(m_vecData.at(i)) == id) - return i; - } - return -1; - } - - QVector m_vecData; - QVector m_vecColumns; + QVector m_vecData; + QVector m_vecColumns; }; -} // namespace LtsWidgets +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_angle_edit.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_angle_edit.cpp index dc627a2ed..fbc99b838 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_angle_edit.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_angle_edit.cpp @@ -1,233 +1,281 @@ - +/** + * LtsAngleEdit + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Steve Kemayou, ESZS, 2024-10-16 + */ #include "lts_angle_edit.h" - #include "ui_lts_angle_edit.h" #include -#include + namespace LtsWidgets { - -inline constexpr double pi() -{ - return M_PI; -} - -inline constexpr double deg2rad() -{ - return pi() / 180.; -} - -inline constexpr double rad2deg() -{ - return 1. / deg2rad(); -} +// some helper functions +inline constexpr double pi() { return M_PI; } +inline constexpr double deg2rad() { return pi() / 180.; } +inline constexpr double rad2deg() { return 1. / deg2rad(); } constexpr int maxAngleDeg = 360; constexpr int maxAngleMil = 6400; -constexpr std::tuple c_limDeg(0, maxAngleDeg, 0, 10); -constexpr std::tuple c_limMil(0, maxAngleMil, 0, 50); -constexpr std::tuple c_limRad(-99999, 99999, 3, 1); +constexpr std::tuple c_limDeg (0, maxAngleDeg,0, 10); // angleMinVal, angleMaxVal, decimal place, spinboxStep +constexpr std::tuple c_limMil(0, maxAngleMil,0, 50); +constexpr std::tuple c_limRad(-99999, 99999, 3, 1); -inline constexpr double mil2Deg(const double& mil) +inline constexpr double mil2Deg(const double &mil) { - return maxAngleDeg * mil / maxAngleMil; + return maxAngleDeg * mil / maxAngleMil; +} +inline constexpr double deg2Mil(const double &angleDeg) +{ + return maxAngleMil * angleDeg / maxAngleDeg; +} +inline constexpr double deg2Rad(const double &angleDeg) +{ + return angleDeg * deg2rad(); +} +inline constexpr double rad2Degree(const double &angleRad) +{ + return angleRad * 180/pi(); +} +inline constexpr double mil2Rad(const double &mil) +{ + return deg2Rad(mil2Deg(mil)); +} +inline constexpr double rad2Mil(const double &angleRad) +{ + return deg2Mil(rad2Degree(angleRad)); } -inline constexpr double deg2Mil(const double& angleDeg) +/*! + * \brief LtsAngleEdit::LtsAngleEdit + * \param parent + */ +LtsAngleEdit::LtsAngleEdit(QWidget *parent) : + QWidget(parent), + m_ui(new Ui_LtsAngleEdit) { - return maxAngleMil * angleDeg / maxAngleDeg; -} + m_ui->setupUi(this); -inline constexpr double deg2Rad(const double& angleDeg) -{ - return angleDeg * deg2rad(); -} - -inline constexpr double rad2Degree(const double& angleRad) -{ - return angleRad * 180 / pi(); -} - -inline constexpr double mil2Rad(const double& mil) -{ - return deg2Rad(mil2Deg(mil)); -} - -inline constexpr double rad2Mil(const double& angleRad) -{ - return deg2Mil(rad2Degree(angleRad)); -} - -LtsAngleEdit::LtsAngleEdit(QWidget* parent) : QWidget(parent), m_ui(new Ui_LtsAngleEdit) -{ - m_ui->setupUi(this); } LtsAngleEdit::~LtsAngleEdit() { - delete m_ui; + delete m_ui; } +/*! + * \brief LtsAngleEdit::initAngleEditWidget + */ void LtsAngleEdit::initAngleEditWidget(const unsigned int sboxCount) { + // set Limits + m_dboxLimitMap.insert(AngleUnitType::Deg, c_limDeg); + m_dboxLimitMap.insert(AngleUnitType::Mil, c_limMil); + m_dboxLimitMap.insert(AngleUnitType::Rad, c_limRad); + m_hiddenUnits.clear(); + m_hiddenUnits.insert((int)AngleUnitType::Rad); // default hid rad unit - m_dboxLimitMap.insert(AngleUnitType::Deg, c_limDeg); - m_dboxLimitMap.insert(AngleUnitType::Mil, c_limMil); - m_dboxLimitMap.insert(AngleUnitType::Rad, c_limRad); - m_hiddenUnits.clear(); - m_hiddenUnits.insert((int)AngleUnitType::Rad); + // add new dboxes + for(unsigned int i=0; i spinbox = QSharedPointer(new QDoubleSpinBox(this) ); + spinbox->setValue(0); + spinbox->setAlignment(Qt::AlignRight); + spinbox->setMinimumWidth(91); + // set object name + spinbox.data()->setObjectName(spinBoxName+QString::number(m_sBoxMap.count())); + m_ui->hLayoutSpinbox->addWidget(spinbox.data(), 0); + m_sBoxMap.insert(m_sBoxMap.count(), spinbox); + } + m_ui->hLayoutSpinbox->setContentsMargins(1,1,1,1); - for (unsigned int i = 0; i < sboxCount; ++i) - { - QSharedPointer spinbox = QSharedPointer(new QDoubleSpinBox(this)); - spinbox->setValue(0); - spinbox->setAlignment(Qt::AlignRight); - spinbox->setMinimumWidth(91); - spinbox.data()->setObjectName(spinBoxName + QString::number(m_sBoxMap.count())); - m_ui->hLayoutSpinbox->addWidget(spinbox.data(), 0); - m_sBoxMap.insert(m_sBoxMap.count(), spinbox); - } - m_ui->hLayoutSpinbox->setContentsMargins(1, 1, 1, 1); + // set combobox units + connect(m_ui->cBoxAngleUnit, qOverload(&QComboBox::currentIndexChanged), + this, &LtsAngleEdit::onCBoxAngleUnitChanged); - connect(m_ui->cBoxAngleUnit, qOverload(&QComboBox::currentIndexChanged), this, - &LtsAngleEdit::onCBoxAngleUnitChanged); - - setCboxUnit(); + setCboxUnit(); + // set default unit } +/*! + * \brief LtsAngleEdit::setValue + * \param value + * \param dboxIndex + */ void LtsAngleEdit::setValue(const double value, unsigned int dboxIndex) { - if ((int)dboxIndex > m_sBoxMap.count()) - return; - auto spinbox = m_sBoxMap.value(dboxIndex); - spinbox->setValue(value); + if ((int)dboxIndex > m_sBoxMap.count()) + return; + auto spinbox = m_sBoxMap.value(dboxIndex); + spinbox->setValue(value); } +/*! + * \brief LtsAngleEdit::setValue + * \param value + * \param valueUnit + * \param dboxIndex + */ void LtsAngleEdit::setValue(const double value, AngleUnitType valueUnit, unsigned int dboxIndex) { - setValue(getAngleConverted(value, getAngleCurrentUnit(), valueUnit), dboxIndex); + setValue(getAngleConverted(value, getAngleCurrentUnit(), valueUnit),dboxIndex); } -void LtsAngleEdit::hideUnits(const QVector& list) +void LtsAngleEdit::hideUnits(const QVector &list) { - for (auto u : list) - m_hiddenUnits.insert((int)u); - setCboxUnit(); + for(auto u : list) + m_hiddenUnits.insert((int)u); + setCboxUnit(); } -void LtsAngleEdit::showUnits(const QVector& list) +void LtsAngleEdit::showUnits(const QVector &list) { - for (const auto& u : list) - m_hiddenUnits.remove((int)u); - setCboxUnit(); + for (const auto &u : list) + m_hiddenUnits.remove((int)u); + setCboxUnit(); } +/*! + * \brief LtsAngleEdit::setCboxUnit + */ void LtsAngleEdit::setCboxUnit() { - m_ui->cBoxAngleUnit->clear(); - const std::vector allUnits = {AngleUnitType::Deg, AngleUnitType::Mil, AngleUnitType::Rad}; - for (const auto& u : allUnits) - { - if (m_hiddenUnits.contains((int)u)) - continue; - m_ui->cBoxAngleUnit->insertItem(static_cast(u), toString(u), static_cast(u)); - } + m_ui->cBoxAngleUnit->clear(); + const std::vector allUnits = {AngleUnitType::Deg, AngleUnitType::Mil, AngleUnitType::Rad}; + for(const auto &u : allUnits) + { + if (m_hiddenUnits.contains((int)u)) + continue; + m_ui->cBoxAngleUnit->insertItem(static_cast(u), toString(u),static_cast(u)); + } - setAngleUnit(AngleUnitType::Deg); + setAngleUnit(AngleUnitType::Deg); } +/*! + * \brief LtsAngleEdit::setValue + * \param value + * \param valueUnit + */ void LtsAngleEdit::setValue(const double value, AngleUnitType valueUnit) { - - setValue(getAngleConverted(value, getAngleCurrentUnit(), valueUnit), 0); + // get current unit of given angle and convert it to current defined in combobox unit + setValue(getAngleConverted(value, getAngleCurrentUnit(), valueUnit),0); } -void LtsAngleEdit::setAngleUnit(const AngleUnitType& type) +/*! + * \brief LtsAngleEdit::setAngleUnit + * \param type + */ +void LtsAngleEdit::setAngleUnit(const AngleUnitType &type) { - m_ui->cBoxAngleUnit->setCurrentIndex(static_cast(type)); + m_ui->cBoxAngleUnit->setCurrentIndex(static_cast(type)); } +/*! + * \brief LtsAngleEdit::getCurrentAngleUnit + * \return + */ LtsAngleEdit::AngleUnitType LtsAngleEdit::getAngleCurrentUnit() const { - return static_cast(m_ui->cBoxAngleUnit->currentIndex()); + return static_cast(m_ui->cBoxAngleUnit->currentIndex()); } +/*! + * \brief LtsAngleEdit::getAngleValue + * \param dboxIndex default index value is 0; also when more than one dbox is created + * \return + */ double LtsAngleEdit::getAngle(unsigned int sboxIndex) const { - if ((int)sboxIndex > m_sBoxMap.count()) - return 0; - auto spinbox = m_sBoxMap.value(sboxIndex); - return spinbox->value(); + if ((int)sboxIndex > m_sBoxMap.count()) + return 0; + auto spinbox = m_sBoxMap.value(sboxIndex); + return spinbox->value(); } +/*! + * \brief LtsAngleEdit::toString + * \param t + * \return + */ QString LtsAngleEdit::toString(LtsAngleEdit::AngleUnitType t) { - switch (t) - { - case AngleUnitType::Deg: - return tr("Degree"); - case AngleUnitType::Mil: - return tr("Mil"); - case AngleUnitType::Rad: - return tr("Radian"); - default: - return tr(""); - } + switch(t) + { + case AngleUnitType::Deg: + return tr("Degree"); + case AngleUnitType::Mil: + return tr("Mil"); + case AngleUnitType::Rad: + return tr("Radian"); + default: return tr(""); + } + return tr(""); } void LtsAngleEdit::onCBoxAngleUnitChanged() { - AngleUnitType newUnit = static_cast(m_ui->cBoxAngleUnit->currentData().toInt()); - for (auto dbox : std::as_const(m_sBoxMap)) - { - const double value = getAngleConverted(dbox->value(), newUnit, m_currAngleUnit); - auto mapVal = m_dboxLimitMap.value(newUnit); - dbox->setMinimum(std::get(mapVal)); - dbox->setMaximum(std::get(mapVal)); - dbox->setDecimals(std::get(mapVal)); - dbox->setSingleStep(std::get(mapVal)); - dbox->setValue(value); - } - m_currAngleUnit = newUnit; + AngleUnitType newUnit = static_cast(m_ui->cBoxAngleUnit->currentData().toInt()); + for(auto dbox : qAsConst(m_sBoxMap)) + { + const double value = getAngleConverted(dbox->value(), newUnit, m_currAngleUnit); + auto mapVal = m_dboxLimitMap.value(newUnit); + dbox->setMinimum(std::get(mapVal)); + dbox->setMaximum(std::get(mapVal)); + dbox->setDecimals(std::get(mapVal)); + dbox->setSingleStep(std::get(mapVal)); + dbox->setValue(value); + } + m_currAngleUnit = newUnit; } -double LtsAngleEdit::getAngleConverted(const double angle, LtsAngleEdit::AngleUnitType newAngleUnit, - LtsAngleEdit::AngleUnitType oldAngleUnit) +/*! + * \brief LtsAngleEdit::convertAngleValue + * \param angle + * \param newAngleUnit + * \param oldAngleUnit + * \return + */ +double LtsAngleEdit::getAngleConverted(const double angle, LtsAngleEdit::AngleUnitType newAngleUnit, LtsAngleEdit::AngleUnitType oldAngleUnit) { - double convertedAngle = angle; - if (oldAngleUnit == AngleUnitType::Deg && newAngleUnit == AngleUnitType::Mil) - convertedAngle = deg2Mil(angle); - else if (oldAngleUnit == AngleUnitType::Deg && newAngleUnit == AngleUnitType::Rad) - convertedAngle = deg2Rad(angle); - else if (oldAngleUnit == AngleUnitType::Mil && newAngleUnit == AngleUnitType::Deg) - convertedAngle = mil2Deg(angle); - else if (oldAngleUnit == AngleUnitType::Mil && newAngleUnit == AngleUnitType::Rad) - convertedAngle = mil2Rad(angle); - else if (oldAngleUnit == AngleUnitType::Rad && newAngleUnit == AngleUnitType::Deg) - convertedAngle = rad2Degree(angle); - else if (oldAngleUnit == AngleUnitType::Rad && newAngleUnit == AngleUnitType::Mil) - convertedAngle = rad2Mil(angle); + double convertedAngle = angle; + if (oldAngleUnit == AngleUnitType::Deg && newAngleUnit == AngleUnitType::Mil ) + convertedAngle = deg2Mil(angle); + else if (oldAngleUnit == AngleUnitType::Deg && newAngleUnit == AngleUnitType::Rad ) + convertedAngle = deg2Rad(angle); + else if (oldAngleUnit == AngleUnitType::Mil && newAngleUnit == AngleUnitType::Deg ) + convertedAngle = mil2Deg(angle); + else if (oldAngleUnit == AngleUnitType::Mil && newAngleUnit == AngleUnitType::Rad ) + convertedAngle = mil2Rad(angle); + else if (oldAngleUnit == AngleUnitType::Rad && newAngleUnit == AngleUnitType::Deg ) + convertedAngle = rad2Degree(angle); + else if (oldAngleUnit == AngleUnitType::Rad && newAngleUnit == AngleUnitType::Mil ) + convertedAngle = rad2Mil(angle); - return convertedAngle; + return convertedAngle; } void LtsAngleEdit::setEnable(int sbIndex, bool enabled) { - if ((int)sbIndex > m_sBoxMap.count()) - return; - m_sBoxMap.value(sbIndex)->setEnabled(enabled); + if ((int)sbIndex > m_sBoxMap.count()) + return; + m_sBoxMap.value(sbIndex)->setEnabled(enabled); } void LtsAngleEdit::showSpinbox(int sbIndex, bool visible) { - if ((int)sbIndex > m_sBoxMap.count()) - return; - m_sBoxMap.value(sbIndex)->setVisible(visible); + if ((int)sbIndex > m_sBoxMap.count()) + return; + m_sBoxMap.value(sbIndex)->setVisible(visible); } -} // namespace LtsWidgets +}// namespace LtsAngleEdit + diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_angle_edit.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_angle_edit.h index 4379a959c..9a745bf44 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_angle_edit.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_angle_edit.h @@ -1,61 +1,77 @@ - +/** + * LtsAngleEdit + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Steve Kemayou, ESZS, 2024-10-16 + */ #pragma once -#include "lts_widgets_export.h" -#include -#include -#include #include +#include +#include +#include + class Ui_LtsAngleEdit; - namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsAngleEdit : public QWidget { - Q_OBJECT + Q_OBJECT - public: - explicit LtsAngleEdit(QWidget* parent = nullptr); - ~LtsAngleEdit(); +public: + explicit LtsAngleEdit(QWidget *parent = nullptr); + ~LtsAngleEdit(); - enum class AngleUnitType : unsigned int { Deg = 0, Mil = 1, Rad = 2 }; - Q_ENUM(AngleUnitType) + enum class AngleUnitType : unsigned int + { + Deg = 0, + Mil = 1, + Rad = 2 + }; + Q_ENUM(AngleUnitType) - enum LimTuple : int { AngleMin, AngleMax, DecimalPlace, SingleStep }; + enum LimTuple : int + { + AngleMin, + AngleMax, + DecimalPlace, + SingleStep + }; - const QString spinBoxName = QStringLiteral("sboxAngleValue"); - QString toString(AngleUnitType t); - void setAngleUnit(const AngleUnitType& type); - void setValue(const double value, unsigned int dboxIndex = 0); - void setValue(const double value, AngleUnitType valueUnit); - void setValue(const double value, AngleUnitType valueUnit, unsigned int dboxIndex); + const QString spinBoxName = QStringLiteral("sboxAngleValue"); + QString toString(AngleUnitType t); + void setAngleUnit(const AngleUnitType &type); + void setValue(const double value, unsigned int dboxIndex=0); /// set value of spinbox with index. index start from 0. Counting from Left to right. + void setValue(const double value, AngleUnitType valueUnit); /// set value with current unit of given angle and convert it to current defined unit in combobox unit + void setValue(const double value, AngleUnitType valueUnit, unsigned int dboxIndex); - void hideUnits(const QVector& list); - void showUnits(const QVector& list); - LtsAngleEdit::AngleUnitType getAngleCurrentUnit() const; - void initAngleEditWidget(const unsigned int sboxCount); - double getAngle(unsigned int sboxIndex = 0) const; - double getAngleConverted(const double angle, LtsAngleEdit::AngleUnitType newAngleUnit, - LtsAngleEdit::AngleUnitType oldAngleUnit); + void hideUnits(const QVector &list); /// list of units that will not be displayed in cbox + void showUnits(const QVector &list); /// list of units to be displayed in cbox + LtsAngleEdit::AngleUnitType getAngleCurrentUnit() const; /// get cbox current unit + void initAngleEditWidget(const unsigned int sboxCount); /// this method initialize the angle edit widget. sboxCount give number of spinbox to be created + double getAngle(unsigned int sboxIndex = 0) const; /// sboxIndex default index value is 0; also when more than one dbox is created + double getAngleConverted(const double angle, LtsAngleEdit::AngleUnitType newAngleUnit, LtsAngleEdit::AngleUnitType oldAngleUnit); - void setEnable(int sbIndex, bool enabled); - void showSpinbox(int sbIndex, bool visible); + void setEnable(int sbIndex, bool enabled); /// set spinbox at index enabled or disabled + void showSpinbox(int sbIndex, bool visible); /// show spinBox of specific index. Indexes start from 0. - protected: - void setCboxUnit(); +protected: + void setCboxUnit(); /// fill combobox with units - private Q_SLOTS: - void onCBoxAngleUnitChanged(); - - private: - Ui_LtsAngleEdit* m_ui; - QMap> m_sBoxMap; - QMap> m_dboxLimitMap; - AngleUnitType m_currAngleUnit; - QSet m_hiddenUnits; +private Q_SLOTS: + void onCBoxAngleUnitChanged(); +private: + Ui_LtsAngleEdit *m_ui; + QMap> m_sBoxMap; /// Map + QMap> m_dboxLimitMap; /// minAngle, maxAngle, decimal place, single step + AngleUnitType m_currAngleUnit; + QSet m_hiddenUnits; }; -} // namespace LtsWidgets +}//namespace LtsAngleEdit + diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_background_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_background_widget.cpp index 748fd5c61..d77d5d897 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_background_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_background_widget.cpp @@ -1,122 +1,142 @@ - +/** + * @RDE_HEADER@ + * Background Widget that covers a monitor with the project image + * $Id$ + * $HeadURL$ + * $Author$ + * Created by Mike Wille, SLSE, 2016-05-05 + */ #include "lts_background_widget.h" -#include -#include #include #include +#include #ifdef Q_OS_WIN #include #endif + namespace LtsWidgets { -LtsBackgroundWidget::LtsBackgroundWidget(QWidget* parent) : QDialog(parent), m_isUltraWide(false) +LtsBackgroundWidget::LtsBackgroundWidget(QWidget *parent) + : QDialog(parent) + , m_isUltraWide(false) { - setMouseTracking(true); - setWindowFlags(windowFlags() | Qt::FramelessWindowHint); - setWindowTitle(QStringLiteral("Splash")); + setMouseTracking(true); // register mouse movement + setWindowFlags(windowFlags() | Qt::FramelessWindowHint /*| Qt::WindowStaysOnBottomHint*/); + setWindowTitle(QStringLiteral("Splash")); - setBackground(); + setBackground(); } + void LtsBackgroundWidget::setBackground() { - static const auto backgroundFiles = { - QStringLiteral(":/project/background.png"), - QStringLiteral(":/project/background.jpg"), - }; - static const auto backgroundFilesWide = { - QStringLiteral(":/project/background_wide.png"), - QStringLiteral(":/project/background_wide.jpg"), - }; - - m_pixmap = QPixmap(); - for (const QString& f : m_isUltraWide ? backgroundFilesWide : backgroundFiles) - { - if (!QFile::exists(f)) - continue; - m_pixmap = QPixmap(f); - if (m_pixmap.isNull()) - continue; - break; - } + static const auto backgroundFiles = + { + QStringLiteral(":/project/background.png"), + QStringLiteral(":/project/background.jpg"), + }; + static const auto backgroundFilesWide = + { + QStringLiteral(":/project/background_wide.png"), + QStringLiteral(":/project/background_wide.jpg"), + }; + m_pixmap = QPixmap(); + for (const QString &f : m_isUltraWide ? backgroundFilesWide : backgroundFiles) + { + if (!QFile::exists(f)) + continue; + m_pixmap = QPixmap(f); if (m_pixmap.isNull()) + continue; + break; + } + + if (m_pixmap.isNull()) + { + if (m_isUltraWide) { - if (m_isUltraWide) - { - m_isUltraWide = false; - setBackground(); - } - else - { - qWarning() << "BackgroundWidget::c_tor: file missing or is not a valid image ':/project/background.png'"; - } + m_isUltraWide = false; + setBackground(); } + else + { + qWarning() << "BackgroundWidget::c_tor: file missing or is not a valid image ':/project/background.png'"; + } + } } + void LtsBackgroundWidget::setUltraWide(bool set) { - if (set == m_isUltraWide) - return; + if (set == m_isUltraWide) // do not set / unset ultra wide if it's already set to specified state + return; - m_isUltraWide = set; - setBackground(); - update(); + m_isUltraWide = set; + setBackground(); + update(); // force redraw on next event loop } -void LtsBackgroundWidget::resizeEvent(QResizeEvent* e) + +void LtsBackgroundWidget::resizeEvent(QResizeEvent *e) { - setUltraWide(width() > 3000); - QDialog::resizeEvent(e); + setUltraWide(width() > 3000); + QDialog::resizeEvent(e); } -void LtsBackgroundWidget::paintEvent(QPaintEvent* e) + +void LtsBackgroundWidget::paintEvent(QPaintEvent *e) { - if (!m_pixmap.isNull()) - { - QPainter painter(this); - painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); - painter.drawPixmap(0, 0, width(), height(), m_pixmap); - } - QDialog::paintEvent(e); + if (!m_pixmap.isNull()) + { + QPainter painter(this); + painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); + painter.drawPixmap(0, 0, width(), height(), m_pixmap); // draw project background on login splash + } + QDialog::paintEvent(e); } -bool LtsBackgroundWidget::event(QEvent* e) + +bool LtsBackgroundWidget::event(QEvent *e) { - if (e->type() == QEvent::KeyPress || e->type() == QEvent::MouseButtonPress || - e->type() == QEvent::MouseButtonRelease || e->type() == QEvent::MouseMove) - { + if (e->type() == QEvent::KeyPress || // respect typing into textfields + e->type() == QEvent::MouseButtonPress || + e->type() == QEvent::MouseButtonRelease || + e->type() == QEvent::MouseMove) + { + //qWarning() << "BGW operator action!"; + emit signalOperatorAction(); + e->ignore(); + return true; + } - emit signalOperatorAction(); - e->ignore(); - return true; - } - - return QDialog::event(e); + return QDialog::event(e); } + void LtsBackgroundWidget::showFullScreen() { - + //qWarning() << "show fullscreen !"; #ifdef Q_OS_WIN - winId(); - QWindowsWindowFunctions::setHasBorderInFullScreen(windowHandle(), true); + winId(); // make sure windowHandle() is not a nullptr + QWindowsWindowFunctions::setHasBorderInFullScreen(windowHandle(), true); #endif - QDialog::showFullScreen(); - raise(); + QDialog::showFullScreen(); + raise(); // as this is a widget for the background, it has to be raised, but only once at startup } -void LtsBackgroundWidget::closeEvent(QCloseEvent* e) + +void LtsBackgroundWidget::closeEvent(QCloseEvent *e) { #ifdef DEVEL - deleteLater(); + deleteLater(); #else - e->ignore(); + e->ignore(); #endif } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_background_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_background_widget.h index a41d2c82e..cb078126f 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_background_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_background_widget.h @@ -1,10 +1,18 @@ - +/** + * @RDE_HEADER@ + * Background Widget that covers a monitor with the project image + * $Id$ + * $HeadURL$ + * $Author$ + * Created by Mike Wille, SLSE, 2016-05-05 + */ #pragma once + #include "lts_widgets_export.h" #include -#include + class QPixmap; class QEvent; @@ -12,34 +20,41 @@ class QEvent; namespace LtsWidgets { +/** + * @brief The LtsBackgroundWidget class creates a fullscreen Widget that covers a monitor with the project image (used for payloads in opApp) + */ class LTSWIDGETS_EXPORT LtsBackgroundWidget : public QDialog { - Q_OBJECT + Q_OBJECT - public: - explicit LtsBackgroundWidget(QWidget* parent = nullptr); +public: + explicit LtsBackgroundWidget(QWidget *parent = nullptr); - protected: - void paintEvent(QPaintEvent* e) override; - void closeEvent(QCloseEvent* e) override; - void resizeEvent(QResizeEvent* e) override; - bool event(QEvent* e) override; +protected: + void paintEvent(QPaintEvent *e) override; + void closeEvent(QCloseEvent *e) override; + void resizeEvent(QResizeEvent *e) override; + bool event(QEvent *e) override; - private: - void setBackground(); - void setUltraWide(bool set = true); +private: + void setBackground(); + void setUltraWide(bool set = true); - signals: +signals: + /** + * @brief signalOperatorAction is emitted when the operator moves/clickes the cursor or enters some letters - for example, show window again after it's hidden (screen saver effect) + */ + void signalOperatorAction(); - void signalOperatorAction(); +public slots: + /** + * @brief showFullScreen shows the widget and raises it. Otherwise the widget would be far in the background (and wihtout a show not shown) + */ + void showFullScreen(); +private: + QPixmap m_pixmap; + bool m_isUltraWide; - public slots: - - void showFullScreen(); - - private: - QPixmap m_pixmap; - bool m_isUltraWide; }; -} // namespace LtsWidgets +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_base.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_base.h index 74b2602ce..962902230 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_base.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_base.h @@ -1,228 +1,277 @@ - +/** +* @RDE_HEADER@ +* Enumerations for ltsbase +* $Id$ +* $HeadURL$ +* $Author$ +*/ #pragma once #include "lts_widgets_export.h" -#include -#include +#include + +#include +#include #include #include #include -#include +#include + #include + namespace LtsWidgets { class LtsDialog; inline QString readableDuration(qint64 msecs, bool foldDays = true) { - if (msecs == 0) - return QObject::tr("---"); + if (msecs == 0) + return QObject::tr("---"); - if (msecs % 1000 != 0 && msecs < 1000 * 60) - return QObject::tr("%1 seconds").arg(QLocale().toString(msecs / 1000.0, 'f', 3)); + // If there's a subsecond value it's less than a minute, then show decimals, Otherwise ignore. + if (msecs % 1000 != 0 && msecs < 1000 * 60) + return QObject::tr("%1 seconds").arg(QLocale().toString(msecs / 1000.0, 'f', 3)); - qint64 secs = msecs / 1000; - qint64 mins = secs / 60; - qint64 hours = mins / 60; - qint64 days = hours / 24; + qint64 secs = msecs / 1000; + qint64 mins = secs / 60; + qint64 hours = mins / 60; + qint64 days = hours / 24; - if (foldDays) - days = 0; - else - hours = hours % 24; + if (foldDays) + days = 0; + else + hours = hours % 24; - mins = mins % 60; - secs = secs % 60; + mins = mins % 60; + secs = secs % 60; - if (!secs && !mins && !hours) - return QObject::tr("%n day(s)", "", days); - if (!secs && !mins && !days) - return QObject::tr("%n hour(s)", "", hours); - if (!secs && !hours && !days) - return QObject::tr("%n minute(s)", "", mins); - if (!mins && !hours && !days) - return QObject::tr("%n second(s)", "", secs); + // If only one is not equal 0, return long readable text: + if (!secs && !mins && !hours) + return QObject::tr("%n day(s)", "", days); + if (!secs && !mins && !days) + return QObject::tr("%n hour(s)", "", hours); + if (!secs && !hours && !days) + return QObject::tr("%n minute(s)", "", mins); + if (!mins && !hours && !days) + return QObject::tr("%n second(s)", "", secs); - QString strSecs = QObject::tr("%1s").arg(secs, 2, 10, QLatin1Char('0')); - QString strMins = QObject::tr("%1m").arg(mins, 2, 10, QLatin1Char('0')); - QString strHours = QObject::tr("%1h").arg(hours, 2, 10, QLatin1Char('0')); - QString strDays = QObject::tr("%1d").arg(days); + QString strSecs = QObject::tr("%1s").arg(secs, 2, 10, QLatin1Char('0')); + QString strMins = QObject::tr("%1m").arg(mins, 2, 10, QLatin1Char('0')); + QString strHours = QObject::tr("%1h").arg(hours, 2, 10, QLatin1Char('0')); + QString strDays = QObject::tr("%1d").arg(days); - QString retVal; - if (days) - retVal += strDays + QLatin1Char(' '); - if (days || hours) - retVal.append(strHours); - if (mins || hours || days) - retVal.append(strMins); - if (secs) - retVal.append(strSecs); + QString retVal; + if (days) + retVal += strDays + QLatin1Char(' '); + if (days || hours) + retVal.append(strHours); + if (mins || hours || days) + retVal.append(strMins); + if (secs) + retVal.append(strSecs); - return retVal; + return retVal; } -inline void addTouchScroll(QWidget* widget) +inline void addTouchScroll(QWidget *widget) { - if (!widget) - return; - widget->setAttribute(Qt::WA_AcceptTouchEvents); + if (!widget) + return; + widget->setAttribute(Qt::WA_AcceptTouchEvents); + { + QScrollArea *sca = qobject_cast(widget); + if (sca) { - QScrollArea* sca = qobject_cast(widget); - if (sca) - { - QScroller::grabGesture(sca->viewport(), QScroller::LeftMouseButtonGesture); - return; - } + QScroller::grabGesture(sca->viewport(), QScroller::LeftMouseButtonGesture); + return; } + } + { + QAbstractItemView *aiv = qobject_cast(widget); + if (aiv) { - QAbstractItemView* aiv = qobject_cast(widget); - if (aiv) - { - QScroller::grabGesture(aiv->viewport(), QScroller::LeftMouseButtonGesture); - aiv->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); - aiv->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); - return; - } + QScroller::grabGesture(aiv->viewport(), QScroller::LeftMouseButtonGesture); + aiv->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); + aiv->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); + return; } + } } -enum class ButtonSize { - eDefault = 40, - +enum class ButtonSize +{ + eDefault = 40, +// eTiny = 15, +// eExtraSmall = 20, +// eSmall = 30, +// eMedium = 48, +// eBig = 50, +// eGigantic = 70 }; -enum class ButtonStyle { eAll = 1, eTextOnly, eIconOnly, eTextNextToIcon }; -enum class LayoutArea { - eUnknown, - eInfoTab, - eDialogTab, - eSpecialTab, - eMainTab, +enum class ButtonStyle +{ + eAll = 1, + eTextOnly, + eIconOnly, + eTextNextToIcon }; -enum class ExercisePart { - ePlanning, - eExecution, - eAfterAction, - eSpecial, +enum class LayoutArea +{ + eUnknown, + eInfoTab, + eDialogTab, + eSpecialTab, + eMainTab, }; +enum class ExercisePart +{ + ePlanning, + eExecution, + eAfterAction, + eSpecial, +}; + +// Damit Q_DECLARE_OPERATORS_FOR_FLAGS funktioniert muss das Enum in einem namespace gekapselt sein namespace ExerciseState { -enum State { - - eUnknown = 0, - eCreated = 1 << 0, - eStarted = 1 << 1, - ePaused = 1 << 2, - eStopped = 1 << 4, + enum State + { + // the shift amount has to be the value of the Corresponding enum (EXM::ExerciseState) entry minus one + eUnknown = 0, + eCreated = 1 << 0, + eStarted = 1 << 1, + ePaused = 1 << 2, + eStopped = 1 << 4, eTerminated = 1 << 5, eAll = eCreated | eStarted | ePaused | eStopped | eTerminated -}; + }; -Q_DECLARE_OPERATORS_FOR_FLAGS(QFlags) -} // namespace ExerciseState + Q_DECLARE_OPERATORS_FOR_FLAGS(QFlags) +} +// convenience +typedef ExerciseState::State ExcState; +typedef QFlags ExerciseStates; -typedef ExerciseState::State ExcState; -typedef QFlags ExerciseStates; - -enum class CreateInstantType { - DontCreateInstant, - CreateInstantAndAddAction, - CreateInstantAndDiscardAction, +enum class CreateInstantType +{ + DontCreateInstant, + CreateInstantAndAddAction, + CreateInstantAndDiscardAction, }; struct PluginData { + // QWidget *createFunc(QWidget *parent); + using createWidgetFuncPtr = std::function; + using directFuncPtr = std::function; - using createWidgetFuncPtr = std::function; - using directFuncPtr = std::function; + createWidgetFuncPtr createWidgetFunc = nullptr; + directFuncPtr directFunc = nullptr; + QStringList iconPaths; + QIcon menuIcon; + QString tooltip; + qulonglong dropHandlerKey = 0; + QString menuText; + QString menuGroup; + LtsUtils::LtsTranslatableIdentifier translatableMenuGroup; + QString identifier; // uuid + bool closable = true; + LayoutArea layoutArea = LayoutArea::eDialogTab; + int operatorRight = 0; + CreateInstantType createInstant = CreateInstantType::DontCreateInstant; + bool visibleInMenu = true; // add to menu tab + ExercisePart exercisePart = ExercisePart::eSpecial; + ExerciseStates exerciseStates = ExerciseState::eAll; - createWidgetFuncPtr createWidgetFunc = nullptr; - directFuncPtr directFunc = nullptr; - QStringList iconPaths; - QIcon menuIcon; - QString tooltip; - qulonglong dropHandlerKey = 0; - QString menuText; - QString menuGroup; - LtsUtils::LtsTranslatableIdentifier translatableMenuGroup; - QString identifier; - bool closable = true; - LayoutArea layoutArea = LayoutArea::eDialogTab; - int operatorRight = 0; - CreateInstantType createInstant = CreateInstantType::DontCreateInstant; - bool visibleInMenu = true; - ExercisePart exercisePart = ExercisePart::eSpecial; - ExerciseStates exerciseStates = ExerciseState::eAll; + PluginData() = default; + PluginData(const QString &_menuGroup, + const QString &_menuText, + const QString &_identifier, + const createWidgetFuncPtr &_cwfp, + int _operatorRight, + ExercisePart _exercisePart = ExercisePart::eSpecial, + ExerciseStates _exerciseStates = ExerciseState::eAll) + : PluginData(_menuGroup, _menuText, _identifier, QIcon(), _cwfp, _operatorRight, _exercisePart, _exerciseStates) + {} - PluginData() = default; + PluginData(const QString &_menuGroup, + const QString &_menuText, + const QString &_identifier, + const QIcon &_icon, + const createWidgetFuncPtr &_cwfp, + int _operatorRight, + ExercisePart _exercisePart = ExercisePart::eSpecial, + ExerciseStates _exerciseStates = ExerciseState::eAll) + : createWidgetFunc(_cwfp) + , menuIcon(_icon) + , menuText(_menuText) + , menuGroup(_menuGroup) + , identifier(_identifier) + , operatorRight(_operatorRight) + , exercisePart(_exercisePart) + , exerciseStates(_exerciseStates) + { + } - PluginData(const QString& _menuGroup, const QString& _menuText, const QString& _identifier, - const createWidgetFuncPtr& _cwfp, int _operatorRight, - ExercisePart _exercisePart = ExercisePart::eSpecial, - ExerciseStates _exerciseStates = ExerciseState::eAll) - : PluginData(_menuGroup, _menuText, _identifier, QIcon(), _cwfp, _operatorRight, _exercisePart, _exerciseStates) - { - } - - PluginData(const QString& _menuGroup, const QString& _menuText, const QString& _identifier, const QIcon& _icon, - const createWidgetFuncPtr& _cwfp, int _operatorRight, - ExercisePart _exercisePart = ExercisePart::eSpecial, - ExerciseStates _exerciseStates = ExerciseState::eAll) - : createWidgetFunc(_cwfp), menuIcon(_icon), menuText(_menuText), menuGroup(_menuGroup), identifier(_identifier), - operatorRight(_operatorRight), exercisePart(_exercisePart), exerciseStates(_exerciseStates) - { - } - - static PluginData createGroup(const QString& menuGroup, const QString& menuText, const QString& identifier, - int operatorRight) - { - return PluginData(menuGroup, menuText, identifier, nullptr, operatorRight, ExercisePart::eSpecial); - } - - bool isValid() const - { - return createWidgetFunc != nullptr; - } + static PluginData createGroup(const QString &menuGroup, + const QString &menuText, + const QString &identifier, + int operatorRight) + { + return PluginData(menuGroup, menuText, identifier, nullptr, operatorRight, ExercisePart::eSpecial); + } + bool isValid() const { return createWidgetFunc != nullptr; } }; +/** + * Dummy class to be able to display enums defined outside of a qobject + * as properties in designer + */ class LTSWIDGETS_EXPORT Designer { - Q_GADGET - public: - enum ButtonSize { - eDefault = static_cast(LtsWidgets::ButtonSize::eDefault), - - }; - Q_ENUM(ButtonSize) - - enum ButtonStyle { - eAll = static_cast(LtsWidgets::ButtonStyle::eAll), - eTextOnly = static_cast(LtsWidgets::ButtonStyle::eTextOnly), - eIconOnly = static_cast(LtsWidgets::ButtonStyle::eIconOnly), - eTextNextToIcon = static_cast(LtsWidgets::ButtonStyle::eTextNextToIcon) - }; - Q_ENUM(ButtonStyle) - - enum LayoutArea { - eUnknownArea = static_cast(LtsWidgets::LayoutArea::eUnknown), - eInfoTab = static_cast(LtsWidgets::LayoutArea::eInfoTab), - eDialogTab = static_cast(LtsWidgets::LayoutArea::eDialogTab), - eSpecialTab = static_cast(LtsWidgets::LayoutArea::eSpecialTab), - eMainTab = static_cast(LtsWidgets::LayoutArea::eMainTab) - }; - Q_ENUM(LayoutArea) + Q_GADGET +public: + enum ButtonSize + { + eDefault = static_cast(LtsWidgets::ButtonSize::eDefault), +// eTiny = static_cast(LtsWidgets::ButtonSize::eTiny), +// eExtraSmall = static_cast(LtsWidgets::ButtonSize::eExtraSmall), +// eSmall = static_cast(LtsWidgets::ButtonSize::eSmall), +// eMedium = static_cast(LtsWidgets::ButtonSize::eMedium), +// eBig = static_cast(LtsWidgets::ButtonSize::eBig), +// eGigantic = static_cast(LtsWidgets::ButtonSize::eGigantic) + }; + Q_ENUM(ButtonSize) + enum ButtonStyle + { + eAll = static_cast(LtsWidgets::ButtonStyle::eAll), + eTextOnly = static_cast(LtsWidgets::ButtonStyle::eTextOnly), + eIconOnly = static_cast(LtsWidgets::ButtonStyle::eIconOnly), + eTextNextToIcon = static_cast(LtsWidgets::ButtonStyle::eTextNextToIcon) + }; + Q_ENUM(ButtonStyle) + enum LayoutArea + { + eUnknownArea = static_cast(LtsWidgets::LayoutArea::eUnknown), + eInfoTab = static_cast(LtsWidgets::LayoutArea::eInfoTab), + eDialogTab = static_cast(LtsWidgets::LayoutArea::eDialogTab), + eSpecialTab = static_cast(LtsWidgets::LayoutArea::eSpecialTab), + eMainTab = static_cast(LtsWidgets::LayoutArea::eMainTab) + }; + Q_ENUM(LayoutArea) }; -} // namespace LtsWidgets +} Q_DECLARE_METATYPE(LtsWidgets::Designer::ButtonSize) Q_DECLARE_METATYPE(LtsWidgets::Designer::ButtonStyle) Q_DECLARE_METATYPE(LtsWidgets::Designer::LayoutArea) diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_base_layout_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_base_layout_widget.cpp index 33705ae7a..977b84952 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_base_layout_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_base_layout_widget.cpp @@ -1,28 +1,35 @@ - +/** +* @RDE_HEADER@ +* Base Layout Widget with all Areas (Info, Main, Detail, Menu) +* $Id$ +* $HeadURL$ +* $Author$ +*/ #include "lts_base_layout_widget.h" +#include "ui_lts_base_layout.h" #include "lts_dialog.h" #include "lts_dialog_helper.h" #include "lts_drag_icon.h" -#include "lts_events.h" #include "lts_grid_layout.h" #include "lts_message_dialog.h" #include "lts_operator_menu.h" -#include "lts_splash.h" #include "lts_tool_bar_area.h" -#include "ui_lts_base_layout.h" +#include "lts_splash.h" +#include "lts_events.h" -#include #include #include +#include +#include + #include #include #include #include #include #include -#include #include #include #include @@ -35,1596 +42,1797 @@ #include #include #include -#include -#include +#include +#include + namespace LtsWidgets { -static QVariant splitterInterpolator(const QList& start, const QList& end, qreal progress) +static QVariant splitterInterpolator(const QList &start, const QList &end, qreal progress) { - QList ret; - ret = start; - for (int i = 0; i < start.size(); i++) - { - ret[i] = start[i] + qRound((end[i] - start[i]) * progress); - if (ret[i] <= 0) - ret[i] = 1; - } + QList ret; + ret = start; + for (int i = 0; i < start.size(); i++) + { + ret[i] = start[i] + qRound((end[i] - start[i]) * progress); + if (ret[i] <= 0) + ret[i] = 1; + } - return QVariant::fromValue(ret); + return QVariant::fromValue(ret); } -LtsBaseLayoutWidget::LtsBaseLayoutWidget(QWidget* parent, bool splitMenu) - : QWidget(parent), m_currentAnimation(nullptr), m_ui(new Ui::LtsBaseLayoutWidget), - m_partitionType(IDL::PartitionType::Global), m_domainId(-1), m_partitionId(-1), m_firstShow(true), - m_showTerminalButton(false), m_exerciseTime(0), m_setCurrentTimeTimer(new QTimer(this)), - m_irreplaceableOnce(false), m_bg(nullptr), m_screenCount(1), m_menuCollapsed(true), m_notiBox(nullptr) + +LtsBaseLayoutWidget::LtsBaseLayoutWidget(QWidget *parent, bool splitMenu) + : QWidget(parent) + , m_currentAnimation(nullptr) + , m_ui(new Ui::LtsBaseLayoutWidget) + , m_partitionType(IDL::PartitionType::Global) /* First ever Session must be the Administrative Global Partition */ + , m_domainId(-1) + , m_partitionId(-1) + , m_firstShow(true) + , m_showTerminalButton(false) + , m_exerciseTime(0) + , m_setCurrentTimeTimer(new QTimer(this)) + , m_irreplaceableOnce(false) + , m_bg(nullptr) + , m_screenCount(1) // at least 1 screen, always + , m_menuCollapsed(true) + , m_notiBox(nullptr) { - m_ui->setupUi(this); + m_ui->setupUi(this); #ifndef LTS_DEBUG - m_ui->pbDebug->hide(); + m_ui->pbDebug->hide(); #endif - addDebugMenu(); + addDebugMenu(); + + { + // Current Time label's context menu + m_ui->lbCurrentTime->setContextMenuPolicy(Qt::CustomContextMenu); + QMenu *currentTimeMenu = new QMenu(m_ui->lbCurrentTime); + currentTimeMenu->addAction(tr("Copy"), this, [this]() { - - m_ui->lbCurrentTime->setContextMenuPolicy(Qt::CustomContextMenu); - QMenu* currentTimeMenu = new QMenu(m_ui->lbCurrentTime); - currentTimeMenu->addAction(tr("Copy"), this, - [this]() { QGuiApplication::clipboard()->setText(m_ui->lbCurrentTime->text()); }); - currentTimeMenu->addAction(tr("Copy in milliseconds"), this, []() { - QGuiApplication::clipboard()->setText(QString::number(QDateTime::currentMSecsSinceEpoch())); - }); - connect(m_ui->lbCurrentTime, &QLabel::customContextMenuRequested, this, - [this, currentTimeMenu](const QPoint& pos) { - currentTimeMenu->popup(m_ui->lbCurrentTime->mapToGlobal(pos)); - }); - } - + QGuiApplication::clipboard()->setText(m_ui->lbCurrentTime->text()); + }); + currentTimeMenu->addAction(tr("Copy in milliseconds"), this, []() { + QGuiApplication::clipboard()->setText(QString::number(QDateTime::currentMSecsSinceEpoch())); + }); + connect(m_ui->lbCurrentTime, &QLabel::customContextMenuRequested, + this, [this, currentTimeMenu](const QPoint &pos) { currentTimeMenu->popup(m_ui->lbCurrentTime->mapToGlobal(pos)); }); + } - m_ui->lbExerciseTime->setContextMenuPolicy(Qt::CustomContextMenu); - QMenu* exerciseTimeMenu = new QMenu(m_ui->lbExerciseTime); - exerciseTimeMenu->addAction(tr("Copy"), this, - [this]() { QGuiApplication::clipboard()->setText(m_ui->lbExerciseTime->text()); }); - exerciseTimeMenu->addAction(tr("Copy in milliseconds"), this, [this]() { - QGuiApplication::clipboard()->setText(QString::number(m_exerciseTime)); - }); - connect(m_ui->lbExerciseTime, &QLabel::customContextMenuRequested, this, - [this, exerciseTimeMenu](const QPoint& pos) { - exerciseTimeMenu->popup(m_ui->lbExerciseTime->mapToGlobal(pos)); - }); - } - setMinimumSize(1280, 900); - - m_ui->detailWidget->setSubTabsVisible(true); - - qRegisterAnimationInterpolator>(splitterInterpolator); - qRegisterMetaType("LayoutArea"); - - m_ui->mainWidget->setTabBarAutoHide(true); - - m_ui->infoWidget->setActuatorTabStyle(true); - m_ui->infoWidget->setTabBarAutoHide(false); - m_ui->infoWidget->setTabPosition(QTabWidget::West); - - if (m_ui->infoWidget->count() == 0) - m_ui->infoWidget->hide(); - - if (m_ui->detailWidget->count() == 0) - m_ui->detailWidget->hide(); - - if (m_ui->specialWidget->count() == 0) - m_ui->specialWidget->hide(); - - m_ui->masterSplitter->setStretchFactor(m_ui->masterSplitter->indexOf(m_ui->infoWidget), 0); - m_ui->masterSplitter->setStretchFactor(m_ui->masterSplitter->indexOf(m_ui->mainSplitter), 20); - - m_ui->mainSplitter->setStretchFactor(m_ui->mainSplitter->indexOf(m_ui->mainWidget), 20); - m_ui->mainSplitter->setStretchFactor(m_ui->mainSplitter->indexOf(m_ui->detailWidget), 0); - - m_ui->rightSplitter->setStretchFactor(m_ui->rightSplitter->indexOf(m_ui->stackedWidget), 20); - m_ui->rightSplitter->setStretchFactor(m_ui->rightSplitter->indexOf(m_ui->specialWidget), 0); - - m_isHidden = false; - - connect(m_ui->profileButton, &LtsProfileButton::signalClicked, this, &LtsBaseLayoutWidget::slotOperatorMenuClicked); - - m_ui->lbCustomTextBullet->hide(); - m_ui->lbCustomText->hide(); - - m_ui->lbExerciseTime->setText(QStringLiteral(" # ")); - m_ui->lbCurrentTime->setText(QStringLiteral(" # ")); - - connect(m_setCurrentTimeTimer, &QTimer::timeout, this, &LtsBaseLayoutWidget::setCurrentTime); - m_setCurrentTimeTimer->start(200); - - setExerciseData(m_exerciseData); - - if (splitMenu) + { + // Exercise Time label's context menu + m_ui->lbExerciseTime->setContextMenuPolicy(Qt::CustomContextMenu); + QMenu *exerciseTimeMenu = new QMenu(m_ui->lbExerciseTime); + exerciseTimeMenu->addAction(tr("Copy"), this, [this]() { - m_bg = new QButtonGroup(m_ui->naviWidget); - m_bg->addButton(m_ui->pbPlanning, (int)ExercisePart::ePlanning); - m_bg->addButton(m_ui->pbExecution, (int)ExercisePart::eExecution); - m_bg->addButton(m_ui->pbAfterAction, (int)ExercisePart::eAfterAction); - m_bg->addButton(m_ui->pbSpecial, (int)ExercisePart::eSpecial); - - connect(m_bg, &QButtonGroup::idClicked, m_ui->stackedWidget, - [this](int id) { m_ui->stackedWidget->setCurrentWidget(getToolBox((ExercisePart)id)); }); - m_ui->pbSpecial->click(); - } - else + QGuiApplication::clipboard()->setText(m_ui->lbExerciseTime->text()); + }); + exerciseTimeMenu->addAction(tr("Copy in milliseconds"), this, [this]() { - m_ui->stackedWidget->setCurrentWidget(getToolBox(ExercisePart::eSpecial)); - } + QGuiApplication::clipboard()->setText(QString::number(m_exerciseTime)); + }); + connect(m_ui->lbExerciseTime, &QLabel::customContextMenuRequested, + this, [this, exerciseTimeMenu](const QPoint &pos) { exerciseTimeMenu->popup(m_ui->lbExerciseTime->mapToGlobal(pos)); }); + } - checkExercisePartButtonVisibility(); + + setMinimumSize(1280, 900); + + m_ui->detailWidget->setSubTabsVisible(true); // only the detail tab widget has sub tabs !! + + //Register + qRegisterAnimationInterpolator >(splitterInterpolator); + qRegisterMetaType("LayoutArea"); + + m_ui->mainWidget->setTabBarAutoHide(true); + + m_ui->infoWidget->setActuatorTabStyle(true); + m_ui->infoWidget->setTabBarAutoHide(false); + m_ui->infoWidget->setTabPosition(QTabWidget::West); + + if (m_ui->infoWidget->count() == 0) + m_ui->infoWidget->hide(); + + if (m_ui->detailWidget->count() == 0) + m_ui->detailWidget->hide(); + + if (m_ui->specialWidget->count() == 0) + m_ui->specialWidget->hide(); + + // master splitter stretch + m_ui->masterSplitter->setStretchFactor(m_ui->masterSplitter->indexOf(m_ui->infoWidget), 0); + m_ui->masterSplitter->setStretchFactor(m_ui->masterSplitter->indexOf(m_ui->mainSplitter), 20); + + // main splitter stretch + m_ui->mainSplitter->setStretchFactor(m_ui->mainSplitter->indexOf(m_ui->mainWidget), 20); + m_ui->mainSplitter->setStretchFactor(m_ui->mainSplitter->indexOf(m_ui->detailWidget), 0); + + // right splitter stretch + m_ui->rightSplitter->setStretchFactor(m_ui->rightSplitter->indexOf(m_ui->stackedWidget), 20); + m_ui->rightSplitter->setStretchFactor(m_ui->rightSplitter->indexOf(m_ui->specialWidget), 0); + + m_isHidden = false; + + + connect(m_ui->profileButton, &LtsProfileButton::signalClicked, this, &LtsBaseLayoutWidget::slotOperatorMenuClicked); + + //m_ui->lbExerciseTime->hide(); + //m_ui->lbExercisePhase->hide(); + //m_ui->lbExerciseStatus->hide(); + //m_ui->lbExerciseName->hide(); + m_ui->lbCustomTextBullet->hide(); + m_ui->lbCustomText->hide(); + + m_ui->lbExerciseTime->setText(QStringLiteral(" # ")); + m_ui->lbCurrentTime->setText(QStringLiteral(" # ")); + + connect(m_setCurrentTimeTimer, &QTimer::timeout, this, &LtsBaseLayoutWidget::setCurrentTime); + m_setCurrentTimeTimer->start(200); + + setExerciseData(m_exerciseData); // initially set labels to invalid values + + if (splitMenu) + { + m_bg = new QButtonGroup(m_ui->naviWidget); + m_bg->addButton(m_ui->pbPlanning, (int) ExercisePart::ePlanning); + m_bg->addButton(m_ui->pbExecution, (int) ExercisePart::eExecution); + m_bg->addButton(m_ui->pbAfterAction, (int) ExercisePart::eAfterAction); + m_bg->addButton(m_ui->pbSpecial, (int) ExercisePart::eSpecial); + + connect(m_bg, QOverload::of(&QButtonGroup::buttonClicked), m_ui->stackedWidget, [this](int id) + { + m_ui->stackedWidget->setCurrentWidget(getToolBox((ExercisePart) id)); + }); + m_ui->pbSpecial->click(); + } + else + { + m_ui->stackedWidget->setCurrentWidget(getToolBox(ExercisePart::eSpecial)); + } + + checkExercisePartButtonVisibility(); } + LtsBaseLayoutWidget::~LtsBaseLayoutWidget() { + // memleak .. x) - if (m_notiBox != nullptr) - m_notiBox->setParent(nullptr); - delete m_notiBox; + // qCritical() << "~LtsBaseLayoutWidget"; - delete m_currentAnimation; - m_currentAnimation = nullptr; - clearMenuActions(); - delete m_ui; - m_ui = nullptr; + if (m_notiBox != nullptr) + m_notiBox->setParent(nullptr); + delete m_notiBox; + + delete m_currentAnimation; + m_currentAnimation = nullptr; + clearMenuActions(); + delete m_ui; + m_ui = nullptr; + // do not delete m_progressDialogHelper because it is parented with this object (??!!) } + void LtsBaseLayoutWidget::setCurrentTime() { - m_ui->lbCurrentTime->setText(DTG::toString(QDateTime::currentDateTime())); + m_ui->lbCurrentTime->setText(DTG::toString(QDateTime::currentDateTime())); - if (m_exerciseTime > 0) - m_ui->lbExerciseTime->setText(DTG::toStringMSec(m_exerciseTime)); - else - m_ui->lbExerciseTime->setText(QStringLiteral(" # ")); + if (m_exerciseTime > 0) + m_ui->lbExerciseTime->setText(DTG::toStringMSec(m_exerciseTime)); + else + m_ui->lbExerciseTime->setText(QStringLiteral(" # ")); } + void LtsBaseLayoutWidget::slotScreenCountChanged(int count) { - m_screenCount = count; + m_screenCount = count; } + const QString LtsBaseLayoutWidget::customText() const { - return m_ui->lbCustomText->text(); + return m_ui->lbCustomText->text(); } -void LtsBaseLayoutWidget::setCustomText(const QString& text) + +void LtsBaseLayoutWidget::setCustomText(const QString &text) { - if (text.isEmpty()) - { - m_ui->lbCustomText->setText(QString()); - m_ui->lbCustomText->hide(); - m_ui->lbCustomTextBullet->hide(); + if (text.isEmpty()) + { + m_ui->lbCustomText->setText(QString()); + m_ui->lbCustomText->hide(); + m_ui->lbCustomTextBullet->hide(); - return; - } + return; + } - m_ui->lbCustomText->show(); - m_ui->lbCustomTextBullet->show(); - m_ui->lbCustomText->setText(text); + m_ui->lbCustomText->show(); + m_ui->lbCustomTextBullet->show(); + m_ui->lbCustomText->setText(text); } + void LtsBaseLayoutWidget::addDebugMenu() { #ifdef LTS_DEBUG - QMenu* menu = new QMenu(this); + QMenu *menu = new QMenu(this); - menu->addAction(QStringLiteral("NOTE: all actions are delayed by 1s"))->setEnabled(false); + menu->addAction(QStringLiteral("NOTE: all actions are delayed by 1s"))->setEnabled(false); - menu->addSeparator(); + menu->addSeparator(); - menu->addAction(QStringLiteral("logout"), this, - [this]() { QTimer::singleShot(1000, this, &LtsBaseLayoutWidget::slotLogout); }); + menu->addAction(QStringLiteral("logout"), this, [this]() + { + QTimer::singleShot(1000, this, &LtsBaseLayoutWidget::slotLogout); + }); - menu->addAction(QStringLiteral("forced logout"), this, - [this]() { QTimer::singleShot(1000, this, &LtsBaseLayoutWidget::signalLogout); }); + menu->addAction(QStringLiteral("forced logout"), this, [this]() + { + QTimer::singleShot(1000, this, &LtsBaseLayoutWidget::signalLogout); + }); - menu->addAction(QStringLiteral("app exit"), this, - [this]() { QTimer::singleShot(1000, this, &LtsBaseLayoutWidget::signalClose); }); + menu->addAction(QStringLiteral("app exit"), this, [this]() + { + QTimer::singleShot(1000, this, &LtsBaseLayoutWidget::signalClose); + }); - menu->addSeparator(); + menu->addSeparator(); - menu->addAction(QStringLiteral("show test message, unparented"), this, [this]() { - QTimer::singleShot(1000, this, []() { - LtsWidgets::LtsMessageDialog::showMessage(nullptr, QStringLiteral("test"), QStringLiteral("test")); - }); + menu->addAction(QStringLiteral("show test message, unparented"), this, [this]() + { + QTimer::singleShot(1000, this, []() { LtsWidgets::LtsMessageDialog::showMessage(nullptr /* INTENDED! */, QStringLiteral("test"), QStringLiteral("test")); } ); + }); + + menu->addAction(QStringLiteral("show test message"), this, [this]() + { + QTimer::singleShot(1000, this, [this]() { LtsWidgets::LtsMessageDialog::showMessage(this, QStringLiteral("test"), QStringLiteral("test")); } ); + }); + + menu->addSeparator(); + + menu->addAction(QStringLiteral("hide details tab"), this, [this]() + { + QTimer::singleShot(1000, this, [this]() { this->hideWidgets(); } ); + }); + + menu->addAction(QStringLiteral("show details tab"), this, [this]() + { + QTimer::singleShot(1000, this, [this]() { this->showWidgets(); } ); + }); + + menu->addAction(QStringLiteral("hide details tab, animated"), this, [this]() + { + QTimer::singleShot(1000, this, [this]() { this->onHideAnimated(); } ); + }); + + menu->addAction(QStringLiteral("show details tab, animated"), this, [this]() + { + QTimer::singleShot(1000, this, [this]() { this->onReShowAnimated(); } ); + }); + + menu->addSeparator(); + + menu->addAction(QStringLiteral("hide top bar"), this, [this]() + { + QTimer::singleShot(1000, this, [this]() { this->setTopBarVisible(false); } ); + }); + + menu->addSeparator(); + + menu->addAction(QStringLiteral("test NotificationBox with error"), this, [this]() + { + QTimer::singleShot(1000, this, [this]() + { + showMessage(QStringLiteral("Test Title"), QStringLiteral("A long test text that notifies the user about something
that spreads over two lines to fit even more text."), LtsWidgets::LtsNotificationBox::MessageType::Error, + [this](const QString &) + { + new LtsWidgets::LtsMessageDialogNew(this, QStringLiteral("You clicked the link!")); + }, true, QInputDialog::getText(this, QStringLiteral("Identifier"), QStringLiteral("Identifier (keep empty to not set)"))); }); + }); - menu->addAction(QStringLiteral("show test message"), this, [this]() { - QTimer::singleShot(1000, this, [this]() { - LtsWidgets::LtsMessageDialog::showMessage(this, QStringLiteral("test"), QStringLiteral("test")); - }); + menu->addAction(QStringLiteral("test NotificationBox with success"), this, [this]() + { + QTimer::singleShot(1000, this, [this]() + { + showMessage(QStringLiteral("Test Title"), QStringLiteral("A long test text that notifies the user about something
that spreads over two lines to fit even more text."), LtsWidgets::LtsNotificationBox::MessageType::Success, + [this](const QString &) + { + new LtsWidgets::LtsMessageDialogNew(this, QStringLiteral("You clicked the link!")); + }, true, QInputDialog::getText(this, QStringLiteral("Identifier"), QStringLiteral("Identifier (keep empty to not set)"))); }); + }); - menu->addSeparator(); - - menu->addAction(QStringLiteral("hide details tab"), this, - [this]() { QTimer::singleShot(1000, this, [this]() { this->hideWidgets(); }); }); - - menu->addAction(QStringLiteral("show details tab"), this, - [this]() { QTimer::singleShot(1000, this, [this]() { this->showWidgets(); }); }); - - menu->addAction(QStringLiteral("hide details tab, animated"), this, - [this]() { QTimer::singleShot(1000, this, [this]() { this->onHideAnimated(); }); }); - - menu->addAction(QStringLiteral("show details tab, animated"), this, - [this]() { QTimer::singleShot(1000, this, [this]() { this->onReShowAnimated(); }); }); - - menu->addSeparator(); - - menu->addAction(QStringLiteral("hide top bar"), this, - [this]() { QTimer::singleShot(1000, this, [this]() { this->setTopBarVisible(false); }); }); - - menu->addSeparator(); - - menu->addAction(QStringLiteral("test NotificationBox with error"), this, [this]() { - QTimer::singleShot(1000, this, [this]() { - showMessage( - QStringLiteral("Test Title"), - QStringLiteral( - "A long test text that notifies the user about something
that spreads over two lines to fit even more text."), - LtsWidgets::LtsNotificationBox::MessageType::Error, - [this](const QString&) { - new LtsWidgets::LtsMessageDialogNew(this, QStringLiteral("You clicked the link!")); - }, - true, - QInputDialog::getText(this, QStringLiteral("Identifier"), - QStringLiteral("Identifier (keep empty to not set)"))); - }); + menu->addAction(QStringLiteral("test NotificationBox with info"), this, [this]() + { + QTimer::singleShot(1000, this, [this]() + { + showMessage(QStringLiteral("Test Title"), QStringLiteral("A long test text that notifies the user about something
that spreads over two lines to fit even more text."), LtsWidgets::LtsNotificationBox::MessageType::Info, + [this](const QString &) + { + new LtsWidgets::LtsMessageDialogNew(this, QStringLiteral("You clicked the link!")); + }, true, QInputDialog::getText(this, QStringLiteral("Identifier"), QStringLiteral("Identifier (keep empty to not set)"))); }); + }); - menu->addAction(QStringLiteral("test NotificationBox with success"), this, [this]() { - QTimer::singleShot(1000, this, [this]() { - showMessage( - QStringLiteral("Test Title"), - QStringLiteral( - "A long test text that notifies the user about something
that spreads over two lines to fit even more text."), - LtsWidgets::LtsNotificationBox::MessageType::Success, - [this](const QString&) { - new LtsWidgets::LtsMessageDialogNew(this, QStringLiteral("You clicked the link!")); - }, - true, - QInputDialog::getText(this, QStringLiteral("Identifier"), - QStringLiteral("Identifier (keep empty to not set)"))); - }); + menu->addAction(QStringLiteral("test NotificationBox with warning"), this, [this]() + { + QTimer::singleShot(1000, this, [this]() + { + showMessage(QStringLiteral("Test Title"), QStringLiteral("A long test text that notifies the user about something
that spreads over two lines to fit even more text."), LtsWidgets::LtsNotificationBox::MessageType::Warning, + [this](const QString &) + { + new LtsWidgets::LtsMessageDialogNew(this, QStringLiteral("You clicked the link!")); + }, true, QInputDialog::getText(this, QStringLiteral("Identifier"), QStringLiteral("Identifier (keep empty to not set)"))); }); + }); - menu->addAction(QStringLiteral("test NotificationBox with info"), this, [this]() { - QTimer::singleShot(1000, this, [this]() { - showMessage( - QStringLiteral("Test Title"), - QStringLiteral( - "A long test text that notifies the user about something
that spreads over two lines to fit even more text."), - LtsWidgets::LtsNotificationBox::MessageType::Info, - [this](const QString&) { - new LtsWidgets::LtsMessageDialogNew(this, QStringLiteral("You clicked the link!")); - }, - true, - QInputDialog::getText(this, QStringLiteral("Identifier"), - QStringLiteral("Identifier (keep empty to not set)"))); - }); - }); - - menu->addAction(QStringLiteral("test NotificationBox with warning"), this, [this]() { - QTimer::singleShot(1000, this, [this]() { - showMessage( - QStringLiteral("Test Title"), - QStringLiteral( - "A long test text that notifies the user about something
that spreads over two lines to fit even more text."), - LtsWidgets::LtsNotificationBox::MessageType::Warning, - [this](const QString&) { - new LtsWidgets::LtsMessageDialogNew(this, QStringLiteral("You clicked the link!")); - }, - true, - QInputDialog::getText(this, QStringLiteral("Identifier"), - QStringLiteral("Identifier (keep empty to not set)"))); - }); - }); - - m_ui->pbDebug->setMenu(menu); + m_ui->pbDebug->setMenu(menu); #endif } -void LtsBaseLayoutWidget::showEvent(QShowEvent* event) + +void LtsBaseLayoutWidget::showEvent(QShowEvent *event) { - QWidget::showEvent(event); + QWidget::showEvent(event); - if (!m_firstShow) - return; + if (!m_firstShow) + return; - m_firstShow = false; + m_firstShow = false; - QSize rendererSizeHint = m_ui->topLayoutWidget->sizeHint(); - rendererSizeHint.scale(rendererSizeHint.width() * 0.65, rendererSizeHint.height() * 0.65, Qt::IgnoreAspectRatio); - const auto dpr = devicePixelRatioF(); + QSize rendererSizeHint = m_ui->topLayoutWidget->sizeHint(); + rendererSizeHint.scale(rendererSizeHint.width() * 0.65, rendererSizeHint.height() * 0.65, Qt::IgnoreAspectRatio); + const auto dpr = devicePixelRatioF(); + + { + const QSize s(QSize(rendererSizeHint.height(), rendererSizeHint.height()) * dpr); + // RDE SPLITTER LEFT + QSvgRenderer svgRenderer; + QPixmap pixmap(s); + pixmap.fill(Qt::transparent); + + QPainter painter(&pixmap); + svgRenderer.load(QLatin1String(":rde_splitter_left.svg")); + svgRenderer.render(&painter); + painter.end(); + + pixmap.setDevicePixelRatio(dpr); + m_ui->lbRdeSplitterLeft->setPixmap(pixmap); + } + + { + // PROJECT LOGO + QString projectLogoFilename = QLatin1String(":project/logo.png"); + QPixmap pixmap(projectLogoFilename); + pixmap.setDevicePixelRatio(dpr); + + if (pixmap.isNull()) { - const QSize s(QSize(rendererSizeHint.height(), rendererSizeHint.height()) * dpr); - - QSvgRenderer svgRenderer; - QPixmap pixmap(s); - pixmap.fill(Qt::transparent); - - QPainter painter(&pixmap); - svgRenderer.load(QLatin1String(":rde_splitter_left.svg")); - svgRenderer.render(&painter); - painter.end(); - - pixmap.setDevicePixelRatio(dpr); - m_ui->lbRdeSplitterLeft->setPixmap(pixmap); + qWarning() << "LoginWindow::c_tor: (PROJECT LOGO) file missing or is not an valid image '" << projectLogoFilename << "'"; } - + else { - - QString projectLogoFilename = QLatin1String(":project/logo.png"); - QPixmap pixmap(projectLogoFilename); - pixmap.setDevicePixelRatio(dpr); - - if (pixmap.isNull()) - { - qWarning() << "LoginWindow::c_tor: (PROJECT LOGO) file missing or is not an valid image '" - << projectLogoFilename << "'"; - } - else - { - pixmap = pixmap.scaled(rendererSizeHint * dpr, Qt::KeepAspectRatio, Qt::SmoothTransformation); - m_ui->lbProjectLogo->setPixmap(pixmap); - } + pixmap = pixmap.scaled(rendererSizeHint * dpr, Qt::KeepAspectRatio, Qt::SmoothTransformation); + m_ui->lbProjectLogo->setPixmap(pixmap); } + } #ifdef TABLET_MODE - QList scrollWidgets = findChildren(); + QList scrollWidgets = findChildren(); - for (auto i = scrollWidgets.begin(); i != scrollWidgets.end(); ++i) - { - QWidget* widget = *i; + for (auto i = scrollWidgets.begin(); i != scrollWidgets.end(); ++i) + { + QWidget *widget = *i; - QVariant isConst = widget->property("const"); - if (isConst.isValid() && isConst.toBool()) - continue; + QVariant isConst = widget->property("const"); + if (isConst.isValid() && isConst.toBool()) + continue; - addTouchScroll(widget); - } + addTouchScroll(widget); + } #endif - Splash::getInstance()->done(); + Splash::getInstance()->done(); } -void LtsBaseLayoutWidget::addTouchScroll(QWidget* widget) + +void LtsBaseLayoutWidget::addTouchScroll(QWidget *widget) { - if (!widget) - return; - widget->setAttribute(Qt::WA_AcceptTouchEvents); + if (!widget) + return; + widget->setAttribute(Qt::WA_AcceptTouchEvents); - QScrollArea* sca = qobject_cast(widget); - if (sca) - { - QScroller::grabGesture(sca->viewport(), QScroller::LeftMouseButtonGesture); - return; - } + QScrollArea *sca = qobject_cast(widget); + if (sca) + { + QScroller::grabGesture(sca->viewport(), QScroller::LeftMouseButtonGesture); + return; + } - QAbstractItemView* aiv = qobject_cast(widget); - if (aiv) - { - QScroller::grabGesture(aiv->viewport(), QScroller::LeftMouseButtonGesture); - aiv->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); - aiv->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); - return; - } + QAbstractItemView *aiv = qobject_cast(widget); + if (aiv) + { + QScroller::grabGesture(aiv->viewport(), QScroller::LeftMouseButtonGesture); + aiv->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); + aiv->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); + return; + } } -void LtsBaseLayoutWidget::setAppName(const QString& appName) + +void LtsBaseLayoutWidget::setAppName(const QString &appName) { - m_ui->lbAppName->setText(appName); + m_ui->lbAppName->setText(appName); } -void LtsBaseLayoutWidget::setExerciseData(const ExerciseData& data) + +void LtsBaseLayoutWidget::setExerciseData(const ExerciseData &data) { - m_exerciseData = data; + m_exerciseData = data; // copy - m_ui->lbExerciseName->setText(data.exName.isEmpty() ? tr("no exercise") : data.exName); + m_ui->lbExerciseName->setText(data.exName.isEmpty() ? tr("no exercise") : data.exName); - QString exerciseNameToolTip(tr("Exercise name")); - if (!data.exName.isEmpty() && m_partitionId > 0) - { - exerciseNameToolTip += tr("\nPartition Id:"); - exerciseNameToolTip += QStringLiteral(" %1").arg(m_partitionId); - } + QString exerciseNameToolTip(tr("Exercise name")); + if (!data.exName.isEmpty() && m_partitionId > 0) + { + exerciseNameToolTip += tr("\nPartition Id:"); + exerciseNameToolTip += QStringLiteral(" %1").arg(m_partitionId); + } - if (!data.exDescription.isEmpty()) - { - exerciseNameToolTip += tr("\nDescription:"); - exerciseNameToolTip += QStringLiteral(" %1").arg(data.exDescription); - } - m_ui->lbExerciseName->setToolTip(exerciseNameToolTip); + if (!data.exDescription.isEmpty()) + { + exerciseNameToolTip += tr("\nDescription:"); + exerciseNameToolTip += QStringLiteral(" %1").arg(data.exDescription); + } + m_ui->lbExerciseName->setToolTip(exerciseNameToolTip); - LtsUtils::ProjectSettings* ps = LtsUtils::ProjectSettings::getInstance(); - const bool enableEditPhases = ps->value(QStringLiteral("exm"), QStringLiteral("enableEditPhases")).toBool(); - if (!enableEditPhases) - { - m_ui->lbExercisePhase->hide(); - m_ui->bullet1->hide(); - } + LtsUtils::ProjectSettings *ps = LtsUtils::ProjectSettings::getInstance(); + const bool enableEditPhases = ps->value(QStringLiteral("exm"), + QStringLiteral("enableEditPhases")).toBool(); + if (!enableEditPhases) + { + m_ui->lbExercisePhase->hide(); + m_ui->bullet1->hide(); + } - m_ui->lbExercisePhase->setText(data.phName.isEmpty() ? tr("no phase") : data.phName); + m_ui->lbExercisePhase->setText(data.phName.isEmpty() ? tr("no phase") : data.phName); - QString phaseNameToolTip(tr("Exercise phase")); - if (!data.phDescription.isEmpty()) - { - phaseNameToolTip += tr("\nDescription:"); - phaseNameToolTip += QStringLiteral(" %1").arg(data.phDescription); - } - m_ui->lbExercisePhase->setToolTip(phaseNameToolTip); + QString phaseNameToolTip(tr("Exercise phase")); + if (!data.phDescription.isEmpty()) + { + phaseNameToolTip += tr("\nDescription:"); + phaseNameToolTip += QStringLiteral(" %1").arg(data.phDescription); + } + m_ui->lbExercisePhase->setToolTip(phaseNameToolTip); - m_ui->lbExerciseStatus->setText(data.exStateString.isEmpty() ? tr("no status") : data.exStateString); + m_ui->lbExerciseStatus->setText(data.exStateString.isEmpty() ? tr("no status") : data.exStateString); - if (data.exStateCol.isValid() && data.exStateCol != QColor()) - { - QPalette p = m_ui->lbExerciseStatus->palette(); - p.setColor(m_ui->lbExerciseStatus->backgroundRole(), data.exStateCol); - p.setColor(m_ui->lbExerciseStatus->foregroundRole(), data.exStateCol); - m_ui->lbExerciseStatus->setPalette(p); - } + if (data.exStateCol.isValid() && data.exStateCol != QColor()) + { + QPalette p = m_ui->lbExerciseStatus->palette(); + p.setColor(m_ui->lbExerciseStatus->backgroundRole(), data.exStateCol); + p.setColor(m_ui->lbExerciseStatus->foregroundRole(), data.exStateCol); + m_ui->lbExerciseStatus->setPalette(p); + } - m_ui->lbPartitionType->setText(data.partitionType); + m_ui->lbPartitionType->setText(data.partitionType); - applyExerciseStateRestricition(); + applyExerciseStateRestricition(); } void LtsBaseLayoutWidget::applyExerciseStateRestricition() { - for (auto it = m_mapButtons.cbegin(); it != m_mapButtons.cend(); ++it) - { - bool visible = it.value().exerciseStates.testFlag(m_exerciseData.exState); - it.key()->setButtonVisible(visible); - } + for (auto it = m_mapButtons.cbegin(); it != m_mapButtons.cend(); ++it) + { + bool visible = it.value().exerciseStates.testFlag(m_exerciseData.exState); + it.key()->setButtonVisible(visible); + } } -void LtsBaseLayoutWidget::initilizationFinished() {} - -void LtsBaseLayoutWidget::setToolBarActions(const QStringList& actions) +void LtsBaseLayoutWidget::initilizationFinished() { - QVector desiredActions; + // nothing... - m_notFoundYet = actions; + // QMap fKeys; + // for(auto it = variantMap.cbegin(); it != variantMap.cend(); ++it) + // fKeys[it.key().toInt()] = it.value().toString(); - for (const QString& action : actions) + // setToolBarActions(settings); + // setFunctionKeys(fKeys); +} + +void LtsBaseLayoutWidget::setToolBarActions(const QStringList &actions) +{ + QVector desiredActions; + + m_notFoundYet = actions; + + for (const QString &action : actions) + { + for (auto innerIt = m_mapButtons.cbegin(); innerIt != m_mapButtons.cend(); ++innerIt) { - for (auto innerIt = m_mapButtons.cbegin(); innerIt != m_mapButtons.cend(); ++innerIt) - { - if (innerIt.value().identifier.compare(action) == 0) - { - desiredActions << innerIt.key(); - m_notFoundYet.removeAll(action); - } - } + if (innerIt.value().identifier.compare(action) == 0) + { + desiredActions << innerIt.key(); + m_notFoundYet.removeAll(action); + } } + } - m_ui->toolBar->setMenuEntries(desiredActions); + m_ui->toolBar->setMenuEntries(desiredActions); } QStringList LtsBaseLayoutWidget::toolBarActions() const { - if (m_ui == nullptr || m_ui->toolBar == nullptr) - return QStringList(); - return m_ui->toolBar->menuEntries(); + if (m_ui == nullptr || m_ui->toolBar == nullptr) + return QStringList(); + return m_ui->toolBar->menuEntries(); } -void LtsBaseLayoutWidget::setFunctionKeys(const QMap& actions) +void LtsBaseLayoutWidget::setFunctionKeys(const QMap &actions) { - for (auto it = actions.cbegin(); it != actions.cend(); ++it) - m_ui->toolBar->setFunctionKey(it.key(), it.value()); + for (auto it = actions.cbegin(); it != actions.cend(); ++it) + m_ui->toolBar->setFunctionKey(it.key(), it.value()); } -QMap LtsBaseLayoutWidget::functionKeys() const +QMap LtsBaseLayoutWidget::functionKeys() const { - if (m_ui == nullptr) - return QMap(); - return m_ui->toolBar->functionKeys(); + if (m_ui == nullptr) + return QMap(); + return m_ui->toolBar->functionKeys(); } -void LtsBaseLayoutWidget::setSessionInfo(const int domainId, const IDL::PartitionType& partitionType, - const int partitionId, const QString& workspaceId) +void LtsBaseLayoutWidget::setSessionInfo(const int domainId, const IDL::PartitionType &partitionType, const int partitionId, const QString &workspaceId) { - m_domainId = domainId; - m_partitionType = partitionType; - m_partitionId = partitionId; - m_workspaceId = workspaceId; + m_domainId = domainId; + m_partitionType = partitionType; + m_partitionId = partitionId; + m_workspaceId = workspaceId; } -void LtsBaseLayoutWidget::setOperatorName(const QString& operatorName, bool showTerminalButton) + +// public +void LtsBaseLayoutWidget::setOperatorName(const QString &operatorName, bool showTerminalButton) { - m_operatorName = operatorName; - if (m_operatorName.isEmpty()) - m_operatorName = tr("Admin"); + m_operatorName = operatorName; + if (m_operatorName.isEmpty()) + m_operatorName = tr("Admin"); - m_ui->profileButton->setToolTip(tr("Operator Name: %1").arg(m_operatorName)); - m_showTerminalButton = showTerminalButton; + m_ui->profileButton->setToolTip(tr("Operator Name: %1").arg(m_operatorName)); + m_showTerminalButton = showTerminalButton; } -void LtsBaseLayoutWidget::setProfilePicture(const QPixmap& profilePicture) + +void LtsBaseLayoutWidget::setProfilePicture(const QPixmap &profilePicture) { - m_ui->profileButton->setPixmap(profilePicture); + m_ui->profileButton->setPixmap(profilePicture); } + void LtsBaseLayoutWidget::slotOperatorMenuClicked() { - bool debug = false; + bool debug = false; #ifndef LTS_DEBUG - if (LtsSessionData::LtsSessionData::getInstance()->debugFlagValue(QStringLiteral("DeveloperTools.Actions")) == - QVariant(true)) + if (LtsSessionData::LtsSessionData::getInstance()->debugFlagValue(QStringLiteral("DeveloperTools.Actions")) == QVariant(true)) #endif + { + debug = true; + } + + LtsOperatorMenu *operatorMenu = new LtsOperatorMenu(m_operatorName, m_workspaceId, debug, m_screenCount, this); + operatorMenu->setTerminalButton(m_showTerminalButton); + + bool hasOperatorSettings = false; + for (const PluginData &pd : qAsConst(m_mapButtons)) + { + if (pd.identifier == QStringLiteral("_OpmShowOperatorSettings")) { - debug = true; + hasOperatorSettings = true; + break; } + } + operatorMenu->setOperatorSettingsButton(hasOperatorSettings); // available for Replay - LtsOperatorMenu* operatorMenu = new LtsOperatorMenu(m_operatorName, m_workspaceId, debug, m_screenCount, this); - operatorMenu->setTerminalButton(m_showTerminalButton); + connect(operatorMenu, &LtsOperatorMenu::signalLogout, this, &LtsBaseLayoutWidget::slotLogout); + connect(operatorMenu, &LtsOperatorMenu::signalExit, this, &LtsBaseLayoutWidget::slotClose); + connect(operatorMenu, &LtsOperatorMenu::signalShowOperatorSettings, this, &LtsBaseLayoutWidget::signalShowOperatorSettings); + connect(operatorMenu, &LtsOperatorMenu::signalSwap, this, &LtsBaseLayoutWidget::signalSwap); - bool hasOperatorSettings = false; - for (const PluginData& pd : std::as_const(m_mapButtons)) - { - if (pd.identifier == QStringLiteral("_OpmShowOperatorSettings")) - { - hasOperatorSettings = true; - break; - } - } - operatorMenu->setOperatorSettingsButton(hasOperatorSettings); - - connect(operatorMenu, &LtsOperatorMenu::signalLogout, this, &LtsBaseLayoutWidget::slotLogout); - connect(operatorMenu, &LtsOperatorMenu::signalExit, this, &LtsBaseLayoutWidget::slotClose); - connect(operatorMenu, &LtsOperatorMenu::signalShowOperatorSettings, this, - &LtsBaseLayoutWidget::signalShowOperatorSettings); - connect(operatorMenu, &LtsOperatorMenu::signalSwap, this, &LtsBaseLayoutWidget::signalSwap); - - operatorMenu->show(); + operatorMenu->show(); } + bool LtsBaseLayoutWidget::haveUnsavedChanges() { - if (LtsTabWidget::hasUnsavedChanges(getTabFromLayoutArea(LayoutArea::eDialogTab))) - return true; - if (LtsTabWidget::hasUnsavedChanges(getTabFromLayoutArea(LayoutArea::eInfoTab))) - return true; - if (LtsTabWidget::hasUnsavedChanges(getTabFromLayoutArea(LayoutArea::eMainTab))) - return true; - if (LtsTabWidget::hasUnsavedChanges(getTabFromLayoutArea(LayoutArea::eSpecialTab))) - return true; + if (LtsTabWidget::hasUnsavedChanges(getTabFromLayoutArea(LayoutArea::eDialogTab))) + return true; + if (LtsTabWidget::hasUnsavedChanges(getTabFromLayoutArea(LayoutArea::eInfoTab))) + return true; + if (LtsTabWidget::hasUnsavedChanges(getTabFromLayoutArea(LayoutArea::eMainTab))) + return true; + if (LtsTabWidget::hasUnsavedChanges(getTabFromLayoutArea(LayoutArea::eSpecialTab))) + return true; - return false; + return false; // no unsaved changes } + +//LtsUtils::Promise *notifyUnsavedChangesAsync() +//{ +// if (haveUnsavedChanges()) +// { +// LtsMessageDialog::showMessage(this, tr("There are dialogs with unsaved changes.
Please save or discard their changes before closing."), tr("Unsaved changes")); +// return false; +// } +//} + + bool LtsBaseLayoutWidget::notifyUnsavedChanges() { - if (isSignalConnected(QMetaMethod::fromSignal(&LtsBaseLayoutWidget::signalNotifyUnsavedChanges))) + if (isSignalConnected(QMetaMethod::fromSignal(&LtsBaseLayoutWidget::signalNotifyUnsavedChanges))) + { + bool reject = false; + emit signalNotifyUnsavedChanges(reject); + return reject; + } + else + { + if (haveUnsavedChanges()) { - bool reject = false; - emit signalNotifyUnsavedChanges(reject); - return reject; + LtsWidgets::Buttons buttons; + buttons.setFlag(Button::Yes, true); + buttons.setFlag(Button::Cancel, true); + QHash buttonTexts; + buttonTexts.insert(Button::Yes, tr("Discard All")); + const auto ret = LtsMessageDialog::showMessage(this, tr("There are dialogs with unsaved changes.
Please save or discard their changes before closing"), tr("Unsaved changes"),Behaviour::Modal, buttons, buttonTexts); + return ret == Button::Yes; } - else - { - if (haveUnsavedChanges()) - { - LtsWidgets::Buttons buttons; - buttons.setFlag(Button::Yes, true); - buttons.setFlag(Button::Cancel, true); - QHash buttonTexts; - buttonTexts.insert(Button::Yes, tr("Discard All")); - const auto ret = LtsMessageDialog::showMessage( - this, - tr("There are dialogs with unsaved changes.
Please save or discard their changes before closing"), - tr("Unsaved changes"), Behaviour::Modal, buttons, buttonTexts); - return ret == Button::Yes; - } - } - return true; + } + return true; } -void LtsBaseLayoutWidget::slotLogout() + +void LtsBaseLayoutWidget::slotLogout() // TODO: rm, then signal on signal { - emit signalLogout(); + emit signalLogout(); } + bool LtsBaseLayoutWidget::slotClose() { - if (!notifyUnsavedChanges()) - return false; - - hide(); - - emit signalClose(); - return true; -} - -void LtsBaseLayoutWidget::closeEvent(QCloseEvent* event) -{ - event->ignore(); - - slotClose(); -} - -bool LtsBaseLayoutWidget::focusTab(const QString& menuGroup, const QString& identifier, LayoutArea area) -{ - LtsTabWidget* tab = getTabFromLayoutArea(area); - if (!tab) - { - qWarning() << "LtsBaseLayoutWidget::focusTab: tab, by enum type, not found!"; - return false; - } - - return tab->focusTab(menuGroup, identifier); -} - -bool LtsBaseLayoutWidget::isDialogFocused(const LtsDialog* dialog, const LtsTabWidget* tab) const -{ - QWidget* w = tab->widget(tab->currentIndex()); - - if (w == nullptr) - return false; - - const LtsTabWidget* secondTab = qobject_cast(w); - - if (secondTab != nullptr) - return isDialogFocused(dialog, secondTab); - - const LtsDialogHelper* helper = qobject_cast(w); - - if (helper != nullptr) - return helper->compare(dialog); - - qWarning() - << "LtsBaseLayoutWidget::isDialogFocused(LtsDialog *dialog, LtsTabWidget *tab): i found something weird.." - << w->metaObject()->className(); + if (!notifyUnsavedChanges()) return false; + + // // no unsaved changes? delete everything + // getTabFromLayoutArea(LayoutArea::eDialogTab)->clearAll(); + // getTabFromLayoutArea(LayoutArea::eInfoTab)->clearAll(); + // getTabFromLayoutArea(LayoutArea::eMainTab)->clearAll(); + // getTabFromLayoutArea(LayoutArea::eSpecialTab)->clearAll(); + + // // save toolbar entries + // auto toolBarItems = m_ui->toolBar->getMenuEntries(); + // Q_FOREACH(const QString &entry, toolBarItems) + // qCritical() << entry; + + // clearMenuActions(); // delete all menu entries + + // //delete m_ui; // now delete the ui, incl. widgets from any plugin, first ! + // //m_ui = nullptr; // TODO: remove this !! + + // if (!m_progressDialogHelper) + // m_progressDialogHelper = new LtsProgressDialogHelper(this); + + // m_progressDialogHelper->slotShowWaitForReplyWindow(); // this will run, until the LtsSession closes the BaseLayout - this will also delete the pdh, as it's parented + + hide(); + + emit signalClose(); //CloseRequest(m_domainId, m_partitionType, m_partitionId); + return true; } -bool LtsBaseLayoutWidget::isDialogFocused(const LtsDialog* dialog, const LayoutArea& layoutArea) const -{ - const LtsTabWidget* tab = getTabFromLayoutArea(layoutArea); - if (tab == nullptr) - { - qWarning() << "LtsBaseLayoutWidget::addWidget: tab, by enum type, not found!"; - return false; - } - return isDialogFocused(dialog, tab); +//void LtsBaseLayoutWidget::removeNotification(LtsNotificationIcon *noti) +//{ +// ... +//} + + +void LtsBaseLayoutWidget::closeEvent(QCloseEvent *event) +{ + event->ignore(); // do not close this BaseLayout, the Session will do this on signalCloseRequest ! + + slotClose(); } -bool LtsBaseLayoutWidget::isDialogFocused(const LtsDialog* dialog) const + +bool LtsBaseLayoutWidget::focusTab(const QString &menuGroup, const QString &identifier, LayoutArea area) { - return (isDialogFocused(dialog, LayoutArea::eDialogTab) || isDialogFocused(dialog, LayoutArea::eInfoTab) || - isDialogFocused(dialog, LayoutArea::eSpecialTab) || isDialogFocused(dialog, LayoutArea::eMainTab)); + LtsTabWidget *tab = getTabFromLayoutArea(area); + if (!tab) + { + qWarning() << "LtsBaseLayoutWidget::focusTab: tab, by enum type, not found!"; + return false; + } + + return tab->focusTab(menuGroup, identifier); } -bool LtsBaseLayoutWidget::addOrReplaceWidget(LtsDialog* dialog, const QString& menuGroup, const QString& identifier, - LayoutArea area, bool setClosable, bool focusNewTab) -{ - LtsTabWidget* tab = getTabFromLayoutArea(area); - if (tab && dialog && (!identifier.isEmpty())) - { - QWidget* existingWidget = tab->getWidget(menuGroup, identifier); - if (nullptr != existingWidget) - { - if (tab->removeWidget(existingWidget)) - { - existingWidget->deleteLater(); - } - else - { - qWarning() << __FUNCTION__ << " : Remove existing widget from TabWidget failed."; - } - } - } - return addWidget(dialog, menuGroup, identifier, area, setClosable, focusNewTab); +bool LtsBaseLayoutWidget::isDialogFocused(const LtsDialog *dialog, const LtsTabWidget *tab) const +{ + QWidget *w = tab->widget(tab->currentIndex()); + + if (w == nullptr) + return false; + + const LtsTabWidget *secondTab = qobject_cast(w); + + if (secondTab != nullptr) + return isDialogFocused(dialog, secondTab); + + const LtsDialogHelper *helper = qobject_cast(w); + + if (helper != nullptr) + return helper->compare(dialog); + + qWarning() << "LtsBaseLayoutWidget::isDialogFocused(LtsDialog *dialog, LtsTabWidget *tab): i found something weird.." << w->metaObject()->className(); + return false; } -bool LtsBaseLayoutWidget::addWidget(LtsDialog* dialog, const QString& menuGroup, const QString& identifier, - LayoutArea area, bool setClosable, bool focusNewTab) + +bool LtsBaseLayoutWidget::isDialogFocused(const LtsDialog *dialog, const LayoutArea &layoutArea) const { - if (!dialog) + const LtsTabWidget *tab = getTabFromLayoutArea(layoutArea); + if (tab == nullptr) + { + qWarning() << "LtsBaseLayoutWidget::addWidget: tab, by enum type, not found!"; + return false; + } + + return isDialogFocused(dialog, tab); +} + + +bool LtsBaseLayoutWidget::isDialogFocused(const LtsDialog *dialog) const +{ + return (isDialogFocused(dialog, LayoutArea::eDialogTab) || + isDialogFocused(dialog, LayoutArea::eInfoTab) || + isDialogFocused(dialog, LayoutArea::eSpecialTab) || + isDialogFocused(dialog, LayoutArea::eMainTab)); +} + + +bool LtsBaseLayoutWidget::addOrReplaceWidget(LtsDialog *dialog, const QString &menuGroup, const QString &identifier, LayoutArea area, bool setClosable, bool focusNewTab) +{ + LtsTabWidget *tab = getTabFromLayoutArea(area); + if (tab && dialog && (!identifier.isEmpty())) + { + QWidget *existingWidget = tab->getWidget(menuGroup, identifier); + + if (nullptr != existingWidget) { - qWarning() << "LtsBaseLayoutWidget::addWidget: cannot add null-widget!"; - return false; + if (tab->removeWidget(existingWidget)) + { + existingWidget->deleteLater(); // bye bye existingWidget, may be deleteLater already has been called before + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ calling deleteLater multiple times is discuraged.. + } + else + { + qWarning() << __FUNCTION__ << " : Remove existing widget from TabWidget failed."; + } } + } + return addWidget(dialog, menuGroup, identifier, area, setClosable, focusNewTab); +} // bool LtsBaseLayoutWidget::addOrReplaceWidget(LtsDialog *dialog, const QString &menuGroup, const QString &identifier, LayoutArea area, bool setClosable, bool focusNewTab) - LtsTabWidget* tab = getTabFromLayoutArea(area); - if (!tab) + +bool LtsBaseLayoutWidget::addWidget(LtsDialog *dialog, const QString &menuGroup, const QString &identifier, LayoutArea area, bool setClosable, bool focusNewTab) +{ + if (!dialog) + { + qWarning() << "LtsBaseLayoutWidget::addWidget: cannot add null-widget!"; + return false; + } + + LtsTabWidget *tab = getTabFromLayoutArea(area); + if (!tab) + { + qWarning() << "LtsBaseLayoutWidget::addWidget: tab, by enum type, not found!"; + return false; + } + + dialog->setMenuGroup(menuGroup); + dialog->setIdentifier(identifier); + QWidget /*LtsDialogHelper*/ *helper = dialog->getHelper(); + if (!helper) // LtsDialog is in compatibility mode ! bcuz it's old + { + helper = dialog; // pretend that the helper exists + dialog->setAttribute(Qt::WA_DeleteOnClose); // dialog must delete itself, as there is no Dialog Helper + } + + if (!identifier.isEmpty()) // do not check for existing tabs, if ident is empty + { + QWidget *existingWidget = tab->getWidget(menuGroup, identifier); + if (existingWidget != nullptr) // check here also if widget is already there (as widgets can call addWidget when e.g. editing something) { - qWarning() << "LtsBaseLayoutWidget::addWidget: tab, by enum type, not found!"; - return false; - } + helper->deleteLater(); // delete existing widget's helper! - dialog->setMenuGroup(menuGroup); - dialog->setIdentifier(identifier); - QWidget* helper = dialog->getHelper(); - if (!helper) + if (focusNewTab) // "foxus existing tab" + tab->focusTab(menuGroup, identifier); + + // animation tab is hidding? + int indexOfSplitter = getIndexOfTab(tab); + // animate if splitter is collapsed + if (area == LayoutArea::eDialogTab && !(m_ui->mainSplitter->sizes().at(indexOfSplitter))) + m_ui->mainSplitter->animate(1); + else if (area == LayoutArea::eInfoTab && !(m_ui->masterSplitter->sizes().at(indexOfSplitter))) + m_ui->masterSplitter->animate(1); + + + return false; // already exists, do nothing, as focus is done + } + } + + dialog->setBaseLayoutWidget(this); + + connect(dialog, &LtsDialog::startMainSelect, + this, &LtsBaseLayoutWidget::onHideAnimated); + connect(dialog, &LtsDialog::endMainSelect, + this, &LtsBaseLayoutWidget::onReShowAnimated); + + // Lock : + emit signalStapleTopicLockHandler(dialog); // must be called before addTab, as addTab calls retranslate, which also might try a lock so the connection must be already made - this slot is called sync/directly - sequential + dialog->triggerTopicLock(); + // : Lock + + + + tab->addTab(menuGroup, identifier, helper, setClosable, focusNewTab); // tell the MAIN tab that he should add a new MAIN tab, when there is none, and to add a SUB tab on the MAIN tab, with the given widget + // animate if splitter is collapsed + if (tab->count() > 1) + { + int indexOfSplitter = getIndexOfTab(tab); + if (area == LayoutArea::eDialogTab && !(m_ui->mainSplitter->sizes().at(indexOfSplitter))) { - helper = dialog; - dialog->setAttribute(Qt::WA_DeleteOnClose); + qDebug()<<"animate 1a: "; + m_ui->mainSplitter->animate(1); } - - if (!identifier.isEmpty()) + else if (area == LayoutArea::eInfoTab && !(m_ui->masterSplitter->sizes().at(indexOfSplitter))) { - QWidget* existingWidget = tab->getWidget(menuGroup, identifier); - if (existingWidget != nullptr) - { - helper->deleteLater(); - - if (focusNewTab) - tab->focusTab(menuGroup, identifier); - - int indexOfSplitter = getIndexOfTab(tab); - - if (area == LayoutArea::eDialogTab && !(m_ui->mainSplitter->sizes().at(indexOfSplitter))) - m_ui->mainSplitter->animate(1); - else if (area == LayoutArea::eInfoTab && !(m_ui->masterSplitter->sizes().at(indexOfSplitter))) - m_ui->masterSplitter->animate(1); - - return false; - } + qDebug()<<"animate 1b: "; + m_ui->masterSplitter->animate(1); } - - dialog->setBaseLayoutWidget(this); - - connect(dialog, &LtsDialog::startMainSelect, this, &LtsBaseLayoutWidget::onHideAnimated); - connect(dialog, &LtsDialog::endMainSelect, this, &LtsBaseLayoutWidget::onReShowAnimated); - - emit signalStapleTopicLockHandler(dialog); - dialog->triggerTopicLock(); - - tab->addTab(menuGroup, identifier, helper, setClosable, focusNewTab); - - if (tab->count() > 1) - { - int indexOfSplitter = getIndexOfTab(tab); - if (area == LayoutArea::eDialogTab && !(m_ui->mainSplitter->sizes().at(indexOfSplitter))) - { - qDebug() << "animate 1a: "; - m_ui->mainSplitter->animate(1); - } - else if (area == LayoutArea::eInfoTab && !(m_ui->masterSplitter->sizes().at(indexOfSplitter))) - { - qDebug() << "animate 1b: "; - m_ui->masterSplitter->animate(1); - } - } - + } + //#define ADJUST_SPLITTER_SIZES_DIALOGTAB #ifdef ADJUST_SPLITTER_SIZES_DIALOGTAB + /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * In layout area DialogTab dialogs are created and destroyed after use. The requested size of the tab widget changes every time. + * But the superordinate splitter doesn't adjust its geometry automatically. Do it here manually to get the PlanEditor working now. + * + * JT 2017/02/10 + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ + if (LayoutArea::eDialogTab == area) + { + const QList & sizes = m_ui->mainSplitter->sizes(); + int requestedTabHeight = tab->sizeHint().height(); + int mainHeight = sizes[0]+sizes[1]-requestedTabHeight; - if (LayoutArea::eDialogTab == area) - { - const QList& sizes = m_ui->mainSplitter->sizes(); - int requestedTabHeight = tab->sizeHint().height(); - int mainHeight = sizes[0] + sizes[1] - requestedTabHeight; + m_ui->mainSplitter->setSizes( QList() << mainHeight << requestedTabHeight ); + } +#endif // ADJUST_SPLITTER_SIZES_DIALOGTAB - m_ui->mainSplitter->setSizes(QList() << mainHeight << requestedTabHeight); - } -#endif - - return true; + return true; } -LtsDialog* LtsBaseLayoutWidget::getWidget(const QString& menuGroup, const QString& identifier, LayoutArea area) + +LtsDialog *LtsBaseLayoutWidget::getWidget(const QString &menuGroup, const QString &identifier, LayoutArea area) { - LtsTabWidget* tab = getTabFromLayoutArea(area); + LtsTabWidget *tab = getTabFromLayoutArea(area); - if (tab == nullptr) - return nullptr; + if (tab == nullptr) + return nullptr; - QWidget* w = tab->getWidget(menuGroup, identifier); + QWidget *w = tab->getWidget(menuGroup, identifier); - if (w == nullptr) - return nullptr; + if (w == nullptr) + return nullptr; - LtsDialogHelper* helper = qobject_cast(w); + LtsDialogHelper *helper = qobject_cast(w); - if (helper == nullptr) - return nullptr; + if (helper == nullptr) + return nullptr; - LtsDialog* dialog = qobject_cast(helper->getDialog()); - return dialog; + LtsDialog *dialog = qobject_cast(helper->getDialog()); + return dialog; } + void LtsBaseLayoutWidget::clearMenuActions() { + // menu + while (m_ui->naviActionsPlanning->count()) // remove all items + m_ui->naviActionsPlanning->removeItem(0); + while (m_ui->naviActionsExecution->count()) // remove all items + m_ui->naviActionsExecution->removeItem(0); + while (m_ui->naviActionsAfterAction->count()) // remove all items + m_ui->naviActionsAfterAction->removeItem(0); + while (m_ui->naviActionsSpecial->count()) // remove all items + m_ui->naviActionsSpecial->removeItem(0); - while (m_ui->naviActionsPlanning->count()) - m_ui->naviActionsPlanning->removeItem(0); - while (m_ui->naviActionsExecution->count()) - m_ui->naviActionsExecution->removeItem(0); - while (m_ui->naviActionsAfterAction->count()) - m_ui->naviActionsAfterAction->removeItem(0); - while (m_ui->naviActionsSpecial->count()) - m_ui->naviActionsSpecial->removeItem(0); + checkExercisePartButtonVisibility(); - checkExercisePartButtonVisibility(); + // map buttons + for(auto it = m_mapButtons.begin(); it != m_mapButtons.end(); ++it) + delete it.key(); - for (auto it = m_mapButtons.begin(); it != m_mapButtons.end(); ++it) - delete it.key(); - - m_mapButtons.clear(); + m_mapButtons.clear(); } -void LtsBaseLayoutWidget::executeCreateInstantFunctions(const PluginData& plData) + +void LtsBaseLayoutWidget::executeCreateInstantFunctions(const PluginData &plData) { - if (plData.createWidgetFunc) - { - LtsDialog* w = plData.createWidgetFunc(this); + if (plData.createWidgetFunc) + { + LtsDialog *w = plData.createWidgetFunc(this); - if (w) - addWidget(w, plData.menuGroup, plData.identifier, plData.layoutArea, plData.closable); - } + if (w) + addWidget(w, plData.menuGroup, plData.identifier, plData.layoutArea, plData.closable); + } - if (plData.directFunc) - { - plData.directFunc(plData); - } + if (plData.directFunc) + { + plData.directFunc(plData); + } } + void LtsBaseLayoutWidget::setExerciseTime(qint64 mSecsSinceEpoch) { - m_exerciseTime = mSecsSinceEpoch; + m_exerciseTime = mSecsSinceEpoch; } -LtsDragIcon* LtsBaseLayoutWidget::addMenuAction(const PluginData& plData, bool isFirstRun) +LtsDragIcon *LtsBaseLayoutWidget::addMenuAction(const PluginData &plData, bool isFirstRun) { - if (!LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(plData.operatorRight)) + if (!LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(plData.operatorRight)) + { + qDebug() << " > Action" << plData.menuGroup << ":" << plData.menuText << "was not added due to missing operator right 0x" << QString::number(plData.operatorRight, 16); + return nullptr; + } + + if (isFirstRun) + { + switch (plData.createInstant) // init and show every action, that goes must be created instantly { - qDebug() << " > Action" << plData.menuGroup << ":" << plData.menuText - << "was not added due to missing operator right 0x" << QString::number(plData.operatorRight, 16); - return nullptr; + case CreateInstantType::CreateInstantAndAddAction: + { + executeCreateInstantFunctions(plData); + break; } - if (isFirstRun) + case CreateInstantType::CreateInstantAndDiscardAction: { - switch (plData.createInstant) + executeCreateInstantFunctions(plData); + return nullptr; + } + + default: // case CreateInstantType::DontCreateInstant: + { + break; + } + } + } + else + { + if (plData.createInstant == CreateInstantType::CreateInstantAndDiscardAction) // discarded actions are not shown, ignore them + return nullptr; + } + + + + bool err = false; + if (plData.identifier.isEmpty()) + { +#ifdef LTS_DEBUG + LtsWidgets::LtsMessageDialog::showMessage(this, QStringLiteral("STOP!\n" + "Hier wurde ein Menu Entry hinzugefuegt, welcher ueber keinen Identifier verfuegt!\n" + "Bitte aendern!\n" + "Jetzt Debugger attachen und schauen woher der aufruf kommt.\n" + "Da der Identifier fehlt kann ich Dir hier nicht sagen um welchen Menu Entry es sich handelt =)")); +#endif + err = true; + } + + if (plData.menuGroup.isEmpty()) + { +#ifdef LTS_DEBUG + LtsWidgets::LtsMessageDialog::showMessage(this, QStringLiteral("STOP!\n" + "Hier wurde ein Menu Entry hinzugefuegt, welcher ueber keine Menu Group verfuegt!\n" + "Bitte aendern!\n" + "Jetzt Debugger attachen und schauen woher der aufruf kommt.\n" + "Da der Identifier fehlt kann ich Dir hier nicht sagen um welchen Menu Entry es sich handelt =)")); +#endif + err = true; + } + + if (err) + return nullptr; + + + + bool found = false; + + if (!isFirstRun) // refetch + { + for (auto it = m_mapButtons.begin(); it != m_mapButtons.end(); ++it) + { + LtsDragIcon *thatIcon = it.key(); + + if (thatIcon->objectName() == plData.identifier) + { + thatIcon->setText(plData.menuText); + thatIcon->setContext(plData.menuGroup); + + bool groupFound = false; + // rename group + for (int i = 0; i < m_ui->stackedWidget->count(); ++i) { - case CreateInstantType::CreateInstantAndAddAction: { - executeCreateInstantFunctions(plData); - break; - } - - case CreateInstantType::CreateInstantAndDiscardAction: { - executeCreateInstantFunctions(plData); - return nullptr; - } - - default: { - break; - } + LtsWidgets::LtsToolBox *tb = qobject_cast(m_ui->stackedWidget->widget(i)); + int groupWidgetIndex = tb->indexOf(thatIcon->parentWidget() /* the group entry */); + if (groupWidgetIndex >= 0) + { + tb->setItemText(groupWidgetIndex, plData.menuGroup); + groupFound = true; + break; + } } + if (!groupFound) + { + qWarning() << "group widget not found"; + } + found = true; + break; + } + } + + if (!found) + { + //qWarning() << "Could not find and replace the menu item" << plData.identifier << " - creating it!"; } else { - if (plData.createInstant == CreateInstantType::CreateInstantAndDiscardAction) - return nullptr; + return nullptr; // only replace texts on re-adding actions } + } - bool err = false; - if (plData.identifier.isEmpty()) - { -#ifdef LTS_DEBUG - LtsWidgets::LtsMessageDialog::showMessage( - this, - QStringLiteral( - "STOP!\n" - "Hier wurde ein Menu Entry hinzugefuegt, welcher ueber keinen Identifier verfuegt!\n" - "Bitte aendern!\n" - "Jetzt Debugger attachen und schauen woher der aufruf kommt.\n" - "Da der Identifier fehlt kann ich Dir hier nicht sagen um welchen Menu Entry es sich handelt =)")); -#endif - err = true; - } + LtsWidgets::LtsToolBox *tb = getToolBox(m_bg ? plData.exercisePart : ExercisePart::eSpecial); - if (plData.menuGroup.isEmpty()) - { -#ifdef LTS_DEBUG - LtsWidgets::LtsMessageDialog::showMessage( - this, - QStringLiteral( - "STOP!\n" - "Hier wurde ein Menu Entry hinzugefuegt, welcher ueber keine Menu Group verfuegt!\n" - "Bitte aendern!\n" - "Jetzt Debugger attachen und schauen woher der aufruf kommt.\n" - "Da der Identifier fehlt kann ich Dir hier nicht sagen um welchen Menu Entry es sich handelt =)")); -#endif - err = true; - } - - if (err) - return nullptr; - - bool found = false; - - if (!isFirstRun) - { - for (auto it = m_mapButtons.begin(); it != m_mapButtons.end(); ++it) - { - LtsDragIcon* thatIcon = it.key(); - - if (thatIcon->objectName() == plData.identifier) - { - thatIcon->setText(plData.menuText); - thatIcon->setContext(plData.menuGroup); - - bool groupFound = false; - - for (int i = 0; i < m_ui->stackedWidget->count(); ++i) - { - LtsWidgets::LtsToolBox* tb = qobject_cast(m_ui->stackedWidget->widget(i)); - int groupWidgetIndex = tb->indexOf(thatIcon->parentWidget()); - if (groupWidgetIndex >= 0) - { - tb->setItemText(groupWidgetIndex, plData.menuGroup); - groupFound = true; - break; - } - } - if (!groupFound) - { - qWarning() << "group widget not found"; - } - found = true; - break; - } - } - - if (!found) - { - } - else - { - return nullptr; - } - } - - LtsWidgets::LtsToolBox* tb = getToolBox(m_bg ? plData.exercisePart : ExercisePart::eSpecial); - - QWidget* tmpW = tb->findChild(plData.menuGroup); - if (!tmpW) - { - - if (plData.createWidgetFunc == nullptr && plData.directFunc == nullptr) - return nullptr; - - tmpW = new QWidget; - tmpW->setObjectName(plData.menuGroup); - - LtsGridLayout* ltsGridLayout = new LtsGridLayout(LtsWidgets::ButtonSize::eDefault, tmpW); - tmpW->setLayout(ltsGridLayout); - - tb->addItem(tmpW, plData.menuGroup); - connect(tb, &LtsToolBox::resized, ltsGridLayout, &LtsGridLayout::onParentResize); - } - - QLayout* widgetLayout = tmpW->layout(); - LtsGridLayout* ltsGridLayout = qobject_cast(widgetLayout); - if (!ltsGridLayout) - { - - qWarning() << "temp widget has no layout! cannot add action" << plData.menuText - << "to menu! (the bad widget was of type" << tmpW->metaObject()->className() - << ") [did you forget to add the menuGroup to that action?]"; - return nullptr; - } - - if (widgetLayout->count() > 0) - { - QSpacerItem* spacer = dynamic_cast(widgetLayout->itemAt(widgetLayout->count() - 1)); - if (spacer) - { - ltsGridLayout->removeItem(spacer); - delete spacer; - } - } - - LtsDragIcon* dragIcon = nullptr; + // otherwise create an action and add it to the menu + QWidget *tmpW = tb->findChild(plData.menuGroup); + if (!tmpW) + { + // no separator on first place if (plData.createWidgetFunc == nullptr && plData.directFunc == nullptr) - { - QFrame* line = new QFrame(tmpW); - line->setLineWidth(2); - line->setFrameStyle(QFrame::HLine); + return nullptr; - ltsGridLayout->add_widget(line); + // no tab for this menu group available -> create new one + tmpW = new QWidget; + tmpW->setObjectName(plData.menuGroup); + + LtsGridLayout *ltsGridLayout = new LtsGridLayout(LtsWidgets::ButtonSize::eDefault, tmpW); + tmpW->setLayout(ltsGridLayout); + + tb->addItem(tmpW, plData.menuGroup); + connect(tb, &LtsToolBox::resized, + ltsGridLayout, &LtsGridLayout::onParentResize); + } + + // layout should now already be here ... + QLayout *widgetLayout = tmpW->layout(); + LtsGridLayout *ltsGridLayout = qobject_cast(widgetLayout); + if (!ltsGridLayout) + { + //ERROR_LOG(m_logger) << "temp widget has no layout! cannot add action to menu!"; + qWarning() << "temp widget has no layout! cannot add action" << plData.menuText << "to menu! (the bad widget was of type" << tmpW->metaObject()->className() << ") [did you forget to add the menuGroup to that action?]"; + return nullptr; + } + + // remove old spacer (a new one is created at the end) + if (widgetLayout->count() > 0) + { + QSpacerItem *spacer = dynamic_cast(widgetLayout->itemAt(widgetLayout->count() - 1)); + if (spacer) + { + ltsGridLayout->removeItem(spacer); + delete spacer; } - else + } + + // create entry + LtsDragIcon *dragIcon = nullptr; + if (plData.createWidgetFunc == nullptr && plData.directFunc == nullptr) + { + QFrame *line = new QFrame(tmpW); + line->setLineWidth(2); + line->setFrameStyle(QFrame::HLine); + // add to layout + ltsGridLayout->add_widget(line); + } + else + { + if (isFirstRun || !found) { - if (isFirstRun || !found) - { - dragIcon = createButton(plData); - - ltsGridLayout->add_widget(dragIcon); - m_mapButtons.insert(dragIcon, plData); - - auto it = std::find_if(m_notFoundYet.begin(), m_notFoundYet.end(), - [plData](const QString& s) { return s == plData.identifier; }); - - if (it != m_notFoundYet.end()) - { - m_ui->toolBar->addMenuEntry(dragIcon); - m_notFoundYet.erase(it); - } - } + dragIcon = createButton(plData); + // add to layout + ltsGridLayout->add_widget(dragIcon); + m_mapButtons.insert(dragIcon, plData); // FIXME: rm destroyed buttons !! + + auto it = std::find_if(m_notFoundYet.begin(), m_notFoundYet.end(), [plData](const QString &s) + { + return s == plData.identifier; + }); + + if (it != m_notFoundYet.end()) // found + { + m_ui->toolBar->addMenuEntry(dragIcon); + m_notFoundYet.erase(it); + } } - - checkExercisePartButtonVisibility(); + } - QSpacerItem* spacer = new QSpacerItem(10, 1, QSizePolicy::Minimum, QSizePolicy::MinimumExpanding); - ltsGridLayout->addItem(spacer, ltsGridLayout->rowCount(), 0); + checkExercisePartButtonVisibility(); + // add spacer at end + QSpacerItem *spacer = new QSpacerItem(10, 1, QSizePolicy::Minimum, QSizePolicy::MinimumExpanding); + ltsGridLayout->addItem(spacer, ltsGridLayout->rowCount(), 0); - return dragIcon; + return dragIcon; } -void LtsBaseLayoutWidget::addNotification(QToolButton* noti) + +void LtsBaseLayoutWidget::addNotification(QToolButton *noti) { - m_ui->notificationLayoutWidget->layout()->addWidget(noti); + m_ui->notificationLayoutWidget->layout()->addWidget(noti); } -bool LtsBaseLayoutWidget::notificationExists(const QString& identifier) const + +bool LtsBaseLayoutWidget::notificationExists(const QString &identifier) const { - return (m_ui->notificationLayoutWidget->findChild(identifier, Qt::FindDirectChildrenOnly) != nullptr); + return (m_ui->notificationLayoutWidget->findChild(identifier, Qt::FindDirectChildrenOnly) != nullptr); } -bool LtsBaseLayoutWidget::removeMenuAction(const QString& byIdentifier) + +bool LtsBaseLayoutWidget::removeMenuAction(const QString &byIdentifier) { - for (auto it = m_mapButtons.begin(); it != m_mapButtons.end(); ++it) - { - if (it.value().identifier == byIdentifier) - return removeMenuAction(it.key()); - } + for (auto it = m_mapButtons.begin(); it != m_mapButtons.end(); ++it) + { + if (it.value().identifier == byIdentifier) + return removeMenuAction(it.key()); + } - return false; + return false; } -bool LtsBaseLayoutWidget::removeMenuAction(const PluginData& plData) + +bool LtsBaseLayoutWidget::removeMenuAction(const PluginData &plData) { - for (auto it = m_mapButtons.begin(); it != m_mapButtons.end(); ++it) - { - if (it.value().identifier == plData.identifier) - return removeMenuAction(it.key()); - } + for (auto it = m_mapButtons.begin(); it != m_mapButtons.end(); ++it) + { + if (it.value().identifier == plData.identifier) + return removeMenuAction(it.key()); + } - return false; + return false; } -bool LtsBaseLayoutWidget::removeMenuAction(LtsDragIcon* icon) + +bool LtsBaseLayoutWidget::removeMenuAction(LtsDragIcon *icon) { - auto it = m_mapButtons.find(icon); - if (it == m_mapButtons.end()) - return false; + auto it = m_mapButtons.find(icon); + if (it == m_mapButtons.end()) + return false; - const QString menuGroup = it->menuGroup; - const ExercisePart ep = it->exercisePart; - m_mapButtons.erase(it); + const QString menuGroup = it->menuGroup; + const ExercisePart ep = it->exercisePart; + m_mapButtons.erase(it); - icon->setParent(nullptr); - icon->deleteLater(); + icon->setParent(nullptr); + icon->deleteLater(); - checkMenuGroup(menuGroup, ep); + checkMenuGroup(menuGroup, ep); - return true; + return true; } -void LtsBaseLayoutWidget::executeAction(const QString& actionIdentifier) +void LtsBaseLayoutWidget::executeAction(const QString &actionIdentifier) { - const QList plDatas(m_mapButtons.values()); - auto it = std::find_if(plDatas.constBegin(), plDatas.constEnd(), [actionIdentifier](const PluginData& plData) { - return (plData.identifier == actionIdentifier); - }); - - if (it == plDatas.constEnd()) - return; - executePluginData(*it); + const QList plDatas(m_mapButtons.values()); + auto it = std::find_if(plDatas.constBegin(), plDatas.constEnd(), [actionIdentifier](const PluginData &plData) + { + return (plData.identifier == actionIdentifier); + }); + + if (it == plDatas.constEnd()) + return; + executePluginData(*it); } -void LtsBaseLayoutWidget::executePluginData(const PluginData& plData) + +void LtsBaseLayoutWidget::executePluginData(const PluginData &plData) { - const QString& identifier = plData.identifier; - const QString& menuGroup = plData.menuGroup; + const QString &identifier = plData.identifier; + const QString &menuGroup = plData.menuGroup; - LtsTabWidget* tab = getTabFromLayoutArea(plData.layoutArea); + LtsTabWidget *tab = getTabFromLayoutArea(plData.layoutArea); - if (!tab->focusTab(menuGroup, identifier)) - { + if (!tab->focusTab(menuGroup, identifier)) // focus widget - is there a widget to focus? no? add a new one! yes? focus and do nothing.. + { + //qWarning() << "LtsBaseLayoutWidget::onMenuEntryClicked: cannot focus - creating new widget!"; - if (plData.createWidgetFunc) - { - LtsDialog* w = plData.createWidgetFunc(this); - if (w) - { - - addWidget(w, menuGroup, identifier, plData.layoutArea, plData.closable); - } - else - { - } - } - else - { - if (plData.directFunc) - plData.directFunc(plData); - } + if (plData.createWidgetFunc) + { + LtsDialog *w = plData.createWidgetFunc(this); + if (w) + { + //qWarning() << "LtsBaseLayoutWidget::onMenuEntryClicked: adding widget!"; + addWidget(w, menuGroup, identifier, plData.layoutArea, plData.closable); + } + else + { + //qWarning() << "LtsBaseLayoutWidget::onMenuEntryClicked: no widget to add.."; + } } else { + if (plData.directFunc) + plData.directFunc(plData); } + } + else + { + //qWarning() << "LtsBaseLayoutWidget::onMenuEntryClicked: focused!"; + } } +//SLOTS void LtsBaseLayoutWidget::onMenuEntryClicked() { - LtsDragIcon* btn = qobject_cast(sender()); - if (!btn) - return; + LtsDragIcon *btn = qobject_cast(sender()); + if (!btn) + return; - if (!m_mapButtons.contains(btn)) - return; + if (!m_mapButtons.contains(btn)) + return; - executePluginData(m_mapButtons.value(btn)); + executePluginData(m_mapButtons.value(btn)); } + void LtsBaseLayoutWidget::resetLayoutVisibility() { - for (auto i = m_oldLayoutVisibilityStates.cbegin(); i != m_oldLayoutVisibilityStates.cend(); ++i) - { - const auto& tabPtr = i.key(); - if (tabPtr) - tabPtr->setVisible(i.value()); - } + for (auto i = m_oldLayoutVisibilityStates.cbegin(); i != m_oldLayoutVisibilityStates.cend(); ++i) + { + const auto &tabPtr = i.key(); + if (tabPtr) + tabPtr->setVisible(i.value()); + } - m_oldLayoutVisibilityStates.clear(); + m_oldLayoutVisibilityStates.clear(); } + void LtsBaseLayoutWidget::hideVisibleLayouts() { - if (!m_oldLayoutVisibilityStates.isEmpty()) - { - qWarning() << "LtsBaseLayoutWidget::hideVisibleLayouts: old states available - ignoring"; - return; - } + if (!m_oldLayoutVisibilityStates.isEmpty()) + { + qWarning() << "LtsBaseLayoutWidget::hideVisibleLayouts: old states available - ignoring"; + return; + } - LtsWidgets::LtsTabWidget* infoTab = getTabFromLayoutArea(LtsWidgets::LayoutArea::eInfoTab); - LtsWidgets::LtsTabWidget* specialTab = getTabFromLayoutArea(LtsWidgets::LayoutArea::eSpecialTab); - LtsWidgets::LtsTabWidget* dialogTab = getTabFromLayoutArea(LtsWidgets::LayoutArea::eDialogTab); + LtsWidgets::LtsTabWidget *infoTab = getTabFromLayoutArea(LtsWidgets::LayoutArea::eInfoTab); + LtsWidgets::LtsTabWidget *specialTab = getTabFromLayoutArea(LtsWidgets::LayoutArea::eSpecialTab); + LtsWidgets::LtsTabWidget *dialogTab = getTabFromLayoutArea(LtsWidgets::LayoutArea::eDialogTab); - m_oldLayoutVisibilityStates.insert(infoTab, infoTab->isVisible()); - m_oldLayoutVisibilityStates.insert(specialTab, specialTab->isVisible()); - m_oldLayoutVisibilityStates.insert(dialogTab, dialogTab->isVisible()); + m_oldLayoutVisibilityStates.insert(infoTab, infoTab->isVisible()); + m_oldLayoutVisibilityStates.insert(specialTab, specialTab->isVisible()); + m_oldLayoutVisibilityStates.insert(dialogTab, dialogTab->isVisible()); - if (infoTab->isVisible()) - infoTab->setVisible(false); - if (specialTab->isVisible()) - specialTab->setVisible(false); - if (dialogTab->isVisible()) - dialogTab->setVisible(false); + // hiding an invisible tab makes the splitter reduce the tab's size to 0 - only hide if visible + if (infoTab->isVisible()) + infoTab->setVisible(false); + if (specialTab->isVisible()) + specialTab->setVisible(false); + if (dialogTab->isVisible()) + dialogTab->setVisible(false); } + void LtsBaseLayoutWidget::setTopBarVisible(bool visible) { - m_ui->topLayoutWidget->setVisible(visible); + m_ui->topLayoutWidget->setVisible(visible); } + bool LtsBaseLayoutWidget::isTopBarVisible() const { - return m_ui->topLayoutWidget->isVisible(); + return m_ui->topLayoutWidget->isVisible(); } + bool LtsBaseLayoutWidget::isMenuCollapsed() const { - return m_menuCollapsed; + return m_menuCollapsed; } + void LtsBaseLayoutWidget::setMenuVisible(bool visible) { - m_ui->rightSplitter->setVisible(visible); + m_ui->rightSplitter->setVisible(visible); } + bool LtsBaseLayoutWidget::isMenuVisible() const { - return m_ui->rightSplitter->isVisible(); + return m_ui->rightSplitter->isVisible(); } + void LtsBaseLayoutWidget::collapseMenu(bool collapse) { - m_menuCollapsed = collapse; - if (collapse) - { - m_ui->masterSplitter->setSizes(m_menuSplitterSizes); - } - else - { - m_menuSplitterSizes = m_ui->masterSplitter->sizes(); - m_ui->masterSplitter->setSizes(QList() << 1 << 0); - } + m_menuCollapsed = collapse; + if (collapse) + { + m_ui->masterSplitter->setSizes(m_menuSplitterSizes); + } + else + { + m_menuSplitterSizes = m_ui->masterSplitter->sizes(); + m_ui->masterSplitter->setSizes(QList() << 1 /* main, info, etc. */ << 0 /* menu */); + } } + void LtsBaseLayoutWidget::onReShowAnimated() { - QPropertyAnimation* animation = new QPropertyAnimation(m_ui->mainSplitter, "sizes", this); - animation->setDuration(500); + QPropertyAnimation *animation = new QPropertyAnimation(m_ui->mainSplitter, "sizes", this); + animation->setDuration(500); + //Save Old Sizes - QList start = m_mainSplitterSizes; - start[getIndexOfTab(getTabFromLayoutArea(LayoutArea::eDialogTab))] = 0; + QList start = m_mainSplitterSizes; + start[getIndexOfTab(getTabFromLayoutArea(LayoutArea::eDialogTab))] = 0; - QList end = m_mainSplitterSizes; + QList end = m_mainSplitterSizes; - animation->setStartValue(QVariant::fromValue(start)); - animation->setEndValue(QVariant::fromValue(end)); + animation->setStartValue(QVariant::fromValue(start)); + animation->setEndValue(QVariant::fromValue(end)); - connect(animation, &QPropertyAnimation::finished, this, [this]() { m_currentAnimation = nullptr; }); + connect(animation, &QPropertyAnimation::finished, this, [this]() { m_currentAnimation = nullptr; }); - m_ui->detailWidget->show(); - animation->start(QAbstractAnimation::DeleteWhenStopped); - m_isHidden = false; + m_ui->detailWidget->show(); + animation->start(QAbstractAnimation::DeleteWhenStopped); + m_isHidden = false; - delete m_currentAnimation; - m_currentAnimation = animation; + delete m_currentAnimation; + m_currentAnimation = animation; } + void LtsBaseLayoutWidget::onHideAnimated() { - if (m_currentAnimation) - { - delete m_currentAnimation; - m_currentAnimation = nullptr; - } + if (m_currentAnimation) + { + delete m_currentAnimation; + m_currentAnimation = nullptr; + } - QPropertyAnimation* animation = new QPropertyAnimation(m_ui->mainSplitter, "sizes", this); - animation->setDuration(500); + QPropertyAnimation *animation = new QPropertyAnimation(m_ui->mainSplitter, "sizes", this); + animation->setDuration(500); + //Save Old Sizes + m_mainSplitterSizes = m_ui->mainSplitter->sizes(); + QList start = m_ui->mainSplitter->sizes(); - m_mainSplitterSizes = m_ui->mainSplitter->sizes(); - QList start = m_ui->mainSplitter->sizes(); + QList end = start; + end[getIndexOfTab(getTabFromLayoutArea(LayoutArea::eDialogTab))] = 1; - QList end = start; - end[getIndexOfTab(getTabFromLayoutArea(LayoutArea::eDialogTab))] = 1; + animation->setStartValue(QVariant::fromValue(start)); + animation->setEndValue(QVariant::fromValue(end)); + connect(animation, &QPropertyAnimation::finished, this, &LtsBaseLayoutWidget::hideWidgets); + connect(animation, &QPropertyAnimation::finished, this, [this]() { m_currentAnimation = nullptr; }); - animation->setStartValue(QVariant::fromValue(start)); - animation->setEndValue(QVariant::fromValue(end)); - connect(animation, &QPropertyAnimation::finished, this, &LtsBaseLayoutWidget::hideWidgets); - connect(animation, &QPropertyAnimation::finished, this, [this]() { m_currentAnimation = nullptr; }); - - animation->start(QAbstractAnimation::DeleteWhenStopped); - m_isHidden = true; - m_currentAnimation = animation; + animation->start(QAbstractAnimation::DeleteWhenStopped); + m_isHidden = true; + m_currentAnimation = animation; } + void LtsBaseLayoutWidget::retranslate() { - emit signalRetranslateActions(); - setExerciseData(m_exerciseData); - m_ui->retranslateUi(this); + emit signalRetranslateActions(); + setExerciseData(m_exerciseData); + m_ui->retranslateUi(this); + // etc. } -void LtsBaseLayoutWidget::changeEvent(QEvent* e) + +void LtsBaseLayoutWidget::changeEvent(QEvent *e) { - QWidget::changeEvent(e); - if (e->type() == QEvent::LanguageChange) - retranslate(); + QWidget::changeEvent(e); + if (e->type() == QEvent::LanguageChange) + retranslate(); } -int LtsBaseLayoutWidget::getIndexOfTab(LtsTabWidget* tab) + +int LtsBaseLayoutWidget::getIndexOfTab(LtsTabWidget *tab) { - int result = 0; + int result = 0; // emergency value - result = m_ui->masterSplitter->indexOf(tab); + result = m_ui->masterSplitter->indexOf(tab); - if (result > -1) - return result; - - result = m_ui->mainSplitter->indexOf(tab); - - if (result > -1) - return result; - - result = m_ui->rightSplitter->indexOf(tab); - - if (result > -1) - return result; - - qWarning() << "LtsBaseLayoutWidget::getIndexOfTab: tab not found in any splitter.."; + if (result > -1) // found? return result; + + + // not found? + result = m_ui->mainSplitter->indexOf(tab); + + if (result > -1) // now found? + return result; + + + // still not found? + result = m_ui->rightSplitter->indexOf(tab); + + if (result > -1) // and now? + return result; + + + qWarning() << "LtsBaseLayoutWidget::getIndexOfTab: tab not found in any splitter.."; + return result; } -LtsToolBox* LtsBaseLayoutWidget::getToolBox(const ExercisePart& exercisePart) const + +LtsToolBox* LtsBaseLayoutWidget::getToolBox(const ExercisePart &exercisePart) const { - switch (exercisePart) - { - case ExercisePart::eAfterAction: - return m_ui->naviActionsAfterAction; - case ExercisePart::eExecution: - return m_ui->naviActionsExecution; - case ExercisePart::ePlanning: - return m_ui->naviActionsPlanning; - case ExercisePart::eSpecial: - return m_ui->naviActionsSpecial; - } - Q_ASSERT(false); - return nullptr; + switch (exercisePart) + { + case ExercisePart::eAfterAction: + return m_ui->naviActionsAfterAction; + case ExercisePart::eExecution: + return m_ui->naviActionsExecution; + case ExercisePart::ePlanning: + return m_ui->naviActionsPlanning; + case ExercisePart::eSpecial: + return m_ui->naviActionsSpecial; + } + Q_ASSERT(false); + return nullptr; } -QPushButton* LtsBaseLayoutWidget::getExercisePartButton(const ExercisePart& exercisePart) const + +QPushButton* LtsBaseLayoutWidget::getExercisePartButton(const ExercisePart &exercisePart) const { - switch (exercisePart) - { - case ExercisePart::eAfterAction: - return m_ui->pbAfterAction; - case ExercisePart::eExecution: - return m_ui->pbExecution; - case ExercisePart::ePlanning: - return m_ui->pbPlanning; - case ExercisePart::eSpecial: - return m_ui->pbSpecial; - } - Q_ASSERT(false); - return nullptr; + switch (exercisePart) + { + case ExercisePart::eAfterAction: + return m_ui->pbAfterAction; + case ExercisePart::eExecution: + return m_ui->pbExecution; + case ExercisePart::ePlanning: + return m_ui->pbPlanning; + case ExercisePart::eSpecial: + return m_ui->pbSpecial; + } + Q_ASSERT(false); + return nullptr; } -void LtsBaseLayoutWidget::checkMenuGroup(const QString& menuGroup, const ExercisePart& exercisePart) + +void LtsBaseLayoutWidget::checkMenuGroup(const QString &menuGroup, const ExercisePart &exercisePart) { - QWidget* tmpW = getToolBox(exercisePart)->findChild(menuGroup); - if (!tmpW) - return; + QWidget *tmpW = getToolBox(exercisePart)->findChild(menuGroup); + if (!tmpW) + return; // should not happen #ifdef NEVER_PRINT_DEBUG - for (int i = 0; i < tmpW->children().size(); i++) - { - QObject* whatEver = tmpW->children().at(i); - const QString& name = whatEver->objectName(); - qCritical() << "MenuGroup child " << i << " : " << name; - } + for (int i = 0; i < tmpW->children().size(); i++) + { + QObject * whatEver = tmpW->children().at( i ); + const QString & name = whatEver->objectName(); + qCritical() << "MenuGroup child " << i << " : " << name; + } #endif - if (tmpW->children().size() <= 1) - delete tmpW; - checkExercisePartButtonVisibility(); + // Something is wrong here! The printing shows an additional object besides the + // LtsDragIcons of the menuGroup. + // As workaround chnage condition + // if (tmpW->children().size() == 0) to + if (tmpW->children().size() <= 1) // JT 2016/08/03 + delete tmpW; + checkExercisePartButtonVisibility(); } + void LtsBaseLayoutWidget::checkExercisePartButtonVisibility() { - if (nullptr == m_bg) - { - for (int ep = (int)ExercisePart::ePlanning; ep <= (int)ExercisePart::eSpecial; ++ep) - { - getExercisePartButton(static_cast(ep))->setVisible(false); - } - return; - } - - int visibleButtons = 0; - ExercisePart lastVisibleButton = ExercisePart::ePlanning; + if (nullptr == m_bg) + { for (int ep = (int)ExercisePart::ePlanning; ep <= (int)ExercisePart::eSpecial; ++ep) { - bool visible = getToolBox((ExercisePart)ep)->children().count() > 1; - getExercisePartButton((ExercisePart)ep)->setVisible(visible); - if (visible) - { - ++visibleButtons; - lastVisibleButton = (ExercisePart)ep; - } + getExercisePartButton(static_cast(ep))->setVisible(false); } - if (visibleButtons == 0) - lastVisibleButton = ExercisePart::eSpecial; - getExercisePartButton(lastVisibleButton)->setChecked(true); - getExercisePartButton(lastVisibleButton)->setVisible(visibleButtons > 1); + return; + } + + int visibleButtons = 0; + ExercisePart lastVisibleButton = ExercisePart::ePlanning; + for (int ep = (int) ExercisePart::ePlanning; ep <= (int) ExercisePart::eSpecial; ++ep) + { + bool visible = getToolBox((ExercisePart) ep)->children().count() > 1; + getExercisePartButton((ExercisePart) ep)->setVisible(visible); + if (visible) + { + ++visibleButtons; + lastVisibleButton = (ExercisePart) ep; + } + } + if (visibleButtons == 0) + lastVisibleButton = ExercisePart::eSpecial; + getExercisePartButton(lastVisibleButton)->setChecked(true); + getExercisePartButton(lastVisibleButton)->setVisible(visibleButtons > 1); } + bool LtsBaseLayoutWidget::isWidgetsHidden() const { - return m_ui->detailWidget->isVisible(); + return m_ui->detailWidget->isVisible(); } + void LtsBaseLayoutWidget::showWidgets() { - m_ui->detailWidget->show(); + m_ui->detailWidget->show(); } + void LtsBaseLayoutWidget::hideWidgets() { - m_ui->detailWidget->hide(); + m_ui->detailWidget->hide(); } -LtsDragIcon* LtsBaseLayoutWidget::createButton(const PluginData& plData) + +LtsDragIcon *LtsBaseLayoutWidget::createButton(const PluginData &plData) { + // TODO: really nullptr? + LtsDragIcon *tmpBtn = new LtsDragIcon(nullptr); + tmpBtn->setObjectName(plData.identifier); + tmpBtn->setButtonStyle(LtsWidgets::ButtonStyle::eTextNextToIcon); + tmpBtn->setIcon(plData.menuIcon); + tmpBtn->setContext(plData.menuGroup); + tmpBtn->setText(plData.menuText); + if (!plData.tooltip.isEmpty()) + tmpBtn->setToolTip(plData.tooltip); + tmpBtn->setDropHandlerKey(plData.dropHandlerKey); + tmpBtn->setIdentifier(plData.identifier); - LtsDragIcon* tmpBtn = new LtsDragIcon(nullptr); - tmpBtn->setObjectName(plData.identifier); - tmpBtn->setButtonStyle(LtsWidgets::ButtonStyle::eTextNextToIcon); - tmpBtn->setIcon(plData.menuIcon); - tmpBtn->setContext(plData.menuGroup); - tmpBtn->setText(plData.menuText); - if (!plData.tooltip.isEmpty()) - tmpBtn->setToolTip(plData.tooltip); - tmpBtn->setDropHandlerKey(plData.dropHandlerKey); - tmpBtn->setIdentifier(plData.identifier); + connect(tmpBtn, &QWidget::destroyed, + this, []() + { + qDebug() << "LtsDragIcon was destroyed"; + }); - connect(tmpBtn, &QWidget::destroyed, this, []() { qDebug() << "LtsDragIcon was destroyed"; }); - - connect(tmpBtn, &LtsDragIcon::clicked, this, &LtsBaseLayoutWidget::onMenuEntryClicked); - return tmpBtn; + connect(tmpBtn, &LtsDragIcon::clicked, this, &LtsBaseLayoutWidget::onMenuEntryClicked); + return tmpBtn; } -LtsToolBarArea* LtsBaseLayoutWidget::getToolbar() const + +LtsToolBarArea * LtsBaseLayoutWidget::getToolbar() const { - return m_ui->toolBar; + return m_ui->toolBar; } -QWidget* LtsBaseLayoutWidget::getMenu() const + +QWidget *LtsBaseLayoutWidget::getMenu() const { - return m_ui->naviWidget; + return m_ui->naviWidget; } -LtsTabWidget* LtsBaseLayoutWidget::getTabFromLayoutArea(LayoutArea area) const + +LtsTabWidget *LtsBaseLayoutWidget::getTabFromLayoutArea(LayoutArea area) const { - switch (area) - { - case LayoutArea::eDialogTab: - return m_ui->detailWidget; - case LayoutArea::eInfoTab: - return m_ui->infoWidget; - case LayoutArea::eSpecialTab: - return m_ui->specialWidget; - case LayoutArea::eMainTab: - return m_ui->mainWidget; - case LayoutArea::eUnknown: - return m_ui->detailWidget; - } - return nullptr; + switch (area) + { + case LayoutArea::eDialogTab: + return m_ui->detailWidget; + case LayoutArea::eInfoTab: + return m_ui->infoWidget; + case LayoutArea::eSpecialTab: + return m_ui->specialWidget; + case LayoutArea::eMainTab: + return m_ui->mainWidget; + case LayoutArea::eUnknown: // better than returning a 0ptr + return m_ui->detailWidget; + } + return nullptr; } + void LtsBaseLayoutWidget::showNextQueuedMessage() { - if (m_messageQueue.isEmpty()) - { - return; - } + if (m_messageQueue.isEmpty()) + { + return; + } - const Message m = m_messageQueue.takeLast(); + const Message m = m_messageQueue.takeLast(); - showMessage(m.title, m.text, m.type, m.clickedLinkCallback, m.closeOnLinkClicked, m.identifier); + showMessage(m.title, m.text, m.type, m.clickedLinkCallback, m.closeOnLinkClicked, m.identifier); } -void LtsBaseLayoutWidget::removeQueuedMessage(const QString& messageIdentifier) + +void LtsBaseLayoutWidget::removeQueuedMessage(const QString &messageIdentifier) { - if (messageIdentifier.isEmpty()) + if (messageIdentifier.isEmpty()) // empty / unset identifiers can't be removed + { + return; + } + + m_messageQueue.erase(std::remove_if(m_messageQueue.begin(), m_messageQueue.end(), [messageIdentifier](const Message &m) // remove all queued messages with the same identifier + { + return (m.identifier == messageIdentifier); + }), m_messageQueue.end()); + + if (!m_currentMessage.isEmpty()) + { + if (m_currentMessage.first().identifier == messageIdentifier) { - return; - } - - m_messageQueue.erase( - std::remove_if(m_messageQueue.begin(), m_messageQueue.end(), - [messageIdentifier](const Message& m) { return (m.identifier == messageIdentifier); }), - m_messageQueue.end()); - - if (!m_currentMessage.isEmpty()) - { - if (m_currentMessage.first().identifier == messageIdentifier) - { - - m_currentMessage.clear(); - m_notiBox->hide(); - showNextQueuedMessage(); - } + // this is the current active message - hide it and call show next queued message (if any) + m_currentMessage.clear(); + m_notiBox->hide(); + showNextQueuedMessage(); } + } } -void LtsBaseLayoutWidget::showMessage(const QString& title, const QString& text, LtsNotificationBox::MessageType type, - const std::function& clickedLinkCallback, - bool closeOnLinkClicked, const QString& identifier) + +void LtsBaseLayoutWidget::showMessage(const QString &title, const QString &text, LtsNotificationBox::MessageType type, const std::function &clickedLinkCallback, bool closeOnLinkClicked, const QString &identifier) { - if (m_notiBox == nullptr) + if (m_notiBox == nullptr) + { + m_notiBox = new LtsNotificationBox; + + connect(m_notiBox, &LtsNotificationBox::signalLinkClicked, + this, [this, closeOnLinkClicked, clickedLinkCallback](const QString &link) { - m_notiBox = new LtsNotificationBox; + // qWarning() << "link" << link; - connect(m_notiBox, &LtsNotificationBox::signalLinkClicked, this, - [this, closeOnLinkClicked, clickedLinkCallback](const QString& link) { - auto* event = new LtsLinkEvent(QUrl(link), this); - event->setAccepted(false); - QApplication::postEvent(qApp, event); + auto *event = new LtsLinkEvent(QUrl(link), this); + event->setAccepted(false); + QApplication::postEvent(qApp, event); // receive link events by overriding eventFilter of your *parented* QObject class - if (clickedLinkCallback) - clickedLinkCallback(link); + if (clickedLinkCallback) + clickedLinkCallback(link); - if (closeOnLinkClicked) - { - m_notiBox->hide(); - m_currentMessage.clear(); - showNextQueuedMessage(); - } - }); + if (closeOnLinkClicked) + { + m_notiBox->hide(); + m_currentMessage.clear(); + showNextQueuedMessage(); // show next message (if any) after closing current message + } + }); - connect(m_notiBox, &QObject::destroyed, this, [this]() { - if (qobject_cast(sender()) == m_notiBox) - m_notiBox = nullptr; - }); - - connect(m_notiBox, &LtsNotificationBox::signalClose, this, [this]() { - m_notiBox->hide(); - m_currentMessage.clear(); - showNextQueuedMessage(); - }); - - connect(m_notiBox, &LtsNotificationBox::signalAck, this, [this]() { - auto* event = new LtsLinkEvent( - QUrl(QStringLiteral("lts://NotificationAck/%1").arg(m_currentMessage.first().identifier)), this); - event->setAccepted(false); - QApplication::postEvent(qApp, event); - - m_notiBox->hide(); - m_currentMessage.clear(); - showNextQueuedMessage(); - }); - - m_notiBox->setParent(this); - m_notiBox->setGeometry(0, 0, m_notiBox->width(), m_notiBox->height()); - } - - m_messageQueue.erase(std::remove_if(m_messageQueue.begin(), m_messageQueue.end(), - [identifier](const Message& m) { - return (!identifier.isEmpty() && m.identifier == identifier); - }), - m_messageQueue.end()); - - if (!m_currentMessage.isEmpty()) + connect(m_notiBox, &QObject::destroyed, + this, [this]() { - const auto m = m_currentMessage.takeFirst(); - if (identifier.isEmpty() || m.identifier != identifier) - { - m_messageQueue += m; - } + if (qobject_cast(sender()) == m_notiBox) + m_notiBox = nullptr; + }); + + connect(m_notiBox, &LtsNotificationBox::signalClose, + this, [this]() + { + m_notiBox->hide(); + m_currentMessage.clear(); + showNextQueuedMessage(); // show next message (if any) after closing current message + }); + + connect(m_notiBox, &LtsNotificationBox::signalAck, + this, [this]() + { + auto *event = new LtsLinkEvent(QUrl(QStringLiteral("lts://NotificationAck/%1").arg(m_currentMessage.first().identifier)), this); + event->setAccepted(false); + QApplication::postEvent(qApp, event); // send link event to tell NotificationManagement to ack this notification + + m_notiBox->hide(); + m_currentMessage.clear(); + showNextQueuedMessage(); // show next message (if any) after closing current message + }); + + m_notiBox->setParent(this); + m_notiBox->setGeometry(0, 0, m_notiBox->width(), m_notiBox->height()); + } + + + m_messageQueue.erase(std::remove_if(m_messageQueue.begin(), m_messageQueue.end(), [identifier](const Message &m) // remove all queued messages with the same identifier (if not empty) + { + return (!identifier.isEmpty() && m.identifier == identifier); + }), m_messageQueue.end()); + + if (!m_currentMessage.isEmpty()) + { + const auto m = m_currentMessage.takeFirst(); + if (identifier.isEmpty() || m.identifier != identifier) // replace current message with new message if identifier is same (and not empty) + { + m_messageQueue += m; } + } - m_currentMessage += Message({title, text, type, clickedLinkCallback, closeOnLinkClicked, identifier}); + m_currentMessage += Message({ title, text, type, clickedLinkCallback, closeOnLinkClicked, identifier }); - m_notiBox->message(title, text, type); + m_notiBox->message(title, text, type); - auto* animation = new QPropertyAnimation(m_notiBox, "geometry"); - connect(animation, &QPropertyAnimation::finished, animation, &QObject::deleteLater); - animation->setDuration(700); - animation->setStartValue(QRect(width() + 10, height() + 10, m_notiBox->width(), m_notiBox->height())); - animation->setEndValue(QRect(width() - m_notiBox->width() - 15, height() - m_notiBox->height() - 15, - m_notiBox->width(), m_notiBox->height())); - animation->setEasingCurve(QEasingCurve::OutElastic); - animation->start(QAbstractAnimation::DeleteWhenStopped); + + // TODO: ahtc set new x on resize + auto *animation = new QPropertyAnimation(m_notiBox, "geometry"); + connect(animation, &QPropertyAnimation::finished, animation, &QObject::deleteLater); + animation->setDuration(700); + animation->setStartValue(QRect(width() + 10, height() + 10, m_notiBox->width(), m_notiBox->height())); + animation->setEndValue(QRect(width() - m_notiBox->width() - 15, height() - m_notiBox->height() - 15, m_notiBox->width(), m_notiBox->height())); + animation->setEasingCurve(QEasingCurve::OutElastic); + animation->start(QAbstractAnimation::DeleteWhenStopped); } -bool LtsBaseLayoutWidget::messageIdentifierExists(const QString& identifier) const + +bool LtsBaseLayoutWidget::messageIdentifierExists(const QString &identifier) const { - if (identifier.isEmpty()) - { - return false; - } - - if (!m_currentMessage.isEmpty() && m_currentMessage.first().identifier == identifier) - { - return true; - } - - for (const Message& m : std::as_const(m_messageQueue)) - { - if (m.identifier == identifier) - { - return true; - } - } - + if (identifier.isEmpty()) // empty / unset identifiers never exist + { return false; + } + + if (!m_currentMessage.isEmpty() && m_currentMessage.first().identifier == identifier) + { + return true; + } + + for (const Message &m : qAsConst(m_messageQueue)) + { + if (m.identifier == identifier) + { + return true; + } + } + + return false; } } // namespace LtsWidgets + + + + + + + + + + + + + + + + + + + +// diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_base_layout_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_base_layout_widget.h index bde6282b0..78faf69a3 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_base_layout_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_base_layout_widget.h @@ -1,16 +1,23 @@ - +/** +* @RDE_HEADER@ +* Base Layout Widget with all Areas (Info, Main, Detail, Menu) +* $Id$ +* $HeadURL$ +* $Author$ +*/ #pragma once + #include "lts_base.h" -#include "lts_notification_box.h" #include "lts_widgets_export.h" +#include "lts_notification_box.h" #include "qevent.h" +#include #include -#include #include #include -#include + class QButtonGroup; class QPropertyAnimation; @@ -28,10 +35,7 @@ namespace IDL enum class PartitionType; } -namespace LtsUtils -{ -class Promise; -} +namespace LtsUtils { class Promise; } namespace LtsWidgets { @@ -43,253 +47,404 @@ class LtsToolBox; struct ExerciseData { - QString exName; - QString exDescription; - int phId = -1; - QString phName; - QString phDescription; - QString exStateString; - ExcState exState = ExerciseState::eUnknown; - QColor exStateCol; - QString partitionType; + QString exName; + QString exDescription; + int phId = -1; + QString phName; + QString phDescription; + QString exStateString; // Already translated. Todo: Probably won't change, if Language is changed on the fly. + ExcState exState = ExerciseState::eUnknown; + QColor exStateCol; + QString partitionType; - bool operator==(const ExerciseData& o) const - { - return exName == o.exName && exDescription == o.exDescription && phId == o.phId && phName == o.phName && - phDescription == o.phDescription && exStateString == o.exStateString && exState == o.exState && - exStateCol == o.exStateCol && partitionType == o.partitionType; - } + bool operator==(const ExerciseData &o) const + { + return exName == o.exName && + exDescription == o.exDescription && + phId == o.phId && + phName == o.phName && + phDescription == o.phDescription && + exStateString == o.exStateString && + exState == o.exState && + exStateCol == o.exStateCol && + partitionType == o.partitionType; + } + bool operator!=(const ExerciseData &o) const + { + return !operator ==(o); + } - bool operator!=(const ExerciseData& o) const - { - return !operator==(o); - } }; + +/** + * @brief The LtsBaseLayoutWidget class represents the Patric-Layout-System (all Areas: Info, Main, Detail, Menu), which is used as stand-alone widget per Screen. + * It is created per Session by the LtsSession, created by the LtsSessionManager whenever a new Session was created. + */ class LTSWIDGETS_EXPORT LtsBaseLayoutWidget : public QWidget { - Q_OBJECT + Q_OBJECT +public: + + explicit LtsBaseLayoutWidget(QWidget *parent = nullptr, bool splitMenu = true); + ~LtsBaseLayoutWidget(); + + /** + * @brief hideVisibleLayouts hides all layouts without interfering layout sizes and saves all layout's old states that can be restored by calling resetLayoutVisibility + */ + void hideVisibleLayouts(); + + /** + * @brief resetLayoutVisibility reverts the actions done by hideVisibleLayouts - reshows all hidden layouts + */ + void resetLayoutVisibility(); + + /** + * @brief setMenuVisible sets the visibility of the menu (and the special tab, too!) + * @param visible true to reshow the menu and special tab, false to completely hide them + */ + void setMenuVisible(bool visible); + + /** + * @brief isMenuVisible returns the visibility state of the menu (and special tab, too!) + * @return true if both are visibly, false if not + */ + bool isMenuVisible() const; + + bool isTopBarVisible() const; + void setTopBarVisible(bool visible); + + /** + * @brief isMenuCollapsed returns if the menu was collapsed programmatically by calling clappseMenu. + * NOTE: does not consider the collapsed state if the user collapsed the menu himself by reducing the menu size to zero by moving the splitter. + * @return true is collapsed before, false if menu is not size zero. + */ + bool isMenuCollapsed() const; + + /** + * @brief collapseMenu reduces the size of the menu to zero, but the visibility doesn't change, so that the user can still restore the menu with the splitter. + * NOTE: the special tab widget is collapsed, too. + * @param collapse true to collapse, false to restore to the state before the collapse. + */ + void collapseMenu(bool collapse = true); + + /** + * @brief setSessionInfo sets the informations about the Session of this BaseLayout, so that the window can request a Session close (by logging out) when this window receives a close request. + */ + void setSessionInfo(const int domainId, const IDL::PartitionType &partitionType, const int partitionId, const QString &workspaceId); + + /** + * @brief addMenuAction adds an action (aka. menu entry) to the menu layout. The Action will be added into the given group. + * @param plData Action data with information about where to put the menu entry and what to do when the menu entry is clicked + * @return the LtsDragIcon that was now created and put into the menu layout + */ + LtsDragIcon *addMenuAction(const PluginData &plData, bool isFirstRun = false); + + /** + * @brief removeMenuAction removes an action (aka. menu entry) previously created by the addMenuAction method by identifying it by the information in the given plData + * @param plData Action data to identify the menu entry with (group name + captioin text of the menu entry) + * @return true when found & deleted, false when not found and also not deleted + */ + bool removeMenuAction(const PluginData &plData); + + /** + * @brief removeMenuAction removes an action (aka. menu entry) previously created by the addMenuAction method by identifying it by the pointer value + * @param icon to identify the action (aka. menu entry) by the menu entry the LtsDragIcon that was created by the addMenuAction method and put into the menu layout + * @return true when found & deleted, false when not found and also not deleted (as it was deleted before) + */ + bool removeMenuAction(LtsDragIcon *icon); + + bool removeMenuAction(const QString &byIdentifier); + + /** + * @brief clearMenuActions deletes all actions (aka. menu entries) in the menu layout + */ + void clearMenuActions(); + + void setAppName(const QString &appName); + bool isDialogFocused(const LtsDialog *dialog) const; + + /** + * @brief setCustomText shows a custom text to the top layout of the base layout, right after the partition type text. + * Also prepends a bullet before the text to clearly differenciate between the partition type text and the custom text. + * Call with an empty string to hide the custom text again. + * @param text to print on the label + */ + void setCustomText(const QString &text); + const QString customText() const; + + /** + * @brief getTabFromLayoutArea returns the pointer to the LtsTabWidget that is of the type LayoutArea 'area' + * @param area the area of which the LtsTabWidget's type of + * @return the pointer to the LtsTabWidget + */ + LtsTabWidget *getTabFromLayoutArea(LayoutArea area) const; + + /** TODO: rename to getDialog + * @brief getWidget returns the Dialog which is located in the given LayoutArea, identified by the group + identifier strings + * @param menuGroup the name of the main tab of the LayoutArea + * @param identifier the name of the sub tab (when sub-tabbed) of the LayoutArea, otherwise the identifier is added to the menuGroup string + * @param area the LayoutArea (/LtsTabWidget) the Dialog is located + * @return the LtsDialog when found, otherwise nullptr when not found + */ + LtsDialog *getWidget(const QString &menuGroup, const QString &identifier, LayoutArea area = LayoutArea::eUnknown); + + /** + * @brief getMenu returns the Widget of the Menu Layout Area (as the Menu is not an actual LayoutArea (not an LtsTabWidget which could be returned by 'getTabFromLayoutArea') + * @return the pointer to the Widget of the Menu Layout + */ + QWidget *getMenu() const; + + /** + * @brief getToolbar returns the LtsToolBarArea of the Menu Layout Area + * @return the pointer to the LtsToolBarArea of the Menu Layout + */ + LtsToolBarArea *getToolbar() const; + + /** + * @brief setOperatorName sets the operator name of this session's operator and sets the operator name widget's text + * @param operatorName the human readable operator name of this session's operator + */ + void setOperatorName(const QString &operatorName, bool showTerminalButton); + + /** + * @brief setProfilePicture sets the profile picture of this session's operator and sets the profile picture widget's picture + * @param profilePicture the profgile picture of this session's operator + */ + void setProfilePicture(const QPixmap &profilePicture); + + /** + * @brief setExerciseData sets the name and phase of this Exercise (if it is an Exercise) of this session - only sets the text of a label (label is hidden of not set) + * @param exerciseData necessary data to show + */ + void setExerciseData(const ExerciseData &data); + + /** + * @brief Call this function when the base layout was properly constructed so baselayout can do some internal stuff + */ + void initilizationFinished(); + + /** + * @brief addNotification [Do not use.] used by LtsSession to add a Notification to the Notification Bar, but as a QToolButton + * @param noti the noti to add to the Notification Bar + */ + void addNotification(QToolButton *noti); + + /** + * @brief isWidgetsHidden returns the visibility state of the detail tab - the state changes with calling either of + * these methods: onReShowAnimated, onHideAnimated, showWidgets, hideWidgets + * @return detail tab visible (not to be confused with resizing the detail widget with the splitter, that only + * minized the tab, but the tab is still visible) + */ + bool isWidgetsHidden() const; + + bool notificationExists(const QString &identifier) const; + const QMap &mapButtons() const { return m_mapButtons; } + void setToolBarActions(const QStringList &actions); + QStringList toolBarActions() const; + void setFunctionKeys(const QMap &actions); + QMap functionKeys() const; + void setWorkspaceId(const QString &workspaceId) { m_workspaceId = workspaceId; } + + /** + * @brief showMessage adds a notification bubble to the bottom right of the blw. Text can be formatted with HTML. + * If a message is already visible, it will be replaced and will be shown after the new message was closed. + * A message with the same identifier will be replaced in the queue or if currently shown. + * @param title The title in bold which is show obove the text. + * @param text The text to show in the bubble - should be as short as possible as bubbles are small. Can be HTML. + * @param type The type which sets the color and icon the bubble should have. See LtsNotificationBox::MessageType. + * @param clickedLinkCallback The function to call if a link inside the bubble has been clicked (HTML 'a' tag) + * @param closeOnLinkClicked Closes the bubble if a link has been clicked. Note: queued messages (if any) will be shown next + * @param identifier An invisible identifier a message will be queued with. Can be left empty. If another message with the + * same identifier (if not empty) is shown, the other message with the same identifier will be removed from the queue or if + * it's the shown message, it will be closed. + */ + void showMessage(const QString &title, const QString &text, LtsNotificationBox::MessageType type = LtsNotificationBox::MessageType::Info, const std::function &clickedLinkCallback = nullptr, bool closeOnLinkClicked = true, const QString &identifier = {}); + bool messageIdentifierExists(const QString &identifier) const; + + void executeAction(const QString &actionIdentifier); + bool isSecondaryWidget() const { return m_isSecondaryWidget; } // for the LtsScreenContainer to determine if this is a 'Hilfsansicht' for GUEZ SWP 2023 (https://devhub.defence-elec.de/confluence/x/yLjeDg) (siehe 1.1.1) + void setSecondaryWidget() { m_isSecondaryWidget = true; } + + /** + + * @brief Remove Messages from Queue, as it's handled by someones else + * @param message identifier to remote from que or diplay. + */ + void removeQueuedMessage(const QString &messageIdentifier); + + +public slots: + bool slotClose(); // checks for unsaved changes first and aborts if there are any + void slotLogout(); // checks for unsaved changes first and aborts if there are any + + void slotScreenCountChanged(int count); + + /** + * @brief onMenuEntryClicked is triggered when an action (aka. menu entry) in the menu layout is clicked, executes the action's payload (or focuses the coherant dialog when already open) + */ + void onMenuEntryClicked(); + + void onHideAnimated(); + void onReShowAnimated(); + + /** + * @brief addWidget adds a widget to the operator-specified base layout (either selection by cursor or by permanent selectioin) NOTE: deletes dialog if it already exists + * @param widget the Dialog to be added + * @param menuGroup the main tab identified by 'menuGroup' (tab is created when tab not existent) to add the Dialog into + * @param identifier the sub tab (when LtsTabWidget is sub-tabbed, otherwise only added to tab identified by menuGroup + identifier), identified by 'identifier' to add the Dialog into - keep empty to prevent checking for existing tabs + * @param area the LayoutArea to add the Dialog into + * @param setClosable true when closable by operator (shows a close-button in the tab), false when not closable by operator + * @return true when added, false when not (invalid widget or non-existant LayoutArea) + */ + bool addWidget(LtsWidgets::LtsDialog *dialog, const QString &menuGroup, const QString &identifier, LtsWidgets::LayoutArea area = LayoutArea::eUnknown, bool setClosable = true, bool focusNewTab = true); + + /** + * @brief Like addWidget addOrReplaceWidget adds a dialog widget to base layout with the difference that an existing widget with same identifier is removed from layout before adding he new one. + * The new dialog will not be deleted (compare with adddWidget) + * @param widget the Dialog to be added + * @param menuGroup the main tab identified by 'menuGroup' (tab is created when tab not existent) to add the Dialog into + * @param identifier the sub tab (when LtsTabWidget is sub-tabbed, otherwise only added to tab identified by menuGroup + identifier), identified by 'identifier' to add the Dialog into - keep empty to prevent checking for existing tabs + * @param area the LayoutArea to add the Dialog into + * @param setClosable true when closable by operator (shows a close-button in the tab), false when not closable by operator + * @return true when added, false when not (invalid widget or non-existant LayoutArea) + * @see addWidget + */ + bool addOrReplaceWidget(LtsDialog *dialog, const QString &menuGroup, const QString &identifier, LayoutArea area = LayoutArea::eUnknown, bool setClosable = true, bool focusNewTab = true ); + + bool focusTab(const QString &menuGroup, const QString &identifier, LtsWidgets::LayoutArea area); + + /** + * @brief executeCreateInstantFunctions executes both the createWidgetFunc and the directFunc (if available). (only used by LtsSession & this addMenuAction) + * @param plData + */ + void executeCreateInstantFunctions(const LtsWidgets::PluginData &plData); + + void setExerciseTime(qint64 mSecsSinceEpoch); + bool haveUnsavedChanges(); + + + + /** + * @brief notifyUnsavedChanges + * @return true if there were NO unsaved changes (method 'failed') and vice versa + * + */ + bool notifyUnsavedChanges(); + +// LtsUtils::Promise *notifyUnsavedChangesAsync(); + + void setIrreplaceableOnce() { m_irreplaceableOnce = true; } + bool irreplaceableReset() { bool r = m_irreplaceableOnce; m_irreplaceableOnce = false; return r; } + bool isIrreplaceable() const { return m_irreplaceableOnce; } + + /** + * @brief showWidgets shows the Dialog Layout again after it was previously hidden + */ + void showWidgets(); + + /** + * @brief hideWidgets hides the visible Dialog Layout (for example e.g. when more space is needed for selection on the map) + */ + void hideWidgets(); + + +private slots: + /** + * @brief slotOperatorMenuClicked shows a menu to change things affecting the operator (logout, etc.) + */ + void slotOperatorMenuClicked(); + + void setCurrentTime(); + + +signals: + /** + * @brief signalCloseRequest is emitted by the closeEvent and requests a logout / close of the current Session (if this is the last BaseLayout) + */ + //void signalCloseRequest(const int domainId, const IDL::PartitionType &partitionType, const int partitionId); + + void signalClose(); + void signalLogout(); + void signalShowOperatorSettings(); + void signalRetranslateActions(); + void signalSwap(); + void signalStapleTopicLockHandler(LtsWidgets::LtsDialog *widget); + void signalSuccessfullyPlaced(); // called by MMM if this widget was successfully placed (even works if MMM is inactive (off)) + + /** + * Notify about unsaved changes before popup message box. + */ + void signalNotifyUnsavedChanges(bool &reject); + +protected: + /** + * @brief closeEvent requests to close a session. As a BaseLayout is linked to a Session, the Session must be closed before allowing + * the BaseLayout to close. So a logout is executed before closing the BaseLayout. + * TODO: One or more BaseLayouts can be linked to a Session - look if it's the last BaseLayout + * @param event + */ + void closeEvent(QCloseEvent *event) override; + + void showEvent(QShowEvent *event) override; + void changeEvent(QEvent *e) override; + + +private: + void addDebugMenu(); + void retranslate(); + void addTouchScroll(QWidget *widget); + LtsDragIcon *createButton(const PluginData &plData); + int getIndexOfTab(LtsTabWidget *tab); + LtsToolBox *getToolBox(const ExercisePart &exercisePart) const; + QPushButton *getExercisePartButton(const ExercisePart &exercisePart) const; + void checkExercisePartButtonVisibility(); + void checkMenuGroup(const QString &menuGroup, const ExercisePart &exercisePart); + bool isDialogFocused(const LtsDialog *dialog, const LayoutArea &layoutArea) const; + bool isDialogFocused(const LtsDialog *dialog, const LtsTabWidget *tab) const; + void applyExerciseStateRestricition(); + void executePluginData(const PluginData &plData); + void showNextQueuedMessage(); + //void removeQueuedMessage(const QString &messageIdentifier); + + struct Message + { public: - explicit LtsBaseLayoutWidget(QWidget* parent = nullptr, bool splitMenu = true); - ~LtsBaseLayoutWidget(); + QString title; + QString text; + LtsNotificationBox::MessageType type; + std::function clickedLinkCallback; + bool closeOnLinkClicked; + QString identifier; + }; - void hideVisibleLayouts(); - - void resetLayoutVisibility(); - - void setMenuVisible(bool visible); - - bool isMenuVisible() const; - - bool isTopBarVisible() const; - void setTopBarVisible(bool visible); - - bool isMenuCollapsed() const; - - void collapseMenu(bool collapse = true); - - void setSessionInfo(const int domainId, const IDL::PartitionType& partitionType, const int partitionId, - const QString& workspaceId); - - LtsDragIcon* addMenuAction(const PluginData& plData, bool isFirstRun = false); - - bool removeMenuAction(const PluginData& plData); - - bool removeMenuAction(LtsDragIcon* icon); - - bool removeMenuAction(const QString& byIdentifier); - - void clearMenuActions(); - - void setAppName(const QString& appName); - bool isDialogFocused(const LtsDialog* dialog) const; - - void setCustomText(const QString& text); - const QString customText() const; - - LtsTabWidget* getTabFromLayoutArea(LayoutArea area) const; - - LtsDialog* getWidget(const QString& menuGroup, const QString& identifier, LayoutArea area = LayoutArea::eUnknown); - - QWidget* getMenu() const; - - LtsToolBarArea* getToolbar() const; - - void setOperatorName(const QString& operatorName, bool showTerminalButton); - - void setProfilePicture(const QPixmap& profilePicture); - - void setExerciseData(const ExerciseData& data); - - void initilizationFinished(); - - void addNotification(QToolButton* noti); - - bool isWidgetsHidden() const; - - bool notificationExists(const QString& identifier) const; - - const QMap& mapButtons() const - { - return m_mapButtons; - } - - void setToolBarActions(const QStringList& actions); - QStringList toolBarActions() const; - void setFunctionKeys(const QMap& actions); - QMap functionKeys() const; - - void setWorkspaceId(const QString& workspaceId) - { - m_workspaceId = workspaceId; - } - - void showMessage(const QString& title, const QString& text, - LtsNotificationBox::MessageType type = LtsNotificationBox::MessageType::Info, - const std::function& clickedLinkCallback = nullptr, - bool closeOnLinkClicked = true, const QString& identifier = {}); - bool messageIdentifierExists(const QString& identifier) const; - - void executeAction(const QString& actionIdentifier); - - bool isSecondaryWidget() const - { - return m_isSecondaryWidget; - } - - void setSecondaryWidget() - { - m_isSecondaryWidget = true; - } - - void removeQueuedMessage(const QString& messageIdentifier); - - public slots: - bool slotClose(); - void slotLogout(); - - void slotScreenCountChanged(int count); - - void onMenuEntryClicked(); - - void onHideAnimated(); - void onReShowAnimated(); - - bool addWidget(LtsWidgets::LtsDialog* dialog, const QString& menuGroup, const QString& identifier, - LtsWidgets::LayoutArea area = LayoutArea::eUnknown, bool setClosable = true, - bool focusNewTab = true); - - bool addOrReplaceWidget(LtsDialog* dialog, const QString& menuGroup, const QString& identifier, - LayoutArea area = LayoutArea::eUnknown, bool setClosable = true, bool focusNewTab = true); - - bool focusTab(const QString& menuGroup, const QString& identifier, LtsWidgets::LayoutArea area); - - void executeCreateInstantFunctions(const LtsWidgets::PluginData& plData); - - void setExerciseTime(qint64 mSecsSinceEpoch); - bool haveUnsavedChanges(); - - bool notifyUnsavedChanges(); - - void setIrreplaceableOnce() - { - m_irreplaceableOnce = true; - } - - bool irreplaceableReset() - { - bool r = m_irreplaceableOnce; - m_irreplaceableOnce = false; - return r; - } - - bool isIrreplaceable() const - { - return m_irreplaceableOnce; - } - - void showWidgets(); - - void hideWidgets(); - - private slots: - - void slotOperatorMenuClicked(); - - void setCurrentTime(); - - signals: - - void signalClose(); - void signalLogout(); - void signalShowOperatorSettings(); - void signalRetranslateActions(); - void signalSwap(); - void signalStapleTopicLockHandler(LtsWidgets::LtsDialog* widget); - void signalSuccessfullyPlaced(); - - void signalNotifyUnsavedChanges(bool& reject); - - protected: - void closeEvent(QCloseEvent* event) override; - - void showEvent(QShowEvent* event) override; - void changeEvent(QEvent* e) override; - - private: - void addDebugMenu(); - void retranslate(); - void addTouchScroll(QWidget* widget); - LtsDragIcon* createButton(const PluginData& plData); - int getIndexOfTab(LtsTabWidget* tab); - LtsToolBox* getToolBox(const ExercisePart& exercisePart) const; - QPushButton* getExercisePartButton(const ExercisePart& exercisePart) const; - void checkExercisePartButtonVisibility(); - void checkMenuGroup(const QString& menuGroup, const ExercisePart& exercisePart); - bool isDialogFocused(const LtsDialog* dialog, const LayoutArea& layoutArea) const; - bool isDialogFocused(const LtsDialog* dialog, const LtsTabWidget* tab) const; - void applyExerciseStateRestricition(); - void executePluginData(const PluginData& plData); - void showNextQueuedMessage(); - - struct Message - { - public: - QString title; - QString text; - LtsNotificationBox::MessageType type; - std::function clickedLinkCallback; - bool closeOnLinkClicked; - QString identifier; - }; - - ExerciseData m_exerciseData; - QMap m_mapButtons; - QList m_mainSplitterSizes; - QList m_menuSplitterSizes; - bool m_isHidden; - QPropertyAnimation* m_currentAnimation{nullptr}; - Ui::LtsBaseLayoutWidget* m_ui{nullptr}; - IDL::PartitionType m_partitionType; - int m_domainId; - int m_partitionId; - QString m_operatorName; - bool m_firstShow; - bool m_showTerminalButton; - qint64 m_exerciseTime; - QTimer* m_setCurrentTimeTimer{nullptr}; - bool m_irreplaceableOnce; - QButtonGroup* m_bg{nullptr}; - QString m_workspaceId; - int m_screenCount; - bool m_menuCollapsed; - QMap, bool> m_oldLayoutVisibilityStates; - LtsNotificationBox* m_notiBox{nullptr}; - QStringList m_notFoundYet; - bool m_isSecondaryWidget{false}; - QVector m_currentMessage; - QVector m_messageQueue; + ExerciseData m_exerciseData; + QMap m_mapButtons; + QList m_mainSplitterSizes; + QList m_menuSplitterSizes; + bool m_isHidden; + QPropertyAnimation *m_currentAnimation{nullptr}; + Ui::LtsBaseLayoutWidget *m_ui{nullptr}; + IDL::PartitionType m_partitionType; + int m_domainId; + int m_partitionId; + QString m_operatorName; + bool m_firstShow; + bool m_showTerminalButton; + qint64 m_exerciseTime; + QTimer *m_setCurrentTimeTimer{nullptr}; + bool m_irreplaceableOnce; + QButtonGroup *m_bg{nullptr}; + QString m_workspaceId; + int m_screenCount; + bool m_menuCollapsed; + QMap, bool> m_oldLayoutVisibilityStates; + LtsNotificationBox *m_notiBox{nullptr}; + QStringList m_notFoundYet; + bool m_isSecondaryWidget { false }; + QVector m_currentMessage; // optional + QVector m_messageQueue; }; } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_bitfield_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_bitfield_widget.cpp index 151ec05c1..9ab7cf1bd 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_bitfield_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_bitfield_widget.cpp @@ -1,4 +1,11 @@ - +/** +* @RDE_HEADER@ +* Bitfield Widget for bitwise displaying and editing of quint8 values +* Created by Christian Kaemmerer +* $Id$ +* $HeadURL$ +* $Author$ +*/ #include "lts_bitfield_widget.h" @@ -7,119 +14,122 @@ namespace LtsWidgets { -LtsBitfieldWidget::LtsBitfieldWidget(QWidget* parent, quint8 value) : QWidget(parent), m_value(value) +LtsBitfieldWidget::LtsBitfieldWidget(QWidget *parent, quint8 value) + : QWidget(parent) + , m_value(value) { - setObjectName(QString::fromUtf8("LtsBitfieldWidget")); + setObjectName(QString::fromUtf8("LtsBitfieldWidget")); } -void LtsBitfieldWidget::paintEvent(QPaintEvent* pe) +void LtsBitfieldWidget::paintEvent(QPaintEvent *pe) { - QWidget::paintEvent(pe); + QWidget::paintEvent(pe); - QPainter painter; - painter.begin(this); - painter.setPen(Qt::SolidLine); + QPainter painter; + painter.begin(this); + painter.setPen(Qt::SolidLine); + + if (m_hasCaption) + { + QFont font = painter.font(); + font.setPointSizeF( (height()/2.0 > width()/8.0) ? width()/8.0 : height()/2.0 ); + painter.setFont(font); + } + + for (int i = 0; i < 8; ++i) + { + QRectF bitGraphic; + + bitGraphic.setLeft(width() / 8.0 * i); + bitGraphic.setWidth((width() / 8.0) - 1); + bitGraphic.setHeight(height() - 1); + + bool bitVal = (m_value & (1 << (7 - i))) > 0; + + painter.fillRect(bitGraphic, QBrush(bitVal ? m_onColor : m_offColor, Qt::SolidPattern)); if (m_hasCaption) { - QFont font = painter.font(); - font.setPointSizeF((height() / 2.0 > width() / 8.0) ? width() / 8.0 : height() / 2.0); - painter.setFont(font); + painter.setPen(bitVal ? m_offColor : m_onColor); + painter.drawText(bitGraphic, Qt::AlignCenter, bitVal ? QStringLiteral("1") : QStringLiteral("0")); } - for (int i = 0; i < 8; ++i) - { - QRectF bitGraphic; + painter.setPen(Qt::gray); + painter.drawRect(bitGraphic); + } // for(..) - bitGraphic.setLeft(width() / 8.0 * i); - bitGraphic.setWidth((width() / 8.0) - 1); - bitGraphic.setHeight(height() - 1); - - bool bitVal = (m_value & (1 << (7 - i))) > 0; - - painter.fillRect(bitGraphic, QBrush(bitVal ? m_onColor : m_offColor, Qt::SolidPattern)); - - if (m_hasCaption) - { - painter.setPen(bitVal ? m_offColor : m_onColor); - painter.drawText(bitGraphic, Qt::AlignCenter, bitVal ? QStringLiteral("1") : QStringLiteral("0")); - } - - painter.setPen(Qt::gray); - painter.drawRect(bitGraphic); - } - - painter.end(); + painter.end(); } void LtsBitfieldWidget::setHasCaption(bool hasCaption) { - if (m_hasCaption == hasCaption) - return; + if (m_hasCaption == hasCaption) + return; - m_hasCaption = hasCaption; - repaint(); + m_hasCaption = hasCaption; + repaint(); - emit hasCaptionChanged(hasCaption); + emit hasCaptionChanged(hasCaption); } -void LtsBitfieldWidget::setOnColor(const QColor& onColor) +void LtsBitfieldWidget::setOnColor(const QColor &onColor) { - if (m_onColor == onColor) - return; + if (m_onColor == onColor) + return; - m_onColor = onColor; - repaint(); + m_onColor = onColor; + repaint(); } -void LtsBitfieldWidget::setOffColor(const QColor& offColor) +void LtsBitfieldWidget::setOffColor(const QColor &offColor) { - if (m_offColor == offColor) - return; + if (m_offColor == offColor) + return; - m_offColor = offColor; - repaint(); + m_offColor = offColor; + repaint(); } -void LtsBitfieldWidget::mousePressEvent(QMouseEvent* event) +void LtsBitfieldWidget::mousePressEvent(QMouseEvent *event) { - if (!m_isEditable) + if (!m_isEditable) + { + QWidget::mousePressEvent(event); + return; + } + + for (int i = 0; i < 8; ++i) + { + if (event->pos().x() > width()/8 * i && + event->pos().x() < width()/8 * (i + 1)) { - QWidget::mousePressEvent(event); - return; + m_value ^= (1 << (7 - i)); + emit valueChanged(m_value); + break; } - - for (int i = 0; i < 8; ++i) - { - if (event->pos().x() > width() / 8 * i && event->pos().x() < width() / 8 * (i + 1)) - { - m_value ^= (1 << (7 - i)); - emit valueChanged(m_value); - break; - } - } - repaint(); + } + repaint(); } void LtsBitfieldWidget::setEditable(bool editable) { - if (m_isEditable == editable) - return; + if (m_isEditable == editable) + return; - m_isEditable = editable; + m_isEditable = editable; - emit isEditableChanged(m_isEditable); + emit isEditableChanged(m_isEditable); } void LtsBitfieldWidget::setValue(quint8 value) { - if (m_value == value) - return; + if (m_value == value) + return; - m_value = value; - repaint(); + m_value = value; + repaint(); - emit valueChanged(m_value); + emit valueChanged(m_value); } -} // namespace LtsWidgets +} // namespace diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_bitfield_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_bitfield_widget.h index bc4e20023..a1ea8d814 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_bitfield_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_bitfield_widget.h @@ -1,84 +1,141 @@ - +/** +* @RDE_HEADER@ +* Bitfield Widget for bitwise displaying and editing of quint8 values +* Created by Christian Kaemmerer +* $Id$ +* $HeadURL$ +* $Author$ +*/ #pragma once + +#include +#include + #include "lts_widgets_export.h" -#include -#include -#include namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsBitfieldWidget : public QWidget { - Q_OBJECT + Q_OBJECT - Q_PROPERTY(quint8 value READ value WRITE setValue NOTIFY valueChanged) - Q_PROPERTY(bool isEditable READ isEditable WRITE setEditable NOTIFY isEditableChanged) - Q_PROPERTY(bool hasCaption READ hasCaption WRITE setHasCaption NOTIFY hasCaptionChanged) - Q_PROPERTY(QColor onColor READ onColor WRITE setOnColor) - Q_PROPERTY(QColor offColor READ offColor WRITE setOffColor) + Q_PROPERTY(quint8 value READ value WRITE setValue NOTIFY valueChanged) + Q_PROPERTY(bool isEditable READ isEditable WRITE setEditable NOTIFY isEditableChanged) + Q_PROPERTY(bool hasCaption READ hasCaption WRITE setHasCaption NOTIFY hasCaptionChanged) + Q_PROPERTY(QColor onColor READ onColor WRITE setOnColor) + Q_PROPERTY(QColor offColor READ offColor WRITE setOffColor) - public: - explicit LtsBitfieldWidget(QWidget* parent = nullptr, quint8 value = 0); +public: + explicit LtsBitfieldWidget(QWidget *parent = nullptr, quint8 value = 0); - signals: - void valueChanged(quint8 newValue); - void isEditableChanged(bool option); - void hasCaptionChanged(bool option); +signals: + void valueChanged(quint8 newValue); + void isEditableChanged(bool option); + void hasCaptionChanged(bool option); - public slots: +public slots: + /** + * @brief setvalue + * sets m_value to the given quint8 + * @param quint8 value + */ + void setValue(quint8 value); - void setValue(quint8 value); + /** + * @brief setIsEditable + * sets m_isEditable to option. + * true meaning the value of the widget can be changed via mousePressEvent + * @param bool option + */ + void setEditable(bool editable); - void setEditable(bool editable); + /** + * @brief setHasCaption + * sets m_hasCaption to 0 or 1 which toggels if text should be + * drawn on each bitGraphic + * @param bool hasCaption + */ + void setHasCaption(bool hasCaption); - void setHasCaption(bool hasCaption); + /** + * @brief setOnColor + * sets the onColor for m_bitGraphic + * @param QColor onColor + */ + void setOnColor(const QColor &onColor); - void setOnColor(const QColor& onColor); + /** + * @brief setOffColor + * sets the offColor for m_bitGraphic + * @param QColor offColor + */ + void setOffColor(const QColor &offColor); - void setOffColor(const QColor& offColor); - public: - quint8 value() const - { - return m_value; - } +public: + /** + * @brief value + * get the current value + * @return quint8 of current value + */ + quint8 value() const { return m_value; } - bool isEditable() const - { - return m_isEditable; - } + /** + * @brief isEditable + * get the current state of editability + * @return bool of editability state + */ + bool isEditable() const { return m_isEditable; } - bool hasCaption() const - { - return m_hasCaption; - } + /** + * @brief hasCaption + * gets state of m_hasCaption + * @return bool hasCaption + */ + bool hasCaption() const { return m_hasCaption; } - QColor onColor() const - { - return m_onColor; - } + /** + * @brief onColor + * gets the onColor for m_bitGraphic + * @return QColor m_onColor + */ + QColor onColor() const {return m_onColor;} - QColor offColor() const - { - return m_offColor; - } + /** + * @brief offColor + * gets the offColor for m_bitGraphic + * @return QColor m_offColor + */ + QColor offColor() const {return m_offColor;} - private: - void mousePressEvent(QMouseEvent* event) override; +private: + /** + * @brief mousePressEvent + * Checks if the click position falls within any of the bit rectangles. If there + * is a match the value of that bit gets flipped + * @param event QMouseEvent + */ + void mousePressEvent(QMouseEvent *event) override; - void paintEvent(QPaintEvent* pe) override; + /** + * @brief paintEvent + * Draws m_bitGraphic.Size() rectangles and depending on the bit value of m_value draw either + * a onColor rectangle with a offColor 1 or a offColor rectangle with a onColor 0 + * @param pe QPaintEvent (isn't used to do anything) + */ + void paintEvent(QPaintEvent *pe) override; - private: - quint8 m_value = 0; +private: + quint8 m_value = 0; - bool m_isEditable = true; - bool m_hasCaption = true; + bool m_isEditable = true; + bool m_hasCaption = true; - QColor m_onColor = Qt::black; - QColor m_offColor = Qt::white; + QColor m_onColor = Qt::black; + QColor m_offColor = Qt::white; }; } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_checkable_table_model.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_checkable_table_model.h index badd4c081..ed95fd18e 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_checkable_table_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_checkable_table_model.h @@ -1,129 +1,137 @@ - +/** + * @RDE_HEADER@ + * + * $Id$ + * $HeadURL$ + * $Author$ + * Created by Malte Diers, SLSE, 2017-10-10 + */ #pragma once #include "lts_abstract_table_model.h" + namespace LtsWidgets { -template class LtsCheckableTableModel : public LtsAbstractTableModel +template +class LtsCheckableTableModel : public LtsAbstractTableModel { - public: - LtsCheckableTableModel(const QVector& header, int checkableColumn, QObject* parent) - : LtsAbstractTableModel(header, parent), m_checkableColumn(checkableColumn) +public: + LtsCheckableTableModel(const QVector &header, int checkableColumn, QObject *parent) + : LtsAbstractTableModel(header, parent) + , m_checkableColumn(checkableColumn) + { + } + + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override + { + if (role == Qt::CheckStateRole && index.column() == m_checkableColumn && LtsAbstractTableModel::indexIsValid(index)) + return LtsAbstractTableModel::m_vecData.at(index.row()).first ? Qt::Checked : Qt::Unchecked; + return QVariant(); + } + + bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override + { + if (role == Qt::CheckStateRole) { + switchCheckbox(index); + return true; + } + return QAbstractItemModel::setData(index, value, role); + } + + Qt::ItemFlags flags(const QModelIndex &index) const override + { + Qt::ItemFlags flags(LtsWidgets::LtsAbstractTableModel::flags(index) & ~Qt::ItemIsSelectable); + if (index.column() == m_checkableColumn) + return flags.setFlag(Qt::ItemIsUserCheckable); + + return flags; + } + + QVector getCheckedIds() const + { + QVector ids; + + for (int row = 0; row < LtsAbstractTableModel::rowCount(); ++row) + { + const T &entry = LtsAbstractTableModel::m_vecData.at(row); + if (entry.first) + ids << entry.second.id(); } - QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override + return ids; + } + + QVector getUncheckedIds() const + { + QVector ids; + + for (int row = 0; row < LtsAbstractTableModel::rowCount(); ++row) { - if (role == Qt::CheckStateRole && index.column() == m_checkableColumn && - LtsAbstractTableModel::indexIsValid(index)) - return LtsAbstractTableModel::m_vecData.at(index.row()).first ? Qt::Checked : Qt::Unchecked; - return QVariant(); + const T &entry = LtsAbstractTableModel::m_vecData.at(row); + if (!entry.first) + ids << entry.second.id(); } - bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) override + return ids; + } + + bool setChecked(const QVector &vecCheckedIds) + { + for (int row = 0; row < LtsAbstractTableModel::rowCount(); ++row) { - if (role == Qt::CheckStateRole) - { - switchCheckbox(index); - return true; - } - return QAbstractItemModel::setData(index, value, role); + T &entry = LtsAbstractTableModel::m_vecData[row]; + bool bContains = vecCheckedIds.contains(entry.second.id()); + if (entry.first != bContains) + { + entry.first = bContains; + const QModelIndex idx(LtsAbstractTableModel::index(row, m_checkableColumn, QModelIndex())); + emit LtsAbstractTableModel::dataChanged(idx, idx, {Qt::CheckStateRole}); + } } - Qt::ItemFlags flags(const QModelIndex& index) const override + return true; + } + bool isFiltered(const T &data, DataModification modType) const override + { + Q_UNUSED(data); + Q_UNUSED(modType); + return false; + } + +public slots: + void switchCheckbox(const QModelIndex &index) + { + auto entry = LtsAbstractTableModel::getRowData(index.row()); + entry.first = !entry.first; + LtsAbstractTableModel::setRowData(index.row(), entry); + } + + void selectAll() + { + for (int row = 0; row < LtsAbstractTableModel::rowCount(); ++row) { - Qt::ItemFlags flags(LtsWidgets::LtsAbstractTableModel::flags(index) & ~Qt::ItemIsSelectable); - if (index.column() == m_checkableColumn) - return flags.setFlag(Qt::ItemIsUserCheckable); - - return flags; + T entry = LtsAbstractTableModel::m_vecData.at(row); + entry.first = true; + LtsAbstractTableModel::setRowData(row, entry); } + } - QVector getCheckedIds() const + void unselectAll() + { + for (int row = 0; row < LtsAbstractTableModel::rowCount(); ++row) { - QVector ids; - - for (int row = 0; row < LtsAbstractTableModel::rowCount(); ++row) - { - const T& entry = LtsAbstractTableModel::m_vecData.at(row); - if (entry.first) - ids << entry.second.id(); - } - - return ids; + T entry = LtsAbstractTableModel::m_vecData.at(row); + entry.first = false; + LtsAbstractTableModel::setRowData(row, entry); } + } - QVector getUncheckedIds() const - { - QVector ids; +private: + int m_checkableColumn; - for (int row = 0; row < LtsAbstractTableModel::rowCount(); ++row) - { - const T& entry = LtsAbstractTableModel::m_vecData.at(row); - if (!entry.first) - ids << entry.second.id(); - } - - return ids; - } - - bool setChecked(const QVector& vecCheckedIds) - { - for (int row = 0; row < LtsAbstractTableModel::rowCount(); ++row) - { - T& entry = LtsAbstractTableModel::m_vecData[row]; - bool bContains = vecCheckedIds.contains(entry.second.id()); - if (entry.first != bContains) - { - entry.first = bContains; - const QModelIndex idx(LtsAbstractTableModel::index(row, m_checkableColumn, QModelIndex())); - emit LtsAbstractTableModel::dataChanged(idx, idx, {Qt::CheckStateRole}); - } - } - - return true; - } - - bool isFiltered(const T& data, DataModification modType) const override - { - Q_UNUSED(data); - Q_UNUSED(modType); - return false; - } - - public slots: - - void switchCheckbox(const QModelIndex& index) - { - auto entry = LtsAbstractTableModel::getRowData(index.row()); - entry.first = !entry.first; - LtsAbstractTableModel::setRowData(index.row(), entry); - } - - void selectAll() - { - for (int row = 0; row < LtsAbstractTableModel::rowCount(); ++row) - { - T entry = LtsAbstractTableModel::m_vecData.at(row); - entry.first = true; - LtsAbstractTableModel::setRowData(row, entry); - } - } - - void unselectAll() - { - for (int row = 0; row < LtsAbstractTableModel::rowCount(); ++row) - { - T entry = LtsAbstractTableModel::m_vecData.at(row); - entry.first = false; - LtsAbstractTableModel::setRowData(row, entry); - } - } - - private: - int m_checkableColumn; }; -} // namespace LtsWidgets +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_column_filter_proxy_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_column_filter_proxy_model.cpp index 4165cd3a7..2ea273ed7 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_column_filter_proxy_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_column_filter_proxy_model.cpp @@ -1,149 +1,161 @@ - +/** + * @RDE_HEADER@ + * Advanced Filter, enables filtering per column + * $Id: lts_filter_proxy.cpp 27949 2016-06-22 18:31:13Z ehrlicher $ + * $HeadURL: svn://slssvn/TDS/branches/product/devel/trunk/Lts/Common/LtsSearchModel/lts_filter_proxy.cpp $ + * $Author: ehrlicher $ + * Created by Mike Wille, SLSE, 2016-03-14 + */ #include "lts_column_filter_proxy_model.h" -#include +#include + #include + namespace LtsWidgets { -LtsColumnFilterProxyModel::LtsColumnFilterProxyModel(QObject* parent) : QSortFilterProxyModel(parent) +LtsColumnFilterProxyModel::LtsColumnFilterProxyModel(QObject *parent) + : QSortFilterProxyModel(parent) { - setSortCaseSensitivity(Qt::CaseInsensitive); + setSortCaseSensitivity(Qt::CaseInsensitive); } -bool LtsColumnFilterProxyModel::lessThan(const QModelIndex& left, const QModelIndex& right) const +bool LtsColumnFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { - return LtsUtils::lessThan(sourceModel()->data(left), sourceModel()->data(right)); + return LtsUtils::lessThan(sourceModel()->data(left), sourceModel()->data(right)); } -void LtsColumnFilterProxyModel::onSetColumnStringFilter(const QString& newFilterString, int column) +void LtsColumnFilterProxyModel::onSetColumnStringFilter(const QString &newFilterString, int column) { - setColumnStringFilter(newFilterString, column); + setColumnStringFilter(newFilterString, column); } -void LtsColumnFilterProxyModel::onSetColumnDataFilter(const QVariant& newFilterData, int column) +void LtsColumnFilterProxyModel::onSetColumnDataFilter(const QVariant &newFilterData, int column) { - setColumnDataFilter(newFilterData, column); + setColumnDataFilter(newFilterData, column); } -void LtsColumnFilterProxyModel::setColumnStringFilter(const QString& newFilterString, int column) +void LtsColumnFilterProxyModel::setColumnStringFilter(const QString &newFilterString, int column) { - if (column < 0) - return; - auto it = m_columnStringFilters.find(column); - if (newFilterString.isEmpty()) + if (column < 0) + return; + auto it = m_columnStringFilters.find(column); + if (newFilterString.isEmpty()) + { + if (it == m_columnStringFilters.end()) + return; + m_columnStringFilters.erase(it); + } + else + { + auto rx = QRegularExpression(newFilterString, + QRegularExpression::CaseInsensitiveOption); + if (it == m_columnStringFilters.end()) { - if (it == m_columnStringFilters.end()) - return; - m_columnStringFilters.erase(it); + m_columnStringFilters.insert(column, rx); } else { - auto rx = QRegularExpression(newFilterString, QRegularExpression::CaseInsensitiveOption); - if (it == m_columnStringFilters.end()) - { - m_columnStringFilters.insert(column, rx); - } - else - { - if (rx == it.value()) - return; - it.value() = rx; - } + if (rx == it.value()) + return; + it.value() = rx; } - invalidateFilter(); + } + invalidateFilter(); } -void LtsColumnFilterProxyModel::setColumnDataFilter(const QVariant& newFilterData, int column) +void LtsColumnFilterProxyModel::setColumnDataFilter(const QVariant &newFilterData, int column) { - if (column < 0) - return; - auto it = m_columnDataFilters.find(column); - if (newFilterData.isNull()) + if (column < 0) + return; + auto it = m_columnDataFilters.find(column); + if (newFilterData.isNull()) + { + if (it == m_columnDataFilters.end()) + return; + m_columnDataFilters.erase(it); + } + else + { + if (it == m_columnDataFilters.end()) { - if (it == m_columnDataFilters.end()) - return; - m_columnDataFilters.erase(it); + m_columnDataFilters[column] = newFilterData; } else { - if (it == m_columnDataFilters.end()) - { - m_columnDataFilters[column] = newFilterData; - } - else - { - if (newFilterData == it.value()) - return; - it.value() = newFilterData; - } + if (newFilterData == it.value()) + return; + it.value() = newFilterData; } - invalidateFilter(); + } + invalidateFilter(); } -bool LtsColumnFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const + +bool LtsColumnFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const { + // filtering + const auto sm = sourceModel(); + bool bRet = true; + for (auto it = m_columnDataFilters.begin(); bRet && it != m_columnDataFilters.end(); ++it) + { + const QModelIndex idx = sm->index(source_row, it.key(), source_parent); + const QVariant _data = sm->data(idx, LtsWidgets::LtsColumnFilterProxyModel::ComboboxFilterRole).toString(); // MW: variant => string => variant? is this intended? + bRet = _data == it.value(); + if (!bRet) + break; + } - const auto sm = sourceModel(); - bool bRet = true; - for (auto it = m_columnDataFilters.begin(); bRet && it != m_columnDataFilters.end(); ++it) - { - const QModelIndex idx = sm->index(source_row, it.key(), source_parent); - const QVariant _data = sm->data(idx, LtsWidgets::LtsColumnFilterProxyModel::ComboboxFilterRole).toString(); - bRet = _data == it.value(); - if (!bRet) - break; - } - - for (auto it = m_columnStringFilters.begin(); bRet && it != m_columnStringFilters.end(); ++it) - { - const QRegularExpression& rx = it.value(); - if (!rx.isValid()) - continue; - const QModelIndex idx = sm->index(source_row, it.key(), source_parent); - const QString _data = sm->data(idx, Qt::DisplayRole).toString(); - bRet = _data.contains(rx); - if (!bRet) - break; - } + for (auto it = m_columnStringFilters.begin(); bRet && it != m_columnStringFilters.end(); ++it) + { + const QRegularExpression &rx = it.value(); + if (!rx.isValid()) + continue; + const QModelIndex idx = sm->index(source_row, it.key(), source_parent); + const QString _data = sm->data(idx, Qt::DisplayRole).toString(); + bRet = _data.contains(rx); + if (!bRet) + break; + } #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) - if (!bRet && m_bRecursiveFiltering) - { - const QModelIndex idx = sm->index(source_row, 0, source_parent); - if (checkIfOneChildIsVisible(idx)) - return true; - } + if (!bRet && m_bRecursiveFiltering) + { + const QModelIndex idx = sm->index(source_row, 0, source_parent); + if (checkIfOneChildIsVisible(idx)) + return true; + } #endif - return bRet; + return bRet; } #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) void LtsColumnFilterProxyModel::setRecursiveFilteringEnabled(bool recursive) { - if (m_bRecursiveFiltering == recursive) - return; - m_bRecursiveFiltering = recursive; - invalidateFilter(); + if (m_bRecursiveFiltering == recursive) + return; + m_bRecursiveFiltering = recursive; + invalidateFilter(); } bool LtsColumnFilterProxyModel::recursiveFilteringEnabled() const { - return m_bRecursiveFiltering; + return m_bRecursiveFiltering; } -bool LtsColumnFilterProxyModel::checkIfOneChildIsVisible(const QModelIndex& parent) const +bool LtsColumnFilterProxyModel::checkIfOneChildIsVisible(const QModelIndex &parent) const { - const auto sm = sourceModel(); - const int childCount = sm->rowCount(parent); - for (int i = 0; i < childCount; ++i) - { - if (filterAcceptsRow(i, parent)) - return true; - } - return false; + const auto sm = sourceModel(); + const int childCount = sm->rowCount(parent); + for (int i = 0; i < childCount; ++i) + { + if (filterAcceptsRow(i, parent)) + return true; + } + return false; } #endif diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_column_filter_proxy_model.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_column_filter_proxy_model.h index 9f35d6366..d16caaf31 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_column_filter_proxy_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_column_filter_proxy_model.h @@ -1,133 +1,128 @@ - +/** + * @RDE_HEADER@ + * Advanced Filter, enables filtering per column + * $Id: lts_filter_proxy.h 27949 2016-06-22 18:31:13Z ehrlicher $ + * $HeadURL: svn://slssvn/TDS/branches/product/devel/trunk/Lts/Common/LtsSearchModel/lts_filter_proxy.h $ + * $Author: ehrlicher $ + * Created by Mike Wille, SLSE, 2016-03-14 + */ #pragma once -#include "lts_widgets_export.h" -#include +#include +#include + #include -#include #include -#include #include #include #include + namespace LtsWidgets { struct ComboboxFilterData { - QString text; - QVariant data; - QIcon icon; + QString text; // visible text in ComboBox + QVariant data; // data cor comparison during filtering + QIcon icon; // decoration of text in ComboBox - inline bool operator<(const ComboboxFilterData& cfd) - { - return LtsUtils::lessThan(data, cfd.data); - } - - inline friend QDataStream& operator<<(QDataStream& ds, const ComboboxFilterData& cfd) - { - ds << cfd.text << cfd.data << cfd.icon; - return ds; - } - - inline friend QDataStream& operator>>(QDataStream& ds, ComboboxFilterData& cfd) - { - ds >> cfd.text >> cfd.data >> cfd.icon; - return ds; - } + inline bool operator<(const ComboboxFilterData &cfd) + { + return LtsUtils::lessThan(data, cfd.data); + } + inline friend QDataStream &operator<<(QDataStream &ds, const ComboboxFilterData &cfd) + { + ds << cfd.text << cfd.data << cfd.icon; + return ds; + } + inline friend QDataStream &operator>>(QDataStream &ds, ComboboxFilterData &cfd) + { + ds >> cfd.text >> cfd.data >> cfd.icon; + return ds; + } }; + struct ComboboxFilterContent { - QVector data; - bool sortItems = false; + QVector data; + bool sortItems = false; // sort items in ComboBox yes/no + bool isValid() const { return m_isValid; } - bool isValid() const - { - return m_isValid; - } + QVariant toVariant() const + { + if (!isValid()) + return QVariant(); + QByteArray ba; + QDataStream ds(&ba, QIODevice::WriteOnly); + ds << (*this); + return ba; + } - QVariant toVariant() const - { - if (!isValid()) - return QVariant(); - QByteArray ba; - QDataStream ds(&ba, QIODevice::WriteOnly); - ds << (*this); - return ba; - } + static ComboboxFilterContent fromVariant(const QVariant &v) + { + ComboboxFilterContent ret; + QDataStream ds(v.toByteArray()); + ds.startTransaction(); + ds >> ret; + ds.commitTransaction(); + ret.m_isValid = ds.status() == QDataStream::Ok; - static ComboboxFilterContent fromVariant(const QVariant& v) - { - ComboboxFilterContent ret; - QDataStream ds(v.toByteArray()); - ds.startTransaction(); - ds >> ret; - ds.commitTransaction(); - ret.m_isValid = ds.status() == QDataStream::Ok; + return ret; + } - return ret; - } + inline friend QDataStream &operator<<(QDataStream &ds, const ComboboxFilterContent &cfc) + { + ds << cfc.data << cfc.sortItems; + return ds; + } + inline friend QDataStream &operator>>(QDataStream &ds, ComboboxFilterContent &cfc) + { + ds >> cfc.data >> cfc.sortItems; + return ds; + } - inline friend QDataStream& operator<<(QDataStream& ds, const ComboboxFilterContent& cfc) - { - ds << cfc.data << cfc.sortItems; - return ds; - } - - inline friend QDataStream& operator>>(QDataStream& ds, ComboboxFilterContent& cfc) - { - ds >> cfc.data >> cfc.sortItems; - return ds; - } - - private: - bool m_isValid = true; +private: + bool m_isValid = true; // internal, will be set to true/false in fromVariant() }; + class LTSWIDGETS_EXPORT LtsColumnFilterProxyModel : public QSortFilterProxyModel { - Q_OBJECT - public: - static constexpr int ComboboxFilterRole = Qt::UserRole + 17; + Q_OBJECT +public: + static constexpr int ComboboxFilterRole = Qt::UserRole + 17; - explicit LtsColumnFilterProxyModel(QObject* parent = nullptr); + explicit LtsColumnFilterProxyModel(QObject *parent = nullptr); #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) - void setRecursiveFilteringEnabled(bool recursive); - bool recursiveFilteringEnabled() const; + void setRecursiveFilteringEnabled(bool recursive); + bool recursiveFilteringEnabled() const; #endif - const QHash& columnStringFilters() const - { - return m_columnStringFilters; - } + const QHash &columnStringFilters() const { return m_columnStringFilters; } + const QHash &columnDataFilters() const { return m_columnDataFilters; } - const QHash& columnDataFilters() const - { - return m_columnDataFilters; - } + bool lessThan(const QModelIndex &left, const QModelIndex &right) const override; - bool lessThan(const QModelIndex& left, const QModelIndex& right) const override; + virtual void setColumnStringFilter(const QString &newFilterString, int column); + virtual void setColumnDataFilter(const QVariant &newFilterData, int column); - virtual void setColumnStringFilter(const QString& newFilterString, int column); - virtual void setColumnDataFilter(const QVariant& newFilterData, int column); +public slots: + void onSetColumnStringFilter(const QString &newFilterString, int column); + void onSetColumnDataFilter(const QVariant &newFilterData, int column); - public slots: - void onSetColumnStringFilter(const QString& newFilterString, int column); - void onSetColumnDataFilter(const QVariant& newFilterData, int column); - - protected: - virtual bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override; +protected: + virtual bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override; #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) - bool checkIfOneChildIsVisible(const QModelIndex& parent) const; + bool checkIfOneChildIsVisible(const QModelIndex &parent) const; #endif - private: - QHash m_columnStringFilters; - QHash m_columnDataFilters; +private: + QHash m_columnStringFilters; + QHash m_columnDataFilters; #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) - bool m_bRecursiveFiltering = false; + bool m_bRecursiveFiltering = false; #endif }; } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_combo_box.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_combo_box.cpp index 30d20f081..fed7e2de6 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_combo_box.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_combo_box.cpp @@ -1,99 +1,125 @@ - +/** + * @RDE_HEADER@ + * ComboBox, optimized for tablets (bigger dropdown/popup and more comfortable completer) + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Mike Wille, SLSE, 2016-03-09 + */ #include "lts_combo_box.h" - -#include "lts_message_dialog.h" #include "lts_selection_popup.h" +#include "lts_message_dialog.h" #include #include +//#define NEVER #ifdef NEVER -#include -#endif +# include +#endif // NEVER namespace LtsWidgets { bool LtsComboBox::s_useSelectionDialog = false; -LtsComboBox::LtsComboBox(QWidget* parent) : QComboBox(parent), m_currentIndex(-1) +LtsComboBox::LtsComboBox(QWidget *parent) + : QComboBox(parent) + , m_currentIndex(-1) { - connect(this, &LtsComboBox::signalExternallyChanged, this, &LtsComboBox::signalRefill); + connect(this, &LtsComboBox::signalExternallyChanged, + this, &LtsComboBox::signalRefill); // sig on sig (to fetch cbx as sender) } void LtsComboBox::setUseSelectionDialog(bool bUseSelectionDialog) { - s_useSelectionDialog = bUseSelectionDialog; + s_useSelectionDialog = bUseSelectionDialog; } -void LtsComboBox::showEvent(QShowEvent* e) +void LtsComboBox::showEvent(QShowEvent *e) { - QComboBox::showEvent(e); + QComboBox::showEvent(e); - m_currentIndex = currentIndex(); + m_currentIndex = currentIndex(); } -void LtsComboBox::enterEvent(QEnterEvent* e) +void LtsComboBox::enterEvent(QEnterEvent *e) { - BaseClass::enterEvent(e); - emit signalEnterEvent(); + BaseClass::enterEvent(e); + emit signalEnterEvent(); } -void LtsComboBox::leaveEvent(QEvent* e) +void LtsComboBox::leaveEvent(QEvent *e) { - BaseClass::leaveEvent(e); - emit signalLeaveEvent(); + BaseClass::leaveEvent(e); + emit signalLeaveEvent(); } void LtsComboBox::showPopup() { - bool bUseSelectionDialog = s_useSelectionDialog; - if (QGuiApplication::queryKeyboardModifiers() == Qt::ControlModifier) - bUseSelectionDialog = !bUseSelectionDialog; - if (!bUseSelectionDialog) - { - QComboBox::showPopup(); - return; - } + bool bUseSelectionDialog = s_useSelectionDialog; + if (QGuiApplication::queryKeyboardModifiers() == Qt::ControlModifier) + bUseSelectionDialog = !bUseSelectionDialog; + if (!bUseSelectionDialog) + { + QComboBox::showPopup(); // show original popup when CTRL is pressed + return; + } - if (!model()->rowCount()) - { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("There are no items available!")); - return; - } + if (!model()->rowCount()) // nothing to show? tell the user. + { + LtsWidgets::LtsMessageDialog::showMessage(this, tr("There are no items available!")); + return; + } - LtsSelectionPopup* popup = new LtsSelectionPopup(model(), currentIndex(), this); - popup->setAttribute(Qt::WA_DeleteOnClose); + // create the touch-friendly, screen-centered custom popup and show it + LtsSelectionPopup* popup = new LtsSelectionPopup(model(), currentIndex(), this); + popup->setAttribute(Qt::WA_DeleteOnClose); // dialog must delete itself, as there is no Dialog Helper #ifdef NEVER + // debugging : + // // highlighted -> UserInteraction +// connect(popup, static_cast(&LtsSelectionPopup::highlighted), this, [](int idx){ +// qCritical() << " LtsComboBox: called: highlighted(int), idx=" << idx; +// }); - connect(popup, static_cast(&LtsSelectionPopup::currentIndexChanged), this, - [](int idx) { qCritical() << " LtsComboBox: called: currentIndexChanged(int), idx=" << idx; }); + // currentIndexChanged -> programmatically & UserInteraction + connect(popup, static_cast(&LtsSelectionPopup::currentIndexChanged), this, [](int idx){ + qCritical() << " LtsComboBox: called: currentIndexChanged(int), idx=" << idx; + }); - connect(popup, static_cast(&LtsSelectionPopup::activated), this, - [](int idx) { qCritical() << " LtsComboBox: called: activated(int), idx=" << idx; }); + // activated -> UserInteraction + connect(popup, static_cast(&LtsSelectionPopup::activated), this, [](int idx){ + qCritical() << " LtsComboBox: called: activated(int), idx=" << idx; + }); + // : debugging +#endif // NEVER -#endif + // Although we derive from QComboBox, there seems to be no signal emitted implicitly. + // Therefore we have to listen to our popup: + connect(popup, &LtsSelectionPopup::currentIndexChanged, + this, &LtsComboBox::userChangedIndex); // listen on changes + connect(popup, &LtsSelectionPopup::activated, + this, static_cast(&LtsComboBox::activated)); // SIGNAL on SIGNAL ! - connect(popup, &LtsSelectionPopup::currentIndexChanged, this, &LtsComboBox::userChangedIndex); - connect(popup, &LtsSelectionPopup::activated, this, - static_cast(&LtsComboBox::activated)); - - popup->show(); + popup->show(); } + void LtsComboBox::userChangedIndex(int index) { - m_currentIndex = index; - setCurrentIndex(index); + m_currentIndex = index; + setCurrentIndex(index); } + bool LtsComboBox::hasValueChanged() const { - if (m_currentIndex == -1) - return false; - return !(currentIndex() == m_currentIndex); + if (m_currentIndex == -1) + return false; + return !(currentIndex() == m_currentIndex); } } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_combo_box.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_combo_box.h index 758f4bd26..570979fcd 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_combo_box.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_combo_box.h @@ -1,56 +1,76 @@ - +/** + * @RDE_HEADER@ + * ComboBox, optimized for tablets (bigger dropdown/popup and more comfortable completer) + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Mike Wille, SLSE, 2016-03-09 + */ #pragma once + #include "lts_widgets_export.h" #include -#include + namespace LtsWidgets { -class LTSWIDGETS_EXPORT LtsComboBox : public QComboBox +/** + * @brief The LtsComboBox class provides an almost identically version of the QComboBox, with the main difference that this version is more touch friendly. + * The LtsComboBox's Popup (LtsComboBoxPopup) is a LtsFramelessDialog (screen-centered) with bigger selection-items. + * For debug purpose: press CTRL while clicking on the popup-button to open the original QComboBox-Popup + */ +class LTSWIDGETS_EXPORT LtsComboBox : public QComboBox // TODO: change title of selection window { - Q_OBJECT - using BaseClass = QComboBox; + Q_OBJECT + using BaseClass = QComboBox; - public: - explicit LtsComboBox(QWidget* parent = nullptr); - ~LtsComboBox() = default; +public: + explicit LtsComboBox(QWidget *parent = nullptr); + ~LtsComboBox() = default; - static void setUseSelectionDialog(bool bUseSelectionDialog); + /** + * @brief Set the default widget to use - either the default QComboBox or the selection widget + * @param bUseSelectionDialog true if the selection widget should be used, false for the normal combobox + */ + static void setUseSelectionDialog(bool bUseSelectionDialog); - bool hasValueChanged() const; + /** + * @brief hasValueChanged tells if the value set by default (initialization) or by the user to another value, + * different by the default value. If the user sets the value back to the default value, 'hasValueChanged' will return false again. + * Use this in your UiRequirement to see if value differs from the default value to determine a change. + * @return true if value differs from default value and v.v. + */ + bool hasValueChanged() const; - void setExternalContentType(int ect) - { - m_externalContentType = ect; - } + void setExternalContentType(int ect) { m_externalContentType = ect; } + int externalContentType() const { return m_externalContentType; } - int externalContentType() const - { - return m_externalContentType; - } +protected: + /** + * @brief showPopup is emited by the native widget when the popup should be triggered (e.g. by clicking a non-writeable LtsComboBox or by clicking the popup-button) and shows an touch-friendly, screen-centered LtsComboBoxPopup + */ + void showPopup() override; - protected: - void showPopup() override; + void showEvent(QShowEvent *e) override; + void enterEvent(QEnterEvent *e) override; + void leaveEvent(QEvent *) override; - void showEvent(QShowEvent* e) override; - void enterEvent(QEnterEvent* e) override; - void leaveEvent(QEvent*) override; +protected slots: + void userChangedIndex(int index); // user change - for 'hasValueChanged' - protected slots: - void userChangedIndex(int index); +signals: + void signalExternallyChanged(); // e.g. PPM's parties changed, ComboBox should report to PpmComboBox for a refill + void signalRefill(); // outgoing + void signalEnterEvent(); + void signalLeaveEvent(); - signals: - void signalExternallyChanged(); - void signalRefill(); - void signalEnterEvent(); - void signalLeaveEvent(); - - private: - int m_currentIndex; - int m_externalContentType; - static bool s_useSelectionDialog; +private: + int m_currentIndex; + int m_externalContentType; + static bool s_useSelectionDialog; }; -} // namespace LtsWidgets +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit.cpp index da2793261..44ad120b7 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit.cpp @@ -1,11 +1,23 @@ - +/** + * @RDE_HEADER@ + * DTGEdit + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Mike Wille, SLSE, 2016-08-17 + */ #include "lts_date_time_edit.h" - #include "lts_date_time_edit_p.h" + #include "ui_lts_date_time_edit_touch.h" + #include + +#include + #include #include #include @@ -19,1697 +31,1762 @@ #include #include #include -#include -#include static constexpr qint64 s_oneSecondMSec = 1000LL; static constexpr qint64 s_oneMinuteMSec = 60 * s_oneSecondMSec; -static constexpr qint64 s_oneHourMSec = 60 * s_oneMinuteMSec; -static constexpr qint64 s_oneDayMSec = 24 * s_oneHourMSec; +static constexpr qint64 s_oneHourMSec = 60 * s_oneMinuteMSec; +static constexpr qint64 s_oneDayMSec = 24 * s_oneHourMSec; namespace Ui { class LtsDateTimeEditLe { - public: - LtsWidgets::DigitsLineEdit* leLongDay = nullptr; - LtsWidgets::DigitsLineEdit* leLongHHMMSS = nullptr; - LtsWidgets::LineEdit* leLongTZ = nullptr; - LtsWidgets::DigitsLineEdit* leLongMonth = nullptr; - LtsWidgets::DigitsLineEdit* leLongYear = nullptr; - QCheckBox* checkBox = nullptr; - QGridLayout* gridLayout = nullptr; - QPushButton* pbBBB = nullptr; - QPushButton* pbBB = nullptr; - QPushButton* pbB = nullptr; - QPushButton* pbF = nullptr; - QPushButton* pbFF = nullptr; - QPushButton* pbFFF = nullptr; - QPushButton* pbNow = nullptr; - QSlider* slTime = nullptr; +public: + LtsWidgets::DigitsLineEdit *leLongDay = nullptr; + LtsWidgets::DigitsLineEdit *leLongHHMMSS = nullptr; + LtsWidgets::LineEdit *leLongTZ = nullptr; + LtsWidgets::DigitsLineEdit *leLongMonth = nullptr; + LtsWidgets::DigitsLineEdit *leLongYear = nullptr; + QCheckBox *checkBox = nullptr; + QGridLayout *gridLayout = nullptr; + QPushButton *pbBBB = nullptr; + QPushButton *pbBB = nullptr; + QPushButton *pbB = nullptr; + QPushButton *pbF = nullptr; + QPushButton *pbFF = nullptr; + QPushButton *pbFFF = nullptr; + QPushButton *pbNow = nullptr; + QSlider *slTime = nullptr; - static void setFixedSize(QLineEdit* le, int charCount) - { - QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); - sizePolicy.setVerticalStretch(0); - sizePolicy.setHeightForWidth(false); + static void setFixedSize(QLineEdit *le, int charCount) + { + QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); + sizePolicy.setVerticalStretch(0); + sizePolicy.setHeightForWidth(false); - const QFontMetricsF fm(le->font()); - const auto textMargins = le->textMargins(); - le->setSizePolicy(sizePolicy); - charCount += 3; + const QFontMetricsF fm(le->font()); + const auto textMargins = le->textMargins(); + le->setSizePolicy(sizePolicy); + charCount += 3; // don't know why #if QT_VERSION < QT_VERSION_CHECK(5, 11, 0) - const qreal w = fm.width(QLatin1Char('x')) * charCount + textMargins.left() + textMargins.right(); + const qreal w = fm.width(QLatin1Char('x')) * charCount + textMargins.left() + textMargins.right(); #else - const qreal w = fm.horizontalAdvance(QLatin1Char('x')) * charCount + textMargins.left() + textMargins.right(); + const qreal w = fm.horizontalAdvance(QLatin1Char('x')) * charCount + textMargins.left() + textMargins.right(); #endif - le->setMinimumWidth(w); - le->setMaximumWidth(w); - } + le->setMinimumWidth(w); + le->setMaximumWidth(w); + } - void setupUi(QWidget* parent) - { - gridLayout = new QGridLayout(parent); - gridLayout->setContentsMargins(0, 0, 0, 0); + void setupUi(QWidget *parent) + { + gridLayout = new QGridLayout(parent); + gridLayout->setMargin(0); - int iStart = 3; + int iStart = 3; // 3 invisible widgets before - checkBox = new QCheckBox; - gridLayout->addWidget(checkBox, 0, iStart++, 1, 1); + checkBox = new QCheckBox; + gridLayout->addWidget(checkBox, 0, iStart++, 1, 1); - auto horizontalLayout = new QHBoxLayout; - horizontalLayout->setSpacing(0); - horizontalLayout->setContentsMargins(0, 0, 0, 0); + auto horizontalLayout = new QHBoxLayout; + horizontalLayout->setSpacing(0); + horizontalLayout->setContentsMargins(0, 0, 0, 0); - leLongDay = new LtsWidgets::DigitsLineEdit(parent); - setFixedSize(leLongDay, 2); - leLongDay->setObjectName(QStringLiteral("leLongDay")); - horizontalLayout->addWidget(leLongDay); + leLongDay = new LtsWidgets::DigitsLineEdit(parent); + setFixedSize(leLongDay, 2); + leLongDay->setObjectName(QStringLiteral("leLongDay")); + horizontalLayout->addWidget(leLongDay); - leLongHHMMSS = new LtsWidgets::DigitsLineEdit(parent); - leLongHHMMSS->setExactNumDigits(6); - setFixedSize(leLongHHMMSS, 6); - leLongHHMMSS->setObjectName(QStringLiteral("leLongHHMMSS")); - horizontalLayout->addWidget(leLongHHMMSS); + leLongHHMMSS = new LtsWidgets::DigitsLineEdit(parent); + leLongHHMMSS->setExactNumDigits(6); + setFixedSize(leLongHHMMSS, 6); + leLongHHMMSS->setObjectName(QStringLiteral("leLongHHMMSS")); + horizontalLayout->addWidget(leLongHHMMSS); - leLongTZ = new LtsWidgets::LineEdit(parent); - leLongTZ->setAlignment(Qt::AlignCenter); - setFixedSize(leLongTZ, 1); - leLongTZ->setObjectName(QStringLiteral("leLongTZ")); - horizontalLayout->addWidget(leLongTZ); + leLongTZ = new LtsWidgets::LineEdit(parent); + leLongTZ->setAlignment(Qt::AlignCenter); + setFixedSize(leLongTZ, 1); + leLongTZ->setObjectName(QStringLiteral("leLongTZ")); + horizontalLayout->addWidget(leLongTZ); - leLongMonth = new LtsWidgets::DigitsLineEdit(parent); - leLongMonth->setAlignment(Qt::AlignCenter); - setFixedSize(leLongMonth, 3); - leLongMonth->setObjectName(QStringLiteral("leLongMonth")); - horizontalLayout->addWidget(leLongMonth); + leLongMonth = new LtsWidgets::DigitsLineEdit(parent); + leLongMonth->setAlignment(Qt::AlignCenter); + setFixedSize(leLongMonth, 3); + leLongMonth->setObjectName(QStringLiteral("leLongMonth")); + horizontalLayout->addWidget(leLongMonth); - leLongYear = new LtsWidgets::DigitsLineEdit(parent); - leLongYear->setExactNumDigits(2); - setFixedSize(leLongYear, 2); - leLongYear->setObjectName(QStringLiteral("leLongYear")); - horizontalLayout->addWidget(leLongYear); + leLongYear = new LtsWidgets::DigitsLineEdit(parent); + leLongYear->setExactNumDigits(2); + setFixedSize(leLongYear, 2); + leLongYear->setObjectName(QStringLiteral("leLongYear")); + horizontalLayout->addWidget(leLongYear); - gridLayout->addLayout(horizontalLayout, 0, iStart++, 1, 1); + gridLayout->addLayout(horizontalLayout, 0, iStart++, 1, 1); - pbNow = new QPushButton(QApplication::translate("LtsDateTimeEdit", "Now", nullptr)); - pbNow->setObjectName(QStringLiteral("pbNow")); - gridLayout->addWidget(pbNow, 0, iStart++, 1, 1); + pbNow = new QPushButton(QApplication::translate("LtsDateTimeEdit", "Now", nullptr)); + pbNow->setObjectName(QStringLiteral("pbNow")); + gridLayout->addWidget(pbNow, 0, iStart++, 1, 1); - QWidget::setTabOrder(checkBox, leLongDay); - QWidget::setTabOrder(leLongDay, leLongHHMMSS); - QWidget::setTabOrder(leLongHHMMSS, leLongTZ); - QWidget::setTabOrder(leLongTZ, leLongMonth); - QWidget::setTabOrder(leLongMonth, leLongYear); - QWidget::setTabOrder(leLongYear, pbNow); + QWidget::setTabOrder(checkBox, leLongDay); + QWidget::setTabOrder(leLongDay, leLongHHMMSS); + QWidget::setTabOrder(leLongHHMMSS, leLongTZ); + QWidget::setTabOrder(leLongTZ, leLongMonth); + QWidget::setTabOrder(leLongMonth, leLongYear); + QWidget::setTabOrder(leLongYear, pbNow); - parent->setFocusProxy(leLongDay); - } + parent->setFocusProxy(leLongDay); + } // setupUi - static QPushButton* addButton(const QString& text, QWidget* parent) - { - QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + static QPushButton *addButton(const QString &text, QWidget *parent) + { + QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - auto pb = new QPushButton(parent); - pb->setMinimumWidth(27); - pb->setMaximumWidth(27); - pb->setText(text); - sizePolicy.setHorizontalStretch(0); - sizePolicy.setVerticalStretch(0); - sizePolicy.setHeightForWidth(pb->sizePolicy().hasHeightForWidth()); - pb->setSizePolicy(sizePolicy); - return pb; - } + auto pb = new QPushButton(parent); + pb->setMinimumWidth(27); + pb->setMaximumWidth(27); + pb->setText(text); + sizePolicy.setHorizontalStretch(0); + sizePolicy.setVerticalStretch(0); + sizePolicy.setHeightForWidth(pb->sizePolicy().hasHeightForWidth()); + pb->setSizePolicy(sizePolicy); + return pb; + } - void addButtons(QWidget* parent) - { - pbBBB = addButton(QLatin1String("<<<"), parent); - pbBB = addButton(QLatin1String("<<"), parent); - pbB = addButton(QLatin1String("<"), parent); - gridLayout->addWidget(pbBBB, 0, 0, 1, 1); - gridLayout->addWidget(pbBB, 0, 1, 1, 1); - gridLayout->addWidget(pbB, 0, 2, 1, 1); + void addButtons(QWidget *parent) + { + pbBBB = addButton(QLatin1String("<<<"), parent); + pbBB = addButton(QLatin1String("<<"), parent); + pbB = addButton(QLatin1String("<"), parent); + gridLayout->addWidget(pbBBB, 0, 0, 1, 1); + gridLayout->addWidget(pbBB, 0, 1, 1, 1); + gridLayout->addWidget(pbB, 0, 2, 1, 1); - int iStart = 5; - pbF = addButton(QLatin1String(">"), parent); - pbFF = addButton(QLatin1String(">>"), parent); - pbFFF = addButton(QLatin1String(">>>"), parent); - gridLayout->addWidget(pbF, 0, iStart++, 1, 1); - gridLayout->addWidget(pbFF, 0, iStart++, 1, 1); - gridLayout->addWidget(pbFFF, 0, iStart++, 1, 1); - } + int iStart = 5; // 3 from above, 3 by default + pbF = addButton(QLatin1String(">"), parent); + pbFF = addButton(QLatin1String(">>"), parent); + pbFFF = addButton(QLatin1String(">>>"), parent); + gridLayout->addWidget(pbF, 0, iStart++, 1, 1); + gridLayout->addWidget(pbFF, 0, iStart++, 1, 1); + gridLayout->addWidget(pbFFF, 0, iStart++, 1, 1); + } //addButtons - void addSlider(QWidget* parent) - { - slTime = new QSlider(parent); - slTime->setOrientation(Qt::Horizontal); - gridLayout->addWidget(slTime, 1, 0, 1, 7); - } + void addSlider(QWidget *parent) + { + slTime = new QSlider(parent); + slTime->setOrientation(Qt::Horizontal); + gridLayout->addWidget(slTime, 1, 0, 1, 7); + } //addSlider }; -} // namespace Ui +} + namespace LtsWidgets { -void setItemText(LtsWidgets::LineEdit* lineEdit, const QString& text) +// +// helper (via overloading) +// +void setItemText(LtsWidgets::LineEdit *lineEdit, const QString &text) { - if (!lineEdit) - return; - lineEdit->setText(text); + if (!lineEdit) + return; + lineEdit->setText(text); +} +void setItemText(QComboBox *comboxBox, const QString &text) +{ + if (!comboxBox) + return; + comboxBox->setCurrentIndex(comboxBox->findText(text)); +} +void setItemData(QComboBox *comboxBox, int data) +{ + if (!comboxBox) + return; + comboxBox->setCurrentIndex(comboxBox->findData(data)); +} +void setItemValue(QSpinBox *spinBox, int value) +{ + if (!spinBox) + return; + spinBox->setValue(value); } -void setItemText(QComboBox* comboxBox, const QString& text) + +QString getItemText(LtsWidgets::LineEdit *lineEdit) { - if (!comboxBox) - return; - comboxBox->setCurrentIndex(comboxBox->findText(text)); + if (!lineEdit) + return {}; + return lineEdit->text(); } - -void setItemData(QComboBox* comboxBox, int data) +QString getItemText(QComboBox *comboxBox) { - if (!comboxBox) - return; - comboxBox->setCurrentIndex(comboxBox->findData(data)); + if (!comboxBox || (comboxBox->count() <= 0)) + return {}; + const QString &curTest = comboxBox->currentText(); + if (curTest.isEmpty()) + return {}; + return curTest.at(0).toUpper(); } - -void setItemValue(QSpinBox* spinBox, int value) +int getItemData(QComboBox *comboxBox) { - if (!spinBox) - return; - spinBox->setValue(value); + if (!comboxBox || (comboxBox->count() <= 0)) + return {}; + int data = comboxBox->currentData().toInt(); + return data; } - -QString getItemText(LtsWidgets::LineEdit* lineEdit) +int getItemValue(QSpinBox *spinBox) { - if (!lineEdit) - return {}; - return lineEdit->text(); + if (!spinBox) + return 0; + return spinBox->value(); } +// helper (via overloading) END -QString getItemText(QComboBox* comboxBox) -{ - if (!comboxBox || (comboxBox->count() <= 0)) - return {}; - const QString& curTest = comboxBox->currentText(); - if (curTest.isEmpty()) - return {}; - return curTest.at(0).toUpper(); -} -int getItemData(QComboBox* comboxBox) -{ - if (!comboxBox || (comboxBox->count() <= 0)) - return {}; - int data = comboxBox->currentData().toInt(); - return data; -} - -int getItemValue(QSpinBox* spinBox) -{ - if (!spinBox) - return 0; - return spinBox->value(); -} - -LtsDateTimeEdit::LtsDateTimeEdit(QWidget* parent, bool withNowButton, bool checkable) - : QWidget(parent) - - , - m_scFixed(new QShortcut(QKeySequence(Qt::ShiftModifier + Qt::Key_F2), this, SLOT(setFixedDateTime()), nullptr, - Qt::WidgetWithChildrenShortcut)), - m_scOffset(new QShortcut(QKeySequence(Qt::Key_F2), this, SLOT(setOffsetDateTime()), nullptr, - Qt::WidgetWithChildrenShortcut)), - m_checkable(checkable), m_withNowButton(withNowButton) +// +// class LtsDateTimeEdit +// +LtsDateTimeEdit::LtsDateTimeEdit(QWidget *parent, bool withNowButton, bool checkable) + : QWidget(parent) +// , m_uiLe(new Ui::LtsDateTimeEditLe) + , m_scFixed(new QShortcut(QKeySequence(Qt::ShiftModifier + Qt::Key_F2), this, SLOT(setFixedDateTime()), nullptr, Qt::WidgetWithChildrenShortcut)) + , m_scOffset(new QShortcut(QKeySequence(Qt::Key_F2), this, SLOT(setOffsetDateTime()), nullptr, Qt::WidgetWithChildrenShortcut)) + , m_checkable(checkable) // see below + , m_withNowButton(withNowButton) // see below { #ifdef TABLET_MODE - - setupUiTouch(); - return; + // entweder TOUCH (SpinBox/ComboBox) + setupUiTouch(); + return; #else + // oder default (LineEdit) + m_uiLe = new Ui::LtsDateTimeEditLe; + m_uiLe->setupUi(this); - m_uiLe = new Ui::LtsDateTimeEditLe; - m_uiLe->setupUi(this); + setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); + setFocusPolicy(Qt::StrongFocus); + setContentsMargins(QMargins()); - setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); - setFocusPolicy(Qt::StrongFocus); - setContentsMargins(QMargins()); + QCompleter *completer = new QCompleter(DTG::months(), this); + completer->setCaseSensitivity(Qt::CaseInsensitive); + completer->setCompletionMode(QCompleter::InlineCompletion); - QCompleter* completer = new QCompleter(DTG::months(), this); - completer->setCaseSensitivity(Qt::CaseInsensitive); - completer->setCompletionMode(QCompleter::InlineCompletion); + QRegularExpression rx(DTG::months().join(QLatin1Char('|'))); + QRegularExpressionValidator *val = new QRegularExpressionValidator(rx, this); + m_uiLe->leLongMonth->setCompleter(completer); + m_uiLe->leLongMonth->setValidator(val); - QRegularExpression rx(DTG::months().join(QLatin1Char('|'))); - QRegularExpressionValidator* val = new QRegularExpressionValidator(rx, this); - m_uiLe->leLongMonth->setCompleter(completer); - m_uiLe->leLongMonth->setValidator(val); + connect(m_uiLe->leLongDay, &DigitsLineEdit::textEdited, this, &LtsDateTimeEdit::valueDayChanged); + connect(m_uiLe->leLongMonth, &LineEdit::textEdited, this, &LtsDateTimeEdit::valueMonthChanged2); + connect(m_uiLe->leLongTZ, &LineEdit::textEdited, this, &LtsDateTimeEdit::valueTimezoneChangedStr); + connect(m_uiLe->leLongYear, &DigitsLineEdit::textEdited, this, &LtsDateTimeEdit::valueYearChanged); - connect(m_uiLe->leLongDay, &DigitsLineEdit::textEdited, this, &LtsDateTimeEdit::valueDayChanged); - connect(m_uiLe->leLongMonth, &LineEdit::textEdited, this, &LtsDateTimeEdit::valueMonthChanged2); - connect(m_uiLe->leLongTZ, &LineEdit::textEdited, this, &LtsDateTimeEdit::valueTimezoneChangedStr); - connect(m_uiLe->leLongYear, &DigitsLineEdit::textEdited, this, &LtsDateTimeEdit::valueYearChanged); + connect(m_uiLe->leLongHHMMSS, &DigitsLineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutHHMMSS); + connect(m_uiLe->leLongDay, &DigitsLineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutDay); + connect(m_uiLe->leLongMonth, &LineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutMonth); + connect(m_uiLe->leLongTZ, &LineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutTZ); + connect(m_uiLe->leLongYear, &DigitsLineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutYear); - connect(m_uiLe->leLongHHMMSS, &DigitsLineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutHHMMSS); - connect(m_uiLe->leLongDay, &DigitsLineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutDay); - connect(m_uiLe->leLongMonth, &LineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutMonth); - connect(m_uiLe->leLongTZ, &LineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutTZ); - connect(m_uiLe->leLongYear, &DigitsLineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutYear); + connect(m_uiLe->leLongHHMMSS, &DigitsLineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); + connect(m_uiLe->leLongDay, &DigitsLineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); + connect(m_uiLe->leLongMonth, &LineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); + connect(m_uiLe->leLongTZ, &LineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); + connect(m_uiLe->leLongYear, &DigitsLineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); - connect(m_uiLe->leLongHHMMSS, &DigitsLineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); - connect(m_uiLe->leLongDay, &DigitsLineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); - connect(m_uiLe->leLongMonth, &LineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); - connect(m_uiLe->leLongTZ, &LineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); - connect(m_uiLe->leLongYear, &DigitsLineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); + connect(m_uiLe->leLongHHMMSS, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onHmsWheelEvent); + connect(m_uiLe->leLongDay, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onDayWheelEvent); + connect(m_uiLe->leLongMonth, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onMonthWheelEvent); + connect(m_uiLe->leLongYear, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onYearWheelEvent); - connect(m_uiLe->leLongHHMMSS, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onHmsWheelEvent); - connect(m_uiLe->leLongDay, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onDayWheelEvent); - connect(m_uiLe->leLongMonth, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onMonthWheelEvent); - connect(m_uiLe->leLongYear, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onYearWheelEvent); + connect(m_uiLe->checkBox, &QCheckBox::toggled, this, &LtsDateTimeEdit::onCheckBoxChanged); + connect(m_uiLe->pbNow, &QPushButton::clicked, this, &LtsDateTimeEdit::setOffsetDateTime); + connect(checkBox(), &QCheckBox::toggled, this, &LtsDateTimeEdit::toggled); - connect(m_uiLe->checkBox, &QCheckBox::toggled, this, &LtsDateTimeEdit::onCheckBoxChanged); - connect(m_uiLe->pbNow, &QPushButton::clicked, this, &LtsDateTimeEdit::setOffsetDateTime); - connect(checkBox(), &QCheckBox::toggled, this, &LtsDateTimeEdit::toggled); + setTimezone(DTG::timezone()); - setTimezone(DTG::timezone()); + setCheckable(m_checkable); - setCheckable(m_checkable); + setWithNowButton(m_withNowButton); - setWithNowButton(m_withNowButton); - - onCheckBoxChanged(); + onCheckBoxChanged(); #endif } LtsDateTimeEdit::~LtsDateTimeEdit() { - delete m_uiLe; + delete m_uiLe; } bool LtsDateTimeEdit::setupUiTouch() { - m_uiTouch = new Ui::LtsDateTimeEdit; - m_uiTouch->setupUi(this); - setFocusPolicy(Qt::StrongFocus); + m_uiTouch = new Ui::LtsDateTimeEdit; + m_uiTouch->setupUi(this); + setFocusPolicy(Qt::StrongFocus); - for (int i = 65; i < 91; i++) - { - if (QChar(i).toUpper() == QChar::fromLatin1('I')) - continue; - m_uiTouch->cbxTimeZone->addItem(QChar(i), QChar(i)); - } + for (int i = 65; i < 91; i++ ) + { + if (QChar(i).toUpper() == QChar::fromLatin1('I')) + continue; + m_uiTouch->cbxTimeZone->addItem(QChar(i), QChar(i)); + } - connect(m_uiTouch->pbNow, &QPushButton::clicked, this, &LtsDateTimeEdit::setOffsetDateTime); - connect(m_uiTouch->cbxMonth, static_cast(&QComboBox::currentIndexChanged), this, - &LtsDateTimeEdit::dateTimeChanged); - connect(m_uiTouch->spDay, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged); - connect(m_uiTouch->spHour, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged); - connect(m_uiTouch->spMinutes, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged); - connect(m_uiTouch->spSeconds, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged); - connect(m_uiTouch->spYear, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged); + connect(m_uiTouch->pbNow, &QPushButton::clicked, + this, &LtsDateTimeEdit::setOffsetDateTime); + connect(m_uiTouch->cbxMonth, static_cast(&QComboBox::currentIndexChanged), + this, &LtsDateTimeEdit::dateTimeChanged); + connect(m_uiTouch->spDay, &QSpinBox::editingFinished, + this, &LtsDateTimeEdit::dateTimeChanged); + connect(m_uiTouch->spHour, &QSpinBox::editingFinished, + this, &LtsDateTimeEdit::dateTimeChanged); + connect(m_uiTouch->spMinutes, &QSpinBox::editingFinished, + this, &LtsDateTimeEdit::dateTimeChanged); + connect(m_uiTouch->spSeconds, &QSpinBox::editingFinished, + this, &LtsDateTimeEdit::dateTimeChanged); + connect(m_uiTouch->spYear, &QSpinBox::editingFinished, + this, &LtsDateTimeEdit::dateTimeChanged); - connect(m_uiTouch->checkBox, &QCheckBox::toggled, this, &LtsDateTimeEdit::onCheckBoxChanged); - connect(m_uiTouch->cbxTimeZone, static_cast(&QComboBox::currentIndexChanged), this, - &LtsDateTimeEdit::valueTimezoneChangedInt); + connect(m_uiTouch->checkBox, &QCheckBox::toggled, + this, &LtsDateTimeEdit::onCheckBoxChanged); + connect(m_uiTouch->cbxTimeZone, static_cast(&QComboBox::currentIndexChanged), + this, &LtsDateTimeEdit::valueTimezoneChangedInt); - connect(m_uiTouch->cbxMonth, &QComboBox::currentTextChanged, this, &LtsDateTimeEdit::valueMonthChanged); + // connect(m_uiTouch->cbxMonth, static_cast(&QComboBox::currentIndexChanged), + // this, &LtsDateTimeEdit::valueMonthChanged); + connect(m_uiTouch->cbxMonth, &QComboBox::currentTextChanged, + this, &LtsDateTimeEdit::valueMonthChanged); - connect(checkBox(), &QCheckBox::toggled, this, &LtsDateTimeEdit::toggled); + connect(checkBox(), &QCheckBox::toggled, this, &LtsDateTimeEdit::toggled); - setMinMaxMonth(1, 12); + setMinMaxMonth(1,12); - setTimezone(DTG::timezone()); + setTimezone(DTG::timezone()); + //m_tzOffset = DTG::timezone2Secs(QLatin1Char(DTG::timezone()).toLatin1()); - setCheckable(m_checkable); + setCheckable(m_checkable); - setWithNowButton(m_withNowButton); + setWithNowButton(m_withNowButton); - onCheckBoxChanged(); + onCheckBoxChanged(); - return true; + return true; } -void LtsDateTimeEdit::setRetrieveCurrentTimeCallback(const CurrentTimeCallback& cb) + +void LtsDateTimeEdit::setRetrieveCurrentTimeCallback(const CurrentTimeCallback &cb) { - m_getCurrentTimeCallback = cb; + m_getCurrentTimeCallback = cb; } void LtsDateTimeEdit::setEditTimezone(const bool edit) { - m_editTimezone = edit; - if (m_uiLe) - m_uiLe->leLongTZ->setEnabled(m_editTimezone); - if (m_uiTouch) - m_uiTouch->cbxTimeZone->setEnabled(m_editTimezone); + m_editTimezone = edit; + if (m_uiLe) + m_uiLe->leLongTZ->setEnabled(m_editTimezone); + if (m_uiTouch) + m_uiTouch->cbxTimeZone->setEnabled(m_editTimezone); } void LtsDateTimeEdit::setWithButtons(const bool buttons) { - m_withButtons = buttons; - if (buttons) + m_withButtons = buttons; + if (buttons) + { + if (m_uiLe && !m_uiLe->pbBBB) { - if (m_uiLe && !m_uiLe->pbBBB) - { - m_uiLe->addButtons(this); - connect(m_uiLe->pbBBB, &QPushButton::clicked, this, &LtsDateTimeEdit::onBackHourClicked); - connect(m_uiLe->pbBB, &QPushButton::clicked, this, &LtsDateTimeEdit::onBackMinuteClicked); - connect(m_uiLe->pbB, &QPushButton::clicked, this, &LtsDateTimeEdit::onBackSecondClicked); - connect(m_uiLe->pbF, &QPushButton::clicked, this, &LtsDateTimeEdit::onForwardSecondClicked); - connect(m_uiLe->pbFF, &QPushButton::clicked, this, &LtsDateTimeEdit::onForwardMinuteClicked); - connect(m_uiLe->pbFFF, &QPushButton::clicked, this, &LtsDateTimeEdit::onForwardHourClicked); - disableControls(); - } + m_uiLe->addButtons(this); + connect(m_uiLe->pbBBB, &QPushButton::clicked, this, &LtsDateTimeEdit::onBackHourClicked); + connect(m_uiLe->pbBB, &QPushButton::clicked, this, &LtsDateTimeEdit::onBackMinuteClicked); + connect(m_uiLe->pbB, &QPushButton::clicked, this, &LtsDateTimeEdit::onBackSecondClicked); + connect(m_uiLe->pbF, &QPushButton::clicked, this, &LtsDateTimeEdit::onForwardSecondClicked); + connect(m_uiLe->pbFF, &QPushButton::clicked, this, &LtsDateTimeEdit::onForwardMinuteClicked); + connect(m_uiLe->pbFFF, &QPushButton::clicked, this, &LtsDateTimeEdit::onForwardHourClicked); + disableControls(); } - else + } + else + { + if (m_uiLe) { - if (m_uiLe) - { - delete m_uiLe->pbBBB; - delete m_uiLe->pbBB; - delete m_uiLe->pbB; - delete m_uiLe->pbFFF; - delete m_uiLe->pbFF; - delete m_uiLe->pbF; + delete m_uiLe->pbBBB; + delete m_uiLe->pbBB; + delete m_uiLe->pbB; + delete m_uiLe->pbFFF; + delete m_uiLe->pbFF; + delete m_uiLe->pbF; - m_uiLe->pbBBB = nullptr; - m_uiLe->pbBB = nullptr; - m_uiLe->pbB = nullptr; - m_uiLe->pbFFF = nullptr; - m_uiLe->pbFF = nullptr; - m_uiLe->pbF = nullptr; - } + m_uiLe->pbBBB = nullptr; + m_uiLe->pbBB = nullptr; + m_uiLe->pbB = nullptr; + m_uiLe->pbFFF = nullptr; + m_uiLe->pbFF = nullptr; + m_uiLe->pbF = nullptr; } + } } void LtsDateTimeEdit::setWithSlider(const bool slider) { - m_withSlider = slider; + m_withSlider = slider; - if (!m_uiLe) - return; + if (!m_uiLe) + return; - if (slider) - { - m_uiLe->addSlider(this); - m_uiLe->slTime->setMinimum(m_minTimeMSec / 1000); - m_uiLe->slTime->setMaximum(m_maxTimeMSec > 0 ? m_maxTimeMSec / 1000 : time(nullptr)); - connect(m_uiLe->slTime, &QSlider::sliderMoved, this, &LtsDateTimeEdit::setSliderValue); - disableControls(); - } - else - { - delete m_uiLe->slTime; - m_uiLe->slTime = nullptr; - } + if (slider) + { + m_uiLe->addSlider(this); + m_uiLe->slTime->setMinimum(m_minTimeMSec / 1000); + m_uiLe->slTime->setMaximum(m_maxTimeMSec > 0 ? m_maxTimeMSec / 1000 : time(nullptr)); + connect(m_uiLe->slTime, &QSlider::sliderMoved, this, &LtsDateTimeEdit::setSliderValue); + disableControls(); + } + else + { + delete m_uiLe->slTime; + m_uiLe->slTime = nullptr; + } } void LtsDateTimeEdit::setReadOnly(const bool readOnly) { - if (m_readOnly == readOnly) - return; - m_readOnly = readOnly; + if (m_readOnly == readOnly) + return; + m_readOnly = readOnly; - if (m_uiLe) - { - m_uiLe->leLongDay->setReadOnly(m_readOnly); - m_uiLe->leLongHHMMSS->setReadOnly(m_readOnly); - m_uiLe->leLongMonth->setReadOnly(m_readOnly); - m_uiLe->leLongTZ->setReadOnly(m_readOnly); - m_uiLe->leLongYear->setReadOnly(m_readOnly); - } - if (m_uiTouch) - { - m_uiTouch->spDay->setReadOnly(m_readOnly); - m_uiTouch->spHour->setReadOnly(m_readOnly); - m_uiTouch->spMinutes->setReadOnly(m_readOnly); - m_uiTouch->spSeconds->setReadOnly(m_readOnly); - m_uiTouch->spYear->setReadOnly(m_readOnly); - m_uiTouch->cbxTimeZone->setEnabled(m_readOnly); - } + if (m_uiLe) + { + m_uiLe->leLongDay->setReadOnly(m_readOnly); + m_uiLe->leLongHHMMSS->setReadOnly(m_readOnly); + m_uiLe->leLongMonth->setReadOnly(m_readOnly); + m_uiLe->leLongTZ->setReadOnly(m_readOnly); + m_uiLe->leLongYear->setReadOnly(m_readOnly); + } + if (m_uiTouch) + { + m_uiTouch->spDay->setReadOnly(m_readOnly); + m_uiTouch->spHour->setReadOnly(m_readOnly); + m_uiTouch->spMinutes->setReadOnly(m_readOnly); + m_uiTouch->spSeconds->setReadOnly(m_readOnly); + m_uiTouch->spYear->setReadOnly(m_readOnly); + m_uiTouch->cbxTimeZone->setEnabled(m_readOnly); + } } -QCheckBox* LtsDateTimeEdit::checkBox() const +QCheckBox *LtsDateTimeEdit::checkBox() const { - return m_uiLe ? m_uiLe->checkBox : m_uiTouch ? m_uiTouch->checkBox : nullptr; + return m_uiLe ? m_uiLe->checkBox : m_uiTouch ? m_uiTouch->checkBox : nullptr; } void LtsDateTimeEdit::setCheckable(bool checkable) { - if (!checkBox() || (m_checkable == checkable)) - return; + if (!checkBox() || (m_checkable == checkable)) + return; - m_checkable = checkable; - checkBox()->setVisible(checkable); - if (!checkable) - checkBox()->setChecked(true); + m_checkable = checkable; + checkBox()->setVisible(checkable); + if (!checkable) // If no checkBox -> set other Elements enabled + checkBox()->setChecked(true); } void LtsDateTimeEdit::setChecked(bool bChecked) { - if (!checkBox()) - return; - checkBox()->setChecked(bChecked); + if (!checkBox()) + return; + checkBox()->setChecked(bChecked); } bool LtsDateTimeEdit::isChecked() const { - if (!checkBox()) - return false; - return checkBox()->isChecked(); + if (!checkBox()) + return false; + return checkBox()->isChecked(); } -QPushButton* LtsDateTimeEdit::pbNow() const +QPushButton *LtsDateTimeEdit::pbNow() const { - return m_uiLe ? m_uiLe->pbNow : m_uiTouch ? m_uiTouch->pbNow : nullptr; + return m_uiLe ? m_uiLe->pbNow : m_uiTouch ? m_uiTouch->pbNow : nullptr; } void LtsDateTimeEdit::setWithNowButton(bool nowButton) { - if (!pbNow()) - return; + if (!pbNow()) + return; - pbNow()->setVisible(nowButton); + pbNow()->setVisible(nowButton); } bool LtsDateTimeEdit::setMsecsSinceEpoch(qint64 msec, bool setToNearestPossible) { - if (msec == 0 && isCheckable()) - { - if (m_uiLe) - m_uiLe->checkBox->setChecked(false); - m_dateIsAcceptable = true; - return true; - } + if (msec == 0 && isCheckable()) + { if (m_uiLe) - m_uiLe->checkBox->setChecked(true); - - m_dateIsAcceptable = false; - if (msec == 0) - return false; - - if (!setToNearestPossible) - { - if (!isDataAcceptable()) - return false; - } - else - { - if (msec < m_minTimeMSec && m_minTimeMSec > 0) - msec = m_minTimeMSec; - if (msec > m_maxTimeMSec && m_maxTimeMSec > 0) - msec = m_maxTimeMSec; - } - - m_curTimeMSec = msec; - - const qint64 offsetTimeZoneMsec = getTimezoneAsSecs() * 1000; - const QDateTime datetime(QDateTime::fromMSecsSinceEpoch(m_curTimeMSec + offsetTimeZoneMsec, Qt::UTC)); - const QDate date(datetime.date()); - const QTime time(datetime.time()); - - const int day = date.day(); - const int month = date.month(); - const int year = date.year(); - const int hour = time.hour(); - const int minute = time.minute(); - const int second = time.second(); - - if (!setYear(year) || !setMonth(month) || !setDay(day) || !setHHMMSS(hour, minute, second)) - return false; - - if (!isDataAcceptable()) - return false; - - enableControls(); - - emit dateTimeChanged(); - + m_uiLe->checkBox->setChecked(false); + m_dateIsAcceptable = true; return true; + } + if (m_uiLe) + m_uiLe->checkBox->setChecked(true); + + m_dateIsAcceptable = false; // will be correctly set in isDataAcceptable() + if (msec == 0) + return false; + + // nothing changed ? + // deactivate since m_offsetTimeZone may have changed: + // if (m_curTimeMSec / 1000 == msec / 1000) + // return isDataAcceptable(); + + if (!setToNearestPossible) + { + if (!isDataAcceptable()) + return false; + } + else + { + if (msec < m_minTimeMSec && m_minTimeMSec > 0) + msec = m_minTimeMSec; + if (msec > m_maxTimeMSec && m_maxTimeMSec > 0) + msec = m_maxTimeMSec; + } + + m_curTimeMSec = msec; + + const qint64 offsetTimeZoneMsec = getTimezoneAsSecs() * 1000; + const QDateTime datetime(QDateTime::fromMSecsSinceEpoch(m_curTimeMSec + offsetTimeZoneMsec, Qt::UTC)); + const QDate date(datetime.date()); + const QTime time(datetime.time()); + + const int day = date.day(); + const int month = date.month(); + const int year = date.year(); + const int hour = time.hour(); + const int minute = time.minute(); + const int second = time.second(); + + //if (!setTimezone(tz) || + if (!setYear(year) || + !setMonth(month) || + !setDay(day) || + !setHHMMSS(hour, minute, second)) + return false; + + if (!isDataAcceptable()) + return false; + + enableControls(); + + emit dateTimeChanged(); + + return true; } + qint64 LtsDateTimeEdit::msecsSinceEpoch() const { - if (isEmpty()) - return 0; + if (isEmpty()) + return 0; - if (m_uiLe && !m_uiLe->checkBox->isChecked()) - return 0; - if (m_uiTouch && !m_uiTouch->checkBox->isChecked()) - return 0; + if (m_uiLe && !m_uiLe->checkBox->isChecked()) + return 0; + if (m_uiTouch && !m_uiTouch->checkBox->isChecked()) + return 0; - auto that = const_cast(this); - if (!that->isDataAcceptable()) - return 0; + auto that = const_cast(this); + if (!that->isDataAcceptable()) + return 0; - return m_curTimeMSec; + return m_curTimeMSec; } bool LtsDateTimeEdit::setTimezone(char tz) { - tz = toupper(tz); - if (!DTG::isTimezoneValid(tz)) - return false; + tz = toupper(tz); + if (!DTG::isTimezoneValid(tz)) + return false; - if (m_uiLe) - setItemText(m_uiLe->leLongTZ, QString(QLatin1Char(tz))); - if (m_uiTouch) - setItemText(m_uiTouch->cbxTimeZone, QString(QLatin1Char(tz))); + if (m_uiLe) + setItemText(m_uiLe->leLongTZ, QString(QLatin1Char(tz))); + if (m_uiTouch) + setItemText(m_uiTouch->cbxTimeZone, QString(QLatin1Char(tz))); - setMsecsSinceEpoch(m_curTimeMSec); + setMsecsSinceEpoch(m_curTimeMSec); // to update GUI - return true; + return true; } char LtsDateTimeEdit::getTimezone() const { - QString str; - if (m_uiLe) - str = getItemText(m_uiLe->leLongTZ); - if (m_uiTouch) - str = getItemText(m_uiTouch->cbxTimeZone); + QString str; + if (m_uiLe) + str = getItemText(m_uiLe->leLongTZ); + if (m_uiTouch) + str = getItemText(m_uiTouch->cbxTimeZone); - if (str.isEmpty()) - return DTG::timezone(); - return str[0].toUpper().toLatin1(); + if (str.isEmpty()) + return DTG::timezone(); + return str[0].toUpper().toLatin1(); } qint64 LtsDateTimeEdit::getTimezoneAsSecs() const { - const char tzGUI = getTimezone(); - return DTG::timezone2Secs(tzGUI); + const char tzGUI = getTimezone(); + return DTG::timezone2Secs(tzGUI); } void LtsDateTimeEdit::clearTimezone() { - if (m_uiLe) - m_uiLe->leLongTZ->clear(); - if (m_uiTouch) - m_uiTouch->cbxTimeZone->setCurrentIndex(0); + if (m_uiLe) + m_uiLe->leLongTZ->clear(); + if (m_uiTouch) + m_uiTouch->cbxTimeZone->setCurrentIndex(0); } void LtsDateTimeEdit::setMinMaxMonth(int minMonth, int maxMonth) { - if (!m_uiTouch) - return; + if (!m_uiTouch) + return; - m_minMonth = minMonth; - m_maxMonth = maxMonth; + m_minMonth = minMonth; + m_maxMonth = maxMonth; - const int currentMonth = m_uiTouch->cbxMonth->currentData().toInt(); - m_uiTouch->cbxMonth->blockSignals(true); - m_uiTouch->cbxMonth->clear(); - for (int i = 1; i <= 12; ++i) - { - if (i < m_minMonth) - continue; - if (i > m_maxMonth) - break; + const int currentMonth = m_uiTouch->cbxMonth->currentData().toInt(); + m_uiTouch->cbxMonth->blockSignals(true); + m_uiTouch->cbxMonth->clear(); + for (int i = 1; i <= 12; ++i) + { + if (i < m_minMonth) + continue; + if (i > m_maxMonth) + break; - const QStringList& monthSl = DTG::months(); - m_uiTouch->cbxMonth->addItem(monthSl[i - 1], i); - } + // DTG-Widget: DTG = DateTimeGroup. + // So using the english abbreviations (available via DTG::months()) is correct: + const QStringList &monthSl = DTG::months(); + m_uiTouch->cbxMonth->addItem(monthSl[i-1], i); + // Former (incorrect) way + // QDate date(1777,i,1); + // m_uiTouch->cbxMonth->addItem(date.toString(QStringLiteral("MMM")), i); - m_uiTouch->cbxMonth->setCurrentIndex(m_uiTouch->cbxMonth->findData(currentMonth)); - m_uiTouch->cbxMonth->blockSignals(false); + } + // cbxMonth.currentData return the correct inht value for the month :-) + + m_uiTouch->cbxMonth->setCurrentIndex(m_uiTouch->cbxMonth->findData(currentMonth)); + m_uiTouch->cbxMonth->blockSignals(false); } -void LtsDateTimeEdit::setSubWidgetsProperties(const QString& name, const QVariant& value) + +void LtsDateTimeEdit::setSubWidgetsProperties(const QString &name, const QVariant &value) { - if (m_uiLe) - { - m_uiLe->leLongDay->setProperty(name.toStdString().c_str(), value); - m_uiLe->leLongHHMMSS->setProperty(name.toStdString().c_str(), value); - m_uiLe->leLongMonth->setProperty(name.toStdString().c_str(), value); - m_uiLe->leLongYear->setProperty(name.toStdString().c_str(), value); - m_uiLe->leLongTZ->setProperty(name.toStdString().c_str(), value); - } - if (m_uiTouch) - { - m_uiTouch->spDay->setProperty(name.toStdString().c_str(), value); - m_uiTouch->spHour->setProperty(name.toStdString().c_str(), value); - m_uiTouch->spMinutes->setProperty(name.toStdString().c_str(), value); - m_uiTouch->spSeconds->setProperty(name.toStdString().c_str(), value); - m_uiTouch->spYear->setProperty(name.toStdString().c_str(), value); - } + if (m_uiLe) + { + m_uiLe->leLongDay->setProperty(name.toStdString().c_str(), value); + m_uiLe->leLongHHMMSS->setProperty(name.toStdString().c_str(), value); + m_uiLe->leLongMonth->setProperty(name.toStdString().c_str(), value); + m_uiLe->leLongYear->setProperty(name.toStdString().c_str(), value); + m_uiLe->leLongTZ->setProperty(name.toStdString().c_str(), value); + } + if (m_uiTouch) + { + m_uiTouch->spDay->setProperty(name.toStdString().c_str(), value); + m_uiTouch->spHour->setProperty(name.toStdString().c_str(), value); + m_uiTouch->spMinutes->setProperty(name.toStdString().c_str(), value); + m_uiTouch->spSeconds->setProperty(name.toStdString().c_str(), value); + m_uiTouch->spYear->setProperty(name.toStdString().c_str(), value); + } } bool LtsDateTimeEdit::setMonth(int month) { - const auto months(DTG::months()); - if (month < 1 || month > months.size()) - return false; + const auto months(DTG::months()); + if (month < 1 || month > months.size()) + return false; - if (m_uiLe) - setItemText(m_uiLe->leLongMonth, months.at(month - 1)); - if (m_uiTouch) - setItemData(m_uiTouch->cbxMonth, month); - return true; + if (m_uiLe) + setItemText(m_uiLe->leLongMonth, months.at(month - 1)); + if (m_uiTouch) + setItemData(m_uiTouch->cbxMonth, month); + return true; } int LtsDateTimeEdit::getMonth() const { - if (m_uiLe) - { - const QString str = getItemText(m_uiLe->leLongMonth); - if (str.length() != 3) - return -1; + if (m_uiLe) + { + const QString str = getItemText(m_uiLe->leLongMonth); + if (str.length() != 3) + return -1; - int idx = DTG::months().indexOf(str); - if (idx < 0) - return -1; - return idx + 1; - } - if (m_uiTouch) - { - int month = getItemData(m_uiTouch->cbxMonth); - return month; - } - return 0; + int idx = DTG::months().indexOf(str); + if (idx < 0) + return -1; + return idx + 1; + } + if (m_uiTouch) + { + int month = getItemData(m_uiTouch->cbxMonth); + return month; + } + return 0; } bool LtsDateTimeEdit::setDay(int day) { - if (day < 1 || day > 31) - return false; + if (day < 1 || day > 31) + return false; - QString oldDay; + QString oldDay; + if (m_uiLe) + oldDay = m_uiLe->leLongDay->text(); + int oldDayInt = 0; + if (m_uiTouch) + oldDayInt = getItemValue(m_uiTouch->spDay); + + if (m_uiLe) + setItemText(m_uiLe->leLongDay, QStringLiteral("%1").arg(day, 2, 10, QLatin1Char('0'))); + if (m_uiTouch) + setItemValue(m_uiTouch->spDay, day); + + if (!isDayAcceptable()) + { if (m_uiLe) - oldDay = m_uiLe->leLongDay->text(); - int oldDayInt = 0; + setItemText(m_uiLe->leLongDay, oldDay); if (m_uiTouch) - oldDayInt = getItemValue(m_uiTouch->spDay); + setItemValue(m_uiTouch->spDay, oldDayInt); + return false; + } - if (m_uiLe) - setItemText(m_uiLe->leLongDay, QStringLiteral("%1").arg(day, 2, 10, QLatin1Char('0'))); - if (m_uiTouch) - setItemValue(m_uiTouch->spDay, day); - - if (!isDayAcceptable()) - { - if (m_uiLe) - setItemText(m_uiLe->leLongDay, oldDay); - if (m_uiTouch) - setItemValue(m_uiTouch->spDay, oldDayInt); - return false; - } - - return true; + return true; } int LtsDateTimeEdit::getDay() const { - if (m_uiLe) - return m_uiLe->leLongDay->getValue(); - if (m_uiTouch) - return getItemValue(m_uiTouch->spDay); - return 0; + if (m_uiLe) + return m_uiLe->leLongDay->getValue(); + if (m_uiTouch) + return getItemValue(m_uiTouch->spDay); + return 0; } bool LtsDateTimeEdit::setHHMMSS(int hour, int minute, int second) { - if (hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59) - return false; + if (hour < 0 || hour > 23 || + minute < 0 || minute > 59 || + second < 0 || second > 59) + return false; - if (m_uiLe) - m_uiLe->leLongHHMMSS->setValue(hour * 10000 + minute * 100 + second); - if (m_uiTouch) - { - setItemValue(m_uiTouch->spHour, hour); - setItemValue(m_uiTouch->spMinutes, minute); - setItemValue(m_uiTouch->spSeconds, second); - } + if (m_uiLe) + m_uiLe->leLongHHMMSS->setValue(hour * 10000 + minute * 100 + second); + if (m_uiTouch) + { + setItemValue(m_uiTouch->spHour , hour); + setItemValue(m_uiTouch->spMinutes, minute); + setItemValue(m_uiTouch->spSeconds, second); + } - return true; + return true; } int LtsDateTimeEdit::getHour() const { - if (m_uiLe) - { - const int time = m_uiLe->leLongHHMMSS->getValue(); - return time / 10000; - } - if (m_uiTouch) - { - return getItemValue(m_uiTouch->spHour); - } - return 0; + if (m_uiLe) + { + const int time = m_uiLe->leLongHHMMSS->getValue(); + return time / 10000; + } + if (m_uiTouch) + { + return getItemValue(m_uiTouch->spHour); + } + return 0; } int LtsDateTimeEdit::getMinute() const { - if (m_uiLe) - { - const int time = m_uiLe->leLongHHMMSS->getValue(); - return (time / 100) % 100; - } - if (m_uiTouch) - { - return getItemValue(m_uiTouch->spMinutes); - } - return 0; + if (m_uiLe) + { + const int time = m_uiLe->leLongHHMMSS->getValue(); + return (time / 100) % 100; + } + if (m_uiTouch) + { + return getItemValue(m_uiTouch->spMinutes); + } + return 0; } int LtsDateTimeEdit::getSecond() const { - if (m_uiLe) - { - const int time = m_uiLe->leLongHHMMSS->getValue(); - return time % 100; - } - if (m_uiTouch) - { - return getItemValue(m_uiTouch->spSeconds); - } - return 0; + if (m_uiLe) + { + const int time = m_uiLe->leLongHHMMSS->getValue(); + return time % 100; + } + if (m_uiTouch) + { + return getItemValue(m_uiTouch->spSeconds); + } + return 0; } bool LtsDateTimeEdit::setYear(int year) { - int finalYear = -1; - if (year >= 0 && year <= 99) - finalYear = year; - else if (year >= 2000 && year <= 2099) - finalYear = year - 2000; + int finalYear = -1; + if (year >= 0 && year <= 99) + finalYear = year; + else if (year >= 2000 && year <= 2099) + finalYear = year - 2000; - if (finalYear >= 0) - { - if (m_uiLe) - m_uiLe->leLongYear->setValue(finalYear); - if (m_uiTouch) - setItemValue(m_uiTouch->spYear, finalYear); - return true; - } + if (finalYear >= 0) + { + if (m_uiLe) + m_uiLe->leLongYear->setValue(finalYear); + if (m_uiTouch) + setItemValue(m_uiTouch->spYear, finalYear); + return true; + } - return false; + return false; } int LtsDateTimeEdit::getYear() const { - if (m_uiLe) - return 2000 + m_uiLe->leLongYear->getValue(); - if (m_uiTouch) - return 2000 + m_uiTouch->spYear->value(); - return 2000; + if (m_uiLe) + return 2000 + m_uiLe->leLongYear->getValue(); + if (m_uiTouch) + return 2000 + m_uiTouch->spYear->value(); + return 2000; } bool LtsDateTimeEdit::isEmpty() const { - return (isEmptyDay() || isEmptyHHMMSS() || isEmptyMonth() || isEmptyTimezone() || isEmptyYear()); + return (isEmptyDay() || + isEmptyHHMMSS() || + isEmptyMonth() || + isEmptyTimezone() || + isEmptyYear()); } bool LtsDateTimeEdit::isValidDate() const { - return m_dateIsAcceptable; + return m_dateIsAcceptable; } + bool LtsDateTimeEdit::isEmptyDay() const { - if (m_uiLe) - return m_uiLe->leLongDay->isEmpty(); - return false; + if (m_uiLe) + return m_uiLe->leLongDay->isEmpty(); + return false; // spinBox can´t be empty } bool LtsDateTimeEdit::isEmptyHHMMSS() const { - if (m_uiLe) - return m_uiLe->leLongHHMMSS->isEmpty(); - return false; + if (m_uiLe) + return m_uiLe->leLongHHMMSS->isEmpty(); + return false; // spinBox can´t be empty } bool LtsDateTimeEdit::isEmptyMonth() const { - if (m_uiLe) - return m_uiLe->leLongMonth->text().isEmpty(); - return false; + if (m_uiLe) + return m_uiLe->leLongMonth->text().isEmpty(); + return false; // spinBox can´t be empty } bool LtsDateTimeEdit::isEmptyTimezone() const { - if (m_uiLe) - return m_uiLe->leLongTZ->text().isEmpty(); - return false; + if (m_uiLe) + return m_uiLe->leLongTZ->text().isEmpty(); + return false; // comboBox can´t be empty } bool LtsDateTimeEdit::isEmptyYear() const { - if (m_uiLe) - return m_uiLe->leLongYear->isEmpty(); - return false; + if (m_uiLe) + return m_uiLe->leLongYear->isEmpty(); + return false; // spinBox can´t be empty } bool LtsDateTimeEdit::hasFocus() const { - if (!m_uiLe) - return false; - return (m_uiLe->leLongDay->hasFocus() || m_uiLe->leLongHHMMSS->hasFocus() || m_uiLe->leLongMonth->hasFocus() || - m_uiLe->leLongTZ->hasFocus() || m_uiLe->leLongYear->hasFocus()); + if (!m_uiLe) + return false; + return (m_uiLe->leLongDay->hasFocus() || + m_uiLe->leLongHHMMSS->hasFocus() || + m_uiLe->leLongMonth->hasFocus() || + m_uiLe->leLongTZ->hasFocus() || + m_uiLe->leLongYear->hasFocus()); } bool LtsDateTimeEdit::isDataAcceptable() { - m_dateIsAcceptable = false; + m_dateIsAcceptable = false; - bool state = isDayAcceptable() && isHHMMSSAcceptable() && isMonthAcceptable() && isYearAcceptable() && - QDate::isValid(getYear(), getMonth(), getDay()) && QTime::isValid(getHour(), getMinute(), getSecond()); + bool state = + isDayAcceptable() && + isHHMMSSAcceptable() && + isMonthAcceptable() && + isYearAcceptable() && + QDate::isValid(getYear(), getMonth(), getDay()) && + QTime::isValid(getHour(), getMinute(), getSecond()); - if (m_editTimezone && state) - state = isTzAcceptable(); + if (m_editTimezone && state) + state = isTzAcceptable(); - showInvalidData(false); + showInvalidData(false); - if (!state) - { - disableControls(); - return false; - } + if (!state) + { + disableControls(); + return false; + } - qint64 msec = QDateTime(QDate(getYear(), getMonth(), getDay()), QTime(getHour(), getMinute(), getSecond()), Qt::UTC) - .toMSecsSinceEpoch(); - msec -= DTG::timezone2Secs(getTimezone()) * 1000LL; - if (m_minTimeMSec > 0 && m_maxTimeMSec > 0 && m_minTimeMSec < m_maxTimeMSec) - { - if (msec < m_minTimeMSec || msec > m_maxTimeMSec) - return false; - } + qint64 msec = QDateTime(QDate(getYear(), getMonth(), getDay()), QTime(getHour(), getMinute(), getSecond()), Qt::UTC).toMSecsSinceEpoch(); + msec -= DTG::timezone2Secs(getTimezone()) * 1000LL; + if (m_minTimeMSec > 0 && m_maxTimeMSec > 0 && m_minTimeMSec < m_maxTimeMSec) + { + if (msec < m_minTimeMSec || msec > m_maxTimeMSec) + return false; + } - m_curTimeMSec = msec; - enableControls(); - m_dateIsAcceptable = true; - return true; + m_curTimeMSec = msec; + enableControls(); + m_dateIsAcceptable = true; + return true; } bool LtsDateTimeEdit::isDayAcceptable() const { - int value = getDay(); - int max = 31; - if (isMonthAcceptable()) + int value = getDay(); + int max = 31; + if (isMonthAcceptable()) + { + const int month = getMonth(); + switch (month) { - const int month = getMonth(); - switch (month) - { - case 2: { - max = 28; - if (isYearAcceptable()) - { - if (getYear() % 4 == 0 && (getYear() % 100 != 0 || getYear() % 400 == 0)) - - max = 29; - } - break; - } - case 4: - case 6: - case 9: - case 11: - max = 30; - break; - default: - break; - } + case 2: + { + max = 28; + if (isYearAcceptable()) + { + if (getYear() % 4 == 0 && (getYear() % 100 != 0 || getYear() % 400 == 0)) + // centennial years (2100, 2200...) are not leap, unless they divide by 400 (2000, 2400...)! + max = 29; + } + break; } - return (value > 0 && value <= max); + case 4: + case 6: + case 9: + case 11: + max = 30; + break; + default: + break; + } + } + return (value > 0 && value <= max); } bool LtsDateTimeEdit::isHHMMSSAcceptable() const { - int hh = getHour(); - if (hh < 0 || hh > 23) - return false; + int hh = getHour(); + if (hh < 0 || hh > 23) + return false; - int mm = getMinute(); - if (mm < 0 || mm > 59) - return false; + int mm = getMinute(); + if (mm < 0 || mm > 59) + return false; - int ss = getSecond(); - if (ss < 0 || ss > 59) - return false; + int ss = getSecond(); + if (ss < 0 || ss > 59) + return false; - return true; + return true; } bool LtsDateTimeEdit::isMonthAcceptable() const { - int value = getMonth(); - return (value > 0 && value <= 12); + int value = getMonth(); + return (value > 0 && value <= 12); } bool LtsDateTimeEdit::isYearAcceptable() const { - if (m_uiLe) - return isLineEditDataAcceptable(m_uiLe->leLongYear); - return true; + if (m_uiLe) + return isLineEditDataAcceptable(m_uiLe->leLongYear); + return true; // spinBox/combobox !acceptable } bool LtsDateTimeEdit::isTzAcceptable() const { - if (m_uiLe) - return isLineEditDataAcceptable(m_uiLe->leLongTZ); - return true; + if (m_uiLe) + return isLineEditDataAcceptable(m_uiLe->leLongTZ); + return true; // spinBox/combobox !acceptable } void LtsDateTimeEdit::showInvalidData(bool setFocus) { - if (!m_uiLe) - return; + if (!m_uiLe) + return; - bool focus = setFocus; + bool focus = setFocus; // Fokus bei Fehler setzen ??? - auto check = [&](QLineEdit* le, bool isValid) { - if (isValid) - le->setStyleSheet(QString()); - else - { - le->setStyleSheet(QLatin1String("background-color: yellow;")); - if (focus) - { - le->setFocus(); - focus = false; - } - } - }; + auto check = [&](QLineEdit * le, bool isValid) + { + if (isValid) + le->setStyleSheet(QString()); + else + { + le->setStyleSheet(QLatin1String("background-color: yellow;")); + if (focus) + { + le->setFocus(); + focus = false; + } + } + }; - check(m_uiLe->leLongDay, isDayAcceptable()); - check(m_uiLe->leLongHHMMSS, isHHMMSSAcceptable()); - if (m_editTimezone) - check(m_uiLe->leLongTZ, isTzAcceptable()); - check(m_uiLe->leLongMonth, isMonthAcceptable()); - check(m_uiLe->leLongYear, isYearAcceptable()); + check(m_uiLe->leLongDay, isDayAcceptable()); + check(m_uiLe->leLongHHMMSS, isHHMMSSAcceptable()); + if (m_editTimezone) + check(m_uiLe->leLongTZ, isTzAcceptable()); + check(m_uiLe->leLongMonth, isMonthAcceptable()); + check(m_uiLe->leLongYear, isYearAcceptable()); } -bool LtsDateTimeEdit::isLineEditDataAcceptable(QLineEdit* le) const +bool LtsDateTimeEdit::isLineEditDataAcceptable(QLineEdit *le) const { - const QValidator* pValidator = le->validator(); + const QValidator *pValidator = le->validator(); - if (!pValidator) - return true; + if (!pValidator) + return true; - QString text = le->text(); + QString text = le->text(); - int pos; - QValidator::State state = pValidator->validate(text, pos); + int pos; + QValidator::State state = pValidator->validate(text, pos); - if (state == QValidator::Acceptable || state == QValidator::Intermediate) - return true; + if (state == QValidator::Acceptable || state == QValidator::Intermediate) + return true; - return false; + return false; } void LtsDateTimeEdit::setFixedDateTime() { - setMsecsSinceEpoch(LtsUtils::OperatorSettings::getInstance() - ->value(QStringLiteral("TimeSettings"), QStringLiteral("FixedTime"), 0) - .toLongLong()); + setMsecsSinceEpoch(LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("TimeSettings"), QStringLiteral("FixedTime"), 0).toLongLong()); } void LtsDateTimeEdit::setOffsetDateTime() { - if (!m_getCurrentTimeCallback) - return; + if (!m_getCurrentTimeCallback) + return; - qint64 offset = LtsUtils::OperatorSettings::getInstance() - ->value(QStringLiteral("TimeSettings"), QStringLiteral("Offset"), 0) - .toLongLong(); - - setMsecsSinceEpoch((m_getCurrentTimeCallback() / 1000) * 1000 + offset); + qint64 offset = LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("TimeSettings"), QStringLiteral("Offset"), 0).toLongLong(); + // we only show seconds, so strip away milliseconds + setMsecsSinceEpoch((m_getCurrentTimeCallback() / 1000) * 1000 + offset); } void LtsDateTimeEdit::setSliderValue(int val) { - setMsecsSinceEpoch(val * 1000LL); + setMsecsSinceEpoch(val * 1000LL); } -void LtsDateTimeEdit::valueDayChanged(const QString& str) +void LtsDateTimeEdit::valueDayChanged(const QString &str) { - if (!m_uiLe) - return; - int curpos = m_uiLe->leLongDay->cursorPosition(); - int cp = curpos; + if (!m_uiLe) + return; + int curpos = m_uiLe->leLongDay->cursorPosition(); + int cp = curpos; - bool changed = false; + bool changed = false; - QString tag(str); + QString tag(str); - if (tag.length() > 2) + if (tag.length() > 2) + { + tag = tag.left(2); + changed = true; + } + + bool ok; + int t = tag.toInt(&ok, 10); + + if (ok) + { + if (t > 31) { - tag = tag.left(2); - changed = true; + tag.remove(curpos - 1, 1); // letztes Zeichen wieder entfernen + if (cp >= curpos) + cp--; // Korrektur der neuen Cursorposition + changed = true; } + } - bool ok; - int t = tag.toInt(&ok, 10); + if (changed) + { + m_uiLe->leLongDay->setText(tag); + m_uiLe->leLongDay->setCursorPosition(cp); + } - if (ok) - { - if (t > 31) - { - tag.remove(curpos - 1, 1); - if (cp >= curpos) - cp--; - changed = true; - } - } + if (tag.length() == 2) + { + showInvalidData(false); - if (changed) - { - m_uiLe->leLongDay->setText(tag); - m_uiLe->leLongDay->setCursorPosition(cp); - } - - if (tag.length() == 2) - { - showInvalidData(false); - - if (m_autoForward) - focusNextPrevChild(true); - } + if (m_autoForward) + focusNextPrevChild(true); + } } void LtsDateTimeEdit::fixupHHMMSS() { - if (!m_uiLe) - return; + if (!m_uiLe) + return; - int curpos = m_uiLe->leLongHHMMSS->cursorPosition(); - int cp = curpos; + int curpos = m_uiLe->leLongHHMMSS->cursorPosition(); + int cp = curpos; - bool changed = false; + bool changed = false; - QString uhrzeit(m_uiLe->leLongHHMMSS->text()); + QString uhrzeit(m_uiLe->leLongHHMMSS->text()); - QString hh; - QString mm; - QString ss; + // + // Wertebereich überprüfen: 000000 bis 235959 zulässig + // - if (uhrzeit.length() > 1) - hh = uhrzeit.left(2); + + QString hh; + QString mm; + QString ss; + + if (uhrzeit.length() > 1) + hh = uhrzeit.left(2); + else + hh = uhrzeit + QLatin1Char('0'); + + if (uhrzeit.length() > 0) + { + if (uhrzeit.length() == 1) + hh = uhrzeit.mid(0, 1) + QLatin1Char('0'); + else if (uhrzeit.length() >= 2) + { + hh = uhrzeit.mid(0, 2); + if (uhrzeit.length() > 2) + { + if (uhrzeit.length() == 3) + mm = uhrzeit.mid(2, 1) + QLatin1Char('0'); + else if (uhrzeit.length() >= 4) + { + mm = uhrzeit.mid(2, 2); + if (uhrzeit.length() == 5) + ss = uhrzeit.mid(4, 1) + QLatin1Char('0'); + else if (uhrzeit.length() == 6) + ss = uhrzeit.mid(4, 2); + } + } + } + } + + bool ok; + + int h = hh.toInt(&ok, 10); + if (ok) + { + if (h > 23) + { + uhrzeit.remove(curpos - 1, 1); // letztes Zeichen wieder entfernen + if (cp >= curpos) + cp--; // Korrektur der neuen Cursorposition + changed = true; + } + } + + int m = mm.toInt(&ok, 10); + + if (ok) + { + if ((hh.length() == 2) && (m > 59)) // WICHTIG: beide Stellen fuer Stunde bereits gesetzt !!! + { + uhrzeit.remove(curpos - 1, 1); // letztes Zeichen wieder entfernen + if (cp >= curpos) + cp--; // Korrektur der neuen Cursorposition + changed = true; + } + } + + int s = ss.toInt(&ok, 10); + + if (ok) + { + if ((hh.length() == 2 && mm.length() == 2) && (s > 59)) // WICHTIG: beide Stellen fuer Stunde und Minute bereits gesetzt !!! + { + uhrzeit.remove(curpos - 1, 1); // letztes Zeichen wieder entfernen + if (cp >= curpos) + cp--; // Korrektur der neuen Cursorposition + changed = true; + } + } + + if (changed) + { + m_uiLe->leLongHHMMSS->setText(uhrzeit); + m_uiLe->leLongHHMMSS->setCursorPosition(cp); + } + + isDataAcceptable(); + emit dateTimeChanged(); +} + +void LtsDateTimeEdit::valueMonthChanged2(const QString &str) +{ + if (!m_uiLe) + return; + if (str.length() == 3 && m_uiLe->leLongMonth->selectedText().isEmpty()) + focusNextPrevChild(true); +} + +void LtsDateTimeEdit::valueMonthChanged(const QString &str) +{ + if (!m_uiLe) + return; + int curpos = m_uiLe->leLongMonth->cursorPosition(); + int cp = curpos; + + bool changed = false; + + QString monStr = str; + + const auto months = DTG::months(); + for (int i = 0; i < months.size(); ++i) + { + const QString &mon = months.at(i); + if (mon.startsWith(monStr, Qt::CaseInsensitive)) + { + monStr = mon; + changed = true; + break; + } + } + + if (!changed) + { + monStr.remove(curpos - 1, 1); // letztes Zeichen wieder entfernen + if (cp >= curpos) + cp--; // Korrektur der neuen Cursorposition + changed = true; + } + + if (changed) + { + m_uiLe->leLongMonth->setText(monStr); + // WICHTIG: keine negativen Cursorpositionen setzen, da sonst Absturzgefahr !!! + // Bem.: wird in DigitsLineEdit bereits abgefangen + if (cp > 0) + m_uiLe->leLongMonth->setCursorPosition(cp); else - hh = uhrzeit + QLatin1Char('0'); - - if (uhrzeit.length() > 0) - { - if (uhrzeit.length() == 1) - hh = uhrzeit.mid(0, 1) + QLatin1Char('0'); - else if (uhrzeit.length() >= 2) - { - hh = uhrzeit.mid(0, 2); - if (uhrzeit.length() > 2) - { - if (uhrzeit.length() == 3) - mm = uhrzeit.mid(2, 1) + QLatin1Char('0'); - else if (uhrzeit.length() >= 4) - { - mm = uhrzeit.mid(2, 2); - if (uhrzeit.length() == 5) - ss = uhrzeit.mid(4, 1) + QLatin1Char('0'); - else if (uhrzeit.length() == 6) - ss = uhrzeit.mid(4, 2); - } - } - } - } - - bool ok; - - int h = hh.toInt(&ok, 10); - if (ok) - { - if (h > 23) - { - uhrzeit.remove(curpos - 1, 1); - if (cp >= curpos) - cp--; - changed = true; - } - } - - int m = mm.toInt(&ok, 10); - - if (ok) - { - if ((hh.length() == 2) && (m > 59)) - { - uhrzeit.remove(curpos - 1, 1); - if (cp >= curpos) - cp--; - changed = true; - } - } - - int s = ss.toInt(&ok, 10); - - if (ok) - { - if ((hh.length() == 2 && mm.length() == 2) && (s > 59)) - { - uhrzeit.remove(curpos - 1, 1); - if (cp >= curpos) - cp--; - changed = true; - } - } - - if (changed) - { - m_uiLe->leLongHHMMSS->setText(uhrzeit); - m_uiLe->leLongHHMMSS->setCursorPosition(cp); - } - - isDataAcceptable(); - emit dateTimeChanged(); -} - -void LtsDateTimeEdit::valueMonthChanged2(const QString& str) -{ - if (!m_uiLe) - return; - if (str.length() == 3 && m_uiLe->leLongMonth->selectedText().isEmpty()) - focusNextPrevChild(true); -} - -void LtsDateTimeEdit::valueMonthChanged(const QString& str) -{ - if (!m_uiLe) - return; - int curpos = m_uiLe->leLongMonth->cursorPosition(); - int cp = curpos; - - bool changed = false; - - QString monStr = str; - - const auto months = DTG::months(); - for (int i = 0; i < months.size(); ++i) - { - const QString& mon = months.at(i); - if (mon.startsWith(monStr, Qt::CaseInsensitive)) - { - monStr = mon; - changed = true; - break; - } - } - - if (!changed) - { - monStr.remove(curpos - 1, 1); - if (cp >= curpos) - cp--; - changed = true; - } - - if (changed) - { - m_uiLe->leLongMonth->setText(monStr); - - if (cp > 0) - m_uiLe->leLongMonth->setCursorPosition(cp); - else - m_uiLe->leLongMonth->setCursorPosition(1); - } - - if (monStr.size() == 3) - { - showInvalidData(false); - if (m_autoForward) - focusNextPrevChild(true); - } -} - -void LtsDateTimeEdit::valueTimezoneChangedStr(const QString& str) -{ - if (str.length() > 1) - { - clearTimezone(); - return; - } - if (str.length() == 0) - return; - QChar c = str.at(0); - if (!c.isLetter() || c.toUpper() == QLatin1Char('J')) - { - clearTimezone(); - return; - } - if (c.isLower()) - setTimezone(c.toUpper().toLatin1()); + m_uiLe->leLongMonth->setCursorPosition(1); // Ausweichposition linker Textanfang + } + if (monStr.size() == 3) + { showInvalidData(false); if (m_autoForward) - focusNextPrevChild(true); + focusNextPrevChild(true); + } +} + +void LtsDateTimeEdit::valueTimezoneChangedStr(const QString &str) +{ + if (str.length() > 1) + { + clearTimezone(); + return; + } + if (str.length() == 0) + return; + QChar c = str.at(0); + if (!c.isLetter() || c.toUpper() == QLatin1Char('J')) + { + clearTimezone(); + return; + } + if (c.isLower()) + setTimezone(c.toUpper().toLatin1()); + + showInvalidData(false); + if (m_autoForward) + focusNextPrevChild(true); } void LtsDateTimeEdit::valueTimezoneChangedInt(int newTimezone) { - Q_UNUSED(newTimezone); - if (!m_uiTouch) - return; - const QString& curText = m_uiTouch->cbxTimeZone->currentText(); - if (curText.isEmpty()) - return; + Q_UNUSED(newTimezone); + if (!m_uiTouch) + return; + const QString &curText = m_uiTouch->cbxTimeZone->currentText(); + if (curText.isEmpty()) + return; - const QChar tz = curText.at(0); - setTimezone(tz.toUpper().toLatin1()); + const QChar tz = curText.at(0); + setTimezone(tz.toUpper().toLatin1()); } -void LtsDateTimeEdit::valueYearChanged(const QString& str) +void LtsDateTimeEdit::valueYearChanged(const QString &str) { - if (!m_uiLe) - return; - int curpos = m_uiLe->leLongYear->cursorPosition(); - int cp = curpos; + if (!m_uiLe) + return; + int curpos = m_uiLe->leLongYear->cursorPosition(); + int cp = curpos; - bool changed = false; + bool changed = false; - const QString& year = str; + const QString &year = str; - QString yy; - if (year.length() > 2) - { - yy = year.left(2); - changed = true; - } + QString yy; + if (year.length() > 2) + { + yy = year.left(2); + changed = true; + } - if (changed) - { - m_uiLe->leLongYear->setText(yy); - m_uiLe->leLongYear->setCursorPosition(cp); - } + if (changed) + { + m_uiLe->leLongYear->setText(yy); + m_uiLe->leLongYear->setCursorPosition(cp); + } - if (year.length() == 2) - { - showInvalidData(false); - if (m_autoForward) - focusNextPrevChild(true); - } + if (year.length() == 2) + { + showInvalidData(false); + if (m_autoForward) + focusNextPrevChild(true); + } } void LtsDateTimeEdit::onBackHourClicked() { - if (!setMsecsSinceEpoch(m_curTimeMSec - s_oneHourMSec)) - setMsecsSinceEpoch(m_minTimeMSec); + if (!setMsecsSinceEpoch(m_curTimeMSec - s_oneHourMSec)) + setMsecsSinceEpoch(m_minTimeMSec); } void LtsDateTimeEdit::onBackMinuteClicked() { - const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; - if (!setMsecsSinceEpoch(m_curTimeMSec - ofs * s_oneMinuteMSec)) - setMsecsSinceEpoch(m_minTimeMSec); + const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; + if (!setMsecsSinceEpoch(m_curTimeMSec - ofs * s_oneMinuteMSec)) + setMsecsSinceEpoch(m_minTimeMSec); } void LtsDateTimeEdit::onBackSecondClicked() { - const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; - if (!setMsecsSinceEpoch(m_curTimeMSec - ofs * s_oneSecondMSec)) - setMsecsSinceEpoch(m_minTimeMSec); + const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; + if (!setMsecsSinceEpoch(m_curTimeMSec - ofs * s_oneSecondMSec)) + setMsecsSinceEpoch(m_minTimeMSec); } void LtsDateTimeEdit::onForwardSecondClicked() { - const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; - if (!setMsecsSinceEpoch(m_curTimeMSec + ofs * s_oneSecondMSec)) - setMsecsSinceEpoch(m_maxTimeMSec); + const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; + if (!setMsecsSinceEpoch(m_curTimeMSec + ofs * s_oneSecondMSec)) + setMsecsSinceEpoch(m_maxTimeMSec); } void LtsDateTimeEdit::onForwardMinuteClicked() { - const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; - if (!setMsecsSinceEpoch(m_curTimeMSec + ofs * s_oneMinuteMSec)) - setMsecsSinceEpoch(m_maxTimeMSec); + const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; + if (!setMsecsSinceEpoch(m_curTimeMSec + ofs * s_oneMinuteMSec)) + setMsecsSinceEpoch(m_maxTimeMSec); } void LtsDateTimeEdit::onForwardHourClicked() { - if (!setMsecsSinceEpoch(m_curTimeMSec + s_oneHourMSec)) - setMsecsSinceEpoch(m_maxTimeMSec); + if (!setMsecsSinceEpoch(m_curTimeMSec + s_oneHourMSec)) + setMsecsSinceEpoch(m_maxTimeMSec); } void LtsDateTimeEdit::onCheckBoxChanged() { - QVector widgets; - bool bEnable = false; + QVector widgets; + bool bEnable = false; - if (m_uiLe) - { - widgets = {m_uiLe->leLongDay, m_uiLe->leLongHHMMSS, m_uiLe->leLongTZ, m_uiLe->leLongMonth, m_uiLe->leLongYear}; - } + if (m_uiLe) + { + widgets = {m_uiLe->leLongDay, m_uiLe->leLongHHMMSS, m_uiLe->leLongTZ, + m_uiLe->leLongMonth, m_uiLe->leLongYear}; + } - if (m_uiTouch) - { - widgets = {m_uiTouch->spDay, m_uiTouch->spHour, m_uiTouch->spMinutes, m_uiTouch->spSeconds, - m_uiTouch->spYear, m_uiTouch->cbxMonth, m_uiTouch->cbxTimeZone, m_uiTouch->pbNow}; - } + if (m_uiTouch) + { + widgets = {m_uiTouch->spDay, m_uiTouch->spHour, m_uiTouch->spMinutes, m_uiTouch->spSeconds, m_uiTouch->spYear, m_uiTouch->cbxMonth, m_uiTouch->cbxTimeZone, m_uiTouch->pbNow}; + } - bEnable = checkBox()->isChecked(); - for (auto w : std::as_const(widgets)) - { - if (w) - w->setEnabled(bEnable); - } - enaDisaControls(bEnable); + bEnable = checkBox()->isChecked(); + for (auto w : qAsConst(widgets)) + { + if (w) + w->setEnabled(bEnable); + } + enaDisaControls(bEnable); } void LtsDateTimeEdit::disableControls() { - enaDisaControls(false); + enaDisaControls(false); } void LtsDateTimeEdit::enableControls() { - if (!m_uiLe) - return; + if (!m_uiLe) + return; - enaDisaControls(true); - if (m_withSlider && m_minTimeMSec != 0 && m_maxTimeMSec > 0 && m_maxTimeMSec > m_minTimeMSec) - { - m_uiLe->slTime->setEnabled(true); - m_uiLe->slTime->setValue(m_curTimeMSec / 1000LL); - } + enaDisaControls(true); + if (m_withSlider && + m_minTimeMSec != 0 && + m_maxTimeMSec > 0 && + m_maxTimeMSec > m_minTimeMSec) + { + m_uiLe->slTime->setEnabled(true); + m_uiLe->slTime->setValue(m_curTimeMSec / 1000LL); + } } void LtsDateTimeEdit::enaDisaControls(bool bEnable) { - if (!m_uiLe) - return; - const QVector widgets( - {m_uiLe->pbBBB, m_uiLe->pbBB, m_uiLe->pbB, m_uiLe->pbF, m_uiLe->pbFF, m_uiLe->pbFFF, m_uiLe->slTime}); - for (auto w : widgets) - { - if (w) - w->setEnabled(bEnable); - } + if (!m_uiLe) + return; + const QVector widgets({m_uiLe->pbBBB, m_uiLe->pbBB, m_uiLe->pbB, + m_uiLe->pbF, m_uiLe->pbFF, m_uiLe->pbFFF, + m_uiLe->slTime}); + for (auto w : widgets) + { + if (w) + w->setEnabled(bEnable); + } } void LtsDateTimeEdit::setMinimumTimeMSec(qint64 msec) { - if (m_minTimeMSec == msec) - return; - m_minTimeMSec = msec; - if (m_minTimeMSec > 0 && m_uiLe && m_uiLe->slTime) - { - m_uiLe->slTime->setMinimum(m_minTimeMSec / 1000LL); - if (m_maxTimeMSec > m_minTimeMSec) - m_uiLe->slTime->setEnabled(true); - } - if (m_curTimeMSec < m_minTimeMSec) - setMsecsSinceEpoch(m_minTimeMSec); + if (m_minTimeMSec == msec) + return; + m_minTimeMSec = msec; + if (m_minTimeMSec > 0 && m_uiLe && m_uiLe->slTime) + { + m_uiLe->slTime->setMinimum(m_minTimeMSec / 1000LL); + if (m_maxTimeMSec > m_minTimeMSec) + m_uiLe->slTime->setEnabled(true); + } + if (m_curTimeMSec < m_minTimeMSec) + setMsecsSinceEpoch(m_minTimeMSec); } void LtsDateTimeEdit::setMaximumTimeMSec(qint64 msec) { - if (m_maxTimeMSec == msec) - return; - m_maxTimeMSec = msec; - if (!m_uiLe || !m_uiLe->slTime) - return; + if (m_maxTimeMSec == msec) + return; + m_maxTimeMSec = msec; + if (!m_uiLe || !m_uiLe->slTime) + return; - m_uiLe->slTime->setMaximum(m_maxTimeMSec / 1000LL); - if (m_minTimeMSec > 0 && m_maxTimeMSec > m_minTimeMSec) - m_uiLe->slTime->setEnabled(true); - if (m_maxTimeMSec > 0 && m_curTimeMSec > m_maxTimeMSec) - setMsecsSinceEpoch(m_maxTimeMSec); + m_uiLe->slTime->setMaximum(m_maxTimeMSec / 1000LL); + if (m_minTimeMSec > 0 && m_maxTimeMSec > m_minTimeMSec) + m_uiLe->slTime->setEnabled(true); + if (m_maxTimeMSec > 0 && m_curTimeMSec > m_maxTimeMSec) + setMsecsSinceEpoch(m_maxTimeMSec); } void LtsDateTimeEdit::clear() { - if (m_uiLe) - { - m_uiLe->leLongDay->clear(); - m_uiLe->leLongHHMMSS->clear(); - m_uiLe->leLongMonth->clear(); - m_uiLe->leLongYear->clear(); - m_uiLe->leLongTZ->clear(); - m_curTimeMSec = 0; - } - if (m_uiTouch) - { - m_uiTouch->spDay->clear(); - m_uiTouch->spHour->clear(); - m_uiTouch->spMinutes->clear(); - m_uiTouch->spSeconds->clear(); - m_uiTouch->spYear->clear(); - } - emit dateTimeChanged(); + if (m_uiLe) + { + m_uiLe->leLongDay->clear(); + m_uiLe->leLongHHMMSS->clear(); + m_uiLe->leLongMonth->clear(); + m_uiLe->leLongYear->clear(); + m_uiLe->leLongTZ->clear(); + m_curTimeMSec = 0; + } + if (m_uiTouch) + { + m_uiTouch->spDay->clear(); + m_uiTouch->spHour->clear(); + m_uiTouch->spMinutes->clear(); + m_uiTouch->spSeconds->clear(); + m_uiTouch->spYear->clear(); + } + emit dateTimeChanged(); + } void LtsDateTimeEdit::onFocusOutDay() { - if (!m_uiLe) - return; - if (m_backspacePressed) - { - m_backspacePressed = false; - return; - } - if (!m_recursionAvoid && !hasFocus()) - onFocusOut(); + if (!m_uiLe) + return; + if (m_backspacePressed) + { + m_backspacePressed = false; + return; + } + if (!m_recursionAvoid && !hasFocus()) + onFocusOut(); - QString value = m_uiLe->leLongDay->text(); - - if (value.length() == 0 && !m_backspacePressed) + QString value = m_uiLe->leLongDay->text(); + // Leeres Feld nur mit aktueller Uhrzeit auffüllen, wenn irgendein Feld schon befüllt ist: + if (value.length() == 0 && !m_backspacePressed) + { + if (!isEmptyHHMMSS() || + !isEmptyMonth() || + (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || + !isEmptyYear()) { - if (!isEmptyHHMMSS() || !isEmptyMonth() || (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || - !isEmptyYear()) - { - if (m_getCurrentTimeCallback) - { - const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); - setDay(dt.date().day()); - } - } + if (m_getCurrentTimeCallback) + { + const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); + setDay(dt.date().day()); + } } - isDataAcceptable(); - emit dateTimeChanged(); + } + isDataAcceptable(); + emit dateTimeChanged(); } void LtsDateTimeEdit::onFocusOutHHMMSS() { - if (!m_uiLe) - return; - if (m_backspacePressed) - { - m_backspacePressed = false; - return; - } - if (!m_recursionAvoid && !hasFocus()) - onFocusOut(); + if (!m_uiLe) + return; + if (m_backspacePressed) + { + m_backspacePressed = false; + return; + } + if (!m_recursionAvoid && !hasFocus()) + onFocusOut(); - QString value = m_uiLe->leLongHHMMSS->text(); - - if (value.length() == 0 && !m_backspacePressed) + QString value = m_uiLe->leLongHHMMSS->text(); + // Leeres Feld nur mit aktueller Uhrzeit auffüllen, wenn irgendein Feld schon befüllt ist: + if (value.length() == 0 && !m_backspacePressed) + { + if (!isEmptyDay() || + !isEmptyMonth() || + !(isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || + !isEmptyYear()) { - if (!isEmptyDay() || !isEmptyMonth() || !(isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || !isEmptyYear()) - { - if (m_getCurrentTimeCallback) - { - const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); - setHHMMSS(dt.time().hour(), dt.time().minute(), dt.time().second()); - } - } + if (m_getCurrentTimeCallback) + { + const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); + setHHMMSS(dt.time().hour(), dt.time().minute(), dt.time().second()); + } } - value += QString(6 - value.length(), QLatin1Char('0')); - m_uiLe->leLongHHMMSS->setText(value); - isDataAcceptable(); - emit dateTimeChanged(); + } + value += QString(6 - value.length(), QLatin1Char('0')); + m_uiLe->leLongHHMMSS->setText(value); + isDataAcceptable(); + emit dateTimeChanged(); } void LtsDateTimeEdit::onFocusOutTZ() { - if (!m_uiLe) - return; - if (m_backspacePressed) - { - m_backspacePressed = false; - return; - } - if (!m_recursionAvoid && !hasFocus()) - onFocusOut(); + if (!m_uiLe) + return; + if (m_backspacePressed) + { + m_backspacePressed = false; + return; + } + if (!m_recursionAvoid && !hasFocus()) + onFocusOut(); - QString value = m_uiLe->leLongTZ->text(); - - if (value.length() == 0 && !m_backspacePressed) - { - if (!isEmptyHHMMSS() || !isEmptyMonth() || !isEmptyDay() || !isEmptyYear()) - setTimezone(DTG::timezone()); - } - isDataAcceptable(); - emit dateTimeChanged(); + QString value = m_uiLe->leLongTZ->text(); + // Leeres Feld nur mit aktueller Uhrzeit auffüllen, wenn irgendein Feld schon befüllt ist: + if (value.length() == 0 && !m_backspacePressed) + { + if (!isEmptyHHMMSS() || + !isEmptyMonth() || + !isEmptyDay() || + !isEmptyYear()) + setTimezone(DTG::timezone()); + } + isDataAcceptable(); + emit dateTimeChanged(); } void LtsDateTimeEdit::onFocusOutMonth() { - if (!m_uiLe) - return; - if (m_backspacePressed) + if (!m_uiLe) + return; + if (m_backspacePressed) + { + m_backspacePressed = false; + return; + } + + if (!m_recursionAvoid && !hasFocus()) + onFocusOut(); + + QString value = m_uiLe->leLongMonth->text(); + // Leeres Feld nur mit aktueller Uhrzeit auffüllen, wenn irgendein Feld schon befüllt ist: + if (value.length() == 0 && !m_backspacePressed) + { + if (!isEmptyHHMMSS() || + !isEmptyDay() || + (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || + !isEmptyYear()) { - m_backspacePressed = false; - return; + if (m_getCurrentTimeCallback) + { + const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); + setMonth(dt.date().month()); + } } - - if (!m_recursionAvoid && !hasFocus()) - onFocusOut(); - - QString value = m_uiLe->leLongMonth->text(); - - if (value.length() == 0 && !m_backspacePressed) - { - if (!isEmptyHHMMSS() || !isEmptyDay() || (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || - !isEmptyYear()) - { - if (m_getCurrentTimeCallback) - { - const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); - setMonth(dt.date().month()); - } - } - } - isDataAcceptable(); - emit dateTimeChanged(); + } + isDataAcceptable(); + emit dateTimeChanged(); } void LtsDateTimeEdit::onFocusOutYear() { - if (!m_uiLe) - return; - if (m_backspacePressed) + if (!m_uiLe) + return; + if (m_backspacePressed) + { + m_backspacePressed = false; + return; + } + + if (!m_recursionAvoid && !hasFocus()) + onFocusOut(); + + QString value = m_uiLe->leLongYear->text(); + // should always be displayed with 2 digits + if (value.length() == 1) + { + value = QLatin1Char('0') + value; + m_uiLe->leLongYear->setText(value); + } + // Leeres Feld nur mit aktueller Uhrzeit auffüllen, wenn irgendein Feld schon befüllt ist: + if (value.length() == 0 && !m_backspacePressed) + { + if (!isEmptyHHMMSS() || + !isEmptyMonth() || + (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || + !isEmptyDay()) { - m_backspacePressed = false; - return; + if (m_getCurrentTimeCallback) + { + const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); + setYear(dt.date().year()); + } } - - if (!m_recursionAvoid && !hasFocus()) - onFocusOut(); - - QString value = m_uiLe->leLongYear->text(); - - if (value.length() == 1) - { - value = QLatin1Char('0') + value; - m_uiLe->leLongYear->setText(value); - } - - if (value.length() == 0 && !m_backspacePressed) - { - if (!isEmptyHHMMSS() || !isEmptyMonth() || (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || - !isEmptyDay()) - { - if (m_getCurrentTimeCallback) - { - const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); - setYear(dt.date().year()); - } - } - } - isDataAcceptable(); - emit dateTimeChanged(); + } + isDataAcceptable(); + emit dateTimeChanged(); } void LtsDateTimeEdit::onFocusOutBackspace() { - m_backspacePressed = true; + m_backspacePressed = true; } void LtsDateTimeEdit::onFocusOut() { - if (!m_uiLe) - return; - if (m_backspacePressed) - { - m_backspacePressed = false; - return; - } - m_recursionAvoid = true; - onFocusOutDay(); - onFocusOutHHMMSS(); - onFocusOutMonth(); - onFocusOutTZ(); - onFocusOutYear(); - m_recursionAvoid = false; + if (!m_uiLe) + return; + if (m_backspacePressed) + { + m_backspacePressed = false; + return; + } + m_recursionAvoid = true; + onFocusOutDay(); + onFocusOutHHMMSS(); + onFocusOutMonth(); + onFocusOutTZ(); + onFocusOutYear(); + m_recursionAvoid = false; } void LtsDateTimeEdit::onHmsWheelEvent(bool bForward, int cursorPos) { - if (!m_uiLe) - return; - if (m_uiLe->leLongHHMMSS->text().size() != 6) - return; + if (!m_uiLe) + return; + if (m_uiLe->leLongHHMMSS->text().size() != 6) + return; - fixupHHMMSS(); + fixupHHMMSS(); - int selStart = 0; - switch (cursorPos) - { - case 0: - case 1: - case 2: - if (bForward) - onForwardHourClicked(); - else - onBackHourClicked(); - selStart = 0; - break; - case 3: - case 4: - if (bForward) - onForwardMinuteClicked(); - else - onBackMinuteClicked(); - selStart = 2; - break; - case 5: - case 6: - if (bForward) - onForwardSecondClicked(); - else - onBackSecondClicked(); - selStart = 4; - break; - default: - return; - } - m_uiLe->leLongHHMMSS->setCursorPosition(cursorPos); - m_uiLe->leLongHHMMSS->setSelection(selStart, 2); - emit dateTimeChanged(); + int selStart = 0; + switch (cursorPos) + { + case 0: + case 1: + case 2: + if (bForward) + onForwardHourClicked(); + else + onBackHourClicked(); + selStart = 0; + break; + case 3: + case 4: + if (bForward) + onForwardMinuteClicked(); + else + onBackMinuteClicked(); + selStart = 2; + break; + case 5: + case 6: + if (bForward) + onForwardSecondClicked(); + else + onBackSecondClicked(); + selStart = 4; + break; + default: + return; + } + m_uiLe->leLongHHMMSS->setCursorPosition(cursorPos); + m_uiLe->leLongHHMMSS->setSelection(selStart, 2); + emit dateTimeChanged(); } void LtsDateTimeEdit::onDayWheelEvent(bool bForward, int cursorPos) { - if (!m_uiLe) - return; - if (!isDayAcceptable()) - return; - const int ofs = bForward ? 1 : -1; - setMsecsSinceEpoch(m_curTimeMSec + ofs * s_oneDayMSec, true); - m_uiLe->leLongDay->setCursorPosition(cursorPos); - m_uiLe->leLongDay->setSelection(0, 2); - emit dateTimeChanged(); + if (!m_uiLe) + return; + if (!isDayAcceptable()) + return; + const int ofs = bForward ? 1 : -1; + setMsecsSinceEpoch(m_curTimeMSec + ofs * s_oneDayMSec, true); + m_uiLe->leLongDay->setCursorPosition(cursorPos); + m_uiLe->leLongDay->setSelection(0, 2); + emit dateTimeChanged(); } void LtsDateTimeEdit::onMonthWheelEvent(bool bForward, int cursorPos) { - if (!m_uiLe) - return; - if (!isMonthAcceptable()) - return; - const int ofs = bForward ? 1 : -1; - const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_curTimeMSec, Qt::UTC).addMonths(ofs)); - setMsecsSinceEpoch(dt.toMSecsSinceEpoch(), true); - m_uiLe->leLongMonth->setCursorPosition(cursorPos); - m_uiLe->leLongMonth->setSelection(0, 3); - emit dateTimeChanged(); + if (!m_uiLe) + return; + if (!isMonthAcceptable()) + return; + const int ofs = bForward ? 1 : -1; + const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_curTimeMSec, Qt::UTC).addMonths(ofs)); + setMsecsSinceEpoch(dt.toMSecsSinceEpoch(), true); + m_uiLe->leLongMonth->setCursorPosition(cursorPos); + m_uiLe->leLongMonth->setSelection(0, 3); + emit dateTimeChanged(); } void LtsDateTimeEdit::onYearWheelEvent(bool bForward, int cursorPos) { - if (!m_uiLe) - return; - if (!isYearAcceptable()) - return; - const int ofs = bForward ? 1 : -1; - const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_curTimeMSec, Qt::UTC).addYears(ofs)); - setMsecsSinceEpoch(dt.toMSecsSinceEpoch(), true); - m_uiLe->leLongYear->setCursorPosition(cursorPos); - m_uiLe->leLongYear->setSelection(0, 2); - emit dateTimeChanged(); + if (!m_uiLe) + return; + if (!isYearAcceptable()) + return; + const int ofs = bForward ? 1 : -1; + const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_curTimeMSec, Qt::UTC).addYears(ofs)); + setMsecsSinceEpoch(dt.toMSecsSinceEpoch(), true); + m_uiLe->leLongYear->setCursorPosition(cursorPos); + m_uiLe->leLongYear->setSelection(0, 2); + emit dateTimeChanged(); } } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit.h index d5b41d14d..96ec9c77d 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit.h @@ -1,19 +1,29 @@ - +/** + * @RDE_HEADER@ + * DTG Edit + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Mike Wille, SLSE, 2016-08-17 + */ #pragma once + +//#include "lts_date_time_edit_touch.h" #include "lts_widgets_export.h" #include "qcheckbox.h" #include "qpushbutton.h" -#include #include #include + namespace Ui { -class LtsDateTimeEditLe; -class LtsDateTimeEdit; -} // namespace Ui +class LtsDateTimeEditLe; // default, based on QLineEdit +class LtsDateTimeEdit; // touch , based on QSpinBox, QComboBox +} class QLineEdit; class QShortcut; @@ -22,228 +32,189 @@ namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsDateTimeEdit : public QWidget { - Q_OBJECT + Q_OBJECT - Q_PROPERTY(bool autoForward READ getAutoForward WRITE setAutoForward) - Q_PROPERTY(bool editTimezone READ getEditTimezone WRITE setEditTimezone) - Q_PROPERTY(bool withButtons READ getWithButtons WRITE setWithButtons) - Q_PROPERTY(bool withSlider READ getWithSlider WRITE setWithSlider) - Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly) - Q_PROPERTY(bool withNowButton READ withNowButton WRITE setWithNowButton) - Q_PROPERTY(bool checkable READ isCheckable WRITE setCheckable) - Q_PROPERTY(bool checked READ isChecked WRITE setChecked NOTIFY toggled) + Q_PROPERTY(bool autoForward READ getAutoForward WRITE setAutoForward) + Q_PROPERTY(bool editTimezone READ getEditTimezone WRITE setEditTimezone) + Q_PROPERTY(bool withButtons READ getWithButtons WRITE setWithButtons) + Q_PROPERTY(bool withSlider READ getWithSlider WRITE setWithSlider) + Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly) + Q_PROPERTY(bool withNowButton READ withNowButton WRITE setWithNowButton) + Q_PROPERTY(bool checkable READ isCheckable WRITE setCheckable) + Q_PROPERTY(bool checked READ isChecked WRITE setChecked NOTIFY toggled) - public: - using CurrentTimeCallback = std::function; +public: + // returns the current time in msec + using CurrentTimeCallback = std::function; - explicit LtsDateTimeEdit(QWidget* parent = nullptr, bool withNowButton = true, bool checkable = false); - ~LtsDateTimeEdit(); + explicit LtsDateTimeEdit(QWidget *parent = nullptr, bool withNowButton = true, bool checkable = false); + ~LtsDateTimeEdit(); - bool setupUiTouch(); + bool setupUiTouch(); - qint64 msecsSinceEpoch() const; - bool isEmpty() const; - bool isValidDate() const; - void setAutoForward(const bool af) - { - m_autoForward = af; - } + qint64 msecsSinceEpoch() const; + bool isEmpty() const; + bool isValidDate() const; // should be preferred over isEmpty() - bool getAutoForward() const - { - return m_autoForward; - } + void setAutoForward(const bool af) { m_autoForward = af; } + bool getAutoForward() const { return m_autoForward; } - void setEditTimezone(const bool edit); + void setEditTimezone(const bool edit); + bool getEditTimezone() const { return m_editTimezone; } - bool getEditTimezone() const - { - return m_editTimezone; - } + void setWithButtons(const bool buttons); + bool getWithButtons() const { return m_withButtons; } - void setWithButtons(const bool buttons); + void setWithSlider(const bool slider); + bool getWithSlider() const { return m_withSlider; } - bool getWithButtons() const - { - return m_withButtons; - } + void setReadOnly(const bool readOnly); + bool isReadOnly() const { return m_readOnly; } - void setWithSlider(const bool slider); + void setCheckable(bool checkable); + bool isCheckable() const { return m_checkable; } + void setChecked(bool bChecked); + bool isChecked() const; - bool getWithSlider() const - { - return m_withSlider; - } + void setWithNowButton(bool nowButton); + bool withNowButton() const { return m_withNowButton; } - void setReadOnly(const bool readOnly); + // Setzt die minimal eingebbare Zeit + void setMinimumTimeMSec(qint64 msec); + qint64 minimumTimeMSec() const { return m_minTimeMSec; } - bool isReadOnly() const - { - return m_readOnly; - } + // Setzt die maximal eingebbare Zeit + void setMaximumTimeMSec(qint64 msec); + qint64 maximumTimeMSec() const { return m_maxTimeMSec; } - void setCheckable(bool checkable); + void setMinMaxTimeMSec(qint64 min, qint64 max) { setMinimumTimeMSec(min); setMaximumTimeMSec(max); } - bool isCheckable() const - { - return m_checkable; - } + void setRetrieveCurrentTimeCallback(const CurrentTimeCallback &cb); - void setChecked(bool bChecked); - bool isChecked() const; + bool setTimezone(char tz); + char getTimezone() const; + qint64 getTimezoneAsSecs() const; - void setWithNowButton(bool nowButton); + void setSubWidgetsProperties(const QString &name, const QVariant &value); - bool withNowButton() const - { - return m_withNowButton; - } +Q_SIGNALS: + void dateTimeChanged(); + void toggled(bool on); - void setMinimumTimeMSec(qint64 msec); +public Q_SLOTS: + bool setMsecsSinceEpoch(qint64 msec, bool setToNearestPossible = true); + void clear(); - qint64 minimumTimeMSec() const - { - return m_minTimeMSec; - } +private: + void clearTimezone(); - void setMaximumTimeMSec(qint64 msec); + void setMinMaxMonth(int minMonth, int maxMonth); - qint64 maximumTimeMSec() const - { - return m_maxTimeMSec; - } + bool setMonth(int month); + int getMonth() const; - void setMinMaxTimeMSec(qint64 min, qint64 max) - { - setMinimumTimeMSec(min); - setMaximumTimeMSec(max); - } + bool setDay(int day); + int getDay() const; - void setRetrieveCurrentTimeCallback(const CurrentTimeCallback& cb); + bool setHHMMSS(int hour, int minute, int second); + int getHour() const; + int getMinute() const; + int getSecond() const; - bool setTimezone(char tz); - char getTimezone() const; - qint64 getTimezoneAsSecs() const; + bool setYear(int year); + int getYear() const; - void setSubWidgetsProperties(const QString& name, const QVariant& value); + bool isEmptyDay() const; + bool isEmptyHHMMSS() const; + bool isEmptyTimezone() const; + bool isEmptyMonth() const; + bool isEmptyYear() const; - Q_SIGNALS: - void dateTimeChanged(); - void toggled(bool on); + bool hasFocus() const; - public Q_SLOTS: - bool setMsecsSinceEpoch(qint64 msec, bool setToNearestPossible = true); - void clear(); + bool isDataAcceptable(); - private: - void clearTimezone(); + void showInvalidData(bool setFocus); - void setMinMaxMonth(int minMonth, int maxMonth); + bool isLineEditDataAcceptable(QLineEdit *le) const; - bool setMonth(int month); - int getMonth() const; + bool isDayAcceptable() const; + bool isHHMMSSAcceptable() const; + bool isMonthAcceptable() const; + bool isYearAcceptable() const; + bool isTzAcceptable() const; - bool setDay(int day); - int getDay() const; + QCheckBox* checkBox() const; + QPushButton* pbNow() const; - bool setHHMMSS(int hour, int minute, int second); - int getHour() const; - int getMinute() const; - int getSecond() const; +private Q_SLOTS: + void setFixedDateTime(); + void setOffsetDateTime(); - bool setYear(int year); - int getYear() const; + void setSliderValue(int val); + void valueDayChanged(const QString &str); + void fixupHHMMSS(); + void valueMonthChanged(const QString &str); + void valueMonthChanged2(const QString &str); + void valueTimezoneChangedStr(const QString &str); + void valueTimezoneChangedInt(int newTimezone); + void valueYearChanged(const QString &str); - bool isEmptyDay() const; - bool isEmptyHHMMSS() const; - bool isEmptyTimezone() const; - bool isEmptyMonth() const; - bool isEmptyYear() const; + void onBackHourClicked(); + void onBackMinuteClicked(); + void onBackSecondClicked(); + void onForwardSecondClicked(); + void onForwardMinuteClicked(); + void onForwardHourClicked(); - bool hasFocus() const; + void onCheckBoxChanged(); + void disableControls(); + void enableControls(); + void enaDisaControls(bool bEnable); - bool isDataAcceptable(); + void onFocusOutHHMMSS(); + void onFocusOutTZ(); + void onFocusOutDay(); + void onFocusOutMonth(); + void onFocusOutYear(); - void showInvalidData(bool setFocus); + void onFocusOutBackspace(); + void onFocusOut(); - bool isLineEditDataAcceptable(QLineEdit* le) const; + void onHmsWheelEvent(bool bForward, int cursorPos); + void onDayWheelEvent(bool bForward, int cursorPos); + void onMonthWheelEvent(bool bForward, int cursorPos); + void onYearWheelEvent(bool bForward, int cursorPos); - bool isDayAcceptable() const; - bool isHHMMSSAcceptable() const; - bool isMonthAcceptable() const; - bool isYearAcceptable() const; - bool isTzAcceptable() const; +private: + Ui::LtsDateTimeEditLe *m_uiLe{nullptr}; + Ui::LtsDateTimeEdit *m_uiTouch{nullptr}; + QShortcut *m_scFixed = nullptr; + QShortcut *m_scOffset = nullptr; - QCheckBox* checkBox() const; - QPushButton* pbNow() const; + CurrentTimeCallback m_getCurrentTimeCallback = nullptr; - private Q_SLOTS: - void setFixedDateTime(); - void setOffsetDateTime(); + qint64 m_minTimeMSec = 0; + qint64 m_maxTimeMSec = 0; - void setSliderValue(int val); - void valueDayChanged(const QString& str); - void fixupHHMMSS(); - void valueMonthChanged(const QString& str); - void valueMonthChanged2(const QString& str); - void valueTimezoneChangedStr(const QString& str); - void valueTimezoneChangedInt(int newTimezone); - void valueYearChanged(const QString& str); + qint64 m_curTimeMSec = -1; // IMMER UTC - void onBackHourClicked(); - void onBackMinuteClicked(); - void onBackSecondClicked(); - void onForwardSecondClicked(); - void onForwardMinuteClicked(); - void onForwardHourClicked(); + bool m_editTimezone = true; + bool m_autoForward = true; + bool m_withButtons = false; + bool m_withSlider = false; + bool m_readOnly = false; + bool m_checkable = false; + bool m_withNowButton = false; - void onCheckBoxChanged(); - void disableControls(); - void enableControls(); - void enaDisaControls(bool bEnable); + int m_minMonth{0}; + int m_maxMonth{0}; - void onFocusOutHHMMSS(); - void onFocusOutTZ(); - void onFocusOutDay(); - void onFocusOutMonth(); - void onFocusOutYear(); - void onFocusOutBackspace(); - void onFocusOut(); - - void onHmsWheelEvent(bool bForward, int cursorPos); - void onDayWheelEvent(bool bForward, int cursorPos); - void onMonthWheelEvent(bool bForward, int cursorPos); - void onYearWheelEvent(bool bForward, int cursorPos); - - private: - Ui::LtsDateTimeEditLe* m_uiLe{nullptr}; - Ui::LtsDateTimeEdit* m_uiTouch{nullptr}; - QShortcut* m_scFixed = nullptr; - QShortcut* m_scOffset = nullptr; - - CurrentTimeCallback m_getCurrentTimeCallback = nullptr; - - qint64 m_minTimeMSec = 0; - qint64 m_maxTimeMSec = 0; - - qint64 m_curTimeMSec = -1; - - bool m_editTimezone = true; - bool m_autoForward = true; - bool m_withButtons = false; - bool m_withSlider = false; - bool m_readOnly = false; - bool m_checkable = false; - bool m_withNowButton = false; - - int m_minMonth{0}; - int m_maxMonth{0}; - - bool m_backspacePressed = false; - bool m_recursionAvoid = false; - bool m_dateIsAcceptable = false; + bool m_backspacePressed = false; + bool m_recursionAvoid = false; + bool m_dateIsAcceptable = false; }; } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_p.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_p.cpp index ae4d3d85c..0d2a12ce1 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_p.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_p.cpp @@ -1,109 +1,118 @@ #include "lts_date_time_edit_p.h" #include -#include #include #include +#include + namespace LtsWidgets { +// +// LineEdit +// void LineEdit::clear() { - setStyleSheet(QString()); - QLineEdit::clear(); + setStyleSheet(QString()); + QLineEdit::clear(); } bool LineEdit::isEmpty() const { - return text().isEmpty(); + return text().isEmpty(); } -void LineEdit::keyPressEvent(QKeyEvent* event) +void LineEdit::keyPressEvent(QKeyEvent *event) { - const bool wasEmpty = isEmpty(); - QLineEdit::keyPressEvent(event); - int keyCode = event->key(); - if (keyCode == Qt::Key_Backspace && wasEmpty) - { - emit focusOutBackspace(); - focusPreviousChild(); - event->accept(); - } + const bool wasEmpty = isEmpty(); + QLineEdit::keyPressEvent(event); + int keyCode = event->key(); + if (keyCode == Qt::Key_Backspace && wasEmpty) + { + emit focusOutBackspace(); + focusPreviousChild(); + event->accept(); + } } -void LineEdit::contextMenuEvent(QContextMenuEvent* e) +void LineEdit::contextMenuEvent(QContextMenuEvent *e) { - Q_UNUSED(e); + Q_UNUSED(e); + // damit das Default-Kontextmenü nicht erscheint } -void LineEdit::focusOutEvent(QFocusEvent* event) +void LineEdit::focusOutEvent(QFocusEvent *event) { - QLineEdit::focusOutEvent(event); - emit focusOut(); + QLineEdit::focusOutEvent(event); + emit focusOut(); } -DigitsLineEdit::DigitsLineEdit(QWidget* parent) : LineEdit(parent) +// +// DigitsLineEdit +// +DigitsLineEdit::DigitsLineEdit(QWidget *parent) + : LineEdit(parent) { - setAlignment(Qt::AlignRight); - QRegularExpression rx(QLatin1String("[-]{0,1}[0-9 ]*")); - setValidator(new QRegularExpressionValidator(rx, this)); + setAlignment(Qt::AlignRight); + QRegularExpression rx(QLatin1String("[-]{0,1}[0-9 ]*")); + setValidator(new QRegularExpressionValidator(rx, this)); } void DigitsLineEdit::setExactNumDigits(int num) { - m_exactNumDigits = num; + m_exactNumDigits = num; - QRegularExpression rx(QString::asprintf("^[0-9 ]{%d}$", num)); - setValidator(new QRegularExpressionValidator(rx, this)); + QRegularExpression rx(QString::asprintf("^[0-9 ]{%d}$", num)); + setValidator(new QRegularExpressionValidator(rx, this)); } void DigitsLineEdit::setValue(int val) { - QString str; + QString str; - if (m_exactNumDigits == -1) - str.setNum(val); - else - str = QStringLiteral("%1").arg(val, m_exactNumDigits, 10, QLatin1Char('0')); + if (m_exactNumDigits == -1) + str.setNum(val); + else + str = QStringLiteral("%1").arg(val, m_exactNumDigits, 10, QLatin1Char('0')); - setText(str); + setText(str); } int DigitsLineEdit::getValue() const { - if (text().isEmpty()) - return 0; - return text().remove(QLatin1Char(' ')).toInt(); + if (text().isEmpty()) + return 0; + return text().remove(QLatin1Char(' ')).toInt(); } void DigitsLineEdit::setCursorPosition(int curPos) { - - curPos = curPos < 0 ? 1 : curPos; - QLineEdit::setCursorPosition(curPos); + // WICHTIG: keine negativen Cursorpositionen setzen, da sonst Absturzgefahr !!! + curPos = curPos < 0 ? 1 : curPos; + QLineEdit::setCursorPosition(curPos); } -void DigitsLineEdit::wheelEvent(QWheelEvent* event) +void DigitsLineEdit::wheelEvent(QWheelEvent *event) { - LineEdit::wheelEvent(event); - const QString txt = text(); - if (m_exactNumDigits > 0 && txt.length() != m_exactNumDigits) - return; - event->accept(); - int cursorPos = cursorPosition(); - emit wheelEventReceived(event->angleDelta().y() > 0, cursorPos); + LineEdit::wheelEvent(event); + const QString txt = text(); + if (m_exactNumDigits > 0 && txt.length() != m_exactNumDigits) + return; + event->accept(); + int cursorPos = cursorPosition(); + emit wheelEventReceived(event->delta() > 0, cursorPos); } -void DigitsLineEdit::keyPressEvent(QKeyEvent* event) +void DigitsLineEdit::keyPressEvent(QKeyEvent *event) { - LineEdit::keyPressEvent(event); - if (event->key() == Qt::Key_Up || event->key() == Qt::Key_Down) - { - const bool bUp = event->key() == Qt::Key_Up; - const int cursorPos = cursorPosition(); - emit wheelEventReceived(bUp, cursorPos); - } + LineEdit::keyPressEvent(event); + if (event->key() == Qt::Key_Up || event->key() == Qt::Key_Down) + { + const bool bUp = event->key() == Qt::Key_Up; + const int cursorPos = cursorPosition(); + emit wheelEventReceived(bUp, cursorPos); + } } } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_p.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_p.h index 0532ac4e3..5477276f1 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_p.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_p.h @@ -1,46 +1,43 @@ #pragma once + #include -#include namespace LtsWidgets { class LineEdit : public QLineEdit { - Q_OBJECT - public: - using QLineEdit::QLineEdit; + Q_OBJECT +public: + using QLineEdit::QLineEdit; - void clear(); - bool isEmpty() const; - - protected: - void contextMenuEvent(QContextMenuEvent* e) override; - void focusOutEvent(QFocusEvent* event) override; - void keyPressEvent(QKeyEvent* event) override; - Q_SIGNALS: - void focusOutBackspace(); - void focusOut(); + void clear(); + bool isEmpty() const; +protected: + void contextMenuEvent(QContextMenuEvent *e) override; + void focusOutEvent(QFocusEvent *event) override; + void keyPressEvent(QKeyEvent *event) override; +Q_SIGNALS: + void focusOutBackspace(); + void focusOut(); }; class DigitsLineEdit final : public LineEdit { - Q_OBJECT - public: - DigitsLineEdit(QWidget* parent = nullptr); + Q_OBJECT +public: + DigitsLineEdit(QWidget *parent = nullptr); - void setExactNumDigits(int num); - void setCursorPosition(int curPos); - void setValue(int val); - int getValue() const; - Q_SIGNALS: - void wheelEventReceived(bool bForward, int cursorPos); - - protected: - void wheelEvent(QWheelEvent* event) override; - void keyPressEvent(QKeyEvent* event) override; - - private: - int m_exactNumDigits = -1; + void setExactNumDigits(int num); + void setCursorPosition(int curPos); + void setValue(int val); + int getValue() const; +Q_SIGNALS: + void wheelEventReceived(bool bForward, int cursorPos); +protected: + void wheelEvent(QWheelEvent *event) override; + void keyPressEvent(QKeyEvent *event) override; +private: + int m_exactNumDigits = -1; }; } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_rc.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_rc.cpp index 6d3bf2a4f..f4a921eff 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_rc.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_rc.cpp @@ -1,10 +1,23 @@ - +/** + * @RDE_HEADER@ + * DTGEdit + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Mike Wille, SLSE, 2016-08-17 + */ #include "lts_date_time_edit.h" #include "lts_date_time_edit_p.h" + #include "ui_lts_date_time_edit_touch.h" + #include + +#include + #include #include #include @@ -18,1704 +31,1769 @@ #include #include #include -#include static constexpr qint64 s_oneSecondMSec = 1000LL; static constexpr qint64 s_oneMinuteMSec = 60 * s_oneSecondMSec; -static constexpr qint64 s_oneHourMSec = 60 * s_oneMinuteMSec; -static constexpr qint64 s_oneDayMSec = 24 * s_oneHourMSec; +static constexpr qint64 s_oneHourMSec = 60 * s_oneMinuteMSec; +static constexpr qint64 s_oneDayMSec = 24 * s_oneHourMSec; namespace Ui { class LtsDateTimeEditLe { - public: - LtsWidgets::DigitsLineEdit* leLongDay = nullptr; - LtsWidgets::DigitsLineEdit* leLongHHMMSS = nullptr; - LtsWidgets::LineEdit* leLongTZ = nullptr; - LtsWidgets::DigitsLineEdit* leLongMonth = nullptr; - LtsWidgets::DigitsLineEdit* leLongYear = nullptr; - QCheckBox* checkBox = nullptr; - QGridLayout* gridLayout = nullptr; - QPushButton* pbBBB = nullptr; - QPushButton* pbBB = nullptr; - QPushButton* pbB = nullptr; - QPushButton* pbF = nullptr; - QPushButton* pbFF = nullptr; - QPushButton* pbFFF = nullptr; - QPushButton* pbNow = nullptr; - QSlider* slTime = nullptr; +public: + LtsWidgets::DigitsLineEdit *leLongDay = nullptr; + LtsWidgets::DigitsLineEdit *leLongHHMMSS = nullptr; + LtsWidgets::LineEdit *leLongTZ = nullptr; + LtsWidgets::DigitsLineEdit *leLongMonth = nullptr; + LtsWidgets::DigitsLineEdit *leLongYear = nullptr; + QCheckBox *checkBox = nullptr; + QGridLayout *gridLayout = nullptr; + QPushButton *pbBBB = nullptr; + QPushButton *pbBB = nullptr; + QPushButton *pbB = nullptr; + QPushButton *pbF = nullptr; + QPushButton *pbFF = nullptr; + QPushButton *pbFFF = nullptr; + QPushButton *pbNow = nullptr; + QSlider *slTime = nullptr; - static void setFixedSize(QLineEdit* le, int charCount) - { - QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); - sizePolicy.setVerticalStretch(0); - sizePolicy.setHeightForWidth(false); + static void setFixedSize(QLineEdit *le, int charCount) + { + QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); + sizePolicy.setVerticalStretch(0); + sizePolicy.setHeightForWidth(false); - const QFontMetricsF fm(le->font()); - const auto textMargins = le->textMargins(); - le->setSizePolicy(sizePolicy); - charCount += 3; + const QFontMetricsF fm(le->font()); + const auto textMargins = le->textMargins(); + le->setSizePolicy(sizePolicy); + charCount += 3; // don't know why #if QT_VERSION < QT_VERSION_CHECK(5, 11, 0) - const qreal w = fm.width(QLatin1Char('x')) * charCount + textMargins.left() + textMargins.right(); + const qreal w = fm.width(QLatin1Char('x')) * charCount + textMargins.left() + textMargins.right(); #else - const qreal w = fm.horizontalAdvance(QLatin1Char('x')) * charCount + textMargins.left() + textMargins.right(); + const qreal w = fm.horizontalAdvance(QLatin1Char('x')) * charCount + textMargins.left() + textMargins.right(); #endif - le->setMinimumWidth(w); - le->setMaximumWidth(w); - } + le->setMinimumWidth(w); + le->setMaximumWidth(w); + } - void setupUi(QWidget* parent) - { - gridLayout = new QGridLayout(parent); - gridLayout->setContentsMargins(0, 0, 0, 0); + void setupUi(QWidget *parent) + { + gridLayout = new QGridLayout(parent); + gridLayout->setMargin(0); - int iStart = 3; + int iStart = 3; // 3 invisible widgets before - checkBox = new QCheckBox; - gridLayout->addWidget(checkBox, 0, iStart++, 1, 1); + checkBox = new QCheckBox; + gridLayout->addWidget(checkBox, 0, iStart++, 1, 1); - auto horizontalLayout = new QHBoxLayout; - horizontalLayout->setSpacing(0); - horizontalLayout->setContentsMargins(0, 0, 0, 0); + auto horizontalLayout = new QHBoxLayout; + horizontalLayout->setSpacing(0); + horizontalLayout->setContentsMargins(0, 0, 0, 0); - leLongDay = new LtsWidgets::DigitsLineEdit(parent); - setFixedSize(leLongDay, 2); - leLongDay->setObjectName(QStringLiteral("leLongDay")); - horizontalLayout->addWidget(leLongDay); + leLongDay = new LtsWidgets::DigitsLineEdit(parent); + setFixedSize(leLongDay, 2); + leLongDay->setObjectName(QStringLiteral("leLongDay")); + horizontalLayout->addWidget(leLongDay); - leLongHHMMSS = new LtsWidgets::DigitsLineEdit(parent); - leLongHHMMSS->setExactNumDigits(6); - setFixedSize(leLongHHMMSS, 6); - leLongHHMMSS->setObjectName(QStringLiteral("leLongHHMMSS")); - horizontalLayout->addWidget(leLongHHMMSS); + leLongHHMMSS = new LtsWidgets::DigitsLineEdit(parent); + leLongHHMMSS->setExactNumDigits(6); + setFixedSize(leLongHHMMSS, 6); + leLongHHMMSS->setObjectName(QStringLiteral("leLongHHMMSS")); + horizontalLayout->addWidget(leLongHHMMSS); - leLongTZ = new LtsWidgets::LineEdit(parent); - leLongTZ->setAlignment(Qt::AlignCenter); - setFixedSize(leLongTZ, 1); - leLongTZ->setObjectName(QStringLiteral("leLongTZ")); - horizontalLayout->addWidget(leLongTZ); + leLongTZ = new LtsWidgets::LineEdit(parent); + leLongTZ->setAlignment(Qt::AlignCenter); + setFixedSize(leLongTZ, 1); + leLongTZ->setObjectName(QStringLiteral("leLongTZ")); + horizontalLayout->addWidget(leLongTZ); - leLongMonth = new LtsWidgets::DigitsLineEdit(parent); - leLongMonth->setAlignment(Qt::AlignCenter); - setFixedSize(leLongMonth, 3); - leLongMonth->setObjectName(QStringLiteral("leLongMonth")); - horizontalLayout->addWidget(leLongMonth); + leLongMonth = new LtsWidgets::DigitsLineEdit(parent); + leLongMonth->setAlignment(Qt::AlignCenter); + setFixedSize(leLongMonth, 3); + leLongMonth->setObjectName(QStringLiteral("leLongMonth")); + horizontalLayout->addWidget(leLongMonth); - leLongYear = new LtsWidgets::DigitsLineEdit(parent); - leLongYear->setExactNumDigits(2); - setFixedSize(leLongYear, 2); - leLongYear->setObjectName(QStringLiteral("leLongYear")); - horizontalLayout->addWidget(leLongYear); + leLongYear = new LtsWidgets::DigitsLineEdit(parent); + leLongYear->setExactNumDigits(2); + setFixedSize(leLongYear, 2); + leLongYear->setObjectName(QStringLiteral("leLongYear")); + horizontalLayout->addWidget(leLongYear); - gridLayout->addLayout(horizontalLayout, 0, iStart++, 1, 1); + gridLayout->addLayout(horizontalLayout, 0, iStart++, 1, 1); - pbNow = new QPushButton(QApplication::translate("LtsDateTimeEdit", "Now", nullptr)); - pbNow->setObjectName(QStringLiteral("pbNow")); - gridLayout->addWidget(pbNow, 0, iStart++, 1, 1); + pbNow = new QPushButton(QApplication::translate("LtsDateTimeEdit", "Now", nullptr)); + pbNow->setObjectName(QStringLiteral("pbNow")); + gridLayout->addWidget(pbNow, 0, iStart++, 1, 1); - QWidget::setTabOrder(checkBox, leLongDay); - QWidget::setTabOrder(leLongDay, leLongHHMMSS); - QWidget::setTabOrder(leLongHHMMSS, leLongTZ); - QWidget::setTabOrder(leLongTZ, leLongMonth); - QWidget::setTabOrder(leLongMonth, leLongYear); - QWidget::setTabOrder(leLongYear, pbNow); + QWidget::setTabOrder(checkBox, leLongDay); + QWidget::setTabOrder(leLongDay, leLongHHMMSS); + QWidget::setTabOrder(leLongHHMMSS, leLongTZ); + QWidget::setTabOrder(leLongTZ, leLongMonth); + QWidget::setTabOrder(leLongMonth, leLongYear); + QWidget::setTabOrder(leLongYear, pbNow); - parent->setFocusProxy(leLongDay); - } + parent->setFocusProxy(leLongDay); + } // setupUi - static QPushButton* addButton(const QString& text, QWidget* parent) - { - QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + static QPushButton *addButton(const QString &text, QWidget *parent) + { + QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - auto pb = new QPushButton(parent); - pb->setMinimumWidth(27); - pb->setMaximumWidth(27); - pb->setText(text); - sizePolicy.setHorizontalStretch(0); - sizePolicy.setVerticalStretch(0); - sizePolicy.setHeightForWidth(pb->sizePolicy().hasHeightForWidth()); - pb->setSizePolicy(sizePolicy); - return pb; - } + auto pb = new QPushButton(parent); + pb->setMinimumWidth(27); + pb->setMaximumWidth(27); + pb->setText(text); + sizePolicy.setHorizontalStretch(0); + sizePolicy.setVerticalStretch(0); + sizePolicy.setHeightForWidth(pb->sizePolicy().hasHeightForWidth()); + pb->setSizePolicy(sizePolicy); + return pb; + } - void addButtons(QWidget* parent) - { - pbBBB = addButton(QLatin1String("<<<"), parent); - pbBB = addButton(QLatin1String("<<"), parent); - pbB = addButton(QLatin1String("<"), parent); - gridLayout->addWidget(pbBBB, 0, 0, 1, 1); - gridLayout->addWidget(pbBB, 0, 1, 1, 1); - gridLayout->addWidget(pbB, 0, 2, 1, 1); + void addButtons(QWidget *parent) + { + pbBBB = addButton(QLatin1String("<<<"), parent); + pbBB = addButton(QLatin1String("<<"), parent); + pbB = addButton(QLatin1String("<"), parent); + gridLayout->addWidget(pbBBB, 0, 0, 1, 1); + gridLayout->addWidget(pbBB, 0, 1, 1, 1); + gridLayout->addWidget(pbB, 0, 2, 1, 1); - int iStart = 5; - pbF = addButton(QLatin1String(">"), parent); - pbFF = addButton(QLatin1String(">>"), parent); - pbFFF = addButton(QLatin1String(">>>"), parent); - gridLayout->addWidget(pbF, 0, iStart++, 1, 1); - gridLayout->addWidget(pbFF, 0, iStart++, 1, 1); - gridLayout->addWidget(pbFFF, 0, iStart++, 1, 1); - } + int iStart = 5; // 3 from above, 3 by default + pbF = addButton(QLatin1String(">"), parent); + pbFF = addButton(QLatin1String(">>"), parent); + pbFFF = addButton(QLatin1String(">>>"), parent); + gridLayout->addWidget(pbF, 0, iStart++, 1, 1); + gridLayout->addWidget(pbFF, 0, iStart++, 1, 1); + gridLayout->addWidget(pbFFF, 0, iStart++, 1, 1); + } //addButtons - void addSlider(QWidget* parent) - { - slTime = new QSlider(parent); - slTime->setOrientation(Qt::Horizontal); - gridLayout->addWidget(slTime, 1, 0, 1, 7); - } + void addSlider(QWidget *parent) + { + slTime = new QSlider(parent); + slTime->setOrientation(Qt::Horizontal); + gridLayout->addWidget(slTime, 1, 0, 1, 7); + } //addSlider }; -} // namespace Ui +} + namespace LtsWidgets { -void setItemText(LtsWidgets::LineEdit* lineEdit, const QString& text) +// +// helper (via overloading) +// +void setItemText(LtsWidgets::LineEdit *lineEdit, const QString &text) { - if (!lineEdit) - return; - lineEdit->setText(text); + if (!lineEdit) + return; + lineEdit->setText(text); +} +void setItemText(QComboBox *comboxBox, const QString &text) +{ + if (!comboxBox) + return; + comboxBox->setCurrentIndex(comboxBox->findText(text)); +} +void setItemData(QComboBox *comboxBox, int data) +{ + if (!comboxBox) + return; + comboxBox->setCurrentIndex(comboxBox->findData(data)); +} +void setItemValue(QSpinBox *spinBox, int value) +{ + if (!spinBox) + return; + spinBox->setValue(value); } -void setItemText(QComboBox* comboxBox, const QString& text) + +QString getItemText(LtsWidgets::LineEdit *lineEdit) { - if (!comboxBox) - return; - comboxBox->setCurrentIndex(comboxBox->findText(text)); + if (!lineEdit) + return {}; + return lineEdit->text(); } - -void setItemData(QComboBox* comboxBox, int data) +QString getItemText(QComboBox *comboxBox) { - if (!comboxBox) - return; - comboxBox->setCurrentIndex(comboxBox->findData(data)); + if (!comboxBox || (comboxBox->count() <= 0)) + return {}; + const QString &curTest = comboxBox->currentText(); + if (curTest.isEmpty()) + return {}; + return curTest.at(0).toUpper(); } - -void setItemValue(QSpinBox* spinBox, int value) +int getItemData(QComboBox *comboxBox) { - if (!spinBox) - return; - spinBox->setValue(value); + if (!comboxBox || (comboxBox->count() <= 0)) + return {}; + int data = comboxBox->currentData().toInt(); + return data; } - -QString getItemText(LtsWidgets::LineEdit* lineEdit) +int getItemValue(QSpinBox *spinBox) { - if (!lineEdit) - return {}; - return lineEdit->text(); + if (!spinBox) + return 0; + return spinBox->value(); } +// helper (via overloading) END -QString getItemText(QComboBox* comboxBox) -{ - if (!comboxBox || (comboxBox->count() <= 0)) - return {}; - const QString& curTest = comboxBox->currentText(); - if (curTest.isEmpty()) - return {}; - return curTest.at(0).toUpper(); -} -int getItemData(QComboBox* comboxBox) -{ - if (!comboxBox || (comboxBox->count() <= 0)) - return {}; - int data = comboxBox->currentData().toInt(); - return data; -} - -int getItemValue(QSpinBox* spinBox) -{ - if (!spinBox) - return 0; - return spinBox->value(); -} - -LtsDateTimeEdit::LtsDateTimeEdit(QWidget* parent, bool withNowButton, bool withCheckBox) - : QWidget(parent) - - , - m_scFixed(new QShortcut(QKeySequence(Qt::ShiftModifier + Qt::Key_F2), this, SLOT(setFixedDateTime()), nullptr, - Qt::WidgetWithChildrenShortcut)), - m_scOffset(new QShortcut(QKeySequence(Qt::Key_F2), this, SLOT(setOffsetDateTime()), nullptr, - Qt::WidgetWithChildrenShortcut)), - m_withCheckBox(withCheckBox), m_withNowButton(withNowButton) +// +// class LtsDateTimeEdit +// +LtsDateTimeEdit::LtsDateTimeEdit(QWidget *parent, bool withNowButton, bool withCheckBox) + : QWidget(parent) +// , m_uiLe(new Ui::LtsDateTimeEditLe) + , m_scFixed(new QShortcut(QKeySequence(Qt::ShiftModifier + Qt::Key_F2), this, SLOT(setFixedDateTime()), nullptr, Qt::WidgetWithChildrenShortcut)) + , m_scOffset(new QShortcut(QKeySequence(Qt::Key_F2), this, SLOT(setOffsetDateTime()), nullptr, Qt::WidgetWithChildrenShortcut)) + , m_withCheckBox(withCheckBox) // see below + , m_withNowButton(withNowButton) // see below { #ifdef TABLET_MODE - - setupUiTouch(); - return; + // entweder TOUCH (SpinBox/ComboBox) + setupUiTouch(); + return; #else + // oder default (LineEdit) + m_uiLe = new Ui::LtsDateTimeEditLe; + m_uiLe->setupUi(this); - m_uiLe = new Ui::LtsDateTimeEditLe; - m_uiLe->setupUi(this); + setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); + setFocusPolicy(Qt::StrongFocus); + setContentsMargins(QMargins()); - setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); - setFocusPolicy(Qt::StrongFocus); - setContentsMargins(QMargins()); + QCompleter *completer = new QCompleter(DTG::months(), this); + completer->setCaseSensitivity(Qt::CaseInsensitive); + completer->setCompletionMode(QCompleter::InlineCompletion); - QCompleter* completer = new QCompleter(DTG::months(), this); - completer->setCaseSensitivity(Qt::CaseInsensitive); - completer->setCompletionMode(QCompleter::InlineCompletion); + QRegularExpression rx(DTG::months().join(QLatin1Char('|'))); + QRegularExpressionValidator *val = new QRegularExpressionValidator(rx, this); + m_uiLe->leLongMonth->setCompleter(completer); + m_uiLe->leLongMonth->setValidator(val); - QRegularExpression rx(DTG::months().join(QLatin1Char('|'))); - QRegularExpressionValidator* val = new QRegularExpressionValidator(rx, this); - m_uiLe->leLongMonth->setCompleter(completer); - m_uiLe->leLongMonth->setValidator(val); + connect(m_uiLe->leLongDay, &DigitsLineEdit::textEdited, this, &LtsDateTimeEdit::valueDayChanged); + connect(m_uiLe->leLongMonth, &LineEdit::textEdited, this, &LtsDateTimeEdit::valueMonthChanged2); + connect(m_uiLe->leLongTZ, &LineEdit::textEdited, this, &LtsDateTimeEdit::valueTimezoneChangedStr); + connect(m_uiLe->leLongYear, &DigitsLineEdit::textEdited, this, &LtsDateTimeEdit::valueYearChanged); - connect(m_uiLe->leLongDay, &DigitsLineEdit::textEdited, this, &LtsDateTimeEdit::valueDayChanged); - connect(m_uiLe->leLongMonth, &LineEdit::textEdited, this, &LtsDateTimeEdit::valueMonthChanged2); - connect(m_uiLe->leLongTZ, &LineEdit::textEdited, this, &LtsDateTimeEdit::valueTimezoneChangedStr); - connect(m_uiLe->leLongYear, &DigitsLineEdit::textEdited, this, &LtsDateTimeEdit::valueYearChanged); + connect(m_uiLe->leLongHHMMSS, &DigitsLineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutHHMMSS); + connect(m_uiLe->leLongDay, &DigitsLineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutDay); + connect(m_uiLe->leLongMonth, &LineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutMonth); + connect(m_uiLe->leLongTZ, &LineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutTZ); + connect(m_uiLe->leLongYear, &DigitsLineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutYear); - connect(m_uiLe->leLongHHMMSS, &DigitsLineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutHHMMSS); - connect(m_uiLe->leLongDay, &DigitsLineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutDay); - connect(m_uiLe->leLongMonth, &LineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutMonth); - connect(m_uiLe->leLongTZ, &LineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutTZ); - connect(m_uiLe->leLongYear, &DigitsLineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutYear); + connect(m_uiLe->leLongHHMMSS, &DigitsLineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); + connect(m_uiLe->leLongDay, &DigitsLineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); + connect(m_uiLe->leLongMonth, &LineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); + connect(m_uiLe->leLongTZ, &LineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); + connect(m_uiLe->leLongYear, &DigitsLineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); - connect(m_uiLe->leLongHHMMSS, &DigitsLineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); - connect(m_uiLe->leLongDay, &DigitsLineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); - connect(m_uiLe->leLongMonth, &LineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); - connect(m_uiLe->leLongTZ, &LineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); - connect(m_uiLe->leLongYear, &DigitsLineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); + connect(m_uiLe->leLongHHMMSS, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onHmsWheelEvent); + connect(m_uiLe->leLongDay, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onDayWheelEvent); + connect(m_uiLe->leLongMonth, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onMonthWheelEvent); + connect(m_uiLe->leLongYear, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onYearWheelEvent); - connect(m_uiLe->leLongHHMMSS, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onHmsWheelEvent); - connect(m_uiLe->leLongDay, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onDayWheelEvent); - connect(m_uiLe->leLongMonth, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onMonthWheelEvent); - connect(m_uiLe->leLongYear, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onYearWheelEvent); + connect(m_uiLe->checkBox, &QCheckBox::toggled, this, &LtsDateTimeEdit::onCheckBoxChanged); + connect(m_uiLe->pbNow, &QPushButton::clicked, this, &LtsDateTimeEdit::setOffsetDateTime); - connect(m_uiLe->checkBox, &QCheckBox::toggled, this, &LtsDateTimeEdit::onCheckBoxChanged); - connect(m_uiLe->pbNow, &QPushButton::clicked, this, &LtsDateTimeEdit::setOffsetDateTime); + setTimezone(DTG::timezone()); - setTimezone(DTG::timezone()); + bool temp = m_withCheckBox; + m_withCheckBox = !m_withCheckBox; + setWithCheckBox(temp); - bool temp = m_withCheckBox; - m_withCheckBox = !m_withCheckBox; - setWithCheckBox(temp); + temp = m_withNowButton; + m_withNowButton = !m_withNowButton; + setWithNowButton(temp); - temp = m_withNowButton; - m_withNowButton = !m_withNowButton; - setWithNowButton(temp); - - onCheckBoxChanged(); + onCheckBoxChanged(); #endif } LtsDateTimeEdit::~LtsDateTimeEdit() { - delete m_uiLe; + delete m_uiLe; } bool LtsDateTimeEdit::setupUiTouch() { - m_uiTouch = new Ui::LtsDateTimeEdit; - m_uiTouch->setupUi(this); - setFocusPolicy(Qt::StrongFocus); + m_uiTouch = new Ui::LtsDateTimeEdit; + m_uiTouch->setupUi(this); + setFocusPolicy(Qt::StrongFocus); - for (int i = 65; i < 91; i++) - { - if (QChar(i).toUpper() == QChar::fromLatin1('I')) - continue; - m_uiTouch->cbxTimeZone->addItem(QChar(i), QChar(i)); - } + for (int i = 65; i < 91; i++ ) + { + if (QChar(i).toUpper() == QChar::fromLatin1('I')) + continue; + m_uiTouch->cbxTimeZone->addItem(QChar(i), QChar(i)); + } - connect(m_uiTouch->pbNow, &QPushButton::clicked, this, &LtsDateTimeEdit::setOffsetDateTime); - connect(m_uiTouch->cbxMonth, static_cast(&QComboBox::currentIndexChanged), this, - &LtsDateTimeEdit::dateTimeChanged); - connect(m_uiTouch->spDay, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged); - connect(m_uiTouch->spHour, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged); - connect(m_uiTouch->spMinutes, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged); - connect(m_uiTouch->spSeconds, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged); - connect(m_uiTouch->spYear, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged); + connect(m_uiTouch->pbNow, &QPushButton::clicked, + this, &LtsDateTimeEdit::setOffsetDateTime); + connect(m_uiTouch->cbxMonth, static_cast(&QComboBox::currentIndexChanged), + this, &LtsDateTimeEdit::dateTimeChanged); + connect(m_uiTouch->spDay, &QSpinBox::editingFinished, + this, &LtsDateTimeEdit::dateTimeChanged); + connect(m_uiTouch->spHour, &QSpinBox::editingFinished, + this, &LtsDateTimeEdit::dateTimeChanged); + connect(m_uiTouch->spMinutes, &QSpinBox::editingFinished, + this, &LtsDateTimeEdit::dateTimeChanged); + connect(m_uiTouch->spSeconds, &QSpinBox::editingFinished, + this, &LtsDateTimeEdit::dateTimeChanged); + connect(m_uiTouch->spYear, &QSpinBox::editingFinished, + this, &LtsDateTimeEdit::dateTimeChanged); - connect(m_uiTouch->checkBox, &QCheckBox::toggled, this, &LtsDateTimeEdit::onCheckBoxChanged); - connect(m_uiTouch->cbxTimeZone, static_cast(&QComboBox::currentIndexChanged), this, - &LtsDateTimeEdit::valueTimezoneChangedInt); + connect(m_uiTouch->checkBox, &QCheckBox::toggled, + this, &LtsDateTimeEdit::onCheckBoxChanged); + connect(m_uiTouch->cbxTimeZone, static_cast(&QComboBox::currentIndexChanged), + this, &LtsDateTimeEdit::valueTimezoneChangedInt); - connect(m_uiTouch->cbxMonth, &QComboBox::currentTextChanged, this, &LtsDateTimeEdit::valueMonthChanged); + // connect(m_uiTouch->cbxMonth, static_cast(&QComboBox::currentIndexChanged), + // this, &LtsDateTimeEdit::valueMonthChanged); + connect(m_uiTouch->cbxMonth, &QComboBox::currentTextChanged, + this, &LtsDateTimeEdit::valueMonthChanged); - setMinMaxMonth(1, 12); - setTimezone(DTG::timezone()); + setMinMaxMonth(1,12); - bool temp = m_withCheckBox; - m_withCheckBox = !m_withCheckBox; - setWithCheckBox(temp); + setTimezone(DTG::timezone()); + //m_tzOffset = DTG::timezone2Secs(QLatin1Char(DTG::timezone()).toLatin1()); - temp = m_withNowButton; - m_withNowButton = !m_withNowButton; - setWithNowButton(temp); + bool temp = m_withCheckBox; + m_withCheckBox = !m_withCheckBox; + setWithCheckBox(temp); - onCheckBoxChanged(); + temp = m_withNowButton; + m_withNowButton = !m_withNowButton; + setWithNowButton(temp); - return true; + onCheckBoxChanged(); + + + return true; } -void LtsDateTimeEdit::setRetrieveCurrentTimeCallback(const CurrentTimeCallback& cb) + +void LtsDateTimeEdit::setRetrieveCurrentTimeCallback(const CurrentTimeCallback &cb) { - m_getCurrentTimeCallback = cb; + m_getCurrentTimeCallback = cb; } void LtsDateTimeEdit::setEditTimezone(const bool edit) { - m_editTimezone = edit; - if (m_uiLe) - m_uiLe->leLongTZ->setEnabled(m_editTimezone); - if (m_uiTouch) - m_uiTouch->cbxTimeZone->setEnabled(m_editTimezone); + m_editTimezone = edit; + if (m_uiLe) + m_uiLe->leLongTZ->setEnabled(m_editTimezone); + if (m_uiTouch) + m_uiTouch->cbxTimeZone->setEnabled(m_editTimezone); } void LtsDateTimeEdit::setWithButtons(const bool buttons) { - m_withButtons = buttons; - if (buttons) + m_withButtons = buttons; + if (buttons) + { + if (!m_uiLe->pbBBB) { - if (!m_uiLe->pbBBB) - { - m_uiLe->addButtons(this); - connect(m_uiLe->pbBBB, &QPushButton::clicked, this, &LtsDateTimeEdit::onBackHourClicked); - connect(m_uiLe->pbBB, &QPushButton::clicked, this, &LtsDateTimeEdit::onBackMinuteClicked); - connect(m_uiLe->pbB, &QPushButton::clicked, this, &LtsDateTimeEdit::onBackSecondClicked); - connect(m_uiLe->pbF, &QPushButton::clicked, this, &LtsDateTimeEdit::onForwardSecondClicked); - connect(m_uiLe->pbFF, &QPushButton::clicked, this, &LtsDateTimeEdit::onForwardMinuteClicked); - connect(m_uiLe->pbFFF, &QPushButton::clicked, this, &LtsDateTimeEdit::onForwardHourClicked); - disableControls(); - } + m_uiLe->addButtons(this); + connect(m_uiLe->pbBBB, &QPushButton::clicked, this, &LtsDateTimeEdit::onBackHourClicked); + connect(m_uiLe->pbBB, &QPushButton::clicked, this, &LtsDateTimeEdit::onBackMinuteClicked); + connect(m_uiLe->pbB, &QPushButton::clicked, this, &LtsDateTimeEdit::onBackSecondClicked); + connect(m_uiLe->pbF, &QPushButton::clicked, this, &LtsDateTimeEdit::onForwardSecondClicked); + connect(m_uiLe->pbFF, &QPushButton::clicked, this, &LtsDateTimeEdit::onForwardMinuteClicked); + connect(m_uiLe->pbFFF, &QPushButton::clicked, this, &LtsDateTimeEdit::onForwardHourClicked); + disableControls(); } - else - { - delete m_uiLe->pbBBB; - delete m_uiLe->pbBB; - delete m_uiLe->pbB; - delete m_uiLe->pbFFF; - delete m_uiLe->pbFF; - delete m_uiLe->pbF; + } + else + { + delete m_uiLe->pbBBB; + delete m_uiLe->pbBB; + delete m_uiLe->pbB; + delete m_uiLe->pbFFF; + delete m_uiLe->pbFF; + delete m_uiLe->pbF; - m_uiLe->pbBBB = nullptr; - m_uiLe->pbBB = nullptr; - m_uiLe->pbB = nullptr; - m_uiLe->pbFFF = nullptr; - m_uiLe->pbFF = nullptr; - m_uiLe->pbF = nullptr; - } + m_uiLe->pbBBB = nullptr; + m_uiLe->pbBB = nullptr; + m_uiLe->pbB = nullptr; + m_uiLe->pbFFF = nullptr; + m_uiLe->pbFF = nullptr; + m_uiLe->pbF = nullptr; + } } void LtsDateTimeEdit::setWithSlider(const bool slider) { - m_withSlider = slider; + m_withSlider = slider; - if (!m_uiLe) - return; + if (!m_uiLe) + return; - if (slider) - { - m_uiLe->addSlider(this); - m_uiLe->slTime->setMinimum(m_minTimeMSec / 1000); - m_uiLe->slTime->setMaximum(m_maxTimeMSec > 0 ? m_maxTimeMSec / 1000 : time(nullptr)); - connect(m_uiLe->slTime, &QSlider::sliderMoved, this, &LtsDateTimeEdit::setSliderValue); - disableControls(); - } - else - { - delete m_uiLe->slTime; - m_uiLe->slTime = nullptr; - } + if (slider) + { + m_uiLe->addSlider(this); + m_uiLe->slTime->setMinimum(m_minTimeMSec / 1000); + m_uiLe->slTime->setMaximum(m_maxTimeMSec > 0 ? m_maxTimeMSec / 1000 : time(nullptr)); + connect(m_uiLe->slTime, &QSlider::sliderMoved, this, &LtsDateTimeEdit::setSliderValue); + disableControls(); + } + else + { + delete m_uiLe->slTime; + m_uiLe->slTime = nullptr; + } } void LtsDateTimeEdit::setReadOnly(const bool readOnly) { - if (m_readOnly == readOnly) - return; - m_readOnly = readOnly; + if (m_readOnly == readOnly) + return; + m_readOnly = readOnly; - if (m_uiLe) - { - m_uiLe->leLongDay->setReadOnly(m_readOnly); - m_uiLe->leLongHHMMSS->setReadOnly(m_readOnly); - m_uiLe->leLongMonth->setReadOnly(m_readOnly); - m_uiLe->leLongTZ->setReadOnly(m_readOnly); - m_uiLe->leLongYear->setReadOnly(m_readOnly); - } - if (m_uiTouch) - { - m_uiTouch->spDay->setReadOnly(m_readOnly); - m_uiTouch->spHour->setReadOnly(m_readOnly); - m_uiTouch->spMinutes->setReadOnly(m_readOnly); - m_uiTouch->spSeconds->setReadOnly(m_readOnly); - m_uiTouch->spYear->setReadOnly(m_readOnly); - m_uiTouch->cbxTimeZone->setEnabled(m_readOnly); - } + if (m_uiLe) + { + m_uiLe->leLongDay->setReadOnly(m_readOnly); + m_uiLe->leLongHHMMSS->setReadOnly(m_readOnly); + m_uiLe->leLongMonth->setReadOnly(m_readOnly); + m_uiLe->leLongTZ->setReadOnly(m_readOnly); + m_uiLe->leLongYear->setReadOnly(m_readOnly); + } + if (m_uiTouch) + { + m_uiTouch->spDay->setReadOnly(m_readOnly); + m_uiTouch->spHour->setReadOnly(m_readOnly); + m_uiTouch->spMinutes->setReadOnly(m_readOnly); + m_uiTouch->spSeconds->setReadOnly(m_readOnly); + m_uiTouch->spYear->setReadOnly(m_readOnly); + m_uiTouch->cbxTimeZone->setEnabled(m_readOnly); + } } void LtsDateTimeEdit::setWithCheckBox(bool checkBoxEnabled) { - if (m_withCheckBox == checkBoxEnabled) - return; + if (m_withCheckBox == checkBoxEnabled) + return; - m_withCheckBox = checkBoxEnabled; - if (m_uiLe) - { - m_uiLe->checkBox->setVisible(m_withCheckBox); - if (!m_withCheckBox) - m_uiLe->checkBox->setChecked(true); - } - if (m_uiTouch) - { - m_uiTouch->checkBox->setVisible(m_withCheckBox); - if (!m_withCheckBox) - m_uiTouch->checkBox->setChecked(true); - } + m_withCheckBox = checkBoxEnabled; + if (m_uiLe) + { + m_uiLe->checkBox->setVisible(m_withCheckBox); + if (!m_withCheckBox) // If no checkBox -> set other Elements enabled + m_uiLe->checkBox->setChecked(true); + } + if (m_uiTouch) + { + m_uiTouch->checkBox->setVisible(m_withCheckBox); + if (!m_withCheckBox) // If no checkBox -> set other Elements enabled + m_uiTouch->checkBox->setChecked(true); + } } void LtsDateTimeEdit::setCheckBoxChecked(bool bChecked) { - if (!m_uiLe) - return; - m_uiLe->checkBox->setChecked(bChecked); + if (!m_uiLe) + return; + m_uiLe->checkBox->setChecked(bChecked); } bool LtsDateTimeEdit::isCheckBoxChecked() const { - if (!m_uiLe) - return false; - return m_uiLe->checkBox->isChecked(); + if (!m_uiLe) + return false; + return m_uiLe->checkBox->isChecked(); } void LtsDateTimeEdit::setWithNowButton(bool nowButton) { - if (m_withNowButton == nowButton) - return; + if (m_withNowButton == nowButton) + return; - m_withNowButton = nowButton; - if (m_uiLe) - m_uiLe->pbNow->setVisible(m_withNowButton); - if (m_uiTouch) - m_uiTouch->pbNow->setVisible(m_withNowButton); + m_withNowButton = nowButton; + if (m_uiLe) + m_uiLe->pbNow->setVisible(m_withNowButton); + if (m_uiTouch) + m_uiTouch->pbNow->setVisible(m_withNowButton); } bool LtsDateTimeEdit::setMsecsSinceEpoch(qint64 msec, bool setToNearestPossible) { - if (msec == 0 && m_withCheckBox) - { - if (m_uiLe) - m_uiLe->checkBox->setChecked(false); - m_dateIsAcceptable = true; - return true; - } + if (msec == 0 && m_withCheckBox) + { if (m_uiLe) - m_uiLe->checkBox->setChecked(true); - - m_dateIsAcceptable = false; - if (msec == 0) - return false; - - if (!setToNearestPossible) - { - if (!isDataAcceptable()) - return false; - } - else - { - if (msec < m_minTimeMSec && m_minTimeMSec > 0) - msec = m_minTimeMSec; - if (msec > m_maxTimeMSec && m_maxTimeMSec > 0) - msec = m_maxTimeMSec; - } - - m_curTimeMSec = msec; - - const qint64 offsetTimeZoneMsec = getTimezoneAsSecs() * 1000; - const QDateTime datetime(QDateTime::fromMSecsSinceEpoch(m_curTimeMSec + offsetTimeZoneMsec, Qt::UTC)); - const QDate date(datetime.date()); - const QTime time(datetime.time()); - - const int day = date.day(); - const int month = date.month(); - const int year = date.year(); - const int hour = time.hour(); - const int minute = time.minute(); - const int second = time.second(); - - if (!setYear(year) || !setMonth(month) || !setDay(day) || !setHHMMSS(hour, minute, second)) - return false; - - if (!isDataAcceptable()) - return false; - - enableControls(); - - emit dateTimeChanged(); - + m_uiLe->checkBox->setChecked(false); + m_dateIsAcceptable = true; return true; + } + if (m_uiLe) + m_uiLe->checkBox->setChecked(true); + + m_dateIsAcceptable = false; // will be correctly set in isDataAcceptable() + if (msec == 0) + return false; + + // nothing changed ? + // deactivate since m_offsetTimeZone may have changed: + // if (m_curTimeMSec / 1000 == msec / 1000) + // return isDataAcceptable(); + + if (!setToNearestPossible) + { + if (!isDataAcceptable()) + return false; + } + else + { + if (msec < m_minTimeMSec && m_minTimeMSec > 0) + msec = m_minTimeMSec; + if (msec > m_maxTimeMSec && m_maxTimeMSec > 0) + msec = m_maxTimeMSec; + } + + m_curTimeMSec = msec; + + const qint64 offsetTimeZoneMsec = getTimezoneAsSecs() * 1000; + const QDateTime datetime(QDateTime::fromMSecsSinceEpoch(m_curTimeMSec + offsetTimeZoneMsec, Qt::UTC)); + const QDate date(datetime.date()); + const QTime time(datetime.time()); + + const int day = date.day(); + const int month = date.month(); + const int year = date.year(); + const int hour = time.hour(); + const int minute = time.minute(); + const int second = time.second(); + + //if (!setTimezone(tz) || + if (!setYear(year) || + !setMonth(month) || + !setDay(day) || + !setHHMMSS(hour, minute, second)) + return false; + + if (!isDataAcceptable()) + return false; + + enableControls(); + + emit dateTimeChanged(); + + return true; } + qint64 LtsDateTimeEdit::msecsSinceEpoch() const { - if (isEmpty()) - return 0; + if (isEmpty()) + return 0; - if (m_uiLe && !m_uiLe->checkBox->isChecked()) - return 0; - if (m_uiTouch && !m_uiTouch->checkBox->isChecked()) - return 0; + if (m_uiLe && !m_uiLe->checkBox->isChecked()) + return 0; + if (m_uiTouch && !m_uiTouch->checkBox->isChecked()) + return 0; - auto that = const_cast(this); - if (!that->isDataAcceptable()) - return 0; + auto that = const_cast(this); + if (!that->isDataAcceptable()) + return 0; - return m_curTimeMSec; + return m_curTimeMSec; } bool LtsDateTimeEdit::setTimezone(char tz) { - tz = toupper(tz); - if (!DTG::isTimezoneValid(tz)) - return false; + tz = toupper(tz); + if (!DTG::isTimezoneValid(tz)) + return false; - if (m_uiLe) - setItemText(m_uiLe->leLongTZ, QString(QLatin1Char(tz))); - if (m_uiTouch) - setItemText(m_uiTouch->cbxTimeZone, QString(QLatin1Char(tz))); + if (m_uiLe) + setItemText(m_uiLe->leLongTZ, QString(QLatin1Char(tz))); + if (m_uiTouch) + setItemText(m_uiTouch->cbxTimeZone, QString(QLatin1Char(tz))); - setMsecsSinceEpoch(m_curTimeMSec); + setMsecsSinceEpoch(m_curTimeMSec); // to update GUI - return true; + return true; } char LtsDateTimeEdit::getTimezone() const { - QString str; - if (m_uiLe) - str = getItemText(m_uiLe->leLongTZ); - if (m_uiTouch) - str = getItemText(m_uiTouch->cbxTimeZone); + QString str; + if (m_uiLe) + str = getItemText(m_uiLe->leLongTZ); + if (m_uiTouch) + str = getItemText(m_uiTouch->cbxTimeZone); - if (str.isEmpty()) - return DTG::timezone(); - return str[0].toUpper().toLatin1(); + if (str.isEmpty()) + return DTG::timezone(); + return str[0].toUpper().toLatin1(); } qint64 LtsDateTimeEdit::getTimezoneAsSecs() const { - const char tzGUI = getTimezone(); - return DTG::timezone2Secs(tzGUI); + const char tzGUI = getTimezone(); + return DTG::timezone2Secs(tzGUI); } void LtsDateTimeEdit::clearTimezone() { - if (m_uiLe) - m_uiLe->leLongTZ->clear(); - if (m_uiTouch) - m_uiTouch->cbxTimeZone->setCurrentIndex(0); + if (m_uiLe) + m_uiLe->leLongTZ->clear(); + if (m_uiTouch) + m_uiTouch->cbxTimeZone->setCurrentIndex(0); } void LtsDateTimeEdit::setMinMaxMonth(int minMonth, int maxMonth) { - if (!m_uiTouch) - return; + if (!m_uiTouch) + return; - if (m_minMonth != minMonth) - m_minMonth = minMonth; - if (m_maxMonth != maxMonth) - m_maxMonth = maxMonth; + if (m_minMonth != minMonth) + m_minMonth = minMonth; + if (m_maxMonth != maxMonth) + m_maxMonth = maxMonth; - int currentMonth = m_uiTouch->cbxMonth->currentData().toInt(); - m_uiTouch->cbxMonth->blockSignals(true); - m_uiTouch->cbxMonth->clear(); - for (int i = 1; i <= 12; ++i) - { - if (i < m_minMonth) - continue; - if (i > m_maxMonth) - break; + int currentMonth = m_uiTouch->cbxMonth->currentData().toInt(); + m_uiTouch->cbxMonth->blockSignals(true); + m_uiTouch->cbxMonth->clear(); + for (int i =1; i<= 12 ; ++i) + { + if (i < m_minMonth) + continue; + if (i > m_maxMonth) + break; - const QStringList monthSl = DTG::months(); - m_uiTouch->cbxMonth->addItem(monthSl[i - 1], i); - } + const QStringList monthSl = DTG::months(); + m_uiTouch->cbxMonth->addItem(monthSl[i-1], i); + // QDate date(1777,i,1); + // m_uiTouch->cbxMonth->addItem(date.toString(QStringLiteral("MMM")), i); - m_uiTouch->cbxMonth->setCurrentIndex(m_uiTouch->cbxMonth->findData(currentMonth)); - m_uiTouch->cbxMonth->blockSignals(false); + } + // cbxMonth.currentData return the correct inht value for the month :-) + + m_uiTouch->cbxMonth->setCurrentIndex(m_uiTouch->cbxMonth->findData(currentMonth)); + m_uiTouch->cbxMonth->blockSignals(false); } -void LtsDateTimeEdit::setSubWidgetsProperties(const QString& name, const QVariant& value) + +void LtsDateTimeEdit::setSubWidgetsProperties(const QString &name, const QVariant &value) { - if (m_uiLe) - { - m_uiLe->leLongDay->setProperty(name.toStdString().c_str(), value); - m_uiLe->leLongHHMMSS->setProperty(name.toStdString().c_str(), value); - m_uiLe->leLongMonth->setProperty(name.toStdString().c_str(), value); - m_uiLe->leLongYear->setProperty(name.toStdString().c_str(), value); - m_uiLe->leLongTZ->setProperty(name.toStdString().c_str(), value); - } - if (m_uiTouch) - { - m_uiTouch->spDay->setProperty(name.toStdString().c_str(), value); - m_uiTouch->spHour->setProperty(name.toStdString().c_str(), value); - m_uiTouch->spMinutes->setProperty(name.toStdString().c_str(), value); - m_uiTouch->spSeconds->setProperty(name.toStdString().c_str(), value); - m_uiTouch->spYear->setProperty(name.toStdString().c_str(), value); - } + if (m_uiLe) + { + m_uiLe->leLongDay->setProperty(name.toStdString().c_str(), value); + m_uiLe->leLongHHMMSS->setProperty(name.toStdString().c_str(), value); + m_uiLe->leLongMonth->setProperty(name.toStdString().c_str(), value); + m_uiLe->leLongYear->setProperty(name.toStdString().c_str(), value); + m_uiLe->leLongTZ->setProperty(name.toStdString().c_str(), value); + } + if (m_uiTouch) + { + m_uiTouch->spDay->setProperty(name.toStdString().c_str(), value); + m_uiTouch->spHour->setProperty(name.toStdString().c_str(), value); + m_uiTouch->spMinutes->setProperty(name.toStdString().c_str(), value); + m_uiTouch->spSeconds->setProperty(name.toStdString().c_str(), value); + m_uiTouch->spYear->setProperty(name.toStdString().c_str(), value); + } } bool LtsDateTimeEdit::setMonth(int month) { - const auto months(DTG::months()); - if (month < 1 || month > months.size()) - return false; + const auto months(DTG::months()); + if (month < 1 || month > months.size()) + return false; - if (m_uiLe) - setItemText(m_uiLe->leLongMonth, months.at(month - 1)); - if (m_uiTouch) - setItemData(m_uiTouch->cbxMonth, month); - return true; + if (m_uiLe) + setItemText(m_uiLe->leLongMonth, months.at(month - 1)); + if (m_uiTouch) + setItemData(m_uiTouch->cbxMonth, month); + return true; } int LtsDateTimeEdit::getMonth() const { - if (m_uiLe) - { - const QString str = getItemText(m_uiLe->leLongMonth); - if (str.length() != 3) - return -1; + if (m_uiLe) + { + const QString str = getItemText(m_uiLe->leLongMonth); + if (str.length() != 3) + return -1; - int idx = DTG::months().indexOf(str); - if (idx < 0) - return -1; - return idx + 1; - } - if (m_uiTouch) - { - int month = getItemData(m_uiTouch->cbxMonth); - return month; - } - return 0; + int idx = DTG::months().indexOf(str); + if (idx < 0) + return -1; + return idx + 1; + } + if (m_uiTouch) + { + int month = getItemData(m_uiTouch->cbxMonth); + return month; + } + return 0; } bool LtsDateTimeEdit::setDay(int day) { - if (day < 1 || day > 31) - return false; + if (day < 1 || day > 31) + return false; - QString oldDay; + QString oldDay; + if (m_uiLe) + oldDay = m_uiLe->leLongDay->text(); + int oldDayInt = 0; + if (m_uiTouch) + oldDayInt = getItemValue(m_uiTouch->spDay); + + if (m_uiLe) + setItemText(m_uiLe->leLongDay, QStringLiteral("%1").arg(day, 2, 10, QLatin1Char('0'))); + if (m_uiTouch) + setItemValue(m_uiTouch->spDay, day); + + if (!isDayAcceptable()) + { if (m_uiLe) - oldDay = m_uiLe->leLongDay->text(); - int oldDayInt = 0; + setItemText(m_uiLe->leLongDay, oldDay); if (m_uiTouch) - oldDayInt = getItemValue(m_uiTouch->spDay); + setItemValue(m_uiTouch->spDay, oldDayInt); + return false; + } - if (m_uiLe) - setItemText(m_uiLe->leLongDay, QStringLiteral("%1").arg(day, 2, 10, QLatin1Char('0'))); - if (m_uiTouch) - setItemValue(m_uiTouch->spDay, day); - - if (!isDayAcceptable()) - { - if (m_uiLe) - setItemText(m_uiLe->leLongDay, oldDay); - if (m_uiTouch) - setItemValue(m_uiTouch->spDay, oldDayInt); - return false; - } - - return true; + return true; } int LtsDateTimeEdit::getDay() const { - if (m_uiLe) - return m_uiLe->leLongDay->getValue(); - if (m_uiTouch) - return getItemValue(m_uiTouch->spDay); - return 0; + if (m_uiLe) + return m_uiLe->leLongDay->getValue(); + if (m_uiTouch) + return getItemValue(m_uiTouch->spDay); + return 0; } bool LtsDateTimeEdit::setHHMMSS(int hour, int minute, int second) { - if (hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59) - return false; + if (hour < 0 || hour > 23 || + minute < 0 || minute > 59 || + second < 0 || second > 59) + return false; - if (m_uiLe) - m_uiLe->leLongHHMMSS->setValue(hour * 10000 + minute * 100 + second); - if (m_uiTouch) - { - setItemValue(m_uiTouch->spHour, hour); - setItemValue(m_uiTouch->spMinutes, minute); - setItemValue(m_uiTouch->spSeconds, second); - } + if (m_uiLe) + m_uiLe->leLongHHMMSS->setValue(hour * 10000 + minute * 100 + second); + if (m_uiTouch) + { + setItemValue(m_uiTouch->spHour , hour); + setItemValue(m_uiTouch->spMinutes, minute); + setItemValue(m_uiTouch->spSeconds, second); + } - return true; + return true; } int LtsDateTimeEdit::getHour() const { - if (m_uiLe) - { - const int time = m_uiLe->leLongHHMMSS->getValue(); - return time / 10000; - } - if (m_uiTouch) - { - return getItemValue(m_uiTouch->spHour); - } - return 0; + if (m_uiLe) + { + const int time = m_uiLe->leLongHHMMSS->getValue(); + return time / 10000; + } + if (m_uiTouch) + { + return getItemValue(m_uiTouch->spHour); + } + return 0; } int LtsDateTimeEdit::getMinute() const { - if (m_uiLe) - { - const int time = m_uiLe->leLongHHMMSS->getValue(); - return (time / 100) % 100; - } - if (m_uiTouch) - { - return getItemValue(m_uiTouch->spMinutes); - } - return 0; + if (m_uiLe) + { + const int time = m_uiLe->leLongHHMMSS->getValue(); + return (time / 100) % 100; + } + if (m_uiTouch) + { + return getItemValue(m_uiTouch->spMinutes); + } + return 0; } int LtsDateTimeEdit::getSecond() const { - if (m_uiLe) - { - const int time = m_uiLe->leLongHHMMSS->getValue(); - return time % 100; - } - if (m_uiTouch) - { - return getItemValue(m_uiTouch->spSeconds); - } - return 0; + if (m_uiLe) + { + const int time = m_uiLe->leLongHHMMSS->getValue(); + return time % 100; + } + if (m_uiTouch) + { + return getItemValue(m_uiTouch->spSeconds); + } + return 0; } bool LtsDateTimeEdit::setYear(int year) { - int finalYear = -1; - if (year >= 0 && year <= 99) - finalYear = year; - else if (year >= 2000 && year <= 2099) - finalYear = year - 2000; + int finalYear = -1; + if (year >= 0 && year <= 99) + finalYear = year; + else if (year >= 2000 && year <= 2099) + finalYear = year - 2000; - if (finalYear >= 0) - { - if (m_uiLe) - m_uiLe->leLongYear->setValue(finalYear); - if (m_uiTouch) - setItemValue(m_uiTouch->spYear, finalYear); - return true; - } + if (finalYear >= 0) + { + if (m_uiLe) + m_uiLe->leLongYear->setValue(finalYear); + if (m_uiTouch) + setItemValue(m_uiTouch->spYear, finalYear); + return true; + } - return false; + return false; } int LtsDateTimeEdit::getYear() const { - if (m_uiLe) - return 2000 + m_uiLe->leLongYear->getValue(); - if (m_uiTouch) - return 2000 + m_uiTouch->spYear->value(); - return 2000; + if (m_uiLe) + return 2000 + m_uiLe->leLongYear->getValue(); + if (m_uiTouch) + return 2000 + m_uiTouch->spYear->value(); + return 2000; } bool LtsDateTimeEdit::isEmpty() const { - return (isEmptyDay() || isEmptyHHMMSS() || isEmptyMonth() || isEmptyTimezone() || isEmptyYear()); + return (isEmptyDay() || + isEmptyHHMMSS() || + isEmptyMonth() || + isEmptyTimezone() || + isEmptyYear()); } bool LtsDateTimeEdit::isValidDate() const { - return m_dateIsAcceptable; + return m_dateIsAcceptable; } + bool LtsDateTimeEdit::isEmptyDay() const { - if (m_uiLe) - return m_uiLe->leLongDay->isEmpty(); - return false; + if (m_uiLe) + return m_uiLe->leLongDay->isEmpty(); + return false; // spinBox can´t be empty } bool LtsDateTimeEdit::isEmptyHHMMSS() const { - if (m_uiLe) - return m_uiLe->leLongHHMMSS->isEmpty(); - return false; + if (m_uiLe) + return m_uiLe->leLongHHMMSS->isEmpty(); + return false; // spinBox can´t be empty } bool LtsDateTimeEdit::isEmptyMonth() const { - if (m_uiLe) - return m_uiLe->leLongMonth->text().isEmpty(); - return false; + if (m_uiLe) + return m_uiLe->leLongMonth->text().isEmpty(); + return false; // spinBox can´t be empty } bool LtsDateTimeEdit::isEmptyTimezone() const { - if (m_uiLe) - return m_uiLe->leLongTZ->text().isEmpty(); - return false; + if (m_uiLe) + return m_uiLe->leLongTZ->text().isEmpty(); + return false; // comboBox can´t be empty } bool LtsDateTimeEdit::isEmptyYear() const { - if (m_uiLe) - return m_uiLe->leLongYear->isEmpty(); - return false; + if (m_uiLe) + return m_uiLe->leLongYear->isEmpty(); + return false; // spinBox can´t be empty } bool LtsDateTimeEdit::hasFocus() const { - if (!m_uiLe) - return false; - return (m_uiLe->leLongDay->hasFocus() || m_uiLe->leLongHHMMSS->hasFocus() || m_uiLe->leLongMonth->hasFocus() || - m_uiLe->leLongTZ->hasFocus() || m_uiLe->leLongYear->hasFocus()); + if (!m_uiLe) + return false; + return (m_uiLe->leLongDay->hasFocus() || + m_uiLe->leLongHHMMSS->hasFocus() || + m_uiLe->leLongMonth->hasFocus() || + m_uiLe->leLongTZ->hasFocus() || + m_uiLe->leLongYear->hasFocus()); } bool LtsDateTimeEdit::isDataAcceptable() { - m_dateIsAcceptable = false; + m_dateIsAcceptable = false; - bool state = isDayAcceptable() && isHHMMSSAcceptable() && isMonthAcceptable() && isYearAcceptable() && - QDate::isValid(getYear(), getMonth(), getDay()) && QTime::isValid(getHour(), getMinute(), getSecond()); + bool state = + isDayAcceptable() && + isHHMMSSAcceptable() && + isMonthAcceptable() && + isYearAcceptable() && + QDate::isValid(getYear(), getMonth(), getDay()) && + QTime::isValid(getHour(), getMinute(), getSecond()); - if (m_editTimezone && state) - state = isTzAcceptable(); + if (m_editTimezone && state) + state = isTzAcceptable(); - showInvalidData(false); + showInvalidData(false); - if (!state) - { - disableControls(); - return false; - } + if (!state) + { + disableControls(); + return false; + } - qint64 msec = QDateTime(QDate(getYear(), getMonth(), getDay()), QTime(getHour(), getMinute(), getSecond()), Qt::UTC) - .toMSecsSinceEpoch(); - msec -= DTG::timezone2Secs(getTimezone()) * 1000LL; - if (m_minTimeMSec > 0 && m_maxTimeMSec > 0 && m_minTimeMSec < m_maxTimeMSec) - { - if (msec < m_minTimeMSec || msec > m_maxTimeMSec) - return false; - } + qint64 msec = QDateTime(QDate(getYear(), getMonth(), getDay()), QTime(getHour(), getMinute(), getSecond()), Qt::UTC).toMSecsSinceEpoch(); + msec -= DTG::timezone2Secs(getTimezone()) * 1000LL; + if (m_minTimeMSec > 0 && m_maxTimeMSec > 0 && m_minTimeMSec < m_maxTimeMSec) + { + if (msec < m_minTimeMSec || msec > m_maxTimeMSec) + return false; + } - m_curTimeMSec = msec; - enableControls(); - m_dateIsAcceptable = true; - return true; + m_curTimeMSec = msec; + enableControls(); + m_dateIsAcceptable = true; + return true; } bool LtsDateTimeEdit::isDayAcceptable() const { - int value = getDay(); - int max = 31; - if (isMonthAcceptable()) + int value = getDay(); + int max = 31; + if (isMonthAcceptable()) + { + const int month = getMonth(); + switch (month) { - const int month = getMonth(); - switch (month) - { - case 2: { - max = 28; - if (isYearAcceptable()) - { - if (getYear() % 4 == 0 && (getYear() % 100 != 0 || getYear() % 400 == 0)) - - max = 29; - } - break; - } - case 4: - case 6: - case 9: - case 11: - max = 30; - break; - default: - break; - } + case 2: + { + max = 28; + if (isYearAcceptable()) + { + if (getYear() % 4 == 0 && (getYear() % 100 != 0 || getYear() % 400 == 0)) + // centennial years (2100, 2200...) are not leap, unless they divide by 400 (2000, 2400...)! + max = 29; + } + break; } - return (value > 0 && value <= max); + case 4: + case 6: + case 9: + case 11: + max = 30; + break; + default: + break; + } + } + return (value > 0 && value <= max); } bool LtsDateTimeEdit::isHHMMSSAcceptable() const { - int hh = getHour(); - if (hh < 0 || hh > 23) - return false; + int hh = getHour(); + if (hh < 0 || hh > 23) + return false; - int mm = getMinute(); - if (mm < 0 || mm > 59) - return false; + int mm = getMinute(); + if (mm < 0 || mm > 59) + return false; - int ss = getSecond(); - if (ss < 0 || ss > 59) - return false; + int ss = getSecond(); + if (ss < 0 || ss > 59) + return false; - return true; + return true; } bool LtsDateTimeEdit::isMonthAcceptable() const { - int value = getMonth(); - return (value > 0 && value <= 12); + int value = getMonth(); + return (value > 0 && value <= 12); } bool LtsDateTimeEdit::isYearAcceptable() const { - if (m_uiLe) - return isLineEditDataAcceptable(m_uiLe->leLongYear); - return true; + if (m_uiLe) + return isLineEditDataAcceptable(m_uiLe->leLongYear); + return true; // spinBox/combobox !acceptable } bool LtsDateTimeEdit::isTzAcceptable() const { - if (m_uiLe) - return isLineEditDataAcceptable(m_uiLe->leLongTZ); - return true; + if (m_uiLe) + return isLineEditDataAcceptable(m_uiLe->leLongTZ); + return true; // spinBox/combobox !acceptable } void LtsDateTimeEdit::showInvalidData(bool setFocus) { - if (!m_uiLe) - return; + if (!m_uiLe) + return; - bool focus = setFocus; + bool focus = setFocus; // Fokus bei Fehler setzen ??? - auto check = [&](QLineEdit* le, bool isValid) { - if (isValid) - le->setStyleSheet(QString()); - else - { - le->setStyleSheet(QLatin1String("background-color: yellow;")); - if (focus) - { - le->setFocus(); - focus = false; - } - } - }; + auto check = [&](QLineEdit * le, bool isValid) + { + if (isValid) + le->setStyleSheet(QString()); + else + { + le->setStyleSheet(QLatin1String("background-color: yellow;")); + if (focus) + { + le->setFocus(); + focus = false; + } + } + }; - check(m_uiLe->leLongDay, isDayAcceptable()); - check(m_uiLe->leLongHHMMSS, isHHMMSSAcceptable()); - if (m_editTimezone) - check(m_uiLe->leLongTZ, isTzAcceptable()); - check(m_uiLe->leLongMonth, isMonthAcceptable()); - check(m_uiLe->leLongYear, isYearAcceptable()); + check(m_uiLe->leLongDay, isDayAcceptable()); + check(m_uiLe->leLongHHMMSS, isHHMMSSAcceptable()); + if (m_editTimezone) + check(m_uiLe->leLongTZ, isTzAcceptable()); + check(m_uiLe->leLongMonth, isMonthAcceptable()); + check(m_uiLe->leLongYear, isYearAcceptable()); } -bool LtsDateTimeEdit::isLineEditDataAcceptable(QLineEdit* le) const +bool LtsDateTimeEdit::isLineEditDataAcceptable(QLineEdit *le) const { - const QValidator* pValidator = le->validator(); + const QValidator *pValidator = le->validator(); - if (!pValidator) - return true; + if (!pValidator) + return true; - QString text = le->text(); + QString text = le->text(); - int pos; - QValidator::State state = pValidator->validate(text, pos); + int pos; + QValidator::State state = pValidator->validate(text, pos); - if (state == QValidator::Acceptable || state == QValidator::Intermediate) - return true; + if (state == QValidator::Acceptable || state == QValidator::Intermediate) + return true; - return false; + return false; } void LtsDateTimeEdit::setFixedDateTime() { - setMsecsSinceEpoch(LtsUtils::OperatorSettings::getInstance() - ->value(QStringLiteral("TimeSettings"), QStringLiteral("FixedTime"), 0) - .toLongLong()); + setMsecsSinceEpoch(LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("TimeSettings"), QStringLiteral("FixedTime"), 0).toLongLong()); } void LtsDateTimeEdit::setOffsetDateTime() { - if (!m_getCurrentTimeCallback) - return; + if (!m_getCurrentTimeCallback) + return; - qint64 offset = LtsUtils::OperatorSettings::getInstance() - ->value(QStringLiteral("TimeSettings"), QStringLiteral("Offset"), 0) - .toLongLong(); - - setMsecsSinceEpoch((m_getCurrentTimeCallback() / 1000) * 1000 + offset); + qint64 offset = LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("TimeSettings"), QStringLiteral("Offset"), 0).toLongLong(); + // we only show seconds, so strip away milliseconds + setMsecsSinceEpoch((m_getCurrentTimeCallback() / 1000) * 1000 + offset); } void LtsDateTimeEdit::setSliderValue(int val) { - setMsecsSinceEpoch(val * 1000LL); + setMsecsSinceEpoch(val * 1000LL); } -void LtsDateTimeEdit::valueDayChanged(const QString& str) +void LtsDateTimeEdit::valueDayChanged(const QString &str) { - if (!m_uiLe) - return; - int curpos = m_uiLe->leLongDay->cursorPosition(); - int cp = curpos; + if (!m_uiLe) + return; + int curpos = m_uiLe->leLongDay->cursorPosition(); + int cp = curpos; - bool changed = false; + bool changed = false; - QString tag(str); + QString tag(str); - if (tag.length() > 2) + if (tag.length() > 2) + { + tag = tag.left(2); + changed = true; + } + + bool ok; + int t = tag.toInt(&ok, 10); + + if (ok) + { + if (t > 31) { - tag = tag.left(2); - changed = true; + tag.remove(curpos - 1, 1); // letztes Zeichen wieder entfernen + if (cp >= curpos) + cp--; // Korrektur der neuen Cursorposition + changed = true; } + } - bool ok; - int t = tag.toInt(&ok, 10); + if (changed) + { + m_uiLe->leLongDay->setText(tag); + m_uiLe->leLongDay->setCursorPosition(cp); + } - if (ok) - { - if (t > 31) - { - tag.remove(curpos - 1, 1); - if (cp >= curpos) - cp--; - changed = true; - } - } + if (tag.length() == 2) + { + showInvalidData(false); - if (changed) - { - m_uiLe->leLongDay->setText(tag); - m_uiLe->leLongDay->setCursorPosition(cp); - } - - if (tag.length() == 2) - { - showInvalidData(false); - - if (m_autoForward) - focusNextPrevChild(true); - } + if (m_autoForward) + focusNextPrevChild(true); + } } void LtsDateTimeEdit::fixupHHMMSS() { - if (!m_uiLe) - return; + if (!m_uiLe) + return; - int curpos = m_uiLe->leLongHHMMSS->cursorPosition(); - int cp = curpos; + int curpos = m_uiLe->leLongHHMMSS->cursorPosition(); + int cp = curpos; - bool changed = false; + bool changed = false; - QString uhrzeit(m_uiLe->leLongHHMMSS->text()); + QString uhrzeit(m_uiLe->leLongHHMMSS->text()); - QString hh; - QString mm; - QString ss; + // + // Wertebereich überprüfen: 000000 bis 235959 zulässig + // - if (uhrzeit.length() > 1) - hh = uhrzeit.left(2); + + QString hh; + QString mm; + QString ss; + + if (uhrzeit.length() > 1) + hh = uhrzeit.left(2); + else + hh = uhrzeit + QLatin1Char('0'); + + if (uhrzeit.length() > 0) + { + if (uhrzeit.length() == 1) + hh = uhrzeit.mid(0, 1) + QLatin1Char('0'); + else if (uhrzeit.length() >= 2) + { + hh = uhrzeit.mid(0, 2); + if (uhrzeit.length() > 2) + { + if (uhrzeit.length() == 3) + mm = uhrzeit.mid(2, 1) + QLatin1Char('0'); + else if (uhrzeit.length() >= 4) + { + mm = uhrzeit.mid(2, 2); + if (uhrzeit.length() == 5) + ss = uhrzeit.mid(4, 1) + QLatin1Char('0'); + else if (uhrzeit.length() == 6) + ss = uhrzeit.mid(4, 2); + } + } + } + } + + bool ok; + + int h = hh.toInt(&ok, 10); + if (ok) + { + if (h > 23) + { + uhrzeit.remove(curpos - 1, 1); // letztes Zeichen wieder entfernen + if (cp >= curpos) + cp--; // Korrektur der neuen Cursorposition + changed = true; + } + } + + int m = mm.toInt(&ok, 10); + + if (ok) + { + if ((hh.length() == 2) && (m > 59)) // WICHTIG: beide Stellen fuer Stunde bereits gesetzt !!! + { + uhrzeit.remove(curpos - 1, 1); // letztes Zeichen wieder entfernen + if (cp >= curpos) + cp--; // Korrektur der neuen Cursorposition + changed = true; + } + } + + int s = ss.toInt(&ok, 10); + + if (ok) + { + if ((hh.length() == 2 && mm.length() == 2) && (s > 59)) // WICHTIG: beide Stellen fuer Stunde und Minute bereits gesetzt !!! + { + uhrzeit.remove(curpos - 1, 1); // letztes Zeichen wieder entfernen + if (cp >= curpos) + cp--; // Korrektur der neuen Cursorposition + changed = true; + } + } + + if (changed) + { + m_uiLe->leLongHHMMSS->setText(uhrzeit); + m_uiLe->leLongHHMMSS->setCursorPosition(cp); + } + + isDataAcceptable(); + emit dateTimeChanged(); +} + +void LtsDateTimeEdit::valueMonthChanged2(const QString &str) +{ + if (!m_uiLe) + return; + if (str.length() == 3 && m_uiLe->leLongMonth->selectedText().isEmpty()) + focusNextPrevChild(true); +} + +void LtsDateTimeEdit::valueMonthChanged(const QString &str) +{ + if (!m_uiLe) + return; + int curpos = m_uiLe->leLongMonth->cursorPosition(); + int cp = curpos; + + bool changed = false; + + QString monStr = str; + + const auto months = DTG::months(); + for (int i = 0; i < months.size(); ++i) + { + const QString &mon = months.at(i); + if (mon.startsWith(monStr, Qt::CaseInsensitive)) + { + monStr = mon; + changed = true; + break; + } + } + + if (!changed) + { + monStr.remove(curpos - 1, 1); // letztes Zeichen wieder entfernen + if (cp >= curpos) + cp--; // Korrektur der neuen Cursorposition + changed = true; + } + + if (changed) + { + m_uiLe->leLongMonth->setText(monStr); + // WICHTIG: keine negativen Cursorpositionen setzen, da sonst Absturzgefahr !!! + // Bem.: wird in DigitsLineEdit bereits abgefangen + if (cp > 0) + m_uiLe->leLongMonth->setCursorPosition(cp); else - hh = uhrzeit + QLatin1Char('0'); - - if (uhrzeit.length() > 0) - { - if (uhrzeit.length() == 1) - hh = uhrzeit.mid(0, 1) + QLatin1Char('0'); - else if (uhrzeit.length() >= 2) - { - hh = uhrzeit.mid(0, 2); - if (uhrzeit.length() > 2) - { - if (uhrzeit.length() == 3) - mm = uhrzeit.mid(2, 1) + QLatin1Char('0'); - else if (uhrzeit.length() >= 4) - { - mm = uhrzeit.mid(2, 2); - if (uhrzeit.length() == 5) - ss = uhrzeit.mid(4, 1) + QLatin1Char('0'); - else if (uhrzeit.length() == 6) - ss = uhrzeit.mid(4, 2); - } - } - } - } - - bool ok; - - int h = hh.toInt(&ok, 10); - if (ok) - { - if (h > 23) - { - uhrzeit.remove(curpos - 1, 1); - if (cp >= curpos) - cp--; - changed = true; - } - } - - int m = mm.toInt(&ok, 10); - - if (ok) - { - if ((hh.length() == 2) && (m > 59)) - { - uhrzeit.remove(curpos - 1, 1); - if (cp >= curpos) - cp--; - changed = true; - } - } - - int s = ss.toInt(&ok, 10); - - if (ok) - { - if ((hh.length() == 2 && mm.length() == 2) && (s > 59)) - { - uhrzeit.remove(curpos - 1, 1); - if (cp >= curpos) - cp--; - changed = true; - } - } - - if (changed) - { - m_uiLe->leLongHHMMSS->setText(uhrzeit); - m_uiLe->leLongHHMMSS->setCursorPosition(cp); - } - - isDataAcceptable(); - emit dateTimeChanged(); -} - -void LtsDateTimeEdit::valueMonthChanged2(const QString& str) -{ - if (!m_uiLe) - return; - if (str.length() == 3 && m_uiLe->leLongMonth->selectedText().isEmpty()) - focusNextPrevChild(true); -} - -void LtsDateTimeEdit::valueMonthChanged(const QString& str) -{ - if (!m_uiLe) - return; - int curpos = m_uiLe->leLongMonth->cursorPosition(); - int cp = curpos; - - bool changed = false; - - QString monStr = str; - - const auto months = DTG::months(); - for (int i = 0; i < months.size(); ++i) - { - const QString& mon = months.at(i); - if (mon.startsWith(monStr, Qt::CaseInsensitive)) - { - monStr = mon; - changed = true; - break; - } - } - - if (!changed) - { - monStr.remove(curpos - 1, 1); - if (cp >= curpos) - cp--; - changed = true; - } - - if (changed) - { - m_uiLe->leLongMonth->setText(monStr); - - if (cp > 0) - m_uiLe->leLongMonth->setCursorPosition(cp); - else - m_uiLe->leLongMonth->setCursorPosition(1); - } - - if (monStr.size() == 3) - { - showInvalidData(false); - if (m_autoForward) - focusNextPrevChild(true); - } -} - -void LtsDateTimeEdit::valueTimezoneChangedStr(const QString& str) -{ - if (str.length() > 1) - { - clearTimezone(); - return; - } - if (str.length() == 0) - return; - QChar c = str.at(0); - if (!c.isLetter() || c.toUpper() == QLatin1Char('J')) - { - clearTimezone(); - return; - } - if (c.isLower()) - setTimezone(c.toUpper().toLatin1()); + m_uiLe->leLongMonth->setCursorPosition(1); // Ausweichposition linker Textanfang + } + if (monStr.size() == 3) + { showInvalidData(false); if (m_autoForward) - focusNextPrevChild(true); + focusNextPrevChild(true); + } +} + +void LtsDateTimeEdit::valueTimezoneChangedStr(const QString &str) +{ + if (str.length() > 1) + { + clearTimezone(); + return; + } + if (str.length() == 0) + return; + QChar c = str.at(0); + if (!c.isLetter() || c.toUpper() == QLatin1Char('J')) + { + clearTimezone(); + return; + } + if (c.isLower()) + setTimezone(c.toUpper().toLatin1()); + + showInvalidData(false); + if (m_autoForward) + focusNextPrevChild(true); } void LtsDateTimeEdit::valueTimezoneChangedInt(int newTimezone) { - Q_UNUSED(newTimezone); - if (!m_uiTouch) - return; - const QString& curText = m_uiTouch->cbxTimeZone->currentText(); - if (curText.isEmpty()) - return; + Q_UNUSED(newTimezone); + if (!m_uiTouch) + return; + const QString &curText = m_uiTouch->cbxTimeZone->currentText(); + if (curText.isEmpty()) + return; - const QChar tz = curText.at(0); - setTimezone(tz.toUpper().toLatin1()); + const QChar tz = curText.at(0); + setTimezone(tz.toUpper().toLatin1()); } -void LtsDateTimeEdit::valueYearChanged(const QString& str) +void LtsDateTimeEdit::valueYearChanged(const QString &str) { - if (!m_uiLe) - return; - int curpos = m_uiLe->leLongYear->cursorPosition(); - int cp = curpos; + if (!m_uiLe) + return; + int curpos = m_uiLe->leLongYear->cursorPosition(); + int cp = curpos; - bool changed = false; + bool changed = false; - const QString& year = str; + const QString &year = str; - QString yy; - if (year.length() > 2) - { - yy = year.left(2); - changed = true; - } + QString yy; + if (year.length() > 2) + { + yy = year.left(2); + changed = true; + } - if (changed) - { - m_uiLe->leLongYear->setText(yy); - m_uiLe->leLongYear->setCursorPosition(cp); - } + if (changed) + { + m_uiLe->leLongYear->setText(yy); + m_uiLe->leLongYear->setCursorPosition(cp); + } - if (year.length() == 2) - { - showInvalidData(false); - if (m_autoForward) - focusNextPrevChild(true); - } + if (year.length() == 2) + { + showInvalidData(false); + if (m_autoForward) + focusNextPrevChild(true); + } } void LtsDateTimeEdit::onBackHourClicked() { - if (!setMsecsSinceEpoch(m_curTimeMSec - s_oneHourMSec)) - setMsecsSinceEpoch(m_minTimeMSec); + if (!setMsecsSinceEpoch(m_curTimeMSec - s_oneHourMSec)) + setMsecsSinceEpoch(m_minTimeMSec); } void LtsDateTimeEdit::onBackMinuteClicked() { - const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; - if (!setMsecsSinceEpoch(m_curTimeMSec - ofs * s_oneMinuteMSec)) - setMsecsSinceEpoch(m_minTimeMSec); + const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; + if (!setMsecsSinceEpoch(m_curTimeMSec - ofs * s_oneMinuteMSec)) + setMsecsSinceEpoch(m_minTimeMSec); } void LtsDateTimeEdit::onBackSecondClicked() { - const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; - if (!setMsecsSinceEpoch(m_curTimeMSec - ofs * s_oneSecondMSec)) - setMsecsSinceEpoch(m_minTimeMSec); + const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; + if (!setMsecsSinceEpoch(m_curTimeMSec - ofs * s_oneSecondMSec)) + setMsecsSinceEpoch(m_minTimeMSec); } void LtsDateTimeEdit::onForwardSecondClicked() { - const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; - if (!setMsecsSinceEpoch(m_curTimeMSec + ofs * s_oneSecondMSec)) - setMsecsSinceEpoch(m_maxTimeMSec); + const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; + if (!setMsecsSinceEpoch(m_curTimeMSec + ofs * s_oneSecondMSec)) + setMsecsSinceEpoch(m_maxTimeMSec); } void LtsDateTimeEdit::onForwardMinuteClicked() { - const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; - if (!setMsecsSinceEpoch(m_curTimeMSec + ofs * s_oneMinuteMSec)) - setMsecsSinceEpoch(m_maxTimeMSec); + const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; + if (!setMsecsSinceEpoch(m_curTimeMSec + ofs * s_oneMinuteMSec)) + setMsecsSinceEpoch(m_maxTimeMSec); } void LtsDateTimeEdit::onForwardHourClicked() { - if (!setMsecsSinceEpoch(m_curTimeMSec + s_oneHourMSec)) - setMsecsSinceEpoch(m_maxTimeMSec); + if (!setMsecsSinceEpoch(m_curTimeMSec + s_oneHourMSec)) + setMsecsSinceEpoch(m_maxTimeMSec); } void LtsDateTimeEdit::onCheckBoxChanged() { - QVector widgets; - bool bEnable = false; + QVector widgets; + bool bEnable = false; - if (m_uiLe) - { - widgets = {m_uiLe->leLongDay, m_uiLe->leLongHHMMSS, m_uiLe->leLongTZ, m_uiLe->leLongMonth, m_uiLe->leLongYear}; - bEnable = m_uiLe->checkBox->isChecked(); - } + if (m_uiLe) + { + widgets = {m_uiLe->leLongDay, m_uiLe->leLongHHMMSS, m_uiLe->leLongTZ, + m_uiLe->leLongMonth, m_uiLe->leLongYear}; + bEnable = m_uiLe->checkBox->isChecked(); + } - if (m_uiTouch) - { - widgets = {m_uiTouch->spDay, m_uiTouch->spHour, m_uiTouch->spMinutes, m_uiTouch->spSeconds, - m_uiTouch->spYear, m_uiTouch->cbxMonth, m_uiTouch->cbxTimeZone, m_uiTouch->pbNow}; - bEnable = m_uiTouch->checkBox->isChecked(); - } + if (m_uiTouch) + { + widgets = {m_uiTouch->spDay, m_uiTouch->spHour, m_uiTouch->spMinutes, m_uiTouch->spSeconds, m_uiTouch->spYear, m_uiTouch->cbxMonth, m_uiTouch->cbxTimeZone, m_uiTouch->pbNow}; + bEnable = m_uiTouch->checkBox->isChecked(); + } - for (auto w : widgets) - { - if (w) - w->setEnabled(bEnable); - } - enaDisaControls(bEnable); + for (auto w : widgets) + { + if (w) + w->setEnabled(bEnable); + } + enaDisaControls(bEnable); } void LtsDateTimeEdit::disableControls() { - enaDisaControls(false); + enaDisaControls(false); } void LtsDateTimeEdit::enableControls() { - if (!m_uiLe) - return; + if (!m_uiLe) + return; - enaDisaControls(true); - if (m_withSlider && m_minTimeMSec != 0 && m_maxTimeMSec > 0 && m_maxTimeMSec > m_minTimeMSec) - { - m_uiLe->slTime->setEnabled(true); - m_uiLe->slTime->setValue(m_curTimeMSec / 1000LL); - } + enaDisaControls(true); + if (m_withSlider && + m_minTimeMSec != 0 && + m_maxTimeMSec > 0 && + m_maxTimeMSec > m_minTimeMSec) + { + m_uiLe->slTime->setEnabled(true); + m_uiLe->slTime->setValue(m_curTimeMSec / 1000LL); + } } void LtsDateTimeEdit::enaDisaControls(bool bEnable) { - if (!m_uiLe) - return; - const QVector widgets( - {m_uiLe->pbBBB, m_uiLe->pbBB, m_uiLe->pbB, m_uiLe->pbF, m_uiLe->pbFF, m_uiLe->pbFFF, m_uiLe->slTime}); - for (auto w : widgets) - { - if (w) - w->setEnabled(bEnable); - } + if (!m_uiLe) + return; + const QVector widgets({m_uiLe->pbBBB, m_uiLe->pbBB, m_uiLe->pbB, + m_uiLe->pbF, m_uiLe->pbFF, m_uiLe->pbFFF, + m_uiLe->slTime}); + for (auto w : widgets) + { + if (w) + w->setEnabled(bEnable); + } } void LtsDateTimeEdit::setMinimumTimeMSec(qint64 msec) { - if (m_minTimeMSec == msec) - return; - m_minTimeMSec = msec; - if (m_minTimeMSec > 0 && m_uiLe && m_uiLe->slTime) - { - m_uiLe->slTime->setMinimum(m_minTimeMSec / 1000LL); - if (m_maxTimeMSec > m_minTimeMSec) - m_uiLe->slTime->setEnabled(true); - } - if (m_curTimeMSec < m_minTimeMSec) - setMsecsSinceEpoch(m_minTimeMSec); + if (m_minTimeMSec == msec) + return; + m_minTimeMSec = msec; + if (m_minTimeMSec > 0 && m_uiLe && m_uiLe->slTime) + { + m_uiLe->slTime->setMinimum(m_minTimeMSec / 1000LL); + if (m_maxTimeMSec > m_minTimeMSec) + m_uiLe->slTime->setEnabled(true); + } + if (m_curTimeMSec < m_minTimeMSec) + setMsecsSinceEpoch(m_minTimeMSec); } void LtsDateTimeEdit::setMaximumTimeMSec(qint64 msec) { - if (m_maxTimeMSec == msec) - return; - m_maxTimeMSec = msec; - if (!m_uiLe || !m_uiLe->slTime) - return; + if (m_maxTimeMSec == msec) + return; + m_maxTimeMSec = msec; + if (!m_uiLe || !m_uiLe->slTime) + return; - m_uiLe->slTime->setMaximum(m_maxTimeMSec / 1000LL); - if (m_minTimeMSec > 0 && m_maxTimeMSec > m_minTimeMSec) - m_uiLe->slTime->setEnabled(true); - if (m_maxTimeMSec > 0 && m_curTimeMSec > m_maxTimeMSec) - setMsecsSinceEpoch(m_maxTimeMSec); + m_uiLe->slTime->setMaximum(m_maxTimeMSec / 1000LL); + if (m_minTimeMSec > 0 && m_maxTimeMSec > m_minTimeMSec) + m_uiLe->slTime->setEnabled(true); + if (m_maxTimeMSec > 0 && m_curTimeMSec > m_maxTimeMSec) + setMsecsSinceEpoch(m_maxTimeMSec); } void LtsDateTimeEdit::clear() { - if (m_uiLe) - { - m_uiLe->leLongDay->clear(); - m_uiLe->leLongHHMMSS->clear(); - m_uiLe->leLongMonth->clear(); - m_uiLe->leLongYear->clear(); - m_uiLe->leLongTZ->clear(); - m_curTimeMSec = 0; - } - if (m_uiTouch) - { - m_uiTouch->spDay->clear(); - m_uiTouch->spHour->clear(); - m_uiTouch->spMinutes->clear(); - m_uiTouch->spSeconds->clear(); - m_uiTouch->spYear->clear(); - } - emit dateTimeChanged(); + if (m_uiLe) + { + m_uiLe->leLongDay->clear(); + m_uiLe->leLongHHMMSS->clear(); + m_uiLe->leLongMonth->clear(); + m_uiLe->leLongYear->clear(); + m_uiLe->leLongTZ->clear(); + m_curTimeMSec = 0; + } + if (m_uiTouch) + { + m_uiTouch->spDay->clear(); + m_uiTouch->spHour->clear(); + m_uiTouch->spMinutes->clear(); + m_uiTouch->spSeconds->clear(); + m_uiTouch->spYear->clear(); + } + emit dateTimeChanged(); + } void LtsDateTimeEdit::onFocusOutDay() { - if (!m_uiLe) - return; - if (m_backspacePressed) - { - m_backspacePressed = false; - return; - } - if (!m_recursionAvoid && !hasFocus()) - onFocusOut(); + if (!m_uiLe) + return; + if (m_backspacePressed) + { + m_backspacePressed = false; + return; + } + if (!m_recursionAvoid && !hasFocus()) + onFocusOut(); - QString value = m_uiLe->leLongDay->text(); - - if (value.length() == 0 && !m_backspacePressed) + QString value = m_uiLe->leLongDay->text(); + // Leeres Feld nur mit aktueller Uhrzeit auffüllen, wenn irgendein Feld schon befüllt ist: + if (value.length() == 0 && !m_backspacePressed) + { + if (!isEmptyHHMMSS() || + !isEmptyMonth() || + (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || + !isEmptyYear()) { - if (!isEmptyHHMMSS() || !isEmptyMonth() || (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || - !isEmptyYear()) - { - if (m_getCurrentTimeCallback) - { - const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); - setDay(dt.date().day()); - } - } + if (m_getCurrentTimeCallback) + { + const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); + setDay(dt.date().day()); + } } - isDataAcceptable(); - emit dateTimeChanged(); + } + isDataAcceptable(); + emit dateTimeChanged(); } void LtsDateTimeEdit::onFocusOutHHMMSS() { - if (!m_uiLe) - return; - if (m_backspacePressed) - { - m_backspacePressed = false; - return; - } - if (!m_recursionAvoid && !hasFocus()) - onFocusOut(); + if (!m_uiLe) + return; + if (m_backspacePressed) + { + m_backspacePressed = false; + return; + } + if (!m_recursionAvoid && !hasFocus()) + onFocusOut(); - QString value = m_uiLe->leLongHHMMSS->text(); - - if (value.length() == 0 && !m_backspacePressed) + QString value = m_uiLe->leLongHHMMSS->text(); + // Leeres Feld nur mit aktueller Uhrzeit auffüllen, wenn irgendein Feld schon befüllt ist: + if (value.length() == 0 && !m_backspacePressed) + { + if (!isEmptyDay() || + !isEmptyMonth() || + !(isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || + !isEmptyYear()) { - if (!isEmptyDay() || !isEmptyMonth() || !(isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || !isEmptyYear()) - { - if (m_getCurrentTimeCallback) - { - const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); - setHHMMSS(dt.time().hour(), dt.time().minute(), dt.time().second()); - } - } + if (m_getCurrentTimeCallback) + { + const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); + setHHMMSS(dt.time().hour(), dt.time().minute(), dt.time().second()); + } } - value += QString(6 - value.length(), QLatin1Char('0')); - m_uiLe->leLongHHMMSS->setText(value); - isDataAcceptable(); - emit dateTimeChanged(); + } + value += QString(6 - value.length(), QLatin1Char('0')); + m_uiLe->leLongHHMMSS->setText(value); + isDataAcceptable(); + emit dateTimeChanged(); } void LtsDateTimeEdit::onFocusOutTZ() { - if (!m_uiLe) - return; - if (m_backspacePressed) - { - m_backspacePressed = false; - return; - } - if (!m_recursionAvoid && !hasFocus()) - onFocusOut(); + if (!m_uiLe) + return; + if (m_backspacePressed) + { + m_backspacePressed = false; + return; + } + if (!m_recursionAvoid && !hasFocus()) + onFocusOut(); - QString value = m_uiLe->leLongTZ->text(); - - if (value.length() == 0 && !m_backspacePressed) - { - if (!isEmptyHHMMSS() || !isEmptyMonth() || !isEmptyDay() || !isEmptyYear()) - setTimezone(DTG::timezone()); - } - isDataAcceptable(); - emit dateTimeChanged(); + QString value = m_uiLe->leLongTZ->text(); + // Leeres Feld nur mit aktueller Uhrzeit auffüllen, wenn irgendein Feld schon befüllt ist: + if (value.length() == 0 && !m_backspacePressed) + { + if (!isEmptyHHMMSS() || + !isEmptyMonth() || + !isEmptyDay() || + !isEmptyYear()) + setTimezone(DTG::timezone()); + } + isDataAcceptable(); + emit dateTimeChanged(); } void LtsDateTimeEdit::onFocusOutMonth() { - if (!m_uiLe) - return; - if (m_backspacePressed) + if (!m_uiLe) + return; + if (m_backspacePressed) + { + m_backspacePressed = false; + return; + } + + if (!m_recursionAvoid && !hasFocus()) + onFocusOut(); + + QString value = m_uiLe->leLongMonth->text(); + // Leeres Feld nur mit aktueller Uhrzeit auffüllen, wenn irgendein Feld schon befüllt ist: + if (value.length() == 0 && !m_backspacePressed) + { + if (!isEmptyHHMMSS() || + !isEmptyDay() || + (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || + !isEmptyYear()) { - m_backspacePressed = false; - return; + if (m_getCurrentTimeCallback) + { + const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); + setMonth(dt.date().month()); + } } - - if (!m_recursionAvoid && !hasFocus()) - onFocusOut(); - - QString value = m_uiLe->leLongMonth->text(); - - if (value.length() == 0 && !m_backspacePressed) - { - if (!isEmptyHHMMSS() || !isEmptyDay() || (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || - !isEmptyYear()) - { - if (m_getCurrentTimeCallback) - { - const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); - setMonth(dt.date().month()); - } - } - } - isDataAcceptable(); - emit dateTimeChanged(); + } + isDataAcceptable(); + emit dateTimeChanged(); } void LtsDateTimeEdit::onFocusOutYear() { - if (!m_uiLe) - return; - if (m_backspacePressed) + if (!m_uiLe) + return; + if (m_backspacePressed) + { + m_backspacePressed = false; + return; + } + + if (!m_recursionAvoid && !hasFocus()) + onFocusOut(); + + QString value = m_uiLe->leLongYear->text(); + // should always be displayed with 2 digits + if (value.length() == 1) + { + value = QLatin1Char('0') + value; + m_uiLe->leLongYear->setText(value); + } + // Leeres Feld nur mit aktueller Uhrzeit auffüllen, wenn irgendein Feld schon befüllt ist: + if (value.length() == 0 && !m_backspacePressed) + { + if (!isEmptyHHMMSS() || + !isEmptyMonth() || + (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || + !isEmptyDay()) { - m_backspacePressed = false; - return; + if (m_getCurrentTimeCallback) + { + const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); + setYear(dt.date().year()); + } } - - if (!m_recursionAvoid && !hasFocus()) - onFocusOut(); - - QString value = m_uiLe->leLongYear->text(); - - if (value.length() == 1) - { - value = QLatin1Char('0') + value; - m_uiLe->leLongYear->setText(value); - } - - if (value.length() == 0 && !m_backspacePressed) - { - if (!isEmptyHHMMSS() || !isEmptyMonth() || (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || - !isEmptyDay()) - { - if (m_getCurrentTimeCallback) - { - const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); - setYear(dt.date().year()); - } - } - } - isDataAcceptable(); - emit dateTimeChanged(); + } + isDataAcceptable(); + emit dateTimeChanged(); } void LtsDateTimeEdit::onFocusOutBackspace() { - m_backspacePressed = true; + m_backspacePressed = true; } void LtsDateTimeEdit::onFocusOut() { - if (!m_uiLe) - return; - if (m_backspacePressed) - { - m_backspacePressed = false; - return; - } - m_recursionAvoid = true; - onFocusOutDay(); - onFocusOutHHMMSS(); - onFocusOutMonth(); - onFocusOutTZ(); - onFocusOutYear(); - m_recursionAvoid = false; + if (!m_uiLe) + return; + if (m_backspacePressed) + { + m_backspacePressed = false; + return; + } + m_recursionAvoid = true; + onFocusOutDay(); + onFocusOutHHMMSS(); + onFocusOutMonth(); + onFocusOutTZ(); + onFocusOutYear(); + m_recursionAvoid = false; } void LtsDateTimeEdit::onHmsWheelEvent(bool bForward, int cursorPos) { - if (!m_uiLe) - return; - if (m_uiLe->leLongHHMMSS->text().size() != 6) - return; + if (!m_uiLe) + return; + if (m_uiLe->leLongHHMMSS->text().size() != 6) + return; - fixupHHMMSS(); + fixupHHMMSS(); - int selStart = 0; - switch (cursorPos) - { - case 0: - case 1: - case 2: - if (bForward) - onForwardHourClicked(); - else - onBackHourClicked(); - selStart = 0; - break; - case 3: - case 4: - if (bForward) - onForwardMinuteClicked(); - else - onBackMinuteClicked(); - selStart = 2; - break; - case 5: - case 6: - if (bForward) - onForwardSecondClicked(); - else - onBackSecondClicked(); - selStart = 4; - break; - default: - return; - } - m_uiLe->leLongHHMMSS->setCursorPosition(cursorPos); - m_uiLe->leLongHHMMSS->setSelection(selStart, 2); - emit dateTimeChanged(); + int selStart = 0; + switch (cursorPos) + { + case 0: + case 1: + case 2: + if (bForward) + onForwardHourClicked(); + else + onBackHourClicked(); + selStart = 0; + break; + case 3: + case 4: + if (bForward) + onForwardMinuteClicked(); + else + onBackMinuteClicked(); + selStart = 2; + break; + case 5: + case 6: + if (bForward) + onForwardSecondClicked(); + else + onBackSecondClicked(); + selStart = 4; + break; + default: + return; + } + m_uiLe->leLongHHMMSS->setCursorPosition(cursorPos); + m_uiLe->leLongHHMMSS->setSelection(selStart, 2); + emit dateTimeChanged(); } void LtsDateTimeEdit::onDayWheelEvent(bool bForward, int cursorPos) { - if (!m_uiLe) - return; - if (!isDayAcceptable()) - return; - const int ofs = bForward ? 1 : -1; - setMsecsSinceEpoch(m_curTimeMSec + ofs * s_oneDayMSec, true); - m_uiLe->leLongDay->setCursorPosition(cursorPos); - m_uiLe->leLongDay->setSelection(0, 2); - emit dateTimeChanged(); + if (!m_uiLe) + return; + if (!isDayAcceptable()) + return; + const int ofs = bForward ? 1 : -1; + setMsecsSinceEpoch(m_curTimeMSec + ofs * s_oneDayMSec, true); + m_uiLe->leLongDay->setCursorPosition(cursorPos); + m_uiLe->leLongDay->setSelection(0, 2); + emit dateTimeChanged(); } void LtsDateTimeEdit::onMonthWheelEvent(bool bForward, int cursorPos) { - if (!m_uiLe) - return; - if (!isMonthAcceptable()) - return; - const int ofs = bForward ? 1 : -1; - const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_curTimeMSec, Qt::UTC).addMonths(ofs)); - setMsecsSinceEpoch(dt.toMSecsSinceEpoch(), true); - m_uiLe->leLongMonth->setCursorPosition(cursorPos); - m_uiLe->leLongMonth->setSelection(0, 3); - emit dateTimeChanged(); + if (!m_uiLe) + return; + if (!isMonthAcceptable()) + return; + const int ofs = bForward ? 1 : -1; + const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_curTimeMSec, Qt::UTC).addMonths(ofs)); + setMsecsSinceEpoch(dt.toMSecsSinceEpoch(), true); + m_uiLe->leLongMonth->setCursorPosition(cursorPos); + m_uiLe->leLongMonth->setSelection(0, 3); + emit dateTimeChanged(); } void LtsDateTimeEdit::onYearWheelEvent(bool bForward, int cursorPos) { - if (!m_uiLe) - return; - if (!isYearAcceptable()) - return; - const int ofs = bForward ? 1 : -1; - const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_curTimeMSec, Qt::UTC).addYears(ofs)); - setMsecsSinceEpoch(dt.toMSecsSinceEpoch(), true); - m_uiLe->leLongYear->setCursorPosition(cursorPos); - m_uiLe->leLongYear->setSelection(0, 2); - emit dateTimeChanged(); + if (!m_uiLe) + return; + if (!isYearAcceptable()) + return; + const int ofs = bForward ? 1 : -1; + const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_curTimeMSec, Qt::UTC).addYears(ofs)); + setMsecsSinceEpoch(dt.toMSecsSinceEpoch(), true); + m_uiLe->leLongYear->setCursorPosition(cursorPos); + m_uiLe->leLongYear->setSelection(0, 2); + emit dateTimeChanged(); } } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_rc.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_rc.h index b73e5af27..58f76e608 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_rc.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_rc.h @@ -1,17 +1,27 @@ - +/** + * @RDE_HEADER@ + * DTG Edit + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Mike Wille, SLSE, 2016-08-17 + */ #pragma once + +//#include "lts_date_time_edit_touch.h" #include "lts_widgets_export.h" -#include #include #include + namespace Ui { -class LtsDateTimeEditLe; -class LtsDateTimeEdit; -} // namespace Ui +class LtsDateTimeEditLe; // default, based on QLineEdit +class LtsDateTimeEdit; // touch , based on QSpinBox, QComboBox +} class QLineEdit; class QShortcut; @@ -20,223 +30,184 @@ namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsDateTimeEdit : public QWidget { - Q_OBJECT + Q_OBJECT - Q_PROPERTY(bool autoForward READ getAutoForward WRITE setAutoForward) - Q_PROPERTY(bool editTimezone READ getEditTimezone WRITE setEditTimezone) - Q_PROPERTY(bool withButtons READ getWithButtons WRITE setWithButtons) - Q_PROPERTY(bool withSlider READ getWithSlider WRITE setWithSlider) - Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly) - Q_PROPERTY(bool withNowButton READ withNowButton WRITE setWithNowButton) - Q_PROPERTY(bool withCheckBox READ withCheckBox WRITE setWithCheckBox) + Q_PROPERTY(bool autoForward READ getAutoForward WRITE setAutoForward) + Q_PROPERTY(bool editTimezone READ getEditTimezone WRITE setEditTimezone) + Q_PROPERTY(bool withButtons READ getWithButtons WRITE setWithButtons) + Q_PROPERTY(bool withSlider READ getWithSlider WRITE setWithSlider) + Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly) + Q_PROPERTY(bool withNowButton READ withNowButton WRITE setWithNowButton) + Q_PROPERTY(bool withCheckBox READ withCheckBox WRITE setWithCheckBox) - public: - using CurrentTimeCallback = std::function; +public: + // returns the current time in msec + using CurrentTimeCallback = std::function; - explicit LtsDateTimeEdit(QWidget* parent = nullptr, bool withNowButton = true, bool withCheckBox = false); - ~LtsDateTimeEdit(); + explicit LtsDateTimeEdit(QWidget *parent = nullptr, bool withNowButton = true, bool withCheckBox = false); + ~LtsDateTimeEdit(); - bool setupUiTouch(); + bool setupUiTouch(); - qint64 msecsSinceEpoch() const; - bool isEmpty() const; - bool isValidDate() const; - void setAutoForward(const bool af) - { - m_autoForward = af; - } + qint64 msecsSinceEpoch() const; + bool isEmpty() const; + bool isValidDate() const; // should be preferred over isEmpty() - bool getAutoForward() const - { - return m_autoForward; - } + void setAutoForward(const bool af) { m_autoForward = af; } + bool getAutoForward() const { return m_autoForward; } - void setEditTimezone(const bool edit); + void setEditTimezone(const bool edit); + bool getEditTimezone() const { return m_editTimezone; } - bool getEditTimezone() const - { - return m_editTimezone; - } + void setWithButtons(const bool buttons); + bool getWithButtons() const { return m_withButtons; } - void setWithButtons(const bool buttons); + void setWithSlider(const bool slider); + bool getWithSlider() const { return m_withSlider; } - bool getWithButtons() const - { - return m_withButtons; - } + void setReadOnly(const bool readOnly); + bool isReadOnly() const { return m_readOnly; } - void setWithSlider(const bool slider); + void setWithCheckBox(bool checkBoxEnabled); + bool withCheckBox() const { return m_withCheckBox; } + void setCheckBoxChecked(bool bChecked); + bool isCheckBoxChecked() const; - bool getWithSlider() const - { - return m_withSlider; - } + void setWithNowButton(bool nowButton); + bool withNowButton() const { return m_withNowButton; } - void setReadOnly(const bool readOnly); + // Setzt die minimal eingebbare Zeit + void setMinimumTimeMSec(qint64 msec); + qint64 minimumTimeMSec() const { return m_minTimeMSec; } - bool isReadOnly() const - { - return m_readOnly; - } + // Setzt die maximal eingebbare Zeit + void setMaximumTimeMSec(qint64 msec); + qint64 maximumTimeMSec() const { return m_maxTimeMSec; } - void setWithCheckBox(bool checkBoxEnabled); + void setMinMaxTimeMSec(qint64 min, qint64 max) { setMinimumTimeMSec(min); setMaximumTimeMSec(max); } - bool withCheckBox() const - { - return m_withCheckBox; - } + void setRetrieveCurrentTimeCallback(const CurrentTimeCallback &cb); - void setCheckBoxChecked(bool bChecked); - bool isCheckBoxChecked() const; + bool setTimezone(char tz); + char getTimezone() const; + qint64 getTimezoneAsSecs() const; - void setWithNowButton(bool nowButton); + void setSubWidgetsProperties(const QString &name, const QVariant &value); - bool withNowButton() const - { - return m_withNowButton; - } +Q_SIGNALS: + void dateTimeChanged(); - void setMinimumTimeMSec(qint64 msec); +public Q_SLOTS: + bool setMsecsSinceEpoch(qint64 msec, bool setToNearestPossible = true); + void clear(); - qint64 minimumTimeMSec() const - { - return m_minTimeMSec; - } +private: + void clearTimezone(); - void setMaximumTimeMSec(qint64 msec); + void setMinMaxMonth(int minMonth, int maxMonth); - qint64 maximumTimeMSec() const - { - return m_maxTimeMSec; - } + bool setMonth(int month); + int getMonth() const; - void setMinMaxTimeMSec(qint64 min, qint64 max) - { - setMinimumTimeMSec(min); - setMaximumTimeMSec(max); - } + bool setDay(int day); + int getDay() const; - void setRetrieveCurrentTimeCallback(const CurrentTimeCallback& cb); + bool setHHMMSS(int hour, int minute, int second); + int getHour() const; + int getMinute() const; + int getSecond() const; - bool setTimezone(char tz); - char getTimezone() const; - qint64 getTimezoneAsSecs() const; + bool setYear(int year); + int getYear() const; - void setSubWidgetsProperties(const QString& name, const QVariant& value); + bool isEmptyDay() const; + bool isEmptyHHMMSS() const; + bool isEmptyTimezone() const; + bool isEmptyMonth() const; + bool isEmptyYear() const; - Q_SIGNALS: - void dateTimeChanged(); + bool hasFocus() const; - public Q_SLOTS: - bool setMsecsSinceEpoch(qint64 msec, bool setToNearestPossible = true); - void clear(); + bool isDataAcceptable(); - private: - void clearTimezone(); + void showInvalidData(bool setFocus); - void setMinMaxMonth(int minMonth, int maxMonth); + bool isLineEditDataAcceptable(QLineEdit *le) const; - bool setMonth(int month); - int getMonth() const; + bool isDayAcceptable() const; + bool isHHMMSSAcceptable() const; + bool isMonthAcceptable() const; + bool isYearAcceptable() const; + bool isTzAcceptable() const; - bool setDay(int day); - int getDay() const; +private Q_SLOTS: + void setFixedDateTime(); + void setOffsetDateTime(); - bool setHHMMSS(int hour, int minute, int second); - int getHour() const; - int getMinute() const; - int getSecond() const; + void setSliderValue(int val); + void valueDayChanged(const QString &str); + void fixupHHMMSS(); + void valueMonthChanged(const QString &str); + void valueMonthChanged2(const QString &str); + void valueTimezoneChangedStr(const QString &str); + void valueTimezoneChangedInt(int newTimezone); + void valueYearChanged(const QString &str); - bool setYear(int year); - int getYear() const; + void onBackHourClicked(); + void onBackMinuteClicked(); + void onBackSecondClicked(); + void onForwardSecondClicked(); + void onForwardMinuteClicked(); + void onForwardHourClicked(); - bool isEmptyDay() const; - bool isEmptyHHMMSS() const; - bool isEmptyTimezone() const; - bool isEmptyMonth() const; - bool isEmptyYear() const; + void onCheckBoxChanged(); + void disableControls(); + void enableControls(); + void enaDisaControls(bool bEnable); - bool hasFocus() const; + void onFocusOutHHMMSS(); + void onFocusOutTZ(); + void onFocusOutDay(); + void onFocusOutMonth(); + void onFocusOutYear(); - bool isDataAcceptable(); + void onFocusOutBackspace(); + void onFocusOut(); - void showInvalidData(bool setFocus); + void onHmsWheelEvent(bool bForward, int cursorPos); + void onDayWheelEvent(bool bForward, int cursorPos); + void onMonthWheelEvent(bool bForward, int cursorPos); + void onYearWheelEvent(bool bForward, int cursorPos); - bool isLineEditDataAcceptable(QLineEdit* le) const; +private: + Ui::LtsDateTimeEditLe *m_uiLe{nullptr}; + Ui::LtsDateTimeEdit *m_uiTouch{nullptr}; + QShortcut *m_scFixed = nullptr; + QShortcut *m_scOffset = nullptr; - bool isDayAcceptable() const; - bool isHHMMSSAcceptable() const; - bool isMonthAcceptable() const; - bool isYearAcceptable() const; - bool isTzAcceptable() const; + CurrentTimeCallback m_getCurrentTimeCallback = nullptr; - private Q_SLOTS: - void setFixedDateTime(); - void setOffsetDateTime(); + qint64 m_minTimeMSec = 0; + qint64 m_maxTimeMSec = 0; - void setSliderValue(int val); - void valueDayChanged(const QString& str); - void fixupHHMMSS(); - void valueMonthChanged(const QString& str); - void valueMonthChanged2(const QString& str); - void valueTimezoneChangedStr(const QString& str); - void valueTimezoneChangedInt(int newTimezone); - void valueYearChanged(const QString& str); + qint64 m_curTimeMSec = -1; // IMMER UTC - void onBackHourClicked(); - void onBackMinuteClicked(); - void onBackSecondClicked(); - void onForwardSecondClicked(); - void onForwardMinuteClicked(); - void onForwardHourClicked(); + bool m_editTimezone = true; + bool m_autoForward = true; + bool m_withButtons = false; + bool m_withSlider = false; + bool m_readOnly = false; + bool m_withCheckBox = false; + bool m_withNowButton = false; - void onCheckBoxChanged(); - void disableControls(); - void enableControls(); - void enaDisaControls(bool bEnable); + int m_minMonth{0}; + int m_maxMonth{0}; - void onFocusOutHHMMSS(); - void onFocusOutTZ(); - void onFocusOutDay(); - void onFocusOutMonth(); - void onFocusOutYear(); - void onFocusOutBackspace(); - void onFocusOut(); - - void onHmsWheelEvent(bool bForward, int cursorPos); - void onDayWheelEvent(bool bForward, int cursorPos); - void onMonthWheelEvent(bool bForward, int cursorPos); - void onYearWheelEvent(bool bForward, int cursorPos); - - private: - Ui::LtsDateTimeEditLe* m_uiLe{nullptr}; - Ui::LtsDateTimeEdit* m_uiTouch{nullptr}; - QShortcut* m_scFixed = nullptr; - QShortcut* m_scOffset = nullptr; - - CurrentTimeCallback m_getCurrentTimeCallback = nullptr; - - qint64 m_minTimeMSec = 0; - qint64 m_maxTimeMSec = 0; - - qint64 m_curTimeMSec = -1; - - bool m_editTimezone = true; - bool m_autoForward = true; - bool m_withButtons = false; - bool m_withSlider = false; - bool m_readOnly = false; - bool m_withCheckBox = false; - bool m_withNowButton = false; - - int m_minMonth{0}; - int m_maxMonth{0}; - - bool m_backspacePressed = false; - bool m_recursionAvoid = false; - bool m_dateIsAcceptable = false; + bool m_backspacePressed = false; + bool m_recursionAvoid = false; + bool m_dateIsAcceptable = false; }; } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_touch.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_touch.cpp index a0898de6d..3ad49a890 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_touch.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_touch.cpp @@ -1,364 +1,396 @@ - +/** + * @RDE_HEADER@ + * Edit which contains some widgets to edit each: Date + Timezone + Time + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Patric Karwat, NLE, 2019-06-27 + */ #include "lts_date_time_edit_touch.h" - #include "ui_lts_date_time_edit_touch.h" +#include #include #include #include -#include namespace LtsWidgets { -LtsDateTimeEdit::LtsDateTimeEdit(QWidget* parent, bool withNowButton, bool withCheckBox) - : QWidget(parent), m_withCheckBox(withCheckBox), m_withNowButton(withNowButton), m_tzOffset(0), m_minMonth(1), - m_maxMonth(12), m_scFixed(new QShortcut(QKeySequence(Qt::ShiftModifier + Qt::Key_F2), this, - SLOT(onSetFixedDateTime()), nullptr, Qt::WidgetWithChildrenShortcut)), - m_scOffset(new QShortcut(QKeySequence(Qt::Key_F2), this, SLOT(onSetOffsetDateTime()), nullptr, - Qt::WidgetWithChildrenShortcut)), - m_getCurrentTimeCallback(nullptr), m_ui(new Ui::LtsDateTimeEdit) +LtsDateTimeEdit::LtsDateTimeEdit(QWidget *parent, bool withNowButton, bool withCheckBox) + : QWidget(parent) + , m_withCheckBox(withCheckBox) + , m_withNowButton(withNowButton) + , m_tzOffset(0) + , m_minMonth(1) + , m_maxMonth(12) + , m_scFixed(new QShortcut(QKeySequence(Qt::ShiftModifier + Qt::Key_F2), this, SLOT(onSetFixedDateTime()), nullptr, Qt::WidgetWithChildrenShortcut)) + , m_scOffset(new QShortcut(QKeySequence(Qt::Key_F2), this, SLOT(onSetOffsetDateTime()), nullptr, Qt::WidgetWithChildrenShortcut)) + , m_getCurrentTimeCallback(nullptr) + , m_ui(new Ui::LtsDateTimeEdit) { - m_ui->setupUi(this); - setFocusPolicy(Qt::StrongFocus); + m_ui->setupUi(this); + setFocusPolicy(Qt::StrongFocus); - for (int i = 65; i < 91; i++) - { - if (QChar(i).toUpper() == QChar::fromLatin1('I')) - continue; - m_ui->cbxTimeZone->addItem(QChar(i), QChar(i)); - } - connect(m_ui->pbNow, &QPushButton::clicked, this, &LtsDateTimeEdit::onSetOffsetDateTime); - connect(m_ui->cbxMonth, static_cast(&QComboBox::currentIndexChanged), this, - &LtsDateTimeEdit::onDateTimeChanged); - connect(m_ui->spDay, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::onDateTimeChanged); - connect(m_ui->spHour, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::onDateTimeChanged); - connect(m_ui->spMinutes, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::onDateTimeChanged); - connect(m_ui->spSeconds, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::onDateTimeChanged); - connect(m_ui->spYear, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::onDateTimeChanged); + for (int i = 65; i < 91; i++ ) + { + if (QChar(i).toUpper() == QChar::fromLatin1('I')) + continue; + m_ui->cbxTimeZone->addItem(QChar(i), QChar(i)); - connect(m_ui->checkBox, &QCheckBox::toggled, this, &LtsDateTimeEdit::onCheckBoxChanged); - connect(m_ui->cbxTimeZone, static_cast(&QComboBox::currentIndexChanged), this, - &LtsDateTimeEdit::onTimeZoneChanged); + } - connect(m_ui->cbxMonth, static_cast(&QComboBox::currentIndexChanged), this, - &LtsDateTimeEdit::onMonthChanged); + connect(m_ui->pbNow, &QPushButton::clicked, + this, &LtsDateTimeEdit::onSetOffsetDateTime); + connect(m_ui->cbxMonth, static_cast(&QComboBox::currentIndexChanged), + this, &LtsDateTimeEdit::onDateTimeChanged); + connect(m_ui->spDay, &QSpinBox::editingFinished, + this, &LtsDateTimeEdit::onDateTimeChanged); + connect(m_ui->spHour, &QSpinBox::editingFinished, + this, &LtsDateTimeEdit::onDateTimeChanged); + connect(m_ui->spMinutes, &QSpinBox::editingFinished, + this, &LtsDateTimeEdit::onDateTimeChanged); + connect(m_ui->spSeconds, &QSpinBox::editingFinished, + this, &LtsDateTimeEdit::onDateTimeChanged); + connect(m_ui->spYear, &QSpinBox::editingFinished, + this, &LtsDateTimeEdit::onDateTimeChanged); - m_tzOffset = DTG::timezone2Secs(QLatin1Char(DTG::timezone()).toLatin1()); + connect(m_ui->checkBox, &QCheckBox::toggled, + this, &LtsDateTimeEdit::onCheckBoxChanged); + connect(m_ui->cbxTimeZone, static_cast(&QComboBox::currentIndexChanged), + this, &LtsDateTimeEdit::onTimeZoneChanged); - m_ui->cbxTimeZone->setCurrentIndex(m_ui->cbxTimeZone->findText(QString(QLatin1Char(DTG::timezone())))); - onTimeZoneChanged(); - setMinMaxMonth(1, 12); + connect(m_ui->cbxMonth, static_cast(&QComboBox::currentIndexChanged), + this, &LtsDateTimeEdit::onMonthChanged); - int offset = LtsUtils::OperatorSettings::getInstance() - ->value(QStringLiteral("TimeSettings"), QStringLiteral("Offset"), 0) - .toLongLong() / - 1000; - m_ui->pbNow->setToolTip(tr("Set to current time plus %n second(s) offset", "", offset)); + m_tzOffset = DTG::timezone2Secs(QLatin1Char(DTG::timezone()).toLatin1()); - updateDateTimeType(); + + m_ui->cbxTimeZone->setCurrentIndex(m_ui->cbxTimeZone->findText(QString(QLatin1Char(DTG::timezone())))); + onTimeZoneChanged(); + setMinMaxMonth(1,12); - m_ui->checkBox->setVisible(m_withCheckBox); - m_ui->pbNow->setVisible(m_withNowButton); + //m_ui->pbNow->setMaximumHeight(m_ui->dteLeft->height()); + int offset = LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("TimeSettings"), QStringLiteral("Offset"), 0).toLongLong()/1000; + m_ui->pbNow->setToolTip(tr("Set to current time plus %n second(s) offset", "", offset)); + + updateDateTimeType(); + + m_ui->checkBox->setVisible(m_withCheckBox); + m_ui->pbNow->setVisible(m_withNowButton); } LtsDateTimeEdit::~LtsDateTimeEdit() { - delete m_ui; + delete m_ui; } void LtsDateTimeEdit::updateDateTimeType() { - switch (DTG::dateTimeType()) - { - case DTG::DateTimeType::DTG: - break; - case DTG::DateTimeType::DDMMYYYY_HHMMSS_Z: - break; - case DTG::DateTimeType::DDMMYYYY_Z_HHMMSS: - break; - default: - break; - } + switch (DTG::dateTimeType()) + { + case DTG::DateTimeType::DTG: + break; + case DTG::DateTimeType::DDMMYYYY_HHMMSS_Z: + break; + case DTG::DateTimeType::DDMMYYYY_Z_HHMMSS: + break; + default: + break; + } } bool LtsDateTimeEdit::setTimezone(char tz) { - QChar tzLocal = QChar(QLatin1Char(tz)).toUpper(); - if (tzLocal.toLatin1() == 'J') - tzLocal = QLatin1Char('Z'); - m_ui->cbxTimeZone->setCurrentIndex(m_ui->cbxTimeZone->findData(tzLocal)); - int offset = DTG::timezone2Secs(tzLocal.toLatin1()); - if (offset != m_tzOffset) - { - const auto ms = msecsSinceEpoch(); - m_tzOffset = offset; - setMsecsSinceEpoch(ms + m_tzOffset); - } - return true; + QChar tzLocal = QChar(QLatin1Char(tz)).toUpper(); + if (tzLocal.toLatin1() == 'J') + tzLocal = QLatin1Char('Z'); + m_ui->cbxTimeZone->setCurrentIndex(m_ui->cbxTimeZone->findData(tzLocal)); + int offset = DTG::timezone2Secs(tzLocal.toLatin1()); + if (offset != m_tzOffset) + { + const auto ms = msecsSinceEpoch(); + m_tzOffset = offset; + setMsecsSinceEpoch(ms+m_tzOffset); + } + return true; } char LtsDateTimeEdit::getTimezone() const { - QChar tz = m_ui->cbxTimeZone->currentText().at(0).toUpper(); + QChar tz = m_ui->cbxTimeZone->currentText().at(0).toUpper(); +// if (tz.isLower()) +// tz = tz.toUpper(); + if (tz.toLatin1() == 'J') + tz = QLatin1Char('Z'); - if (tz.toLatin1() == 'J') - tz = QLatin1Char('Z'); - - if (tz.isNull()) - return DTG::timezone(); - return tz.toLatin1(); + if (tz.isNull()) + return DTG::timezone(); + return tz.toLatin1(); } -void LtsDateTimeEdit::setMinMaxMonth(int minMonth, int maxMonth) + +void LtsDateTimeEdit::setMinMaxMonth(int minMonth, int maxMonth ) { - if (m_minMonth != minMonth) - m_minMonth = minMonth; - if (m_maxMonth != maxMonth) - m_maxMonth = maxMonth; + if (m_minMonth != minMonth) + m_minMonth = minMonth; + if (m_maxMonth != maxMonth) + m_maxMonth = maxMonth; - int currentMonth = m_ui->cbxMonth->currentData().toInt(); - m_ui->cbxMonth->blockSignals(true); - m_ui->cbxMonth->clear(); - for (int i = 1; i <= 12; i++) - { - if (i < m_minMonth) - continue; - if (i > m_maxMonth) - break; - QDate date(1777, i, 1); - m_ui->cbxMonth->addItem(date.toString(QStringLiteral("MMM")), i); - } - m_ui->cbxMonth->setCurrentIndex(m_ui->cbxMonth->findData(currentMonth)); - m_ui->cbxMonth->blockSignals(false); + int currentMonth = m_ui->cbxMonth->currentData().toInt(); + m_ui->cbxMonth->blockSignals(true); + m_ui->cbxMonth->clear(); + for (int i =1; i<= 12 ; i++) + { + if (i < m_minMonth) + continue; + if (i > m_maxMonth) + break; + QDate date(1777,i,1); + m_ui->cbxMonth->addItem(date.toString(QStringLiteral("MMM")),i); + + } + m_ui->cbxMonth->setCurrentIndex(m_ui->cbxMonth->findData(currentMonth)); + m_ui->cbxMonth->blockSignals(false); } -void LtsDateTimeEdit::setDateTime(const QDateTime& datetime) + +void LtsDateTimeEdit::setDateTime(const QDateTime &datetime) { - if (!datetime.isValid() && m_withCheckBox) - { - m_ui->checkBox->setChecked(false); - return; - } + if (!datetime.isValid() && m_withCheckBox) + { + m_ui->checkBox->setChecked(false); + return; + } - QDateTime dt = datetime.toUTC().addSecs(m_tzOffset); - dt.setOffsetFromUtc(m_tzOffset); + QDateTime dt = datetime.toUTC().addSecs(m_tzOffset); + dt.setOffsetFromUtc(m_tzOffset); - QDateTime oldDateTime = dateTime(); - if (dt == oldDateTime) - return; + //QDateTime oldDateTime = m_dateTime; // Keep to emit signal only when actually changed! (i.e. non-active or out of bounds) + QDateTime oldDateTime = dateTime(); + if (dt == oldDateTime) + return; - blockSignals(true); + blockSignals(true); // don't emit dateTimeChanged() twice! - m_ui->spDay->setValue(dt.date().day()); - m_ui->cbxMonth->setCurrentIndex(m_ui->cbxMonth->findData(dt.date().month())); + m_ui->spDay->setValue(dt.date().day()); //day + m_ui->cbxMonth->setCurrentIndex(m_ui->cbxMonth->findData(dt.date().month())); //month + // year + //if (m_ui->spYear->maximum() > 1000) + // m_ui->spYear->setValue(dt.date().year()); + //else + m_ui->spYear->setValue(dt.date().year()-2000); - m_ui->spYear->setValue(dt.date().year() - 2000); + m_ui->spHour->setValue(dt.time().hour()); + m_ui->spMinutes->setValue(dt.time().minute()); + m_ui->spSeconds->setValue(dt.time().second()); - m_ui->spHour->setValue(dt.time().hour()); - m_ui->spMinutes->setValue(dt.time().minute()); - m_ui->spSeconds->setValue(dt.time().second()); + blockSignals(false); - blockSignals(false); - - const QDateTime dtNew = dateTime(); - if (dtNew != oldDateTime) - emit dateTimeChanged(); + const QDateTime dtNew = dateTime(); + if (dtNew != oldDateTime) + emit dateTimeChanged(); } + void LtsDateTimeEdit::onDateTimeChanged() { - emit dateTimeChanged(); + emit dateTimeChanged(); - QDateTime dateTime; - dateTime = dateTime.addYears(m_ui->spYear->value()); - dateTime = dateTime.addMonths(m_ui->cbxMonth->currentData().toInt()); - dateTime = dateTime.addDays(m_ui->spDay->value()); - dateTime = - dateTime.addSecs(m_ui->spHour->value() * 60 * 60 + m_ui->spMinutes->value() * 60 + m_ui->spSeconds->value()); - if (dateTime.isValid()) - { - m_dateTime = dateTime; - } + QDateTime dateTime; + dateTime = dateTime.addYears(m_ui->spYear->value()); + dateTime = dateTime.addMonths(m_ui->cbxMonth->currentData().toInt()); + dateTime = dateTime.addDays(m_ui->spDay->value()); + dateTime = dateTime.addSecs(m_ui->spHour->value()*60*60 + m_ui->spMinutes->value()*60 + m_ui->spSeconds->value()); + if (dateTime.isValid()) + { + m_dateTime = dateTime; + // emit dateTimeChanged(m_dateTime); + } } void LtsDateTimeEdit::onTimeZoneChanged() { - if (m_ui->cbxMonth->currentText().isEmpty()) - { - return; - } - QChar tz = m_ui->cbxTimeZone->currentText().at(0); - if (tz.isLower()) - tz = tz.toUpper(); - if (tz.toLatin1() == 'J') - tz = QLatin1Char('Z'); - m_ui->cbxTimeZone->setCurrentIndex(m_ui->cbxTimeZone->findData(tz)); - int offset = DTG::timezone2Secs(tz.toLatin1()); - if (offset != m_tzOffset) - { - const auto ms = msecsSinceEpoch(); - m_tzOffset = offset; - setMsecsSinceEpoch(ms + m_tzOffset); - } + if (m_ui->cbxMonth->currentText().isEmpty()) + { + return; + } + QChar tz = m_ui->cbxTimeZone->currentText().at(0); + if (tz.isLower()) + tz = tz.toUpper(); + if (tz.toLatin1() == 'J') + tz = QLatin1Char('Z'); + m_ui->cbxTimeZone->setCurrentIndex(m_ui->cbxTimeZone->findData(tz)); + int offset = DTG::timezone2Secs(tz.toLatin1()); + if (offset != m_tzOffset) + { + const auto ms = msecsSinceEpoch(); + m_tzOffset = offset; + setMsecsSinceEpoch(ms+m_tzOffset); + } } void LtsDateTimeEdit::onMonthChanged(int month) { - - Q_UNUSED(month); + // TODO + Q_UNUSED(month); } void LtsDateTimeEdit::setWithCheckBox(bool checkBoxEnabled) { - if (m_withCheckBox == checkBoxEnabled) - return; + if (m_withCheckBox == checkBoxEnabled) + return; - m_withCheckBox = checkBoxEnabled; - m_ui->checkBox->setVisible(m_withCheckBox); - if (!m_withCheckBox) - m_ui->checkBox->setChecked(true); - emit withCheckBoxChanged(m_withCheckBox); + m_withCheckBox = checkBoxEnabled; + m_ui->checkBox->setVisible(m_withCheckBox); + if (!m_withCheckBox) // If no checkBox -> set other Elements enabled + m_ui->checkBox->setChecked(true); + emit withCheckBoxChanged(m_withCheckBox); } bool LtsDateTimeEdit::isCheckBoxChecked() const { - return m_ui->checkBox->isChecked(); + return m_ui->checkBox->isChecked(); } void LtsDateTimeEdit::setWithNowButton(bool nowButton) { - if (m_withNowButton == nowButton) - return; + if (m_withNowButton == nowButton) + return; - m_withNowButton = nowButton; - m_ui->pbNow->setVisible(m_withNowButton); - emit withNowButtonChanged(m_withNowButton); + m_withNowButton = nowButton; + m_ui->pbNow->setVisible(m_withNowButton); + emit withNowButtonChanged(m_withNowButton); } void LtsDateTimeEdit::onCheckBoxChanged(bool checked) { - m_ui->spDay->setEnabled(checked); - m_ui->spHour->setEnabled(checked); - m_ui->spMinutes->setEnabled(checked); - m_ui->spSeconds->setEnabled(checked); - m_ui->spYear->setEnabled(checked); - m_ui->cbxMonth->setEnabled(checked); - m_ui->cbxTimeZone->setEnabled(checked); - m_ui->pbNow->setEnabled(checked); - emit dateTimeChanged(); + m_ui->spDay->setEnabled(checked); + m_ui->spHour->setEnabled(checked); + m_ui->spMinutes->setEnabled(checked); + m_ui->spSeconds->setEnabled(checked); + m_ui->spYear->setEnabled(checked); + m_ui->cbxMonth->setEnabled(checked); + m_ui->cbxTimeZone->setEnabled(checked); + m_ui->pbNow->setEnabled(checked); + emit dateTimeChanged(); } void LtsDateTimeEdit::setMsecsSinceEpoch(qint64 mSecsSinceEpoch) { - if (mSecsSinceEpoch == 0 && m_withCheckBox) - { - m_ui->checkBox->setChecked(false); - return; - } - m_ui->checkBox->setChecked(true); - setDateTime(QDateTime::fromMSecsSinceEpoch(mSecsSinceEpoch).toUTC()); + if (mSecsSinceEpoch == 0 && m_withCheckBox) + { + m_ui->checkBox->setChecked(false); + return; + } + m_ui->checkBox->setChecked(true); + setDateTime(QDateTime::fromMSecsSinceEpoch(mSecsSinceEpoch).toUTC()); } qint64 LtsDateTimeEdit::msecsSinceEpoch() const { - const QDateTime dt(dateTime()); - if (dt.isNull()) - return 0; - return dt.toMSecsSinceEpoch(); + const QDateTime dt(dateTime()); + if (dt.isNull()) + return 0; + return dt.toMSecsSinceEpoch(); } void LtsDateTimeEdit::clear() { - m_ui->spDay->clear(); - m_ui->spHour->clear(); - m_ui->spMinutes->clear(); - m_ui->spSeconds->clear(); - m_ui->spYear->clear(); - emit dateTimeChanged(); + m_ui->spDay->clear(); + m_ui->spHour->clear(); + m_ui->spMinutes->clear(); + m_ui->spSeconds->clear(); + m_ui->spYear->clear(); + emit dateTimeChanged(); } void LtsDateTimeEdit::setCheckBoxChecked(bool bChecked) { - m_ui->checkBox->setChecked(bChecked); + m_ui->checkBox->setChecked(bChecked); } QDateTime LtsDateTimeEdit::dateTime() const { - if (!m_ui->checkBox->isChecked()) - return QDateTime(); + if (!m_ui->checkBox->isChecked()) + return QDateTime(); - QDateTime final; - int year = 0; - if (m_ui->spYear->value() < 1000) - { - year = m_ui->spYear->value() + 2000; - } - else - { - year = m_ui->spYear->value(); - } - QDate date(year, m_ui->cbxMonth->currentData().toInt(), m_ui->spDay->value()); - final.setDate(date); - final = final.addSecs(m_ui->spHour->value() * 60 * 60 + m_ui->spMinutes->value() * 60 + m_ui->spSeconds->value()); + QDateTime final; + int year = 0; + if (m_ui->spYear->value() < 1000) + { + year=m_ui->spYear->value()+2000; + } + else + { + year=m_ui->spYear->value(); + } + QDate date(year,m_ui->cbxMonth->currentData().toInt(), m_ui->spDay->value()); + final.setDate(date); + final = final.addSecs(m_ui->spHour->value()*60*60 + m_ui->spMinutes->value()*60 + m_ui->spSeconds->value()); - if (!final.isValid()) - return QDateTime(); + if (!final.isValid()) + return QDateTime(); - return QDateTime(final.date(), final.time(), Qt::OffsetFromUTC, m_tzOffset).toUTC(); + // Todo: Enhance? + return QDateTime(final.date(), final.time(), Qt::OffsetFromUTC, m_tzOffset).toUTC(); } void LtsDateTimeEdit::setMaximumTimeMSec(qint64 msec) { - const auto maximumDate(QDateTime::fromMSecsSinceEpoch(msec).date()); - m_ui->spYear->setMaximum(maximumDate.year() - 2000); + const auto maximumDate(QDateTime::fromMSecsSinceEpoch(msec).date()); + m_ui->spYear->setMaximum(maximumDate.year()-2000); + + //m_ui->spDay->setMaximum(maximumDate.day()); + // setMinMaxMonth(maximumDate.month(), m_maxMonth); + } qint64 LtsDateTimeEdit::minimumTimeMSec() const { - QDate date; - date.setDate(m_ui->spYear->minimum(), m_maxMonth, m_ui->spMinutes->minimum()); - return QDateTime(date).toMSecsSinceEpoch(); + QDate date; + date.setDate(m_ui->spYear->minimum(), m_maxMonth, m_ui->spMinutes->minimum() ); + return QDateTime(date).toMSecsSinceEpoch(); } void LtsDateTimeEdit::setMinimumTimeMSec(qint64 msec) { - const auto minimumDate(QDateTime::fromMSecsSinceEpoch(msec).date()); - - m_ui->spYear->setMinimum(minimumDate.year() - 2000); + const auto minimumDate(QDateTime::fromMSecsSinceEpoch(msec).date()); + //setMinMaxMonth(minimumDate.month(), m_maxMonth); + m_ui->spYear->setMinimum(minimumDate.year()-2000); + //m_ui->spDay->setMinimum(minimumDate.day()); } -void LtsDateTimeEdit::setRetrieveCurrentTimeCallback(const CurrentTimeCallback& cb) +void LtsDateTimeEdit::setRetrieveCurrentTimeCallback(const CurrentTimeCallback &cb) { - m_getCurrentTimeCallback = cb; + m_getCurrentTimeCallback = cb; } void LtsDateTimeEdit::onSetFixedDateTime() { - setMsecsSinceEpoch(LtsUtils::OperatorSettings::getInstance() - ->value(QStringLiteral("TimeSettings"), QStringLiteral("FixedTime"), 0) - .toLongLong()); + setMsecsSinceEpoch(LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("TimeSettings"), QStringLiteral("FixedTime"), 0).toLongLong()); } void LtsDateTimeEdit::onSetOffsetDateTime() { - if (!m_getCurrentTimeCallback) - return; - qint64 offset = LtsUtils::OperatorSettings::getInstance() - ->value(QStringLiteral("TimeSettings"), QStringLiteral("Offset"), 0) - .toLongLong(); - - setMsecsSinceEpoch((m_getCurrentTimeCallback() / 1000) * 1000 + offset); + if (!m_getCurrentTimeCallback) + return; + qint64 offset = LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("TimeSettings"), QStringLiteral("Offset"), 0).toLongLong(); + // we only show seconds, so strip away milliseconds + setMsecsSinceEpoch((m_getCurrentTimeCallback() / 1000) * 1000 + offset); } + void LtsDateTimeEdit::setSubWidgetsProperties(QString name, QVariant value) { - m_ui->spDay->setProperty(name.toStdString().c_str(), value); - m_ui->spHour->setProperty(name.toStdString().c_str(), value); - m_ui->spMinutes->setProperty(name.toStdString().c_str(), value); - m_ui->spSeconds->setProperty(name.toStdString().c_str(), value); - m_ui->spYear->setProperty(name.toStdString().c_str(), value); + m_ui->spDay->setProperty(name.toStdString().c_str(), value); + m_ui->spHour->setProperty(name.toStdString().c_str(), value); + m_ui->spMinutes->setProperty(name.toStdString().c_str(), value); + m_ui->spSeconds->setProperty(name.toStdString().c_str(), value); + m_ui->spYear->setProperty(name.toStdString().c_str(), value); + } -} // namespace LtsWidgets +} //namespace diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_touch.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_touch.h index 8d3fe8786..333b8b7fb 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_touch.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_touch.h @@ -1,10 +1,18 @@ - +/** + * @RDE_HEADER@ + * Edit which contains some widgets to edit each: Date + Timezone + Time + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Patric Karwat, NLE, 2019-06-27 + */ #pragma once + #include "lts_widgets_export.h" #include -#include #include #include @@ -21,170 +29,119 @@ namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsDateTimeEdit : public QWidget { - Q_OBJECT + Q_OBJECT - Q_PROPERTY(bool autoForward READ getAutoForward WRITE setAutoForward) - Q_PROPERTY(bool editTimezone READ getEditTimezone WRITE setEditTimezone) - Q_PROPERTY(bool withButtons READ getWithButtons WRITE setWithButtons) - Q_PROPERTY(bool withSlider READ getWithSlider WRITE setWithSlider) - Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly) - Q_PROPERTY(bool withNowButton READ withNowButton WRITE setWithNowButton) - Q_PROPERTY(bool withCheckBox READ withCheckBox WRITE setWithCheckBox) + Q_PROPERTY(bool autoForward READ getAutoForward WRITE setAutoForward) + Q_PROPERTY(bool editTimezone READ getEditTimezone WRITE setEditTimezone) + Q_PROPERTY(bool withButtons READ getWithButtons WRITE setWithButtons) + Q_PROPERTY(bool withSlider READ getWithSlider WRITE setWithSlider) + Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly) + Q_PROPERTY(bool withNowButton READ withNowButton WRITE setWithNowButton) + Q_PROPERTY(bool withCheckBox READ withCheckBox WRITE setWithCheckBox) - public: - using CurrentTimeCallback = std::function; - explicit LtsDateTimeEdit(QWidget* parent = nullptr, bool withNowButton = true, bool withCheckBox = false); - ~LtsDateTimeEdit(); +public: + using CurrentTimeCallback = std::function; + explicit LtsDateTimeEdit(QWidget *parent = nullptr, bool withNowButton = true, bool withCheckBox = false); + ~LtsDateTimeEdit(); - qint64 msecsSinceEpoch() const; + qint64 msecsSinceEpoch() const; + bool isEmpty() const { return msecsSinceEpoch() == 0; } - bool isEmpty() const - { - return msecsSinceEpoch() == 0; - } + void setAutoForward(const bool af) { m_autoForward = af; } + bool getAutoForward() const { return m_autoForward; } - void setAutoForward(const bool af) - { - m_autoForward = af; - } + void setEditTimezone(const bool edit) { m_editTimezone = edit; } + bool getEditTimezone() const { return m_editTimezone; } - bool getAutoForward() const - { - return m_autoForward; - } + void setWithButtons(const bool buttons) { m_withButtons = buttons; } + bool getWithButtons() const { return m_withButtons; } - void setEditTimezone(const bool edit) - { - m_editTimezone = edit; - } + void setWithSlider(const bool slider) { m_withSlider = slider; } + bool getWithSlider() const { return m_withSlider; } - bool getEditTimezone() const - { - return m_editTimezone; - } + void setReadOnly(const bool readOnly) { m_readOnly = readOnly; } + bool isReadOnly() const { return m_readOnly; } - void setWithButtons(const bool buttons) - { - m_withButtons = buttons; - } + bool withCheckBox() const { return m_withCheckBox; } + void setCheckBoxChecked(bool bChecked); + bool isCheckBoxChecked() const; - bool getWithButtons() const - { - return m_withButtons; - } + bool withNowButton() const { return m_withNowButton; } + void setDateTime(const QDateTime &datetime); - void setWithSlider(const bool slider) - { - m_withSlider = slider; - } + // Setzt die minimal eingebbare Zeit + void setMinimumTimeMSec(qint64 msec); + qint64 minimumTimeMSec() const; - bool getWithSlider() const - { - return m_withSlider; - } + // Setzt die maximal eingebbare Zeit + void setMaximumTimeMSec(qint64 msec); + qint64 maximumTimeMSec() const { return m_maxTimeMSec; }; - void setReadOnly(const bool readOnly) - { - m_readOnly = readOnly; - } + void setMinMaxTimeMSec(qint64 min, qint64 max) { setMinimumTimeMSec(min); setMaximumTimeMSec(max); } - bool isReadOnly() const - { - return m_readOnly; - } + void setRetrieveCurrentTimeCallback(const CurrentTimeCallback &cb); + void updateDateTimeType(); - bool withCheckBox() const - { - return m_withCheckBox; - } + bool setTimezone(char tz); + char getTimezone() const; - void setCheckBoxChecked(bool bChecked); - bool isCheckBoxChecked() const; - bool withNowButton() const - { - return m_withNowButton; - } + void setSubWidgetsProperties(QString name, QVariant value); - void setDateTime(const QDateTime& datetime); + bool isValidDate() const + { + //Face validator for touch. + return m_dateTime.isValid(); + } - void setMinimumTimeMSec(qint64 msec); - qint64 minimumTimeMSec() const; +private: + QDateTime dateTime() const; + void setMinMaxMonth(int minMonth, int maxMonth); - void setMaximumTimeMSec(qint64 msec); +public slots: + void setWithCheckBox(bool checkBoxEnabled); + void setWithNowButton(bool nowButton); + void setMsecsSinceEpoch(qint64 mSecsSinceEpoch); + void clear(); - qint64 maximumTimeMSec() const - { - return m_maxTimeMSec; - }; + void onSetFixedDateTime(); + void onSetOffsetDateTime(); - void setMinMaxTimeMSec(qint64 min, qint64 max) - { - setMinimumTimeMSec(min); - setMaximumTimeMSec(max); - } +public slots: + void onDateTimeChanged(); - void setRetrieveCurrentTimeCallback(const CurrentTimeCallback& cb); - void updateDateTimeType(); +signals: + void dateTimeChanged(); + void withCheckBoxChanged(bool checkBoxEnabled); + void withNowButtonChanged(bool nowButton); - bool setTimezone(char tz); - char getTimezone() const; +private slots: + void onCheckBoxChanged(bool checked); + void onTimeZoneChanged(); + void onMonthChanged(int month); - void setSubWidgetsProperties(QString name, QVariant value); +private: - bool isValidDate() const - { + qint64 m_minTimeMSec = 0; + qint64 m_maxTimeMSec = 0; + qint64 m_curTimeMSec = -1; - return m_dateTime.isValid(); - } + bool m_editTimezone = true; + bool m_autoForward = true; + bool m_withButtons = false; + bool m_withSlider = false; + bool m_readOnly = false; + bool m_withCheckBox = false; + bool m_withNowButton = false; - private: - QDateTime dateTime() const; - void setMinMaxMonth(int minMonth, int maxMonth); - - public slots: - void setWithCheckBox(bool checkBoxEnabled); - void setWithNowButton(bool nowButton); - void setMsecsSinceEpoch(qint64 mSecsSinceEpoch); - void clear(); - - void onSetFixedDateTime(); - void onSetOffsetDateTime(); - - public slots: - void onDateTimeChanged(); - - signals: - void dateTimeChanged(); - void withCheckBoxChanged(bool checkBoxEnabled); - void withNowButtonChanged(bool nowButton); - - private slots: - void onCheckBoxChanged(bool checked); - void onTimeZoneChanged(); - void onMonthChanged(int month); - - private: - qint64 m_minTimeMSec = 0; - qint64 m_maxTimeMSec = 0; - qint64 m_curTimeMSec = -1; - - bool m_editTimezone = true; - bool m_autoForward = true; - bool m_withButtons = false; - bool m_withSlider = false; - bool m_readOnly = false; - bool m_withCheckBox = false; - bool m_withNowButton = false; - - int m_tzOffset; - int m_minMonth; - int m_maxMonth; - QShortcut* m_scFixed; - QShortcut* m_scOffset; - QDateTime m_dateTime; - CurrentTimeCallback m_getCurrentTimeCallback; - Ui::LtsDateTimeEdit* m_ui; + int m_tzOffset; // in secs + int m_minMonth; + int m_maxMonth; + QShortcut *m_scFixed; + QShortcut *m_scOffset; + QDateTime m_dateTime; + CurrentTimeCallback m_getCurrentTimeCallback; + Ui::LtsDateTimeEdit *m_ui; }; -} // namespace LtsWidgets +} //namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog.cpp index 9d1125a38..4e771fcc7 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog.cpp @@ -1,699 +1,819 @@ - +/** +* @RDE_HEADER@ +* Dialog for the new Layout system +* $Id$ +* $HeadURL$ +* $Author$ +*/ #include "lts_dialog.h" - +#include "lts_progress_dialog_helper.h" +#include "lts_message_dialog.h" +#include "lts_dialog_helper.h" +#include "lts_dialog_button_box.h" #include "lts_base_layout_widget.h" #include "lts_date_time_edit.h" -#include "lts_dialog_button_box.h" -#include "lts_dialog_helper.h" -#include "lts_message_dialog.h" -#include "lts_progress_dialog_helper.h" -#include -#include -#include -#include -#include -#include #include -#include -#include -#include -#include -#include -#include -#include -#include #include -#include -#include -#include -#include +#include +#include +#include #include -#include -#include +#include +#include +#include #include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +//#include +#include +#include +#include +#include + +#include + namespace LtsWidgets { int LtsDialog::s_object_count = 0; + class OverlayContainer : public QWidget { - Q_OBJECT - public: - OverlayContainer(QWidget* parent); + Q_OBJECT +public: + OverlayContainer(QWidget *parent); - protected: - void paintEvent(QPaintEvent* e) override; +protected: + void paintEvent(QPaintEvent *e) override; }; -OverlayContainer::OverlayContainer(QWidget* parent) : QWidget(parent) + +OverlayContainer::OverlayContainer(QWidget *parent) + : QWidget(parent) { - setAttribute(Qt::WA_TranslucentBackground); + setAttribute(Qt::WA_TranslucentBackground); } -void OverlayContainer::paintEvent(QPaintEvent* e) + +void OverlayContainer::paintEvent(QPaintEvent *e) { - QPainter p(this); - p.fillRect(rect(), {80, 80, 80, 200}); - QWidget::paintEvent(e); + QPainter p(this); + p.fillRect(rect(), { 80, 80, 80, 200 }); + QWidget::paintEvent(e); } -LtsDialog::LtsDialog(QWidget* parent, ButtonCombination buttonCombination, bool closeable) - : QWidget(), m_changesMade(false), m_firstShow(true), m_baseLayoutWidget(nullptr), m_isClosable(closeable), - m_noLockTopic(false), m_unchangeableDialog(false), m_dialogHelper(new LtsDialogHelper(nullptr)), m_topicInfo(), - m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("LtsWidget.LtsDialog")), m_buttonBox(nullptr), - m_uiRequirements(new UiRequirementList()) + + +// LtsDialog +LtsDialog::LtsDialog(QWidget *parent, ButtonCombination buttonCombination, bool closeable) + : QWidget(/*parent*/) + , m_changesMade(false) + , m_firstShow(true) + , m_baseLayoutWidget(nullptr) + , m_isClosable(closeable) + , m_noLockTopic(false) + , m_unchangeableDialog(false) + , m_dialogHelper(new LtsDialogHelper(nullptr)) // has no parent, but LtsTabWidget sets it to itself + //, m_progressDialogHelper(new LtsProgressDialogHelper(this)) + + // protected + , m_buttonBox(nullptr) + , m_uiRequirements(new UiRequirementList()) + , m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("LtsWidget.LtsDialog")) { - Q_UNUSED(parent); + Q_UNUSED(parent); - s_object_count++; + s_object_count++; - m_dialogHelper->setDialog(this); - m_buttonBox = m_dialogHelper->getButtonBox(); + m_dialogHelper->setDialog(this); // shadow this dialog on the helper class + m_buttonBox = m_dialogHelper->getButtonBox(); // for new dialogs, so they can connect to it - addDebugMenuButton(); - connect(m_buttonBox->getButton(DialogButton::Close), &QPushButton::clicked, this, &LtsDialog::slotClose); +// connect(this, &QObject::destroyed, +// new QObject, [this]() +// { +// qWarning() << (qintptr)this << "LtsDialog destroyed"; +// }); - switch (buttonCombination) +// connect(m_dialogHelper, &QObject::destroyed, +// new QObject, [this]() +// { +// qWarning() << (qintptr)m_dialogHelper.data() << "LtsDialogHelper destroyed"; +// }); + + + addDebugMenuButton(); + + + /* + OkApplyCancel, // Ok saves changes, closes the Dialog - Apply only saves changes, does not close the Dialog - Cancel closes the Dialog if there are no changes made + OkCancel, // Special case: only use if you are 100% sure what this is => example: New Message: there is only a SEND button, if sent, the dialog MUST be closed + CloseOnly, // For Dialogs that do not save anything + SeamlessDialog, // No buttons, no margins! + */ + + connect(m_buttonBox->getButton(DialogButton::Close), &QPushButton::clicked, this, &LtsDialog::slotClose); // is (almost) always shown + + switch(buttonCombination) + { + case ButtonCombination::OkCancel: { - case ButtonCombination::OkCancel: { - m_buttonBox->getButton(DialogButton::Close)->setText(tr("Cancel")); - connect(m_buttonBox->getButton(DialogButton::Ok), &QPushButton::clicked, this, &LtsDialog::slotOkay); - break; - } - - case ButtonCombination::OkApplyCancel: { - m_buttonBox->getButton(DialogButton::Close)->setText(tr("Cancel")); - connect(m_buttonBox->getButton(DialogButton::Ok), &QPushButton::clicked, this, &LtsDialog::slotOkay); - connect(m_buttonBox->getButton(DialogButton::Apply), &QPushButton::clicked, this, &LtsDialog::slotApply); - m_buttonBox->getButton(DialogButton::Apply)->setVisible(true); - break; - } - - case ButtonCombination::CloseOnly: { - m_buttonBox->getButton(DialogButton::Ok)->setVisible(false); - setUnchangeable(); - break; - } - - default: - case ButtonCombination::SeamlessDialog: { - m_buttonBox->setVisible(false); - setContentsMargins(0, 0, 0, 0); - m_dialogHelper->setContentsMargins(0, 0, 0, 0); - - QLayout* l = m_dialogHelper->layout(); - - if (l) - { - l->setContentsMargins(0, 0, 0, 0); - } - else - { - qWarning() << "LtsDialog::c_tor: Dialog Helper has no layout to set margins"; - } - - break; - } + m_buttonBox->getButton(DialogButton::Close)->setText(tr("Cancel")); // kb den button enum zu "cancel" umzubenennen + connect(m_buttonBox->getButton(DialogButton::Ok), &QPushButton::clicked, this, &LtsDialog::slotOkay); + break; } - if (!closeable) + case ButtonCombination::OkApplyCancel: { - m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->setVisible(false); - m_buttonBox->getButton(LtsWidgets::DialogButton::Close)->setVisible(false); + m_buttonBox->getButton(DialogButton::Close)->setText(tr("Cancel")); // kb den button enum zu "cancel" umzubenennen + connect(m_buttonBox->getButton(DialogButton::Ok), &QPushButton::clicked, this, &LtsDialog::slotOkay); + connect(m_buttonBox->getButton(DialogButton::Apply), &QPushButton::clicked, this, &LtsDialog::slotApply); + m_buttonBox->getButton(DialogButton::Apply)->setVisible(true); + break; } + + case ButtonCombination::CloseOnly: + { + m_buttonBox->getButton(DialogButton::Ok)->setVisible(false); + setUnchangeable(); + break; + } + + default: + case ButtonCombination::SeamlessDialog: + { + m_buttonBox->setVisible(false); + setContentsMargins(0,0,0,0); + m_dialogHelper->setContentsMargins(0,0,0,0); + + QLayout *l = m_dialogHelper->layout(); + + if (l) + { + l->setContentsMargins(0,0,0,0); + l->setMargin(0); + } + else + { + qWarning() << "LtsDialog::c_tor: Dialog Helper has no layout to set margins"; + } + + break; + } + } + + if (!closeable) + { + m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->setVisible(false); + m_buttonBox->getButton(LtsWidgets::DialogButton::Close)->setVisible(false); + } } + LtsDialog::~LtsDialog() { - delete m_uiRequirements; + delete m_uiRequirements; - if (m_overlayWidget) - m_overlayWidget->setParent(nullptr); + if (m_overlayWidget) + m_overlayWidget->setParent(nullptr); - s_object_count--; + // do not delete the dialog helper, as the dialog helper deletes this class + // also do not delete, as it is parented! => delete m_progressDialogHelper; + + s_object_count--; } -void LtsDialog::setOverlay(QWidget* widget) -{ - if (m_overlayContainer) - { - if (m_overlayWidget) - { - m_overlayWidget->hide(); - m_overlayWidget->setParent(nullptr); - m_overlayWidget->hide(); - m_overlayWidget = nullptr; - } - m_overlayContainer->hide(); - m_overlayContainer->setParent(nullptr); - m_overlayContainer->hide(); - m_overlayContainer->deleteLater(); - m_overlayContainer = nullptr; +void LtsDialog::setOverlay(QWidget *widget) +{ + if (m_overlayContainer) + { + if (m_overlayWidget) + { + m_overlayWidget->hide(); + m_overlayWidget->setParent(nullptr); + m_overlayWidget->hide(); + m_overlayWidget = nullptr; + // NOTE: we didn't create the widget so we don't delete it } - OverlayContainer* overlayContainer = new OverlayContainer(m_dialogHelper); + m_overlayContainer->hide(); + m_overlayContainer->setParent(nullptr); + m_overlayContainer->hide(); + m_overlayContainer->deleteLater(); + m_overlayContainer = nullptr; + } - connect(m_dialogHelper.data(), &LtsDialogHelper::signalSizeChanged, overlayContainer, - [overlayContainer](const QSize& size) { overlayContainer->setGeometry(QRect(QPoint(0, 0), size)); }); + // add a cool transparent background as an overlay to block the underlying dialog from user input, etc. + OverlayContainer *overlayContainer = new OverlayContainer(m_dialogHelper); // TODO: check race condition with dialogHelper's deletion / unparenting - overlayContainer->setGeometry(QRect(QPoint(0, 0), m_dialogHelper->size())); - m_overlayContainer = overlayContainer; + connect(m_dialogHelper.data(), &LtsDialogHelper::signalSizeChanged, + overlayContainer, [overlayContainer](const QSize &size) + { + overlayContainer->setGeometry(QRect(QPoint(0, 0), size)); + }); - QHBoxLayout* l = new QHBoxLayout; - m_overlayContainer->setLayout(l); + overlayContainer->setGeometry(QRect(QPoint(0, 0), m_dialogHelper->size())); + m_overlayContainer = overlayContainer; - widget->setAutoFillBackground(true); - l->addWidget(widget, 0, Qt::AlignCenter); - widget->show(); - connect(widget, &QWidget::destroyed, m_overlayContainer.data(), &QObject::deleteLater); + QHBoxLayout *l = new QHBoxLayout; + m_overlayContainer->setLayout(l); - m_overlayWidget = widget; + widget->setAutoFillBackground(true); + l->addWidget(widget, 0, Qt::AlignCenter); + widget->show(); - m_overlayContainer->show(); - m_overlayContainer->raise(); + connect(widget, &QWidget::destroyed, + m_overlayContainer.data(), &QObject::deleteLater); // every widget has its own container, so deleteLater is okay here + + m_overlayWidget = widget; + + m_overlayContainer->show(); + m_overlayContainer->raise(); } + void LtsDialog::unsetOverlay() { - if (m_overlayWidget) - m_overlayWidget->setParent(nullptr); + if (m_overlayWidget) + m_overlayWidget->setParent(nullptr); - if (!m_overlayContainer) - return; + if (!m_overlayContainer) + return; - m_overlayContainer->setParent(nullptr); - m_overlayContainer->deleteLater(); + m_overlayContainer->setParent(nullptr); + m_overlayContainer->deleteLater(); } -LtsDialogHelper* LtsDialog::getHelper() + +LtsDialogHelper *LtsDialog::getHelper() { - return m_dialogHelper; + return m_dialogHelper; } + LtsBaseLayoutWidget* LtsDialog::baseLayoutWidget() { - return m_baseLayoutWidget; + return m_baseLayoutWidget; } -void LtsDialog::setOnlineHelpFilename(const QString& fileName) + +void LtsDialog::setOnlineHelpFilename(const QString &fileName) // string without file extension !! { - m_onlineHelpFileName = fileName; - QPushButton* btn = m_buttonBox->getButton(DialogButton::Help); + m_onlineHelpFileName = fileName; + QPushButton *btn = m_buttonBox->getButton(DialogButton::Help); - if (btn == nullptr) - return; + if (btn == nullptr) // paranoid + return; - if (LtsSessionData::LtsSessionData::getInstance()->isTablet() && strcmp(PROJECTBUILD, "guez") == 0) - return; + if (LtsSessionData::LtsSessionData::getInstance()->isTablet() && strcmp(PROJECTBUILD, "guez") == 0) + return; //no more help in Guez OC - connect(btn, &QPushButton::clicked, this, [this]() { emit signalShowOnlineHelp(m_onlineHelpFileName); }); + connect(btn, &QPushButton::clicked, + this, [this]() + { + emit signalShowOnlineHelp(m_onlineHelpFileName); + }); - btn->setVisible(true); + btn->setVisible(true); } + void LtsDialog::addDebugMenuButton() { -#ifdef LTS_DEBUG - QMenu* menu = new QMenu(this); +#ifdef LTS_DEBUG // debug menu + QMenu *menu = new QMenu(this); - menu->addAction(QStringLiteral("simulate changes"), this, &LtsDialog::slotChangesMade); - menu->addAction(QStringLiteral("unchange"), this, &LtsDialog::__unchange__); - menu->addAction(QStringLiteral("retranslate"), this, &LtsDialog::retranslate); - menu->addAction(QStringLiteral("force unlock"), this, [this]() { setUnchangeable(false); }); - menu->addAction(QStringLiteral("set unchangeable"), this, [this]() { setUnchangeable(); }); - menu->addAction(QStringLiteral("try lock"), this, &LtsDialog::tryLockTopic); - menu->addAction(QStringLiteral("set closable"), this, [this]() { m_isClosable = true; }); - menu->addAction(QStringLiteral("set unclosable"), this, [this]() { m_isClosable = false; }); - menu->addAction(QStringLiteral("clear requirements"), this, [this] { m_uiRequirements->clear(); }); - menu->addAction(QStringLiteral("enable all button box buttons"), this, [this]() { - const auto children = m_buttonBox->findChildren(); - for (QPushButton* pb : children) - pb->setEnabled(true); - }); - menu->addAction(QStringLiteral("show button box button .."), this, [this]() { - QString buttonObjectName = QInputDialog::getText(this, QString(), QStringLiteral("Enter button object name")); - if (buttonObjectName.isEmpty()) - return; + menu->addAction(QStringLiteral("simulate changes"), this, &LtsDialog::slotChangesMade); + menu->addAction(QStringLiteral("unchange"), this, &LtsDialog::__unchange__); + menu->addAction(QStringLiteral("retranslate"), this, &LtsDialog::retranslate); + menu->addAction(QStringLiteral("force unlock"), this, [this]() { setUnchangeable(false); }); + menu->addAction(QStringLiteral("set unchangeable"), this, [this]() { setUnchangeable(); }); + menu->addAction(QStringLiteral("try lock"), this, &LtsDialog::tryLockTopic); + menu->addAction(QStringLiteral("set closable"), this, [this]() { m_isClosable = true; }); + menu->addAction(QStringLiteral("set unclosable"), this, [this]() { m_isClosable = false; }); + menu->addAction(QStringLiteral("clear requirements"), this, [this] { m_uiRequirements->clear(); }); + menu->addAction(QStringLiteral("enable all button box buttons"), this, [this]() + { + const auto children = m_buttonBox->findChildren(); + for (QPushButton *pb : children) + pb->setEnabled(true); + }); + menu->addAction(QStringLiteral("show button box button .."), this, [this]() + { + QString buttonObjectName = QInputDialog::getText(this, QString(), QStringLiteral("Enter button object name")); + if (buttonObjectName.isEmpty()) + return; - const QList buttons = m_buttonBox->findChildren(buttonObjectName); + const QList buttons = m_buttonBox->findChildren(buttonObjectName); - int btnCount = buttons.count(); - if (btnCount == 0) - { - LtsMessageDialog::showMessage(this, QStringLiteral("button not found")); - return; - } + int btnCount = buttons.count(); + if (btnCount == 0) + { + LtsMessageDialog::showMessage(this, QStringLiteral("button not found")); + return; + } - if (btnCount > 1) - { - QStringList buttonStringList; - buttonStringList.reserve(buttons.size()); - for (QPushButton* pb : buttons) - buttonStringList += pb->objectName(); + if (btnCount > 1) + { + QStringList buttonStringList; + buttonStringList.reserve(buttons.size()); + for (QPushButton *pb : buttons) + buttonStringList += pb->objectName(); - LtsMessageDialog::showMessage( - this, QStringLiteral("button ambiguous: %1").arg(buttonStringList.join(QStringLiteral(", ")))); - return; - } + LtsMessageDialog::showMessage(this, QStringLiteral("button ambiguous: %1").arg(buttonStringList.join(QStringLiteral(", ")))); + return; + } - buttons.at(0)->setVisible(true); - }); + buttons.at(0)->setVisible(true); + }); - QPushButton* debugBtn = m_buttonBox->getButton(DialogButton::_debug_); - debugBtn->setMenu(menu); - debugBtn->setVisible(true); + QPushButton *debugBtn = m_buttonBox->getButton(DialogButton::_debug_); + debugBtn->setMenu(menu); + debugBtn->setVisible(true); #endif } + void LtsDialog::updateWindowTitle() { - QString completeTitle = m_title; + QString completeTitle = m_title; - if (m_changesMade) - completeTitle.insert(0, QStringLiteral("\u2022")); + if (m_changesMade) + completeTitle.insert(0, QStringLiteral("\u2022")); // add modified-indicator unicode 'bullet' - if (!m_topicLockedBy.isEmpty()) - completeTitle.push_back(QString(QStringLiteral(" - READ-ONLY (%1)")).arg(m_topicLockedBy)); + if (!m_topicLockedBy.isEmpty()) + completeTitle.push_back(QString(QStringLiteral(" - READ-ONLY (%1)")).arg(m_topicLockedBy)); - QWidget::setWindowTitle(completeTitle); - if (m_dialogHelper != nullptr) - m_dialogHelper->setWindowTitle(completeTitle); + QWidget::setWindowTitle(completeTitle); + if (m_dialogHelper != nullptr) + m_dialogHelper->setWindowTitle(completeTitle); } -void LtsDialog::setWindowTitle(const QString& title) + +void LtsDialog::setWindowTitle(const QString &title) { - m_title = title; - updateWindowTitle(); + m_title = title; + updateWindowTitle(); } -void LtsDialog::setBaseLayoutWidget(LtsBaseLayoutWidget* baseLayoutWidget) + +void LtsDialog::setBaseLayoutWidget(LtsBaseLayoutWidget *baseLayoutWidget) { - m_baseLayoutWidget = baseLayoutWidget; + m_baseLayoutWidget = baseLayoutWidget; } -void LtsDialog::setIdentifier(const QString& identifier) +void LtsDialog::setIdentifier(const QString &identifier) { - m_identifier = identifier; - tableColumnOrganiserSetting(); + m_identifier = identifier; + tableColumnOrganiserSetting(); } -void LtsDialog::addConnections(QWidget* widget) + +void LtsDialog::addConnections(QWidget *widget) { - if (addChangesMadeSignal(widget, &QLineEdit::textChanged)) - return; - if (addChangesMadeSignal(widget, &QDateTimeEdit::dateTimeChanged)) - return; - if (addChangesMadeSignal(widget, &QComboBox::currentTextChanged)) - return; - if (addChangesMadeSignal(widget, &QCheckBox::stateChanged)) - return; - if (addChangesMadeSignal(widget, static_cast(&QSpinBox::valueChanged))) - return; - if (addChangesMadeSignal( - widget, static_cast(&QDoubleSpinBox::valueChanged))) - return; - if (addChangesMadeSignal(widget, &QSlider::valueChanged)) - return; - if (addChangesMadeSignal(widget, &QPlainTextEdit::textChanged)) - return; - if (addChangesMadeSignal(widget, &QTextEdit::textChanged)) - return; - if (addChangesMadeSignal(widget, &QAbstractButton::toggled)) - return; - if (addChangesMadeSignal(widget, &LtsDateTimeEdit::dateTimeChanged)) - return; + if (addChangesMadeSignal(widget, &QLineEdit::textChanged)) return; + if (addChangesMadeSignal(widget, &QDateTimeEdit::dateTimeChanged)) return; + if (addChangesMadeSignal(widget, &QComboBox::currentTextChanged)) return; + if (addChangesMadeSignal(widget, &QCheckBox::stateChanged)) return; + if (addChangesMadeSignal(widget, static_cast(&QSpinBox::valueChanged))) return; + if (addChangesMadeSignal(widget, static_cast(&QDoubleSpinBox::valueChanged))) return; + if (addChangesMadeSignal(widget, &QSlider::valueChanged)) return; + if (addChangesMadeSignal(widget, &QPlainTextEdit::textChanged)) return; + if (addChangesMadeSignal(widget, &QTextEdit::textChanged)) return; // TODO: rm - plain text only! + if (addChangesMadeSignal(widget, &QAbstractButton::toggled)) return; + if (addChangesMadeSignal(widget, &LtsDateTimeEdit::dateTimeChanged)) return; } -void LtsDialog::setUnchangeable(bool unchangeable) + +void LtsDialog::setUnchangeable(bool unchangeable) // adjust structure to new functionality (NOTE: calling this twice without restoring will currently result in bad behaviour) { - m_unchangeableDialog = unchangeable; + m_unchangeableDialog = unchangeable; } -bool LtsDialog::addDialogFixed(LtsDialog* dialog, const char* menuGroupUntranslated, const QString& identifier, - const LayoutArea& layoutArea, bool setClosable, bool focusNewTab) + +bool LtsDialog::addDialogFixed(LtsDialog *dialog, const char *menuGroupUntranslated, const QString &identifier, const LayoutArea &layoutArea, bool setClosable, bool focusNewTab) { - return addDialog(dialog, tr(menuGroupUntranslated), identifier, layoutArea, setClosable, focusNewTab); + return addDialog(dialog, /* >> */ tr(menuGroupUntranslated) /* << */, identifier, layoutArea, setClosable, focusNewTab); } -bool LtsDialog::addDialog(LtsDialog* dialog, const QString& menuGroup, const QString& identifier, - const LayoutArea& layoutArea, bool setClosable, bool focusNewTab) + +bool LtsDialog::addDialog(LtsDialog *dialog, const QString &menuGroup, const QString &identifier, const LayoutArea &layoutArea, bool setClosable, bool focusNewTab) { - if (!m_baseLayoutWidget) - { - qCritical() << "LtsDialog: addDialog: no base layout set - cannot add Dialog !"; - return false; - } + if (!m_baseLayoutWidget) + { + qCritical() << "LtsDialog: addDialog: no base layout set - cannot add Dialog !"; + return false; + } - return m_baseLayoutWidget->addWidget(dialog, menuGroup, identifier, layoutArea, setClosable, focusNewTab); + return m_baseLayoutWidget->addWidget(dialog, menuGroup, identifier, layoutArea, setClosable, focusNewTab); } + bool LtsDialog::amIFocused() const { - if (!m_baseLayoutWidget) - { - qCritical() << "LtsDialog: addDialog: no base layout set - cannot check for focus!"; - return false; - } + if (!m_baseLayoutWidget) + { + qCritical() << "LtsDialog: addDialog: no base layout set - cannot check for focus!"; + return false; + } - return m_baseLayoutWidget->isDialogFocused(this); + return m_baseLayoutWidget->isDialogFocused(this); } -bool LtsDialog::focusDialog(const QString& menuGroup, const QString& identifier, const LayoutArea& layoutArea) -{ - if (!m_baseLayoutWidget) - { - qCritical() << "LtsDialog: addDialog: no base layout set - cannot focus Dialog !"; - return false; - } - return m_baseLayoutWidget->focusTab(menuGroup, identifier, layoutArea); +bool LtsDialog::focusDialog(const QString &menuGroup, const QString &identifier, const LayoutArea &layoutArea) +{ + if (!m_baseLayoutWidget) + { + qCritical() << "LtsDialog: addDialog: no base layout set - cannot focus Dialog !"; + return false; + } + + return m_baseLayoutWidget->focusTab(menuGroup, identifier, layoutArea); } -void LtsDialog::showEvent(QShowEvent* event) + +void LtsDialog::showEvent(QShowEvent *event) { - emit visibilityChanged(true); + emit visibilityChanged(true); - bool tmp = m_unchangeableDialog; + bool tmp = m_unchangeableDialog; - if (!m_firstShow) - { - QWidget::showEvent(event); - return; - } + if (!m_firstShow) // do not reconnect if already connected (and do nothing if it's an unchangeable dialog) + { + QWidget::showEvent(event); + return; + } - m_unchangeableDialog = true; - m_firstShow = false; + m_unchangeableDialog = true; // do not monitor changes, yet + m_firstShow = false; - QList listenWidgets = findChildren(); + // the fact that all widgets are created before a window is shown, lets us connect to all editable widgets and listen to changes - for (auto i = listenWidgets.begin(); i != listenWidgets.end(); ++i) - { + // TODO: mit chris drueber reden ;) evtl. event listener, im widget event abfangen oder an ganz anderer stelle ? - QWidget* widget = *i; + QList listenWidgets = findChildren(); - QVariant isConst = widget->property("const"); - if (isConst.isValid() && isConst.toBool()) - continue; + for (auto i = listenWidgets.begin(); i != listenWidgets.end(); ++i) + { + // TODO: more widgets + // TODO: NGLPositionEdit / LtsPositionEdit - if (!tmp) - addConnections(widget); + QWidget *widget = *i; + + QVariant isConst = widget->property("const"); + if (isConst.isValid() && isConst.toBool()) + continue; + + if (!tmp) + addConnections(widget); #ifdef TABLET_MODE - LtsWidgets::addTouchScroll(widget); + LtsWidgets::addTouchScroll(widget); #endif - } + } - QWidget::showEvent(event); - m_unchangeableDialog = tmp; + QWidget::showEvent(event); + m_unchangeableDialog = tmp; // start monitoring changes only after this point, as user changes may now be made } + void LtsDialog::tryLockTopic() { - TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; - if (!m_topicInfo.isValid()) - return; + TRACE_LOG(m_logger) << LOGFUNCTION << " START"; + if (!m_topicInfo.isValid()) + return; - if (m_topicInfo.isLocked()) - { - WARNING_LOG(m_logger) << Q_FUNC_INFO << " tried to lock with an already locked topic info, return"; - return; - } + if (m_topicInfo.isLocked()) + { + WARNING_LOG(m_logger) << LOGFUNCTION << " tried to lock with an already locked topic info, return"; + return; + } - if (m_noLockTopic) - return; + if (m_noLockTopic) + return; - bool bIsConnected = isSignalConnected(QMetaMethod::fromSignal(&LtsDialog::signalLockTopic)); - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " signalLockTopic(): " - << ", TopicName =" << m_topicInfo.topicName() << ", entity =" << m_topicInfo.entityId() - << ", signalLockTopic isConnected=" << bIsConnected; + // case ParticipantEdit: + // LtsDialog::tryLockTopicNew is called by ParticipantEdit::onPartyChanged + // This slot is executed while + // - initialization (signal not connected) + // and + // - by user interaction (signal connected) + bool bIsConnected = isSignalConnected(QMetaMethod::fromSignal(&LtsDialog::signalLockTopic)); - if (bIsConnected) - { - emit signalLockTopic(m_topicInfo); + DEBUG_LOG(m_logger) << LOGFUNCTION + << " signalLockTopic(): " + << ", TopicName =" << m_topicInfo.topicName() + << ", entity =" << m_topicInfo.entityId() + << ", signalLockTopic isConnected=" << bIsConnected; - m_topicInfo.setLocked(); - } - TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; + if (bIsConnected) + { + emit signalLockTopic(m_topicInfo); // blocks! + // TODO: setUnchangeable(true); + m_topicInfo.setLocked(); + } + TRACE_LOG(m_logger) << LOGFUNCTION << " END"; } -void LtsDialog::initTopicLockHandler(const QString& topicName, int entityId) +void LtsDialog::initTopicLockHandler(const QString &topicName, int entityId) { + //qWarning() << "initTopicLockHandler"; - m_topicInfo.setTopicName(topicName); - m_topicInfo.setEntity(entityId); - m_topicInfo.setValid(); + m_topicInfo.setTopicName(topicName); + m_topicInfo.setEntity(entityId); + m_topicInfo.setValid(); } + void LtsDialog::tryLockTopicNew() { - TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; - tryLockTopic(); - TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; + TRACE_LOG(m_logger) << LOGFUNCTION << " START"; + tryLockTopic(); + TRACE_LOG(m_logger) << LOGFUNCTION << " END"; } -void LtsDialog::tryLockTopicNew(const QString& topicName, int entityId) +void LtsDialog::tryLockTopicNew(const QString &topicName, int entityId) { - TRACE_LOG(m_logger) << Q_FUNC_INFO << " START" - << ", topicName='" << topicName << "'" - << ", entityId=" << entityId; + TRACE_LOG(m_logger) << LOGFUNCTION << " START" + << ", topicName='" << topicName << "'" + << ", entityId=" << entityId; - if (m_topicInfo.entityId() != entityId) - { - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " topicName='" << topicName << "'" - << " change from " << m_topicInfo.entityId() << " to " << entityId; - m_topicInfo.setLocked(false); - } + // similar to "initTopicLockHandler" - m_topicInfo.setTopicName(topicName); - m_topicInfo.setEntity(entityId); - m_topicInfo.setValid(); + if (m_topicInfo.entityId() != entityId) + { + DEBUG_LOG(m_logger) << LOGFUNCTION << " topicName='" << topicName << "'" + << " change from " << m_topicInfo.entityId() << " to " << entityId; + m_topicInfo.setLocked(false); + } - tryLockTopic(); - TRACE_LOG(m_logger) << Q_FUNC_INFO << " END" - << ", topicName='" << topicName << "'" - << ", entityId=" << entityId; + + m_topicInfo.setTopicName(topicName); + m_topicInfo.setEntity(entityId); + m_topicInfo.setValid(); + + tryLockTopic(); + TRACE_LOG(m_logger) << LOGFUNCTION << " END" + << ", topicName='" << topicName << "'" + << ", entityId=" << entityId; } void LtsDialog::triggerTopicLock() { - TRACE_LOG(m_logger) << Q_FUNC_INFO << " START" - << " !!trigger!!"; - tryLockTopic(); - TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; + TRACE_LOG(m_logger) << LOGFUNCTION << " START" << " !!trigger!!"; + tryLockTopic(); + TRACE_LOG(m_logger) << LOGFUNCTION << " END"; } -void LtsDialog::translate(const QString& title) + +void LtsDialog::translate(const QString &title) // Only use if Mike says it's okay! { - bool isAlreadyUnchangeable = unchangeable(); + bool isAlreadyUnchangeable = unchangeable(); - if (!isAlreadyUnchangeable) - setUnchangeable(true); + if (!isAlreadyUnchangeable) + setUnchangeable(true); // retranslation is no change! - setWindowTitle(title); + setWindowTitle(title); - if (!isAlreadyUnchangeable) - setUnchangeable(false); +// qCritical() << " m_topicLockedBy : " << m_topicLockedBy.lockHint +// << ", operatorId=" << m_topicLockedBy.operatorId +// << ", workstationId=" << m_topicLockedBy.workstationId; + if (!isAlreadyUnchangeable) + setUnchangeable(false); // retranslation done + + { + bool isNowAlreadyUnchangeable = unchangeable(); + + QPushButton *b = m_buttonBox->getButton(DialogButton::ReadOnly); + if (b) { - bool isNowAlreadyUnchangeable = unchangeable(); + connect(b, &QPushButton::clicked, this, &LtsDialog::onReadOnlyButtonClicked, Qt::UniqueConnection); - QPushButton* b = m_buttonBox->getButton(DialogButton::ReadOnly); - if (b) - { - connect(b, &QPushButton::clicked, this, &LtsDialog::onReadOnlyButtonClicked, Qt::UniqueConnection); - - b->setVisible(isNowAlreadyUnchangeable && !m_topicLockedBy.isEmpty()); - if (b->isVisible()) - b->setToolTip(tr("Locked by: %1").arg(m_topicLockedBy)); - else - b->setToolTip({}); - } + // ExerciseDialog (CloseOnlyDialog -> no Ok-, Apply-Btn) + b->setVisible(isNowAlreadyUnchangeable && !m_topicLockedBy.isEmpty()); + if (b->isVisible()) + b->setToolTip(tr("Locked by: %1").arg(m_topicLockedBy)); + else + b->setToolTip({}); } + } } -void LtsDialog::slotLock(const QString& lockedBy) + + +void LtsDialog::slotLock(const QString &lockedBy) { - setUnchangeable(true); + setUnchangeable(true); - m_topicLockedBy = lockedBy; + m_topicLockedBy = lockedBy; - lock(); - retranslate(); + lock(); + retranslate(); } + void LtsDialog::slotUnlock() { - setUnchangeable(false); + setUnchangeable(false); - m_topicLockedBy.clear(); + m_topicLockedBy.clear(); - unlock(); - retranslate(); + unlock(); + retranslate(); } + void LtsDialog::lock() { - setWidgetsReadonly(true); - setWidgetsReadonly(true); + setWidgetsReadonly(true); + setWidgetsReadonly(true); + // setWidgetsCustom([](QComboBox *cb, bool readonly) { if (cb->lineEdit()) cb->lineEdit()->setReadOnly(readonly); }, unchangeable); + setWidgetsReadonly(true); + setWidgetsReadonly(true); + setWidgetsReadonly(true); + setWidgetsReadonly(true); - setWidgetsReadonly(true); - setWidgetsReadonly(true); - setWidgetsReadonly(true); - setWidgetsReadonly(true); - - setWidgetsDisabled(true); - setWidgetsDisabled(true); - setWidgetsDisabled(true); - setWidgetsDisabled(true); - setWidgetsDisabled(true); - setWidgetsDisabled(true); - setWidgetsDisabled(true); - setWidgetsDisabled(true); - setWidgetsDisabled(true); + setWidgetsDisabled(true); + setWidgetsDisabled(true); + setWidgetsDisabled(true); + setWidgetsDisabled(true); + setWidgetsDisabled(true); + setWidgetsDisabled(true); + setWidgetsDisabled(true); + setWidgetsDisabled(true); + setWidgetsDisabled(true); } + void LtsDialog::unlock() { - restoreReadonly(); - restoreReadonly(); + restoreReadonly(); + restoreReadonly(); +// setWidgetsCustom([](QComboBox *cb, bool readonly) { if (cb->lineEdit()) cb->lineEdit()->setReadOnly(readonly); }, unchangeable); + restoreReadonly(); + restoreReadonly(); + restoreReadonly(); + restoreReadonly(); - restoreReadonly(); - restoreReadonly(); - restoreReadonly(); - restoreReadonly(); - - restoreEnabled(); - restoreEnabled(); - restoreEnabled(); - restoreEnabled(); - restoreEnabled(); - restoreEnabled(); - restoreEnabled(); - restoreEnabled(); + restoreEnabled(); + restoreEnabled(); + restoreEnabled(); + restoreEnabled(); + restoreEnabled(); + restoreEnabled(); + restoreEnabled(); + restoreEnabled(); } -void LtsDialog::slotChangesMade() + +void LtsDialog::slotChangesMade() // TODO: get receiver's name, add to changes-made-list to identify changes to specific widgets { - if (m_unchangeableDialog) - return; + if (m_unchangeableDialog) + return; - m_changesMade = true; - updateWindowTitle(); + m_changesMade = true; + updateWindowTitle(); - m_buttonBox->getButton(DialogButton::Ok)->setEnabled(true); - m_buttonBox->getButton(DialogButton::Apply)->setEnabled(true); + m_buttonBox->getButton(DialogButton::Ok)->setEnabled(true); + m_buttonBox->getButton(DialogButton::Apply)->setEnabled(true); - emit signalChangesMade(); + emit signalChangesMade(); // tell dialogs that a Widget has received changes } + void LtsDialog::resetChanges() { - m_changesMade = false; + m_changesMade = false; - updateWindowTitle(); + updateWindowTitle(); + //if (!m_title.isEmpty()) + //setWindowTitle(m_title); // set title back to original - no more [*] needed - m_buttonBox->getButton(DialogButton::Ok)->setEnabled(false); - m_buttonBox->getButton(DialogButton::Apply)->setEnabled(false); - emit signalChangesReset(); + m_buttonBox->getButton(DialogButton::Ok)->setEnabled(false); + m_buttonBox->getButton(DialogButton::Apply)->setEnabled(false); + emit signalChangesReset(); } + bool LtsDialog::_apply() { - if (m_uiRequirements->checkRequirements(this) && apply()) - { - resetChanges(); - return true; - } + if (m_uiRequirements->checkRequirements(this) && apply()) + { + resetChanges(); // as all changes were saved successfully + return true; + } - return false; + return false; } + Button LtsDialog::askApplyDiscardCancel() { - return LtsMessageDialog::askApplyDiscardCancel(this); + return LtsMessageDialog::askApplyDiscardCancel(this); } -void LtsDialog::slotApply() + +void LtsDialog::slotApply() // does not close! only saves. { - _apply(); + _apply(); } -void LtsDialog::slotOkay() + +void LtsDialog::slotOkay() // closes and saves. (calls 'apply()', then calls 'close()') { - if (_apply()) - _close(); + if (_apply()) // if there were errors while applying, do not close! If not, close. + _close(); } + void LtsDialog::slotHide() { - _hide(); + _hide(); } -void LtsDialog::slotClose() -{ - if ((m_changesMade) && (!m_unchangeableDialog)) +void LtsDialog::slotClose() // closes but does NOT save (but asks for it (SaveDialog) - if 'save' was selected by the user in the SaveDialog, then 'okay()' will be called). +{ + // m_changesMade == true means that apply-btn is enabled + if ((m_changesMade) && (!m_unchangeableDialog)) + { + switch (askApplyDiscardCancel()) { - switch (askApplyDiscardCancel()) - { - case Button::Apply: - slotOkay(); - break; - case Button::Discard: - _discard(); - break; - default: - break; - } - } - else - { - _close(); + case Button::Apply: + slotOkay(); // save & close + break; + case Button::Discard: + _discard(); // do not save, just close + break; + default: // cancel + break; // do nothing } + } + else + { + _close(); // nothing has changed, so just close + } } void LtsDialog::onReadOnlyButtonClicked() { - if (m_topicLockedBy.isEmpty()) - return; - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Locked by: %1").arg(m_topicLockedBy)); + if (m_topicLockedBy.isEmpty()) + return; + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Locked by: %1").arg(m_topicLockedBy)); } + void LtsDialog::closeRequest() { - slotClose(); + slotClose(); } + void LtsDialog::_hide() { - if (m_dialogHelper != nullptr) - { - emit signalHide(m_dialogHelper); - } + if (m_dialogHelper != nullptr) + { + emit signalHide(m_dialogHelper); + //m_dialogHelper->hide(); + } } + void LtsDialog::_close() { - resetChanges(); - aboutToClose(); - if (m_dialogHelper != nullptr) - m_dialogHelper->close(); + resetChanges(); // for safety reasons + aboutToClose(); + if (m_dialogHelper != nullptr) + m_dialogHelper->close(); } void LtsDialog::_discard() { - dialogCanceled(); - _close(); + dialogCanceled(); + _close(); } } // namespace LtsWidgets + + + #include "lts_dialog.moc" diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog.h index 6785b0b10..2e0880e88 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog.h @@ -1,79 +1,61 @@ - +/** +* @RDE_HEADER@ +* Dialog for the new Layout system +* $Id$ +* $HeadURL$ +* $Author$ +*/ #pragma once + #include "lts_base.h" -#include "lts_dialog_button_box.h" #include "lts_widgets_export.h" -#include "requirement_widget.h" +#include "lts_dialog_button_box.h" // so that LtsDialogs don't have to include it #include -#include -#include -#include -#include -#include -#include -#include -#include + #include -#include -#include +#include +#include +#include #include +#include +#include +#include #include #include +#include +#include + +#include + +// Forward declaration - ui_requirement.h is not a UI file but regular C++ code +namespace LtsWidgets { class UiRequirementList; } + namespace LtsWidgets { class TopicInfo { - public: - int entityId() const - { - return m_entityId; - } +public: + int entityId() const { return m_entityId; } + const QString &topicName() const { return m_topicName; } + bool isLocked() const { return m_locked; } + bool isValid() const { return m_valid; } - const QString& topicName() const - { - return m_topicName; - } + void setEntity(int entityId) { m_entityId = entityId; } + void setTopicName(const QString &topicName) { m_topicName = topicName; } + void setLocked(bool locked = true) { m_locked = locked; } + void setValid() { m_valid = true; } - bool isLocked() const - { - return m_locked; - } - - bool isValid() const - { - return m_valid; - } - - void setEntity(int entityId) - { - m_entityId = entityId; - } - - void setTopicName(const QString& topicName) - { - m_topicName = topicName; - } - - void setLocked(bool locked = true) - { - m_locked = locked; - } - - void setValid() - { - m_valid = true; - } - - private: - QString m_topicName; - int m_entityId{0}; - bool m_locked{false}; - bool m_valid{false}; +private: + QString m_topicName; + int m_entityId{0}; + bool m_locked{false}; + bool m_valid{false}; }; + class LtsBaseLayoutWidget; class LtsDialogHelper; class LtsProgressDialogHelper; @@ -81,393 +63,481 @@ class LtsDialogButtonBox; class LtsToolBarArea; class OverlayContainer; -enum class ButtonCombination { - OkApplyCancel, - OkCancel, +enum class ButtonCombination +{ + OkApplyCancel, // Ok saves changes, closes the Dialog - Apply only saves changes, does not close the Dialog - Cancel closes the Dialog if there are no changes made - CloseOnly, - SeamlessDialog, + OkCancel, // TODO: rm + /* [deprecated => do not use! use 'OkApplyCancel' instead and tell the Dialog that 'this is a new element' by giving the + * translate-method inside the retranslate-method inside your LtsDialog either an empty/new dds element or by setting + * 'isNew' to true on one of the overloaded translate-methods + * OLD: Special case: only use if you are 100% sure what this is => example: New Message: there is only a SEND button, if sent, the dialog MUST be closed + */ + + CloseOnly, // For Dialogs that do not save anything + SeamlessDialog, // No buttons, no margins! }; + +/** + * @brief The LtsDialog class provides a Dialog for the Lts Layout System and is the equivalent to the QDialog. An LtsDialog can be added to a LayoutArea to interact with the user. + * WARNING: do not add widgets once the window is shown, as the ui requirements cannot be triggered after this point. + */ class LTSWIDGETS_EXPORT LtsDialog : public QWidget { - Q_OBJECT + Q_OBJECT - Q_PROPERTY(bool unchangeable READ unchangeable WRITE setUnchangeable) - public: - static int s_object_count; + Q_PROPERTY(bool unchangeable READ unchangeable WRITE setUnchangeable) +public: + static int s_object_count; - explicit LtsDialog(QWidget* parent = nullptr, ButtonCombination buttonCombination = ButtonCombination::CloseOnly, - bool closeable = true); - ~LtsDialog(); + /** + * @brief LtsDialog TODO: ! + * @param parent + */ + explicit LtsDialog(QWidget *parent = nullptr, ButtonCombination buttonCombination = ButtonCombination::CloseOnly, bool closeable = true); + ~LtsDialog(); - LtsDialogHelper* getHelper(); + /** + * @brief getHelper returns the internal helper class which contains this LtsDialog on it (do not use, for LtsTabWidget's addTab only!) + * @return class internal helper class + */ + LtsDialogHelper *getHelper(); - bool hasUnsavedChanges() const + bool hasUnsavedChanges() const { return m_changesMade || m_currentlyBlocking; } + + /** + * @brief retranslate is called on first show and when Qt is told to retranslate the whole application, should be used in all LtsDialogs + * NOTE: Everything inside this method does NOT trigger slotChangesMade (which is good ;). Is called by the framework. + * NOTE: Do not call retranslate yourself. Not even if you've overriden it. That won't work. The frameworks needs to call it. + */ + virtual void retranslate() = 0; + + void closeRequest(); // call this from outside of this class to request the close of this dialog (save request dialog is shown if there are unsaved changes) + void setUnchangeable(bool unchangeable = true); + bool unchangeable() const { return m_unchangeableDialog; } + + /** + * @brief addDialog + * @param dialog + * @param menuGroup use m_menuGroup / menuGroup() << This is NOT the Tab Title - override 'retranslate' for Tab Titles + * @param identifier use QStringLiteral - example: "exmEditDialog" << This is NOT the Tab Title - override 'retranslate' for Tab Titles + * @param layoutArea + * @return false if dialog / tab already exists - determined by menuGroup + identifier - and so the Dialog / Tab is not added + */ + bool addDialog(LtsDialog *dialog, const QString &menuGroup, const QString &identifier, const LayoutArea &layoutArea = LayoutArea::eDialogTab, bool setClosable = true, bool focusNewTab = true); + + + Q_DECL_DEPRECATED bool addDialogFixed(LtsDialog *dialog, const char *menuGroupUntranslated, const QString &identifier, const LayoutArea &layoutArea = LayoutArea::eDialogTab, bool setClosable = true, bool focusNewTab = true); + bool focusDialog(const QString &menuGroup, const QString &identifier, const LayoutArea &layoutArea); + bool amIFocused() const; + void setBaseLayoutWidget(LtsBaseLayoutWidget *baseLayoutWidget); // Do not use. + void __unchange__() { resetChanges(); } // Do not use. + void setClosable(bool closable) { m_isClosable = closable; } + bool isClosable() const { return m_isClosable; } + virtual void aboutToClose() {} // called just before the dialog is closed + void setMenuGroup(const QString &menuGroup) { m_menuGroup = menuGroup; } // Do not call. Called by Framework. + const QString &menuGroup() const { return m_menuGroup; } + void setIdentifier(const QString &identifier); // Do not call. Called by Framework. + virtual void tableColumnOrganiserSetting(){}; + const QString &identifier() const { return m_identifier; } + + void setOverlay(QWidget *widget); + void unsetOverlay(); + + /** + * @brief Sets the current width of the given widget as minimum width. + * Useful for Labels showing changing values to not jitter when then value changes + * Therefore you have to make sure, that the biggest (textual) value is set when calling this function + * @param Widget to set fixed width for + */ + static inline void setMinWidthForWidgetHelper(QWidget *w) + { + int width = w->sizeHint().width(); + w->setMinimumWidth(width); + } + + QString windowTitle() const + { + return m_title; + } + + + // neu tryLockTopic methode mit n Parametern, je nach Einsatzfall: + // ( LtsWidgets::TopicInfo ) + // Diese n Überladungen entsprechen jeweils eine Lock-Bedarfsfall. + // a) Dlg über pro Exercise sperren ("Exercise Purpose") + // b) Dlg über pro Exercise, PartyId sperren ("Edit Partitipants") + // jeder PartyChanged @ "Edit Partitipants" aktualisieren + // c) 2 verschiedene Dialog (pro Exercise) -> nur einer ReadWrite + // In beiden Dialog DENSELBEN topicName nutzen + + // "Gesperrt von anzeigen" + + // a) + void tryLockTopicNew(); + + + // b) + virtual void tryLockTopicNew (const QString &topicName, int entityId = -1); + + + void triggerTopicLock(); + + void setOnlineHelpFilename(const QString &fileName); // string without file extension !! + void setCurrentlyBlocking(bool currentlyBlocking = true) { m_currentlyBlocking = currentlyBlocking; } + +signals: + /** + * @brief Emit this signal to start the onHideAnimated Animation + * Only works when the dialog is a child of the LtsBaseLayoutWidget + * @param layoutArea the LayoutArea that should hide with an animation + */ + void startMainSelect(LtsWidgets::LayoutArea); + + /** + * @brief Emit this signal to start the onReShowAnimated Animation + * Only works when the dialog is a child of the LtsBaseLayoutWidget + * @param layoutArea the LayoutArea that should be shown again with an animation + */ + void endMainSelect(LtsWidgets::LayoutArea); + + /** + * @brief signalChangesMade is emitted after slotChangesMade was called + * (if you want to enable the Ok and/or Apply button, use slotChangesMade) + * For a list of supported Widgets, see LtsDialog::showEvent. + */ + void signalChangesMade(); + + void signalHide(QObject *object); // tells the TabWidget to remove the tab + + /** + * @brief Emit tells that all changes are reset + * and ok/apply buttons are now disabled + */ + void signalChangesReset(); // + + void signalFocused(); + void visibilityChanged(bool visible); + void signalLockTopic(const LtsWidgets::TopicInfo &topicInfo); + void signalShowOnlineHelp(const QString &fileName); + +protected: + /** + * @brief translate #1 is the same as translate #2, but does not retranslate the ui. DO NOT USE until permission by Mike! + * @param title + */ + void translate(const QString &title); + + + + template + /** + * @brief translate #2 is the same as translate #3, but only sets the title by a single parameter. DO NOT USE until permission by Mike! + * @param ui + * @param title + */ + void translate(T *ui, const QString &title) // main translate method! Only use if Mike says it's okay! + { + translate(title); + if (ui) + ui->retranslateUi(this); + // after ui->retranslate() to make sure all labels have the correct content + m_uiRequirements->retranslate(); + } + + void hideEvent(QHideEvent *event) override + { + QWidget::hideEvent(event); + emit visibilityChanged(false); + } + + template + /** + * @brief translate #3 is the same as translate #4, but lacks Topic handling. The window title is a combination of the given parameters. + * @param ui + * @param custom + * @param isNew set to true if this dialog is about creating a new entry (equivalent to Topic id 0) + * @param title + */ + void translate(T *ui, const QString &custom, bool isNew, const QString &title) + { + QString newTitle; + if (!isNew) { - return m_changesMade || m_currentlyBlocking; - } - - virtual void retranslate() = 0; - - void closeRequest(); - void setUnchangeable(bool unchangeable = true); - - bool unchangeable() const - { - return m_unchangeableDialog; - } - - bool addDialog(LtsDialog* dialog, const QString& menuGroup, const QString& identifier, - const LayoutArea& layoutArea = LayoutArea::eDialogTab, bool setClosable = true, - bool focusNewTab = true); - - Q_DECL_DEPRECATED bool addDialogFixed(LtsDialog* dialog, const char* menuGroupUntranslated, - const QString& identifier, - const LayoutArea& layoutArea = LayoutArea::eDialogTab, - bool setClosable = true, bool focusNewTab = true); - bool focusDialog(const QString& menuGroup, const QString& identifier, const LayoutArea& layoutArea); - bool amIFocused() const; - void setBaseLayoutWidget(LtsBaseLayoutWidget* baseLayoutWidget); - - void __unchange__() - { - resetChanges(); - } - - void setClosable(bool closable) - { - m_isClosable = closable; - } - - bool isClosable() const - { - return m_isClosable; - } - - virtual void aboutToClose() {} - - void setMenuGroup(const QString& menuGroup) - { - m_menuGroup = menuGroup; - } - - const QString& menuGroup() const - { - return m_menuGroup; - } - - void setIdentifier(const QString& identifier); - virtual void tableColumnOrganiserSetting(){}; - - const QString& identifier() const - { - return m_identifier; - } - - void setOverlay(QWidget* widget); - void unsetOverlay(); - - static inline void setMinWidthForWidgetHelper(QWidget* w) - { - int width = w->sizeHint().width(); - w->setMinimumWidth(width); - } - - QString windowTitle() const - { - return m_title; - } - - void tryLockTopicNew(); - - virtual void tryLockTopicNew(const QString& topicName, int entityId = -1); - - void triggerTopicLock(); - - void setOnlineHelpFilename(const QString& fileName); - - void setCurrentlyBlocking(bool currentlyBlocking = true) - { - m_currentlyBlocking = currentlyBlocking; - } - - signals: - - void startMainSelect(LtsWidgets::LayoutArea); - - void endMainSelect(LtsWidgets::LayoutArea); - - void signalChangesMade(); - - void signalHide(QObject* object); - - void signalChangesReset(); - - void signalFocused(); - void visibilityChanged(bool visible); - void signalLockTopic(const LtsWidgets::TopicInfo& topicInfo); - void signalShowOnlineHelp(const QString& fileName); - - protected: - void translate(const QString& title); - - template - - void translate(T* ui, const QString& title) - { - translate(title); - if (ui) - ui->retranslateUi(this); - - m_uiRequirements->retranslate(); - } - - void hideEvent(QHideEvent* event) override - { - QWidget::hideEvent(event); - emit visibilityChanged(false); - } - - template - - void translate(T* ui, const QString& custom, bool isNew, const QString& title) - { - QString newTitle; - if (!isNew) - { - if (unchangeable()) - { - if (custom.isEmpty()) - newTitle = (tr("Show %1").arg(title)); - else - newTitle = (tr("Show %1: %2").arg(title, custom)); - } - else - { - if (custom.isEmpty()) - newTitle = (tr("Edit %1").arg(title)); - else - newTitle = (tr("Edit %1: %2").arg(title, custom)); - - tryLockTopicNew(); - } - } + if (unchangeable()) + { + if (custom.isEmpty()) + newTitle = (tr("Show %1").arg(title)); else - { - newTitle = (tr("New %1").arg(title)); - m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->hide(); - m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->setText(tr("Create")); - } + newTitle = (tr("Show %1: %2").arg(title, custom)); + } + else + { + if (custom.isEmpty()) + newTitle = (tr("Edit %1").arg(title)); + else + newTitle = (tr("Edit %1: %2").arg(title, custom)); - translate(ui, newTitle); +// tryLockTopic(); + tryLockTopicNew(); + } } - - template - - void translate(T* ui, const QString& customUniqueTopicName, int topicId, const QString& custom, - const QString& title) + else { - Q_UNUSED(customUniqueTopicName); - - initTopicLockHandler(customUniqueTopicName, topicId); - - translate(ui, custom, (topicId < 1), title); + newTitle = (tr("New %1").arg(title)); + m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->hide(); // otherwise applying something after clicking apply results in another new object being created + m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->setText(tr("Create")); // Deutsch: "Anlegen" } - template + translate(ui, newTitle); + } - void translate(T* ui, const S& data, const QString& custom, const QString& title) + + template + /** + * @brief translate #4 is the same as translate #5, but without a Topic. 'customUniqueTopicName' and 'topicId' replace the missing Topic. + * @param ui + * @param customUniqueTopicName the name you would give the Topic class (e.g. "MeteoDataManagement::StaticWeather") + * @param topicId the Topic's id (e.g. 1) - use id smaller than 1 if it's a non-existent (new) entry + * @param custom + * @param title + */ + void translate(T* ui, const QString &customUniqueTopicName, int topicId, const QString &custom, const QString &title) + { + Q_UNUSED(customUniqueTopicName); + + initTopicLockHandler(customUniqueTopicName, topicId); + + translate(ui, custom /* can be empty */, + (topicId < 1 /* 0 is dds's equivalent to 'new', sadly there are cases where the id == -1, catch this case */), + title); + } + + + template + /** + * @brief translate #5 is the same as translate #6, but uses 'custom' as Topic name (for Topics without a 'name' entry) + * @param ui + * @param data + * @param custom the Topic's name (e.g. "Test Exercise 42") + * @param title + */ + void translate(T *ui, const S &data, const QString &custom, const QString &title) // same as 'void translate(T *ui, const S &data, const QString &title)', but for topics without the 'name' entry + { + translate(ui, QString::fromUtf8(typeid(data).name()), data.id(), custom /* can be empty */, title); + } + + + template + /** + * @brief translate #6 should be the most common and is easiest translate method for exactly one Topic. + * It locks the specific topic and creates a complex tab title with only a Topic and a general title. + * @param ui + * @param data the Topic which contains the id and the name (e.g. instance of ExerciseManagement::Exercise) + * @param title the topic of this dialog (e.g. "Exercise" if this Dialog is about a specific Exercise) + */ + void translate(T *ui, const S &data, const QString &title) + { + translate(ui, data, QString::fromStdString(data.name()), title); // -> translate #5 + } + + + // this is called when the dialog was cancel to be able to reset changes made + virtual void dialogCanceled() {} + LtsBaseLayoutWidget* baseLayoutWidget(); + void setNoTopicLock() { m_noLockTopic = true; } // Call in LtsDialog c_tor and nowhere else! + +private: + friend class LtsDialogHelper; + + bool m_changesMade; + bool m_currentlyBlocking { false }; // set to true if the dialog must not be closed because it is currently in a blocking call + bool m_firstShow; + QPointer m_baseLayoutWidget; // "cannot" outlive BLW, but to be sure.. + bool m_isClosable; + TopicInfo m_topicInfo; + +public: + QString m_topicLockedBy; + +private: + bool m_noLockTopic; + bool m_unchangeableDialog; // no '[*]' or asking in case of unsaved changes + QPointer m_dialogHelper; + //LtsProgressDialogHelper *m_progressDialogHelper; + QString m_title; + QString m_onlineHelpFileName; + QString m_menuGroup; + QString m_identifier; + + // overlay stuff: + QPointer m_overlayContainer; + QPointer m_overlayWidget; + + bool _apply(); + void _close(); + void _discard(); + void _hide(); + void resetChanges(); + void addDebugMenuButton(); + void tryLockTopic(); + void initTopicLockHandler(const QString &topicName, int entityId); + + /** + * @brief setWindowTitle sets this window title and of the Dialog Helper (use retranslate() instead!) + * @param title + */ + void setWindowTitle(const QString &title); + void updateWindowTitle(); + void addConnections(QWidget *widget); + + template + bool addChangesMadeSignal(QWidget *widget, SignalFunc signal) + { + WidgetType *concreteWidget = qobject_cast(widget); + + if (!concreteWidget) + return false; + + connect(concreteWidget, signal, this, &LtsDialog::slotChangesMade); + return true; + } + + + template + void setWidgetsReadonly(bool readonly) + { + const auto children = findChildren(); + for (WidgetType *widget : children ) { - translate(ui, QString::fromUtf8(typeid(data).name()), data.id(), custom, title); + widget->setProperty("lastReadOnlyState", widget->isReadOnly()); + widget->setReadOnly(readonly); } + } - template - void translate(T* ui, const S& data, const QString& title) + template + void setWidgetsDisabled(bool disabled) + { + const auto children = findChildren(); + for (WidgetType *widget : children) { - translate(ui, data, QString::fromStdString(data.name()), title); + widget->setProperty("lastEnabledState", widget->isEnabled()); + widget->setEnabled(!disabled); } + } - virtual void dialogCanceled() {} - - LtsBaseLayoutWidget* baseLayoutWidget(); - - void setNoTopicLock() + template + void restoreReadonly() + { + const auto children = findChildren(); + for (WidgetType *widget : children) { - m_noLockTopic = true; + QVariant lastState = widget->property("lastReadOnlyState"); + if (lastState.isValid() && !lastState.isNull() && lastState.canConvert(QMetaType::Bool)) + widget->setReadOnly(lastState.toBool()); } + } - private: - friend class LtsDialogHelper; - - bool m_changesMade; - bool m_currentlyBlocking{false}; - bool m_firstShow; - QPointer m_baseLayoutWidget; - bool m_isClosable; - TopicInfo m_topicInfo; - - public: - QString m_topicLockedBy; - - private: - bool m_noLockTopic; - bool m_unchangeableDialog; - QPointer m_dialogHelper; - NGL::INGLLogger& m_logger; - - QString m_title; - QString m_onlineHelpFileName; - QString m_menuGroup; - QString m_identifier; - - QPointer m_overlayContainer; - QPointer m_overlayWidget; - - bool _apply(); - void _close(); - void _discard(); - void _hide(); - void resetChanges(); - void addDebugMenuButton(); - void tryLockTopic(); - void initTopicLockHandler(const QString& topicName, int entityId); - - void setWindowTitle(const QString& title); - void updateWindowTitle(); - void addConnections(QWidget* widget); - - template bool addChangesMadeSignal(QWidget* widget, SignalFunc signal) + template + void restoreEnabled() + { + const auto children = findChildren(); + for (WidgetType *widget : children) { - WidgetType* concreteWidget = qobject_cast(widget); - - if (!concreteWidget) - return false; - - connect(concreteWidget, signal, this, &LtsDialog::slotChangesMade); - return true; + QVariant lastState = widget->property("lastEnabledState"); + if (lastState.isValid() && !lastState.isNull() && lastState.canConvert(QMetaType::Bool)) + widget->setEnabled(lastState.toBool()); } + } - template void setWidgetsReadonly(bool readonly) - { - const auto children = findChildren(); - for (WidgetType* widget : children) - { - widget->setProperty("lastReadOnlyState", widget->isReadOnly()); - widget->setReadOnly(readonly); - } - } +public slots: + /** + * @brief slotChangesMade emits 'signalChangesMade()' and tells the dialog that changes on editable Widgets were made. So that the Save-Dialog will be shown on Close. + * For a list of supported Widgets, see LtsDialog::showEvent. + */ + void slotChangesMade(); - template void setWidgetsDisabled(bool disabled) - { - const auto children = findChildren(); - for (WidgetType* widget : children) - { - widget->setProperty("lastEnabledState", widget->isEnabled()); - widget->setEnabled(!disabled); - } - } + void slotHide(); // hides dialog, removes tab, does not delete dialog + void slotLock(const QString &lockedBy); + void slotUnlock(); - template void restoreReadonly() - { - const auto children = findChildren(); - for (WidgetType* widget : children) - { - QVariant lastState = widget->property("lastReadOnlyState"); - if (lastState.isValid() && !lastState.isNull() && lastState.canConvert(QMetaType::Bool)) - widget->setReadOnly(lastState.toBool()); - } - } +private slots: + void slotApply(); // does not close! only saves. + void slotOkay(); // closes and saves. (calls 'apply()', then calls 'close()') + void slotClose(); // closes but does NOT save (but asks for it (SaveDialog) - if 'save' was selected by the user in the SaveDialog, then 'okay()' will be called). + //void slotSizeChanged(const QSize &size); + void onReadOnlyButtonClicked(); - template void restoreEnabled() - { - const auto children = findChildren(); - for (WidgetType* widget : children) - { - QVariant lastState = widget->property("lastEnabledState"); - if (lastState.isValid() && !lastState.isNull() && lastState.canConvert(QMetaType::Bool)) - widget->setEnabled(lastState.toBool()); - } - } +protected: + virtual void lock(); + virtual void unlock(); - public slots: + virtual bool apply() { return true; } // reimpl to save your changes here, DO NOT CLOSE! return true if changes could be saved (this will close the dialog on 'okay') or return false if NOT (dialog will NOT be closed then) + void showEvent(QShowEvent *event) override; + Button askApplyDiscardCancel(); - void slotChangesMade(); + LtsDialogButtonBox *m_buttonBox; + UiRequirementList *m_uiRequirements; - void slotHide(); - void slotLock(const QString& lockedBy); - void slotUnlock(); - - private slots: - void slotApply(); - void slotOkay(); - void slotClose(); - - void onReadOnlyButtonClicked(); - - protected: - virtual void lock(); - virtual void unlock(); - - virtual bool apply() - { - return true; - } - - void showEvent(QShowEvent* event) override; - Button askApplyDiscardCancel(); - - LtsDialogButtonBox* m_buttonBox; - UiRequirementList* m_uiRequirements; + NGL::INGLLogger &m_logger; }; -template T* initDialog(T* dialog) + +// support init WITHOUT parameter +template +T *initDialog(T *dialog) { - if (!dialog->init()) - { - dialog->deleteLater(); - return nullptr; - } - return dialog; + if (!dialog->init()) + { + dialog->deleteLater(); + return nullptr; + } + return dialog; } -template T* initDialog(T* dialog, F&&... f) +// support init WITH parameter +template +T *initDialog(T *dialog, F&&... f) { - if (!dialog->init(std::forward(f)...)) - { - dialog->deleteLater(); - return nullptr; - } - return dialog; + if (!dialog->init(std::forward(f)...)) + { + dialog->deleteLater(); + return nullptr; + } + return dialog; } -template T* createThrowableDialog(F&&... f) + +template +T *createThrowableDialog(F&&... f) { - T* dlg = nullptr; + T *dlg = nullptr; - try - { - dlg = new T(std::forward(f)...); - } - catch (const char* s) - { - fprintf(stderr, "Dialog could not be created: %s\n", s); - return nullptr; - } - catch (const QString& msg) - { - fprintf(stderr, "Dialog could not be created: %s\n", msg.toStdString().c_str()); - return nullptr; - } - catch (...) - { - fprintf(stderr, "Dialog could not be created: unknown error\n"); - return nullptr; - } + try + { + dlg = new T(std::forward(f)...); + } + catch (const char *s) + { + fprintf(stderr, "Dialog could not be created: %s\n", s); + return nullptr; + } + catch (const QString &msg) + { + fprintf(stderr, "Dialog could not be created: %s\n", msg.toStdString().c_str()); + return nullptr; + } + catch (...) + { + fprintf(stderr, "Dialog could not be created: unknown error\n"); + return nullptr; + } - return dlg; + return dlg; } + } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_button_box.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_button_box.cpp index 894ce5bd6..fc9d4c691 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_button_box.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_button_box.cpp @@ -1,199 +1,224 @@ - +/** + * @RDE_HEADER@ + * Bottom Button Box for Dialogs which need actions + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Mike Wille, SLSE, 2016-08-17 + */ #include "lts_dialog_button_box.h" - -#include "lts_message_dialog.h" #include "ui_lts_dialog_button_box.h" +#include "lts_message_dialog.h" #include #include namespace LtsWidgets { -LtsDialogButtonBox::LtsDialogButtonBox(QWidget* parent) - : QWidget(parent), m_isTablet(LtsSessionData::LtsSessionData::getInstance()->isTablet()), - m_ui(new Ui::LtsDialogButtonBox) +LtsDialogButtonBox::LtsDialogButtonBox(QWidget *parent) + : QWidget(parent) + , m_isTablet(LtsSessionData::LtsSessionData::getInstance()->isTablet()) + , m_ui(new Ui::LtsDialogButtonBox) { - m_ui->setupUi(this); - _setVisibilityForAll(false); + m_ui->setupUi(this); + _setVisibilityForAll(false); // hide all buttons - QMenu* libraryMenu = new QMenu(m_ui->pbLibrary); - libraryMenu->addAction(QIcon(QLatin1String(":/style/library_load.svg")), tr("Load"), this, - &LtsDialogButtonBox::signalLibraryLoadClicked); - libraryMenu->addAction(QIcon(QLatin1String(":/style/library_save.svg")), tr("Save"), this, - &LtsDialogButtonBox::signalLibrarySaveClicked); - m_ui->pbLibrary->setMenu(libraryMenu); + // Btn 'Library' + QMenu *libraryMenu = new QMenu(m_ui->pbLibrary); + libraryMenu->addAction(QIcon(QLatin1String(":/style/library_load.svg")), + tr("Load"), this, &LtsDialogButtonBox::signalLibraryLoadClicked); + libraryMenu->addAction(QIcon(QLatin1String(":/style/library_save.svg")), + tr("Save"), this, &LtsDialogButtonBox::signalLibrarySaveClicked); + m_ui->pbLibrary->setMenu(libraryMenu); - m_ui->pbOk->setVisible(true); - m_ui->pbClose->setVisible(true); + // exceptions for call above: + m_ui->pbOk->setVisible(true); // c LtsDialog's impl 2 c y ! + m_ui->pbClose->setVisible(true); // s.a.a. + // no help file name set = no help button ! => m_ui->pbHelp->setVisible(true); // must be explicitly hidden for dialogs without help content } + LtsDialogButtonBox::~LtsDialogButtonBox() { - delete m_ui; + delete m_ui; } + void LtsDialogButtonBox::_setVisibilityForAll(bool visible) { - const auto buttons = findChildren(); - for (QPushButton* button : buttons) - button->setVisible(visible); + const auto buttons = findChildren(); + for (QPushButton *button : buttons) + button->setVisible(visible); } -void LtsDialogButtonBox::setText(DialogButton button, const QString& text) + +void LtsDialogButtonBox::setText(DialogButton button, const QString &text) { + // TODO: check if setText was called by a 'retranslate' method, if not debug msg ! - QPushButton* btn = getButton(button); + QPushButton *btn = getButton(button); - if (btn) - btn->setText(text); + if (btn) + btn->setText(text); } -void LtsDialogButtonBox::setToolTip(DialogButton button, const QString& text) -{ - QPushButton* btn = getButton(button); - if (btn) - btn->setToolTip(text); +void LtsDialogButtonBox::setToolTip(DialogButton button, const QString &text) +{ + QPushButton *btn = getButton(button); + + if (btn) + btn->setToolTip(text); } -void LtsDialogButtonBox::setIcon(DialogButton button, const QIcon& icon) -{ - QPushButton* btn = getButton(button); - if (btn) - btn->setIcon(icon); +void LtsDialogButtonBox::setIcon(DialogButton button, const QIcon &icon) +{ + QPushButton *btn = getButton(button); + + if (btn) + btn->setIcon(icon); } -void LtsDialogButtonBox::setMenu(DialogButton button, QMenu* menu) -{ - QPushButton* btn = getButton(button); - if (btn) - btn->setMenu(menu); +void LtsDialogButtonBox::setMenu(DialogButton button, QMenu *menu) +{ + QPushButton *btn = getButton(button); + + if (btn) + btn->setMenu(menu); } -QPushButton* LtsDialogButtonBox::getButton(DialogButton button) const + +QPushButton *LtsDialogButtonBox::getButton(DialogButton button) const { - switch (button) - { - case DialogButton::ReadOnly: - return m_ui->pbReadOnly; - case DialogButton::Ok: - return m_ui->pbOk; - case DialogButton::Apply: - return m_ui->pbApply; - case DialogButton::Close: - return m_ui->pbClose; - case DialogButton::Yes: - return m_ui->pbYes; - case DialogButton::No: - return m_ui->pbNo; - case DialogButton::Remove: - return m_ui->pbRemove; - case DialogButton::Hide: - return m_ui->pbHide; - case DialogButton::Add: - return m_ui->pbAdd; - case DialogButton::Help: - return m_ui->pbHelp; - case DialogButton::Edit: - return m_ui->pbEdit; - case DialogButton::Save: - return m_ui->pbSave; - case DialogButton::Load: - return m_ui->pbLoad; - case DialogButton::Show: - return m_ui->pbShow; - case DialogButton::Import: - return m_ui->pbImport; - case DialogButton::Export: - return m_ui->pbExport; - case DialogButton::Library: - return m_ui->pbLibrary; - case DialogButton::CenterMap: - return m_ui->pbCenterMap; - case DialogButton::ZoomMapTo: - return m_ui->pbZoomMapTo; - case DialogButton::Print: - return m_ui->pbPrint; + switch (button) + { + case DialogButton::ReadOnly: + return m_ui->pbReadOnly; + case DialogButton::Ok: + return m_ui->pbOk; + case DialogButton::Apply: + return m_ui->pbApply; + case DialogButton::Close: + return m_ui->pbClose; + case DialogButton::Yes: + return m_ui->pbYes; + case DialogButton::No: + return m_ui->pbNo; + case DialogButton::Remove: + return m_ui->pbRemove; + case DialogButton::Hide: + return m_ui->pbHide; + case DialogButton::Add: + return m_ui->pbAdd; + case DialogButton::Help: + return m_ui->pbHelp; + case DialogButton::Edit: + return m_ui->pbEdit; + case DialogButton::Save: + return m_ui->pbSave; + case DialogButton::Load: + return m_ui->pbLoad; + case DialogButton::Show: + return m_ui->pbShow; + case DialogButton::Import: + return m_ui->pbImport; + case DialogButton::Export: + return m_ui->pbExport; + case DialogButton::Library: + return m_ui->pbLibrary; + case DialogButton::CenterMap: + return m_ui->pbCenterMap; + case DialogButton::ZoomMapTo: + return m_ui->pbZoomMapTo; + case DialogButton::Print: + return m_ui->pbPrint; #ifdef LTS_DEBUG - case DialogButton::_debug_: - return m_ui->_pbChanges; + case DialogButton::_debug_: + return m_ui->_pbChanges; #endif - } - Q_ASSERT(false); - return nullptr; + } + Q_ASSERT(false); + return nullptr; // sec } + void LtsDialogButtonBox::slotRemoveClicked() { - if (LtsMessageDialog::showMessage(this, tr("Are you sure you want to delete the selected entry(ies)?"), - tr("Remove selected entry(ies)"), Behaviour::Modal, - Button::Yes | Button::No) == Button::Yes) - emit signalRemoveClicked(); + if (LtsMessageDialog::showMessage(this, + tr("Are you sure you want to delete the selected entry(ies)?"), + tr("Remove selected entry(ies)"), + Behaviour::Modal, + Button::Yes | Button::No) + == Button::Yes) + emit signalRemoveClicked(); } -void LtsDialogButtonBox::setButtonsVisible(QPushButton* pb) + +void LtsDialogButtonBox::setButtonsVisible(QPushButton *pb) { - if (!pb || (pb == m_ui->pbPrint && m_isTablet)) - return; - m_ui->line->setVisible(true); - pb->setVisible(true); + if (!pb || (pb == m_ui->pbPrint && m_isTablet)) + return; + m_ui->line->setVisible(true); + pb->setVisible(true); } + void LtsDialogButtonBox::setButtonVisible(DialogButton button, bool visible) { - QPushButton* pb = getButton(button); - if (!pb) - return; - if (m_isTablet && pb == m_ui->pbPrint) - { - pb->setVisible(false); - return; - } - pb->setVisible(visible); + QPushButton *pb = getButton(button); + if (!pb) + return; + if (m_isTablet && pb == m_ui->pbPrint) + { + pb->setVisible(false); + return; + } + pb->setVisible(visible); } + bool LtsDialogButtonBox::isButtonVisible(DialogButton button) const { - const QPushButton* pb = getButton(button); - return (pb ? pb->isVisible() : false); + const QPushButton *pb = getButton(button); + return (pb ? pb->isVisible() : false); } + void LtsDialogButtonBox::setButtonEnabled(DialogButton button, bool enabled) { - QPushButton* pb = getButton(button); + QPushButton *pb = getButton(button); - switch (button) - { - case DialogButton::Close: - case DialogButton::Ok: - case DialogButton::Apply: - - { + switch (button) + { + case DialogButton::Close: + case DialogButton::Ok: + case DialogButton::Apply: + //case DialogButton::Yes: + //case DialogButton::No: + { #ifdef LTS_DEBUG - LtsMessageDialog::showMessage( - this, - QStringLiteral("Hier stimmt etwas nicht. Bitte MIKE bescheid geben WAS geklickt oder gemacht wurde als " - "dieser Dialog auftauchte, damit ich es fixen kann. Danke."), - QStringLiteral(">>> STOP <<<")); + LtsMessageDialog::showMessage(this, QStringLiteral("Hier stimmt etwas nicht. Bitte MIKE bescheid geben WAS geklickt oder gemacht wurde als dieser Dialog auftauchte, damit ich es fixen kann. Danke."), QStringLiteral(">>> STOP <<<")); #endif - break; - } + break; + } - default: - break; - } + default: + break; + } - if (pb) - pb->setEnabled(enabled); + if (pb) + pb->setEnabled(enabled); } + bool LtsDialogButtonBox::isButtonEnabled(DialogButton button) const { - auto* that = const_cast(this); - const QPushButton* pb = that->getButton(button); - return (pb ? pb->isEnabled() : false); + auto *that = const_cast(this); // ... + const QPushButton *pb = that->getButton(button); + return (pb ? pb->isEnabled() : false); } } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_button_box.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_button_box.h index 6d249d5a3..d280795ba 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_button_box.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_button_box.h @@ -1,12 +1,20 @@ - +/** + * @RDE_HEADER@ + * Bottom Button Box for Dialogs which need actions + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Mike Wille, SLSE, 2016-08-17 + */ #pragma once -#include "lts_message_dialog.h" -#include "lts_widgets_export.h" -#include -#include +#include "lts_widgets_export.h" +#include "lts_message_dialog.h" + #include +#include namespace Ui { @@ -15,159 +23,230 @@ class LtsDialogButtonBox; namespace LtsWidgets { -enum class DialogButton { +enum class DialogButton +{ + // Do not connect these: + ReadOnly, + Ok, + Apply, + Close, + Yes, + No, - ReadOnly, - Ok, - Apply, - Close, - Yes, - No, - - Remove, - Hide, - Add, - Help, - Edit, - Save, - Load, - Show, - Import, - Export, - CenterMap, - ZoomMapTo, - Library, - Print, + // You can connect these: + Remove, + Hide, + Add, + Help, + Edit, + Save, + Load, + Show, + Import, + Export, + CenterMap, + ZoomMapTo, + Library, + Print, #ifdef LTS_DEBUG - _debug_, + _debug_, #endif }; + + +// TODO: doc: close is now autoconnected by NEW LtsDialogs not running in compatibility mode ! + +/** + * @brief The LtsDialogButtonBox class is a replacement for the NGLDialogButtonBox. With the significant difference that + * Actions ('Ok', 'Close', etc.) are select in code, not in the designer. + * + * Pro: + * > no dead/unconnected buttons + * > no designer plugin needed + * > no killed dialog boxes after editing uis + * > auto connecting the close button to the Dialogs accept / Widgets close (important for close requests on dialogs before closing) + * > solid connections only (safer & faster than connections by char*) [also con] + * + * Con: + * > no possibility to see which Actions are available for a specific dialog + * > solid connections only (more complicated) [also pro] + * + * To make Actions visible & usable, use 'connectButton' with the coherant Action (DialogButton). + * 'connectButton' works similar to Qt's Connect mechanism, with the main difference that there is neither a sender nor a signal to specify. + * + * Example: connectButton(DialogButton::Ok, this, &ThisDialog::accept); + * + * + * >>You have overloaded slots?<< + * For example you have: slotSomethingChanged(int) and slotSomethingChanged(QString) + * For the 'int'-version the result should look like: connect(DialogButton::Ok, this, static_cast(&ThisDialog::slotSOmethingChanged)); + * Unfortunately this is the Qt version to solve this problem.. + * + */ class LTSWIDGETS_EXPORT LtsDialogButtonBox : public QWidget { - Q_OBJECT + Q_OBJECT - public: - explicit LtsDialogButtonBox(QWidget* parent); - ~LtsDialogButtonBox(); +public: + explicit LtsDialogButtonBox(QWidget *parent); + ~LtsDialogButtonBox(); - template - void connectButton(DialogButton button, const typename QtPrivate::FunctionPointer::Object* receiver, - Func2 slot, Qt::ConnectionType type = Qt::AutoConnection) + /** + * @brief connectButton connects a Button (like 'Apply', 'Ok', etc.) to the given receiver + slot. + * This method prevents the existence of dead buttons (not connected) and that a missing Designer plugin messes up the button properties. + * So, to make a button visible, use this method. + * + * Important: only solid connections possible (yet) + * Example: connectButton(DialogButton::Ok, this, &ThisDialog::accept); + * + * @param button the DialogButton to make visible and connect it to the given 'slot' + * @param receiver the receiver of the signal when a DialogButton is clicked - like the receiver in Qt's connect method + * @param slot the slot on the 'receiver' called when the clicked signal is called by a DialogButton - like the slot in the Qt's connect method + * @param type Qt::ConnectionType (does not need bo be set) + */ + template + void connectButton(DialogButton button, const typename QtPrivate::FunctionPointer::Object *receiver, + Func2 slot, Qt::ConnectionType type = Qt::AutoConnection) + { + //if (!LtsDialog::plan_editor_compatibility) { - - { - switch (button) - { + switch (button) + { #ifdef LTS_DEBUG - case DialogButton::_debug_: + case DialogButton::_debug_: #endif - case DialogButton::Close: - case DialogButton::Ok: - case DialogButton::ReadOnly: - case DialogButton::Apply: - case DialogButton::Help: { - LtsMessageDialog::showMessage( - this, - QStringLiteral( - "Bitte den fuer das Plugin verantwortlichen kontaktieren:
" - "m_buttonBox nicht mit Ok, Apply, Help, _debug_ oder Close verbinden
" - "Note: Bitte nur m_buttonBox verwenden, keine LtsDialogButtonBox selber erstellen" - "Ok & Apply werden automatisch zur virtual Methode 'apply()' im LtsDialog " - "weitergeleitet.
" - "Close schließt einfach den Dialog - im Destruktor oder in 'aboutToClose()' ist der 'Close " - "Code' gut aufgehoben.
" - "
" - "FIXEN !!!!!"), - QStringLiteral("--- STOP --- !!! FIXEN !!! ---")); - break; - } + case DialogButton::Close: + case DialogButton::Ok: + case DialogButton::ReadOnly: + case DialogButton::Apply: + case DialogButton::Help: + { + LtsMessageDialog::showMessage(this, + QStringLiteral("Bitte den fuer das Plugin verantwortlichen kontaktieren:
" + "m_buttonBox nicht mit Ok, Apply, Help, _debug_ oder Close verbinden
" + "Note: Bitte nur m_buttonBox verwenden, keine LtsDialogButtonBox selber erstellen" + "Ok & Apply werden automatisch zur virtual Methode 'apply()' im LtsDialog weitergeleitet.
" + "Close schließt einfach den Dialog - im Destruktor oder in 'aboutToClose()' ist der 'Close Code' gut aufgehoben.
" + "
" + "FIXEN !!!!!"), + QStringLiteral("--- STOP --- !!! FIXEN !!! ---")); + break; + } - default: - break; - } - } - - QPushButton* theSender = getButton(button); - - if (!theSender) - return; - - switch (button) - { - case DialogButton::Remove: { - connect(this, &LtsDialogButtonBox::signalRemoveClicked, receiver, slot, type); - connect(theSender, &QPushButton::clicked, this, &LtsDialogButtonBox::slotRemoveClicked); - - break; - } - case DialogButton::Export: - case DialogButton::Import: { - if (m_isTablet) - { - theSender->setVisible(false); - return; - } - Q_FALLTHROUGH(); - } - default: - connect(theSender, &QPushButton::clicked, receiver, slot, type); - break; - } - - setButtonsVisible(theSender); + default: + break; + } } - template - bool connectLibraryButton(const typename QtPrivate::FunctionPointer::Object* receiver, Func1 slotLoad, - Func2 slotSave, Qt::ConnectionType type = Qt::AutoConnection) + + QPushButton *theSender = getButton(button); + + if (!theSender) + return; + + // special cases for Buttons with embedded Dialogs + switch (button) { - QPushButton* theSender = getButton(DialogButton::Library); - if (!theSender) - return false; - if (m_isTablet) - { - theSender->setVisible(false); - return true; - } - setButtonsVisible(theSender); - type = static_cast(type | Qt::UniqueConnection); - return (connect(this, &LtsDialogButtonBox::signalLibraryLoadClicked, receiver, slotLoad, type) && - connect(this, &LtsDialogButtonBox::signalLibrarySaveClicked, receiver, slotSave, type)); + case DialogButton::Remove: + { + connect(this, &LtsDialogButtonBox::signalRemoveClicked, receiver, slot, type); + connect(theSender, &QPushButton::clicked, this, &LtsDialogButtonBox::slotRemoveClicked); + + break; + } + case DialogButton::Export: + case DialogButton::Import: + { + if (m_isTablet) + { + theSender->setVisible(false); + return; + } + Q_FALLTHROUGH(); + } + default: + connect(theSender, &QPushButton::clicked, receiver, slot, type); + break; } - void setText(DialogButton button, const QString& text); + setButtonsVisible(theSender); // this method's magic + } + template + bool connectLibraryButton(const typename QtPrivate::FunctionPointer::Object *receiver, + Func1 slotLoad, + Func2 slotSave, + Qt::ConnectionType type = Qt::AutoConnection) + { + QPushButton *theSender = getButton(DialogButton::Library); + if (!theSender) + return false; + if (m_isTablet) + { + theSender->setVisible(false); + return true; + } + setButtonsVisible(theSender); + type = static_cast(type | Qt::UniqueConnection); + return (connect(this, &LtsDialogButtonBox::signalLibraryLoadClicked, receiver, slotLoad, type) && + connect(this, &LtsDialogButtonBox::signalLibrarySaveClicked, receiver, slotSave, type)); + } - void setToolTip(DialogButton button, const QString& text); - void setIcon(DialogButton button, const QIcon& icon); - void setMenu(DialogButton button, QMenu* menu); + /** + * @brief setText changes the text of a DialogButton to the 'text' specified. + * @param button the DialogButton to rename + * @param text new text of DialogButton + */ + void setText(DialogButton button, const QString &text); - void setButtonEnabled(DialogButton button, bool enabled = true); - bool isButtonEnabled(DialogButton button) const; + void setToolTip(DialogButton button, const QString &text); + void setIcon(DialogButton button, const QIcon &icon); + void setMenu(DialogButton button, QMenu *menu); - void setButtonVisible(DialogButton button, bool visible = true); - bool isButtonVisible(DialogButton button) const; + /** + * @brief setButtonEnabled enables / disables a DialogButton. + * @param button the DialogButton to dis-/enable + * @param enabled true = enabled; false = disabled + */ + void setButtonEnabled(DialogButton button, bool enabled = true); + bool isButtonEnabled(DialogButton button) const; - QPushButton* getButton(DialogButton button) const; + void setButtonVisible(DialogButton button, bool visible = true); + bool isButtonVisible(DialogButton button) const; - void _setVisibilityForAll(bool visible); + /** + * Do not use! + * @brief getButton DialogButton to real QPushButton* widget (do not use outside of this class!) + * @param button + * @return Pointer to QPushButton or nullptr when not found / available + */ + QPushButton *getButton(DialogButton button) const; - signals: - void signalRemoveClicked(); - void signalHelpClicked(); - void signalLibraryLoadClicked(); - void signalLibrarySaveClicked(); + /** + * @brief _showAll Do not use. + */ + void _setVisibilityForAll(bool visible); - private slots: - void slotRemoveClicked(); +signals: + void signalRemoveClicked(); + void signalHelpClicked(); + void signalLibraryLoadClicked(); + void signalLibrarySaveClicked(); - private: - const bool m_isTablet; +private slots: + void slotRemoveClicked(); - void setButtonsVisible(QPushButton* pb); +private: + const bool m_isTablet; - Ui::LtsDialogButtonBox* m_ui; + /** + * @brief setButtonVisible makes a QPushButton visible and also shows the horizontal line, etc. when it's first called (every button box is empty before one button was made visible) + * @param pb + */ + void setButtonsVisible(QPushButton *pb); + + Ui::LtsDialogButtonBox *m_ui; }; } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_helper.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_helper.cpp index 0323c9838..a21c85b41 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_helper.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_helper.cpp @@ -1,153 +1,180 @@ - +/** + * @RDE_HEADER@ + * Helper Class for LtsDialog - creates Dialog Button Box and Scroll Area automatically + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Mike Wille, SLSE, 2016-09-23 + * + */ #include "lts_dialog_helper.h" - #include "lts_dialog.h" #include "ui_lts_dialog_helper.h" -#include #include #include +#include + namespace LtsWidgets { class LDHScrollBar : public QScrollBar { - Q_OBJECT - public: - using QScrollBar::QScrollBar; + Q_OBJECT +public: + using QScrollBar::QScrollBar; - void showEvent(QShowEvent* e) override - { - QScrollBar::showEvent(e); - emit scrollbarVisiblityChanged(true); - } - - void hideEvent(QHideEvent* e) override - { - QScrollBar::hideEvent(e); - emit scrollbarVisiblityChanged(false); - } - - Q_SIGNALS: - void scrollbarVisiblityChanged(bool visible); + void showEvent(QShowEvent *e) override + { + QScrollBar::showEvent(e); + emit scrollbarVisiblityChanged(true); + } + void hideEvent(QHideEvent *e) override + { + QScrollBar::hideEvent(e); + emit scrollbarVisiblityChanged(false); + } +Q_SIGNALS: + void scrollbarVisiblityChanged(bool visible); }; -LtsDialogHelper::LtsDialogHelper(QWidget* parent) : QWidget(parent), m_ui(new Ui::LtsDialogHelper()), m_dialog(nullptr) + +LtsDialogHelper::LtsDialogHelper(QWidget *parent) + : QWidget(parent) + , m_ui(new Ui::LtsDialogHelper()) + , m_dialog(nullptr) { - m_ui->setupUi(this); - setAttribute(Qt::WA_DeleteOnClose); - auto hScroll = new LDHScrollBar(this); - auto vScroll = new LDHScrollBar(this); - m_ui->scrollArea->setHorizontalScrollBar(hScroll); - m_ui->scrollArea->setVerticalScrollBar(vScroll); - connect(hScroll, &LDHScrollBar::scrollbarVisiblityChanged, this, &LtsDialogHelper::onHScrollBarVisibilityChanged); - connect(vScroll, &LDHScrollBar::scrollbarVisiblityChanged, this, &LtsDialogHelper::onVScrollBarVisibilityChanged); + m_ui->setupUi(this); + setAttribute(Qt::WA_DeleteOnClose); + auto hScroll = new LDHScrollBar(this); + auto vScroll = new LDHScrollBar(this); + m_ui->scrollArea->setHorizontalScrollBar(hScroll); + m_ui->scrollArea->setVerticalScrollBar(vScroll); + connect(hScroll, &LDHScrollBar::scrollbarVisiblityChanged, + this, &LtsDialogHelper::onHScrollBarVisibilityChanged); + connect(vScroll, &LDHScrollBar::scrollbarVisiblityChanged, + this, &LtsDialogHelper::onVScrollBarVisibilityChanged); #ifdef TABLET_MODE - QList scrollWidgets = findChildren(); + QList scrollWidgets = findChildren(); - for (auto i = scrollWidgets.begin(); i != scrollWidgets.end(); ++i) - { - QWidget* widget = *i; + for (auto i = scrollWidgets.begin(); i != scrollWidgets.end(); ++i) + { + QWidget *widget = *i; - QVariant isConst = widget->property("const"); - if (isConst.isValid() && isConst.toBool()) - continue; + QVariant isConst = widget->property("const"); + if (isConst.isValid() && isConst.toBool()) + continue; - LtsWidgets::addTouchScroll(widget); - } + LtsWidgets::addTouchScroll(widget); + } #endif m_ui->buttonBox->setMinimumHeight(m_ui->buttonBox->sizeHint().height()); } + LtsDialogHelper::~LtsDialogHelper() { - m_ui->scrollArea->horizontalScrollBar()->disconnect(this); - m_ui->scrollArea->verticalScrollBar()->disconnect(this); - delete m_ui; + m_ui->scrollArea->horizontalScrollBar()->disconnect(this); + m_ui->scrollArea->verticalScrollBar()->disconnect(this); + delete m_ui; } -LtsDialogButtonBox* LtsDialogHelper::getButtonBox() + +LtsDialogButtonBox *LtsDialogHelper::getButtonBox() { - return m_ui->buttonBox; + return m_ui->buttonBox; } -void LtsDialogHelper::setDialog(LtsDialog* dialog) + +void LtsDialogHelper::setDialog(LtsDialog *dialog) { - if (m_dialog != nullptr) - return; + if (m_dialog != nullptr) // set dialog only one time + return; - m_dialog = dialog; - m_dialog->setContentsMargins(QMargins()); - if (m_dialog->layout()) - m_dialog->layout()->setContentsMargins(QMargins()); - m_ui->scrollArea->setWidget(m_dialog); + m_dialog = dialog; + m_dialog->setContentsMargins(QMargins()); + if (m_dialog->layout()) + m_dialog->layout()->setContentsMargins(QMargins()); + m_ui->scrollArea->setWidget(m_dialog); + //if (LtsDialog::plan_editor_compatibility) + { + connect(dialog, &LtsDialog::destroyed, this, [this]() { - connect(dialog, &LtsDialog::destroyed, this, [this]() { - m_dialog = nullptr; - deleteLater(); - }); - } + m_dialog = nullptr; + deleteLater(); + }); + } + +// connect(this, &LtsDialogHelper::signalSizeChanged, +// dialog, &LtsDialog::slotSizeChanged); } -LtsDialog* LtsDialogHelper::getDialog() +LtsDialog *LtsDialogHelper::getDialog() { - return m_dialog; + return m_dialog; } void LtsDialogHelper::retranslate() { - if (m_dialog == nullptr) - return; + if (m_dialog == nullptr) + return; - m_dialog->setContentsMargins(QMargins()); - if (m_dialog->layout()) - m_dialog->layout()->setContentsMargins(QMargins()); + m_dialog->setContentsMargins(QMargins()); + if (m_dialog->layout()) + m_dialog->layout()->setContentsMargins(QMargins()); - bool oldChangesFlag = m_dialog->m_changesMade; + bool oldChangesFlag = m_dialog->m_changesMade; - m_dialog->retranslate(); + // TODO: clear uiRequirements !! But tell devs first to move all uiReqs to retranslate() - if (oldChangesFlag) - m_dialog->slotChangesMade(); - else - m_dialog->resetChanges(); + m_dialog->retranslate(); + + if (oldChangesFlag) + m_dialog->slotChangesMade(); + else + m_dialog->resetChanges(); } -void LtsDialogHelper::resizeEvent(QResizeEvent* e) + +void LtsDialogHelper::resizeEvent(QResizeEvent *e) { - emit signalSizeChanged(e->size()); + emit signalSizeChanged(e->size()); } -void LtsDialogHelper::changeEvent(QEvent* e) + +void LtsDialogHelper::changeEvent(QEvent *e) { - QWidget::changeEvent(e); - if (e->type() == QEvent::LanguageChange) - retranslate(); + QWidget::changeEvent(e); + if (e->type() == QEvent::LanguageChange) + retranslate(); } + void LtsDialogHelper::onHScrollBarVisibilityChanged(bool visible) { - if (m_dialog == nullptr || !m_dialog->layout()) - return; + if (m_dialog == nullptr || !m_dialog->layout()) + return; - QMargins m = m_dialog->layout()->contentsMargins(); - m.setBottom(visible ? -1 : 0); - m_dialog->layout()->setContentsMargins(m); + QMargins m = m_dialog->layout()->contentsMargins(); + m.setBottom(visible ? -1 : 0); + m_dialog->layout()->setContentsMargins(m); } + void LtsDialogHelper::onVScrollBarVisibilityChanged(bool visible) { - if (m_dialog == nullptr || !m_dialog->layout()) - return; + if (m_dialog == nullptr || !m_dialog->layout()) + return; - QMargins m = m_dialog->layout()->contentsMargins(); - m.setRight(visible ? -1 : 0); - m_dialog->layout()->setContentsMargins(m); + QMargins m = m_dialog->layout()->contentsMargins(); + m.setRight(visible ? -1 : 0); + m_dialog->layout()->setContentsMargins(m); } -} // namespace LtsWidgets +} #include "lts_dialog_helper.moc" diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_helper.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_helper.h index 2981e5dab..80ec9dcfe 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_helper.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_helper.h @@ -1,50 +1,60 @@ - +/** + * @RDE_HEADER@ + * Helper Class for LtsDialog - creates Dialog Button Box and Scroll Area automatically + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Mike Wille, SLSE, 2016-09-23 + * + */ #pragma once -#include -#include + #include +#include + namespace Ui { class LtsDialogHelper; } + namespace LtsWidgets { class LtsDialogButtonBox; class LtsDialog; +/** + * @brief The LtsDialogHelper class => ***DO NOT USE***, so no export! + */ class LtsDialogHelper : public QWidget { - Q_OBJECT + Q_OBJECT - public: - explicit LtsDialogHelper(QWidget* parent = nullptr); - ~LtsDialogHelper(); +public: + explicit LtsDialogHelper(QWidget *parent = nullptr); + ~LtsDialogHelper(); - LtsDialogButtonBox* getButtonBox(); - void setDialog(LtsDialog* dialog); - LtsDialog* getDialog(); + LtsDialogButtonBox *getButtonBox(); + void setDialog(LtsDialog *dialog); + LtsDialog *getDialog(); + bool compare(const LtsDialog *dialog) const { return (dialog == m_dialog); } // to keep constness... + void retranslate(); - bool compare(const LtsDialog* dialog) const - { - return (dialog == m_dialog); - } +signals: + void signalSizeChanged(const QSize &size); - void retranslate(); +private: + void resizeEvent(QResizeEvent *e) override; + void changeEvent(QEvent *e) override; + void onHScrollBarVisibilityChanged(bool visible); + void onVScrollBarVisibilityChanged(bool visible); - signals: - void signalSizeChanged(const QSize& size); + Ui::LtsDialogHelper *m_ui; + LtsDialog *m_dialog; - private: - void resizeEvent(QResizeEvent* e) override; - void changeEvent(QEvent* e) override; - void onHScrollBarVisibilityChanged(bool visible); - void onVScrollBarVisibilityChanged(bool visible); - - Ui::LtsDialogHelper* m_ui; - LtsDialog* m_dialog; }; } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_drag_icon.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_drag_icon.cpp index 0280ed1f9..50e3a2e29 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_drag_icon.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_drag_icon.cpp @@ -1,483 +1,494 @@ - +/** +* @RDE_HEADER@ +* Draggable Icon with Text for Menus +* $Id$ +* $HeadURL$ +* $Author$ +*/ #include "lts_drag_icon.h" -#include -#include #include #include #include #include -#include #include -#include +#include +#include +#include #include #include -#include +#include +#include namespace LtsWidgets { class LtsToolButton : public QToolButton { - Q_OBJECT - public: - explicit LtsToolButton(QWidget* parent) - : QToolButton(parent), m_sameWidgetDrop(false), m_isDraggable(true), m_startPos(QPoint()) - { - setAutoFillBackground(false); - setToolButtonStyle(Qt::ToolButtonTextUnderIcon); - } + Q_OBJECT +public: + explicit LtsToolButton(QWidget *parent) + : QToolButton(parent) + , m_sameWidgetDrop(false) + , m_isDraggable(true) + , m_startPos(QPoint()) + { + setAutoFillBackground(false); + setToolButtonStyle(Qt::ToolButtonTextUnderIcon); + } - virtual ~LtsToolButton() = default; + virtual ~LtsToolButton() = default; - void mousePressEvent(QMouseEvent* event) override; - void mouseReleaseEvent(QMouseEvent* event) override; - void mouseMoveEvent(QMouseEvent* event) override; - void dragEnterEvent(QDragEnterEvent* event) override; + void mousePressEvent(QMouseEvent *event) override; + void mouseReleaseEvent(QMouseEvent *event) override; + void mouseMoveEvent(QMouseEvent *event) override; + void dragEnterEvent(QDragEnterEvent *event) override; + void setSameWidgetDrop(bool drop) { m_sameWidgetDrop = drop; } + bool sameWidgetDrop() const { return m_sameWidgetDrop; } + void setDraggable(bool isDraggable) { m_isDraggable = isDraggable; } + void dropEvent(QDropEvent *event) override + { + emit newDropEvent(event); + QToolButton::dropEvent(event); + } + void addMimeData(const QString &mimeType, const QByteArray &data); + bool removeMimeData(const QString &mimeType); + void removeAllMimeData() { m_mimeData.clear(); } - void setSameWidgetDrop(bool drop) - { - m_sameWidgetDrop = drop; - } +protected: + void initButton(); - bool sameWidgetDrop() const - { - return m_sameWidgetDrop; - } +signals: + void newDropEvent(QDropEvent *e); + void dropSuc(); - void setDraggable(bool isDraggable) - { - m_isDraggable = isDraggable; - } +private: + void performDrag(QMouseEvent *event); + bool m_sameWidgetDrop; + bool m_isDraggable; + QPoint m_startPos; + QMap m_mimeData; - void dropEvent(QDropEvent* event) override - { - emit newDropEvent(event); - QToolButton::dropEvent(event); - } - - void addMimeData(const QString& mimeType, const QByteArray& data); - bool removeMimeData(const QString& mimeType); - - void removeAllMimeData() - { - m_mimeData.clear(); - } - - protected: - void initButton(); - - signals: - void newDropEvent(QDropEvent* e); - void dropSuc(); - - private: - void performDrag(QMouseEvent* event); - bool m_sameWidgetDrop; - bool m_isDraggable; - QPoint m_startPos; - QMap m_mimeData; }; -LtsDragIcon::LtsDragIcon(QWidget* parent) - : QWidget(parent), m_lay(nullptr), m_toolButton(nullptr), m_icon(), m_dragLabel(new QLabel(this)), m_text(), - m_style(ButtonStyle::eAll), m_forceFixedSize(false), m_isDraggable(true), m_dropHandlerKey(0L), - m_buttonSize(ButtonSize::eDefault), m_showDragIcon(true) + + +LtsDragIcon::LtsDragIcon(QWidget *parent) + : QWidget(parent) + , m_lay(nullptr) + , m_toolButton(nullptr) + , m_icon() + , m_dragLabel(new QLabel(this)) + , m_text() + , m_style(ButtonStyle::eAll) + , m_forceFixedSize(false) + , m_isDraggable(true) + , m_dropHandlerKey(0L) + , m_buttonSize(ButtonSize::eDefault) + , m_showDragIcon(true) { - setAutoFillBackground(false); - initButton(); + setAutoFillBackground(false); + initButton(); } + void LtsDragIcon::setStyleToButton() { - if (nullptr == m_toolButton) - return; + if (nullptr == m_toolButton) return; - switch (m_style) - { - case ButtonStyle::eIconOnly: { - setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - m_toolButton->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); - setFixedSize(QSize(static_cast(m_buttonSize), static_cast(m_buttonSize))); - m_toolButton->setToolButtonStyle(Qt::ToolButtonIconOnly); - } - break; + switch (m_style) + { + case ButtonStyle::eIconOnly: + { + setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + m_toolButton->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); + setFixedSize(QSize(static_cast(m_buttonSize), static_cast(m_buttonSize))); + m_toolButton->setToolButtonStyle(Qt::ToolButtonIconOnly); + } break; - case ButtonStyle::eTextOnly: { - setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); - m_toolButton->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); - setFixedSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)); - m_toolButton->setToolButtonStyle(Qt::ToolButtonTextOnly); - layout()->setSizeConstraint(QLayout::SetDefaultConstraint); - } - break; + case ButtonStyle::eTextOnly: + { + setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); + m_toolButton->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); + setFixedSize( QSize(QWIDGETSIZE_MAX,QWIDGETSIZE_MAX) ); + m_toolButton->setToolButtonStyle(Qt::ToolButtonTextOnly); + layout()->setSizeConstraint( QLayout::SetDefaultConstraint ); + } break; - case ButtonStyle::eTextNextToIcon: { - setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); - m_toolButton->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); - setFixedSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)); - m_toolButton->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); - layout()->setSizeConstraint(QLayout::SetDefaultConstraint); - } - break; + case ButtonStyle::eTextNextToIcon: + { + setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); + m_toolButton->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); + setFixedSize( QSize(QWIDGETSIZE_MAX,QWIDGETSIZE_MAX) ); + m_toolButton->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); + layout()->setSizeConstraint( QLayout::SetDefaultConstraint ); + } break; + + default: break; + } + +} // void LtsDragIcon::setStyleToButton() - default: - break; - } -} void LtsDragIcon::initButton() { - setMinimumSize(static_cast(m_buttonSize), static_cast(m_buttonSize)); + setMinimumSize(static_cast(m_buttonSize), static_cast(m_buttonSize)); - delete m_toolButton; - delete m_lay; - delete layout(); + delete m_toolButton; + delete m_lay; + delete layout(); - m_toolButton = new LtsToolButton(this); - m_toolButton->setDraggable(m_isDraggable); - connect(m_toolButton, &LtsToolButton::clicked, this, &LtsDragIcon::clicked); - connect(m_toolButton, &LtsToolButton::toggled, this, &LtsDragIcon::toggled); - connect(m_toolButton, &LtsToolButton::newDropEvent, this, &LtsDragIcon::newDropEvent); - connect(m_toolButton, &LtsToolButton::dropSuc, this, &LtsDragIcon::dropSuc); + m_toolButton = new LtsToolButton(this); + m_toolButton->setDraggable(m_isDraggable); + connect(m_toolButton, &LtsToolButton::clicked, this, &LtsDragIcon::clicked); + connect(m_toolButton, &LtsToolButton::toggled, this, &LtsDragIcon::toggled); + connect(m_toolButton, &LtsToolButton::newDropEvent, this, &LtsDragIcon::newDropEvent); + connect(m_toolButton, &LtsToolButton::dropSuc, this, &LtsDragIcon::dropSuc); - m_toolButton->setIcon(modifyIcon(m_icon)); - m_toolButton->setText(m_text); - generateToolTip(); - m_toolButton->setIconSize(QSize(static_cast(m_buttonSize), static_cast(m_buttonSize))); + m_toolButton->setIcon(modifyIcon(m_icon)); + m_toolButton->setText(m_text); + generateToolTip(); + m_toolButton->setIconSize(QSize(static_cast(m_buttonSize), static_cast(m_buttonSize))); - QVBoxLayout* box = new QVBoxLayout(this); - box->setContentsMargins(0, 0, 0, 0); - box->setSpacing(0); - box->addWidget(m_toolButton); - this->setLayout(box); + QVBoxLayout *box = new QVBoxLayout(this); + box->setMargin(0); + box->setSpacing(0); + box->addWidget(m_toolButton); - m_toolButton->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); + this->setLayout(box); - if (m_forceFixedSize) - { - m_toolButton->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); - setFixedSize(QSize(static_cast(m_buttonSize), static_cast(m_buttonSize))); - } - else - { - m_toolButton->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); - setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); - } + m_toolButton->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); - setStyleToButton(); + if (m_forceFixedSize) + { + m_toolButton->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); + setFixedSize(QSize(static_cast(m_buttonSize), static_cast(m_buttonSize))); + } + else + { + m_toolButton->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); + setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); + } + + setStyleToButton(); } -void LtsDragIcon::addToButtonGroup(QButtonGroup* btnGrp, int btnGrpId) +void LtsDragIcon::addToButtonGroup(QButtonGroup *btnGrp, int btnGrpId) { - btnGrp->addButton(m_toolButton, btnGrpId); + btnGrp->addButton(m_toolButton, btnGrpId); } -void LtsDragIcon::setIcon(const QIcon& icon) + +void LtsDragIcon::setIcon(const QIcon &icon) { - m_icon = icon; - (m_toolButton) ? m_toolButton->setIcon(modifyIcon(m_icon)) : initButton(); + m_icon = icon; + (m_toolButton) ? m_toolButton->setIcon(modifyIcon(m_icon)) : initButton(); } -void LtsDragIcon::setMenu(QMenu* menu) + +void LtsDragIcon::setMenu(QMenu *menu) { - if (nullptr == m_toolButton) - initButton(); - m_toolButton->setMenu(menu); + if (nullptr == m_toolButton) + initButton(); + m_toolButton->setMenu(menu); } -QMenu* LtsDragIcon::menu() const +QMenu *LtsDragIcon::menu() const { - if (nullptr == m_toolButton) - return nullptr; + if (nullptr == m_toolButton) + return nullptr; - return m_toolButton->menu(); + return m_toolButton->menu(); } -void LtsDragIcon::setText(const QString& text) + +void LtsDragIcon::setText(const QString &text) { - m_text = text; - (m_toolButton) ? generateToolTip() : initButton(); + m_text = text; + (m_toolButton) ? generateToolTip() : initButton(); } -void LtsDragIcon::setContext(const QString& context) +void LtsDragIcon::setContext(const QString &context) { - m_context = context; - generateToolTip(); + m_context = context; + generateToolTip(); } void LtsDragIcon::generateToolTip() { - if (!m_toolButton || m_text.isEmpty()) - return; + if (!m_toolButton || m_text.isEmpty()) + return; - QString text(m_text); - if (!m_context.isEmpty()) - text.prepend(m_context + QLatin1String(" - ")); + QString text(m_text); + if (!m_context.isEmpty()) + text.prepend(m_context + QLatin1String(" - ")); - m_toolButton->setText(m_text); - m_toolButton->setToolTip(text); + m_toolButton->setText(m_text); + m_toolButton->setToolTip(text); } bool LtsDragIcon::isCheckable() { - return (m_toolButton) ? m_toolButton->isCheckable() : false; + return (m_toolButton) ? m_toolButton->isCheckable() : false; } void LtsDragIcon::setDraggable(bool draggable) { - m_isDraggable = draggable; - m_toolButton->setDraggable(m_isDraggable); + m_isDraggable = draggable; + m_toolButton->setDraggable(m_isDraggable); } void LtsDragIcon::setCheckable(bool checkable) { - m_toolButton->setCheckable(checkable); + m_toolButton->setCheckable(checkable); } bool LtsDragIcon::isChecked() const { - return (m_toolButton) ? m_toolButton->isChecked() : false; + return (m_toolButton) ? m_toolButton->isChecked() : false; } void LtsDragIcon::setChecked(bool checked) { - if (nullptr == m_toolButton) - initButton(); - m_toolButton->setChecked(checked); + if (nullptr == m_toolButton) + initButton(); + m_toolButton->setChecked(checked); } void LtsDragIcon::setSameWidgetDrop(bool drop) { - if (nullptr == m_toolButton) - initButton(); - m_toolButton->setSameWidgetDrop(drop); + if (nullptr == m_toolButton) + initButton(); + m_toolButton->setSameWidgetDrop(drop); } bool LtsDragIcon::sameWidgetDrop() const { - if (nullptr == m_toolButton) - return false; - return m_toolButton->sameWidgetDrop(); + if (nullptr == m_toolButton) + return false; + return m_toolButton->sameWidgetDrop(); } -void LtsDragIcon::addMimeData(const QString& mimeType, const QByteArray& data) +void LtsDragIcon::addMimeData(const QString &mimeType, const QByteArray &data) { - if (nullptr == m_toolButton) - initButton(); - m_toolButton->addMimeData(mimeType, data); + if (nullptr == m_toolButton) + initButton(); + m_toolButton->addMimeData(mimeType, data); } -bool LtsDragIcon::removeMimeData(const QString& mimeType) +bool LtsDragIcon::removeMimeData(const QString &mimeType) { - if (nullptr == m_toolButton) - initButton(); - return m_toolButton->removeMimeData(mimeType); + if (nullptr == m_toolButton) + initButton(); + return m_toolButton->removeMimeData(mimeType); } void LtsDragIcon::removeAllMimeData() { - if (nullptr == m_toolButton) - initButton(); - m_toolButton->removeAllMimeData(); + if (nullptr == m_toolButton) + initButton(); + m_toolButton->removeAllMimeData(); } void LtsDragIcon::setAcceptDrops(bool on) { - if (nullptr == m_toolButton) - initButton(); - m_toolButton->setAcceptDrops(on); + if (nullptr == m_toolButton) + initButton(); + m_toolButton->setAcceptDrops(on); } -void LtsDragIcon::dragEnterEvent(QDragEnterEvent* e) +void LtsDragIcon::dragEnterEvent(QDragEnterEvent *e) { - if (m_toolButton) - m_toolButton->dragEnterEvent(e); + if (m_toolButton) + m_toolButton->dragEnterEvent(e); } - -void LtsDragIcon::dropEvent(QDropEvent* e) +void LtsDragIcon::dropEvent(QDropEvent *e) { - QWidget::dropEvent(e); + QWidget::dropEvent(e); } void LtsDragIcon::setButtonStyle(ButtonStyle style) { - m_style = style; - setStyleToButton(); + m_style = style; + setStyleToButton(); } void LtsDragIcon::setIconSize(ButtonSize buttonSize) { - m_buttonSize = buttonSize; - (m_toolButton) ? m_toolButton->setIconSize(QSize(static_cast(m_buttonSize), static_cast(m_buttonSize))) - : initButton(); + m_buttonSize = buttonSize; + (m_toolButton) ? m_toolButton->setIconSize(QSize(static_cast(m_buttonSize), static_cast(m_buttonSize))) : initButton(); } void LtsDragIcon::setForceFixedSize(bool force) { - m_forceFixedSize = force; - initButton(); + m_forceFixedSize = force; + initButton(); } void LtsDragIcon::setButtonVisible(bool visible) { - if (nullptr == m_toolButton) - initButton(); - m_toolButton->setVisible(visible); + if (nullptr == m_toolButton) + initButton(); + m_toolButton->setVisible(visible); } bool LtsDragIcon::buttonVisible() const { - if (nullptr == m_toolButton) - return false; - return m_toolButton->isVisible(); + if (nullptr == m_toolButton) + return false; + return m_toolButton->isVisible(); } -void LtsDragIcon::setAction(QAction* action) +void LtsDragIcon::setAction(QAction *action) { - QIcon icon = action->icon(); - if (!icon.isNull()) - m_icon = icon; - m_toolButton->setDefaultAction(action); - this->setObjectName(action->objectName()); + QIcon icon = action->icon(); + if(!icon.isNull()) + m_icon = icon; + m_toolButton->setDefaultAction(action); + this->setObjectName(action->objectName()); } -void LtsDragIcon::changeEvent(QEvent* event) +void LtsDragIcon::changeEvent(QEvent *event) { - if (event->type() == QEvent::EnabledChange) - emit enabledChanged(isEnabled()); + if (event->type() == QEvent::EnabledChange) + emit enabledChanged(isEnabled()); } -void LtsToolButton::mousePressEvent(QMouseEvent* event) + + +void LtsToolButton::mousePressEvent(QMouseEvent *event) { - if (event->button() == Qt::LeftButton) - m_startPos = event->pos(); - QToolButton::mousePressEvent(event); + if (event->button() == Qt::LeftButton) + m_startPos = event->pos(); + QToolButton::mousePressEvent(event); } -void LtsToolButton::mouseReleaseEvent(QMouseEvent* event) + +void LtsToolButton::mouseReleaseEvent(QMouseEvent *event) { - QToolButton::mouseReleaseEvent(event); + QToolButton::mouseReleaseEvent(event); } -void LtsToolButton::mouseMoveEvent(QMouseEvent* event) +void LtsToolButton::mouseMoveEvent(QMouseEvent *event) { - if (!m_isDraggable) - return; - if (event->buttons() & Qt::LeftButton) + if (!m_isDraggable) + return; + if (event->buttons() & Qt::LeftButton) { + int distance = (event->pos() - m_startPos).manhattanLength(); + if (distance >= 5) { - int distance = (event->pos() - m_startPos).manhattanLength(); - if (distance >= 5) - { - this->setDown(false); - performDrag(event); - return; - } + this->setDown(false); + performDrag(event); + return; } - QToolButton::mouseMoveEvent(event); + } + QToolButton::mouseMoveEvent(event); } -void LtsToolButton::performDrag(QMouseEvent*) +void LtsToolButton::performDrag(QMouseEvent *) { - QWidget* item = this; - if (item) + QWidget *item = this; + if (item) + { + + LtsDragIcon *dragIcon = nullptr; + QString name; + + while (dragIcon == nullptr) { - - LtsDragIcon* dragIcon = nullptr; - QString name; - - while (dragIcon == nullptr) - { - if ((!item->objectName().isEmpty()) && (name.isNull())) - { - name = item->objectName(); - } - item = item->parentWidget(); - if (nullptr == item) - return; - dragIcon = dynamic_cast(item); - } - QMimeData* mimeData = new QMimeData(); - mimeData->setText(name); - for (auto it = m_mimeData.cbegin(); it != m_mimeData.cend(); ++it) - mimeData->setData(it.key(), it.value()); - - if (dragIcon->dropHandlerKey() != 0L) - { - QByteArray data = QByteArray(QByteArray::number(dragIcon->dropHandlerKey())); - mimeData->setData(QLatin1String("DropHandlerPtr"), data); - } - - QDrag* drag = new QDrag(item); - - drag->setMimeData(mimeData); - - QAction* action = defaultAction(); - - if ((action) && (dragIcon->showDragIcon())) - { - drag->setPixmap(action->icon().pixmap(16, 16)); - } - else - { - drag->setPixmap(dragIcon->icon().pixmap(16, 16)); - } - Qt::DropAction drop = drag->exec(Qt::CopyAction | Qt::MoveAction); - if (drop == Qt::MoveAction || drop == Qt::CopyAction) - emit dropSuc(); + if ((!item->objectName().isEmpty()) && (name.isNull())) + { + name = item->objectName(); + } + item = item->parentWidget(); + if (nullptr == item) return; // Huchhhhhhhh, that should never happen + dragIcon = dynamic_cast(item); } -} + QMimeData *mimeData = new QMimeData(); + mimeData->setText(name); + for(auto it = m_mimeData.cbegin(); it != m_mimeData.cend(); ++it) + mimeData->setData(it.key(), it.value()); -void LtsToolButton::dragEnterEvent(QDragEnterEvent* event) -{ - QWidget* source = qobject_cast(event->source()); - if (source && source != this) + + if (dragIcon->dropHandlerKey() != 0L) { - event->setDropAction(Qt::MoveAction); - event->accept(); + QByteArray data = QByteArray(QByteArray::number(dragIcon->dropHandlerKey())); + mimeData->setData(QLatin1String("DropHandlerPtr"),data); } - QWidget::dragEnterEvent(event); + + QDrag *drag = new QDrag(item); + + drag->setMimeData(mimeData); + + QAction *action = defaultAction(); + + if ((action) && (dragIcon->showDragIcon())) + { + drag->setPixmap(action->icon().pixmap(16,16) ); + } + else + { + drag->setPixmap(dragIcon->icon().pixmap(16, 16)); + } + Qt::DropAction drop = drag->exec(Qt::CopyAction | Qt::MoveAction); + if (drop == Qt::MoveAction || drop == Qt::CopyAction ) + emit dropSuc(); + } + } -void LtsToolButton::addMimeData(const QString& mimeType, const QByteArray& data) +void LtsToolButton::dragEnterEvent(QDragEnterEvent *event) { - m_mimeData.insert(mimeType, data); + QWidget *source = + qobject_cast(event->source()); + if (source && source != this) { + event->setDropAction(Qt::MoveAction); + event->accept(); + } + QWidget::dragEnterEvent(event); } -bool LtsToolButton::removeMimeData(const QString& mimeType) +void LtsToolButton::addMimeData(const QString &mimeType, const QByteArray &data) { - return (m_mimeData.remove(mimeType) > 0); + m_mimeData.insert(mimeType,data); +} + +bool LtsToolButton::removeMimeData(const QString &mimeType) +{ + return (m_mimeData.remove(mimeType) > 0); } #define SIZE 40 -QIcon LtsDragIcon::modifyIcon(const QIcon& icon) +QIcon LtsDragIcon::modifyIcon(const QIcon &icon) { - if (m_modification.isEmpty()) - return icon; + if (m_modification.isEmpty()) + return icon; - QPixmap iconImage(icon.pixmap(SIZE * 0.8, SIZE * 0.8)); - QPainter painter(&iconImage); + QPixmap iconImage(icon.pixmap(SIZE*0.8, SIZE*0.8)); + QPainter painter(&iconImage); - painter.save(); - painter.setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing | QPainter::SmoothPixmapTransform); - painter.setBrush(QColor("red")); - painter.setPen(QPen(QColor("red"), 3)); + painter.save(); + painter.setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing | QPainter::HighQualityAntialiasing | QPainter::SmoothPixmapTransform); + painter.setBrush(QColor("red")); + painter.setPen(QPen(QColor("red"), 3)); - QFont f; - f.setFamily(QStringLiteral("Monospace")); - f.setPointSize(12); - f.setBold(true); - painter.setFont(f); + QFont f; + f.setFamily(QStringLiteral("Monospace")); + f.setPointSize(12); + f.setBold(true); + painter.setFont(f); - painter.drawText(QRect(0, 0, 28, 28), m_modification); - painter.restore(); + painter.drawText(QRect(0, 0, 28, 28), m_modification); // TODO: working version of this: , QTextOption(Qt::AlignRight | Qt::AlignBottom)); + painter.restore(); - return iconImage; + return iconImage; } } // namespace LtsWidgets + #include "lts_drag_icon.moc" + diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_drag_icon.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_drag_icon.h index 9f59a00cc..c155551d8 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_drag_icon.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_drag_icon.h @@ -1,231 +1,339 @@ - +/** +* @RDE_HEADER@ +* Draggable Icon with Text for Menus +* $Id$ +* $HeadURL$ +* $Author$ +*/ #pragma once + #include "lts_base.h" #include "lts_drop_handler.h" #include "lts_widgets_export.h" -#include -#include #include +#include #include + class QButtonGroup; class QHBoxLayout; class QLabel; class QMenu; -namespace LtsWidgets -{ +namespace LtsWidgets { class LtsToolButton; +/** + @brief Tool button with drag & drop functionality + */ class LTSWIDGETS_EXPORT LtsDragIcon : public QWidget { - public: - Q_OBJECT - Q_PROPERTY(QString text READ text WRITE setText) - Q_PROPERTY(QString context READ context WRITE setContext) - Q_PROPERTY(QString identifier READ identifier WRITE setIdentifier) - Q_PROPERTY(QIcon icon READ icon WRITE setIcon) - Q_PROPERTY(LtsWidgets::Designer::ButtonSize eButtonSize READ iconSizeDesigner WRITE setIconSizeDesigner) - Q_PROPERTY(bool eForceFixedSize READ isForceFixedSize WRITE setForceFixedSize) - Q_PROPERTY(bool isCheckable READ isCheckable WRITE setCheckable) - Q_PROPERTY(bool isChecked READ isChecked WRITE setChecked) - Q_PROPERTY(bool showDragIcon READ showDragIcon WRITE setShowDragIcon) - Q_PROPERTY(bool isDraggable READ isDraggable WRITE setDraggable) +public: + Q_OBJECT + Q_PROPERTY(QString text READ text WRITE setText) + Q_PROPERTY(QString context READ context WRITE setContext) + Q_PROPERTY(QString identifier READ identifier WRITE setIdentifier) + Q_PROPERTY(QIcon icon READ icon WRITE setIcon) + Q_PROPERTY(LtsWidgets::Designer::ButtonSize eButtonSize READ iconSizeDesigner WRITE setIconSizeDesigner) + Q_PROPERTY(bool eForceFixedSize READ isForceFixedSize WRITE setForceFixedSize) + Q_PROPERTY(bool isCheckable READ isCheckable WRITE setCheckable) + Q_PROPERTY(bool isChecked READ isChecked WRITE setChecked) + Q_PROPERTY(bool showDragIcon READ showDragIcon WRITE setShowDragIcon) + Q_PROPERTY(bool isDraggable READ isDraggable WRITE setDraggable) - Q_PROPERTY(LtsWidgets::Designer::ButtonStyle eStyle READ buttonStyleDesigner WRITE setButtonStyleDesigner) - void setButtonStyleDesigner(Designer::ButtonStyle t) - { - setButtonStyle(static_cast(t)); - } + //last + Q_PROPERTY(LtsWidgets::Designer::ButtonStyle eStyle READ buttonStyleDesigner WRITE setButtonStyleDesigner) - Designer::ButtonStyle buttonStyleDesigner() const - { - return static_cast(buttonStyle()); - } - void setIconSizeDesigner(Designer::ButtonSize t) - { - setIconSize(static_cast(t)); - } + /** + * @brief Set the ButtonStyle in Designer + * @param ButtonStyle to define the possible IconStyles + */ + void setButtonStyleDesigner(Designer::ButtonStyle t) { setButtonStyle(static_cast(t)); } - Designer::ButtonSize iconSizeDesigner() const - { - return static_cast(iconSize()); - } + /** + * @brief ButtonStyle Getter for Designer + * @return the current ButtonStyle for the DragIcon in the designer + */ + Designer::ButtonStyle buttonStyleDesigner() const { return static_cast(buttonStyle()); } - public: - explicit LtsDragIcon(QWidget* parent); + /** + * @brief Set the ButtonSize in Designer + * @param ButtonSize + */ + void setIconSizeDesigner(Designer::ButtonSize t) { setIconSize(static_cast(t)); } - virtual ~LtsDragIcon() = default; + /** + * @brief OpenType Getter for Designer + * @return the current BUttonSize Value for the DragIcon in the designer + */ + Designer::ButtonSize iconSizeDesigner() const { return static_cast(iconSize()); } - void setMenu(QMenu* menu); +public: + /** + * @brief Constructor for LtsDragIcon + * @param parent for the Widget + */ + explicit LtsDragIcon(QWidget *parent); - QMenu* menu() const; + virtual ~LtsDragIcon() = default; - void setText(const QString& text); + /** + * @brief set a QMenu to the Button + * @param QMenu to show + */ + void setMenu(QMenu *menu); - QString text() const - { - return m_text; - } + /** + * @brief get QMenu from the Button + * @return QMenu or nullptr if no button or menu is defined + */ + QMenu* menu() const; - void setContext(const QString& context); + /** + * @brief set a text to the Button + * @param QString as text shown + */ + void setText(const QString &text); - QString context() const - { - return m_context; - } + /** + * @brief Returns the widget's text value + * @return Current text + */ + QString text() const { return m_text; } - void setCheckable(bool checkable); + /** + * @brief set a context to the Button + * @param QString as context shown + */ + void setContext(const QString &context); - bool isCheckable(); + /** + * @brief Returns the widget's context value + * @return Current context + */ + QString context() const { return m_context; } - void setDraggable(bool draggable); + /** + * @brief set if the Button should be checkable + * By default, the button is not checkable. + * @param new checkable state + */ + void setCheckable(bool checkable); - bool isDraggable() const - { - return m_isDraggable; - } + /** + * @brief Return if Button is checkable + * @return This property holds whether the button is checkable. + */ + bool isCheckable(); - void setChecked(bool checked); - bool isChecked() const; + /** + * @brief set if the Button should be draggable + * By default, the button is draggable. + * @param new dragabble state + */ + void setDraggable(bool draggable); - void setShowDragIcon(bool showDragIcon) - { - m_showDragIcon = showDragIcon; - } + /** + * @brief Return if Button is checkable + * @return This property holds whether the button is checkable. + */ + bool isDraggable() const { return m_isDraggable; } - bool showDragIcon() const - { - return m_showDragIcon; - } + /** + * @brief (un)check the Button + * Only checkable buttons can be checked. By default, the button is unchecked. + * @param new checked state + */ + void setChecked(bool checked); - void setSameWidgetDrop(bool drop); + /** + * @brief Return the current check state + * @return This property holds whether the button is checked. + */ + bool isChecked() const; - bool sameWidgetDrop() const; + /** + * @brief Use Icon / Default Icon when dragging + * By default, the icon is used. + * @param new checked state + */ + void setShowDragIcon(bool showDragIcon) { m_showDragIcon = showDragIcon; } + bool showDragIcon() const { return m_showDragIcon; } - void setButtonStyle(ButtonStyle style); + /** + * @brief set new the SameWidgetDrop State + * drag&drop property to allow sameWidgetDrops + * @param new drop state + */ + void setSameWidgetDrop(bool drop); - ButtonStyle buttonStyle() const - { - return m_style; - } + /** + * @brief get wether SameWidgetDrop is enabled + * @return the drop state + */ + bool sameWidgetDrop() const; - void setIconSize(ButtonSize buttonSize); + /** + * @brief Set the ButtonStyle in Code + * @param ButtonStyle to define the possible IconStyles + */ + void setButtonStyle(ButtonStyle style); - ButtonSize iconSize() const - { - return m_buttonSize; - } + /** + * @brief Returns the currently used ButtonStyle Value + * @return Current ButtonStyle + */ + ButtonStyle buttonStyle() const { return m_style; } - void setButtonVisible(bool visible); + /** + * @brief Set the ButtonSize in Code + * @param ButtonSize + */ + void setIconSize(ButtonSize buttonSize); - bool buttonVisible() const; + /** + * @brief Returns the current used ButtonSize Value + * @return Current ButtonSize + */ + ButtonSize iconSize() const { return m_buttonSize; } - void setIcon(const QIcon& icon); + /** + * @brief set new visibilty fo the Icon + * @param New visibilty + */ + void setButtonVisible(bool visible); - QIcon icon() const - { - return m_icon; - } + /** + * @brief set new visibilty fo the Icon + * @param New visibilty + */ + bool buttonVisible() const; - void setForceFixedSize(bool force); + /** + * @brief set Icon to the Button + * @param New QIcon to use + */ + void setIcon(const QIcon &icon); - bool isForceFixedSize() const - { - return m_forceFixedSize; - } + /** + * @brief Return the current used QIcon + * @return This property holds the current used QIcon. + */ + QIcon icon() const { return m_icon; } - void setAction(QAction* action); + /** + * @brief Set to Force the given IconSize and forbid resizing + * By default, the button resizes into given space + * @param bool to force the Icon to hold it's given + * IconSize even if the LayoutSystem provides more space to fill + */ + void setForceFixedSize(bool force); - void addToButtonGroup(QButtonGroup* btnGrp, int btnGrpId); + /** + * @brief Return the current ForeFixedSize value + * @return This property holds the set ForceFicedSize value + */ + bool isForceFixedSize() const { return m_forceFixedSize; } - void setDropHandlerKey(qulonglong key) - { - m_dropHandlerKey = key; - } + /** + * @brief set a QAction to the Button + * @param New QAction + * the new Action will override the old one and replaces + * the ObjectName with the new ActionName + */ + void setAction(QAction *action); - void addMimeData(const QString& mimeType, const QByteArray& data); - bool removeMimeData(const QString& mimeType); - void removeAllMimeData(); + /** + Adds dragButton to a button group + @param btnGrp button group to add dragButton + @param btnGrpId Button identifier in button group + */ + void addToButtonGroup(QButtonGroup *btnGrp, int btnGrpId); - void setAcceptDrops(bool on); + /** + * @brief Sets a dropHandler. The dropHandler must be allocated with new operator. The owner ship now has the LtsDragIcon. The LtsDragIcon calls delete in hier dtor + * @see LtsDropHandler + */ + void setDropHandlerKey(qulonglong key) { m_dropHandlerKey = key; } - qulonglong dropHandlerKey() const - { - return m_dropHandlerKey; - } + /** + * @brief Adds MimeData. + * This sets MimeData to the Drag Action + * @param QString with MimeType Description + * @param QByteArray with MimeData + */ + void addMimeData(const QString &mimeType, const QByteArray &data); + bool removeMimeData(const QString &mimeType); + void removeAllMimeData(); - void setIdentifier(const QString& id) - { - m_identifier = id; - } + /** + * @brief Sets the drop acceptance of the Icon + * @param bool value to set drop acceptance + */ + void setAcceptDrops(bool on); - QString identifier() const - { - return m_identifier; - } + qulonglong dropHandlerKey() const { return m_dropHandlerKey; } - void setModification(const QString& id) - { - m_modification = id; - setIcon(m_icon); - } + // Todo: Isn't this something like objectName? + void setIdentifier(const QString &id) { m_identifier = id; } + QString identifier() const { return m_identifier; } - QString modification() const - { - return m_modification; - } + void setModification(const QString &id) { m_modification = id; setIcon(m_icon); } + QString modification() const { return m_modification; } + void removeModification() { m_modification = QString(); setIcon(m_icon);} - void removeModification() - { - m_modification = QString(); - setIcon(m_icon); - } +signals: + /** + * @brief The Signal is emitted when the Button is activated + * (i.e. pressed down then released while the mouse cursor is inside the button) + * @param bool checked = false + */ + void clicked(); - signals: + /** + * @brief The Signal is emitted when the Button is toggled + * @param bool checked + */ + void toggled(bool); + void newDropEvent(QDropEvent *e); + void dropSuc(); - void clicked(); + void enabledChanged(bool); - void toggled(bool); - void newDropEvent(QDropEvent* e); - void dropSuc(); +protected: + void dragEnterEvent(QDragEnterEvent *e) override; + void dropEvent(QDropEvent *e) override; + void initButton(); - void enabledChanged(bool); +private: + void setStyleToButton(); + QIcon modifyIcon(const QIcon &icon); + void generateToolTip(); - protected: - void dragEnterEvent(QDragEnterEvent* e) override; - void dropEvent(QDropEvent* e) override; - void initButton(); +protected slots: + void changeEvent(QEvent *event) override; - private: - void setStyleToButton(); - QIcon modifyIcon(const QIcon& icon); - void generateToolTip(); - - protected slots: - void changeEvent(QEvent* event) override; - - private: - QHBoxLayout* m_lay; - LtsToolButton* m_toolButton; - QIcon m_icon; - QLabel* m_dragLabel; - QString m_text; - QString m_identifier; - QString m_modification; - ButtonStyle m_style; - bool m_forceFixedSize; - bool m_isDraggable; - qulonglong m_dropHandlerKey; - ButtonSize m_buttonSize; - bool m_showDragIcon; - QString m_context; +private: + QHBoxLayout *m_lay; + LtsToolButton *m_toolButton; + QIcon m_icon; + QLabel *m_dragLabel; + QString m_text; + QString m_identifier; + QString m_modification; + ButtonStyle m_style; + bool m_forceFixedSize; + bool m_isDraggable; + qulonglong m_dropHandlerKey; + ButtonSize m_buttonSize; + bool m_showDragIcon; + QString m_context; }; -} // namespace LtsWidgets +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_drop_handler.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_drop_handler.h index 5da8c6c29..52dd5103f 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_drop_handler.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_drop_handler.h @@ -1,22 +1,141 @@ - +/** +** +** @RDE_HEADER@ +** Virtual base class of a simple drop handler. +** $Id$ +** $HeadURL$ +** $Author$ +** +** ----------------------------------------------------------------------------------------------- +** +** Hardware-Environment: Intel-PC +** Software-Environment: Windows 7, Linux, Qt 5.4. ArcGIS 10.2.5 +** +** Language ........: C++ 11 +** +** ----------------------------------------------------------------------------------------------- +** +** Author ...........: Jörg Turla, SPD G, Tel. 3132 +** +** ----------------------------------------------------------------------------------------------- +** +** Notes .........: +** +** 18.12.2015, JT : First edition for use with Qt5 +** +** ----------------------------------------------------------------------------------------------- +*/ #pragma once + class QMimeData; + namespace LtsWidgets { + /** + @class LtsDropHandler pdrophandler.h + @brief Interface class to handle drop events of special mime data type. + @see SituationMap::Map, SituationMap::DropEventManager -class LtsDropHandler -{ - public: - LtsDropHandler() = default; - virtual ~LtsDropHandler() = default; + The LtsDropHandler class is an interface class to handle drop event for one type of mime data. It is used from DropEventManager to process drop events. + The DropEventManager will call the doDrop function to process events. The doDrop fuction has to be implemented in derived class. - LtsDropHandler(const LtsDropHandler&) = delete; - LtsDropHandler& operator=(const LtsDropHandler&) = delete; + Following example shows how to implement a drop handler. + + @code + + #include + + class DropCreatePolyLine : public LtsWidgets::LtsDropHandler + { + PlanEditor * m_planEditor; + PlanEditor::InternalData * m_planEditorInternal; + bool m_smooth; + + public: + + DropCreatePolyLine( PlanEditor * planEditor + , PlanEditor::InternalData * planEditorInternal + , bool smooth = false ) + : LtsWidgets::LtsDropHandler() + , m_planEditor(planEditor) + , m_planEditorInternal(planEditorInternal) + , m_smooth(smooth) {;} + + virtual ~DropCreatePolyLine() = default; + + void doDrop( int x, int y, const QMimeData * mimeData = nullptr) const override; + + }; // DropCreatePolyLine + + + void PlanEditor::installLineDropHandler( LtsWidgets::LtsDragIcon * dragIcon ) + { + qulonglong key = m_dropEventManager->add(new DropCreatePolyLine(this,m_internal)); + dragIcon->setDropHandlerKey( key ); + } // PlanEditor::installLineDropHandler( LtsWidgets::LtsDragIcon * dragIcon ) + + + void DropCreatePolyLine::doDrop( int x, int y, const QMimeData * mimeData ) const + { + SituationMap::Map * map; + SituationMap::RB::RubberbandMultiPointFeature * rubberband; + SituationMap::RB::RubberbandFactory & rbFactory; + + map = m_planEditorInternal->m_map; + rbFactory = map->rubberbandFactory(); + + if (m_smooth) rubberband = rbFactory.create(); + else rubberband = rbFactory.create(); + + if (rubberband != nullptr) + { + rubberband -> setAutoDelete( true ); + rubberband -> enableClosed( false ); + + uint dx = map->width() * 0.25; + uint dy = map->height() * 0.25; + + QVector lineCoordinates; + + lineCoordinates += map->viewPortWindowPointToGeoCoordinate(QPoint(x-dx,y-dy)); + lineCoordinates += map->viewPortWindowPointToGeoCoordinate(QPoint(x+dx,y+dy)); + + rubberband->setCoordinateVector( lineCoordinates ); + + QObject::connect( rubberband , &SituationMap::RB::Rubberband::apply + , m_planEditor, &PlanEditor::onPolylineCreate ); + QObject::connect( rubberband , &SituationMap::RB::Rubberband::abort + , m_planEditor, &PlanEditor::onRubberbandAbort ); + + } // DropCreatePolyLine::doDrop( int x, int y ) + + } // DropCreatePolyLine::doDrop( int x, int y ) const + + @endcode + */ + class LtsDropHandler + { + public: + + LtsDropHandler() = default; + virtual ~LtsDropHandler() = default; + + LtsDropHandler( const LtsDropHandler & ) = delete; + LtsDropHandler & operator = ( const LtsDropHandler & ) = delete; + + /** + Function to process drop events. + + @param x x coordinate of cursor position referred to widget pixel coordinates. + @param y y coordinate of cursor position referred to widget pixel coordinates. + @param mimeData Pointer to data to be dropped. + */ + virtual void doDrop( int x, int y, const QMimeData * mimeData ) const = 0; + + }; // class LtsDropHandler - virtual void doDrop(int x, int y, const QMimeData* mimeData) const = 0; -}; } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_elided_label.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_elided_label.cpp index 513cf6a1d..98eda69db 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_elided_label.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_elided_label.cpp @@ -1,55 +1,66 @@ - +/** + * @RDE_HEADER@ + * LtsWidget - a QLabel which elides the text if necessary + * $Id$ + * $HeadURL$ + * $Author$ + * Created by Christian Ehrlicher, NLE, 2018-12-17 + */ #include "lts_elided_label.h" #include #include + namespace LtsWidgets { void LtsElidedLabel::setElideMode(Qt::TextElideMode elideMode) { - m_elideMode = elideMode; - m_cachedText.clear(); - update(); + m_elideMode = elideMode; + m_cachedText.clear(); + update(); } -void LtsElidedLabel::resizeEvent(QResizeEvent* e) +void LtsElidedLabel::resizeEvent(QResizeEvent *e) { - QLabel::resizeEvent(e); - m_cachedText.clear(); + QLabel::resizeEvent(e); + m_cachedText.clear(); } -void LtsElidedLabel::paintEvent(QPaintEvent* e) +void LtsElidedLabel::paintEvent(QPaintEvent *e) { - if (m_elideMode == Qt::ElideNone) - return QLabel::paintEvent(e); + if (m_elideMode == Qt::ElideNone) + return QLabel::paintEvent(e); - updateCachedTexts(); - QLabel::setText(m_cachedElidedText); - QLabel::paintEvent(e); - QLabel::setText(m_cachedText); + updateCachedTexts(); + QLabel::setText(m_cachedElidedText); + QLabel::paintEvent(e); + QLabel::setText(m_cachedText); } void LtsElidedLabel::updateCachedTexts() { - - const auto txt = text(); - if (m_cachedText == txt) - return; - m_cachedText = txt; - const QFontMetrics fm(fontMetrics()); - m_cachedElidedText = fm.elidedText(text(), m_elideMode, width(), Qt::TextShowMnemonic); - if (!m_cachedText.isEmpty()) - { - const QString showFirstCharacter = m_cachedText.at(0) + QStringLiteral("..."); + // setText() is not virtual ... :/ + const auto txt = text(); + if (m_cachedText == txt) + return; + m_cachedText = txt; + const QFontMetrics fm(fontMetrics()); + m_cachedElidedText = fm.elidedText(text(), + m_elideMode, + width(), + Qt::TextShowMnemonic); + if (!m_cachedText.isEmpty()) + { + const QString showFirstCharacter = m_cachedText.at(0) + QStringLiteral("..."); #if QT_VERSION < QT_VERSION_CHECK(5, 11, 0) - const int width = fm.width(showFirstCharacter); + const int width = fm.width(showFirstCharacter); #else - const int width = fm.horizontalAdvance(showFirstCharacter); + const int width = fm.horizontalAdvance(showFirstCharacter); #endif - setMinimumWidth(width + 1); - } + setMinimumWidth(width + 1); + } } } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_elided_label.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_elided_label.h index e781cbc79..3424a914a 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_elided_label.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_elided_label.h @@ -1,40 +1,42 @@ - +/** + * @RDE_HEADER@ + * LtsWidget - a QLabel which elides the text if necessary + * $Id$ + * $HeadURL$ + * $Author$ + * Created by Christian Ehrlicher, NLE, 2018-12-17 + */ #pragma once -#include "lts_widgets_export.h" #include -#include +#include namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsElidedLabel : public QLabel { - Q_OBJECT - public: - Q_PROPERTY(Qt::TextElideMode ElideMode READ elideMode WRITE setElideMode) + Q_OBJECT +public: + Q_PROPERTY(Qt::TextElideMode ElideMode READ elideMode WRITE setElideMode) - using QLabel::QLabel; + using QLabel::QLabel; - void setElideMode(Qt::TextElideMode elideMode); + void setElideMode(Qt::TextElideMode elideMode); + Qt::TextElideMode elideMode() const { return m_elideMode; } - Qt::TextElideMode elideMode() const - { - return m_elideMode; - } +protected: + void paintEvent(QPaintEvent *e) override; + void resizeEvent(QResizeEvent *e) override; - protected: - void paintEvent(QPaintEvent* e) override; - void resizeEvent(QResizeEvent* e) override; +private: + void updateCachedTexts(); - private: - void updateCachedTexts(); - - private: - Qt::TextElideMode m_elideMode = Qt::ElideRight; - QString m_cachedElidedText; - QString m_cachedText; +private: + Qt::TextElideMode m_elideMode = Qt::ElideRight; + QString m_cachedElidedText; + QString m_cachedText; }; } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_events.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_events.cpp index bee3b1e21..5eab728c1 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_events.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_events.cpp @@ -1,4 +1,10 @@ - +/** +* @RDE_HEADER@ +* Events provided by LtsWidgets +* $Id$ +* $HeadURL$ +* $Author$ +*/ #include "lts_events.h" @@ -6,50 +12,52 @@ namespace LtsWidgets { QEvent::Type LtsLinkEvent::eventTypeId() { - static QEvent::Type sLinkEventId = QEvent::None; - if (sLinkEventId == QEvent::None) - sLinkEventId = static_cast(QEvent::registerEventType()); - return sLinkEventId; + static QEvent::Type sLinkEventId = QEvent::None; + if (sLinkEventId == QEvent::None) + sLinkEventId = static_cast(QEvent::registerEventType()); + return sLinkEventId; } QEvent::Type SaveImageEvent::saveImageEventId() { - static QEvent::Type sSaveImageEventId = QEvent::None; - if (sSaveImageEventId == QEvent::None) - sSaveImageEventId = static_cast(QEvent::registerEventType()); - return sSaveImageEventId; + static QEvent::Type sSaveImageEventId = QEvent::None; + if (sSaveImageEventId == QEvent::None) + sSaveImageEventId = static_cast(QEvent::registerEventType()); + return sSaveImageEventId; } QEvent::Type SetMarkerEvent::setMarkerEventId() { - static QEvent::Type sSetMarkerEventId = QEvent::None; - if (sSetMarkerEventId == QEvent::None) - sSetMarkerEventId = static_cast(QEvent::registerEventType()); - return sSetMarkerEventId; + static QEvent::Type sSetMarkerEventId = QEvent::None; + if (sSetMarkerEventId == QEvent::None) + sSetMarkerEventId = static_cast(QEvent::registerEventType()); + return sSetMarkerEventId; } QEvent::Type AddMarkerEvent::addMarkerEventId() { - static QEvent::Type sAddMarkerEventId = QEvent::None; - if (sAddMarkerEventId == QEvent::None) - sAddMarkerEventId = static_cast(QEvent::registerEventType()); - return sAddMarkerEventId; + static QEvent::Type sAddMarkerEventId = QEvent::None; + if (sAddMarkerEventId == QEvent::None) + sAddMarkerEventId = static_cast(QEvent::registerEventType()); + return sAddMarkerEventId; } QEvent::Type AddSnapshotEvent::addSnapshotEventId() { - static QEvent::Type eventId = QEvent::None; - if (eventId == QEvent::None) - eventId = static_cast(QEvent::registerEventType()); - return eventId; + static QEvent::Type eventId = QEvent::None; + if (eventId == QEvent::None) + eventId = static_cast(QEvent::registerEventType()); + return eventId; } QEvent::Type SaveSnapshotEvent::saveSnapshotEventId() { - static QEvent::Type eventId = QEvent::None; - if (eventId == QEvent::None) - eventId = static_cast(QEvent::registerEventType()); - return eventId; + static QEvent::Type eventId = QEvent::None; + if (eventId == QEvent::None) + eventId = static_cast(QEvent::registerEventType()); + return eventId; } + + } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_events.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_events.h index 6bf2d678b..d4c05a960 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_events.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_events.h @@ -1,121 +1,99 @@ - +/** +* @RDE_HEADER@ +* Events provided by LtsWidgets +* $Id$ +* $HeadURL$ +* $Author$ +*/ #pragma once #include "lts_widgets_export.h" #include -#include #include #include -#include #include +#include + namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsLinkEvent : public QEvent { - public: - explicit LtsLinkEvent(QUrl url, QWidget* sourceBaseLayoutWidget) - : QEvent(eventTypeId()), m_url(std::move(url)), m_sourceBaseLayoutWidget(sourceBaseLayoutWidget) - { - } +public: + explicit LtsLinkEvent(QUrl url, QWidget *sourceBaseLayoutWidget) + : QEvent(eventTypeId()) + , m_url(std::move(url)) + , m_sourceBaseLayoutWidget(sourceBaseLayoutWidget) + {} - static QEvent::Type eventTypeId(); - - QWidget* sourceBaseLayoutWidget() const - { - return m_sourceBaseLayoutWidget.data(); - } - - QUrl url() const - { - return m_url; - } - - private: - QUrl m_url; - QPointer m_sourceBaseLayoutWidget; + static QEvent::Type eventTypeId(); + QWidget *sourceBaseLayoutWidget() const { return m_sourceBaseLayoutWidget.data(); } + QUrl url() const { return m_url; } +private: + QUrl m_url; + QPointer m_sourceBaseLayoutWidget; }; class LTSWIDGETS_EXPORT SaveImageEvent : public QEvent { - public: - SaveImageEvent(QWidget* w, QPixmap&& pm) : QEvent(saveImageEventId()), m_widget(w), m_pix(std::move(pm)) {} +public: + SaveImageEvent(QWidget *w, QPixmap &&pm) + : QEvent(saveImageEventId()), m_widget(w), m_pix(std::move(pm)) + {} - const QPixmap& pixmap() const - { - return m_pix; - } - - QWidget* widget() const - { - return m_widget.data(); - } - - static QEvent::Type saveImageEventId(); - - private: - QPointer m_widget; - QPixmap m_pix; + const QPixmap &pixmap() const { return m_pix; } + QWidget *widget() const { return m_widget.data(); } + static QEvent::Type saveImageEventId(); +private: + QPointer m_widget; + QPixmap m_pix; }; class LTSWIDGETS_EXPORT AddMarkerEvent : public QEvent { - public: - AddMarkerEvent() : QEvent(addMarkerEventId()) {} - - static QEvent::Type addMarkerEventId(); +public: + AddMarkerEvent() + : QEvent(addMarkerEventId()) + {} + static QEvent::Type addMarkerEventId(); }; class LTSWIDGETS_EXPORT SetMarkerEvent : public QEvent { - public: - SetMarkerEvent(const QString& description) : QEvent(setMarkerEventId()), m_description(description) {} - - const QString& getDescription() const - { - return m_description; - } - - void setDescription(const QString& description) - { - m_description = description; - } - - static QEvent::Type setMarkerEventId(); - - private: - QString m_description; +public: + SetMarkerEvent(const QString &description) + : QEvent(setMarkerEventId()), m_description(description) + {} + const QString &getDescription() const { return m_description; } + void setDescription(const QString &description) { m_description = description; } + static QEvent::Type setMarkerEventId(); +private: + QString m_description; }; class LTSWIDGETS_EXPORT AddSnapshotEvent : public QEvent { - public: - AddSnapshotEvent() : QEvent(addSnapshotEventId()) {} - - static QEvent::Type addSnapshotEventId(); +public: + AddSnapshotEvent() + : QEvent(addSnapshotEventId()) + {} + static QEvent::Type addSnapshotEventId(); }; class LTSWIDGETS_EXPORT SaveSnapshotEvent : public QEvent { - public: - SaveSnapshotEvent(const QString& description) : QEvent(saveSnapshotEventId()), m_description(description) {} - - const QString& getDescription() const - { - return m_description; - } - - void setDescription(const QString& description) - { - m_description = description; - } - - static QEvent::Type saveSnapshotEventId(); - - private: - QString m_description; +public: + SaveSnapshotEvent(const QString &description) + : QEvent(saveSnapshotEventId()), m_description(description) + {} + const QString &getDescription() const { return m_description; } + void setDescription(const QString &description) { m_description = description; } + static QEvent::Type saveSnapshotEventId(); +private: + QString m_description; }; + } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_frameless_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_frameless_dialog.cpp index 8c38ebe1b..b383d66df 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_frameless_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_frameless_dialog.cpp @@ -1,126 +1,159 @@ - +/** +* @RDE_HEADER@ +* FrameLess Dialog with alternatie basecolor +* $Id$ +* $HeadURL$ +* $Author$ +* +* Created by Mike Wille, SLSE, 2016-03-09 +*/ #include "lts_frameless_dialog.h" #include #include -#include -#include -#include -#include -#include #include +#include +#include +#include +#include +#include #include + namespace LtsWidgets { -LtsFramelessDialog::LtsFramelessDialog(QWidget* parent, const Behaviour& behaviour) : QDialog(parent) +LtsFramelessDialog::LtsFramelessDialog(QWidget *parent, const Behaviour &behaviour) + : QDialog(parent) { + // Qt-Bug? Qt::FramelessWindowHint in the underlying windows results in + // mapToGlobal(QPoint(0,0)) == QPoint(0,0) when a popup window is show on top of it + Qt::WindowFlags wf; // TODO: FIX WM AFTER FAT!! = Qt::FramelessWindowHint; // make frameless, composite manager drops the shadow + // frameless dialogs cannot have (completety working) children dialogs => frames 4 fat - Qt::WindowFlags wf; - - switch (behaviour) + switch (behaviour) + { + case Behaviour::Modal: { - case Behaviour::Modal: { #ifndef TABLET_MODE - setModal(true); - wf |= Qt::Dialog; + setModal(true); + wf |= Qt::Dialog; #else - wf |= Qt::Window; + wf |= Qt::Window; #endif - wf |= Qt::WindowStaysOnTopHint; - break; - } - - case Behaviour::Popup: - wf |= Qt::Popup; - break; + wf |= Qt::WindowStaysOnTopHint; + break; } - setWindowFlags(wf); + case Behaviour::Popup: + wf |= Qt::Popup; + break; + } - QTimer* t = new QTimer(this); - t->setInterval(250); - connect(t, &QTimer::timeout, this, [this]() { - QSize s = size(); - setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, s, screenRectFromPoint(QCursor::pos()))); - }); + setWindowFlags(wf); + + + QTimer *t = new QTimer(this); + t->setInterval(250); + connect(t, &QTimer::timeout, + this, [this]() + { + //qWarning() << "my pos" << QCursor::pos(); + //qWarning() << "my screen rect" << screenRectFromPoint(QCursor::pos()); + + QSize s = size(); + setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, s, screenRectFromPoint(QCursor::pos()))); + }); + //t->start(); TODO: impl this! } -LtsFramelessDialog::~LtsFramelessDialog() {} -QRect LtsFramelessDialog::screenRectFromPoint(const QPoint& pos) const +LtsFramelessDialog::~LtsFramelessDialog() { - const auto screens = QGuiApplication::screens(); - for (QScreen* screen : screens) - { - QRect s = screen->geometry().adjusted(-50, -50, 50, 50); - bool contains = s.contains(pos); - - if (contains) - return screen->geometry(); - } - - return QRect(); } -void LtsFramelessDialog::showEvent(QShowEvent* event) + +QRect LtsFramelessDialog::screenRectFromPoint(const QPoint &pos) const { - QDialog::showEvent(event); - QTimer::singleShot(0, this, &LtsFramelessDialog::onUpdateGeometry); + const auto screens = QGuiApplication::screens(); + for (QScreen *screen : screens) + { + QRect s = screen->geometry().adjusted(-50, -50, 50, 50); // graceful offset for desktop managers + + bool contains = s.contains(pos); + + //qWarning() << "screen" << s << " widget" << w << " contains?" << contains; + //qWarning() << "screen: x" << s.x() << "y" << s.y() << "h" << s.height() << "w" << s.width(); + //qWarning() << "widget: x" << w.x() << "y" << w.y() << "h" << w.height() << "w" << w.width(); + + if (contains) + return screen->geometry(); + } + + return QRect(); +} + + +void LtsFramelessDialog::showEvent(QShowEvent *event) +{ + QDialog::showEvent(event); + QTimer::singleShot(0, this, &LtsFramelessDialog::onUpdateGeometry); + #ifdef TABLET_MODE - QList scrollWidgets = findChildren(); + QList scrollWidgets = findChildren(); - for (auto i = scrollWidgets.begin(); i != scrollWidgets.end(); ++i) - { - QWidget* widget = *i; + for (auto i = scrollWidgets.begin(); i != scrollWidgets.end(); ++i) + { + QWidget *widget = *i; - QVariant isConst = widget->property("const"); - if (isConst.isValid() && isConst.toBool()) - continue; + QVariant isConst = widget->property("const"); + if (isConst.isValid() && isConst.toBool()) + continue; - addTouchScroll(widget); - } + addTouchScroll(widget); + } #endif } -void LtsFramelessDialog::addTouchScroll(QWidget* widget) -{ - if (!widget) - return; - widget->setAttribute(Qt::WA_AcceptTouchEvents); - QScrollArea* sca = qobject_cast(widget); - if (sca) - { - QScroller::grabGesture(sca->viewport(), QScroller::LeftMouseButtonGesture); - return; - } +void LtsFramelessDialog::addTouchScroll(QWidget *widget) +{ + if (!widget) + return; + widget->setAttribute(Qt::WA_AcceptTouchEvents); + + QScrollArea *sca = qobject_cast(widget); + if (sca) + { + QScroller::grabGesture(sca->viewport(), QScroller::LeftMouseButtonGesture); + return; + } } + void LtsFramelessDialog::onUpdateGeometry() { - QRect r; - QWidget* p = parentWidget(); + QRect r; + QWidget *p = parentWidget(); - if (p) - { - QWidget* window = p->window(); - QPoint global = window->mapToGlobal(QPoint(0, 0)); - QSize size = window->size(); + if (p) // get the parent's window and center the dialog on the center of the parent's window + { + QWidget *window = p->window(); + QPoint global = window->mapToGlobal(QPoint(0,0)); + QSize size = window->size(); - r = QRect(global, size); - } - else - { - r = QGuiApplication::primaryScreen()->geometry(); - } + r = QRect(global, size); + } + else // no parent - no alignment! + { + r = QGuiApplication::primaryScreen()->geometry(); + } - QSize s = size(); - setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, s, r)); + QSize s = size(); + setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, s, r)); } } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_frameless_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_frameless_dialog.h index 39232eb74..34815d78d 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_frameless_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_frameless_dialog.h @@ -1,37 +1,61 @@ - +/** +* @RDE_HEADER@ +* FrameLess Dialog with alternatie basecolor +* $Id$ +* $HeadURL$ +* $Author$ +* +* Created by Mike Wille, SLSE, 2016-03-09 +*/ #pragma once + +#include + #include "lts_base.h" #include "lts_widgets_export.h" -#include -#include namespace LtsWidgets { - -enum class Behaviour { - Popup = 0, - Modal, +/** + * @brief The Behaviour enum describes how the FramelessDialog handles user input while shown. + */ +enum class Behaviour +{ + Popup = 0, // a mouse click on any surface other than this dialog will close/hide this dialog + Modal, // disallow any input, but do not block the program execution (does not apply when exec() is used), and avoid rejecting when dialog is modal }; -class LTSWIDGETS_EXPORT LtsFramelessDialog : public QDialog + +/** + * @brief The LtsFramelessDialog class creates a Popup-Dialog, without a frame, but with a shadow as border. This Popup-Dialog is centered in the window . + * The purpose is to cover the window the user is working with, to interupt the user with a message he has to attend first before continuing work. + * LtsFramelessDialog is actually a QWidget as this class uses a QWidget which casts a shadow and lays itself on it. Sorry. + * The Application must never be interrupted, so there is no exec(). + */ +class LTSWIDGETS_EXPORT LtsFramelessDialog : public QDialog // TODO: many methods use this to show messages, use LtsMessageDialog instead { - Q_OBJECT + Q_OBJECT - public: - explicit LtsFramelessDialog(QWidget* parent = nullptr, const Behaviour& behaviour = Behaviour::Popup); - virtual ~LtsFramelessDialog(); +public: + /** + * @brief LtsFramelessDialog + * @param parent the widget to be covered + * @param behaviour see enum LtsWidgets::Behaviour - only affects this Dialog when currently shown + */ + explicit LtsFramelessDialog(QWidget *parent = nullptr, const Behaviour &behaviour = Behaviour::Popup); + virtual ~LtsFramelessDialog(); - public Q_SLOTS: - void onUpdateGeometry(); +public Q_SLOTS: + void onUpdateGeometry(); +private: + QRect screenRectFromPoint(const QPoint &pos) const; + void addTouchScroll(QWidget *widget); - private: - QRect screenRectFromPoint(const QPoint& pos) const; - void addTouchScroll(QWidget* widget); +protected: + void showEvent(QShowEvent *event) override; - protected: - void showEvent(QShowEvent* event) override; }; } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_global_wait_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_global_wait_dialog.cpp index f8f4685a8..91b5c8eff 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_global_wait_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_global_wait_dialog.cpp @@ -1,195 +1,225 @@ - +// TODO: hdr #include "lts_global_wait_dialog.h" - +#include "lts_progress_dialog_helper.h" +#include "lts_overlay_loading.h" #include "lts_dialog.h" #include "lts_frameless_dialog.h" -#include "lts_overlay_loading.h" -#include "lts_progress_dialog_helper.h" #include #include +//#include #ifdef Q_OS_UNIX -#include -#include -#include +#include // backtrace(..) +#include // dladdr(..) +#include // demangle #endif + namespace LtsWidgets { LtsGlobalWaitDialog::~LtsGlobalWaitDialog() { - delete m_progressDialog; + delete m_progressDialog; } + LtsGlobalWaitDialog::LtsGlobalWaitDialog() - : m_waitingCount(0), m_visible(true), m_progressDialog(new LtsProgressDialogHelper(nullptr)), - m_hideTimer(new QTimer(this)) + : m_waitingCount(0) + , m_visible(true) + , m_progressDialog(new LtsProgressDialogHelper(nullptr)) + , m_hideTimer(new QTimer(this)) // avoids blinking windows by waiting a little until the wait window will be hidden { - m_hideTimer->setSingleShot(true); - m_hideTimer->setInterval(500); - connect(m_hideTimer, &QTimer::timeout, this, &LtsGlobalWaitDialog::hideIt); + m_hideTimer->setSingleShot(true); + m_hideTimer->setInterval(500); + connect(m_hideTimer, &QTimer::timeout, + this, &LtsGlobalWaitDialog::hideIt); } + void LtsGlobalWaitDialog::unarm() { - m_armed = false; - hideIt(); + m_armed = false; + hideIt(); // force hide it (don't worry, does nothing if now shown) } + void LtsGlobalWaitDialog::rearm() { - m_armed = true; - setVisible(true); + m_armed = true; + setVisible(true); // show again (if some component is still waiting) } + void LtsGlobalWaitDialog::setVisible(bool visible) { - if (m_waitingCount > 0 && visible) - showIt(); + if (m_waitingCount > 0 && visible) + showIt(); - if (m_waitingCount < 1 && !visible) - hideIt(); + if (m_waitingCount < 1 && !visible) + hideIt(); } + void LtsGlobalWaitDialog::showIt() { - if (m_progressDialog->isShown()) - return; + if (m_progressDialog->isShown()) + return; - m_hideTimer->stop(); - if (m_armed) - { - m_progressDialog->slotShowWaitForReplyWindow(); - } + m_hideTimer->stop(); + if (m_armed) + { + m_progressDialog->slotShowWaitForReplyWindow(); + } } + void LtsGlobalWaitDialog::hideIt() { - if (!m_progressDialog->isShown()) - return; + if (!m_progressDialog->isShown()) + return; - m_hideTimer->stop(); - m_progressDialog->slotStopWaitForReplyWindow(); + m_hideTimer->stop(); + m_progressDialog->slotStopWaitForReplyWindow(); } + void bt() { #ifdef Q_OS_UNIX - void* callstack[128]; - const int nMaxFrames = sizeof(callstack) / sizeof(callstack[0]); - int nFrames = backtrace(callstack, nMaxFrames); - char** symbols = backtrace_symbols(callstack, nFrames); + void *callstack[128]; + const int nMaxFrames = sizeof(callstack) / sizeof(callstack[0]); + int nFrames = backtrace(callstack, nMaxFrames); + char **symbols = backtrace_symbols(callstack, nFrames); - for (int i = 1; i < nFrames; i++) + for (int i = 1; i < nFrames; i++) + { + QString address(QStringLiteral("0x%1").arg(QString::number(*(quintptr *)callstack[i], 16))); + QString function; + int offset = -1; // aka. invalid + + Dl_info info; + if (dladdr(callstack[i], &info) && info.dli_sname) { - QString address(QStringLiteral("0x%1").arg(QString::number(*(quintptr*)callstack[i], 16))); - QString function; - int offset = -1; + char *demangled = nullptr; + int status = -1; + if (info.dli_sname[0] == '_') + demangled = abi::__cxa_demangle(info.dli_sname, nullptr, 0, &status); - Dl_info info; - if (dladdr(callstack[i], &info) && info.dli_sname) - { - char* demangled = nullptr; - int status = -1; - if (info.dli_sname[0] == '_') - demangled = abi::__cxa_demangle(info.dli_sname, nullptr, 0, &status); + function = QString::fromUtf8(status == 0 ? demangled : info.dli_sname == 0 ? symbols[i] : info.dli_sname); + offset = (char *)callstack[i] - (char *)info.dli_saddr; - function = QString::fromUtf8(status == 0 ? demangled : info.dli_sname == 0 ? symbols[i] : info.dli_sname); - offset = (char*)callstack[i] - (char*)info.dli_saddr; - - free(demangled); - } - else - { - function = QString::fromUtf8(symbols[i]); - } + free(demangled); + } + else + { + function = QString::fromUtf8(symbols[i]); } - free(symbols); + //qWarning() << "frame" << i << address << function << offset; + } + free(symbols); + +// if (nFrames == nMaxFrames) +// qWarning() << "[BACKTRACE TRUNCATED]"; #endif } -void LtsGlobalWaitDialog::wait(QWidget* parent, const QString& customText) + +void LtsGlobalWaitDialog::wait(QWidget *parent, const QString &customText) { - m_progressDialog->setParentWidget(parent); - if (m_waitingCount < 1 && m_visible) - showIt(); + m_progressDialog->setParentWidget(parent); + if (m_waitingCount < 1 && m_visible) // nothing is waiting + showIt(); - setCustomText(customText); + setCustomText(customText); - m_waitingCount++; + m_waitingCount++; // count even if not visible ! + + //qWarning() << "LtsGlobalWaitDialog ++" << m_waitingCount; + + //bt(); } -void LtsGlobalWaitDialog::setCustomText(const QString& customText) + +void LtsGlobalWaitDialog::setCustomText(const QString &customText) { - m_progressDialog->setCustomText(customText); + m_progressDialog->setCustomText(customText); } + void LtsGlobalWaitDialog::done() { - if (m_waitingCount == 0) - { + if (m_waitingCount == 0) + { + //qWarning() << "LtsGlobalWaitDialog: called done() while there is nothing waiting!"; + m_hideTimer->start(); + return; + } - m_hideTimer->start(); - return; - } + Q_ASSERT(m_waitingCount > 0); - Q_ASSERT(m_waitingCount > 0); + m_waitingCount--; + //qWarning() << "LtsGlobalWaitDialog --" << m_waitingCount; - m_waitingCount--; - - if (m_waitingCount == 0) - m_hideTimer->start(); + if (m_waitingCount == 0) // no more waiting classes + m_hideTimer->start(); } -static LtsGlobalWaitDialog* s_gwdInstance = nullptr; - +static LtsGlobalWaitDialog *s_gwdInstance = nullptr; void LtsGlobalWaitDialog::cleanupGwdInstance() { - delete s_gwdInstance; - s_gwdInstance = nullptr; + delete s_gwdInstance; + s_gwdInstance = nullptr; } -LtsGlobalWaitDialog* LtsGlobalWaitDialog::getInstance() +LtsGlobalWaitDialog *LtsGlobalWaitDialog::getInstance() { - if (!s_gwdInstance) - { - s_gwdInstance = new LtsGlobalWaitDialog; - qAddPostRoutine(&LtsGlobalWaitDialog::cleanupGwdInstance); - } - return s_gwdInstance; + if (!s_gwdInstance) + { + s_gwdInstance = new LtsGlobalWaitDialog; + qAddPostRoutine(&LtsGlobalWaitDialog::cleanupGwdInstance); + } + return s_gwdInstance; } } // namespace LtsWidgets -Waiter::Waiter(const QString& customText) + +/// Waiter +Waiter::Waiter(const QString &customText) { - LtsWidgets::LtsGlobalWaitDialog::getInstance()->wait(nullptr, customText); + LtsWidgets::LtsGlobalWaitDialog::getInstance()->wait(nullptr, customText); } -Waiter::Waiter(LtsWidgets::LtsDialog* parent, const QString& customText) : m_parent(parent) + +Waiter::Waiter(LtsWidgets::LtsDialog *parent, const QString &customText) + : m_parent(parent) { - m_oldClosableState = m_parent->isClosable(); - m_parent->setClosable(false); - m_parent->setCurrentlyBlocking(true); - auto* wait = new LtsWidgets::LtsOverlayLoading; - wait->setText(customText.isEmpty() ? QObject::tr("Waiting for server reply...") : customText); - m_parent->setOverlay(wait); - m_loadingOverlay = wait; + m_oldClosableState = m_parent->isClosable(); + m_parent->setClosable(false); + m_parent->setCurrentlyBlocking(true); + auto *wait = new LtsWidgets::LtsOverlayLoading; + wait->setText(customText.isEmpty() ? QObject::tr("Waiting for server reply...") : customText); + m_parent->setOverlay(wait); + m_loadingOverlay = wait; } + Waiter::~Waiter() { - if (m_loadingOverlay == nullptr) - { - LtsWidgets::LtsGlobalWaitDialog::getInstance()->done(); - return; - } + if (m_loadingOverlay == nullptr) + { + LtsWidgets::LtsGlobalWaitDialog::getInstance()->done(); + return; + } - m_parent->setClosable(m_oldClosableState); - m_parent->setCurrentlyBlocking(false); - m_loadingOverlay->deleteLater(); + m_parent->setClosable(m_oldClosableState); + m_parent->setCurrentlyBlocking(false); + m_loadingOverlay->deleteLater(); } + + + diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_global_wait_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_global_wait_dialog.h index 2b7c3b379..0cbf40ca6 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_global_wait_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_global_wait_dialog.h @@ -1,4 +1,12 @@ - +/** + * @RDE_HEADER@ + * Frameless Dialog, modal, exists exactly once per - a global/static wait dlg which counts for all compontens that are waiting for their operation to be done but don't want to own a progress dialog ! + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Mike Wille, SLSE, 2017-03-17 + */ #pragma once @@ -6,62 +14,64 @@ #include + class QTimer; class QWidget; + namespace LtsWidgets { class LtsDialog; class LtsOverlayLoading; class LtsProgressDialogHelper; - +/** + * @brief The LtsGlobalWaitDialog class is a global/static wait dlg which counts for all compontens that are waiting for their operation to be done but don't want to own a progress dialog ! + */ class LTSWIDGETS_EXPORT LtsGlobalWaitDialog : public QObject { - Q_OBJECT + Q_OBJECT - public: - static LtsGlobalWaitDialog* getInstance(); - void wait(QWidget* parent, const QString& customText = QString()); +public: + static LtsGlobalWaitDialog* getInstance(); + void wait(QWidget *parent, const QString &customText = QString()); // shows the Progress Dialog + void wait(const QString &customText = QString()) { wait(nullptr, customText); } + void done(); // hides the Progress Dialog IF all wait()s were canceled with done() ! + void setVisible(bool visible = true); + void setCustomText(const QString &customText = QString()); // call with empty string to reset text to default text "waiting for server" + void unarm(); // deactivate the global wait dialog from showing up (e.g. wait dialog should not be recorded while recording a script in the script editor) + void rearm(); // undo the unarm (re-activate global wait dialog) - void wait(const QString& customText = QString()) - { - wait(nullptr, customText); - } +private: + friend struct LtsGlobalWaitDialogHandler; - void done(); - void setVisible(bool visible = true); - void setCustomText(const QString& customText = QString()); - void unarm(); - void rearm(); + LtsGlobalWaitDialog(); + ~LtsGlobalWaitDialog(); + static void cleanupGwdInstance(); - private: - friend struct LtsGlobalWaitDialogHandler; + void showIt(); + void hideIt(); - LtsGlobalWaitDialog(); - ~LtsGlobalWaitDialog(); - static void cleanupGwdInstance(); - - void showIt(); - void hideIt(); - - int m_waitingCount; - bool m_visible; - bool m_armed{true}; - LtsProgressDialogHelper* m_progressDialog; - QTimer* m_hideTimer; + int m_waitingCount; + bool m_visible; + bool m_armed { true }; + LtsProgressDialogHelper *m_progressDialog; + QTimer *m_hideTimer; }; } // namespace LtsWidgets + + +// 'hyper-global' stuff into main namespace class LTSWIDGETS_EXPORT Waiter { - public: - explicit Waiter(const QString& customText = {}); - explicit Waiter(LtsWidgets::LtsDialog* parent, const QString& customText = {}); - ~Waiter(); +public: + explicit Waiter(const QString &customText = {}); + explicit Waiter(LtsWidgets::LtsDialog *parent, const QString &customText = {}); + ~Waiter(); - private: - LtsWidgets::LtsOverlayLoading* m_loadingOverlay{nullptr}; - LtsWidgets::LtsDialog* m_parent{nullptr}; - bool m_oldClosableState{false}; +private: + LtsWidgets::LtsOverlayLoading *m_loadingOverlay { nullptr }; + LtsWidgets::LtsDialog *m_parent { nullptr }; + bool m_oldClosableState { false }; }; diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_grid_layout.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_grid_layout.cpp index d12c1d700..1340994a2 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_grid_layout.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_grid_layout.cpp @@ -1,122 +1,135 @@ - +/** +* @RDE_HEADER@ +* GridLaout with auto column layouter. +* Layouts all widgets depending on the maxColumn value +* releayouts if maxColumn changed +* $Id$ +* $HeadURL$ +* $Author$ +*/ #include "lts_grid_layout.h" - #include -#include namespace LtsWidgets { -LtsGridLayout::LtsGridLayout(LtsWidgets::ButtonSize buttonSize, QWidget* parent, int maxColumn) - : QGridLayout(parent), m_buttonSize(buttonSize), m_defaultMaxColumn(maxColumn), m_maxColumn(maxColumn), - m_colSize(0), m_autoSize(maxColumn < 0) +LtsGridLayout::LtsGridLayout(LtsWidgets::ButtonSize buttonSize, QWidget *parent, int maxColumn) + : QGridLayout(parent) + , m_buttonSize(buttonSize) + , m_defaultMaxColumn(maxColumn) + , m_maxColumn(maxColumn) + , m_colSize(0) + , m_autoSize(maxColumn < 0) { - setSizeConstraint(SizeConstraint::SetNoConstraint); - - setVerticalSpacing(1); - setContentsMargins(0, 0, 0, 0); + setSizeConstraint(SizeConstraint::SetNoConstraint); + //setHorizontalSpacing(1); + setVerticalSpacing(1); + setMargin(0); } -void LtsGridLayout::add_widget(QWidget* widget) +void LtsGridLayout::add_widget(QWidget *widget) { - for (auto it = m_widgetList.cbegin(); it != m_widgetList.cend(); ++it) - { - if (*it == widget) - return; - } - connect(widget, &QWidget::destroyed, this, &LtsGridLayout::onWidgetDestroyed); - addWidgetInternal(widget); - m_widgetList.push_back(widget); + for (auto it = m_widgetList.cbegin(); it != m_widgetList.cend(); ++it) + { + if (*it == widget) + return; + } + connect(widget, &QWidget::destroyed, this, &LtsGridLayout::onWidgetDestroyed); + addWidgetInternal(widget); + m_widgetList.push_back(widget); } void LtsGridLayout::setAutoSize(bool enable) { - m_autoSize = enable; - if (m_autoSize == false) - setMaxColumn(1); - else - { - m_maxColumn = -1; - m_oldSize = QSize(); - m_oldGeo = QRect(); - QResizeEvent e(sizeHint(), sizeHint()); - onParentResize(&e); - setGeometry(QRect(0, 0, sizeHint().width(), sizeHint().height())); - } + m_autoSize = enable; + if (m_autoSize == false) + setMaxColumn(1); + else + { + m_maxColumn = -1; + m_oldSize = QSize(); + m_oldGeo = QRect(); + QResizeEvent e(sizeHint(), sizeHint()); + onParentResize(&e); + setGeometry(QRect(0, 0, sizeHint().width(), sizeHint().height())); + } } void LtsGridLayout::setMaxColumn(int max) { - m_maxColumn = max; - m_defaultMaxColumn = max; + m_maxColumn = max; + m_defaultMaxColumn = max; - m_colSize = 0; + //resetInternalSize + m_colSize = 0; - for (QWidget* wid : std::as_const(m_widgetList)) - removeWidget(wid); + for (QWidget *wid : qAsConst(m_widgetList)) + removeWidget(wid); + + for (QWidget *wid : qAsConst(m_widgetList)) + addWidgetInternal(wid); - for (QWidget* wid : std::as_const(m_widgetList)) - addWidgetInternal(wid); } -void LtsGridLayout::addWidgetInternal(QWidget* widget) +void LtsGridLayout::addWidgetInternal(QWidget *widget) { - int current_row = 0; - int current_column = 0; + int current_row = 0; + int current_column = 0; - while (QLayoutItem* item = itemAtPosition(current_row, current_column)) + while (QLayoutItem *item = itemAtPosition(current_row, current_column)) + { + if (!item->widget()) { - if (!item->widget()) - { - removeItem(item); - continue; - } - - if (current_column == (m_maxColumn - 1)) - { - current_column = 0; - ++current_row; - } - else - ++current_column; + removeItem(item); + continue; } - if (current_row == 0) - m_colSize += 1; + if (current_column == (m_maxColumn - 1)) + { + current_column = 0; + ++current_row; + } + else + ++current_column; + } - QGridLayout::addWidget(widget, current_row, current_column); + if (current_row == 0) + m_colSize += 1; + + QGridLayout::addWidget(widget, current_row, current_column); } -void LtsGridLayout::onParentResize(QResizeEvent* e) -{ - if (m_autoSize && m_oldSize != e->size()) - { - bool bigger = (e->size().width() > m_oldSize.width()); - m_oldSize = e->size(); - int newWidth = m_oldSize.width(); - int maxIconsInRow = newWidth / (static_cast(m_buttonSize) + 4); - if (!bigger && newWidth <= (static_cast(m_buttonSize) * m_colSize - static_cast(m_buttonSize) / 2)) - maxIconsInRow--; - if (m_maxColumn != maxIconsInRow) - setMaxColumn(maxIconsInRow); - } +void LtsGridLayout::onParentResize(QResizeEvent *e) +{ + if (m_autoSize && m_oldSize != e->size()) + { + bool bigger = (e->size().width() > m_oldSize.width()); + m_oldSize = e->size(); + int newWidth = m_oldSize.width(); + int maxIconsInRow = newWidth / (static_cast(m_buttonSize) + 4); + + if (!bigger && newWidth <= (static_cast(m_buttonSize)*m_colSize - static_cast(m_buttonSize) / 2)) + maxIconsInRow--; + if (m_maxColumn != maxIconsInRow) + setMaxColumn(maxIconsInRow); + } } void LtsGridLayout::onWidgetDestroyed() { - QWidget* s = qobject_cast(sender()); - for (auto it = m_widgetList.begin(); it != m_widgetList.end(); ++it) + QWidget *s = qobject_cast(sender()); + for (auto it = m_widgetList.begin(); it != m_widgetList.end(); ++it) + { + if (*it == s) { - if (*it == s) - { - QGridLayout::removeWidget(s); - m_widgetList.erase(it); - setMaxColumn(m_maxColumn); - break; - } + QGridLayout::removeWidget(s); + m_widgetList.erase(it); + setMaxColumn(m_maxColumn); // resort, also remove the layoutitem + break; } + } } } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_grid_layout.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_grid_layout.h index 8c4616e88..e2c1ad9ef 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_grid_layout.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_grid_layout.h @@ -1,48 +1,92 @@ - +/** +* @RDE_HEADER@ +* GridLaout with auto column layouter. +* Layouts all widgets depending on the maxColumn value +* releayouts if maxColumn changed +* $Id$ +* $HeadURL$ +* $Author$ +*/ #pragma once -#include "lts_base.h" -#include "lts_widgets_export.h" - #include -#include #include +#include "lts_widgets_export.h" +#include "lts_base.h" + class QWidget; namespace LtsWidgets { - +/** +* @brief The LtsGridLayout class provides a LayoutItem for the Lts Layout System and is the equivalent to the QGridLayout. +* An LtsGridLayout can be added to a Widget as any other LayoutItem +* A LtsGridLayout got two modes: +* The first one is the normal operation Mode with a fixed ColumnSize +* every time a widget is added wit add_widget (not addWidget!) +* it will use the next column at the current used row +* when maxColum is reached in the current row +* the Widget will be added to a new row +* +* The Second Mode is enabeled with AutoSize +* There the MaxColumnSize will be calculated +* when a rezize event accure +*/ class LTSWIDGETS_EXPORT LtsGridLayout : public QGridLayout { - Q_OBJECT - public: - explicit LtsGridLayout(LtsWidgets::ButtonSize buttonSize, QWidget* parent = nullptr, int maxColumn = 1); + Q_OBJECT +public: + /** + * @brief Constructor for LtsGridLayout + * @param ButtonSize for calcualting Gridzize on autoSize + * @param Parent widget + * @param max Column to use + */ + explicit LtsGridLayout(LtsWidgets::ButtonSize buttonSize, QWidget *parent = nullptr, int maxColumn = 1); - void add_widget(QWidget* widget); + /** + * @brief adds a QWidget to the Layout in the current Row + * if MaxColumn is reached, the widget will be added to a new row + * @param QWidget addet to the Layout + */ + void add_widget(QWidget *widget); - void setAutoSize(bool enable); + /** + * @brief enables autoSize + * calculates on rezize the MaxColum count for given ButtonSize + * @param enable autoSize + */ + void setAutoSize(bool enable); - void setMaxColumn(int max); + /** + * @brief set MaxColumn + * @param int maxColum count + */ + void setMaxColumn(int max); - private: - void addWidgetInternal(QWidget* widget); - public Q_SLOTS: - void onParentResize(QResizeEvent* e); +private: + void addWidgetInternal(QWidget *widget); + +public Q_SLOTS: + void onParentResize(QResizeEvent *e); + + +private Q_SLOTS: + void onWidgetDestroyed(); +private: + + LtsWidgets::ButtonSize m_buttonSize; + int m_defaultMaxColumn; + int m_maxColumn; + int m_colSize; + QVector m_widgetList; + QRect m_oldGeo; + QSize m_oldSize; + bool m_autoSize; - private Q_SLOTS: - void onWidgetDestroyed(); - private: - LtsWidgets::ButtonSize m_buttonSize; - int m_defaultMaxColumn; - int m_maxColumn; - int m_colSize; - QVector m_widgetList; - QRect m_oldGeo; - QSize m_oldSize; - bool m_autoSize; }; -} // namespace LtsWidgets +} // namespace diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_height_plot_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_height_plot_widget.cpp index 4e6785d41..eaeb77fea 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_height_plot_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_height_plot_widget.cpp @@ -1,583 +1,627 @@ - +/** +* @RDE_HEADER@ +* Widget that visualizes the topography of a bunch of points along a rubberband +* $Id$ +* $HeadURL$ +* $Author$ +* Created by Malte Schroeder, NLSE, 2018-03-07 +*/ #include "lts_height_plot_widget.h" -#include #include #include #include #include +#include + #include -static inline double getLength(const QPointF& p1, const QPointF& p2) + +static inline double getLength(const QPointF &p1, const QPointF &p2) { - const double x = p1.x() - p2.x(); - const double y = p1.y() - p2.y(); - return sqrt(x * x + y * y); + const double x = p1.x() - p2.x(); + const double y = p1.y() - p2.y(); + return sqrt(x * x + y * y); } class LtsHeightPlotWidget::Private { - public: - Private() - : m_length(0), m_minElevation(0), m_maxElevation(0), m_nullX(0), m_nullY(0), m_scaleX(0), m_scaleY(0), - m_fillBrush(Qt::gray), m_axisPen(Qt::black), m_mousePosPen(Qt::blue), m_markerPen(Qt::magenta), - iPositionHint(1) - { - m_axisPen.setWidth(1); - m_viewLinePen.setWidth(1); - m_textFont.setPixelSize(10); - m_markerPen.setWidth(2); - m_markerPen.setCapStyle(Qt::RoundCap); - m_mousePosPen.setStyle(Qt::DashDotDotLine); - m_viewLinePen.setStyle(Qt::DashLine); - } +public: + Private() + : m_length(0) + , m_minElevation(0) + , m_maxElevation(0) + , m_nullX(0) + , m_nullY(0) + , m_scaleX(0) + , m_scaleY(0) + , m_fillBrush(Qt::gray) + , m_axisPen(Qt::black) + , m_mousePosPen(Qt::blue) + , m_markerPen(Qt::magenta) + , iPositionHint(1) + { + m_axisPen.setWidth(1); + m_viewLinePen.setWidth(1); + m_textFont.setPixelSize(10); + m_markerPen.setWidth(2); + m_markerPen.setCapStyle(Qt::RoundCap); + m_mousePosPen.setStyle(Qt::DashDotDotLine); + m_viewLinePen.setStyle(Qt::DashLine); + } + void clearPixmap(); - void clearPixmap(); + double getDataHeight(double pos) const; + QPointF getDataPos(double pos) const; + int findDataPointIdx(const QPointF &point) const; + void clear(); + void recalcData(); + void setData(const QVector > &data); + void setMarks(const QVector &data); + void resize(const QSize &newSize); + void repaint(); + void paintLines(QPainter &p) const; - double getDataHeight(double pos) const; - QPointF getDataPos(double pos) const; - int findDataPointIdx(const QPointF& point) const; - void clear(); - void recalcData(); - void setData(const QVector>& data); - void setMarks(const QVector& data); - void resize(const QSize& newSize); - void repaint(); - void paintLines(QPainter& p) const; + QVector< QPair< QPointF, double > > m_data; + QVector< QPointF > m_marks; + QVector< QPair< double, double > > m_heightList; // Laenge, Hoehe - QVector> m_data; - QVector m_marks; - QVector> m_heightList; + double m_length; + double m_minElevation; + double m_maxElevation; + double m_nullX; + double m_nullY; + double m_scaleX; + double m_scaleY; + QPainterPath m_drawPoints; // PainterPath der Daten, unskaliert + QBrush m_fillBrush; + QPen m_axisPen; + QPen m_viewLinePen; + QPen m_mousePosPen; + QPen m_markerPen; + QFont m_textFont; + QPointF m_mousePos; + QPointF m_mouseLeftClickPos; - double m_length; - double m_minElevation; - double m_maxElevation; - double m_nullX; - double m_nullY; - double m_scaleX; - double m_scaleY; - QPainterPath m_drawPoints; - QBrush m_fillBrush; - QPen m_axisPen; - QPen m_viewLinePen; - QPen m_mousePosPen; - QPen m_markerPen; - QFont m_textFont; - QPointF m_mousePos; - QPointF m_mouseLeftClickPos; + QSize m_curSize; // aktuelle Groesse des Widgets + QTransform m_trans1; // nur Verschiebung des Koordinatensystem + QTransform m_trans2; // Translation Pixel <-> Daten + QTransform m_transInverted; // m_trans1.inverted() * m_trans2.inverted() + QTransform m_transCombined; // m_trans2 * m_trans1 - QSize m_curSize; - QTransform m_trans1; - QTransform m_trans2; - QTransform m_transInverted; - QTransform m_transCombined; + QPixmap m_pixmap; - QPixmap m_pixmap; - - mutable int iPositionHint; + mutable int iPositionHint; }; double LtsHeightPlotWidget::Private::getDataHeight(double pos) const { - if (m_heightList.count() <= 1) - return 0; + if (m_heightList.count() <= 1) + return 0; + // boundary checks + if (pos <= 0.) + return m_heightList[0].second; + if (pos >= m_heightList[m_heightList.count() - 1].first) + return m_heightList[m_heightList.count() - 1].second; - if (pos <= 0.) - return m_heightList[0].second; - if (pos >= m_heightList[m_heightList.count() - 1].first) - return m_heightList[m_heightList.count() - 1].second; - - if (iPositionHint >= m_heightList.size()) - iPositionHint = 1; - if (pos <= m_heightList[iPositionHint].first) - { - while (iPositionHint > 1 && pos <= m_heightList[iPositionHint - 1].first) - --iPositionHint; - } - else - { - while (iPositionHint < m_heightList.count() - 1 && pos > m_heightList[iPositionHint].first) - ++iPositionHint; - } - const int iFound = iPositionHint; - - const double x = m_heightList[iFound].first - m_heightList[iFound - 1].first; - const double y = m_heightList[iFound].second - m_heightList[iFound - 1].second; - const double m = y / x; - const double n = m_heightList[iFound].second - m * m_heightList[iFound].first; - return m * pos + n; + if (iPositionHint >= m_heightList.size()) + iPositionHint = 1; + if (pos <= m_heightList[iPositionHint].first) + { + while (iPositionHint > 1 && pos <= m_heightList[iPositionHint - 1].first) + --iPositionHint; + } + else + { + while (iPositionHint < m_heightList.count() - 1 && pos > m_heightList[iPositionHint].first) + ++iPositionHint; + } + const int iFound = iPositionHint; + // y = m*x + n + const double x = m_heightList[iFound].first - m_heightList[iFound - 1].first; + const double y = m_heightList[iFound].second - m_heightList[iFound - 1].second; + const double m = y / x; + const double n = m_heightList[iFound].second - m * m_heightList[iFound].first; + return m * pos + n; } QPointF LtsHeightPlotWidget::Private::getDataPos(double pos) const { - if (m_heightList.count() <= 1) - return QPointF(); + if (m_heightList.count() <= 1) + return QPointF(); + // boundary checks + if (pos <= 0.) + return m_data[0].first; + if (pos >= m_heightList[m_heightList.count() - 1].first) + return m_data[m_heightList.count() - 1].first; - if (pos <= 0.) - return m_data[0].first; - if (pos >= m_heightList[m_heightList.count() - 1].first) - return m_data[m_heightList.count() - 1].first; - - if (pos <= m_heightList[iPositionHint].first) - { - while (iPositionHint > 1 && pos <= m_heightList[iPositionHint - 1].first) - --iPositionHint; - } - else - { - while (iPositionHint < m_heightList.count() - 1 && pos > m_heightList[iPositionHint].first) - ++iPositionHint; - } - const int iFound = iPositionHint; - - const double diff = m_heightList[iFound].first - m_heightList[iFound - 1].first; - double percentile = (pos - m_heightList[iFound - 1].first) / diff; - const QPointF& p1 = m_data[iFound - 1].first; - const QPointF p2 = m_data[iFound].first - m_data[iFound - 1].first; - return QPointF(p1.x() + p2.x() * percentile, p1.y() + p2.y() * percentile); + if (pos <= m_heightList[iPositionHint].first) + { + while (iPositionHint > 1 && pos <= m_heightList[iPositionHint - 1].first) + --iPositionHint; + } + else + { + while (iPositionHint < m_heightList.count() - 1 && pos > m_heightList[iPositionHint].first) + ++iPositionHint; + } + const int iFound = iPositionHint; + // pos = pos1 + pos1 * prozent(p1,p2) + const double diff = m_heightList[iFound].first - m_heightList[iFound - 1].first; + double percentile = (pos - m_heightList[iFound - 1].first) / diff; + const QPointF &p1 = m_data[iFound - 1].first; + const QPointF p2 = m_data[iFound].first - m_data[iFound - 1].first; + return QPointF(p1.x() + p2.x() * percentile, p1.y() + p2.y() * percentile); } -int LtsHeightPlotWidget::Private::findDataPointIdx(const QPointF& point) const +int LtsHeightPlotWidget::Private::findDataPointIdx(const QPointF &point) const { - for (int i = 0; i < m_heightList.count() - 1; ++i) + for (int i = 0; i < m_heightList.count() - 1; ++i) + { + // y = m*x + n + const double x = m_data[i + 1].first.x() - m_data[i].first.x(); + const double y = m_data[i + 1].first.y() - m_data[i].first.y(); + const double m = y / x; + const double n = m_data[i].first.y() - m * m_data[i].first.x(); + + // Punkt testen ob er auf der Linie liegt + const double yRes = m * point.x() + n; + if (fabs(yRes - point.y()) < 1.) { - - const double x = m_data[i + 1].first.x() - m_data[i].first.x(); - const double y = m_data[i + 1].first.y() - m_data[i].first.y(); - const double m = y / x; - const double n = m_data[i].first.y() - m * m_data[i].first.x(); - - const double yRes = m * point.x() + n; - if (fabs(yRes - point.y()) < 1.) - { - - const double len = getLength(m_data[i].first, point); - if (len <= m_heightList[i].first) - return i; - } + // und schauen ob er nicht hinter dem zweiten Punkt liegt + const double len = getLength(m_data[ i ].first, point); + if (len <= m_heightList[i].first) + return i; } - return -1; + } + return -1; } void LtsHeightPlotWidget::Private::clear() { - m_data.clear(); - m_marks.clear(); - m_length = 0; - m_minElevation = 0; - m_maxElevation = 0; - m_scaleX = 0; - m_scaleY = 0; - m_drawPoints = QPainterPath(); - m_heightList.clear(); - m_curSize = QSize(); + m_data.clear(); + m_marks.clear(); + m_length = 0; + m_minElevation = 0; + m_maxElevation = 0; + m_scaleX = 0; + m_scaleY = 0; + m_drawPoints = QPainterPath(); + m_heightList.clear(); + m_curSize = QSize(); - iPositionHint = 1; + iPositionHint = 1; } void LtsHeightPlotWidget::Private::clearPixmap() { - m_pixmap = QPixmap(); + m_pixmap = QPixmap(); } inline double log5(double x) { - return log10(x) / log10(5.); + return log10(x) / log10(5.); } void LtsHeightPlotWidget::Private::recalcData() { - m_heightList.clear(); - m_drawPoints = QPainterPath(); + m_heightList.clear(); + m_drawPoints = QPainterPath(); - if (m_data.isEmpty()) - { - clear(); - return; - } - - double length = 0; - double minElevation = m_data.at(0).second; - double maxElevation = minElevation; - - for (int i = 1; i < m_data.count(); ++i) - { - length += getLength(m_data.at(i - 1).first, m_data.at(i).first); - minElevation = std::min(minElevation, m_data.at(i).second); - maxElevation = std::max(maxElevation, m_data.at(i).second); - } - - if (minElevation < -10000.0) - minElevation = -10000.0; - if (maxElevation < -10000.0) - maxElevation = -10000.0; - - if (minElevation > 10000.0) - minElevation = 10000.0; - if (maxElevation > 10000.0) - maxElevation = 10000.0; - - if (qFuzzyCompare(minElevation, maxElevation)) - { - minElevation -= 1.0; - maxElevation += 1.0; - } - - double n2 = pow(5, floor(log5(fabs(minElevation))) - 1); - if (qFuzzyIsNull(n2)) - n2 = 0.1; - - m_minElevation = lrint(floor(minElevation / n2) * n2); - m_maxElevation = lrint(ceil(maxElevation / n2) * n2); - m_scaleY = pow(10, floor(log10(m_maxElevation - m_minElevation)) - 1); - if (m_scaleY < 0.1) - m_scaleY = 0.1; - m_nullY = m_minElevation; - if (m_minElevation < 0 && m_maxElevation > 0) - m_nullY = 0; - - const double n = pow(10, floor(log10(length))) / 2; - m_length = lrint(ceil(length / n) * n); - m_scaleX = pow(10, floor(log10(length)) - 1); - if (m_scaleX < 0.1) - m_scaleX = 0.1; - m_nullX = 0; - - double len = 0; - m_drawPoints.moveTo(len, m_data.at(0).second); - m_heightList.append(QPair(len, m_data.at(0).second)); - for (int i = 1; i < m_data.count(); ++i) - { - len += getLength(m_data.at(i - 1).first, m_data.at(i).first); - m_drawPoints.lineTo(len, m_data.at(i).second); - - m_heightList.append(QPair(len, m_data.at(i).second)); - } - m_drawPoints.lineTo(len, m_minElevation); - m_drawPoints.lineTo(0, m_minElevation); - m_drawPoints.setFillRule(Qt::WindingFill); -} - -void LtsHeightPlotWidget::Private::setData(const QVector>& data) -{ - if (data.isEmpty()) - { - clear(); - return; - } - QSize tmp = m_curSize; + if (m_data.isEmpty()) + { clear(); + return; + } - m_data = data; + double length = 0; + double minElevation = m_data.at(0).second; + double maxElevation = minElevation; - recalcData(); - resize(tmp); + for (int i = 1; i < m_data.count(); ++i) + { + length += getLength(m_data.at(i - 1).first, m_data.at(i).first); + minElevation = std::min(minElevation, m_data.at(i).second); + maxElevation = std::max(maxElevation, m_data.at(i).second); + } + // some sanity checks: + if (minElevation < -10000.0) minElevation = -10000.0; + if (maxElevation < -10000.0) maxElevation = -10000.0; + + if (minElevation > 10000.0) minElevation = 10000.0; + if (maxElevation > 10000.0) maxElevation = 10000.0; + + if (qFuzzyCompare(minElevation, maxElevation)) + { + minElevation -= 1.0; + maxElevation += 1.0; + } + + // Laenge auf 5^(n-1) m runden + double n2 = pow(5, floor(log5(fabs(minElevation))) - 1); + if (qFuzzyIsNull(n2)) + n2 = 0.1; // avoid division by zero + + m_minElevation = lrint(floor(minElevation / n2) * n2); + m_maxElevation = lrint(ceil(maxElevation / n2) * n2); + m_scaleY = pow(10, floor(log10(m_maxElevation - m_minElevation)) - 1); + if (m_scaleY < 0.1) + m_scaleY = 0.1; + m_nullY = m_minElevation; + if (m_minElevation < 0 && m_maxElevation > 0) + m_nullY = 0; + + // Laenge auf 10^n / 2 m runden + const double n = pow(10, floor(log10(length))) / 2; + m_length = lrint(ceil(length / n) * n); + m_scaleX = pow(10, floor(log10(length)) - 1); + if (m_scaleX < 0.1) + m_scaleX = 0.1; + m_nullX = 0; + + double len = 0; + m_drawPoints.moveTo(len, m_data.at(0).second); + m_heightList.append(QPair(len, m_data.at(0).second)); + for (int i = 1; i < m_data.count(); ++i) + { + len += getLength(m_data.at(i - 1).first, m_data.at(i).first); + m_drawPoints.lineTo(len, m_data.at(i).second); + + m_heightList.append(QPair(len, m_data.at(i).second)); + //fprintf(stderr, "point at len %f\n", len); + } + m_drawPoints.lineTo(len, m_minElevation); + m_drawPoints.lineTo(0, m_minElevation); + m_drawPoints.setFillRule(Qt::WindingFill); } -void LtsHeightPlotWidget::Private::setMarks(const QVector& data) +void LtsHeightPlotWidget::Private::setData(const QVector< QPair< QPointF, double > > &data) { - m_marks = data; + if (data.isEmpty()) + { + clear(); + return; + } + QSize tmp = m_curSize; + clear(); - recalcData(); - repaint(); + m_data = data; + + recalcData(); + resize(tmp); } -void LtsHeightPlotWidget::Private::resize(const QSize& newSize) + +void LtsHeightPlotWidget::Private::setMarks(const QVector< QPointF > &data) { - if (newSize == m_curSize) - return; + m_marks = data; - m_curSize = newSize; + recalcData(); + repaint(); +} - const int border = 25; - const double width = m_curSize.width(); - const double height = m_curSize.height(); +void LtsHeightPlotWidget::Private::resize(const QSize &newSize) +{ + if (newSize == m_curSize) + return; - const double minY = m_minElevation - m_scaleY; - const double maxY = m_maxElevation + m_scaleY; - const double wertebereichY = maxY - minY; + m_curSize = newSize; - const double minX = 0 - m_scaleX; - const double maxX = m_length + m_scaleX; - const double wertebereichX = maxX - minX; + const int border = 25; + const double width = m_curSize.width(); + const double height = m_curSize.height(); - m_trans1.reset(); - m_trans2.reset(); + const double minY = m_minElevation - m_scaleY; + const double maxY = m_maxElevation + m_scaleY; + const double wertebereichY = maxY - minY; - m_trans1.translate(10, height); + const double minX = 0 - m_scaleX; + const double maxX = m_length + m_scaleX; + const double wertebereichX = maxX - minX; - m_trans1.scale(1, -1); + m_trans1.reset(); + m_trans2.reset(); - m_trans1.translate(border, border); + // 10 Pixel nach rechts und y = 0 ist unten anstatt oben + m_trans1.translate(10, height); + // + und - y tauschen - damit im ersten Quadrant x und y positiv sind + m_trans1.scale(1, -1); + // und noch etwas vom Rand weg + m_trans1.translate(border, border); + // und wieder zurueck + m_trans1.scale(1, -1); - m_trans1.scale(1, -1); + // die aktuelle Breite und Hoehe relativ zu der Breite und Hoehe der Daten + m_trans2.scale((width - 2 * border) / (wertebereichX), + (height - 2 * border) / (wertebereichY)); + // m_minElevation ist unser '0-Wert', minY demnach der kleinste y-Wert + m_trans2.translate(0, minY); + // + und - y tauschen - damit im ersten Quadrant x und y positiv sind + m_trans2.scale(1, -1); - m_trans2.scale((width - 2 * border) / (wertebereichX), (height - 2 * border) / (wertebereichY)); + m_transInverted = m_trans1.inverted() * m_trans2.inverted(); + m_transCombined = m_trans2 * m_trans1; - m_trans2.translate(0, minY); - - m_trans2.scale(1, -1); - - m_transInverted = m_trans1.inverted() * m_trans2.inverted(); - m_transCombined = m_trans2 * m_trans1; - - repaint(); + repaint(); } void LtsHeightPlotWidget::Private::repaint() { - if (!m_curSize.isValid()) - return; - if (!m_heightList.count()) - return; + if (!m_curSize.isValid()) + return; + if (!m_heightList.count()) + return; - QImage img(m_curSize, QImage::Format_ARGB32); - img.fill(Qt::transparent); - QPainter p(&img); - const QPainter::RenderHints hints = - QPainter::SmoothPixmapTransform | QPainter::TextAntialiasing | QPainter::Antialiasing; - p.setRenderHints(hints); - p.setTransform(m_trans1); + QImage img(m_curSize, QImage::Format_ARGB32); + img.fill(Qt::transparent); + QPainter p(&img); + const QPainter::RenderHints hints = QPainter::HighQualityAntialiasing | + QPainter::SmoothPixmapTransform | + QPainter::TextAntialiasing | + QPainter::Antialiasing; + p.setRenderHints(hints); + p.setTransform(m_trans1); - p.setPen(QPen(m_fillBrush, 0.1)); - p.setBrush(m_fillBrush); - p.drawPath(m_trans2.map(m_drawPoints)); - p.setRenderHint(QPainter::Antialiasing, false); + // Daten zeichnen + p.setPen(QPen(m_fillBrush, 0.1)); + p.setBrush(m_fillBrush); + p.drawPath(m_trans2.map(m_drawPoints)); + p.setRenderHint(QPainter::Antialiasing, false); - p.setPen(m_markerPen); - for (int i = 0; i < m_marks.count(); ++i) - { - int posIdx = findDataPointIdx(m_marks.at(i)); - if (posIdx < 0) - continue; - double len = getLength(m_data.at(posIdx).first, m_marks.at(i)); - len += m_heightList.at(posIdx).first; - const double height = getDataHeight(len); - const QLineF l(len, m_minElevation, len, height); + // Marker zeichnen + p.setPen(m_markerPen); + for (int i = 0; i < m_marks.count(); ++i) + { + int posIdx = findDataPointIdx(m_marks.at(i)); + if (posIdx < 0) + continue; + double len = getLength(m_data.at(posIdx).first, m_marks.at(i)); + len += m_heightList.at(posIdx).first; + const double height = getDataHeight(len); + const QLineF l(len, m_minElevation, len, height); + //fprintf(stderr, "marker at len %f\n", len); - p.drawLine(m_trans2.map(l)); - } + p.drawLine(m_trans2.map(l)); + } - p.setPen(m_axisPen); - p.setFont(m_textFont); + // Koordinatensystem + Beschriftung + p.setPen(m_axisPen); + p.setFont(m_textFont); - p.drawLine(m_trans2.map(QPointF(m_nullX, m_minElevation - m_scaleY)), - m_trans2.map(QPointF(m_nullX, m_maxElevation + m_scaleY))); + // Y-Achse + p.drawLine(m_trans2.map(QPointF(m_nullX, m_minElevation - m_scaleY)), + m_trans2.map(QPointF(m_nullX, m_maxElevation + m_scaleY))); - for (double i = m_minElevation; i <= m_maxElevation; i += m_scaleY) - { - const qreal y = m_trans2.map(QPointF(0, i)).y(); - p.drawLine(QLineF(-2, y, 2, y)); - } + // kleine Striche + for (double i = m_minElevation; i <= m_maxElevation; i += m_scaleY) + { + const qreal y = m_trans2.map(QPointF(0, i)).y(); + p.drawLine(QLineF(-2, y, 2, y)); + } - for (double i = m_minElevation; i <= m_maxElevation; i += m_scaleY * 5) - { - const qreal y = m_trans2.map(QPointF(0, i)).y(); - p.drawLine(QLineF(-4, y, 4, y)); - } + // grosse Striche + for (double i = m_minElevation; i <= m_maxElevation; i += m_scaleY * 5) + { + const qreal y = m_trans2.map(QPointF(0, i)).y(); + p.drawLine(QLineF(-4, y, 4, y)); + } - QFontMetricsF fm(m_textFont); - for (double i = m_minElevation; i <= m_maxElevation; i += m_scaleY * 5) - { - if (qFuzzyCompare(i, m_nullY)) - continue; - const qreal y = m_trans2.map(QPointF(m_nullX, i)).y(); - const QPointF p1(-20, y); - const QString str = QString::number(i); - QRectF r = fm.boundingRect(str); - r.setWidth(fm.horizontalAdvance(str)); - r.moveTo(p1.x() - r.width() / 2., p1.y() - r.height() / 2.); - p.drawText(r, str, Qt::AlignHCenter | Qt::AlignVCenter); - } + QFontMetricsF fm(m_textFont); + for (double i = m_minElevation; i <= m_maxElevation; i += m_scaleY * 5) + { + if (qFuzzyCompare(i, m_nullY)) + continue; + const qreal y = m_trans2.map(QPointF(m_nullX, i)).y(); + const QPointF p1(-20, y); + const QString str = QString::number(i); + QRectF r = fm.boundingRect(str); + r.setWidth(fm.width(str)); // important, see docu! + r.moveTo(p1.x() - r.width() / 2., p1.y() - r.height() / 2.); + p.drawText(r, str, Qt::AlignHCenter | Qt::AlignVCenter); + } - p.drawLine(m_trans2.map(QPointF(-m_scaleX, m_nullY)), m_trans2.map(QPointF(m_scaleX + m_length, m_nullY))); + // X-Achse + p.drawLine(m_trans2.map(QPointF(-m_scaleX, m_nullY)), + m_trans2.map(QPointF(m_scaleX + m_length, m_nullY))); - for (double i = m_scaleX; i <= m_length; i += m_scaleX) - { - const QPointF point = m_trans2.map(QPointF(i, m_nullY)); - p.drawLine(QLineF(point.x(), point.y() - 2, point.x(), point.y() + 2)); - } + // kleine Striche + for (double i = m_scaleX; i <= m_length; i += m_scaleX) + { + const QPointF point = m_trans2.map(QPointF(i, m_nullY)); + p.drawLine(QLineF(point.x(), point.y() - 2, point.x(), point.y() + 2)); + } - for (double i = 0; i <= m_length; i += m_scaleX * 5) - { - const QPointF point = m_trans2.map(QPointF(i, m_nullY)); - p.drawLine(QLineF(point.x(), point.y() - 4, point.x(), point.y() + 4)); - } + // grosse Striche + for (double i = 0; i <= m_length; i += m_scaleX * 5) + { + const QPointF point = m_trans2.map(QPointF(i, m_nullY)); + p.drawLine(QLineF(point.x(), point.y() - 4, point.x(), point.y() + 4)); + } - for (double i = 0; i <= m_length; i += m_scaleX * 5) - { - if (qFuzzyCompare(i, m_nullX)) - continue; - const QPointF point = m_trans2.map(QPointF(i, m_nullY)); - const QPointF p1(point.x(), point.y() + 15); - const QString str = QString::number(i); - QRectF r = fm.boundingRect(str); - r.setWidth(fm.horizontalAdvance(str)); - r.moveTo(p1.x() - r.width() / 2., p1.y() - r.height() / 2.); - p.drawText(r, str, Qt::AlignHCenter | Qt::AlignVCenter); - } - p.end(); - m_pixmap = QPixmap::fromImage(img); + for (double i = 0; i <= m_length; i += m_scaleX * 5) + { + if (qFuzzyCompare(i, m_nullX)) + continue; + const QPointF point = m_trans2.map(QPointF(i, m_nullY)); + const QPointF p1(point.x(), point.y() + 15); + const QString str = QString::number(i); + QRectF r = fm.boundingRect(str); + r.setWidth(fm.width(str)); // important, see docu! + r.moveTo(p1.x() - r.width() / 2., p1.y() - r.height() / 2.); + p.drawText(r, str, Qt::AlignHCenter | Qt::AlignVCenter); + } + p.end(); + m_pixmap = QPixmap::fromImage(img); } -void LtsHeightPlotWidget::Private::paintLines(QPainter& p) const +void LtsHeightPlotWidget::Private::paintLines(QPainter &p) const { - if (m_heightList.count() > 0) + if (m_heightList.count() > 0) + { + // Mouse-Position zeichnen + QPointF pos = m_mousePos; + if (pos.x() < 0) + pos.setX(0); + if (pos.x() > m_heightList.at(m_heightList.count() - 1).first) + pos.setX(m_heightList.at(m_heightList.count() - 1).first); + + //keine Transformation setzen da sonst die Linienstaerke des Pens veraendert wird! + //p.setTransform(d->m_transCombined); + const double curHeight = getDataHeight(pos.x()); + p.setPen(m_mousePosPen); + p.drawLine(m_transCombined.map(QLineF(m_nullX, curHeight, pos.x(), curHeight))); + p.drawLine(m_transCombined.map(QLineF(pos.x(), m_nullY, pos.x(), curHeight))); + + // Sichtlinie zeichnen + if (!m_mouseLeftClickPos.isNull()) { + const double y = curHeight > pos.y() ? curHeight : pos.y(); + p.drawLine(m_transCombined.map(QLineF(m_nullX, y, pos.x(), y))); + p.drawLine(m_transCombined.map(QLineF(pos.x(), m_nullY, pos.x(), y))); - QPointF pos = m_mousePos; - if (pos.x() < 0) - pos.setX(0); - if (pos.x() > m_heightList.at(m_heightList.count() - 1).first) - pos.setX(m_heightList.at(m_heightList.count() - 1).first); + p.setPen(m_viewLinePen); + const QPointF &c = m_mouseLeftClickPos; + p.drawLine(m_transCombined.map(QLineF(m_nullX, c.y(), c.x(), c.y()))); + p.drawLine(m_transCombined.map(QLineF(c.x(), m_nullY, c.x(), c.y()))); - const double curHeight = getDataHeight(pos.x()); - p.setPen(m_mousePosPen); - p.drawLine(m_transCombined.map(QLineF(m_nullX, curHeight, pos.x(), curHeight))); - p.drawLine(m_transCombined.map(QLineF(pos.x(), m_nullY, pos.x(), curHeight))); - - if (!m_mouseLeftClickPos.isNull()) - { - const double y = curHeight > pos.y() ? curHeight : pos.y(); - p.drawLine(m_transCombined.map(QLineF(m_nullX, y, pos.x(), y))); - p.drawLine(m_transCombined.map(QLineF(pos.x(), m_nullY, pos.x(), y))); - - p.setPen(m_viewLinePen); - const QPointF& c = m_mouseLeftClickPos; - p.drawLine(m_transCombined.map(QLineF(m_nullX, c.y(), c.x(), c.y()))); - p.drawLine(m_transCombined.map(QLineF(c.x(), m_nullY, c.x(), c.y()))); - - const QLineF line(m_mouseLeftClickPos, QPointF(pos.x(), y)); - p.drawLine(m_transCombined.map(line)); - } + // nur hier da die anderen beiden Linien sonst nicht schoen aussehen + const QLineF line(m_mouseLeftClickPos, QPointF(pos.x(), y)); + p.drawLine(m_transCombined.map(line)); } + } } -LtsHeightPlotWidget::LtsHeightPlotWidget(QWidget* parent) : QWidget(parent), d(new Private) +LtsHeightPlotWidget::LtsHeightPlotWidget(QWidget *parent) + : QWidget(parent) + , d(new Private) { - setMinimumSize(300, 300); - resize(size()); - setMouseTracking(true); + setMinimumSize(300, 300); + resize(size()); + setMouseTracking(true); } LtsHeightPlotWidget::~LtsHeightPlotWidget() { - delete d; + delete d; } void LtsHeightPlotWidget::clearView() { - d->clearPixmap(); + d->clearPixmap(); + update(); +} + +void LtsHeightPlotWidget::setData(const QVector< QPair< QPointF, double > > &data) +{ + d->setData(data); + update(); +} + +void LtsHeightPlotWidget::setMarks(const QVector &data) +{ + d->setMarks(data); +} + +void LtsHeightPlotWidget::setBackgroundBrush(const QBrush &brush) +{ + QPalette pal = palette(); + pal.setBrush(QPalette::Background, brush); + setPalette(pal); +} + +void LtsHeightPlotWidget::setTextFont(const QFont &f) +{ + d->m_textFont = f; + d->repaint(); +} + +void LtsHeightPlotWidget::setAxisPen(const QPen &pen) +{ + d->m_axisPen = pen; + d->repaint(); +} + +void LtsHeightPlotWidget::setPositionPen(const QPen &pen) +{ + d->m_mousePosPen = pen; +} + +void LtsHeightPlotWidget::setViewLinePen(const QPen &pen) +{ + d->m_viewLinePen = pen; +} + +void LtsHeightPlotWidget::setContourBrush(const QBrush &brush) +{ + d->m_fillBrush = brush; + d->repaint(); +} + +void LtsHeightPlotWidget::setMarkerPen(const QPen &pen) +{ + d->m_markerPen = pen; + d->repaint(); +} + +void LtsHeightPlotWidget::resizeEvent(QResizeEvent *e) +{ + d->resize(size()); + QWidget::resizeEvent(e); +} + +void LtsHeightPlotWidget::paintEvent(QPaintEvent *e) +{ + Q_UNUSED(e); + QPainter p(this); + + const QPainter::RenderHints hints = QPainter::SmoothPixmapTransform | + QPainter::TextAntialiasing | + QPainter::Antialiasing; + p.setRenderHints(hints); + + // vorgefertiges Bild zeichnen + p.drawPixmap(0, 0, d->m_pixmap); + + // und jetzt die Hilfslinien + d->paintLines(p); + p.end(); +} + +void LtsHeightPlotWidget::mouseMoveEvent(QMouseEvent *e) +{ + QWidget::mouseMoveEvent(e); + if (!d->m_heightList.count()) + return; + + const QPointF pos = d->m_transInverted.map(e->localPos()); + emit mousePositionChanged(d->getDataPos(pos.x()), d->getDataHeight(pos.x()), pos.y()); + d->m_mousePos = pos; + update(); +} + +void LtsHeightPlotWidget::mouseReleaseEvent(QMouseEvent *e) +{ + QWidget::mouseReleaseEvent(e); + if (!d->m_heightList.count()) + return; + if (e->button() == Qt::LeftButton) + { + const QPointF &pos = d->m_mousePos; + if (pos.x() < 0) + return; + if (pos.x() > d->m_heightList.at(d->m_heightList.count() - 1).first) + return; + + const double curHeight = d->getDataHeight(pos.x()); + d->m_mouseLeftClickPos = QPointF(pos.x(), curHeight > pos.y() ? curHeight : pos.y()); + emit startLineOfSight(d->getDataPos(pos.x())); + } + else if (e->button() == Qt::RightButton) + { + d->m_mouseLeftClickPos = QPointF(); + emit stopLineOfSight(); update(); + } } -void LtsHeightPlotWidget::setData(const QVector>& data) -{ - d->setData(data); - update(); -} - -void LtsHeightPlotWidget::setMarks(const QVector& data) -{ - d->setMarks(data); -} - -void LtsHeightPlotWidget::setBackgroundBrush(const QBrush& brush) -{ - QPalette pal = palette(); - pal.setBrush(QPalette::Window, brush); - setPalette(pal); -} - -void LtsHeightPlotWidget::setTextFont(const QFont& f) -{ - d->m_textFont = f; - d->repaint(); -} - -void LtsHeightPlotWidget::setAxisPen(const QPen& pen) -{ - d->m_axisPen = pen; - d->repaint(); -} - -void LtsHeightPlotWidget::setPositionPen(const QPen& pen) -{ - d->m_mousePosPen = pen; -} - -void LtsHeightPlotWidget::setViewLinePen(const QPen& pen) -{ - d->m_viewLinePen = pen; -} - -void LtsHeightPlotWidget::setContourBrush(const QBrush& brush) -{ - d->m_fillBrush = brush; - d->repaint(); -} - -void LtsHeightPlotWidget::setMarkerPen(const QPen& pen) -{ - d->m_markerPen = pen; - d->repaint(); -} - -void LtsHeightPlotWidget::resizeEvent(QResizeEvent* e) -{ - d->resize(size()); - QWidget::resizeEvent(e); -} - -void LtsHeightPlotWidget::paintEvent(QPaintEvent* e) -{ - Q_UNUSED(e); - QPainter p(this); - - const QPainter::RenderHints hints = - QPainter::SmoothPixmapTransform | QPainter::TextAntialiasing | QPainter::Antialiasing; - p.setRenderHints(hints); - - p.drawPixmap(0, 0, d->m_pixmap); - - d->paintLines(p); - p.end(); -} - -void LtsHeightPlotWidget::mouseMoveEvent(QMouseEvent* e) -{ - QWidget::mouseMoveEvent(e); - if (!d->m_heightList.count()) - return; - - const QPointF pos = d->m_transInverted.map(e->localPos()); - emit mousePositionChanged(d->getDataPos(pos.x()), d->getDataHeight(pos.x()), pos.y()); - d->m_mousePos = pos; - update(); -} - -void LtsHeightPlotWidget::mouseReleaseEvent(QMouseEvent* e) -{ - QWidget::mouseReleaseEvent(e); - if (!d->m_heightList.count()) - return; - if (e->button() == Qt::LeftButton) - { - const QPointF& pos = d->m_mousePos; - if (pos.x() < 0) - return; - if (pos.x() > d->m_heightList.at(d->m_heightList.count() - 1).first) - return; - - const double curHeight = d->getDataHeight(pos.x()); - d->m_mouseLeftClickPos = QPointF(pos.x(), curHeight > pos.y() ? curHeight : pos.y()); - emit startLineOfSight(d->getDataPos(pos.x())); - } - else if (e->button() == Qt::RightButton) - { - d->m_mouseLeftClickPos = QPointF(); - emit stopLineOfSight(); - update(); - } -} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_height_plot_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_height_plot_widget.h index 60e3fab2e..96c5fb1f9 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_height_plot_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_height_plot_widget.h @@ -1,55 +1,97 @@ - +/** +* @RDE_HEADER@ +* Widget that visualizes the topography of a bunch of points along a rubberband +* $Id$ +* $HeadURL$ +* $Author$ +* Created by Malte Schroeder, NLSE, 2018-03-07 +*/ #pragma once -#include "lts_widgets_export.h" -#include #include -#include -#include #include +#include +#include + +#include "lts_widgets_export.h" class LTSWIDGETS_EXPORT LtsHeightPlotWidget final : public QWidget { - Q_OBJECT - public: - explicit LtsHeightPlotWidget(QWidget* parent = nullptr); - virtual ~LtsHeightPlotWidget(); + Q_OBJECT +public: + explicit LtsHeightPlotWidget(QWidget *parent = nullptr); + virtual ~LtsHeightPlotWidget(); - void clearView(); + void clearView(); - void setData(const QVector>& data); + /** + * Set the data in the form + * QPoint - x/y values + * double - height values + * @param data the height data to display + */ + void setData(const QVector > &data); + /** + * Set the markers to show + * QPoint - x/y values + * @param data the markers to display + */ + void setMarks(const QVector &data); - void setMarks(const QVector& data); + /** + * Set the background of the widget + */ + void setBackgroundBrush(const QBrush &brush); + /** + * Set the font for the axis labels + */ + void setTextFont(const QFont &f); + /** + * Set the pen used for the axis lines + */ + void setAxisPen(const QPen &pen); + /** + * Set the pen for the position marker + */ + void setPositionPen(const QPen &pen); + /** + * Set the pen for the viewline + */ + void setViewLinePen(const QPen &pen); + /** + * Set the brush for the contour (+ fill) + */ + void setContourBrush(const QBrush &brush); + /** + * Set the pen for the markers + */ + void setMarkerPen(const QPen &pen); - void setBackgroundBrush(const QBrush& brush); +Q_SIGNALS: + /** + * The current mouse position has changed. + * @param curPoint the current point (in map coordinates) of the mouse + * @param curHeight the current height at the given point + * @param mouseHeight the current height at the current mouse point (>= curHeight) + */ + void mousePositionChanged(const QPointF &curPoint, double curHeight, double mouseHeight); + /** + * A line of sight has started. This signal can emitted more than once + * wich means that the old line of sight was stopped + * @param startPoint the startpoint (in map coordinates) of the line + */ + void startLineOfSight(const QPointF &startPoint); + /** + * A line of sight has stopped + */ + void stopLineOfSight(); +protected: + void resizeEvent(QResizeEvent *e) override; + void paintEvent(QPaintEvent *e) override; + void mouseMoveEvent(QMouseEvent *e) override; + void mouseReleaseEvent(QMouseEvent *e) override; - void setTextFont(const QFont& f); - - void setAxisPen(const QPen& pen); - - void setPositionPen(const QPen& pen); - - void setViewLinePen(const QPen& pen); - - void setContourBrush(const QBrush& brush); - - void setMarkerPen(const QPen& pen); - - Q_SIGNALS: - - void mousePositionChanged(const QPointF& curPoint, double curHeight, double mouseHeight); - - void startLineOfSight(const QPointF& startPoint); - - void stopLineOfSight(); - - protected: - void resizeEvent(QResizeEvent* e) override; - void paintEvent(QPaintEvent* e) override; - void mouseMoveEvent(QMouseEvent* e) override; - void mouseReleaseEvent(QMouseEvent* e) override; - - class Private; - Private* const d; + class Private; + Private *const d; }; diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_image_editor.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_image_editor.cpp index 3ec194ef1..6f9e1c157 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_image_editor.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_image_editor.cpp @@ -1,101 +1,123 @@ - +/** + * @RDE_HEADER@ + * An Image Editor which shows an Image, and emits a signal when clicked (to edit/swap an Image) + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Mike Wille, SLSE, 2016-09-19 + */ #include "lts_image_editor.h" -#include -#include -#include #include +#include +#include #include #include +#include using namespace LtsWidgets; -LtsImageEditor::LtsImageEditor(QWidget* parent) - : QWidget(parent), m_isHovered(false), m_menuEnabled(true), m_bDrawOuterRect(true) + +LtsImageEditor::LtsImageEditor(QWidget *parent) + : QWidget(parent) + , m_isHovered(false) + , m_menuEnabled(true) // enabled by default + , m_bDrawOuterRect(true) +{} + + +void LtsImageEditor::setPixmap(const QPixmap &pixmap) { + if (pixmap.isNull()) // invalid / empty pixmap given, trying to replace it with one from lts_resources + m_pixmap = QPixmap(QStringLiteral(":style/noimage.png")); // when this fails, the pixmap is still invalid, so no checks needed TODO: add noimage.png ! + else + m_pixmap = pixmap; + + update(); + emit imageChanged(); } -void LtsImageEditor::setPixmap(const QPixmap& pixmap) -{ - if (pixmap.isNull()) - m_pixmap = QPixmap(QStringLiteral(":style/noimage.png")); - else - m_pixmap = pixmap; - update(); - emit imageChanged(); +void LtsImageEditor::enterEvent(QEvent *) +{ + //qWarning() << "enter"; + m_isHovered = true; + update(); } -void LtsImageEditor::enterEvent(QEnterEvent*) -{ - m_isHovered = true; - update(); +void LtsImageEditor::leaveEvent(QEvent *) +{ + //qWarning() << "leave"; + m_isHovered = false; + update(); } -void LtsImageEditor::leaveEvent(QEvent*) + +bool LtsImageEditor::event(QEvent *event) { - - m_isHovered = false; - update(); -} - -bool LtsImageEditor::event(QEvent* event) -{ - if (event->type() == QEvent::MouseButtonPress && m_menuEnabled) - { - emit signalClicked(); - event->accept(); - m_isHovered = false; - update(); - return true; - } - - return QWidget::event(event); -} - -void LtsImageEditor::paintEvent(QPaintEvent* event) -{ - QPainter p(this); - - p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); - QBrush brush = QColor(QStringLiteral("white")); - - if (!m_pixmap.isNull()) - { - if (!(m_isHovered && m_menuEnabled)) - { - const QSize s(size()); - const QPixmap pixmap(m_pixmap.scaled(s, Qt::KeepAspectRatio, Qt::SmoothTransformation)); - const int x = qRound((s.width() - pixmap.width()) / 2.); - const int y = qRound((s.height() - pixmap.height()) / 2.); - if (m_bDrawOuterRect) - { - p.setPen(QPen(QColor("gray"), 2)); - p.drawRect(rect()); - } - p.drawPixmap(x, y, pixmap); - event->accept(); - return; - } - } - - p.setPen(QPen(QColor("gray"), 2)); - p.setBrush(brush); - p.drawRect(rect()); - - if (m_isHovered && m_menuEnabled) - { - p.setPen(QPen(QColor(QStringLiteral("gray")), (size().height() / 48 * 2))); - - double xc = size().width() / 2.012; - double yc = size().height() / 2.012; - - p.drawLine(QPointF(xc - (xc / 2.01f), yc - (yc / 3.01f)), QPointF(xc + (xc / 2.02f), yc - (yc / 3.02f))); - p.drawLine(QPointF(xc - (xc / 2.01f), yc - 0.01f), QPointF(xc + (xc / 2.02f), yc - 0)); - p.drawLine(QPointF(xc - (xc / 2.01f), yc + (yc / 3.01f)), QPointF(xc + (xc / 2.02f), yc + (yc / 3.02f))); - } - + if (event->type() == QEvent::MouseButtonPress && m_menuEnabled) + { + emit signalClicked(); event->accept(); + m_isHovered = false; // unhovered on click + update(); + return true; + } + + return QWidget::event(event); // otherwise.. +} + + +void LtsImageEditor::paintEvent(QPaintEvent* event) // TODO: colors from palette (style plugin) ? +{ + QPainter p(this); + + // draw profile picture + p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); + QBrush brush = QColor(QStringLiteral("white")); // TODO: get from palette + + + if (!m_pixmap.isNull()) + { + if (!(m_isHovered && m_menuEnabled)) // draw if NOT hovered or draw when hovered but menu is disabled + { + const QSize s(size()); + const QPixmap pixmap(m_pixmap.scaled(s, Qt::KeepAspectRatio, Qt::SmoothTransformation)); + const int x = qRound((s.width() - pixmap.width()) / 2.); + const int y = qRound((s.height() - pixmap.height()) / 2.); + if (m_bDrawOuterRect) + { + p.setPen(QPen(QColor("gray"), 2)); + p.drawRect(rect()); + } + p.drawPixmap(x, y, pixmap); + event->accept(); + return; + } + } + + + // draw frame + p.setPen(QPen(QColor("gray"), 2)); + p.setBrush(brush); + p.drawRect(rect()); + + + // draw menu icon + if (m_isHovered && m_menuEnabled) + { + p.setPen(QPen(QColor(QStringLiteral("gray")), (size().height() / 48 * 2))); // respect height, width is unnecessary + + double xc = size().width()/2.012; + double yc = size().height()/2.012; + + p.drawLine(QPointF(xc - (xc/2.01f), yc - (yc/3.01f)), QPointF(xc + (xc/2.02f), yc - (yc/3.02f))); + p.drawLine(QPointF(xc - (xc/2.01f), yc - 0.01f), QPointF(xc + (xc/2.02f), yc - 0)); + p.drawLine(QPointF(xc - (xc/2.01f), yc + (yc/3.01f)), QPointF(xc + (xc/2.02f), yc + (yc/3.02f))); + } + + event->accept(); } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_image_editor.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_image_editor.h index a10791323..6878524f9 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_image_editor.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_image_editor.h @@ -1,68 +1,74 @@ - +/** + * @RDE_HEADER@ + * An Image Editor which shows an Image, and emits a signal when clicked (to edit/swap an Image) + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Mike Wille, SLSE, 2016-09-19 + */ #pragma once + #include "lts_widgets_export.h" -#include #include + namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsImageEditor : public QWidget { - Q_OBJECT + Q_OBJECT - Q_PROPERTY(QPixmap pixmap READ pixmap WRITE setPixmap) - Q_PROPERTY(bool menuEnabled READ isMenuEnabled WRITE setMenuEnabled) + Q_PROPERTY(QPixmap pixmap READ pixmap WRITE setPixmap) + Q_PROPERTY(bool menuEnabled READ isMenuEnabled WRITE setMenuEnabled) - public: - explicit LtsImageEditor(QWidget* parent = nullptr); +public: + explicit LtsImageEditor(QWidget *parent = nullptr); - void setPixmap(const QPixmap& pixmap); + /** + * @brief setPixmap sets the picture of this button. If no pixmap / picture is set, the picture-layer is button colored. + * @param pixmap The picture to draw on the button. + */ + void setPixmap(const QPixmap &pixmap); - QPixmap pixmap() const - { - return m_pixmap; - } + /** + * @brief getPixmap TODO + * @return + */ + QPixmap pixmap() const { return m_pixmap; } - void setMenuEnabled(bool enabled = true) - { - m_menuEnabled = enabled; - } + /** + * @brief setMenuEnabled changes the hover & click behaviour. If the menu is enabled, the profile button indicates a menu on hovering, and by clicking it, the signal 'signalClicked' is emitted (menu is enabled by default) + * @param enabled true if menu is enabled, false if not + */ + void setMenuEnabled(bool enabled = true) { m_menuEnabled = enabled; } + bool isMenuEnabled() const { return m_menuEnabled; } - bool isMenuEnabled() const - { - return m_menuEnabled; - } + void setDrawOuterRect(bool bDraw) { m_bDrawOuterRect = bDraw; } + bool drawOuterRect() const { return m_bDrawOuterRect; } - void setDrawOuterRect(bool bDraw) - { - m_bDrawOuterRect = bDraw; - } +protected: + void paintEvent(QPaintEvent *event); + void enterEvent(QEvent *); + void leaveEvent(QEvent *); + bool event(QEvent *event); - bool drawOuterRect() const - { - return m_bDrawOuterRect; - } +private: + QPixmap m_pixmap; + bool m_isHovered; + bool m_menuEnabled; + bool m_bDrawOuterRect; - protected: - void paintEvent(QPaintEvent* event); - void enterEvent(QEnterEvent*); - void leaveEvent(QEvent*); - bool event(QEvent* event); +signals: + /** + * @brief signalClicked is emitted when this widget has been clicked. + */ + void signalClicked(); - private: - QPixmap m_pixmap; - bool m_isHovered; - bool m_menuEnabled; - bool m_bDrawOuterRect; - - signals: - - void signalClicked(); - - void imageChanged(); + void imageChanged(); }; -} // namespace LtsWidgets +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_info_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_info_dialog.cpp index f5e3385d9..57b6efb46 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_info_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_info_dialog.cpp @@ -1,27 +1,35 @@ - +/** + * @RDE_HEADER@ + * Info Dialog, containing informations about this software & build + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Mike Wille, NLSE, 2018-02-26 + */ #include "lts_info_dialog.h" - #include "ui_lts_info_dialog.h" -#include -#include #include +#include +#include + #ifndef LTS_VERSION_MAJOR -#define LTS_VERSION_MAJOR "undefined" + #define LTS_VERSION_MAJOR "undefined" #endif #ifndef LTS_VERSION_MINOR -#define LTS_VERSION_MINOR "undefined" + #define LTS_VERSION_MINOR "undefined" #endif #ifndef LTS_VERSION_PATCH -#define LTS_VERSION_PATCH "undefined" + #define LTS_VERSION_PATCH "undefined" #endif #ifndef LTS_VERSION_DATE -#define LTS_VERSION_DATE "undefined" + #define LTS_VERSION_DATE "undefined" #endif #ifndef JENKINS_BUILD_NUMBER -#define JENKINS_BUILD_NUMBER "unknown" + #define JENKINS_BUILD_NUMBER "unknown" #endif static const char ver_major[] = LTS_VERSION_MAJOR; static const char ver_minor[] = LTS_VERSION_MINOR; @@ -32,43 +40,49 @@ static const char ver_jenkins[] = JENKINS_BUILD_NUMBER; namespace LtsWidgets { -LtsInfoDialog::LtsInfoDialog(QWidget* parent) : LtsFramelessDialog(parent), m_ui(new Ui::LtsInfoDialog) +LtsInfoDialog::LtsInfoDialog(QWidget *parent) + : LtsFramelessDialog(parent) + , m_ui(new Ui::LtsInfoDialog) { - m_ui->setupUi(this); + m_ui->setupUi(this); - QFont f = font(); - f.setBold(true); - m_ui->lblVersion->setFont(f); - m_ui->lblDate->setFont(f); + QFont f = font(); + f.setBold(true); + m_ui->lblVersion->setFont(f); + m_ui->lblDate->setFont(f); - const QString versionString = QStringLiteral("%1.%2-%3 (rev: %4)") - .arg(QString::fromLatin1(ver_major), QString::fromLatin1(ver_minor), - QString::fromLatin1(ver_jenkins), QString::fromLatin1(ver_patch)); - m_ui->lblVersion->setText(versionString); - m_ui->lblDate->setText(QString::fromLatin1(ver_date)); + const QString versionString = QStringLiteral("%1.%2-%3 (rev: %4)") + .arg(QString::fromLatin1(ver_major), + QString::fromLatin1(ver_minor), + QString::fromLatin1(ver_jenkins), + QString::fromLatin1(ver_patch)); + m_ui->lblVersion->setText(versionString); + m_ui->lblDate->setText(QString::fromLatin1(ver_date)); - QString projectLogoFilename(QStringLiteral(":project/login_logo.png")); - if (!QFile(projectLogoFilename).exists()) - projectLogoFilename = QStringLiteral(":/project/logo.png"); + // project logo (have different sizes) + QString projectLogoFilename(QStringLiteral(":project/login_logo.png")); + if (!QFile(projectLogoFilename).exists()) + projectLogoFilename = QStringLiteral(":/project/logo.png"); - QPixmap pixmap(projectLogoFilename); + QPixmap pixmap(projectLogoFilename); - if (pixmap.isNull()) - { - qWarning() << "LtsInfoDialog: project logo missing or is not an valid image " << projectLogoFilename; - } - else - { - int max = m_ui->lblProjectLogo->maximumHeight(); - pixmap = pixmap.scaled(999, max * 0.85f, Qt::KeepAspectRatio, Qt::SmoothTransformation); - m_ui->lblProjectLogo->setPixmap(pixmap); - } - connect(m_ui->pbClose, &QPushButton::clicked, this, &LtsInfoDialog::close); + if (pixmap.isNull()) + { + qWarning() << "LtsInfoDialog: project logo missing or is not an valid image " << projectLogoFilename; + } + else + { + int max = m_ui->lblProjectLogo->maximumHeight(); + pixmap = pixmap.scaled(999, max * 0.85f, Qt::KeepAspectRatio, Qt::SmoothTransformation); + m_ui->lblProjectLogo->setPixmap(pixmap); + } + connect(m_ui->pbClose, &QPushButton::clicked, this, &LtsInfoDialog::close); } + LtsInfoDialog::~LtsInfoDialog() { - delete m_ui; + delete m_ui; } } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_info_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_info_dialog.h index 1c65c1817..72a25648d 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_info_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_info_dialog.h @@ -1,10 +1,18 @@ - +/** + * @RDE_HEADER@ + * Info Dialog, containing informations about this software & build + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Mike Wille, NLSE, 2018-02-26 + */ #pragma once + #include "lts_frameless_dialog.h" #include "lts_widgets_export.h" -#include namespace Ui { @@ -15,13 +23,13 @@ namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsInfoDialog : public LtsFramelessDialog { - Q_OBJECT + Q_OBJECT - public: - explicit LtsInfoDialog(QWidget* parent = nullptr); - ~LtsInfoDialog(); +public: + explicit LtsInfoDialog(QWidget *parent = nullptr); + ~LtsInfoDialog(); - private: - Ui::LtsInfoDialog* m_ui; +private: + Ui::LtsInfoDialog *m_ui; }; } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_led_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_led_widget.cpp index 22ca53fbb..a7c9b3cb8 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_led_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_led_widget.cpp @@ -1,137 +1,154 @@ - +/** + * @RDE_HEADER@ + * Class of Led Widget + * $Id$ + * $HeadURL$ + * $Author$ + */ #include "lts_led_widget.h" - #include #include #include - namespace LtsWidgets { -void LtsLedWidget::resizeEvent(QResizeEvent* event) +void LtsLedWidget::resizeEvent(QResizeEvent *event) { - switch (m_aspectHint) - { - case AspectHint::NoHint: { - - QWidget::resizeEvent(event); - break; - } - case AspectHint::HeightIsWidth: - setMinimumHeight(event->size().width()); - setMaximumHeight(event->size().width()); - setMinimumWidth(0); - setMaximumWidth(65000); - break; - case AspectHint::WidthIsHeight: - setMinimumHeight(0); - setMaximumHeight(65000); - setMinimumWidth(event->size().height()); - setMaximumWidth(event->size().height()); - break; - } + switch (m_aspectHint) { + case AspectHint::NoHint: + { + // NOTE: the next 4 lines would overwrite set properties from ui files +// setMinimumWidth(0); +// setMaximumWidth(65000); +// setMinimumHeight(0); +// setMaximumHeight(65000); + QWidget::resizeEvent(event); + break; + } + case AspectHint::HeightIsWidth: + setMinimumHeight(event->size().width()); + setMaximumHeight(event->size().width()); + setMinimumWidth(0); + setMaximumWidth(65000); + break; + case AspectHint::WidthIsHeight: + setMinimumHeight(0); + setMaximumHeight(65000); + setMinimumWidth(event->size().height()); + setMaximumWidth(event->size().height()); + break; + } } -static constexpr double GRADIENT_KEY_LOWER = 0.3; -static constexpr double GRADIENT_KEY_UPPER = 0.9; -static constexpr int GRADIENT_VALUE_LOWER = 125; -static constexpr int GRADIENT_VALUE_UPPER = 165; -static constexpr double GRADIENT_CENTER_OFFSET = 5.0; -static constexpr double GRADIENT_FOCALPOINT_OFFSET = 2.7; -static constexpr double PERCENTAGE_OF_BORDER = 0.1; -static constexpr int DARK_FACTOR = 200; +/** + * The following values were determined by trial and error: + */ +static constexpr double GRADIENT_KEY_LOWER = 0.3; +static constexpr double GRADIENT_KEY_UPPER = 0.9; +static constexpr int GRADIENT_VALUE_LOWER = 125; +static constexpr int GRADIENT_VALUE_UPPER = 165; +static constexpr double GRADIENT_CENTER_OFFSET = 5.0; +static constexpr double GRADIENT_FOCALPOINT_OFFSET = 2.7; +static constexpr double PERCENTAGE_OF_BORDER = 0.1; +static constexpr int DARK_FACTOR = 200; -LtsLedWidget::LtsLedWidget(QWidget* parent, const QColor& oncolor, const QColor& offcolor, bool useGradient, - int animtime) - : QWidget(parent), m_status(true), m_oncolor(oncolor), m_offcolor(offcolor), m_currentcolor(oncolor), - m_gradient(useGradient), m_animTime(animtime) +LtsLedWidget::LtsLedWidget(QWidget *parent, const QColor &oncolor, const QColor &offcolor, bool useGradient, int animtime) + : QWidget(parent) + , m_status(true) + , m_oncolor(oncolor) + , m_offcolor(offcolor) + , m_currentcolor(oncolor) + , m_gradient(useGradient) + , m_animTime(animtime) { - setObjectName(QString::fromUtf8("LtsLedWidget")); + setObjectName(QString::fromUtf8("LtsLedWidget")); } -void LtsLedWidget::paintEvent(QPaintEvent* pe) +void LtsLedWidget::paintEvent(QPaintEvent *pe) { - Q_UNUSED(pe); - QPainter p; - p.begin(this); - p.setOpacity(QWidget::isEnabled() ? 1.00 : 0.5); + Q_UNUSED(pe); + QPainter p; + p.begin(this); + p.setOpacity(QWidget::isEnabled() ? 1.00 : 0.5); - int minSize = height() > width() ? width() : height(); - if (m_gradient) - { - QRadialGradient grad(QPointF(width(), height()) / GRADIENT_CENTER_OFFSET, minSize, - QPointF(width(), height()) / GRADIENT_FOCALPOINT_OFFSET); - grad.setColorAt(GRADIENT_KEY_LOWER, m_currentcolor.lighter(GRADIENT_VALUE_LOWER)); - grad.setColorAt(GRADIENT_KEY_UPPER, m_currentcolor.darker(GRADIENT_VALUE_UPPER)); - p.setBrush(grad); - } - else - p.setBrush(QBrush(m_currentcolor, Qt::SolidPattern)); + int minSize = height() > width() ? width() : height(); + if (m_gradient) + { + QRadialGradient grad(QPointF(width(), height()) / GRADIENT_CENTER_OFFSET, // Center + minSize, // Radius + QPointF(width(), height()) / GRADIENT_FOCALPOINT_OFFSET); // FocalPoint + grad.setColorAt(GRADIENT_KEY_LOWER, m_currentcolor.lighter(GRADIENT_VALUE_LOWER)); + grad.setColorAt(GRADIENT_KEY_UPPER, m_currentcolor.darker(GRADIENT_VALUE_UPPER)); + p.setBrush(grad); + } + else + p.setBrush(QBrush(m_currentcolor, Qt::SolidPattern)); - p.setRenderHint(QPainter::Antialiasing); - p.setPen(QPen(Qt::black, PERCENTAGE_OF_BORDER * minSize, Qt::SolidLine, Qt::SquareCap)); - p.drawEllipse(QPointF(width(), height()) / 2.0, width() / (2.0 * (1.00 + PERCENTAGE_OF_BORDER)), - height() / (2.0 * (1.00 + PERCENTAGE_OF_BORDER))); - p.end(); + p.setRenderHint(QPainter::Antialiasing); + p.setPen(QPen(Qt::black, PERCENTAGE_OF_BORDER * minSize, Qt::SolidLine, Qt::SquareCap)); + p.drawEllipse(QPointF(width(), height()) / 2.0, + width() / (2.0 * (1.00 + PERCENTAGE_OF_BORDER)), + height() / (2.0 * (1.00 + PERCENTAGE_OF_BORDER))); + p.end(); } void LtsLedWidget::animate() { - QPropertyAnimation* anim = new QPropertyAnimation(this, "currentcolor"); - anim->setDuration(m_animTime); - anim->setEasingCurve(QEasingCurve::OutBack); - anim->setStartValue(m_currentcolor); - anim->setEndValue(m_status ? m_oncolor : m_offcolor == Qt::black ? m_oncolor.darker(DARK_FACTOR) : m_offcolor); - anim->start(QPropertyAnimation::DeleteWhenStopped); + QPropertyAnimation *anim = new QPropertyAnimation(this, "currentcolor"); + anim->setDuration(m_animTime); + anim->setEasingCurve(QEasingCurve::OutBack); + anim->setStartValue(m_currentcolor); + anim->setEndValue(m_status ? m_oncolor : m_offcolor == Qt::black ? m_oncolor.darker(DARK_FACTOR) : m_offcolor); + anim->start(QPropertyAnimation::DeleteWhenStopped); } void LtsLedWidget::setStatus(bool status) { - if (m_status == status) - return; - m_status = status; - animate(); + if (m_status == status) + return; + m_status = status; + animate(); } void LtsLedWidget::setUseGradient(bool useGradient) { - if (m_gradient == useGradient) - return; - m_gradient = useGradient; - repaint(); + if (m_gradient == useGradient) + return; + m_gradient = useGradient; + repaint(); } -void LtsLedWidget::setColor(const QColor& oncolor, const QColor& offcolor) +void LtsLedWidget::setColor(const QColor &oncolor, const QColor &offcolor) { - setOnColor(oncolor); - setOffColor(offcolor); + setOnColor(oncolor); + setOffColor(offcolor); } -void LtsLedWidget::setOnColor(const QColor& oncolor) +void LtsLedWidget::setOnColor(const QColor &oncolor) { - if (m_oncolor == oncolor) - return; - m_oncolor = oncolor; - if (m_status) - animate(); + if (m_oncolor == oncolor) + return; + m_oncolor = oncolor; + if (m_status) + animate(); } -void LtsLedWidget::setOffColor(const QColor& offcolor) +void LtsLedWidget::setOffColor(const QColor &offcolor) { - if (m_offcolor == offcolor) - return; - m_offcolor = offcolor; - if (!m_status) - animate(); + if (m_offcolor == offcolor) + return; + m_offcolor = offcolor; + if (!m_status) + animate(); } -void LtsLedWidget::setCurrentColor(const QColor& currentcolor) +void LtsLedWidget::setCurrentColor(const QColor ¤tcolor) { - if (m_currentcolor == currentcolor) - return; - m_currentcolor = currentcolor; - repaint(); + if (m_currentcolor == currentcolor) + return; + m_currentcolor = currentcolor; + repaint(); } -} // namespace LtsWidgets +} // namespace namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_led_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_led_widget.h index 0ee246170..18e86154e 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_led_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_led_widget.h @@ -1,107 +1,178 @@ - - +/** + * @RDE_HEADER@ + * LTS LED Widget + * $Id$ + * $HeadURL$ + * $Author$ + */ #pragma once -#include "lts_widgets_export.h" -#include #include +#include "lts_widgets_export.h" namespace LtsWidgets { +/** + * This class generates a LED with 2D/3D design, customizable colors and animation. + * + * If you need more than two states, simple derive from this class, only use "status=on" + * generate pairs of identifiers and colors and change the colors with appropriate method: + * e.g.: + * DerivedLEDWidget(...) : LtsLedWidget() {} + * enum Status { ST_STATUS1 = 0, ST_STATUS2, ST_STATUS3 }; + * static QMap cMap; // Fill it respectively + * DerivedLEDWidget::setStatus(Status b) { setOnColor(cMap.value(b, Qt::black)); } + */ class LTSWIDGETS_EXPORT LtsLedWidget : public QWidget { - Q_OBJECT + Q_OBJECT - public: - enum class AspectHint { WidthIsHeight, NoHint, HeightIsWidth }; - Q_ENUM(AspectHint) +public: + enum class AspectHint + { + WidthIsHeight, + NoHint, + HeightIsWidth + }; + Q_ENUM(AspectHint) - Q_PROPERTY(QColor oncolor READ onColor WRITE setOnColor) - Q_PROPERTY(QColor offcolor READ offColor WRITE setOffColor) - Q_PROPERTY(bool status READ status WRITE setStatus) - Q_PROPERTY(bool usesGradient READ usesGradient WRITE setUseGradient) - Q_PROPERTY(int animTime READ animTime WRITE setAnimTime) - Q_PROPERTY(AspectHint aspectHint READ aspectHint WRITE setAspectHint) - Q_PROPERTY(QColor currentcolor READ currentColor WRITE setCurrentColor DESIGNABLE false) + Q_PROPERTY(QColor oncolor READ onColor WRITE setOnColor) + Q_PROPERTY(QColor offcolor READ offColor WRITE setOffColor) + Q_PROPERTY(bool status READ status WRITE setStatus) + Q_PROPERTY(bool usesGradient READ usesGradient WRITE setUseGradient) + Q_PROPERTY(int animTime READ animTime WRITE setAnimTime) + Q_PROPERTY(AspectHint aspectHint READ aspectHint WRITE setAspectHint) + Q_PROPERTY(QColor currentcolor READ currentColor WRITE setCurrentColor DESIGNABLE false) - explicit LtsLedWidget(QWidget* parent = nullptr, const QColor& oncolor = Qt::red, - const QColor& offcolor = Qt::black, bool useGradient = true, int animtime = 0); + /** + * Constructor + * @param parent The widget's parent. Default value is NULL. + * @param oncolor The color for LED when turned on. Default value is Qt::red, see also setOnColor() for details. + * @param offcolor The color for LED when turned off. Default value is Qt::black (i.e. "Use darker color"), see also setOffColor() for details. + * @param useGradient The 2D/3D design status. Default value is true (3D). + * @param animtime The animation time in msecs. Default value is 0. + */ + explicit LtsLedWidget(QWidget *parent = nullptr, const QColor &oncolor = Qt::red, const QColor &offcolor = Qt::black, bool useGradient = true, int animtime = 0); - void paintEvent(QPaintEvent* pe); + void paintEvent(QPaintEvent *pe); - void setAnimTime(int time) - { - m_animTime = time; - } + /** + * Set animation time in msec + * Value = 0 shows no animation + * Reasonable value is between 400 and 700 msecs + * @param time time in msecs + */ + void setAnimTime(int time) { m_animTime = time; } - int animTime() const - { - return m_animTime; - } + /** + * Get current animation time in msecs + * @return animation time in msecs + */ + int animTime() const { return m_animTime; } - bool status() const - { - return m_status; - } + /** + * Get current led status + * @return the LED's status + */ + bool status() const { return m_status; } - void setUseGradient(bool useGradient); + /** + * Set 2D/3D design + * Value true set a 3D design of the led widget, + * Value false set a 2D design of the led widget + * @param useGradient + */ + void setUseGradient(bool useGradient); - bool usesGradient() const - { - return m_gradient; - } + /** + * Get a state info about the current 2D/3D design + * @return true for 3D and false for 2D design + */ + bool usesGradient() const { return m_gradient; } - void setOnColor(const QColor& oncolor); + /** + * Set the color for the LED when turned "on". + * If status is "on" and the oncolor is changed + * the animation will be run. + * @param oncolor color for LED in state "on" + */ + void setOnColor(const QColor &oncolor); - QColor onColor() const - { - return m_oncolor; - } + /** + * Get the current oncolor + * @return the current oncolor + */ + QColor onColor() const { return m_oncolor; } - void setOffColor(const QColor& offcolor); + /** + * Set the color for the LED when turned "off". + * If offcolor is black the wigdet use a darker version of oncolor as offcolor value. + * If status is "off" and the offcolor is changed + * the animation will be run. + * @param offcolor color for LED in state "off" + */ + void setOffColor(const QColor &offcolor); - QColor offColor() const - { - return m_offcolor; - } + /** + * Get the current offcolor + * @return the current offcolor + */ + QColor offColor() const { return m_offcolor; } - void setColor(const QColor& oncolor, const QColor& offcolor = Qt::black); + /** + * Convenience function set oncolor and offcolor in one step + * Default value for offcolor is black. + * If offcolor is black the wigdet use a darker version of oncolor as offcolor value. + * @param oncolor The color for LED when turned on. + * @param offcolor The color for LED when turned off. Default value is Qt::black (i.e. "Use darker color"). + */ + void setColor(const QColor &oncolor, const QColor &offcolor = Qt::black); - QColor currentColor() const - { - return m_currentcolor; - } + /** + * Get current color + * @return the currently visible color + */ + QColor currentColor() const { return m_currentcolor; } - void resizeEvent(QResizeEvent* event); + void resizeEvent(QResizeEvent *event); - AspectHint aspectHint() const - { - return m_aspectHint; - } + AspectHint aspectHint() const { return m_aspectHint; } - public slots: +public slots: + /** + * Public slot set current led status + * @param status The LED's status (on/off) + */ + void setStatus(bool status); - void setStatus(bool status); + void setAspectHint(AspectHint aspectHint) + { + m_aspectHint = aspectHint; + } - void setAspectHint(AspectHint aspectHint) - { - m_aspectHint = aspectHint; - } +private: + /** + * Set current color + * Needed for color animation + * ***This method is private for a reason!*** + * @param currentcolor + */ + void setCurrentColor(const QColor ¤tcolor); - private: - void setCurrentColor(const QColor& currentcolor); + /** + * Private function to start the color animation + */ + void animate(); - void animate(); + bool m_status; + QColor m_oncolor; + QColor m_offcolor; + QColor m_currentcolor; - bool m_status; - QColor m_oncolor; - QColor m_offcolor; - QColor m_currentcolor; - - bool m_gradient; - int m_animTime; - AspectHint m_aspectHint = AspectHint::NoHint; + bool m_gradient; + int m_animTime; + AspectHint m_aspectHint = AspectHint::NoHint; }; } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog.cpp index 98e001272..13f450b47 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog.cpp @@ -1,126 +1,133 @@ #include "lts_message_dialog.h" - #include "lts_message_dialog_helper.h" #include -#include +#include #include #include -#include +#include + namespace LtsWidgets { namespace LtsMessageDialog { -Button showMessage(QWidget* parent, const QString& message, const QString& title, const Behaviour behaviour, - const Buttons buttons, const QHash& buttonTexts) +Button showMessage(QWidget* parent, + const QString& message, + const QString &title, + const Behaviour behaviour, + const Buttons buttons, + const QHash &buttonTexts) { - static QAtomicInt s_used = 0; + static QAtomicInt s_used = 0; - if (s_used) - qDebug() << "LtsMessageDialog: showMessage called while showMessage is in its Event Loop - do not open more " - "than one Dialog at once !!"; + if (s_used) + qDebug() << "LtsMessageDialog: showMessage called while showMessage is in its Event Loop - do not open more than one Dialog at once !!"; - s_used = 1; + s_used = 1; - LtsMessageDialogHelper* dialog = new LtsMessageDialogHelper(); - Button result = dialog->showMessage(parent, message, title, behaviour, buttons, buttonTexts); - dialog->deleteLater(); + LtsMessageDialogHelper *dialog = new LtsMessageDialogHelper(); // NOT 'parent' ! + Button result = dialog->showMessage(parent, message, title, behaviour, buttons, buttonTexts); + dialog->deleteLater(); - s_used = 0; + s_used = 0; - return result; + return result; } -Button askApplyDiscardCancel(QWidget* parent) +Button askApplyDiscardCancel(QWidget *parent) { - const QString question = QCoreApplication::translate("LtsDialog", "
" - "Apply - apply changes and close.
" - "Discard - discard changes and close.
" - "Cancel - do not close."); - const QString title = QCoreApplication::translate("LtsDialog", "Unapplied changes made. Apply the changes?"); - return LtsMessageDialog::showMessage(parent, question, title, Behaviour::Modal, - Button::Apply | Button::Discard | Button::Cancel); + const QString question = QCoreApplication::translate("LtsDialog", + "
" + "Apply - apply changes and close.
" + "Discard - discard changes and close.
" + "Cancel - do not close."); + const QString title = QCoreApplication::translate("LtsDialog", "Unapplied changes made. Apply the changes?"); + return LtsMessageDialog::showMessage(parent, + question, + title, + Behaviour::Modal, + Button::Apply | Button::Discard | Button::Cancel); } + } // namespace LtsMessageDialog -LtsMessageDialogNew::LtsMessageDialogNew(QWidget* parent, const QString& message, const QString& title, - const Behaviour behaviour, const Buttons buttons, - const QHash& buttonTexts, bool deleteOnClose) + + +// LtsWidgets +LtsMessageDialogNew::LtsMessageDialogNew(QWidget *parent, const QString &message, const QString &title, const Behaviour behaviour, const Buttons buttons, const QHash &buttonTexts, bool deleteOnClose) { - m_dialog = new LtsFramelessDialog(parent, behaviour); + m_dialog = new LtsFramelessDialog(parent, behaviour); - if (deleteOnClose) - m_dialog->setAttribute(Qt::WA_DeleteOnClose); + if (deleteOnClose) + m_dialog->setAttribute(Qt::WA_DeleteOnClose); // Message Dialogs are loose instances that must delete theirselves, because noone keeps a pointer to the message dialog - connect(m_dialog, &LtsFramelessDialog::destroyed, this, &LtsMessageDialogNew::deleteLater); + connect(m_dialog, &LtsFramelessDialog::destroyed, + this, &LtsMessageDialogNew::deleteLater); - QVBoxLayout* mainLayout = new QVBoxLayout(m_dialog); + QVBoxLayout *mainLayout = new QVBoxLayout(m_dialog); - QString text; - if (!title.isEmpty()) - { - text = QStringLiteral("%1

").arg(title); - } + QString text; + if (!title.isEmpty()) // title given? + { + text = QStringLiteral("%1

").arg(title); + } - text += message; + text += message; - QLabel* messageLabel = new QLabel(text, m_dialog); - messageLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); - mainLayout->addWidget(messageLabel); + QLabel *messageLabel = new QLabel(text, m_dialog); + messageLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); // make text selectable by mouse + mainLayout->addWidget(messageLabel); - QHBoxLayout* buttonLayout = new QHBoxLayout; - buttonLayout->setContentsMargins(0, 0, 0, 0); + QHBoxLayout *buttonLayout = new QHBoxLayout; + buttonLayout->setMargin(0); - if (buttons.testFlag(Button::Ok)) - connect(addButton(buttonTexts.value(Button::Ok, tr("Ok")), buttonLayout, m_dialog, Button::Ok, parent), - &QPushButton::clicked, this, &LtsMessageDialogNew::ok); + // TODO: FIXME: can this be called after the selection was made and the shadow just dies ? + //connect(m_dialog, &LtsFramelessDialog::rejected, this, &LtsMessageDialogHelper::slotCancel); // respect that non-modal dialogs can be closed by clicking outside of it - if (buttons.testFlag(Button::Yes)) - connect(addButton(buttonTexts.value(Button::Yes, tr("Yes")), buttonLayout, m_dialog, Button::Yes, parent), - &QPushButton::clicked, this, &LtsMessageDialogNew::yes); + if (buttons.testFlag(Button::Ok)) + connect(addButton(buttonTexts.value(Button::Ok, tr("Ok")), buttonLayout, m_dialog, Button::Ok, parent), &QPushButton::clicked, this, &LtsMessageDialogNew::ok); - if (buttons.testFlag(Button::No)) - connect(addButton(buttonTexts.value(Button::No, tr("No")), buttonLayout, m_dialog, Button::No, parent), - &QPushButton::clicked, this, &LtsMessageDialogNew::no); + if (buttons.testFlag(Button::Yes)) + connect(addButton(buttonTexts.value(Button::Yes, tr("Yes")), buttonLayout, m_dialog, Button::Yes, parent), &QPushButton::clicked, this, &LtsMessageDialogNew::yes); - if (buttons.testFlag(Button::Apply)) - connect(addButton(buttonTexts.value(Button::Apply, tr("Apply")), buttonLayout, m_dialog, Button::Apply, parent), - &QPushButton::clicked, this, &LtsMessageDialogNew::apply); + if (buttons.testFlag(Button::No)) + connect(addButton(buttonTexts.value(Button::No, tr("No")), buttonLayout, m_dialog, Button::No, parent), &QPushButton::clicked, this, &LtsMessageDialogNew::no); - if (buttons.testFlag(Button::Discard)) - connect(addButton(buttonTexts.value(Button::Discard, tr("Discard")), buttonLayout, m_dialog, Button::Discard, - parent), - &QPushButton::clicked, this, &LtsMessageDialogNew::discard); + if (buttons.testFlag(Button::Apply)) + connect(addButton(buttonTexts.value(Button::Apply, tr("Apply")), buttonLayout, m_dialog, Button::Apply, parent), &QPushButton::clicked, this, &LtsMessageDialogNew::apply); // same as yes - if (buttons.testFlag(Button::Cancel)) - connect( - addButton(buttonTexts.value(Button::Cancel, tr("Cancel")), buttonLayout, m_dialog, Button::Cancel, parent), - &QPushButton::clicked, this, &LtsMessageDialogNew::cancel); + if (buttons.testFlag(Button::Discard)) + connect(addButton(buttonTexts.value(Button::Discard, tr("Discard")), buttonLayout, m_dialog, Button::Discard, parent), &QPushButton::clicked, this, &LtsMessageDialogNew::discard); // same as no - QWidget* buttonLayoutWidget = new QWidget; - buttonLayoutWidget->setLayout(buttonLayout); + if (buttons.testFlag(Button::Cancel)) + connect(addButton(buttonTexts.value(Button::Cancel, tr("Cancel")), buttonLayout, m_dialog, Button::Cancel, parent), &QPushButton::clicked, this, &LtsMessageDialogNew::cancel); - mainLayout->addWidget(buttonLayoutWidget); + QWidget *buttonLayoutWidget = new QWidget; + buttonLayoutWidget->setLayout(buttonLayout); - m_dialog->show(); - m_dialog->raise(); + mainLayout->addWidget(buttonLayoutWidget); + + m_dialog->show(); + m_dialog->raise(); } -QPushButton* LtsMessageDialogNew::addButton(const QString& text, QHBoxLayout* thatLayout, LtsFramelessDialog* dialog, - const Button& button, QWidget* parent) + +QPushButton* LtsMessageDialogNew::addButton(const QString &text, QHBoxLayout *thatLayout, LtsFramelessDialog *dialog, const Button &button, QWidget *parent) { - QPushButton* btn = new QPushButton(text, parent); - connect(btn, &QPushButton::clicked, dialog, &LtsFramelessDialog::accept); - thatLayout->addWidget(btn); + QPushButton* btn = new QPushButton(text, parent); + connect(btn, &QPushButton::clicked, dialog, &LtsFramelessDialog::accept); + thatLayout->addWidget(btn); - if (button == Button::Ok || button == Button::Cancel) - { - btn->setDefault(true); - } + if (button == Button::Ok || + button == Button::Cancel) // ok and cancel should not be used together, so there is no check needed (as only one button can be the default button) + { + btn->setDefault(true); + } - return btn; + return btn; } + } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog.h index f6fee4bea..4d1b4ac81 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog.h @@ -1,67 +1,102 @@ #pragma once -#include "lts_frameless_dialog.h" #include "lts_widgets_export.h" +#include "lts_frameless_dialog.h" -#include -#include #include +#include + class QWidget; class QHBoxLayout; + namespace LtsWidgets { -enum class Button { - UNKNOWN = 0, - Ok = 1, - Yes = 2, - No = 4, - Cancel = 8, +/** + * @brief The Button enum describes one or more buttons, which should be shown on a Dialog which supports LtsWidgets::Button. Also this enum + * is the return type of LtsMessageDialog and provides the button clicked to close the Popup-Dialog. + */ +enum class Button +{ + UNKNOWN = 0, + Ok = 1, + Yes = 2, + No = 4, + Cancel = 8, - Apply = 16, - Discard = 32, + Apply = 16, + Discard = 32, }; Q_DECLARE_FLAGS(Buttons, Button) - inline uint qHash(LtsWidgets::Button b) { - return ::qHash(static_cast(b)); + return ::qHash(static_cast(b)); } -namespace LtsMessageDialog +/** + * @brief [Please consider using LtsMessageDialogNew] The LtsMessageDialog class provides a BLOCKING Popup-Dialog (based on LtsFramelessDialog) to show a message to the user with selectable buttons. This class is static and cannot be instantiated. + * To show a message to the user class 'LtsMessageDialog::showMessage(..)'. And to get the button that was selected by the user to close the dialog, consider the return type 'LtsWidgets::Button'. + * This Popup-Dialog closes automatically if any button on it is clicked. + * The return type is an enum class instance which contains the information about the clicked button. + * If no button was specified there is no chance to close the dialog if LtsWidgets::Behaviour::Modal was specified. + */ +namespace LtsMessageDialog // in reality this is the helper, but for "naming's sake", this is not called the helper { - -LTSWIDGETS_EXPORT Button showMessage(QWidget* parent, const QString& message, const QString& title = QString(), - const Behaviour behaviour = Behaviour::Modal, const Buttons buttons = Button::Ok, - const QHash& buttonTexts = QHash()); -LTSWIDGETS_EXPORT Button askApplyDiscardCancel(QWidget* parent); +/** + * @brief showMessage shows a Popup-Dialog to show a message to the user with selectable buttons - method is blocking (creates new EventLoop)! + * @param parent The widget to be covered. + * @param message The message to the user. + * @param behaviour How the Popup-Dialog should behave (see LtsFramelessDialog). + * @param buttons A list of Buttons to provide to the user. + * @param buttonTexts If set, the button texts are used from there instead the default ones + * @return The button that has been clicked by the user to close this Popup-Dialog. + */ +LTSWIDGETS_EXPORT Button showMessage(QWidget* parent, + const QString &message, + const QString &title = QString(), + const Behaviour behaviour = Behaviour::Modal, + const Buttons buttons = Button::Ok, + const QHash &buttonTexts = QHash()); +LTSWIDGETS_EXPORT Button askApplyDiscardCancel(QWidget *parent); } // namespace LtsMessageDialog + + +/** + * @brief The LtsMessageDialog class provides a NON-BLOCKING Popup-Dialog (based on LtsFramelessDialog) to show a message to the user with selectable buttons. + * To show a message to the user use: connect(new LtsMessageDialogNew(this, title, message), &LtsMessageDialogNew::ok, this, &MyDialog::mySlot); + * This Popup-Dialog closes automatically if any button on it is clicked. + * Keep in mind that as this dialog does not block, following code gets executed right afetr creating this dialog. + */ class LTSWIDGETS_EXPORT LtsMessageDialogNew : public QObject { - Q_OBJECT + Q_OBJECT - public: - explicit LtsMessageDialogNew(QWidget* parent, const QString& message, const QString& title = QString(), - const Behaviour behaviour = Behaviour::Modal, const Buttons buttons = Button::Ok, - const QHash& buttonTexts = QHash(), - bool deleteOnClose = true); +public: + explicit LtsMessageDialogNew(QWidget* parent, + const QString &message, + const QString &title = QString(), + const Behaviour behaviour = Behaviour::Modal, + const Buttons buttons = Button::Ok, + const QHash &buttonTexts = QHash(), + bool deleteOnClose = true /* retain c++ conformity by this convenience bool */); - private: - LtsFramelessDialog* m_dialog; +private: + LtsFramelessDialog *m_dialog; - QPushButton* addButton(const QString& text, QHBoxLayout* thatLayout, LtsFramelessDialog* dialog, - const Button& button, QWidget* parent); + QPushButton *addButton(const QString &text, QHBoxLayout *thatLayout, LtsFramelessDialog *dialog, const Button &button, QWidget *parent); + + +signals: + void ok(); + void yes(); + void no(); + void apply(); + void discard(); + void cancel(); - signals: - void ok(); - void yes(); - void no(); - void apply(); - void discard(); - void cancel(); }; } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog_helper.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog_helper.cpp index e66ffe28a..0e4817e57 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog_helper.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog_helper.cpp @@ -1,142 +1,155 @@ #include "lts_message_dialog_helper.h" -#include -#include -#include #include #include +#include +#include +#include + namespace LtsWidgets { -LtsMessageDialogHelper::LtsMessageDialogHelper(QObject* parent) - : QObject(parent), m_result(Button::Cancel), m_dialog(nullptr) +LtsMessageDialogHelper::LtsMessageDialogHelper(QObject *parent) + : QObject(parent) + , m_result(Button::Cancel) + , m_dialog(nullptr) +{} + + +Button LtsMessageDialogHelper::showMessage(QWidget *parent, + const QString &message, + const QString &title, + Behaviour behaviour, + Buttons buttons, + const QHash &buttonTexts) { -} + m_dialog = new LtsFramelessDialog(parent, behaviour); -Button LtsMessageDialogHelper::showMessage(QWidget* parent, const QString& message, const QString& title, - Behaviour behaviour, Buttons buttons, - const QHash& buttonTexts) -{ - m_dialog = new LtsFramelessDialog(parent, behaviour); + m_dialog->setAttribute(Qt::WA_DeleteOnClose); // Message Dialogs are loose instances that must delete theirselves, because noone keeps a pointer to the message dialog - m_dialog->setAttribute(Qt::WA_DeleteOnClose); + QVBoxLayout *mainLayout = new QVBoxLayout(m_dialog); - QVBoxLayout* mainLayout = new QVBoxLayout(m_dialog); + QString text; + if (!title.isEmpty()) // title given? + { + text = QStringLiteral("%1

").arg(title); + } - QString text; - if (!title.isEmpty()) - { - text = QStringLiteral("%1

").arg(title); - } + text += message; - text += message; + QLabel *messageLabel = new QLabel(text, m_dialog); + messageLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); // make text selectable by mouse + mainLayout->addWidget(messageLabel); - QLabel* messageLabel = new QLabel(text, m_dialog); - messageLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); - mainLayout->addWidget(messageLabel); + QHBoxLayout *buttonLayout = new QHBoxLayout; + buttonLayout->setMargin(0); - QHBoxLayout* buttonLayout = new QHBoxLayout; - buttonLayout->setContentsMargins(0, 0, 0, 0); + // TODO: FIXME: can this be called after the selection was made and the shadow just dies ? + connect(m_dialog, &LtsFramelessDialog::rejected, this, &LtsMessageDialogHelper::slotCancel); // respect that non-modal dialogs can be closed by clicking outside of it - connect(m_dialog, &LtsFramelessDialog::rejected, this, &LtsMessageDialogHelper::slotCancel); + if (buttons.testFlag(Button::Ok)) + connect(addButton(buttonTexts.value(Button::Ok, tr("Ok")), buttonLayout, m_dialog, Button::Ok, parent), + &QPushButton::clicked, this, &LtsMessageDialogHelper::slotOkay); - if (buttons.testFlag(Button::Ok)) - connect(addButton(buttonTexts.value(Button::Ok, tr("Ok")), buttonLayout, m_dialog, Button::Ok, parent), - &QPushButton::clicked, this, &LtsMessageDialogHelper::slotOkay); + if (buttons.testFlag(Button::Yes)) + connect(addButton(buttonTexts.value(Button::Yes, tr("Yes")), buttonLayout, m_dialog, Button::Yes, parent), + &QPushButton::clicked, this, &LtsMessageDialogHelper::slotYes); - if (buttons.testFlag(Button::Yes)) - connect(addButton(buttonTexts.value(Button::Yes, tr("Yes")), buttonLayout, m_dialog, Button::Yes, parent), - &QPushButton::clicked, this, &LtsMessageDialogHelper::slotYes); + if (buttons.testFlag(Button::No)) + connect(addButton(buttonTexts.value(Button::No, tr("No")), buttonLayout, m_dialog, Button::No, parent), + &QPushButton::clicked, this, &LtsMessageDialogHelper::slotNo); - if (buttons.testFlag(Button::No)) - connect(addButton(buttonTexts.value(Button::No, tr("No")), buttonLayout, m_dialog, Button::No, parent), - &QPushButton::clicked, this, &LtsMessageDialogHelper::slotNo); + if (buttons.testFlag(Button::Apply)) + connect(addButton(buttonTexts.value(Button::Apply, tr("Apply")), buttonLayout, m_dialog, Button::Apply, parent), + &QPushButton::clicked, this, &LtsMessageDialogHelper::slotApply); // same as yes - if (buttons.testFlag(Button::Apply)) - connect(addButton(buttonTexts.value(Button::Apply, tr("Apply")), buttonLayout, m_dialog, Button::Apply, parent), - &QPushButton::clicked, this, &LtsMessageDialogHelper::slotApply); + if (buttons.testFlag(Button::Discard)) + connect(addButton(buttonTexts.value(Button::Discard, tr("Discard")), buttonLayout, m_dialog, Button::Discard, parent), + &QPushButton::clicked, this, &LtsMessageDialogHelper::slotDiscard); // same as no - if (buttons.testFlag(Button::Discard)) - connect(addButton(buttonTexts.value(Button::Discard, tr("Discard")), buttonLayout, m_dialog, Button::Discard, - parent), - &QPushButton::clicked, this, &LtsMessageDialogHelper::slotDiscard); - - if (buttons.testFlag(Button::Cancel)) - connect( - addButton(buttonTexts.value(Button::Cancel, tr("Cancel")), buttonLayout, m_dialog, Button::Cancel, parent), + if (buttons.testFlag(Button::Cancel)) + connect(addButton(buttonTexts.value(Button::Cancel, tr("Cancel")), buttonLayout, m_dialog, Button::Cancel, parent), &QPushButton::clicked, this, &LtsMessageDialogHelper::slotCancel); - QWidget* buttonLayoutWidget = new QWidget; - buttonLayoutWidget->setLayout(buttonLayout); + QWidget *buttonLayoutWidget = new QWidget; + buttonLayoutWidget->setLayout(buttonLayout); - mainLayout->addWidget(buttonLayoutWidget); + mainLayout->addWidget(buttonLayoutWidget); - m_dialog->show(); - m_dialog->raise(); + m_dialog->show(); + m_dialog->raise(); - QEventLoop loop; - connect(this, &LtsMessageDialogHelper::signalQuitEventLoop, &loop, &QEventLoop::quit, Qt::QueuedConnection); - loop.exec(); + // this class is called a dialog, but is not a QDialog, so there is no event loop to wait for a result to return, so we create our own event loop + QEventLoop loop; + connect(this, &LtsMessageDialogHelper::signalQuitEventLoop, &loop, &QEventLoop::quit, Qt::QueuedConnection); + loop.exec(); // now wait for new result value before returning - return m_result; + return m_result; } + void LtsMessageDialogHelper::slotOkay() { - m_dialog->hide(); - m_result = Button::Ok; - emit signalQuitEventLoop(); + m_dialog->hide(); + m_result = Button::Ok; + emit signalQuitEventLoop(); } + void LtsMessageDialogHelper::slotYes() { - m_dialog->hide(); - m_result = Button::Yes; - emit signalQuitEventLoop(); + m_dialog->hide(); + m_result = Button::Yes; + emit signalQuitEventLoop(); } + void LtsMessageDialogHelper::slotNo() { - m_dialog->hide(); - m_result = Button::No; - emit signalQuitEventLoop(); + m_dialog->hide(); + m_result = Button::No; + emit signalQuitEventLoop(); } + void LtsMessageDialogHelper::slotApply() { - m_dialog->hide(); - m_result = Button::Apply; - emit signalQuitEventLoop(); + m_dialog->hide(); + m_result = Button::Apply; + emit signalQuitEventLoop(); } + void LtsMessageDialogHelper::slotDiscard() { - m_dialog->hide(); - m_result = Button::Discard; - emit signalQuitEventLoop(); + m_dialog->hide(); + m_result = Button::Discard; + emit signalQuitEventLoop(); } + void LtsMessageDialogHelper::slotCancel() { - m_dialog->hide(); - m_result = Button::Cancel; - emit signalQuitEventLoop(); + m_dialog->hide(); + m_result = Button::Cancel; + emit signalQuitEventLoop(); } -QPushButton* LtsMessageDialogHelper::addButton(const QString& text, QHBoxLayout* thatLayout, LtsFramelessDialog* dialog, - const Button& button, QWidget* parent) + +QPushButton* LtsMessageDialogHelper::addButton(const QString &text, QHBoxLayout *thatLayout, LtsFramelessDialog *dialog, const Button &button, QWidget *parent) { - QPushButton* btn = new QPushButton(text, parent); - connect(btn, &QPushButton::clicked, dialog, &LtsFramelessDialog::accept); - thatLayout->addWidget(btn); + QPushButton* btn = new QPushButton(text, parent); + connect(btn, &QPushButton::clicked, dialog, &LtsFramelessDialog::accept); + thatLayout->addWidget(btn); - if (button == Button::Ok || button == Button::Cancel) - { - btn->setDefault(true); - } + if (button == Button::Ok || + button == Button::Cancel) // ok and cancel should not be used together, so there is no check needed (as only one button can be the default button) + { + btn->setDefault(true); + } - return btn; + return btn; } } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog_helper.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog_helper.h index 0d05b02cd..0560e8f06 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog_helper.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog_helper.h @@ -7,39 +7,49 @@ #include #include + class QPushButton; class QHBoxLayout; + namespace LtsWidgets { +/** + * @brief The LtsMessageDialogHelper class cannot be exported and only is a helper class which is actually instantiated, shows the LtsMessageDialog. + * To provide the blocking call to showMessage (call with return type), an event loop is created and exited when the user has selected a button to close the dialog. + * If the behaviour is non-modal, closing the Dialog by clicking outside of it will return Button::Cancel. + */ class LtsMessageDialogHelper : public QObject { - Q_OBJECT + Q_OBJECT - public: - explicit LtsMessageDialogHelper(QObject* parent = nullptr); - ~LtsMessageDialogHelper() = default; +public: + explicit LtsMessageDialogHelper(QObject *parent = nullptr); + ~LtsMessageDialogHelper() = default; - Button showMessage(QWidget* parent, const QString& message, const QString& title, Behaviour behaviour, - LtsWidgets::Buttons buttons, const QHash& buttonTexts); + Button showMessage(QWidget *parent, + const QString &message, + const QString &title, + Behaviour behaviour, + LtsWidgets::Buttons buttons, + const QHash &buttonTexts); - private: - QPushButton* addButton(const QString& text, QHBoxLayout* thatLayout, LtsFramelessDialog* dialog, - const Button& button, QWidget* parent); +private: + QPushButton *addButton(const QString &text, QHBoxLayout *thatLayout, LtsFramelessDialog *dialog, const Button &button, QWidget *parent); - Button m_result; - LtsFramelessDialog* m_dialog; + Button m_result; + LtsFramelessDialog *m_dialog; - private slots: - void slotOkay(); - void slotYes(); - void slotNo(); - void slotCancel(); - void slotApply(); - void slotDiscard(); +private slots: + void slotOkay(); + void slotYes(); + void slotNo(); + void slotCancel(); + void slotApply(); + void slotDiscard(); - signals: - void signalQuitEventLoop(); +signals: + void signalQuitEventLoop(); }; } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_msec_date_time_edit.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_msec_date_time_edit.cpp index e0a83234f..117802a1a 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_msec_date_time_edit.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_msec_date_time_edit.cpp @@ -1,113 +1,114 @@ #include "lts_msec_date_time_edit.h" + namespace LtsWidgets { -LtsMSecDateTimeEdit::LtsMSecDateTimeEdit(QWidget* parent) : QDateTimeEdit(parent) +LtsMSecDateTimeEdit::LtsMSecDateTimeEdit(QWidget *parent) + : QDateTimeEdit(parent) { - setWrapping(true); - setDisplayFormat(QLatin1String("dd.MM.yy HH:mm:ss.zzz")); - connect(this, &LtsMSecDateTimeEdit::editingFinished, this, &LtsMSecDateTimeEdit::onEditingFinished); + setWrapping(true); + setDisplayFormat(QLatin1String("dd.MM.yy HH:mm:ss.zzz")); + connect(this, &LtsMSecDateTimeEdit::editingFinished, this, &LtsMSecDateTimeEdit::onEditingFinished); } -LtsMSecDateTimeEdit::LtsMSecDateTimeEdit(const QDateTime& dt, QWidget* parent) : QDateTimeEdit(dt, parent) +LtsMSecDateTimeEdit::LtsMSecDateTimeEdit(const QDateTime &dt, QWidget *parent) + : QDateTimeEdit(dt, parent) { - setWrapping(true); - setDisplayFormat(QLatin1String("dd.MM.yy HH:mm:ss.zzz")); - connect(this, &LtsMSecDateTimeEdit::editingFinished, this, &LtsMSecDateTimeEdit::onEditingFinished); + setWrapping(true); + setDisplayFormat(QLatin1String("dd.MM.yy HH:mm:ss.zzz")); + connect(this, &LtsMSecDateTimeEdit::editingFinished, this, &LtsMSecDateTimeEdit::onEditingFinished); } -LtsMSecDateTimeEdit::LtsMSecDateTimeEdit(const QDate& d, QWidget* parent) : QDateTimeEdit(d, parent) +LtsMSecDateTimeEdit::LtsMSecDateTimeEdit(const QDate &d, QWidget *parent) + : QDateTimeEdit(d, parent) { - setWrapping(true); - setDisplayFormat(QLatin1String("dd.MM.yy HH:mm:ss.zzz")); - connect(this, &LtsMSecDateTimeEdit::editingFinished, this, &LtsMSecDateTimeEdit::onEditingFinished); + setWrapping(true); + setDisplayFormat(QLatin1String("dd.MM.yy HH:mm:ss.zzz")); + connect(this, &LtsMSecDateTimeEdit::editingFinished, this, &LtsMSecDateTimeEdit::onEditingFinished); } -LtsMSecDateTimeEdit::LtsMSecDateTimeEdit(const QTime& t, QWidget* parent) : QDateTimeEdit(t, parent) +LtsMSecDateTimeEdit::LtsMSecDateTimeEdit(const QTime &t, QWidget *parent) + : QDateTimeEdit(t, parent) { - setWrapping(true); - setDisplayFormat(QLatin1String("dd.MM.yy HH:mm:ss.zzz")); - connect(this, &LtsMSecDateTimeEdit::editingFinished, this, &LtsMSecDateTimeEdit::onEditingFinished); + setWrapping(true); + setDisplayFormat(QLatin1String("dd.MM.yy HH:mm:ss.zzz")); + connect(this, &LtsMSecDateTimeEdit::editingFinished, this, &LtsMSecDateTimeEdit::onEditingFinished); } void LtsMSecDateTimeEdit::stepBy(int steps) { - switch (currentSection()) - { - case QDateTimeEdit::MonthSection: - QDateTimeEdit::setDateTime(dateTime().addMonths(steps)); - break; - case QDateTimeEdit::YearSection: - QDateTimeEdit::setDateTime(dateTime().addYears(steps)); - break; - case QDateTimeEdit::DaySection: - QDateTimeEdit::setDateTime(dateTime().addDays(steps)); - break; - case QDateTimeEdit::HourSection: - QDateTimeEdit::setDateTime(dateTime().addSecs(steps * 3600)); - break; - case QDateTimeEdit::MinuteSection: - QDateTimeEdit::setDateTime(dateTime().addSecs(steps * 60)); - break; - case QDateTimeEdit::SecondSection: - QDateTimeEdit::setDateTime(dateTime().addSecs(steps)); - break; - case QDateTimeEdit::MSecSection: - QDateTimeEdit::setDateTime(dateTime().addMSecs(steps * m_msecStepSize)); - break; - case QDateTimeEdit::NoSection: - case QDateTimeEdit::AmPmSection: - case QDateTimeEdit::TimeSections_Mask: - case QDateTimeEdit::DateSections_Mask: - default: - break; - } + switch (currentSection()) { + case QDateTimeEdit::MonthSection: + QDateTimeEdit::setDateTime(dateTime().addMonths(steps)); + break; + case QDateTimeEdit::YearSection: + QDateTimeEdit::setDateTime(dateTime().addYears(steps)); + break; + case QDateTimeEdit::DaySection: + QDateTimeEdit::setDateTime(dateTime().addDays(steps)); + break; + case QDateTimeEdit::HourSection: + QDateTimeEdit::setDateTime(dateTime().addSecs(steps * 3600)); + break; + case QDateTimeEdit::MinuteSection: + QDateTimeEdit::setDateTime(dateTime().addSecs(steps * 60)); + break; + case QDateTimeEdit::SecondSection: + QDateTimeEdit::setDateTime(dateTime().addSecs(steps)); + break; + case QDateTimeEdit::MSecSection: + QDateTimeEdit::setDateTime(dateTime().addMSecs(steps * m_msecStepSize)); + break; + case QDateTimeEdit::NoSection: + case QDateTimeEdit::AmPmSection: + case QDateTimeEdit::TimeSections_Mask: + case QDateTimeEdit::DateSections_Mask: + default: + break; + } } qint64 LtsMSecDateTimeEdit::msecsSinceEpoch() const { - return dateTime().toMSecsSinceEpoch() - (m_timezoneHoursOffset * 3600 * 1000); + return dateTime().toMSecsSinceEpoch() - (m_timezoneHoursOffset * 3600 * 1000); // ..UGH.. } void LtsMSecDateTimeEdit::setTimezoneHoursOffset(int timezoneHoursOffset) { - qint64 b4 = msecsSinceEpoch(); - m_timezoneHoursOffset = timezoneHoursOffset; - setMsecsSinceEpoch(b4); + qint64 b4 = msecsSinceEpoch(); + m_timezoneHoursOffset = timezoneHoursOffset; // set timezone AFTER reading the old value (otherwise timezone conversion would fail) + setMsecsSinceEpoch(b4); // apply timezone by re-setting } -void LtsMSecDateTimeEdit::setDateTime(const QDateTime& dateTime) +void LtsMSecDateTimeEdit::setDateTime(const QDateTime &dateTime) { - - setMsecsSinceEpoch(QDateTime::fromMSecsSinceEpoch(dateTime.toMSecsSinceEpoch(), Qt::TimeSpec::OffsetFromUTC, - m_timezoneHoursOffset * 3600) - .toMSecsSinceEpoch()); + // TODO: doesn't make sense, as toMSecsSinceEpoch returns the *UTC version* of the dt, so the timespec stuff does nothing + setMsecsSinceEpoch(QDateTime::fromMSecsSinceEpoch(dateTime.toMSecsSinceEpoch(), Qt::TimeSpec::OffsetFromUTC, m_timezoneHoursOffset * 3600).toMSecsSinceEpoch()); } void LtsMSecDateTimeEdit::setMsecsSinceEpoch(qint64 msecs) { - QDateTimeEdit::setDateTime( - QDateTime::fromMSecsSinceEpoch(msecs, Qt::TimeSpec::OffsetFromUTC, m_timezoneHoursOffset * 3600)); + QDateTimeEdit::setDateTime(QDateTime::fromMSecsSinceEpoch(msecs, Qt::TimeSpec::OffsetFromUTC, m_timezoneHoursOffset * 3600)); } int LtsMSecDateTimeEdit::msecStepSize() const { - return m_msecStepSize; + return m_msecStepSize; } void LtsMSecDateTimeEdit::setMsecStepSize(int msecStepSize) { - m_msecStepSize = msecStepSize; + m_msecStepSize = msecStepSize; } void LtsMSecDateTimeEdit::onEditingFinished() { - qint64 val = msecsSinceEpoch(); - if (val % m_msecStepSize == 0) - return; - val = (val + (m_msecStepSize / 2)) / m_msecStepSize * m_msecStepSize; - setMsecsSinceEpoch(val); + qint64 val = msecsSinceEpoch(); + if (val % m_msecStepSize == 0) + return; + val = (val + (m_msecStepSize/2) ) / m_msecStepSize * m_msecStepSize; + setMsecsSinceEpoch(val); } -} // namespace LtsWidgets +} // namespace diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_msec_date_time_edit.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_msec_date_time_edit.h index d35a30b3c..3d656312b 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_msec_date_time_edit.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_msec_date_time_edit.h @@ -1,46 +1,41 @@ #pragma once -#include "lts_widgets_export.h" #include -#include -namespace LtsWidgets -{ +#include "lts_widgets_export.h" + + +namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsMSecDateTimeEdit : public QDateTimeEdit { - Q_OBJECT + Q_OBJECT - Q_PROPERTY(int msecStepSize READ msecStepSize WRITE setMsecStepSize) + Q_PROPERTY(int msecStepSize READ msecStepSize WRITE setMsecStepSize) - public: - explicit LtsMSecDateTimeEdit(QWidget* parent = nullptr); - explicit LtsMSecDateTimeEdit(const QDateTime& dt, QWidget* parent = nullptr); - explicit LtsMSecDateTimeEdit(const QDate& d, QWidget* parent = nullptr); - explicit LtsMSecDateTimeEdit(const QTime& t, QWidget* parent = nullptr); +public: + explicit LtsMSecDateTimeEdit(QWidget *parent = nullptr); + explicit LtsMSecDateTimeEdit(const QDateTime &dt, QWidget *parent = nullptr); + explicit LtsMSecDateTimeEdit(const QDate &d, QWidget *parent = nullptr); + explicit LtsMSecDateTimeEdit(const QTime &t, QWidget *parent = nullptr); - qint64 msecsSinceEpoch() const; + qint64 msecsSinceEpoch() const; + int timezoneHoursOffset() const { return m_timezoneHoursOffset; } + void stepBy(int steps) override; + int msecStepSize() const; - int timezoneHoursOffset() const - { - return m_timezoneHoursOffset; - } +public slots: + void setDateTime(const QDateTime &dateTime); + void setMsecsSinceEpoch(qint64 msecs); + void setMsecStepSize(int msecStepSize); + void setTimezoneHoursOffset(int timezoneHoursOffset); - void stepBy(int steps) override; - int msecStepSize() const; +private slots: + void onEditingFinished(); - public slots: - void setDateTime(const QDateTime& dateTime); - void setMsecsSinceEpoch(qint64 msecs); - void setMsecStepSize(int msecStepSize); - void setTimezoneHoursOffset(int timezoneHoursOffset); - - private slots: - void onEditingFinished(); - - private: - int m_msecStepSize = 10; - int m_timezoneHoursOffset = 0; +private: + int m_msecStepSize = 10; + int m_timezoneHoursOffset = 0; }; -} // namespace LtsWidgets +} // namespace diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_multi_range_spinbox.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_multi_range_spinbox.cpp index d23f06a6d..5642acbc8 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_multi_range_spinbox.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_multi_range_spinbox.cpp @@ -1,261 +1,334 @@ - +/** + * @RDE_HEADER@ + * SpinBox, that corrects values to a valid value that fits minimum() + n * singleStep() = value + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Malte Diers DER LOSER, NLSE, 2018-05-07 + */ #include "lts_multi_range_spinbox.h" #include #include #include -#include namespace LtsWidgets { -LtsMultiRangeSpinBox::LtsMultiRangeSpinBox(QWidget* parent) : QSpinBox(parent) +LtsMultiRangeSpinBox::LtsMultiRangeSpinBox(QWidget *parent) + : QSpinBox(parent) { - m_curVal = minimum(); + m_curVal = minimum(); + } -QValidator::State LtsMultiRangeSpinBox::validate(QString& input, int& pos) const -{ +/*! + * \brief LtsSpinBoxNew::validate + * \param input + * \param pos + * \brief only used if enter pressed + * \return + */ - return QValidator::Acceptable; +QValidator::State LtsMultiRangeSpinBox::validate(QString &input, int &pos) const +{ +// QIntValidator validator; + +// int minimumVal = minimum(); +// int maximumVal = maximum(); +// validator.setBottom(minimum()); +// validator.setTop(maximum()); +// QValidator::State state = validator.validate(input, pos); +// if (state == QValidator::Invalid || +// state == QValidator::Intermediate) +// { +// return state; +// } +// // Now we're sure, it's an int. Therefore toInt() will always be okay: +// int value = input.toInt(); +// value -= minimum(); +// return (value % singleStep() == 0) ? QValidator::Acceptable : QValidator::Intermediate; + return QValidator::Acceptable; } -void LtsMultiRangeSpinBox::fixup(QString& str) const {} - -QValidator::State LtsMultiRangeSpinBox::validateAll(QString& input, int& pos) +void LtsMultiRangeSpinBox::fixup(QString &str) const { - for (QPair range : std::as_const(m_rangesList)) + +// QSpinBox::fixup(str); + +// if (singleStep() == 1) +// { +// return; +// } +// bool bOk = false; +// int value = str.toInt(&bOk); +// if (!bOk) +// { +// return; +// } +// fixupValue(value); + +// str = QString::number(value); +} + +QValidator::State LtsMultiRangeSpinBox::validateAll(QString &input, int &pos) +{ + for(QPair range : qAsConst(m_rangesList)) + { + QIntValidator validator(range.first, range.second); + QValidator::State valState = validator.validate(input, pos); + if (valState == QValidator::Acceptable) { - QIntValidator validator(range.first, range.second); - QValidator::State valState = validator.validate(input, pos); - if (valState == QValidator::Acceptable) - { - return valState; - } + return valState; } - return QValidator::Invalid; -} + } + return QValidator::Invalid; -QVector> LtsWidgets::LtsMultiRangeSpinBox::sortRanges(const QVector>& ranges) + //return validate(input, pos); +} +/*! + * \brief LtsSpinBoxNew::setGaps + * \param gaps + * \author Niklas Schmidt + */ +QVector> LtsWidgets::LtsMultiRangeSpinBox::sortRanges(const QVector > &ranges) { - QVector> rangesEditable = ranges; - QVector> result; - std::sort(rangesEditable.begin(), rangesEditable.end()); - QVector>::iterator it = rangesEditable.begin(); - QPair current = *(it)++; - while (it != rangesEditable.end()) + QVector> rangesEditable = ranges; + QVector> result; + std::sort(rangesEditable.begin(), rangesEditable.end()); + QVector>::iterator it = rangesEditable.begin(); + QPair current = *(it)++; + while (it != rangesEditable.end()) + { + if (current.second > it->first) + current.second = std::max(current.second, it->second); + else { - if (current.second > it->first) - current.second = std::max(current.second, it->second); - else - { - result.push_back(current); - current = *(it); - } - ++it; + result.push_back(current); + current = *(it); } - result.push_back(current); - return result; + ++it; + } + result.push_back(current); + return result; } -void LtsMultiRangeSpinBox::setRanges(const QVector>& ranges) +void LtsMultiRangeSpinBox::setRanges(const QVector> &ranges) { - if (ranges.empty()) - return; + if(ranges.empty()) + return; - m_rangesList = sortRanges(ranges); + m_rangesList = sortRanges(ranges); - QSpinBox::setMaximum(m_rangesList.last().second); - QSpinBox::setMinimum(m_rangesList.first().first); + QSpinBox::setMaximum(m_rangesList.last().second); + QSpinBox::setMinimum(m_rangesList.first().first); - QStringList rangeStrings; - rangeStrings.reserve(m_rangesList.size()); - for (const QPair& range : std::as_const(m_rangesList)) - rangeStrings << tr("%1-%2%3").arg(range.first).arg(range.second).arg(suffix()); - setToolTip(tr("Ranges:\n%1").arg(rangeStrings.join(QStringLiteral(",\n")))); + QStringList rangeStrings; + rangeStrings.reserve(m_rangesList.size()); + for (const QPair &range : qAsConst(m_rangesList)) + rangeStrings << tr("%1-%2%3").arg(range.first).arg(range.second).arg(suffix()); + setToolTip(tr("Ranges:\n%1").arg(rangeStrings.join(QStringLiteral(",\n")))); } void LtsMultiRangeSpinBox::setRange(int min, int max) { - setRanges({{min, max}}); + setRanges({{min,max}}); } void LtsMultiRangeSpinBox::setMinimum(int min) { - auto ranges = m_rangesList; - ranges.first().first = min; - setRanges(ranges); + auto ranges = m_rangesList; + ranges.first().first = min; + setRanges(ranges); } void LtsMultiRangeSpinBox::setMaximum(int max) { - auto ranges = m_rangesList; - ranges.last().second = max; - setRanges(ranges); + auto ranges = m_rangesList; + ranges.last().second = max; + setRanges(ranges); } int LtsMultiRangeSpinBox::fixupValue(int value) const { - int nearestValue = INT_MAX; - for (QPair range : m_rangesList) - { - if (std::abs(range.first - value) < std::abs(nearestValue - value)) - nearestValue = range.first; - if (std::abs(range.second - value) < std::abs(nearestValue - value)) - nearestValue = range.second; - } - value = nearestValue; - int buffer = value; + int nearestValue = INT_MAX; + for(QPair range : m_rangesList) + { + if(std::abs(range.first - value) < std::abs(nearestValue - value)) + nearestValue = range.first; + if(std::abs(range.second - value) < std::abs(nearestValue - value)) + nearestValue = range.second; + } + value = nearestValue; + int buffer = value; - int remainder = (value - minimum()) % singleStep(); + int remainder = (value - minimum()) % singleStep(); - if (2 * remainder > singleStep()) - { - value += singleStep(); - } - value -= remainder; + if (2 * remainder > singleStep()) + { + value += singleStep(); + } + value -= remainder; - if (buffer + singleStep() > value + singleStep()) - { - value += singleStep(); - } + if(buffer + singleStep() > value + singleStep()) + { + value+= singleStep(); + } - if (value > maximum()) - { - value -= singleStep(); - } + if (value > maximum()) + { + value -= singleStep(); + } - return value; + return value; } int LtsMultiRangeSpinBox::fixupValue(int value, bool higher) const { - int nearestValue = INT_MAX; - for (QPair range : m_rangesList) + int nearestValue = INT_MAX; + for(QPair range : m_rangesList) + { + if(std::abs(range.first - value) < std::abs(nearestValue - value)) { - if (std::abs(range.first - value) < std::abs(nearestValue - value)) - { - if (higher) - { - if (range.second < value) - continue; - } - else if (range.second > value) - continue; + if(higher) + { + if(range.second < value) + continue; - nearestValue = range.first; - } - if (std::abs(range.second - value) < std::abs(nearestValue - value)) - { - if (higher) - { - if (range.second < value) - continue; - } - else if (range.second > value) - continue; + } else + if(range.second > value) + continue; - nearestValue = range.second; - } + nearestValue = range.first; } - - value = nearestValue; - int curVal = value; - - int remainder = (value - minimum()) % singleStep(); - - if (2 * remainder > singleStep()) + if(std::abs(range.second - value) < std::abs(nearestValue - value)) { - value += singleStep(); - } - value -= remainder; + if(higher) + { + if(range.second < value) + continue; - if (curVal + singleStep() > value + singleStep()) - { - value += singleStep(); - } - if (value > maximum()) - { - value -= singleStep(); - } + } else + if(range.second > value) + continue; - return value; + nearestValue = range.second; + } + } + + value = nearestValue; + int curVal = value; + + int remainder = (value - minimum()) % singleStep(); + + if (2 * remainder > singleStep()) + { + value += singleStep(); + } + value -= remainder; + + if(curVal + singleStep() > value + singleStep()) + { + value+= singleStep(); + } + if (value > maximum()) + { + value -= singleStep(); + } + + return value; } -void LtsMultiRangeSpinBox::focusOutEvent(QFocusEvent* event) + +void LtsMultiRangeSpinBox::focusOutEvent(QFocusEvent *event) { - QSpinBox::focusOutEvent(event); - QString value = QString::number(this->value()); - int length = value.length(); - QValidator::State valState = validateAll(value, length); + QSpinBox::focusOutEvent(event); + QString value = QString::number(this->value()); + int length = value.length(); + QValidator::State valState = validateAll(value, length); - if (valState == QValidator::State::Invalid) - { - this->setValue(fixupValue(value.toInt())); - } + if(valState == QValidator::State::Invalid) + { + this->setValue(fixupValue(value.toInt())); + } } -void LtsMultiRangeSpinBox::wheelEvent(QWheelEvent* event) +void LtsMultiRangeSpinBox::wheelEvent(QWheelEvent *event) { - QSpinBox::wheelEvent(event); + QSpinBox::wheelEvent(event); - QString valueStr = QString::number(this->value()); - int length = valueStr.length(); - QValidator::State valState = validateAll(valueStr, length); + QString valueStr = QString::number(this->value()); + int length = valueStr.length(); + QValidator::State valState = validateAll(valueStr, length); - if (valState == QValidator::State::Invalid) + if(valState == QValidator::State::Invalid) + { + /*! + Check if the new value is lower or higher the past value + Example: Gap between 50 and 100. Value changed from 100 to 99 requested + So the new value is lower so the SpinBox need to be corrected down to 49 + !*/ + + if(this->value() < m_curVal) { - - if (this->value() < m_curVal) - { - m_curVal = fixupValue(this->value(), false); - setValue(m_curVal); - } - else - { - m_curVal = fixupValue(this->value(), true); - setValue(m_curVal); - } + m_curVal = fixupValue(this->value(), false); + setValue(m_curVal); } + else + { + m_curVal = fixupValue(this->value(), true); + setValue(m_curVal); + } + } } -void LtsMultiRangeSpinBox::mousePressEvent(QMouseEvent* event) +void LtsMultiRangeSpinBox::mousePressEvent(QMouseEvent *event) { - QSpinBox::mousePressEvent(event); - QString valueStr = QString::number(this->value()); - int length = valueStr.length(); - QValidator::State valState = validateAll(valueStr, length); + QSpinBox::mousePressEvent(event); + QString valueStr = QString::number(this->value()); + int length = valueStr.length(); + QValidator::State valState = validateAll(valueStr, length); - if (valState == QValidator::State::Invalid) + if(valState == QValidator::State::Invalid) + { + /*! + Check if the new value is lower or higher the past value + Example: Gap between 50 and 100. Value changed from 100 to 99 requested + So the new value is lower so the SpinBox need to be corrected down to 49 + !*/ + + + if(this->value() < m_curVal) { - - if (this->value() < m_curVal) - { - m_curVal = fixupValue(this->value(), false); - setValue(m_curVal); - } - else - { - m_curVal = fixupValue(this->value(), true); - setValue(m_curVal); - } + m_curVal = fixupValue(this->value(), false); + setValue(m_curVal); } + else + { + m_curVal = fixupValue(this->value(), true); + setValue(m_curVal); + } + } + + } -void LtsMultiRangeSpinBox::keyPressEvent(QKeyEvent* event) +void LtsMultiRangeSpinBox::keyPressEvent(QKeyEvent *event) { - QSpinBox::keyPressEvent(event); - QString value = QString::number(this->value()); - int length = value.length(); - QValidator::State valState = validateAll(value, length); + QSpinBox::keyPressEvent(event); + QString value = QString::number(this->value()); + int length = value.length(); + QValidator::State valState = validateAll(value, length); - if (valState == QValidator::State::Invalid) - { - setValue(fixupValue(value.toInt())); - } + if(valState == QValidator::State::Invalid) + { + setValue(fixupValue(value.toInt())); + } } + } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_multi_range_spinbox.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_multi_range_spinbox.h index 95029044b..621d873d3 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_multi_range_spinbox.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_multi_range_spinbox.h @@ -1,12 +1,19 @@ - +/** + * @RDE_HEADER@ + * SpinBox, that corrects values to a valid value that fits minimum() + n * singleStep() = value + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Malte Diers, NLSE, 2018-05-07 + */ #pragma once -#include "lts_widgets_export.h" -#include -#include +#include "lts_widgets_export.h" #include #include +#include namespace LtsWidgets { @@ -15,37 +22,39 @@ class LTSWIDGETS_EXPORT LtsMultiRangeSpinBox : public QSpinBox { Q_OBJECT - public: - explicit LtsMultiRangeSpinBox(QWidget* parent = nullptr); +public: + explicit LtsMultiRangeSpinBox(QWidget *parent = nullptr); ~LtsMultiRangeSpinBox() = default; - public slots: - void setRanges(const QVector>& ranges); + +public slots: + void setRanges(const QVector> &ranges); void setRange(int min, int max); void setMinimum(int min); void setMaximum(int max); - protected: - QValidator::State validate(QString& input, int& pos) const override; - void fixup(QString& str) const override; - void focusOutEvent(QFocusEvent* event) override; - void wheelEvent(QWheelEvent* event) override; - void mousePressEvent(QMouseEvent* event) override; - void keyPressEvent(QKeyEvent* event) override; +protected: + QValidator::State validate(QString &input, int &pos) const override; + void fixup(QString &str) const override; + void focusOutEvent(QFocusEvent *event) override; + void wheelEvent(QWheelEvent *event) override; + void mousePressEvent(QMouseEvent *event) override; + void keyPressEvent(QKeyEvent *event) override; - private: - static QVector> sortRanges(const QVector>& ranges); - - QValidator::State validateAll(QString& input, int& pos); +private: + static QVector> sortRanges(const QVector > &ranges); + QValidator::State validateAll(QString &input, int &pos); + //void buildRegex(); int fixupValue(int value) const; int fixupValue(int value, bool higher) const; - - private: +private: QVector> m_rangesList; int m_curVal = minimum(); QRegularExpression m_regex; }; -} // namespace LtsWidgets + + +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_notification_box.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_notification_box.cpp index 37610d673..40e06ef8e 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_notification_box.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_notification_box.cpp @@ -1,176 +1,198 @@ #include "lts_notification_box.h" - #include "ui_lts_notification_box.h" +#include +#include #include #include -#include -#include -#include #include +#include #ifdef NOTIBOX_DEBUG #include #endif + namespace LtsWidgets { const int LtsNotificationBox::margin = 14; -LtsNotificationBox::LtsNotificationBox(QWidget* parent) : QWidget(parent), m_ui(new Ui::NotiBox) +LtsNotificationBox::LtsNotificationBox(QWidget *parent) + : QWidget(parent) + , m_ui(new Ui::NotiBox) { - m_ui->setupUi(this); - m_ui->lblText->setText({}); + m_ui->setupUi(this); + m_ui->lblText->setText({}); - connect(m_ui->lblText, &QLabel::linkActivated, this, [this](const QString& link) { emit signalLinkClicked(link); }); + connect(m_ui->lblText, &QLabel::linkActivated, + this, [this](const QString &link) + { + emit signalLinkClicked(link); + }); - connect(m_ui->tbClose, &QToolButton::clicked, this, &LtsNotificationBox::signalClose); - connect(m_ui->tbAck, &QToolButton::clicked, this, &LtsNotificationBox::signalAck); + connect(m_ui->tbClose, &QToolButton::clicked, + this, &LtsNotificationBox::signalClose); + connect(m_ui->tbAck, &QToolButton::clicked, + this, &LtsNotificationBox::signalAck); - setObjectName(QStringLiteral("NotiBox")); + setObjectName(QStringLiteral("NotiBox")); - QGraphicsDropShadowEffect* shadow = new QGraphicsDropShadowEffect(this); - shadow->setOffset(0, 0); - shadow->setBlurRadius(margin * 2); - shadow->setColor(QColor(25, 25, 25)); + QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect(this); + shadow->setOffset(0, 0); + shadow->setBlurRadius(margin*2); + shadow->setColor(QColor(25, 25, 25)); - setGraphicsEffect(shadow); + setGraphicsEffect(shadow); } -void LtsNotificationBox::message(const QString& title, const QString& text, MessageType type) + +void LtsNotificationBox::message(const QString &title, const QString &text, MessageType type) { - static QString rgbBaseString(QStringLiteral("%1, %2, %3")); - static QString closeDefault(QStringLiteral("close.svg")); - static QString closeDark(QStringLiteral("close_dark.svg")); - static QString ackDefault(QStringLiteral("ack.svg")); - static QString ackDark(QStringLiteral("ack_dark.svg")); - static QString lightTextColor(QStringLiteral("fbfbfb")); - static QString darkTextColor(QStringLiteral("2c3642")); + static QString rgbBaseString(QStringLiteral("%1, %2, %3")); + static QString closeDefault(QStringLiteral("close.svg")); + static QString closeDark(QStringLiteral("close_dark.svg")); + static QString ackDefault(QStringLiteral("ack.svg")); + static QString ackDark(QStringLiteral("ack_dark.svg")); + static QString lightTextColor(QStringLiteral("fbfbfb")); + static QString darkTextColor(QStringLiteral("2c3642")); - static QColor errorStart(254, 45, 102); - static QColor errorEnd(255, 92, 61); + static QColor errorStart(254, 45, 102); + static QColor errorEnd(255, 92, 61); - static QColor successStart(43, 167, 70); - static QColor successEnd(130, 180, 45); + static QColor successStart(43, 167, 70); + static QColor successEnd(130, 180, 45); - static QColor infoStart(74, 74, 74); - static QColor infoEnd(43, 43, 43); + static QColor infoStart(74, 74, 74); + static QColor infoEnd(43, 43, 43); - static QColor warningStart(253, 151, 4); - static QColor warningEnd(253, 202, 0); + static QColor warningStart(253, 151, 4); + static QColor warningEnd(253, 202, 0); - QColor start; - QColor end; - QString close; - QString closeHover; - QString ack; - QString ackHover; - QString textColor; - switch (type) + QColor start; + QColor end; + QString close; + QString closeHover; + QString ack; + QString ackHover; + QString textColor; + + switch (type) + { + case MessageType::Error: { - case MessageType::Error: { - start = errorStart; - end = errorEnd; - close = closeDefault; - closeHover = closeDark; - ack = ackDefault; - ackHover = ackDark; - textColor = lightTextColor; - m_ui->lblImage->setPixmap(QPixmap(QStringLiteral(":/error.svg"))); + start = errorStart; + end = errorEnd; + close = closeDefault; + closeHover = closeDark; + ack = ackDefault; + ackHover = ackDark; + textColor = lightTextColor; + m_ui->lblImage->setPixmap(QPixmap(QStringLiteral(":/error.svg"))); - break; - } - - case MessageType::Success: { - start = successStart; - end = successEnd; - close = closeDefault; - closeHover = closeDark; - ack = ackDefault; - ackHover = ackDark; - textColor = lightTextColor; - m_ui->lblImage->setPixmap(QPixmap(QStringLiteral(":/success.svg"))); - - break; - } - - case MessageType::Info: { - start = infoStart; - end = infoEnd; - close = closeDefault; - closeHover = closeDark; - ack = ackDefault; - ackHover = ackDark; - textColor = lightTextColor; - m_ui->lblImage->setPixmap(QPixmap(QStringLiteral(":/info.svg"))); - - break; - } - - case MessageType::Warning: { - start = warningStart; - end = warningEnd; - close = closeDark; - closeHover = closeDefault; - ack = ackDark; - ackHover = ackDefault; - textColor = darkTextColor; - m_ui->lblImage->setPixmap(QPixmap(QStringLiteral(":/warning.svg"))); - - break; - } + break; } - QStringList css; + case MessageType::Success: + { + start = successStart; + end = successEnd; + close = closeDefault; + closeHover = closeDark; + ack = ackDefault; + ackHover = ackDark; + textColor = lightTextColor; + m_ui->lblImage->setPixmap(QPixmap(QStringLiteral(":/success.svg"))); - css << QStringLiteral("#NotiBox { background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop: 0 rgb(%1), stop: 1 " - "rgb(%2)); border: 1px solid rgb(%3); border-radius: 8px; margin: %4px }") - .arg(rgbBaseString.arg(start.red()).arg(start.green()).arg(start.blue()), - rgbBaseString.arg(end.red()).arg(end.green()).arg(end.blue()), - rgbBaseString.arg(end.red()).arg(end.green()).arg(end.blue())) - .arg(margin); + break; + } - css << QStringLiteral("QToolButton#tbClose { border-image: url(:/%1) 0 0 0 0 stretch stretch; border-width: 0px; " - "background-color: transparent; }") - .arg(close); - css << QStringLiteral("QToolButton#tbClose:hover { border-image: url(:/%1) 0 0 0 0 stretch stretch; border-width: " - "0px; background-color: transparent; }") - .arg(closeHover); + case MessageType::Info: + { + start = infoStart; + end = infoEnd; + close = closeDefault; + closeHover = closeDark; + ack = ackDefault; + ackHover = ackDark; + textColor = lightTextColor; + m_ui->lblImage->setPixmap(QPixmap(QStringLiteral(":/info.svg"))); - css << QStringLiteral("QToolButton#tbAck { border-image: url(:/%1) 0 0 0 0 stretch stretch; border-width: 0px; " - "background-color: transparent; }") - .arg(ack); - css << QStringLiteral("QToolButton#tbAck:hover { border-image: url(:/%1) 0 0 0 0 stretch stretch; border-width: " - "0px; background-color: transparent; }") - .arg(ackHover); + break; + } + + case MessageType::Warning: + { + start = warningStart; + end = warningEnd; + close = closeDark; + closeHover = closeDefault; + ack = ackDark; + ackHover = ackDefault; + textColor = darkTextColor; + m_ui->lblImage->setPixmap(QPixmap(QStringLiteral(":/warning.svg"))); + + break; + } + } + + QStringList css; + + css << QStringLiteral("#NotiBox { background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop: 0 rgb(%1), stop: 1 rgb(%2)); border: 1px solid rgb(%3); border-radius: 8px; margin: %4px }"). + arg(rgbBaseString.arg(start.red()).arg(start.green()).arg(start.blue()), + rgbBaseString.arg(end.red()).arg(end.green()).arg(end.blue()), + rgbBaseString.arg(end.red()).arg(end.green()).arg(end.blue())). + arg(margin); + + css << QStringLiteral("QToolButton#tbClose { border-image: url(:/%1) 0 0 0 0 stretch stretch; border-width: 0px; background-color: transparent; }").arg(close); + css << QStringLiteral("QToolButton#tbClose:hover { border-image: url(:/%1) 0 0 0 0 stretch stretch; border-width: 0px; background-color: transparent; }").arg(closeHover); + + css << QStringLiteral("QToolButton#tbAck { border-image: url(:/%1) 0 0 0 0 stretch stretch; border-width: 0px; background-color: transparent; }").arg(ack); + css << QStringLiteral("QToolButton#tbAck:hover { border-image: url(:/%1) 0 0 0 0 stretch stretch; border-width: 0px; background-color: transparent; }").arg(ackHover); #ifdef NOTIBOX_DEBUG - qWarning() << "css" << css; + qWarning() << "css" << css; - qWarning() << "exists?" << QFile::exists(QStringLiteral(":/close.svg")); - qWarning() << "exists?" << QFile::exists(QStringLiteral(":/close_dark.svg")); - qWarning() << "exists?" << QFile::exists(QStringLiteral(":/error.svg")); - qWarning() << "exists?" << QFile::exists(QStringLiteral(":/info.svg")); - qWarning() << "exists?" << QFile::exists(QStringLiteral(":/warning.svg")); - qWarning() << "exists?" << QFile::exists(QStringLiteral(":/success.svg")); + qWarning() << "exists?" << QFile::exists(QStringLiteral(":/close.svg")); + qWarning() << "exists?" << QFile::exists(QStringLiteral(":/close_dark.svg")); + qWarning() << "exists?" << QFile::exists(QStringLiteral(":/error.svg")); + qWarning() << "exists?" << QFile::exists(QStringLiteral(":/info.svg")); + qWarning() << "exists?" << QFile::exists(QStringLiteral(":/warning.svg")); + qWarning() << "exists?" << QFile::exists(QStringLiteral(":/success.svg")); #endif - m_ui->lblImage->setStyleSheet(QString()); - setStyleSheet(css.join(QStringLiteral(" "))); + m_ui->lblImage->setStyleSheet(QString()); + setStyleSheet(css.join(QStringLiteral(" "))); - m_ui->lblText->setText( - QStringLiteral("

%2

%4

") - .arg(textColor, title, textColor, text)); + m_ui->lblText->setText(QStringLiteral("

%2

%4

").arg(textColor, title, textColor, text)); - show(); + show(); } -void LtsNotificationBox::paintEvent(QPaintEvent*) + +void LtsNotificationBox::paintEvent(QPaintEvent *) { - QStyleOption opt; - opt.initFrom(this); - QPainter p(this); - style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); + QStyleOption opt; + opt.init(this); + QPainter p(this); + style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); } } // namespace LtsWidgets + + + + + + + + + + + + + + + + + + +// diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_notification_box.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_notification_box.h index df68d35b1..a4192e993 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_notification_box.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_notification_box.h @@ -1,46 +1,50 @@ #pragma once -#include "lts_widgets_export.h" -#include -#include +#include "lts_widgets_export.h" #include +#include + class QPaintEvent; class QResizeEvent; + namespace Ui { class NotiBox; } + namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsNotificationBox : public QWidget { - Q_OBJECT - public: - enum class MessageType { - Success, - Error, - Warning, - Info, - }; + Q_OBJECT +public: + enum class MessageType + { + Success, + Error, + Warning, + Info, + }; - explicit LtsNotificationBox(QWidget* parent = nullptr); + explicit LtsNotificationBox(QWidget *parent = nullptr); - void message(const QString& title, const QString& text, MessageType type = MessageType::Error); + void message(const QString &title, const QString &text, MessageType type = MessageType::Error); - signals: - void signalClose(); - void signalAck(); - void signalLinkClicked(const QString& link); +signals: + void signalClose(); + void signalAck(); + void signalLinkClicked(const QString &link); - protected: - void paintEvent(QPaintEvent*) override; +protected: + void paintEvent(QPaintEvent *) override; - private: - Ui::NotiBox* m_ui; - QPainterPath roundRectPath; - const static int margin; +private: + Ui::NotiBox *m_ui; + QPainterPath roundRectPath; + const static int margin; }; } // namespace LtsWidgets + diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_operator_menu.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_operator_menu.cpp index 469b90584..9680dc13a 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_operator_menu.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_operator_menu.cpp @@ -1,105 +1,121 @@ - +/** + * @RDE_HEADER@ + * User Menu on active sessions (logout, etc.) + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Mike Wille, SLSE, 2016-08-17 + */ #include "lts_operator_menu.h" - -#include "lts_info_dialog.h" #include "ui_lts_operator_menu.h" - -#include -#include -#include +#include "lts_info_dialog.h" #include +#include +#include +#include + + namespace LtsWidgets { -LtsOperatorMenu::LtsOperatorMenu(const QString& operatorName, const QString& workspaceId, bool debug, int screenCount, - QWidget* parent) - : LtsFramelessDialog(parent), m_ui(new Ui::LtsOperatorMenu) +LtsOperatorMenu::LtsOperatorMenu(const QString &operatorName, const QString &workspaceId, bool debug, int screenCount, QWidget *parent) + : LtsFramelessDialog(parent) + , m_ui(new Ui::LtsOperatorMenu) { - m_ui->setupUi(this); - m_ui->lbOperatorName->setText(operatorName); - m_ui->lbHostName->setText(QHostInfo::localHostName()); + m_ui->setupUi(this); + m_ui->lbOperatorName->setText(operatorName); + m_ui->lbHostName->setText(QHostInfo::localHostName()); - if (screenCount < 2) - m_ui->pbSwap->hide(); + if (screenCount < 2) + m_ui->pbSwap->hide(); // swaps only possible if more than 1 screen is available - if (debug) - m_ui->lbWorkspaceId->setText(tr("Workspace: >>>%1<<<").arg(workspaceId)); - else - m_ui->lbWorkspaceId->hide(); + if (debug) + m_ui->lbWorkspaceId->setText(tr("Workspace: >>>%1<<<").arg(workspaceId)); + else + m_ui->lbWorkspaceId->hide(); - connect(m_ui->pbOperatorSettings, &QPushButton::clicked, this, &LtsOperatorMenu::signalShowOperatorSettings); - connect(m_ui->pbOperatorSettings, &QPushButton::clicked, this, &LtsOperatorMenu::close); - connect(m_ui->pbWindow, &QPushButton::clicked, this, &LtsOperatorMenu::onTerminalButtonClicked); - connect(m_ui->pbWindow, &QPushButton::clicked, this, &LtsOperatorMenu::close); - connect(m_ui->pbLogout, &QPushButton::clicked, this, &LtsOperatorMenu::signalLogout); - connect(m_ui->pbExit, &QPushButton::clicked, this, &LtsOperatorMenu::signalExit); - connect(m_ui->pbCancel, &QPushButton::clicked, this, &LtsOperatorMenu::close); - connect(m_ui->pbSwap, &QPushButton::clicked, this, &LtsOperatorMenu::signalSwap); - connect(m_ui->pbSwap, &QPushButton::clicked, this, &LtsOperatorMenu::close); - connect(m_ui->pbAbout, &QPushButton::clicked, this, &LtsOperatorMenu::slotShowInfoDialog); - connect(m_ui->pbAbout, &QPushButton::clicked, this, &LtsOperatorMenu::close); + connect(m_ui->pbOperatorSettings, &QPushButton::clicked, this, &LtsOperatorMenu::signalShowOperatorSettings); + connect(m_ui->pbOperatorSettings, &QPushButton::clicked, this, &LtsOperatorMenu::close); + connect(m_ui->pbWindow, &QPushButton::clicked, this, &LtsOperatorMenu::onTerminalButtonClicked); + connect(m_ui->pbWindow, &QPushButton::clicked, this, &LtsOperatorMenu::close); + connect(m_ui->pbLogout, &QPushButton::clicked, this, &LtsOperatorMenu::signalLogout); + connect(m_ui->pbExit, &QPushButton::clicked, this, &LtsOperatorMenu::signalExit); + connect(m_ui->pbCancel, &QPushButton::clicked, this, &LtsOperatorMenu::close); + connect(m_ui->pbSwap, &QPushButton::clicked, this, &LtsOperatorMenu::signalSwap); + connect(m_ui->pbSwap, &QPushButton::clicked, this, &LtsOperatorMenu::close); + connect(m_ui->pbAbout, &QPushButton::clicked, this, &LtsOperatorMenu::slotShowInfoDialog); + connect(m_ui->pbAbout, &QPushButton::clicked, this, &LtsOperatorMenu::close); - if (NGL::translationLocale() == "de_DE") - m_ui->pbGer->setChecked(true); - else - m_ui->pbInt->setChecked(true); - connect(m_ui->pbGer, &QPushButton::clicked, this, &LtsOperatorMenu::onLanguageChange); - connect(m_ui->pbInt, &QPushButton::clicked, this, &LtsOperatorMenu::onLanguageChange); + if (NGL::translationLocale() == "de_DE") + m_ui->pbGer->setChecked(true); + else + m_ui->pbInt->setChecked(true); + + connect(m_ui->pbGer, &QPushButton::clicked, + this, &LtsOperatorMenu::onLanguageChange); + connect(m_ui->pbInt, &QPushButton::clicked, + this, &LtsOperatorMenu::onLanguageChange); #ifndef LTS_DEBUG - m_ui->debugWidget->hide(); + m_ui->debugWidget->hide(); #endif } + LtsOperatorMenu::~LtsOperatorMenu() { - delete m_ui; + delete m_ui; } + void LtsOperatorMenu::slotShowInfoDialog() { - LtsInfoDialog* infoDialog = new LtsInfoDialog(); - infoDialog->setAttribute(Qt::WA_DeleteOnClose); - infoDialog->show(); + LtsInfoDialog *infoDialog = new LtsInfoDialog(); + infoDialog->setAttribute(Qt::WA_DeleteOnClose); + infoDialog->show(); } + void LtsOperatorMenu::onTerminalButtonClicked() { - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); + QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - QString lang = QString::fromLatin1(NGL::translationLocale()); - lang.append(QStringLiteral(".UTF-8")); - env.insert(QStringLiteral("LANG"), lang); + QString lang = QString::fromLatin1(NGL::translationLocale()); + lang.append(QStringLiteral(".UTF-8")); + env.insert(QStringLiteral("LANG"), lang); - QProcess process; - process.setProcessEnvironment(env); - QStringList args; - args << QStringLiteral("--geometry") << QStringLiteral("800x800+200+100"); + QProcess process; + process.setProcessEnvironment(env); //Da startDetached static ist wird hier drauf nicht zugegriffen + QStringList args; + args << QStringLiteral("--geometry") << QStringLiteral("800x800+200+100"); - if (QApplication::queryKeyboardModifiers() == Qt::ControlModifier) - process.startDetached(QStringLiteral("xterm"), args); - else - process.startDetached(QStringLiteral("konsole"), args); + if (QApplication::queryKeyboardModifiers() == Qt::ControlModifier) + process.startDetached(QStringLiteral("xterm"), args); + else + process.startDetached(QStringLiteral("konsole"), args); } + void LtsOperatorMenu::setTerminalButton(bool bVisible) { - m_ui->pbWindow->setVisible(bVisible); + m_ui->pbWindow->setVisible(bVisible); } void LtsOperatorMenu::setOperatorSettingsButton(bool bVisible) { - m_ui->pbOperatorSettings->setVisible(bVisible); + m_ui->pbOperatorSettings->setVisible(bVisible); } + void LtsOperatorMenu::onLanguageChange() { - if (m_ui->pbGer->isChecked()) - NGL::setTranslationLocale(QByteArray("de_DE")); + if (m_ui->pbGer->isChecked()) + NGL::setTranslationLocale(QByteArray("de_DE")); - if (m_ui->pbInt->isChecked()) - NGL::setTranslationLocale(QByteArray("en_GB")); + if (m_ui->pbInt->isChecked()) + NGL::setTranslationLocale(QByteArray("en_GB")); } } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_operator_menu.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_operator_menu.h index 2e1036142..700453197 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_operator_menu.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_operator_menu.h @@ -1,13 +1,20 @@ - +/** + * @RDE_HEADER@ + * User Menu on active sessions (logout, etc.) + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Mike Wille, SLSE, 2016-08-17 + */ #pragma once + #include "lts_frameless_dialog.h" #include "lts_widgets_export.h" -#include -namespace Ui -{ +namespace Ui { class LtsOperatorMenu; } @@ -15,29 +22,28 @@ namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsOperatorMenu : public LtsFramelessDialog { - Q_OBJECT + Q_OBJECT - public: - explicit LtsOperatorMenu(const QString& operatorName, const QString& workspaceId, bool debug, int screenCount, - QWidget* parent); - ~LtsOperatorMenu(); +public: + explicit LtsOperatorMenu(const QString &operatorName, const QString &workspaceId, bool debug, int screenCount, QWidget *parent); + ~LtsOperatorMenu(); - void setTerminalButton(bool bVisible); - void setOperatorSettingsButton(bool bVisible); + void setTerminalButton(bool bVisible); + void setOperatorSettingsButton(bool bVisible); - private: - Ui::LtsOperatorMenu* m_ui; +private: + Ui::LtsOperatorMenu *m_ui; - signals: - void signalLogout(); - void signalExit(); - void signalShowOperatorSettings(); - void signalSwap(); +signals: + void signalLogout(); + void signalExit(); + void signalShowOperatorSettings(); + void signalSwap(); - private slots: - void onTerminalButtonClicked(); - void onLanguageChange(); - void slotShowInfoDialog(); +private slots: + void onTerminalButtonClicked(); + void onLanguageChange(); + void slotShowInfoDialog(); }; } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_overlay_loading.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_overlay_loading.cpp index 6c3ee7ab1..65a951bb0 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_overlay_loading.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_overlay_loading.cpp @@ -1,7 +1,16 @@ - +/** + * @RDE_HEADER@ + * An overlay for LtsDialog's setOverlay(..) which shows a 'loading bar' + * (a progress bar in a special state) and a default label "Loading ...", which + * can be altered + * $Id: $ + * $HeadURL: $ + * $Author: $ + * + * Created by Mike Lennart Wille, SLTE, 2022-07-07 + */ #include "lts_overlay_loading.h" - #include "ui_lts_overlay_loading.h" #include @@ -9,29 +18,37 @@ #include #include + namespace LtsWidgets { -LtsOverlayLoading::LtsOverlayLoading(QWidget* parent) : QWidget(parent), m_ui(new Ui::LtsOverlayLoading) +LtsOverlayLoading::LtsOverlayLoading(QWidget *parent) + : QWidget(parent) + , m_ui(new Ui::LtsOverlayLoading) { - m_ui->setupUi(this); - setCancelButtonVisible(false); - connect(m_ui->pbCancel, &QPushButton::clicked, this, [this]() { setCancelButtonEnabled(false); }); - connect(m_ui->pbCancel, &QPushButton::clicked, this, &LtsOverlayLoading::cancel); + m_ui->setupUi(this); + setCancelButtonVisible(false); + connect(m_ui->pbCancel, &QPushButton::clicked, + this, [this](){ setCancelButtonEnabled(false); }); + connect(m_ui->pbCancel, &QPushButton::clicked, + this, &LtsOverlayLoading::cancel); } -void LtsOverlayLoading::setText(const QString& text) + +void LtsOverlayLoading::setText(const QString &text) { - m_ui->label->setText(text); + m_ui->label->setText(text); } + void LtsOverlayLoading::setCancelButtonVisible(bool visible) { - m_ui->pbCancel->setVisible(visible); + m_ui->pbCancel->setVisible(visible); } + void LtsOverlayLoading::setCancelButtonEnabled(bool enabled) { - m_ui->pbCancel->setEnabled(enabled); + m_ui->pbCancel->setEnabled(enabled); } } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_overlay_loading.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_overlay_loading.h index 9b3a3bb9f..5ce4b529e 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_overlay_loading.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_overlay_loading.h @@ -1,33 +1,48 @@ - +/** + * @RDE_HEADER@ + * An overlay for LtsDialog's setOverlay(..) which shows a 'loading bar' + * (a progress bar in a special state) and a default label "Loading ...", which + * can be altered + * $Id: $ + * $HeadURL: $ + * $Author: $ + * + * Created by Mike Lennart Wille, SLTE, 2022-07-07 + */ #pragma once + #include "lts_widgets_export.h" -#include #include -namespace Ui -{ -class LtsOverlayLoading; -} + +namespace Ui { class LtsOverlayLoading; } + namespace LtsWidgets { - +/** + * @brief The LtsOverlayLoading class is an overlay for LtsDialog's + * setOverlay(..) which shows a 'loading bar' (a progress bar in a special + * state), a default label "Loading ..." - which can be altered with + * 'setText(..)' - and a cancel button (hidden by default) that emits the + * 'cancel' signal. + */ class LTSWIDGETS_EXPORT LtsOverlayLoading : public QWidget { - Q_OBJECT - public: - explicit LtsOverlayLoading(QWidget* parent = nullptr); + Q_OBJECT +public: + explicit LtsOverlayLoading(QWidget *parent = nullptr); - void setText(const QString& text); - void setCancelButtonVisible(bool visible); - void setCancelButtonEnabled(bool enabled); + void setText(const QString &text); + void setCancelButtonVisible(bool visible); + void setCancelButtonEnabled(bool enabled); - signals: - void cancel(); +signals: + void cancel(); - private: - Ui::LtsOverlayLoading* m_ui; +private: + Ui::LtsOverlayLoading *m_ui; }; -} // namespace LtsWidgets +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_picture_view.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_picture_view.cpp index b39ae38a2..2cc3c7a88 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_picture_view.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_picture_view.cpp @@ -1,334 +1,345 @@ - +/** + * @RDE_HEADER@ + * Crop pictures + * $Id$ + * $HeadURL$ + * $Author$ + * Created by Raphael Becker + */ #include "lts_picture_view.h" - -#include -#include #include +#include +#include #include + using namespace LtsWidgets; -LtsPictureView::LtsPictureView(QWidget* parent) - : QGraphicsView(parent), m_gsPicture(new QGraphicsScene(this)), - m_rubberband(new QRubberBand(QRubberBand::Rectangle, this)), m_image(nullptr), m_origimage(nullptr) +LtsPictureView::LtsPictureView(QWidget *parent) + : QGraphicsView(parent) + , m_gsPicture(new QGraphicsScene(this)) + , m_rubberband(new QRubberBand(QRubberBand::Rectangle, this)) + , m_image(nullptr) + , m_origimage(nullptr) { - m_mouseActive = false; - m_moveable = false; - m_aspectRatioEnabled = true; - m_s_inEdit = false; + m_mouseActive = false; + m_moveable = false; + m_aspectRatioEnabled = true; + m_s_inEdit = false; - m_aspectRatio = 1; + m_aspectRatio = 1; - setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); } LtsPictureView::~LtsPictureView() { - delete m_rubberband; + delete m_rubberband; } void LtsPictureView::setAspectRatio(double aspectRatio) { - m_aspectRatio = aspectRatio; - newRubberBand(); + m_aspectRatio = aspectRatio; + newRubberBand(); } void LtsPictureView::ratioClicked(bool enabled) { - m_aspectRatioEnabled = enabled; - if (enabled) - newRubberBand(); + m_aspectRatioEnabled = enabled; + if (enabled) + newRubberBand(); } -void LtsPictureView::mousePressEvent(QMouseEvent* event) +void LtsPictureView::mousePressEvent(QMouseEvent *event) { - if (event->button() == Qt::LeftButton) + if (event->button() == Qt::LeftButton) + { + if (m_rubberband->geometry().contains(event->pos())) { - if (m_rubberband->geometry().contains(event->pos())) + m_bandoffset = event->pos() - m_rubberband->pos(); + m_moveable = true; + m_rubberband->show(); + } + else + { + m_origin = event->pos(); + m_curRectangle = QRect(m_origin.x(), m_origin.y(), 0, 0); + m_rubberband->setGeometry(m_curRectangle); + m_rubberband->show(); + m_mouseActive = true; + } + } + else + { + hideRubberband(); + newRubberBand(); + m_mouseActive = false; + } + QGraphicsView::mousePressEvent(event); +} + +void LtsPictureView::mouseMoveEvent(QMouseEvent *event) +{ + if (m_moveable == true) + { + QPoint newCoord = event->pos() - m_bandoffset; + if (newCoord.x() < 0) + newCoord.setX(0); + if (newCoord.y() < 0) + newCoord.setY(0); + if (m_origimage->pixmap().width() < (newCoord.x() + m_rubberband->width())) + newCoord.setX(m_origimage->pixmap().width() - m_rubberband->width() + 1); + if (m_origimage->pixmap().height() < (newCoord.y() + m_rubberband->height())) + newCoord.setY(m_origimage->pixmap().height() - m_rubberband->height() + 1); + m_rubberband->move(newCoord); + QPoint move = m_rubberband->pos(); + int left = move.x(); + int top = move.y(); + int width = m_rubberband->rect().width(); + int height = m_rubberband->rect().height(); + emit mouseMoved(QRect(left, top, width, height)); + } + else + { + if (m_mouseActive) + { + QRect rect; + + int xMax = event->pos().x(); + int yMax = event->pos().y(); + + if (event->pos().x() > m_origimage->pixmap().width()) + xMax = m_origimage->pixmap().width(); + if (event->pos().x() < 0) + xMax = 0; + if (event->pos().y() > m_origimage->pixmap().height()) + yMax = m_origimage->pixmap().height(); + if (event->pos().y() < 0) + yMax = 0; + + if (m_aspectRatioEnabled) + { + const int xMin = m_origin.x(); + const int yMin = m_origin.y(); + + int xLengthAbs(std::abs(xMax - xMin)); + int yLengthAbs(std::abs(yMax - yMin)); + + QPoint length; + + if (xLengthAbs / m_aspectRatio > yLengthAbs * m_aspectRatio) { - m_bandoffset = event->pos() - m_rubberband->pos(); - m_moveable = true; - m_rubberband->show(); + length.setX(xLengthAbs); + length.setY(length.x() / m_aspectRatio); } else { - m_origin = event->pos(); - m_curRectangle = QRect(m_origin.x(), m_origin.y(), 0, 0); - m_rubberband->setGeometry(m_curRectangle); - m_rubberband->show(); - m_mouseActive = true; + length.setY(yLengthAbs); + length.setX(length.y() * m_aspectRatio); } - } - else - { - hideRubberband(); - newRubberBand(); - m_mouseActive = false; - } - QGraphicsView::mousePressEvent(event); -} -void LtsPictureView::mouseMoveEvent(QMouseEvent* event) -{ - if (m_moveable == true) - { - QPoint newCoord = event->pos() - m_bandoffset; - if (newCoord.x() < 0) - newCoord.setX(0); - if (newCoord.y() < 0) - newCoord.setY(0); - if (m_origimage->pixmap().width() < (newCoord.x() + m_rubberband->width())) - newCoord.setX(m_origimage->pixmap().width() - m_rubberband->width() + 1); - if (m_origimage->pixmap().height() < (newCoord.y() + m_rubberband->height())) - newCoord.setY(m_origimage->pixmap().height() - m_rubberband->height() + 1); - m_rubberband->move(newCoord); - QPoint move = m_rubberband->pos(); - int left = move.x(); - int top = move.y(); - int width = m_rubberband->rect().width(); - int height = m_rubberband->rect().height(); - emit mouseMoved(QRect(left, top, width, height)); - } - else - { - if (m_mouseActive) + if (!(yMax - yMin < 0) && length.y() + m_origin.y() > m_origimage->pixmap().height()) { - QRect rect; - - int xMax = event->pos().x(); - int yMax = event->pos().y(); - - if (event->pos().x() > m_origimage->pixmap().width()) - xMax = m_origimage->pixmap().width(); - if (event->pos().x() < 0) - xMax = 0; - if (event->pos().y() > m_origimage->pixmap().height()) - yMax = m_origimage->pixmap().height(); - if (event->pos().y() < 0) - yMax = 0; - - if (m_aspectRatioEnabled) - { - const int xMin = m_origin.x(); - const int yMin = m_origin.y(); - - int xLengthAbs(std::abs(xMax - xMin)); - int yLengthAbs(std::abs(yMax - yMin)); - - QPoint length; - - if (xLengthAbs / m_aspectRatio > yLengthAbs * m_aspectRatio) - { - length.setX(xLengthAbs); - length.setY(length.x() / m_aspectRatio); - } - else - { - length.setY(yLengthAbs); - length.setX(length.y() * m_aspectRatio); - } - - if (!(yMax - yMin < 0) && length.y() + m_origin.y() > m_origimage->pixmap().height()) - { - length.setY(m_origimage->pixmap().height() - m_origin.y()); - length.setX(length.y() * m_aspectRatio); - } - if (!(xMax - xMin < 0) && length.x() + m_origin.x() > m_origimage->pixmap().width()) - { - length.setX(m_origimage->pixmap().width() - m_origin.x()); - length.setY(length.x() / m_aspectRatio); - } - - if (xMax - xMin < 0) - { - length.setX(length.x() * -1); - if (length.x() + m_origin.x() < 0) - { - length.setX(0 - m_origin.x()); - length.setY((length.x() / m_aspectRatio) * -1); - } - } - - if (yMax - yMin < 0) - { - length.setY(length.y() * -1); - if (length.y() + m_origin.y() < 0) - { - length.setY(0 - m_origin.y()); - length.setX(length.y() * m_aspectRatio); - if (!(xMax - xMin < 0)) - length.setX(length.x() * -1); - } - } - - length = m_origin + length; - rect.setTopLeft(m_origin); - rect.setBottomRight(length); - } - else - { - rect.setTopLeft(m_origin); - rect.setBottomRight(QPoint(xMax, yMax)); - } - m_curRectangle = rect.normalized(); - m_rubberband->setGeometry(m_curRectangle); - emit mouseMoved(m_curRectangle); + length.setY(m_origimage->pixmap().height() - m_origin.y()); + length.setX(length.y()* m_aspectRatio); } + if (!(xMax - xMin < 0) && length.x() + m_origin.x() > m_origimage->pixmap().width()) + { + length.setX(m_origimage->pixmap().width() - m_origin.x()); + length.setY(length.x() / m_aspectRatio); + } + + if (xMax - xMin < 0) + { + length.setX(length.x() * -1); + if (length.x() + m_origin.x() < 0) + { + length.setX(0 - m_origin.x()); + length.setY((length.x() / m_aspectRatio) * -1); + } + } + + if (yMax - yMin < 0) + { + length.setY(length.y() * -1); + if (length.y() + m_origin.y() < 0) + { + length.setY(0 - m_origin.y()); + length.setX(length.y() * m_aspectRatio); + if (!(xMax - xMin < 0)) + length.setX(length.x() * -1); + } + } + + length = m_origin + length; + rect.setTopLeft(m_origin); + rect.setBottomRight(length); + } + else + { + rect.setTopLeft(m_origin); + rect.setBottomRight(QPoint(xMax, yMax)); + } + m_curRectangle = rect.normalized(); + m_rubberband->setGeometry(m_curRectangle); + emit mouseMoved(m_curRectangle); } - QGraphicsView::mouseMoveEvent(event); + } + QGraphicsView::mouseMoveEvent(event); } -void LtsPictureView::mouseReleaseEvent(QMouseEvent* event) +void LtsPictureView::mouseReleaseEvent(QMouseEvent *event) { - m_moveable = false; - QGraphicsView::mouseReleaseEvent(event); + m_moveable = false; + QGraphicsView::mouseReleaseEvent(event); } void LtsPictureView::hideRubberband() { - m_rubberband->hide(); + m_rubberband->hide(); } void LtsPictureView::newRubberBand() { - delete m_rubberband; - m_rubberband = new QRubberBand(QRubberBand::Rectangle, this); + delete m_rubberband; + m_rubberband = new QRubberBand(QRubberBand::Rectangle, this); } -void LtsPictureView::setPicture(const QImage& image, const QPoint& pos, const bool flag) +void LtsPictureView::setPicture(const QImage &image, const QPoint &pos, const bool flag) { - if (m_image) + if (m_image) + { + m_gsPicture->removeItem(m_image); + delete m_image; + } + if (flag) + { + if (m_origimage) { - m_gsPicture->removeItem(m_image); - delete m_image; + m_gsPicture->removeItem(m_origimage); + delete m_origimage; } - if (flag) - { - if (m_origimage) - { - m_gsPicture->removeItem(m_origimage); - delete m_origimage; - } - QGraphicsOpacityEffect* opacity = new QGraphicsOpacityEffect; - opacity->setOpacity(0.2); + QGraphicsOpacityEffect *opacity = new QGraphicsOpacityEffect; + opacity->setOpacity(0.2); - m_origimage = new QGraphicsPixmapItem(QPixmap::fromImage(image)); - m_origimage->setGraphicsEffect(opacity); + m_origimage = new QGraphicsPixmapItem(QPixmap::fromImage(image)); + m_origimage->setGraphicsEffect(opacity); - m_gsPicture->addItem(m_origimage); + m_gsPicture->addItem(m_origimage); - setMinimumSize(image.size()); - setMaximumSize(image.size()); - emit setLimits(m_origimage->pixmap().size(), true); - } - m_image = new QGraphicsPixmapItem(QPixmap::fromImage(image)); + setMinimumSize(image.size()); + setMaximumSize(image.size()); + emit setLimits(m_origimage->pixmap().size(), true); + } + m_image = new QGraphicsPixmapItem(QPixmap::fromImage(image)); - m_image->setPos(pos); - m_gsPicture->addItem(m_image); - setScene(m_gsPicture); + m_image->setPos(pos); + m_gsPicture->addItem(m_image); + setScene(m_gsPicture); } void LtsPictureView::leftChanged(int left) { - if (m_s_inEdit || m_mouseActive) - return; - m_s_inEdit = true; - m_curRectangle.setLeft(left); - if (m_aspectRatioEnabled) + if (m_s_inEdit || m_mouseActive) + return; + m_s_inEdit = true; + m_curRectangle.setLeft(left); + if(m_aspectRatioEnabled) + { + int newHeight = m_curRectangle.width() / m_aspectRatio; + if (m_origin.y() < m_curRectangle.bottom()) { - int newHeight = m_curRectangle.width() / m_aspectRatio; - if (m_origin.y() < m_curRectangle.bottom()) - { - m_curRectangle.setHeight(newHeight); - } - else - { - int offset = m_curRectangle.height() - newHeight; - m_curRectangle.setTop(m_curRectangle.top() + offset); - } + m_curRectangle.setHeight(newHeight); } - m_rubberband->setGeometry(m_curRectangle); - emit mouseMoved(m_curRectangle); - m_s_inEdit = false; + else + { + int offset = m_curRectangle.height() - newHeight; + m_curRectangle.setTop(m_curRectangle.top() + offset); + } + } + m_rubberband->setGeometry(m_curRectangle); + emit mouseMoved(m_curRectangle); + m_s_inEdit = false; } void LtsPictureView::rightChanged(int right) { - if (m_s_inEdit || m_mouseActive) - return; - m_s_inEdit = true; - m_curRectangle.setRight(right); - if (m_aspectRatioEnabled) + if (m_s_inEdit || m_mouseActive) + return; + m_s_inEdit = true; + m_curRectangle.setRight(right); + if(m_aspectRatioEnabled) + { + int newHeight = m_curRectangle.width() / m_aspectRatio; + if (m_origin.y() < m_curRectangle.bottom()) { - int newHeight = m_curRectangle.width() / m_aspectRatio; - if (m_origin.y() < m_curRectangle.bottom()) - { - m_curRectangle.setHeight(newHeight); - } - else - { - int offset = m_curRectangle.height() - newHeight; - m_curRectangle.setTop(m_curRectangle.top() + offset); - } + m_curRectangle.setHeight(newHeight); } - m_rubberband->setGeometry(m_curRectangle); - emit mouseMoved(m_curRectangle); - m_s_inEdit = false; + else + { + int offset = m_curRectangle.height() - newHeight; + m_curRectangle.setTop(m_curRectangle.top() + offset); + } + } + m_rubberband->setGeometry(m_curRectangle); + emit mouseMoved(m_curRectangle); + m_s_inEdit = false; } void LtsPictureView::topChanged(int top) { - if (m_s_inEdit || m_mouseActive) - return; - m_s_inEdit = true; - m_curRectangle.setTop(top); - if (m_aspectRatioEnabled) + if (m_s_inEdit || m_mouseActive) + return; + m_s_inEdit = true; + m_curRectangle.setTop(top); + if(m_aspectRatioEnabled) + { + int newWidth = m_curRectangle.height() * m_aspectRatio; + if (m_origin.x() <= m_curRectangle.left()) { - int newWidth = m_curRectangle.height() * m_aspectRatio; - if (m_origin.x() <= m_curRectangle.left()) - { - m_curRectangle.setWidth(newWidth); - } - else - { - int offset = m_curRectangle.width() - newWidth; - m_curRectangle.setLeft(m_curRectangle.left() + offset); - } + m_curRectangle.setWidth(newWidth); } - m_rubberband->setGeometry(m_curRectangle); - emit mouseMoved(m_curRectangle); - m_s_inEdit = false; + else + { + int offset = m_curRectangle.width() - newWidth; + m_curRectangle.setLeft(m_curRectangle.left() + offset); + } + } + m_rubberband->setGeometry(m_curRectangle); + emit mouseMoved(m_curRectangle); + m_s_inEdit = false; } void LtsPictureView::bottomChanged(int bottom) { - if (m_s_inEdit || m_mouseActive) - return; - m_s_inEdit = true; - m_curRectangle.setBottom(bottom); - if (m_aspectRatioEnabled) + if (m_s_inEdit || m_mouseActive) + return; + m_s_inEdit = true; + m_curRectangle.setBottom(bottom); + if(m_aspectRatioEnabled) + { + int newWidth = m_curRectangle.height() * m_aspectRatio; + if (m_origin.x() <= m_curRectangle.left()) { - int newWidth = m_curRectangle.height() * m_aspectRatio; - if (m_origin.x() <= m_curRectangle.left()) - { - m_curRectangle.setWidth(newWidth); - } - else - { - int offset = m_curRectangle.width() - newWidth; - m_curRectangle.setLeft(m_curRectangle.left() + offset); - } + m_curRectangle.setWidth(newWidth); } - m_rubberband->setGeometry(m_curRectangle); - emit mouseMoved(m_curRectangle); - m_s_inEdit = false; + else + { + int offset = m_curRectangle.width() - newWidth; + m_curRectangle.setLeft(m_curRectangle.left() + offset); + } + } + m_rubberband->setGeometry(m_curRectangle); + emit mouseMoved(m_curRectangle); + m_s_inEdit = false; } -QGraphicsPixmapItem* LtsPictureView::getImage() + +QGraphicsPixmapItem *LtsPictureView::getImage() { - if (!m_image) - m_image = new QGraphicsPixmapItem; - return m_image; + if (!m_image) + m_image = new QGraphicsPixmapItem; + return m_image; } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_picture_view.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_picture_view.h index bbba9fe3b..03e4069f1 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_picture_view.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_picture_view.h @@ -1,10 +1,16 @@ - +/** + * @RDE_HEADER@ + * Crop pictures + * $Id$ + * $HeadURL$ + * $Author$ + * Created by Raphael Becker + */ #pragma once -#include "lts_widgets_export.h" +#include "lts_widgets_export.h" #include -#include class QRubberBand; @@ -12,49 +18,49 @@ namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsPictureView : public QGraphicsView { - Q_OBJECT + Q_OBJECT - public: - explicit LtsPictureView(QWidget* parent = nullptr); - ~LtsPictureView(); - void hideRubberband(); - void newRubberBand(); - void cutPicture(); - QGraphicsPixmapItem* getImage(); +public: + explicit LtsPictureView(QWidget *parent = nullptr); + ~LtsPictureView(); + void hideRubberband(); + void newRubberBand(); + void cutPicture(); + QGraphicsPixmapItem *getImage(); - protected: - void mousePressEvent(QMouseEvent* event) override; - void mouseMoveEvent(QMouseEvent* event) override; - void mouseReleaseEvent(QMouseEvent* event) override; +protected: + void mousePressEvent(QMouseEvent *event) override; + void mouseMoveEvent(QMouseEvent *event) override; + void mouseReleaseEvent(QMouseEvent *event) override; - private: - bool m_mouseActive; - bool m_moveable; - bool m_aspectRatioEnabled; - bool m_s_inEdit; +private: + bool m_mouseActive; + bool m_moveable; + bool m_aspectRatioEnabled; + bool m_s_inEdit; - double m_aspectRatio; - QRect m_curRectangle; + double m_aspectRatio; + QRect m_curRectangle; - QGraphicsScene* m_gsPicture; - QRubberBand* m_rubberband; - QGraphicsPixmapItem* m_image; - QGraphicsPixmapItem* m_origimage; + QGraphicsScene *m_gsPicture; + QRubberBand *m_rubberband; + QGraphicsPixmapItem *m_image; + QGraphicsPixmapItem *m_origimage; - QPoint m_origin; - QPoint m_bandoffset; + QPoint m_origin; + QPoint m_bandoffset; - public slots: - void setPicture(const QImage& image, const QPoint& pos, const bool flag); - void setAspectRatio(double aspectRatio); - void ratioClicked(bool enabled); - void leftChanged(int left); - void rightChanged(int right); - void topChanged(int top); - void bottomChanged(int bottom); +public slots: + void setPicture(const QImage &image, const QPoint &pos, const bool flag); + void setAspectRatio(double aspectRatio); + void ratioClicked(bool enabled); + void leftChanged(int left); + void rightChanged(int right); + void topChanged(int top); + void bottomChanged(int bottom); - signals: - void mouseMoved(const QRect&); - void setLimits(const QSize&, bool); +signals: + void mouseMoved(const QRect &); + void setLimits(const QSize &, bool); }; -} // namespace LtsWidgets +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_profile_button.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_profile_button.cpp index 3ff4711ac..9d6bc8b15 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_profile_button.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_profile_button.cpp @@ -1,110 +1,140 @@ - +/** + * @RDE_HEADER@ + * A Button with an elliptic Pixmap and a menu icon when hovering. In the style of LtsStyle. + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Mike Wille, SLSE, 2016-06-20 + */ #include "lts_profile_button.h" -#include -#include -#include #include #include +#include +#include #include #include +#include using namespace LtsWidgets; -LtsProfileButton::LtsProfileButton(QWidget* parent) : QWidget(parent), m_isHovered(false), m_menuEnabled(true) + +LtsProfileButton::LtsProfileButton(QWidget *parent) + : QWidget(parent) + , m_isHovered(false) + , m_menuEnabled(true) // enabled by default { - QSizePolicy qsp = QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); - qsp.setHeightForWidth(true); - setSizePolicy(qsp); + QSizePolicy qsp = QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); + qsp.setHeightForWidth(true); + setSizePolicy(qsp); } -void LtsProfileButton::setPixmap(const QPixmap& pixmap) -{ - if (pixmap.isNull()) - m_pixmap = QPixmap(QStringLiteral("icon:no_pic.svg")); - else - m_pixmap = pixmap; - update(); +void LtsProfileButton::setPixmap(const QPixmap &pixmap) +{ + if (pixmap.isNull()) // invalid / empty pixmap given, trying to replace it with one from lts_resources + m_pixmap = QPixmap(QStringLiteral("icon:no_pic.svg")); // when this fails, the pixmap is still invalid, so no checks needed + else + m_pixmap = pixmap; + + update(); } -void LtsProfileButton::enterEvent(QEvent* event) -{ - m_isHovered = true; - update(); - QWidget::enterEvent(static_cast(event)); +void LtsProfileButton::enterEvent(QEvent *event) +{ + //qWarning() << "enter"; + m_isHovered = true; + update(); + QWidget::enterEvent(event); } -void LtsProfileButton::leaveEvent(QEvent* event) -{ - m_isHovered = false; - update(); - QWidget::leaveEvent(event); +void LtsProfileButton::leaveEvent(QEvent *event) +{ + //qWarning() << "leave"; + m_isHovered = false; + update(); + QWidget::leaveEvent(event); } -bool LtsProfileButton::event(QEvent* event) + +bool LtsProfileButton::event(QEvent *event) { - if (event->type() == QEvent::MouseButtonPress && m_menuEnabled) - { - emit signalClicked(); - event->accept(); - - update(); - return true; - } - - return QWidget::event(event); -} - -void LtsProfileButton::paintEvent(QPaintEvent* event) -{ - QPainter p(this); - p.save(); - - int minSize; - QPointF center; - minSize = height() > width() ? width() : height(); - center = QPointF(width() / 2.0, height() / 2.0); - - p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); - - QPixmap pixmap(minSize, minSize); - pixmap.fill(Qt::white); - - if (!m_pixmap.isNull()) - { - if (!(m_isHovered && m_menuEnabled)) - { - pixmap = m_pixmap.scaled(minSize, minSize, Qt::KeepAspectRatioByExpanding); - } - } - - QPainterPath path; - path.addEllipse(center, minSize / 2.0 - 4, minSize / 2.0 - 4); - p.setClipPath(path); - p.drawPixmap(center - QPointF(minSize / 2.0, minSize / 2.0), pixmap); - - p.setPen(QPen(QColor("gray"), 2)); - p.drawEllipse(center, minSize / 2.0 - 4, minSize / 2.0 - 4); - - if (m_isHovered && m_menuEnabled) - { - p.setPen(QPen(QColor(QStringLiteral("gray")), (minSize / 48 * 2))); - - double xc = size().width() / 2.012; - double yc = size().height() / 2.012; - double diff = minSize / 2.012; - - p.drawLine(QPointF(xc - (diff / 2.01f), yc - (diff / 3.01f)), - QPointF(xc + (diff / 2.02f), yc - (diff / 3.02f))); - p.drawLine(QPointF(xc - (diff / 2.01f), yc - 0.01f), QPointF(xc + (diff / 2.02f), yc - 0)); - p.drawLine(QPointF(xc - (diff / 2.01f), yc + (diff / 3.01f)), - QPointF(xc + (diff / 2.02f), yc + (diff / 3.02f))); - } - + if (event->type() == QEvent::MouseButtonPress && m_menuEnabled) + { + emit signalClicked(); event->accept(); - p.restore(); +// m_isHovered = false; // unhovered on click + update(); + return true; + } + + return QWidget::event(event); // otherwise.. +} + + +void LtsProfileButton::paintEvent(QPaintEvent* event) // TODO: colors from palette (style plugin) ? +{ + QPainter p(this); + p.save(); + + int minSize; + QPointF center; + minSize = height() > width() ? width() : height(); + center = QPointF(width() / 2.0, height() / 2.0); + + + // draw profile picture + p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); +// QBrush brush = QColor(QStringLiteral("white")); // TODO: from palette + + QPixmap pixmap(minSize, minSize); + pixmap.fill(Qt::white); + + if (!m_pixmap.isNull()) + { + if (!(m_isHovered && m_menuEnabled)) // draw if NOT hovered or draw when hovered but menu is disabled + { + pixmap = m_pixmap.scaled(minSize, minSize, Qt::KeepAspectRatioByExpanding); + } + } + +// p.setBrush(Qt::white); +// p.setPen(Qt::NoPen); + QPainterPath path; + path.addEllipse(center, + minSize / 2.0 - 4, + minSize / 2.0 - 4); + p.setClipPath(path); + p.drawPixmap(center - QPointF(minSize/2.0,minSize/2.0),pixmap); + + + + // draw frame + p.setPen(QPen(QColor("gray"), 2)); + p.drawEllipse(center, + minSize / 2.0 - 4, + minSize / 2.0 - 4); + + + // draw menu icon + if (m_isHovered && m_menuEnabled) + { + p.setPen(QPen(QColor(QStringLiteral("gray")), (minSize / 48 * 2))); // respect height, width is unnecessary + + double xc = size().width()/2.012; + double yc = size().height()/2.012; + double diff = minSize/2.012; + + p.drawLine(QPointF(xc - (diff/2.01f), yc - (diff/3.01f)), QPointF(xc + (diff/2.02f), yc - (diff/3.02f))); + p.drawLine(QPointF(xc - (diff/2.01f), yc - 0.01f), QPointF(xc + (diff/2.02f), yc - 0)); + p.drawLine(QPointF(xc - (diff/2.01f), yc + (diff/3.01f)), QPointF(xc + (diff/2.02f), yc + (diff/3.02f))); + } + + + event->accept(); + p.restore(); } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_profile_button.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_profile_button.h index 668ba5358..fc4432aa0 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_profile_button.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_profile_button.h @@ -1,55 +1,70 @@ - +/** + * @RDE_HEADER@ + * A Button with an elliptic Pixmap and a menu icon when hovering. In the style of LtsStyle. + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Mike Wille, SLSE, 2016-06-20 + */ #pragma once + #include "lts_widgets_export.h" -#include #include + namespace LtsWidgets { +/** + * @brief The LtsProfileButton class provides a Button which has a round form, containing a picture. On hovering the picture turns into + * a "menu" icon to symbolize the clickability of the button. + * If no pixmap / picture is set, the picture-layer is button colored. + */ class LTSWIDGETS_EXPORT LtsProfileButton : public QWidget { - Q_OBJECT + Q_OBJECT - Q_PROPERTY(QPixmap pixMap READ pixmap WRITE setPixmap) - Q_PROPERTY(bool menuEnabled READ menuEnabled WRITE setMenuEnabled) + Q_PROPERTY( QPixmap pixMap READ pixmap WRITE setPixmap ) + Q_PROPERTY( bool menuEnabled READ menuEnabled WRITE setMenuEnabled ) - public: - explicit LtsProfileButton(QWidget* parent = nullptr); +public: + explicit LtsProfileButton(QWidget *parent = nullptr); - void setPixmap(const QPixmap& pixmap); + /** + * @brief setPixmap sets the picture of this button. If no pixmap / picture is set, the picture-layer is button colored. + * @param pixmap The picture to draw on the button. + */ + void setPixmap(const QPixmap &pixmap); - const QPixmap& pixmap() const - { - return m_pixmap; - } + const QPixmap &pixmap() const { return m_pixmap; } - void setMenuEnabled(bool enabled = true) - { - m_menuEnabled = enabled; - } + /** + * @brief setMenuEnabled changes the hover & click behaviour. If the menu is enabled, the profile button indicates a menu on hovering, and by clicking it, the signal 'signalClicked' is emitted (menu is enabled by default) + * @param enabled true if menu is enabled, false if not + */ + void setMenuEnabled(bool enabled = true) { m_menuEnabled = enabled; } + bool menuEnabled() const { return m_menuEnabled; } - bool menuEnabled() const - { - return m_menuEnabled; - } - protected: - void paintEvent(QPaintEvent* event); - void enterEvent(QEvent* event); - void leaveEvent(QEvent* event); - bool event(QEvent* event); +protected: + void paintEvent(QPaintEvent *event); + void enterEvent(QEvent *event); + void leaveEvent(QEvent *event); + bool event(QEvent *event); - private: - QPixmap m_pixmap; - bool m_isHovered; - bool m_menuEnabled; +private: + QPixmap m_pixmap; + bool m_isHovered; + bool m_menuEnabled; - signals: - - void signalClicked(); +signals: + /** + * @brief signalClicked is emitted when the button has been clicked. + */ + void signalClicked(); }; -} // namespace LtsWidgets +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_progress_dialog_helper.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_progress_dialog_helper.cpp index 91f4dcfe3..8324b3f16 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_progress_dialog_helper.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_progress_dialog_helper.cpp @@ -1,4 +1,12 @@ - +/** + * @RDE_HEADER@ + * Helper Class, which manages a progress Dialog with two states. + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Mike Wille, SLSE, 2016-06-20 + */ #include "lts_progress_dialog_helper.h" @@ -11,118 +19,136 @@ #include #include + namespace LtsWidgets { -LtsProgressDialogHelper::LtsProgressDialogHelper(QWidget* parent) - : QObject(parent), m_waitDlg(nullptr), m_parentWidget(parent), m_textLabel(nullptr) -{ -} +LtsProgressDialogHelper::LtsProgressDialogHelper(QWidget *parent) + : QObject(parent) + , m_waitDlg(nullptr) // save mem + , m_parentWidget(parent) + , m_textLabel(nullptr) +{} + LtsProgressDialogHelper::~LtsProgressDialogHelper() { - delete m_waitDlg; + delete m_waitDlg; } -void LtsProgressDialogHelper::setCustomText(const QString& customText) -{ - if (m_waitDlg == nullptr || m_textLabel == nullptr) - return; - if (customText.isEmpty()) - m_textLabel->setText(tr("Waiting for server reply...")); - else - m_textLabel->setText(customText); +void LtsProgressDialogHelper::setCustomText(const QString &customText) +{ + if (m_waitDlg == nullptr || m_textLabel == nullptr) + return; + + if (customText.isEmpty()) + m_textLabel->setText(tr("Waiting for server reply...")); + else + m_textLabel->setText(customText); } -void LtsProgressDialogHelper::setParentWidget(QWidget* newParent) +void LtsProgressDialogHelper::setParentWidget(QWidget *newParent) { - m_parentWidget = newParent; - if (m_waitDlg) - { - m_waitDlg->setParent(newParent); - QTimer::singleShot(0, m_waitDlg.data(), &LtsFramelessDialog::onUpdateGeometry); - } + m_parentWidget = newParent; + if (m_waitDlg) + { + m_waitDlg->setParent(newParent); + QTimer::singleShot(0, m_waitDlg.data(), &LtsFramelessDialog::onUpdateGeometry); + } } void LtsProgressDialogHelper::slotShowWaitForReplyWindow() { - if (m_waitDlg) - m_waitDlg->deleteLater(); - m_waitDlg = new LtsFramelessDialog(m_parentWidget, Behaviour::Modal); + if (m_waitDlg) + m_waitDlg->deleteLater(); //delete m_waitDlg; // when there is already an instance + m_waitDlg = new LtsFramelessDialog(m_parentWidget, Behaviour::Modal); - QHBoxLayout* l = new QHBoxLayout(m_waitDlg); + QHBoxLayout *l = new QHBoxLayout(m_waitDlg); - QProgressBar* pb = new QProgressBar(m_waitDlg); - pb->setMaximum(0); - pb->setValue(-1); + QProgressBar *pb = new QProgressBar(m_waitDlg); + pb->setMaximum(0); + pb->setValue(-1); - l->addWidget(pb); + l->addWidget(pb); - m_textLabel = new QLabel(m_waitDlg); - setCustomText(); - l->addWidget(m_textLabel); + m_textLabel = new QLabel(m_waitDlg); + setCustomText(); + l->addWidget(m_textLabel); - m_waitDlg->setLayout(l); - m_waitDlg->show(); - m_waitDlg->raise(); + m_waitDlg->setLayout(l); + m_waitDlg->show(); + m_waitDlg->raise(); // TODO: needed when StyOnTop is active ? + + //QCoreApplication::processEvents(); // do not look glitched if dds hangs } -void LtsProgressDialogHelper::slotStopWaitForReplyWindow(const ReplyResult& replyResult, const QString& replyString) + +void LtsProgressDialogHelper::slotStopWaitForReplyWindow(const ReplyResult &replyResult, const QString &replyString) { - if (m_waitDlg == nullptr) - { + if (m_waitDlg == nullptr) + { + // TODO: debug/warning that there is no wait dlg.. + return; + } - return; + //qDeleteAll(m_waitDlg->children()); // delete the layout and it's children + m_waitDlg->deleteLater(); // the easiest way + m_waitDlg = nullptr; + + // .. a new layout, telling the reply result + QString resultText = tr("Unknown result (%1)!").arg((int)replyResult); + + switch (replyResult) + { + case ReplyResult::Close: + { + return; // say nothing, just close } - m_waitDlg->deleteLater(); - m_waitDlg = nullptr; - - QString resultText = tr("Unknown result (%1)!").arg((int)replyResult); - - switch (replyResult) + case ReplyResult::Success: { - case ReplyResult::Close: { - return; - } - - case ReplyResult::Success: { - resultText = tr("Operation was successful"); - break; - } - - case ReplyResult::Failure: { - resultText = tr("Operation has failed!\nReason: '%1'").arg(replyString); - break; - } - - case ReplyResult::TimeOut: { - resultText = tr("Operation has timed out and could not be processed! Please try again later"); - break; - } + resultText = tr("Operation was successful"); + break; } - m_waitDlg = new LtsFramelessDialog(m_parentWidget, Behaviour::Modal); + case ReplyResult::Failure: + { + resultText = tr("Operation has failed!\nReason: '%1'").arg(replyString); + break; + } - QVBoxLayout* newLayout = new QVBoxLayout(m_waitDlg); - newLayout->addWidget(new QLabel(resultText, m_waitDlg)); + case ReplyResult::TimeOut: + { + resultText = tr("Operation has timed out and could not be processed! Please try again later"); + break; + } + } - QPushButton* btn = new QPushButton(tr("OK"), m_waitDlg); - connect(btn, &QPushButton::clicked, this, &LtsProgressDialogHelper::accept); + m_waitDlg = new LtsFramelessDialog(m_parentWidget, Behaviour::Modal); - newLayout->addWidget(btn); + QVBoxLayout *newLayout = new QVBoxLayout(m_waitDlg); + newLayout->addWidget(new QLabel(resultText, m_waitDlg)); - m_waitDlg->setLayout(newLayout); - m_waitDlg->show(); + QPushButton *btn = new QPushButton(tr("OK"),m_waitDlg); + connect(btn, &QPushButton::clicked, + this, &LtsProgressDialogHelper::accept); // TODO: or close? + + newLayout->addWidget(btn); + + m_waitDlg->setLayout(newLayout); + m_waitDlg->show(); + + //QCoreApplication::processEvents(); // do not look glitched if dds hangs } + void LtsProgressDialogHelper::accept() { - m_waitDlg->accept(); - m_waitDlg->deleteLater(); - m_waitDlg = nullptr; - emit accepted(); + m_waitDlg->accept(); + m_waitDlg->deleteLater(); + m_waitDlg = nullptr; + emit accepted(); } } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_progress_dialog_helper.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_progress_dialog_helper.h index a1943d38d..2dbc0a312 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_progress_dialog_helper.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_progress_dialog_helper.h @@ -1,4 +1,12 @@ - +/** + * @RDE_HEADER@ + * Helper Class, which manages a progress Dialog with two states. + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Mike Wille, SLSE, 2016-06-20 + */ #pragma once @@ -14,49 +22,61 @@ namespace LtsWidgets { class LtsFramelessDialog; +/** + * @brief The LtsProgressDialogHelper class is a helper class, which can be used to easily + * show a Dialog with eather a wait state (indefinite progress bar), or a default message, + * adjusted to the result type (see ReplyResult) + */ class LTSWIDGETS_EXPORT LtsProgressDialogHelper : public QObject { - Q_OBJECT + Q_OBJECT - public: - enum class ReplyResult { - Close = 0, - Success, - Failure, - TimeOut, - }; +public: + /** + * @brief The ReplyResult enum describes the behaviour of the slotSopWaitForReplyWindow method. + */ + enum class ReplyResult + { + Close = 0, // say nothing, just close automatically + Success, // dialog with success message, has to be receipted + Failure, // dialog with failure message plus reply string, has to be receipted + TimeOut, // dialog with timeout message, has to be receipted + }; - explicit LtsProgressDialogHelper(QWidget* parent = nullptr); - ~LtsProgressDialogHelper(); + explicit LtsProgressDialogHelper(QWidget *parent = nullptr); + ~LtsProgressDialogHelper(); + bool isShown() const { return !!m_waitDlg; } + void setCustomText(const QString &customText = QString()); - bool isShown() const - { - return !!m_waitDlg; - } + void setParentWidget(QWidget *newParent); - void setCustomText(const QString& customText = QString()); +public slots: + /** + * @brief slotShowWaitForReplyWindow shows a centered wait dialog which does not allow the user to interact with the application and cannot be canceled. + */ + void slotShowWaitForReplyWindow(/*const QString &textToShow*/); - void setParentWidget(QWidget* newParent); + /** + * @brief slotStopWaitForReplyWindow closes the wait dialog. Nothing happens when there was no show wait dialog called before. + * @param replyResult The wait dialog is closed on ReplyResult::Close. A new centered, modal dialog is shown on ReplyResult::Failure/Success/Timeout with an error message in it. + * @param replyString An explanatory string shown on ReplyResult::Failure to tell the user what went wrong on. + */ + void slotStopWaitForReplyWindow(const LtsWidgets::LtsProgressDialogHelper::ReplyResult &replyResult = ReplyResult::Close /* say nothing, just close */, + const QString &replyString = QString()); - public slots: +private: + QPointer m_waitDlg; + QWidget *m_parentWidget; + QPointer m_textLabel; - void slotShowWaitForReplyWindow(); +signals: + /** + * @brief accepted is emitted when accept() was called (e.g. by clicking okay) + */ + void accepted(); - void - slotStopWaitForReplyWindow(const LtsWidgets::LtsProgressDialogHelper::ReplyResult& replyResult = ReplyResult::Close, - const QString& replyString = QString()); - - private: - QPointer m_waitDlg; - QWidget* m_parentWidget; - QPointer m_textLabel; - - signals: - - void accepted(); - - private slots: - void accept(); +private slots: + void accept(); }; -} // namespace LtsWidgets +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_range_slider.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_range_slider.cpp index 35abe3b8d..aad9b92e0 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_range_slider.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_range_slider.cpp @@ -1,13 +1,43 @@ +/** + * @RDE_HEADER@ + * A slider that has a minimum and a maximum value, thus can define a range within a range. + * That could be a a snippet out of a video, a time range within an exercise... + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Malte Diers, NLE, 2020-01-06 + */ +/*========================================================================= + + Library: CTK + + Copyright (c) Kitware Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0.txt + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=========================================================================*/ #include "lts_range_slider.h" +// Qt includes #include -#include #include -#include +#include #include #include +#include #include namespace LtsWidgets @@ -15,666 +45,804 @@ namespace LtsWidgets class LtsRangeSliderPrivate { - Q_DECLARE_PUBLIC(LtsRangeSlider) - protected: - LtsRangeSlider* const q_ptr; + Q_DECLARE_PUBLIC(LtsRangeSlider) +protected: + LtsRangeSlider *const q_ptr; +public: + /// Boolean indicates the selected handle + /// True for the minimum range handle, false for the maximum range handle + enum Handle + { + NoHandle = 0x0, + MinimumHandle = 0x1, + MaximumHandle = 0x2 + }; + Q_DECLARE_FLAGS(Handles, Handle) - public: - enum Handle { NoHandle = 0x0, MinimumHandle = 0x1, MaximumHandle = 0x2 }; - Q_DECLARE_FLAGS(Handles, Handle) + explicit LtsRangeSliderPrivate(LtsRangeSlider &object); + void init(); - explicit LtsRangeSliderPrivate(LtsRangeSlider& object); - void init(); + /// Return the handle at the given pos, or none if no handle is at the pos. + /// If a handle is selected, handleRect is set to the handle rect. + /// otherwise return NoHandle and handleRect is set to the combined rect of + /// the min and max handles + Handle handleAtPos(const QPoint &pos, QRect &handleRect) const; - Handle handleAtPos(const QPoint& pos, QRect& handleRect) const; + /// Copied verbatim from QSliderPrivate class (see QSlider.cpp) + int pixelPosToRangeValue(int pos) const; + int pixelPosFromRangeValue(int val) const; - int pixelPosToRangeValue(int pos) const; - int pixelPosFromRangeValue(int val) const; + /// Draw the bottom and top sliders. + void drawMinimumSlider(QStylePainter *painter) const; + void drawMaximumSlider(QStylePainter *painter) const; - void drawMinimumSlider(QStylePainter* painter) const; - void drawMaximumSlider(QStylePainter* painter) const; + /// End points of the range on the Model + int m_minimumValue = 0; + int m_maximumValue = 100; - int m_minimumValue = 0; - int m_maximumValue = 100; + /// End points of the range on the GUI. This is synced with the model. + int m_minimumPosition = 0; + int m_maximumPosition = 100; - int m_minimumPosition = 0; - int m_maximumPosition = 100; + /// Controls selected ? + QStyle::SubControl m_minimumSliderSelected = QStyle::SC_None; + QStyle::SubControl m_maximumSliderSelected = QStyle::SC_None; - QStyle::SubControl m_minimumSliderSelected = QStyle::SC_None; - QStyle::SubControl m_maximumSliderSelected = QStyle::SC_None; + /// See QSliderPrivate::clickOffset. + /// Overrides this ivar + int m_subclassClickOffset = 0; - int m_subclassClickOffset = 0; + /// See QSliderPrivate::position + /// Overrides this ivar. + int m_subclassPosition = 0; - int m_subclassPosition = 0; + /// Original width between the 2 bounds before any moves + float m_subclassWidth = 0; - float m_subclassWidth = 0; + LtsRangeSliderPrivate::Handles m_selectedHandles = {}; - LtsRangeSliderPrivate::Handles m_selectedHandles = {}; + /// When symmetricMoves is true, moving a handle will move the other handle + /// symmetrically, otherwise the handles are independent. + bool m_symmetricMoves = false; - bool m_symmetricMoves = false; + QString m_handleToolTip; - QString m_handleToolTip; - - private: - Q_DISABLE_COPY(LtsRangeSliderPrivate) +private: + Q_DISABLE_COPY(LtsRangeSliderPrivate) }; -LtsRangeSliderPrivate::LtsRangeSliderPrivate(LtsRangeSlider& object) : q_ptr(&object) {} +// -------------------------------------------------------------------------- +LtsRangeSliderPrivate::LtsRangeSliderPrivate(LtsRangeSlider &object) + : q_ptr(&object) +{} +// -------------------------------------------------------------------------- void LtsRangeSliderPrivate::init() { - Q_Q(LtsRangeSlider); - m_minimumValue = q->minimum(); - m_maximumValue = q->maximum(); - m_minimumPosition = q->minimum(); - m_maximumPosition = q->maximum(); - q->connect(q, &LtsRangeSlider::rangeChanged, q, &LtsRangeSlider::onRangeChanged); + Q_Q(LtsRangeSlider); + m_minimumValue = q->minimum(); + m_maximumValue = q->maximum(); + m_minimumPosition = q->minimum(); + m_maximumPosition = q->maximum(); + q->connect(q, &LtsRangeSlider::rangeChanged, q, &LtsRangeSlider::onRangeChanged); } -LtsRangeSliderPrivate::Handle LtsRangeSliderPrivate::handleAtPos(const QPoint& pos, QRect& handleRect) const +// -------------------------------------------------------------------------- +LtsRangeSliderPrivate::Handle LtsRangeSliderPrivate::handleAtPos(const QPoint &pos, QRect &handleRect)const { - Q_Q(const LtsRangeSlider); + Q_Q(const LtsRangeSlider); - QStyleOptionSlider option; - q->initStyleOption(&option); + QStyleOptionSlider option; + q->initStyleOption(&option); - option.sliderPosition = m_minimumPosition; - option.sliderValue = m_minimumValue; + // The functinos hitTestComplexControl only know about 1 handle. As we have + // 2, we change the position of the handle and test if the pos correspond to + // any of the 2 positions. - QStyle::SubControl minimumControl = q->style()->hitTestComplexControl(QStyle::CC_Slider, &option, pos, q); - QRect minimumHandleRect = q->style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, q); + // Test the MinimumHandle + option.sliderPosition = m_minimumPosition; + option.sliderValue = m_minimumValue; - option.sliderPosition = m_maximumPosition; - option.sliderValue = m_maximumValue; + QStyle::SubControl minimumControl = q->style()->hitTestComplexControl( + QStyle::CC_Slider, &option, pos, q); + QRect minimumHandleRect = q->style()->subControlRect( + QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, q); - QStyle::SubControl maximumControl = q->style()->hitTestComplexControl(QStyle::CC_Slider, &option, pos, q); - QRect maximumHandleRect = q->style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, q); + // Test if the pos is under the Maximum handle + option.sliderPosition = m_maximumPosition; + option.sliderValue = m_maximumValue; - if (minimumControl == QStyle::SC_SliderHandle && maximumControl == QStyle::SC_SliderHandle) + QStyle::SubControl maximumControl = q->style()->hitTestComplexControl(QStyle::CC_Slider, &option, pos, q); + QRect maximumHandleRect = q->style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, q); + + // The pos is above both handles, select the closest handle + if (minimumControl == QStyle::SC_SliderHandle && + maximumControl == QStyle::SC_SliderHandle) + { + int minDist = 0; + int maxDist = 0; + if (q->orientation() == Qt::Horizontal) { - int minDist = 0; - int maxDist = 0; - if (q->orientation() == Qt::Horizontal) - { - minDist = pos.x() - minimumHandleRect.left(); - maxDist = maximumHandleRect.right() - pos.x(); - } - else - { - minDist = minimumHandleRect.bottom() - pos.y(); - maxDist = pos.y() - maximumHandleRect.top(); - } - Q_ASSERT(minDist >= 0 && maxDist >= 0); - minimumControl = minDist < maxDist ? minimumControl : QStyle::SC_None; + minDist = pos.x() - minimumHandleRect.left(); + maxDist = maximumHandleRect.right() - pos.x(); } - - if (maximumControl == QStyle::SC_SliderHandle) + else //if (q->orientation() == Qt::Vertical) { - handleRect = maximumHandleRect; - return MaximumHandle; - } - else if (minimumControl == QStyle::SC_SliderHandle) - { - handleRect = minimumHandleRect; - return MinimumHandle; + minDist = minimumHandleRect.bottom() - pos.y(); + maxDist = pos.y() - maximumHandleRect.top(); } + Q_ASSERT(minDist >= 0 && maxDist >= 0); + minimumControl = minDist < maxDist ? minimumControl : QStyle::SC_None; + } - handleRect = minimumHandleRect.united(maximumHandleRect); - return NoHandle; + if (maximumControl == QStyle::SC_SliderHandle) + { + handleRect = maximumHandleRect; + return MaximumHandle; + } + else if (minimumControl == QStyle::SC_SliderHandle) + { + handleRect = minimumHandleRect; + return MinimumHandle; + } + + handleRect = minimumHandleRect.united(maximumHandleRect); + return NoHandle; } +// -------------------------------------------------------------------------- +// Copied verbatim from QSliderPrivate::pixelPosToRangeValue. See QSlider.cpp +// int LtsRangeSliderPrivate::pixelPosToRangeValue(int pos) const { - Q_Q(const LtsRangeSlider); - QStyleOptionSlider option; - q->initStyleOption(&option); + Q_Q(const LtsRangeSlider); + QStyleOptionSlider option; + q->initStyleOption(&option); - QRect gr = q->style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderGroove, q); - QRect sr = q->style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, q); - int sliderMin, sliderMax, sliderLength; - if (option.orientation == Qt::Horizontal) - { - sliderLength = sr.width(); - sliderMin = gr.x(); - sliderMax = gr.right() - sliderLength + 1; - } - else - { - sliderLength = sr.height(); - sliderMin = gr.y(); - sliderMax = gr.bottom() - sliderLength + 1; - } + QRect gr = q->style()->subControlRect(QStyle::CC_Slider, + &option, + QStyle::SC_SliderGroove, + q); + QRect sr = q->style()->subControlRect(QStyle::CC_Slider, + &option, + QStyle::SC_SliderHandle, + q); + int sliderMin, sliderMax, sliderLength; + if (option.orientation == Qt::Horizontal) + { + sliderLength = sr.width(); + sliderMin = gr.x(); + sliderMax = gr.right() - sliderLength + 1; + } + else + { + sliderLength = sr.height(); + sliderMin = gr.y(); + sliderMax = gr.bottom() - sliderLength + 1; + } - return QStyle::sliderValueFromPosition(q->minimum(), q->maximum(), pos - sliderMin, sliderMax - sliderMin, - option.upsideDown); + return QStyle::sliderValueFromPosition(q->minimum(), + q->maximum(), + pos - sliderMin, + sliderMax - sliderMin, + option.upsideDown); } +//--------------------------------------------------------------------------- int LtsRangeSliderPrivate::pixelPosFromRangeValue(int val) const { - Q_Q(const LtsRangeSlider); - QStyleOptionSlider option; - q->initStyleOption(&option); + Q_Q(const LtsRangeSlider); + QStyleOptionSlider option; + q->initStyleOption(&option); - QRect gr = q->style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderGroove, q); - QRect sr = q->style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, q); - int sliderMin, sliderMax, sliderLength; - if (option.orientation == Qt::Horizontal) - { - sliderLength = sr.width(); - sliderMin = gr.x(); - sliderMax = gr.right() - sliderLength + 1; - } - else - { - sliderLength = sr.height(); - sliderMin = gr.y(); - sliderMax = gr.bottom() - sliderLength + 1; - } + QRect gr = q->style()->subControlRect(QStyle::CC_Slider, + &option, + QStyle::SC_SliderGroove, + q); + QRect sr = q->style()->subControlRect(QStyle::CC_Slider, + &option, + QStyle::SC_SliderHandle, + q); + int sliderMin, sliderMax, sliderLength; + if (option.orientation == Qt::Horizontal) + { + sliderLength = sr.width(); + sliderMin = gr.x(); + sliderMax = gr.right() - sliderLength + 1; + } + else + { + sliderLength = sr.height(); + sliderMin = gr.y(); + sliderMax = gr.bottom() - sliderLength + 1; + } - return QStyle::sliderPositionFromValue(q->minimum(), q->maximum(), val, sliderMax - sliderMin, option.upsideDown) + - sliderMin; + return QStyle::sliderPositionFromValue(q->minimum(), + q->maximum(), + val, + sliderMax - sliderMin, + option.upsideDown) + sliderMin; } -void LtsRangeSliderPrivate::drawMinimumSlider(QStylePainter* painter) const +//--------------------------------------------------------------------------- +// Draw slider at the bottom end of the range +void LtsRangeSliderPrivate::drawMinimumSlider(QStylePainter *painter) const { - Q_Q(const LtsRangeSlider); - QStyleOptionSlider option; - q->initMinimumSliderStyleOption(&option); + Q_Q(const LtsRangeSlider); + QStyleOptionSlider option; + q->initMinimumSliderStyleOption(&option); - option.subControls = QStyle::SC_SliderHandle; - option.sliderValue = m_minimumValue; - option.sliderPosition = m_minimumPosition; - if (q->isMinimumSliderDown()) - { - option.activeSubControls = QStyle::SC_SliderHandle; - option.state |= QStyle::State_Sunken; - } + option.subControls = QStyle::SC_SliderHandle; + option.sliderValue = m_minimumValue; + option.sliderPosition = m_minimumPosition; + if (q->isMinimumSliderDown()) + { + option.activeSubControls = QStyle::SC_SliderHandle; + option.state |= QStyle::State_Sunken; + } #ifdef Q_OS_MAC - - QRect clip = q->style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, q); - painter->setClipRect(clip); + // On mac style, drawing just the handle actually draws also the groove. + QRect clip = q->style()->subControlRect(QStyle::CC_Slider, &option, + QStyle::SC_SliderHandle, q); + painter->setClipRect(clip); #endif - painter->drawComplexControl(QStyle::CC_Slider, option); + painter->drawComplexControl(QStyle::CC_Slider, option); } -void LtsRangeSliderPrivate::drawMaximumSlider(QStylePainter* painter) const +//--------------------------------------------------------------------------- +// Draw slider at the top end of the range +void LtsRangeSliderPrivate::drawMaximumSlider(QStylePainter *painter) const { - Q_Q(const LtsRangeSlider); - QStyleOptionSlider option; - q->initMaximumSliderStyleOption(&option); + Q_Q(const LtsRangeSlider); + QStyleOptionSlider option; + q->initMaximumSliderStyleOption(&option); - option.subControls = QStyle::SC_SliderHandle; - option.sliderValue = m_maximumValue; - option.sliderPosition = m_maximumPosition; - if (q->isMaximumSliderDown()) - { - option.activeSubControls = QStyle::SC_SliderHandle; - option.state |= QStyle::State_Sunken; - } + option.subControls = QStyle::SC_SliderHandle; + option.sliderValue = m_maximumValue; + option.sliderPosition = m_maximumPosition; + if (q->isMaximumSliderDown()) + { + option.activeSubControls = QStyle::SC_SliderHandle; + option.state |= QStyle::State_Sunken; + } #ifdef Q_OS_MAC - - QRect clip = q->style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, q); - painter->setClipRect(clip); + // On mac style, drawing just the handle actually draws also the groove. + QRect clip = q->style()->subControlRect(QStyle::CC_Slider, &option, + QStyle::SC_SliderHandle, q); + painter->setClipRect(clip); #endif - painter->drawComplexControl(QStyle::CC_Slider, option); + painter->drawComplexControl(QStyle::CC_Slider, option); } -LtsRangeSlider::LtsRangeSlider(Qt::Orientation o, QWidget* parent) - : QSlider(o, parent), d_ptr(new LtsRangeSliderPrivate(*this)) +// -------------------------------------------------------------------------- +LtsRangeSlider::LtsRangeSlider(Qt::Orientation o, + QWidget *parent) + : QSlider(o, parent) + , d_ptr(new LtsRangeSliderPrivate(*this)) { - Q_D(LtsRangeSlider); - d->init(); + Q_D(LtsRangeSlider); + d->init(); } -LtsRangeSlider::LtsRangeSlider(LtsRangeSliderPrivate* impl, Qt::Orientation o, QWidget* parent) - : QSlider(o, parent), d_ptr(impl) +// -------------------------------------------------------------------------- +LtsRangeSlider::LtsRangeSlider(LtsRangeSliderPrivate *impl, Qt::Orientation o, + QWidget *parent) + : QSlider(o, parent) + , d_ptr(impl) { - Q_D(LtsRangeSlider); - d->init(); + Q_D(LtsRangeSlider); + d->init(); } -LtsRangeSlider::~LtsRangeSlider() {} +// -------------------------------------------------------------------------- +LtsRangeSlider::~LtsRangeSlider() +{ +} +// -------------------------------------------------------------------------- int LtsRangeSlider::minimumValue() const { - Q_D(const LtsRangeSlider); - return d->m_minimumValue; + Q_D(const LtsRangeSlider); + return d->m_minimumValue; } +// -------------------------------------------------------------------------- void LtsRangeSlider::setMinimumValue(int min) { - Q_D(LtsRangeSlider); - setValues(min, qMax(d->m_maximumValue, min)); + Q_D(LtsRangeSlider); + setValues(min, qMax(d->m_maximumValue, min)); } +// -------------------------------------------------------------------------- int LtsRangeSlider::maximumValue() const { - Q_D(const LtsRangeSlider); - return d->m_maximumValue; + Q_D(const LtsRangeSlider); + return d->m_maximumValue; } +// -------------------------------------------------------------------------- void LtsRangeSlider::setMaximumValue(int max) { - Q_D(LtsRangeSlider); - setValues(qMin(d->m_minimumValue, max), max); + Q_D(LtsRangeSlider); + setValues(qMin(d->m_minimumValue, max), max); } +// -------------------------------------------------------------------------- void LtsRangeSlider::setValues(int min, int max) { - Q_D(LtsRangeSlider); - const int minValue = qBound(minimum(), qMin(min, max), maximum()); - const int maxValue = qBound(minimum(), qMax(min, max), maximum()); - bool emitMinValChanged = (minValue != d->m_minimumValue); - bool emitMaxValChanged = (maxValue != d->m_maximumValue); + Q_D(LtsRangeSlider); + const int minValue = qBound(minimum(), qMin(min, max), maximum()); + const int maxValue = qBound(minimum(), qMax(min, max), maximum()); + bool emitMinValChanged = (minValue != d->m_minimumValue); + bool emitMaxValChanged = (maxValue != d->m_maximumValue); - d->m_minimumValue = minValue; - d->m_maximumValue = maxValue; + d->m_minimumValue = minValue; + d->m_maximumValue = maxValue; - bool emitMinPosChanged = (minValue != d->m_minimumPosition); - bool emitMaxPosChanged = (maxValue != d->m_maximumPosition); - d->m_minimumPosition = minValue; - d->m_maximumPosition = maxValue; + bool emitMinPosChanged = (minValue != d->m_minimumPosition); + bool emitMaxPosChanged = (maxValue != d->m_maximumPosition); + d->m_minimumPosition = minValue; + d->m_maximumPosition = maxValue; - if (isSliderDown()) - { - if (emitMinPosChanged || emitMaxPosChanged) - emit positionsChanged(d->m_minimumPosition, d->m_maximumPosition); - if (emitMinPosChanged) - emit minimumPositionChanged(d->m_minimumPosition); - if (emitMaxPosChanged) - emit maximumPositionChanged(d->m_maximumPosition); - } - if (emitMinValChanged || emitMaxValChanged) - emit valuesChanged(d->m_minimumValue, d->m_maximumValue); + if (isSliderDown()) + { + if (emitMinPosChanged || emitMaxPosChanged) + emit positionsChanged(d->m_minimumPosition, d->m_maximumPosition); + if (emitMinPosChanged) + emit minimumPositionChanged(d->m_minimumPosition); + if (emitMaxPosChanged) + emit maximumPositionChanged(d->m_maximumPosition); + } + if (emitMinValChanged || emitMaxValChanged) + emit valuesChanged(d->m_minimumValue, d->m_maximumValue); - if (emitMinValChanged) - emit minimumValueChanged(d->m_minimumValue); + if (emitMinValChanged) + emit minimumValueChanged(d->m_minimumValue); - if (emitMaxValChanged) - emit maximumValueChanged(d->m_maximumValue); - - if (emitMinPosChanged || emitMaxPosChanged || emitMinValChanged || emitMaxValChanged) - update(); -} - -int LtsRangeSlider::minimumPosition() const -{ - Q_D(const LtsRangeSlider); - return d->m_minimumPosition; -} - -int LtsRangeSlider::maximumPosition() const -{ - Q_D(const LtsRangeSlider); - return d->m_maximumPosition; -} - -void LtsRangeSlider::setMinimumPosition(int min) -{ - Q_D(const LtsRangeSlider); - setPositions(min, qMax(min, d->m_maximumPosition)); -} - -void LtsRangeSlider::setMaximumPosition(int max) -{ - Q_D(const LtsRangeSlider); - setPositions(qMin(d->m_minimumPosition, max), max); -} - -void LtsRangeSlider::setPositions(int min, int max) -{ - Q_D(LtsRangeSlider); - const int minPosition = qBound(minimum(), qMin(min, max), maximum()); - const int maxPosition = qBound(minimum(), qMax(min, max), maximum()); - - bool emitMinPosChanged = (minPosition != d->m_minimumPosition); - bool emitMaxPosChanged = (maxPosition != d->m_maximumPosition); - - if (!emitMinPosChanged && !emitMaxPosChanged) - return; - - d->m_minimumPosition = minPosition; - d->m_maximumPosition = maxPosition; - - if (!hasTracking()) - update(); - - if (isSliderDown()) - { - if (emitMinPosChanged) - emit minimumPositionChanged(d->m_minimumPosition); - if (emitMaxPosChanged) - emit maximumPositionChanged(d->m_maximumPosition); - if (emitMinPosChanged || emitMaxPosChanged) - emit positionsChanged(d->m_minimumPosition, d->m_maximumPosition); - } - if (hasTracking()) - { - triggerAction(SliderMove); - setValues(d->m_minimumPosition, d->m_maximumPosition); - } -} - -void LtsRangeSlider::setSymmetricMoves(bool symmetry) -{ - Q_D(LtsRangeSlider); - d->m_symmetricMoves = symmetry; -} - -bool LtsRangeSlider::symmetricMoves() const -{ - Q_D(const LtsRangeSlider); - return d->m_symmetricMoves; -} - -void LtsRangeSlider::onRangeChanged(int minimum, int maximum) -{ - Q_UNUSED(minimum); - Q_UNUSED(maximum); - Q_D(LtsRangeSlider); - setValues(d->m_minimumValue, d->m_maximumValue); -} - -void LtsRangeSlider::paintEvent(QPaintEvent*) -{ - Q_D(LtsRangeSlider); - QStyleOptionSlider option; - initStyleOption(&option); - - QStylePainter painter(this); - - painter.setPen(Qt::lightGray); - if (option.orientation == Qt::Horizontal) - { - painter.drawLine(option.rect.left(), option.rect.top(), option.rect.left(), option.rect.bottom()); - painter.drawRect(option.rect.left(), option.rect.center().y() - 1, option.rect.right() - option.rect.left(), 3); - painter.drawLine(option.rect.right(), option.rect.top(), option.rect.right(), option.rect.bottom()); - } - else - { - painter.drawLine(option.rect.left(), option.rect.top(), option.rect.right(), option.rect.top()); - painter.drawRect(option.rect.center().x() - 1, option.rect.top(), 3, option.rect.top() - option.rect.bottom()); - painter.drawLine(option.rect.center().x(), option.rect.top(), option.rect.center().x(), option.rect.bottom()); - painter.drawLine(option.rect.left(), option.rect.bottom(), option.rect.right(), option.rect.bottom()); - } - - option.subControls = QStyle::SC_SliderGroove; - - option.sliderValue = minimum() - maximum(); - option.sliderPosition = minimum() - maximum(); - option.subControls &= ~QStyle::SC_SliderGroove; - painter.drawComplexControl(QStyle::CC_Slider, option); - option.subControls |= QStyle::SC_SliderGroove; - - option.sliderPosition = d->m_minimumPosition; - const QRect lr = style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, this); - - option.sliderPosition = d->m_maximumPosition; - const QRect ur = style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, this); - - QRect sr = style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderGroove, this); - QRect rangeBox; - if (option.orientation == Qt::Horizontal) - { - rangeBox = QRect(QPoint(qMin(lr.center().x(), ur.center().x()), sr.center().y() - 2), - QPoint(qMax(lr.center().x(), ur.center().x()), sr.center().y() + 1)); - } - else - { - rangeBox = QRect(QPoint(sr.center().x() - 2, qMin(lr.center().y(), ur.center().y())), - QPoint(sr.center().x() + 1, qMax(lr.center().y(), ur.center().y()))); - } - - QRect groove = style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderGroove, this); - groove.adjust(0, 0, -1, 0); - - QColor highlight = palette().color(QPalette::Normal, QPalette::Highlight); - QLinearGradient gradient; - if (option.orientation == Qt::Horizontal) - gradient = QLinearGradient(groove.center().x(), groove.top(), groove.center().x(), groove.bottom()); - else - gradient = QLinearGradient(groove.left(), groove.center().y(), groove.right(), groove.center().y()); - - gradient.setColorAt(0, highlight.darker(120)); - gradient.setColorAt(1, highlight.lighter(160)); - - painter.setPen(QPen(highlight.darker(150), 0)); - painter.setBrush(gradient); - painter.drawRect(rangeBox.intersected(groove)); - - if (isMinimumSliderDown()) - { - painter.setClipRect(ur); - d->drawMaximumSlider(&painter); - painter.setClipRect(lr); - d->drawMinimumSlider(&painter); - } - else - { - painter.setClipRect(lr); - d->drawMinimumSlider(&painter); - painter.setClipRect(ur); - d->drawMaximumSlider(&painter); - } -} - -void LtsRangeSlider::mousePressEvent(QMouseEvent* ev) -{ - Q_D(LtsRangeSlider); - if (minimum() == maximum() || (ev->buttons() ^ ev->button())) - { - ev->ignore(); - return; - } - int mepos = orientation() == Qt::Horizontal ? ev->pos().x() : ev->pos().y(); - - QStyleOptionSlider option; - initStyleOption(&option); - - QRect handleRect; - LtsRangeSliderPrivate::Handle handle_ = d->handleAtPos(ev->pos(), handleRect); - - if (handle_ != LtsRangeSliderPrivate::NoHandle) - { - if (ev->buttons() == Qt::RightButton) - { - d->m_subclassPosition = (d->m_minimumPosition + d->m_maximumPosition) / 2.; - d->m_subclassClickOffset = mepos - d->pixelPosFromRangeValue(d->m_subclassPosition); - d->m_subclassWidth = (d->m_maximumPosition - d->m_minimumPosition) / 2.; - - setSliderDown(true); - if (!isMinimumSliderDown() || !isMaximumSliderDown()) - { - d->m_selectedHandles = QFlags(LtsRangeSliderPrivate::MinimumHandle) | - QFlags(LtsRangeSliderPrivate::MaximumHandle); - QRect sr = style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderGroove, this); - update(handleRect.united(sr)); - } - ev->accept(); - return; - } - - d->m_subclassPosition = - (handle_ == LtsRangeSliderPrivate::MinimumHandle) ? d->m_minimumPosition : d->m_maximumPosition; - - d->m_subclassClickOffset = mepos - (orientation() == Qt::Horizontal ? handleRect.left() : handleRect.top()); - - setSliderDown(true); - - if (d->m_selectedHandles != handle_) - { - d->m_selectedHandles = handle_; - update(handleRect); - } - - ev->accept(); - return; - } - - QStyle::SubControl control = style()->hitTestComplexControl(QStyle::CC_Slider, &option, ev->pos(), this); - QRect sr = style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderGroove, this); - int minCenter = (orientation() == Qt::Horizontal ? handleRect.left() : handleRect.top()); - int maxCenter = (orientation() == Qt::Horizontal ? handleRect.right() : handleRect.bottom()); - if (control == QStyle::SC_SliderGroove && mepos > minCenter && mepos < maxCenter) - { - - d->m_subclassPosition = (d->m_minimumPosition + d->m_maximumPosition) / 2.; - d->m_subclassClickOffset = mepos - d->pixelPosFromRangeValue(d->m_subclassPosition); - d->m_subclassWidth = (d->m_maximumPosition - d->m_minimumPosition) / 2.; - - setSliderDown(true); - if (!isMinimumSliderDown() || !isMaximumSliderDown()) - { - d->m_selectedHandles = QFlags(LtsRangeSliderPrivate::MinimumHandle) | - QFlags(LtsRangeSliderPrivate::MaximumHandle); - update(handleRect.united(sr)); - } - ev->accept(); - return; - } - ev->ignore(); -} - -void LtsRangeSlider::mouseMoveEvent(QMouseEvent* ev) -{ - Q_D(LtsRangeSlider); - if (!d->m_selectedHandles) - { - ev->ignore(); - return; - } - int mepos = orientation() == Qt::Horizontal ? ev->pos().x() : ev->pos().y(); - - QStyleOptionSlider option; - initStyleOption(&option); - - if (isMinimumSliderDown() && isMaximumSliderDown()) - { - int newPosition = d->pixelPosToRangeValue(mepos); - int newMinPosition = newPosition - static_cast(d->m_subclassWidth); - int newMaxPosition = newPosition + static_cast(d->m_subclassWidth + .5); - - if (newMinPosition < minimum()) - { - newMinPosition = minimum(); - newMaxPosition = newMinPosition + (d->m_maximumPosition - d->m_minimumPosition); - } - else if (newMaxPosition > maximum()) - { - newMaxPosition = maximum(); - newMinPosition = newMaxPosition - (d->m_maximumPosition - d->m_minimumPosition); - } - setPositions(newMinPosition, newMaxPosition); - ev->accept(); - return; - } - - const int m = style()->pixelMetric(QStyle::PM_MaximumDragDistance, &option, this); - - int newPosition = d->pixelPosToRangeValue(mepos - d->m_subclassClickOffset); - - if (m >= 0) - { - const QRect r = rect().adjusted(-m, -m, m, m); - if (!r.contains(ev->pos())) - newPosition = d->m_subclassPosition; - } - - if (isMinimumSliderDown() && !isMaximumSliderDown()) - { - double newMinPos = qMin(newPosition, d->m_maximumPosition); - setPositions(newMinPos, d->m_maximumPosition + (d->m_symmetricMoves ? d->m_minimumPosition - newMinPos : 0)); - } - - else if (isMaximumSliderDown() && !isMinimumSliderDown()) - { - double newMaxPos = qMax(d->m_minimumPosition, newPosition); - setPositions(d->m_minimumPosition - (d->m_symmetricMoves ? newMaxPos - d->m_maximumPosition : 0), newMaxPos); - } - ev->accept(); -} - -void LtsRangeSlider::mouseReleaseEvent(QMouseEvent* ev) -{ - Q_D(LtsRangeSlider); - QSlider::mouseReleaseEvent(ev); - - setSliderDown(false); - d->m_selectedHandles = {}; + if (emitMaxValChanged) + emit maximumValueChanged(d->m_maximumValue); + if (emitMinPosChanged || emitMaxPosChanged || + emitMinValChanged || emitMaxValChanged) update(); } +// -------------------------------------------------------------------------- +int LtsRangeSlider::minimumPosition() const +{ + Q_D(const LtsRangeSlider); + return d->m_minimumPosition; +} + +// -------------------------------------------------------------------------- +int LtsRangeSlider::maximumPosition() const +{ + Q_D(const LtsRangeSlider); + return d->m_maximumPosition; +} + +// -------------------------------------------------------------------------- +void LtsRangeSlider::setMinimumPosition(int min) +{ + Q_D(const LtsRangeSlider); + setPositions(min, qMax(min, d->m_maximumPosition)); +} + +// -------------------------------------------------------------------------- +void LtsRangeSlider::setMaximumPosition(int max) +{ + Q_D(const LtsRangeSlider); + setPositions(qMin(d->m_minimumPosition, max), max); +} + +// -------------------------------------------------------------------------- +void LtsRangeSlider::setPositions(int min, int max) +{ + Q_D(LtsRangeSlider); + const int minPosition = qBound(minimum(), qMin(min, max), maximum()); + const int maxPosition = qBound(minimum(), qMax(min, max), maximum()); + + bool emitMinPosChanged = (minPosition != d->m_minimumPosition); + bool emitMaxPosChanged = (maxPosition != d->m_maximumPosition); + + if (!emitMinPosChanged && !emitMaxPosChanged) + return; + + d->m_minimumPosition = minPosition; + d->m_maximumPosition = maxPosition; + + if (!hasTracking()) + update(); + + if (isSliderDown()) + { + if (emitMinPosChanged) + emit minimumPositionChanged(d->m_minimumPosition); + if (emitMaxPosChanged) + emit maximumPositionChanged(d->m_maximumPosition); + if (emitMinPosChanged || emitMaxPosChanged) + emit positionsChanged(d->m_minimumPosition, d->m_maximumPosition); + } + if (hasTracking()) + { + triggerAction(SliderMove); + setValues(d->m_minimumPosition, d->m_maximumPosition); + } +} + +// -------------------------------------------------------------------------- +void LtsRangeSlider::setSymmetricMoves(bool symmetry) +{ + Q_D(LtsRangeSlider); + d->m_symmetricMoves = symmetry; +} + +// -------------------------------------------------------------------------- +bool LtsRangeSlider::symmetricMoves() const +{ + Q_D(const LtsRangeSlider); + return d->m_symmetricMoves; +} + +// -------------------------------------------------------------------------- +void LtsRangeSlider::onRangeChanged(int minimum, int maximum) +{ + Q_UNUSED(minimum); + Q_UNUSED(maximum); + Q_D(LtsRangeSlider); + setValues(d->m_minimumValue, d->m_maximumValue); +} + +// -------------------------------------------------------------------------- +// Render +void LtsRangeSlider::paintEvent(QPaintEvent *) +{ + Q_D(LtsRangeSlider); + QStyleOptionSlider option; + initStyleOption(&option); + + QStylePainter painter(this); + + // ------------------------------------------------------------------------- + // Render complete range + // + painter.setPen(Qt::lightGray); + if (option.orientation == Qt::Horizontal) + { + painter.drawLine(option.rect.left(), option.rect.top(), option.rect.left(), option.rect.bottom()); + painter.drawRect(option.rect.left(), option.rect.center().y() - 1, option.rect.right() - option.rect.left(), 3); + painter.drawLine(option.rect.right(), option.rect.top(), option.rect.right(), option.rect.bottom()); + } + else + { + painter.drawLine(option.rect.left(), option.rect.top(), option.rect.right(), option.rect.top()); + painter.drawRect(option.rect.center().x() - 1, option.rect.top(), 3, option.rect.top() - option.rect.bottom()); + painter.drawLine(option.rect.center().x(), option.rect.top(), option.rect.center().x(), option.rect.bottom()); + painter.drawLine(option.rect.left(), option.rect.bottom(), option.rect.right(), option.rect.bottom()); + } + // ------------------------------------------------------------------------- + + option.subControls = QStyle::SC_SliderGroove; + // Move to minimum to not highlight the SliderGroove. + // On mac style, drawing just the slider groove also draws the handles, + // therefore we give a negative (outside of view) position. + option.sliderValue = minimum() - maximum(); + option.sliderPosition = minimum() - maximum(); + option.subControls &= ~QStyle::SC_SliderGroove; + painter.drawComplexControl(QStyle::CC_Slider, option); + option.subControls |= QStyle::SC_SliderGroove; + + option.sliderPosition = d->m_minimumPosition; + const QRect lr = style()->subControlRect(QStyle::CC_Slider, + &option, + QStyle::SC_SliderHandle, + this); + + option.sliderPosition = d->m_maximumPosition; + const QRect ur = style()->subControlRect(QStyle::CC_Slider, + &option, + QStyle::SC_SliderHandle, + this); + + QRect sr = style()->subControlRect(QStyle::CC_Slider, + &option, + QStyle::SC_SliderGroove, + this); + QRect rangeBox; + if (option.orientation == Qt::Horizontal) + { + rangeBox = QRect(QPoint(qMin(lr.center().x(), ur.center().x()), sr.center().y() - 2), + QPoint(qMax(lr.center().x(), ur.center().x()), sr.center().y() + 1)); + } + else + { + rangeBox = QRect(QPoint(sr.center().x() - 2, qMin(lr.center().y(), ur.center().y())), + QPoint(sr.center().x() + 1, qMax(lr.center().y(), ur.center().y()))); + } + + // ----------------------------- + // Render the range + // + QRect groove = style()->subControlRect(QStyle::CC_Slider, + &option, + QStyle::SC_SliderGroove, + this); + groove.adjust(0, 0, -1, 0); + + // Create default colors based on the transfer function. + // + QColor highlight = palette().color(QPalette::Normal, QPalette::Highlight); + QLinearGradient gradient; + if (option.orientation == Qt::Horizontal) + gradient = QLinearGradient(groove.center().x(), groove.top(), groove.center().x(), groove.bottom()); + else + gradient = QLinearGradient(groove.left(), groove.center().y(), groove.right(), groove.center().y()); + + // TODO: Set this based on the supplied transfer function + //QColor l = Qt::darkGray; + //QColor u = Qt::black; + + gradient.setColorAt(0, highlight.darker(120)); + gradient.setColorAt(1, highlight.lighter(160)); + + painter.setPen(QPen(highlight.darker(150), 0)); + painter.setBrush(gradient); + painter.drawRect(rangeBox.intersected(groove)); + + // ----------------------------------- + // Render the sliders + // + if (isMinimumSliderDown()) + { + painter.setClipRect(ur); + d->drawMaximumSlider(&painter); + painter.setClipRect(lr); + d->drawMinimumSlider(&painter); + } + else + { + painter.setClipRect(lr); + d->drawMinimumSlider(&painter); + painter.setClipRect(ur); + d->drawMaximumSlider(&painter); + } +} + +// -------------------------------------------------------------------------- +// Standard Qt UI events +void LtsRangeSlider::mousePressEvent(QMouseEvent *ev) +{ + Q_D(LtsRangeSlider); + if (minimum() == maximum() || (ev->buttons() ^ ev->button())) + { + ev->ignore(); + return; + } + int mepos = orientation() == Qt::Horizontal ? ev->pos().x() : ev->pos().y(); + + QStyleOptionSlider option; + initStyleOption(&option); + + QRect handleRect; + LtsRangeSliderPrivate::Handle handle_ = d->handleAtPos(ev->pos(), handleRect); + + if (handle_ != LtsRangeSliderPrivate::NoHandle) + { + if (ev->buttons() == Qt::RightButton) + { + d->m_subclassPosition = (d->m_minimumPosition + d->m_maximumPosition) / 2.; + d->m_subclassClickOffset = mepos - d->pixelPosFromRangeValue(d->m_subclassPosition); + d->m_subclassWidth = (d->m_maximumPosition - d->m_minimumPosition) / 2.; + //qMax(d->m_subclassPosition - d->m_minimumPosition, d->m_maximumPosition - d->m_subclassPosition); + setSliderDown(true); + if (!isMinimumSliderDown() || !isMaximumSliderDown()) + { + d->m_selectedHandles = QFlags(LtsRangeSliderPrivate::MinimumHandle) | + QFlags(LtsRangeSliderPrivate::MaximumHandle); + QRect sr = style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderGroove, this); + update(handleRect.united(sr)); + } + ev->accept(); + return; + } + + d->m_subclassPosition = (handle_ == LtsRangeSliderPrivate::MinimumHandle) ? d->m_minimumPosition : d->m_maximumPosition; + + // save the position of the mouse inside the handle for later + d->m_subclassClickOffset = mepos - (orientation() == Qt::Horizontal ? handleRect.left() : handleRect.top()); + + setSliderDown(true); + + if (d->m_selectedHandles != handle_) + { + d->m_selectedHandles = handle_; + update(handleRect); + } + // Accept the mouseEvent + ev->accept(); + return; + } + + // if we are here, no handles have been pressed + // Check if we pressed on the groove between the 2 handles + + QStyle::SubControl control = style()->hitTestComplexControl(QStyle::CC_Slider, &option, ev->pos(), this); + QRect sr = style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderGroove, this); + int minCenter = (orientation() == Qt::Horizontal ? handleRect.left() : handleRect.top()); + int maxCenter = (orientation() == Qt::Horizontal ? handleRect.right() : handleRect.bottom()); + if (control == QStyle::SC_SliderGroove && mepos > minCenter && mepos < maxCenter) + { + // warning lost of precision it might be fatal + d->m_subclassPosition = (d->m_minimumPosition + d->m_maximumPosition) / 2.; + d->m_subclassClickOffset = mepos - d->pixelPosFromRangeValue(d->m_subclassPosition); + d->m_subclassWidth = (d->m_maximumPosition - d->m_minimumPosition) / 2.; + //qMax(d->m_subclassPosition - d->m_minimumPosition, d->m_maximumPosition - d->m_subclassPosition); + setSliderDown(true); + if (!isMinimumSliderDown() || !isMaximumSliderDown()) + { + d->m_selectedHandles = QFlags(LtsRangeSliderPrivate::MinimumHandle) | + QFlags(LtsRangeSliderPrivate::MaximumHandle); + update(handleRect.united(sr)); + } + ev->accept(); + return; + } + ev->ignore(); +} + +// -------------------------------------------------------------------------- +// Standard Qt UI events +void LtsRangeSlider::mouseMoveEvent(QMouseEvent *ev) +{ + Q_D(LtsRangeSlider); + if (!d->m_selectedHandles) + { + ev->ignore(); + return; + } + int mepos = orientation() == Qt::Horizontal ? ev->pos().x() : ev->pos().y(); + + QStyleOptionSlider option; + initStyleOption(&option); + + // Both handles are down (the user clicked in between the handles) + if (isMinimumSliderDown() && isMaximumSliderDown()) + { + int newPosition = d->pixelPosToRangeValue(mepos); + int newMinPosition = newPosition - static_cast(d->m_subclassWidth); + int newMaxPosition = newPosition + static_cast(d->m_subclassWidth + .5); + // prevent the range from becoming smaller + if (newMinPosition < minimum()) + { + newMinPosition = minimum(); + newMaxPosition = newMinPosition + (d->m_maximumPosition - d->m_minimumPosition); + } + else if (newMaxPosition > maximum()) + { + newMaxPosition = maximum(); + newMinPosition = newMaxPosition - (d->m_maximumPosition - d->m_minimumPosition); + } + setPositions(newMinPosition, newMaxPosition); + ev->accept(); + return; + } + + const int m = style()->pixelMetric(QStyle::PM_MaximumDragDistance, &option, this); + + int newPosition = d->pixelPosToRangeValue(mepos - d->m_subclassClickOffset); + + if (m >= 0) + { + const QRect r = rect().adjusted(-m, -m, m, m); + if (!r.contains(ev->pos())) + newPosition = d->m_subclassPosition; + } + + // Only the lower/left slider is down + if (isMinimumSliderDown() && !isMaximumSliderDown()) + { + double newMinPos = qMin(newPosition, d->m_maximumPosition); + setPositions(newMinPos, d->m_maximumPosition + (d->m_symmetricMoves ? d->m_minimumPosition - newMinPos : 0)); + } + // Only the upper/right slider is down + else if (isMaximumSliderDown() && !isMinimumSliderDown()) + { + double newMaxPos = qMax(d->m_minimumPosition, newPosition); + setPositions(d->m_minimumPosition - (d->m_symmetricMoves ? newMaxPos - d->m_maximumPosition : 0), newMaxPos); + } + ev->accept(); +} + +// -------------------------------------------------------------------------- +// Standard Qt UI mouseEvents +void LtsRangeSlider::mouseReleaseEvent(QMouseEvent *ev) +{ + Q_D(LtsRangeSlider); + QSlider::mouseReleaseEvent(ev); + + setSliderDown(false); + d->m_selectedHandles = {}; + + update(); +} + +// -------------------------------------------------------------------------- bool LtsRangeSlider::isMinimumSliderDown() const { - Q_D(const LtsRangeSlider); - return d->m_selectedHandles & LtsRangeSliderPrivate::MinimumHandle; + Q_D(const LtsRangeSlider); + return d->m_selectedHandles & LtsRangeSliderPrivate::MinimumHandle; } +// -------------------------------------------------------------------------- bool LtsRangeSlider::isMaximumSliderDown() const { - Q_D(const LtsRangeSlider); - return d->m_selectedHandles & LtsRangeSliderPrivate::MaximumHandle; + Q_D(const LtsRangeSlider); + return d->m_selectedHandles & LtsRangeSliderPrivate::MaximumHandle; } -void LtsRangeSlider::initMinimumSliderStyleOption(QStyleOptionSlider* option) const +// -------------------------------------------------------------------------- +void LtsRangeSlider::initMinimumSliderStyleOption(QStyleOptionSlider *option) const { - initStyleOption(option); + initStyleOption(option); } -void LtsRangeSlider::initMaximumSliderStyleOption(QStyleOptionSlider* option) const +// -------------------------------------------------------------------------- +void LtsRangeSlider::initMaximumSliderStyleOption(QStyleOptionSlider *option) const { - initStyleOption(option); + initStyleOption(option); } -QString LtsRangeSlider::handleToolTip() const +// -------------------------------------------------------------------------- +QString LtsRangeSlider::handleToolTip()const { - Q_D(const LtsRangeSlider); - return d->m_handleToolTip; + Q_D(const LtsRangeSlider); + return d->m_handleToolTip; } -void LtsRangeSlider::setHandleToolTip(const QString& toolTip) +// -------------------------------------------------------------------------- +void LtsRangeSlider::setHandleToolTip(const QString &toolTip) { - Q_D(LtsRangeSlider); - d->m_handleToolTip = toolTip; + Q_D(LtsRangeSlider); + d->m_handleToolTip = toolTip; } -bool LtsRangeSlider::event(QEvent* event) +// -------------------------------------------------------------------------- +bool LtsRangeSlider::event(QEvent *event) { - Q_D(LtsRangeSlider); - switch (event->type()) + Q_D(LtsRangeSlider); + switch (event->type()) + { + case QEvent::ToolTip: + { + QHelpEvent *helpEvent = static_cast(event); + QStyleOptionSlider opt; + // Test the MinimumHandle + opt.sliderPosition = d->m_minimumPosition; + opt.sliderValue = d->m_minimumValue; + initStyleOption(&opt); + QStyle::SubControl hoveredControl = style()->hitTestComplexControl(QStyle::CC_Slider, &opt, helpEvent->pos(), this); + if (!d->m_handleToolTip.isEmpty() && hoveredControl == QStyle::SC_SliderHandle) { - case QEvent::ToolTip: { - QHelpEvent* helpEvent = static_cast(event); - QStyleOptionSlider opt; - - opt.sliderPosition = d->m_minimumPosition; - opt.sliderValue = d->m_minimumValue; - initStyleOption(&opt); - QStyle::SubControl hoveredControl = - style()->hitTestComplexControl(QStyle::CC_Slider, &opt, helpEvent->pos(), this); - if (!d->m_handleToolTip.isEmpty() && hoveredControl == QStyle::SC_SliderHandle) - { - QToolTip::showText(helpEvent->globalPos(), d->m_handleToolTip.arg(minimumValue())); - event->accept(); - return true; - } - - opt.sliderPosition = d->m_maximumPosition; - opt.sliderValue = d->m_maximumValue; - initStyleOption(&opt); - hoveredControl = style()->hitTestComplexControl(QStyle::CC_Slider, &opt, helpEvent->pos(), this); - if (!d->m_handleToolTip.isEmpty() && hoveredControl == QStyle::SC_SliderHandle) - { - QToolTip::showText(helpEvent->globalPos(), d->m_handleToolTip.arg(maximumValue())); - event->accept(); - return true; - } - } - default: - break; + QToolTip::showText(helpEvent->globalPos(), d->m_handleToolTip.arg(minimumValue())); + event->accept(); + return true; } - return QSlider::event(event); + // Test the MaximumHandle + opt.sliderPosition = d->m_maximumPosition; + opt.sliderValue = d->m_maximumValue; + initStyleOption(&opt); + hoveredControl = style()->hitTestComplexControl(QStyle::CC_Slider, &opt, helpEvent->pos(), this); + if (!d->m_handleToolTip.isEmpty() && hoveredControl == QStyle::SC_SliderHandle) + { + QToolTip::showText(helpEvent->globalPos(), d->m_handleToolTip.arg(maximumValue())); + event->accept(); + return true; + } + } + default: + break; + } + return QSlider::event(event); } -} // namespace LtsWidgets +} // namespace diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_range_slider.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_range_slider.h index c2f55b62a..9827d481b 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_range_slider.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_range_slider.h @@ -1,9 +1,38 @@ +/** + * @RDE_HEADER@ + * A slider that has a minimum and a maximum value, thus can define a range within a range. + * That could be a a snippet out of a video, a time range within an exercise... + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Malte Diers, NLE, 2020-01-06 + */ +/*========================================================================= + Library: CTK + + Copyright (c) Kitware Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0.txt + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=========================================================================*/ #pragma once + #include "lts_widgets_export.h" -#include +// Qt includes #include namespace LtsWidgets @@ -11,90 +40,180 @@ namespace LtsWidgets class LtsRangeSliderPrivate; +/// \ingroup Widgets +/// +/// A ctkRangeSlider is a slider that lets you input 2 values instead of one +/// (see QSlider). These values are typically a lower and upper bound. +/// Values are comprised between the range of the slider. See setRange(), +/// minimum() and maximum(). The upper bound can't be smaller than the +/// lower bound and vice-versa. +/// When setting new values (setMinimumValue(), setMaximumValue() or +/// setValues()), make sure they lie between the range (minimum(), maximum()) +/// of the slider, they would be forced otherwised. If it is not the behavior +/// you desire, you can set the range first (setRange(), setMinimum(), +/// setMaximum()) +/// TODO: support triggerAction(QAbstractSlider::SliderSingleStepSub) that +/// moves both values at a time. +/// \sa ctkDoubleRangeSlider, ctkDoubleSlider, ctkRangeWidget class LTSWIDGETS_EXPORT LtsRangeSlider : public QSlider { - Q_OBJECT + Q_OBJECT - Q_PROPERTY(int minimumValue READ minimumValue WRITE setMinimumValue) - Q_PROPERTY(int maximumValue READ maximumValue WRITE setMaximumValue) - Q_PROPERTY(int minimumPosition READ minimumPosition WRITE setMinimumPosition) - Q_PROPERTY(int maximumPosition READ maximumPosition WRITE setMaximumPosition) - Q_PROPERTY(bool symmetricMoves READ symmetricMoves WRITE setSymmetricMoves) - Q_PROPERTY(QString handleToolTip READ handleToolTip WRITE setHandleToolTip) + Q_PROPERTY(int minimumValue READ minimumValue WRITE setMinimumValue) + Q_PROPERTY(int maximumValue READ maximumValue WRITE setMaximumValue) + Q_PROPERTY(int minimumPosition READ minimumPosition WRITE setMinimumPosition) + Q_PROPERTY(int maximumPosition READ maximumPosition WRITE setMaximumPosition) + Q_PROPERTY(bool symmetricMoves READ symmetricMoves WRITE setSymmetricMoves) + Q_PROPERTY(QString handleToolTip READ handleToolTip WRITE setHandleToolTip) - public: - explicit LtsRangeSlider(Qt::Orientation o, QWidget* parent = nullptr); +public: + /// Constructor, builds a ctkRangeSlider that ranges from 0 to 100 and has + /// a lower and upper values of 0 and 100 respectively, other properties + /// are set the QSlider default properties. + explicit LtsRangeSlider(Qt::Orientation o, QWidget *parent = nullptr); + explicit LtsRangeSlider(QWidget *parent = nullptr) + : LtsRangeSlider(Qt::Vertical, parent) + {} + ~LtsRangeSlider(); - explicit LtsRangeSlider(QWidget* parent = nullptr) : LtsRangeSlider(Qt::Vertical, parent) {} + /// + /// This property holds the slider's current minimum value. + /// The slider silently forces minimumValue to be within the legal range: + /// minimum() <= minimumValue() <= maximumValue() <= maximum(). + /// Changing the minimumValue also changes the minimumPosition. + int minimumValue() const; - ~LtsRangeSlider(); + /// + /// This property holds the slider's current maximum value. + /// The slider forces the maximum value to be within the legal range: + /// The slider silently forces maximumValue to be within the legal range: + /// Changing the maximumValue also changes the maximumPosition. + int maximumValue() const; - int minimumValue() const; + /// + /// This property holds the current slider minimum position. + /// If tracking is enabled (the default), this is identical to minimumValue. + int minimumPosition() const; + void setMinimumPosition(int min); - int maximumValue() const; + /// + /// This property holds the current slider maximum position. + /// If tracking is enabled (the default), this is identical to maximumValue. + int maximumPosition() const; + void setMaximumPosition(int max); - int minimumPosition() const; - void setMinimumPosition(int min); + /// + /// Utility function that set the minimum position and + /// maximum position at once. + void setPositions(int min, int max); - int maximumPosition() const; - void setMaximumPosition(int max); + /// + /// When symmetricMoves is true, moving a handle will move the other handle + /// symmetrically, otherwise the handles are independent. False by default + bool symmetricMoves() const; + void setSymmetricMoves(bool symmetry); - void setPositions(int min, int max); + /// + /// Controls the text to display for the handle tooltip. It is in addition + /// to the widget tooltip. + /// "%1" is replaced by the current value of the slider. + /// Empty string (by default) means no tooltip. + QString handleToolTip() const; + void setHandleToolTip(const QString &toolTip); - bool symmetricMoves() const; - void setSymmetricMoves(bool symmetry); + /// Returns true if the minimum value handle is down, false if it is up. + /// \sa isMaximumSliderDown() + bool isMinimumSliderDown() const; + /// Returns true if the maximum value handle is down, false if it is up. + /// \sa isMinimumSliderDown() + bool isMaximumSliderDown() const; - QString handleToolTip() const; - void setHandleToolTip(const QString& toolTip); +Q_SIGNALS: + /// + /// This signal is emitted when the slider minimum value has changed, + /// with the new slider value as argument. + void minimumValueChanged(int min); + /// + /// This signal is emitted when the slider maximum value has changed, + /// with the new slider value as argument. + void maximumValueChanged(int max); + /// + /// Utility signal that is fired when minimum or maximum values have changed. + void valuesChanged(int min, int max); - bool isMinimumSliderDown() const; + /// + /// This signal is emitted when sliderDown is true and the slider moves. + /// This usually happens when the user is dragging the minimum slider. + /// The value is the new slider minimum position. + /// This signal is emitted even when tracking is turned off. + void minimumPositionChanged(int min); - bool isMaximumSliderDown() const; + /// + /// This signal is emitted when sliderDown is true and the slider moves. + /// This usually happens when the user is dragging the maximum slider. + /// The value is the new slider maximum position. + /// This signal is emitted even when tracking is turned off. + void maximumPositionChanged(int max); - Q_SIGNALS: + /// + /// Utility signal that is fired when minimum or maximum positions + /// have changed. + void positionsChanged(int min, int max); - void minimumValueChanged(int min); +public Q_SLOTS: + /// + /// This property holds the slider's current minimum value. + /// The slider silently forces min to be within the legal range: + /// minimum() <= min <= maximumValue() <= maximum(). + /// Note: Changing the minimumValue also changes the minimumPosition. + /// \sa stMaximumValue, setValues, setMinimum, setMaximum, setRange + void setMinimumValue(int min); - void maximumValueChanged(int max); + /// + /// This property holds the slider's current maximum value. + /// The slider silently forces max to be within the legal range: + /// minimum() <= minimumValue() <= max <= maximum(). + /// Note: Changing the maximumValue also changes the maximumPosition. + /// \sa stMinimumValue, setValues, setMinimum, setMaximum, setRange + void setMaximumValue(int max); - void valuesChanged(int min, int max); + /// + /// Utility function that set the minimum value and maximum value at once. + /// The slider silently forces min and max to be within the legal range: + /// minimum() <= min <= max <= maximum(). + /// Note: Changing the minimumValue and maximumValue also changes the + /// minimumPosition and maximumPosition. + /// \sa setMinimumValue, setMaximumValue, setMinimum, setMaximum, setRange + void setValues(int min, int max); - void minimumPositionChanged(int min); +protected Q_SLOTS: + void onRangeChanged(int minimum, int maximum); - void maximumPositionChanged(int max); +protected: + LtsRangeSlider(LtsRangeSliderPrivate *impl, Qt::Orientation o, QWidget *parent = nullptr); - void positionsChanged(int min, int max); + // Description: + // Standard Qt UI events + void mousePressEvent(QMouseEvent *ev) override; + void mouseMoveEvent(QMouseEvent *ev) override; + void mouseReleaseEvent(QMouseEvent *ev) override; - public Q_SLOTS: + // Description: + // Rendering is done here. + void paintEvent(QPaintEvent *ev) override; + void initMinimumSliderStyleOption(QStyleOptionSlider *option) const; + void initMaximumSliderStyleOption(QStyleOptionSlider *option) const; - void setMinimumValue(int min); + // Description: + // Reimplemented for the tooltips + bool event(QEvent *event) override; - void setMaximumValue(int max); +protected: + QScopedPointer d_ptr; - void setValues(int min, int max); - - protected Q_SLOTS: - void onRangeChanged(int minimum, int maximum); - - protected: - LtsRangeSlider(LtsRangeSliderPrivate* impl, Qt::Orientation o, QWidget* parent = nullptr); - - void mousePressEvent(QMouseEvent* ev) override; - void mouseMoveEvent(QMouseEvent* ev) override; - void mouseReleaseEvent(QMouseEvent* ev) override; - - void paintEvent(QPaintEvent* ev) override; - void initMinimumSliderStyleOption(QStyleOptionSlider* option) const; - void initMaximumSliderStyleOption(QStyleOptionSlider* option) const; - - bool event(QEvent* event) override; - - protected: - QScopedPointer d_ptr; - - private: - Q_DECLARE_PRIVATE(LtsRangeSlider) - Q_DISABLE_COPY(LtsRangeSlider) +private: + Q_DECLARE_PRIVATE(LtsRangeSlider) + Q_DISABLE_COPY(LtsRangeSlider) }; -} // namespace LtsWidgets +} // namespace diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_selection_popup.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_selection_popup.cpp index ef995f16a..82bcbd281 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_selection_popup.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_selection_popup.cpp @@ -1,178 +1,217 @@ - +/** + * @RDE_HEADER@ + * ComboBox's popup, optimized for tablets (bigger dropdown/popup) + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Mike Wille, SLSE, 2016-03-09 + */ #include "lts_selection_popup.h" - -#include "lts_base.h" #include "ui_lts_selection_popup.h" +#include "lts_base.h" +#include #include #include #include -#include +//#define NEVER #ifdef NEVER -#include -#endif +# include +#endif // NEVER + namespace LtsWidgets { class RadioButton : public QRadioButton { - Q_OBJECT + Q_OBJECT - public: - explicit RadioButton(int row, const QString& text) : QRadioButton(text), m_row(row) {} +public: + explicit RadioButton(int row, const QString &text) + : QRadioButton(text) + , m_row(row) + {} - int row() const - { - return m_row; - } + int row() const { return m_row; } - signals: - void doubleClickEvent(); +signals: + void doubleClickEvent(); - private: - int m_row; +private: + int m_row; - void mouseDoubleClickEvent(QMouseEvent*) override - { - emit doubleClickEvent(); - } + void mouseDoubleClickEvent(QMouseEvent *) override + { + emit doubleClickEvent(); + } }; -LtsSelectionPopup::LtsSelectionPopup(QAbstractItemModel* model, int currentIndex, QWidget* parent) - : LtsFramelessDialog(parent, Behaviour::Popup), m_ui(new Ui::LtsSelectionPopup), m_currentIndex(currentIndex), - m_firstIndex(currentIndex), m_filter(new QSortFilterProxyModel(this)), m_valid(false) + + +LtsSelectionPopup::LtsSelectionPopup(QAbstractItemModel* model, + int currentIndex, + QWidget *parent) + : LtsFramelessDialog(parent, Behaviour::Popup) + , m_ui(new Ui::LtsSelectionPopup) // TODO: morph .ui to QDialog (is QWidget) + , m_currentIndex(currentIndex) + , m_firstIndex(currentIndex) + , m_filter(new QSortFilterProxyModel(this)) + , m_valid(false) { - m_ui->setupUi(this); + m_ui->setupUi(this); // i am sorry for this solution, but qlistview's are so unthankfully to work with - m_filter->setSourceModel(model); - m_filter->setFilterCaseSensitivity(Qt::CaseInsensitive); + m_filter->setSourceModel(model); + m_filter->setFilterCaseSensitivity(Qt::CaseInsensitive); - slotFilterChanged(); -#ifdef TABLET_MODE + slotFilterChanged(); + #ifdef TABLET_MODE m_ui->leSearch->setVisible(false); m_ui->label->setVisible(false); -#endif - connect(m_ui->pbCancel, &QPushButton::clicked, this, &LtsSelectionPopup::reject); - connect(m_ui->pbSelect, &QPushButton::clicked, this, &LtsSelectionPopup::accept); - connect(m_ui->leSearch, &QLineEdit::textEdited, this, &LtsSelectionPopup::slotFilterChanged); + #endif + connect(m_ui->pbCancel, &QPushButton::clicked, this, &LtsSelectionPopup::reject); + connect(m_ui->pbSelect, &QPushButton::clicked, this, &LtsSelectionPopup::accept); + connect(m_ui->leSearch, &QLineEdit::textEdited, + this, &LtsSelectionPopup::slotFilterChanged); -#ifdef NEVER + #ifdef NEVER + // debugging : +// // highlighted -> UserInteraction +// connect(this, static_cast(&LtsSelectionPopup::highlighted), this, [](int idx){ +// qCritical() << " called: highlighted(int)"; +// }); - connect(this, static_cast(&LtsSelectionPopup::currentIndexChanged), this, - [](int idx) { qCritical() << " LtsSelectionPopup: called: currentIndexChanged(int), idx=" << idx; }); + // currentIndexChanged -> programmatically & UserInteraction + connect(this, static_cast(&LtsSelectionPopup::currentIndexChanged), this, [](int idx){ + qCritical() << " LtsSelectionPopup: called: currentIndexChanged(int), idx=" << idx; + }); - connect(this, static_cast(&LtsSelectionPopup::activated), this, - [](int idx) { qCritical() << " LtsSelectionPopup: called: activated(int), idx=" << idx; }); - -#endif + // activated -> UserInteraction + connect(this, static_cast(&LtsSelectionPopup::activated), this, [](int idx){ + qCritical() << " LtsSelectionPopup: called: activated(int), idx=" << idx; + }); + // : debugging + #endif // NEVER } + LtsSelectionPopup::~LtsSelectionPopup() { - delete m_ui; + delete m_ui; } + void LtsSelectionPopup::slotFilterChanged() { - m_filter->setFilterWildcard(m_ui->leSearch->text().count() ? m_ui->leSearch->text() : QStringLiteral("*")); - refresh(); + m_filter->setFilterWildcard(m_ui->leSearch->text().count() ? m_ui->leSearch->text() : QStringLiteral("*") /* show everything if nothing was entered */); + refresh(); } + void LtsSelectionPopup::refresh() { - m_valid = false; - qDeleteAll(m_ui->itemLayoutWidget->findChildren()); - QLayoutItem* tem = nullptr; - if (m_ui->itemLayoutWidget->layout()->count() > 0) + m_valid = false; // invalidate, none selected as all deleted + qDeleteAll(m_ui->itemLayoutWidget->findChildren()); // delete all RBs + QLayoutItem *tem = nullptr; + if (m_ui->itemLayoutWidget->layout()->count() > 0) + { + tem = m_ui->itemLayoutWidget->layout()->takeAt(0); + } + + int count = m_filter->rowCount(); + + for (int i = 0; i < count; i++) + { + int realRow = m_filter->mapToSource(m_filter->index(i, 0)).row(); + + RadioButton *rbItem = new RadioButton(realRow, m_filter->data(m_filter->index(i, 0)).toString()); + int disable = m_filter->data(m_filter->index(i, 0), Qt::UserRole-1).toInt(); + if (disable == 1) + rbItem->setEnabled(false); + m_ui->itemLayoutWidget->layout()->addWidget(rbItem); + + if (realRow == m_currentIndex) { - tem = m_ui->itemLayoutWidget->layout()->takeAt(0); + rbItem->setChecked(true); + m_valid = true; } - int count = m_filter->rowCount(); - - for (int i = 0; i < count; i++) + connect(rbItem, &RadioButton::doubleClickEvent, + this, &LtsSelectionPopup::accept); // is always selected then.. + connect(rbItem, &RadioButton::toggled, + this, [this](bool checked) { - int realRow = m_filter->mapToSource(m_filter->index(i, 0)).row(); + if (checked) + m_ui->pbSelect->setEnabled(true); + }); + } + if (tem) + m_ui->itemLayoutWidget->layout()->addItem(tem); - RadioButton* rbItem = new RadioButton(realRow, m_filter->data(m_filter->index(i, 0)).toString()); - int disable = m_filter->data(m_filter->index(i, 0), Qt::UserRole - 1).toInt(); - if (disable == 1) - rbItem->setEnabled(false); - m_ui->itemLayoutWidget->layout()->addWidget(rbItem); + if (count == 1) // if there is only one item, then allow the user to click Select (or pressing enter) to select the only item available + m_valid = true; - if (realRow == m_currentIndex) - { - rbItem->setChecked(true); - m_valid = true; - } - - connect(rbItem, &RadioButton::doubleClickEvent, this, &LtsSelectionPopup::accept); - connect(rbItem, &RadioButton::toggled, this, [this](bool checked) { - if (checked) - m_ui->pbSelect->setEnabled(true); - }); - } - if (tem) - m_ui->itemLayoutWidget->layout()->addItem(tem); - - if (count == 1) - m_valid = true; - - m_ui->pbSelect->setEnabled(m_valid); + m_ui->pbSelect->setEnabled(m_valid); } -void LtsSelectionPopup::showEvent(QShowEvent* event) + +void LtsSelectionPopup::showEvent(QShowEvent *event) { - LtsFramelessDialog::showEvent(event); - m_ui->leSearch->setFocus(); + LtsFramelessDialog::showEvent(event); + m_ui->leSearch->setFocus(); - resize(sizeHint().width() + m_ui->scrollArea->horizontalScrollBar()->height(), sizeHint().height()); + resize(sizeHint().width() + m_ui->scrollArea->horizontalScrollBar()->height() , sizeHint().height()); } + void LtsSelectionPopup::selectItem(int row, bool bCurrentIndexChanged, bool bActivated) { + // order of signals (like Qt 5.9): 1st: currentIndexChanged 2nd: activated - if (bCurrentIndexChanged) - emit currentIndexChanged(row); + if (bCurrentIndexChanged) + emit currentIndexChanged(row); - if (bActivated) - emit activated(row); + if (bActivated) + emit activated(row); - m_ui->pbSelect->setEnabled(true); + m_ui->pbSelect->setEnabled(true); - LtsFramelessDialog::accept(); + LtsFramelessDialog::accept(); // only accept if one item is selected } + void LtsSelectionPopup::accept() { - const QList items = m_ui->itemLayoutWidget->findChildren(); + const QList items = m_ui->itemLayoutWidget->findChildren(); - int count = items.count(); + int count = items.count(); - for (int i = 0; i < count; i++) + for (int i = 0; i < count; i++) + { + const RadioButton *rb = items.at(i); + + if (rb->isChecked()) { - const RadioButton* rb = items.at(i); + int realRow = m_filter->mapToSource(m_filter->index(i, 0)).row(); - if (rb->isChecked()) - { - int realRow = m_filter->mapToSource(m_filter->index(i, 0)).row(); - - bool bCurrentIndexChanged = realRow != m_firstIndex; - bool bActivated = true; - selectItem(realRow, bCurrentIndexChanged, bActivated); - return; - } + bool bCurrentIndexChanged = realRow != m_firstIndex; // currentIndex has changed? + bool bActivated = true; + selectItem(realRow, bCurrentIndexChanged, bActivated); // & closes dialog + return; // no need to go further } + } - if (count == 1) - { - const RadioButton* rb = items.at(0); - selectItem(rb->row(), true, true); - return; - } + // okay, nothing was selected, is there only one item available? if yes, select it and accept + if (count == 1) + { + const RadioButton *rb = items.at(0); + selectItem(rb->row(), true, true); // item was not selected before, so it must also be emitted as "activated" // & closes dialog + return; // no need to go further + } + // none selected and multiple choises? ignore.. } } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_selection_popup.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_selection_popup.h index d6cc901ab..2e45022fa 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_selection_popup.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_selection_popup.h @@ -1,10 +1,18 @@ - +/** + * @RDE_HEADER@ + * ComboBox's popup, optimized for tablets (bigger dropdown/popup) + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Mike Wille, SLSE, 2016-03-09 + */ #pragma once + #include "lts_frameless_dialog.h" #include "lts_widgets_export.h" -#include namespace Ui { @@ -17,38 +25,88 @@ class QSortFilterProxyModel; namespace LtsWidgets { +/** + * @brief The LtsSelectionPopup is a popup window (LtsFramelessDialog) with a list of all QRadioButtons from a model with a search/filter edit. + * (former 'LtsComboBoxPopup' class WAS an internal Popup class for the LtsComboBox and is not meant for export) + * This is a custom Popup which is touch-friendly and screen-centered. + */ class LTSWIDGETS_EXPORT LtsSelectionPopup : public LtsFramelessDialog { - Q_OBJECT + Q_OBJECT - public: - LtsSelectionPopup(QAbstractItemModel* model, int currentIndex, QWidget* parent = nullptr); - ~LtsSelectionPopup(); +public: + /** + * @brief LtsSelectionPopup creates a popup with all its items (from model) in it + * @param model the model which contains all items + * @param currentIndex which item is currently selected (to not select any item: a value smaller than 0) + * @param parent parent of this widget (not the LtsComboBox, the actual parent) + */ + LtsSelectionPopup(QAbstractItemModel *model, + int currentIndex, + QWidget *parent = nullptr); + ~LtsSelectionPopup(); - protected: - void showEvent(QShowEvent* event) override; +protected: + /** + * @brief showEvent selects the search/filter widget on show + * @param event + */ + void showEvent(QShowEvent *event) override; - private: - Ui::LtsSelectionPopup* m_ui; - int m_currentIndex; - int m_firstIndex; - QSortFilterProxyModel* m_filter; - bool m_valid; +private: + Ui::LtsSelectionPopup *m_ui; + int m_currentIndex; + int m_firstIndex; + QSortFilterProxyModel *m_filter; + bool m_valid; // selection is valid? (e.g. not hidden because it's filtered) - void refresh(); + /** + * @brief refresh deletes all Radio Buttons and creates them new (e.g. filtering) + */ + void refresh(); - void selectItem(int row, bool bCurrentIndexChanged, bool bActivated); + /** + * @brief selectItem emits signals that tell the connected slot which item was selected + * @param row the row number of the model + * @param text the text of the radio button + * @param activate if the item was activated (see QRadioButton doc) - by default false as it not not used everytime + */ + void selectItem(int row, bool bCurrentIndexChanged, bool bActivated); - signals: +signals: - void activated(int index); + // void highlighted(int index); // not supported yet - void currentIndexChanged(int index); + // activated(row); // Qt::Doc: is only emitted when the change is caused by user interaction - public slots: + // currentIndexChanged(row); // Qt::Doc: is always emitted regardless if the change was done programmatically or by user interaction + // My note: If the uses selects the already selected item, only activated is emitted. - void accept() override; - void slotFilterChanged(); + /** + * @brief activated is emitted when the selection has changed or is confirmded by the user + * Qt::Doc: is only emitted when the change is caused by user interaction + * Addon: If the uses selects the already selected item, only activated is emitted. + */ + void activated(int index); + + /** + * @brief currentIndexChanged is emitted when the current item changes (by user interaction or programmatically) + * Qt::Doc: is always emitted regardless if the change was done programmatically or by user interaction + * Addon: If the uses selects the already selected item, only activated is emitted. + */ + void currentIndexChanged(int index); + +public slots: + /** + * @brief accept is called when the selection ends successfully (user double-clicked an item or clicked the 'Select' button) and emits signalSelectItem + */ + void accept() override; + + /** + * @brief slotFilterChanged is called if the search / filter text changed and recreates all Radio Buttons after filtering + */ + void slotFilterChanged(); + }; } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_spinbox.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_spinbox.cpp index 4c5bba931..f9283b121 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_spinbox.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_spinbox.cpp @@ -1,4 +1,12 @@ - +/** + * @RDE_HEADER@ + * SpinBox, that corrects values to a valid value that fits minimum() + n * singleStep() = value + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Malte Diers, NLSE, 2018-05-07 + */ #include "lts_spinbox.h" @@ -7,155 +15,166 @@ namespace LtsWidgets { -LtsSpinBox::LtsSpinBox(QWidget* parent) : QSpinBox(parent) {} - -QValidator::State LtsSpinBox::validate(QString& input, int& pos) const +LtsSpinBox::LtsSpinBox(QWidget *parent) + : QSpinBox(parent) { - QIntValidator validator; - for (auto range : m_validRanges) - { - validator.setBottom(range.first); - validator.setTop(range.second); - QValidator::State state = validator.validate(input, pos); - if (state == QValidator::Invalid || state == QValidator::Intermediate) - return state; - } - - int value = input.toInt(); - value -= minimum(); - return (value % singleStep() == 0) ? QValidator::Acceptable : QValidator::Intermediate; } -void LtsSpinBox::fixup(QString& str) const +QValidator::State LtsSpinBox::validate(QString &input, int &pos) const { - QSpinBox::fixup(str); + QIntValidator validator; + for (auto range : m_validRanges) + { + validator.setBottom(range.first); + validator.setTop(range.second); + QValidator::State state = validator.validate(input, pos); + if (state == QValidator::Invalid || + state == QValidator::Intermediate) + return state; + } - if (singleStep() == 1) - return; - - bool bOk; - int value = str.toInt(&bOk); - if (!bOk) - return; - - int remainder = (value - minimum()) % singleStep(); - - if (2 * remainder > singleStep()) - value += singleStep(); - - value -= remainder; - - if (value > maximum()) - value -= singleStep(); - - str = QString::number(value); + // Now we're sure, it's an int. Therefore toInt() will always be okay: + int value = input.toInt(); + value -= minimum(); + return (value % singleStep() == 0) ? QValidator::Acceptable : QValidator::Intermediate; } -bool LtsSpinBox::setExclusionRanges(const QVector>& exclusionRanges, bool preserveCurrentValues) +void LtsSpinBox::fixup(QString &str) const { - bool retVal = true; + QSpinBox::fixup(str); - auto newExclusions = exclusionRanges; + if (singleStep() == 1) + return; - if (preserveCurrentValues) - newExclusions += m_exclusions; + bool bOk; + int value = str.toInt(&bOk); + if (!bOk) + return; - for (auto& elem : newExclusions) + int remainder = (value - minimum()) % singleStep(); + + if (2 * remainder > singleStep()) + value += singleStep(); + + value -= remainder; + + if (value > maximum()) + value -= singleStep(); + + str = QString::number(value); +} + +bool LtsSpinBox::setExclusionRanges(const QVector > &exclusionRanges, bool preserveCurrentValues) +{ + bool retVal = true; + // In eigene Variable + auto newExclusions = exclusionRanges; + // Hinzufügen? + if (preserveCurrentValues) + newExclusions += m_exclusions; + // ggf. Min und Max tauschen: + for (auto &elem : newExclusions) + { + if (elem.first > elem.second) { - if (elem.first > elem.second) - { - int tmp = elem.first; - elem.first = elem.second; - elem.second = tmp; - } + int tmp = elem.first; + elem.first= elem.second; + elem.second = tmp; } - - std::sort(newExclusions.begin(), newExclusions.end(), - [](const QPair& a, const QPair& b) { return a.first < b.first; }); - for (int i = 0; i < newExclusions.size() - 1; ++i) + } + // Sortieren und + std::sort(newExclusions.begin(), newExclusions.end(), [](const QPair &a, const QPair &b) { return a.first < b.first; }); + for (int i=0; i= newExclusions[i+1].first) { - - if (newExclusions[i].second >= newExclusions[i + 1].first) - { - retVal = false; - break; - } + retVal = false; + break; } + } + // Falls doch - oder falls out of range + if (!retVal || newExclusions[0].first <= minimum() || newExclusions[newExclusions.size()-1].second >= maximum()) + { + // Falls nicht "Hinzufügen", Liste leeren. Sonst bleibt alles beim Alten. + if (!preserveCurrentValues) + m_exclusions.clear(); + return false; + } + // Alles in Butter: + m_exclusions = exclusionRanges; - if (!retVal || newExclusions[0].first <= minimum() || newExclusions[newExclusions.size() - 1].second >= maximum()) - { + // Put that into validRanges... + m_validRanges.clear(); + if (m_exclusions[0].first - 1 > minimum()) + m_validRanges.append({minimum(), m_exclusions[0].first - 1}); + for (int i=0; i minimum()) - m_validRanges.append({minimum(), m_exclusions[0].first - 1}); - for (int i = 0; i < m_exclusions.size() - 1; ++i) - { - - if (m_exclusions[i].second + 1 < m_exclusions[i + 1].first - 1) - m_validRanges.append({m_exclusions[i].second + 1, m_exclusions[i + 1].first - 1}); - } - if (m_exclusions[m_exclusions.size() - 1].second + 1 < maximum()) - m_validRanges.append({m_exclusions[0].first - 1, maximum()}); - - return true; + return true; } bool LtsSpinBox::addExclusionRange(int min, int max) { - return setExclusionRanges({{min, max}}, true); + return setExclusionRanges({{min, max}}, true); } void LtsSpinBox::clearExclusionRanges() { - m_exclusions.clear(); + m_exclusions.clear(); } -LtsDoubleSpinBox::LtsDoubleSpinBox(QWidget* parent) : QDoubleSpinBox(parent) {} -QValidator::State LtsDoubleSpinBox::validate(QString& input, int& pos) const +LtsDoubleSpinBox::LtsDoubleSpinBox(QWidget *parent) + : QDoubleSpinBox(parent) { - QDoubleValidator validator; - validator.setBottom(minimum()); - validator.setTop(maximum()); - QValidator::State state = validator.validate(input, pos); - if (state == QValidator::Invalid || state == QValidator::Intermediate) - return state; - - double value = input.toDouble(); - value -= minimum(); - return qFuzzyCompare(std::fmod(value, singleStep()), 0.0) ? QValidator::Acceptable : QValidator::Intermediate; } -void LtsDoubleSpinBox::fixup(QString& str) const +QValidator::State LtsDoubleSpinBox::validate(QString &input, int &pos) const { - QDoubleSpinBox::fixup(str); + QDoubleValidator validator; + validator.setBottom(minimum()); + validator.setTop(maximum()); + QValidator::State state = validator.validate(input, pos); + if (state == QValidator::Invalid || + state == QValidator::Intermediate) + return state; - if (qFuzzyCompare(singleStep(), pow(10, decimals()))) - return; + // Now we're sure, it's an int. Therefore toInt() will always be okay: + double value = input.toDouble(); + value -= minimum(); + return qFuzzyCompare(std::fmod(value, singleStep()), 0.0) ? QValidator::Acceptable : QValidator::Intermediate; +} - bool bOk; - double value = str.toDouble(&bOk); - if (!bOk) - return; +void LtsDoubleSpinBox::fixup(QString &str) const +{ + QDoubleSpinBox::fixup(str); - double remainder = std::fmod(value - minimum(), singleStep()); + if (qFuzzyCompare(singleStep(), pow(10, decimals()))) + return; - if (2 * remainder > singleStep()) - value += singleStep(); + bool bOk; + double value = str.toDouble(&bOk); + if (!bOk) + return; - value -= remainder; + double remainder = std::fmod(value - minimum(), singleStep()); - if (value > maximum()) - value -= singleStep(); + if (2 * remainder > singleStep()) + value += singleStep(); - str = QString::number(value, 'f', decimals()); + value -= remainder; + + if (value > maximum()) + value -= singleStep(); + + str = QString::number(value, 'f', decimals()); } } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_spinbox.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_spinbox.h index 9eb79065d..5ee3beb48 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_spinbox.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_spinbox.h @@ -1,9 +1,17 @@ - +/** + * @RDE_HEADER@ + * SpinBox, that corrects values to a valid value that fits minimum() + n * singleStep() = value + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Malte Diers, NLSE, 2018-05-07 + */ #pragma once + #include "lts_widgets_export.h" -#include #include namespace LtsWidgets @@ -11,62 +19,49 @@ namespace LtsWidgets class LTSWIDGETS_EXPORT LtsSpinBox : public QSpinBox { - Q_OBJECT + Q_OBJECT - public: - explicit LtsSpinBox(QWidget* parent = nullptr); - ~LtsSpinBox() = default; +public: + explicit LtsSpinBox(QWidget *parent = nullptr); + ~LtsSpinBox() = default; - public slots: +public slots: + void setValue(int val) { QString valStr = QString::number(val); fixup(valStr); QSpinBox::setValue(valStr.toInt()); } + bool setExclusionRanges(const QVector > &exclusionRanges, bool preserveCurrentValues = false); + bool addExclusionRange(int min, int max); + void clearExclusionRanges(); - void setValue(int val) - { - QString valStr = QString::number(val); - fixup(valStr); - QSpinBox::setValue(valStr.toInt()); - } +protected: + QValidator::State validate(QString &input, int &pos) const override; + void fixup(QString &str) const override; - bool setExclusionRanges(const QVector>& exclusionRanges, bool preserveCurrentValues = false); - bool addExclusionRange(int min, int max); - void clearExclusionRanges(); +private: - protected: - QValidator::State validate(QString& input, int& pos) const override; - void fixup(QString& str) const override; + struct + { + bool operator()(const QPair &a, const QPair &b) const { return a.first < b.first; } + } customless; - private: - struct - { - bool operator()(const QPair& a, const QPair& b) const - { - return a.first < b.first; - } - } customless; + QVector > m_exclusions; + QVector > m_validRanges; // Doubles the information. However, it saves calculation... - QVector> m_exclusions; - QVector> m_validRanges; }; class LTSWIDGETS_EXPORT LtsDoubleSpinBox : public QDoubleSpinBox { - Q_OBJECT + Q_OBJECT - public: - explicit LtsDoubleSpinBox(QWidget* parent = nullptr); - ~LtsDoubleSpinBox() = default; +public: + explicit LtsDoubleSpinBox(QWidget *parent = nullptr); + ~LtsDoubleSpinBox() = default; - public slots: +public slots: + void setValue(double val) { QString valStr = QString::number(val); fixup(valStr); QDoubleSpinBox::setValue(valStr.toDouble()); } - void setValue(double val) - { - QString valStr = QString::number(val); - fixup(valStr); - QDoubleSpinBox::setValue(valStr.toDouble()); - } +protected: + QValidator::State validate(QString &input, int &pos) const override; + void fixup(QString &str) const override; - protected: - QValidator::State validate(QString& input, int& pos) const override; - void fixup(QString& str) const override; }; -} // namespace LtsWidgets +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splash.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splash.cpp index 5ff73af96..7d909d9c1 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splash.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splash.cpp @@ -1,71 +1,81 @@ #include "lts_splash.h" #include + #include -#include #include +#include + namespace LtsWidgets { -Splash::Splash() : QSplashScreen(), m_done(false) +Splash::Splash() + : QSplashScreen() + , m_done(false) { - static const auto splashFiles = { - QStringLiteral(":/project/splash.png"), - QStringLiteral(":/project/splash.jpg"), - }; - for (const QString& f : splashFiles) - { - if (!QFile::exists(f)) - continue; - setPixmap(QPixmap(f)); - break; - } + static const auto splashFiles = + { + QStringLiteral(":/project/splash.png"), + QStringLiteral(":/project/splash.jpg"), + }; + for (const QString &f : splashFiles) + { + if (!QFile::exists(f)) + continue; + setPixmap(QPixmap(f)); + break; + } } -bool Splash::event(QEvent* e) -{ - if (e->type() == QEvent::MouseButtonPress || e->type() == QEvent::MouseButtonRelease || - e->type() == QEvent::MouseButtonDblClick) - { - e->ignore(); - return false; - } - return QSplashScreen::event(e); +bool Splash::event(QEvent *e) +{ + if (e->type() == QEvent::MouseButtonPress || + e->type() == QEvent::MouseButtonRelease || + e->type() == QEvent::MouseButtonDblClick) + { + e->ignore(); + return false; + } + + return QSplashScreen::event(e); } -void Splash::setMessage(const QString& message) + +void Splash::setMessage(const QString &message) { - showMessage(message, Qt::AlignRight | Qt::AlignBottom); + showMessage(message, Qt::AlignRight | Qt::AlignBottom); } + void Splash::done() { - if (m_done) - return; - m_done = true; + if (m_done) + return; + m_done = true; - hide(); - LtsWidgets::LtsGlobalWaitDialog::getInstance()->setVisible(true); + hide(); + LtsWidgets::LtsGlobalWaitDialog::getInstance()->setVisible(true); // after the splash has finished, wait dlgs are allowed } -static Splash* s_splashInstance = nullptr; +static Splash *s_splashInstance = nullptr; void Splash::cleanupSplashInstance() { - delete s_splashInstance; - s_splashInstance = nullptr; + delete s_splashInstance; + s_splashInstance = nullptr; } -Splash* Splash::getInstance() + +Splash *Splash::getInstance() { - if (!s_splashInstance) - { - s_splashInstance = new Splash; - qAddPostRoutine(&Splash::cleanupSplashInstance); - } - return s_splashInstance; + if (!s_splashInstance) + { + s_splashInstance = new Splash; + qAddPostRoutine(&Splash::cleanupSplashInstance); + } + return s_splashInstance; } } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splash.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splash.h index e4e7e6c9f..f5cf1d224 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splash.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splash.h @@ -1,27 +1,28 @@ #pragma once -#include "lts_widgets_export.h" +#include -#include #include +#include + namespace LtsWidgets { class LTSWIDGETS_EXPORT Splash : public QSplashScreen { - Q_OBJECT - public: - static Splash* getInstance(); + Q_OBJECT +public: + static Splash* getInstance(); - void done(); - void setMessage(const QString& message); + void done(); + void setMessage(const QString &message); - private: - Splash(); - static void cleanupSplashInstance(); +private: + Splash(); + static void cleanupSplashInstance(); - bool event(QEvent* e) override; + bool event(QEvent *e) override; - bool m_done; + bool m_done; }; } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter.cpp index 05ed7374c..c0db93b94 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter.cpp @@ -1,53 +1,62 @@ - +/** +* @RDE_HEADER@ +* Splitter with sizes Proberty for Animation +* $Id$ +* $HeadURL$ +* $Author$ +*/ #include "lts_splitter.h" - #include "lts_splitter_handle.h" + namespace LtsWidgets { -LtsSplitter::LtsSplitter(QWidget* parent) : QSplitter(parent) +LtsSplitter::LtsSplitter(QWidget *parent) + : QSplitter(parent) { - connect(this, &LtsSplitter::sizesChanged, this, &LtsSplitter::changeSizes); + connect(this, &LtsSplitter::sizesChanged, this, &LtsSplitter::changeSizes); } -LtsSplitter::~LtsSplitter() {} - -QSplitterHandle* LtsSplitter::createHandle() +LtsSplitter::~LtsSplitter() { - LtsSplitterHandle* hand = new LtsSplitterHandle(orientation(), this); +} + +QSplitterHandle *LtsSplitter::createHandle() +{ + LtsSplitterHandle *hand = new LtsSplitterHandle(orientation(), this); #ifdef TABLET_MODE - setHandleWidth(25); + setHandleWidth(25); #else - setHandleWidth(10); + setHandleWidth(10); #endif - return hand; + return hand; } void LtsSplitter::collapseChild(const int index) { - if (children().size() > index) + if (children().size() > index) + { + QWidget *widget = static_cast(children().at(index)); + if (widget) { - QWidget* widget = static_cast(children().at(index)); - if (widget) - { - QList s = sizes(); - s[index] = 0; - setSizes(s); - } + QList s = sizes(); + s[index] = 0; + setSizes(s); } + } } void LtsSplitter::animate(int handleId) { - LtsSplitterHandle* handle = dynamic_cast(this->handle(handleId)); - handle->animate(); + LtsSplitterHandle *handle = dynamic_cast(this->handle(handleId)); + handle->animate(); } -void LtsSplitter::changeSizes(const QList& list) +void LtsSplitter::changeSizes(const QList &list) { - QSplitter::setSizes(list); + QSplitter::setSizes(list); } } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter.h index 252bfa2ea..f68d41619 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter.h @@ -1,40 +1,42 @@ - +/** +* @RDE_HEADER@ +* Splitter with sizes Proberty for Animation +* $Id$ +* $HeadURL$ +* $Author$ +*/ #pragma once + #include "lts_base.h" #include "lts_widgets_export.h" -#include -#include #include +#include + namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsSplitter : public QSplitter { - Q_OBJECT - Q_PROPERTY(QList sizes READ getSizes WRITE setSizes NOTIFY sizesChanged) + Q_OBJECT + Q_PROPERTY(QList sizes READ getSizes WRITE setSizes NOTIFY sizesChanged) - public: - explicit LtsSplitter(QWidget* parent = nullptr); - ~LtsSplitter(); +public: + explicit LtsSplitter(QWidget *parent = nullptr); + ~LtsSplitter(); - QSplitterHandle* createHandle(); - void collapseChild(const int index); + QSplitterHandle *createHandle(); + void collapseChild(const int index); + QList getSizes() const { return sizes(); } + void animate(int handleId); - QList getSizes() const - { - return sizes(); - } +signals: + void sizesChanged(const QList &newSizes); - void animate(int handleId); - - signals: - void sizesChanged(const QList& newSizes); - - public slots: - void changeSizes(const QList& list); +public slots: + void changeSizes(const QList &list); }; } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter_handle.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter_handle.cpp index 5f8a0186b..213469a48 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter_handle.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter_handle.cpp @@ -1,83 +1,92 @@ - +/** +* @RDE_HEADER@ +* Splitter with sizes Proberty for Animation +* $Id$ +* $HeadURL$ +* $Author kemayou_s$ +*/ #include "lts_splitter_handle.h" - +#include +#include #include -#include #include #include -#include -#include +#include + namespace LtsWidgets { -LtsSplitterHandle::LtsSplitterHandle(Qt::Orientation orientation, QSplitter* parent) - : QSplitterHandle(orientation, parent) +LtsSplitterHandle::LtsSplitterHandle(Qt::Orientation orientation, QSplitter *parent) + : QSplitterHandle(orientation, parent) { - auto bgrole = backgroundRole(); - QPalette p = palette(); - m_endColor = p.color(bgrole); + auto bgrole = backgroundRole(); + QPalette p = palette(); + m_endColor = p.color(bgrole); + + m_colorAnimation = new QPropertyAnimation(this, "splittercolor"); + m_colorAnimation->setDuration(1000); + m_colorAnimation->setStartValue(m_currentColor); + m_colorAnimation->setEndValue(m_endColor); + m_colorAnimation->setLoopCount(2); + connect(m_colorAnimation, &QPropertyAnimation::finished, this, [this]{ + m_animate = false; + m_currentColor = m_endColor; + repaint(); + }); - m_colorAnimation = new QPropertyAnimation(this, "splittercolor"); - m_colorAnimation->setDuration(1000); - m_colorAnimation->setStartValue(m_currentColor); - m_colorAnimation->setEndValue(m_endColor); - m_colorAnimation->setLoopCount(2); - connect(m_colorAnimation, &QPropertyAnimation::finished, this, [this] { - m_animate = false; - m_currentColor = m_endColor; - repaint(); - }); } -LtsSplitterHandle::~LtsSplitterHandle() {} - -void LtsSplitterHandle::paintEvent(QPaintEvent* event) +LtsSplitterHandle::~LtsSplitterHandle() { - if (!m_animate) - { - QSplitterHandle::paintEvent(event); - return; - } - QPainter painter(this); - QLinearGradient gradient; - gradient.setColorAt(0, m_currentColor); +} - if (orientation() == Qt::Horizontal) - { - gradient.setStart(rect().left(), rect().height() / 2); - gradient.setFinalStop(rect().height(), rect().height() / 2); - } - else - { - gradient.setStart(rect().width() / 2, rect().top()); - gradient.setFinalStop(rect().width() / 2, rect().bottom() / 2); - } - painter.fillRect(event->rect(), QBrush(gradient)); +void LtsSplitterHandle::paintEvent(QPaintEvent *event) +{ + if(!m_animate) + { + QSplitterHandle::paintEvent(event); + return; + } + QPainter painter(this); + QLinearGradient gradient; + gradient.setColorAt(0, m_currentColor); + //gradient.setColorAt(1, m_endColor); + + if(orientation() == Qt::Horizontal) + { + gradient.setStart(rect().left(), rect().height()/2); + gradient.setFinalStop(rect().height(), rect().height()/2); + }else + { + gradient.setStart(rect().width()/2, rect().top()); + gradient.setFinalStop(rect().width()/2, rect().bottom()/2); + } + painter.fillRect(event->rect(), QBrush(gradient)); } void LtsSplitterHandle::animate() { - if (m_colorAnimation->state() == QPropertyAnimation::Running) - return; + if (m_colorAnimation->state() == QPropertyAnimation::Running) + return; - m_currentColor = QColor(239, 87, 50); - m_animate = true; - m_colorAnimation->start(); + m_currentColor = QColor(239,87,50); + m_animate = true; + m_colorAnimation->start(); } QColor LtsSplitterHandle::splitterColor() const { - return m_currentColor; + return m_currentColor; } -void LtsSplitterHandle::setCurrentColor(const QColor& currentcolor) +void LtsSplitterHandle::setCurrentColor(const QColor ¤tcolor) { - if (currentcolor == m_currentColor) - return; - m_currentColor = currentcolor; - repaint(); + if (currentcolor == m_currentColor) + return; + m_currentColor = currentcolor; + repaint(); } } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter_handle.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter_handle.h index e787a758b..d05f9edc2 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter_handle.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter_handle.h @@ -1,37 +1,44 @@ - +/** +* @RDE_HEADER@ +* Splitter with sizes Proberty for Animation +* $Id$ +* $HeadURL$ +* $Author kemayou_s$ +*/ #pragma once + #include "lts_base.h" #include "lts_widgets_export.h" -#include -#include -#include #include +#include +#include namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsSplitterHandle : public QSplitterHandle { - Q_OBJECT - Q_PROPERTY(QColor splittercolor READ splitterColor WRITE setCurrentColor DESIGNABLE false) + Q_OBJECT + Q_PROPERTY(QColor splittercolor READ splitterColor WRITE setCurrentColor DESIGNABLE false) - public: - explicit LtsSplitterHandle(Qt::Orientation orientation, QSplitter* parent = nullptr); - ~LtsSplitterHandle(); +public: + explicit LtsSplitterHandle(Qt::Orientation orientation, QSplitter *parent = nullptr); + ~LtsSplitterHandle(); - void paintEvent(QPaintEvent* event) override; - void animate(); + void paintEvent(QPaintEvent *event) override; + void animate(); - QColor splitterColor() const; - void setCurrentColor(const QColor& currentcolor); + QColor splitterColor() const; + void setCurrentColor(const QColor ¤tcolor); + +private: + bool m_animate {false}; + QColor m_endColor {Qt::black}; + QColor m_currentColor{QColor(239,87,50)}; + QPropertyAnimation *m_colorAnimation; - private: - bool m_animate{false}; - QColor m_endColor{Qt::black}; - QColor m_currentColor{QColor(239, 87, 50)}; - QPropertyAnimation* m_colorAnimation; }; } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_bar.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_bar.cpp index f76e1a82c..db442b705 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_bar.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_bar.cpp @@ -1,4 +1,10 @@ - +/** +* @RDE_HEADER@ +* TabBar with special stylesheet settings +* $Id$ +* $HeadURL$ +* $Author$ +*/ #include "lts_tab_bar.h" @@ -7,108 +13,113 @@ #include "lts_events.h" #include "lts_tab_widget.h" +#include #include #include -#include namespace LtsWidgets { -LtsTabBar::LtsTabBar(bool isSecondary, QWidget* parent) : QTabBar(parent), m_secondary(isSecondary) +LtsTabBar::LtsTabBar(bool isSecondary, QWidget *parent) + : QTabBar(parent) + , m_secondary(isSecondary) { - setDocumentMode(true); - setTabsClosable(true); + setDocumentMode(true); + setTabsClosable(true); - connect(this, &LtsTabBar::currentChanged, this, &LtsTabBar::updateCloseButtonColors); + connect(this, &LtsTabBar::currentChanged, this, &LtsTabBar::updateCloseButtonColors); - if (m_secondary) - { - connect(this, &LtsTabBar::customContextMenuRequested, this, &LtsTabBar::onCustomContextMenuRequested); - setContextMenuPolicy(Qt::CustomContextMenu); - } + if (m_secondary) + { + connect(this, &LtsTabBar::customContextMenuRequested, + this, &LtsTabBar::onCustomContextMenuRequested); + setContextMenuPolicy(Qt::CustomContextMenu); + } } -void LtsTabBar::_internal_closeTab() + +void LtsTabBar::_internal_closeTab() // Do not use. { - QObject* object = sender(); - int tabToClose = -1; + QObject *object = sender(); + int tabToClose = -1; - for (int i = 0; i < count(); i++) + for (int i = 0; i < count(); i++) + { + if (tabButton(i, QTabBar::RightSide) == object) { - if (tabButton(i, QTabBar::RightSide) == object) - { - tabToClose = i; - break; - } + tabToClose = i; + break; } + } - if (tabToClose != -1) - emit tabCloseRequested(tabToClose); + if (tabToClose != -1) + emit tabCloseRequested(tabToClose); } -void LtsTabBar::updateCloseButtonColors(int newIndex) + +void LtsTabBar::updateCloseButtonColors(int newIndex) // as this does not happen automatically { + // tell all buttons if there are selected or not + if (newIndex == -1) + newIndex = currentIndex(); // TODO: is currentIndex already set when emitting currentChanged ?? - if (newIndex == -1) - newIndex = currentIndex(); + for (int i = 0; i < count(); i++) + { + QWidget *w = tabButton(i, QTabBar::RightSide); + CloseButton *cb = qobject_cast(w); - for (int i = 0; i < count(); i++) + if (!cb) + continue; + + QColor text; + + bool enabled = isTabEnabled(i); + bool selected = (i == newIndex); + bool secondary = m_secondary; + + if (enabled) { - QWidget* w = tabButton(i, QTabBar::RightSide); - CloseButton* cb = qobject_cast(w); - - if (!cb) - continue; - - QColor text; - - bool enabled = isTabEnabled(i); - bool selected = (i == newIndex); - bool secondary = m_secondary; - - if (enabled) - { - if (selected) - text = - (secondary) ? Styles::TabBarTabStyle::secondarySelected : Styles::TabBarTabStyle::primarySelected; - else - text = (secondary) ? Styles::TabBarTabStyle::secondaryNormal : Styles::TabBarTabStyle::primaryNormal; - } - else - text = (secondary) ? Styles::TabBarTabStyle::secondaryDisabled : Styles::TabBarTabStyle::primaryDisabled; - - cb->setFontColor(text); + if (selected) + text = (secondary) ? Styles::TabBarTabStyle::secondarySelected : Styles::TabBarTabStyle::primarySelected; + else + text = (secondary) ? Styles::TabBarTabStyle::secondaryNormal : Styles::TabBarTabStyle::primaryNormal; } + else + text = (secondary) ? Styles::TabBarTabStyle::secondaryDisabled : Styles::TabBarTabStyle::primaryDisabled; // no 'selected' on disabled! + + //qWarning() << "("<setFontColor(text); + } } void LtsTabBar::onCustomContextMenuRequested(const QPoint pos) { - if (!m_secondary) - return; - QMenu m; - QAction* a = new QAction(tr("Save as image")); - connect(a, &QAction::triggered, this, [this, pos]() { LtsTabBar::onSaveCurrentWidgetAsImage(pos); }); - m.addAction(a); - m.exec(mapToGlobal(pos)); + if (!m_secondary) + return; + QMenu m; + QAction *a = new QAction(tr("Save as image")); + connect(a, &QAction::triggered, this, [this, pos]() { LtsTabBar::onSaveCurrentWidgetAsImage(pos); }); + m.addAction(a); + m.exec(mapToGlobal(pos)); } void LtsTabBar::onSaveCurrentWidgetAsImage(const QPoint pos) { - int curTab = tabAt(pos); - if (curTab < 0) - curTab = currentIndex(); - if (curTab < 0) - return; - LtsTabWidget* tw = qobject_cast(parentWidget()); - QWidget* w = tw ? tw->widget(curTab) : nullptr; - if (!w) - return; - LtsDialogHelper* helper = qobject_cast(w); - if (helper) - w = helper->getDialog(); - SaveImageEvent* ev = new SaveImageEvent(w, w->grab()); - ev->setAccepted(false); - QCoreApplication::postEvent(qApp, ev); + int curTab = tabAt(pos); + if (curTab < 0) + curTab = currentIndex(); + if (curTab < 0) + return; + LtsTabWidget *tw = qobject_cast(parentWidget()); + QWidget *w = tw ? tw->widget(curTab) : nullptr; + if (!w) + return; + LtsDialogHelper *helper = qobject_cast(w); + if (helper) + w = helper->getDialog(); + SaveImageEvent *ev = new SaveImageEvent(w, w->grab()); + ev->setAccepted(false); + QCoreApplication::postEvent(qApp, ev); } } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_bar.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_bar.h index 41b355d19..21b563586 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_bar.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_bar.h @@ -1,33 +1,51 @@ - +/** +* @RDE_HEADER@ +* TabBar with special stylesheet settings +* $Id$ +* $HeadURL$ +* $Author$ +*/ #pragma once -#include "lts_widgets_export.h" -#include #include +#include "lts_widgets_export.h" namespace LtsWidgets { +/** + * @brief The LtsTabBar class provides a QTabBar with the ability to be a master tab or a secondary tab inside a master tab. This allows tabs to be sorted + * into a group of a whole, which promotes better overview. + */ class LTSWIDGETS_EXPORT LtsTabBar : public QTabBar { - Q_OBJECT - Q_PROPERTY(bool secondary MEMBER m_secondary) + Q_OBJECT + Q_PROPERTY(bool secondary MEMBER m_secondary) - public: - explicit LtsTabBar(bool isSecondary = false, QWidget* parent = nullptr); +public: + /** + * @brief LtsTabBar creates a QTabBar + * @param isSecondary true if this is a secondary tab bar, false if this is a master tab bar + * @param width Debug value - do not use + * @param parent The parent. + */ + explicit LtsTabBar(bool isSecondary = false, QWidget *parent = nullptr); - void _internal_closeTab(); + /** + * @brief Do not use. + */ + void _internal_closeTab(); - protected: - void onCustomContextMenuRequested(const QPoint pos); - void onSaveCurrentWidgetAsImage(const QPoint pos); +protected: + void onCustomContextMenuRequested(const QPoint pos); + void onSaveCurrentWidgetAsImage(const QPoint pos); +private: + bool m_secondary; - private: - bool m_secondary; +public slots: + void updateCloseButtonColors(int newIndex = -1); // has to be called AFTER a new Close Button was added, to set his initial status (selected yes/no) - as this does not happen automatically - public slots: - void updateCloseButtonColors(int newIndex = -1); }; -} // namespace LtsWidgets +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_sequence_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_sequence_widget.cpp index c67681602..601403212 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_sequence_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_sequence_widget.cpp @@ -1,59 +1,65 @@ - - +/** + * @RDE_HEADER@ + * widget for creating a tab view of dds sequences + * $Id$ + * $HeadURL$ + * $Author$ + * Created by Verena Eberlein , SPMO, 2023-08-03 + */ #include "lts_tab_sequence_widget.h" -#include #include #include #include +#include namespace LtsWidgets { -LtsTabSequenceWidget::LtsTabSequenceWidget(QWidget* parent) - : LtsAbstractSequenceWidget(parent), m_twSequences(new QTabWidget(this)) +LtsTabSequenceWidget::LtsTabSequenceWidget(QWidget *parent) + : LtsAbstractSequenceWidget(parent) + , m_twSequences(new QTabWidget(this)) { - QHBoxLayout* gridLayout = new QHBoxLayout(this); - gridLayout->addWidget(m_twSequences); - gridLayout->addWidget(pbAddMember(), Qt::AlignTop); + QHBoxLayout *gridLayout = new QHBoxLayout(this); + gridLayout->addWidget(m_twSequences); + gridLayout->addWidget(pbAddMember(), Qt::AlignTop); - m_twSequences->setCornerWidget(pbAddMember()); - pbAddMember()->setFixedSize(m_twSequences->tabBar()->size()); - pbAddMember()->setIconSize(m_twSequences->tabBar()->size()); + m_twSequences->setCornerWidget(pbAddMember()); + pbAddMember()->setFixedSize(m_twSequences->tabBar()->size()); + pbAddMember()->setIconSize(m_twSequences->tabBar()->size()); } LtsTabSequenceWidget::~LtsTabSequenceWidget() { - delete pbAddMember(); - delete m_twSequences; + delete pbAddMember(); + delete m_twSequences; } -void LtsTabSequenceWidget::setupMemberWidget(QWidget* child, QToolButton* pbChild, const QString& objectName, - bool isButtonVisible) +void LtsTabSequenceWidget::setupMemberWidget(QWidget *child, QToolButton *pbChild, const QString &objectName, bool isButtonVisible) { - int index = m_twSequences->addTab(child, objectName); - if (isButtonVisible) - m_twSequences->tabBar()->setTabButton(index, QTabBar::RightSide, pbChild); + int index = m_twSequences->addTab(child, objectName); + if(isButtonVisible) + m_twSequences->tabBar()->setTabButton(index, QTabBar::RightSide, pbChild); } QWidget* LtsTabSequenceWidget::getWidget(int index) { - return m_twSequences->widget(index); + return m_twSequences->widget(index); } QWidget* LtsTabSequenceWidget::getCurrentWidget() { - return m_twSequences->currentWidget(); + return m_twSequences->currentWidget(); } int LtsTabSequenceWidget::getCurrentTabIndex() { - return m_twSequences->currentIndex(); + return m_twSequences->currentIndex(); +} +void LtsTabSequenceWidget::changeTabName(const QString &name) +{ + m_twSequences->setTabText(m_twSequences->currentIndex(), name); } -void LtsTabSequenceWidget::changeTabName(const QString& name) -{ - m_twSequences->setTabText(m_twSequences->currentIndex(), name); -} } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_sequence_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_sequence_widget.h index f738de027..53ddc5365 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_sequence_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_sequence_widget.h @@ -1,39 +1,43 @@ - - +/** + * @RDE_HEADER@ + * widget for creating a tab view of dds sequences + * $Id$ + * $HeadURL$ + * $Author$ + * Created by Verena Eberlein, SPMO, 2023-08-03 + */ #ifndef LTS_TAB_SEQUENCE_WIDGET_H #define LTS_TAB_SEQUENCE_WIDGET_H #pragma once + #include "lts_abstract_sequence_widget.h" #include "lts_widgets_export.h" -#include - class QTabWidget; namespace LtsWidgets { -class LTSWIDGETS_EXPORT LtsTabSequenceWidget : public LtsAbstractSequenceWidget -{ + class LTSWIDGETS_EXPORT LtsTabSequenceWidget : public LtsAbstractSequenceWidget + { Q_OBJECT public: - LtsTabSequenceWidget(QWidget* parent = nullptr); + LtsTabSequenceWidget(QWidget *parent = nullptr); virtual ~LtsTabSequenceWidget(); QWidget* getWidget(int index); QWidget* getCurrentWidget(); int getCurrentTabIndex(); - void changeTabName(const QString& name); + void changeTabName(const QString &name); protected: - void setupMemberWidget(QWidget* child, QToolButton* pbChild, const QString& objectName, - bool isButtonVisible = true) override; + void setupMemberWidget(QWidget *child, QToolButton *pbChild, const QString &objectName, bool isButtonVisible = true) override; private: - QTabWidget* m_twSequences = nullptr; -}; -} // namespace LtsWidgets + QTabWidget *m_twSequences = nullptr; + }; +} -#endif +#endif // LTS_TAB_SEQUENCE_WIDGET_H diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_widget.cpp index e205c1d84..763eb9009 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_widget.cpp @@ -1,803 +1,906 @@ - +/** +* @RDE_HEADER@ +* TabWidget for new EXCON +* $Id$ +* $HeadURL$ +* $Author$ +*/ #include "lts_tab_widget.h" - #include "lts_tab_bar.h" #include #include #include #include -#include -#include -#include -#include #include -#include -#include -#include +#include +#include #include #include +#include +#include +#include #include -#include -#include +#include #include -#include -#include +#include +#include #include +#include +#include namespace LtsWidgets { -LtsTabWidget::LtsTabWidget(QWidget* parent, bool isSecondary) - : QTabWidget(parent), m_tabbar(nullptr), m_hasSubTabs(false), m_isSecondary(isSecondary), - m_mainSplitterState(QByteArray()) +LtsTabWidget::LtsTabWidget(QWidget *parent, bool isSecondary) + : QTabWidget(parent) + , m_tabbar(nullptr) + , m_hasSubTabs(false) + , m_isSecondary(isSecondary) + , m_mainSplitterState(QByteArray()) { - setDocumentMode(true); - setMinimumSize(200, 100); - setSizePolicy(QSizePolicy::Expanding, QSizePolicy::MinimumExpanding); + setDocumentMode(true); + setMinimumSize(200, 100); + setSizePolicy(QSizePolicy::Expanding, QSizePolicy::MinimumExpanding); - LtsTabBar* tabBar = new LtsTabBar(isSecondary, this); - setTabBar(tabBar); + LtsTabBar *tabBar = new LtsTabBar(isSecondary, this); + setTabBar(tabBar); // also sets m_tabBar - QFont currentFont = tabBar->font(); + QFont currentFont = tabBar->font(); - QFont::Capitalization c = QFont::SmallCaps; - bool bold = true; + QFont::Capitalization c = QFont::SmallCaps; // Small Capitals make it look more Rheinmetall + bool bold = true; - if (m_isSecondary) - { - c = QFont::MixedCase; - bold = false; - } + if (m_isSecondary) + { + c = QFont::MixedCase; + bold = false; + } - currentFont.setCapitalization(c); - currentFont.setBold(bold); - tabBar->setFont(currentFont); + currentFont.setCapitalization(c); + currentFont.setBold(bold); - connect(this, &LtsTabWidget::currentChanged, this, &LtsTabWidget::slotCurrentChanged); + tabBar->setFont(currentFont); - QSplitter* splitter = static_cast(parent); - if (splitter && splitter->objectName() == QStringLiteral("mainSplitter") && splitter->widget(1) == this && - !isSecondary) - { - int tabBarHeight = m_tabbar->height() * 1.33; - int tabBarWidth = 20; + connect(this, &LtsTabWidget::currentChanged, + this, &LtsTabWidget::slotCurrentChanged); - setStyleSheet(styleSheet() + QStringLiteral("QTabWidget::tab-bar {" - "left: %1px; " - "} ") - .arg(tabBarWidth)); - QPushButton* maxBtn = new QPushButton(this); - maxBtn->setObjectName(QStringLiteral("MinMaxTabButton")); - maxBtn->setText(QStringLiteral("▲\n▼")); - maxBtn->setFixedSize(tabBarWidth, tabBarHeight * 2); - maxBtn->setStyleSheet(QStringLiteral("QPushButton { " - "border-radius: 0px; " - "border: 1px solid gray; " - "} ")); - connect(maxBtn, &QPushButton::clicked, this, &LtsTabWidget::slotMaximizeButtonClicked); - } + // Adding maximize button aside the tabbar + QSplitter *splitter = static_cast(parent); + if (splitter && + splitter->objectName() == QStringLiteral("mainSplitter") && + splitter->widget(1) == this && + !isSecondary) + { + int tabBarHeight = m_tabbar->height() * 1.33; // Luckily found this factor, no clue where that comes from + int tabBarWidth = 20; + + setStyleSheet(styleSheet() + QStringLiteral("QTabWidget::tab-bar {" + "left: %1px; " + "} ").arg(tabBarWidth)); + QPushButton *maxBtn = new QPushButton(this); + maxBtn->setObjectName(QStringLiteral("MinMaxTabButton")); + maxBtn->setText(QStringLiteral("▲\n▼")); + maxBtn->setFixedSize(tabBarWidth, tabBarHeight * 2); + maxBtn->setStyleSheet(QStringLiteral("QPushButton { " + "border-radius: 0px; " + "border: 1px solid gray; " + "} ")); + connect(maxBtn, &QPushButton::clicked, this, &LtsTabWidget::slotMaximizeButtonClicked); + } } + LtsTabWidget::~LtsTabWidget() { - - clearAll(); + /* no need to delete all widgets as they are parented to this TabWidget, so they get deleted anyways + BUT all tabs have to be removed, otherwise onRemoveTab (from the tabs) is going to be called on a dead LtsTabWidget */ + clearAll(); } + void LtsTabWidget::slotCurrentChanged(int newIdx) { - if (newIdx < 0) - return; + if (newIdx < 0) + return; - QWidget* w = widget(newIdx); + QWidget *w = widget(newIdx); - if (w == nullptr) - return; + if (w == nullptr) + return; - LtsDialogHelper* dialog1 = qobject_cast(w); + LtsDialogHelper *dialog1 = qobject_cast(w); - if (dialog1 != nullptr) + if (dialog1 != nullptr) + { + LtsDialog *mainDialog = dialog1->getDialog(); + + if (mainDialog != nullptr) + emit mainDialog->signalFocused(); + + return; + } + + // the underlying tab widget might have a dialog open, which is automatically focused also + LtsTabWidget *tab = qobject_cast(w); + + if (tab != nullptr) + { + LtsDialogHelper *dialog2 = qobject_cast(tab->widget(tab->currentIndex())); + + if (dialog2 != nullptr) { - LtsDialog* mainDialog = dialog1->getDialog(); + LtsDialog *mainDialog = dialog2->getDialog(); - if (mainDialog != nullptr) - emit mainDialog->signalFocused(); + if (mainDialog != nullptr) + emit mainDialog->signalFocused(); - return; - } - - LtsTabWidget* tab = qobject_cast(w); - - if (tab != nullptr) - { - LtsDialogHelper* dialog2 = qobject_cast(tab->widget(tab->currentIndex())); - - if (dialog2 != nullptr) - { - LtsDialog* mainDialog = dialog2->getDialog(); - - if (mainDialog != nullptr) - emit mainDialog->signalFocused(); - - return; - } + return; } + } } void LtsTabWidget::slotMaximizeButtonClicked() { - LtsSplitter* splitter = static_cast(parent()); - if (splitter) + LtsSplitter *splitter = static_cast(parent()); + if (splitter) + { + if (splitter->widget(0)->height() != splitter->widget(0)->minimumHeight()) { - if (splitter->widget(0)->height() != splitter->widget(0)->minimumHeight()) - { - m_mainSplitterState = splitter->saveState(); - splitter->collapseChild(0); - } - else - { - splitter->restoreState(m_mainSplitterState); - } + m_mainSplitterState = splitter->saveState(); + splitter->collapseChild(0); } + else + { + splitter->restoreState(m_mainSplitterState); + } + } } -void LtsTabWidget::closeRequestTabWidget(LtsTabWidget* tabWidget) + +void LtsTabWidget::closeRequestTabWidget(LtsTabWidget *tabWidget) { - for (int i = 0; i < tabWidget->count(); i++) + for (int i = 0; i < tabWidget->count(); i++) + { + QWidget *w = tabWidget->widget(i); + + LtsDialogHelper *helper = qobject_cast(w); + + if (helper) { - QWidget* w = tabWidget->widget(i); + LtsDialog *dlg = qobject_cast(helper->getDialog()); - LtsDialogHelper* helper = qobject_cast(w); - - if (helper) - { - LtsDialog* dlg = qobject_cast(helper->getDialog()); - - if (dlg) - dlg->closeRequest(); - } - - LtsTabWidget* tab = qobject_cast(w); - if (tab) - closeRequestTabWidget(tab); + if (dlg) + dlg->closeRequest(); } + + LtsTabWidget *tab = qobject_cast(w); // this is a sub tab widget? + if (tab) + closeRequestTabWidget(tab); + } } + void LtsTabWidget::slotTabCloseRequested(int index) { - QWidget* w = widget(index); + QWidget *w = widget(index); - if (w == nullptr) + if (w == nullptr) + return; + + LtsDialogHelper *helper = qobject_cast(w); + + if (helper != nullptr) + { + LtsDialog *dialog = helper->getDialog(); + + if (dialog != nullptr) + { + if (dialog->isClosable()) + { + setCurrentIndex(index); + dialog->closeRequest(); return; + } - LtsDialogHelper* helper = qobject_cast(w); - - if (helper != nullptr) - { - LtsDialog* dialog = helper->getDialog(); - - if (dialog != nullptr) - { - if (dialog->isClosable()) - { - setCurrentIndex(index); - dialog->closeRequest(); - return; - } - - return; - } + return; // is an LtsDialog, but is not closable, so cancel here } + } - LtsTabWidget* tab = qobject_cast(w); + LtsTabWidget *tab = qobject_cast(w); - if (tab != nullptr) + if (tab != nullptr) + { + if (LtsTabWidget::hasUnsavedChanges(tab)) { - if (LtsTabWidget::hasUnsavedChanges(tab)) - { - LtsWidgets::Buttons buttons; - buttons.setFlag(Button::Yes, true); - buttons.setFlag(Button::Cancel, true); - QHash buttonTexts; - buttonTexts.insert(Button::Yes, tr("Discard All")); - const auto ret = LtsMessageDialog::showMessage( - this, - tr("There are dialogs with unsaved changes.
Please save or discard their changes before closing."), - tr("Unsaved changes"), Behaviour::Modal, buttons, buttonTexts); - switch (ret) - { - case Button::Yes: - tab->deleteLater(); - return; - default: - return; - } - } - else - { - - closeRequestTabWidget(tab); - } - } - w->deleteLater(); -} - -void LtsTabWidget::onCheckTabBarVisibility() -{ - - if (!m_isSecondary) - { - - if (count() < 1) - setHidden(true); + LtsWidgets::Buttons buttons; + buttons.setFlag(Button::Yes, true); + buttons.setFlag(Button::Cancel, true); + QHash buttonTexts; + buttonTexts.insert(Button::Yes, tr("Discard All")); + const auto ret = LtsMessageDialog::showMessage(this, tr("There are dialogs with unsaved changes.
Please save or discard their changes before closing."), tr("Unsaved changes"), Behaviour::Modal, buttons, buttonTexts); + switch (ret) + { + case Button::Yes: + tab->deleteLater(); + return; //The double delete might be suspended due to the delete later but safety first + default: + return; + } } else { - if (count() < 1) - deleteLater(); + //tab->deleteLater(); + closeRequestTabWidget(tab); } + } + w->deleteLater(); // closing the widget would destroy the widget, which emits the signal 'destroyed' which removes the tab that widget was on - does not work here + //onRemoveTab(w); <= TODO: reactive if deleteLater active again + // NOTE: calling close on an LtsDialog removes it automatically from the tab widget } + +void LtsTabWidget::onCheckTabBarVisibility() // if this is called directly, the call comes from THIS TabWidget +{ + // The CALL is on the Main Tab when CALLER exists (Sub Tab calls) so, no need to check for hasSubTabs + + if (!m_isSecondary) // iam NOT the secondary, iam the FIRST + { + // i dont have any children anymore, hide me! + if (count() < 1) + setHidden(true); + } + else // IAM THE SECONDARY TAB WIDGET + { + if (count() < 1) + deleteLater(); // this will delete the secondary tab widget (me), but after this. my DESTROYED will call removeTab. after calling removeTab, this method is called on the main tab widget, which hides itself if empty + } + + /*/ + * also re-show close-buttons after they were hidden (only on main tab), + * but must now be visible again (such as there is no closable dialog anymore) + * but this case is very unlikely, because a non-closable tab can't be closed, but this CAN happen... so: impl! + /*/ + + + + // TODO: impl + + + + // if (m_hasSubTabs) + // { + // LtsTabBar *tabbar = m_tabbar; + + // bool showAgain = true; + // for (int i = 0; i < tabbar->count(); i++) + // { + // if (tabbar->tabButton(i, QTabBar::RightSide)->isHidden()) // if something is still hidden, do not show again! + // { + // showAgain = false; + // break; + // } + // } + + // if (showAgain) + // m_tabbar->tabButton(currentIndex(), QTabBar::RightSide)->show(); + // } +} + + void LtsTabWidget::setSubTabsVisible(bool visible) { - if (count()) - { + if (count()) + { + // TODO: warn the dev that this is not allowed after adding tabs! + return; + } - return; - } - - m_hasSubTabs = visible; + m_hasSubTabs = visible; } -void LtsTabWidget::addTab(const QString& menuGroup, const QString& identifier, QWidget* widget, bool setClosable, - bool focusNewTab) + +void LtsTabWidget::addTab(const QString &menuGroup, const QString &identifier, QWidget *widget, + bool setClosable, bool focusNewTab) { + //qWarning() << "LtsTabWidget::addTab"; + setFocus(); + LtsTabWidget *tab = this; // keep this when m_hasSubTabs == false + QString fullName; - setFocus(); - LtsTabWidget* tab = this; - QString fullName; + // TODO: FIXME: rm! TESTING: + //widget->setParent(this); << after tests: interferes with deleted LtsTabWidget and to-be-deleted (and not delete-latered' by qt) - so onRemoveTab gets called on a dead LtsTabWidget + // END TESTING - if (m_hasSubTabs) - { - fullName = identifier; - tab = qobject_cast(m_tabMap.value(menuGroup, nullptr)); - - if (!tab) - { - - tab = new LtsTabWidget(nullptr, true); - tab->setMovable(true); - addWidget(menuGroup, tab, true, focusNewTab); - } - else - { - - tab->setHidden(false); - } - - if (focusNewTab) - setCurrentIndex(indexOf(tab)); - } - else - { - fullName = menuGroup + QLatin1Char('.') + identifier; - } - - setHidden(false); - - tab->addWidget(fullName, widget, setClosable, focusNewTab); - - if (m_hasSubTabs) - { - LtsTabBar* tabbar = tab->tabBar(); - - for (int i = 0; i < tabbar->count(); i++) - { - - if (tabbar->tabButton(i, QTabBar::RightSide)->isHidden()) - { - m_tabbar->tabButton(currentIndex(), QTabBar::RightSide)->hide(); - break; - } - } - } -} - -void LtsTabWidget::addWidget(const QString& fullName, QWidget* widget, bool setClosable, bool focusNewTab) -{ - QString theName = fullName; - - if (fullName.isEmpty()) - { - - const QString possibleCharacters( - QStringLiteral("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")); - const int randomStringLength = 24; - - QString randomString; - for (int i = 0; i < randomStringLength; i++) - { - int index = QRandomGenerator::global()->bounded(possibleCharacters.length()); - QChar nextChar = possibleCharacters.at(index); - randomString.append(nextChar); - } - - theName = randomString; - } - - widget->setObjectName(theName); - - LtsDialogHelper* helper = qobject_cast(widget); - if (helper) - helper->retranslate(); - - QString title = widget->windowTitle(); - - if (title.isEmpty()) - { - if (helper) - title = QStringLiteral("retranslate() fehlt!"); - else - title = widget->objectName(); - } - - if (helper) - { - connect(helper->getDialog(), &LtsDialog::signalHide, this, - static_cast(&LtsTabWidget::onRemoveTab), - static_cast(Qt::QueuedConnection | Qt::UniqueConnection)); - } - - connect(widget, &QWidget::destroyed, this, - static_cast(&LtsTabWidget::onRemoveTab), Qt::DirectConnection); - connect(widget, &QWidget::windowTitleChanged, this, &LtsTabWidget::slotWindowTitleChanged); - - if (helper) - { - m_tabMap.insert(theName, helper); - } - else - { - m_tabMap.insert(theName, widget); - } - - int newTabIndex = QTabWidget::addTab(widget, title); - -#ifdef LTS_DEBUG - setTabToolTip(newTabIndex, tr("DEBUG: WindowName: %1").arg(theName)); -#endif - - if (focusNewTab) - setCurrentIndex(newTabIndex); - - LtsTabBar* tabbar = qobject_cast(tabBar()); - - if (tabbar) - { - - CloseButton* closeBtn = new CloseButton(); - connect(closeBtn, &QPushButton::clicked, tabbar, &LtsTabBar::_internal_closeTab); - tabbar->setTabButton(newTabIndex, QTabBar::RightSide, closeBtn); - } - - if (!setClosable) - m_tabbar->tabButton(newTabIndex, QTabBar::RightSide)->hide(); - - if (tabbar) - tabbar->updateCloseButtonColors(); -} - -void LtsTabWidget::slotWindowTitleChanged(const QString& title) -{ - QWidget* w = qobject_cast(sender()); - - if (!w) - { - qWarning() << "LtsTabWidget: slotWindowTitleChanged failed! (not a QWidget) " << sender(); - return; - } - - int index = indexOf(w); - - if (index < 0) - { - qWarning() << "LtsTabWidget: slotWindowTitleChanged failed! (widget not found on TabBar)"; - return; - } - - QString realTitle = title; - QString readOnlyHint; - QStringList sl = title.split(QStringLiteral("- READ-ONLY")); - if (sl.size() == 2) - { - realTitle = sl.first().trimmed(); - readOnlyHint = sl.back().trimmed(); - - if (readOnlyHint.startsWith(QStringLiteral("("))) - readOnlyHint.remove(0, 1); - if (readOnlyHint.endsWith(QStringLiteral(")"))) - readOnlyHint.remove(readOnlyHint.size() - 1, 1); - - readOnlyHint = tr("Locked by: %1").arg(readOnlyHint); - } - - setTabText(index, realTitle); - - QTabBar* tabBar = this->tabBar(); - - if (!readOnlyHint.isEmpty()) - { - QLabel* readOnly = new QLabel(QStringLiteral("READ-ONLY"), this); - readOnly->setToolTip(readOnlyHint); - readOnly->setPixmap(QIcon(QStringLiteral("icon:warning.svg")).pixmap(QSize(25, 25))); - - tabBar->setTabButton(index, QTabBar::ButtonPosition::LeftSide, readOnly); - } - else - { - QWidget* readOnly = tabBar->tabButton(index, QTabBar::ButtonPosition::LeftSide); - if (readOnly) - { - - tabBar->setTabButton(index, QTabBar::ButtonPosition::LeftSide, nullptr); - readOnly->setParent(this); - delete readOnly; - } - } -} - -QWidget* LtsTabWidget::getWidget(const QString& menuGroup, const QString& identifier) -{ - LtsTabWidget* tab = this; - QString fullName; - - if (m_hasSubTabs) - { - fullName = identifier; - tab = qobject_cast(m_tabMap.value(menuGroup, nullptr)); - - if (tab == nullptr) - return nullptr; - } - else - { - fullName = menuGroup + QLatin1Char('.') + identifier; - } - - return tab->getWidget(fullName); -} - -QWidget* LtsTabWidget::getWidget(const QString& fullName) -{ - return m_tabMap.value(fullName, nullptr); -} - -bool LtsTabWidget::focusTab(const QString& menuGroup, const QString& identifier) -{ - QPointer tab = this; - QString fullName; - - if (m_hasSubTabs) - { - fullName = identifier; - tab = qobject_cast(m_tabMap.value(menuGroup, nullptr)); - - if (!tab) - { - - return false; - } - setCurrentIndex(indexOf(tab)); - } - else - fullName = menuGroup + QLatin1Char('.') + identifier; + if (m_hasSubTabs) + { + fullName = identifier; // for the widget, not for us! + tab = qobject_cast(m_tabMap.value(menuGroup, nullptr)); // get SUB tab, when existing.. wenn ein sub tab nicht existiert, existiert im main tab auch kein tab dafür.... also neuesn tab anlegen if (!tab) - return false; - - LtsSplitter* splitter = static_cast(parent()); - - QTimer::singleShot(500, this, [splitter, tab]() { - if (splitter && tab && (tab->count() >= 1) && splitter->sizes().count() && !(splitter->sizes().at(1))) - { - splitter->animate(1); - } - }); - return tab->focusWidget(fullName); -} - -bool LtsTabWidget::focusWidget(const QString& fullName) -{ - QWidget* widget = m_tabMap.value(fullName, nullptr); - - if (widget == nullptr) - return false; - - setCurrentIndex(indexOf(widget)); - widget->setFocus(); - return true; -} - -bool LtsTabWidget::removeWidget(QWidget* widget) -{ - if (nullptr == widget) - return false; - - for (auto i = m_tabMap.begin(); i != m_tabMap.end(); ++i) { - QWidget* w = i.value(); - - if (w == nullptr) - continue; - - if (w == widget) - { - m_tabMap.erase(i); - disconnect(widget, &QWidget::destroyed, this, - static_cast(&LtsTabWidget::onRemoveTab)); - return true; - } - - if (m_hasSubTabs) - { - LtsTabWidget* tab = qobject_cast(w); - if (tab != nullptr && tab->removeWidget(widget)) - { - return true; - } - } - } - - return false; -} - -void LtsTabWidget::onRemoveTab(QObject* object) -{ - if (object == nullptr) - { - qWarning() << "onRemoveTab: obj == nullptr"; - return; - } - - QWidget* w = static_cast(object); - - bool rmd = false; - for (auto i = m_tabMap.begin(); i != m_tabMap.end(); ++i) - { - if (i.value() == w) - { - m_tabMap.erase(i); - rmd = true; - break; - } - } - - if (!rmd) - { - qWarning() << "LtsTabWidget::onRemoveTab: widget to remove was not on tab map!"; - } - - int index = indexOf(w); - if (index < 0) - { - - qWarning() << "LtsTabWidget::onRemoveTab: cannot remove widget, as it was not found on the tab widget" - << (void*)w; + //qWarning() << "LtsTabWidget::addTab: there is no sub tab - creating it!"; + tab = new LtsTabWidget(nullptr, true); // create new SUB tab..! + tab->setMovable(true); + addWidget(menuGroup, tab, true /* will be checked later! */, focusNewTab); } else { - removeTab(index); + //qWarning() << "LtsTabWidget::addTab: there is already a tab!"; + tab->setHidden(false); // tab regests content, reshow (even when it's visible, that does not matter) } - onCheckTabBarVisibility(); + if (focusNewTab) + setCurrentIndex(indexOf(tab)); + } + else // do not show & use sub tabs + { + fullName = menuGroup + QLatin1Char('.') + identifier; + // addWidget does that: m_tabMap.insert(fullName, widget); // by group + ident name + } + + setHidden(false); // as there will be content, show again! + + tab->addWidget(fullName, widget, setClosable, focusNewTab); // the 'tab' ptr is either THIS tab or ONE OF this tab's subtabs + + /*/ + * check if there are sub tabs that are not closable, + * but only if this tab is the main tab! (as sub tabs have no sub tabs, only the dialogs) + /*/ + if (m_hasSubTabs) + { + LtsTabBar *tabbar = tab->tabBar(); // sub tab + + for (int i = 0; i < tabbar->count(); i++) + { + // hide close btn of main tab if even ONE tab is not closable - otherwise the main tab could close a sub-tab which is not closable + if (tabbar->tabButton(i, QTabBar::RightSide)->isHidden()) + { + /* main tab */ m_tabbar->tabButton(currentIndex(), QTabBar::RightSide)->hide(); + break; // one positive condition is enough to hide the main close-button + } + } + } } + +void LtsTabWidget::addWidget(const QString &fullName, QWidget *widget, bool setClosable, bool focusNewTab) +{ + QString theName = fullName; + + if (fullName.isEmpty()) + { + // create random name....... + const QString possibleCharacters(QStringLiteral("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")); + const int randomStringLength = 24; + + QString randomString; + for (int i = 0; i < randomStringLength; i++) + { + int index = qrand() % possibleCharacters.length(); + QChar nextChar = possibleCharacters.at(index); + randomString.append(nextChar); + } + + theName = randomString; + } + + widget->setObjectName(theName); // must match the string in the tabMap, so it can be deleted by the object's name + + LtsDialogHelper *helper = qobject_cast(widget); + if (helper) + helper->retranslate(); // properly set the window title + + QString title = widget->windowTitle(); + + if (title.isEmpty()) + { + if (helper) + title = QStringLiteral("retranslate() fehlt!"); // Da es sich heir um ein LtsDialog handelt, muss in der retranslate()-Methode des LtsDialog auch eine Uebersetzung des Titels stattfinden! + else + title = widget->objectName(); + } + + if (helper) + { + connect(helper->getDialog(), &LtsDialog::signalHide, this, static_cast(&LtsTabWidget::onRemoveTab), + static_cast(Qt::QueuedConnection | Qt::UniqueConnection)); // hide and delete tab + //qWarning() << "addWidget: was a helper widget, added hide signal"; + } + + connect(widget, &QWidget::destroyed, this, static_cast(&LtsTabWidget::onRemoveTab), Qt::DirectConnection); // as it was deleted, there was DESTROYED called, so only a remove is needed + connect(widget, &QWidget::windowTitleChanged, this, &LtsTabWidget::slotWindowTitleChanged); + + if (helper) + { + m_tabMap.insert(theName, helper); + //qWarning() << "LtsTabWidget::addWidget: added" << theName << helper << "to tab map"; + } + else + { + m_tabMap.insert(theName, widget); // as this is a sub tab, save the pure widgets by their identifier + //qWarning() << "LtsTabWidget::addWidget: added" << theName << widget << "to tab map"; + } + + int newTabIndex = QTabWidget::addTab(widget, title); // finally add widget to a new tab on the sub tab widget + +#ifdef LTS_DEBUG + setTabToolTip(newTabIndex, tr("DEBUG: WindowName: %1").arg(theName)); +#endif + + if (focusNewTab) + setCurrentIndex(newTabIndex); // .. and focus it also (if desired)! + + LtsTabBar *tabbar = qobject_cast(tabBar()); + + if (tabbar) + { + // create close btn + CloseButton *closeBtn = new CloseButton(); + connect(closeBtn, &QPushButton::clicked, tabbar, &LtsTabBar::_internal_closeTab); // because the button does not know its index ... + tabbar->setTabButton(newTabIndex, QTabBar::RightSide, closeBtn); + } + + if (!setClosable) + m_tabbar->tabButton(newTabIndex, QTabBar::RightSide)->hide(); + + if (tabbar) + tabbar->updateCloseButtonColors(); + +} + + +void LtsTabWidget::slotWindowTitleChanged(const QString &title) +{ + QWidget *w = qobject_cast(sender()); + + if (!w) + { + qWarning() << "LtsTabWidget: slotWindowTitleChanged failed! (not a QWidget) " << sender(); + return; + } + + int index = indexOf(w); + + if (index < 0) + { + qWarning() << "LtsTabWidget: slotWindowTitleChanged failed! (widget not found on TabBar)"; + return; + } + + + QString realTitle = title; + QString readOnlyHint; + QStringList sl = title.split(QStringLiteral("- READ-ONLY")); + if (sl.size() == 2) + { + realTitle = sl.first().trimmed(); + readOnlyHint = sl.back().trimmed(); + + // format: remove "(",")", prepend "Locked by: " + if (readOnlyHint.startsWith(QStringLiteral("("))) + readOnlyHint.remove(0,1); + if (readOnlyHint.endsWith(QStringLiteral(")"))) + readOnlyHint.remove(readOnlyHint.size()-1,1); + + readOnlyHint = tr("Locked by: %1").arg(readOnlyHint); + } + + setTabText(index, realTitle); + + QTabBar *tabBar = this->tabBar(); + + if (!readOnlyHint.isEmpty()) + { + QLabel *readOnly = new QLabel(QStringLiteral("READ-ONLY"), this); + readOnly->setToolTip(readOnlyHint); + readOnly->setPixmap(QIcon(QStringLiteral("icon:warning.svg")).pixmap(QSize(25, 25))); // svg -> icon -> pixmap -> scale + + tabBar->setTabButton(index, QTabBar::ButtonPosition::LeftSide, readOnly); + } else { + QWidget *readOnly = tabBar->tabButton(index, QTabBar::ButtonPosition::LeftSide); + if (readOnly) + { + // Qt docu: + // The tab bar will take ownership of the widget and so all widgets set + // here will be deleted by the tab bar when it is destroyed unless you + // separately reparent the widget *after* setting some other widget (or nullptr). + tabBar->setTabButton(index, QTabBar::ButtonPosition::LeftSide, nullptr); + readOnly->setParent(this); + delete readOnly; + } + } +} + + +QWidget *LtsTabWidget::getWidget(const QString &menuGroup, const QString &identifier) +{ + LtsTabWidget *tab = this; // keep this when m_hasSubTabs == false + QString fullName; + + if (m_hasSubTabs) + { + fullName = identifier; + tab = qobject_cast(m_tabMap.value(menuGroup, nullptr)); + + if (tab == nullptr) + return nullptr; // not found! + } + else + { + fullName = menuGroup + QLatin1Char('.') + identifier; + } + + return tab->getWidget(fullName); +} + + +QWidget *LtsTabWidget::getWidget(const QString &fullName) +{ + return m_tabMap.value(fullName, nullptr); +} + + +bool LtsTabWidget::focusTab(const QString &menuGroup, const QString &identifier) +{ + QPointer tab = this; // keep this when m_hasSubTabs == false + QString fullName; + + if (m_hasSubTabs) + { + fullName = identifier; + tab = qobject_cast(m_tabMap.value(menuGroup, nullptr)); + + if (!tab) + { + //qWarning() << "LtsTabWidget::focusTab: tab for" << menuGroup << "not found! Cannot focus."; + return false; + } + setCurrentIndex(indexOf(tab)); // set focus on main tab (e.g. detail tab widget) + } + else // no sub tabs + fullName = menuGroup + QLatin1Char('.') + identifier; + + if (!tab) + return false; + + // start animation if splitter is collapsed + LtsSplitter *splitter = static_cast(parent()); + + // Norbert Thoden, 06.11.2024 + // lambda are sometimes ugly, like here: + // opApp crashes if dialog is closed/destroyed WHILE the 500msec. + // fix: use QPointer for tab + QTimer::singleShot(500, this, [splitter, tab] (){ + // Norbert Thoden, 06.11.2024 + // What does following if mean? really hard to maintain: + if (splitter && tab && (tab->count() >= 1) && splitter->sizes().count() && !(splitter->sizes().at(1))) + { + splitter->animate(1); + } + }); + return tab->focusWidget(fullName); +} + + +bool LtsTabWidget::focusWidget(const QString &fullName) +{ + QWidget *widget = m_tabMap.value(fullName, nullptr); + + if (widget == nullptr) + return false; + + setCurrentIndex(indexOf(widget)); // set focus on sub tab (e.g. Exm => Edit) + widget->setFocus(); + return true; +} + + +bool LtsTabWidget::removeWidget(QWidget * widget) +{ + if (nullptr == widget) + return false; + + for (auto i = m_tabMap.begin(); i != m_tabMap.end(); ++i) + { + QWidget *w = i.value(); + + if (w == nullptr) + continue; + + if (w == widget) + { + m_tabMap.erase(i); + disconnect(widget, &QWidget::destroyed, this, static_cast(&LtsTabWidget::onRemoveTab)); + return true; + } + + if (m_hasSubTabs) + { + LtsTabWidget *tab = qobject_cast(w); + if (tab != nullptr && tab->removeWidget(widget)) + { + return true; + } + } + } + + return false; +} // LtsTabWidget::removeWidget(QWidget * widget) + + +void LtsTabWidget::onRemoveTab(QObject *object) +{ + if (object == nullptr) + { + qWarning() << "onRemoveTab: obj == nullptr"; + return; + } + + QWidget *w = static_cast(object); // destroyed widgets cannot be dynamically casted, but this slot is only called by widgets ! + + bool rmd = false; + for (auto i = m_tabMap.begin(); i != m_tabMap.end(); ++i) // try to remove the tab that belongs to the widget + { + if (i.value() == w) + { + m_tabMap.erase(i); + rmd = true; + break; + } + } + + if (!rmd) + { + qWarning() << "LtsTabWidget::onRemoveTab: widget to remove was not on tab map!"; + } + + int index = indexOf(w); // NOTE: calling indexOf with a dead widget - I might look into the source if it tries to afect the widget + if (index < 0) + { + // ignoring this message, as clearAll() is evil + qWarning() << "LtsTabWidget::onRemoveTab: cannot remove widget, as it was not found on the tab widget" << (void *)w; + } + else + { + removeTab(index); + } + + onCheckTabBarVisibility(); // check if this was the last tab and hide / delete me +} + + void LtsTabWidget::setActuatorTabStyle(bool enable) { - if (enable) - setTabBar(new LtsTabBar(false, this)); + if (enable) + setTabBar(new LtsTabBar(false, this)); } -LtsTabBar* LtsTabWidget::tabBar() + +LtsTabBar *LtsTabWidget::tabBar() { - return m_tabbar; + return m_tabbar; } -void LtsTabWidget::setTabBar(LtsTabBar* tabbar) + +void LtsTabWidget::setTabBar(LtsTabBar *tabbar) { - if (m_tabbar) - m_tabbar->deleteLater(); + if (m_tabbar) + m_tabbar->deleteLater(); - QFont currentFont = font(); - currentFont.setCapitalization(QFont::SmallCaps); - currentFont.setBold(true); + // Small Capitals make it look more Rheinmetall + QFont currentFont = font(); + currentFont.setCapitalization(QFont::SmallCaps); + currentFont.setBold(true); - tabbar->setFont(currentFont); - connect(tabbar, &LtsTabBar::tabCloseRequested, this, &LtsTabWidget::slotTabCloseRequested); + tabbar->setFont(currentFont); + connect(tabbar, &LtsTabBar::tabCloseRequested, this, &LtsTabWidget::slotTabCloseRequested); - m_tabbar = tabbar; - QTabWidget::setTabBar(m_tabbar); + m_tabbar = tabbar; + QTabWidget::setTabBar(m_tabbar); } + void LtsTabWidget::clearAll() { + // FIXME: there is no other way to get all widgets in a tab widget (?), so this code must be used. But removing a tab, then deleting it, causes the widget to call "onRemoveTab" on signal DESTROYED, which then says that the widget was not found (as it was removed here before..) - for (int i = 0; i < count(); i++) - { - QWidget* w = widget(i); + for (int i = 0; i < count(); i++) + { + QWidget *w = widget(i); - if (w == nullptr) - continue; + if (w == nullptr) + continue; - disconnect(w, &QWidget::destroyed, this, - static_cast(&LtsTabWidget::onRemoveTab)); + disconnect(w, &QWidget::destroyed, this, static_cast(&LtsTabWidget::onRemoveTab)); // otherwise call to already deleted LtsTabWidget - w->deleteLater(); - } + w->deleteLater(); // queue deletion + } - clear(); + clear(); // remove (but don't delete) all tabs now. If not, destroyed signal is queued for a dead LtsTabWidget } + void LtsTabWidget::aboutToClose() { - for (int i = 0; i < count(); i++) + for (int i = 0; i < count(); i++) + { + if (m_hasSubTabs) { - if (m_hasSubTabs) - { - LtsTabWidget* tab = qobject_cast(widget(i)); - tab->aboutToClose(); - } - else - { - LtsDialogHelper* helper = qobject_cast(widget(i)); - - if (helper == nullptr) - continue; - - LtsDialog* dialog = qobject_cast(helper->getDialog()); - - if (dialog == nullptr) - continue; - - dialog->aboutToClose(); - } + LtsTabWidget *tab = qobject_cast(widget(i)); + tab->aboutToClose(); } + else + { + LtsDialogHelper *helper = qobject_cast(widget(i)); + + if (helper == nullptr) + continue; + + LtsDialog *dialog = qobject_cast(helper->getDialog()); + + if (dialog == nullptr) + continue; + + dialog->aboutToClose(); + } + } } -bool LtsTabWidget::hasUnsavedChanges(LtsTabWidget* tabWidget) + +bool LtsTabWidget::hasUnsavedChanges(LtsTabWidget *tabWidget) { - for (int i = 0; i < tabWidget->count(); i++) + for (int i = 0; i < tabWidget->count(); i++) + { + QWidget *w = tabWidget->widget(i); + + LtsDialogHelper *helper = qobject_cast(w); + + if (helper) { - QWidget* w = tabWidget->widget(i); + LtsDialog *dlg = qobject_cast(helper->getDialog()); - LtsDialogHelper* helper = qobject_cast(w); + if (dlg != nullptr) + { + //qWarning() << "CHECKING DLG '"<windowTitle()<<"' / '"<objectName()<<"'"; - if (helper) + if (dlg->hasUnsavedChanges()) { - LtsDialog* dlg = qobject_cast(helper->getDialog()); + int dlgIndex = tabWidget->indexOf(helper); + if (dlgIndex != -1) + tabWidget->setCurrentIndex(dlgIndex); - if (dlg != nullptr) - { - - if (dlg->hasUnsavedChanges()) - { - int dlgIndex = tabWidget->indexOf(helper); - if (dlgIndex != -1) - tabWidget->setCurrentIndex(dlgIndex); - - return true; - } - } - } - - LtsTabWidget* tab = qobject_cast(w); - - if (tab) - { - - bool _hasUnsavedChanges = hasUnsavedChanges(tab); - if (_hasUnsavedChanges) - { - int tabIndex = tabWidget->indexOf(tab); - if (tabIndex != -1) - tabWidget->setCurrentIndex(tabIndex); - - return true; - } + //dlg->closeRequest(); // tell the operator .. + return true; // .. and stop here! } + } } - return false; + LtsTabWidget *tab = qobject_cast(w); // this is a sub tab widget? + + if (tab) + { + //qWarning() << "CHECKING NEXT TAB..."; + + bool _hasUnsavedChanges = hasUnsavedChanges(tab); // recursive + if (_hasUnsavedChanges) + { + int tabIndex = tabWidget->indexOf(tab); + if (tabIndex != -1) + tabWidget->setCurrentIndex(tabIndex); + + return true; // only abort if all tested and one of them has changes + } + } + + /*if (!dlg && !tab) + { + qWarning() << "This thing was a "<metaObject()->className()<<".. '"<objectName()<<"' / '"<windowTitle()<<"'"; + }*/ + } + + return false; // has no changes if it comes until here } -void CloseButton::paintEvent(QPaintEvent*) + + + + +// Close Button: +void CloseButton::paintEvent(QPaintEvent *) { - QPainter p(this); + QPainter p(this); - p.save(); - p.setPen(QPen(QColor(m_fontColor), 1.5)); - p.setRenderHint(QPainter::Antialiasing); + p.save(); + p.setPen(QPen(QColor(m_fontColor), 1.5)); // line + p.setRenderHint(QPainter::Antialiasing); - p.drawLine(line()); + // V-Line + p.drawLine(line()); - p.setPen(QPen(QColor(m_fontColor), 2.5)); + // X / cross + p.setPen(QPen(QColor(m_fontColor), 2.5)); // bold cross - QRectF c = cross(); + QRectF c = cross(); - p.drawLine(c.topLeft(), c.bottomRight()); - p.drawLine(c.bottomLeft(), c.topRight()); + p.drawLine(c.topLeft(), c.bottomRight()); + p.drawLine(c.bottomLeft(), c.topRight()); - p.restore(); + p.restore(); } + QLineF CloseButton::line() const { - qreal forceBlur = 0.001; - qreal lineStart = height() * (0.25 / 2) + forceBlur; - qreal lineSize = height() - lineStart; + qreal forceBlur = 0.001; + qreal lineStart = height() * (0.25 / 2) + forceBlur; // starts at the first half of the margin (see sizeHint) + qreal lineSize = height() - lineStart; - return QLineF(QPointF(lineStart, lineStart), QPointF(lineStart, lineSize)); + return QLineF(QPointF(lineStart, lineStart), QPointF(lineStart, lineSize)); } + QRectF CloseButton::cross() const { - QLineF l = line(); + QLineF l = line(); - qreal lineLeft = l.x1(); - qreal forceBlur = 0.001; + qreal lineLeft = l.x1(); + qreal forceBlur = 0.001; - qreal crossStartX = lineLeft * 3; - qreal crossStartY = lineLeft * 2; - qreal crossEndX = width(); - crossEndX -= crossEndX * 0.15 + forceBlur; - qreal crossEndY = height() - crossStartY; + qreal crossStartX = lineLeft * 3; + qreal crossStartY = lineLeft * 2; + qreal crossEndX = width(); crossEndX -= crossEndX * 0.15 + forceBlur; + qreal crossEndY = height() - crossStartY; - return QRectF(QPointF(crossStartX, crossStartY), QPointF(crossEndX, crossEndY)); + return QRectF(QPointF(crossStartX, crossStartY), QPointF(crossEndX, crossEndY)); } + QSize CloseButton::sizeHint() const { - QFontMetrics fm(QApplication::font()); - int fontHeight = fm.height(); + QFontMetrics fm (QApplication::font()); + int fontHeight = fm.height(); - int fontHeightQuarter = fontHeight * 0.25; - int finalSize = fontHeight + fontHeightQuarter; + int fontHeightQuarter = fontHeight * 0.25; + int finalSize = fontHeight + fontHeightQuarter; // add a quarter more space, for looks! #ifdef TABLET_MODE - finalSize = finalSize * 1.5; + finalSize = finalSize*1.5; #endif - return QSize(finalSize, finalSize); + return QSize(finalSize/* + fontHeightQuarter*/, finalSize); } -void CloseButton::mousePressEvent(QMouseEvent* e) + +void CloseButton::mousePressEvent(QMouseEvent *e) { + e->ignore(); + m_isPressed = true; // dunno if qt does this automatically +} + + +void CloseButton::mouseReleaseEvent(QMouseEvent *e) // only accept a click directly on the X / cross +{ + bool isPressed = m_isPressed; + m_isPressed = false; + + if (!isPressed) + { e->ignore(); - m_isPressed = true; -} + return; + } -void CloseButton::mouseReleaseEvent(QMouseEvent* e) -{ - bool isPressed = m_isPressed; - m_isPressed = false; + QRectF c = cross(); + QRect adjusted = QRect(QPoint(floor(c.x()), floor(c.y())), QPoint(ceil(c.right()), ceil(c.bottom() +1 /* hack */))); // be more tolerant - if (!isPressed) - { - e->ignore(); - return; - } + if (!adjusted.contains(e->localPos().toPoint())) + { + //qWarning() << "NO! release - event:" << e->localPos() << "cross:" << cross(); + e->ignore(); + return; + } - QRectF c = cross(); - QRect adjusted = QRect(QPoint(floor(c.x()), floor(c.y())), QPoint(ceil(c.right()), ceil(c.bottom() + 1))); - - if (!adjusted.contains(e->localPos().toPoint())) - { - - e->ignore(); - return; - } - - e->accept(); - emit clicked(); + //qWarning() << "YES! release - event:" << e->localPos() << "cross:" << cross(); + e->accept(); + emit clicked(); } } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_widget.h index f4da40d2b..b0d2e7304 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_widget.h @@ -1,113 +1,244 @@ - +/** +* @RDE_HEADER@ +* TabWidget for new EXCON +* $Id$ +* $HeadURL$ +* $Author$ +*/ #pragma once + #include "lts_base.h" #include "lts_widgets_export.h" -#include -#include -#include #include +#include +#include + namespace LtsWidgets { class LtsDialogHelper; class LtsTabBar; +/** + * @brief The LtsTabWidget class provides a QTabWidget with enhanced functionality for the Lts Layout System. + * This TabWidget can either be a..: + * + * > Master Tab Widget: is the MenuGroup TabWidget (sums up all LtsDialogs which are in the same MenuGroup), contains Tabs to Secondary Identifier TabWidgets + * ..or.. + * > Secondary Tab Widget: is the Identifier TabWidget, contains all LtsDialogs + * + */ class LTSWIDGETS_EXPORT LtsTabWidget : public QTabWidget { - Q_OBJECT - public: - explicit LtsTabWidget(QWidget* parent = nullptr, bool isSecondary = false); - ~LtsTabWidget(); + Q_OBJECT +public: + /** + * @brief LtsTabWidget + * @param parent + * @param isSecondary true if this is a Secondary TabWidget, false if this is a Master TabWidget + */ + explicit LtsTabWidget(QWidget *parent = nullptr, bool isSecondary = false); // isSecondary var = last => easy for usage in ui file + ~LtsTabWidget(); - void setActuatorTabStyle(bool enable); + /** + * @brief setActuatorTabStyle decorates the TabBar in a different way (once enabled, it cannot be disabled anymore). + * @param enable true to change TabBar decoration. false does nothing. + */ + void setActuatorTabStyle(bool enable); - void clearAll(); + /** + * @brief clearAll removes all Widgets (usually LtsDialogs) from this TabWidget and deletes them. + */ + void clearAll(); - void aboutToClose(); - LtsTabBar* tabBar(); + void aboutToClose(); - void setTabBar(LtsTabBar* tabbar); + /** + * @brief tabBar returns the used LtsTabBar + * @return + */ + LtsTabBar *tabBar(); - bool focusTab(const QString& menuGroup, const QString& identifier); + /** + * @brief setTabBar sets the TabBar to an LtsTabBar + * @param tabbar the LtsTabBar to replace the current TabBar with. + */ + void setTabBar(LtsTabBar *tabbar); - void setSubTabsVisible(bool visible); + /** + * @brief focusTab focuses the LtsDialog, identified by the Menu and its Identifier, by setting the current Index to the requested LtsDialog's index. + * @param menuGroup the menu group of the widget + * @param identifier the identifier of the widget + * @return true if found & focused - false if not found (so not focused) + */ + bool focusTab(const QString &menuGroup, const QString &identifier); - QWidget* getWidget(const QString& menuGroup, const QString& identifier); + /** + * @brief setSubTabsVisible allows this TabWidget to have SubTabs, so that this TabWidget contains all Tabs refered as the MenuGroups, and the SubTabs + * refer to the Identifiers of the LtsDialogs. + * DO NOT call this AFTER adding tabs !! + * @param visible true if this TabWidget has SubTabs - false if not. + */ + void setSubTabsVisible(bool visible); - static bool hasUnsavedChanges(LtsTabWidget* tabWidget); + /** + * @brief getWidget returns the Widget (LtsDialogHelper !!) refered by its MenuGroup and its Identifier from this TabWidget. + * @param menuGroup the menu group of the Widget. + * @param identifier the identifier of the Widget. + * @return the Widget if found, nullptr if not found. (LtsDialogHelper) - To get the dialog: ->getDialog() + */ + QWidget *getWidget(const QString &menuGroup, const QString &identifier); - signals: + /** + * @brief hasUnsavedChanges checks if there are open Dialogs which have unsaved changes and tells the operator if there are + * unsaved changes by the "There are unsaved changes"-Dialog. This method only checks until one unsaved dialog was found. + * @param tabWidget The Tab Widget to check if it contains unsaved Dialogs. + * @return true if there are unsaved changes, false if there are no unsaved Dialogs. + */ + static bool hasUnsavedChanges(LtsTabWidget *tabWidget); - void signalCheckTabBarVisibility(); - public slots: - void addTab(const QString& menuGroup, const QString& identifier, QWidget* widget, bool setClosable = true, - bool focusNewTab = true); +signals: + /** + * @brief TODO: DOC ! ! signalCheckTabBarVisibility is emitted when it is necessary to check if this TabWidget can be hidden (e.g. when the last Widget + * on this TabWidget is closed, which makes this TabWidget useless and can be hidden). + */ + void signalCheckTabBarVisibility(); - bool removeWidget(QWidget* widget); - private slots: +public slots: + /** + Do not use. - void onRemoveTab(QObject* object); - void onCheckTabBarVisibility(); + * @brief addTab adds a Tab to this TabWidget (is called by the 'addTab'-signal of your LtsDialog) + * @param menuGroup the menu group in which this widget should be sorted into. + * @param identifier the identifier to check if 1. there already is a widget with this Identifier in this group (so this widget + * will not be added (because duplicate)), 2. to make this widget findable when calling e.g. getWidget. + * @param dialog helper (which contains the LtsDialog) OLD: the LtsDialog (LtsDialog, as its addTab-signal is automatically connected to this addTab-slot in this method) to + * be added to this TabWidget + * @param setClosable true if this new Tab / Widget should be able to be closed by the user via the Close-Button on the Tab itself ONLY! (does not + * prevent this new Tab to be closed by an Close-Button located on this Widget. + */ + void addTab(const QString &menuGroup, const QString &identifier, QWidget *widget, + bool setClosable = true, bool focusNewTab = true); - void slotTabCloseRequested(int index); + /** + * @brief removeWidget removes a Tab from this TabWidget if it's under control of this TabWidget. + * @param widget Tab to remove from TabWidget + * @return In case of success true, in other case false + */ + bool removeWidget(QWidget * widget); - void slotCurrentChanged(int newIdx); +private slots: + /** + * @brief onDeleteTab TODO! rm & free + * @param index + */ + //void onDeleteTab(int index); - void slotMaximizeButtonClicked(); + /** + TODO: update + * @brief onCloseTab removes the Widget (usually LtsDialogs), identified by its index, from this TabWidget and deletes them. + * @param index the index to identify the Widget to be removed + */ + //void onRemoveTab(int index); - private: - void addWidget(const QString& fullName, QWidget* widget, bool setClosable, bool focusNewTab = true); + /** + TODO: update + * @brief onCloseTab removes the Widget (usually LtsDialogs), identified by its Pointer, from this TabWidget and deletes them. + * @param object the pointer to identify the Widget to be removed + */ + void onRemoveTab(QObject *object); - QWidget* getWidget(const QString& fullName); + /** + * @brief onCheckTabBarVisibility checks if this TabWidget can be hidden (e.g. when the last Widget + * on this TabWidget is closed, which makes this TabWidget useless and can be hidden). + */ + void onCheckTabBarVisibility(); - bool focusWidget(const QString& fullName); + /** + * @brief slotTabCloseRequested makes a close request of an LtsDialog, identified by its index, by calling the + * reject-method (see LtsDialog::reject). If the Widget on this index is not an LtsDialog, the close-method of the QWidget-class + * is called. + * @param index the index to identify the Widget to be closed + */ + void slotTabCloseRequested(int index); - void slotWindowTitleChanged(const QString& title); + void slotCurrentChanged(int newIdx); - void closeRequestTabWidget(LtsTabWidget* tabWidget); + void slotMaximizeButtonClicked(); - QPoint startPos; - LtsTabBar* m_tabbar = nullptr; - QPalette m_palette; +private: + /** + * @brief addWidget adds a widget to this TabWidget (no matter if this is an Master-/SubTab) - is called by the addTab-method. ONLY ADD LTSDIALOG !! + * @param fullName MenuGroup + Identifier, as there is no need to differ between Master-/SubTab + * @param widget the widget to add + * @param setClosable true if this new Tab / Widget should be able to be closed by the user via the Close-Button on the Tab itself ONLY! (does not + * prevent this new Tab to be closed by an Close-Button located on this Widget. + */ + void addWidget(const QString &fullName, QWidget *widget, bool setClosable, bool focusNewTab = true); // only called by addTab (means that the called class is a sub tab widget) - QMap m_tabMap; + /** + * @brief getWidget same as getWidget(MenuGroup, Identifier), but only for MasterTabs, as the Tabs are saved with the full name in the Master Tab (MenuGroup + Ident) + * @param fullName MenuGroup + Ident + * @return widget if found, nullptr if not + */ + QWidget *getWidget(const QString &fullName); - bool m_hasSubTabs; - bool m_isSecondary; + /** + * @brief focusWidget only called by focusTab (means that the called class is a sub tab widget) + * @param fullName Menu + Ident + * @return true = found & focused, false = not found, not focused + */ + bool focusWidget(const QString &fullName); - QByteArray m_mainSplitterState; + /** + * @brief slotWindowTitleChanged is called by an LtsDialog(Helper) to sync the Dialog's Title with the Title in the TabBar + * @param title the title which was set and has to be set in the TabBar + */ + void slotWindowTitleChanged(const QString &title); + + void closeRequestTabWidget(LtsTabWidget *tabWidget); + + QPoint startPos; + LtsTabBar *m_tabbar = nullptr; + QPalette m_palette; + + // when this tab contains a second tab.. + /* TODO: use LtsTranslatableIdentifier instead of QString */ QMap m_tabMap; // QWidget because a TabWidget can contain more TabWidgets (Main Tab contains Sub Tabs) and a TabWidget can contain LtsDialogs (Sub Tab contains Dialogs) + + // FIXME: difference ?????? + bool m_hasSubTabs; + bool m_isSecondary; + + QByteArray m_mainSplitterState; }; + class CloseButton : public QAbstractButton { - Q_OBJECT + Q_OBJECT - public: - using QAbstractButton::QAbstractButton; +public: + using QAbstractButton::QAbstractButton; - void setFontColor(const QColor& fontColor) - { - m_fontColor = fontColor; - } + void setFontColor(const QColor &fontColor) { m_fontColor = fontColor; } + QRectF cross() const; + QLineF line() const; - QRectF cross() const; - QLineF line() const; +protected: + void mousePressEvent(QMouseEvent *e) override; + void mouseReleaseEvent(QMouseEvent *e) override; + void paintEvent(QPaintEvent *e) override; + QSize sizeHint() const override; - protected: - void mousePressEvent(QMouseEvent* e) override; - void mouseReleaseEvent(QMouseEvent* e) override; - void paintEvent(QPaintEvent* e) override; - QSize sizeHint() const override; - - private: - QColor m_fontColor; - bool m_isPressed = false; +private: + QColor m_fontColor; + bool m_isPressed = false; }; } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_edit_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_edit_dialog.cpp index fe5998018..cfc206e85 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_edit_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_edit_dialog.cpp @@ -1,7 +1,13 @@ - +/** +* @RDE_HEADER@ +* LtsTextEditDialog +* $Id$ +* $HeadURL$ +* $Author$ +* Created by Norbert Thoden, SLSE, 2023-06-14 +*/ #include "lts_text_edit_dialog.h" - #include "lts_text_editor.h" #include @@ -15,116 +21,123 @@ namespace LtsWidgets { -LtsTextEditDialog::LtsTextEditDialog(QWidget* parent) - : LtsDialog(parent, ButtonCombination::OkApplyCancel) -#ifdef USE_TEXT_EDITOR - , - m_textEditor(new LtsTextEditor(this)) -#else - , - m_textEditor2(new LtsTextEditor2(this)) -#endif +LtsTextEditDialog::LtsTextEditDialog(QWidget *parent) + : LtsDialog(parent, ButtonCombination::OkApplyCancel) + #ifdef USE_TEXT_EDITOR + , m_textEditor(new LtsTextEditor(this)) + #else + , m_textEditor2(new LtsTextEditor2(this)) + #endif { - QHBoxLayout* hbox = new QHBoxLayout(this); + QHBoxLayout *hbox = new QHBoxLayout(this); #ifdef USE_TEXT_EDITOR - hbox->addWidget(m_textEditor); - connect(m_textEditor->textEdit(), &QTextEdit::textChanged, this, - [this]() { emit signalTextChanged(this->getHtmlText()); }); - connect(m_textEditor, &LtsTextEditor::backgroundColorChanged, this, &LtsTextEditDialog::onBackgroundColorChanged); + hbox->addWidget(m_textEditor); + connect(m_textEditor->textEdit(), &QTextEdit::textChanged, this, [this]() { + emit signalTextChanged(this->getHtmlText()); + }); + connect(m_textEditor, &LtsTextEditor::backgroundColorChanged, + this, &LtsTextEditDialog::onBackgroundColorChanged); #else - hbox->addWidget(m_textEditor2); - connect(m_textEditor2->textEdit(), &QTextEdit::textChanged, this, - [this]() { emit signalTextChanged(this->getHtmlText()); }); - connect(m_textEditor2, &LtsTextEditor2::backgroundColorChanged, this, &LtsTextEditDialog::onBackgroundColorChanged); + hbox->addWidget(m_textEditor2); + connect(m_textEditor2->textEdit(), &QTextEdit::textChanged, this, [this]() { + emit signalTextChanged(this->getHtmlText()); + }); + connect(m_textEditor2, &LtsTextEditor2::backgroundColorChanged, + this, &LtsTextEditDialog::onBackgroundColorChanged); #endif - enableBackgroundColor(false); + + enableBackgroundColor(false); } -LtsTextEditDialog::~LtsTextEditDialog() {} +LtsTextEditDialog::~LtsTextEditDialog() +{} void LtsTextEditDialog::enableBackgroundColor(bool onOff) { #ifdef USE_TEXT_EDITOR - m_textEditor->enableBackgroundColor(onOff); + m_textEditor->enableBackgroundColor(onOff); #else - m_textEditor2->enableBackgroundColor(onOff); + m_textEditor2->enableBackgroundColor(onOff); #endif } +/////////////////////////////////////////////////////////////////////////////// +// PUBLIC + void LtsTextEditDialog::retranslate() { - - QString name = tr("Edit Text"); - translate(name); + // in correct translation context + QString name = tr("Edit Text"); + translate(name); } bool LtsTextEditDialog::apply() { #ifdef USE_TEXT_EDITOR - QString textHtml = m_textEditor->textEdit()->document()->toHtml(); - const QString backGroundColor = - QLatin1String("background-color:'%1'; ").arg(m_textEditor->backgroundColor().name()); + QString textHtml = m_textEditor->textEdit()->document()->toHtml(); + const QString backGroundColor = QLatin1String("background-color:'%1'; ").arg(m_textEditor->backgroundColor().name()); #else - QString textHtml = m_textEditor2->textEdit()->document()->toHtml(); - const QString backGroundColor = - QLatin1String("background-color:'%1'; ").arg(m_textEditor2->backgroundColor().name()); + QString textHtml = m_textEditor2->textEdit()->document()->toHtml(); + const QString backGroundColor = QLatin1String("background-color:'%1'; ").arg(m_textEditor2->backgroundColor().name()); #endif - emit signalTextApplied(textHtml); + emit signalTextApplied(textHtml); - const int insertBackGroundColorIndex = textHtml.indexOf(QLatin1String("font-family")); - textHtml.insert(insertBackGroundColorIndex, backGroundColor); + const int insertBackGroundColorIndex = textHtml.indexOf(QLatin1String("font-family")); + textHtml.insert(insertBackGroundColorIndex, backGroundColor); - emit signalTextAppliedWithBackGroundColor(textHtml); + emit signalTextAppliedWithBackGroundColor(textHtml); - return true; + return true; } -void LtsTextEditDialog::setHtml(const QString& htmlText) +void LtsTextEditDialog::setHtml(const QString &htmlText) { - + // QTextEdit::textChanged is add via LtsDialog::addChangesMadeSignal() + // so setHtml will in turn call slotChangesMade() #ifdef USE_TEXT_EDITOR - m_textEditor->textEdit()->document()->setHtml(htmlText); + m_textEditor->textEdit()->document()->setHtml(htmlText); #else - m_textEditor2->textEdit()->document()->setHtml(htmlText); + m_textEditor2->textEdit()->document()->setHtml(htmlText); #endif } QString LtsTextEditDialog::getHtmlText() const { #ifdef USE_TEXT_EDITOR - if (m_textEditor && m_textEditor->textEdit() && m_textEditor->textEdit()->document()) - return m_textEditor->textEdit()->document()->toHtml(); + if(m_textEditor && m_textEditor->textEdit() && m_textEditor->textEdit()->document()) + return m_textEditor->textEdit()->document()->toHtml(); #else - if (m_textEditor2 && m_textEditor2->textEdit() && m_textEditor2->textEdit()->document()) - return m_textEditor2->textEdit()->document()->toHtml(); + if(m_textEditor2 && m_textEditor2->textEdit() && m_textEditor2->textEdit()->document()) + return m_textEditor2->textEdit()->document()->toHtml(); #endif - return {}; + return {}; } -void LtsTextEditDialog::setInitialBackgroundColor(const QColor& bgColor) +void LtsTextEditDialog::setInitialBackgroundColor(const QColor &bgColor) { #ifdef USE_TEXT_EDITOR - if (m_textEditor) - m_textEditor->setInitialBackgroundColor(bgColor); + if (m_textEditor) + m_textEditor->setInitialBackgroundColor(bgColor); #else - if (m_textEditor2) - m_textEditor2->setInitialBackgroundColor(bgColor); + if (m_textEditor2) + m_textEditor2->setInitialBackgroundColor(bgColor); #endif } void LtsTextEditDialog::dialogCanceled() { - emit signalDialogCanceled(); - BaseClass::dialogCanceled(); + emit signalDialogCanceled(); + BaseClass::dialogCanceled(); } -void LtsTextEditDialog::onBackgroundColorChanged(const QColor& backgroundColor) +void LtsTextEditDialog::onBackgroundColorChanged(const QColor &backgroundColor) { - slotChangesMade(); - emit signalBackgroundColorChanged(backgroundColor); + slotChangesMade(); + emit signalBackgroundColorChanged(backgroundColor); } } // namespace LtsWidgets + diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_edit_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_edit_dialog.h index ea97d3784..b1fb9a232 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_edit_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_edit_dialog.h @@ -1,49 +1,61 @@ - - +/** +* @RDE_HEADER@ +* LtsTextEditDialog +* $Id$ +* $HeadURL$ +* $Author$ +* Created by Norbert Thoden, SLSE, 2023-06-14 +*/ #pragma once + #include #include #include -#include + namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsTextEditDialog : public LtsWidgets::LtsDialog { - Q_OBJECT + Q_OBJECT - using BaseClass = LtsWidgets::LtsDialog; + using BaseClass = LtsWidgets::LtsDialog; - public: - LtsTextEditDialog(QWidget* parent = nullptr); - ~LtsTextEditDialog(); +public: + LtsTextEditDialog(QWidget *parent = nullptr); + ~LtsTextEditDialog(); - void enableBackgroundColor(bool onOff); - void setInitialBackgroundColor(const QColor& bgColor); + void enableBackgroundColor(bool onOff); + void setInitialBackgroundColor(const QColor &bgColor); - void retranslate() override; - bool apply() override; - void setHtml(const QString& htmlText); - QString getHtmlText() const; + void retranslate() override; + bool apply() override; + void setHtml(const QString &htmlText); + QString getHtmlText() const; - protected: - void dialogCanceled() override; +protected: + void dialogCanceled() override; - private: - LtsTextEditor* m_textEditor{nullptr}; - LtsTextEditor2* m_textEditor2{nullptr}; +private: + LtsTextEditor *m_textEditor{nullptr}; + LtsTextEditor2 *m_textEditor2{nullptr}; - protected Q_SLOTS: - void onBackgroundColorChanged(const QColor& backgroundColor); - Q_SIGNALS: - void signalTextChanged(const QString& htmlText); - void signalTextApplied(const QString& htmlText); - void signalTextAppliedWithBackGroundColor(const QString& htmlText); - void signalBackgroundColorChanged(const QColor& bgColor); - void signalDialogApplied(); - void signalDialogCanceled(); +protected Q_SLOTS: + void onBackgroundColorChanged(const QColor &backgroundColor); + +Q_SIGNALS: + void signalTextChanged(const QString &htmlText); + void signalTextApplied(const QString &htmlText); + void signalTextAppliedWithBackGroundColor(const QString &htmlText); + void signalBackgroundColorChanged(const QColor &bgColor); + void signalDialogApplied(); + void signalDialogCanceled(); + }; -} // namespace LtsWidgets +} // namespace FileManagement + + + diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor.cpp index 57d4d827d..e2559485b 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor.cpp @@ -2,351 +2,390 @@ #include "ui_lts_text_editor.h" +#include +#include #include #include -#include -#include -#include -#include #include -#include +#include #include +#include + +#include namespace LtsWidgets { -LtsTextEditor::LtsTextEditor(QWidget* parent) : QWidget(parent), m_ui(new Ui::LtsTextEditor) +LtsTextEditor::LtsTextEditor(QWidget *parent) + : QWidget(parent) + , m_ui(new Ui::LtsTextEditor) { - m_ui->setupUi(this); + m_ui->setupUi(this); - connect(m_ui->textEdit, &QTextEdit::currentCharFormatChanged, this, &LtsTextEditor::slotCurrentCharFormatChanged); - connect(m_ui->textEdit, &QTextEdit::cursorPositionChanged, this, &LtsTextEditor::slotAlignmentChanged); + connect(m_ui->textEdit, &QTextEdit::currentCharFormatChanged, + this, &LtsTextEditor::slotCurrentCharFormatChanged); + connect(m_ui->textEdit, &QTextEdit::cursorPositionChanged, + this, &LtsTextEditor::slotAlignmentChanged); - connect(m_ui->textEdit->document(), &QTextDocument::undoAvailable, m_ui->pbUndo, &QToolButton::setEnabled); - connect(m_ui->textEdit->document(), &QTextDocument::redoAvailable, m_ui->pbRedo, &QToolButton::setEnabled); + connect(m_ui->textEdit->document(), &QTextDocument::undoAvailable, + m_ui->pbUndo, &QToolButton::setEnabled); + connect(m_ui->textEdit->document(), &QTextDocument::redoAvailable, + m_ui->pbRedo, &QToolButton::setEnabled); - m_ui->pbUndo->setEnabled(m_ui->textEdit->document()->isUndoAvailable()); - m_ui->pbRedo->setEnabled(m_ui->textEdit->document()->isRedoAvailable()); + m_ui->pbUndo->setEnabled(m_ui->textEdit->document()->isUndoAvailable()); + m_ui->pbRedo->setEnabled(m_ui->textEdit->document()->isRedoAvailable()); - connect(QApplication::clipboard(), &QClipboard::dataChanged, this, &LtsTextEditor::slotClipboardDataChanged); + connect(QApplication::clipboard(), &QClipboard::dataChanged, + this, &LtsTextEditor::slotClipboardDataChanged); - connect(m_ui->pbCut, &QToolButton::clicked, m_ui->textEdit, &QTextEdit::cut); - connect(m_ui->pbCopy, &QToolButton::clicked, m_ui->textEdit, &QTextEdit::copy); - connect(m_ui->pbPaste, &QToolButton::clicked, m_ui->textEdit, &QTextEdit::paste); - connect(m_ui->pbUndo, &QToolButton::clicked, m_ui->textEdit, &QTextEdit::undo); - connect(m_ui->pbRedo, &QToolButton::clicked, m_ui->textEdit, &QTextEdit::redo); + connect(m_ui->pbCut, &QToolButton::clicked, + m_ui->textEdit, &QTextEdit::cut); + connect(m_ui->pbCopy, &QToolButton::clicked, + m_ui->textEdit, &QTextEdit::copy); + connect(m_ui->pbPaste, &QToolButton::clicked, + m_ui->textEdit, &QTextEdit::paste); - connect(m_ui->pbBold, &QToolButton::clicked, this, &LtsTextEditor::slotTextBold); - connect(m_ui->pbItalic, &QToolButton::clicked, this, &LtsTextEditor::slotTextItalic); - connect(m_ui->pbUnderline, &QToolButton::clicked, this, &LtsTextEditor::slotTextUnderline); + connect(m_ui->pbUndo, &QToolButton::clicked, + m_ui->textEdit, &QTextEdit::undo); + connect(m_ui->pbRedo, &QToolButton::clicked, + m_ui->textEdit, &QTextEdit::redo); - connect(m_ui->pbTextColor, &QToolButton::clicked, this, &LtsTextEditor::slotTextColor); - connect(m_ui->pbBackgroundColor, &QToolButton::clicked, this, &LtsTextEditor::slotBackgroundColor); + connect(m_ui->pbBold, &QToolButton::clicked, + this, &LtsTextEditor::slotTextBold); + connect(m_ui->pbItalic, &QToolButton::clicked, + this, &LtsTextEditor::slotTextItalic); + connect(m_ui->pbUnderline, &QToolButton::clicked, + this, &LtsTextEditor::slotTextUnderline); - connect(m_ui->pbAlignLeft, &QToolButton::toggled, this, &LtsTextEditor::slotTextAlign); - connect(m_ui->pbAlignCenter, &QToolButton::toggled, this, &LtsTextEditor::slotTextAlign); - connect(m_ui->pbAlignRight, &QToolButton::toggled, this, &LtsTextEditor::slotTextAlign); - connect(m_ui->pbAlignJustify, &QToolButton::toggled, this, &LtsTextEditor::slotTextAlign); + connect(m_ui->pbTextColor, &QToolButton::clicked, + this, &LtsTextEditor::slotTextColor); + connect(m_ui->pbBackgroundColor, &QToolButton::clicked, + this, &LtsTextEditor::slotBackgroundColor); - QFont textFont(QStringLiteral("Sans Serif")); - textFont.setStyleHint(QFont::SansSerif); - m_ui->textEdit->setFont(textFont); - slotFontChanged(m_ui->textEdit->font()); - slotTextColorChanged(m_ui->textEdit->textColor()); - slotAlignmentChanged(); + connect(m_ui->pbAlignLeft, &QToolButton::toggled, + this, &LtsTextEditor::slotTextAlign); + connect(m_ui->pbAlignCenter, &QToolButton::toggled, + this, &LtsTextEditor::slotTextAlign); + connect(m_ui->pbAlignRight, &QToolButton::toggled, + this, &LtsTextEditor::slotTextAlign); + connect(m_ui->pbAlignJustify, &QToolButton::toggled, + this, &LtsTextEditor::slotTextAlign); - slotBackgroundColorChanged(m_backgroundColor); - connect(m_ui->cbFonts, &QComboBox::currentTextChanged, this, &LtsTextEditor::slotTextFamily); + QFont textFont(QStringLiteral("Sans Serif")); + textFont.setStyleHint(QFont::SansSerif); + m_ui->textEdit->setFont(textFont); + slotFontChanged(m_ui->textEdit->font()); + slotTextColorChanged(m_ui->textEdit->textColor()); + slotAlignmentChanged(); - const QList standardSizes = QFontDatabase::standardSizes(); - for (int size : standardSizes) - m_ui->cbFontSize->addItem(QString::number(size)); - m_ui->cbFontSize->setCurrentIndex(standardSizes.indexOf(QApplication::font().pointSize())); + slotBackgroundColorChanged(m_backgroundColor); - connect(m_ui->cbFontSize, &QComboBox::currentTextChanged, this, &LtsTextEditor::slotTextSize); - connect(m_ui->cbFontSize->lineEdit(), &QLineEdit::editingFinished, this, - &LtsTextEditor::slotTextSizeEditingFinished); + connect(m_ui->cbFonts, QOverload::of(&QComboBox::activated), + this, &LtsTextEditor::slotTextFamily); - m_ui->textEdit->setFocus(); + const QList standardSizes = QFontDatabase::standardSizes(); + for (int size : standardSizes) + m_ui->cbFontSize->addItem(QString::number(size)); + m_ui->cbFontSize->setCurrentIndex(standardSizes.indexOf(QApplication::font().pointSize())); + + connect(m_ui->cbFontSize, QOverload::of(&QComboBox::activated), + this, &LtsTextEditor::slotTextSize); + + connect(m_ui->cbFontSize->lineEdit(), &QLineEdit::editingFinished, + this, &LtsTextEditor::slotTextSizeEditingFinished); + + m_ui->textEdit->setFocus(); } + LtsTextEditor::~LtsTextEditor() { - delete m_ui; + delete m_ui; } -QTextEdit* LtsTextEditor::textEdit() + +QTextEdit *LtsTextEditor::textEdit() { - return m_ui->textEdit; + return m_ui->textEdit; } QColor LtsTextEditor::backgroundColor() const { - return m_backgroundColor; + return m_backgroundColor; } void LtsTextEditor::enableBackgroundColor(bool onOff) { - m_ui->pbBackgroundColor->setVisible(onOff); + m_ui->pbBackgroundColor->setVisible(onOff); } -void LtsTextEditor::setInitialBackgroundColor(const QColor& bgColor) +void LtsTextEditor::setInitialBackgroundColor(const QColor &bgColor) { - if (bgColor.isValid()) - m_backgroundColor = bgColor; - slotBackgroundColorChanged(m_backgroundColor); + if (bgColor.isValid()) + m_backgroundColor = bgColor; + slotBackgroundColorChanged(m_backgroundColor); } + void LtsTextEditor::slotTextBold() { - QTextCharFormat fmt; - fmt.setFontItalic(m_ui->pbItalic->isChecked()); - fmt.setFontUnderline(m_ui->pbUnderline->isChecked()); - fmt.setFontWeight(m_ui->pbBold->isChecked() ? QFont::Bold : QFont::Normal); - if (m_ui->textEdit->document()->isEmpty()) - { - const QString& f = m_ui->cbFonts->currentText(); - fmt.setFontFamily(f); - fmt.setFontFamilies({f}); - fmt.setForeground(m_foregroundColor); - const qreal pointSize = - (m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11); - fmt.setFontPointSize(pointSize); - } - slotMergeFormatOnWordOrSelection(fmt); + QTextCharFormat fmt; + fmt.setFontItalic(m_ui->pbItalic->isChecked()); + fmt.setFontUnderline(m_ui->pbUnderline->isChecked()); + fmt.setFontWeight(m_ui->pbBold->isChecked() ? QFont::Bold : QFont::Normal); + if (m_ui->textEdit->document()->isEmpty()) + { + const QString &f = m_ui->cbFonts->currentText(); + fmt.setFontFamily(f); + fmt.setFontFamilies({f}); + fmt.setForeground(m_foregroundColor); + const qreal pointSize = (m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11); + fmt.setFontPointSize(pointSize); + } + slotMergeFormatOnWordOrSelection(fmt); } + void LtsTextEditor::slotTextUnderline() { - QTextCharFormat fmt; - fmt.setFontItalic(m_ui->pbItalic->isChecked()); - fmt.setFontUnderline(m_ui->pbUnderline->isChecked()); - fmt.setFontWeight(m_ui->pbBold->isChecked() ? QFont::Bold : QFont::Normal); - if (m_ui->textEdit->document()->isEmpty()) - { - const QString& f = m_ui->cbFonts->currentText(); - fmt.setFontFamily(f); - fmt.setFontFamilies({f}); - fmt.setForeground(m_foregroundColor); - const qreal pointSize = - (m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11); - fmt.setFontPointSize(pointSize); - } - slotMergeFormatOnWordOrSelection(fmt); + QTextCharFormat fmt; + fmt.setFontItalic(m_ui->pbItalic->isChecked()); + fmt.setFontUnderline(m_ui->pbUnderline->isChecked()); + fmt.setFontWeight(m_ui->pbBold->isChecked() ? QFont::Bold : QFont::Normal); + if (m_ui->textEdit->document()->isEmpty()) + { + const QString &f = m_ui->cbFonts->currentText(); + fmt.setFontFamily(f); + fmt.setFontFamilies({f}); + fmt.setForeground(m_foregroundColor); + const qreal pointSize = (m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11); + fmt.setFontPointSize(pointSize); + } + slotMergeFormatOnWordOrSelection(fmt); } + void LtsTextEditor::slotTextItalic() { - QTextCharFormat fmt; + QTextCharFormat fmt; + fmt.setFontItalic(m_ui->pbItalic->isChecked()); + fmt.setFontUnderline(m_ui->pbUnderline->isChecked()); + fmt.setFontWeight(m_ui->pbBold->isChecked() ? QFont::Bold : QFont::Normal); + if (m_ui->textEdit->document()->isEmpty()) + { + const QString &f = m_ui->cbFonts->currentText(); + fmt.setFontFamily(f); + fmt.setFontFamilies({f}); + fmt.setForeground(m_foregroundColor); + const qreal pointSize = (m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11); + fmt.setFontPointSize(pointSize); + } + slotMergeFormatOnWordOrSelection(fmt); +} + + +void LtsTextEditor::slotTextFamily(const QString &f) +{ + QTextCharFormat fmt; + if (m_ui->textEdit->document()->isEmpty()) + { fmt.setFontItalic(m_ui->pbItalic->isChecked()); fmt.setFontUnderline(m_ui->pbUnderline->isChecked()); fmt.setFontWeight(m_ui->pbBold->isChecked() ? QFont::Bold : QFont::Normal); - if (m_ui->textEdit->document()->isEmpty()) - { - const QString& f = m_ui->cbFonts->currentText(); - fmt.setFontFamily(f); - fmt.setFontFamilies({f}); - fmt.setForeground(m_foregroundColor); - const qreal pointSize = - (m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11); - fmt.setFontPointSize(pointSize); - } - slotMergeFormatOnWordOrSelection(fmt); + + const qreal pointSize = (m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11); + fmt.setFontPointSize(pointSize); + fmt.setForeground(m_foregroundColor); + } + fmt.setFontFamily(f); + fmt.setFontFamilies({f}); + slotMergeFormatOnWordOrSelection(fmt); } -void LtsTextEditor::slotTextFamily(const QString& f) + +void LtsTextEditor::slotTextSize(const QString &p) { + qreal pointSize = p.toFloat(); + + if (p.toFloat() > 0) + { + QSignalBlocker signalBlocker(m_ui->cbFontSize->lineEdit()); + m_ui->cbFontSize->clearFocus(); + QTextCharFormat fmt; if (m_ui->textEdit->document()->isEmpty()) { - fmt.setFontItalic(m_ui->pbItalic->isChecked()); - fmt.setFontUnderline(m_ui->pbUnderline->isChecked()); - fmt.setFontWeight(m_ui->pbBold->isChecked() ? QFont::Bold : QFont::Normal); + const QString &f = m_ui->cbFonts->currentText(); + fmt.setFontFamily(f); + fmt.setFontFamilies({f}); + fmt.setForeground(m_foregroundColor); + + fmt.setFontItalic(m_ui->pbItalic->isChecked()); + fmt.setFontUnderline(m_ui->pbUnderline->isChecked()); + fmt.setFontWeight(m_ui->pbBold->isChecked() ? QFont::Bold : QFont::Normal); - const qreal pointSize = - (m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11); - fmt.setFontPointSize(pointSize); - fmt.setForeground(m_foregroundColor); } - fmt.setFontFamily(f); - fmt.setFontFamilies({f}); + fmt.setFontPointSize(pointSize); slotMergeFormatOnWordOrSelection(fmt); -} - -void LtsTextEditor::slotTextSize(const QString& p) -{ - qreal pointSize = p.toFloat(); - - if (p.toFloat() > 0) - { - QSignalBlocker signalBlocker(m_ui->cbFontSize->lineEdit()); - m_ui->cbFontSize->clearFocus(); - - QTextCharFormat fmt; - if (m_ui->textEdit->document()->isEmpty()) - { - const QString& f = m_ui->cbFonts->currentText(); - fmt.setFontFamily(f); - fmt.setFontFamilies({f}); - fmt.setForeground(m_foregroundColor); - - fmt.setFontItalic(m_ui->pbItalic->isChecked()); - fmt.setFontUnderline(m_ui->pbUnderline->isChecked()); - fmt.setFontWeight(m_ui->pbBold->isChecked() ? QFont::Bold : QFont::Normal); - } - fmt.setFontPointSize(pointSize); - slotMergeFormatOnWordOrSelection(fmt); - } + } } void LtsTextEditor::slotTextSizeEditingFinished() { - qreal pointSize = m_ui->cbFontSize->currentText().toFloat(); + qreal pointSize = m_ui->cbFontSize->currentText().toFloat(); - if (pointSize > 0) - { - QTextCharFormat textCharFormat; + if (pointSize > 0) + { + QTextCharFormat textCharFormat; - textCharFormat.setFontPointSize(pointSize); + textCharFormat.setFontPointSize(pointSize); - QTextCursor cursor = m_ui->textEdit->textCursor(); + QTextCursor cursor = m_ui->textEdit->textCursor(); - if (cursor.charFormat().font().pointSizeF() == pointSize) - return; + if (cursor.charFormat().font().pointSizeF() == pointSize) + return; - if (!cursor.hasSelection()) - cursor.select(QTextCursor::WordUnderCursor); + if (!cursor.hasSelection()) + cursor.select(QTextCursor::WordUnderCursor); - cursor.mergeCharFormat(textCharFormat); - } + cursor.mergeCharFormat(textCharFormat); + } } void LtsTextEditor::slotTextColor() { - QColor col = QColorDialog::getColor(m_ui->textEdit->textColor(), this); - if (!col.isValid()) - return; + QColor col = QColorDialog::getColor(m_ui->textEdit->textColor(), this); + if (!col.isValid()) + return; - QTextCharFormat fmt; - if (m_ui->textEdit->document()->isEmpty()) - { - fmt.setFontItalic(m_ui->pbItalic->isChecked()); - fmt.setFontUnderline(m_ui->pbUnderline->isChecked()); - fmt.setFontWeight(m_ui->pbBold->isChecked() ? QFont::Bold : QFont::Normal); + QTextCharFormat fmt; + if (m_ui->textEdit->document()->isEmpty()) + { + fmt.setFontItalic(m_ui->pbItalic->isChecked()); + fmt.setFontUnderline(m_ui->pbUnderline->isChecked()); + fmt.setFontWeight(m_ui->pbBold->isChecked() ? QFont::Bold : QFont::Normal); - const QString& f = m_ui->cbFonts->currentText(); - fmt.setFontFamily(f); - fmt.setFontFamilies({f}); - const qreal pointSize = - (m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11); - fmt.setFontPointSize(pointSize); - } - fmt.setForeground(col); - slotMergeFormatOnWordOrSelection(fmt); - slotTextColorChanged(col); + const QString &f = m_ui->cbFonts->currentText(); + fmt.setFontFamily(f); + fmt.setFontFamilies({f}); + const qreal pointSize = (m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11); + fmt.setFontPointSize(pointSize); + } + fmt.setForeground(col); + slotMergeFormatOnWordOrSelection(fmt); + slotTextColorChanged(col); } void LtsTextEditor::slotBackgroundColor() { - QColor col = QColorDialog::getColor(m_backgroundColor.isValid() ? m_backgroundColor : Qt::white, this); - if (!col.isValid()) - return; + QColor col = QColorDialog::getColor(m_backgroundColor.isValid() ? m_backgroundColor : Qt::white, this); + if (!col.isValid()) + return; - m_backgroundColor = col; - slotBackgroundColorChanged(m_backgroundColor); - emit backgroundColorChanged(m_backgroundColor); + m_backgroundColor = col; + slotBackgroundColorChanged(m_backgroundColor); + emit backgroundColorChanged(m_backgroundColor); } -void LtsTextEditor::slotCurrentCharFormatChanged(const QTextCharFormat& format) + +void LtsTextEditor::slotCurrentCharFormatChanged(const QTextCharFormat &format) { - slotFontChanged(format.font()); - slotTextColorChanged(format.foreground().color()); + slotFontChanged(format.font()); + slotTextColorChanged(format.foreground().color()); } -void LtsTextEditor::slotFontChanged(const QFont& f) + +void LtsTextEditor::slotFontChanged(const QFont &f) { - m_ui->cbFonts->setCurrentIndex(m_ui->cbFonts->findText(f.family())); + m_ui->cbFonts->setCurrentIndex(m_ui->cbFonts->findText(f.family())); - QSignalBlocker comboBoxsignalBlocker(m_ui->cbFontSize); - QSignalBlocker lineEditSignalBlocker(m_ui->cbFontSize->lineEdit()); - QString fontSizeString = QString::number(f.pointSize()); - int32_t fontSizeIndex = m_ui->cbFontSize->findText(fontSizeString); + QSignalBlocker comboBoxsignalBlocker(m_ui->cbFontSize); + QSignalBlocker lineEditSignalBlocker(m_ui->cbFontSize->lineEdit()); + QString fontSizeString = QString::number(f.pointSize()); + int32_t fontSizeIndex = m_ui->cbFontSize->findText(fontSizeString); - if (fontSizeIndex >= 0) - m_ui->cbFontSize->setCurrentIndex(fontSizeIndex); - else if (m_ui->cbFontSize->currentText() != fontSizeString) - m_ui->cbFontSize->setCurrentText(fontSizeString); + if (fontSizeIndex >= 0) + m_ui->cbFontSize->setCurrentIndex(fontSizeIndex); + else if (m_ui->cbFontSize->currentText() != fontSizeString) + m_ui->cbFontSize->setCurrentText(fontSizeString); - m_ui->pbBold->setChecked(f.bold()); - m_ui->pbItalic->setChecked(f.italic()); - m_ui->pbUnderline->setChecked(f.underline()); + m_ui->pbBold->setChecked(f.bold()); + m_ui->pbItalic->setChecked(f.italic()); + m_ui->pbUnderline->setChecked(f.underline()); } -void LtsTextEditor::slotMergeFormatOnWordOrSelection(const QTextCharFormat& format) + +void LtsTextEditor::slotMergeFormatOnWordOrSelection(const QTextCharFormat &format) { - QTextCursor cursor = m_ui->textEdit->textCursor(); - if (!cursor.hasSelection()) - cursor.select(QTextCursor::WordUnderCursor); + QTextCursor cursor = m_ui->textEdit->textCursor(); + if (!cursor.hasSelection()) + cursor.select(QTextCursor::WordUnderCursor); - cursor.mergeCharFormat(format); - - if (m_ui->textEdit->document()->isEmpty()) - m_ui->textEdit->setTextCursor(cursor); + cursor.mergeCharFormat(format); + //[GUEZE-3151] Voreinstellung vom Text werden wenn text editor leer ist nicht greifen + // Mögliche Grund: je nach position des cursors auf dem Text wird die tools dynamisch eingestellt. + if (m_ui->textEdit->document()->isEmpty()) + m_ui->textEdit->setTextCursor(cursor); } -void LtsTextEditor::slotTextColorChanged(const QColor& c) + +void LtsTextEditor::slotTextColorChanged(const QColor &c) { - QPixmap pix(32, 32); - pix.fill(c); - m_ui->pbTextColor->setIcon(pix); - m_foregroundColor = c; + QPixmap pix(32, 32); + pix.fill(c); + m_ui->pbTextColor->setIcon(pix); + m_foregroundColor = c; } -void LtsTextEditor::slotBackgroundColorChanged(const QColor& bgColor) + +void LtsTextEditor::slotBackgroundColorChanged(const QColor &bgColor) { - QPixmap pix(32, 32); - pix.fill(bgColor); - m_ui->pbBackgroundColor->setIcon(pix); + QPixmap pix(32, 32); + pix.fill(bgColor); + m_ui->pbBackgroundColor->setIcon(pix); } + void LtsTextEditor::slotTextAlign() { - QToolButton* b = qobject_cast(sender()); + QToolButton *b = qobject_cast(sender()); - if (b == nullptr) - return; + if (b == nullptr) + return; - if (b == m_ui->pbAlignLeft) - m_ui->textEdit->setAlignment(Qt::AlignLeft | Qt::AlignAbsolute); - else if (b == m_ui->pbAlignCenter) - m_ui->textEdit->setAlignment(Qt::AlignHCenter); - else if (b == m_ui->pbAlignRight) - m_ui->textEdit->setAlignment(Qt::AlignRight | Qt::AlignAbsolute); - else if (b == m_ui->pbAlignJustify) - m_ui->textEdit->setAlignment(Qt::AlignJustify); + if (b == m_ui->pbAlignLeft) + m_ui->textEdit->setAlignment(Qt::AlignLeft | Qt::AlignAbsolute); + else if (b == m_ui->pbAlignCenter) + m_ui->textEdit->setAlignment(Qt::AlignHCenter); + else if (b == m_ui->pbAlignRight) + m_ui->textEdit->setAlignment(Qt::AlignRight | Qt::AlignAbsolute); + else if (b == m_ui->pbAlignJustify) + m_ui->textEdit->setAlignment(Qt::AlignJustify); } + void LtsTextEditor::slotAlignmentChanged() { - auto a = m_ui->textEdit->alignment(); + auto a = m_ui->textEdit->alignment(); - if (a & Qt::AlignLeft) - m_ui->pbAlignLeft->setChecked(true); - if (a & Qt::AlignHCenter) - m_ui->pbAlignCenter->setChecked(true); - if (a & Qt::AlignRight) - m_ui->pbAlignRight->setChecked(true); - if (a & Qt::AlignJustify) - m_ui->pbAlignJustify->setChecked(true); + if (a & Qt::AlignLeft) + m_ui->pbAlignLeft->setChecked(true); + if (a & Qt::AlignHCenter) + m_ui->pbAlignCenter->setChecked(true); + if (a & Qt::AlignRight) + m_ui->pbAlignRight->setChecked(true); + if (a & Qt::AlignJustify) + m_ui->pbAlignJustify->setChecked(true); } + void LtsTextEditor::slotClipboardDataChanged() { - if (const QMimeData* md = QApplication::clipboard()->mimeData()) - m_ui->pbPaste->setEnabled(md->hasText()); + if (const QMimeData *md = QApplication::clipboard()->mimeData()) + m_ui->pbPaste->setEnabled(md->hasText()); } } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor.h index a5771bcce..cee40099f 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor.h @@ -1,9 +1,10 @@ #pragma once -#include "lts_widgets_export.h" -#include +#include + #include + namespace Ui { class LtsTextEditor; @@ -12,46 +13,49 @@ class LtsTextEditor; class QTextEdit; class QTextCharFormat; + namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsTextEditor : public QWidget { - Q_OBJECT - public: - LtsTextEditor(QWidget* parent = nullptr); - ~LtsTextEditor(); - void enableBackgroundColor(bool onOff); - void setInitialBackgroundColor(const QColor& bgColor); - QTextEdit* textEdit(); - QColor backgroundColor() const; + Q_OBJECT +public: + LtsTextEditor(QWidget *parent = nullptr); + ~LtsTextEditor(); + void enableBackgroundColor(bool onOff); + void setInitialBackgroundColor(const QColor &bgColor); + QTextEdit *textEdit(); + QColor backgroundColor() const; - Q_SIGNALS: - void backgroundColorChanged(const QColor& bgColor); +Q_SIGNALS: + void backgroundColorChanged(const QColor &bgColor); - private: - Ui::LtsTextEditor* m_ui; - QColor m_backgroundColor{Qt::white}; - QColor m_foregroundColor{Qt::black}; +private: + Ui::LtsTextEditor *m_ui; + QColor m_backgroundColor{Qt::white}; + QColor m_foregroundColor{Qt::black}; - private slots: - void slotCurrentCharFormatChanged(const QTextCharFormat& format); - void slotFontChanged(const QFont& f); - void slotTextColorChanged(const QColor& c); - void slotBackgroundColorChanged(const QColor& bgColor); - void slotAlignmentChanged(); - void slotMergeFormatOnWordOrSelection(const QTextCharFormat& format); - void slotClipboardDataChanged(); - void slotTextColor(); - void slotBackgroundColor(); - void slotTextSize(const QString& p); - void slotTextSizeEditingFinished(); - void slotTextFamily(const QString& f); - void slotTextItalic(); - void slotTextUnderline(); - void slotTextBold(); - - void slotTextAlign(); +private slots: + void slotCurrentCharFormatChanged(const QTextCharFormat &format); + void slotFontChanged(const QFont &f); + void slotTextColorChanged(const QColor &c); + void slotBackgroundColorChanged(const QColor &bgColor); + void slotAlignmentChanged(); + void slotMergeFormatOnWordOrSelection(const QTextCharFormat &format); + void slotClipboardDataChanged(); + void slotTextColor(); + void slotBackgroundColor(); + void slotTextSize(const QString &p); + void slotTextSizeEditingFinished(); + void slotTextFamily(const QString &f); + void slotTextItalic(); + void slotTextUnderline(); + void slotTextBold(); + //void slotTextStyle(int styleIndex); + void slotTextAlign(); }; } // namespace LtsWidgets + + diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor2.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor2.cpp index 6be1a2d21..7b0f6aaba 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor2.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor2.cpp @@ -1,31 +1,38 @@ +/** +* @RDE_HEADER@ +* Widget to create Text Editor +* $Id$ +* $HeadURL$ +* $Author$ +*/ #include "lts_text_editor2.h" #include -#include #include #include -#include #include #include +#include #include #include #include -#include #include #include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include #include -#include -#include -#include -#include -#include -#include -#include #if defined(QT_PRINTSUPPORT_LIB) #include #if QT_CONFIG(printer) @@ -39,902 +46,882 @@ #endif #endif + #include #ifdef Q_OS_MAC -inline QString rsrcPath() -{ - QStringLiteral(":/images/mac"); -} +inline QString rsrcPath(){ QStringLiteral(":/images/mac");} #else -inline QString rsrcPath() -{ - return QStringLiteral(":/images/win"); -} +inline QString rsrcPath(){return QStringLiteral(":/images/win");} #endif namespace LtsWidgets { -LtsTextEditor2::LtsTextEditor2(QWidget* parent) : QMainWindow(parent) +LtsTextEditor2::LtsTextEditor2(QWidget *parent) + : QMainWindow(parent) { - setWindowFlags(Qt::CustomizeWindowHint); - setWindowTitle(QCoreApplication::applicationName()); + setWindowFlags(Qt::CustomizeWindowHint /*Qt::WindowStaysOnTopHint */); + setWindowTitle(QCoreApplication::applicationName()); - m_textEdit = new QTextEdit(this); - connect(m_textEdit, &QTextEdit::currentCharFormatChanged, this, &LtsTextEditor2::currentCharFormatChanged); - connect(m_textEdit, &QTextEdit::cursorPositionChanged, this, &LtsTextEditor2::cursorPositionChanged); - setCentralWidget(m_textEdit); + m_textEdit = new QTextEdit(this); + connect(m_textEdit, &QTextEdit::currentCharFormatChanged, + this, &LtsTextEditor2::currentCharFormatChanged); + connect(m_textEdit, &QTextEdit::cursorPositionChanged, + this, &LtsTextEditor2::cursorPositionChanged); + setCentralWidget(m_textEdit); - setToolButtonStyle(Qt::ToolButtonFollowStyle); - setupFileActions(); - setupEditActions(); - setupTextActions(); + setToolButtonStyle(Qt::ToolButtonFollowStyle); + setupFileActions(); + setupEditActions(); + setupTextActions(); - { - QMenu* helpMenu = menuBar()->addMenu(tr("Help")); - helpMenu->addAction(tr("About"), this, &LtsTextEditor2::about); - helpMenu->addAction(tr("About &Qt"), qApp, &QApplication::aboutQt); - } + { + QMenu *helpMenu = menuBar()->addMenu(tr("Help")); + helpMenu->addAction(tr("About"), this, &LtsTextEditor2::about); + helpMenu->addAction(tr("About &Qt"), qApp, &QApplication::aboutQt); + } - QFont textFont(QStringLiteral("Helvetica")); - textFont.setStyleHint(QFont::SansSerif); - m_textEdit->setFont(textFont); - fontChanged(m_textEdit->font()); - colorChanged(m_textEdit->textColor()); - alignmentChanged(m_textEdit->alignment()); + QFont textFont(QStringLiteral("Helvetica")); + textFont.setStyleHint(QFont::SansSerif); + m_textEdit->setFont(textFont); + fontChanged(m_textEdit->font()); + colorChanged(m_textEdit->textColor()); + alignmentChanged(m_textEdit->alignment()); - connect(m_textEdit->document(), &QTextDocument::modificationChanged, m_actionSave, &QAction::setEnabled); - connect(m_textEdit->document(), &QTextDocument::modificationChanged, this, &QWidget::setWindowModified); - connect(m_textEdit->document(), &QTextDocument::undoAvailable, m_actionUndo, &QAction::setEnabled); - connect(m_textEdit->document(), &QTextDocument::redoAvailable, m_actionRedo, &QAction::setEnabled); + connect(m_textEdit->document(), &QTextDocument::modificationChanged, + m_actionSave, &QAction::setEnabled); + connect(m_textEdit->document(), &QTextDocument::modificationChanged, + this, &QWidget::setWindowModified); + connect(m_textEdit->document(), &QTextDocument::undoAvailable, + m_actionUndo, &QAction::setEnabled); + connect(m_textEdit->document(), &QTextDocument::redoAvailable, + m_actionRedo, &QAction::setEnabled); - setWindowModified(m_textEdit->document()->isModified()); - m_actionSave->setEnabled(m_textEdit->document()->isModified()); - m_actionUndo->setEnabled(m_textEdit->document()->isUndoAvailable()); - m_actionRedo->setEnabled(m_textEdit->document()->isRedoAvailable()); + setWindowModified(m_textEdit->document()->isModified()); + m_actionSave->setEnabled(m_textEdit->document()->isModified()); + m_actionUndo->setEnabled(m_textEdit->document()->isUndoAvailable()); + m_actionRedo->setEnabled(m_textEdit->document()->isRedoAvailable()); #ifndef QT_NO_CLIPBOARD - m_actionCut->setEnabled(false); - connect(m_textEdit, &QTextEdit::copyAvailable, m_actionCut, &QAction::setEnabled); - m_actionCopy->setEnabled(false); - connect(m_textEdit, &QTextEdit::copyAvailable, m_actionCopy, &QAction::setEnabled); + m_actionCut->setEnabled(false); + connect(m_textEdit, &QTextEdit::copyAvailable, m_actionCut, &QAction::setEnabled); + m_actionCopy->setEnabled(false); + connect(m_textEdit, &QTextEdit::copyAvailable, m_actionCopy, &QAction::setEnabled); - connect(QApplication::clipboard(), &QClipboard::dataChanged, this, &LtsTextEditor2::clipboardDataChanged); + connect(QApplication::clipboard(), &QClipboard::dataChanged, this, &LtsTextEditor2::clipboardDataChanged); #endif - m_textEdit->setFocus(); - setCurrentFileName(QString()); + m_textEdit->setFocus(); + setCurrentFileName(QString()); - this->menuBar()->hide(); - m_actionSave->setVisible(false); - m_actionOpen->setVisible(false); - m_actionQuit->setVisible(false); - m_actionSaveAs->setVisible(false); - m_actionNew->setVisible(false); + this->menuBar()->hide(); + m_actionSave->setVisible(false); + m_actionOpen->setVisible(false); + m_actionQuit->setVisible(false); + m_actionSaveAs->setVisible(false); + m_actionNew->setVisible(false); #if defined(QT_PRINTSUPPORT_LIB) && QT_CONFIG(printer) - actionPrint->setVisible(false); - actionPreview->setVisible(false); - actionExport->setVisible(false); + actionPrint->setVisible(false); + actionPreview->setVisible(false); + actionExport->setVisible(false); #endif - m_actionToggleCheckState->setVisible(false); - m_actionToggleCheckState->setVisible(false); - m_actionIndentLess->setVisible(false); - m_actionIndentMore->setVisible(false); - m_comboStyleAction->setVisible(false); - m_actionToggleCheckState->setVisible(false); + m_actionToggleCheckState->setVisible(false); + m_actionToggleCheckState->setVisible(false); + m_actionIndentLess->setVisible(false); + m_actionIndentMore->setVisible(false); + m_comboStyleAction->setVisible(false); + m_actionToggleCheckState->setVisible(false); + + } -LtsTextEditor2::~LtsTextEditor2() {} - -QTextEdit* LtsTextEditor2::textEdit() +LtsTextEditor2::~LtsTextEditor2() { - return m_textEdit; + //delete m_ui; } +QTextEdit *LtsTextEditor2::textEdit() +{ + return m_textEdit; +} QColor LtsTextEditor2::backgroundColor() const { - return m_backgroundColor; + return m_backgroundColor; } -void LtsTextEditor2::setInitialBackgroundColor(const QColor& bgColor) +void LtsTextEditor2::setInitialBackgroundColor(const QColor &bgColor) { - if (bgColor.isValid()) - m_backgroundColor = bgColor; - slotBackgroundColorChanged(m_backgroundColor); + if (bgColor.isValid()) + m_backgroundColor = bgColor; + slotBackgroundColorChanged(m_backgroundColor); } - void LtsTextEditor2::enableBackgroundColor(bool onOff) { - m_actionBackgroundColor->setVisible(onOff); + m_actionBackgroundColor->setVisible(onOff); } -void LtsTextEditor2::slotBackgroundColorChanged(const QColor& bgColor) +/*! + * \brief LtsTextEditor2::slotBackgroundColorChanged + * \param bgColor + */ +void LtsTextEditor2::slotBackgroundColorChanged(const QColor &bgColor) { - QPixmap pix(16, 16); - pix.fill(bgColor); - m_actionBackgroundColor->setIcon(pix); + QPixmap pix(16, 16); + pix.fill(bgColor); + m_actionBackgroundColor->setIcon(pix); } - void LtsTextEditor2::slotBackgroundColor() { - QColor col = QColorDialog::getColor(m_backgroundColor.isValid() ? m_backgroundColor : Qt::white, this); - if (!col.isValid()) - return; + QColor col = QColorDialog::getColor(m_backgroundColor.isValid() ? m_backgroundColor : Qt::white, this); + if (!col.isValid()) + return; - m_backgroundColor = col; - slotBackgroundColorChanged(m_backgroundColor); - emit backgroundColorChanged(m_backgroundColor); + m_backgroundColor = col; + slotBackgroundColorChanged(m_backgroundColor); + emit backgroundColorChanged(m_backgroundColor); } + void LtsTextEditor2::setupFileActions() { - QToolBar* tb = addToolBar(tr("File Actions")); - QMenu* menu = menuBar()->addMenu(tr("&File")); + QToolBar *tb = addToolBar(tr("File Actions")); + QMenu *menu = menuBar()->addMenu(tr("&File")); - const QIcon newIcon = - QIcon::fromTheme(QStringLiteral("document-new"), QIcon(rsrcPath() + QStringLiteral("/filenew.png"))); - m_actionNew = menu->addAction(newIcon, tr("&New"), this, &LtsTextEditor2::onFileNew); - tb->addAction(m_actionNew); - m_actionNew->setPriority(QAction::LowPriority); - m_actionNew->setShortcut(QKeySequence::New); + const QIcon newIcon = QIcon::fromTheme(QStringLiteral("document-new"), QIcon(rsrcPath() + QStringLiteral("/filenew.png"))); + m_actionNew = menu->addAction(newIcon, tr("&New"), this, &LtsTextEditor2::onFileNew); + tb->addAction(m_actionNew); + m_actionNew->setPriority(QAction::LowPriority); + m_actionNew->setShortcut(QKeySequence::New); - const QIcon openIcon = - QIcon::fromTheme(QStringLiteral("document-open"), QIcon(rsrcPath() + QStringLiteral("/fileopen.png"))); - m_actionOpen = menu->addAction(openIcon, tr("&Open..."), this, &LtsTextEditor2::onFileOpen); - m_actionOpen->setShortcut(QKeySequence::Open); - tb->addAction(m_actionOpen); + const QIcon openIcon = QIcon::fromTheme(QStringLiteral("document-open"), QIcon(rsrcPath() + QStringLiteral("/fileopen.png"))); + m_actionOpen = menu->addAction(openIcon, tr("&Open..."), this, &LtsTextEditor2::onFileOpen); + m_actionOpen->setShortcut(QKeySequence::Open); + tb->addAction(m_actionOpen); - menu->addSeparator(); + menu->addSeparator(); - const QIcon saveIcon = - QIcon::fromTheme(QStringLiteral("document-save"), QIcon(rsrcPath() + QStringLiteral("/filesave.png"))); - m_actionSave = menu->addAction(saveIcon, tr("&Save"), this, &LtsTextEditor2::onFileSave); - m_actionSave->setShortcut(QKeySequence::Save); - m_actionSave->setEnabled(false); - tb->addAction(m_actionSave); + const QIcon saveIcon = QIcon::fromTheme(QStringLiteral("document-save"), QIcon(rsrcPath()+ QStringLiteral("/filesave.png"))); + m_actionSave = menu->addAction(saveIcon, tr("&Save"), this, &LtsTextEditor2::onFileSave); + m_actionSave->setShortcut(QKeySequence::Save); + m_actionSave->setEnabled(false); + tb->addAction(m_actionSave); - m_actionSaveAs = menu->addAction(tr("Save &As..."), this, &LtsTextEditor2::onFileSaveAs); - m_actionSaveAs->setPriority(QAction::LowPriority); - menu->addSeparator(); + m_actionSaveAs = menu->addAction(tr("Save &As..."), this, &LtsTextEditor2::onFileSaveAs); + m_actionSaveAs->setPriority(QAction::LowPriority); + menu->addSeparator(); #if defined(QT_PRINTSUPPORT_LIB) && QT_CONFIG(printer) - const QIcon printIcon = - QIcon::fromTheme(QStringLiteral("document-print"), QIcon(rsrcPath() + QStringLiteral("/fileprint.png"))); - actionPrint = menu->addAction(printIcon, tr("&Print..."), this, &LtsTextEditor2::filePrint); - actionPrint->setPriority(QAction::LowPriority); - actionPrint->setShortcut(QKeySequence::Print); - tb->addAction(actionPrint); + const QIcon printIcon = QIcon::fromTheme(QStringLiteral("document-print"), QIcon(rsrcPath()+ QStringLiteral("/fileprint.png"))); + actionPrint = menu->addAction(printIcon, tr("&Print..."), this, &LtsTextEditor2::filePrint); + actionPrint->setPriority(QAction::LowPriority); + actionPrint->setShortcut(QKeySequence::Print); + tb->addAction(actionPrint); - const QIcon filePrintIcon = - QIcon::fromTheme(QStringLiteral("fileprint"), QIcon(rsrcPath() + QStringLiteral("/fileprint.png"))); - actionPreview = menu->addAction(filePrintIcon, tr("Print Preview..."), this, &LtsTextEditor2::filePrintPreview); + const QIcon filePrintIcon = QIcon::fromTheme(QStringLiteral("fileprint"), QIcon(rsrcPath()+ QStringLiteral("/fileprint.png"))); + actionPreview = menu->addAction(filePrintIcon, tr("Print Preview..."), this, &LtsTextEditor2::filePrintPreview); - const QIcon exportPdfIcon = - QIcon::fromTheme(QStringLiteral("exportpdf"), QIcon(rsrcPath() + QStringLiteral("/exportpdf.png"))); - actionExport = menu->addAction(exportPdfIcon, tr("&Export PDF..."), this, &LtsTextEditor2::filePrintPdf); - actionExport->setPriority(QAction::LowPriority); - actionExport->setShortcut(Qt::CTRL + Qt::Key_D); - tb->addAction(actionExport); + const QIcon exportPdfIcon = QIcon::fromTheme(QStringLiteral("exportpdf"), QIcon(rsrcPath()+ QStringLiteral("/exportpdf.png"))); + actionExport = menu->addAction(exportPdfIcon, tr("&Export PDF..."), this, &LtsTextEditor2::filePrintPdf); + actionExport->setPriority(QAction::LowPriority); + actionExport->setShortcut(Qt::CTRL + Qt::Key_D); + tb->addAction(actionExport); - menu->addSeparator(); + menu->addSeparator(); #endif - m_actionQuit = menu->addAction(tr("&Quit"), this, &QWidget::close); - m_actionQuit->setShortcut(Qt::CTRL + Qt::Key_Q); + m_actionQuit = menu->addAction(tr("&Quit"), this, &QWidget::close); + m_actionQuit->setShortcut(Qt::CTRL + Qt::Key_Q); } void LtsTextEditor2::setupEditActions() { - QToolBar* tb = addToolBar(tr("Edit Actions")); - QMenu* menu = menuBar()->addMenu(tr("&Edit")); + QToolBar *tb = addToolBar(tr("Edit Actions")); + QMenu *menu = menuBar()->addMenu(tr("&Edit")); - const QIcon undoIcon = QIcon::fromTheme(QStringLiteral("icon:undo.svg")); - m_actionUndo = menu->addAction(undoIcon, {}, m_textEdit, &QTextEdit::undo); - m_actionUndo->setToolTip(tr("&Undo")); - m_actionUndo->setShortcut(QKeySequence::Undo); - tb->addAction(m_actionUndo); + const QIcon undoIcon = QIcon::fromTheme(QStringLiteral("icon:undo.svg")); + m_actionUndo = menu->addAction(undoIcon, {}, m_textEdit, &QTextEdit::undo); + m_actionUndo->setToolTip(tr("&Undo")); + m_actionUndo->setShortcut(QKeySequence::Undo); + tb->addAction(m_actionUndo); - const QIcon redoIcon = QIcon::fromTheme(QStringLiteral("icon:redo.svg")); - m_actionRedo = menu->addAction(redoIcon, tr("&Redo"), m_textEdit, &QTextEdit::redo); - m_actionRedo->setPriority(QAction::LowPriority); - m_actionRedo->setShortcut(QKeySequence::Redo); - tb->addAction(m_actionRedo); - menu->addSeparator(); + const QIcon redoIcon = QIcon::fromTheme(QStringLiteral("icon:redo.svg")); + m_actionRedo = menu->addAction(redoIcon, tr("&Redo"), m_textEdit, &QTextEdit::redo); + m_actionRedo->setPriority(QAction::LowPriority); + m_actionRedo->setShortcut(QKeySequence::Redo); + tb->addAction(m_actionRedo); + menu->addSeparator(); #ifndef QT_NO_CLIPBOARD - const QIcon cutIcon = QIcon::fromTheme(QStringLiteral("icon:edit-cut.svg")); - m_actionCut = menu->addAction(cutIcon, tr("Cu&t"), m_textEdit, &QTextEdit::cut); - m_actionCut->setPriority(QAction::LowPriority); - m_actionCut->setShortcut(QKeySequence::Cut); - tb->addAction(m_actionCut); + const QIcon cutIcon = QIcon::fromTheme(QStringLiteral("icon:edit-cut.svg")); + m_actionCut = menu->addAction(cutIcon, tr("Cu&t"), m_textEdit, &QTextEdit::cut); + m_actionCut->setPriority(QAction::LowPriority); + m_actionCut->setShortcut(QKeySequence::Cut); + tb->addAction(m_actionCut); - const QIcon copyIcon = QIcon::fromTheme(QStringLiteral("icon:edit-copy.svg")); - m_actionCopy = menu->addAction(copyIcon, tr("&Copy"), m_textEdit, &QTextEdit::copy); - m_actionCopy->setPriority(QAction::LowPriority); - m_actionCopy->setShortcut(QKeySequence::Copy); - tb->addAction(m_actionCopy); + const QIcon copyIcon = QIcon::fromTheme(QStringLiteral("icon:edit-copy.svg")); + m_actionCopy = menu->addAction(copyIcon, tr("&Copy"), m_textEdit, &QTextEdit::copy); + m_actionCopy->setPriority(QAction::LowPriority); + m_actionCopy->setShortcut(QKeySequence::Copy); + tb->addAction(m_actionCopy); - const QIcon pasteIcon = QIcon::fromTheme(QStringLiteral("icon:edit-paste.svg")); - m_actionPaste = menu->addAction(pasteIcon, tr("&Paste"), m_textEdit, &QTextEdit::paste); - m_actionPaste->setPriority(QAction::LowPriority); - m_actionPaste->setShortcut(QKeySequence::Paste); - tb->addAction(m_actionPaste); - if (const QMimeData* md = QApplication::clipboard()->mimeData()) - m_actionPaste->setEnabled(md->hasText()); + const QIcon pasteIcon = QIcon::fromTheme(QStringLiteral("icon:edit-paste.svg")); + m_actionPaste = menu->addAction(pasteIcon, tr("&Paste"), m_textEdit, &QTextEdit::paste); + m_actionPaste->setPriority(QAction::LowPriority); + m_actionPaste->setShortcut(QKeySequence::Paste); + tb->addAction(m_actionPaste); + if (const QMimeData *md = QApplication::clipboard()->mimeData()) + m_actionPaste->setEnabled(md->hasText()); #endif } void LtsTextEditor2::setupTextActions() { - QToolBar* tb = addToolBar(tr("Format Actions")); - QMenu* menu = menuBar()->addMenu(tr("F&ormat")); + QToolBar *tb = addToolBar(tr("Format Actions")); + QMenu *menu = menuBar()->addMenu(tr("F&ormat")); - const QIcon boldIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-text-bold.png")); - m_actionTextBold = menu->addAction(boldIcon, tr("&Bold"), this, &LtsTextEditor2::onTextBold); - m_actionTextBold->setShortcut(Qt::CTRL + Qt::Key_B); - m_actionTextBold->setPriority(QAction::LowPriority); - QFont bold; - bold.setBold(true); - m_actionTextBold->setFont(bold); - tb->addAction(m_actionTextBold); - m_actionTextBold->setCheckable(true); + const QIcon boldIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-text-bold.png")); + m_actionTextBold = menu->addAction(boldIcon, tr("&Bold"), this, &LtsTextEditor2::onTextBold); + m_actionTextBold->setShortcut(Qt::CTRL + Qt::Key_B); + m_actionTextBold->setPriority(QAction::LowPriority); + QFont bold; + bold.setBold(true); + m_actionTextBold->setFont(bold); + tb->addAction(m_actionTextBold); + m_actionTextBold->setCheckable(true); - const QIcon italicIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-text-italic.png")); - m_actionTextItalic = menu->addAction(italicIcon, tr("&Italic"), this, &LtsTextEditor2::onTextItalic); - m_actionTextItalic->setPriority(QAction::LowPriority); - m_actionTextItalic->setShortcut(Qt::CTRL + Qt::Key_I); - QFont italic; - italic.setItalic(true); - m_actionTextItalic->setFont(italic); - tb->addAction(m_actionTextItalic); - m_actionTextItalic->setCheckable(true); + const QIcon italicIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-text-italic.png")); + m_actionTextItalic = menu->addAction(italicIcon, tr("&Italic"), this, &LtsTextEditor2::onTextItalic); + m_actionTextItalic->setPriority(QAction::LowPriority); + m_actionTextItalic->setShortcut(Qt::CTRL + Qt::Key_I); + QFont italic; + italic.setItalic(true); + m_actionTextItalic->setFont(italic); + tb->addAction(m_actionTextItalic); + m_actionTextItalic->setCheckable(true); - const QIcon underlineIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-text-underline.png")); - m_actionTextUnderline = menu->addAction(underlineIcon, tr("&Underline"), this, &LtsTextEditor2::onTextUnderline); - m_actionTextUnderline->setShortcut(Qt::CTRL + Qt::Key_U); - m_actionTextUnderline->setPriority(QAction::LowPriority); - QFont underline; - underline.setUnderline(true); - m_actionTextUnderline->setFont(underline); - tb->addAction(m_actionTextUnderline); - m_actionTextUnderline->setCheckable(true); + const QIcon underlineIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-text-underline.png")); + m_actionTextUnderline = menu->addAction(underlineIcon, tr("&Underline"), this, &LtsTextEditor2::onTextUnderline); + m_actionTextUnderline->setShortcut(Qt::CTRL + Qt::Key_U); + m_actionTextUnderline->setPriority(QAction::LowPriority); + QFont underline; + underline.setUnderline(true); + m_actionTextUnderline->setFont(underline); + tb->addAction(m_actionTextUnderline); + m_actionTextUnderline->setCheckable(true); - menu->addSeparator(); + menu->addSeparator(); - const QIcon leftIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-justify-left.png")); - m_actionAlignLeft = new QAction(leftIcon, tr("&Left"), this); - m_actionAlignLeft->setShortcut(Qt::CTRL + Qt::Key_L); - m_actionAlignLeft->setCheckable(true); - m_actionAlignLeft->setPriority(QAction::LowPriority); - const QIcon centerIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-justify-center.png")); - m_actionAlignCenter = new QAction(centerIcon, tr("C&enter"), this); - m_actionAlignCenter->setShortcut(Qt::CTRL + Qt::Key_E); - m_actionAlignCenter->setCheckable(true); - m_actionAlignCenter->setPriority(QAction::LowPriority); - const QIcon rightIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-justify-right.png")); - m_actionAlignRight = new QAction(rightIcon, tr("&Right"), this); - m_actionAlignRight->setShortcut(Qt::CTRL + Qt::Key_R); - m_actionAlignRight->setCheckable(true); - m_actionAlignRight->setPriority(QAction::LowPriority); - const QIcon fillIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-justify-fill.png")); - m_actionAlignJustify = new QAction(fillIcon, tr("&Justify"), this); - m_actionAlignJustify->setShortcut(Qt::CTRL + Qt::Key_J); - m_actionAlignJustify->setCheckable(true); - m_actionAlignJustify->setPriority(QAction::LowPriority); - const QIcon indentMoreIcon = QIcon::fromTheme(QStringLiteral("format-indent-more"), - QIcon(rsrcPath() + QStringLiteral("/format-indent-more.png"))); - m_actionIndentMore = menu->addAction(indentMoreIcon, tr("&Indent"), this, &LtsTextEditor2::indent); - m_actionIndentMore->setShortcut(Qt::CTRL + Qt::Key_BracketRight); - m_actionIndentMore->setPriority(QAction::LowPriority); - const QIcon indentLessIcon = QIcon::fromTheme(QStringLiteral("format-indent-less"), - QIcon(rsrcPath() + QStringLiteral("/format-indent-less.png"))); - m_actionIndentLess = menu->addAction(indentLessIcon, tr("&Unindent"), this, &LtsTextEditor2::unindent); - m_actionIndentLess->setShortcut(Qt::CTRL + Qt::Key_BracketLeft); - m_actionIndentLess->setPriority(QAction::LowPriority); + const QIcon leftIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-justify-left.png")); + m_actionAlignLeft = new QAction(leftIcon, tr("&Left"), this); + m_actionAlignLeft->setShortcut(Qt::CTRL + Qt::Key_L); + m_actionAlignLeft->setCheckable(true); + m_actionAlignLeft->setPriority(QAction::LowPriority); + const QIcon centerIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-justify-center.png")); + m_actionAlignCenter = new QAction(centerIcon, tr("C&enter"), this); + m_actionAlignCenter->setShortcut(Qt::CTRL + Qt::Key_E); + m_actionAlignCenter->setCheckable(true); + m_actionAlignCenter->setPriority(QAction::LowPriority); + const QIcon rightIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-justify-right.png")); + m_actionAlignRight = new QAction(rightIcon, tr("&Right"), this); + m_actionAlignRight->setShortcut(Qt::CTRL + Qt::Key_R); + m_actionAlignRight->setCheckable(true); + m_actionAlignRight->setPriority(QAction::LowPriority); + const QIcon fillIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-justify-fill.png")); + m_actionAlignJustify = new QAction(fillIcon, tr("&Justify"), this); + m_actionAlignJustify->setShortcut(Qt::CTRL + Qt::Key_J); + m_actionAlignJustify->setCheckable(true); + m_actionAlignJustify->setPriority(QAction::LowPriority); + const QIcon indentMoreIcon = QIcon::fromTheme(QStringLiteral("format-indent-more"), QIcon(rsrcPath()+ QStringLiteral("/format-indent-more.png"))); + m_actionIndentMore = menu->addAction(indentMoreIcon, tr("&Indent"), this, &LtsTextEditor2::indent); + m_actionIndentMore->setShortcut(Qt::CTRL + Qt::Key_BracketRight); + m_actionIndentMore->setPriority(QAction::LowPriority); + const QIcon indentLessIcon = QIcon::fromTheme(QStringLiteral("format-indent-less"), QIcon(rsrcPath()+ QStringLiteral("/format-indent-less.png"))); + m_actionIndentLess = menu->addAction(indentLessIcon, tr("&Unindent"), this, &LtsTextEditor2::unindent); + m_actionIndentLess->setShortcut(Qt::CTRL + Qt::Key_BracketLeft); + m_actionIndentLess->setPriority(QAction::LowPriority); - QActionGroup* alignGroup = new QActionGroup(this); - connect(alignGroup, &QActionGroup::triggered, this, &LtsTextEditor2::onTextAlign); + // Make sure the alignLeft is always left of the alignRight + QActionGroup *alignGroup = new QActionGroup(this); + connect(alignGroup, &QActionGroup::triggered, this, &LtsTextEditor2::onTextAlign); - if (QApplication::isLeftToRight()) - { - alignGroup->addAction(m_actionAlignLeft); - alignGroup->addAction(m_actionAlignCenter); - alignGroup->addAction(m_actionAlignRight); - } - else - { - alignGroup->addAction(m_actionAlignRight); - alignGroup->addAction(m_actionAlignCenter); - alignGroup->addAction(m_actionAlignLeft); - } - alignGroup->addAction(m_actionAlignJustify); + if (QApplication::isLeftToRight()) { + alignGroup->addAction(m_actionAlignLeft); + alignGroup->addAction(m_actionAlignCenter); + alignGroup->addAction(m_actionAlignRight); + } else { + alignGroup->addAction(m_actionAlignRight); + alignGroup->addAction(m_actionAlignCenter); + alignGroup->addAction(m_actionAlignLeft); + } + alignGroup->addAction(m_actionAlignJustify); - tb->addActions(alignGroup->actions()); - menu->addActions(alignGroup->actions()); - tb->addAction(m_actionIndentMore); - tb->addAction(m_actionIndentLess); - menu->addAction(m_actionIndentMore); - menu->addAction(m_actionIndentLess); + tb->addActions(alignGroup->actions()); + menu->addActions(alignGroup->actions()); + tb->addAction(m_actionIndentMore); + tb->addAction(m_actionIndentLess); + menu->addAction(m_actionIndentMore); + menu->addAction(m_actionIndentLess); - menu->addSeparator(); + menu->addSeparator(); - QPixmap pix(16, 16); - pix.fill(Qt::black); - m_actionTextColor = menu->addAction(pix, tr("&Color..."), this, &LtsTextEditor2::onTextColor); - m_actionTextColor->setPriority(QAction::LowPriority); - tb->addAction(m_actionTextColor); + QPixmap pix(16, 16); + pix.fill(Qt::black); + m_actionTextColor = menu->addAction(pix, tr("&Color..."), this, &LtsTextEditor2::onTextColor); + m_actionTextColor->setPriority(QAction::LowPriority); + tb->addAction(m_actionTextColor); - QPixmap pix2(16, 16); - pix2.fill(Qt::white); - m_actionBackgroundColor = new QAction(pix2, tr("&Background Color"), this); - m_actionBackgroundColor->setIcon(pix2); - m_actionBackgroundColor->setPriority(QAction::LowPriority); - connect(m_actionBackgroundColor, &QAction::triggered, this, &LtsTextEditor2::slotBackgroundColor); - tb->addAction(m_actionBackgroundColor); - menu->addSeparator(); + QPixmap pix2(16, 16); + pix2.fill(Qt::white); + m_actionBackgroundColor = new QAction(pix2, tr("&Background Color"), this); + m_actionBackgroundColor->setIcon(pix2); + m_actionBackgroundColor->setPriority(QAction::LowPriority); + connect(m_actionBackgroundColor, &QAction::triggered, this, &LtsTextEditor2::slotBackgroundColor); + tb->addAction(m_actionBackgroundColor); + menu->addSeparator(); - const QIcon checkboxIcon = QIcon::fromTheme(QStringLiteral("status-checkbox-checked"), - QIcon(rsrcPath() + QStringLiteral("/checkbox-checked.png"))); - m_actionToggleCheckState = menu->addAction(checkboxIcon, tr("Chec&ked"), this, &LtsTextEditor2::setChecked); - m_actionToggleCheckState->setShortcut(Qt::CTRL + Qt::Key_K); - m_actionToggleCheckState->setCheckable(true); - m_actionToggleCheckState->setPriority(QAction::LowPriority); - tb->addAction(m_actionToggleCheckState); + const QIcon checkboxIcon = QIcon::fromTheme(QStringLiteral("status-checkbox-checked"), QIcon(rsrcPath()+ QStringLiteral("/checkbox-checked.png"))); + m_actionToggleCheckState = menu->addAction(checkboxIcon, tr("Chec&ked"), this, &LtsTextEditor2::setChecked); + m_actionToggleCheckState->setShortcut(Qt::CTRL + Qt::Key_K); + m_actionToggleCheckState->setCheckable(true); + m_actionToggleCheckState->setPriority(QAction::LowPriority); + tb->addAction(m_actionToggleCheckState); - m_comboStyle = new QComboBox(tb); - m_comboStyleAction = tb->addWidget(m_comboStyle); - m_comboStyle->addItem(QStringLiteral("Standard")); - m_comboStyle->addItem(QStringLiteral("Bullet List (Disc)")); - m_comboStyle->addItem(QStringLiteral("Bullet List (Circle)")); - m_comboStyle->addItem(QStringLiteral("Bullet List (Square)")); - m_comboStyle->addItem(QStringLiteral("Task List (Unchecked)")); - m_comboStyle->addItem(QStringLiteral("Task List (Checked)")); - m_comboStyle->addItem(QStringLiteral("Ordered List (Decimal)")); - m_comboStyle->addItem(QStringLiteral("Ordered List (Alpha lower)")); - m_comboStyle->addItem(QStringLiteral("Ordered List (Alpha upper)")); - m_comboStyle->addItem(QStringLiteral("Ordered List (Roman lower)")); - m_comboStyle->addItem(QStringLiteral("Ordered List (Roman upper)")); - m_comboStyle->addItem(QStringLiteral("Heading 1")); - m_comboStyle->addItem(QStringLiteral("Heading 2")); - m_comboStyle->addItem(QStringLiteral("Heading 3")); - m_comboStyle->addItem(QStringLiteral("Heading 4")); - m_comboStyle->addItem(QStringLiteral("Heading 5")); - m_comboStyle->addItem(QStringLiteral("Heading 6")); + // tb = addToolBar(tr("Format Actions")); + // tb->setAllowedAreas(Qt::TopToolBarArea | Qt::BottomToolBarArea); + // addToolBarBreak(Qt::TopToolBarArea); + // addToolBar(tb); - connect(m_comboStyle, QOverload::of(&QComboBox::activated), this, &LtsTextEditor2::onTextStyle); + m_comboStyle = new QComboBox(tb); + m_comboStyleAction = tb->addWidget(m_comboStyle); + m_comboStyle->addItem(QStringLiteral("Standard")); + m_comboStyle->addItem(QStringLiteral("Bullet List (Disc)")); + m_comboStyle->addItem(QStringLiteral("Bullet List (Circle)")); + m_comboStyle->addItem(QStringLiteral("Bullet List (Square)")); + m_comboStyle->addItem(QStringLiteral("Task List (Unchecked)")); + m_comboStyle->addItem(QStringLiteral("Task List (Checked)")); + m_comboStyle->addItem(QStringLiteral("Ordered List (Decimal)")); + m_comboStyle->addItem(QStringLiteral("Ordered List (Alpha lower)")); + m_comboStyle->addItem(QStringLiteral("Ordered List (Alpha upper)")); + m_comboStyle->addItem(QStringLiteral("Ordered List (Roman lower)")); + m_comboStyle->addItem(QStringLiteral("Ordered List (Roman upper)")); + m_comboStyle->addItem(QStringLiteral("Heading 1")); + m_comboStyle->addItem(QStringLiteral("Heading 2")); + m_comboStyle->addItem(QStringLiteral("Heading 3")); + m_comboStyle->addItem(QStringLiteral("Heading 4")); + m_comboStyle->addItem(QStringLiteral("Heading 5")); + m_comboStyle->addItem(QStringLiteral("Heading 6")); - m_comboFont = new QFontComboBox(tb); - tb->addWidget(m_comboFont); - connect(m_comboFont, &QComboBox::textActivated, this, &LtsTextEditor2::onTextFamily); + connect(m_comboStyle, QOverload::of(&QComboBox::activated), this, &LtsTextEditor2::onTextStyle); - m_comboSize = new QComboBox(tb); - m_comboSize->setObjectName(QStringLiteral("comboSize")); - tb->addWidget(m_comboSize); - m_comboSize->setEditable(true); + m_comboFont = new QFontComboBox(tb); + tb->addWidget(m_comboFont); + connect(m_comboFont, &QComboBox::textActivated, this, &LtsTextEditor2::onTextFamily); - const QList standardSizes = QFontDatabase::standardSizes(); - for (int size : standardSizes) - m_comboSize->addItem(QString::number(size)); - m_comboSize->setCurrentIndex(standardSizes.indexOf(QApplication::font().pointSize())); + m_comboSize = new QComboBox(tb); + m_comboSize->setObjectName(QStringLiteral("comboSize")); + tb->addWidget(m_comboSize); + m_comboSize->setEditable(true); - connect(m_comboSize, &QComboBox::textActivated, this, &LtsTextEditor2::onTextSize); + const QList standardSizes = QFontDatabase::standardSizes(); + for (int size : standardSizes) + m_comboSize->addItem(QString::number(size)); + m_comboSize->setCurrentIndex(standardSizes.indexOf(QApplication::font().pointSize())); + + connect(m_comboSize, &QComboBox::textActivated, this, &LtsTextEditor2::onTextSize); } -bool LtsTextEditor2::load(const QString& f) +bool LtsTextEditor2::load(const QString &f) { - if (!QFile::exists(f)) - return false; - QFile file(f); - if (!file.open(QFile::ReadOnly)) - return false; + if (!QFile::exists(f)) + return false; + QFile file(f); + if (!file.open(QFile::ReadOnly)) + return false; - QByteArray data = file.readAll(); - QString str = QString::fromUtf8(data); - if (Qt::mightBeRichText(str)) - { - QUrl baseUrl = - (f.front() == QLatin1Char(':') ? QUrl(f) : QUrl::fromLocalFile(f)).adjusted(QUrl::RemoveFilename); - m_textEdit->document()->setBaseUrl(baseUrl); - m_textEdit->setHtml(str); - } - else - { + QByteArray data = file.readAll(); + QTextCodec *codec = Qt::codecForHtml(data); + QString str = codec->toUnicode(data); + if (Qt::mightBeRichText(str)) { + QUrl baseUrl = (f.front() == QLatin1Char(':') ? QUrl(f) : QUrl::fromLocalFile(f)).adjusted(QUrl::RemoveFilename); + m_textEdit->document()->setBaseUrl(baseUrl); + m_textEdit->setHtml(str); + } else { #if QT_CONFIG(textmarkdownreader) - QMimeDatabase db; - if (db.mimeTypeForFileNameAndData(f, data).name() == QStringLiteral("text/markdown")) - m_textEdit->setMarkdown(QString::fromUtf8(data)); - else + QMimeDatabase db; + if (db.mimeTypeForFileNameAndData(f, data).name() == QStringLiteral("text/markdown")) + m_textEdit->setMarkdown(QString::fromUtf8(data)); + else #endif - m_textEdit->setPlainText(QString::fromUtf8(data)); - } + m_textEdit->setPlainText(QString::fromUtf8(data)); + } - setCurrentFileName(f); - return true; + setCurrentFileName(f); + return true; } bool LtsTextEditor2::maybeSave() { - if (!m_textEdit->document()->isModified()) - return true; - - const QMessageBox::StandardButton ret = - QMessageBox::warning(this, QCoreApplication::applicationName(), - tr("The document has been modified.\n" - "Do you want to save your changes?"), - QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); - if (ret == QMessageBox::Save) - return onFileSave(); - else if (ret == QMessageBox::Cancel) - return false; + if (!m_textEdit->document()->isModified()) return true; + + const QMessageBox::StandardButton ret = + QMessageBox::warning(this, QCoreApplication::applicationName(), + tr("The document has been modified.\n" + "Do you want to save your changes?"), + QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); + if (ret == QMessageBox::Save) + return onFileSave(); + else if (ret == QMessageBox::Cancel) + return false; + return true; } -void LtsTextEditor2::setCurrentFileName(const QString& fileName) +void LtsTextEditor2::setCurrentFileName(const QString &fileName) { - this->m_fileName = fileName; - m_textEdit->document()->setModified(false); + this->m_fileName = fileName; + m_textEdit->document()->setModified(false); - QString shownName; - if (fileName.isEmpty()) - shownName = QStringLiteral("untitled.txt"); - else - shownName = QFileInfo(fileName).fileName(); + QString shownName; + if (fileName.isEmpty()) + shownName = QStringLiteral("untitled.txt"); + else + shownName = QFileInfo(fileName).fileName(); - setWindowTitle(tr("%1[*] - %2").arg(shownName, QCoreApplication::applicationName())); - setWindowModified(false); + setWindowTitle(tr("%1[*] - %2").arg(shownName, QCoreApplication::applicationName())); + setWindowModified(false); } void LtsTextEditor2::onFileNew() { - if (maybeSave()) - { - m_textEdit->clear(); - setCurrentFileName(QString()); - } + if (maybeSave()) { + m_textEdit->clear(); + setCurrentFileName(QString()); + } } void LtsTextEditor2::onFileOpen() { - QFileDialog fileDialog(this, tr("Open File...")); - fileDialog.setAcceptMode(QFileDialog::AcceptOpen); - fileDialog.setFileMode(QFileDialog::ExistingFile); - fileDialog.setMimeTypeFilters(QStringList() -#if QT_CONFIG(texthtmlparser) - << QStringLiteral("text/html") -#endif -#if QT_CONFIG(textmarkdownreader) + QFileDialog fileDialog(this, tr("Open File...")); + fileDialog.setAcceptMode(QFileDialog::AcceptOpen); + fileDialog.setFileMode(QFileDialog::ExistingFile); + fileDialog.setMimeTypeFilters(QStringList() + #if QT_CONFIG(texthtmlparser) + << QStringLiteral("text/html") + #endif + #if QT_CONFIG(textmarkdownreader) - << QStringLiteral("text/markdown") -#endif - << QStringLiteral("text/plain")); - if (fileDialog.exec() != QDialog::Accepted) - return; - const QStringList& fileNameList = fileDialog.selectedFiles(); - if (fileNameList.isEmpty()) - return; - QString fn = fileNameList.constFirst(); - if (load(fn)) - statusBar()->showMessage(tr("Opened \"%1\"").arg(QDir::toNativeSeparators(fn))); - else - statusBar()->showMessage(tr("Could not open \"%1\"").arg(QDir::toNativeSeparators(fn))); + << QStringLiteral("text/markdown") + #endif + << QStringLiteral("text/plain")); + if (fileDialog.exec() != QDialog::Accepted) + return; + const QStringList &fileNameList = fileDialog.selectedFiles(); + if (fileNameList.isEmpty()) + return; + QString fn = fileNameList.constFirst(); + if (load(fn)) + statusBar()->showMessage(tr("Opened \"%1\"").arg(QDir::toNativeSeparators(fn))); + else + statusBar()->showMessage(tr("Could not open \"%1\"").arg(QDir::toNativeSeparators(fn))); } bool LtsTextEditor2::onFileSave() { - if (m_fileName.isEmpty()) - return onFileSaveAs(); - if (m_fileName.startsWith(QStringLiteral(":/"))) - return onFileSaveAs(); + if (m_fileName.isEmpty()) + return onFileSaveAs(); + if (m_fileName.startsWith(QStringLiteral(":/"))) + return onFileSaveAs(); - QTextDocumentWriter writer(m_fileName); - bool success = writer.write(m_textEdit->document()); - if (success) - { - m_textEdit->document()->setModified(false); - statusBar()->showMessage(tr("Wrote \"%1\"").arg(QDir::toNativeSeparators(m_fileName))); - } - else - { - statusBar()->showMessage(tr("Could not write to file \"%1\"").arg(QDir::toNativeSeparators(m_fileName))); - } - return success; + QTextDocumentWriter writer(m_fileName); + bool success = writer.write(m_textEdit->document()); + if (success) { + m_textEdit->document()->setModified(false); + statusBar()->showMessage(tr("Wrote \"%1\"").arg(QDir::toNativeSeparators(m_fileName))); + } else { + statusBar()->showMessage(tr("Could not write to file \"%1\"") + .arg(QDir::toNativeSeparators(m_fileName))); + } + return success; } bool LtsTextEditor2::onFileSaveAs() { - QFileDialog fileDialog(this, tr("Save as...")); - fileDialog.setAcceptMode(QFileDialog::AcceptSave); - QStringList mimeTypes; - mimeTypes << QStringLiteral("text/plain") + QFileDialog fileDialog(this, tr("Save as...")); + fileDialog.setAcceptMode(QFileDialog::AcceptSave); + QStringList mimeTypes; + mimeTypes << QStringLiteral("text/plain") + #if QT_CONFIG(textodfwriter) + << QStringLiteral("application/vnd.oasis.opendocument.text") + #endif + #if QT_CONFIG(textmarkdownwriter) + << QStringLiteral("text/markdown") + #endif + << QStringLiteral("text/html"); + fileDialog.setMimeTypeFilters(mimeTypes); #if QT_CONFIG(textodfwriter) - << QStringLiteral("application/vnd.oasis.opendocument.text") + fileDialog.setDefaultSuffix(QStringLiteral("odt")); #endif -#if QT_CONFIG(textmarkdownwriter) - << QStringLiteral("text/markdown") -#endif - << QStringLiteral("text/html"); - fileDialog.setMimeTypeFilters(mimeTypes); -#if QT_CONFIG(textodfwriter) - fileDialog.setDefaultSuffix(QStringLiteral("odt")); -#endif - if (fileDialog.exec() != QDialog::Accepted) - return false; - const QStringList& fileNameList = fileDialog.selectedFiles(); - if (fileNameList.isEmpty()) - return false; - QString fn = fileNameList.constFirst(); - setCurrentFileName(fn); - return onFileSave(); + if (fileDialog.exec() != QDialog::Accepted) + return false; + const QStringList &fileNameList = fileDialog.selectedFiles(); + if (fileNameList.isEmpty()) + return false; + QString fn = fileNameList.constFirst(); + setCurrentFileName(fn); + return onFileSave(); } void LtsTextEditor2::onFilePrint() { #if defined(QT_PRINTSUPPORT_LIB) && QT_CONFIG(printdialog) - QPrinter printer(QPrinter::HighResolution); - QPrintDialog* dlg = new QPrintDialog(&printer, this); - if (textEdit->textCursor().hasSelection()) - dlg->addEnabledOption(QAbstractPrintDialog::PrintSelection); - dlg->setWindowTitle(tr("Print Document")); - if (dlg->exec() == QDialog::Accepted) - textEdit->print(&printer); - delete dlg; + QPrinter printer(QPrinter::HighResolution); + QPrintDialog *dlg = new QPrintDialog(&printer, this); + if (textEdit->textCursor().hasSelection()) + dlg->addEnabledOption(QAbstractPrintDialog::PrintSelection); + dlg->setWindowTitle(tr("Print Document")); + if (dlg->exec() == QDialog::Accepted) + textEdit->print(&printer); + delete dlg; #endif } void LtsTextEditor2::onFilePrintPreview() { #if defined(QT_PRINTSUPPORT_LIB) && QT_CONFIG(printpreviewdialog) - QPrinter printer(QPrinter::HighResolution); - QPrintPreviewDialog preview(&printer, this); - connect(&preview, &QPrintPreviewDialog::paintRequested, this, &LtsTextEditor2::printPreview); - preview.exec(); + QPrinter printer(QPrinter::HighResolution); + QPrintPreviewDialog preview(&printer, this); + connect(&preview, &QPrintPreviewDialog::paintRequested, this, &LtsTextEditor2::printPreview); + preview.exec(); #endif } -void LtsTextEditor2::printPreview(QPrinter* printer) +void LtsTextEditor2::printPreview(QPrinter *printer) { #if defined(QT_PRINTSUPPORT_LIB) && QT_CONFIG(printer) - textEdit->print(printer); + textEdit->print(printer); #else - Q_UNUSED(printer) + Q_UNUSED(printer) #endif } + void LtsTextEditor2::onFilePrintPdf() { #if defined(QT_PRINTSUPPORT_LIB) && QT_CONFIG(printer) - - QFileDialog fileDialog(this, tr("Export PDF")); - fileDialog.setAcceptMode(QFileDialog::AcceptSave); - fileDialog.setMimeTypeFilters(QStringList(QStringLiteral("application/pdf"))); - fileDialog.setDefaultSuffix(QStringLiteral("pdf")); - if (fileDialog.exec() != QDialog::Accepted) - return; - const QStringList& fileNameList = fileDialog.selectedFiles(); - if (fileNameList.isEmpty()) - return; - QString fileName = fileNameList.constFirst(); - QPrinter printer(QPrinter::HighResolution); - printer.setOutputFormat(QPrinter::PdfFormat); - printer.setOutputFileName(fileName); - textEdit->document()->print(&printer); - statusBar()->showMessage(tr("Exported \"%1\"").arg(QDir::toNativeSeparators(fileName))); - + //! [0] + QFileDialog fileDialog(this, tr("Export PDF")); + fileDialog.setAcceptMode(QFileDialog::AcceptSave); + fileDialog.setMimeTypeFilters(QStringList(QStringLiteral("application/pdf"))); + fileDialog.setDefaultSuffix(QStringLiteral("pdf")); + if (fileDialog.exec() != QDialog::Accepted) + return; + const QStringList &fileNameList = fileDialog.selectedFiles(); + if (fileNameList.isEmpty()) + return; + QString fileName = fileNameList.constFirst(); + QPrinter printer(QPrinter::HighResolution); + printer.setOutputFormat(QPrinter::PdfFormat); + printer.setOutputFileName(fileName); + textEdit->document()->print(&printer); + statusBar()->showMessage(tr("Exported \"%1\"") + .arg(QDir::toNativeSeparators(fileName))); + //! [0] #endif } void LtsTextEditor2::onTextBold() { - QTextCharFormat fmt; - fmt.setFontWeight(m_actionTextBold->isChecked() ? QFont::Bold : QFont::Normal); - mergeFormatOnWordOrSelection(fmt); + QTextCharFormat fmt; + fmt.setFontWeight(m_actionTextBold->isChecked() ? QFont::Bold : QFont::Normal); + mergeFormatOnWordOrSelection(fmt); } void LtsTextEditor2::onTextUnderline() { - QTextCharFormat fmt; - fmt.setFontUnderline(m_actionTextUnderline->isChecked()); - mergeFormatOnWordOrSelection(fmt); + QTextCharFormat fmt; + fmt.setFontUnderline(m_actionTextUnderline->isChecked()); + mergeFormatOnWordOrSelection(fmt); } void LtsTextEditor2::onTextItalic() { - QTextCharFormat fmt; - fmt.setFontItalic(m_actionTextItalic->isChecked()); - mergeFormatOnWordOrSelection(fmt); + QTextCharFormat fmt; + fmt.setFontItalic(m_actionTextItalic->isChecked()); + mergeFormatOnWordOrSelection(fmt); } -void LtsTextEditor2::onTextFamily(const QString& f) +void LtsTextEditor2::onTextFamily(const QString &f) { - QTextCharFormat fmt; - fmt.setFontFamily(f); - mergeFormatOnWordOrSelection(fmt); + QTextCharFormat fmt; + fmt.setFontFamily(f); + mergeFormatOnWordOrSelection(fmt); } -void LtsTextEditor2::onTextSize(const QString& p) +void LtsTextEditor2::onTextSize(const QString &p) { - qreal pointSize = p.toFloat(); - if (p.toFloat() > 0) - { - QTextCharFormat fmt; - fmt.setFontPointSize(pointSize); - mergeFormatOnWordOrSelection(fmt); - } + qreal pointSize = p.toFloat(); + if (p.toFloat() > 0) { + QTextCharFormat fmt; + fmt.setFontPointSize(pointSize); + mergeFormatOnWordOrSelection(fmt); + } } void LtsTextEditor2::onTextStyle(int styleIndex) { - QTextCursor cursor = m_textEdit->textCursor(); - QTextListFormat::Style style = QTextListFormat::ListStyleUndefined; - QTextBlockFormat::MarkerType marker = QTextBlockFormat::MarkerType::NoMarker; + QTextCursor cursor = m_textEdit->textCursor(); + QTextListFormat::Style style = QTextListFormat::ListStyleUndefined; + QTextBlockFormat::MarkerType marker = QTextBlockFormat::MarkerType::NoMarker; - switch (styleIndex) - { - case 1: - style = QTextListFormat::ListDisc; - break; - case 2: - style = QTextListFormat::ListCircle; - break; - case 3: - style = QTextListFormat::ListSquare; - break; - case 4: - if (cursor.currentList()) - style = cursor.currentList()->format().style(); - else - style = QTextListFormat::ListDisc; - marker = QTextBlockFormat::MarkerType::Unchecked; - break; - case 5: - if (cursor.currentList()) - style = cursor.currentList()->format().style(); - else - style = QTextListFormat::ListDisc; - marker = QTextBlockFormat::MarkerType::Checked; - break; - case 6: - style = QTextListFormat::ListDecimal; - break; - case 7: - style = QTextListFormat::ListLowerAlpha; - break; - case 8: - style = QTextListFormat::ListUpperAlpha; - break; - case 9: - style = QTextListFormat::ListLowerRoman; - break; - case 10: - style = QTextListFormat::ListUpperRoman; - break; - default: - break; - } - - cursor.beginEditBlock(); - - QTextBlockFormat blockFmt = cursor.blockFormat(); - - if (style == QTextListFormat::ListStyleUndefined) - { - blockFmt.setObjectIndex(-1); - int headingLevel = styleIndex >= 11 ? styleIndex - 11 + 1 : 0; - blockFmt.setHeadingLevel(headingLevel); - cursor.setBlockFormat(blockFmt); - - int sizeAdjustment = headingLevel ? 4 - headingLevel : 0; - QTextCharFormat fmt; - fmt.setFontWeight(headingLevel ? QFont::Bold : QFont::Normal); - fmt.setProperty(QTextFormat::FontSizeAdjustment, sizeAdjustment); - cursor.select(QTextCursor::LineUnderCursor); - cursor.mergeCharFormat(fmt); - m_textEdit->mergeCurrentCharFormat(fmt); - } + switch (styleIndex) { + case 1: + style = QTextListFormat::ListDisc; + break; + case 2: + style = QTextListFormat::ListCircle; + break; + case 3: + style = QTextListFormat::ListSquare; + break; + case 4: + if (cursor.currentList()) + style = cursor.currentList()->format().style(); else - { - blockFmt.setMarker(marker); - cursor.setBlockFormat(blockFmt); - QTextListFormat listFmt; - if (cursor.currentList()) - { - listFmt = cursor.currentList()->format(); - } - else - { - listFmt.setIndent(blockFmt.indent() + 1); - blockFmt.setIndent(0); - cursor.setBlockFormat(blockFmt); - } - listFmt.setStyle(style); - cursor.createList(listFmt); - } + style = QTextListFormat::ListDisc; + marker = QTextBlockFormat::MarkerType::Unchecked; + break; + case 5: + if (cursor.currentList()) + style = cursor.currentList()->format().style(); + else + style = QTextListFormat::ListDisc; + marker = QTextBlockFormat::MarkerType::Checked; + break; + case 6: + style = QTextListFormat::ListDecimal; + break; + case 7: + style = QTextListFormat::ListLowerAlpha; + break; + case 8: + style = QTextListFormat::ListUpperAlpha; + break; + case 9: + style = QTextListFormat::ListLowerRoman; + break; + case 10: + style = QTextListFormat::ListUpperRoman; + break; + default: + break; + } - cursor.endEditBlock(); + cursor.beginEditBlock(); + + QTextBlockFormat blockFmt = cursor.blockFormat(); + + if (style == QTextListFormat::ListStyleUndefined) { + blockFmt.setObjectIndex(-1); + int headingLevel = styleIndex >= 11 ? styleIndex - 11 + 1 : 0; // H1 to H6, or Standard + blockFmt.setHeadingLevel(headingLevel); + cursor.setBlockFormat(blockFmt); + + int sizeAdjustment = headingLevel ? 4 - headingLevel : 0; // H1 to H6: +3 to -2 + QTextCharFormat fmt; + fmt.setFontWeight(headingLevel ? QFont::Bold : QFont::Normal); + fmt.setProperty(QTextFormat::FontSizeAdjustment, sizeAdjustment); + cursor.select(QTextCursor::LineUnderCursor); + cursor.mergeCharFormat(fmt); + m_textEdit->mergeCurrentCharFormat(fmt); + } else { + blockFmt.setMarker(marker); + cursor.setBlockFormat(blockFmt); + QTextListFormat listFmt; + if (cursor.currentList()) { + listFmt = cursor.currentList()->format(); + } else { + listFmt.setIndent(blockFmt.indent() + 1); + blockFmt.setIndent(0); + cursor.setBlockFormat(blockFmt); + } + listFmt.setStyle(style); + cursor.createList(listFmt); + } + + cursor.endEditBlock(); } void LtsTextEditor2::onTextColor() { - QColor col = QColorDialog::getColor(m_textEdit->textColor(), this); - if (!col.isValid()) - return; - QTextCharFormat fmt; - fmt.setForeground(col); - mergeFormatOnWordOrSelection(fmt); - colorChanged(col); + QColor col = QColorDialog::getColor(m_textEdit->textColor(), this); + if (!col.isValid()) + return; + QTextCharFormat fmt; + fmt.setForeground(col); + mergeFormatOnWordOrSelection(fmt); + colorChanged(col); } -void LtsTextEditor2::onTextAlign(QAction* a) +void LtsTextEditor2::onTextAlign(QAction *a) { - if (a == m_actionAlignLeft) - m_textEdit->setAlignment(Qt::AlignLeft | Qt::AlignAbsolute); - else if (a == m_actionAlignCenter) - m_textEdit->setAlignment(Qt::AlignHCenter); - else if (a == m_actionAlignRight) - m_textEdit->setAlignment(Qt::AlignRight | Qt::AlignAbsolute); - else if (a == m_actionAlignJustify) - m_textEdit->setAlignment(Qt::AlignJustify); + if (a == m_actionAlignLeft) + m_textEdit->setAlignment(Qt::AlignLeft | Qt::AlignAbsolute); + else if (a == m_actionAlignCenter) + m_textEdit->setAlignment(Qt::AlignHCenter); + else if (a == m_actionAlignRight) + m_textEdit->setAlignment(Qt::AlignRight | Qt::AlignAbsolute); + else if (a == m_actionAlignJustify) + m_textEdit->setAlignment(Qt::AlignJustify); } void LtsTextEditor2::setChecked(bool checked) { - onTextStyle(checked ? 5 : 4); + onTextStyle(checked ? 5 : 4); } void LtsTextEditor2::indent() { - modifyIndentation(1); + modifyIndentation(1); } void LtsTextEditor2::unindent() { - modifyIndentation(-1); + modifyIndentation(-1); } void LtsTextEditor2::modifyIndentation(int amount) { - QTextCursor cursor = m_textEdit->textCursor(); - cursor.beginEditBlock(); - if (cursor.currentList()) - { - QTextListFormat listFmt = cursor.currentList()->format(); - - QTextCursor above(cursor); - above.movePosition(QTextCursor::Up); - if (above.currentList() && listFmt.indent() + amount == above.currentList()->format().indent()) - { - above.currentList()->add(cursor.block()); - } - else - { - listFmt.setIndent(listFmt.indent() + amount); - cursor.createList(listFmt); - } + QTextCursor cursor = m_textEdit->textCursor(); + cursor.beginEditBlock(); + if (cursor.currentList()) { + QTextListFormat listFmt = cursor.currentList()->format(); + // See whether the line above is the list we want to move this item into, + // or whether we need a new list. + QTextCursor above(cursor); + above.movePosition(QTextCursor::Up); + if (above.currentList() && listFmt.indent() + amount == above.currentList()->format().indent()) { + above.currentList()->add(cursor.block()); + } else { + listFmt.setIndent(listFmt.indent() + amount); + cursor.createList(listFmt); } - else - { - QTextBlockFormat blockFmt = cursor.blockFormat(); - blockFmt.setIndent(blockFmt.indent() + amount); - cursor.setBlockFormat(blockFmt); - } - cursor.endEditBlock(); + } else { + QTextBlockFormat blockFmt = cursor.blockFormat(); + blockFmt.setIndent(blockFmt.indent() + amount); + cursor.setBlockFormat(blockFmt); + } + cursor.endEditBlock(); } -void LtsTextEditor2::currentCharFormatChanged(const QTextCharFormat& format) +void LtsTextEditor2::currentCharFormatChanged(const QTextCharFormat &format) { - fontChanged(format.font()); - colorChanged(format.foreground().color()); + fontChanged(format.font()); + colorChanged(format.foreground().color()); } void LtsTextEditor2::cursorPositionChanged() { - alignmentChanged(m_textEdit->alignment()); - QTextList* list = m_textEdit->textCursor().currentList(); - if (list) - { - switch (list->format().style()) - { - case QTextListFormat::ListDisc: - m_comboStyle->setCurrentIndex(1); - break; - case QTextListFormat::ListCircle: - m_comboStyle->setCurrentIndex(2); - break; - case QTextListFormat::ListSquare: - m_comboStyle->setCurrentIndex(3); - break; - case QTextListFormat::ListDecimal: - m_comboStyle->setCurrentIndex(6); - break; - case QTextListFormat::ListLowerAlpha: - m_comboStyle->setCurrentIndex(7); - break; - case QTextListFormat::ListUpperAlpha: - m_comboStyle->setCurrentIndex(8); - break; - case QTextListFormat::ListLowerRoman: - m_comboStyle->setCurrentIndex(9); - break; - case QTextListFormat::ListUpperRoman: - m_comboStyle->setCurrentIndex(10); - break; - default: - m_comboStyle->setCurrentIndex(-1); - break; - } - switch (m_textEdit->textCursor().block().blockFormat().marker()) - { - case QTextBlockFormat::MarkerType::NoMarker: - m_actionToggleCheckState->setChecked(false); - break; - case QTextBlockFormat::MarkerType::Unchecked: - m_comboStyle->setCurrentIndex(4); - m_actionToggleCheckState->setChecked(false); - break; - case QTextBlockFormat::MarkerType::Checked: - m_comboStyle->setCurrentIndex(5); - m_actionToggleCheckState->setChecked(true); - break; - } + alignmentChanged(m_textEdit->alignment()); + QTextList *list = m_textEdit->textCursor().currentList(); + if (list) { + switch (list->format().style()) { + case QTextListFormat::ListDisc: + m_comboStyle->setCurrentIndex(1); + break; + case QTextListFormat::ListCircle: + m_comboStyle->setCurrentIndex(2); + break; + case QTextListFormat::ListSquare: + m_comboStyle->setCurrentIndex(3); + break; + case QTextListFormat::ListDecimal: + m_comboStyle->setCurrentIndex(6); + break; + case QTextListFormat::ListLowerAlpha: + m_comboStyle->setCurrentIndex(7); + break; + case QTextListFormat::ListUpperAlpha: + m_comboStyle->setCurrentIndex(8); + break; + case QTextListFormat::ListLowerRoman: + m_comboStyle->setCurrentIndex(9); + break; + case QTextListFormat::ListUpperRoman: + m_comboStyle->setCurrentIndex(10); + break; + default: + m_comboStyle->setCurrentIndex(-1); + break; } - else - { - int headingLevel = m_textEdit->textCursor().blockFormat().headingLevel(); - m_comboStyle->setCurrentIndex(headingLevel ? headingLevel + 10 : 0); + switch (m_textEdit->textCursor().block().blockFormat().marker()) { + case QTextBlockFormat::MarkerType::NoMarker: + m_actionToggleCheckState->setChecked(false); + break; + case QTextBlockFormat::MarkerType::Unchecked: + m_comboStyle->setCurrentIndex(4); + m_actionToggleCheckState->setChecked(false); + break; + case QTextBlockFormat::MarkerType::Checked: + m_comboStyle->setCurrentIndex(5); + m_actionToggleCheckState->setChecked(true); + break; } + } else { + int headingLevel = m_textEdit->textCursor().blockFormat().headingLevel(); + m_comboStyle->setCurrentIndex(headingLevel ? headingLevel + 10 : 0); + } } void LtsTextEditor2::clipboardDataChanged() { #ifndef QT_NO_CLIPBOARD - if (const QMimeData* md = QApplication::clipboard()->mimeData()) - m_actionPaste->setEnabled(md->hasText()); + if (const QMimeData *md = QApplication::clipboard()->mimeData()) + m_actionPaste->setEnabled(md->hasText()); #endif } void LtsTextEditor2::about() { - QMessageBox::about(this, tr("About"), - tr("This example demonstrates Qt's " - "rich text editing facilities in action, providing an example " - "document for you to experiment with.")); + QMessageBox::about(this, tr("About"), tr("This example demonstrates Qt's " + "rich text editing facilities in action, providing an example " + "document for you to experiment with.")); } -void LtsTextEditor2::mergeFormatOnWordOrSelection(const QTextCharFormat& format) +void LtsTextEditor2::mergeFormatOnWordOrSelection(const QTextCharFormat &format) { - QTextCursor cursor = m_textEdit->textCursor(); - if (!cursor.hasSelection()) - cursor.select(QTextCursor::WordUnderCursor); - cursor.mergeCharFormat(format); - m_textEdit->mergeCurrentCharFormat(format); + QTextCursor cursor = m_textEdit->textCursor(); + if (!cursor.hasSelection()) + cursor.select(QTextCursor::WordUnderCursor); + cursor.mergeCharFormat(format); + m_textEdit->mergeCurrentCharFormat(format); } -void LtsTextEditor2::fontChanged(const QFont& f) +void LtsTextEditor2::fontChanged(const QFont &f) { - m_comboFont->setCurrentIndex(m_comboFont->findText(QFontInfo(f).family())); - m_comboSize->setCurrentIndex(m_comboSize->findText(QString::number(f.pointSize()))); - m_actionTextBold->setChecked(f.bold()); - m_actionTextItalic->setChecked(f.italic()); - m_actionTextUnderline->setChecked(f.underline()); + m_comboFont->setCurrentIndex(m_comboFont->findText(QFontInfo(f).family())); + m_comboSize->setCurrentIndex(m_comboSize->findText(QString::number(f.pointSize()))); + m_actionTextBold->setChecked(f.bold()); + m_actionTextItalic->setChecked(f.italic()); + m_actionTextUnderline->setChecked(f.underline()); } -void LtsTextEditor2::colorChanged(const QColor& c) +void LtsTextEditor2::colorChanged(const QColor &c) { - QPixmap pix(16, 16); - pix.fill(c); - m_actionTextColor->setIcon(pix); + QPixmap pix(16, 16); + pix.fill(c); + m_actionTextColor->setIcon(pix); } void LtsTextEditor2::alignmentChanged(Qt::Alignment a) { - if (a & Qt::AlignLeft) - m_actionAlignLeft->setChecked(true); - else if (a & Qt::AlignHCenter) - m_actionAlignCenter->setChecked(true); - else if (a & Qt::AlignRight) - m_actionAlignRight->setChecked(true); - else if (a & Qt::AlignJustify) - m_actionAlignJustify->setChecked(true); + if (a & Qt::AlignLeft) + m_actionAlignLeft->setChecked(true); + else if (a & Qt::AlignHCenter) + m_actionAlignCenter->setChecked(true); + else if (a & Qt::AlignRight) + m_actionAlignRight->setChecked(true); + else if (a & Qt::AlignJustify) + m_actionAlignJustify->setChecked(true); } } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor2.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor2.h index 353f282aa..6f92ae82b 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor2.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor2.h @@ -1,16 +1,22 @@ - - +/** +* @RDE_HEADER@ +* Widget to create Text Editor +* $Id$ +* $HeadURL$ +* $Author$ +*/ #pragma once -#include "lts_widgets_export.h" -#include -#include + +#include + #include #include -#include #include -#include +#include +#include #include +#include QT_BEGIN_NAMESPACE class QAction; @@ -27,110 +33,108 @@ namespace LtsWidgets class LTSWIDGETS_EXPORT LtsTextEditor2 : public QMainWindow { - Q_OBJECT + Q_OBJECT - public: - explicit LtsTextEditor2(QWidget* parent = nullptr); - ~LtsTextEditor2(); +public: + explicit LtsTextEditor2(QWidget *parent = nullptr); + ~LtsTextEditor2(); - static QString rsrcPath() - { - return (QStringLiteral(":/images/win")); - } + static QString rsrcPath(){return (QStringLiteral(":/images/win"));} - QColor m_backgroundColor{Qt::white}; - QColor m_foregroundColor{Qt::black}; + QColor m_backgroundColor{Qt::white}; + QColor m_foregroundColor{Qt::black}; - QTextEdit* textEdit(); - QColor backgroundColor() const; - void enableBackgroundColor(bool onOff); - void setInitialBackgroundColor(const QColor& bgColor); - bool load(const QString& f); + QTextEdit *textEdit(); + QColor backgroundColor() const; + void enableBackgroundColor(bool onOff); + void setInitialBackgroundColor(const QColor &bgColor); + bool load(const QString &f); - Q_SIGNALS: - void backgroundColorChanged(const QColor& bgColor); - public slots: +Q_SIGNALS: + void backgroundColorChanged(const QColor &bgColor); - private slots: - void onFileNew(); - void onFileOpen(); - bool onFileSave(); - bool onFileSaveAs(); - void onFilePrint(); - void onFilePrintPreview(); - void onFilePrintPdf(); +public slots: - void onTextBold(); - void onTextUnderline(); - void onTextItalic(); - void onTextFamily(const QString& f); - void onTextSize(const QString& p); - void onTextStyle(int styleIndex); - void onTextColor(); - void onTextAlign(QAction* a); - void setChecked(bool checked); - void indent(); - void unindent(); - void slotBackgroundColorChanged(const QColor& bgColor); - void slotBackgroundColor(); +private slots: + void onFileNew(); + void onFileOpen(); + bool onFileSave(); + bool onFileSaveAs(); + void onFilePrint(); + void onFilePrintPreview(); + void onFilePrintPdf(); - void currentCharFormatChanged(const QTextCharFormat& format); - void cursorPositionChanged(); + void onTextBold(); + void onTextUnderline(); + void onTextItalic(); + void onTextFamily(const QString &f); + void onTextSize(const QString &p); + void onTextStyle(int styleIndex); + void onTextColor(); + void onTextAlign(QAction *a); + void setChecked(bool checked); + void indent(); + void unindent(); + void slotBackgroundColorChanged(const QColor &bgColor); + void slotBackgroundColor(); - void clipboardDataChanged(); - void about(); - void printPreview(QPrinter*); + void currentCharFormatChanged(const QTextCharFormat &format); + void cursorPositionChanged(); - private: - void setupFileActions(); - void setupEditActions(); - void setupTextActions(); - bool maybeSave(); - void setCurrentFileName(const QString& fileName); - void modifyIndentation(int amount); + void clipboardDataChanged(); + void about(); + void printPreview(QPrinter *); - void mergeFormatOnWordOrSelection(const QTextCharFormat& format); - void fontChanged(const QFont& f); - void colorChanged(const QColor& c); - void alignmentChanged(Qt::Alignment a); +private: + void setupFileActions(); + void setupEditActions(); + void setupTextActions(); + bool maybeSave(); + void setCurrentFileName(const QString &fileName); + void modifyIndentation(int amount); - QAction* m_actionSave; - QAction* m_actionOpen; - QAction* m_actionQuit; - QAction* m_actionSaveAs; - QAction* m_actionNew; - QAction* m_actionPrint; - QAction* m_actionPreview; - QAction* m_actionExport; - QAction* m_actionTextBold; - QAction* m_actionTextUnderline; - QAction* m_actionTextItalic; - QAction* m_actionTextColor; - QAction* m_actionBackgroundColor; - QAction* m_actionAlignLeft; - QAction* m_actionAlignCenter; - QAction* m_actionAlignRight; - QAction* m_actionAlignJustify; - QAction* m_actionIndentLess; - QAction* m_actionIndentMore; - QAction* m_actionToggleCheckState; - QAction* m_actionUndo; - QAction* m_actionRedo; + void mergeFormatOnWordOrSelection(const QTextCharFormat &format); + void fontChanged(const QFont &f); + void colorChanged(const QColor &c); + void alignmentChanged(Qt::Alignment a); + + QAction *m_actionSave; + QAction *m_actionOpen; + QAction *m_actionQuit; + QAction *m_actionSaveAs; + QAction *m_actionNew; + QAction *m_actionPrint; + QAction *m_actionPreview; + QAction *m_actionExport; + QAction *m_actionTextBold; + QAction *m_actionTextUnderline; + QAction *m_actionTextItalic; + QAction *m_actionTextColor; + QAction *m_actionBackgroundColor; + QAction *m_actionAlignLeft; + QAction *m_actionAlignCenter; + QAction *m_actionAlignRight; + QAction *m_actionAlignJustify; + QAction *m_actionIndentLess; + QAction *m_actionIndentMore; + QAction *m_actionToggleCheckState; + QAction *m_actionUndo; + QAction *m_actionRedo; #ifndef QT_NO_CLIPBOARD - QAction* m_actionCut; - QAction* m_actionCopy; - QAction* m_actionPaste; + QAction *m_actionCut; + QAction *m_actionCopy; + QAction *m_actionPaste; #endif - QComboBox* m_comboStyle; - QAction* m_comboStyleAction; - QFontComboBox* m_comboFont; - QComboBox* m_comboSize; + QComboBox *m_comboStyle; + QAction *m_comboStyleAction; + QFontComboBox *m_comboFont; + QComboBox *m_comboSize; - QToolBar* m_tb; - QString m_fileName; - QTextEdit* m_textEdit; + QToolBar *m_tb; + QString m_fileName; + QTextEdit *m_textEdit; }; -} // namespace LtsWidgets + } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar.cpp index f6d1dd17e..64bf21a9e 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar.cpp @@ -1,27 +1,36 @@ - +/** +* @RDE_HEADER@ +* ToolBar wiht autohide on leave +* $Id$ +* $HeadURL$ +* $Author$ +*/ #include "lts_tool_bar.h" using namespace LtsWidgets; -LtsToolBar::LtsToolBar(QWidget* parent) : QToolBar(parent) +LtsToolBar::LtsToolBar(QWidget *parent) + : QToolBar(parent) { - setMaximumHeight(1); - setMinimumHeight(1); + setMaximumHeight(1); + setMinimumHeight(1); } -LtsToolBar::~LtsToolBar() {} - -void LtsToolBar::enterEvent(QEnterEvent* e) +LtsToolBar::~LtsToolBar() { - setMaximumHeight(50); - setMinimumHeight(50); - QToolBar::enterEvent(e); } -void LtsToolBar::leaveEvent(QEvent* e) +void LtsToolBar::enterEvent(QEnterEvent *e) { - setMaximumHeight(1); - setMinimumHeight(1); - QToolBar::leaveEvent(e); + setMaximumHeight(50); + setMinimumHeight(50); + QToolBar::enterEvent(e); +} + +void LtsToolBar::leaveEvent(QEvent *e) +{ + setMaximumHeight(1); + setMinimumHeight(1); + QToolBar::leaveEvent(e); } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar.h index 877dcce35..9c0f366e1 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar.h @@ -1,10 +1,15 @@ - +/** +* @RDE_HEADER@ +* ToolBar wiht autohide on leave +* $Id$ +* $HeadURL$ +* $Author$ +*/ #pragma once -#include "lts_widgets_export.h" -#include #include +#include "lts_widgets_export.h" namespace LtsWidgets { @@ -12,14 +17,16 @@ namespace LtsWidgets class LTSWIDGETS_EXPORT LtsToolBar : public QToolBar { - Q_OBJECT - public: - explicit LtsToolBar(QWidget* parent = nullptr); - ~LtsToolBar(); + Q_OBJECT +public: + explicit LtsToolBar(QWidget *parent = nullptr); + ~LtsToolBar(); + +protected: + void enterEvent(QEnterEvent *e) override; + void leaveEvent(QEvent *e) override; + - protected: - void enterEvent(QEnterEvent* e) override; - void leaveEvent(QEvent* e) override; }; -} // namespace LtsWidgets +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar_area.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar_area.cpp index a10945bcd..97ea5bc20 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar_area.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar_area.cpp @@ -1,345 +1,389 @@ - +/** +* @RDE_HEADER@ +* +* $Id$ +* $HeadURL$ +* $Author$ +*/ #include "lts_tool_bar_area.h" - -#include "lts_drag_icon.h" #include "ui_lts_tool_bar_area.h" +#include "lts_drag_icon.h" #include -#include #include #include #include +#include #include -#include #include -#include -#include +#include + namespace LtsWidgets { - +// +// ShortCut +// void ShortCut::clear() { - name.clear(); - identifier.clear(); - icon = nullptr; - shortcut->disconnect(icon); + name.clear(); + identifier.clear(); + icon = nullptr; + shortcut->disconnect(icon); } -LtsToolBarArea::LtsToolBarArea(QWidget* parent) : QWidget(parent), m_dummyLabel(nullptr), m_ui(new Ui::LtsToolBarArea) +// +// LtsToolBarArea +// +LtsToolBarArea::LtsToolBarArea(QWidget *parent) + : QWidget(parent) + , m_dummyLabel(nullptr) + , m_ui(new Ui::LtsToolBarArea) { - m_ui->setupUi(this); + m_ui->setupUi(this); - setAcceptDrops(true); - clearToolBarArea(); + setAcceptDrops(true); + clearToolBarArea(); - for (int i = Qt::Key_F5; i <= Qt::Key_F12; ++i) - { - ShortCut sc(this); - sc.shortcut->setKey(QKeySequence(i)); - sc.key = i; - m_functionKeys.insert(i, sc); - } + // Initialize shortcuts + for(int i=Qt::Key_F5; i<=Qt::Key_F12; ++i) + { + ShortCut sc(this); + sc.shortcut->setKey(QKeySequence(i)); + sc.key = i; + m_functionKeys.insert(i, sc); + } } LtsToolBarArea::~LtsToolBarArea() { - delete m_ui; + delete m_ui; } -void LtsToolBarArea::addMenuEntry(LtsDragIcon* entry, LtsDragIcon* after) +void LtsToolBarArea::addMenuEntry(LtsDragIcon *entry, LtsDragIcon *after) { - if (!entry) + if (!entry) + return; + // already added? -> ignore + if (m_foreignButtonMap.contains(entry)) + return; + + delete m_dummyLabel; + m_dummyLabel = nullptr; + + bool isInternalMove = false; + LtsDragIcon *foreignDragIcon = entry; + + for (int i = 0; i < m_buttonMap.size(); ++i) + { + if (m_buttonMap.at(i) == entry) + { + isInternalMove = true; + // internal move but no idea where to move to + if (after == nullptr) return; - - if (m_foreignButtonMap.contains(entry)) - return; - - delete m_dummyLabel; - m_dummyLabel = nullptr; - - bool isInternalMove = false; - LtsDragIcon* foreignDragIcon = entry; - - for (int i = 0; i < m_buttonMap.size(); ++i) - { - if (m_buttonMap.at(i) == entry) - { - isInternalMove = true; - - if (after == nullptr) - return; - m_buttonMap.removeAt(i); - foreignDragIcon = m_foreignButtonMap.at(i); - m_foreignButtonMap.removeAt(i); - m_ui->layToolbar->removeWidget(entry); - break; - } + m_buttonMap.removeAt(i); + foreignDragIcon = m_foreignButtonMap.at(i); + m_foreignButtonMap.removeAt(i); + m_ui->layToolbar->removeWidget(entry); + break; } + } - int index = m_buttonMap.size(); - for (int i = 0; i < m_buttonMap.size(); ++i) + // find place where to insert the entry + int index = m_buttonMap.size(); + for(int i = 0; i < m_buttonMap.size(); ++i) + { + if (m_buttonMap.at(i) == after || + m_foreignButtonMap.at(i) == after) { - if (m_buttonMap.at(i) == after || m_foreignButtonMap.at(i) == after) - { - index = i + 1; - break; - } + index = i + 1; + break; } + } - LtsDragIcon* newAction = entry; + // create new LtsDragIcon if it's a new item, otherwise use entry + LtsDragIcon *newAction = entry; - if (!isInternalMove) - { - newAction = new LtsDragIcon(this); - newAction->setIcon(entry->icon()); - newAction->setText(entry->text()); - newAction->setContext(entry->context()); - if (!entry->toolTip().isEmpty()) - newAction->setToolTip(entry->toolTip()); - newAction->setIconSize(ButtonSize::eDefault); - newAction->setButtonStyle(ButtonStyle::eIconOnly); - newAction->setIdentifier(entry->identifier()); + if (!isInternalMove) + { + newAction = new LtsDragIcon(this); + newAction->setIcon(entry->icon()); + newAction->setText(entry->text()); + newAction->setContext(entry->context()); + if (!entry->toolTip().isEmpty()) + newAction->setToolTip(entry->toolTip()); + newAction->setIconSize(ButtonSize::eDefault); + newAction->setButtonStyle(ButtonStyle::eIconOnly); + newAction->setIdentifier(entry->identifier()); - connect(newAction, &LtsDragIcon::clicked, entry, &LtsDragIcon::clicked); - connect(entry, &LtsDragIcon::destroyed, newAction, [this, newAction]() { - m_buttonMap.removeAll(newAction); - newAction->deleteLater(); - }); - newAction->setVisible(!entry->text().isEmpty()); - } - newAction->setContextMenuPolicy(Qt::CustomContextMenu); - connect(newAction, &LtsDragIcon::customContextMenuRequested, this, &LtsToolBarArea::showContextMenu); + connect(newAction, &LtsDragIcon::clicked, entry, &LtsDragIcon::clicked); + connect(entry, &LtsDragIcon::destroyed, newAction, + [this, newAction]() { m_buttonMap.removeAll(newAction); newAction->deleteLater(); }); + newAction->setVisible(!entry->text().isEmpty()); + } + newAction->setContextMenuPolicy(Qt::CustomContextMenu); + connect(newAction, &LtsDragIcon::customContextMenuRequested, + this, &LtsToolBarArea::showContextMenu); - m_foreignButtonMap.insert(index, foreignDragIcon); - m_buttonMap.insert(index, newAction); + m_foreignButtonMap.insert(index, foreignDragIcon); + m_buttonMap.insert(index, newAction); - connect(foreignDragIcon, &LtsDragIcon::enabledChanged, newAction, &LtsDragIcon::setEnabled); + connect(foreignDragIcon, &LtsDragIcon::enabledChanged, newAction, &LtsDragIcon::setEnabled); - m_ui->layToolbar->insertWidget(index + 1, newAction); - saveSettings(); + // first is a spacer -> +1 + m_ui->layToolbar->insertWidget(index + 1, newAction); + saveSettings(); } void LtsToolBarArea::clearToolBarArea() { - qDeleteAll(m_buttonMap); - m_buttonMap.clear(); - m_foreignButtonMap.clear(); - for (ShortCut& item : m_functionKeys) - item.clear(); + qDeleteAll(m_buttonMap); + m_buttonMap.clear(); + m_foreignButtonMap.clear(); + for(ShortCut &item : m_functionKeys) + item.clear(); - delete m_dummyLabel; - - m_dummyLabel = new QLabel(tr("Drop menu entry here"), this); - m_ui->layToolbar->addWidget(m_dummyLabel); + delete m_dummyLabel; + //create dummyLabel to help the operator + m_dummyLabel = new QLabel(tr("Drop menu entry here"), this); + m_ui->layToolbar->addWidget(m_dummyLabel); } -void LtsToolBarArea::setMenuEntries(const QVector& actions) +void LtsToolBarArea::setMenuEntries(const QVector &actions) { - clearToolBarArea(); + clearToolBarArea(); - for (LtsDragIcon* ico : actions) - addMenuEntry(ico); + for (LtsDragIcon* ico : actions) + addMenuEntry(ico); } QStringList LtsToolBarArea::menuEntries() const { - QStringList ret; - ret.reserve(m_foreignButtonMap.size()); - for (LtsDragIcon* dragIcon : m_foreignButtonMap) - ret << dragIcon->identifier(); + QStringList ret; + ret.reserve(m_foreignButtonMap.size()); + for (LtsDragIcon *dragIcon : m_foreignButtonMap) + ret << dragIcon->identifier(); - return ret; + return ret; } -void LtsToolBarArea::dragEnterEvent(QDragEnterEvent* event) + +//protected + +void LtsToolBarArea::dragEnterEvent(QDragEnterEvent *event) { - LtsDragIcon* source = qobject_cast(event->source()); - if (source) + LtsDragIcon *source = + qobject_cast(event->source()); + if (source) + { + if (!m_foreignButtonMap.contains(source)) { - if (!m_foreignButtonMap.contains(source)) - { - event->setDropAction(Qt::MoveAction); - event->accept(); - } + event->setDropAction(Qt::MoveAction); + event->accept(); } + } } -void LtsToolBarArea::dropEvent(QDropEvent* event) +void LtsToolBarArea::dropEvent(QDropEvent *event) { - LtsDragIcon* source = qobject_cast(event->source()); + LtsDragIcon *source = qobject_cast(event->source()); + // does not work when not dragged on a LtsDragIcon ... should be ok for now + LtsDragIcon *after = nullptr; + QWidget *w = childAt(event->pos()); + while (w) + { + after = qobject_cast(w); + if (after) + break; + w = w->parentWidget(); + } - LtsDragIcon* after = nullptr; - QWidget* w = childAt(event->pos()); - while (w) - { - after = qobject_cast(w); - if (after) - break; - w = w->parentWidget(); - } - - addMenuEntry(source, after); + addMenuEntry(source, after); } -QMenu* LtsToolBarArea::functionKeyMenu(QWidget* parent) +QMenu *LtsToolBarArea::functionKeyMenu(QWidget *parent) { - QMenu* menu = new QMenu(parent); - menu->setTitle(tr("Function Key")); - QAction* act; - for (auto val = m_functionKeys.begin(); val != m_functionKeys.end(); ++val) - { - ShortCut& shorty = val.value(); - act = menu->addAction(QStringLiteral("%1%2").arg( - shorty.keyName(), !shorty.name.isEmpty() ? QStringLiteral(" - %1").arg(shorty.name) : QString())); - act->setData(QVariant::fromValue(shorty.shortcut->key()[0])); - connect(act, &QAction::triggered, this, &LtsToolBarArea::functionKeyMenuTriggered); - } - menu->addSeparator(); - act = menu->addAction(tr("Remove Function Key")); - act->setData(-1); + QMenu* menu = new QMenu(parent); + menu->setTitle(tr("Function Key")); + QAction *act; + for(auto val = m_functionKeys.begin(); val != m_functionKeys.end(); ++val) + { + ShortCut &shorty = val.value(); + act = menu->addAction(QStringLiteral("%1%2").arg(shorty.keyName(), !shorty.name.isEmpty() ? QStringLiteral(" - %1").arg(shorty.name) : QString())); + act->setData(shorty.shortcut->key()[0]); connect(act, &QAction::triggered, this, &LtsToolBarArea::functionKeyMenuTriggered); - return menu; + } + menu->addSeparator(); + act = menu->addAction(tr("Remove Function Key")); + act->setData(-1); + connect(act, &QAction::triggered, this, &LtsToolBarArea::functionKeyMenuTriggered); + return menu; } void LtsToolBarArea::functionKeyMenuTriggered() { - QAction* act = qobject_cast(sender()); - if (!act) - return; - int fkey = act->data().toInt(); + QAction* act = qobject_cast(sender()); + if (!act) + return; + int fkey = act->data().toInt(); - if (fkey == -1) - removeFunctionKey(m_currentIdentifierForContextMenue); - else if (fkey > 0) - setFunctionKey(fkey, m_currentIdentifierForContextMenue); + if (fkey == -1) + removeFunctionKey(m_currentIdentifierForContextMenue); + else if (fkey > 0) + setFunctionKey(fkey, m_currentIdentifierForContextMenue); } -bool LtsToolBarArea::removeFunctionKey(const QString& action) -{ - if (action.isEmpty()) - return true; - for (auto val = m_functionKeys.begin(); val != m_functionKeys.end(); ++val) - { - ShortCut& itShortcut = val.value(); - if (itShortcut.identifier == action) - { - itShortcut.icon->removeModification(); - itShortcut.clear(); - break; - } - } - saveSettings(); +bool LtsToolBarArea::removeFunctionKey(const QString &action) +{ + if (action.isEmpty()) return true; + + // Clear Shortcut if it is on another key + for(auto val = m_functionKeys.begin(); val != m_functionKeys.end(); ++val) + { + ShortCut &itShortcut = val.value(); + if (itShortcut.identifier == action) + { + itShortcut.icon->removeModification(); + itShortcut.clear(); + break; + } + } + saveSettings(); + return true; } -bool LtsToolBarArea::setFunctionKey(int fkey, const QString& action) +bool LtsToolBarArea::setFunctionKey(int fkey, const QString &action) { + // Key in range? + if (fkey < Qt::Key_F5 || fkey > Qt::Key_F12) + return false; - if (fkey < Qt::Key_F5 || fkey > Qt::Key_F12) - return false; - - LtsDragIcon* icon = nullptr; - for (LtsDragIcon* ic : std::as_const(m_buttonMap)) + // Icon available? + LtsDragIcon *icon = nullptr; + for (LtsDragIcon *ic : qAsConst(m_buttonMap)) + { + if (ic->identifier() == action) { - if (ic->identifier() == action) - { - icon = ic; - break; - } + icon = ic; + break; } + } - if (!icon) - return false; + if (!icon) + return false; - ShortCut& shorty = m_functionKeys[fkey]; + // Take shortcut for key + ShortCut &shorty = m_functionKeys[fkey]; - for (LtsDragIcon* ic : std::as_const(m_buttonMap)) - if (ic->identifier() == shorty.identifier) - ic->removeModification(); + // Remove key symbol from any icon + for (LtsDragIcon *ic : qAsConst(m_buttonMap)) + if (ic->identifier() == shorty.identifier) + ic->removeModification(); - for (auto val = m_functionKeys.begin(); val != m_functionKeys.end(); ++val) + // Clear Shortcut if it is on another key + for(auto val = m_functionKeys.begin(); val != m_functionKeys.end(); ++val) + { + ShortCut &itShortcut = val.value(); + if (itShortcut.identifier == action) { - ShortCut& itShortcut = val.value(); - if (itShortcut.identifier == action) - { - itShortcut.clear(); - break; - } + itShortcut.clear(); + break; } + } - shorty.clear(); - shorty.identifier = icon->identifier(); - shorty.name = icon->text(); - shorty.icon = icon; - shorty.icon->setModification(shorty.keyName()); - connect(shorty.shortcut, &QShortcut::activated, icon, &LtsDragIcon::clicked); - saveSettings(); - return true; + // Apply new Shortcut + shorty.clear(); + shorty.identifier = icon->identifier(); + shorty.name = icon->text(); + shorty.icon = icon; + shorty.icon->setModification(shorty.keyName()); + connect(shorty.shortcut, &QShortcut::activated, icon, &LtsDragIcon::clicked); + saveSettings(); + return true; } QMap LtsToolBarArea::functionKeys() const { - QMap retVal; - for (auto val = m_functionKeys.begin(); val != m_functionKeys.end(); ++val) - { - const ShortCut& itShortcut = val.value(); - if (!itShortcut.identifier.isEmpty()) - retVal[itShortcut.key] = itShortcut.identifier; - } - return retVal; + QMap retVal; + for(auto val = m_functionKeys.begin(); val != m_functionKeys.end(); ++val) + { + const ShortCut &itShortcut = val.value(); + if (!itShortcut.identifier.isEmpty()) + retVal[itShortcut.key] = itShortcut.identifier; + } + return retVal; } -void LtsToolBarArea::removeMenuAction(LtsDragIcon* icon) +void LtsToolBarArea::removeMenuAction(LtsDragIcon *icon) { - - for (auto val = m_functionKeys.begin(); val != m_functionKeys.end(); ++val) + // Clear Shortcut + for(auto val = m_functionKeys.begin(); val != m_functionKeys.end(); ++val) + { + ShortCut &itShortcut = val.value(); + if (itShortcut.identifier == icon->identifier()) + itShortcut.clear(); + } + for (LtsDragIcon *ic : qAsConst(m_foreignButtonMap)) + { + if(ic->identifier() == icon->identifier()) { - ShortCut& itShortcut = val.value(); - if (itShortcut.identifier == icon->identifier()) - itShortcut.clear(); + m_foreignButtonMap.removeAll(ic); + break; } - for (LtsDragIcon* ic : std::as_const(m_foreignButtonMap)) - { - if (ic->identifier() == icon->identifier()) - { - m_foreignButtonMap.removeAll(ic); - break; - } - } - m_buttonMap.removeAll(icon); - m_ui->layToolbar->removeWidget(icon); - delete icon; - saveSettings(); + } + m_buttonMap.removeAll(icon); + m_ui->layToolbar->removeWidget(icon); + delete icon; + saveSettings(); } -void LtsToolBarArea::showContextMenu(const QPoint& pos) +void LtsToolBarArea::showContextMenu(const QPoint &pos) { - QPointer icon = qobject_cast(sender()); - if (!icon) - return; + QPointer icon = qobject_cast(sender()); + if (!icon) + return; - const QPoint& globalPos = icon->mapToGlobal(pos); + const QPoint &globalPos = icon->mapToGlobal(pos); - QMenu* contextMenu = new QMenu(this); - contextMenu->setAttribute(Qt::WA_DeleteOnClose); + QMenu *contextMenu = new QMenu(this); + contextMenu->setAttribute(Qt::WA_DeleteOnClose); - m_currentIdentifierForContextMenue = icon->identifier(); - connect(contextMenu, &QObject::destroyed, this, [this]() { m_currentIdentifierForContextMenue.clear(); }); + // update m_currentIdentifierForContextMenue + m_currentIdentifierForContextMenue = icon->identifier(); + connect(contextMenu, &QObject::destroyed, this, [this](){ + // qCritical() << " contextMenu destroyed"; + m_currentIdentifierForContextMenue.clear(); + }); - QAction* delAction = contextMenu->addAction(tr("Remove")); - connect(delAction, &QAction::triggered, this, [this, icon]() { - if (icon) - removeMenuAction(icon); - }); + // 1: Remove + QAction *delAction = contextMenu->addAction(tr("Remove")); // QtDocu: addAction: QMenu takes ownership + connect(delAction, &QAction::triggered, this, [this, icon] () { + if (icon) + removeMenuAction(icon); + }); - QMenu* fkeyMenu = functionKeyMenu(contextMenu); - contextMenu->addMenu(fkeyMenu); + // 2: FKeys + QMenu *fkeyMenu = functionKeyMenu(contextMenu); + contextMenu->addMenu(fkeyMenu); // QtDocu: addMenu: QMenu does NOT take ownership - contextMenu->popup(globalPos); + contextMenu->popup(globalPos); } -void LtsToolBarArea::saveSettings() {} + +void LtsToolBarArea::saveSettings() +{ +// LtsUtils::OperatorSettings *settings = LtsUtils::OperatorSettings::getInstance(); + +// settings->setValue(QStringLiteral("FunctionBars"), QStringLiteral("Functions"), menuEntries()); + +// QMap fKeys = functionKeys(); +// QMap variantMap; +// for(auto it = fKeys.cbegin(); it != fKeys.cend(); ++it) +// variantMap[QString::number(it.key())] = it.value(); +// settings->setValue(QStringLiteral("FunctionKeys"), QStringLiteral("Functions"), variantMap); +} } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar_area.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar_area.h index 7ce0f0129..47a067420 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar_area.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar_area.h @@ -1,13 +1,20 @@ - +/** +* @RDE_HEADER@ +* ToolBarArea that accepts LtsDragIcons +* $Id$ +* $HeadURL$ +* $Author$ +*/ #pragma once + #include "lts_widgets_export.h" -#include -#include -#include -#include #include +#include +#include +#include + class QMenu; class QLabel; @@ -23,96 +30,91 @@ class LtsDragIcon; struct ShortCut { - int key = 0; - QShortcut* shortcut = nullptr; - QString name; - QString identifier; - LtsDragIcon* icon = nullptr; + int key = 0; + QShortcut *shortcut = nullptr; + QString name; + QString identifier; + LtsDragIcon *icon = nullptr; + QString keyName() const {return shortcut ? shortcut->key().toString() : QString();} + void clear(); - QString keyName() const + explicit ShortCut(QWidget *parent = nullptr) + : shortcut(new QShortcut(parent)) + {} + + ~ShortCut() { delete shortcut; } + ShortCut(const ShortCut &o) + : key(o.key) + , name(o.name) + , identifier(o.identifier) + , icon(o.icon) + { + if (o.shortcut) { - return shortcut ? shortcut->key().toString() : QString(); + delete shortcut; + shortcut = new QShortcut(o.shortcut->key(), qobject_cast(o.shortcut->parent()), nullptr, nullptr, o.shortcut->context()); } + } - void clear(); + ShortCut &operator=(const ShortCut &o) + { + if (&o == this) + return *this; - explicit ShortCut(QWidget* parent = nullptr) : shortcut(new QShortcut(parent)) {} - - ~ShortCut() - { - delete shortcut; - } - - ShortCut(const ShortCut& o) : key(o.key), name(o.name), identifier(o.identifier), icon(o.icon) - { - if (o.shortcut) - { - delete shortcut; - shortcut = new QShortcut(o.shortcut->key(), qobject_cast(o.shortcut->parent()), nullptr, nullptr, - o.shortcut->context()); - } - } - - ShortCut& operator=(const ShortCut& o) - { - if (&o == this) - return *this; - - key = o.key; - name = o.name; - identifier = o.identifier; - icon = o.icon; - QWidget* parent = qobject_cast(shortcut->parent()); - delete shortcut; - if (o.shortcut) - shortcut = new QShortcut(o.shortcut->key(), qobject_cast(o.shortcut->parent()), nullptr, nullptr, - o.shortcut->context()); - else - shortcut = new QShortcut(parent); - return *this; - } + key = o.key; + name = o.name; + identifier = o.identifier; + icon = o.icon; + QWidget *parent = qobject_cast(shortcut->parent()); + delete shortcut; + if (o.shortcut) + shortcut = new QShortcut(o.shortcut->key(), qobject_cast(o.shortcut->parent()), nullptr, nullptr, o.shortcut->context()); + else + shortcut = new QShortcut(parent); + return *this; + } }; class LTSWIDGETS_EXPORT LtsToolBarArea : public QWidget { - Q_OBJECT - public: - explicit LtsToolBarArea(QWidget* parent = nullptr); - ~LtsToolBarArea(); + Q_OBJECT +public: + explicit LtsToolBarArea(QWidget *parent = nullptr); + ~LtsToolBarArea(); - void addMenuEntry(LtsDragIcon* entry, LtsDragIcon* after = nullptr); - void clearToolBarArea(); + void addMenuEntry(LtsDragIcon *entry, LtsDragIcon *after = nullptr); + void clearToolBarArea(); - void setMenuEntries(const QVector& actions); - QStringList menuEntries() const; + void setMenuEntries(const QVector &actions); + QStringList menuEntries() const; - bool setFunctionKey(int fkey, const QString& action); - QMap functionKeys() const; + bool setFunctionKey(int fkey, const QString &action); + QMap functionKeys() const; - bool removeFunctionKey(const QString& action); - void removeMenuAction(LtsDragIcon* icon); + bool removeFunctionKey(const QString &action); + void removeMenuAction(LtsDragIcon *icon); - public slots: - void showContextMenu(const QPoint& pos); - void functionKeyMenuTriggered(); +public slots: + void showContextMenu(const QPoint &pos); + void functionKeyMenuTriggered(); - protected: - void dragEnterEvent(QDragEnterEvent* event) override; - void dropEvent(QDropEvent* event) override; +protected: + void dragEnterEvent(QDragEnterEvent *event) override; + void dropEvent(QDropEvent *event) override; - private: - QMenu* functionKeyMenu(QWidget* parent); - QString m_currentIdentifierForContextMenue; +private: + QMenu* functionKeyMenu(QWidget *parent); + QString m_currentIdentifierForContextMenue; - QVector m_buttonMap; - QVector m_foreignButtonMap; - QMap m_functionKeys; - QLabel* m_dummyLabel; + QVector m_buttonMap; + QVector m_foreignButtonMap; + QMap m_functionKeys; + QLabel *m_dummyLabel; - Ui::LtsToolBarArea* m_ui; + Ui::LtsToolBarArea *m_ui; - void saveSettings(); + void saveSettings(); }; -} // namespace LtsWidgets +} //namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_box.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_box.cpp index 95a68c0a2..c7249b5a6 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_box.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_box.cpp @@ -1,4 +1,10 @@ - +/** +* @RDE_HEADER@ +* ToolBox for Menus +* $Id$ +* $HeadURL$ +* $Author$ +*/ #include "lts_tool_box.h" @@ -6,65 +12,79 @@ #include "lts_grid_layout.h" #include -#include #include +#include using namespace LtsWidgets; -LtsToolBox::LtsToolBox(QWidget* parent) : QToolBox(parent) + +LtsToolBox::LtsToolBox(QWidget *parent) + : QToolBox(parent) { - setMinimumSize(17, 200); - setContextMenuPolicy(Qt::CustomContextMenu); - connect(this, &LtsToolBox::customContextMenuRequested, this, &LtsToolBox::showContextMenu); + setMinimumSize(17, 200); + setContextMenuPolicy(Qt::CustomContextMenu); + connect(this, &LtsToolBox::customContextMenuRequested, + this, &LtsToolBox::showContextMenu); + + setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); - setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); } -LtsToolBox::~LtsToolBox() {} - -void LtsToolBox::resizeEvent(QResizeEvent* e) +LtsToolBox::~LtsToolBox() { - emit resized(e); - QToolBox::resizeEvent(e); } -void LtsToolBox::addItem(QWidget* widget, const QString& text) +void LtsToolBox::resizeEvent(QResizeEvent *e) { - setMinimumSize(120, 100); - QToolBox::addItem(widget, text); + emit resized(e); + QToolBox::resizeEvent(e); + } -void LtsToolBox::showContextMenu(const QPoint& pos) +void LtsToolBox::addItem(QWidget *widget, const QString &text) +{ + setMinimumSize(120, 100); + QToolBox::addItem(widget, text); +} + + +void LtsToolBox::showContextMenu(const QPoint &pos) { - QPoint globalPos = this->mapToGlobal(pos); + // for most widgets + QPoint globalPos = this->mapToGlobal(pos); + // for QAbstractScrollArea and derived classes you would use: + // QPoint globalPos = myWidget->viewport()->mapToGlobal(pos); - QMenu myMenu; - myMenu.addAction(tr("Icon and Text")); - QAction* to = myMenu.addAction(tr("Text Only")); - QAction* io = myMenu.addAction(tr("Icon Only")); + QMenu myMenu; + myMenu.addAction(tr("Icon and Text")); + QAction *to = myMenu.addAction(tr("Text Only")); + QAction *io = myMenu.addAction(tr("Icon Only")); - QAction* selectedItem = myMenu.exec(globalPos); - if (selectedItem) + + QAction *selectedItem = myMenu.exec(globalPos); // TODO: use popup, use signals & slots + if (selectedItem) + { + ButtonStyle newStyle = ButtonStyle::eTextNextToIcon; + if (selectedItem == to) + newStyle = ButtonStyle::eTextOnly; + if (selectedItem == io) + newStyle = ButtonStyle::eIconOnly; + + for (int i = 0; i < count(); i++) { - ButtonStyle newStyle = ButtonStyle::eTextNextToIcon; - if (selectedItem == to) - newStyle = ButtonStyle::eTextOnly; - if (selectedItem == io) - newStyle = ButtonStyle::eIconOnly; + const QList list = widget(i)->findChildren(); + for (LtsDragIcon *icon : list) + icon->setButtonStyle(newStyle); + LtsGridLayout *lay = qobject_cast(widget(i)->layout()); + if (lay) + lay->setAutoSize((newStyle == ButtonStyle::eIconOnly)); + } - for (int i = 0; i < count(); i++) - { - const QList list = widget(i)->findChildren(); - for (LtsDragIcon* icon : list) - icon->setButtonStyle(newStyle); - LtsGridLayout* lay = qobject_cast(widget(i)->layout()); - if (lay) - lay->setAutoSize((newStyle == ButtonStyle::eIconOnly)); - } - } - else - { - } + } + else + { + // nothing was chosen + } } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_box.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_box.h index a27f55286..b37cc7582 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_box.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_box.h @@ -1,10 +1,16 @@ - +/** +* @RDE_HEADER@ +* ToolBox for Menus +* $Id$ +* $HeadURL$ +* $Author$ +*/ #pragma once + #include "lts_base.h" #include "lts_widgets_export.h" -#include #include namespace LtsWidgets @@ -12,18 +18,19 @@ namespace LtsWidgets class LTSWIDGETS_EXPORT LtsToolBox : public QToolBox { - Q_OBJECT - public: - explicit LtsToolBox(QWidget* parent = nullptr); - ~LtsToolBox(); - void resizeEvent(QResizeEvent* e) override; - void addItem(QWidget* widget, const QString& text); + Q_OBJECT +public: + explicit LtsToolBox(QWidget *parent = nullptr); + ~LtsToolBox(); + void resizeEvent(QResizeEvent *e) override; + void addItem(QWidget *widget, const QString &text); - signals: - void resized(QResizeEvent* e); +signals: + void resized(QResizeEvent *e); + +public slots: + void showContextMenu(const QPoint &pos); - public slots: - void showContextMenu(const QPoint& pos); }; -} // namespace LtsWidgets +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_wait_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_wait_dialog.cpp index 62be76527..cb5e3efa3 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_wait_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_wait_dialog.cpp @@ -1,16 +1,17 @@ #include "lts_wait_dialog.h" - #include "lts_global_wait_dialog.h" + namespace LtsWidgets { -LtsWaitDialog::LtsWaitDialog(const QString& customText) +LtsWaitDialog::LtsWaitDialog(const QString &customText) { - LtsGlobalWaitDialog::getInstance()->wait(customText); + LtsGlobalWaitDialog::getInstance()->wait(customText); } + LtsWaitDialog::~LtsWaitDialog() { - LtsGlobalWaitDialog::getInstance()->done(); + LtsGlobalWaitDialog::getInstance()->done(); +} } -} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_wait_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_wait_dialog.h index 1182ffbe6..bf12ee359 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_wait_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_wait_dialog.h @@ -3,15 +3,17 @@ #include "lts_widgets_export.h" #include + #include + namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsWaitDialog { - public: - LtsWaitDialog(const QString& customText = {}); - ~LtsWaitDialog(); +public: + LtsWaitDialog(const QString &customText = {}); + ~LtsWaitDialog(); }; typedef std::unique_ptr LtsWaitDialogContainer; diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_widgets_export.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_widgets_export.h index 221c1b9fb..42df63dd9 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_widgets_export.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_widgets_export.h @@ -1,17 +1,21 @@ - - +/** + * Export definitions + * $Id$ + * $HeadURL$ + * $Author$ + */ #pragma once #include #ifndef LTSWIDGETS_EXPORT -#ifdef BUILD_STATIC_LIBRARIES -#define LTSWIDGETS_EXPORT -#else -#if defined(MAKE_LTSWIDGETS_LIB) -#define LTSWIDGETS_EXPORT Q_DECL_EXPORT -#else -#define LTSWIDGETS_EXPORT Q_DECL_IMPORT -#endif -#endif +# ifdef BUILD_STATIC_LIBRARIES +# define LTSWIDGETS_EXPORT +# else +# if defined(MAKE_LTSWIDGETS_LIB) +# define LTSWIDGETS_EXPORT Q_DECL_EXPORT +# else +# define LTSWIDGETS_EXPORT Q_DECL_IMPORT +# endif +# endif #endif diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/ltswidgetsplugin.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/ltswidgetsplugin.cpp index 7858bfa3f..1c1ce7053 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/ltswidgetsplugin.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/ltswidgetsplugin.cpp @@ -1,33 +1,39 @@ +/** + * @RDE_HEADER@ + * Das Designer-Plugin für nglwidgets + * $Id$ + * $HeadURL$ + * $Author$ + */ - -#include "lts_bitfield_widget.h" -#include "lts_combo_box.h" -#include "lts_dialog_button_box.h" -#include "lts_drag_icon.h" -#include "lts_elided_label.h" -#include "lts_frameless_dialog.h" -#include "lts_image_editor.h" -#include "lts_msec_date_time_edit.h" -#include "lts_multi_range_spinbox.h" -#include "lts_picture_view.h" -#include "lts_profile_button.h" -#include "lts_range_slider.h" -#include "lts_spinbox.h" -#include "lts_splitter.h" -#include "lts_tab_bar.h" -#include "lts_tab_sequence_widget.h" -#include "lts_tab_widget.h" -#include "lts_tool_bar.h" -#include "lts_tool_bar_area.h" -#include "lts_tool_box.h" +#include +#include +#include #include #include #include #include -#include -#include -#include +#include "lts_dialog_button_box.h" +#include "lts_elided_label.h" +#include "lts_image_editor.h" +#include "lts_picture_view.h" +#include "lts_profile_button.h" +#include "lts_splitter.h" +#include "lts_tab_bar.h" +#include "lts_tab_widget.h" +#include "lts_tool_bar.h" +#include "lts_tool_bar_area.h" +#include "lts_tool_box.h" +#include "lts_frameless_dialog.h" +#include "lts_drag_icon.h" +#include "lts_combo_box.h" +#include "lts_spinbox.h" +#include "lts_multi_range_spinbox.h" +#include "lts_range_slider.h" +#include "lts_msec_date_time_edit.h" +#include "lts_bitfield_widget.h" +#include "lts_tab_sequence_widget.h" #ifdef TABLET_MODE #include "lts_date_time_edit_touch.h" @@ -35,9 +41,9 @@ #include "lts_date_time_edit.h" #endif -#include "LtsImageCropper/lts_image_cropper.h" -#include "lts_base.h" #include "lts_led_widget.h" +#include "lts_base.h" +#include "LtsImageCropper/lts_image_cropper.h" namespace LtsWidgets { @@ -47,40 +53,35 @@ class LtsDesignerCustomWidgetInterface : public QObject, public QDesignerCustomW Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using QObject::QObject; bool isContainer() const override final { return false; } - bool isInitialized() const override final { return mInitialized; } - QIcon icon() const override final { - return QIcon(QStringLiteral(":style/icons/22x22/pushbutton.png")); + return QIcon(QStringLiteral(":style/icons/22x22/pushbutton.png")); // some dummy icon... } - QString codeTemplate() const override final { return QString(); } - QString group() const override final { return QLatin1String("Lts Widgets"); } - - void initialize(QDesignerFormEditorInterface*) override final + void initialize(QDesignerFormEditorInterface *) override final { mInitialized = true; } - private: +private: bool mInitialized = false; }; @@ -89,74 +90,65 @@ class LtsCoordWidgetPlugin final : public LtsDesignerCustomWidgetInterface Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsCoordTrans/lts_coord_widget.h"); } - QString name() const override { return QLatin1String("LtsCoordWidget::LtsCoordWidget"); } - QString toolTip() const override { return QLatin1String("Widget for entering a coordinate"); } - QString whatsThis() const override { return QLatin1String("Widget for entering a coordinate"); } - QString domXml() const override { return QStringLiteral(""); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { return new LtsCoordWidget::LtsCoordWidget(parent); } }; + class LtsDialogButtonBoxPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_dialog_button_box.h"); } - QString name() const override { return QLatin1String("LtsWidgets::LtsDialogButtonBox"); } - QString toolTip() const override { return QLatin1String("Widget for a LTS version of the Button Box"); } - QString whatsThis() const override { return QLatin1String("Widget for a LTS version of the Botton Box"); } - QString domXml() const override { return QStringLiteral(""); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { return new LtsWidgets::LtsDialogButtonBox(parent); } @@ -167,35 +159,30 @@ class LtsElidedLabelPlugin final : public LtsDesignerCustomWidgetInterface Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QStringLiteral("LtsWidgets/lts_elided_label.h"); } - QString name() const override { return QStringLiteral("LtsWidgets::LtsElidedLabel"); } - QString toolTip() const override { return QStringLiteral("A QLabel which automatically elided it's content if needed."); } - QString whatsThis() const override { return toolTip(); } - QString domXml() const override { return QStringLiteral(""); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { return new LtsWidgets::LtsElidedLabel(parent); } @@ -206,419 +193,375 @@ class LtsImageEditorPlugin final : public LtsDesignerCustomWidgetInterface Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_image_editor.h"); } - QString name() const override { return QLatin1String("LtsWidgets::LtsImageEditor"); } - QString toolTip() const override { return QLatin1String("Image Editor"); } - QString whatsThis() const override { return QLatin1String("ImageEditor"); } - QString domXml() const override { return QStringLiteral(""); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { return new LtsWidgets::LtsImageEditor(parent); } }; + class LtsPictureViewPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_picture_view.h"); } - QString name() const override { return QLatin1String("LtsWidgets::LtsPictureView"); } - QString toolTip() const override { return QLatin1String("Picture View Widget"); } - QString whatsThis() const override { return QLatin1String("Picture View Widget"); } - QString domXml() const override { return QStringLiteral(""); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { return new LtsWidgets::LtsPictureView(parent); } }; + class LtsProfileButtonPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_profile_button.h"); } - QString name() const override { return QLatin1String("LtsWidgets::LtsProfileButton"); } - QString toolTip() const override { return QLatin1String("Profile Button"); } - QString whatsThis() const override { return QLatin1String("Profile Button"); } - QString domXml() const override { return QStringLiteral(""); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { return new LtsWidgets::LtsProfileButton(parent); } }; + class LtsSplitterPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_splitter.h"); } - QString name() const override { return QLatin1String("LtsWidgets::LtsSplitter"); } - QString toolTip() const override { return QLatin1String("Splitter with sizes property"); } - QString whatsThis() const override { return QLatin1String("Splitter with sizes property"); } - QString domXml() const override { return QStringLiteral(""); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { return new LtsWidgets::LtsSplitter(parent); } }; + class LtsTabBarPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_tab_bar.h"); } - QString name() const override { return QLatin1String("LtsWidgets::LtsTabBar"); } - QString toolTip() const override { return QLatin1String("Tab Bar"); } - QString whatsThis() const override { return QLatin1String("Tab Bar"); } - QString domXml() const override { return QStringLiteral(""); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { return new LtsWidgets::LtsTabBar(parent); } }; + class LtsTabWidgetPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_tab_widget.h"); } - QString name() const override { return QLatin1String("LtsWidgets::LtsTabWidget"); } - QString toolTip() const override { return QLatin1String("Tab Widget"); } - QString whatsThis() const override { return QLatin1String("Tab Widget"); } - QString domXml() const override { return QStringLiteral(""); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { return new LtsWidgets::LtsTabWidget(parent); } }; + class LtsToolBarPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_tool_bar.h"); } - QString name() const override { return QLatin1String("LtsWidgets::LtsToolBar"); } - QString toolTip() const override { return QLatin1String("Tool Bar"); } - QString whatsThis() const override { return QLatin1String("Tool Bar"); } - QString domXml() const override { return QStringLiteral(""); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { return new LtsWidgets::LtsToolBar(parent); } }; + class LtsToolBarAreaPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_tool_bar_area.h"); } - QString name() const override { return QLatin1String("LtsWidgets::LtsToolBarArea"); } - QString toolTip() const override { return QLatin1String("Tool Bar Area"); } - QString whatsThis() const override { return QLatin1String("Tool Bar Area"); } - QString domXml() const override { return QStringLiteral(""); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { return new LtsWidgets::LtsToolBarArea(parent); } }; + class LtsToolBoxPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_tool_box.h"); } - QString name() const override { return QLatin1String("LtsWidgets::LtsToolBox"); } - QString toolTip() const override { return QLatin1String("Tool Box"); } - QString whatsThis() const override { return QLatin1String("Tool Box"); } - QString domXml() const override { return QStringLiteral(""); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { return new LtsWidgets::LtsToolBox(parent); } }; + class LtsDataViewPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsDataView/lts_data_view.h"); } - QString name() const override { return QLatin1String("LtsDataView::LtsDataView"); } - QString toolTip() const override { return QLatin1String("DataView"); } - QString whatsThis() const override { return QLatin1String("DataView"); } - QString domXml() const override { return QStringLiteral(""); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { return new LtsDataView::LtsDataView(parent); } }; + class LtsFramelessDialogPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_frameless_dialog.h"); } - QString name() const override { return QLatin1String("LtsWidgets::LtsFramelessDialog"); } - QString toolTip() const override { return QLatin1String("Enhanced QDialog"); } - QString whatsThis() const override { return QLatin1String("Dialog Widget"); } - QString domXml() const override { return QLatin1String("\ @@ -634,40 +577,36 @@ class LtsFramelessDialogPlugin final : public LtsDesignerCustomWidgetInterface \ "); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { return new LtsWidgets::LtsFramelessDialog(parent); } }; + class LtsDragIconPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_drag_icon.h"); } - QString name() const override { return QLatin1String("LtsWidgets::LtsDragIcon"); } - QString toolTip() const override { return QLatin1String("Class for standard buttons with icons"); } - QString whatsThis() const override { return QLatin1String("Button Widget"); } - QString domXml() const override { return QLatin1String("\ @@ -675,41 +614,37 @@ class LtsDragIconPlugin final : public LtsDesignerCustomWidgetInterface \ "); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { - LtsWidgets::LtsDragIcon* b = new LtsWidgets::LtsDragIcon(parent); + LtsWidgets::LtsDragIcon *b = new LtsWidgets::LtsDragIcon(parent); return b; } }; + class LtsComboBoxPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_combo_box.h"); } - QString name() const override { return QLatin1String("LtsWidgets::LtsComboBox"); } - QString toolTip() const override { return QLatin1String("Class for standard ComBoBoxes"); } - QString whatsThis() const override { return QLatin1String("ComboBox Widget"); } - QString domXml() const override { return QLatin1String("\ @@ -717,41 +652,37 @@ class LtsComboBoxPlugin final : public LtsDesignerCustomWidgetInterface \ "); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { - LtsWidgets::LtsComboBox* b = new LtsWidgets::LtsComboBox(parent); + LtsWidgets::LtsComboBox *b = new LtsWidgets::LtsComboBox(parent); return b; } }; + class LtsSpinBoxPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_spinbox.h"); } - QString name() const override { return QLatin1String("LtsWidgets::LtsSpinBox"); } - QString toolTip() const override { return QLatin1String("Class for standard SpinBoxes"); } - QString whatsThis() const override { return QLatin1String("SpinBox Widget"); } - QString domXml() const override { return QLatin1String("\ @@ -759,10 +690,9 @@ class LtsSpinBoxPlugin final : public LtsDesignerCustomWidgetInterface \ "); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { - LtsWidgets::LtsSpinBox* b = new LtsWidgets::LtsSpinBox(parent); + LtsWidgets::LtsSpinBox *b = new LtsWidgets::LtsSpinBox(parent); return b; } }; @@ -771,29 +701,25 @@ class LtsMultiRangeSpinBoxPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_multi_range_spinbox.h"); } - QString name() const override { return QLatin1String("LtsWidgets::LtsMultiRangeSpinBox"); } - QString toolTip() const override { return QLatin1String("Class for standard SpinBoxes with multiple ranges"); } - QString whatsThis() const override { return QLatin1String("SpinBox Widget"); } - QString domXml() const override { return QLatin1String("\ @@ -801,41 +727,38 @@ class LtsMultiRangeSpinBoxPlugin final : public LtsDesignerCustomWidgetInterface \ "); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { - LtsWidgets::LtsMultiRangeSpinBox* b = new LtsWidgets::LtsMultiRangeSpinBox(parent); + LtsWidgets::LtsMultiRangeSpinBox *b = new LtsWidgets::LtsMultiRangeSpinBox(parent); return b; } }; + + class LtsDoubleSpinBoxPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_spinbox.h"); } - QString name() const override { return QLatin1String("LtsWidgets::LtsDoubleSpinBox"); } - QString toolTip() const override { return QLatin1String("Class for standard DoubleSpinBoxes"); } - QString whatsThis() const override { return QLatin1String("DoubleSpinBox Widget"); } - QString domXml() const override { return QLatin1String("\ @@ -843,41 +766,37 @@ class LtsDoubleSpinBoxPlugin final : public LtsDesignerCustomWidgetInterface \ "); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { - LtsWidgets::LtsDoubleSpinBox* b = new LtsWidgets::LtsDoubleSpinBox(parent); + LtsWidgets::LtsDoubleSpinBox *b = new LtsWidgets::LtsDoubleSpinBox(parent); return b; } }; + class LtsDateTimeEditPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_date_time_edit.h"); } - QString name() const override { return QLatin1String("LtsWidgets::LtsDateTimeEdit"); } - QString toolTip() const override { return QLatin1String("Class for LTS Date Time Edit"); } - QString whatsThis() const override { return QLatin1String("LtsDateTimeEdit Widget"); } - QString domXml() const override { return QLatin1String("\n" @@ -889,10 +808,9 @@ class LtsDateTimeEditPlugin final : public LtsDesignerCustomWidgetInterface " \n" ""); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { - LtsWidgets::LtsDateTimeEdit* b = new LtsWidgets::LtsDateTimeEdit(parent); + LtsWidgets::LtsDateTimeEdit *b = new LtsWidgets::LtsDateTimeEdit(parent); return b; } }; @@ -902,35 +820,30 @@ class LtsFileDialogWidgetPlugin final : public LtsDesignerCustomWidgetInterface Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsFileDialog/lts_file_dialog.h"); } - QString name() const override { return QLatin1String("LtsWidgets::LtsFileDialogWidget"); } - QString toolTip() const override { return QLatin1String("File Dialog Widget"); } - QString whatsThis() const override { return QLatin1String("FileDialogWidget"); } - QString domXml() const override { return QStringLiteral(""); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { return new LtsWidgets::LtsFileDialogWidget(parent); } @@ -941,35 +854,30 @@ class LtsFileDialogPlugin final : public LtsDesignerCustomWidgetInterface Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsFileDialog/lts_file_dialog.h"); } - QString name() const override { return QLatin1String("LtsWidgets::LtsFileDialog"); } - QString toolTip() const override { return QLatin1String("File Dialog Widget"); } - QString whatsThis() const override { return QLatin1String("FileDialog"); } - QString domXml() const override { return QStringLiteral(""); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { return new LtsWidgets::LtsFileDialog(parent); } @@ -980,35 +888,30 @@ class LtsReportDisplayWidgetPlugin final : public LtsDesignerCustomWidgetInterfa Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsReportDisplay/lts_report_display_widget.h"); } - QString name() const override { return QLatin1String("LtsWidgets::LtsReportDisplayWidget"); } - QString toolTip() const override { return QLatin1String("Report Display Widget"); } - QString whatsThis() const override { return QLatin1String("ReportDisplayWidget"); } - QString domXml() const override { return QStringLiteral(""); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { return new LtsWidgets::LtsReportDisplayWidget(parent); } @@ -1018,29 +921,25 @@ class LtsLedWidgetPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_led_widget.h"); } - QString name() const override { return QLatin1String("LtsWidgets::LtsLedWidget"); } - QString toolTip() const override { return QLatin1String("Class for an LED Widget"); } - QString whatsThis() const override { return QLatin1String("LED Widget"); } - QString domXml() const override { return QLatin1String("\ @@ -1048,8 +947,7 @@ class LtsLedWidgetPlugin final : public LtsDesignerCustomWidgetInterface \ "); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { return new LtsWidgets::LtsLedWidget(parent); } @@ -1059,29 +957,25 @@ class LtsRangeSliderPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_range_slider.h"); } - QString name() const override { return QLatin1String("LtsWidgets::LtsRangeSlider"); } - QString toolTip() const override { return QLatin1String("Class for an Range Slider"); } - QString whatsThis() const override { return QLatin1String("Range Slider"); } - QString domXml() const override { return QLatin1String("\ @@ -1089,8 +983,7 @@ class LtsRangeSliderPlugin final : public LtsDesignerCustomWidgetInterface \ "); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { return new LtsWidgets::LtsRangeSlider(parent); } @@ -1100,34 +993,29 @@ class LtsImageCropperPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString name() const override { return QLatin1String("LtsWidgets::LtsImageCropper"); } - QString toolTip() const override { return QLatin1String("Class for an Image Cropper Widget"); } - QString whatsThis() const override { return QLatin1String("Image Cropper Widget"); } - QString includeFile() const override { return QLatin1String("LtsWidgets/LtsImageCropper/lts_image_cropper.h"); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { return new LtsWidgets::LtsImageCropper(parent); } - QString domXml() const override { return QLatin1String("\n" @@ -1157,34 +1045,29 @@ class LtsMSecDateTimeEditPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString name() const override { return QLatin1String("LtsWidgets::LtsMSecDateTimeEdit"); } - QString toolTip() const override { return QLatin1String("Class for an Date/Time Widget with 40msecs step."); } - QString whatsThis() const override { return QLatin1String("Date/Time Widget with 40msecs step"); } - QString includeFile() const override { return QLatin1String("LtsWidgets/lts_msec_date_time_edit.h"); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { return new LtsWidgets::LtsMSecDateTimeEdit(parent); } - QString domXml() const override { return QLatin1String("\n" @@ -1197,97 +1080,91 @@ class LtsBitfieldWidgetPlugin final : public LtsDesignerCustomWidgetInterface Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("lts_bitfield_widget.h"); } - QString name() const override { return QLatin1String("LtsWidgets::LtsBitfieldWidget"); } - QString toolTip() const override { return QLatin1String("Widget for bitwise displaying and editing of quint8"); } - QString whatsThis() const override { return QLatin1String("Widget for bitwise displaying and editing of quint8"); } - QString domXml() const override { return QStringLiteral(""); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { return new LtsWidgets::LtsBitfieldWidget(parent); } }; + class LtsTabSequenceWidgetPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) - public: +public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_tab_sequence_widget.h"); } - QString name() const override { return QLatin1String("LtsWidgets::LtsTabSequenceWidget"); } - QString toolTip() const override { return QLatin1String("Widget for a Tab Sequence"); } - QString whatsThis() const override { return QLatin1String("Widget for a Tab Sequence"); } - QString domXml() const override { return QStringLiteral(""); } - - QWidget* createWidget(QWidget* parent) override + QWidget *createWidget(QWidget *parent) override { return new LtsWidgets::LtsTabSequenceWidget(parent); } }; + class Plugin final : public QObject, public QDesignerCustomWidgetCollectionInterface { Q_OBJECT Q_PLUGIN_METADATA(IID "org.rde.sls.ltswidgetsplugin" FILE "ltswidgetsplugin.json") Q_INTERFACES(QDesignerCustomWidgetCollectionInterface) - public: - explicit Plugin(QObject* parent = nullptr); +public: + explicit Plugin(QObject *parent = nullptr); - QList customWidgets() const override + QList customWidgets() const override { return m_plugins; } - private: - QList m_plugins; +private: + QList m_plugins; }; -Plugin::Plugin(QObject* parent) : QObject(parent) + +Plugin::Plugin(QObject *parent) + : QObject(parent) { m_plugins.append(new LtsCoordWidgetPlugin(this)); m_plugins.append(new LtsDialogButtonBoxPlugin(this)); @@ -1320,6 +1197,5 @@ Plugin::Plugin(QObject* parent) : QObject(parent) m_plugins.append(new LtsTabSequenceWidgetPlugin(this)); } -} // namespace LtsWidgets - +} // namespace #include "ltswidgetsplugin.moc" diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/lts_picture_editing.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/lts_picture_editing.cpp index 373657a30..2cb882380 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/lts_picture_editing.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/lts_picture_editing.cpp @@ -1,215 +1,227 @@ - +/** + * @RDE_HEADER@ + * Crop pictures + * $Id$ + * $HeadURL$ + * $Author$ + * Created by Raphael Becker + */ #include "lts_picture_editing.h" - -#include "lts_picture_view.h" #include "ui_lts_picture_editing.h" +#include "lts_picture_view.h" + +#include +#include +#include +#include +#include #include -#include -#include -#include -#include -#include #include -LtsPictureEditing::LtsPictureEditing(QWidget* parent) - : QMainWindow(parent), m_gvPicture(nullptr), m_ui(new Ui::PictureEditing) +LtsPictureEditing::LtsPictureEditing(QWidget *parent) + : QMainWindow(parent) + , m_gvPicture(nullptr) + , m_ui(new Ui::PictureEditing) { - m_ui->setupUi(this); - connect(m_ui->actionOpen, &QAction::triggered, this, &LtsPictureEditing::onOpenImage); - connect(m_ui->actionSave, &QAction::triggered, this, &LtsPictureEditing::onSavePicture); - connect(m_ui->actionQuit, &QAction::triggered, this, &LtsPictureEditing::close); - connect(m_ui->pbSetSize, &QPushButton::clicked, this, &LtsPictureEditing::onSetSize); + m_ui->setupUi(this); + connect(m_ui->actionOpen, &QAction::triggered, this, &LtsPictureEditing::onOpenImage); + connect(m_ui->actionSave, &QAction::triggered, this, &LtsPictureEditing::onSavePicture); + connect(m_ui->actionQuit, &QAction::triggered, this, &LtsPictureEditing::close); + connect(m_ui->pbSetSize, &QPushButton::clicked, this, &LtsPictureEditing::onSetSize); - connect(m_ui->sbHeight, QOverload::of(&QSpinBox::valueChanged), this, &LtsPictureEditing::onRatioChanged); - connect(m_ui->sbWidth, QOverload::of(&QSpinBox::valueChanged), this, &LtsPictureEditing::onRatioChanged); - connect(m_ui->chbRatio, &QPushButton::clicked, this, &LtsPictureEditing::onRatioClicked); + connect(m_ui->sbHeight, QOverload::of(&QSpinBox::valueChanged), this, &LtsPictureEditing::onRatioChanged); + connect(m_ui->sbWidth, QOverload::of(&QSpinBox::valueChanged), this, &LtsPictureEditing::onRatioChanged); + connect(m_ui->chbRatio, &QPushButton::clicked, this, &LtsPictureEditing::onRatioClicked); - connect(m_ui->sbXMin, QOverload::of(&QSpinBox::valueChanged), this, &LtsPictureEditing::onLeftChanged); - connect(m_ui->sbXMax, QOverload::of(&QSpinBox::valueChanged), this, &LtsPictureEditing::onRightChanged); - connect(m_ui->sbYMin, QOverload::of(&QSpinBox::valueChanged), this, &LtsPictureEditing::onTopChanged); - connect(m_ui->sbYMax, QOverload::of(&QSpinBox::valueChanged), this, &LtsPictureEditing::onBottomChanged); + connect(m_ui->sbXMin, QOverload::of(&QSpinBox::valueChanged), this, &LtsPictureEditing::onLeftChanged); + connect(m_ui->sbXMax, QOverload::of(&QSpinBox::valueChanged), this, &LtsPictureEditing::onRightChanged); + connect(m_ui->sbYMin, QOverload::of(&QSpinBox::valueChanged), this, &LtsPictureEditing::onTopChanged); + connect(m_ui->sbYMax, QOverload::of(&QSpinBox::valueChanged), this, &LtsPictureEditing::onBottomChanged); - addViewToFrame(); + addViewToFrame(); - connect(this, &LtsPictureEditing::leftChanged, m_gvPicture, &LtsWidgets::LtsPictureView::leftChanged); - connect(this, &LtsPictureEditing::rightChanged, m_gvPicture, &LtsWidgets::LtsPictureView::rightChanged); - connect(this, &LtsPictureEditing::topChanged, m_gvPicture, &LtsWidgets::LtsPictureView::topChanged); - connect(this, &LtsPictureEditing::bottomChanged, m_gvPicture, &LtsWidgets::LtsPictureView::bottomChanged); + connect(this, &LtsPictureEditing::leftChanged, m_gvPicture, &LtsWidgets::LtsPictureView::leftChanged); + connect(this, &LtsPictureEditing::rightChanged, m_gvPicture, &LtsWidgets::LtsPictureView::rightChanged); + connect(this, &LtsPictureEditing::topChanged, m_gvPicture, &LtsWidgets::LtsPictureView::topChanged); + connect(this, &LtsPictureEditing::bottomChanged, m_gvPicture, &LtsWidgets::LtsPictureView::bottomChanged); - connect(this, &LtsPictureEditing::setAspectRatio, m_gvPicture, &LtsWidgets::LtsPictureView::setAspectRatio); - connect(this, &LtsPictureEditing::ratioClicked, m_gvPicture, &LtsWidgets::LtsPictureView::ratioClicked); + connect(this, &LtsPictureEditing::setAspectRatio, m_gvPicture, &LtsWidgets::LtsPictureView::setAspectRatio); + connect(this, &LtsPictureEditing::ratioClicked, m_gvPicture, &LtsWidgets::LtsPictureView::ratioClicked); - connect(m_gvPicture, &LtsWidgets::LtsPictureView::mouseMoved, this, &LtsPictureEditing::setSpinboxValues); - connect(m_gvPicture, &LtsWidgets::LtsPictureView::setLimits, this, &LtsPictureEditing::setSpinboxLimits); - connect(this, &LtsPictureEditing::setPicture, m_gvPicture, &LtsWidgets::LtsPictureView::setPicture); + connect(m_gvPicture, &LtsWidgets::LtsPictureView::mouseMoved, this, &LtsPictureEditing::setSpinboxValues); + connect(m_gvPicture, &LtsWidgets::LtsPictureView::setLimits, this, &LtsPictureEditing::setSpinboxLimits); + connect(this, &LtsPictureEditing::setPicture, m_gvPicture, &LtsWidgets::LtsPictureView::setPicture); - onRatioChanged(); + onRatioChanged(); } LtsPictureEditing::~LtsPictureEditing() { - delete m_ui; + delete m_ui; } void LtsPictureEditing::addViewToFrame() { - QHBoxLayout* layout(new QHBoxLayout(m_ui->frPicFrame)); - m_gvPicture = new LtsWidgets::LtsPictureView(m_ui->frPicFrame); - layout->addWidget(m_gvPicture); - m_gvPicture->setEnabled(false); + QHBoxLayout *layout(new QHBoxLayout(m_ui->frPicFrame)); + m_gvPicture = new LtsWidgets::LtsPictureView(m_ui->frPicFrame); + layout->addWidget(m_gvPicture); + m_gvPicture->setEnabled(false); } void LtsPictureEditing::onOpenImage() { - const QStringList filter({tr("Images (*.jpg *.jpeg *.png)")}); - QString fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), QStringLiteral("../picture_editing"), - filter.join(QStringLiteral(";;"))); + const QStringList filter ({ + tr("Images (*.jpg *.jpeg *.png)") + }); + QString fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), + QStringLiteral("../picture_editing"), + filter.join(QStringLiteral(";;"))); - if (fileName.isEmpty()) - return; + if (fileName.isEmpty()) + return; - QFileInfo fi(fileName); - if (!fi.isReadable()) - { - QMessageBox::warning(this, tr("Error!"), - tr("An error occurred while loading the file.\n" - "The loaded file is not readable.")); - return; - } + QFileInfo fi(fileName); + if (!fi.isReadable()) + { + QMessageBox::warning(this, tr("Error!"), tr("An error occurred while loading the file.\n" + "The loaded file is not readable.")); + return; + } - QImage pic; - pic.load(fileName); - if (pic.isNull()) - { - QMessageBox::warning(this, tr("Error!"), - tr("An error occurred while loading the file.\n" - "The loaded file is no picture file.\n" - "Please load *.jpg, *.jpeg, *.png files only.")); - return; - } - m_image = pic; - emit setPicture(pic, QPoint(0, 0), true); - m_gvPicture->setEnabled(true); - m_gvPicture->newRubberBand(); + QImage pic; + pic.load(fileName); + if (pic.isNull()) + { + QMessageBox::warning(this, tr("Error!"), tr("An error occurred while loading the file.\n" + "The loaded file is no picture file.\n" + "Please load *.jpg, *.jpeg, *.png files only.")); + return; + } + m_image = pic; + emit setPicture(pic, QPoint(0, 0), true); + m_gvPicture->setEnabled(true); + m_gvPicture->newRubberBand(); } void LtsPictureEditing::onSetSize() { - if (m_image.isNull()) - return; + if (m_image.isNull()) + return; - m_gvPicture->hideRubberband(); + m_gvPicture->hideRubberband(); - int xMin = m_ui->sbXMin->value() - 1; - int yMin = m_ui->sbYMin->value() - 1; - int xMax = m_ui->sbXMax->value() - 1; - int yMax = m_ui->sbYMax->value() - 1; + int xMin = m_ui->sbXMin->value() - 1; + int yMin = m_ui->sbYMin->value() - 1; + int xMax = m_ui->sbXMax->value() - 1; + int yMax = m_ui->sbYMax->value() - 1; - if (xMax < xMin || yMax < yMin || xMax == xMin || yMax == yMin) - { - clear(); - return; - } + if (xMax < xMin || yMax < yMin || xMax == xMin || yMax == yMin) + { + clear(); + return; + } - QRect picRect(xMin, yMin, xMax - xMin, yMax - yMin); - QImage newPic = m_image.copy(picRect); - emit setPicture(newPic, QPoint(xMin, yMin), false); + QRect picRect(xMin, + yMin, + xMax - xMin, + yMax - yMin); + QImage newPic = m_image.copy(picRect); + emit setPicture(newPic, QPoint(xMin, yMin), false); } void LtsPictureEditing::onSavePicture() { - if (m_gvPicture->getImage()->pixmap().isNull()) + if (m_gvPicture->getImage()->pixmap().isNull()) + { + QMessageBox::warning(this, tr("Error!"), tr("An error occurred while saving the picture\n" + "Please load a picture before saving it.")); + return; + } + else + { + QString filename = QFileDialog::getSaveFileName(this, tr("Open Image"), QLatin1String("../picture_editing"), + tr("Images (*.jpg *.jpeg *.png)")); + if (filename.isEmpty()) { - QMessageBox::warning(this, tr("Error!"), - tr("An error occurred while saving the picture\n" - "Please load a picture before saving it.")); - return; + QMessageBox::warning(this, tr("Error!"), tr("An error occurred while saving the picture.\n" + "Please choose a valid path to save the picture.")); + return; } - else - { - QString filename = QFileDialog::getSaveFileName(this, tr("Open Image"), QLatin1String("../picture_editing"), - tr("Images (*.jpg *.jpeg *.png)")); - if (filename.isEmpty()) - { - QMessageBox::warning(this, tr("Error!"), - tr("An error occurred while saving the picture.\n" - "Please choose a valid path to save the picture.")); - return; - } - m_gvPicture->getImage()->pixmap().save(filename, "PNG"); - } + m_gvPicture->getImage()->pixmap().save(filename, "PNG"); + } } -void LtsPictureEditing::setSpinboxLimits(const QSize& picSize, bool setValues) +void LtsPictureEditing::setSpinboxLimits(const QSize &picSize, bool setValues) { - m_ui->sbXMin->setMaximum(picSize.width()); - m_ui->sbXMax->setMaximum(picSize.width()); - m_ui->sbYMin->setMaximum(picSize.height()); - m_ui->sbYMax->setMaximum(picSize.height()); + m_ui->sbXMin->setMaximum(picSize.width()); + m_ui->sbXMax->setMaximum(picSize.width()); + m_ui->sbYMin->setMaximum(picSize.height()); + m_ui->sbYMax->setMaximum(picSize.height()); - if (setValues) - { - m_ui->sbXMin->setValue(0); - m_ui->sbYMin->setValue(0); - m_ui->sbXMax->setValue(picSize.width() - 1); - m_ui->sbYMax->setValue(picSize.height() - 1); - } + if (setValues) + { + m_ui->sbXMin->setValue(0); + m_ui->sbYMin->setValue(0); + m_ui->sbXMax->setValue(picSize.width() - 1); + m_ui->sbYMax->setValue(picSize.height() - 1); + } } -void LtsPictureEditing::setSpinboxValues(const QRect& picRect) +void LtsPictureEditing::setSpinboxValues(const QRect &picRect) { - m_ui->sbXMin->setValue(picRect.left()); - m_ui->sbYMin->setValue(picRect.top()); - m_ui->sbXMax->setValue(picRect.right()); - m_ui->sbYMax->setValue(picRect.bottom()); + m_ui->sbXMin->setValue(picRect.left()); + m_ui->sbYMin->setValue(picRect.top()); + m_ui->sbXMax->setValue(picRect.right()); + m_ui->sbYMax->setValue(picRect.bottom()); } void LtsPictureEditing::onRatioChanged() { - double ratio = double(m_ui->sbWidth->value()) / double(m_ui->sbHeight->value()); - emit setAspectRatio(ratio); + double ratio = double(m_ui->sbWidth->value()) / double(m_ui->sbHeight->value()); + emit setAspectRatio(ratio); } void LtsPictureEditing::onRatioClicked() { - if (m_ui->chbRatio->isChecked()) - { - m_ui->sbHeight->setEnabled(true); - m_ui->sbWidth->setEnabled(true); - emit ratioClicked(true); - } - else - { - m_ui->sbHeight->setEnabled(false); - m_ui->sbWidth->setEnabled(false); - emit ratioClicked(false); - } + if (m_ui->chbRatio->isChecked()) + { + m_ui->sbHeight->setEnabled(true); + m_ui->sbWidth->setEnabled(true); + emit ratioClicked(true); + } + else + { + m_ui->sbHeight->setEnabled(false); + m_ui->sbWidth->setEnabled(false); + emit ratioClicked(false); + } } void LtsPictureEditing::onLeftChanged(int left) { - emit leftChanged(left); + emit leftChanged(left); } void LtsPictureEditing::onRightChanged(int right) { - emit rightChanged(right); + emit rightChanged(right); } void LtsPictureEditing::onTopChanged(int top) { - emit topChanged(top); + emit topChanged(top); } void LtsPictureEditing::onBottomChanged(int bottom) { - emit bottomChanged(bottom); + emit bottomChanged(bottom); } + void LtsPictureEditing::clear() { - emit setPicture(QImage(), QPoint(), false); + emit setPicture(QImage(), QPoint(), false); } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/lts_picture_editing.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/lts_picture_editing.h index 9f215637a..4db933dcd 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/lts_picture_editing.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/lts_picture_editing.h @@ -1,59 +1,66 @@ - +/** + * @RDE_HEADER@ + * Crop pictures + * $Id$ + * $HeadURL$ + * $Author$ + * Created by Raphael Becker + */ #pragma once + #include -#include namespace Ui { class PictureEditing; } -namespace LtsWidgets -{ -class LtsPictureView; +namespace LtsWidgets{ + class LtsPictureView; } + class LtsPictureEditing : public QMainWindow { - Q_OBJECT + Q_OBJECT - public: - explicit LtsPictureEditing(QWidget* parent = nullptr); - ~LtsPictureEditing(); +public: + explicit LtsPictureEditing(QWidget *parent = nullptr); + ~LtsPictureEditing(); - private: - QImage m_grayImage; - QImage m_image; +private: + QImage m_grayImage; + QImage m_image; - LtsWidgets::LtsPictureView* m_gvPicture; + LtsWidgets::LtsPictureView *m_gvPicture; - Ui::PictureEditing* m_ui; + Ui::PictureEditing *m_ui; - private: - void setSpinboxLimits(const QSize& picSize, bool setValues = true); - void clear(); - void addViewToFrame(); - void initRatio(); +private: + void setSpinboxLimits(const QSize &picSize, bool setValues = true); + void clear(); + void addViewToFrame(); + void initRatio(); - private slots: - void onOpenImage(); - void onSetSize(); - void setSpinboxValues(const QRect& picRect); - void onRatioChanged(); - void onRatioClicked(); - void onSavePicture(); - void onLeftChanged(int left); - void onRightChanged(int right); - void onTopChanged(int top); - void onBottomChanged(int bottom); +private slots: + void onOpenImage(); + void onSetSize(); + void setSpinboxValues(const QRect &picRect); + void onRatioChanged(); + void onRatioClicked(); + void onSavePicture(); + void onLeftChanged(int left); + void onRightChanged(int right); + void onTopChanged(int top); + void onBottomChanged(int bottom); - signals: - void setPicture(const QImage&, const QPoint&, const bool flag); - void setAspectRatio(double ratio); - void ratioClicked(bool enabled); - int leftChanged(int left); - int rightChanged(int right); - int topChanged(int top); - int bottomChanged(int bottom); +signals: + void setPicture(const QImage &, const QPoint &, const bool flag); + void setAspectRatio(double ratio); + void ratioClicked(bool enabled); + int leftChanged(int left); + int rightChanged(int right); + int topChanged(int top); + int bottomChanged(int bottom); }; diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/lts_picture_editing_main.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/lts_picture_editing_main.cpp index 751290f17..b338e73c7 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/lts_picture_editing_main.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/lts_picture_editing_main.cpp @@ -1,38 +1,45 @@ - +/** + * @RDE_HEADER@ + * Crop pictures + * $Id$ + * $HeadURL$ + * $Author$ + * Created by Raphael Becker + */ #include "lts_picture_editing.h" - #include #include -static void qtMsgHandler(QtMsgType type, const QMessageLogContext&, const QString& msg) +static void qtMsgHandler(QtMsgType type, const QMessageLogContext &, const QString &msg) { - switch (type) - { - case QtDebugMsg: - std::cout << "DEBUG: " << qPrintable(msg) << std::endl; - break; - case QtInfoMsg: - std::cout << "INFO: " << qPrintable(msg) << std::endl; - break; - case QtWarningMsg: - std::cout << "WARN: " << qPrintable(msg) << std::endl; - break; - case QtCriticalMsg: - std::cerr << "ERROR: " << qPrintable(msg) << std::endl; - break; - case QtFatalMsg: - std::cerr << "FATAL: " << qPrintable(msg) << std::endl; - break; - } + switch (type) + { + case QtDebugMsg: + std::cout << "DEBUG: " << qPrintable(msg) << std::endl; + break; + case QtInfoMsg: + std::cout << "INFO: " << qPrintable(msg) << std::endl; + break; + case QtWarningMsg: + std::cout << "WARN: " << qPrintable(msg) << std::endl; + break; + case QtCriticalMsg: + std::cerr << "ERROR: " << qPrintable(msg) << std::endl; + break; + case QtFatalMsg: + std::cerr << "FATAL: " << qPrintable(msg) << std::endl; + break; + } } -int main(int argc, char* argv[]) -{ - QApplication a(argc, argv); - qInstallMessageHandler(&qtMsgHandler); - LtsPictureEditing w; - w.show(); - return a.exec(); +int main(int argc, char *argv[]) +{ + QApplication a(argc, argv); + qInstallMessageHandler(&qtMsgHandler); + LtsPictureEditing w; + w.show(); + + return a.exec(); } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/main.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/main.cpp index 210ed2ec5..87fe42596 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/main.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/main.cpp @@ -1,15 +1,31 @@ -#include "window.h" - -#include #include -int main(int argc, char** argv) +#include "window.h" +#include + + +int main(int argc, char **argv) { - QApplication app(argc, argv); + QApplication app(argc, argv); - LtsWidgets::LtsDateTimeEdit dte; - dte.activateWindow(); - dte.show(); - return app.exec(); +// LtsWidgets::Window w; +// w.show(); +// w.activateWindow(); +// w.show(); + + + LtsWidgets::LtsDateTimeEdit dte; + dte.activateWindow(); + dte.show(); + + +// LtsWidgets::LtsDateTimeEditMod dtemod; +// dtemod.activateWindow(); +// dtemod.show(); + + //dtemod.setMsecsSinceEpoch(979216496789); // 11 12345678(9) Z jan 01 + + + return app.exec(); } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/window.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/window.cpp index 8c28659fa..8c55394a9 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/window.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/window.cpp @@ -1,48 +1,59 @@ #include "window.h" #include + #include #include + namespace LtsWidgets { -Window::Window(QWidget* parent) : QWidget(parent) +Window::Window(QWidget *parent) + : QWidget(parent) { + //Q_INIT_RESOURCE(lts_resources); - setGeometry(x(), y(), 300, 300); + setGeometry(x(), y(), 300, 300); - QHBoxLayout* lay = new QHBoxLayout; + QHBoxLayout *lay = new QHBoxLayout; - lay->setMargin(0); + lay->setMargin(0); + //lay->setSizeConstraint(QLayout::SetMinimumSize); - auto x1 = new LtsWidgets::LtsNotificationBox; - lay->addWidget(x1); - if (qApp->arguments().count() < 2) - abort(); + auto x1 = new LtsWidgets::LtsNotificationBox; + lay->addWidget(x1); - LtsNotificationBox::MessageType type; - if (qApp->arguments().at(1) == QStringLiteral("e")) - type = LtsNotificationBox::MessageType::Error; - else if (qApp->arguments().at(1) == QStringLiteral("w")) - type = LtsNotificationBox::MessageType::Warning; - else if (qApp->arguments().at(1) == QStringLiteral("i")) - type = LtsNotificationBox::MessageType::Info; - else if (qApp->arguments().at(1) == QStringLiteral("s")) - type = LtsNotificationBox::MessageType::Success; - else - abort(); + if (qApp->arguments().count() < 2) + abort(); - x1->message(QStringLiteral("Title Message"), - QStringLiteral("A text that consists of a lot of characters and also even has
two lines."), type); - connect(x1, &LtsNotificationBox::signalClose, this, &QWidget::close); - setLayout(lay); + LtsNotificationBox::MessageType type; - setAttribute(Qt::WA_TranslucentBackground); + if (qApp->arguments().at(1) == QStringLiteral("e")) + type = LtsNotificationBox::MessageType::Error; + else if (qApp->arguments().at(1) == QStringLiteral("w")) + type = LtsNotificationBox::MessageType::Warning; + else if (qApp->arguments().at(1) == QStringLiteral("i")) + type = LtsNotificationBox::MessageType::Info; + else if (qApp->arguments().at(1) == QStringLiteral("s")) + type = LtsNotificationBox::MessageType::Success; + else + abort(); + + x1->message(QStringLiteral("Title Message"), QStringLiteral("A text that consists of a lot of characters and also even has
two lines."), type); + connect(x1, &LtsNotificationBox::signalClose, this, &QWidget::close); + + setLayout(lay); + + setAttribute(Qt::WA_TranslucentBackground); } -Window::~Window() {} + +Window::~Window() +{ + //Q_CLEANUP_RESOURCE(lts_resources); +} } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/window.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/window.h index 43859df41..61f798447 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/window.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/window.h @@ -1,14 +1,16 @@ #pragma once -#include + #include + namespace LtsWidgets { class Window : public QWidget { - Q_OBJECT - public: - Window(QWidget* parent = nullptr); - ~Window(); + Q_OBJECT +public: + Window(QWidget *parent = nullptr); + ~Window(); + }; } // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/ui_requirement.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/ui_requirement.cpp new file mode 100755 index 000000000..6c030dfc6 --- /dev/null +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/ui_requirement.cpp @@ -0,0 +1,160 @@ +/** + * @RDE_HEADER@ + * Helper Classes to manage requirements for end-users to ui elements + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Mike Wille, SLSE, 2016-08-19 + */ + +#include "ui_requirement.h" + +#include + +#include +#include + + +namespace LtsWidgets +{ +UiRequirement::UiRequirement(QLabel *descriptionLabel, const std::function &requirementCheck, const QString &userWarningMessage) + : m_descriptionLabel(descriptionLabel) + , m_requirementCheck(requirementCheck) + , m_lastResult(true) + , m_userWarningMessage(userWarningMessage) +{ + retranslate(); +} + + +void UiRequirement::reset() +{ + if (!isValid()) + return; + m_descriptionLabel->setText(m_originalText); + m_descriptionLabel->setToolTip(m_originalTooltip); +} + + +void UiRequirement::setTexts() +{ + if (!isValid()) + return; + if (!m_lastResult) // requirement not met? change text color but only if this is NOT a simulation! + { + m_descriptionLabel->setText(QStringLiteral("\u2022 %1").arg(m_originalText)); // add requirement-indicator unicode 'bullet' + + if (!m_userWarningMessage.isEmpty()) + { + m_descriptionLabel->setCursor(Qt::WhatsThisCursor); + m_descriptionLabel->setToolTip(m_userWarningMessage); + } + } + else + { + if (m_originalText.startsWith(QStringLiteral("\u2022 "))) + return; + + m_descriptionLabel->setText(QStringLiteral("\u2022 %1").arg(m_originalText)); // set back to original text, as the requirement is now met and add requirement-indicator unicode 'bullet' + m_descriptionLabel->setCursor(Qt::ArrowCursor); + m_descriptionLabel->setToolTip(m_originalTooltip); + } +} + + +void UiRequirement::retranslate() +{ + if (!isValid()) + return; + + if (m_originalText.startsWith(QStringLiteral("\u2022 "))) + return; + + auto x = m_descriptionLabel->text(); + if (x.startsWith(QStringLiteral("\u2022 "))) + return; + + m_originalText = x; + + m_originalTooltip = m_descriptionLabel->toolTip(); + setTexts(); +} + + +bool UiRequirement::checkRequirement() +{ + if (!isValid()) + return m_lastResult; + + m_lastResult = m_requirementCheck(); + + if (!m_descriptionLabel->isVisible() && !m_descriptionLabel->property("checkMe").toBool()) // do not check when label is not visible (on some cases there are elemts which must not be used, so they are hidden and therefor not a requirement, and therefor "a met requirement") + { + return true; + } + + setTexts(); + + return m_lastResult; +} + + +bool UiRequirementList::checkRequirements(QWidget *messageOnThisParent) +{ + bool result = true; // as long no requirement failed (even if there are none), the result is positive + for (auto i = m_requirementList.begin(); i != m_requirementList.end(); ++i) + { + UiRequirement &r = (*i); + + // Todo: Delete from Vector! + if (!r.isValid()) + continue; + + if (!r.checkRequirement()) // requirement failed, so all requirements failed, but keep on checking the requirements (to show the user what exactly is wrong) + { + result = false; // to NOT break here, checkRequirement() marks all important errors, so it must be called, even if result was already set to false + } + } + + if (!result && messageOnThisParent) // show a message that one or more requirements are not met, but only when a pointer has been given to put the LtsMessageDialog on + { + LtsWidgets::LtsMessageDialog::showMessage(messageOnThisParent, + QApplication::translate("LtsWidgets::LtsDialog", + "There are elements that have invalid or no value.
" + "Please change values in the elements which are marked with red text."), + QApplication::translate("LtsWidgets::LtsDialog", "Operation not complete")); + } + + return result; +} + + +void UiRequirementList::addRequirement(const UiRequirement &uiRequirement) +{ + m_requirementList.append(uiRequirement); +} + + +void UiRequirementList::clear() +{ + for (auto i = m_requirementList.begin(); i != m_requirementList.end(); ++i) + { + UiRequirement &uir = *i; + uir.reset(); + } + + m_requirementList.clear(); +} + + +void UiRequirementList::retranslate() +{ + for (auto i = m_requirementList.begin(); i != m_requirementList.end(); ++i) + { + UiRequirement &r = (*i); + + r.retranslate(); + } +} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/ui_requirement.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/ui_requirement.h new file mode 100755 index 000000000..320e0b37c --- /dev/null +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/ui_requirement.h @@ -0,0 +1,98 @@ +/** + * @RDE_HEADER@ + * Helper Classes to manage requirements for end-users to ui elements + * $Id$ + * $HeadURL$ + * $Author$ + * + * Created by Mike Wille, SLSE, 2016-08-19 + */ + +#pragma once + +#include "lts_widgets_export.h" + +#include +#include +#include + + +class QLabel; + + +namespace LtsWidgets +{ +/** + * @brief The UiRequirement class describes a single UiRequirement. An UiRequirement is used to check that (valid) data is entered + * by a user into an editable Widget. After an UiRequirement is created, it automatically changes the description Label of the + * editable Widget by adding "[*]" to visualize that this Widget must be filled. If an UiRequirement is not met after executing the + * checkRequirement-Method, the Label is colored red to visualize an error to the user. + * + */ +class LTSWIDGETS_EXPORT UiRequirement // TODO: optional requirements => simply non-marked labels with advanced requirement checks (MessageDialog with message that e.g. "val of [widget-description] is too small") +{ +public: + explicit UiRequirement() = default; + + /** + * @brief UiRequirement + * @param descriptionLabel the Label, usually left of the editable Widget in a Form Layout, which describes the editable Widget to be checked + * @param requirementCheck the routine (c++11) to check if requirements are met for the editable Widget to be checked - return values: true when requirement(s) are met, false when not + */ + UiRequirement(QLabel *descriptionLabel, const std::function &requirementCheck, const QString &userWarningMessage = QString()); + + void reset(); + + /** + * @brief checkRequirement executes the requirementCheck function. If the description Label of the editable Widget is not visible, + * the requirement check is ignored (as, logically, the Widget is then optional). If the requirement is not met, the + * description Label of the editable Widget is colored red. + * @return true if requirement is met (or description Label of Widget is hidden (optional)), false if not met + */ + bool checkRequirement(); + + bool isValid() const { return m_descriptionLabel != nullptr; } + + void retranslate(); + +private: + void setTexts(); + + QLabel *m_descriptionLabel; + std::function m_requirementCheck; + QString m_originalText; + QString m_originalTooltip; + bool m_lastResult; + QString m_userWarningMessage; +}; + + +/** + * @brief The UiRequirementList class provides a list which contains UiRequirements, that can all be checked by one method call. + */ +class LTSWIDGETS_EXPORT UiRequirementList +{ +public: + UiRequirementList() = default; + + /** + * @brief checkRequirements checks every requirement in this list. If one or more requirements are not met, this method returns false. + * @param messageOnThisParent set this pointer to a QWidget to let the UiRequirementList generate a LtsMessageDialog which states that there are non-met requirements for the user, set to nullptr to not show a message + * @return true if all requirements are met, false if one or more requirements have NOT met + */ + bool checkRequirements(QWidget *messageOnThisParent = nullptr); + + /** + * @brief addRequirement adds an UiRequirement to this list. + * @param uiRequirement the UiRequirement to be copied & added. + */ + void addRequirement(const UiRequirement &uiRequirement); + + void clear(); + + void retranslate(); // TODO: remove after every UiReq is inside retranslate()-method + +private: + QVector m_requirementList; // TODo: to ptr as QVector does a graceful copy of the UiReq class, causing the original class to be destroyed +}; +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Data/asb_foreign_interface_impl.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Data/asb_foreign_interface_impl.h index d4c10bd94..e380f0d8b 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Data/asb_foreign_interface_impl.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Data/asb_foreign_interface_impl.h @@ -73,8 +73,11 @@ class ForeignInterfaceImpl final : public QObject, public ForeignDataInterface AdvancedSymbology::SymbolDictionary& getSymbolDictionary(AdvancedSymbology::SymbologyType type) const override { - static AdvancedSymbology::SymbolDictionary dummy; - return dummy; + Q_UNUSED(type) + // STUB: No external DDS - return nullptr reference (should not be called in stub mode) + static AdvancedSymbology::SymbolDictionary* dummy = nullptr; + Q_ASSERT_X(dummy, "ForeignInterfaceImpl::getSymbolDictionary", "Stub implementation should not be called"); + return *dummy; } QSharedPointer findImage(const SymbolDictionary& dict, @@ -89,8 +92,8 @@ class ForeignInterfaceImpl final : public QObject, public ForeignDataInterface Q_UNUSED(symDataToRender) return nullptr; } - QSharedPointer findImage(int participant, int sizeL = 100, - const QColor& desiredColor = QColor()) const override + QSharedPointer findImage(const ParticipantManagement::Participant& participant, int sizeL, + const QColor& desiredColor) const override { Q_UNUSED(participant) Q_UNUSED(sizeL) @@ -127,9 +130,6 @@ class ForeignInterfaceImpl final : public QObject, public ForeignDataInterface // STUB: No external DDS - return valid default return AdvancedSymbology::SymbologyType::APP6B; } - - private: - NGL::INGLLogger& m_logger = NGL::INGLLogger::instance(); }; #endif } // namespace AdvancedSymbology diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/Common/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/Common/CMakeLists.txt index 629ea63a2..0ca92ff24 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/Common/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/Common/CMakeLists.txt @@ -8,6 +8,7 @@ # # Data Plugin # +IF(BUILD_RTI) SET(alarm_common_gui_SRCS alm_history_alarm_model.cpp alm_history_alarm_model.h @@ -32,4 +33,10 @@ NGL_TARGET_LINK_LIBRARIES(AlmCommon advancedSymbology advancedSymbologyGui ngltools + svcGnaCommon ) +NGL_TARGET_INCLUDE_DIRECTORIES(AlmCommon + PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}/../../Proxies/GuezNasat/ +) +ENDIF(BUILD_RTI) diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Shared/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Shared/CMakeLists.txt index 078479370..3d671ca1f 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Shared/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Shared/CMakeLists.txt @@ -6,6 +6,8 @@ # Created by Christian Fröbel, NLSE, 2018-04-19 # +IF(BUILD_RTI) + set(SRCS avs_app.cpp avs_app.h @@ -43,3 +45,5 @@ NGL_TARGET_LINK_LIBRARIES(AvmShared ngltools ) NGL_INSTALL_TARGET(AvmShared) + +ENDIF(BUILD_RTI) diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CMakeLists.txt index 80142bfe8..aa7ef5adc 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CMakeLists.txt @@ -8,8 +8,10 @@ INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/../Services/) # Add AudioVideoManagement stub headers for non-RTI builds INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/../../include/AudioVideoManagement/) -# Add GuezNasat for logger.h -INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/../Proxies/GuezNasat/) +# Add GuezNasat for logger.h (only with BUILD_RTI) +IF(BUILD_RTI) + INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/../Proxies/GuezNasat/) +ENDIF() # Add Viewer/LtsDataView for abstract_display_widget.h INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/../Viewer/LtsDataView/) # Add OperatorManagement stub headers for non-FilterManagement builds @@ -39,14 +41,18 @@ ADD_SUBDIRECTORY(EffectManagement) ADD_SUBDIRECTORY(EffectShowClient) ADD_SUBDIRECTORY(EffectShowManagement) ADD_SUBDIRECTORY(Evaluations) -ADD_SUBDIRECTORY(ExerciseManagement) +IF(BUILD_RTI) + ADD_SUBDIRECTORY(ExerciseManagement) +ENDIF() ADD_SUBDIRECTORY(FileManagement) IF(BUILD_FILTERMANAGEMENT) ADD_SUBDIRECTORY(FilterManagement) ENDIF() ADD_SUBDIRECTORY(FreeSpace) ADD_SUBDIRECTORY(GuezIedManagement) -ADD_SUBDIRECTORY(GuezNasat) +IF(BUILD_RTI) + ADD_SUBDIRECTORY(GuezNasat) +ENDIF() ADD_SUBDIRECTORY(InfrastructureManagement) # ResMgt uses nglwidgets => NGLTreeModel ADD_SUBDIRECTORY(MarkerManagement) ADD_SUBDIRECTORY(Messaging) diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/EsmComboBox/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/EsmComboBox/CMakeLists.txt index 2faa922e1..47cc42dc4 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/EsmComboBox/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/EsmComboBox/CMakeLists.txt @@ -16,6 +16,7 @@ NGL_ADD_LIBRARY(WS EsmComboBoxGui STATIC ${esm_combobox_gui_SRCS}) NGL_TARGET_INCLUDE_DIRECTORIES(EsmComboBoxGui PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../../.. + ${CMAKE_BINARY_DIR}/Lts/Common/LtsCoordTrans ) NGL_TARGET_LINK_LIBRARIES(EsmComboBoxGui PRIVATE diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/GuezNasat/Gui/Common/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Plugins/GuezNasat/Gui/Common/CMakeLists.txt index 5903f1d85..8e82d7100 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/GuezNasat/Gui/Common/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/GuezNasat/Gui/Common/CMakeLists.txt @@ -30,8 +30,7 @@ NGL_TARGET_LINK_LIBRARIES(GnaCommon PUBLIC LtsWidgets LtsSession - PpmGuiComboboxPluginInterface - svcGnaCommon - svcExmCommon - svcPpmCommon ) + +# Optional: External dependencies (not available in migration context) +# target_link_libraries(GnaCommon PUBLIC PpmGuiComboboxPluginInterface svcGnaCommon svcExmCommon svcPpmCommon) diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/MarkerManagement/Gui/Common/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Plugins/MarkerManagement/Gui/Common/CMakeLists.txt index 767ba0771..225c12a79 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/MarkerManagement/Gui/Common/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/MarkerManagement/Gui/Common/CMakeLists.txt @@ -5,6 +5,9 @@ # Created by Mike Wille, SLSE, 2016-09-06 # +# MrkCommon benötigt LtsDataView, welches nur mit BUILD_RTI verfügbar ist +IF(BUILD_RTI) + # # Data Plugin # @@ -38,10 +41,11 @@ NGL_TARGET_LINK_LIBRARIES(MrkCommon LtsSession LtsSessionData LtsUtilsGuiDds - OpmDataPluginInterface + # OpmDataPluginInterface # External dependency ngltools + # svcMrkCommon # External dependency PUBLIC - MrkDataPluginInterface + # MrkDataPluginInterface # External dependency - check if available Qt6::Widgets LtsWidgets LtsDataView @@ -51,3 +55,5 @@ NGL_TARGET_LINK_LIBRARIES(MrkCommon if(BUILD_RTI) target_link_libraries(MrkCommon PRIVATE FltDataPluginInterface) endif() + +ENDIF() # BUILD_RTI diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ParticipantManagement/Gui/Common/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ParticipantManagement/Gui/Common/CMakeLists.txt index 10bd3ad9f..6565a636e 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ParticipantManagement/Gui/Common/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ParticipantManagement/Gui/Common/CMakeLists.txt @@ -55,19 +55,19 @@ NGL_TARGET_LINK_LIBRARIES(PpmCommon LtsSession Qt6::Widgets NGLLogger - AsbDataPluginInterface - ExmDataPluginInterface - advancedSymbologyGui LtsUtilsSettings PUBLIC Qt6::Core Qt6::Gui nglwidgets - svcPpmCommon LtsDataView LtsUtilsGuiDds ) +# Optional: External dependencies (not available in migration context) +# target_link_libraries(PpmCommon PRIVATE AsbDataPluginInterface ExmDataPluginInterface advancedSymbologyGui) +# target_link_libraries(PpmCommon PUBLIC svcPpmCommon) + NGL_TARGET_INCLUDE_DIRECTORIES(PpmCommon PUBLIC ${CMAKE_CURRENT_BINARY_DIR}/../../.. diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ProjectDataManagement/Gui/PdmChargeTable/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ProjectDataManagement/Gui/PdmChargeTable/CMakeLists.txt index 3601a5380..6c772a80c 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ProjectDataManagement/Gui/PdmChargeTable/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ProjectDataManagement/Gui/PdmChargeTable/CMakeLists.txt @@ -5,6 +5,7 @@ # Created by Mike Wille, SLSE, 2016-05-05 # +IF(BUILD_RTI) SET(charge_table_gui_SRCS pdm_charge_table_foreign_gui_interface_impl.cpp pdm_charge_table_foreign_gui_interface_impl.h @@ -26,6 +27,7 @@ NGL_ADD_LIBRARY(WS PdmChargeTableGui STATIC ${charge_table_gui_SRCS}) NGL_TARGET_INCLUDE_DIRECTORIES(PdmChargeTableGui PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../../.. + ${CMAKE_SOURCE_DIR}/Lts/Widgets/ ) NGL_TARGET_LINK_LIBRARIES(PdmChargeTableGui PRIVATE @@ -61,3 +63,4 @@ NGL_TARGET_LINK_LIBRARIES(PdmChargeTableGuiPlugin ) NGL_INSTALL_TARGET(PdmChargeTableGuiPlugin) +ENDIF() diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ProjectDataManagement/Gui/PdmComboBox/pdm_charge_selector.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ProjectDataManagement/Gui/PdmComboBox/pdm_charge_selector.h index 95160852c..5298dc055 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ProjectDataManagement/Gui/PdmComboBox/pdm_charge_selector.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ProjectDataManagement/Gui/PdmComboBox/pdm_charge_selector.h @@ -16,11 +16,8 @@ namespace ProjectDataManagement { -#ifdef BUILD_WITH_EXTERNAL_DDS + class ChargeSelector final : public LtsWidgets::LtsFramelessDialog -#else -class ChargeSelector; -#endif { Q_OBJECT public: diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ProjectDataManagement/pdm_data_plugin_interface.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ProjectDataManagement/pdm_data_plugin_interface.h index cf1dc25e8..ad96a1fd7 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ProjectDataManagement/pdm_data_plugin_interface.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ProjectDataManagement/pdm_data_plugin_interface.h @@ -5,14 +5,13 @@ #include +// Forward declarations for external DDS types namespace ProjectDataManagement { - -// Forward declarations for external dependencies -namespace Interface { -namespace Dtc { -} -namespace Ftc { +namespace Interface +{ + class Dtc; + class Ftc; } } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ProjectDataManagement/pdm_gui_plugin_interface.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ProjectDataManagement/pdm_gui_plugin_interface.h index 2d13a4142..cbd101341 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ProjectDataManagement/pdm_gui_plugin_interface.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ProjectDataManagement/pdm_gui_plugin_interface.h @@ -10,6 +10,9 @@ class QComboBox; class QWidget; class QVariant; +// Forward declaration for external dependency +enum class GearClass; + namespace ProjectDataManagement { diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/SituationReplayManagement/Gui/ReplayManagement/replay_management_gui_plugin.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/SituationReplayManagement/Gui/ReplayManagement/replay_management_gui_plugin.h index 51d3135d6..c4c59841c 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/SituationReplayManagement/Gui/ReplayManagement/replay_management_gui_plugin.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/SituationReplayManagement/Gui/ReplayManagement/replay_management_gui_plugin.h @@ -19,7 +19,6 @@ namespace SituationReplayManagement class GuiPlugin final : public QObject, public GuiPluginBase::Plugin { Q_PLUGIN_METADATA(IID "gui:3:srm") - Q_INTERFACES(GuiPluginBase::Plugin) Q_OBJECT public: diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/TakeHomePackageManager/THP2/Common2Core/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Plugins/TakeHomePackageManager/THP2/Common2Core/CMakeLists.txt index 26a7e7dc3..06e078803 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/TakeHomePackageManager/THP2/Common2Core/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/TakeHomePackageManager/THP2/Common2Core/CMakeLists.txt @@ -21,6 +21,8 @@ NGL_TARGET_INCLUDE_DIRECTORIES(Thp2CommonCore PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../ ${CMAKE_CURRENT_BINARY_DIR}/../ # export file + ${CMAKE_SOURCE_DIR}/Lts/Common + ${CMAKE_SOURCE_DIR}/Lts/Common/LtsUtils ) NGL_TARGET_LINK_LIBRARIES(Thp2CommonCore PRIVATE diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Timeline/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Timeline/CMakeLists.txt index 026e0336b..433f73382 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Timeline/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Timeline/CMakeLists.txt @@ -34,7 +34,7 @@ ADD_INTERFACE_LIBRARY(TlnEventTimelineGuiPluginInterface NGL_ADD_LIBRARY2(WS TlnDataPluginInterface SHARED tln_data_plugin_interface.h) NGL_TARGET_LINK_LIBRARIES(TlnDataPluginInterface Qt6::Core - svcEemCommon +## svcEemCommon DataPluginInterface ) NGL_INSTALL_TARGET(TlnDataPluginInterface) diff --git a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/AdlerJson/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/AdlerJson/CMakeLists.txt index 8ca720624..a391c8a11 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/AdlerJson/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/AdlerJson/CMakeLists.txt @@ -24,7 +24,7 @@ NGL_TARGET_INCLUDE_DIRECTORIES(saaTelegrams ${CMAKE_CURRENT_BINARY_DIR}/../ ) NGL_TARGET_LINK_LIBRARIES(saaTelegrams - svcPdmClient +# svcPdmClient # Externe Dependency - nicht verfügbar Qt6::Core Qt6::WebSockets ) diff --git a/qt6-after/qt6-migrated-legatus/Lts/Services/AudioVideoManagement/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Services/AudioVideoManagement/CMakeLists.txt index 5e23c820e..2c17d0aa0 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Services/AudioVideoManagement/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Services/AudioVideoManagement/CMakeLists.txt @@ -4,6 +4,8 @@ # $Author$ # +IF(BUILD_RTI) + IF(${CMAKE_VERSION} VERSION_LESS "3.6.0") FIND_PACKAGE(Boost REQUIRED COMPONENTS system) # system wird nicht gebraucht, aber ohne Komponente wird das Boost::boost imported Target nicht angelegt (cmake <= 3.5.2) ELSE() @@ -136,7 +138,6 @@ NGL_TARGET_INCLUDE_DIRECTORIES(svcAvmCommon ${CMAKE_CURRENT_SOURCE_DIR}/../ ${CMAKE_CURRENT_BINARY_DIR}/../ ) -IF(BUILD_RTI) NGL_TARGET_LINK_LIBRARIES(svcAvmCommon PRIVATE RTI::nddscpp2 @@ -151,7 +152,6 @@ NGL_TARGET_LINK_LIBRARIES(svcAvmCommon ngldb Boost::boost ) -ENDIF(BUILD_RTI) NGL_INSTALL_TARGET(svcAvmCommon) # @@ -172,7 +172,6 @@ NGL_TARGET_INCLUDE_DIRECTORIES(svcAvmClient ${CMAKE_CURRENT_BINARY_DIR}/../ ) -IF(BUILD_RTI) NGL_TARGET_LINK_LIBRARIES(svcAvmClient PRIVATE RTI::nddscpp2 @@ -181,7 +180,6 @@ NGL_TARGET_LINK_LIBRARIES(svcAvmClient svcAvmCommon ddsftc ) -ENDIF(BUILD_RTI) NGL_INSTALL_TARGET(svcAvmClient) # @@ -200,7 +198,6 @@ NGL_TARGET_INCLUDE_DIRECTORIES(svcAvmServer ${CMAKE_CURRENT_BINARY_DIR}/../ ) -IF(BUILD_RTI) NGL_TARGET_LINK_LIBRARIES(svcAvmServer PRIVATE RTI::nddscpp2 @@ -210,7 +207,6 @@ NGL_TARGET_LINK_LIBRARIES(svcAvmServer svcAvmCommon ngldb ) -ENDIF(BUILD_RTI) NGL_INSTALL_TARGET(svcAvmServer) # @@ -313,3 +309,5 @@ NGL_ADD_TARGET_LINK(svcAudioVideoManagement sAVM) # Uncomment if necessary ADD_SUBDIRECTORY(ModuleTests) ADD_SUBDIRECTORY(UnitTests) + +ENDIF(BUILD_RTI) diff --git a/qt6-after/qt6-migrated-legatus/Lts/Viewer/SituationMap/Symbology/result_watcher.h b/qt6-after/qt6-migrated-legatus/Lts/Viewer/SituationMap/Symbology/result_watcher.h index d2421fb81..1c2831c3d 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Viewer/SituationMap/Symbology/result_watcher.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Viewer/SituationMap/Symbology/result_watcher.h @@ -14,6 +14,7 @@ // Qt #include +#include //---------------------------------------------------------------------------- @@ -61,8 +62,6 @@ protected Q_SLOTS: } protected: - -NGL::INGLLogger &m_logger; bool m_alreadyEmitted = false; }; diff --git a/qt6-after/qt6-migrated-legatus/cmake/NGLMacros.cmake b/qt6-after/qt6-migrated-legatus/cmake/NGLMacros.cmake index 7e85d8104..f055ff7b7 100755 --- a/qt6-after/qt6-migrated-legatus/cmake/NGLMacros.cmake +++ b/qt6-after/qt6-migrated-legatus/cmake/NGLMacros.cmake @@ -279,6 +279,7 @@ MACRO (NGL_ADD_LIBRARY2) ENDIF() TARGET_INCLUDE_DIRECTORIES(${_target_NAME} PUBLIC + ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_BINARY_DIR}/../ ) GET_PROPERTY(type TARGET ${_target_NAME} PROPERTY TYPE)