DynExp
Highly flexible laboratory automation for dynamically changing experiments.
Loading...
Searching...
No Matches
QtUtil.h
Go to the documentation of this file.
1// This file is part of DynExp.
2
8#pragma once
9
10#include "stdafx.h"
11
12namespace DynExp
13{
14 class DynExpCore;
15 class HardwareAdapterBase;
16 class QModuleWidget;
17}
18
19namespace Util
20{
25 const QLocale& GetDefaultQtLocale();
26
27 using TextType = std::string;
28 using TextRefType = std::string_view;
29 using TextListType = std::vector<TextType>;
30 using TextListIndexType = size_t;
31
36 template <typename ValueType>
37 using TextValueListType = std::vector<std::pair<TextType, ValueType>>;
38
54 template <typename EnumType>
55 auto QtEnumToTextValueList(unsigned short SkipEntriesFront = 0, unsigned short SkipEntriesEnd = 0,
56 unsigned short SkipCharsFront = 0, unsigned short SkipCharsEnd = 0)
57 {
59 auto QtEnum = QMetaEnum::fromType<EnumType>();
60
61 if (static_cast<long>(QtEnum.keyCount()) - SkipEntriesFront - SkipEntriesEnd <= 0)
62 throw Util::OutOfRangeException("Qt enum does not contain any entries (after subtraction).");
63
64 for (int i = SkipEntriesFront; i < QtEnum.keyCount() - SkipEntriesEnd; ++i)
65 {
66 std::string ElementTitle(QtEnum.key(i));
67 ElementTitle = ElementTitle.substr(SkipCharsFront, ElementTitle.length() - SkipCharsFront - SkipCharsEnd);
68
69 List.emplace_back(ElementTitle.c_str(), static_cast<EnumType>(QtEnum.value(i)));
70 }
71
72 return List;
73 }
74
79
86 std::vector<QDomNode> GetChildDOMNodes(const QDomElement& Parent, const QString& ChildTagName);
87
97 QDomNode GetSingleChildDOMNode(const QDomElement& Parent, const QString& ChildTagName);
98
106 QDomElement GetSingleChildDOMElement(const QDomElement& Parent, const QString& ChildTagName);
107
114 std::string GetStringFromDOMElement(const QDomElement& Parent, const QString& ChildTagName);
115
124 template <typename T>
125 T GetTFromDOMElement(const QDomElement& Parent, const QString& ChildTagName)
126 {
127 return Util::StrToT<T>(GetStringFromDOMElement(Parent, ChildTagName));
128 }
129
133 template <>
134 std::string GetTFromDOMElement(const QDomElement& Parent, const QString& ChildTagName);
135
144 QDomAttr GetDOMAttribute(const QDomElement& Element, const QString& AttributeName);
145
152 std::string GetStringFromDOMAttribute(const QDomElement& Element, const QString& AttributeName);
153
162 template <typename T>
163 T GetTFromDOMAttribute(const QDomElement& Element, const QString& AttributeName)
164 {
165 return Util::StrToT<T>(GetStringFromDOMAttribute(Element, AttributeName));
166 }
167
171 template <>
172 std::string GetTFromDOMAttribute(const QDomElement& Element, const QString& AttributeName);
174
178
189 QString PromptOpenFilePath(QWidget* Parent,
190 const QString& Title, const QString& DefaultSuffix, const QString& NameFilter, const QString& InitialDirectory = "");
191
202 QString PromptSaveFilePath(QWidget* Parent,
203 const QString& Title, const QString& DefaultSuffix, const QString& NameFilter, const QString& InitialDirectory = "");
204
217 const QString& Title, const QString& DefaultSuffix, const QString& NameFilter);
219
223
235 QImage QImageFromBlobData(BlobDataType&& BlobData, int Width, int Height, int BytesPerLine, QImage::Format Format);
236
237 // Calculates histograms from Image for RGB/intensity channels. Each array in ImageRGBHistogramType conatins values
238 // assigned to bins given by the element indices. The three arrays contain histograms for RGB channels in this order.
239
244 using ImageHistogramType = std::array<unsigned long long, 256>;
245
250 using ImageRGBHistogramType = std::tuple<ImageHistogramType, ImageHistogramType, ImageHistogramType>;
251
258
264 ImageRGBHistogramType ComputeRGBHistogram(const QImage& Image);
265
272
279 QPolygonF MakeCrossPolygon(QPointF Center, unsigned int ArmLength);
281
286 void ActivateWindow(QWidget& Widget);
287
291
298 bool SaveToFile(const QString& Filename, std::string_view Text);
299
306 std::string ReadFromFile(const QString& Filename);
307
311 std::string ReadFromFile(const std::string& Filename);
312
316 std::string ReadFromFile(const std::filesystem::path& Filename);
318
326 class QWorker : public QObject
327 {
328 Q_OBJECT
329
330 friend class DynExp::DynExpCore;
331
332 protected:
333 QWorker() = default;
334 ~QWorker() = default;
335
336 public:
344
349 auto GetOwner() const noexcept { return Owner.lock(); }
350
351 private:
352 using OwnerPtrType = std::weak_ptr<const DynExp::HardwareAdapterBase>;
353
362 static const DynExp::DynExpCore& GetDynExpCore(const DynExp::DynExpCore* DynExpCore = nullptr);
363
368 void SetOwner(OwnerPtrType Owner) noexcept { this->Owner = Owner; }
369
372 };
373
378 class MarkerGraphicsView : public QGraphicsView
379 {
380 Q_OBJECT
381
382 static constexpr double ZoomFactor = 1.6;
383 static constexpr double DeselectedMarkerOpacity = .5;
384 static constexpr double SelectedMarkerOpacity = 1;
385
386 public:
391 {
392 using IDType = signed long long;
393
402 constexpr MarkerType(QGraphicsPolygonItem* Marker, const QPoint& MarkerPos, bool IsUserDeletable = true, IDType ID = -1, const QPointF& ImagePos = {}) noexcept
404
408 constexpr auto GetMarker() noexcept { return Marker; }
409 constexpr const auto GetMarker() const noexcept { return Marker; }
410 constexpr const auto& GetMarkerPos() const noexcept { return MarkerPos; }
411 constexpr bool IsUserDeletable() const noexcept { return UserDeletable; }
412 constexpr auto GetID() const noexcept { return ID; }
413 constexpr std::string_view GetName() const noexcept { return Name; }
414 constexpr const auto& GetImagePos() const noexcept { return ImagePos; }
416
420 void SetName(std::string_view NewName);
422
423 private:
428 QGraphicsPolygonItem* Marker;
429 QPoint MarkerPos;
432 std::string Name;
433 QPointF ImagePos;
435 };
436
441 MarkerGraphicsView(QWidget* parent);
442
446 auto contextMenu() const noexcept { return ContextMenu; }
447 bool HaveMarkersChanged() noexcept;
448 const std::vector<MarkerType>& GetMarkers() const noexcept { return Markers; }
449 const auto& GetCurrentImagePos() const noexcept { return CurrentImagePos; }
451
455 void SetCurrentImagePos(const QPointF& Pos) { CurrentImagePos = Pos; }
457
461
470 void AddMarker(const QPoint& MarkerPos, const QColor& Color, bool IsUserDeletable = true, MarkerType::IDType ID = -1, std::string Name = {});
471
479 void RemoveMarker(size_t Index, bool OnlyUserDeletableMarkers = false);
480
487 void RemoveMarker(const QPoint& MarkerPos, bool OnlyUserDeletableMarkers = false);
488
495 void RemoveMarker(std::string_view Name, bool OnlyUserDeletableMarkers = false);
496
502 void RemoveMarkers(bool OnlyUserDeletableMarkers);
503
509
515 void RenameMarker(const QPoint& MarkerPos, std::string_view NewName);
516
521 void SelectMarker(const QPoint& MarkerPos);
522
526 void DeselectMarkers();
528
532 void ZoomIn();
533 void ZoomOut();
534 void ZoomReset();
536
537 void EnableActions(bool Enable);
538
539 protected:
540 virtual void mousePressEvent(QMouseEvent* Event) override;
541 virtual void mouseDoubleClickEvent(QMouseEvent* Event) override;
542 virtual void wheelEvent(QWheelEvent* Event) override;
543
544 private:
545 std::vector<MarkerType> Markers;
549
559
560 signals:
561 void mouseClickEvent(QPoint Position);
562
563 private slots:
564 void OnContextMenuRequested(QPoint Position);
565 void OnShowMarkers(bool Checked);
566 void OnRemoveMarkers(bool);
567 void OnSaveMarkers(bool);
568 };
569
573 class QSortingListWidget : public QListWidget
574 {
575 Q_OBJECT
576
577 public:
578 QSortingListWidget(QWidget* parent = nullptr) : QListWidget(parent) {}
580
581 private:
582 virtual void dropEvent(QDropEvent* event) override;
583 };
584
589 class NumericSortingTableWidgetItem : public QTableWidgetItem
590 {
591 public:
598 NumericSortingTableWidgetItem(const QString& text) : QTableWidgetItem(text) {}
599 NumericSortingTableWidgetItem(const QIcon& icon, const QString& text) : QTableWidgetItem(icon, text) {}
601
609 bool operator<(const QTableWidgetItem& Other) const;
610
611 virtual QTableWidgetItem* clone() const override;
612 };
613
617 class NumericOnlyItemDelegate : public QItemDelegate
618 {
619 Q_OBJECT
620
621 public:
629 NumericOnlyItemDelegate(QObject* parent = nullptr, double min = std::numeric_limits<double>::lowest(), double max = std::numeric_limits<double>::max(), int precision = -1)
630 : QItemDelegate(parent), min(min), max(max), precision(precision) {}
631
632 virtual QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const override;
633
634 private:
635 const double min;
636 const double max;
637 const int precision;
638 };
639
644 {
645 Q_OBJECT
646
647 public:
648 DigitalOnlyItemDelegate(QObject* parent = nullptr) : NumericOnlyItemDelegate(parent, 0, 1, 0) {}
649 };
650}
651
Q_DECLARE_METATYPE(Util::MarkerGraphicsView::MarkerType::IDType)
DynExp's core class acts as the interface between the user interface and DynExp's internal data like ...
Definition DynExpCore.h:127
Window class for Qt-based user interfaces belonging to DynExp modules. User interface Qt window class...
Definition Module.h:1079
Implements a QItemDelegate which forces e.g. a QTableWidgetItem's content to be boolean (0 or 1).
Definition QtUtil.h:644
DigitalOnlyItemDelegate(QObject *parent=nullptr)
Definition QtUtil.h:648
Implements a QGraphicsView the user can interact with to insert graphical markers....
Definition QtUtil.h:379
void OnSaveMarkers(bool)
Asks the user for a file name and saves all markers to a CSV file.
Definition QtUtil.cpp:550
void OnContextMenuRequested(QPoint Position)
Shows the context menu at position Position.
Definition QtUtil.cpp:535
virtual void mousePressEvent(QMouseEvent *Event) override
Adds a marker to the mouse pointer position assigning the highest ID amongst all markers in the graph...
Definition QtUtil.cpp:317
QAction * SaveMarkersAction
Definition QtUtil.h:557
bool MarkersChanged
Holds whether the markers have changed by any of the marker operations.
Definition QtUtil.h:547
void ZoomReset()
Resets the zoom.
Definition QtUtil.cpp:522
void DeselectMarkers()
Deselects all selected markers.
Definition QtUtil.cpp:506
void EnableActions(bool Enable)
Definition QtUtil.cpp:527
QAction * ShowMarkersAction
Definition QtUtil.h:555
const std::vector< MarkerType > & GetMarkers() const noexcept
Definition QtUtil.h:448
static constexpr double DeselectedMarkerOpacity
Determines the opacity of a marker which is not selected.
Definition QtUtil.h:383
auto contextMenu() const noexcept
Definition QtUtil.h:446
void setMarkersHidden(bool MarkersHidden)
Hides or shows all markers.
Definition QtUtil.cpp:481
void RenameMarker(const QPoint &MarkerPos, std::string_view NewName)
Assigns a name to the marker at position MarkerPos. Affects MarkersChanged.
Definition QtUtil.cpp:489
void SelectMarker(const QPoint &MarkerPos)
Selects the marker at position MarkerPos.
Definition QtUtil.cpp:500
std::vector< MarkerType > Markers
List of the markers.
Definition QtUtil.h:545
bool HaveMarkersChanged() noexcept
Returns whether a marker operation has changed the stored markers. Resets the flag.
Definition QtUtil.cpp:390
const auto & GetCurrentImagePos() const noexcept
Definition QtUtil.h:449
void RemoveMarker(size_t Index, bool OnlyUserDeletableMarkers=false)
Removes the n-th marker specified by Index. Affects MarkersChanged.
Definition QtUtil.cpp:413
bool MarkersHidden
Determines whether the markers are currently displayed or not.
Definition QtUtil.h:546
QAction * RemoveMarkersAction
Definition QtUtil.h:556
void AddMarker(const QPoint &MarkerPos, const QColor &Color, bool IsUserDeletable=true, MarkerType::IDType ID=-1, std::string Name={})
Adds a marker to the graphics view at position MarkerPos assigning the properties passed as arguments...
Definition QtUtil.cpp:398
void ZoomIn()
Zooms in one step.
Definition QtUtil.cpp:512
static constexpr double ZoomFactor
Determines the magnification of one zoom step.
Definition QtUtil.h:382
void OnShowMarkers(bool Checked)
If Checked is true, all markers are made visible, otherwise they become hidden.
Definition QtUtil.cpp:540
void ZoomOut()
Zooms out one step.
Definition QtUtil.cpp:517
static constexpr double SelectedMarkerOpacity
Determines the opacity of a selected marker.
Definition QtUtil.h:384
virtual void mouseDoubleClickEvent(QMouseEvent *Event) override
Removes the marker at the mouse pointer position if it is user-deletable. Affects MarkersChanged.
Definition QtUtil.cpp:340
QPointF CurrentImagePos
Sample position where the image has been recorded (in nm). Refer to MarkerType::ImagePos.
Definition QtUtil.h:548
void SetCurrentImagePos(const QPointF &Pos)
Definition QtUtil.h:455
void OnRemoveMarkers(bool)
Removes all user-deletable markers. Affects MarkersChanged.
Definition QtUtil.cpp:545
virtual void wheelEvent(QWheelEvent *Event) override
Zooms in or out when Control is pressed on the keyboard at the same time.
Definition QtUtil.cpp:377
void mouseClickEvent(QPoint Position)
void RemoveMarkers(bool OnlyUserDeletableMarkers)
Removes all markers from the graphics view. Affects MarkersChanged.
Definition QtUtil.cpp:464
QAction * EditMarkersAction
Definition QtUtil.h:554
Implements a QItemDelegate which forces e.g. a QTableWidgetItem's content to be numeric (double-preci...
Definition QtUtil.h:618
virtual QWidget * createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override
Definition QtUtil.cpp:591
NumericOnlyItemDelegate(QObject *parent=nullptr, double min=std::numeric_limits< double >::lowest(), double max=std::numeric_limits< double >::max(), int precision=-1)
Constructs a NumericOnlyItemDelegate and sets constraints on the numeric values it considers valid.
Definition QtUtil.h:629
Implements a QTableWidgetItem which contains numeric content such that table widget items can be nume...
Definition QtUtil.h:590
bool operator<(const QTableWidgetItem &Other) const
Compares the content of this table widget item with the content of another table widget item by conve...
Definition QtUtil.cpp:581
NumericSortingTableWidgetItem(const QString &text)
Definition QtUtil.h:598
NumericSortingTableWidgetItem(const QIcon &icon, const QString &text)
Definition QtUtil.h:599
virtual QTableWidgetItem * clone() const override
Definition QtUtil.cpp:586
Thrown when an argument passed to a function exceeds the valid range.
Definition Exception.h:211
Implements a QListWidget that sorts its items after inserting an item by drag & drop.
Definition QtUtil.h:574
virtual void dropEvent(QDropEvent *event) override
Definition QtUtil.cpp:574
QSortingListWidget(QWidget *parent=nullptr)
Definition QtUtil.h:578
Implements a QObject belonging to a hardware adapter (derived from DynExp::HardwareAdapterBase) that ...
Definition QtUtil.h:327
static const DynExp::DynExpCore & GetDynExpCore(const DynExp::DynExpCore *DynExpCore=nullptr)
Returns the application's DynExp::DynExpCore instance which is globally set in constructor DynExp::Dy...
Definition QtUtil.cpp:281
QWorker()=default
friend class DynExp::DynExpCore
Definition QtUtil.h:330
void MoveToWorkerThread(DynExp::ItemIDType ID)
Moves the instance to DynExpCore's worker thread. Do not call from constructor since derived classes ...
Definition QtUtil.cpp:272
std::weak_ptr< const DynExp::HardwareAdapterBase > OwnerPtrType
Definition QtUtil.h:352
~QWorker()=default
bool HasBeenMovedToWorkerThread
Indicates whether the worker has already been moved to the worker thread.
Definition QtUtil.h:370
void SetOwner(OwnerPtrType Owner) noexcept
Sets the hardware adapter owning this worker instance.
Definition QtUtil.h:368
auto GetOwner() const noexcept
Returns this worker instance's owner.
Definition QtUtil.h:349
OwnerPtrType Owner
Pointer to the hardware adapter owning this instance.
Definition QtUtil.h:371
DynExp's main namespace contains the implementation of DynExp including classes to manage resources (...
size_t ItemIDType
ID type of objects/items managed by DynExp.
DynExp's Util namespace contains commonly used functions and templates as well as extensions to Qt an...
std::vector< TextType > TextListType
List type of text-type parameters.
Definition QtUtil.h:29
std::string GetTFromDOMAttribute(const QDomElement &Element, const QString &AttributeName)
Definition QtUtil.cpp:108
ImageHistogramType ConvertRGBToIntensityHistogram(const ImageRGBHistogramType &RGBHistogram)
Computes an intensity (grayscale) histogram from a RGB histogram.
Definition QtUtil.cpp:204
bool SaveToFile(const QString &Filename, std::string_view Text)
Saves a std::string_view to a file (using QFile). Creates a new file or truncates an existing file's ...
Definition QtUtil.cpp:236
QDomElement GetSingleChildDOMElement(const QDomElement &Parent, const QString &ChildTagName)
Behaves like GetSingleChildDOMNode() but returns the node converted to a DOM element.
Definition QtUtil.cpp:62
std::string GetTFromDOMElement(const QDomElement &Parent, const QString &ChildTagName)
Definition QtUtil.cpp:82
size_t TextListIndexType
List index type of Util::TextListType.
Definition QtUtil.h:30
std::string GetStringFromDOMElement(const QDomElement &Parent, const QString &ChildTagName)
Behaves like GetSingleChildDOMElement() but returns the text from a DOM element.
Definition QtUtil.cpp:73
const QLocale & GetDefaultQtLocale()
Returns the default locale properties to be assigned to Qt widgets.
Definition QtUtil.cpp:12
std::string_view TextRefType
Reference-to-string type of text-type parameters (DynExp::ParamsBase::Param)
Definition QtUtil.h:28
std::vector< QDomNode > GetChildDOMNodes(const QDomElement &Parent, const QString &ChildTagName)
Finds child nodes with a certain tag name.
Definition QtUtil.cpp:19
QPolygonF MakeCrossPolygon(QPointF Center, unsigned int ArmLength)
Returns a QPolygonF representing a cross-style marker.
Definition QtUtil.cpp:216
QImage QImageFromBlobData(BlobDataType &&BlobData, int Width, int Height, int BytesPerLine, QImage::Format Format)
Converts raw pixel data stored in a Util::BlobDataType object to a QImage transfering the ownership o...
Definition QtUtil.cpp:153
std::array< unsigned long long, 256 > ImageHistogramType
Alias which represents a histogram as a std::array with 256 numeric bins. The lowest (highest) index ...
Definition QtUtil.h:244
QString PromptOpenFilePath(QWidget *Parent, const QString &Title, const QString &DefaultSuffix, const QString &NameFilter, const QString &InitialDirectory)
Opens a file dialog to ask the user to select a single existing file.
Definition QtUtil.cpp:113
ImageHistogramType ComputeIntensityHistogram(const QImage &Image)
Computes an intensity (grayscale) histogram from a QImage object.
Definition QtUtil.cpp:171
void ActivateWindow(QWidget &Widget)
Renders a window active and brings it to the front.
Definition QtUtil.cpp:229
auto QtEnumToTextValueList(unsigned short SkipEntriesFront=0, unsigned short SkipEntriesEnd=0, unsigned short SkipCharsFront=0, unsigned short SkipCharsEnd=0)
Returns a TextValueListType containing entries which reflect the items (names and values) of an enume...
Definition QtUtil.h:55
std::string ReadFromFile(const QString &Filename)
Reads the entire content from a text file.
Definition QtUtil.cpp:250
QDomAttr GetDOMAttribute(const QDomElement &Element, const QString &AttributeName)
Extracts an attribute from a DOM element.
Definition QtUtil.cpp:87
QDomNode GetSingleChildDOMNode(const QDomElement &Parent, const QString &ChildTagName)
Finds a single child node with a certain tag name.
Definition QtUtil.cpp:36
std::string TextType
String type of text-type parameters (DynExp::ParamsBase::Param)
Definition QtUtil.h:27
std::tuple< ImageHistogramType, ImageHistogramType, ImageHistogramType > ImageRGBHistogramType
Alias which represents a RGB histogram as a std::tuple of three ImageHistogramType elements....
Definition QtUtil.h:250
std::vector< std::pair< TextType, ValueType > > TextValueListType
Type of a list containing key-value pairs where key is a text of type Util::TextType.
Definition QtUtil.h:37
QString PromptSaveFilePath(QWidget *Parent, const QString &Title, const QString &DefaultSuffix, const QString &NameFilter, const QString &InitialDirectory)
Works as PromptOpenFilePath() but asks the user to select a single file which does not need to exist.
Definition QtUtil.cpp:128
ImageRGBHistogramType ComputeRGBHistogram(const QImage &Image)
Computes a RGB histogram from a QImage object.
Definition QtUtil.cpp:186
QString PromptSaveFilePathModule(DynExp::QModuleWidget *Parent, const QString &Title, const QString &DefaultSuffix, const QString &NameFilter)
Works as PromptOpenFilePath() but asks the user to select a single file which does not need to exist....
Definition QtUtil.cpp:143
std::string GetStringFromDOMAttribute(const QDomElement &Element, const QString &AttributeName)
Behaves like GetDOMAttribute() but returns the text from the attribute.
Definition QtUtil.cpp:99
Accumulates include statements to provide a precompiled header.
Data associated with one marker.
Definition QtUtil.h:391
constexpr std::string_view GetName() const noexcept
Definition QtUtil.h:413
constexpr const auto GetMarker() const noexcept
Definition QtUtil.h:409
IDType ID
ID of the marker to identify it amongst other markers in the same graphics view.
Definition QtUtil.h:431
QPointF ImagePos
Position in nm (e.g. of a sample under a microscope) where the associated image the marker belongs to...
Definition QtUtil.h:433
bool UserDeletable
Determines whether the user can interact with this marker to delete it.
Definition QtUtil.h:430
constexpr auto GetID() const noexcept
Definition QtUtil.h:412
QPoint MarkerPos
Position of the marker within the graphics view in pixels.
Definition QtUtil.h:429
QGraphicsPolygonItem * Marker
Qt polygon object to draw the marker onto the graphics view.
Definition QtUtil.h:428
constexpr const auto & GetMarkerPos() const noexcept
Definition QtUtil.h:410
constexpr MarkerType(QGraphicsPolygonItem *Marker, const QPoint &MarkerPos, bool IsUserDeletable=true, IDType ID=-1, const QPointF &ImagePos={}) noexcept
Constructs a marker assigning the properties passed as arguments. Name will stay empty.
Definition QtUtil.h:402
void SetName(std::string_view NewName)
Definition QtUtil.cpp:291
constexpr const auto & GetImagePos() const noexcept
Definition QtUtil.h:414
constexpr bool IsUserDeletable() const noexcept
Definition QtUtil.h:411
std::string Name
Name of the marker to describe it.
Definition QtUtil.h:432
constexpr auto GetMarker() noexcept
Definition QtUtil.h:408