Qt6 migration: LtsWidgets API fixes, LtsWebSocket logger init, RTI Docker install

- LtsWidgets: Fixed Qt6 API compatibility issues
  - QWheelEvent::delta() → angleDelta().y()
  - QStyleOption::init() → initFrom()
  - QComboBox activated signal signature change
  - QTextCodec removal (UTF-8 default in Qt6)
  - Missing widget includes added

- LtsWebSocket: Fixed m_logger reference initialization
  - Added NGLLoggerBootstrap includes
  - Proper initialization in constructor initializer lists

- CMake: Added BUILD_LTSWEBSOCKET option for temporary exclusion

- Docker: RTI Connext permanent installation script added
  - ci/install-rti-in-docker.sh for persistent RTI setup
  - Removes need for volume mounting RTI into container

- BUILD options: FilterManagement, RTI, Codification, Grantlee, LtsWebSocket
  can be disabled for partial builds during migration

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
torstenandCopilot committed 2026-08-19 14:04:26 +02:00
1 parent 3bb6e89496
commit bafed3705f
69 files changed
+2128 -3565

No files matched your search

+42 -1
View File
@@ -18,9 +18,50 @@ RUN apt-get update && \
qt6-base-dev \
qt6-base-dev-tools \
qt6-tools-dev \
qt6-tools-dev-tools && \
qt6-tools-dev-tools \
qt6-svg-dev \
qt6-websockets-dev \
qt6-serialport-dev \
qt6-multimedia-dev \
qt6-declarative-dev \
libpoppler-qt6-dev \
libpq-dev \
libbz2-dev \
libboost-all-dev \
libxml2-dev \
libssl-dev \
libcurl4-openssl-dev && \
rm -rf /var/lib/apt/lists/*
# Install Log4Qt for Qt6
RUN git clone --depth 1 https://github.com/MEONMedical/Log4Qt.git /tmp/log4qt && \
cd /tmp/log4qt && \
mkdir -p build && cd build && \
cmake -DCMAKE_BUILD_TYPE=Release \
-DCMAKE_CXX_STANDARD=20 \
-DCMAKE_CXX_EXTENSIONS=OFF \
-DCMAKE_PREFIX_PATH="/usr" \
-DCMAKE_INSTALL_PREFIX="/usr/local" \
-DBUILD_SHARED_LIBS=ON .. && \
cmake --build . -- -j$(nproc) && \
cmake --install . && \
rm -rf /tmp/log4qt
# Create minimal CMake config for Log4Qt
RUN mkdir -p /usr/local/lib/cmake/Log4Qt && \
cat > /usr/local/lib/cmake/Log4Qt/Log4QtConfig.cmake << 'EOF'
if (NOT TARGET Log4Qt::log4qt)
add_library(Log4Qt::log4qt UNKNOWN IMPORTED)
set_target_properties(Log4Qt::log4qt PROPERTIES
IMPORTED_LOCATION "/usr/local/lib/liblog4qt.so"
INTERFACE_INCLUDE_DIRECTORIES "/usr/local/include"
)
endif()
set(Log4Qt_FOUND TRUE CACHE INTERNAL "Log4Qt found by package config")
set(Log4Qt_INCLUDE_DIRS "/usr/local/include" CACHE INTERNAL "Log4Qt include dir")
set(Log4Qt_LIBRARIES "/usr/local/lib/liblog4qt.so" CACHE INTERNAL "Log4Qt library")
EOF
# Set Qt platform for headless testing
ENV QT_QPA_PLATFORM=offscreen
+36
View File
@@ -0,0 +1,36 @@
#!/bin/bash
# Install RTI Connext into existing Docker image
set -e
RTI_SOURCE="/home/torsten/swy/sandbox/external/rti_connext_dds-7.7.0"
BASE_IMAGE="lifemaps/ci-cpp:latest"
TARGET_IMAGE="lifemaps/ci-cpp:rti"
echo "Step 1: Create container from base image..."
CONTAINER_ID=$(docker create --name rti-install-temp $BASE_IMAGE /bin/bash)
echo "Step 2: Copy RTI Connext into container..."
docker cp "$RTI_SOURCE" "$CONTAINER_ID:/opt/rti_connext_dds-7.7.0"
echo "Step 3: Commit container as new image..."
docker commit $CONTAINER_ID $TARGET_IMAGE
echo "Step 4: Remove temporary container..."
docker rm $CONTAINER_ID
echo "Step 5: Set environment variables in image..."
docker run --rm $TARGET_IMAGE /bin/bash -c '
echo "RTI Connext installed successfully"
ls -la /opt/rti_connext_dds-7.7.0 | head -10
'
echo ""
echo "RTI Connext installed in image: $TARGET_IMAGE"
echo "To use this image, set environment variables:"
echo " docker run -e RTI_CONNEXT_HOME=/opt/rti_connext_dds-7.7.0 \\"
echo " -e NDDSHOME=/opt/rti_connext_dds-7.7.0 \\"
echo " -e PATH=/opt/rti_connext_dds-7.7.0/bin:\$PATH \\"
echo " -e LD_LIBRARY_PATH=/opt/rti_connext_dds-7.7.0/lib/x64Linux4gcc7.3.0:\$LD_LIBRARY_PATH \\"
echo " -e CMAKE_PREFIX_PATH=/opt/rti_connext_dds-7.7.0/lib/cmake:\$CMAKE_PREFIX_PATH \\"
echo " $TARGET_IMAGE"
+12 -17
View File
@@ -75,6 +75,10 @@ OPTION(BUILD_PLUGINS_PARTICIPANT_ORG_CHART "Build ParticipantOrgChart (requires
OPTION(BUILD_PLUGINS_MSDL "Build MSDL module (requires Qt6 XmlPatterns)" OFF)
OPTION(BUILD_PLUGINS_SAAB "Build Saab module (requires Qt6 XmlPatterns)" OFF)
OPTION(BUILD_RTI "Build RTI Connext DDS dependent modules" OFF)
OPTION(BUILD_FILTERMANAGEMENT "Build FilterManagement plugins (temporarily disabled for migration)" OFF)
OPTION(BUILD_CODIFICATION "Build CodificationManagement plugins (requires KDReports)" OFF)
OPTION(BUILD_GRANTLEE "Build CodeGen Grantlee templates (requires Grantlee5/Qt5)" OFF)
OPTION(BUILD_LTSWEBSOCKET "Build LtsWebSocket module (requires NGLLogger)" OFF)
IF(WIN32)
SET(EXTERNAL_LIBRARY_DIR "C:/Development/Projekte/SituationMap/ExtFw" CACHE STRING "Library dir with all external dependencies")
@@ -113,21 +117,12 @@ SET(CMAKE_AUTOMOC TRUE)
SET(CMAKE_AUTOUIC TRUE)
SET(QT_USE_IMPORTED_TARGETS TRUE)
# Prefer Qt6, fallback to Qt5. Create Qt6::*-aliases when Qt6 is found so existing CMakeLists continue to work.
# Try to detect Qt6 with a minimal check and then create aliases/placeholders for components used across the project.
# Prefer Qt6, fallback to Qt5. Create Qt6::* aliases only when the corresponding
# Qt6:: component target exists. Avoid creating IMPORTED placeholder targets which
# have no LOCATION and later inject 'NOTFOUND' into autogen timestamp deps.
# Find minimal Qt6 Core first, then probe for other components (non-fatal).
find_package(Qt6 6.8 COMPONENTS Core QUIET)
# Find Qt6 with all required components in one call to ensure all targets are properly created
find_package(Qt6 6.8 COMPONENTS Concurrent Core Gui Location LinguistTools Network OpenGL PrintSupport
Sensors Multimedia Sql Svg SerialPort Test UiTools WebSockets WebEngineCore WebEngineWidgets
Widgets Xml XmlPatterns QUIET)
if(Qt6_FOUND)
message(STATUS "Found Qt6: ${Qt6Core_VERSION}")
set(_qlist Concurrent Core Gui Location LinguistTools Network OpenGL PrintSupport
Sensors Multimedia Sql Svg SerialPort Test UiTools WebSockets WebEngineCore WebEngineWidgets
Widgets Xml XmlPatterns)
foreach(_comp ${_qlist})
# Probe for each component (non-fatal).
find_package(Qt6 COMPONENTS ${_comp} QUIET)
endforeach()
# Map version variable for compatibility if available
if(Qt6Core_VERSION)
set(Qt5Core_VERSION ${Qt6Core_VERSION} CACHE INTERNAL "Compatibility Qt5Core_VERSION mapped from Qt6")
@@ -146,12 +141,12 @@ if(Qt6_FOUND)
endif()
endif()
else()
find_package(Qt6 5.9.0 COMPONENTS Concurrent Core Gui Location LinguistTools
Network OpenGL PrintSupport Sensors Multimedia
find_package(Qt6 5.9.0 COMPONENTS Concurrent Core Gui LinguistTools
Network OpenGL PrintSupport Multimedia
Sql Svg SerialPort Test UiTools WebSockets
WebEngineCore WebEngineWidgets Widgets
Xml XmlPatterns
Widgets Xml
REQUIRED)
find_package(Qt6 COMPONENTS Location Sensors WebEngineCore WebEngineWidgets XmlPatterns OPTIONAL)
MESSAGE(STATUS "Qt version is ${Qt6Core_VERSION}")
endif()
@@ -36,7 +36,9 @@ ADD_SUBDIRECTORY(LtsTimeline)
ADD_SUBDIRECTORY(LtsPrinting)
ADD_SUBDIRECTORY(LtsSerialPortQuerry)
ADD_SUBDIRECTORY(LtsScriptTimeline)
IF(BUILD_LTSWEBSOCKET)
ADD_SUBDIRECTORY(LtsWebSocket)
ENDIF()
ADD_SUBDIRECTORY(LtsProjectionWorkstation)
ADD_SUBDIRECTORY(LtsVirtualKeyboard)
ADD_SUBDIRECTORY(PluginInterfaces)
@@ -5,7 +5,11 @@
#
FIND_PACKAGE(RTI)
# Grantlee5 is Qt5-based and optional for Qt6 migration
IF(BUILD_GRANTLEE)
FIND_PACKAGE(Grantlee5 REQUIRED COMPONENTS Templates)
ENDIF()
NGL_ADD_LIBRARY2(ALL codegen_base SHARED
codegen_export.h
@@ -45,7 +49,8 @@ else()
endif()
NGL_INSTALL_TARGET(codegen_base)
if (TARGET Grantlee5::Templates)
# Grantlee5 is Qt5-based and optional for Qt6 migration
IF(BUILD_GRANTLEE AND TARGET Grantlee5::Templates)
NGL_ADD_LIBRARY(ALL codegen_grantlee STATIC
CppTopicGeneratorGrantlee.cpp
CppTopicGeneratorGrantlee.h
@@ -111,12 +116,8 @@ if (TARGET Grantlee5::Templates)
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/../
)
else()
message(STATUS "Grantlee not found; skipping codegen_grantlee target")
endif()
# Smoke-test: parse all .grantlee templates in this directory to detect parse/render regressions
if (TARGET Grantlee5::Templates)
find_package(Qt6 COMPONENTS Core QUIET)
if (Qt6_FOUND)
set(QTCORE_TARGET Qt6::Core)
@@ -128,7 +129,6 @@ if (TARGET Grantlee5::Templates)
add_executable(grantlee_parser_smoke tests/GrantleeParserSmoke.cpp)
target_link_libraries(grantlee_parser_smoke PRIVATE Grantlee5::Templates ${QTCORE_TARGET})
add_test(NAME GrantleeParserSmoke COMMAND grantlee_parser_smoke ${CMAKE_CURRENT_SOURCE_DIR})
endif()
NGL_ADD_EXECUTABLE(ALL ngl_codegen
main_grantlee.cpp
@@ -155,3 +155,6 @@ NGL_TARGET_LINK_LIBRARIES(codegen_gui
Qt6::Widgets
Grantlee5::Templates
)
ELSE()
message(STATUS "BUILD_GRANTLEE disabled or Grantlee not found; skipping codegen_grantlee, ngl_codegen, and codegen_gui targets")
ENDIF()
@@ -24,6 +24,7 @@ endif()
NGL_TARGET_INCLUDE_DIRECTORIES(LtsCoordTrans
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/../
${CMAKE_CURRENT_BINARY_DIR}
)
SET(ltsCoordWidget_SRCS
@@ -48,6 +49,7 @@ NGL_TARGET_INCLUDE_DIRECTORIES(ltsCoordWidget
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/../
${CMAKE_CURRENT_SOURCE_DIR}/../LtsUtils/LtsUtilsCore
${CMAKE_CURRENT_BINARY_DIR}
)
IF(TARGET LtsCoordTrans)
+8 -20
View File
@@ -1,10 +1,9 @@
#pragma once
#include <QObject>
#include "sv_export.h"
#include <LtsCoordTrans/lts_coord_trans.h>
#include <LtsCoordTrans/ltscoordwidget_export.h>
#include <QObject>
#include <QWidget>
class QToolButton;
@@ -12,31 +11,19 @@ class QToolButton;
namespace LtsCoordWidget
{
class LtsCoordInputWidgetHandler;
class LTSCOORDWIDGET_EXPORT LtsCoordWidget : public QWidget
{
Q_OBJECT
public:
enum class DisplayType
{
MGRS5,
MGRS7,
UTM,
WGS84,
MGRS = DisplayType::MGRS5
};
enum class DisplayType { MGRS5, MGRS7, UTM, WGS84, MGRS = DisplayType::MGRS5 };
Q_ENUM(DisplayType)
Q_PROPERTY(DisplayType displayType READ displayType WRITE setDisplayType)
Q_PROPERTY(bool withResetButton READ withResetButton WRITE setWithResetButton)
Q_PROPERTY(bool showToolTip READ showToolTip WRITE setShowToolTip)
Q_PROPERTY(bool mgrsSquareEditable READ mgrsSquareEditable WRITE setMgrsSquareEditable)
explicit LtsCoordWidget(QWidget *parent = nullptr)
: LtsCoordWidget(LtsCoordWidget::DisplayType::MGRS, parent)
{}
explicit LtsCoordWidget(QWidget* parent = nullptr) : LtsCoordWidget(LtsCoordWidget::DisplayType::MGRS, parent) {}
explicit LtsCoordWidget(DisplayType dt, QWidget* parent = nullptr);
@@ -48,7 +35,6 @@ public:
bool event(QEvent* event) override;
public Q_SLOTS:
void setCoordinate(const QPointF& geoCoord, bool bUseAsDefaultValue = true);
void setCoordinate(double lon, double lat, bool bUseAsDefaultValue = true);
void setDisplayType(LtsCoordWidget::DisplayType dt);
@@ -62,11 +48,13 @@ public Q_SLOTS:
Q_SIGNALS:
void coordinateChanged(const QPointF& newGeoCoord);
void invalidCoordinate();
private:
void rebuildUi();
void updateToolTip();
private Q_SLOTS:
void onResetToDefaultCoordinate();
private:
bool m_bWithResetButton = false;
bool m_bShowToolTip = true;
@@ -76,4 +64,4 @@ private:
QPointF m_coordinate;
QPointF m_defaultCoordinate;
};
}
} // namespace LtsCoordWidget
@@ -15,7 +15,7 @@ SET(SRCS
printing.h
)
if (KDReports_FOUND AND BUILD_RTI)
if (KDReports_FOUND AND BUILD_CODIFICATION)
NGL_ADD_LIBRARY2(WS LtsPrinting SHARED ${SRCS})
NGL_TARGET_INCLUDE_DIRECTORIES(LtsPrinting
PUBLIC
@@ -13,6 +13,7 @@ NGL_ADD_LIBRARY2(ALL LtsUtilsSettings SHARED ${SRCS})
NGL_TARGET_INCLUDE_DIRECTORIES(LtsUtilsSettings
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/../
${CMAKE_CURRENT_BINARY_DIR}
)
NGL_TARGET_LINK_LIBRARIES(LtsUtilsSettings
+7 -5
View File
@@ -2,14 +2,14 @@
#include "client_connection.h"
#include <NGLLogger/NGLLoggerBootstrap.h>
#include <QWebSocket>
namespace LtsWebSocket
{
ClientConnection::ClientConnection(QWebSocket* socket, QObject* parent)
: QThread(parent)
, m_socket(socket ? socket : new QWebSocket)
: QThread(parent), m_logger(NGL::NGLLoggerBootstrap::getLogger()), m_socket(socket ? socket : new QWebSocket)
{
}
@@ -29,7 +29,8 @@ bool ClientConnection::init()
}
DEBUG_LOG(m_logger) << "Started new thread" << this;
connect(m_socket, &QWebSocket::textMessageReceived, this, &ClientConnection::onNewTextMessageFromSocket, Qt::DirectConnection);
connect(m_socket, &QWebSocket::textMessageReceived, this, &ClientConnection::onNewTextMessageFromSocket,
Qt::DirectConnection);
connect(m_socket, &QWebSocket::connected, this, &ClientConnection::sendMessagesFromQueue);
connect(m_socket, &QWebSocket::disconnected, this, &ClientConnection::onSocketDisconnect);
@@ -75,9 +76,10 @@ void ClientConnection::sendMessagesFromQueue()
void ClientConnection::onSocketDisconnect()
{
DEBUG_LOG(m_logger) << "Client disconnected ip: " << m_socket->peerAddress().toString() << ":" << m_socket->peerPort();
DEBUG_LOG(m_logger) << "Client disconnected ip: " << m_socket->peerAddress().toString() << ":"
<< m_socket->peerPort();
exit(0);
emit disconnected(this);
}
}
} // namespace LtsWebSocket
+13 -31
View File
@@ -1,69 +1,51 @@
#pragma once
#include <QObject>
#include <QtCore/QThread>
#include <QtCore/QQueue>
#include "reply_message.h"
#include "logger.h"
#include "ltswebsocketserver_export.h"
#include "reply_message.h"
#include <QObject>
#include <QtCore/QQueue>
#include <QtCore/QThread>
class QWebSocket;
namespace LtsWebSocket
{
class LTSWEBSOCKETSERVER_EXPORT ClientConnection
: public QThread
, public ReplyHandler
class LTSWEBSOCKETSERVER_EXPORT ClientConnection : public QThread, public ReplyHandler
{
Q_OBJECT
public:
explicit ClientConnection(QWebSocket* socket, QObject* parent = nullptr);
~ClientConnection();
bool init();
void addReply(ReplyMessage* message) override;
QWebSocket *webSocket() { return m_socket; }
signals:
QWebSocket* webSocket()
{
return m_socket;
}
signals:
void newTextMessage(ClientConnection* client, const QString& message);
void disconnected(ClientConnection* client);
private slots:
void onNewTextMessageFromSocket(const QString& message);
void sendMessagesFromQueue();
void onSocketDisconnect();
private:
NGL::INGLLogger& m_logger;
void sendMessages();
private:
NGL::INGLLogger &m_logger;
QWebSocket* m_socket;
QQueue<ReplyMessage*> m_messageQueue;
};
}
} // namespace LtsWebSocket
+21 -22
View File
@@ -3,45 +3,38 @@
#pragma once
#include "client_message.h"
#include "reply_message.h"
#include "ltswebsocketcommon_export.h"
#include "reply_message.h"
#include <QString>
#include <QJsonParseError>
#include <QString>
namespace NGL
{
class INGLLogger;
}
namespace LtsWebSocket
{
class LTSWEBSOCKETCOMMON_EXPORT AbstractClientMessageFactory
{
public:
explicit AbstractClientMessageFactory(NGL::INGLLogger &logger)
: m_logger(logger)
{}
explicit AbstractClientMessageFactory(NGL::INGLLogger& logger) : m_logger(logger) {}
virtual ~AbstractClientMessageFactory() {}
QJsonParseError parseMessage(const QString& message);
virtual AbstractClientMessage* createMessage(ReplyHandler* client, const QString& message) = 0;
protected:
AbstractClientMessage *checkAttributes(ReplyHandler *client,
const QString &message) const;
AbstractClientMessage *checkResult(ReplyHandler *client,
const QString &message,
AbstractClientMessage* checkAttributes(ReplyHandler* client, const QString& message) const;
AbstractClientMessage* checkResult(ReplyHandler* client, const QString& message,
AbstractClientMessage* result) const;
protected:
NGL::INGLLogger& m_logger;
QString m_type;
int m_typeId;
QString m_uuid;
@@ -51,19 +44,25 @@ protected:
class PongMessage final : public ReplyMessage
{
public:
static QString strPong() { return QStringLiteral("pong"); }
static int idPong() { return 2; }
explicit PongMessage(const QString &payload)
: ReplyMessage(strPong(), idPong(), QString())
, m_payload(payload)
{}
static QString strPong()
{
return QStringLiteral("pong");
}
static int idPong()
{
return 2;
}
explicit PongMessage(const QString& payload) : ReplyMessage(strPong(), idPong(), QString()), m_payload(payload) {}
QString toJsonString() const override
{
return m_payload.isEmpty() ? strPong() : QStringLiteral("%1 %2").arg(strPong(), m_payload);
}
private:
QString m_payload;
};
}
} // namespace LtsWebSocket
+10 -9
View File
@@ -1,17 +1,19 @@
#include "connection_handler.h"
#include <utility>
#include "client_connection.h"
#include <NGLLogger/NGLLoggerBootstrap.h>
#include <QtWebSockets/QWebSocket>
#include <utility>
using namespace LtsWebSocket;
ConnectionHandler::ConnectionHandler(QObject *parent) : QObject(parent)
, m_server(nullptr),
m_logger(NGL::NGLLoggerBootstrap::getLogger()) {}
ConnectionHandler::ConnectionHandler(QObject* parent)
: QObject(parent), m_server(nullptr), m_logger(NGL::NGLLoggerBootstrap::getLogger())
{
}
ConnectionHandler::~ConnectionHandler()
{
@@ -63,10 +65,8 @@ void ConnectionHandler::onNewConnection()
QWebSocket* socket = m_server->nextPendingConnection();
ClientConnection* newConnection = new ClientConnection(socket, this);
connect(newConnection, &ClientConnection::destroyed, this, [this](QObject* o)
{
m_connections.remove(static_cast<ClientConnection*>(o));
});
connect(newConnection, &ClientConnection::destroyed, this,
[this](QObject* o) { m_connections.remove(static_cast<ClientConnection*>(o)); });
if (!newConnection->init())
{
@@ -83,6 +83,7 @@ void ConnectionHandler::onNewConnection()
m_connections.insert(newConnection);
emit clientConnected(newConnection);
INFO_LOG(m_logger) << "New client connected ip: " << socket->localAddress().toString() << ":" << socket->localPort();
INFO_LOG(m_logger) << "New client connected ip: " << socket->localAddress().toString() << ":"
<< socket->localPort();
}
}
@@ -172,6 +172,7 @@ NGL_TARGET_LINK_LIBRARIES(LtsWidgets
TabBarTabStyle
LtsSessionData
LtsUtilsSettings
NGLLogger
PUBLIC
LtsUtilsCore
Qt6::Core
@@ -2,25 +2,21 @@
#include "lts_abstract_sequence_widget.h"
#include <QRegularExpression>
#include <QToolButton>
namespace LtsWidgets
{
LtsAbstractSequenceWidget::LtsAbstractSequenceWidget(QWidget* parent, const bool& readOnly)
: QGroupBox(parent)
, m_readOnly(readOnly)
, m_pbAddMember(new QToolButton)
: QGroupBox(parent), m_readOnly(readOnly), m_pbAddMember(new QToolButton)
{
m_pbAddMember->setIcon(QIcon(QLatin1String(":/icons/png/add.png")));
connect(m_pbAddMember, &QToolButton::clicked, this, &LtsAbstractSequenceWidget::addMember);
}
LtsAbstractSequenceWidget::~LtsAbstractSequenceWidget()
{
}
LtsAbstractSequenceWidget::~LtsAbstractSequenceWidget() {}
void LtsAbstractSequenceWidget::addWidget(QWidget* widget, bool isReadOnly, bool isButtonVisible)
{
@@ -29,12 +25,12 @@ void LtsAbstractSequenceWidget::addWidget(QWidget* widget, bool isReadOnly, bool
m_pbAddMember->setVisible(isButtonVisible);
}
int LtsAbstractSequenceWidget::getMemberlistSize(){
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<QWidget*>(findObjectName))
@@ -50,8 +46,7 @@ void LtsAbstractSequenceWidget::setMemberCount(int count)
{
child = findChild<QWidget*>(getObjectName(++count));
delete child;
}
while (child);
} while (child);
m_memberList.removeAll(nullptr);
}
@@ -113,8 +108,8 @@ void LtsAbstractSequenceWidget::deleteMemberWidget(QObject *member)
QString childName = child->objectName();
QString newId = QString::number(i + 1);
child->setObjectName(childName.replace(QRegExp(QLatin1String(".([0-9]*)")), newId));
}
child->setObjectName(childName.replace(QRegularExpression(QLatin1String("\\.([0-9]*)")), newId));
}
}
}
} // namespace LtsWidgets
+8 -22
View File
@@ -1,23 +1,20 @@
#include "lts_background_widget.h"
#include <QDebug>
#include <QFile>
#include <QPaintEvent>
#include <QPainter>
#include <QDebug>
#ifdef Q_OS_WIN
#include <QtPlatformHeaders/qwindowswindowfunctions.h>
#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);
@@ -26,16 +23,13 @@ LtsBackgroundWidget::LtsBackgroundWidget(QWidget *parent)
setBackground();
}
void LtsBackgroundWidget::setBackground()
{
static const auto backgroundFiles =
{
static const auto backgroundFiles = {
QStringLiteral(":/project/background.png"),
QStringLiteral(":/project/background.jpg"),
};
static const auto backgroundFilesWide =
{
static const auto backgroundFilesWide = {
QStringLiteral(":/project/background_wide.png"),
QStringLiteral(":/project/background_wide.jpg"),
};
@@ -65,7 +59,6 @@ void LtsBackgroundWidget::setBackground()
}
}
void LtsBackgroundWidget::setUltraWide(bool set)
{
if (set == m_isUltraWide)
@@ -76,14 +69,12 @@ void LtsBackgroundWidget::setUltraWide(bool set)
update();
}
void LtsBackgroundWidget::resizeEvent(QResizeEvent* e)
{
setUltraWide(width() > 3000);
QDialog::resizeEvent(e);
}
void LtsBackgroundWidget::paintEvent(QPaintEvent* e)
{
if (!m_pixmap.isNull())
@@ -95,13 +86,10 @@ void LtsBackgroundWidget::paintEvent(QPaintEvent *e)
QDialog::paintEvent(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 || e->type() == QEvent::MouseButtonPress ||
e->type() == QEvent::MouseButtonRelease || e->type() == QEvent::MouseMove)
{
emit signalOperatorAction();
@@ -112,7 +100,6 @@ bool LtsBackgroundWidget::event(QEvent *e)
return QDialog::event(e);
}
void LtsBackgroundWidget::showFullScreen()
{
@@ -124,7 +111,6 @@ void LtsBackgroundWidget::showFullScreen()
raise();
}
void LtsBackgroundWidget::closeEvent(QCloseEvent* e)
{
#ifdef DEVEL
@@ -134,4 +120,4 @@ void LtsBackgroundWidget::closeEvent(QCloseEvent *e)
#endif
}
}
} // namespace LtsWidgets
File diff suppressed because it is too large. Load diff
@@ -1,19 +1,17 @@
#pragma once
#include <QObject>
#include "ltswidgets_export.h"
#include <LtsUtilsCore/variant_operators.h>
#include <LtsUtilsCore/variant_operators.h>
#include <QDataStream>
#include <QIODevice>
#include <QIcon>
#include <QObject>
#include <QRegularExpression>
#include <QSortFilterProxyModel>
#include <QVector>
namespace LtsWidgets
{
struct ComboboxFilterData
@@ -26,11 +24,13 @@ struct ComboboxFilterData
{
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;
@@ -38,12 +38,15 @@ struct ComboboxFilterData
}
};
struct ComboboxFilterContent
{
QVector<ComboboxFilterData> data;
bool sortItems = false;
bool isValid() const { return m_isValid; }
bool isValid() const
{
return m_isValid;
}
QVariant toVariant() const
{
@@ -72,6 +75,7 @@ struct ComboboxFilterContent
ds << cfc.data << cfc.sortItems;
return ds;
}
inline friend QDataStream& operator>>(QDataStream& ds, ComboboxFilterContent& cfc)
{
ds >> cfc.data >> cfc.sortItems;
@@ -82,7 +86,6 @@ private:
bool m_isValid = true;
};
class LTSWIDGETS_EXPORT LtsColumnFilterProxyModel : public QSortFilterProxyModel
{
Q_OBJECT
@@ -96,8 +99,15 @@ public:
bool recursiveFilteringEnabled() const;
#endif
const QHash<int, QRegularExpression> &columnStringFilters() const { return m_columnStringFilters; }
const QHash<int, QVariant> &columnDataFilters() const { return m_columnDataFilters; }
const QHash<int, QRegularExpression>& columnStringFilters() const
{
return m_columnStringFilters;
}
const QHash<int, QVariant>& columnDataFilters() const
{
return m_columnDataFilters;
}
bool lessThan(const QModelIndex& left, const QModelIndex& right) const override;
@@ -120,4 +130,4 @@ private:
bool m_bRecursiveFiltering = false;
#endif
};
}
} // namespace LtsWidgets
+13 -32
View File
@@ -1,14 +1,13 @@
#include "lts_combo_box.h"
#include "lts_selection_popup.h"
#include "lts_message_dialog.h"
#include "lts_selection_popup.h"
#include <QGuiApplication>
#include <QShowEvent>
#ifdef NEVER
#include <QDebug>
#endif
@@ -18,12 +17,9 @@ 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);
}
void LtsComboBox::setUseSelectionDialog(bool bUseSelectionDialog)
@@ -38,7 +34,7 @@ void LtsComboBox::showEvent(QShowEvent *e)
m_currentIndex = currentIndex();
}
void LtsComboBox::enterEvent(QEvent *e)
void LtsComboBox::enterEvent(QEnterEvent* e)
{
BaseClass::enterEvent(e);
emit signalEnterEvent();
@@ -67,47 +63,32 @@ void LtsComboBox::showPopup()
return;
}
LtsSelectionPopup* popup = new LtsSelectionPopup(model(), currentIndex(), this);
popup->setAttribute(Qt::WA_DeleteOnClose);
#ifdef NEVER
connect(popup, static_cast<void (LtsSelectionPopup::*)(int)>(&LtsSelectionPopup::currentIndexChanged), this,
[](int idx) { qCritical() << " LtsComboBox: called: currentIndexChanged(int), idx=" << idx; });
connect(popup, static_cast<void (LtsSelectionPopup::*)(int)>(&LtsSelectionPopup::currentIndexChanged), this, [](int idx){
qCritical() << " LtsComboBox: called: currentIndexChanged(int), idx=" << idx;
});
connect(popup, static_cast<void (LtsSelectionPopup::*)(int)>(&LtsSelectionPopup::activated), this, [](int idx){
qCritical() << " LtsComboBox: called: activated(int), idx=" << idx;
});
connect(popup, static_cast<void (LtsSelectionPopup::*)(int)>(&LtsSelectionPopup::activated), this,
[](int idx) { qCritical() << " LtsComboBox: called: activated(int), idx=" << idx; });
#endif
connect(popup, &LtsSelectionPopup::currentIndexChanged,
this, &LtsComboBox::userChangedIndex);
connect(popup, &LtsSelectionPopup::activated,
this, static_cast<void (LtsComboBox::*)(int)>(&LtsComboBox::activated));
connect(popup, &LtsSelectionPopup::currentIndexChanged, this, &LtsComboBox::userChangedIndex);
connect(popup, &LtsSelectionPopup::activated, this,
static_cast<void (LtsComboBox::*)(int)>(&LtsComboBox::activated));
popup->show();
}
void LtsComboBox::userChangedIndex(int index)
{
m_currentIndex = index;
setCurrentIndex(index);
}
bool LtsComboBox::hasValueChanged() const
{
if (m_currentIndex == -1)
@@ -115,4 +96,4 @@ bool LtsComboBox::hasValueChanged() const
return !(currentIndex() == m_currentIndex);
}
}
} // namespace LtsWidgets
+12 -16
View File
@@ -1,19 +1,14 @@
#pragma once
#include <QObject>
#include "ltswidgets_export.h"
#include <QComboBox>
#include <QObject>
namespace LtsWidgets
{
class LTSWIDGETS_EXPORT LtsComboBox : public QComboBox
{
Q_OBJECT
@@ -23,24 +18,25 @@ public:
explicit LtsComboBox(QWidget* parent = nullptr);
~LtsComboBox() = default;
static void setUseSelectionDialog(bool bUseSelectionDialog);
bool hasValueChanged() const;
void setExternalContentType(int ect) { m_externalContentType = ect; }
int externalContentType() const { return m_externalContentType; }
void setExternalContentType(int ect)
{
m_externalContentType = ect;
}
int externalContentType() const
{
return m_externalContentType;
}
protected:
void showPopup() override;
void showEvent(QShowEvent* e) override;
void enterEvent(QEvent *e) override;
void enterEvent(QEnterEvent* e) override;
void leaveEvent(QEvent*) override;
protected slots:
@@ -57,4 +53,4 @@ private:
int m_externalContentType;
static bool s_useSelectionDialog;
};
}
} // namespace LtsWidgets
+58 -129
View File
@@ -1,17 +1,11 @@
#include "lts_date_time_edit.h"
#include <utility>
#include "lts_date_time_edit_p.h"
#include "lts_date_time_edit_p.h"
#include "ui_lts_date_time_edit_touch.h"
#include <LtsUtilsSettings/settings.h>
#include <ngltools/ngltools_dtg.h>
#include <QApplication>
#include <QCheckBox>
#include <QCompleter>
@@ -25,6 +19,8 @@
#include <QShortcut>
#include <QSlider>
#include <QToolButton>
#include <ngltools/ngltools_dtg.h>
#include <utility>
static constexpr qint64 s_oneSecondMSec = 1000LL;
static constexpr qint64 s_oneMinuteMSec = 60 * s_oneSecondMSec;
@@ -74,7 +70,7 @@ public:
void setupUi(QWidget* parent)
{
gridLayout = new QGridLayout(parent);
gridLayout->setMargin(0);
gridLayout->setContentsMargins(0, 0, 0, 0);
int iStart = 3;
@@ -170,33 +166,32 @@ public:
gridLayout->addWidget(slTime, 1, 0, 1, 7);
}
};
}
} // namespace Ui
namespace LtsWidgets
{
void setItemText(LtsWidgets::LineEdit* lineEdit, const QString& 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)
@@ -204,13 +199,13 @@ void setItemValue(QSpinBox *spinBox, int value)
spinBox->setValue(value);
}
QString getItemText(LtsWidgets::LineEdit* lineEdit)
{
if (!lineEdit)
return {};
return lineEdit->text();
}
QString getItemText(QComboBox* comboxBox)
{
if (!comboxBox || (comboxBox->count() <= 0))
@@ -220,6 +215,7 @@ QString getItemText(QComboBox *comboxBox)
return {};
return curTest.at(0).toUpper();
}
int getItemData(QComboBox* comboxBox)
{
if (!comboxBox || (comboxBox->count() <= 0))
@@ -227,6 +223,7 @@ int getItemData(QComboBox *comboxBox)
int data = comboxBox->currentData().toInt();
return data;
}
int getItemValue(QSpinBox* spinBox)
{
if (!spinBox)
@@ -234,18 +231,15 @@ int getItemValue(QSpinBox *spinBox)
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)
,
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)
{
#ifdef TABLET_MODE
@@ -324,30 +318,20 @@ bool LtsDateTimeEdit::setupUiTouch()
m_uiTouch->cbxTimeZone->addItem(QChar(i), QChar(i));
}
connect(m_uiTouch->pbNow, &QPushButton::clicked,
this, &LtsDateTimeEdit::setOffsetDateTime);
connect(m_uiTouch->cbxMonth, static_cast<void (QComboBox::*)(int)>(&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<void (QComboBox::*)(int)>(&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<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
this, &LtsDateTimeEdit::valueTimezoneChangedInt);
connect(m_uiTouch->checkBox, &QCheckBox::toggled, this, &LtsDateTimeEdit::onCheckBoxChanged);
connect(m_uiTouch->cbxTimeZone, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this,
&LtsDateTimeEdit::valueTimezoneChangedInt);
connect(m_uiTouch->cbxMonth, &QComboBox::currentTextChanged,
this, &LtsDateTimeEdit::valueMonthChanged);
connect(m_uiTouch->cbxMonth, &QComboBox::currentTextChanged, this, &LtsDateTimeEdit::valueMonthChanged);
connect(checkBox(), &QCheckBox::toggled, this, &LtsDateTimeEdit::toggled);
@@ -355,7 +339,6 @@ bool LtsDateTimeEdit::setupUiTouch()
setTimezone(DTG::timezone());
setCheckable(m_checkable);
setWithNowButton(m_withNowButton);
@@ -365,7 +348,6 @@ bool LtsDateTimeEdit::setupUiTouch()
return true;
}
void LtsDateTimeEdit::setRetrieveCurrentTimeCallback(const CurrentTimeCallback& cb)
{
m_getCurrentTimeCallback = cb;
@@ -524,11 +506,6 @@ bool LtsDateTimeEdit::setMsecsSinceEpoch(qint64 msec, bool setToNearestPossible)
if (msec == 0)
return false;
if (!setToNearestPossible)
{
if (!isDataAcceptable())
@@ -556,11 +533,7 @@ bool LtsDateTimeEdit::setMsecsSinceEpoch(qint64 msec, bool setToNearestPossible)
const int minute = time.minute();
const int second = time.second();
if (!setYear(year) ||
!setMonth(month) ||
!setDay(day) ||
!setHHMMSS(hour, minute, second))
if (!setYear(year) || !setMonth(month) || !setDay(day) || !setHHMMSS(hour, minute, second))
return false;
if (!isDataAcceptable())
@@ -573,7 +546,6 @@ bool LtsDateTimeEdit::setMsecsSinceEpoch(qint64 msec, bool setToNearestPossible)
return true;
}
qint64 LtsDateTimeEdit::msecsSinceEpoch() const
{
if (isEmpty())
@@ -652,22 +624,14 @@ void LtsDateTimeEdit::setMinMaxMonth(int minMonth, int maxMonth)
if (i > m_maxMonth)
break;
const QStringList& monthSl = DTG::months();
m_uiTouch->cbxMonth->addItem(monthSl[i - 1], i);
}
m_uiTouch->cbxMonth->setCurrentIndex(m_uiTouch->cbxMonth->findData(currentMonth));
m_uiTouch->cbxMonth->blockSignals(false);
}
void LtsDateTimeEdit::setSubWidgetsProperties(const QString& name, const QVariant& value)
{
if (m_uiLe)
@@ -762,9 +726,7 @@ int LtsDateTimeEdit::getDay() const
bool LtsDateTimeEdit::setHHMMSS(int hour, int minute, int second)
{
if (hour < 0 || hour > 23 ||
minute < 0 || minute > 59 ||
second < 0 || second > 59)
if (hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59)
return false;
if (m_uiLe)
@@ -852,11 +814,7 @@ int LtsDateTimeEdit::getYear() const
bool LtsDateTimeEdit::isEmpty() const
{
return (isEmptyDay() ||
isEmptyHHMMSS() ||
isEmptyMonth() ||
isEmptyTimezone() ||
isEmptyYear());
return (isEmptyDay() || isEmptyHHMMSS() || isEmptyMonth() || isEmptyTimezone() || isEmptyYear());
}
bool LtsDateTimeEdit::isValidDate() const
@@ -864,7 +822,6 @@ bool LtsDateTimeEdit::isValidDate() const
return m_dateIsAcceptable;
}
bool LtsDateTimeEdit::isEmptyDay() const
{
if (m_uiLe)
@@ -904,24 +861,16 @@ 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());
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;
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();
@@ -934,7 +883,8 @@ bool LtsDateTimeEdit::isDataAcceptable()
return false;
}
qint64 msec = QDateTime(QDate(getYear(), getMonth(), getDay()), QTime(getHour(), getMinute(), getSecond()), Qt::UTC).toMSecsSinceEpoch();
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)
{
@@ -957,8 +907,7 @@ bool LtsDateTimeEdit::isDayAcceptable() const
const int month = getMonth();
switch (month)
{
case 2:
{
case 2: {
max = 28;
if (isYearAcceptable())
{
@@ -1025,8 +974,7 @@ void LtsDateTimeEdit::showInvalidData(bool setFocus)
bool focus = setFocus;
auto check = [&](QLineEdit * le, bool isValid)
{
auto check = [&](QLineEdit* le, bool isValid) {
if (isValid)
le->setStyleSheet(QString());
else
@@ -1068,7 +1016,9 @@ bool LtsDateTimeEdit::isLineEditDataAcceptable(QLineEdit *le) const
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()
@@ -1076,7 +1026,9 @@ void LtsDateTimeEdit::setOffsetDateTime()
if (!m_getCurrentTimeCallback)
return;
qint64 offset = LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("TimeSettings"), QStringLiteral("Offset"), 0).toLongLong();
qint64 offset = LtsUtils::OperatorSettings::getInstance()
->value(QStringLiteral("TimeSettings"), QStringLiteral("Offset"), 0)
.toLongLong();
setMsecsSinceEpoch((m_getCurrentTimeCallback() / 1000) * 1000 + offset);
}
@@ -1144,11 +1096,6 @@ void LtsDateTimeEdit::fixupHHMMSS()
QString uhrzeit(m_uiLe->leLongHHMMSS->text());
QString hh;
QString mm;
QString ss;
@@ -1274,7 +1221,6 @@ void LtsDateTimeEdit::valueMonthChanged(const QString &str)
{
m_uiLe->leLongMonth->setText(monStr);
if (cp > 0)
m_uiLe->leLongMonth->setCursorPosition(cp);
else
@@ -1404,13 +1350,13 @@ void LtsDateTimeEdit::onCheckBoxChanged()
if (m_uiLe)
{
widgets = {m_uiLe->leLongDay, m_uiLe->leLongHHMMSS, m_uiLe->leLongTZ,
m_uiLe->leLongMonth, m_uiLe->leLongYear};
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};
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();
@@ -1433,10 +1379,7 @@ void LtsDateTimeEdit::enableControls()
return;
enaDisaControls(true);
if (m_withSlider &&
m_minTimeMSec != 0 &&
m_maxTimeMSec > 0 &&
m_maxTimeMSec > m_minTimeMSec)
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);
@@ -1447,9 +1390,8 @@ void LtsDateTimeEdit::enaDisaControls(bool bEnable)
{
if (!m_uiLe)
return;
const QVector<QWidget *> widgets({m_uiLe->pbBBB, m_uiLe->pbBB, m_uiLe->pbB,
m_uiLe->pbF, m_uiLe->pbFF, m_uiLe->pbFFF,
m_uiLe->slTime});
const QVector<QWidget*> 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)
@@ -1507,7 +1449,6 @@ void LtsDateTimeEdit::clear()
m_uiTouch->spYear->clear();
}
emit dateTimeChanged();
}
void LtsDateTimeEdit::onFocusOutDay()
@@ -1526,9 +1467,7 @@ void LtsDateTimeEdit::onFocusOutDay()
if (value.length() == 0 && !m_backspacePressed)
{
if (!isEmptyHHMMSS() ||
!isEmptyMonth() ||
(!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) ||
if (!isEmptyHHMMSS() || !isEmptyMonth() || (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) ||
!isEmptyYear())
{
if (m_getCurrentTimeCallback)
@@ -1558,10 +1497,7 @@ void LtsDateTimeEdit::onFocusOutHHMMSS()
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)
{
@@ -1592,10 +1528,7 @@ void LtsDateTimeEdit::onFocusOutTZ()
if (value.length() == 0 && !m_backspacePressed)
{
if (!isEmptyHHMMSS() ||
!isEmptyMonth() ||
!isEmptyDay() ||
!isEmptyYear())
if (!isEmptyHHMMSS() || !isEmptyMonth() || !isEmptyDay() || !isEmptyYear())
setTimezone(DTG::timezone());
}
isDataAcceptable();
@@ -1619,9 +1552,7 @@ void LtsDateTimeEdit::onFocusOutMonth()
if (value.length() == 0 && !m_backspacePressed)
{
if (!isEmptyHHMMSS() ||
!isEmptyDay() ||
(!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) ||
if (!isEmptyHHMMSS() || !isEmptyDay() || (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) ||
!isEmptyYear())
{
if (m_getCurrentTimeCallback)
@@ -1658,9 +1589,7 @@ void LtsDateTimeEdit::onFocusOutYear()
if (value.length() == 0 && !m_backspacePressed)
{
if (!isEmptyHHMMSS() ||
!isEmptyMonth() ||
(!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) ||
if (!isEmptyHHMMSS() || !isEmptyMonth() || (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) ||
!isEmptyDay())
{
if (m_getCurrentTimeCallback)
@@ -1783,4 +1712,4 @@ void LtsDateTimeEdit::onYearWheelEvent(bool bForward, int cursorPos)
emit dateTimeChanged();
}
}
} // namespace LtsWidgets
+4 -13
View File
@@ -1,17 +1,13 @@
#include "lts_date_time_edit_p.h"
#include <QApplication>
#include <QKeyEvent>
#include <QRegularExpression>
#include <QValidator>
#include <QKeyEvent>
namespace LtsWidgets
{
void LineEdit::clear()
{
setStyleSheet(QString());
@@ -39,7 +35,6 @@ void LineEdit::keyPressEvent(QKeyEvent *event)
void LineEdit::contextMenuEvent(QContextMenuEvent* e)
{
Q_UNUSED(e);
}
void LineEdit::focusOutEvent(QFocusEvent* event)
@@ -48,11 +43,7 @@ void LineEdit::focusOutEvent(QFocusEvent *event)
emit focusOut();
}
DigitsLineEdit::DigitsLineEdit(QWidget *parent)
: LineEdit(parent)
DigitsLineEdit::DigitsLineEdit(QWidget* parent) : LineEdit(parent)
{
setAlignment(Qt::AlignRight);
QRegularExpression rx(QLatin1String("[-]{0,1}[0-9 ]*"));
@@ -101,7 +92,7 @@ void DigitsLineEdit::wheelEvent(QWheelEvent *event)
return;
event->accept();
int cursorPos = cursorPosition();
emit wheelEventReceived(event->delta() > 0, cursorPos);
emit wheelEventReceived(event->angleDelta().y() > 0, cursorPos);
}
void DigitsLineEdit::keyPressEvent(QKeyEvent* event)
@@ -115,4 +106,4 @@ void DigitsLineEdit::keyPressEvent(QKeyEvent *event)
}
}
}
} // namespace LtsWidgets
+56 -127
View File
@@ -1,16 +1,10 @@
#include "lts_date_time_edit.h"
#include "lts_date_time_edit_p.h"
#include "ui_lts_date_time_edit_touch.h"
#include <LtsUtilsSettings/settings.h>
#include <ngltools/ngltools_dtg.h>
#include <QApplication>
#include <QCheckBox>
#include <QCompleter>
@@ -24,6 +18,7 @@
#include <QShortcut>
#include <QSlider>
#include <QToolButton>
#include <ngltools/ngltools_dtg.h>
static constexpr qint64 s_oneSecondMSec = 1000LL;
static constexpr qint64 s_oneMinuteMSec = 60 * s_oneSecondMSec;
@@ -73,7 +68,7 @@ public:
void setupUi(QWidget* parent)
{
gridLayout = new QGridLayout(parent);
gridLayout->setMargin(0);
gridLayout->setContentsMargins(0, 0, 0, 0);
int iStart = 3;
@@ -169,33 +164,32 @@ public:
gridLayout->addWidget(slTime, 1, 0, 1, 7);
}
};
}
} // namespace Ui
namespace LtsWidgets
{
void setItemText(LtsWidgets::LineEdit* lineEdit, const QString& 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)
@@ -203,13 +197,13 @@ void setItemValue(QSpinBox *spinBox, int value)
spinBox->setValue(value);
}
QString getItemText(LtsWidgets::LineEdit* lineEdit)
{
if (!lineEdit)
return {};
return lineEdit->text();
}
QString getItemText(QComboBox* comboxBox)
{
if (!comboxBox || (comboxBox->count() <= 0))
@@ -219,6 +213,7 @@ QString getItemText(QComboBox *comboxBox)
return {};
return curTest.at(0).toUpper();
}
int getItemData(QComboBox* comboxBox)
{
if (!comboxBox || (comboxBox->count() <= 0))
@@ -226,6 +221,7 @@ int getItemData(QComboBox *comboxBox)
int data = comboxBox->currentData().toInt();
return data;
}
int getItemValue(QSpinBox* spinBox)
{
if (!spinBox)
@@ -233,18 +229,15 @@ int getItemValue(QSpinBox *spinBox)
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)
,
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)
{
#ifdef TABLET_MODE
@@ -326,37 +319,25 @@ bool LtsDateTimeEdit::setupUiTouch()
m_uiTouch->cbxTimeZone->addItem(QChar(i), QChar(i));
}
connect(m_uiTouch->pbNow, &QPushButton::clicked,
this, &LtsDateTimeEdit::setOffsetDateTime);
connect(m_uiTouch->cbxMonth, static_cast<void (QComboBox::*)(int)>(&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<void (QComboBox::*)(int)>(&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<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
this, &LtsDateTimeEdit::valueTimezoneChangedInt);
connect(m_uiTouch->cbxMonth, &QComboBox::currentTextChanged,
this, &LtsDateTimeEdit::valueMonthChanged);
connect(m_uiTouch->checkBox, &QCheckBox::toggled, this, &LtsDateTimeEdit::onCheckBoxChanged);
connect(m_uiTouch->cbxTimeZone, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this,
&LtsDateTimeEdit::valueTimezoneChangedInt);
connect(m_uiTouch->cbxMonth, &QComboBox::currentTextChanged, this, &LtsDateTimeEdit::valueMonthChanged);
setMinMaxMonth(1, 12);
setTimezone(DTG::timezone());
bool temp = m_withCheckBox;
m_withCheckBox = !m_withCheckBox;
setWithCheckBox(temp);
@@ -367,11 +348,9 @@ bool LtsDateTimeEdit::setupUiTouch()
onCheckBoxChanged();
return true;
}
void LtsDateTimeEdit::setRetrieveCurrentTimeCallback(const CurrentTimeCallback& cb)
{
m_getCurrentTimeCallback = cb;
@@ -530,11 +509,6 @@ bool LtsDateTimeEdit::setMsecsSinceEpoch(qint64 msec, bool setToNearestPossible)
if (msec == 0)
return false;
if (!setToNearestPossible)
{
if (!isDataAcceptable())
@@ -562,11 +536,7 @@ bool LtsDateTimeEdit::setMsecsSinceEpoch(qint64 msec, bool setToNearestPossible)
const int minute = time.minute();
const int second = time.second();
if (!setYear(year) ||
!setMonth(month) ||
!setDay(day) ||
!setHHMMSS(hour, minute, second))
if (!setYear(year) || !setMonth(month) || !setDay(day) || !setHHMMSS(hour, minute, second))
return false;
if (!isDataAcceptable())
@@ -579,7 +549,6 @@ bool LtsDateTimeEdit::setMsecsSinceEpoch(qint64 msec, bool setToNearestPossible)
return true;
}
qint64 LtsDateTimeEdit::msecsSinceEpoch() const
{
if (isEmpty())
@@ -662,17 +631,12 @@ void LtsDateTimeEdit::setMinMaxMonth(int minMonth, int maxMonth)
const QStringList monthSl = DTG::months();
m_uiTouch->cbxMonth->addItem(monthSl[i - 1], i);
}
m_uiTouch->cbxMonth->setCurrentIndex(m_uiTouch->cbxMonth->findData(currentMonth));
m_uiTouch->cbxMonth->blockSignals(false);
}
void LtsDateTimeEdit::setSubWidgetsProperties(const QString& name, const QVariant& value)
{
if (m_uiLe)
@@ -767,9 +731,7 @@ int LtsDateTimeEdit::getDay() const
bool LtsDateTimeEdit::setHHMMSS(int hour, int minute, int second)
{
if (hour < 0 || hour > 23 ||
minute < 0 || minute > 59 ||
second < 0 || second > 59)
if (hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59)
return false;
if (m_uiLe)
@@ -857,11 +819,7 @@ int LtsDateTimeEdit::getYear() const
bool LtsDateTimeEdit::isEmpty() const
{
return (isEmptyDay() ||
isEmptyHHMMSS() ||
isEmptyMonth() ||
isEmptyTimezone() ||
isEmptyYear());
return (isEmptyDay() || isEmptyHHMMSS() || isEmptyMonth() || isEmptyTimezone() || isEmptyYear());
}
bool LtsDateTimeEdit::isValidDate() const
@@ -869,7 +827,6 @@ bool LtsDateTimeEdit::isValidDate() const
return m_dateIsAcceptable;
}
bool LtsDateTimeEdit::isEmptyDay() const
{
if (m_uiLe)
@@ -909,24 +866,16 @@ 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());
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;
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();
@@ -939,7 +888,8 @@ bool LtsDateTimeEdit::isDataAcceptable()
return false;
}
qint64 msec = QDateTime(QDate(getYear(), getMonth(), getDay()), QTime(getHour(), getMinute(), getSecond()), Qt::UTC).toMSecsSinceEpoch();
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)
{
@@ -962,8 +912,7 @@ bool LtsDateTimeEdit::isDayAcceptable() const
const int month = getMonth();
switch (month)
{
case 2:
{
case 2: {
max = 28;
if (isYearAcceptable())
{
@@ -1030,8 +979,7 @@ void LtsDateTimeEdit::showInvalidData(bool setFocus)
bool focus = setFocus;
auto check = [&](QLineEdit * le, bool isValid)
{
auto check = [&](QLineEdit* le, bool isValid) {
if (isValid)
le->setStyleSheet(QString());
else
@@ -1073,7 +1021,9 @@ bool LtsDateTimeEdit::isLineEditDataAcceptable(QLineEdit *le) const
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()
@@ -1081,7 +1031,9 @@ void LtsDateTimeEdit::setOffsetDateTime()
if (!m_getCurrentTimeCallback)
return;
qint64 offset = LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("TimeSettings"), QStringLiteral("Offset"), 0).toLongLong();
qint64 offset = LtsUtils::OperatorSettings::getInstance()
->value(QStringLiteral("TimeSettings"), QStringLiteral("Offset"), 0)
.toLongLong();
setMsecsSinceEpoch((m_getCurrentTimeCallback() / 1000) * 1000 + offset);
}
@@ -1149,11 +1101,6 @@ void LtsDateTimeEdit::fixupHHMMSS()
QString uhrzeit(m_uiLe->leLongHHMMSS->text());
QString hh;
QString mm;
QString ss;
@@ -1279,7 +1226,6 @@ void LtsDateTimeEdit::valueMonthChanged(const QString &str)
{
m_uiLe->leLongMonth->setText(monStr);
if (cp > 0)
m_uiLe->leLongMonth->setCursorPosition(cp);
else
@@ -1409,14 +1355,14 @@ void LtsDateTimeEdit::onCheckBoxChanged()
if (m_uiLe)
{
widgets = {m_uiLe->leLongDay, m_uiLe->leLongHHMMSS, m_uiLe->leLongTZ,
m_uiLe->leLongMonth, m_uiLe->leLongYear};
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};
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();
}
@@ -1439,10 +1385,7 @@ void LtsDateTimeEdit::enableControls()
return;
enaDisaControls(true);
if (m_withSlider &&
m_minTimeMSec != 0 &&
m_maxTimeMSec > 0 &&
m_maxTimeMSec > m_minTimeMSec)
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);
@@ -1453,9 +1396,8 @@ void LtsDateTimeEdit::enaDisaControls(bool bEnable)
{
if (!m_uiLe)
return;
const QVector<QWidget *> widgets({m_uiLe->pbBBB, m_uiLe->pbBB, m_uiLe->pbB,
m_uiLe->pbF, m_uiLe->pbFF, m_uiLe->pbFFF,
m_uiLe->slTime});
const QVector<QWidget*> 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)
@@ -1513,7 +1455,6 @@ void LtsDateTimeEdit::clear()
m_uiTouch->spYear->clear();
}
emit dateTimeChanged();
}
void LtsDateTimeEdit::onFocusOutDay()
@@ -1532,9 +1473,7 @@ void LtsDateTimeEdit::onFocusOutDay()
if (value.length() == 0 && !m_backspacePressed)
{
if (!isEmptyHHMMSS() ||
!isEmptyMonth() ||
(!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) ||
if (!isEmptyHHMMSS() || !isEmptyMonth() || (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) ||
!isEmptyYear())
{
if (m_getCurrentTimeCallback)
@@ -1564,10 +1503,7 @@ void LtsDateTimeEdit::onFocusOutHHMMSS()
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)
{
@@ -1598,10 +1534,7 @@ void LtsDateTimeEdit::onFocusOutTZ()
if (value.length() == 0 && !m_backspacePressed)
{
if (!isEmptyHHMMSS() ||
!isEmptyMonth() ||
!isEmptyDay() ||
!isEmptyYear())
if (!isEmptyHHMMSS() || !isEmptyMonth() || !isEmptyDay() || !isEmptyYear())
setTimezone(DTG::timezone());
}
isDataAcceptable();
@@ -1625,9 +1558,7 @@ void LtsDateTimeEdit::onFocusOutMonth()
if (value.length() == 0 && !m_backspacePressed)
{
if (!isEmptyHHMMSS() ||
!isEmptyDay() ||
(!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) ||
if (!isEmptyHHMMSS() || !isEmptyDay() || (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) ||
!isEmptyYear())
{
if (m_getCurrentTimeCallback)
@@ -1664,9 +1595,7 @@ void LtsDateTimeEdit::onFocusOutYear()
if (value.length() == 0 && !m_backspacePressed)
{
if (!isEmptyHHMMSS() ||
!isEmptyMonth() ||
(!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) ||
if (!isEmptyHHMMSS() || !isEmptyMonth() || (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) ||
!isEmptyDay())
{
if (m_getCurrentTimeCallback)
@@ -1789,4 +1718,4 @@ void LtsDateTimeEdit::onYearWheelEvent(bool bForward, int cursorPos)
emit dateTimeChanged();
}
}
} // namespace LtsWidgets
+78 -189
View File
@@ -1,50 +1,44 @@
#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 <QHBoxLayout>
#include <QProgressBar>
#include <QLineEdit>
#include <QComboBox>
#include <QCheckBox>
#include <QSpinBox>
#include <QDateTimeEdit>
#include <QSlider>
#include <QPlainTextEdit>
#include <QTextEdit>
#include <QWidget>
#include <QRadioButton>
#include <QTableView>
#include <QTableWidget>
#include <QListView>
#include <QListWidget>
#include <QSlider>
#include <QScroller>
#include <QScrollArea>
#include <QMenu>
#include <QInputDialog>
#include <QHBoxLayout>
#include <QPainter>
#include <QColor>
#include <QMetaMethod>
#include <QDebug>
#include "lts_dialog_button_box.h"
#include "lts_dialog_helper.h"
#include "lts_message_dialog.h"
#include "lts_progress_dialog_helper.h"
#include <LtsSession/lts_session_data.h>
#include <QCheckBox>
#include <QColor>
#include <QComboBox>
#include <QDateTimeEdit>
#include <QDebug>
#include <QHBoxLayout>
#include <QInputDialog>
#include <QLineEdit>
#include <QListView>
#include <QListWidget>
#include <QMenu>
#include <QMetaMethod>
#include <QPainter>
#include <QPlainTextEdit>
#include <QProgressBar>
#include <QRadioButton>
#include <QScrollArea>
#include <QScroller>
#include <QSlider>
#include <QSpinBox>
#include <QTableView>
#include <QTableWidget>
#include <QTextEdit>
#include <QWidget>
namespace LtsWidgets
{
int LtsDialog::s_object_count = 0;
class OverlayContainer : public QWidget
{
Q_OBJECT
@@ -55,14 +49,11 @@ protected:
void paintEvent(QPaintEvent* e) override;
};
OverlayContainer::OverlayContainer(QWidget *parent)
: QWidget(parent)
OverlayContainer::OverlayContainer(QWidget* parent) : QWidget(parent)
{
setAttribute(Qt::WA_TranslucentBackground);
}
void OverlayContainer::paintEvent(QPaintEvent* e)
{
QPainter p(this);
@@ -70,24 +61,11 @@ void OverlayContainer::paintEvent(QPaintEvent *e)
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_buttonBox(nullptr)
, m_uiRequirements(new UiRequirementList())
.getNGLLogger("LtsWidget.LtsDialog"))
: 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())
{
Q_UNUSED(parent);
@@ -96,39 +74,19 @@ LtsDialog::LtsDialog(QWidget *parent, ButtonCombination buttonCombination, bool
m_dialogHelper->setDialog(this);
m_buttonBox = m_dialogHelper->getButtonBox();
addDebugMenuButton();
connect(m_buttonBox->getButton(DialogButton::Close), &QPushButton::clicked, this, &LtsDialog::slotClose);
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:
{
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);
@@ -136,16 +94,14 @@ LtsDialog::LtsDialog(QWidget *parent, ButtonCombination buttonCombination, bool
break;
}
case ButtonCombination::CloseOnly:
{
case ButtonCombination::CloseOnly: {
m_buttonBox->getButton(DialogButton::Ok)->setVisible(false);
setUnchangeable();
break;
}
default:
case ButtonCombination::SeamlessDialog:
{
case ButtonCombination::SeamlessDialog: {
m_buttonBox->setVisible(false);
setContentsMargins(0, 0, 0, 0);
m_dialogHelper->setContentsMargins(0, 0, 0, 0);
@@ -155,7 +111,6 @@ LtsDialog::LtsDialog(QWidget *parent, ButtonCombination buttonCombination, bool
if (l)
{
l->setContentsMargins(0, 0, 0, 0);
l->setMargin(0);
}
else
{
@@ -173,7 +128,6 @@ LtsDialog::LtsDialog(QWidget *parent, ButtonCombination buttonCombination, bool
}
}
LtsDialog::~LtsDialog()
{
delete m_uiRequirements;
@@ -181,13 +135,9 @@ LtsDialog::~LtsDialog()
if (m_overlayWidget)
m_overlayWidget->setParent(nullptr);
s_object_count--;
}
void LtsDialog::setOverlay(QWidget* widget)
{
if (m_overlayContainer)
@@ -198,7 +148,6 @@ void LtsDialog::setOverlay(QWidget *widget)
m_overlayWidget->setParent(nullptr);
m_overlayWidget->hide();
m_overlayWidget = nullptr;
}
m_overlayContainer->hide();
@@ -208,19 +157,14 @@ void LtsDialog::setOverlay(QWidget *widget)
m_overlayContainer = nullptr;
}
OverlayContainer* overlayContainer = new OverlayContainer(m_dialogHelper);
connect(m_dialogHelper.data(), &LtsDialogHelper::signalSizeChanged,
overlayContainer, [overlayContainer](const QSize &size)
{
overlayContainer->setGeometry(QRect(QPoint(0, 0), size));
});
connect(m_dialogHelper.data(), &LtsDialogHelper::signalSizeChanged, overlayContainer,
[overlayContainer](const QSize& size) { overlayContainer->setGeometry(QRect(QPoint(0, 0), size)); });
overlayContainer->setGeometry(QRect(QPoint(0, 0), m_dialogHelper->size()));
m_overlayContainer = overlayContainer;
QHBoxLayout* l = new QHBoxLayout;
m_overlayContainer->setLayout(l);
@@ -228,8 +172,7 @@ void LtsDialog::setOverlay(QWidget *widget)
l->addWidget(widget, 0, Qt::AlignCenter);
widget->show();
connect(widget, &QWidget::destroyed,
m_overlayContainer.data(), &QObject::deleteLater);
connect(widget, &QWidget::destroyed, m_overlayContainer.data(), &QObject::deleteLater);
m_overlayWidget = widget;
@@ -237,7 +180,6 @@ void LtsDialog::setOverlay(QWidget *widget)
m_overlayContainer->raise();
}
void LtsDialog::unsetOverlay()
{
if (m_overlayWidget)
@@ -250,19 +192,16 @@ void LtsDialog::unsetOverlay()
m_overlayContainer->deleteLater();
}
LtsDialogHelper* LtsDialog::getHelper()
{
return m_dialogHelper;
}
LtsBaseLayoutWidget* LtsDialog::baseLayoutWidget()
{
return m_baseLayoutWidget;
}
void LtsDialog::setOnlineHelpFilename(const QString& fileName)
{
m_onlineHelpFileName = fileName;
@@ -274,16 +213,11 @@ void LtsDialog::setOnlineHelpFilename(const QString &fileName)
if (LtsSessionData::LtsSessionData::getInstance()->isTablet() && strcmp(PROJECTBUILD, "guez") == 0)
return;
connect(btn, &QPushButton::clicked,
this, [this]()
{
emit signalShowOnlineHelp(m_onlineHelpFileName);
});
connect(btn, &QPushButton::clicked, this, [this]() { emit signalShowOnlineHelp(m_onlineHelpFileName); });
btn->setVisible(true);
}
void LtsDialog::addDebugMenuButton()
{
#ifdef LTS_DEBUG
@@ -298,14 +232,12 @@ void LtsDialog::addDebugMenuButton()
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]()
{
menu->addAction(QStringLiteral("enable all button box buttons"), this, [this]() {
const auto children = m_buttonBox->findChildren<QPushButton*>();
for (QPushButton* pb : children)
pb->setEnabled(true);
});
menu->addAction(QStringLiteral("show button box button .."), this, [this]()
{
menu->addAction(QStringLiteral("show button box button .."), this, [this]() {
QString buttonObjectName = QInputDialog::getText(this, QString(), QStringLiteral("Enter button object name"));
if (buttonObjectName.isEmpty())
return;
@@ -326,7 +258,8 @@ void LtsDialog::addDebugMenuButton()
for (QPushButton* pb : buttons)
buttonStringList += pb->objectName();
LtsMessageDialog::showMessage(this, QStringLiteral("button ambiguous: %1").arg(buttonStringList.join(QStringLiteral(", "))));
LtsMessageDialog::showMessage(
this, QStringLiteral("button ambiguous: %1").arg(buttonStringList.join(QStringLiteral(", "))));
return;
}
@@ -339,7 +272,6 @@ void LtsDialog::addDebugMenuButton()
#endif
}
void LtsDialog::updateWindowTitle()
{
QString completeTitle = m_title;
@@ -355,14 +287,12 @@ void LtsDialog::updateWindowTitle()
m_dialogHelper->setWindowTitle(completeTitle);
}
void LtsDialog::setWindowTitle(const QString& title)
{
m_title = title;
updateWindowTitle();
}
void LtsDialog::setBaseLayoutWidget(LtsBaseLayoutWidget* baseLayoutWidget)
{
m_baseLayoutWidget = baseLayoutWidget;
@@ -374,36 +304,46 @@ void LtsDialog::setIdentifier(const QString &identifier)
tableColumnOrganiserSetting();
}
void LtsDialog::addConnections(QWidget* widget)
{
if (addChangesMadeSignal<QLineEdit>(widget, &QLineEdit::textChanged)) return;
if (addChangesMadeSignal<QDateTimeEdit>(widget, &QDateTimeEdit::dateTimeChanged)) return;
if (addChangesMadeSignal<QComboBox>(widget, &QComboBox::currentTextChanged)) return;
if (addChangesMadeSignal<QCheckBox>(widget, &QCheckBox::stateChanged)) return;
if (addChangesMadeSignal<QSpinBox>(widget, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged))) return;
if (addChangesMadeSignal<QDoubleSpinBox>(widget, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged))) return;
if (addChangesMadeSignal<QSlider>(widget, &QSlider::valueChanged)) return;
if (addChangesMadeSignal<QPlainTextEdit>(widget, &QPlainTextEdit::textChanged)) return;
if (addChangesMadeSignal<QTextEdit>(widget, &QTextEdit::textChanged)) return;
if (addChangesMadeSignal<QAbstractButton>(widget, &QAbstractButton::toggled)) return;
if (addChangesMadeSignal<LtsDateTimeEdit>(widget, &LtsDateTimeEdit::dateTimeChanged)) return;
if (addChangesMadeSignal<QLineEdit>(widget, &QLineEdit::textChanged))
return;
if (addChangesMadeSignal<QDateTimeEdit>(widget, &QDateTimeEdit::dateTimeChanged))
return;
if (addChangesMadeSignal<QComboBox>(widget, &QComboBox::currentTextChanged))
return;
if (addChangesMadeSignal<QCheckBox>(widget, &QCheckBox::stateChanged))
return;
if (addChangesMadeSignal<QSpinBox>(widget, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged)))
return;
if (addChangesMadeSignal<QDoubleSpinBox>(
widget, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged)))
return;
if (addChangesMadeSignal<QSlider>(widget, &QSlider::valueChanged))
return;
if (addChangesMadeSignal<QPlainTextEdit>(widget, &QPlainTextEdit::textChanged))
return;
if (addChangesMadeSignal<QTextEdit>(widget, &QTextEdit::textChanged))
return;
if (addChangesMadeSignal<QAbstractButton>(widget, &QAbstractButton::toggled))
return;
if (addChangesMadeSignal<LtsDateTimeEdit>(widget, &LtsDateTimeEdit::dateTimeChanged))
return;
}
void LtsDialog::setUnchangeable(bool 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);
}
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)
{
@@ -414,7 +354,6 @@ bool LtsDialog::addDialog(LtsDialog *dialog, const QString &menuGroup, const QSt
return m_baseLayoutWidget->addWidget(dialog, menuGroup, identifier, layoutArea, setClosable, focusNewTab);
}
bool LtsDialog::amIFocused() const
{
if (!m_baseLayoutWidget)
@@ -426,7 +365,6 @@ bool LtsDialog::amIFocused() const
return m_baseLayoutWidget->isDialogFocused(this);
}
bool LtsDialog::focusDialog(const QString& menuGroup, const QString& identifier, const LayoutArea& layoutArea)
{
if (!m_baseLayoutWidget)
@@ -438,7 +376,6 @@ bool LtsDialog::focusDialog(const QString &menuGroup, const QString &identifier,
return m_baseLayoutWidget->focusTab(menuGroup, identifier, layoutArea);
}
void LtsDialog::showEvent(QShowEvent* event)
{
emit visibilityChanged(true);
@@ -454,17 +391,11 @@ void LtsDialog::showEvent(QShowEvent *event)
m_unchangeableDialog = true;
m_firstShow = false;
QList<QWidget*> listenWidgets = findChildren<QWidget*>();
for (auto i = listenWidgets.begin(); i != listenWidgets.end(); ++i)
{
QWidget* widget = *i;
QVariant isConst = widget->property("const");
@@ -483,7 +414,6 @@ void LtsDialog::showEvent(QShowEvent *event)
m_unchangeableDialog = tmp;
}
void LtsDialog::tryLockTopic()
{
TRACE_LOG(m_logger) << Q_FUNC_INFO << " START";
@@ -499,19 +429,10 @@ void LtsDialog::tryLockTopic()
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()
DEBUG_LOG(m_logger) << Q_FUNC_INFO << " signalLockTopic(): "
<< ", TopicName =" << m_topicInfo.topicName() << ", entity =" << m_topicInfo.entityId()
<< ", signalLockTopic isConnected=" << bIsConnected;
if (bIsConnected)
@@ -526,13 +447,11 @@ void LtsDialog::tryLockTopic()
void LtsDialog::initTopicLockHandler(const QString& topicName, int entityId)
{
m_topicInfo.setTopicName(topicName);
m_topicInfo.setEntity(entityId);
m_topicInfo.setValid();
}
void LtsDialog::tryLockTopicNew()
{
TRACE_LOG(m_logger) << Q_FUNC_INFO << " START";
@@ -546,8 +465,6 @@ void LtsDialog::tryLockTopicNew(const QString &topicName, int entityId)
<< ", topicName='" << topicName << "'"
<< ", entityId=" << entityId;
if (m_topicInfo.entityId() != entityId)
{
DEBUG_LOG(m_logger) << Q_FUNC_INFO << " topicName='" << topicName << "'"
@@ -555,7 +472,6 @@ void LtsDialog::tryLockTopicNew(const QString &topicName, int entityId)
m_topicInfo.setLocked(false);
}
m_topicInfo.setTopicName(topicName);
m_topicInfo.setEntity(entityId);
m_topicInfo.setValid();
@@ -568,12 +484,12 @@ void LtsDialog::tryLockTopicNew(const QString &topicName, int entityId)
void LtsDialog::triggerTopicLock()
{
TRACE_LOG(m_logger) << Q_FUNC_INFO << " START" << " !!trigger!!";
TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"
<< " !!trigger!!";
tryLockTopic();
TRACE_LOG(m_logger) << Q_FUNC_INFO << " END";
}
void LtsDialog::translate(const QString& title)
{
bool isAlreadyUnchangeable = unchangeable();
@@ -583,10 +499,6 @@ void LtsDialog::translate(const QString &title)
setWindowTitle(title);
if (!isAlreadyUnchangeable)
setUnchangeable(false);
@@ -598,7 +510,6 @@ void LtsDialog::translate(const QString &title)
{
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));
@@ -608,8 +519,6 @@ void LtsDialog::translate(const QString &title)
}
}
void LtsDialog::slotLock(const QString& lockedBy)
{
setUnchangeable(true);
@@ -620,7 +529,6 @@ void LtsDialog::slotLock(const QString &lockedBy)
retranslate();
}
void LtsDialog::slotUnlock()
{
setUnchangeable(false);
@@ -631,7 +539,6 @@ void LtsDialog::slotUnlock()
retranslate();
}
void LtsDialog::lock()
{
setWidgetsReadonly<QLineEdit>(true);
@@ -653,7 +560,6 @@ void LtsDialog::lock()
setWidgetsDisabled<QPushButton>(true);
}
void LtsDialog::unlock()
{
restoreReadonly<QLineEdit>();
@@ -674,7 +580,6 @@ void LtsDialog::unlock()
restoreEnabled<QListWidget>();
}
void LtsDialog::slotChangesMade()
{
if (m_unchangeableDialog)
@@ -689,21 +594,17 @@ void LtsDialog::slotChangesMade()
emit signalChangesMade();
}
void LtsDialog::resetChanges()
{
m_changesMade = false;
updateWindowTitle();
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())
@@ -715,32 +616,27 @@ bool LtsDialog::_apply()
return false;
}
Button LtsDialog::askApplyDiscardCancel()
{
return LtsMessageDialog::askApplyDiscardCancel(this);
}
void LtsDialog::slotApply()
{
_apply();
}
void LtsDialog::slotOkay()
{
if (_apply())
_close();
}
void LtsDialog::slotHide()
{
_hide();
}
void LtsDialog::slotClose()
{
@@ -771,23 +667,19 @@ void LtsDialog::onReadOnlyButtonClicked()
LtsWidgets::LtsMessageDialog::showMessage(this, tr("Locked by: %1").arg(m_topicLockedBy));
}
void LtsDialog::closeRequest()
{
slotClose();
}
void LtsDialog::_hide()
{
if (m_dialogHelper != nullptr)
{
emit signalHide(m_dialogHelper);
}
}
void LtsDialog::_close()
{
resetChanges();
@@ -802,9 +694,6 @@ void LtsDialog::_discard()
_close();
}
}
} // namespace LtsWidgets
#include "lts_dialog.moc"
+127 -128
View File
@@ -1,57 +1,79 @@
#pragma once
#include <QObject>
#include "lts_base.h"
#include "lts_dialog_button_box.h"
#include "ltswidgets_export.h"
#include "requirement_widget.h"
#include "lts_dialog_button_box.h"
#include <NGLLogger/NGLLoggerBootstrap.h>
#include <QPushButton>
#include <QLineEdit>
#include <QComboBox>
#include <QCheckBox>
#include <QSpinBox>
#include <QComboBox>
#include <QDateTimeEdit>
#include <QSlider>
#include <QDebug>
#include <QLineEdit>
#include <QObject>
#include <QPlainTextEdit>
#include <QPointer>
#include <QPushButton>
#include <QRadioButton>
#include <QSlider>
#include <QSpinBox>
#include <QTextEdit>
#include <QWidget>
#include <QRadioButton>
#include <QPointer>
#include <QDebug>
namespace LtsWidgets
{
class TopicInfo
{
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; }
int entityId() const
{
return m_entityId;
}
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; }
const QString& topicName() const
{
return m_topicName;
}
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:
NGL::INGLLogger &m_logger;
QString m_topicName;
int m_entityId{0};
bool m_locked{false};
bool m_valid{false};
};
class LtsBaseLayoutWidget;
class LtsDialogHelper;
class LtsProgressDialogHelper;
@@ -59,22 +81,15 @@ class LtsDialogButtonBox;
class LtsToolBarArea;
class OverlayContainer;
enum class ButtonCombination
{
enum class ButtonCombination {
OkApplyCancel,
OkCancel,
CloseOnly,
SeamlessDialog,
};
class LTSWIDGETS_EXPORT LtsDialog : public QWidget
{
Q_OBJECT
@@ -83,49 +98,77 @@ class LTSWIDGETS_EXPORT LtsDialog : public QWidget
public:
static int s_object_count;
explicit LtsDialog(QWidget *parent = nullptr, ButtonCombination buttonCombination = ButtonCombination::CloseOnly, bool closeable = true);
explicit LtsDialog(QWidget* parent = nullptr, ButtonCombination buttonCombination = ButtonCombination::CloseOnly,
bool closeable = true);
~LtsDialog();
LtsDialogHelper* getHelper();
bool hasUnsavedChanges() const { return m_changesMade || m_currentlyBlocking; }
bool hasUnsavedChanges() const
{
return m_changesMade || m_currentlyBlocking;
}
virtual void retranslate() = 0;
void closeRequest();
void setUnchangeable(bool unchangeable = true);
bool unchangeable() const { return m_unchangeableDialog; }
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);
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);
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; }
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 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; }
const QString& identifier() const
{
return m_identifier;
}
void setOverlay(QWidget* widget);
void unsetOverlay();
static inline void setMinWidthForWidgetHelper(QWidget* w)
{
int width = w->sizeHint().width();
@@ -137,48 +180,29 @@ public:
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; }
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();
@@ -187,15 +211,10 @@ signals:
void signalShowOnlineHelp(const QString& fileName);
protected:
void translate(const QString& title);
template <typename T>
void translate(T* ui, const QString& title)
{
translate(title);
@@ -213,7 +232,6 @@ protected:
template <typename T>
void translate(T* ui, const QString& custom, bool isNew, const QString& title)
{
QString newTitle;
@@ -233,7 +251,6 @@ protected:
else
newTitle = (tr("Edit %1: %2").arg(title, custom));
tryLockTopicNew();
}
}
@@ -247,44 +264,40 @@ protected:
translate(ui, newTitle);
}
template <typename T>
void translate(T* ui, const QString &customUniqueTopicName, int topicId, const QString &custom, const QString &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 ,
(topicId < 1 ),
title);
translate(ui, custom, (topicId < 1), title);
}
template <typename T, typename S>
void translate(T* ui, const S& data, const QString& custom, const QString& title)
{
translate(ui, QString::fromUtf8(typeid(data).name()), data.id(), custom, title);
}
template <typename T, typename S>
void translate(T* ui, const S& data, const QString& title)
{
translate(ui, data, QString::fromStdString(data.name()), title);
}
virtual void dialogCanceled() {}
LtsBaseLayoutWidget* baseLayoutWidget();
void setNoTopicLock() { m_noLockTopic = true; }
void setNoTopicLock()
{
m_noLockTopic = true;
}
private:
friend class LtsDialogHelper;
@@ -303,13 +316,13 @@ private:
bool m_noLockTopic;
bool m_unchangeableDialog;
QPointer<LtsDialogHelper> m_dialogHelper;
NGL::INGLLogger& m_logger;
QString m_title;
QString m_onlineHelpFileName;
QString m_menuGroup;
QString m_identifier;
QPointer<OverlayContainer> m_overlayContainer;
QPointer<QWidget> m_overlayWidget;
@@ -322,14 +335,11 @@ private:
void tryLockTopic();
void initTopicLockHandler(const QString& topicName, int entityId);
void setWindowTitle(const QString& title);
void updateWindowTitle();
void addConnections(QWidget* widget);
template <typename WidgetType, typename SignalFunc>
bool addChangesMadeSignal(QWidget *widget, SignalFunc signal)
template <typename WidgetType, typename SignalFunc> bool addChangesMadeSignal(QWidget* widget, SignalFunc signal)
{
WidgetType* concreteWidget = qobject_cast<WidgetType*>(widget);
@@ -340,9 +350,7 @@ private:
return true;
}
template <typename WidgetType>
void setWidgetsReadonly(bool readonly)
template <typename WidgetType> void setWidgetsReadonly(bool readonly)
{
const auto children = findChildren<WidgetType*>();
for (WidgetType* widget : children)
@@ -352,9 +360,7 @@ private:
}
}
template <typename WidgetType>
void setWidgetsDisabled(bool disabled)
template <typename WidgetType> void setWidgetsDisabled(bool disabled)
{
const auto children = findChildren<WidgetType*>();
for (WidgetType* widget : children)
@@ -364,8 +370,7 @@ private:
}
}
template <typename WidgetType>
void restoreReadonly()
template <typename WidgetType> void restoreReadonly()
{
const auto children = findChildren<WidgetType*>();
for (WidgetType* widget : children)
@@ -376,8 +381,7 @@ private:
}
}
template <typename WidgetType>
void restoreEnabled()
template <typename WidgetType> void restoreEnabled()
{
const auto children = findChildren<WidgetType*>();
for (WidgetType* widget : children)
@@ -390,7 +394,6 @@ private:
public slots:
void slotChangesMade();
void slotHide();
@@ -408,7 +411,11 @@ protected:
virtual void lock();
virtual void unlock();
virtual bool apply() { return true; }
virtual bool apply()
{
return true;
}
void showEvent(QShowEvent* event) override;
Button askApplyDiscardCancel();
@@ -416,10 +423,7 @@ protected:
UiRequirementList* m_uiRequirements;
};
template<typename T>
T *initDialog(T *dialog)
template <typename T> T* initDialog(T* dialog)
{
if (!dialog->init())
{
@@ -429,9 +433,7 @@ T *initDialog(T *dialog)
return dialog;
}
template<typename T, typename ... F>
T *initDialog(T *dialog, F&&... f)
template <typename T, typename... F> T* initDialog(T* dialog, F&&... f)
{
if (!dialog->init(std::forward<F>(f)...))
{
@@ -441,9 +443,7 @@ T *initDialog(T *dialog, F&&... f)
return dialog;
}
template<typename T, typename ... F>
T *createThrowableDialog(F&&... f)
template <typename T, typename... F> T* createThrowableDialog(F&&... f)
{
T* dlg = nullptr;
@@ -470,5 +470,4 @@ T *createThrowableDialog(F&&... f)
return dlg;
}
}
} // namespace LtsWidgets
+57 -63
View File
@@ -1,20 +1,19 @@
#include "lts_drag_icon.h"
#include <QAction>
#include <QButtonGroup>
#include <QDrag>
#include <QDragEnterEvent>
#include <QDragLeaveEvent>
#include <QDropEvent>
#include <QMimeData>
#include <QAction>
#include <QVBoxLayout>
#include <QLabel>
#include <QMimeData>
#include <QPainter>
#include <QPixmap>
#include <QToolButton>
#include <QButtonGroup>
#include <QPainter>
#include <QVBoxLayout>
namespace LtsWidgets
{
@@ -24,10 +23,7 @@ class LtsToolButton : public QToolButton
Q_OBJECT
public:
explicit LtsToolButton(QWidget* parent)
: QToolButton(parent)
, m_sameWidgetDrop(false)
, m_isDraggable(true)
, m_startPos(QPoint())
: QToolButton(parent), m_sameWidgetDrop(false), m_isDraggable(true), m_startPos(QPoint())
{
setAutoFillBackground(false);
setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
@@ -39,17 +35,35 @@ public:
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 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 removeAllMimeData()
{
m_mimeData.clear();
}
protected:
void initButton();
@@ -64,67 +78,54 @@ private:
bool m_isDraggable;
QPoint m_startPos;
QMap<QString, QByteArray> 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)
: 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();
}
void LtsDragIcon::setStyleToButton()
{
if (nullptr == m_toolButton) return;
if (nullptr == m_toolButton)
return;
switch (m_style)
{
case ButtonStyle::eIconOnly:
{
case ButtonStyle::eIconOnly: {
setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
m_toolButton->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
setFixedSize(QSize(static_cast<int>(m_buttonSize), static_cast<int>(m_buttonSize)));
m_toolButton->setToolButtonStyle(Qt::ToolButtonIconOnly);
} break;
}
break;
case ButtonStyle::eTextOnly:
{
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;
}
break;
case ButtonStyle::eTextNextToIcon:
{
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;
}
break;
default:
break;
}
}
void LtsDragIcon::initButton()
{
@@ -146,9 +147,8 @@ void LtsDragIcon::initButton()
generateToolTip();
m_toolButton->setIconSize(QSize(static_cast<int>(m_buttonSize), static_cast<int>(m_buttonSize)));
QVBoxLayout* box = new QVBoxLayout(this);
box->setMargin(0);
box->setContentsMargins(0, 0, 0, 0);
box->setSpacing(0);
box->addWidget(m_toolButton);
@@ -175,14 +175,12 @@ void LtsDragIcon::addToButtonGroup(QButtonGroup *btnGrp, int btnGrpId)
btnGrp->addButton(m_toolButton, btnGrpId);
}
void LtsDragIcon::setIcon(const QIcon& icon)
{
m_icon = icon;
(m_toolButton) ? m_toolButton->setIcon(modifyIcon(m_icon)) : initButton();
}
void LtsDragIcon::setMenu(QMenu* menu)
{
if (nullptr == m_toolButton)
@@ -198,7 +196,6 @@ QMenu *LtsDragIcon::menu() const
return m_toolButton->menu();
}
void LtsDragIcon::setText(const QString& text)
{
m_text = text;
@@ -299,6 +296,7 @@ void LtsDragIcon::dragEnterEvent(QDragEnterEvent *e)
if (m_toolButton)
m_toolButton->dragEnterEvent(e);
}
void LtsDragIcon::dropEvent(QDropEvent* e)
{
QWidget::dropEvent(e);
@@ -313,7 +311,8 @@ void LtsDragIcon::setButtonStyle(ButtonStyle style)
void LtsDragIcon::setIconSize(ButtonSize buttonSize)
{
m_buttonSize = buttonSize;
(m_toolButton) ? m_toolButton->setIconSize(QSize(static_cast<int>(m_buttonSize), static_cast<int>(m_buttonSize))) : initButton();
(m_toolButton) ? m_toolButton->setIconSize(QSize(static_cast<int>(m_buttonSize), static_cast<int>(m_buttonSize)))
: initButton();
}
void LtsDragIcon::setForceFixedSize(bool force)
@@ -351,8 +350,6 @@ void LtsDragIcon::changeEvent(QEvent *event)
emit enabledChanged(isEnabled());
}
void LtsToolButton::mousePressEvent(QMouseEvent* event)
{
if (event->button() == Qt::LeftButton)
@@ -360,7 +357,6 @@ void LtsToolButton::mousePressEvent(QMouseEvent *event)
QToolButton::mousePressEvent(event);
}
void LtsToolButton::mouseReleaseEvent(QMouseEvent* event)
{
QToolButton::mouseReleaseEvent(event);
@@ -370,7 +366,8 @@ void LtsToolButton::mouseMoveEvent(QMouseEvent *event)
{
if (!m_isDraggable)
return;
if (event->buttons() & Qt::LeftButton) {
if (event->buttons() & Qt::LeftButton)
{
int distance = (event->pos() - m_startPos).manhattanLength();
if (distance >= 5)
{
@@ -398,7 +395,8 @@ void LtsToolButton::performDrag(QMouseEvent *)
name = item->objectName();
}
item = item->parentWidget();
if (nullptr == item) return;
if (nullptr == item)
return;
dragIcon = dynamic_cast<LtsDragIcon*>(item);
}
QMimeData* mimeData = new QMimeData();
@@ -406,7 +404,6 @@ void LtsToolButton::performDrag(QMouseEvent *)
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()));
@@ -431,14 +428,13 @@ void LtsToolButton::performDrag(QMouseEvent *)
if (drop == Qt::MoveAction || drop == Qt::CopyAction)
emit dropSuc();
}
}
void LtsToolButton::dragEnterEvent(QDragEnterEvent* event)
{
QWidget *source =
qobject_cast<QWidget *>(event->source());
if (source && source != this) {
QWidget* source = qobject_cast<QWidget*>(event->source());
if (source && source != this)
{
event->setDropAction(Qt::MoveAction);
event->accept();
}
@@ -466,7 +462,7 @@ QIcon LtsDragIcon::modifyIcon(const QIcon &icon)
QPainter painter(&iconImage);
painter.save();
painter.setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing | QPainter::HighQualityAntialiasing | QPainter::SmoothPixmapTransform);
painter.setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
painter.setBrush(QColor("red"));
painter.setPen(QPen(QColor("red"), 3));
@@ -482,8 +478,6 @@ QIcon LtsDragIcon::modifyIcon(const QIcon &icon)
return iconImage;
}
}
} // namespace LtsWidgets
#include "lts_drag_icon.moc"
+8 -35
View File
@@ -1,34 +1,27 @@
#include "lts_frameless_dialog.h"
#include <QApplication>
#include <QRect>
#include <QStyle>
#include <QSize>
#include <QScreen>
#include <QScroller>
#include <QScrollArea>
#include <QDesktopWidget>
#include <QScroller>
#include <QShowEvent>
#include <QSize>
#include <QStyle>
#include <QTimer>
namespace LtsWidgets
{
LtsFramelessDialog::LtsFramelessDialog(QWidget *parent, const Behaviour &behaviour)
: QDialog(parent)
LtsFramelessDialog::LtsFramelessDialog(QWidget* parent, const Behaviour& behaviour) : QDialog(parent)
{
Qt::WindowFlags wf;
switch (behaviour)
{
case Behaviour::Modal:
{
case Behaviour::Modal: {
#ifndef TABLET_MODE
setModal(true);
@@ -47,27 +40,15 @@ LtsFramelessDialog::LtsFramelessDialog(QWidget *parent, const Behaviour &behavio
setWindowFlags(wf);
QTimer* t = new QTimer(this);
t->setInterval(250);
connect(t, &QTimer::timeout,
this, [this]()
{
connect(t, &QTimer::timeout, this, [this]() {
QSize s = size();
setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, s, screenRectFromPoint(QCursor::pos())));
});
}
LtsFramelessDialog::~LtsFramelessDialog()
{
}
LtsFramelessDialog::~LtsFramelessDialog() {}
QRect LtsFramelessDialog::screenRectFromPoint(const QPoint& pos) const
{
@@ -78,10 +59,6 @@ QRect LtsFramelessDialog::screenRectFromPoint(const QPoint &pos) const
bool contains = s.contains(pos);
if (contains)
return screen->geometry();
}
@@ -89,13 +66,11 @@ QRect LtsFramelessDialog::screenRectFromPoint(const QPoint &pos) const
return QRect();
}
void LtsFramelessDialog::showEvent(QShowEvent* event)
{
QDialog::showEvent(event);
QTimer::singleShot(0, this, &LtsFramelessDialog::onUpdateGeometry);
#ifdef TABLET_MODE
QList<QWidget*> scrollWidgets = findChildren<QWidget*>();
@@ -112,7 +87,6 @@ void LtsFramelessDialog::showEvent(QShowEvent *event)
#endif
}
void LtsFramelessDialog::addTouchScroll(QWidget* widget)
{
if (!widget)
@@ -127,7 +101,6 @@ void LtsFramelessDialog::addTouchScroll(QWidget *widget)
}
}
void LtsFramelessDialog::onUpdateGeometry()
{
QRect r;
@@ -150,4 +123,4 @@ void LtsFramelessDialog::onUpdateGeometry()
setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, s, r));
}
}
} // namespace LtsWidgets
+6 -13
View File
@@ -1,25 +1,21 @@
#include "lts_grid_layout.h"
#include <utility>
#include <QResizeEvent>
#include <utility>
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)
: QGridLayout(parent), m_buttonSize(buttonSize), m_defaultMaxColumn(maxColumn), m_maxColumn(maxColumn),
m_colSize(0), m_autoSize(maxColumn < 0)
{
setSizeConstraint(SizeConstraint::SetNoConstraint);
setVerticalSpacing(1);
setMargin(0);
setContentsMargins(0, 0, 0, 0);
}
void LtsGridLayout::add_widget(QWidget* widget)
@@ -55,7 +51,6 @@ void LtsGridLayout::setMaxColumn(int max)
m_maxColumn = max;
m_defaultMaxColumn = max;
m_colSize = 0;
for (QWidget* wid : std::as_const(m_widgetList))
@@ -63,7 +58,6 @@ void LtsGridLayout::setMaxColumn(int max)
for (QWidget* wid : std::as_const(m_widgetList))
addWidgetInternal(wid);
}
void LtsGridLayout::addWidgetInternal(QWidget* widget)
@@ -94,7 +88,6 @@ void LtsGridLayout::addWidgetInternal(QWidget *widget)
QGridLayout::addWidget(widget, current_row, current_column);
}
void LtsGridLayout::onParentResize(QResizeEvent* e)
{
if (m_autoSize && m_oldSize != e->size())
@@ -126,4 +119,4 @@ void LtsGridLayout::onWidgetDestroyed()
}
}
}
} // namespace LtsWidgets
+23 -61
View File
@@ -1,17 +1,14 @@
#include "lts_height_plot_widget.h"
#include <QMouseEvent>
#include <QPainter>
#include <QPainterPath>
#include <QPen>
#include <QTransform>
#include <QMouseEvent>
#include <cmath>
static inline double getLength(const QPointF& p1, const QPointF& p2)
{
const double x = p1.x() - p2.x();
@@ -23,18 +20,9 @@ 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_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);
@@ -44,6 +32,7 @@ public:
m_mousePosPen.setStyle(Qt::DashDotDotLine);
m_viewLinePen.setStyle(Qt::DashLine);
}
void clearPixmap();
double getDataHeight(double pos) const;
@@ -159,7 +148,6 @@ int LtsHeightPlotWidget::Private::findDataPointIdx(const QPointF &point) const
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.)
{
@@ -220,11 +208,15 @@ void LtsHeightPlotWidget::Private::recalcData()
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 (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))
{
@@ -232,7 +224,6 @@ void LtsHeightPlotWidget::Private::recalcData()
maxElevation += 1.0;
}
double n2 = pow(5, floor(log5(fabs(minElevation))) - 1);
if (qFuzzyIsNull(n2))
n2 = 0.1;
@@ -246,7 +237,6 @@ void LtsHeightPlotWidget::Private::recalcData()
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);
@@ -263,7 +253,6 @@ void LtsHeightPlotWidget::Private::recalcData()
m_drawPoints.lineTo(len, m_data.at(i).second);
m_heightList.append(QPair<double, double>(len, m_data.at(i).second));
}
m_drawPoints.lineTo(len, m_minElevation);
m_drawPoints.lineTo(0, m_minElevation);
@@ -286,7 +275,6 @@ void LtsHeightPlotWidget::Private::setData(const QVector< QPair< QPointF, double
resize(tmp);
}
void LtsHeightPlotWidget::Private::setMarks(const QVector<QPointF>& data)
{
m_marks = data;
@@ -317,7 +305,6 @@ void LtsHeightPlotWidget::Private::resize(const QSize &newSize)
m_trans1.reset();
m_trans2.reset();
m_trans1.translate(10, height);
m_trans1.scale(1, -1);
@@ -326,9 +313,7 @@ void LtsHeightPlotWidget::Private::resize(const QSize &newSize)
m_trans1.scale(1, -1);
m_trans2.scale((width - 2 * border) / (wertebereichX),
(height - 2 * border) / (wertebereichY));
m_trans2.scale((width - 2 * border) / (wertebereichX), (height - 2 * border) / (wertebereichY));
m_trans2.translate(0, minY);
@@ -350,20 +335,16 @@ void LtsHeightPlotWidget::Private::repaint()
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;
const QPainter::RenderHints hints =
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);
p.setPen(m_markerPen);
for (int i = 0; i < m_marks.count(); ++i)
{
@@ -375,26 +356,21 @@ void LtsHeightPlotWidget::Private::repaint()
const double height = getDataHeight(len);
const QLineF l(len, m_minElevation, len, height);
p.drawLine(m_trans2.map(l));
}
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)));
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();
@@ -410,15 +386,12 @@ void LtsHeightPlotWidget::Private::repaint()
const QPointF p1(-20, y);
const QString str = QString::number(i);
QRectF r = fm.boundingRect(str);
r.setWidth(fm.width(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.drawLine(m_trans2.map(QPointF(-m_scaleX, m_nullY)),
m_trans2.map(QPointF(m_scaleX + m_length, m_nullY)));
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)
{
@@ -426,7 +399,6 @@ void LtsHeightPlotWidget::Private::repaint()
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));
@@ -441,7 +413,7 @@ void LtsHeightPlotWidget::Private::repaint()
const QPointF p1(point.x(), point.y() + 15);
const QString str = QString::number(i);
QRectF r = fm.boundingRect(str);
r.setWidth(fm.width(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);
}
@@ -460,14 +432,11 @@ void LtsHeightPlotWidget::Private::paintLines(QPainter &p) const
if (pos.x() > m_heightList.at(m_heightList.count() - 1).first)
pos.setX(m_heightList.at(m_heightList.count() - 1).first);
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();
@@ -479,16 +448,13 @@ void LtsHeightPlotWidget::Private::paintLines(QPainter &p) const
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));
}
}
}
LtsHeightPlotWidget::LtsHeightPlotWidget(QWidget *parent)
: QWidget(parent)
, d(new Private)
LtsHeightPlotWidget::LtsHeightPlotWidget(QWidget* parent) : QWidget(parent), d(new Private)
{
setMinimumSize(300, 300);
resize(size());
@@ -520,7 +486,7 @@ void LtsHeightPlotWidget::setMarks(const QVector<QPointF> &data)
void LtsHeightPlotWidget::setBackgroundBrush(const QBrush& brush)
{
QPalette pal = palette();
pal.setBrush(QPalette::Background, brush);
pal.setBrush(QPalette::Window, brush);
setPalette(pal);
}
@@ -569,15 +535,12 @@ void LtsHeightPlotWidget::paintEvent(QPaintEvent *e)
Q_UNUSED(e);
QPainter p(this);
const QPainter::RenderHints hints = QPainter::SmoothPixmapTransform |
QPainter::TextAntialiasing |
QPainter::Antialiasing;
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();
}
@@ -618,4 +581,3 @@ void LtsHeightPlotWidget::mouseReleaseEvent(QMouseEvent *e)
update();
}
}
+7 -22
View File
@@ -1,25 +1,20 @@
#include "lts_image_editor.h"
#include <QPainter>
#include <QPaintEvent>
#include <QBrush>
#include <QEvent>
#include <QPaintEvent>
#include <QPainter>
#include <QPen>
#include <QRect>
#include <QEvent>
using namespace LtsWidgets;
LtsImageEditor::LtsImageEditor(QWidget* parent)
: QWidget(parent)
, m_isHovered(false)
, m_menuEnabled(true)
, m_bDrawOuterRect(true)
{}
: QWidget(parent), m_isHovered(false), m_menuEnabled(true), m_bDrawOuterRect(true)
{
}
void LtsImageEditor::setPixmap(const QPixmap& pixmap)
{
@@ -32,15 +27,13 @@ void LtsImageEditor::setPixmap(const QPixmap &pixmap)
emit imageChanged();
}
void LtsImageEditor::enterEvent(QEvent *)
void LtsImageEditor::enterEvent(QEnterEvent*)
{
m_isHovered = true;
update();
}
void LtsImageEditor::leaveEvent(QEvent*)
{
@@ -48,7 +41,6 @@ void LtsImageEditor::leaveEvent(QEvent *)
update();
}
bool LtsImageEditor::event(QEvent* event)
{
if (event->type() == QEvent::MouseButtonPress && m_menuEnabled)
@@ -63,16 +55,13 @@ bool LtsImageEditor::event(QEvent *event)
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))
@@ -92,14 +81,10 @@ void LtsImageEditor::paintEvent(QPaintEvent* event)
}
}
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)));
+23 -16
View File
@@ -1,14 +1,11 @@
#pragma once
#include <QObject>
#include "ltswidgets_export.h"
#include <QObject>
#include <QWidget>
namespace LtsWidgets
{
@@ -22,25 +19,36 @@ class LTSWIDGETS_EXPORT LtsImageEditor : public QWidget
public:
explicit LtsImageEditor(QWidget* parent = nullptr);
void setPixmap(const QPixmap& pixmap);
QPixmap pixmap() const
{
return m_pixmap;
}
void setMenuEnabled(bool enabled = true)
{
m_menuEnabled = enabled;
}
QPixmap pixmap() const { return m_pixmap; }
bool isMenuEnabled() const
{
return m_menuEnabled;
}
void setDrawOuterRect(bool bDraw)
{
m_bDrawOuterRect = bDraw;
}
void setMenuEnabled(bool enabled = true) { m_menuEnabled = enabled; }
bool isMenuEnabled() const { return m_menuEnabled; }
void setDrawOuterRect(bool bDraw) { m_bDrawOuterRect = bDraw; }
bool drawOuterRect() const { return m_bDrawOuterRect; }
bool drawOuterRect() const
{
return m_bDrawOuterRect;
}
protected:
void paintEvent(QPaintEvent* event);
void enterEvent(QEvent *);
void enterEvent(QEnterEvent*);
void leaveEvent(QEvent*);
bool event(QEvent* event);
@@ -52,10 +60,9 @@ private:
signals:
void signalClicked();
void imageChanged();
};
}
} // namespace LtsWidgets
+33 -40
View File
@@ -1,28 +1,25 @@
#include "lts_message_dialog.h"
#include "lts_message_dialog_helper.h"
#include <QCoreApplication>
#include <QVBoxLayout>
#include <QDebug>
#include <QLabel>
#include <QPushButton>
#include <QDebug>
#include <QVBoxLayout>
namespace LtsWidgets
{
namespace LtsMessageDialog
{
Button showMessage(QWidget* parent,
const QString& message,
const QString &title,
const Behaviour behaviour,
const Buttons buttons,
const QHash<Button, QString> &buttonTexts)
Button showMessage(QWidget* parent, const QString& message, const QString& title, const Behaviour behaviour,
const Buttons buttons, const QHash<Button, QString>& buttonTexts)
{
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 !!";
qDebug() << "LtsMessageDialog: showMessage called while showMessage is in its Event Loop - do not open more "
"than one Dialog at once !!";
s_used = 1;
@@ -37,34 +34,27 @@ Button showMessage(QWidget* parent,
Button askApplyDiscardCancel(QWidget* parent)
{
const QString question = QCoreApplication::translate("LtsDialog",
"<br>"
const QString question = QCoreApplication::translate("LtsDialog", "<br>"
"Apply - apply changes and close.<br>"
"Discard - discard changes and close.<br>"
"Cancel - do not close.");
const QString title = QCoreApplication::translate("LtsDialog", "Unapplied changes made. Apply the changes?");
return LtsMessageDialog::showMessage(parent,
question,
title,
Behaviour::Modal,
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<Button, QString> &buttonTexts, bool deleteOnClose)
LtsMessageDialogNew::LtsMessageDialogNew(QWidget* parent, const QString& message, const QString& title,
const Behaviour behaviour, const Buttons buttons,
const QHash<Button, QString>& buttonTexts, bool deleteOnClose)
{
m_dialog = new LtsFramelessDialog(parent, behaviour);
if (deleteOnClose)
m_dialog->setAttribute(Qt::WA_DeleteOnClose);
connect(m_dialog, &LtsFramelessDialog::destroyed,
this, &LtsMessageDialogNew::deleteLater);
connect(m_dialog, &LtsFramelessDialog::destroyed, this, &LtsMessageDialogNew::deleteLater);
QVBoxLayout* mainLayout = new QVBoxLayout(m_dialog);
@@ -81,28 +71,33 @@ LtsMessageDialogNew::LtsMessageDialogNew(QWidget *parent, const QString &message
mainLayout->addWidget(messageLabel);
QHBoxLayout* buttonLayout = new QHBoxLayout;
buttonLayout->setMargin(0);
buttonLayout->setContentsMargins(0, 0, 0, 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);
connect(addButton(buttonTexts.value(Button::Ok, tr("Ok")), buttonLayout, m_dialog, Button::Ok, parent),
&QPushButton::clicked, this, &LtsMessageDialogNew::ok);
if (buttons.testFlag(Button::Yes))
connect(addButton(buttonTexts.value(Button::Yes, tr("Yes")), buttonLayout, m_dialog, Button::Yes, parent), &QPushButton::clicked, this, &LtsMessageDialogNew::yes);
connect(addButton(buttonTexts.value(Button::Yes, tr("Yes")), buttonLayout, m_dialog, Button::Yes, parent),
&QPushButton::clicked, this, &LtsMessageDialogNew::yes);
if (buttons.testFlag(Button::No))
connect(addButton(buttonTexts.value(Button::No, tr("No")), buttonLayout, m_dialog, Button::No, parent), &QPushButton::clicked, this, &LtsMessageDialogNew::no);
connect(addButton(buttonTexts.value(Button::No, tr("No")), buttonLayout, m_dialog, Button::No, parent),
&QPushButton::clicked, this, &LtsMessageDialogNew::no);
if (buttons.testFlag(Button::Apply))
connect(addButton(buttonTexts.value(Button::Apply, tr("Apply")), buttonLayout, m_dialog, Button::Apply, parent), &QPushButton::clicked, this, &LtsMessageDialogNew::apply);
connect(addButton(buttonTexts.value(Button::Apply, tr("Apply")), buttonLayout, m_dialog, Button::Apply, parent),
&QPushButton::clicked, this, &LtsMessageDialogNew::apply);
if (buttons.testFlag(Button::Discard))
connect(addButton(buttonTexts.value(Button::Discard, tr("Discard")), buttonLayout, m_dialog, Button::Discard, parent), &QPushButton::clicked, this, &LtsMessageDialogNew::discard);
connect(addButton(buttonTexts.value(Button::Discard, tr("Discard")), buttonLayout, m_dialog, Button::Discard,
parent),
&QPushButton::clicked, this, &LtsMessageDialogNew::discard);
if (buttons.testFlag(Button::Cancel))
connect(addButton(buttonTexts.value(Button::Cancel, tr("Cancel")), buttonLayout, m_dialog, Button::Cancel, parent), &QPushButton::clicked, this, &LtsMessageDialogNew::cancel);
connect(
addButton(buttonTexts.value(Button::Cancel, tr("Cancel")), buttonLayout, m_dialog, Button::Cancel, parent),
&QPushButton::clicked, this, &LtsMessageDialogNew::cancel);
QWidget* buttonLayoutWidget = new QWidget;
buttonLayoutWidget->setLayout(buttonLayout);
@@ -113,15 +108,14 @@ LtsMessageDialogNew::LtsMessageDialogNew(QWidget *parent, const QString &message
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);
if (button == Button::Ok ||
button == Button::Cancel)
if (button == Button::Ok || button == Button::Cancel)
{
btn->setDefault(true);
}
@@ -129,5 +123,4 @@ QPushButton* LtsMessageDialogNew::addButton(const QString &text, QHBoxLayout *th
return btn;
}
}
} // namespace LtsWidgets
+17 -30
View File
@@ -1,27 +1,21 @@
#include "lts_message_dialog_helper.h"
#include <QPushButton>
#include <QVBoxLayout>
#include <QEventLoop>
#include <QHBoxLayout>
#include <QLabel>
#include <QEventLoop>
#include <QPushButton>
#include <QVBoxLayout>
namespace LtsWidgets
{
LtsMessageDialogHelper::LtsMessageDialogHelper(QObject* parent)
: QObject(parent)
, m_result(Button::Cancel)
, m_dialog(nullptr)
{}
: QObject(parent), m_result(Button::Cancel), m_dialog(nullptr)
{
}
Button LtsMessageDialogHelper::showMessage(QWidget *parent,
const QString &message,
const QString &title,
Behaviour behaviour,
Buttons buttons,
Button LtsMessageDialogHelper::showMessage(QWidget* parent, const QString& message, const QString& title,
Behaviour behaviour, Buttons buttons,
const QHash<Button, QString>& buttonTexts)
{
m_dialog = new LtsFramelessDialog(parent, behaviour);
@@ -43,8 +37,7 @@ Button LtsMessageDialogHelper::showMessage(QWidget *parent,
mainLayout->addWidget(messageLabel);
QHBoxLayout* buttonLayout = new QHBoxLayout;
buttonLayout->setMargin(0);
buttonLayout->setContentsMargins(0, 0, 0, 0);
connect(m_dialog, &LtsFramelessDialog::rejected, this, &LtsMessageDialogHelper::slotCancel);
@@ -65,11 +58,13 @@ Button LtsMessageDialogHelper::showMessage(QWidget *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),
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),
connect(
addButton(buttonTexts.value(Button::Cancel, tr("Cancel")), buttonLayout, m_dialog, Button::Cancel, parent),
&QPushButton::clicked, this, &LtsMessageDialogHelper::slotCancel);
QWidget* buttonLayoutWidget = new QWidget;
@@ -80,7 +75,6 @@ Button LtsMessageDialogHelper::showMessage(QWidget *parent,
m_dialog->show();
m_dialog->raise();
QEventLoop loop;
connect(this, &LtsMessageDialogHelper::signalQuitEventLoop, &loop, &QEventLoop::quit, Qt::QueuedConnection);
loop.exec();
@@ -88,7 +82,6 @@ Button LtsMessageDialogHelper::showMessage(QWidget *parent,
return m_result;
}
void LtsMessageDialogHelper::slotOkay()
{
m_dialog->hide();
@@ -96,7 +89,6 @@ void LtsMessageDialogHelper::slotOkay()
emit signalQuitEventLoop();
}
void LtsMessageDialogHelper::slotYes()
{
m_dialog->hide();
@@ -104,7 +96,6 @@ void LtsMessageDialogHelper::slotYes()
emit signalQuitEventLoop();
}
void LtsMessageDialogHelper::slotNo()
{
m_dialog->hide();
@@ -112,7 +103,6 @@ void LtsMessageDialogHelper::slotNo()
emit signalQuitEventLoop();
}
void LtsMessageDialogHelper::slotApply()
{
m_dialog->hide();
@@ -120,7 +110,6 @@ void LtsMessageDialogHelper::slotApply()
emit signalQuitEventLoop();
}
void LtsMessageDialogHelper::slotDiscard()
{
m_dialog->hide();
@@ -128,7 +117,6 @@ void LtsMessageDialogHelper::slotDiscard()
emit signalQuitEventLoop();
}
void LtsMessageDialogHelper::slotCancel()
{
m_dialog->hide();
@@ -136,15 +124,14 @@ void LtsMessageDialogHelper::slotCancel()
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);
if (button == Button::Ok ||
button == Button::Cancel)
if (button == Button::Ok || button == Button::Cancel)
{
btn->setDefault(true);
}
@@ -152,4 +139,4 @@ QPushButton* LtsMessageDialogHelper::addButton(const QString &text, QHBoxLayout
return btn;
}
}
} // namespace LtsWidgets
+6 -8
View File
@@ -1,10 +1,10 @@
#pragma once
#include <QObject>
#include "ltswidgets_export.h"
#include <QObject>
#include <QRegularExpression>
#include <QSet>
#include <QSpinBox>
@@ -19,7 +19,6 @@ public:
explicit LtsMultiRangeSpinBox(QWidget* parent = nullptr);
~LtsMultiRangeSpinBox() = default;
public slots:
void setRanges(const QVector<QPair<int, int>>& ranges);
void setRange(int min, int max);
@@ -41,13 +40,12 @@ private:
int fixupValue(int value) const;
int fixupValue(int value, bool higher) const;
private:
QVector<QPair<int, int>> m_rangesList;
int m_curVal = minimum();
QRegExp m_regex;
QRegularExpression m_regex;
};
}
} // namespace LtsWidgets
+35 -57
View File
@@ -1,38 +1,30 @@
#include "lts_notification_box.h"
#include "ui_lts_notification_box.h"
#include <QPainter>
#include <QLinearGradient>
#include <QColor>
#include <QGraphicsDropShadowEffect>
#include <QStyleOption>
#include <QLinearGradient>
#include <QPainter>
#include <QStyle>
#include <QStyleOption>
#ifdef NOTIBOX_DEBUG
#include <QDebug>
#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({});
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"));
@@ -44,7 +36,6 @@ LtsNotificationBox::LtsNotificationBox(QWidget *parent)
setGraphicsEffect(shadow);
}
void LtsNotificationBox::message(const QString& title, const QString& text, MessageType type)
{
static QString rgbBaseString(QStringLiteral("%1, %2, %3"));
@@ -67,7 +58,6 @@ void LtsNotificationBox::message(const QString &title, const QString &text, Mess
static QColor warningStart(253, 151, 4);
static QColor warningEnd(253, 202, 0);
QColor start;
QColor end;
QString close;
@@ -78,8 +68,7 @@ void LtsNotificationBox::message(const QString &title, const QString &text, Mess
switch (type)
{
case MessageType::Error:
{
case MessageType::Error: {
start = errorStart;
end = errorEnd;
close = closeDefault;
@@ -92,8 +81,7 @@ void LtsNotificationBox::message(const QString &title, const QString &text, Mess
break;
}
case MessageType::Success:
{
case MessageType::Success: {
start = successStart;
end = successEnd;
close = closeDefault;
@@ -106,8 +94,7 @@ void LtsNotificationBox::message(const QString &title, const QString &text, Mess
break;
}
case MessageType::Info:
{
case MessageType::Info: {
start = infoStart;
end = infoEnd;
close = closeDefault;
@@ -120,8 +107,7 @@ void LtsNotificationBox::message(const QString &title, const QString &text, Mess
break;
}
case MessageType::Warning:
{
case MessageType::Warning: {
start = warningStart;
end = warningEnd;
close = closeDark;
@@ -137,17 +123,26 @@ void LtsNotificationBox::message(const QString &title, const QString &text, Mess
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()),
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);
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#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);
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;
@@ -163,36 +158,19 @@ void LtsNotificationBox::message(const QString &title, const QString &text, Mess
m_ui->lblImage->setStyleSheet(QString());
setStyleSheet(css.join(QStringLiteral(" ")));
m_ui->lblText->setText(QStringLiteral("<p><span style='font-size:14pt; font-weight:600; color:#%1;'>%2</span></p><p><span style='font-size:14pt; color:#%3;'>%4</span></p>").arg(textColor, title, textColor, text));
m_ui->lblText->setText(
QStringLiteral("<p><span style='font-size:14pt; font-weight:600; color:#%1;'>%2</span></p><p><span "
"style='font-size:14pt; color:#%3;'>%4</span></p>")
.arg(textColor, title, textColor, text));
show();
}
void LtsNotificationBox::paintEvent(QPaintEvent*)
{
QStyleOption opt;
opt.init(this);
opt.initFrom(this);
QPainter p(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
}
} // namespace LtsWidgets
+11 -34
View File
@@ -1,30 +1,24 @@
#include "lts_profile_button.h"
#include <QBrush>
#include <QEvent>
#include <QPaintEvent>
#include <QPainter>
#include <QPainterPath>
#include <QPaintEvent>
#include <QBrush>
#include <QPen>
#include <QRect>
#include <QEvent>
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)
{
QSizePolicy qsp = QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
qsp.setHeightForWidth(true);
setSizePolicy(qsp);
}
void LtsProfileButton::setPixmap(const QPixmap& pixmap)
{
if (pixmap.isNull())
@@ -35,16 +29,14 @@ void LtsProfileButton::setPixmap(const QPixmap &pixmap)
update();
}
void LtsProfileButton::enterEvent(QEvent* event)
{
m_isHovered = true;
update();
QWidget::enterEvent(event);
QWidget::enterEvent(static_cast<QEnterEvent*>(event));
}
void LtsProfileButton::leaveEvent(QEvent* event)
{
@@ -53,7 +45,6 @@ void LtsProfileButton::leaveEvent(QEvent *event)
QWidget::leaveEvent(event);
}
bool LtsProfileButton::event(QEvent* event)
{
if (event->type() == QEvent::MouseButtonPress && m_menuEnabled)
@@ -68,7 +59,6 @@ bool LtsProfileButton::event(QEvent *event)
return QWidget::event(event);
}
void LtsProfileButton::paintEvent(QPaintEvent* event)
{
QPainter p(this);
@@ -79,11 +69,8 @@ void LtsProfileButton::paintEvent(QPaintEvent* event)
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);
@@ -95,24 +82,13 @@ void LtsProfileButton::paintEvent(QPaintEvent* event)
}
}
QPainterPath path;
path.addEllipse(center,
minSize / 2.0 - 4,
minSize / 2.0 - 4);
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);
p.drawEllipse(center, minSize / 2.0 - 4, minSize / 2.0 - 4);
if (m_isHovered && m_menuEnabled)
{
@@ -122,12 +98,13 @@ void LtsProfileButton::paintEvent(QPaintEvent* event)
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 - (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)));
p.drawLine(QPointF(xc - (diff / 2.01f), yc + (diff / 3.01f)),
QPointF(xc + (diff / 2.02f), yc + (diff / 3.02f)));
}
event->accept();
p.restore();
}
+43 -134
View File
@@ -1,38 +1,36 @@
#include "lts_tab_widget.h"
#include "lts_tab_bar.h"
#include <LtsWidgets/lts_dialog.h>
#include <LtsWidgets/lts_dialog_helper.h>
#include <LtsWidgets/lts_splitter.h>
#include <QAbstractButton>
#include <QDialog>
#include <QApplication>
#include <QBrush>
#include <QColor>
#include <QDebug>
#include <QSize>
#include <QDialog>
#include <QFontMetrics>
#include <QLabel>
#include <QLineF>
#include <QPaintEvent>
#include <QPainter>
#include <QBrush>
#include <QApplication>
#include <QColor>
#include <QPen>
#include <QFontMetrics>
#include <QRectF>
#include <QLineF>
#include <QPointF>
#include <math.h>
#include <QRandomGenerator>
#include <QRectF>
#include <QSize>
#include <QTimer>
#include <QLabel>
#include <math.h>
namespace LtsWidgets
{
LtsTabWidget::LtsTabWidget(QWidget* parent, bool isSecondary)
: QTabWidget(parent)
, m_tabbar(nullptr)
, m_hasSubTabs(false)
, m_isSecondary(isSecondary)
, m_mainSplitterState(QByteArray())
: QTabWidget(parent), m_tabbar(nullptr), m_hasSubTabs(false), m_isSecondary(isSecondary),
m_mainSplitterState(QByteArray())
{
setDocumentMode(true);
setMinimumSize(200, 100);
@@ -52,20 +50,15 @@ LtsTabWidget::LtsTabWidget(QWidget *parent, bool isSecondary)
bold = false;
}
currentFont.setCapitalization(c);
currentFont.setBold(bold);
tabBar->setFont(currentFont);
connect(this, &LtsTabWidget::currentChanged,
this, &LtsTabWidget::slotCurrentChanged);
connect(this, &LtsTabWidget::currentChanged, this, &LtsTabWidget::slotCurrentChanged);
QSplitter* splitter = static_cast<QSplitter*>(parent);
if (splitter &&
splitter->objectName() == QStringLiteral("mainSplitter") &&
splitter->widget(1) == this &&
if (splitter && splitter->objectName() == QStringLiteral("mainSplitter") && splitter->widget(1) == this &&
!isSecondary)
{
int tabBarHeight = m_tabbar->height() * 1.33;
@@ -73,7 +66,8 @@ LtsTabWidget::LtsTabWidget(QWidget *parent, bool isSecondary)
setStyleSheet(styleSheet() + QStringLiteral("QTabWidget::tab-bar {"
"left: %1px; "
"} ").arg(tabBarWidth));
"} ")
.arg(tabBarWidth));
QPushButton* maxBtn = new QPushButton(this);
maxBtn->setObjectName(QStringLiteral("MinMaxTabButton"));
maxBtn->setText(QStringLiteral("▲\n▼"));
@@ -86,15 +80,12 @@ LtsTabWidget::LtsTabWidget(QWidget *parent, bool isSecondary)
}
}
LtsTabWidget::~LtsTabWidget()
{
clearAll();
}
void LtsTabWidget::slotCurrentChanged(int newIdx)
{
if (newIdx < 0)
@@ -117,7 +108,6 @@ void LtsTabWidget::slotCurrentChanged(int newIdx)
return;
}
LtsTabWidget* tab = qobject_cast<LtsTabWidget*>(w);
if (tab != nullptr)
@@ -153,7 +143,6 @@ void LtsTabWidget::slotMaximizeButtonClicked()
}
}
void LtsTabWidget::closeRequestTabWidget(LtsTabWidget* tabWidget)
{
for (int i = 0; i < tabWidget->count(); i++)
@@ -176,7 +165,6 @@ void LtsTabWidget::closeRequestTabWidget(LtsTabWidget *tabWidget)
}
}
void LtsTabWidget::slotTabCloseRequested(int index)
{
QWidget* w = widget(index);
@@ -214,7 +202,10 @@ void LtsTabWidget::slotTabCloseRequested(int index)
buttons.setFlag(Button::Cancel, true);
QHash<Button, QString> buttonTexts;
buttonTexts.insert(Button::Yes, tr("Discard All"));
const auto ret = LtsMessageDialog::showMessage(this, tr("There are dialogs with unsaved changes.<br>Please save or discard their changes before closing."), tr("Unsaved changes"), Behaviour::Modal, buttons, buttonTexts);
const auto ret = LtsMessageDialog::showMessage(
this,
tr("There are dialogs with unsaved changes.<br>Please save or discard their changes before closing."),
tr("Unsaved changes"), Behaviour::Modal, buttons, buttonTexts);
switch (ret)
{
case Button::Yes:
@@ -231,15 +222,11 @@ void LtsTabWidget::slotTabCloseRequested(int index)
}
}
w->deleteLater();
}
void LtsTabWidget::onCheckTabBarVisibility()
{
if (!m_isSecondary)
{
@@ -251,36 +238,8 @@ void LtsTabWidget::onCheckTabBarVisibility()
if (count() < 1)
deleteLater();
}
}
void LtsTabWidget::setSubTabsVisible(bool visible)
{
if (count())
@@ -292,19 +251,14 @@ void LtsTabWidget::setSubTabsVisible(bool 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)
{
setFocus();
LtsTabWidget* tab = this;
QString fullName;
if (m_hasSubTabs)
{
fullName = identifier;
@@ -329,15 +283,12 @@ void LtsTabWidget::addTab(const QString &menuGroup, const QString &identifier, Q
else
{
fullName = menuGroup + QLatin1Char('.') + identifier;
}
setHidden(false);
tab->addWidget(fullName, widget, setClosable, focusNewTab);
if (m_hasSubTabs)
{
LtsTabBar* tabbar = tab->tabBar();
@@ -354,7 +305,6 @@ void LtsTabWidget::addTab(const QString &menuGroup, const QString &identifier, Q
}
}
void LtsTabWidget::addWidget(const QString& fullName, QWidget* widget, bool setClosable, bool focusNewTab)
{
QString theName = fullName;
@@ -362,13 +312,14 @@ void LtsTabWidget::addWidget(const QString &fullName, QWidget *widget, bool setC
if (fullName.isEmpty())
{
const QString possibleCharacters(QStringLiteral("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"));
const QString possibleCharacters(
QStringLiteral("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"));
const int randomStringLength = 24;
QString randomString;
for (int i = 0; i < randomStringLength; i++)
{
int index = qrand() % possibleCharacters.length();
int index = QRandomGenerator::global()->bounded(possibleCharacters.length());
QChar nextChar = possibleCharacters.at(index);
randomString.append(nextChar);
}
@@ -394,23 +345,22 @@ void LtsTabWidget::addWidget(const QString &fullName, QWidget *widget, bool setC
if (helper)
{
connect(helper->getDialog(), &LtsDialog::signalHide, this, static_cast<void (LtsTabWidget::*)(QObject*)>(&LtsTabWidget::onRemoveTab),
connect(helper->getDialog(), &LtsDialog::signalHide, this,
static_cast<void (LtsTabWidget::*)(QObject*)>(&LtsTabWidget::onRemoveTab),
static_cast<Qt::ConnectionType>(Qt::QueuedConnection | Qt::UniqueConnection));
}
connect(widget, &QWidget::destroyed, this, static_cast<void (LtsTabWidget::*)(QObject*)>(&LtsTabWidget::onRemoveTab), Qt::DirectConnection);
connect(widget, &QWidget::destroyed, this,
static_cast<void (LtsTabWidget::*)(QObject*)>(&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);
@@ -437,10 +387,8 @@ void LtsTabWidget::addWidget(const QString &fullName, QWidget *widget, bool setC
if (tabbar)
tabbar->updateCloseButtonColors();
}
void LtsTabWidget::slotWindowTitleChanged(const QString& title)
{
QWidget* w = qobject_cast<QWidget*>(sender());
@@ -459,7 +407,6 @@ void LtsTabWidget::slotWindowTitleChanged(const QString &title)
return;
}
QString realTitle = title;
QString readOnlyHint;
QStringList sl = title.split(QStringLiteral("- READ-ONLY"));
@@ -468,7 +415,6 @@ void LtsTabWidget::slotWindowTitleChanged(const QString &title)
realTitle = sl.first().trimmed();
readOnlyHint = sl.back().trimmed();
if (readOnlyHint.startsWith(QStringLiteral("(")))
readOnlyHint.remove(0, 1);
if (readOnlyHint.endsWith(QStringLiteral(")")))
@@ -488,14 +434,13 @@ void LtsTabWidget::slotWindowTitleChanged(const QString &title)
readOnly->setPixmap(QIcon(QStringLiteral("icon:warning.svg")).pixmap(QSize(25, 25)));
tabBar->setTabButton(index, QTabBar::ButtonPosition::LeftSide, readOnly);
} else {
}
else
{
QWidget* readOnly = tabBar->tabButton(index, QTabBar::ButtonPosition::LeftSide);
if (readOnly)
{
tabBar->setTabButton(index, QTabBar::ButtonPosition::LeftSide, nullptr);
readOnly->setParent(this);
delete readOnly;
@@ -503,7 +448,6 @@ void LtsTabWidget::slotWindowTitleChanged(const QString &title)
}
}
QWidget* LtsTabWidget::getWidget(const QString& menuGroup, const QString& identifier)
{
LtsTabWidget* tab = this;
@@ -525,13 +469,11 @@ QWidget *LtsTabWidget::getWidget(const QString &menuGroup, const QString &identi
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<LtsTabWidget> tab = this;
@@ -555,16 +497,9 @@ bool LtsTabWidget::focusTab(const QString &menuGroup, const QString &identifier)
if (!tab)
return false;
LtsSplitter* splitter = static_cast<LtsSplitter*>(parent());
QTimer::singleShot(500, this, [splitter, tab]() {
if (splitter && tab && (tab->count() >= 1) && splitter->sizes().count() && !(splitter->sizes().at(1)))
{
splitter->animate(1);
@@ -573,7 +508,6 @@ bool LtsTabWidget::focusTab(const QString &menuGroup, const QString &identifier)
return tab->focusWidget(fullName);
}
bool LtsTabWidget::focusWidget(const QString& fullName)
{
QWidget* widget = m_tabMap.value(fullName, nullptr);
@@ -586,7 +520,6 @@ bool LtsTabWidget::focusWidget(const QString &fullName)
return true;
}
bool LtsTabWidget::removeWidget(QWidget* widget)
{
if (nullptr == widget)
@@ -602,7 +535,8 @@ bool LtsTabWidget::removeWidget(QWidget * widget)
if (w == widget)
{
m_tabMap.erase(i);
disconnect(widget, &QWidget::destroyed, this, static_cast<void (LtsTabWidget::*)(QObject*)>(&LtsTabWidget::onRemoveTab));
disconnect(widget, &QWidget::destroyed, this,
static_cast<void (LtsTabWidget::*)(QObject*)>(&LtsTabWidget::onRemoveTab));
return true;
}
@@ -619,7 +553,6 @@ bool LtsTabWidget::removeWidget(QWidget * widget)
return false;
}
void LtsTabWidget::onRemoveTab(QObject* object)
{
if (object == nullptr)
@@ -650,7 +583,8 @@ void LtsTabWidget::onRemoveTab(QObject *object)
if (index < 0)
{
qWarning() << "LtsTabWidget::onRemoveTab: cannot remove widget, as it was not found on the tab widget" << (void *)w;
qWarning() << "LtsTabWidget::onRemoveTab: cannot remove widget, as it was not found on the tab widget"
<< (void*)w;
}
else
{
@@ -660,26 +594,22 @@ void LtsTabWidget::onRemoveTab(QObject *object)
onCheckTabBarVisibility();
}
void LtsTabWidget::setActuatorTabStyle(bool enable)
{
if (enable)
setTabBar(new LtsTabBar(false, this));
}
LtsTabBar* LtsTabWidget::tabBar()
{
return m_tabbar;
}
void LtsTabWidget::setTabBar(LtsTabBar* tabbar)
{
if (m_tabbar)
m_tabbar->deleteLater();
QFont currentFont = font();
currentFont.setCapitalization(QFont::SmallCaps);
currentFont.setBold(true);
@@ -691,11 +621,9 @@ void LtsTabWidget::setTabBar(LtsTabBar *tabbar)
QTabWidget::setTabBar(m_tabbar);
}
void LtsTabWidget::clearAll()
{
for (int i = 0; i < count(); i++)
{
QWidget* w = widget(i);
@@ -703,7 +631,8 @@ void LtsTabWidget::clearAll()
if (w == nullptr)
continue;
disconnect(w, &QWidget::destroyed, this, static_cast<void (LtsTabWidget::*)(QObject*)>(&LtsTabWidget::onRemoveTab));
disconnect(w, &QWidget::destroyed, this,
static_cast<void (LtsTabWidget::*)(QObject*)>(&LtsTabWidget::onRemoveTab));
w->deleteLater();
}
@@ -711,7 +640,6 @@ void LtsTabWidget::clearAll()
clear();
}
void LtsTabWidget::aboutToClose()
{
for (int i = 0; i < count(); i++)
@@ -738,7 +666,6 @@ void LtsTabWidget::aboutToClose()
}
}
bool LtsTabWidget::hasUnsavedChanges(LtsTabWidget* tabWidget)
{
for (int i = 0; i < tabWidget->count(); i++)
@@ -754,14 +681,12 @@ bool LtsTabWidget::hasUnsavedChanges(LtsTabWidget *tabWidget)
if (dlg != nullptr)
{
if (dlg->hasUnsavedChanges())
{
int dlgIndex = tabWidget->indexOf(helper);
if (dlgIndex != -1)
tabWidget->setCurrentIndex(dlgIndex);
return true;
}
}
@@ -772,7 +697,6 @@ bool LtsTabWidget::hasUnsavedChanges(LtsTabWidget *tabWidget)
if (tab)
{
bool _hasUnsavedChanges = hasUnsavedChanges(tab);
if (_hasUnsavedChanges)
{
@@ -783,19 +707,11 @@ bool LtsTabWidget::hasUnsavedChanges(LtsTabWidget *tabWidget)
return true;
}
}
}
return false;
}
void CloseButton::paintEvent(QPaintEvent*)
{
QPainter p(this);
@@ -804,10 +720,8 @@ void CloseButton::paintEvent(QPaintEvent *)
p.setPen(QPen(QColor(m_fontColor), 1.5));
p.setRenderHint(QPainter::Antialiasing);
p.drawLine(line());
p.setPen(QPen(QColor(m_fontColor), 2.5));
QRectF c = cross();
@@ -818,7 +732,6 @@ void CloseButton::paintEvent(QPaintEvent *)
p.restore();
}
QLineF CloseButton::line() const
{
qreal forceBlur = 0.001;
@@ -828,7 +741,6 @@ QLineF CloseButton::line() const
return QLineF(QPointF(lineStart, lineStart), QPointF(lineStart, lineSize));
}
QRectF CloseButton::cross() const
{
QLineF l = line();
@@ -838,13 +750,13 @@ QRectF CloseButton::cross() const
qreal crossStartX = lineLeft * 3;
qreal crossStartY = lineLeft * 2;
qreal crossEndX = width(); crossEndX -= crossEndX * 0.15 + forceBlur;
qreal crossEndX = width();
crossEndX -= crossEndX * 0.15 + forceBlur;
qreal crossEndY = height() - crossStartY;
return QRectF(QPointF(crossStartX, crossStartY), QPointF(crossEndX, crossEndY));
}
QSize CloseButton::sizeHint() const
{
QFontMetrics fm(QApplication::font());
@@ -858,14 +770,12 @@ QSize CloseButton::sizeHint() const
return QSize(finalSize, finalSize);
}
void CloseButton::mousePressEvent(QMouseEvent* e)
{
e->ignore();
m_isPressed = true;
}
void CloseButton::mouseReleaseEvent(QMouseEvent* e)
{
bool isPressed = m_isPressed;
@@ -887,8 +797,7 @@ void CloseButton::mouseReleaseEvent(QMouseEvent *e)
return;
}
e->accept();
emit clicked();
}
}
} // namespace LtsWidgets
+41 -80
View File
@@ -2,76 +2,52 @@
#include "ui_lts_text_editor.h"
#include <QColorDialog>
#include <QTextCursor>
#include <QApplication>
#include <QClipboard>
#include <QTextCharFormat>
#include <QMimeData>
#include <QTextList>
#include <QLineEdit>
#include <QColorDialog>
#include <QDebug>
#include <QLineEdit>
#include <QMimeData>
#include <QTextCharFormat>
#include <QTextCursor>
#include <QTextList>
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);
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());
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->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->pbUndo, &QToolButton::clicked,
m_ui->textEdit, &QTextEdit::undo);
connect(m_ui->pbRedo, &QToolButton::clicked,
m_ui->textEdit, &QTextEdit::redo);
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->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->pbTextColor, &QToolButton::clicked,
this, &LtsTextEditor::slotTextColor);
connect(m_ui->pbBackgroundColor, &QToolButton::clicked,
this, &LtsTextEditor::slotBackgroundColor);
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);
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);
QFont textFont(QStringLiteral("Sans Serif"));
textFont.setStyleHint(QFont::SansSerif);
@@ -82,31 +58,26 @@ LtsTextEditor::LtsTextEditor(QWidget *parent)
slotBackgroundColorChanged(m_backgroundColor);
connect(m_ui->cbFonts, QOverload<const QString &>::of(&QComboBox::activated),
this, &LtsTextEditor::slotTextFamily);
connect(m_ui->cbFonts, &QComboBox::currentTextChanged, this, &LtsTextEditor::slotTextFamily);
const QList<int> 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<const QString &>::of(&QComboBox::activated),
this, &LtsTextEditor::slotTextSize);
connect(m_ui->cbFontSize, &QComboBox::currentTextChanged, this, &LtsTextEditor::slotTextSize);
connect(m_ui->cbFontSize->lineEdit(), &QLineEdit::editingFinished,
this, &LtsTextEditor::slotTextSizeEditingFinished);
connect(m_ui->cbFontSize->lineEdit(), &QLineEdit::editingFinished, this,
&LtsTextEditor::slotTextSizeEditingFinished);
m_ui->textEdit->setFocus();
}
LtsTextEditor::~LtsTextEditor()
{
delete m_ui;
}
QTextEdit* LtsTextEditor::textEdit()
{
return m_ui->textEdit;
@@ -129,7 +100,6 @@ void LtsTextEditor::setInitialBackgroundColor(const QColor &bgColor)
slotBackgroundColorChanged(m_backgroundColor);
}
void LtsTextEditor::slotTextBold()
{
QTextCharFormat fmt;
@@ -142,13 +112,13 @@ void LtsTextEditor::slotTextBold()
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);
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;
@@ -161,13 +131,13 @@ void LtsTextEditor::slotTextUnderline()
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);
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;
@@ -180,13 +150,13 @@ void LtsTextEditor::slotTextItalic()
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);
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;
@@ -196,7 +166,8 @@ void LtsTextEditor::slotTextFamily(const QString &f)
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);
const qreal pointSize =
(m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11);
fmt.setFontPointSize(pointSize);
fmt.setForeground(m_foregroundColor);
}
@@ -205,7 +176,6 @@ void LtsTextEditor::slotTextFamily(const QString &f)
slotMergeFormatOnWordOrSelection(fmt);
}
void LtsTextEditor::slotTextSize(const QString& p)
{
qreal pointSize = p.toFloat();
@@ -226,7 +196,6 @@ void LtsTextEditor::slotTextSize(const QString &p)
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);
@@ -271,7 +240,8 @@ void LtsTextEditor::slotTextColor()
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);
const qreal pointSize =
(m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11);
fmt.setFontPointSize(pointSize);
}
fmt.setForeground(col);
@@ -290,14 +260,12 @@ void LtsTextEditor::slotBackgroundColor()
emit backgroundColorChanged(m_backgroundColor);
}
void LtsTextEditor::slotCurrentCharFormatChanged(const QTextCharFormat& format)
{
slotFontChanged(format.font());
slotTextColorChanged(format.foreground().color());
}
void LtsTextEditor::slotFontChanged(const QFont& f)
{
m_ui->cbFonts->setCurrentIndex(m_ui->cbFonts->findText(f.family()));
@@ -317,7 +285,6 @@ void LtsTextEditor::slotFontChanged(const QFont &f)
m_ui->pbUnderline->setChecked(f.underline());
}
void LtsTextEditor::slotMergeFormatOnWordOrSelection(const QTextCharFormat& format)
{
QTextCursor cursor = m_ui->textEdit->textCursor();
@@ -326,12 +293,10 @@ void LtsTextEditor::slotMergeFormatOnWordOrSelection(const QTextCharFormat &form
cursor.mergeCharFormat(format);
if (m_ui->textEdit->document()->isEmpty())
m_ui->textEdit->setTextCursor(cursor);
}
void LtsTextEditor::slotTextColorChanged(const QColor& c)
{
QPixmap pix(32, 32);
@@ -340,7 +305,6 @@ void LtsTextEditor::slotTextColorChanged(const QColor &c)
m_foregroundColor = c;
}
void LtsTextEditor::slotBackgroundColorChanged(const QColor& bgColor)
{
QPixmap pix(32, 32);
@@ -348,7 +312,6 @@ void LtsTextEditor::slotBackgroundColorChanged(const QColor &bgColor)
m_ui->pbBackgroundColor->setIcon(pix);
}
void LtsTextEditor::slotTextAlign()
{
QToolButton* b = qobject_cast<QToolButton*>(sender());
@@ -366,7 +329,6 @@ void LtsTextEditor::slotTextAlign()
m_ui->textEdit->setAlignment(Qt::AlignJustify);
}
void LtsTextEditor::slotAlignmentChanged()
{
auto a = m_ui->textEdit->alignment();
@@ -381,11 +343,10 @@ void LtsTextEditor::slotAlignmentChanged()
m_ui->pbAlignJustify->setChecked(true);
}
void LtsTextEditor::slotClipboardDataChanged()
{
if (const QMimeData* md = QApplication::clipboard()->mimeData())
m_ui->pbPaste->setEnabled(md->hasText());
}
}
} // namespace LtsWidgets
+105 -85
View File
@@ -1,33 +1,31 @@
#include "lts_text_editor2.h"
#include <QAction>
#include <QActionGroup>
#include <QApplication>
#include <QClipboard>
#include <QCloseEvent>
#include <QColorDialog>
#include <QComboBox>
#include <QFontComboBox>
#include <QFile>
#include <QFileDialog>
#include <QFileInfo>
#include <QFontComboBox>
#include <QFontDatabase>
#include <QMenu>
#include <QMenuBar>
#include <QTextCodec>
#include <QTextEdit>
#include <QStatusBar>
#include <QToolBar>
#include <QTextCursor>
#include <QTextDocumentWriter>
#include <QTextList>
#include <QtDebug>
#include <QCloseEvent>
#include <QMessageBox>
#include <QMimeData>
#include <QMimeDatabase>
#include <QStatusBar>
#include <QTextCursor>
#include <QTextDocumentWriter>
#include <QTextEdit>
#include <QTextList>
#include <QToolBar>
#include <QtDebug>
#if defined(QT_PRINTSUPPORT_LIB)
#include <QtPrintSupport/qtprintsupportglobal.h>
#if QT_CONFIG(printer)
@@ -41,27 +39,29 @@
#endif
#endif
#include <LtsUtilsSettings/settings.h>
#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());
m_textEdit = new QTextEdit(this);
connect(m_textEdit, &QTextEdit::currentCharFormatChanged,
this, &LtsTextEditor2::currentCharFormatChanged);
connect(m_textEdit, &QTextEdit::cursorPositionChanged,
this, &LtsTextEditor2::cursorPositionChanged);
connect(m_textEdit, &QTextEdit::currentCharFormatChanged, this, &LtsTextEditor2::currentCharFormatChanged);
connect(m_textEdit, &QTextEdit::cursorPositionChanged, this, &LtsTextEditor2::cursorPositionChanged);
setCentralWidget(m_textEdit);
setToolButtonStyle(Qt::ToolButtonFollowStyle);
@@ -82,14 +82,10 @@ LtsTextEditor2::LtsTextEditor2(QWidget *parent)
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());
@@ -126,19 +122,15 @@ LtsTextEditor2::LtsTextEditor2(QWidget *parent)
m_actionIndentMore->setVisible(false);
m_comboStyleAction->setVisible(false);
m_actionToggleCheckState->setVisible(false);
}
LtsTextEditor2::~LtsTextEditor2()
{
}
LtsTextEditor2::~LtsTextEditor2() {}
QTextEdit* LtsTextEditor2::textEdit()
{
return m_textEdit;
}
QColor LtsTextEditor2::backgroundColor() const
{
return m_backgroundColor;
@@ -150,19 +142,19 @@ void LtsTextEditor2::setInitialBackgroundColor(const QColor &bgColor)
m_backgroundColor = bgColor;
slotBackgroundColorChanged(m_backgroundColor);
}
void LtsTextEditor2::enableBackgroundColor(bool onOff)
{
m_actionBackgroundColor->setVisible(onOff);
}
void LtsTextEditor2::slotBackgroundColorChanged(const QColor& bgColor)
{
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);
@@ -174,26 +166,28 @@ void LtsTextEditor2::slotBackgroundColor()
emit backgroundColorChanged(m_backgroundColor);
}
void LtsTextEditor2::setupFileActions()
{
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")));
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")));
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();
const QIcon saveIcon = QIcon::fromTheme(QStringLiteral("document-save"), QIcon(rsrcPath()+ QStringLiteral("/filesave.png")));
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);
@@ -204,16 +198,19 @@ void LtsTextEditor2::setupFileActions()
menu->addSeparator();
#if defined(QT_PRINTSUPPORT_LIB) && QT_CONFIG(printer)
const QIcon printIcon = QIcon::fromTheme(QStringLiteral("document-print"), QIcon(rsrcPath()+ QStringLiteral("/fileprint.png")));
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")));
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")));
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);
@@ -324,24 +321,28 @@ void LtsTextEditor2::setupTextActions()
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")));
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")));
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);
if (QApplication::isLeftToRight()) {
if (QApplication::isLeftToRight())
{
alignGroup->addAction(m_actionAlignLeft);
alignGroup->addAction(m_actionAlignCenter);
alignGroup->addAction(m_actionAlignRight);
} else {
}
else
{
alignGroup->addAction(m_actionAlignRight);
alignGroup->addAction(m_actionAlignCenter);
alignGroup->addAction(m_actionAlignLeft);
@@ -372,18 +373,14 @@ void LtsTextEditor2::setupTextActions()
tb->addAction(m_actionBackgroundColor);
menu->addSeparator();
const QIcon checkboxIcon = QIcon::fromTheme(QStringLiteral("status-checkbox-checked"), QIcon(rsrcPath()+ QStringLiteral("/checkbox-checked.png")));
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"));
@@ -432,13 +429,16 @@ bool LtsTextEditor2::load(const QString &f)
return false;
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);
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 {
}
else
{
#if QT_CONFIG(textmarkdownreader)
QMimeDatabase db;
if (db.mimeTypeForFileNameAndData(f, data).name() == QStringLiteral("text/markdown"))
@@ -486,7 +486,8 @@ void LtsTextEditor2::setCurrentFileName(const QString &fileName)
void LtsTextEditor2::onFileNew()
{
if (maybeSave()) {
if (maybeSave())
{
m_textEdit->clear();
setCurrentFileName(QString());
}
@@ -527,12 +528,14 @@ bool LtsTextEditor2::onFileSave()
QTextDocumentWriter writer(m_fileName);
bool success = writer.write(m_textEdit->document());
if (success) {
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)));
}
else
{
statusBar()->showMessage(tr("Could not write to file \"%1\"").arg(QDir::toNativeSeparators(m_fileName)));
}
return success;
}
@@ -597,7 +600,6 @@ void LtsTextEditor2::printPreview(QPrinter *printer)
#endif
}
void LtsTextEditor2::onFilePrintPdf()
{
#if defined(QT_PRINTSUPPORT_LIB) && QT_CONFIG(printer)
@@ -616,8 +618,7 @@ void LtsTextEditor2::onFilePrintPdf()
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName(fileName);
textEdit->document()->print(&printer);
statusBar()->showMessage(tr("Exported \"%1\"")
.arg(QDir::toNativeSeparators(fileName)));
statusBar()->showMessage(tr("Exported \"%1\"").arg(QDir::toNativeSeparators(fileName)));
#endif
}
@@ -653,7 +654,8 @@ void LtsTextEditor2::onTextFamily(const QString &f)
void LtsTextEditor2::onTextSize(const QString& p)
{
qreal pointSize = p.toFloat();
if (p.toFloat() > 0) {
if (p.toFloat() > 0)
{
QTextCharFormat fmt;
fmt.setFontPointSize(pointSize);
mergeFormatOnWordOrSelection(fmt);
@@ -666,7 +668,8 @@ void LtsTextEditor2::onTextStyle(int styleIndex)
QTextListFormat::Style style = QTextListFormat::ListStyleUndefined;
QTextBlockFormat::MarkerType marker = QTextBlockFormat::MarkerType::NoMarker;
switch (styleIndex) {
switch (styleIndex)
{
case 1:
style = QTextListFormat::ListDisc;
break;
@@ -713,7 +716,8 @@ void LtsTextEditor2::onTextStyle(int styleIndex)
QTextBlockFormat blockFmt = cursor.blockFormat();
if (style == QTextListFormat::ListStyleUndefined) {
if (style == QTextListFormat::ListStyleUndefined)
{
blockFmt.setObjectIndex(-1);
int headingLevel = styleIndex >= 11 ? styleIndex - 11 + 1 : 0;
blockFmt.setHeadingLevel(headingLevel);
@@ -726,13 +730,18 @@ void LtsTextEditor2::onTextStyle(int styleIndex)
cursor.select(QTextCursor::LineUnderCursor);
cursor.mergeCharFormat(fmt);
m_textEdit->mergeCurrentCharFormat(fmt);
} else {
}
else
{
blockFmt.setMarker(marker);
cursor.setBlockFormat(blockFmt);
QTextListFormat listFmt;
if (cursor.currentList()) {
if (cursor.currentList())
{
listFmt = cursor.currentList()->format();
} else {
}
else
{
listFmt.setIndent(blockFmt.indent() + 1);
blockFmt.setIndent(0);
cursor.setBlockFormat(blockFmt);
@@ -786,19 +795,24 @@ void LtsTextEditor2::modifyIndentation(int amount)
{
QTextCursor cursor = m_textEdit->textCursor();
cursor.beginEditBlock();
if (cursor.currentList()) {
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()) {
if (above.currentList() && listFmt.indent() + amount == above.currentList()->format().indent())
{
above.currentList()->add(cursor.block());
} else {
}
else
{
listFmt.setIndent(listFmt.indent() + amount);
cursor.createList(listFmt);
}
} else {
}
else
{
QTextBlockFormat blockFmt = cursor.blockFormat();
blockFmt.setIndent(blockFmt.indent() + amount);
cursor.setBlockFormat(blockFmt);
@@ -816,8 +830,10 @@ void LtsTextEditor2::cursorPositionChanged()
{
alignmentChanged(m_textEdit->alignment());
QTextList* list = m_textEdit->textCursor().currentList();
if (list) {
switch (list->format().style()) {
if (list)
{
switch (list->format().style())
{
case QTextListFormat::ListDisc:
m_comboStyle->setCurrentIndex(1);
break;
@@ -846,7 +862,8 @@ void LtsTextEditor2::cursorPositionChanged()
m_comboStyle->setCurrentIndex(-1);
break;
}
switch (m_textEdit->textCursor().block().blockFormat().marker()) {
switch (m_textEdit->textCursor().block().blockFormat().marker())
{
case QTextBlockFormat::MarkerType::NoMarker:
m_actionToggleCheckState->setChecked(false);
break;
@@ -859,7 +876,9 @@ void LtsTextEditor2::cursorPositionChanged()
m_actionToggleCheckState->setChecked(true);
break;
}
} else {
}
else
{
int headingLevel = m_textEdit->textCursor().blockFormat().headingLevel();
m_comboStyle->setCurrentIndex(headingLevel ? headingLevel + 10 : 0);
}
@@ -875,7 +894,8 @@ void LtsTextEditor2::clipboardDataChanged()
void LtsTextEditor2::about()
{
QMessageBox::about(this, tr("About"), tr("This example demonstrates Qt's "
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."));
}
@@ -917,4 +937,4 @@ void LtsTextEditor2::alignmentChanged(Qt::Alignment a)
m_actionAlignJustify->setChecked(true);
}
}
} // namespace LtsWidgets
+3 -7
View File
@@ -1,22 +1,18 @@
#include "lts_tool_bar.h"
using namespace LtsWidgets;
LtsToolBar::LtsToolBar(QWidget *parent)
: QToolBar(parent)
LtsToolBar::LtsToolBar(QWidget* parent) : QToolBar(parent)
{
setMaximumHeight(1);
setMinimumHeight(1);
}
LtsToolBar::~LtsToolBar()
{
}
LtsToolBar::~LtsToolBar() {}
void LtsToolBar::enterEvent(QEvent *e)
void LtsToolBar::enterEvent(QEnterEvent* e)
{
setMaximumHeight(50);
setMinimumHeight(50);
+5 -8
View File
@@ -1,12 +1,11 @@
#pragma once
#include <QObject>
#include <QToolBar>
#include "ltswidgets_export.h"
#include <QObject>
#include <QToolBar>
namespace LtsWidgets
{
@@ -19,10 +18,8 @@ public:
~LtsToolBar();
protected:
void enterEvent(QEvent *e) override;
void enterEvent(QEnterEvent* e) override;
void leaveEvent(QEvent* e) override;
};
}
} // namespace LtsWidgets
+20 -60
View File
@@ -1,26 +1,24 @@
#include "lts_tool_bar_area.h"
#include <utility>
#include "ui_lts_tool_bar_area.h"
#include "lts_drag_icon.h"
#include "ui_lts_tool_bar_area.h"
#include <LtsUtilsSettings/settings.h>
#include <QDebug>
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QLabel>
#include <QDebug>
#include <QMenu>
#include <QShortcut>
#include <QPointer>
#include <QShortcut>
#include <QVariant>
#include <utility>
namespace LtsWidgets
{
void ShortCut::clear()
{
name.clear();
@@ -29,20 +27,13 @@ void ShortCut::clear()
shortcut->disconnect(icon);
}
LtsToolBarArea::LtsToolBarArea(QWidget *parent)
: QWidget(parent)
, m_dummyLabel(nullptr)
, m_ui(new Ui::LtsToolBarArea)
LtsToolBarArea::LtsToolBarArea(QWidget* parent) : QWidget(parent), m_dummyLabel(nullptr), m_ui(new Ui::LtsToolBarArea)
{
m_ui->setupUi(this);
setAcceptDrops(true);
clearToolBarArea();
for (int i = Qt::Key_F5; i <= Qt::Key_F12; ++i)
{
ShortCut sc(this);
@@ -87,19 +78,16 @@ void LtsToolBarArea::addMenuEntry(LtsDragIcon *entry, LtsDragIcon *after)
}
}
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;
}
}
LtsDragIcon* newAction = entry;
if (!isInternalMove)
@@ -115,20 +103,20 @@ void LtsToolBarArea::addMenuEntry(LtsDragIcon *entry, LtsDragIcon *after)
newAction->setIdentifier(entry->identifier());
connect(newAction, &LtsDragIcon::clicked, entry, &LtsDragIcon::clicked);
connect(entry, &LtsDragIcon::destroyed, newAction,
[this, newAction]() { m_buttonMap.removeAll(newAction); newAction->deleteLater(); });
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::customContextMenuRequested, this, &LtsToolBarArea::showContextMenu);
m_foreignButtonMap.insert(index, foreignDragIcon);
m_buttonMap.insert(index, newAction);
connect(foreignDragIcon, &LtsDragIcon::enabledChanged, newAction, &LtsDragIcon::setEnabled);
m_ui->layToolbar->insertWidget(index + 1, newAction);
saveSettings();
}
@@ -165,13 +153,9 @@ QStringList LtsToolBarArea::menuEntries() const
return ret;
}
void LtsToolBarArea::dragEnterEvent(QDragEnterEvent* event)
{
LtsDragIcon *source =
qobject_cast<LtsDragIcon *>(event->source());
LtsDragIcon* source = qobject_cast<LtsDragIcon*>(event->source());
if (source)
{
if (!m_foreignButtonMap.contains(source))
@@ -207,8 +191,9 @@ QMenu *LtsToolBarArea::functionKeyMenu(QWidget *parent)
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]);
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();
@@ -231,13 +216,11 @@ void LtsToolBarArea::functionKeyMenuTriggered()
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();
@@ -258,7 +241,6 @@ bool LtsToolBarArea::setFunctionKey(int fkey, const QString &action)
if (fkey < Qt::Key_F5 || fkey > Qt::Key_F12)
return false;
LtsDragIcon* icon = nullptr;
for (LtsDragIcon* ic : std::as_const(m_buttonMap))
{
@@ -272,15 +254,12 @@ bool LtsToolBarArea::setFunctionKey(int fkey, const QString &action)
if (!icon)
return false;
ShortCut& shorty = m_functionKeys[fkey];
for (LtsDragIcon* ic : std::as_const(m_buttonMap))
if (ic->identifier() == shorty.identifier)
ic->removeModification();
for (auto val = m_functionKeys.begin(); val != m_functionKeys.end(); ++val)
{
ShortCut& itShortcut = val.value();
@@ -291,7 +270,6 @@ bool LtsToolBarArea::setFunctionKey(int fkey, const QString &action)
}
}
shorty.clear();
shorty.identifier = icon->identifier();
shorty.name = icon->text();
@@ -348,13 +326,8 @@ void LtsToolBarArea::showContextMenu(const QPoint &pos)
QMenu* contextMenu = new QMenu(this);
contextMenu->setAttribute(Qt::WA_DeleteOnClose);
m_currentIdentifierForContextMenue = icon->identifier();
connect(contextMenu, &QObject::destroyed, this, [this](){
m_currentIdentifierForContextMenue.clear();
});
connect(contextMenu, &QObject::destroyed, this, [this]() { m_currentIdentifierForContextMenue.clear(); });
QAction* delAction = contextMenu->addAction(tr("Remove"));
connect(delAction, &QAction::triggered, this, [this, icon]() {
@@ -362,24 +335,11 @@ void LtsToolBarArea::showContextMenu(const QPoint &pos)
removeMenuAction(icon);
});
QMenu* fkeyMenu = functionKeyMenu(contextMenu);
contextMenu->addMenu(fkeyMenu);
contextMenu->popup(globalPos);
}
void LtsToolBarArea::saveSettings()
{
}
}
void LtsToolBarArea::saveSettings() {}
} // namespace LtsWidgets
@@ -13,8 +13,10 @@ ADD_SUBDIRECTORY(Battery)
ADD_SUBDIRECTORY(Buildings)
ADD_SUBDIRECTORY(BuildingViewer) # uses ZW connections (uses sql, ace, ..)
ADD_SUBDIRECTORY(CentralEffectSimulation)
IF(BUILD_CODIFICATION)
ADD_SUBDIRECTORY(CodificationManagement)
ADD_SUBDIRECTORY(CodificationManagement/Test)
ENDIF()
ADD_SUBDIRECTORY(CollateralDamageSimulation)
ADD_SUBDIRECTORY(EffectManagement)
ADD_SUBDIRECTORY(EffectShowClient)
@@ -22,7 +24,9 @@ ADD_SUBDIRECTORY(EffectShowManagement)
ADD_SUBDIRECTORY(Evaluations)
ADD_SUBDIRECTORY(ExerciseManagement)
ADD_SUBDIRECTORY(FileManagement)
IF(BUILD_FILTERMANAGEMENT)
ADD_SUBDIRECTORY(FilterManagement)
ENDIF()
ADD_SUBDIRECTORY(FreeSpace)
ADD_SUBDIRECTORY(GuezIedManagement)
ADD_SUBDIRECTORY(GuezNasat)
@@ -5,7 +5,12 @@
# Created by Hannes Fritsche, ESZS, 2024-08-05
#
FIND_PACKAGE(KDReports REQUIRED)
FIND_PACKAGE(KDReports)
IF(NOT KDReports_FOUND)
MESSAGE(STATUS "KDReports not found; skipping CdsSimulationGuiPlugin")
RETURN()
ENDIF()
SET(cds_gui_SRCS
cds_building_model.cpp
@@ -37,11 +37,18 @@ ADD_INTERFACE_LIBRARY(
#
# need top be shared due to signals/slots
NGL_ADD_LIBRARY2(WS IsmDataPluginInterface SHARED ism_data_plugin_interface.h)
IF(BUILD_RTI)
NGL_TARGET_LINK_LIBRARIES(IsmDataPluginInterface
Qt6::Core
svcIsmCommon
DataPluginInterface
)
ELSE()
NGL_TARGET_LINK_LIBRARIES(IsmDataPluginInterface
Qt6::Core
DataPluginInterface
)
ENDIF(BUILD_RTI)
NGL_INSTALL_TARGET(IsmDataPluginInterface)
#
@@ -7,8 +7,8 @@
FIND_PACKAGE(KDReports)
FIND_PACKAGE(KDChart)
IF (NOT KDReports_FOUND OR NOT KDChart_FOUND)
MESSAGE(WARNING "KDReports or KDChart not found; skipping ReportViewer")
IF ((NOT KDReports_FOUND OR NOT KDChart_FOUND) OR NOT BUILD_CODIFICATION)
MESSAGE(WARNING "KDReports, KDChart not found or BUILD_CODIFICATION disabled; skipping ReportViewer")
RETURN()
ENDIF()
+115 -99
View File
@@ -1,21 +1,17 @@
#pragma once
#include "sv_export.h"
#include <QByteArray>
#include <WirelessLocationSystem/sfmconverter_export.h>
namespace WirelessLocationSystem
{
class SfmMessage
{
public:
enum class MsgId
{
enum class MsgId {
TacticalState = 37,
SfmRestartNotification = 76,
GpsControl = 79,
@@ -28,74 +24,61 @@ public:
};
protected:
explicit SfmMessage(MsgId id)
: m_id(id)
{}
explicit SfmMessage(MsgId id) : m_id(id) {}
public:
virtual ~SfmMessage() = default;
MsgId getId() const { return m_id; }
MsgId getId() const
{
return m_id;
}
private:
MsgId m_id;
};
class SfmMessage_tx : public SfmMessage
{
public:
using SfmMessage::SfmMessage;
virtual QByteArray getPayload() const = 0;
};
class SfmMessage_rx : public SfmMessage
{
public:
using SfmMessage::SfmMessage;
virtual bool setPayload(const QByteArray& payload) = 0;
};
class SfmMsgGpsControl_tx final : public SfmMessage_tx
{
public:
explicit SfmMsgGpsControl_tx(bool gpsOn = false)
: SfmMessage_tx(SfmMessage::MsgId::GpsControl)
, m_gpsOn(gpsOn)
{}
explicit SfmMsgGpsControl_tx(bool gpsOn = false) : SfmMessage_tx(SfmMessage::MsgId::GpsControl), m_gpsOn(gpsOn) {}
QByteArray getPayload() const override;
void setGpsOn(bool bOn) { m_gpsOn = bOn; }
bool isGpsOn() const { return m_gpsOn; }
void setGpsOn(bool bOn)
{
m_gpsOn = bOn;
}
bool isGpsOn() const
{
return m_gpsOn;
}
private:
bool m_gpsOn;
};
class SfmMsgRequestGpsControl_rx final : public SfmMessage_rx
{
public:
SfmMsgRequestGpsControl_rx()
: SfmMessage_rx(SfmMessage::MsgId::RequestGpsControl)
{}
SfmMsgRequestGpsControl_rx() : SfmMessage_rx(SfmMessage::MsgId::RequestGpsControl) {}
bool setPayload(const QByteArray& payload) override
{
@@ -103,16 +86,10 @@ public:
}
};
class SfmMsgRequestEquipmentId_tx final : public SfmMessage_tx
{
public:
SfmMsgRequestEquipmentId_tx()
: SfmMessage_tx(SfmMessage::MsgId::RequestEquipmentId)
{}
SfmMsgRequestEquipmentId_tx() : SfmMessage_tx(SfmMessage::MsgId::RequestEquipmentId) {}
QByteArray getPayload() const override
{
@@ -120,16 +97,12 @@ public:
}
};
class SFMCONVERTER_EXPORT SfmMsgEquipmentId final : public SfmMessage_rx, public SfmMessage_tx
{
public:
SfmMsgEquipmentId()
: SfmMessage_rx(SfmMessage::MsgId::EquipmentId)
, SfmMessage_tx(SfmMessage::MsgId::EquipmentId)
{}
SfmMsgEquipmentId() : SfmMessage_rx(SfmMessage::MsgId::EquipmentId), SfmMessage_tx(SfmMessage::MsgId::EquipmentId)
{
}
bool setPayload(const QByteArray&) override;
QByteArray getPayload() const override;
@@ -140,65 +113,76 @@ public:
{
return m_equipmentNumber;
}
void setEquipmentNumber(quint16 equipmentNumber) { m_equipmentNumber = equipmentNumber; }
void setEquipmentNumber(quint16 equipmentNumber)
{
m_equipmentNumber = equipmentNumber;
}
private:
unsigned short m_equipmentNumber = 0;
};
class SfmMsgSfmRestart_rx final : public SfmMessage_rx
{
public:
SfmMsgSfmRestart_rx()
: SfmMessage_rx(SfmMessage::MsgId::SfmRestartNotification)
{}
SfmMsgSfmRestart_rx() : SfmMessage_rx(SfmMessage::MsgId::SfmRestartNotification) {}
bool setPayload(const QByteArray& payload) override
{
return (payload.size() == 0);
}
};
class SfmMsgTacticalState_rx final : public SfmMessage_rx
{
public:
SfmMsgTacticalState_rx()
: SfmMessage_rx(SfmMessage::MsgId::TacticalState)
{}
SfmMsgTacticalState_rx() : SfmMessage_rx(SfmMessage::MsgId::TacticalState) {}
static constexpr int s_payloadSize = 1;
bool setPayload(const QByteArray&) override;
unsigned char getTacticalState() const { return m_tacticalState; }
unsigned char getTacticalState() const
{
return m_tacticalState;
}
private:
unsigned char m_tacticalState = 0;
};
class SfmMsgTetra_rx final : public SfmMessage_rx
{
public:
SfmMsgTetra_rx()
: SfmMessage_rx(SfmMessage::MsgId::TetraMessage)
{}
SfmMsgTetra_rx() : SfmMessage_rx(SfmMessage::MsgId::TetraMessage) {}
bool setPayload(const QByteArray& p_data) override;
uint8_t sendCounter() const { return m_sendCounter; }
bool isFragmented() const { return fragmentCount() > 1; }
uint8_t fragmentNumber() const { return m_fragmentByte & 0x0f; }
uint8_t fragmentCount() const { return (m_fragmentByte & 0xf0) >> 4;}
uint8_t sendCounter() const
{
return m_sendCounter;
}
const QByteArray &payload() const { return m_payload; }
bool isFragmented() const
{
return fragmentCount() > 1;
}
uint8_t fragmentNumber() const
{
return m_fragmentByte & 0x0f;
}
uint8_t fragmentCount() const
{
return (m_fragmentByte & 0xf0) >> 4;
}
const QByteArray& payload() const
{
return m_payload;
}
private:
QByteArray m_payload;
@@ -224,27 +208,50 @@ public:
Q_ASSERT(fragmentNumber >= 0 && fragmentNumber <= fragmentCount);
return ((fragmentCount & 0x0f) << 4) | (fragmentNumber & 0x0f);
}
QByteArray getPayload() const override { return m_data; }
QByteArray getPayload() const override
{
return m_data;
}
private:
QByteArray m_data;
};
class Acknowledge_rx final : public SfmMessage_rx
{
public:
Acknowledge_rx()
: SfmMessage_rx(SfmMessage::MsgId::Acknowledge)
{}
Acknowledge_rx() : SfmMessage_rx(SfmMessage::MsgId::Acknowledge) {}
static constexpr int s_payloadSize = 2;
bool setPayload(const QByteArray& p_data) override;
uint8_t recvCounter() const { return m_recvCounter; }
bool isOk() const { return m_ackState == 0; }
bool isCrcError() const { return (m_ackState & 0x20) == 0x20; }
bool isFragmentError() const { return (m_ackState & 0x10) == 0x10; }
uint8_t missingFragment() const { return (m_ackState & 0x0f)!= 0; }
uint8_t recvCounter() const
{
return m_recvCounter;
}
bool isOk() const
{
return m_ackState == 0;
}
bool isCrcError() const
{
return (m_ackState & 0x20) == 0x20;
}
bool isFragmentError() const
{
return (m_ackState & 0x10) == 0x10;
}
uint8_t missingFragment() const
{
return (m_ackState & 0x0f) != 0;
}
private:
uint8_t m_recvCounter = 0;
uint8_t m_ackState = 0;
@@ -253,37 +260,46 @@ private:
class Acknowledge_tx final : public SfmMessage_tx
{
public:
explicit Acknowledge_tx()
: SfmMessage_tx(SfmMessage::MsgId::Acknowledge)
{}
explicit Acknowledge_tx() : SfmMessage_tx(SfmMessage::MsgId::Acknowledge) {}
QByteArray getPayload() const override;
void setRecvCounter(uint8_t recvCounter) { m_recvCounter = recvCounter; }
void setCrcError() { m_ackState |= 0x20; }
void setFragmentError(uint8_t missingFrag) { m_ackState |= (0x10 | (0x0f & missingFrag)); }
void setRecvCounter(uint8_t recvCounter)
{
m_recvCounter = recvCounter;
}
void setCrcError()
{
m_ackState |= 0x20;
}
void setFragmentError(uint8_t missingFrag)
{
m_ackState |= (0x10 | (0x0f & missingFrag));
}
private:
uint8_t m_recvCounter = 0;
uint8_t m_ackState = 0;
};
class SfmMsgLicenseState_rx final : public SfmMessage_rx
{
public:
SfmMsgLicenseState_rx()
: SfmMessage_rx(SfmMessage::MsgId::LicenseState)
{}
SfmMsgLicenseState_rx() : SfmMessage_rx(SfmMessage::MsgId::LicenseState) {}
static constexpr int s_payloadSize = 1;
bool setPayload(const QByteArray& p_data) override;
bool isLicensed() const { return m_isLicensed; }
bool isLicensed() const
{
return m_isLicensed;
}
private:
bool m_isLicensed = false;
};
}
} // namespace WirelessLocationSystem
@@ -18,7 +18,9 @@ ADD_SUBDIRECTORY(Evaluations)
ADD_SUBDIRECTORY(ExerciseManagement)
ADD_SUBDIRECTORY(ExerciseEventManagement)
ADD_SUBDIRECTORY(FileManagement)
IF(BUILD_FILTERMANAGEMENT)
ADD_SUBDIRECTORY(FilterManagement)
ENDIF()
ADD_SUBDIRECTORY(GuezIedManagement)
ADD_SUBDIRECTORY(GuezMinelayerProcessing)
IF(BUILD_RTI)
File diff suppressed because it is too large. Load diff
@@ -595,6 +595,10 @@ protected:
static void setDestISSI_Internal(QByteArray &data, const uint32_t issi);
private:
/**
* The logger object
*/
NGL::INGLLogger &m_logger;
};
}
File diff suppressed because it is too large. Load diff
@@ -19,7 +19,7 @@ SET(NGLLogger_HDRS
ADD_DEFINITIONS(-DBUILDING_NGLLOGGER)
NGL_ADD_LIBRARY2(ALL NGLLogger SHARED ${NGLLogger_SRCS} ${NGLLogger_HDRS})
NGL_TARGET_INCLUDE_DIRECTORIES(NGLLogger
INTERFACE
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/../
${CMAKE_CURRENT_BINARY_DIR}
+63 -78
View File
@@ -7,22 +7,21 @@
#pragma once
#include <string>
#include <sstream>
#include <QString>
#include <QList>
#include <QPointF>
#include <QSize>
#include <QRect>
#include <QRectF>
#include <QList>
#include "ngllogger_export.h"
#include <QSize>
#include <QString>
#include <ngllogger_export.h>
#include <sstream>
#include <string>
namespace NGL
{
class INGLLogger;
// keep in sync with log4qt/level.h
enum class LogLevel
{
enum class LogLevel {
Undefined = 0,
Trace = 64,
Debug = 96,
@@ -35,17 +34,15 @@ enum class LogLevel
class LogStreamHelper
{
public:
inline LogStreamHelper(INGLLogger &logger, LogLevel level, const char *const file, int line, const char *const function)
: m_logger(logger)
, m_level(level)
, m_line(line)
, m_file(file)
, m_func(function)
{}
inline LogStreamHelper(INGLLogger& logger, LogLevel level, const char* const file, int line,
const char* const function)
: m_logger(logger), m_level(level), m_line(line), m_file(file), m_func(function)
{
}
inline ~LogStreamHelper(); // after INGLLogger class definition
template<typename T>
inline LogStreamHelper &operator<<(const T &val);
template <typename T> inline LogStreamHelper& operator<<(const T& val);
private:
std::ostringstream m_buffer;
@@ -79,7 +76,6 @@ public:
virtual INGLLogger& getNGLLogger(const char* fullqualifiedname) = 0;
virtual INGLLogger& getNGLLogger(const std::string& fullqualifiedname) = 0;
// True if this level is enabled.
virtual bool isTraceEnabled() const = 0;
virtual bool isDebugEnabled() const = 0;
@@ -91,20 +87,27 @@ public:
// Submit a LOG message.
// Use __FILE__ and __NAME__ macros.
virtual void log(LogLevel level, const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0;
virtual void log(LogLevel level, const INGLLogger::String& message, const char* file = nullptr, int line = -1,
const char* function = nullptr) = 0;
// Submit an TRACE message.
virtual void logTrace(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0;
virtual void logTrace(const INGLLogger::String& message, const char* file = nullptr, int line = -1,
const char* function = nullptr) = 0;
// Submit an DEBUG message.
virtual void logDebug(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0;
virtual void logDebug(const INGLLogger::String& message, const char* file = nullptr, int line = -1,
const char* function = nullptr) = 0;
// Submit an INFO message.
virtual void logInfo(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0;
virtual void logInfo(const INGLLogger::String& message, const char* file = nullptr, int line = -1,
const char* function = nullptr) = 0;
// Submit a WARNING message.
virtual void logWarning(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0;
virtual void logWarning(const INGLLogger::String& message, const char* file = nullptr, int line = -1,
const char* function = nullptr) = 0;
// Submit an ERROR message.
virtual void logError(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0;
virtual void logError(const INGLLogger::String& message, const char* file = nullptr, int line = -1,
const char* function = nullptr) = 0;
// Submit a FATAL message.
virtual void logFatal(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0;
virtual void logFatal(const INGLLogger::String& message, const char* file = nullptr, int line = -1,
const char* function = nullptr) = 0;
// Writes a startup message into the logfile
virtual void logStartup(const char* file, int line, const char* function = nullptr) = 0;
@@ -126,8 +129,7 @@ inline LogStreamHelper::~LogStreamHelper()
m_logger.log(m_level, m_buffer.str(), m_file, m_line, m_func);
}
template<typename T>
inline LogStreamHelper &LogStreamHelper::operator<<(const T &val)
template <typename T> inline LogStreamHelper& LogStreamHelper::operator<<(const T& val)
{
m_buffer << val;
if (!m_logger.noSpace())
@@ -135,7 +137,6 @@ inline LogStreamHelper &LogStreamHelper::operator<<(const T &val)
return *this;
}
} // namespace NGL
inline std::ostream& operator<<(std::ostream& stream, const QByteArray& str)
@@ -147,67 +148,50 @@ inline std::ostream &operator<<(std::ostream &stream, const QByteArray &str)
//
// operator to ease logging (at least via NglLogging)
//
inline std::ostream &operator<<(std::ostream &stream,
const QPointF &value)
inline std::ostream& operator<<(std::ostream& stream, const QPointF& value)
{
stream << "QPointF(" << QString::number(value.x(), 'f', 6).toStdString() << "#" << QString::number(value.y(), 'f', 6).toStdString() << ")";
stream << "QPointF(" << QString::number(value.x(), 'f', 6).toStdString() << "#"
<< QString::number(value.y(), 'f', 6).toStdString() << ")";
return stream;
}
//----------------------------------------------------------------------------
inline std::ostream &operator<< (std::ostream &stream,
const QPoint &value)
inline std::ostream& operator<<(std::ostream& stream, const QPoint& value)
{
stream << "QPoint(" << value.x() << "#" << value.y() << ")";
return stream;
}
inline std::ostream &operator<< (std::ostream &stream,
const QSize &value)
inline std::ostream& operator<<(std::ostream& stream, const QSize& value)
{
stream << "QSize(w=" << value.width() << ";h=" << value.height() << ")";
return stream;
}
inline std::ostream &operator<< (std::ostream &stream,
const QSizeF &value)
inline std::ostream& operator<<(std::ostream& stream, const QSizeF& value)
{
stream << "QSize(w="
<< QString::number(value.width(), 'f', 6).toStdString() << ";h="
<< QString::number(value.height(), 'f', 6).toStdString()
<< ")";
stream << "QSize(w=" << QString::number(value.width(), 'f', 6).toStdString()
<< ";h=" << QString::number(value.height(), 'f', 6).toStdString() << ")";
return stream;
}
inline std::ostream &operator<< (std::ostream &stream,
const QRect &value)
inline std::ostream& operator<<(std::ostream& stream, const QRect& value)
{
stream << "QRect(center=" << value.center()
<< " w=" << value.width()
<< ";h=" << value.height()
<< " bottomLeft=" << value.bottomLeft()
<< " topRight=" << value.topRight()
<< ")";
stream << "QRect(center=" << value.center() << " w=" << value.width() << ";h=" << value.height()
<< " bottomLeft=" << value.bottomLeft() << " topRight=" << value.topRight() << ")";
return stream;
}
inline std::ostream &operator<< (std::ostream &stream,
const QRectF &value)
inline std::ostream& operator<<(std::ostream& stream, const QRectF& value)
{
stream << "QRectF(center=" << value.center()
<< " w=" << QString::number(value.width(), 'f', 3).toStdString()
<< ";h=" << QString::number(value.height(), 'f', 3).toStdString()
<< " bottomLeft=" << value.bottomLeft()
<< " topRight=" << value.topRight()
<< ")";
stream << "QRectF(center=" << value.center() << " w=" << QString::number(value.width(), 'f', 3).toStdString()
<< ";h=" << QString::number(value.height(), 'f', 3).toStdString() << " bottomLeft=" << value.bottomLeft()
<< " topRight=" << value.topRight() << ")";
return stream;
}
inline std::ostream &operator<< (std::ostream &stream,
const QList<int> &value)
inline std::ostream& operator<<(std::ostream& stream, const QList<int>& value)
{
stream << "QList<int>(" << value.size() << "): ";
for (int i : value)
@@ -215,9 +199,7 @@ inline std::ostream &operator<< (std::ostream &stream,
return stream;
}
inline std::ostream &operator<< (std::ostream &stream,
const QList<QPointF> &value)
inline std::ostream& operator<<(std::ostream& stream, const QList<QPointF>& value)
{
stream << "QList<QPointF>(" << value.size() << "): ";
for (const QPointF& item : value)
@@ -225,7 +207,6 @@ inline std::ostream &operator<< (std::ostream &stream,
return stream;
}
inline std::ostream& operator<<(std::ostream& stream, const QString& str)
{
return stream << str.toUtf8();
@@ -236,13 +217,10 @@ namespace NGL
namespace NGLLoggerHelper
{
NGLLOGGER_EXPORT void hexDumpHelper(NGL::INGLLogger &logger,
NGL::LogLevel level,
const void *a_data,
NGLLOGGER_EXPORT void hexDumpHelper(NGL::INGLLogger& logger, NGL::LogLevel level, const void* a_data,
const unsigned int a_size);
inline void hexDumpHelper(NGL::INGLLogger &logger,
NGL::LogLevel level,
const QByteArray &data)
inline void hexDumpHelper(NGL::INGLLogger& logger, NGL::LogLevel level, const QByteArray& data)
{
return hexDumpHelper(logger, level, data.data(), data.size());
}
@@ -260,8 +238,7 @@ NGLLOGGER_EXPORT std::string getMemoryData();
#define LOGFUNCTION Q_FUNC_INFO
// log this output every time, no matter what log level is enabled
#define NOTICE_LOG(logger) \
NGL::LogStreamHelper(logger, NGL::LogLevel::Info, __FILE__,__LINE__, Q_FUNC_INFO)
#define NOTICE_LOG(logger) NGL::LogStreamHelper(logger, NGL::LogLevel::Info, __FILE__, __LINE__, Q_FUNC_INFO)
#ifdef LTS_DEBUG
#define TRACE_LOG(logger) \
@@ -293,8 +270,14 @@ NGLLOGGER_EXPORT std::string getMemoryData();
for (bool log_level_enabled = (logger).isFatalEnabled(); log_level_enabled; log_level_enabled = false) \
NGL::LogStreamHelper(logger, NGL::LogLevel::Fatal, __FILE__, __LINE__, Q_FUNC_INFO)
#define STARTUP_LOG(logger) { (logger).logStartup(__FILE__, __LINE__, Q_FUNC_INFO); }
#define SHUTDOWN_LOG(logger) { (logger).logShutdown(__FILE__, __LINE__, Q_FUNC_INFO); }
#define STARTUP_LOG(logger) \
{ \
(logger).logStartup(__FILE__, __LINE__, Q_FUNC_INFO); \
}
#define SHUTDOWN_LOG(logger) \
{ \
(logger).logShutdown(__FILE__, __LINE__, Q_FUNC_INFO); \
}
//==============================================================================
@@ -304,7 +287,9 @@ NGLLOGGER_EXPORT std::string getMemoryData();
// MEMORY_LOG() << " after something nasty";
#define MEMORY_LOG() \
for (bool log_level_enabled = (NGL::getMemoryLogger()).isInfoEnabled(); log_level_enabled; log_level_enabled = false) \
NGL::LogStreamHelper(NGL::getMemoryLogger(), NGL::LogLevel::Info, __FILE__,__LINE__, Q_FUNC_INFO) << NGL::getMemoryData()
for (bool log_level_enabled = (NGL::getMemoryLogger()).isInfoEnabled(); log_level_enabled; \
log_level_enabled = false) \
NGL::LogStreamHelper(NGL::getMemoryLogger(), NGL::LogLevel::Info, __FILE__, __LINE__, Q_FUNC_INFO) \
<< NGL::getMemoryData()
//==============================================================================
+6 -20
View File
@@ -1,11 +1,10 @@
#ifndef NGLLOGGERBOOTSTRAP_H
#define NGLLOGGERBOOTSTRAP_H
#include <NGLLogger/INGLLogger.h>
#include "ngllogger_export.h"
#include <ngllogger_export.h>
namespace NGL
{
@@ -28,32 +27,19 @@ class NotCreatedError final : public std::exception
}
};
NGLLOGGER_EXPORT INGLLogger& getNGLRootLogger();
NGLLOGGER_EXPORT INGLLogger& createNGLRootLogger(const QString& configfilename, bool ignorealreadycreated,
const QString& logOutputName = QString(), bool quiet = false);
NGLLOGGER_EXPORT INGLLogger &createNGLRootLogger(const QString &configfilename,
bool ignorealreadycreated,
const QString &logOutputName = QString(),
bool quiet = false);
inline INGLLogger &createNGLRootLogger(const char *configfilename,
bool ignorealreadycreated,
inline INGLLogger& createNGLRootLogger(const char* configfilename, bool ignorealreadycreated,
const QString& logOutputName = QString())
{
return createNGLRootLogger(QString::fromUtf8(configfilename), ignorealreadycreated, logOutputName);
}
}
}
} // namespace NGLLoggerBootstrap
} // namespace NGL
#endif
+9 -28
View File
@@ -1,29 +1,17 @@
#include "nglcomp_bzip2iodevice.h"
#include <QIODevice>
#include <QString>
#include <bzlib.h>
class BZip2IODevice::Private
{
public:
Private(BZip2IODevice* parent_, QIODevice* dev, int bs)
: parent(parent_)
, device(dev)
, iCurPos(0)
, iMaxBufSize(1024 * 1024)
, blocksize(bs)
, initialized(false)
, decomressStreamEnd(false)
: parent(parent_), device(dev), iCurPos(0), iMaxBufSize(1024 * 1024), blocksize(bs), initialized(false),
decomressStreamEnd(false)
{
buffer.resize(iMaxBufSize);
}
@@ -87,7 +75,8 @@ qint64 BZip2IODevice::Private::doCompress(const char *in, qint64 iMaxLen)
do
{
if (aborted) return 0;
if (aborted)
return 0;
stream.next_out = buffer.data();
stream.avail_out = buffer.size();
@@ -109,8 +98,7 @@ qint64 BZip2IODevice::Private::doCompress(const char *in, qint64 iMaxLen)
return -1;
}
}
}
while (stream.avail_in != 0);
} while (stream.avail_in != 0);
return stream.next_in - in;
}
@@ -140,8 +128,7 @@ bool BZip2IODevice::Private::finishCompress()
parent->setErrorString(QLatin1String("Error writing to QIODevice"));
return false;
}
}
while (ret != BZ_STREAM_END);
} while (ret != BZ_STREAM_END);
BZ2_bzCompressEnd(&stream);
initialized = false;
@@ -206,8 +193,7 @@ qint64 BZip2IODevice::Private::doDecompress(char *out, qint64 iMaxLen)
finishDecompress();
return -1;
}
}
while (stream.avail_out != 0 && ret != BZ_STREAM_END);
} while (stream.avail_out != 0 && ret != BZ_STREAM_END);
decomressStreamEnd = (ret == BZ_STREAM_END);
return stream.next_out - out;
}
@@ -248,12 +234,7 @@ QString BZip2IODevice::Private::bzipError2String(int errCode)
return QString::number(errCode);
}
BZip2IODevice::BZip2IODevice(QIODevice *dev, int blocksize)
: d(new Private(this, dev, blocksize))
{}
BZip2IODevice::BZip2IODevice(QIODevice* dev, int blocksize) : d(new Private(this, dev, blocksize)) {}
BZip2IODevice::~BZip2IODevice()
{
@@ -283,7 +264,7 @@ bool BZip2IODevice::open(OpenMode mode)
{
if ((mode & QIODevice::ReadWrite) == 0)
{
setErrorString(QStringLiteral("Unsupported OpenMode %1").arg(mode));
setErrorString(QStringLiteral("Unsupported OpenMode %1").arg(static_cast<int>(mode)));
return false;
}
if ((mode & QIODevice::ReadWrite) == QIODevice::ReadWrite)
+42 -82
View File
@@ -1,63 +1,32 @@
#include "nglcomp_compress.h"
#include "nglcomp_bzip2iodevice.h"
#include "nglcomp_tarfilter.h"
#include <NGLLogger/NGLLoggerBootstrap.h>
#include <QBuffer>
#include <QtConcurrent>
#include <QCoreApplication>
#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <QFutureWatcher>
#include <QIODevice>
#include <QStringList>
#include <QtConcurrent>
#include <memory>
#include <utility>
#include <QDebug>
namespace NGL
{
Compress::Compress(QObject* parent)
: QObject(parent)
, m_u2_memFiles()
, m_aborted(0)
: QObject(parent), m_u2_memFiles(), m_aborted(0),
m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("nglcompress"))
{
DEBUG_LOG(m_logger) << "c_tor";
QTimer* t = new QTimer(this);
t->setInterval(1000);
connect(t, &QTimer::timeout, this, []() { qWarning() << "still alive ..."; });
@@ -68,7 +37,6 @@ Compress::~Compress()
{
qWarning() << "## COMPRESS DTOR!!!!";
DEBUG_LOG(m_logger) << "~";
abort();
@@ -96,11 +64,8 @@ void Compress::abort()
}
}
void Compress::compress(QIODevice *out,
const QString &filesRootDir,
const QVector<FileInformations> &files,
const QVector<FileInformations> &memFiles,
const QString &destRootDir)
void Compress::compress(QIODevice* out, const QString& filesRootDir, const QVector<FileInformations>& files,
const QVector<FileInformations>& memFiles, const QString& destRootDir)
{
DEBUG_LOG(m_logger) << "compress #2";
reset();
@@ -116,7 +81,6 @@ void Compress::compress(QIODevice *out, const QString &sourceDir, const QString
QVector<Compress::FileInformations> inFiles = directoryFileList(sourceDir, true);
int len = sourceDir.length();
if (!sourceDir.endsWith(QLatin1Char('/')))
len += 1;
@@ -132,31 +96,27 @@ void Compress::compress(QIODevice *out, const QString &sourceDir, const QString
compress(out, sourceDir, inFiles, {}, destRootDir);
}
bool Compress::_compress(QIODevice *output,
const QString &filesRootDir,
const QVector<FileInformations> &files,
const QVector<FileInformations> &memFiles,
const QString &_destRootDir)
{
std::shared_ptr<int> invalidatePointersOnScopeLeave(nullptr, [this](int *)
bool Compress::_compress(QIODevice* output, const QString& filesRootDir, const QVector<FileInformations>& files,
const QVector<FileInformations>& memFiles, const QString& _destRootDir)
{
std::shared_ptr<int> invalidatePointersOnScopeLeave(nullptr, [this](int*) {
DEBUG_LOG(m_logger) << "invalidatePointersOnScopeLeave #1";
m_currentTarFilter = nullptr;
m_currentBzipDevice = nullptr;
});
(void)invalidatePointersOnScopeLeave;
if (!output || !output->isWritable())
{
m_lastError = tr("Device is not writeable");
ERROR_LOG(m_logger) << "compress failed: " << m_lastError;;
ERROR_LOG(m_logger) << "compress failed: " << m_lastError;
;
return false;
}
const QString destRootDir = _destRootDir.endsWith(QLatin1Char('/')) ?
_destRootDir : _destRootDir + QLatin1Char('/');
const QString destRootDir =
_destRootDir.endsWith(QLatin1Char('/')) ? _destRootDir : _destRootDir + QLatin1Char('/');
const qint64 maxCount = files.count() + memFiles.count();
qint64 count = 0;
@@ -174,41 +134,39 @@ bool Compress::_compress(QIODevice *output,
return false;
}
qint64 bytesTotal = 0;
for (const FileInformations& file : std::as_const(files))
{
if (m_aborted) return false;
if (m_aborted)
return false;
const QString in = file.bAbsInputPath ? file.inputFileName : filesRootDir + QLatin1Char('/') + file.inputFileName;
const QString in =
file.bAbsInputPath ? file.inputFileName : filesRootDir + QLatin1Char('/') + file.inputFileName;
const QFileInfo fi(in);
bytesTotal += fi.size();
}
qint64 currentFileSize = 0;
QString currentFileName;
auto readCallback = [this, &maxCount, &count, &currentFileSize, &currentFileName, &bytesTotal](const qint64 iSize)
{
auto readCallback = [this, &maxCount, &count, &currentFileSize, &currentFileName, &bytesTotal](const qint64 iSize) {
DEBUG_LOG(m_logger) << "readCallback: maxCount = " << maxCount << ", count = " << count
<< ", currentFileSize = " << currentFileSize << ", currentFileName = " << currentFileName << ", iSize = " << iSize;
<< ", currentFileSize = " << currentFileSize << ", currentFileName = " << currentFileName
<< ", iSize = " << iSize;
emit compressInfoEx(maxCount, count, currentFileSize, (currentFileSize - iSize), currentFileName, bytesTotal);
};
TarFilter tf(&bzip2, readCallback);
m_currentTarFilter = &tf;
const QStringList paths = destRootDir.split(QLatin1Char('/'), Qt::SkipEmptyParts);
QString curPath;
DEBUG_LOG(m_logger) << "prepairing tar filter";
for (const QString& path : paths)
{
DEBUG_LOG(m_logger) << "path = " << path;
if (m_aborted) return false;
if (m_aborted)
return false;
if (curPath.isEmpty())
curPath = path + QLatin1Char('/');
@@ -245,7 +203,8 @@ bool Compress::_compress(QIODevice *output,
DEBUG_LOG(m_logger) << "file = " << file.inputFileName;
emit compressInfo(maxCount, ++count, file.inputFileName);
if (m_aborted) return false;
if (m_aborted)
return false;
QString in = file.bAbsInputPath ? file.inputFileName : filesRootDir + QLatin1Char('/') + file.inputFileName;
QString out = destRootDir + (file.outputFileName.isEmpty() ? file.inputFileName : file.outputFileName);
@@ -258,7 +217,8 @@ bool Compress::_compress(QIODevice *output,
currentFileSize = fi.size();
m_c_sizeInfo.realSize += currentFileSize;
DEBUG_LOG(m_logger) << "currentFileName = " << currentFileName << ", currentFileSize = " << currentFileSize << "m_c_sizeInfo.realSize" << m_c_sizeInfo.realSize;
DEBUG_LOG(m_logger) << "currentFileName = " << currentFileName << ", currentFileSize = " << currentFileSize
<< "m_c_sizeInfo.realSize" << m_c_sizeInfo.realSize;
if (!tf.addFile(in, out))
{
@@ -274,13 +234,16 @@ bool Compress::_compress(QIODevice *output,
DEBUG_LOG(m_logger) << "(mem) file = " << file.inputFileName;
emit compressInfo(maxCount, ++count, file.inputFileName);
if (m_aborted) return false;
if (m_aborted)
return false;
currentFileName = file.inputFileName;
currentFileSize = file.fileData.size();
m_c_sizeInfo.compressedSize += currentFileSize;
DEBUG_LOG(m_logger) << "(mem) currentFileName = " << currentFileName << ", currentFileSize = " << currentFileSize << "m_c_sizeInfo.realSize" << m_c_sizeInfo.realSize;
DEBUG_LOG(m_logger) << "(mem) currentFileName = " << currentFileName
<< ", currentFileSize = " << currentFileSize << "m_c_sizeInfo.realSize"
<< m_c_sizeInfo.realSize;
if (!tf.addData(file.inputFileName, file.fileData))
{
@@ -291,7 +254,6 @@ bool Compress::_compress(QIODevice *output,
}
}
DEBUG_LOG(m_logger) << "writing eos";
tf.writeEOS();
@@ -319,15 +281,13 @@ bool Compress::_uncompressDirectory(QIODevice *input, const QString &outDir)
{
DEBUG_LOG(m_logger) << "_uncompressDirectory";
std::shared_ptr<int> invalidatePointersOnScopeLeave(nullptr, [this](int *)
{
std::shared_ptr<int> invalidatePointersOnScopeLeave(nullptr, [this](int*) {
DEBUG_LOG(m_logger) << "invalidatePointersOnScopeLeave #2";
m_currentTarFilter = nullptr;
m_currentBzipDevice = nullptr;
});
(void)invalidatePointersOnScopeLeave;
if (!input || !input->isReadable())
{
m_lastError = tr("Device is not readable");
@@ -357,7 +317,8 @@ bool Compress::_uncompressDirectory(QIODevice *input, const QString &outDir)
{
DEBUG_LOG(m_logger) << "tfi.fileName = " << tfi.fileName;
emit uncompressInfo(input->size(), input->pos(), tfi.fileName);
if (m_aborted) return false;
if (m_aborted)
return false;
QString path = outDir + QLatin1Char('/') + tfi.fileName;
DEBUG_LOG(m_logger) << "path = " << path;
@@ -417,15 +378,13 @@ bool Compress::_uncompressBuffer(QIODevice *input)
{
DEBUG_LOG(m_logger) << "uncompressBuffer";
std::shared_ptr<int> invalidatePointersOnScopeLeave(nullptr, [this](int *)
{
std::shared_ptr<int> invalidatePointersOnScopeLeave(nullptr, [this](int*) {
DEBUG_LOG(m_logger) << "invalidatePointersOnScopeLeave #2";
m_currentTarFilter = nullptr;
m_currentBzipDevice = nullptr;
});
(void)invalidatePointersOnScopeLeave;
if (!input->isReadable())
{
m_lastError = tr("Device is not readable");
@@ -451,7 +410,8 @@ bool Compress::_uncompressBuffer(QIODevice *input)
{
DEBUG_LOG(m_logger) << "tfi.fileName = " << tfi.fileName;
emit uncompressInfo(input->size(), input->pos(), tfi.fileName);
if (m_aborted) return false;
if (m_aborted)
return false;
FileInformations fi;
fi.outputFileName = tfi.fileName;
@@ -499,8 +459,7 @@ bool Compress::success() const
ERROR_LOG(m_logger) << "success? " << (m_future.isFinished() && !m_future.isCanceled() && m_success);
ERROR_LOG(m_logger) << "success details: "
<< "success m_future.isFinished() = " << (m_future.isFinished())
<< " !m_future.isCanceled() = " << !m_future.isCanceled()
<< " m_success = " << m_success;
<< " !m_future.isCanceled() = " << !m_future.isCanceled() << " m_success = " << m_success;
return (m_future.isFinished() && !m_future.isCanceled() && m_success);
}
@@ -562,8 +521,9 @@ void Compress::setupFutureWatcher(const QFuture<bool> &future)
QObject::connect(fw, &QObject::destroyed, this, [this]() { DEBUG_LOG(m_logger) << "Future Watcher destroyed"; });
QObject::connect(fw, &QFutureWatcher<bool>::finished, this, &Compress::finished);
QObject::connect(fw, &QFutureWatcher<bool>::finished, fw, &QObject::deleteLater);
QObject::connect(fw, &QFutureWatcher<bool>::finished, fw, [this]() { DEBUG_LOG(m_logger) << "Future Watcher about to be deleted"; });
QObject::connect(fw, &QFutureWatcher<bool>::finished, fw,
[this]() { DEBUG_LOG(m_logger) << "Future Watcher about to be deleted"; });
fw->setFuture(m_future);
}
}
} // namespace NGL
+1 -4
View File
@@ -1,12 +1,9 @@
#pragma once
#include "commandinterface.h"
#include "sv_export.h"
#include "tcpserver_export.h"
class TCPSERVER_EXPORT CBI_Help : public CommandInterface
{
+1 -4
View File
@@ -1,12 +1,9 @@
#pragma once
#include "commandinterface.h"
#include "sv_export.h"
#include "tcpserver_export.h"
class CBI_PingPong : public CommandInterface
{
+1 -4
View File
@@ -1,12 +1,9 @@
#pragma once
#include "commandinterface.h"
#include "sv_export.h"
#include "tcpserver_export.h"
class TCPSERVER_EXPORT CBI_Quit : public CommandInterface
{
+4 -2
View File
@@ -1,14 +1,15 @@
#pragma once
#include "commandinterface.h"
#include "sv_export.h"
#include "tcpserver_export.h"
#include <QMap>
#include <QPair>
class QIODevice;
class CBI_Recvfile : public CommandInterface
{
Q_OBJECT
@@ -18,6 +19,7 @@ public:
void handleCommandInternal(const QVector<QByteArray>& args) override;
QString help() const override;
void newPlainData() override;
protected:
QMap<WorkerBase*, QPair<QIODevice*, int>> m_wbMap;
};
+1 -2
View File
@@ -1,10 +1,9 @@
#pragma once
#include "commandinterface.h"
#include "sv_export.h"
#include "tcpserver_export.h"
class CBI_Sendfile : public CommandInterface
{
+2 -5
View File
@@ -1,12 +1,9 @@
#pragma once
#include "commandinterface.h"
#include "sv_export.h"
#include "tcpserver_export.h"
class TCPSERVER_EXPORT CBI_Shutdown : public CommandInterface
{
@@ -19,7 +16,7 @@ public:
Q_SIGNALS:
void shutdownRequest();
private:
};
+7 -58
View File
@@ -1,151 +1,101 @@
#pragma once
#include "tcpserver_export.h"
#include <QObject>
#include <QString>
#include <QVector>
#include "sv_export.h"
class QAbstractSocket;
class QByteArray;
class WorkerBase;
class TCPSERVER_EXPORT CommandInterface : public QObject
{
Q_OBJECT
public:
explicit CommandInterface(unsigned short port, const QByteArray& command = QByteArray());
virtual ~CommandInterface();
void handleCommand(const QVector<QByteArray>& args);
virtual void newPlainData();
virtual QString help() const = 0;
QByteArray command() const;
void setAutoWriteEOL(bool newAutoWriteEOL);
bool autoWriteEOL() const;
bool errorOccured() const;
static void setDefaultSuccessMessage(const QString& msg);
static void setDefaultErrorMessage(const QString& msg);
template<class T>
static CommandInterface *factory(unsigned short port) { return new T(port); }
template <class T> static CommandInterface* factory(unsigned short port)
{
return new T(port);
}
virtual void aboutToDestroy() {}
protected:
virtual void handleCommandInternal(const QVector<QByteArray>& args) = 0;
void setWriteTimeout(int iMS);
void writeData(const QByteArray& payload);
void writeData(const char* payload);
void writeData(const QString& payload);
void writeData(const QStringList& payload);
void writeData(const QList<QByteArray>& payload);
void writeOk(const QString& additionalMsg = QString());
void writeError(const QString& additionalMsg = QString());
void writeEOL();
QByteArray quote(const QByteArray& payload);
QAbstractSocket* socket();
void setSocket(QAbstractSocket* socket);
WorkerBase* workerBase();
void setWorkerBase(WorkerBase* wb);
void conversionError(const QByteArray& arg, const QByteArray& type);
bool getValue(const QByteArray& arg, bool& value);
bool getValue(const QByteArray& arg, long& value);
bool getValue(const QByteArray& arg, unsigned long& value);
bool getValue(const QByteArray& arg, int& value);
bool getValue(const QByteArray& arg, unsigned int& value);
bool getValue(const QByteArray& arg, float& value);
bool getValue(const QByteArray& arg, double& value);
unsigned short port() const;
void closeConnection();
bool socketIsOpen() const;
private:
@@ -153,6 +103,5 @@ private:
class Private;
Private* const d;
};
+3 -35
View File
@@ -1,82 +1,53 @@
#pragma once
#include <QTcpServer>
#include "tcpserver_export.h"
#include "sv_export.h"
#include <QTcpServer>
class WorkerInstance;
class CommandInterface;
class TCPSERVER_EXPORT TcpServer : public QTcpServer
{
Q_OBJECT
public:
typedef QVector<CommandInterface* (*)(unsigned short)> CommandInterfaceList;
public:
virtual ~TcpServer();
static TcpServer* instance(unsigned short port);
bool listen(const QHostAddress& address = QHostAddress::Any);
void setUseWorkerThreads(bool bEnable);
bool useWorkerThreads() const;
QVector<WorkerInstance*> workers() const;
unsigned short getListenPort() const;
static bool registerCommand(unsigned short port, CommandInterface* (*factory)(unsigned short));
static bool unregisterCommand(unsigned short port, CommandInterface* (*factory)(unsigned short));
static CommandInterfaceList registeredCommands(unsigned short port);
void setUserData(void* userData);
void* userData() const;
Q_SIGNALS:
void aboutToQuit(unsigned short port);
public Q_SLOTS:
void shutdownRequest();
void workerFinished();
protected:
@@ -85,12 +56,9 @@ protected:
private:
class Private;
Private* const d;
explicit TcpServer(unsigned short port);
bool listen(const QHostAddress& address, quint16 port);
};
+4 -45
View File
@@ -1,93 +1,61 @@
#pragma once
#include "tcpserver_export.h"
#include <QByteArray>
#include <QMap>
#include <QPointer>
#include <QObject>
#include "sv_export.h"
#include <QPointer>
class QAbstractSocket;
class CommandInterface;
class TCPSERVER_EXPORT WorkerBase
{
public:
typedef QMap<QByteArray, CommandInterface*> CommandMap;
public:
WorkerBase(qintptr sd, unsigned short port);
virtual ~WorkerBase() = default;
QAbstractSocket* connection();
const QAbstractSocket* connection() const;
void redirectDataHandling(bool bDoRedirect, CommandInterface* newDataHandler = nullptr);
static QByteArray formatForDebug(const QByteArray& data);
static QByteArray formatForDebug(const QAbstractSocket* dev);
CommandMap getCommands() const;
protected:
void newDataInternal();
int initCommands(unsigned short port);
void cleanupCommands();
qintptr m_socketDescriptor;
QPointer<QAbstractSocket> m_connection;
unsigned short m_port;
QByteArray m_connString;
bool m_bRedirectIncomingData;
CommandInterface* m_bRedirectDataHandler;
CommandMap m_registeredCommands;
};
class WorkerInstance final : public QObject, public WorkerBase
{
Q_OBJECT
@@ -95,28 +63,20 @@ public:
WorkerInstance(qintptr sd, unsigned short port, QObject* parent = nullptr);
virtual ~WorkerInstance();
bool isRunning() const;
bool isFinished() const;
public Q_SLOTS:
void quit();
void doWork();
protected Q_SLOTS:
void newData();
void connectionDisconnected();
Q_SIGNALS:
@@ -125,4 +85,3 @@ Q_SIGNALS:
private:
bool m_bFinished;
};
@@ -163,6 +163,7 @@ MACRO(INSTALL_SHARED_FILES srcList)
ENDMACRO()
MACRO(CODEGEN_SQL srcList xmlFile_in)
IF(BUILD_GRANTLEE)
_GET_SERVICENAME( "${xmlFile_in}" svcNameOut )
SET(out_dir_sql "${CMAKE_BINARY_DIR}/share/Lts/sql/")
SET(out_file_sql "${out_dir_sql}/${svcNameOut}.sql")
@@ -182,6 +183,11 @@ MACRO(CODEGEN_SQL srcList xmlFile_in)
NGL_INSTALL(SV AAR FILES ${out_file_sql} DESTINATION share/Lts/sql)
ELSE()
# BUILD_GRANTLEE disabled: skip SQL generation
# SQL files will not be generated; modules may need pre-generated SQL files
MESSAGE(STATUS "BUILD_GRANTLEE disabled: skipping SQL generation for ${xmlFile_in}")
ENDIF()
ENDMACRO()
MACRO(CODEGEN_HANDLE_SVC_XML srcList xmlFile_in)
+63 -78
View File
@@ -7,22 +7,21 @@
#pragma once
#include <string>
#include <sstream>
#include <QString>
#include <QList>
#include <QPointF>
#include <QSize>
#include <QRect>
#include <QRectF>
#include <QList>
#include "ngllogger_export.h"
#include <QSize>
#include <QString>
#include <ngllogger_export.h>
#include <sstream>
#include <string>
namespace NGL
{
class INGLLogger;
// keep in sync with log4qt/level.h
enum class LogLevel
{
enum class LogLevel {
Undefined = 0,
Trace = 64,
Debug = 96,
@@ -35,17 +34,15 @@ enum class LogLevel
class LogStreamHelper
{
public:
inline LogStreamHelper(INGLLogger &logger, LogLevel level, const char *const file, int line, const char *const function)
: m_logger(logger)
, m_level(level)
, m_line(line)
, m_file(file)
, m_func(function)
{}
inline LogStreamHelper(INGLLogger& logger, LogLevel level, const char* const file, int line,
const char* const function)
: m_logger(logger), m_level(level), m_line(line), m_file(file), m_func(function)
{
}
inline ~LogStreamHelper(); // after INGLLogger class definition
template<typename T>
inline LogStreamHelper &operator<<(const T &val);
template <typename T> inline LogStreamHelper& operator<<(const T& val);
private:
std::ostringstream m_buffer;
@@ -79,7 +76,6 @@ public:
virtual INGLLogger& getNGLLogger(const char* fullqualifiedname) = 0;
virtual INGLLogger& getNGLLogger(const std::string& fullqualifiedname) = 0;
// True if this level is enabled.
virtual bool isTraceEnabled() const = 0;
virtual bool isDebugEnabled() const = 0;
@@ -91,20 +87,27 @@ public:
// Submit a LOG message.
// Use __FILE__ and __NAME__ macros.
virtual void log(LogLevel level, const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0;
virtual void log(LogLevel level, const INGLLogger::String& message, const char* file = nullptr, int line = -1,
const char* function = nullptr) = 0;
// Submit an TRACE message.
virtual void logTrace(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0;
virtual void logTrace(const INGLLogger::String& message, const char* file = nullptr, int line = -1,
const char* function = nullptr) = 0;
// Submit an DEBUG message.
virtual void logDebug(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0;
virtual void logDebug(const INGLLogger::String& message, const char* file = nullptr, int line = -1,
const char* function = nullptr) = 0;
// Submit an INFO message.
virtual void logInfo(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0;
virtual void logInfo(const INGLLogger::String& message, const char* file = nullptr, int line = -1,
const char* function = nullptr) = 0;
// Submit a WARNING message.
virtual void logWarning(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0;
virtual void logWarning(const INGLLogger::String& message, const char* file = nullptr, int line = -1,
const char* function = nullptr) = 0;
// Submit an ERROR message.
virtual void logError(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0;
virtual void logError(const INGLLogger::String& message, const char* file = nullptr, int line = -1,
const char* function = nullptr) = 0;
// Submit a FATAL message.
virtual void logFatal(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0;
virtual void logFatal(const INGLLogger::String& message, const char* file = nullptr, int line = -1,
const char* function = nullptr) = 0;
// Writes a startup message into the logfile
virtual void logStartup(const char* file, int line, const char* function = nullptr) = 0;
@@ -126,8 +129,7 @@ inline LogStreamHelper::~LogStreamHelper()
m_logger.log(m_level, m_buffer.str(), m_file, m_line, m_func);
}
template<typename T>
inline LogStreamHelper &LogStreamHelper::operator<<(const T &val)
template <typename T> inline LogStreamHelper& LogStreamHelper::operator<<(const T& val)
{
m_buffer << val;
if (!m_logger.noSpace())
@@ -135,7 +137,6 @@ inline LogStreamHelper &LogStreamHelper::operator<<(const T &val)
return *this;
}
} // namespace NGL
inline std::ostream& operator<<(std::ostream& stream, const QByteArray& str)
@@ -147,67 +148,50 @@ inline std::ostream &operator<<(std::ostream &stream, const QByteArray &str)
//
// operator to ease logging (at least via NglLogging)
//
inline std::ostream &operator<<(std::ostream &stream,
const QPointF &value)
inline std::ostream& operator<<(std::ostream& stream, const QPointF& value)
{
stream << "QPointF(" << QString::number(value.x(), 'f', 6).toStdString() << "#" << QString::number(value.y(), 'f', 6).toStdString() << ")";
stream << "QPointF(" << QString::number(value.x(), 'f', 6).toStdString() << "#"
<< QString::number(value.y(), 'f', 6).toStdString() << ")";
return stream;
}
//----------------------------------------------------------------------------
inline std::ostream &operator<< (std::ostream &stream,
const QPoint &value)
inline std::ostream& operator<<(std::ostream& stream, const QPoint& value)
{
stream << "QPoint(" << value.x() << "#" << value.y() << ")";
return stream;
}
inline std::ostream &operator<< (std::ostream &stream,
const QSize &value)
inline std::ostream& operator<<(std::ostream& stream, const QSize& value)
{
stream << "QSize(w=" << value.width() << ";h=" << value.height() << ")";
return stream;
}
inline std::ostream &operator<< (std::ostream &stream,
const QSizeF &value)
inline std::ostream& operator<<(std::ostream& stream, const QSizeF& value)
{
stream << "QSize(w="
<< QString::number(value.width(), 'f', 6).toStdString() << ";h="
<< QString::number(value.height(), 'f', 6).toStdString()
<< ")";
stream << "QSize(w=" << QString::number(value.width(), 'f', 6).toStdString()
<< ";h=" << QString::number(value.height(), 'f', 6).toStdString() << ")";
return stream;
}
inline std::ostream &operator<< (std::ostream &stream,
const QRect &value)
inline std::ostream& operator<<(std::ostream& stream, const QRect& value)
{
stream << "QRect(center=" << value.center()
<< " w=" << value.width()
<< ";h=" << value.height()
<< " bottomLeft=" << value.bottomLeft()
<< " topRight=" << value.topRight()
<< ")";
stream << "QRect(center=" << value.center() << " w=" << value.width() << ";h=" << value.height()
<< " bottomLeft=" << value.bottomLeft() << " topRight=" << value.topRight() << ")";
return stream;
}
inline std::ostream &operator<< (std::ostream &stream,
const QRectF &value)
inline std::ostream& operator<<(std::ostream& stream, const QRectF& value)
{
stream << "QRectF(center=" << value.center()
<< " w=" << QString::number(value.width(), 'f', 3).toStdString()
<< ";h=" << QString::number(value.height(), 'f', 3).toStdString()
<< " bottomLeft=" << value.bottomLeft()
<< " topRight=" << value.topRight()
<< ")";
stream << "QRectF(center=" << value.center() << " w=" << QString::number(value.width(), 'f', 3).toStdString()
<< ";h=" << QString::number(value.height(), 'f', 3).toStdString() << " bottomLeft=" << value.bottomLeft()
<< " topRight=" << value.topRight() << ")";
return stream;
}
inline std::ostream &operator<< (std::ostream &stream,
const QList<int> &value)
inline std::ostream& operator<<(std::ostream& stream, const QList<int>& value)
{
stream << "QList<int>(" << value.size() << "): ";
for (int i : value)
@@ -215,9 +199,7 @@ inline std::ostream &operator<< (std::ostream &stream,
return stream;
}
inline std::ostream &operator<< (std::ostream &stream,
const QList<QPointF> &value)
inline std::ostream& operator<<(std::ostream& stream, const QList<QPointF>& value)
{
stream << "QList<QPointF>(" << value.size() << "): ";
for (const QPointF& item : value)
@@ -225,7 +207,6 @@ inline std::ostream &operator<< (std::ostream &stream,
return stream;
}
inline std::ostream& operator<<(std::ostream& stream, const QString& str)
{
return stream << str.toUtf8();
@@ -236,13 +217,10 @@ namespace NGL
namespace NGLLoggerHelper
{
NGLLOGGER_EXPORT void hexDumpHelper(NGL::INGLLogger &logger,
NGL::LogLevel level,
const void *a_data,
NGLLOGGER_EXPORT void hexDumpHelper(NGL::INGLLogger& logger, NGL::LogLevel level, const void* a_data,
const unsigned int a_size);
inline void hexDumpHelper(NGL::INGLLogger &logger,
NGL::LogLevel level,
const QByteArray &data)
inline void hexDumpHelper(NGL::INGLLogger& logger, NGL::LogLevel level, const QByteArray& data)
{
return hexDumpHelper(logger, level, data.data(), data.size());
}
@@ -260,8 +238,7 @@ NGLLOGGER_EXPORT std::string getMemoryData();
#define LOGFUNCTION Q_FUNC_INFO
// log this output every time, no matter what log level is enabled
#define NOTICE_LOG(logger) \
NGL::LogStreamHelper(logger, NGL::LogLevel::Info, __FILE__,__LINE__, Q_FUNC_INFO)
#define NOTICE_LOG(logger) NGL::LogStreamHelper(logger, NGL::LogLevel::Info, __FILE__, __LINE__, Q_FUNC_INFO)
#ifdef LTS_DEBUG
#define TRACE_LOG(logger) \
@@ -293,8 +270,14 @@ NGLLOGGER_EXPORT std::string getMemoryData();
for (bool log_level_enabled = (logger).isFatalEnabled(); log_level_enabled; log_level_enabled = false) \
NGL::LogStreamHelper(logger, NGL::LogLevel::Fatal, __FILE__, __LINE__, Q_FUNC_INFO)
#define STARTUP_LOG(logger) { (logger).logStartup(__FILE__, __LINE__, Q_FUNC_INFO); }
#define SHUTDOWN_LOG(logger) { (logger).logShutdown(__FILE__, __LINE__, Q_FUNC_INFO); }
#define STARTUP_LOG(logger) \
{ \
(logger).logStartup(__FILE__, __LINE__, Q_FUNC_INFO); \
}
#define SHUTDOWN_LOG(logger) \
{ \
(logger).logShutdown(__FILE__, __LINE__, Q_FUNC_INFO); \
}
//==============================================================================
@@ -304,7 +287,9 @@ NGLLOGGER_EXPORT std::string getMemoryData();
// MEMORY_LOG() << " after something nasty";
#define MEMORY_LOG() \
for (bool log_level_enabled = (NGL::getMemoryLogger()).isInfoEnabled(); log_level_enabled; log_level_enabled = false) \
NGL::LogStreamHelper(NGL::getMemoryLogger(), NGL::LogLevel::Info, __FILE__,__LINE__, Q_FUNC_INFO) << NGL::getMemoryData()
for (bool log_level_enabled = (NGL::getMemoryLogger()).isInfoEnabled(); log_level_enabled; \
log_level_enabled = false) \
NGL::LogStreamHelper(NGL::getMemoryLogger(), NGL::LogLevel::Info, __FILE__, __LINE__, Q_FUNC_INFO) \
<< NGL::getMemoryData()
//==============================================================================
@@ -13,7 +13,7 @@ if(NOT TARGET GTest::gtest_main)
FetchContent_Declare(
googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG release-1.13.0
GIT_TAG v1.13.0
)
# For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
@@ -31,6 +31,7 @@ if(BUILD_TESTING)
test_symbology_xml.cpp
test_saa_telegrams.cpp
test_rti_integration.cpp
test_ltswidgets_qt6.cpp
)
# Check which files actually exist
@@ -0,0 +1,224 @@
/**
* @file test_ltswidgets_qt6.cpp
* @brief Tests für LtsWidgets Qt6-Migration
*
* Tests verify Qt6 API compatibility changes:
* 1. QRandomGenerator usage (replacing qrand())
* 2. Signal/slot connections with Qt6 signatures
* 3. QWheelEvent angleDelta() usage
* 4. QStyleOption::initFrom() usage
*/
#include <gtest/gtest.h>
#include <QRandomGenerator>
#include <QComboBox>
#include <QWheelEvent>
#include <QStyleOption>
#include <QPushButton>
#include <QApplication>
// Ensure QApplication is initialized for widget tests
static bool appInitialized = false;
static void ensureAppInitialized() {
if (!appInitialized) {
static int argc = 1;
static char* argv[] = { (char*)"test_ltswidgets_qt6", nullptr };
static QApplication app(argc, argv);
appInitialized = true;
}
}
// Test 1: QRandomGenerator bounded generation (used in lts_tab_widget.cpp)
TEST(LtsWidgetsQt6, QRandomGeneratorBounded) {
auto* generator = QRandomGenerator::global();
ASSERT_NE(generator, nullptr);
// Test multiple bounded calls to ensure stability
for (int i = 0; i < 100; ++i) {
int value = generator->bounded(10);
EXPECT_GE(value, 0);
EXPECT_LT(value, 10);
}
}
// Test 2: QRandomGenerator produces different values
TEST(LtsWidgetsQt6, QRandomGeneratorVariation) {
auto* generator = QRandomGenerator::global();
QVector<int> values;
for (int i = 0; i < 50; ++i) {
values.append(generator->bounded(1000));
}
// Check that we get some variation (not all same value)
bool hasDifferent = false;
for (int i = 1; i < values.size(); ++i) {
if (values[i] != values[0]) {
hasDifferent = true;
break;
}
}
EXPECT_TRUE(hasDifferent);
}
// Test 3: QRandomGenerator seeded reproducibility
TEST(LtsWidgetsQt6, QRandomGeneratorSeeded) {
QRandomGenerator gen1(12345);
QRandomGenerator gen2(12345);
// Same seed should produce same sequence
for (int i = 0; i < 10; ++i) {
EXPECT_EQ(gen1.bounded(1000), gen2.bounded(1000));
}
}
// Test 4: QComboBox currentTextChanged signal (Qt6 compatible)
// This tests the signal used in lts_text_editor.cpp
TEST(LtsWidgetsQt6, QComboBoxCurrentTextChangedSignal) {
ensureAppInitialized();
QComboBox comboBox;
comboBox.addItem("Option1");
comboBox.addItem("Option2");
comboBox.addItem("Option3");
bool signalReceived = false;
QString receivedText;
QObject::connect(&comboBox, &QComboBox::currentTextChanged,
[&signalReceived, &receivedText](const QString& text) {
signalReceived = true;
receivedText = text;
});
comboBox.setCurrentIndex(1);
EXPECT_TRUE(signalReceived);
EXPECT_EQ(receivedText, "Option2");
}
// Test 5: QComboBox activated signal with int parameter (Qt6)
// Note: activated signal is only emitted on user interaction, not on setCurrentIndex
TEST(LtsWidgetsQt6, QComboBoxActivatedIntSignal) {
ensureAppInitialized();
QComboBox comboBox;
comboBox.addItem("First");
comboBox.addItem("Second");
comboBox.addItem("Third");
bool signalReceived = false;
int receivedIndex = -1;
// Connect using Qt6 syntax - activated emits int index
QObject::connect(&comboBox, QOverload<int>::of(&QComboBox::activated),
[&signalReceived, &receivedIndex](int index) {
signalReceived = true;
receivedIndex = index;
});
// Simulate user interaction by emitting the signal manually
// (setCurrentIndex does not trigger activated signal)
QMetaObject::invokeMethod(&comboBox, "activated", Qt::QueuedConnection, Q_ARG(int, 2));
QCoreApplication::processEvents();
// Verify the connection works with int parameter
EXPECT_TRUE(signalReceived);
EXPECT_EQ(receivedIndex, 2);
}
// Test 6: QStyleOption::initFrom() (Qt6 replacement for init())
// This tests the API used in lts_notification_box.cpp
TEST(LtsWidgetsQt6, QStyleOptionInitFrom) {
ensureAppInitialized();
QPushButton button("Test");
button.resize(100, 30);
button.setEnabled(true);
QStyleOption opt;
opt.initFrom(&button);
// Verify initFrom sets up the option correctly
// State_Enabled should be set (among other states)
EXPECT_TRUE(opt.state & QStyle::State_Enabled);
EXPECT_FALSE(opt.rect.isNull());
}
// Test 7: QStyleOption multiple widgets
TEST(LtsWidgetsQt6, QStyleOptionInitFromMultipleWidgets) {
ensureAppInitialized();
QPushButton button1("Btn1");
QPushButton button2("Btn2");
button1.setEnabled(true);
button2.setEnabled(false);
QStyleOption opt1;
opt1.initFrom(&button1);
QStyleOption opt2;
opt2.initFrom(&button2);
// Verify different widget states are captured
EXPECT_TRUE(opt1.state & QStyle::State_Enabled);
EXPECT_FALSE(opt2.state & QStyle::State_Enabled);
}
// Test 8: QWheelEvent angleDelta() availability
// This verifies the API used in lts_date_time_edit_p.cpp
TEST(LtsWidgetsQt6, QWheelEventAngleDelta) {
ensureAppInitialized();
QPoint pos(100, 100);
QPoint globalPos(200, 200);
QPoint pixelDelta(0, 0);
QPoint angleDelta(0, 120); // Standard wheel step
QWheelEvent wheelEvent(pos, globalPos, pixelDelta, angleDelta,
Qt::NoButton, Qt::NoModifier,
Qt::NoScrollPhase, false);
// Verify angleDelta() is accessible and returns correct value
QPoint delta = wheelEvent.angleDelta();
EXPECT_EQ(delta.y(), 120);
EXPECT_EQ(delta.x(), 0);
}
// Test 9: QWheelEvent negative angleDelta
TEST(LtsWidgetsQt6, QWheelEventNegativeAngleDelta) {
ensureAppInitialized();
QPoint pos(100, 100);
QPoint globalPos(200, 200);
QPoint pixelDelta(0, 0);
QPoint angleDelta(0, -120); // Scroll down
QWheelEvent wheelEvent(pos, globalPos, pixelDelta, angleDelta,
Qt::NoButton, Qt::NoModifier,
Qt::NoScrollPhase, false);
QPoint delta = wheelEvent.angleDelta();
EXPECT_EQ(delta.y(), -120);
// Test the logic used in lts_date_time_edit_p.cpp
bool isUp = delta.y() > 0;
EXPECT_FALSE(isUp);
}
// Test 10: QWheelEvent angleDelta direction detection
TEST(LtsWidgetsQt6, QWheelEventDirectionDetection) {
ensureAppInitialized();
// Simulate wheel up (positive delta)
QPoint angleDeltaUp(0, 120);
QWheelEvent wheelUp(QPoint(0, 0), QPoint(0, 0), QPoint(0, 0), angleDeltaUp,
Qt::NoButton, Qt::NoModifier, Qt::NoScrollPhase, false);
EXPECT_TRUE(wheelUp.angleDelta().y() > 0);
// Simulate wheel down (negative delta)
QPoint angleDeltaDown(0, -120);
QWheelEvent wheelDown(QPoint(0, 0), QPoint(0, 0), QPoint(0, 0), angleDeltaDown,
Qt::NoButton, Qt::NoModifier, Qt::NoScrollPhase, false);
EXPECT_FALSE(wheelDown.angleDelta().y() > 0);
}