replace 4 spaces by a tab

This commit is contained in:
Martin Marmsoler
2020-10-17 20:25:30 +02:00
parent f3097fc537
commit 12e301b887
62 changed files with 18980 additions and 18980 deletions

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef QETGRAPHICSHANDLERITEM_H
#define QETGRAPHICSHANDLERITEM_H
@@ -22,43 +22,43 @@
#include <QPen>
/**
@brief The QetGraphicsHandlerItem class
This graphics item represents a point,
destined to be used as an handler,
for modifie the geometrie of a another graphics item (like shapes).
The graphics item to be modified,
must call "installSceneEventFilter"
of this item with itself for argument,.
The ghraphics item to be modified,
need to reimplement "sceneEventFilter"
for create the modification behavior.
@brief The QetGraphicsHandlerItem class
This graphics item represents a point,
destined to be used as an handler,
for modifie the geometrie of a another graphics item (like shapes).
The graphics item to be modified,
must call "installSceneEventFilter"
of this item with itself for argument,.
The ghraphics item to be modified,
need to reimplement "sceneEventFilter"
for create the modification behavior.
*/
class QetGraphicsHandlerItem : public QGraphicsItem
{
public:
QetGraphicsHandlerItem(qreal size = 10);
QRectF boundingRect() const override;
public:
QetGraphicsHandlerItem(qreal size = 10);
QRectF boundingRect() const override;
enum { Type = UserType + 1200};
int type() const override {return Type;}
enum { Type = UserType + 1200};
int type() const override {return Type;}
void setColor(QColor color);
void setColor(QColor color);
protected:
void paint(QPainter *painter,
const QStyleOptionGraphicsItem *option,
QWidget *widget) override;
protected:
void paint(QPainter *painter,
const QStyleOptionGraphicsItem *option,
QWidget *widget) override;
private:
QRectF m_handler_rect,
m_br;
qreal m_size;
QColor m_color{Qt::black};
QPen m_pen;
private:
QRectF m_handler_rect,
m_br;
qreal m_size;
QColor m_color{Qt::black};
QPen m_pen;
public:
static QVector<QetGraphicsHandlerItem *> handlerForPoint(
const QVector<QPointF> &points, int size = 10);
public:
static QVector<QetGraphicsHandlerItem *> handlerForPoint(
const QVector<QPointF> &points, int size = 10);
};
#endif // QETGRAPHICSHANDLERITEM_H

View File

@@ -1,192 +1,192 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#include "borderproperties.h"
/**
@brief BorderProperties::BorderProperties
constructor
Initializes a BorderProperties object with default properties
@brief BorderProperties::BorderProperties
constructor
Initializes a BorderProperties object with default properties
Initializes a BorderProperties object
with the following default properties:
- 17 columns of 60.0 px wide by 20.0px high
- 8 lines of 80.0 px high by 20.0px wide
Initializes a BorderProperties object
with the following default properties:
- 17 columns of 60.0 px wide by 20.0px high
- 8 lines of 80.0 px high by 20.0px wide
\~French Initialise un objet BorderProperties avec les proprietes par
defaut suivantes :
- 17 colonnes affichees de 60.0 px de large pour 20.0px de haut
- 8 lignes affichees de 80.0 px de haut pour 20.0px de large
\~French Initialise un objet BorderProperties avec les proprietes par
defaut suivantes :
- 17 colonnes affichees de 60.0 px de large pour 20.0px de haut
- 8 lignes affichees de 80.0 px de haut pour 20.0px de large
*/
BorderProperties::BorderProperties()
{
}
/**
@brief BorderProperties::~BorderProperties
destructor
@brief BorderProperties::~BorderProperties
destructor
*/
BorderProperties::~BorderProperties()
{
}
/**
@brief BorderProperties::operator ==
@brief BorderProperties::operator ==
\~ @param bp : Other BorderProperties container/class.
\~French Autre conteneur BorderProperties
\~ @return True if it and this container are identical, false otherwise.
\~French True si ip et ce conteneur sont identiques, false sinon
\~ @param bp : Other BorderProperties container/class.
\~French Autre conteneur BorderProperties
\~ @return True if it and this container are identical, false otherwise.
\~French True si ip et ce conteneur sont identiques, false sinon
*/
bool BorderProperties::operator==(const BorderProperties &bp) {
return(
bp.columns_count == columns_count &&\
bp.columns_width == columns_width &&\
bp.columns_header_height == columns_header_height &&\
bp.display_columns == display_columns &&\
bp.rows_count == rows_count &&\
bp.rows_height == rows_height &&\
bp.rows_header_width == rows_header_width &&\
bp.display_rows == display_rows
);
return(
bp.columns_count == columns_count &&\
bp.columns_width == columns_width &&\
bp.columns_header_height == columns_header_height &&\
bp.display_columns == display_columns &&\
bp.rows_count == rows_count &&\
bp.rows_height == rows_height &&\
bp.rows_header_width == rows_header_width &&\
bp.display_rows == display_rows
);
}
/**
@brief BorderProperties::operator !=
@brief BorderProperties::operator !=
\~ @param bp :
Other BorderProperties container/class.
\~French Autre conteneur BorderProperties
\~ @return
False if it and this container are identical, true otherwise.
\~French False si bp et ce conteneur sont identiques, true sinon
\~ @param bp :
Other BorderProperties container/class.
\~French Autre conteneur BorderProperties
\~ @return
False if it and this container are identical, true otherwise.
\~French False si bp et ce conteneur sont identiques, true sinon
*/
bool BorderProperties::operator!=(const BorderProperties &bp) {
return(!(*this == bp));
return(!(*this == bp));
}
/**
@brief BorderProperties::toXml
Exports dimensions as XML attributes added to element e.
\~French Exporte les dimensions sous formes d'attributs XML ajoutes a l'element e.
@brief BorderProperties::toXml
Exports dimensions as XML attributes added to element e.
\~French Exporte les dimensions sous formes d'attributs XML ajoutes a l'element e.
\~ @param e :
XML element to which attributes will be added
\~French Element XML auquel seront ajoutes des attributs
\~ @param e :
XML element to which attributes will be added
\~French Element XML auquel seront ajoutes des attributs
*/
QDomElement BorderProperties::toXml(QDomDocument &dom_doc) const {
QDomElement e = dom_doc.createElement("border");
QDomElement e = dom_doc.createElement("border");
e.appendChild(createXmlProperty(dom_doc, "cols", columns_count));
e.appendChild(createXmlProperty(dom_doc, "colsize", columns_width));
e.appendChild(createXmlProperty(dom_doc, "rows", rows_count));
e.appendChild(createXmlProperty(dom_doc, "rowsize", rows_height));
e.appendChild(createXmlProperty(dom_doc, "displayrows", display_rows));
e.appendChild(createXmlProperty(dom_doc, "displaycols", display_columns));
e.appendChild(createXmlProperty(dom_doc, "cols", columns_count));
e.appendChild(createXmlProperty(dom_doc, "colsize", columns_width));
e.appendChild(createXmlProperty(dom_doc, "rows", rows_count));
e.appendChild(createXmlProperty(dom_doc, "rowsize", rows_height));
e.appendChild(createXmlProperty(dom_doc, "displayrows", display_rows));
e.appendChild(createXmlProperty(dom_doc, "displaycols", display_columns));
return e;
return e;
}
/**RETURNS True
@brief BorderProperties::fromXml
Import dimensions from XML attributes of element e
\~French Importe les dimensions a partir des attributs XML de l'element e
@brief BorderProperties::fromXml
Import dimensions from XML attributes of element e
\~French Importe les dimensions a partir des attributs XML de l'element e
\~ @param e :
XML element whose attributes will be read
\~French Element XML dont les attributs seront lus
\~ @param e :
XML element whose attributes will be read
\~French Element XML dont les attributs seront lus
*/
bool BorderProperties::fromXml(const QDomElement &e) {
if (propertyInteger(e, "cols", &columns_count) == PropertyFlags::NoValidConversion ||
propertyDouble(e, "colsize", &columns_width) == PropertyFlags::NoValidConversion ||
propertyInteger(e, "rows", &rows_count) == PropertyFlags::NoValidConversion ||
propertyDouble(e, "rowsize", &rows_height) == PropertyFlags::NoValidConversion ||
propertyBool(e, "displaycols", &display_columns) == PropertyFlags::NoValidConversion ||
propertyBool(e, "displayrows", &display_rows) == PropertyFlags::NoValidConversion)
return false;
if (propertyInteger(e, "cols", &columns_count) == PropertyFlags::NoValidConversion ||
propertyDouble(e, "colsize", &columns_width) == PropertyFlags::NoValidConversion ||
propertyInteger(e, "rows", &rows_count) == PropertyFlags::NoValidConversion ||
propertyDouble(e, "rowsize", &rows_height) == PropertyFlags::NoValidConversion ||
propertyBool(e, "displaycols", &display_columns) == PropertyFlags::NoValidConversion ||
propertyBool(e, "displayrows", &display_rows) == PropertyFlags::NoValidConversion)
return false;
return true;
return true;
}
bool BorderProperties::valideXml(QDomElement& e) {
if (propertyInteger(e, "cols") == PropertyFlags::Success ||
propertyDouble(e, "colsize") == PropertyFlags::Success ||
propertyInteger(e, "rows") == PropertyFlags::Success ||
propertyDouble(e, "rowsize") == PropertyFlags::Success ||
propertyBool(e, "displaycols") == PropertyFlags::Success ||
propertyBool(e, "displayrows") == PropertyFlags::Success)
return true;
return false;
if (propertyInteger(e, "cols") == PropertyFlags::Success ||
propertyDouble(e, "colsize") == PropertyFlags::Success ||
propertyInteger(e, "rows") == PropertyFlags::Success ||
propertyDouble(e, "rowsize") == PropertyFlags::Success ||
propertyBool(e, "displaycols") == PropertyFlags::Success ||
propertyBool(e, "displayrows") == PropertyFlags::Success)
return true;
return false;
}
/**
@brief BorderProperties::toSettings
Export dimensions in a QSettings object.
\~French Exporte les dimensions dans une configuration.
@brief BorderProperties::toSettings
Export dimensions in a QSettings object.
\~French Exporte les dimensions dans une configuration.
\~ @param settings :
QSettings object to write
\~French Parametres a ecrire
\~ @param prefix :
prefix to be added before the names of the parameters
\~French prefixe a ajouter devant les noms des parametres
\~ @param settings :
QSettings object to write
\~French Parametres a ecrire
\~ @param prefix :
prefix to be added before the names of the parameters
\~French prefixe a ajouter devant les noms des parametres
*/
void BorderProperties::toSettings(QSettings &settings, const QString &prefix) const
{
settings.setValue(prefix + "cols", columns_count);
settings.setValue(prefix + "colsize", columns_width);
settings.setValue(prefix + "displaycols", display_columns);
settings.setValue(prefix + "rows", rows_count);
settings.setValue(prefix + "rowsize", rows_height);
settings.setValue(prefix + "displayrows", display_rows);
settings.setValue(prefix + "cols", columns_count);
settings.setValue(prefix + "colsize", columns_width);
settings.setValue(prefix + "displaycols", display_columns);
settings.setValue(prefix + "rows", rows_count);
settings.setValue(prefix + "rowsize", rows_height);
settings.setValue(prefix + "displayrows", display_rows);
}
/**
@brief BorderProperties::fromSettings
Import dimensions from a QSettings object.
\~French Importe les dimensions depuis une configuration.
\~ @param settings : QSettings object to read
\~French Parametres a lire
\~ @param prefix : prefix to be added before the names of the parameters
\~French prefixe a ajouter devant les noms des parametres
@brief BorderProperties::fromSettings
Import dimensions from a QSettings object.
\~French Importe les dimensions depuis une configuration.
\~ @param settings : QSettings object to read
\~French Parametres a lire
\~ @param prefix : prefix to be added before the names of the parameters
\~French prefixe a ajouter devant les noms des parametres
*/
void BorderProperties::fromSettings(const QSettings &settings, const QString &prefix) {
columns_count = settings.value(prefix + "cols", columns_count).toInt();
columns_width = qRound(settings.value(prefix + "colsize", columns_width).toDouble());
display_columns = settings.value(prefix + "displaycols", display_columns).toBool();
columns_count = settings.value(prefix + "cols", columns_count).toInt();
columns_width = qRound(settings.value(prefix + "colsize", columns_width).toDouble());
display_columns = settings.value(prefix + "displaycols", display_columns).toBool();
rows_count = settings.value(prefix + "rows", rows_count).toInt();
rows_height = qRound(settings.value(prefix + "rowsize", rows_height).toDouble());
display_rows = settings.value(prefix + "displayrows", display_rows).toBool();
rows_count = settings.value(prefix + "rows", rows_count).toInt();
rows_height = qRound(settings.value(prefix + "rowsize", rows_height).toDouble());
display_rows = settings.value(prefix + "displayrows", display_rows).toBool();
}
/**
@brief BorderProperties::defaultProperties
@return the default properties stored in the setting file
@brief BorderProperties::defaultProperties
@return the default properties stored in the setting file
*/
BorderProperties BorderProperties::defaultProperties()
{
QSettings settings;
QSettings settings;
BorderProperties def;
def.fromSettings(settings, "diagrameditor/default");
BorderProperties def;
def.fromSettings(settings, "diagrameditor/default");
return(def);
return(def);
}

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef BORDER_PROPERTIES_H
#define BORDER_PROPERTIES_H
@@ -23,37 +23,37 @@
#include "propertiesinterface.h"
/**
@brief The BorderProperties class
This class is a container for dimensions and display properties of a
diagram.
@remark Attributes are public
@brief The BorderProperties class
This class is a container for dimensions and display properties of a
diagram.
@remark Attributes are public
*/
class BorderProperties : public PropertiesInterface {
public:
// constructor, destructor, operators
BorderProperties();
virtual ~BorderProperties();
public:
// constructor, destructor, operators
BorderProperties();
virtual ~BorderProperties();
bool operator==(const BorderProperties &);
bool operator!=(const BorderProperties &);
bool operator==(const BorderProperties &);
bool operator!=(const BorderProperties &);
QDomElement toXml(QDomDocument &dom_doc) const override;
bool fromXml(const QDomElement &) override;
static bool valideXml(QDomElement& e);
void toSettings(QSettings &, const QString & = QString()) const;
void fromSettings(QSettings &, const QString & = QString());
QDomElement toXml(QDomDocument &dom_doc) const override;
bool fromXml(const QDomElement &) override;
static bool valideXml(QDomElement& e);
void toSettings(QSettings &, const QString & = QString()) const;
void fromSettings(QSettings &, const QString & = QString());
static BorderProperties defaultProperties();
static BorderProperties defaultProperties();
// attributes
int columns_count{17}; ///< Columns count
qreal columns_width{60.0}; ///< Columns width
qreal columns_header_height{20.0}; ///< Column headers height
bool display_columns{true}; ///< Whether to display column headers
// attributes
int columns_count{17}; ///< Columns count
qreal columns_width{60.0}; ///< Columns width
qreal columns_header_height{20.0}; ///< Column headers height
bool display_columns{true}; ///< Whether to display column headers
int rows_count{8}; ///< Rows count
qreal rows_height{80.0}; ///< Rows height
qreal rows_header_width{20.0}; ///< Row headers width
bool display_rows{true}; ///< Whether to display row headers
int rows_count{8}; ///< Rows count
qreal rows_height{80.0}; ///< Rows height
qreal rows_header_width{20.0}; ///< Row headers width
bool display_rows{true}; ///< Whether to display row headers
};
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef BORDERTITLEBLOCK_H
#define BORDERTITLEBLOCK_H
@@ -29,266 +29,266 @@ class DiagramPosition;
class TitleBlockTemplate;
class TitleBlockTemplateRenderer;
/**
@brief The BorderTitleBlock class
This class represents the border and the titleblock which frame a
particular electric diagram.
@brief The BorderTitleBlock class
This class represents the border and the titleblock which frame a
particular electric diagram.
*/
class BorderTitleBlock : public QObject
{
Q_OBJECT
Q_OBJECT
public:
BorderTitleBlock(QObject * = nullptr);
~BorderTitleBlock() override;
public:
BorderTitleBlock(QObject * = nullptr);
~BorderTitleBlock() override;
private:
BorderTitleBlock(const BorderTitleBlock &);
private:
BorderTitleBlock(const BorderTitleBlock &);
//METHODS
public:
void draw(QPainter *painter);
void drawDxf(QString &, int);
//METHODS
public:
void draw(QPainter *painter);
void drawDxf(QString &, int);
//METHODS TO GET DIMENSION
//COLUMNS
/// @return the number of columns
int columnsCount() const { return(columns_count_); }
/// @return the columns width, in pixels
qreal columnsWidth() const { return(columns_width_); }
/// @return the total width of all columns, headers excluded
qreal columnsTotalWidth() const {
return(columns_count_ * columns_width_); }
/// @return the column headers height, in pixels
qreal columnsHeaderHeight() const {
return(columns_header_height_); }
//METHODS TO GET DIMENSION
//COLUMNS
/// @return the number of columns
int columnsCount() const { return(columns_count_); }
/// @return the columns width, in pixels
qreal columnsWidth() const { return(columns_width_); }
/// @return the total width of all columns, headers excluded
qreal columnsTotalWidth() const {
return(columns_count_ * columns_width_); }
/// @return the column headers height, in pixels
qreal columnsHeaderHeight() const {
return(columns_header_height_); }
//ROWS
/// @return the number of rows
int rowsCount() const { return(rows_count_); }
/// @return the rows height, in pixels
qreal rowsHeight() const { return(rows_height_); }
/// @return the total height of all rows, headers excluded
qreal rowsTotalHeight() const {
return(rows_count_ * rows_height_); }
/// @return la rows header width, in pixels
qreal rowsHeaderWidth() const { return(rows_header_width_); }
//ROWS
/// @return the number of rows
int rowsCount() const { return(rows_count_); }
/// @return the rows height, in pixels
qreal rowsHeight() const { return(rows_height_); }
/// @return the total height of all rows, headers excluded
qreal rowsTotalHeight() const {
return(rows_count_ * rows_height_); }
/// @return la rows header width, in pixels
qreal rowsHeaderWidth() const { return(rows_header_width_); }
// border - title block = diagram
/**
@brief diagramWidth
@return the diagram width,
i.e. the width of the border without title block
*/
qreal diagramWidth() const
// border - title block = diagram
/**
@brief diagramWidth
@return the diagram width,
i.e. the width of the border without title block
*/
qreal diagramWidth() const
{
return(columnsTotalWidth() + rowsHeaderWidth()); }
/**
@brief diagramHeight
@return the diagram height,
i.e. the height of the border without title block
*/
qreal diagramHeight() const
return(columnsTotalWidth() + rowsHeaderWidth()); }
/**
@brief diagramHeight
@return the diagram height,
i.e. the height of the border without title block
*/
qreal diagramHeight() const
{
return(rowsTotalHeight() + columnsHeaderHeight()); }
return(rowsTotalHeight() + columnsHeaderHeight()); }
QRectF titleBlockRect () const;
QRectF titleBlockRect () const;
DiagramContext titleblockInformation() const;
private:
QRectF titleBlockRectForQPainter () const;
DiagramContext titleblockInformation() const;
private:
QRectF titleBlockRectForQPainter () const;
public:
QRectF borderAndTitleBlockRect () const;
QRectF columnsRect () const;
QRectF rowsRect () const;
QRectF outsideBorderRect() const;
QRectF insideBorderRect() const;
public:
QRectF borderAndTitleBlockRect () const;
QRectF columnsRect () const;
QRectF rowsRect () const;
QRectF outsideBorderRect() const;
QRectF insideBorderRect() const;
// methods to get title block basic data
/// @return the value of the title block "Author" field
QString author() const { return(btb_author_); }
/// @return the value of the title block "Date" field
QDate date() const { return(btb_date_); }
/// @return the value of the title block "Title" field
QString title() const { return(btb_title_); }
/// @return the value of the title block "Folio" field
QString folio() const { return(btb_folio_); }
/// @return the value of the title block "Folio" field as displayed
QString finalfolio() const { return(btb_final_folio_); }
/// @return the value of the title block "Plant" field
QString plant() const { return(btb_plant_); }
/// @return the value of the title block "Locmach" field
QString locmach() const { return(btb_locmach_); }
/// @return the value of the revision index block "Folio" field
QString indexrev() const { return(btb_indexrev_); }
/// @return the value of the title block "File" field
QString fileName() const { return(btb_filename_); }
/// @return the value of the title block Additional Fields
QString version() const { return(btb_version_); }
/// @return the value of the title block Additional Fields
DiagramContext additionalFields() const {
return (additional_fields_); }
/// @return the value of the title block
QString autoPageNum() const { return(btb_auto_page_num_); }
/// @return the value of the total number of folios
int folioTotal() const { return(folio_total_);}
// methods to get title block basic data
/// @return the value of the title block "Author" field
QString author() const { return(btb_author_); }
/// @return the value of the title block "Date" field
QDate date() const { return(btb_date_); }
/// @return the value of the title block "Title" field
QString title() const { return(btb_title_); }
/// @return the value of the title block "Folio" field
QString folio() const { return(btb_folio_); }
/// @return the value of the title block "Folio" field as displayed
QString finalfolio() const { return(btb_final_folio_); }
/// @return the value of the title block "Plant" field
QString plant() const { return(btb_plant_); }
/// @return the value of the title block "Locmach" field
QString locmach() const { return(btb_locmach_); }
/// @return the value of the revision index block "Folio" field
QString indexrev() const { return(btb_indexrev_); }
/// @return the value of the title block "File" field
QString fileName() const { return(btb_filename_); }
/// @return the value of the title block Additional Fields
QString version() const { return(btb_version_); }
/// @return the value of the title block Additional Fields
DiagramContext additionalFields() const {
return (additional_fields_); }
/// @return the value of the title block
QString autoPageNum() const { return(btb_auto_page_num_); }
/// @return the value of the total number of folios
int folioTotal() const { return(folio_total_);}
// methods to get display options
/// @return true si le cartouche est affiche, false sinon
bool titleBlockIsDisplayed() const {
return(display_titleblock_); }
/// @return true si les entetes des colonnes sont affiches,
/// false sinon
bool columnsAreDisplayed() const { return(display_columns_); }
/// @return true si les entetes des lignes sont affiches,
/// false sinon
bool rowsAreDisplayed() const { return(display_rows_); }
/// @return true si la bordure est affichee, false sinon
bool borderIsDisplayed() const { return(display_border_); }
// methods to get display options
/// @return true si le cartouche est affiche, false sinon
bool titleBlockIsDisplayed() const {
return(display_titleblock_); }
/// @return true si les entetes des colonnes sont affiches,
/// false sinon
bool columnsAreDisplayed() const { return(display_columns_); }
/// @return true si les entetes des lignes sont affiches,
/// false sinon
bool rowsAreDisplayed() const { return(display_rows_); }
/// @return true si la bordure est affichee, false sinon
bool borderIsDisplayed() const { return(display_border_); }
// methods to set dimensions
void setColumnsCount(int);
void setRowsCount(int);
void setColumnsWidth(const qreal &);
void setRowsHeight(const qreal &);
void setColumnsHeaderHeight(const qreal &);
void setRowsHeaderWidth(const qreal &);
void setDiagramHeight(const qreal &);
// methods to set dimensions
void setColumnsCount(int);
void setRowsCount(int);
void setColumnsWidth(const qreal &);
void setRowsHeight(const qreal &);
void setColumnsHeaderHeight(const qreal &);
void setRowsHeaderWidth(const qreal &);
void setDiagramHeight(const qreal &);
DiagramPosition convertPosition(const QPointF &);
DiagramPosition convertPosition(const QPointF &);
// methods to set title block basic data
void setAuthor(const QString &author);
void setDate(const QDate &date);
void setTitle(const QString &title);
void setFolio(const QString &folio);
void setFolioData(int, int, const QString& = nullptr,
const DiagramContext & = DiagramContext());
void setPlant(const QString &plant);
void setLocMach(const QString &locmach);
void setIndicerev(const QString &indexrev);
void setFileName(const QString &filename);
void setVersion(const QString &version);
void setAutoPageNum(const QString &auto_page_num);
void setPreviousFolioNum(const QString &previous);
void setNextFolioNum(const QString &next);
// methods to set title block basic data
void setAuthor(const QString &author);
void setDate(const QDate &date);
void setTitle(const QString &title);
void setFolio(const QString &folio);
void setFolioData(int, int, const QString& = nullptr,
const DiagramContext & = DiagramContext());
void setPlant(const QString &plant);
void setLocMach(const QString &locmach);
void setIndicerev(const QString &indexrev);
void setFileName(const QString &filename);
void setVersion(const QString &version);
void setAutoPageNum(const QString &auto_page_num);
void setPreviousFolioNum(const QString &previous);
void setNextFolioNum(const QString &next);
void titleBlockToXml(QDomElement &doc);
void titleBlockFromXml(const QDomElement &);
void borderToXml(QDomElement &);
void borderFromXml(const QDomElement &);
void titleBlockToXml(QDomElement &doc);
void titleBlockFromXml(const QDomElement &);
void borderToXml(QDomElement &);
void borderFromXml(const QDomElement &);
TitleBlockProperties exportTitleBlock();
void importTitleBlock(const TitleBlockProperties &);
BorderProperties exportBorder();
void importBorder(const BorderProperties &);
TitleBlockProperties exportTitleBlock();
void importTitleBlock(const TitleBlockProperties &);
BorderProperties exportBorder();
void importBorder(const BorderProperties &);
const TitleBlockTemplate *titleBlockTemplate();
void setTitleBlockTemplate(const TitleBlockTemplate *);
QString titleBlockTemplateName() const;
const TitleBlockTemplate *titleBlockTemplate();
void setTitleBlockTemplate(const TitleBlockTemplate *);
QString titleBlockTemplateName() const;
public slots:
void titleBlockTemplateChanged(const QString &);
void titleBlockTemplateRemoved(
const QString &,
const TitleBlockTemplate * = nullptr);
public slots:
void titleBlockTemplateChanged(const QString &);
void titleBlockTemplateRemoved(
const QString &,
const TitleBlockTemplate * = nullptr);
// methods to set display options
void displayTitleBlock(bool);
void displayColumns(bool);
void displayRows(bool);
void displayBorder(bool);
void slot_setAutoPageNum (QString);
// methods to set display options
void displayTitleBlock(bool);
void displayColumns(bool);
void displayRows(bool);
void displayBorder(bool);
void slot_setAutoPageNum (QString);
private:
void updateRectangles();
void updateDiagramContextForTitleBlock(
const DiagramContext & = DiagramContext());
QString incrementLetters(const QString &);
private:
void updateRectangles();
void updateDiagramContextForTitleBlock(
const DiagramContext & = DiagramContext());
QString incrementLetters(const QString &);
signals:
/**
@brief borderChanged
Signal emitted after the border has changed
@param old_border Former border
@param new_border New border
*/
void borderChanged(QRectF old_border, QRectF new_border);
/**
@brief displayChanged
Signal emitted after display options have changed
*/
void displayChanged();
/**
@brief diagramTitleChanged
Signal emitted after the title has changed
*/
void diagramTitleChanged(const QString &);
/**
@brief titleBlockFolioChanged
Signal emitted after Folio has changed
*/
void titleBlockFolioChanged(const QString &);
/**
@brief needFolioData
Signal emitted when the title block
requires its data to be updated
in order to generate the folio field.
*/
void needFolioData();
/**
@brief needTitleBlockTemplate
Signal emitted when this object needs to
set a specific title block template.
This object cannot handle the job
since it does not know of its parent project.
*/
void needTitleBlockTemplate(const QString &);
signals:
/**
@brief borderChanged
Signal emitted after the border has changed
@param old_border Former border
@param new_border New border
*/
void borderChanged(QRectF old_border, QRectF new_border);
/**
@brief displayChanged
Signal emitted after display options have changed
*/
void displayChanged();
/**
@brief diagramTitleChanged
Signal emitted after the title has changed
*/
void diagramTitleChanged(const QString &);
/**
@brief titleBlockFolioChanged
Signal emitted after Folio has changed
*/
void titleBlockFolioChanged(const QString &);
/**
@brief needFolioData
Signal emitted when the title block
requires its data to be updated
in order to generate the folio field.
*/
void needFolioData();
/**
@brief needTitleBlockTemplate
Signal emitted when this object needs to
set a specific title block template.
This object cannot handle the job
since it does not know of its parent project.
*/
void needTitleBlockTemplate(const QString &);
// attributes
private:
// titleblock basic data
QString btb_author_; ///< titleblock author
QDate btb_date_; ///< titleblock date
QString btb_title_; ///< titleblock title
QString btb_folio_; ///< titleblock folio
QString btb_plant_; ///< titleblock plant
QString btb_locmach_; ///< titleblock locmach
QString btb_indexrev_; ///< titleblock index rev
QString btb_final_folio_; ///< titleblock final folio
QString btb_auto_page_num_; ///< titleblock auto page num
int folio_index_; ///< titleblock index
int folio_total_; ///< titleblock total
QString btb_filename_; ///< titleblock filename
QString btb_version_; ///< titleblock version
/// titleblock additional fields
DiagramContext additional_fields_;
Qt::Edge m_edge; ///< titleblock edge
QString m_next_folio_num; ///< titleblock next folio num
QString m_previous_folio_num; ///< titleblock previous folio num
// attributes
private:
// titleblock basic data
QString btb_author_; ///< titleblock author
QDate btb_date_; ///< titleblock date
QString btb_title_; ///< titleblock title
QString btb_folio_; ///< titleblock folio
QString btb_plant_; ///< titleblock plant
QString btb_locmach_; ///< titleblock locmach
QString btb_indexrev_; ///< titleblock index rev
QString btb_final_folio_; ///< titleblock final folio
QString btb_auto_page_num_; ///< titleblock auto page num
int folio_index_; ///< titleblock index
int folio_total_; ///< titleblock total
QString btb_filename_; ///< titleblock filename
QString btb_version_; ///< titleblock version
/// titleblock additional fields
DiagramContext additional_fields_;
Qt::Edge m_edge; ///< titleblock edge
QString m_next_folio_num; ///< titleblock next folio num
QString m_previous_folio_num; ///< titleblock previous folio num
// border dimensions (rows and columns)
// columns: number and dimensions
int columns_count_; ///< columns count
qreal columns_width_; ///< columns width
qreal columns_header_height_; ///< columns header height
// border dimensions (rows and columns)
// columns: number and dimensions
int columns_count_; ///< columns count
qreal columns_width_; ///< columns width
qreal columns_header_height_; ///< columns header height
// rows: number and dimensions
int rows_count_; ///< rows count
qreal rows_height_; ///< rows height
qreal rows_header_width_; ///< rows header width
// rows: number and dimensions
int rows_count_; ///< rows count
qreal rows_height_; ///< rows height
qreal rows_header_width_; ///< rows header width
// title block dimensions
qreal titleblock_height_;
// title block dimensions
qreal titleblock_height_;
// rectangles used for drawing operations
QRectF diagram_rect_;
// rectangles used for drawing operations
QRectF diagram_rect_;
// display options
bool display_titleblock_;
bool display_columns_;
bool display_rows_;
bool display_border_;
TitleBlockTemplateRenderer *m_titleblock_template_renderer;
// display options
bool display_titleblock_;
bool display_columns_;
bool display_rows_;
bool display_border_;
TitleBlockTemplateRenderer *m_titleblock_template_renderer;
};
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CONDUCTOR_PROPERTIES_H
#define CONDUCTOR_PROPERTIES_H
@@ -27,119 +27,119 @@
class QPainter;
/**
@brief The SingleLineProperties class
This class represents the properties of a singleline conductor.
@brief The SingleLineProperties class
This class represents the properties of a singleline conductor.
*/
class SingleLineProperties: public PropertiesInterface {
public:
SingleLineProperties();
virtual ~SingleLineProperties();
public:
SingleLineProperties();
virtual ~SingleLineProperties();
void setPhasesCount(int);
unsigned short int phasesCount();
bool isPen() const;
void draw(QPainter *, QET::ConductorSegmentType, const QRectF &);
QDomElement toXml(QDomDocument& doc) const override;
bool fromXml(const QDomElement &) override;
static bool valideXml(QDomElement& element);
void toSettings(QSettings &, const QString & = QString()) const;
void fromSettings(QSettings &, const QString & = QString());
void setPhasesCount(int);
unsigned short int phasesCount();
bool isPen() const;
void draw(QPainter *, QET::ConductorSegmentType, const QRectF &);
QDomElement toXml(QDomDocument& doc) const override;
bool fromXml(const QDomElement &) override;
static bool valideXml(QDomElement& element);
void toSettings(QSettings &, const QString & = QString()) const;
void fromSettings(QSettings &, const QString & = QString());
/// Whether the singleline conductor should display the ground symbol
bool hasGround{true};
/// Whether the singleline conductor should display the neutral symbol
bool hasNeutral{true};
/// Protective Earth Neutral: visually merge neutral and ground
bool is_pen{false};
/// Whether the singleline conductor should display the ground symbol
bool hasGround{true};
/// Whether the singleline conductor should display the neutral symbol
bool hasNeutral{true};
/// Protective Earth Neutral: visually merge neutral and ground
bool is_pen{false};
int operator==(const SingleLineProperties &) const;
int operator!=(const SingleLineProperties &) const;
int operator==(const SingleLineProperties &) const;
int operator!=(const SingleLineProperties &) const;
private:
unsigned short int phases{1};
void drawGround (QPainter *, QET::ConductorSegmentType, QPointF, qreal);
void drawNeutral(QPainter *, QPointF, qreal);
void drawPen(QPainter *, QET::ConductorSegmentType, QPointF, qreal);
private:
unsigned short int phases{1};
void drawGround (QPainter *, QET::ConductorSegmentType, QPointF, qreal);
void drawNeutral(QPainter *, QPointF, qreal);
void drawPen(QPainter *, QET::ConductorSegmentType, QPointF, qreal);
};
/**
@brief The ConductorProperties class
This class represents the functional properties of a particular conductor,
i.e. properties other than path and terminals.
@brief The ConductorProperties class
This class represents the functional properties of a particular conductor,
i.e. properties other than path and terminals.
*/
class ConductorProperties: public PropertiesInterface
{
public:
ConductorProperties();
virtual ~ConductorProperties();
public:
ConductorProperties();
virtual ~ConductorProperties();
/**
@brief The ConductorType enum Represents
the kind of a particular conductor:
Single: singleline symbols, no text input
Multi: text input, no symbol
*/
enum ConductorType { Single, Multi };
/**
@brief The ConductorType enum Represents
the kind of a particular conductor:
Single: singleline symbols, no text input
Multi: text input, no symbol
*/
enum ConductorType { Single, Multi };
//Attributes
ConductorType type{ConductorType::Single};
//Attributes
ConductorType type{ConductorType::Single};
// TODO: set default values!
QColor color{QColor(Qt::black)},
m_color_2{QColor(Qt::black)},
text_color{QColor(Qt::black)};
// TODO: set default values!
QColor color{QColor(Qt::black)},
m_color_2{QColor(Qt::black)},
text_color{QColor(Qt::black)};
QString
text,
m_function,
m_tension_protocol,
m_wire_color,
m_wire_section,
m_formula,
m_bus,
m_cable;
QString
text,
m_function,
m_tension_protocol,
m_wire_color,
m_wire_section,
m_formula,
m_bus,
m_cable;
int text_size{9},
text_size,
m_dash_size = 1;
int text_size{9},
text_size,
m_dash_size = 1;
double cond_size{1},
cond_size,
verti_rotate_text,
horiz_rotate_text;
double cond_size{1},
cond_size,
verti_rotate_text,
horiz_rotate_text;
bool m_show_text{true},
m_one_text_per_folio{true},
m_bicolor = false;
bool m_show_text{true},
m_one_text_per_folio{true},
m_bicolor = false;
Qt::Alignment
m_horizontal_alignment = Qt::AlignBottom,
m_horizontal_alignment = Qt::AlignBottom,
m_vertical_alignment = Qt::AlignRight;
Qt::Alignment
m_horizontal_alignment = Qt::AlignBottom,
m_horizontal_alignment = Qt::AlignBottom,
m_vertical_alignment = Qt::AlignRight;
Qt::PenStyle style{Qt::PenStyle::SolidLine};
Qt::PenStyle style{Qt::PenStyle::SolidLine};
SingleLineProperties singleLineProperties;
SingleLineProperties singleLineProperties;
// methods
QDomElement toXml(QDomDocument &doc) const override;
bool fromXml(const QDomElement &) override;
static bool valideXml(QDomElement& element);
void toSettings(QSettings &, const QString & = QString()) const;
void fromSettings(QSettings &, const QString & = QString());
static QString typeToString(ConductorType);
void applyForEqualAttributes(QList<ConductorProperties> list);
// methods
QDomElement toXml(QDomDocument &doc) const override;
bool fromXml(const QDomElement &) override;
static bool valideXml(QDomElement& element);
void toSettings(QSettings &, const QString & = QString()) const;
void fromSettings(QSettings &, const QString & = QString());
static QString typeToString(ConductorType);
void applyForEqualAttributes(QList<ConductorProperties> list);
static ConductorProperties defaultProperties();
static ConductorProperties defaultProperties();
// operators
bool operator==(const ConductorProperties &) const;
bool operator!=(const ConductorProperties &) const;
// operators
bool operator==(const ConductorProperties &) const;
bool operator!=(const ConductorProperties &) const;
private:
void readStyle(const QString &);
QString writeStyle() const;
private:
void readStyle(const QString &);
QString writeStyle() const;
};
Q_DECLARE_METATYPE(ConductorProperties)

File diff suppressed because it is too large Load Diff

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef DIAGRAM_H
#define DIAGRAM_H
@@ -47,379 +47,379 @@ class DiagramFolioList;
class QETProject;
/**
@brief The Diagram class
This class represents an electric diagram.
It manages its various child elements,
conductors and texts and handles their graphic rendering.
@brief The Diagram class
This class represents an electric diagram.
It manages its various child elements,
conductors and texts and handles their graphic rendering.
*/
class Diagram : public QGraphicsScene
{
friend DiagramFolioList;
friend QETProject;
friend DiagramFolioList;
friend QETProject;
Q_OBJECT
Q_OBJECT
// constructors, destructor
private:
Diagram(QETProject *project);
~Diagram() override;
Diagram(const Diagram &diagram);
// constructors, destructor
private:
Diagram(QETProject *project);
~Diagram() override;
Diagram(const Diagram &diagram);
// ATTRIBUTES
public:
/**
@brief The BorderOptions enum
Represents available options when rendering a particular diagram:
EmptyBorder: display border only
TitleBlock: display title block
Columns: display columns
*/
enum BorderOptions { EmptyBorder, TitleBlock, Columns };
/// Represents available option of Numerotation type.
enum NumerotationType { Conductors };
/// Default properties for new conductors
ConductorProperties defaultConductorProperties;
/// Diagram dimensions and title block
BorderTitleBlock border_and_titleblock;
/// abscissa grid step size
static int xGrid;
/// ordinate grid step size
static int yGrid;
/// Key grid x step size
static int xKeyGrid;
/// Key grid y step size
static int yKeyGrid;
/// Key grid fine x step size
static int xKeyGridFine;
/// Key grid fine y step size
static int yKeyGridFine;
/// margin around the diagram
static const qreal margin;
/// background color of diagram
static QColor background_color; // default value set in cpp file
/// Hash containing max values for folio sequential autonums in this diagram
QHash <QString, QStringList> m_elmt_unitfolio_max;
QHash <QString, QStringList> m_elmt_tenfolio_max;
QHash <QString, QStringList> m_elmt_hundredfolio_max;
/// Hash containing max values for folio sequential autonums in this diagram
QHash <QString, QStringList> m_cnd_unitfolio_max;
QHash <QString, QStringList> m_cnd_tenfolio_max;
QHash <QString, QStringList> m_cnd_hundredfolio_max;
// ATTRIBUTES
public:
/**
@brief The BorderOptions enum
Represents available options when rendering a particular diagram:
EmptyBorder: display border only
TitleBlock: display title block
Columns: display columns
*/
enum BorderOptions { EmptyBorder, TitleBlock, Columns };
/// Represents available option of Numerotation type.
enum NumerotationType { Conductors };
/// Default properties for new conductors
ConductorProperties defaultConductorProperties;
/// Diagram dimensions and title block
BorderTitleBlock border_and_titleblock;
/// abscissa grid step size
static int xGrid;
/// ordinate grid step size
static int yGrid;
/// Key grid x step size
static int xKeyGrid;
/// Key grid y step size
static int yKeyGrid;
/// Key grid fine x step size
static int xKeyGridFine;
/// Key grid fine y step size
static int yKeyGridFine;
/// margin around the diagram
static const qreal margin;
/// background color of diagram
static QColor background_color; // default value set in cpp file
/// Hash containing max values for folio sequential autonums in this diagram
QHash <QString, QStringList> m_elmt_unitfolio_max;
QHash <QString, QStringList> m_elmt_tenfolio_max;
QHash <QString, QStringList> m_elmt_hundredfolio_max;
/// Hash containing max values for folio sequential autonums in this diagram
QHash <QString, QStringList> m_cnd_unitfolio_max;
QHash <QString, QStringList> m_cnd_tenfolio_max;
QHash <QString, QStringList> m_cnd_hundredfolio_max;
private:
QGraphicsLineItem *conductor_setter_;
ElementsMover m_elements_mover;
ElementTextsMover m_element_texts_mover;
QGIManager *qgi_manager_;
QETProject *m_project;
private:
QGraphicsLineItem *conductor_setter_;
ElementsMover m_elements_mover;
ElementTextsMover m_element_texts_mover;
QGIManager *qgi_manager_;
QETProject *m_project;
QDomDocument xml_document_;
QDomDocument xml_document_;
qreal diagram_qet_version_;
qreal diagram_qet_version_;
bool draw_grid_;
bool use_border_;
bool draw_terminals_;
bool draw_colored_conductors_;
bool draw_grid_;
bool use_border_;
bool draw_terminals_;
bool draw_colored_conductors_;
QString m_conductors_autonum_name;
DiagramEventInterface *m_event_interface;
QString m_conductors_autonum_name;
DiagramEventInterface *m_event_interface;
bool m_freeze_new_elements;
bool m_freeze_new_conductors_;
QUuid m_uuid = QUuid::createUuid();
bool m_freeze_new_elements;
bool m_freeze_new_conductors_;
QUuid m_uuid = QUuid::createUuid();
// METHODS
protected:
void drawBackground(QPainter *, const QRectF &) override;
// METHODS
protected:
void drawBackground(QPainter *, const QRectF &) override;
void mouseDoubleClickEvent (
QGraphicsSceneMouseEvent *event) override;
void mousePressEvent (QGraphicsSceneMouseEvent *event) override;
void mouseMoveEvent (QGraphicsSceneMouseEvent *event) override;
void mouseReleaseEvent (
QGraphicsSceneMouseEvent *event) override;
void wheelEvent (QGraphicsSceneWheelEvent *event) override;
void keyPressEvent (QKeyEvent *event) override;
void keyReleaseEvent (QKeyEvent *) override;
void mouseDoubleClickEvent (
QGraphicsSceneMouseEvent *event) override;
void mousePressEvent (QGraphicsSceneMouseEvent *event) override;
void mouseMoveEvent (QGraphicsSceneMouseEvent *event) override;
void mouseReleaseEvent (
QGraphicsSceneMouseEvent *event) override;
void wheelEvent (QGraphicsSceneWheelEvent *event) override;
void keyPressEvent (QKeyEvent *event) override;
void keyReleaseEvent (QKeyEvent *) override;
public:
QUuid uuid();
void setEventInterface (DiagramEventInterface *event_interface);
void clearEventInterface();
public:
QUuid uuid();
void setEventInterface (DiagramEventInterface *event_interface);
void clearEventInterface();
//methods related to autonum
QString conductorsAutonumName() const;
void setConductorsAutonumName(const QString &name);
//methods related to autonum
QString conductorsAutonumName() const;
void setConductorsAutonumName(const QString &name);
static bool clipboardMayContainDiagram();
static bool clipboardMayContainDiagram();
// methods related to parent project
QETProject *project() const;
int folioIndex() const;
void showMe() {emit showDiagram(this);}
bool isReadOnly() const;
// methods related to parent project
QETProject *project() const;
int folioIndex() const;
void showMe() {emit showDiagram(this);}
bool isReadOnly() const;
// methods related to conductor creation
void setConductor(bool);
void setConductorStart (QPointF);
void setConductorStop(QPointF);
QList < QSet <Conductor *> > potentials();
// methods related to conductor creation
void setConductor(bool);
void setConductorStart (QPointF);
void setConductorStop(QPointF);
QList < QSet <Conductor *> > potentials();
// methods related to XML import/export
QDomDocument toXml(bool = true);
bool initFromXml(QDomElement &,
QPointF = QPointF(),
bool = true,
DiagramContent * = nullptr);
bool fromXml(QDomDocument &,
QPointF = QPointF(),
bool = true,
DiagramContent * = nullptr);
bool fromXml(QDomElement &,
QPointF = QPointF(),
bool = true,
DiagramContent * = nullptr);
void folioSequentialsToXml(QHash<QString,
QStringList>*,
QDomElement *,
const QString&,
const QString&,
QDomDocument *);
void folioSequentialsFromXml(const QDomElement&,
QHash<QString,
QStringList>*,
const QString&,
const QString&,
const QString&,
const QString&);
// methods related to XML import/export
QDomDocument toXml(bool = true);
bool initFromXml(QDomElement &,
QPointF = QPointF(),
bool = true,
DiagramContent * = nullptr);
bool fromXml(QDomDocument &,
QPointF = QPointF(),
bool = true,
DiagramContent * = nullptr);
bool fromXml(QDomElement &,
QPointF = QPointF(),
bool = true,
DiagramContent * = nullptr);
void folioSequentialsToXml(QHash<QString,
QStringList>*,
QDomElement *,
const QString&,
const QString&,
QDomDocument *);
void folioSequentialsFromXml(const QDomElement&,
QHash<QString,
QStringList>*,
const QString&,
const QString&,
const QString&,
const QString&);
void refreshContents();
void refreshContents();
// methods related to graphics items addition/removal on the diagram
virtual void addItem (QGraphicsItem *item);
virtual void removeItem (QGraphicsItem *item);
// methods related to graphics items addition/removal on the diagram
virtual void addItem (QGraphicsItem *item);
virtual void removeItem (QGraphicsItem *item);
// methods related to graphics options
ExportProperties applyProperties(const ExportProperties &);
void setDisplayGrid(bool);
bool displayGrid();
void setUseBorder(bool);
bool useBorder();
void setBorderOptions(BorderOptions);
BorderOptions borderOptions();
DiagramPosition convertPosition(const QPointF &);
static QPointF snapToGrid(const QPointF &p);
// methods related to graphics options
ExportProperties applyProperties(const ExportProperties &);
void setDisplayGrid(bool);
bool displayGrid();
void setUseBorder(bool);
bool useBorder();
void setBorderOptions(BorderOptions);
BorderOptions borderOptions();
DiagramPosition convertPosition(const QPointF &);
static QPointF snapToGrid(const QPointF &p);
bool drawTerminals() const;
void setDrawTerminals(bool);
bool drawColoredConductors() const;
void setDrawColoredConductors(bool);
bool drawTerminals() const;
void setDrawTerminals(bool);
bool drawColoredConductors() const;
void setDrawColoredConductors(bool);
QString title() const;
bool toPaintDevice(QPaintDevice &, int = -1, int = -1,
Qt::AspectRatioMode = Qt::KeepAspectRatio);
QSize imageSize() const;
QString title() const;
bool toPaintDevice(QPaintDevice &, int = -1, int = -1,
Qt::AspectRatioMode = Qt::KeepAspectRatio);
QSize imageSize() const;
bool isEmpty() const;
bool isEmpty() const;
QList<Element *> elements() const;
QList<Conductor *> conductors() const;
QSet<Conductor *> selectedConductors() const;
DiagramContent content() const;
bool canRotateSelection() const;
ElementsMover &elementsMover();
ElementTextsMover &elementTextsMover();
bool usesElement(const ElementsLocation &);
bool usesTitleBlockTemplate(const QString &);
QList<Element *> elements() const;
QList<Conductor *> conductors() const;
QSet<Conductor *> selectedConductors() const;
DiagramContent content() const;
bool canRotateSelection() const;
ElementsMover &elementsMover();
ElementTextsMover &elementTextsMover();
bool usesElement(const ElementsLocation &);
bool usesTitleBlockTemplate(const QString &);
QUndoStack &undoStack();
QGIManager &qgiManager();
QUndoStack &undoStack();
QGIManager &qgiManager();
//methods related to element label Update Policy
void freezeElements(bool freeze);
void unfreezeElements();
void setFreezeNewElements(bool);
bool freezeNewElements();
//methods related to element label Update Policy
void freezeElements(bool freeze);
void unfreezeElements();
void setFreezeNewElements(bool);
bool freezeNewElements();
//methods related to conductor label Update Policy
void freezeConductors(bool freeze);
void setFreezeNewConductors(bool);
bool freezeNewConductors();
//methods related to conductor label Update Policy
void freezeConductors(bool freeze);
void setFreezeNewConductors(bool);
bool freezeNewConductors();
//methods related to insertion and loading of folio sequential
void insertFolioSeqHash (QHash<QString, QStringList> *hash,
const QString& title,
const QString& seq,
NumerotationContext *nc);
void loadFolioSeqHash (QHash<QString, QStringList> *hash,
const QString& title, const QString& seq,
NumerotationContext *nc);
void changeZValue(QET::DepthOption option);
//methods related to insertion and loading of folio sequential
void insertFolioSeqHash (QHash<QString, QStringList> *hash,
const QString& title,
const QString& seq,
NumerotationContext *nc);
void loadFolioSeqHash (QHash<QString, QStringList> *hash,
const QString& title, const QString& seq,
NumerotationContext *nc);
void changeZValue(QET::DepthOption option);
public slots:
void adjustSceneRect ();
void titleChanged(const QString &);
void titleBlockTemplateChanged(const QString &);
void titleBlockTemplateRemoved(const QString &,
const QString & = QString());
void setTitleBlockTemplate(const QString &);
void updateLabels();
void loadElmtFolioSeq();
void loadCndFolioSeq();
public slots:
void adjustSceneRect ();
void titleChanged(const QString &);
void titleBlockTemplateChanged(const QString &);
void titleBlockTemplateRemoved(const QString &,
const QString & = QString());
void setTitleBlockTemplate(const QString &);
void updateLabels();
void loadElmtFolioSeq();
void loadCndFolioSeq();
// methods related to graphics items selection
void selectAll();
void deselectAll();
void invertSelection();
// methods related to graphics items selection
void selectAll();
void deselectAll();
void invertSelection();
signals:
void showDiagram (Diagram *);
void usedTitleBlockTemplateChanged(const QString &);
void diagramTitleChanged(Diagram *, const QString &);
signals:
void showDiagram (Diagram *);
void usedTitleBlockTemplateChanged(const QString &);
void diagramTitleChanged(Diagram *, const QString &);
/// Signal emitted when users wish to locate an element
/// from the diagram within elements collection
void findElementRequired(const ElementsLocation &);
/// Signal emitted when users wish to locate an element
/// from the diagram within elements collection
void findElementRequired(const ElementsLocation &);
/// Signal emitted when users wish to edit an element from the diagram
void editElementRequired(const ElementsLocation &);
void diagramActivated();
/// Signal emitted when users wish to edit an element from the diagram
void editElementRequired(const ElementsLocation &);
void diagramActivated();
};
Q_DECLARE_METATYPE(Diagram *)
/**
@brief Diagram::setConductor
Display or hide the conductor setter,
i.e. a dashed conductor stub which appears
when creating a conductor between two terminals.
@param adding true add conductor ,false remove conductor
@brief Diagram::setConductor
Display or hide the conductor setter,
i.e. a dashed conductor stub which appears
when creating a conductor between two terminals.
@param adding true add conductor ,false remove conductor
*/
inline void Diagram::setConductor(bool adding) {
if (adding) {
if (!conductor_setter_ -> scene()) addItem(conductor_setter_);
} else {
if (conductor_setter_ -> scene()) removeItem(conductor_setter_);
}
if (adding) {
if (!conductor_setter_ -> scene()) addItem(conductor_setter_);
} else {
if (conductor_setter_ -> scene()) removeItem(conductor_setter_);
}
}
/**
@brief Diagram::setConductorStart
Set the start point of the conductor setter.
@param start the point (in scene coordinates) which the newly created
conductor should start from.
@brief Diagram::setConductorStart
Set the start point of the conductor setter.
@param start the point (in scene coordinates) which the newly created
conductor should start from.
*/
inline void Diagram::setConductorStart(QPointF start) {
conductor_setter_ -> setLine(QLineF(start, conductor_setter_ -> line().p2()));
conductor_setter_ -> setLine(QLineF(start, conductor_setter_ -> line().p2()));
}
/**
@brief Diagram::setConductorStop
Set the end point of the conductor setter.
@param end the point (in scene coordinates) upon to which the newly created
conductor should be drawn.
@brief Diagram::setConductorStop
Set the end point of the conductor setter.
@param end the point (in scene coordinates) upon to which the newly created
conductor should be drawn.
*/
inline void Diagram::setConductorStop(QPointF end) {
conductor_setter_ -> setLine(QLineF(conductor_setter_ -> line().p1(), end));
conductor_setter_ -> setLine(QLineF(conductor_setter_ -> line().p1(), end));
}
/**
@brief Diagram::setDisplayGrid
Set whether the diagram grid should be drawn.
@param dg true to render the grid, false otherwise.
@brief Diagram::setDisplayGrid
Set whether the diagram grid should be drawn.
@param dg true to render the grid, false otherwise.
*/
inline void Diagram::setDisplayGrid(bool dg) {
draw_grid_ = dg;
draw_grid_ = dg;
}
/**
@brief Diagram::displayGrid
@return draw_grid_ true if the grid is drawn, false otherwise.
@brief Diagram::displayGrid
@return draw_grid_ true if the grid is drawn, false otherwise.
*/
inline bool Diagram::displayGrid() {
return(draw_grid_);
return(draw_grid_);
}
/**
@brief Diagram::setUseBorder
Set whether the diagram border (including rows/colums headers and the title
block) should be rendered along with the diagram. When set to false, the size
of the smallest rectangle containing all items is considered as the diagram
size.
@param ub true to take the border into account, false otherwise
@brief Diagram::setUseBorder
Set whether the diagram border (including rows/colums headers and the title
block) should be rendered along with the diagram. When set to false, the size
of the smallest rectangle containing all items is considered as the diagram
size.
@param ub true to take the border into account, false otherwise
*/
inline void Diagram::setUseBorder(bool ub) {
use_border_ = ub;
use_border_ = ub;
}
/**
@brief Diagram::useBorder
@return use_border_ true if the border is rendered and take into account,
false otherwise.
@brief Diagram::useBorder
@return use_border_ true if the border is rendered and take into account,
false otherwise.
*/
inline bool Diagram::useBorder() {
return(use_border_);
return(use_border_);
}
/**
@brief Diagram::setBorderOptions
Set the rendering options for the diagram border (including rows/colums
headers and the title block)
@param bo Enabled options ORed together
@see BorderOptions
@brief Diagram::setBorderOptions
Set the rendering options for the diagram border (including rows/colums
headers and the title block)
@param bo Enabled options ORed together
@see BorderOptions
*/
inline void Diagram::setBorderOptions(Diagram::BorderOptions bo) {
border_and_titleblock.displayBorder(!(bo & EmptyBorder));
border_and_titleblock.displayColumns(bo & Columns);
border_and_titleblock.displayTitleBlock(bo & TitleBlock);
border_and_titleblock.displayBorder(!(bo & EmptyBorder));
border_and_titleblock.displayColumns(bo & Columns);
border_and_titleblock.displayTitleBlock(bo & TitleBlock);
}
/**
@brief Diagram::borderOptions
@return The rendering optios for the diagram border
@see setBorderOptions
@brief Diagram::borderOptions
@return The rendering optios for the diagram border
@see setBorderOptions
*/
inline Diagram::BorderOptions Diagram::borderOptions() {
BorderOptions options = EmptyBorder;
if (border_and_titleblock.titleBlockIsDisplayed())
options = (BorderOptions)(options|TitleBlock);
if (border_and_titleblock.columnsAreDisplayed())
options = (BorderOptions)(options|Columns);
return(options);
BorderOptions options = EmptyBorder;
if (border_and_titleblock.titleBlockIsDisplayed())
options = (BorderOptions)(options|TitleBlock);
if (border_and_titleblock.columnsAreDisplayed())
options = (BorderOptions)(options|Columns);
return(options);
}
/**
@brief Diagram::undoStack
@return the diagram undo stack
@brief Diagram::undoStack
@return the diagram undo stack
*/
inline QUndoStack &Diagram::undoStack() {
return *(project()->undoStack());
return *(project()->undoStack());
}
/**
@brief Diagram::qgiManager
@return the diagram graphics item manager
@brief Diagram::qgiManager
@return the diagram graphics item manager
*/
inline QGIManager &Diagram::qgiManager() {
return(*qgi_manager_);
return(*qgi_manager_);
}
/**
@brief Diagram::drawTerminals
@return true if terminals are rendered, false otherwise
@brief Diagram::drawTerminals
@return true if terminals are rendered, false otherwise
*/
inline bool Diagram::drawTerminals() const
{
return(draw_terminals_);
return(draw_terminals_);
}
/**
@brief Diagram::drawColoredConductors
@return true if conductors colors are rendered, false otherwise.
@brief Diagram::drawColoredConductors
@return true if conductors colors are rendered, false otherwise.
*/
inline bool Diagram::drawColoredConductors() const
{
return(draw_colored_conductors_);
return(draw_colored_conductors_);
}
#endif

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#include "diagramcontext.h"
#include "qet.h"
@@ -22,240 +22,240 @@
#include <QRegularExpressionMatch>
/**
@brief DiagramContext::add
Add all value of other to this.
If a key already exist, the value is replaced.
If a key doesn't exist, she will be added.
All other keys of this context, which are not present in other, stay unchanged.
@param other
@brief DiagramContext::add
Add all value of other to this.
If a key already exist, the value is replaced.
If a key doesn't exist, she will be added.
All other keys of this context, which are not present in other, stay unchanged.
@param other
*/
void DiagramContext::add(DiagramContext other)
{
for (QString key : other.keys()) {
addValue(key, other.value(key));
}
for (QString key : other.keys()) {
addValue(key, other.value(key));
}
}
/**
@brief DiagramContext::remove
@param key
@brief DiagramContext::remove
@param key
*/
void DiagramContext::remove(const QString &key) {
m_content.remove(key);
m_content.remove(key);
}
/**
@return a list containing all the keys in the context object.
@return a list containing all the keys in the context object.
*/
QList<QString> DiagramContext::keys(DiagramContext::KeyOrder order) const
{
if (order == None) {
return m_content.keys();
}
else
{
QList<QString> keys_list = m_content.keys();
if (order == Alphabetical) {
std::sort(keys_list.begin(), keys_list.end());
} else {
std::sort(keys_list.begin(), keys_list.end(), DiagramContext::stringLongerThan);
}
return(keys_list);
}
if (order == None) {
return m_content.keys();
}
else
{
QList<QString> keys_list = m_content.keys();
if (order == Alphabetical) {
std::sort(keys_list.begin(), keys_list.end());
} else {
std::sort(keys_list.begin(), keys_list.end(), DiagramContext::stringLongerThan);
}
return(keys_list);
}
}
/**
@param key string key
@return true if that key is known to the diagram context, false otherwise
@param key string key
@return true if that key is known to the diagram context, false otherwise
*/
bool DiagramContext::contains(const QString &key) const
{
return(m_content.contains(key));
return(m_content.contains(key));
}
/**
@param key
@param key
*/
const QVariant DiagramContext::operator[](const QString &key) const
{
return(m_content[key]);
return(m_content[key]);
}
/**
@param key key to insert in the context - the key may only contain lowercase
letters and dashes.
If embedded key is set, key must be find it else value is not added.
@see DiagramContext::keyIsAcceptable()
@param value value to insert in the context
@param show if value is used to be show on the diagram or somewhere else,
we can specify if he is show(true) or not(false)
@return true if the insertion succeeds, false otherwise
@param key key to insert in the context - the key may only contain lowercase
letters and dashes.
If embedded key is set, key must be find it else value is not added.
@see DiagramContext::keyIsAcceptable()
@param value value to insert in the context
@param show if value is used to be show on the diagram or somewhere else,
we can specify if he is show(true) or not(false)
@return true if the insertion succeeds, false otherwise
*/
bool DiagramContext::addValue(const QString &key, const QVariant &value, bool show) {
if (keyIsAcceptable(key)) {
m_content.insert(key, value);
m_content_show.insert(key, show);
return(true);
}
return(false);
if (keyIsAcceptable(key)) {
m_content.insert(key, value);
m_content_show.insert(key, show);
return(true);
}
return(false);
}
QVariant DiagramContext::value(const QString &key) const
{
return m_content.value(key);
return m_content.value(key);
}
/**
Clear the content of this diagram context.
Clear the content of this diagram context.
*/
void DiagramContext::clear()
{
m_content.clear();
m_content_show.clear();
m_content.clear();
m_content_show.clear();
}
/**
@return the number of key/value pairs stored in this object.
@return the number of key/value pairs stored in this object.
*/
int DiagramContext::count()
{
return(m_content.count());
return(m_content.count());
}
/**
@brief DiagramContext::keyMustShow
@return the value pairs with key, if key no found, return false
@brief DiagramContext::keyMustShow
@return the value pairs with key, if key no found, return false
*/
bool DiagramContext::keyMustShow(const QString &key) const
{
if (m_content_show.contains(key))
return m_content_show[key];
return false;
if (m_content_show.contains(key))
return m_content_show[key];
return false;
}
bool DiagramContext::operator==(const DiagramContext &dc) const
{
return(m_content == dc.m_content &&
m_content_show == dc.m_content_show);
return(m_content == dc.m_content &&
m_content_show == dc.m_content_show);
}
bool DiagramContext::operator!=(const DiagramContext &dc) const
{
return(!(*this == dc));
return(!(*this == dc));
}
/**
Export this context properties under the \a e XML element, using tags
named \a tag_name (defaults to "property").
Export this context properties under the \a e XML element, using tags
named \a tag_name (defaults to "property").
*/
void DiagramContext::toXml(QDomElement &e, const QString &tag_name) const
{
foreach (QString key, keys()) {
QDomElement property = e.ownerDocument().createElement(tag_name);
property.setAttribute("name", key);
property.setAttribute("show",m_content_show[key]);
QDomText value = e.ownerDocument().createTextNode(m_content[key].toString());
property.appendChild(value);
e.appendChild(property);
}
foreach (QString key, keys()) {
QDomElement property = e.ownerDocument().createElement(tag_name);
property.setAttribute("name", key);
property.setAttribute("show",m_content_show[key]);
QDomText value = e.ownerDocument().createTextNode(m_content[key].toString());
property.appendChild(value);
e.appendChild(property);
}
}
/**
Read this context properties from the \a e XML element, looking for tags named
\a tag_name (defaults to "property").
Read this context properties from the \a e XML element, looking for tags named
\a tag_name (defaults to "property").
*/
void DiagramContext::fromXml(const QDomElement &e, const QString &tag_name) {
foreach (QDomElement property, QET::findInDomElement(e, tag_name)) {
if (!property.hasAttribute("name")) continue;
addValue(property.attribute("name"), QVariant(property.text()));
m_content_show.insert(property.attribute("name"), property.attribute("show", "1").toInt());
}
foreach (QDomElement property, QET::findInDomElement(e, tag_name)) {
if (!property.hasAttribute("name")) continue;
addValue(property.attribute("name"), QVariant(property.text()));
m_content_show.insert(property.attribute("name"), property.attribute("show", "1").toInt());
}
}
/**
@brief DiagramContext::fromXml
Read this context properties from the dom_element,
looking for tags named tag_name
@param dom_element : dom element to parse
@param tag_name : tag name to find, by default "property"
@brief DiagramContext::fromXml
Read this context properties from the dom_element,
looking for tags named tag_name
@param dom_element : dom element to parse
@param tag_name : tag name to find, by default "property"
*/
void DiagramContext::fromXml(const pugi::xml_node &dom_element, const QString &tag_name)
{
for(auto node = dom_element.child(tag_name.toStdString().c_str()) ; node ; node = node.next_sibling(tag_name.toStdString().c_str()))
{
addValue(node.attribute("name").as_string(), QVariant(node.text().as_string()));
m_content_show.insert(node.attribute("name").as_string(), node.attribute("show").empty()? 1 : node.attribute("show").as_int());
}
for(auto node = dom_element.child(tag_name.toStdString().c_str()) ; node ; node = node.next_sibling(tag_name.toStdString().c_str()))
{
addValue(node.attribute("name").as_string(), QVariant(node.text().as_string()));
m_content_show.insert(node.attribute("name").as_string(), node.attribute("show").empty()? 1 : node.attribute("show").as_int());
}
}
/**
Export this context properties to \a settings by creating an array named \a
array_name.
Export this context properties to \a settings by creating an array named \a
array_name.
*/
void DiagramContext::toSettings(QSettings &settings, const QString &array_name) const
{
settings.beginWriteArray(array_name);
int i = 0;
foreach (QString key, m_content.keys()) {
settings.setArrayIndex(i);
settings.setValue("name", key);
settings.setValue("value", m_content[key].toString());
++ i;
}
settings.endArray();
settings.beginWriteArray(array_name);
int i = 0;
foreach (QString key, m_content.keys()) {
settings.setArrayIndex(i);
settings.setValue("name", key);
settings.setValue("value", m_content[key].toString());
++ i;
}
settings.endArray();
}
/**
Read this context properties from \a settings by running through the array
named \a array_name.
Read this context properties from \a settings by running through the array
named \a array_name.
*/
void DiagramContext::fromSettings(const QSettings &settings, const QString &array_name) {
int size = settings.beginReadArray(array_name);
QSettings& s = const_cast<QSettings&>(settings);
int size = s.beginReadArray(array_name);
for (int i = 0 ; i < size; ++ i) {
settings.setArrayIndex(i);
QString key = settings.value("name").toString();
if (key.isEmpty()) continue;
addValue(key, settings.value("value").toString());
}
settings.endArray();
int size = settings.beginReadArray(array_name);
QSettings& s = const_cast<QSettings&>(settings);
int size = s.beginReadArray(array_name);
for (int i = 0 ; i < size; ++ i) {
settings.setArrayIndex(i);
QString key = settings.value("name").toString();
if (key.isEmpty()) continue;
addValue(key, settings.value("value").toString());
}
settings.endArray();
}
/**
@return the regular expression used to check whether a given key is acceptable.
@see keyIsAcceptable()
@return the regular expression used to check whether a given key is acceptable.
@see keyIsAcceptable()
*/
QString DiagramContext::validKeyRegExp()
{
return("^[a-z0-9-_]+$");
return("^[a-z0-9-_]+$");
}
/**
@return True if \a a is longer than \a b, false otherwise.
@return True if \a a is longer than \a b, false otherwise.
*/
bool DiagramContext::stringLongerThan(const QString &a, const QString &b) {
return (a.length() > b.length());
return (a.length() > b.length());
}
/**
@param key a key string
@return true if that key is acceptable, false otherwise
@param key a key string
@return true if that key is acceptable, false otherwise
*/
bool DiagramContext::keyIsAcceptable(const QString &key) const
{
QRegularExpression re(DiagramContext::validKeyRegExp());
QRegularExpressionMatch match =re.match(key);
return match.hasMatch();
QRegularExpression re(DiagramContext::validKeyRegExp());
QRegularExpressionMatch match =re.match(key);
return match.hasMatch();
}
QDebug operator <<(QDebug debug, const DiagramContext &context)
{
debug << "DiagramContext";
for (auto key : context.keys()) {
debug.nospace() << key << " : " << context.value(key) << "\n";
}
debug << " end DiagramContext";
debug << "DiagramContext";
for (auto key : context.keys()) {
debug.nospace() << key << " : " << context.value(key) << "\n";
}
debug << " end DiagramContext";
return debug;
return debug;
}

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef DIAGRAM_CONTEXT_H
#define DIAGRAM_CONTEXT_H
@@ -26,69 +26,69 @@
#include "pugixml.hpp"
/**
This class represents a diagram context, i.e. the data (a list of key/value
pairs) of a diagram at a given time. It is notably used by titleblock templates
to fetch the informations they need to do their rendering, or element for retrieve information about itself
This class represents a diagram context, i.e. the data (a list of key/value
pairs) of a diagram at a given time. It is notably used by titleblock templates
to fetch the informations they need to do their rendering, or element for retrieve information about itself
*/
/**
* Key for element :
* label -> label or identification of element
* formula -> formula used to create the label (formula is make with variable)
* designation -> exhaustive comment used to explain what the element does.
* description -> exhaustive description used to explain what the element does.
* plant -> the plant assigned to the element
* comment -> a little comment wich can be displayed in the folio
* manufacturer -> the manufacturer of the element
* manufacturer_reference -> the manufacturer reference of the element
* quantity -> quantity of the element
* unity -> unity of the element
* auxiliary1 -> auxiliary 1 of element
* auxiliary2 -> auxiliary 2 of element
* label -> label or identification of element
* formula -> formula used to create the label (formula is make with variable)
* designation -> exhaustive comment used to explain what the element does.
* description -> exhaustive description used to explain what the element does.
* plant -> the plant assigned to the element
* comment -> a little comment wich can be displayed in the folio
* manufacturer -> the manufacturer of the element
* manufacturer_reference -> the manufacturer reference of the element
* quantity -> quantity of the element
* unity -> unity of the element
* auxiliary1 -> auxiliary 1 of element
* auxiliary2 -> auxiliary 2 of element
* machine_manufacturer_reference -> reference of the machine manufacturer
* supplier -> the supplier of the element
* function -> the function of element
* location -> the location assigned to the element
* frozenLabel -> label locked at a given time
* supplier -> the supplier of the element
* function -> the function of element
* location -> the location assigned to the element
* frozenLabel -> label locked at a given time
*
*/
class DiagramContext
{
public:
enum KeyOrder {
None,
Alphabetical,
DecreasingLength
};
public:
enum KeyOrder {
None,
Alphabetical,
DecreasingLength
};
void add(DiagramContext other);
void remove(const QString &key);
QList<QString> keys(KeyOrder = None) const;
bool contains(const QString &) const;
const QVariant operator[](const QString &) const;
bool addValue(const QString &, const QVariant &, bool show = true);
QVariant value(const QString &key) const;
void clear();
int count();
bool keyMustShow (const QString &) const;
void add(DiagramContext other);
void remove(const QString &key);
QList<QString> keys(KeyOrder = None) const;
bool contains(const QString &) const;
const QVariant operator[](const QString &) const;
bool addValue(const QString &, const QVariant &, bool show = true);
QVariant value(const QString &key) const;
void clear();
int count();
bool keyMustShow (const QString &) const;
bool operator==(const DiagramContext &) const;
bool operator!=(const DiagramContext &) const;
bool operator==(const DiagramContext &) const;
bool operator!=(const DiagramContext &) const;
void toXml(QDomElement &, const QString & = "property") const;
void fromXml(const QDomElement &, const QString & = "property");
void fromXml(const pugi::xml_node &dom_element, const QString &tag_name = "property");
void toSettings(QSettings &, const QString &) const;
void fromSettings(QSettings &, const QString &);
void toXml(QDomElement &, const QString & = "property") const;
void fromXml(const QDomElement &, const QString & = "property");
void fromXml(const pugi::xml_node &dom_element, const QString &tag_name = "property");
void toSettings(QSettings &, const QString &) const;
void fromSettings(QSettings &, const QString &);
static QString validKeyRegExp();
static QString validKeyRegExp();
private:
static bool stringLongerThan(const QString &, const QString &);
bool keyIsAcceptable(const QString &) const;
/// Diagram context data (key/value pairs)
QHash<QString, QVariant> m_content;
QHash<QString, bool> m_content_show;
private:
static bool stringLongerThan(const QString &, const QString &);
bool keyIsAcceptable(const QString &) const;
/// Diagram context data (key/value pairs)
QHash<QString, QVariant> m_content;
QHash<QString, bool> m_content_show;
};
QDebug operator <<(QDebug debug, const DiagramContext &context);

File diff suppressed because it is too large Load Diff

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CUSTOM_ELEMENT_GRAPHIC_PART_H
#define CUSTOM_ELEMENT_GRAPHIC_PART_H
@@ -26,308 +26,308 @@ class QPainter;
/**
@brief The CustomElementGraphicPart class
This class is the base for all home-made primitive like line,
rectangle, ellipse etc....
It provides methods and enums to manage style attributes available
for primitive (color, pen style, etc...)
@brief The CustomElementGraphicPart class
This class is the base for all home-made primitive like line,
rectangle, ellipse etc....
It provides methods and enums to manage style attributes available
for primitive (color, pen style, etc...)
*/
class CustomElementGraphicPart : public QGraphicsObject, public CustomElementPart
{
#define SHADOWS_HEIGHT 4.0
#define SHADOWS_HEIGHT 4.0
Q_OBJECT
Q_OBJECT
Q_PROPERTY(LineStyle line_style READ lineStyle WRITE setLineStyle)
Q_PROPERTY(LineWeight line_weight READ lineWeight WRITE setLineWeight)
Q_PROPERTY(Filling filling READ filling WRITE setFilling)
Q_PROPERTY(Color color READ color WRITE setColor)
Q_PROPERTY(bool antialias READ antialiased WRITE setAntialiased)
Q_PROPERTY(LineStyle line_style READ lineStyle WRITE setLineStyle)
Q_PROPERTY(LineWeight line_weight READ lineWeight WRITE setLineWeight)
Q_PROPERTY(Filling filling READ filling WRITE setFilling)
Q_PROPERTY(Color color READ color WRITE setColor)
Q_PROPERTY(bool antialias READ antialiased WRITE setAntialiased)
public:
//Line style
enum LineStyle {NormalStyle,
DashedStyle,
DottedStyle,
DashdottedStyle};
Q_ENUM (LineStyle)
public:
//Line style
enum LineStyle {NormalStyle,
DashedStyle,
DottedStyle,
DashdottedStyle};
Q_ENUM (LineStyle)
//Line weight : invisible, 0px, 1px, 2px, 5px
enum LineWeight {NoneWeight,
ThinWeight,
NormalWeight,
UltraWeight,
BigWeight};
Q_ENUM (LineWeight)
//Line weight : invisible, 0px, 1px, 2px, 5px
enum LineWeight {NoneWeight,
ThinWeight,
NormalWeight,
UltraWeight,
BigWeight};
Q_ENUM (LineWeight)
//Filling color of the part : NoneFilling -> No filling (i.e. transparent)
enum Filling { NoneFilling, BlackFilling, WhiteFilling,
GreenFilling, RedFilling, BlueFilling,
GrayFilling, BrunFilling, YellowFilling,
CyanFilling, MagentaFilling, LightgrayFilling,
OrangeFilling, PurpleFilling,
HTMLPinkPinkFilling, HTMLPinkLightPinkFilling,
HTMLPinkHotPinkFilling, HTMLPinkDeepPinkFilling,
HTMLPinkPaleVioletRedFilling,
HTMLPinkMediumVioletRedFilling,
HTMLRedLightSalmonFilling, HTMLRedSalmonFilling,
HTMLRedDarkSalmonFilling,
HTMLRedLightCoralFilling,
HTMLRedIndianRedFilling, HTMLRedCrimsonFilling,
HTMLRedFirebrickFilling, HTMLRedDarkRedFilling,
HTMLRedRedFilling, HTMLOrangeOrangeRedFilling,
HTMLOrangeTomatoFilling, HTMLOrangeCoralFilling,
HTMLOrangeDarkOrangeFilling,
HTMLOrangeOrangeFilling, HTMLYellowYellowFilling,
HTMLYellowLightYellowFilling,
HTMLYellowLemonChiffonFilling,
HTMLYellowLightGoldenrodYellowFilling,
HTMLYellowPapayaWhipFilling,
HTMLYellowMoccasinFilling,
HTMLYellowPeachPuffFilling,
HTMLYellowPaleGoldenrodFilling,
HTMLYellowKhakiFilling,
HTMLYellowDarkKhakiFilling,
HTMLYellowGoldFilling, HTMLBrownCornsilkFilling,
HTMLBrownBlanchedAlmondFilling,
HTMLBrownBisqueFilling,
HTMLBrownNavajoWhiteFilling,
HTMLBrownWheatFilling, HTMLBrownBurlywoodFilling,
HTMLBrownTanFilling, HTMLBrownRosyBrownFilling,
HTMLBrownSandyBrownFilling,
HTMLBrownGoldenrodFilling,
HTMLBrownDarkGoldenrodFilling,
HTMLBrownPeruFilling, HTMLBrownChocolateFilling,
HTMLBrownSaddleBrownFilling,
HTMLBrownSiennaFilling, HTMLBrownBrownFilling,
HTMLBrownMaroonFilling,
HTMLGreenDarkOliveGreenFilling,
HTMLGreenOliveFilling, HTMLGreenOliveDrabFilling,
HTMLGreenYellowGreenFilling,
HTMLGreenLimeGreenFilling, HTMLGreenLimeFilling,
HTMLGreenLawnGreenFilling,
HTMLGreenChartreuseFilling,
HTMLGreenGreenYellowFilling,
HTMLGreenSpringGreenFilling,
HTMLGreenMediumSpringGreenFilling,
HTMLGreenLightGreenFilling,
HTMLGreenPaleGreenFilling,
HTMLGreenDarkSeaGreenFilling,
HTMLGreenMediumAquamarineFilling,
HTMLGreenMediumSeaGreenFilling,
HTMLGreenSeaGreenFilling,
HTMLGreenForestGreenFilling,
HTMLGreenGreenFilling, HTMLGreenDarkGreenFilling,
HTMLCyanAquaFilling, HTMLCyanCyanFilling,
HTMLCyanLightCyanFilling,
HTMLCyanPaleTurquoiseFilling,
HTMLCyanAquamarineFilling,
HTMLCyanTurquoiseFilling,
HTMLCyanMediumTurquoiseFilling,
HTMLCyanDarkTurquoiseFilling,
HTMLCyanLightSeaGreenFilling,
HTMLCyanCadetBlueFilling,
HTMLCyanDarkCyanFilling, HTMLCyanTealFilling,
HTMLBlueLightSteelBlueFilling,
HTMLBluePowderBlueFilling,
HTMLBlueLightBlueFilling, HTMLBlueSkyBlueFilling,
HTMLBlueLightSkyBlueFilling,
HTMLBlueDeepSkyBlueFilling,
HTMLBlueDodgerBlueFilling,
HTMLBlueCornflowerBlueFilling,
HTMLBlueSteelBlueFilling,
HTMLBlueRoyalBlueFilling, HTMLBlueBlueFilling,
HTMLBlueMediumBlueFilling,
HTMLBlueDarkBlueFilling, HTMLBlueNavyFilling,
HTMLBlueMidnightBlueFilling,
HTMLPurpleLavenderFilling,
HTMLPurpleThistleFilling, HTMLPurplePlumFilling,
HTMLPurpleVioletFilling, HTMLPurpleOrchidFilling,
HTMLPurpleFuchsiaFilling,
HTMLPurpleMagentaFilling,
HTMLPurpleMediumOrchidFilling,
HTMLPurpleMediumPurpleFilling,
HTMLPurpleBlueVioletFilling,
HTMLPurpleDarkVioletFilling,
HTMLPurpleDarkOrchidFilling,
HTMLPurpleDarkMagentaFilling,
HTMLPurplePurpleFilling, HTMLPurpleIndigoFilling,
HTMLPurpleDarkSlateBlueFilling,
HTMLPurpleSlateBlueFilling,
HTMLPurpleMediumSlateBlueFilling,
HTMLWhiteWhiteFilling, HTMLWhiteSnowFilling,
HTMLWhiteHoneydewFilling,
HTMLWhiteMintCreamFilling, HTMLWhiteAzureFilling,
HTMLWhiteAliceBlueFilling,
HTMLWhiteGhostWhiteFilling,
HTMLWhiteWhiteSmokeFilling,
HTMLWhiteSeashellFilling, HTMLWhiteBeigeFilling,
HTMLWhiteOldLaceFilling,
HTMLWhiteFloralWhiteFilling,
HTMLWhiteIvoryFilling,
HTMLWhiteAntiqueWhiteFilling,
HTMLWhiteLinenFilling,
HTMLWhiteLavenderBlushFilling,
HTMLWhiteMistyRoseFilling,
HTMLGrayGainsboroFilling,
HTMLGrayLightGrayFilling, HTMLGraySilverFilling,
HTMLGrayDarkGrayFilling, HTMLGrayGrayFilling,
HTMLGrayDimGrayFilling,
HTMLGrayLightSlateGrayFilling,
HTMLGraySlateGrayFilling,
HTMLGrayDarkSlateGrayFilling,
HTMLGrayBlackFilling, HorFilling, VerFilling,
BdiagFilling, FdiagFilling};
Q_ENUM (Filling)
//Filling color of the part : NoneFilling -> No filling (i.e. transparent)
enum Filling { NoneFilling, BlackFilling, WhiteFilling,
GreenFilling, RedFilling, BlueFilling,
GrayFilling, BrunFilling, YellowFilling,
CyanFilling, MagentaFilling, LightgrayFilling,
OrangeFilling, PurpleFilling,
HTMLPinkPinkFilling, HTMLPinkLightPinkFilling,
HTMLPinkHotPinkFilling, HTMLPinkDeepPinkFilling,
HTMLPinkPaleVioletRedFilling,
HTMLPinkMediumVioletRedFilling,
HTMLRedLightSalmonFilling, HTMLRedSalmonFilling,
HTMLRedDarkSalmonFilling,
HTMLRedLightCoralFilling,
HTMLRedIndianRedFilling, HTMLRedCrimsonFilling,
HTMLRedFirebrickFilling, HTMLRedDarkRedFilling,
HTMLRedRedFilling, HTMLOrangeOrangeRedFilling,
HTMLOrangeTomatoFilling, HTMLOrangeCoralFilling,
HTMLOrangeDarkOrangeFilling,
HTMLOrangeOrangeFilling, HTMLYellowYellowFilling,
HTMLYellowLightYellowFilling,
HTMLYellowLemonChiffonFilling,
HTMLYellowLightGoldenrodYellowFilling,
HTMLYellowPapayaWhipFilling,
HTMLYellowMoccasinFilling,
HTMLYellowPeachPuffFilling,
HTMLYellowPaleGoldenrodFilling,
HTMLYellowKhakiFilling,
HTMLYellowDarkKhakiFilling,
HTMLYellowGoldFilling, HTMLBrownCornsilkFilling,
HTMLBrownBlanchedAlmondFilling,
HTMLBrownBisqueFilling,
HTMLBrownNavajoWhiteFilling,
HTMLBrownWheatFilling, HTMLBrownBurlywoodFilling,
HTMLBrownTanFilling, HTMLBrownRosyBrownFilling,
HTMLBrownSandyBrownFilling,
HTMLBrownGoldenrodFilling,
HTMLBrownDarkGoldenrodFilling,
HTMLBrownPeruFilling, HTMLBrownChocolateFilling,
HTMLBrownSaddleBrownFilling,
HTMLBrownSiennaFilling, HTMLBrownBrownFilling,
HTMLBrownMaroonFilling,
HTMLGreenDarkOliveGreenFilling,
HTMLGreenOliveFilling, HTMLGreenOliveDrabFilling,
HTMLGreenYellowGreenFilling,
HTMLGreenLimeGreenFilling, HTMLGreenLimeFilling,
HTMLGreenLawnGreenFilling,
HTMLGreenChartreuseFilling,
HTMLGreenGreenYellowFilling,
HTMLGreenSpringGreenFilling,
HTMLGreenMediumSpringGreenFilling,
HTMLGreenLightGreenFilling,
HTMLGreenPaleGreenFilling,
HTMLGreenDarkSeaGreenFilling,
HTMLGreenMediumAquamarineFilling,
HTMLGreenMediumSeaGreenFilling,
HTMLGreenSeaGreenFilling,
HTMLGreenForestGreenFilling,
HTMLGreenGreenFilling, HTMLGreenDarkGreenFilling,
HTMLCyanAquaFilling, HTMLCyanCyanFilling,
HTMLCyanLightCyanFilling,
HTMLCyanPaleTurquoiseFilling,
HTMLCyanAquamarineFilling,
HTMLCyanTurquoiseFilling,
HTMLCyanMediumTurquoiseFilling,
HTMLCyanDarkTurquoiseFilling,
HTMLCyanLightSeaGreenFilling,
HTMLCyanCadetBlueFilling,
HTMLCyanDarkCyanFilling, HTMLCyanTealFilling,
HTMLBlueLightSteelBlueFilling,
HTMLBluePowderBlueFilling,
HTMLBlueLightBlueFilling, HTMLBlueSkyBlueFilling,
HTMLBlueLightSkyBlueFilling,
HTMLBlueDeepSkyBlueFilling,
HTMLBlueDodgerBlueFilling,
HTMLBlueCornflowerBlueFilling,
HTMLBlueSteelBlueFilling,
HTMLBlueRoyalBlueFilling, HTMLBlueBlueFilling,
HTMLBlueMediumBlueFilling,
HTMLBlueDarkBlueFilling, HTMLBlueNavyFilling,
HTMLBlueMidnightBlueFilling,
HTMLPurpleLavenderFilling,
HTMLPurpleThistleFilling, HTMLPurplePlumFilling,
HTMLPurpleVioletFilling, HTMLPurpleOrchidFilling,
HTMLPurpleFuchsiaFilling,
HTMLPurpleMagentaFilling,
HTMLPurpleMediumOrchidFilling,
HTMLPurpleMediumPurpleFilling,
HTMLPurpleBlueVioletFilling,
HTMLPurpleDarkVioletFilling,
HTMLPurpleDarkOrchidFilling,
HTMLPurpleDarkMagentaFilling,
HTMLPurplePurpleFilling, HTMLPurpleIndigoFilling,
HTMLPurpleDarkSlateBlueFilling,
HTMLPurpleSlateBlueFilling,
HTMLPurpleMediumSlateBlueFilling,
HTMLWhiteWhiteFilling, HTMLWhiteSnowFilling,
HTMLWhiteHoneydewFilling,
HTMLWhiteMintCreamFilling, HTMLWhiteAzureFilling,
HTMLWhiteAliceBlueFilling,
HTMLWhiteGhostWhiteFilling,
HTMLWhiteWhiteSmokeFilling,
HTMLWhiteSeashellFilling, HTMLWhiteBeigeFilling,
HTMLWhiteOldLaceFilling,
HTMLWhiteFloralWhiteFilling,
HTMLWhiteIvoryFilling,
HTMLWhiteAntiqueWhiteFilling,
HTMLWhiteLinenFilling,
HTMLWhiteLavenderBlushFilling,
HTMLWhiteMistyRoseFilling,
HTMLGrayGainsboroFilling,
HTMLGrayLightGrayFilling, HTMLGraySilverFilling,
HTMLGrayDarkGrayFilling, HTMLGrayGrayFilling,
HTMLGrayDimGrayFilling,
HTMLGrayLightSlateGrayFilling,
HTMLGraySlateGrayFilling,
HTMLGrayDarkSlateGrayFilling,
HTMLGrayBlackFilling, HorFilling, VerFilling,
BdiagFilling, FdiagFilling};
Q_ENUM (Filling)
//Line color
enum Color {
BlackColor, WhiteColor, GreenColor, RedColor, BlueColor,
GrayColor, BrunColor, YellowColor, CyanColor,
MagentaColor, LightgrayColor, OrangeColor, PurpleColor,
HTMLPinkPinkColor, HTMLPinkLightPinkColor,
HTMLPinkHotPinkColor, HTMLPinkDeepPinkColor,
HTMLPinkPaleVioletRedColor,
HTMLPinkMediumVioletRedColor, HTMLRedLightSalmonColor,
HTMLRedSalmonColor, HTMLRedDarkSalmonColor,
HTMLRedLightCoralColor, HTMLRedIndianRedColor,
HTMLRedCrimsonColor, HTMLRedFirebrickColor,
HTMLRedDarkRedColor, HTMLRedRedColor,
HTMLOrangeOrangeRedColor, HTMLOrangeTomatoColor,
HTMLOrangeCoralColor, HTMLOrangeDarkOrangeColor,
HTMLOrangeOrangeColor, HTMLYellowYellowColor,
HTMLYellowLightYellowColor, HTMLYellowLemonChiffonColor,
HTMLYellowLightGoldenrodYellowColor,
HTMLYellowPapayaWhipColor, HTMLYellowMoccasinColor,
HTMLYellowPeachPuffColor, HTMLYellowPaleGoldenrodColor,
HTMLYellowKhakiColor, HTMLYellowDarkKhakiColor,
HTMLYellowGoldColor, HTMLBrownCornsilkColor,
HTMLBrownBlanchedAlmondColor, HTMLBrownBisqueColor,
HTMLBrownNavajoWhiteColor, HTMLBrownWheatColor,
HTMLBrownBurlywoodColor, HTMLBrownTanColor,
HTMLBrownRosyBrownColor, HTMLBrownSandyBrownColor,
HTMLBrownGoldenrodColor, HTMLBrownDarkGoldenrodColor,
HTMLBrownPeruColor, HTMLBrownChocolateColor,
HTMLBrownSaddleBrownColor, HTMLBrownSiennaColor,
HTMLBrownBrownColor, HTMLBrownMaroonColor,
HTMLGreenDarkOliveGreenColor, HTMLGreenOliveColor,
HTMLGreenOliveDrabColor, HTMLGreenYellowGreenColor,
HTMLGreenLimeGreenColor, HTMLGreenLimeColor,
HTMLGreenLawnGreenColor, HTMLGreenChartreuseColor,
HTMLGreenGreenYellowColor, HTMLGreenSpringGreenColor,
HTMLGreenMediumSpringGreenColor,
HTMLGreenLightGreenColor, HTMLGreenPaleGreenColor,
HTMLGreenDarkSeaGreenColor,
HTMLGreenMediumAquamarineColor,
HTMLGreenMediumSeaGreenColor, HTMLGreenSeaGreenColor,
HTMLGreenForestGreenColor, HTMLGreenGreenColor,
HTMLGreenDarkGreenColor, HTMLCyanAquaColor,
HTMLCyanCyanColor, HTMLCyanLightCyanColor,
HTMLCyanPaleTurquoiseColor, HTMLCyanAquamarineColor,
HTMLCyanTurquoiseColor, HTMLCyanMediumTurquoiseColor,
HTMLCyanDarkTurquoiseColor, HTMLCyanLightSeaGreenColor,
HTMLCyanCadetBlueColor, HTMLCyanDarkCyanColor,
HTMLCyanTealColor, HTMLBlueLightSteelBlueColor,
HTMLBluePowderBlueColor, HTMLBlueLightBlueColor,
HTMLBlueSkyBlueColor, HTMLBlueLightSkyBlueColor,
HTMLBlueDeepSkyBlueColor, HTMLBlueDodgerBlueColor,
HTMLBlueCornflowerBlueColor, HTMLBlueSteelBlueColor,
HTMLBlueRoyalBlueColor, HTMLBlueBlueColor,
HTMLBlueMediumBlueColor, HTMLBlueDarkBlueColor,
HTMLBlueNavyColor, HTMLBlueMidnightBlueColor,
HTMLPurpleLavenderColor, HTMLPurpleThistleColor,
HTMLPurplePlumColor, HTMLPurpleVioletColor,
HTMLPurpleOrchidColor, HTMLPurpleFuchsiaColor,
HTMLPurpleMagentaColor, HTMLPurpleMediumOrchidColor,
HTMLPurpleMediumPurpleColor, HTMLPurpleBlueVioletColor,
HTMLPurpleDarkVioletColor, HTMLPurpleDarkOrchidColor,
HTMLPurpleDarkMagentaColor, HTMLPurplePurpleColor,
HTMLPurpleIndigoColor, HTMLPurpleDarkSlateBlueColor,
HTMLPurpleSlateBlueColor,
HTMLPurpleMediumSlateBlueColor,
HTMLWhiteWhiteColor, HTMLWhiteSnowColor,
HTMLWhiteHoneydewColor, HTMLWhiteMintCreamColor,
HTMLWhiteAzureColor, HTMLWhiteAliceBlueColor,
HTMLWhiteGhostWhiteColor, HTMLWhiteWhiteSmokeColor,
HTMLWhiteSeashellColor, HTMLWhiteBeigeColor,
HTMLWhiteOldLaceColor, HTMLWhiteFloralWhiteColor,
HTMLWhiteIvoryColor, HTMLWhiteAntiqueWhiteColor,
HTMLWhiteLinenColor, HTMLWhiteLavenderBlushColor,
HTMLWhiteMistyRoseColor, HTMLGrayGainsboroColor,
HTMLGrayLightGrayColor, HTMLGraySilverColor,
HTMLGrayDarkGrayColor, HTMLGrayGrayColor,
HTMLGrayDimGrayColor, HTMLGrayLightSlateGrayColor,
HTMLGraySlateGrayColor, HTMLGrayDarkSlateGrayColor,
HTMLGrayBlackColor, NoneColor};
Q_ENUM (Color)
//Line color
enum Color {
BlackColor, WhiteColor, GreenColor, RedColor, BlueColor,
GrayColor, BrunColor, YellowColor, CyanColor,
MagentaColor, LightgrayColor, OrangeColor, PurpleColor,
HTMLPinkPinkColor, HTMLPinkLightPinkColor,
HTMLPinkHotPinkColor, HTMLPinkDeepPinkColor,
HTMLPinkPaleVioletRedColor,
HTMLPinkMediumVioletRedColor, HTMLRedLightSalmonColor,
HTMLRedSalmonColor, HTMLRedDarkSalmonColor,
HTMLRedLightCoralColor, HTMLRedIndianRedColor,
HTMLRedCrimsonColor, HTMLRedFirebrickColor,
HTMLRedDarkRedColor, HTMLRedRedColor,
HTMLOrangeOrangeRedColor, HTMLOrangeTomatoColor,
HTMLOrangeCoralColor, HTMLOrangeDarkOrangeColor,
HTMLOrangeOrangeColor, HTMLYellowYellowColor,
HTMLYellowLightYellowColor, HTMLYellowLemonChiffonColor,
HTMLYellowLightGoldenrodYellowColor,
HTMLYellowPapayaWhipColor, HTMLYellowMoccasinColor,
HTMLYellowPeachPuffColor, HTMLYellowPaleGoldenrodColor,
HTMLYellowKhakiColor, HTMLYellowDarkKhakiColor,
HTMLYellowGoldColor, HTMLBrownCornsilkColor,
HTMLBrownBlanchedAlmondColor, HTMLBrownBisqueColor,
HTMLBrownNavajoWhiteColor, HTMLBrownWheatColor,
HTMLBrownBurlywoodColor, HTMLBrownTanColor,
HTMLBrownRosyBrownColor, HTMLBrownSandyBrownColor,
HTMLBrownGoldenrodColor, HTMLBrownDarkGoldenrodColor,
HTMLBrownPeruColor, HTMLBrownChocolateColor,
HTMLBrownSaddleBrownColor, HTMLBrownSiennaColor,
HTMLBrownBrownColor, HTMLBrownMaroonColor,
HTMLGreenDarkOliveGreenColor, HTMLGreenOliveColor,
HTMLGreenOliveDrabColor, HTMLGreenYellowGreenColor,
HTMLGreenLimeGreenColor, HTMLGreenLimeColor,
HTMLGreenLawnGreenColor, HTMLGreenChartreuseColor,
HTMLGreenGreenYellowColor, HTMLGreenSpringGreenColor,
HTMLGreenMediumSpringGreenColor,
HTMLGreenLightGreenColor, HTMLGreenPaleGreenColor,
HTMLGreenDarkSeaGreenColor,
HTMLGreenMediumAquamarineColor,
HTMLGreenMediumSeaGreenColor, HTMLGreenSeaGreenColor,
HTMLGreenForestGreenColor, HTMLGreenGreenColor,
HTMLGreenDarkGreenColor, HTMLCyanAquaColor,
HTMLCyanCyanColor, HTMLCyanLightCyanColor,
HTMLCyanPaleTurquoiseColor, HTMLCyanAquamarineColor,
HTMLCyanTurquoiseColor, HTMLCyanMediumTurquoiseColor,
HTMLCyanDarkTurquoiseColor, HTMLCyanLightSeaGreenColor,
HTMLCyanCadetBlueColor, HTMLCyanDarkCyanColor,
HTMLCyanTealColor, HTMLBlueLightSteelBlueColor,
HTMLBluePowderBlueColor, HTMLBlueLightBlueColor,
HTMLBlueSkyBlueColor, HTMLBlueLightSkyBlueColor,
HTMLBlueDeepSkyBlueColor, HTMLBlueDodgerBlueColor,
HTMLBlueCornflowerBlueColor, HTMLBlueSteelBlueColor,
HTMLBlueRoyalBlueColor, HTMLBlueBlueColor,
HTMLBlueMediumBlueColor, HTMLBlueDarkBlueColor,
HTMLBlueNavyColor, HTMLBlueMidnightBlueColor,
HTMLPurpleLavenderColor, HTMLPurpleThistleColor,
HTMLPurplePlumColor, HTMLPurpleVioletColor,
HTMLPurpleOrchidColor, HTMLPurpleFuchsiaColor,
HTMLPurpleMagentaColor, HTMLPurpleMediumOrchidColor,
HTMLPurpleMediumPurpleColor, HTMLPurpleBlueVioletColor,
HTMLPurpleDarkVioletColor, HTMLPurpleDarkOrchidColor,
HTMLPurpleDarkMagentaColor, HTMLPurplePurpleColor,
HTMLPurpleIndigoColor, HTMLPurpleDarkSlateBlueColor,
HTMLPurpleSlateBlueColor,
HTMLPurpleMediumSlateBlueColor,
HTMLWhiteWhiteColor, HTMLWhiteSnowColor,
HTMLWhiteHoneydewColor, HTMLWhiteMintCreamColor,
HTMLWhiteAzureColor, HTMLWhiteAliceBlueColor,
HTMLWhiteGhostWhiteColor, HTMLWhiteWhiteSmokeColor,
HTMLWhiteSeashellColor, HTMLWhiteBeigeColor,
HTMLWhiteOldLaceColor, HTMLWhiteFloralWhiteColor,
HTMLWhiteIvoryColor, HTMLWhiteAntiqueWhiteColor,
HTMLWhiteLinenColor, HTMLWhiteLavenderBlushColor,
HTMLWhiteMistyRoseColor, HTMLGrayGainsboroColor,
HTMLGrayLightGrayColor, HTMLGraySilverColor,
HTMLGrayDarkGrayColor, HTMLGrayGrayColor,
HTMLGrayDimGrayColor, HTMLGrayLightSlateGrayColor,
HTMLGraySlateGrayColor, HTMLGrayDarkSlateGrayColor,
HTMLGrayBlackColor, NoneColor};
Q_ENUM (Color)
// constructors, destructor
public:
// constructors, destructor
public:
CustomElementGraphicPart(QETElementEditor *editor,
QGraphicsItem *parent = nullptr);
~CustomElementGraphicPart() override;
CustomElementGraphicPart(QETElementEditor *editor,
QGraphicsItem *parent = nullptr);
~CustomElementGraphicPart() override;
static void drawCross (const QPointF &center,
QPainter *painter);
static void drawCross (const QPointF &center,
QPainter *painter);
//Getter and setter
LineStyle lineStyle () const {return _linestyle;}
void setLineStyle (const LineStyle ls);
//Getter and setter
LineStyle lineStyle () const {return _linestyle;}
void setLineStyle (const LineStyle ls);
LineWeight lineWeight () const {return _lineweight;}
void setLineWeight (const LineWeight lw);
qreal penWeight () const;
LineWeight lineWeight () const {return _lineweight;}
void setLineWeight (const LineWeight lw);
qreal penWeight () const;
Filling filling () const {return _filling;}
void setFilling(const Filling f);
Filling filling () const {return _filling;}
void setFilling(const Filling f);
Color color () const {return _color;}
void setColor(const Color c);
Color color () const {return _color;}
void setColor(const Color c);
bool antialiased () const {return _antialiased;}
void setAntialiased(const bool b);
//End of getter and setter
bool antialiased () const {return _antialiased;}
void setAntialiased(const bool b);
//End of getter and setter
//Rediriged to QObject Q_PROPERTY system
void setProperty (const char *name,
const QVariant &value) override {
QObject::setProperty(name, value);}
QVariant property (const char *name) const override {
return QObject::property(name);}
//Rediriged to QObject Q_PROPERTY system
void setProperty (const char *name,
const QVariant &value) override {
QObject::setProperty(name, value);}
QVariant property (const char *name) const override {
return QObject::property(name);}
virtual QPainterPath shadowShape ()const = 0;
virtual void setHandlerColor(QPointF /*pos*/,
const QColor &/*color*/) {}
virtual void resetAllHandlerColor() {}
virtual QPainterPath shadowShape ()const = 0;
virtual void setHandlerColor(QPointF /*pos*/,
const QColor &/*color*/) {}
virtual void resetAllHandlerColor() {}
protected:
void stylesToXml (QDomDocument &xml_document, QDomElement &) const;
void stylesFromXml(const QDomElement &);
void resetStyles ();
void applyStylesToQPainter(QPainter &) const;
void drawShadowShape (QPainter *painter);
protected:
void stylesToXml (QDomDocument &xml_document, QDomElement &) const;
void stylesFromXml(const QDomElement &);
void resetStyles ();
void applyStylesToQPainter(QPainter &) const;
void drawShadowShape (QPainter *painter);
QVariant itemChange(GraphicsItemChange change,
const QVariant &value) override;
void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override;
void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override;
QVariant itemChange(GraphicsItemChange change,
const QVariant &value) override;
void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override;
void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override;
void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
void mouseReleaseEvent(
QGraphicsSceneMouseEvent *event) override;
void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
void mouseReleaseEvent(
QGraphicsSceneMouseEvent *event) override;
// attributes
bool m_hovered;
private:
LineStyle _linestyle;
LineWeight _lineweight;
Filling _filling ;
Color _color;
bool _antialiased;
QPointF m_origin_pos;
// attributes
bool m_hovered;
private:
LineStyle _linestyle;
LineWeight _lineweight;
Filling _filling ;
Color _color;
bool _antialiased;
QPointF m_origin_pos;
};
typedef CustomElementGraphicPart CEGP;

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CUSTOM_ELEMENT_PART_H
#define CUSTOM_ELEMENT_PART_H
@@ -30,86 +30,86 @@ class QGraphicsItem;
class QGraphicsSceneMouseEvent;
/**
@brief The CustomElementPart class
This abstract class represents a primitive of
the visual representation of an electrical element.
The Element, FixedElement and CustomElement classes do not embed
its attributes and methods in order to remain lightweight; indeed,
there is no point for those classes to store their visual representation
with anything more complex than a QImage.
@brief The CustomElementPart class
This abstract class represents a primitive of
the visual representation of an electrical element.
The Element, FixedElement and CustomElement classes do not embed
its attributes and methods in order to remain lightweight; indeed,
there is no point for those classes to store their visual representation
with anything more complex than a QImage.
*/
class CustomElementPart: public PropertiesInterface {
// constructors, destructor
public:
/**
@brief CustomElementPart
Constructor
@param editor Element editor this primitive is attached to
*/
CustomElementPart(QETElementEditor *editor) : element_editor(editor) {}
/**
@brief ~CustomElementPart
Destructor
*/
virtual ~CustomElementPart() {}
// constructors, destructor
public:
/**
@brief CustomElementPart
Constructor
@param editor Element editor this primitive is attached to
*/
CustomElementPart(QETElementEditor *editor) : element_editor(editor) {}
/**
@brief ~CustomElementPart
Destructor
*/
virtual ~CustomElementPart() {}
private:
CustomElementPart(const CustomElementPart &);
private:
CustomElementPart(const CustomElementPart &);
// attributes
private:
QETElementEditor *element_editor;
// attributes
private:
QETElementEditor *element_editor;
// methods
public:
/**
Set a specific property of the primitive
*/
virtual void setProperty(const char *name, const QVariant &value) = 0;
/**
Get the current value of a specific primitive property
*/
virtual QVariant property(const char *name) const = 0;
/**
@return whether the primitive appears to be useless (e.g. 0-length line)
Typically, useless primitives are discarded when saving the element.
*/
virtual bool isUseless() const = 0;
virtual QRectF sceneGeometricRect() const = 0;
/**
Inform this part a user-induced transformation is about to begin.
This method can be used to save data required by handleUserTransformation().
*/
virtual void startUserTransformation(const QRectF &) = 0;
/**
Make this part fit into the provided rectangle.
*/
virtual void handleUserTransformation(const QRectF &,
const QRectF &) = 0;
/// @return a pointer to the parent element editor
virtual QETElementEditor *elementEditor() const;
/**
Call the updateCurrentPartEditor() slot of the editor
@see QETElementEditor::updateCurrentPartEditor()
*/
virtual void updateCurrentPartEditor() const;
/// @return a pointer to the parent editing scene
virtual ElementScene *elementScene() const;
/// @return the element editor undo stack
virtual QUndoStack &undoStack() const;
/// @return the name of the primitive
virtual QString name() const = 0;
/// @return the name that will be used as XML tag when exporting the primitive
virtual QString xmlName() const = 0;
// methods
public:
/**
Set a specific property of the primitive
*/
virtual void setProperty(const char *name, const QVariant &value) = 0;
/**
Get the current value of a specific primitive property
*/
virtual QVariant property(const char *name) const = 0;
/**
@return whether the primitive appears to be useless (e.g. 0-length line)
Typically, useless primitives are discarded when saving the element.
*/
virtual bool isUseless() const = 0;
virtual QRectF sceneGeometricRect() const = 0;
/**
Inform this part a user-induced transformation is about to begin.
This method can be used to save data required by handleUserTransformation().
*/
virtual void startUserTransformation(const QRectF &) = 0;
/**
Make this part fit into the provided rectangle.
*/
virtual void handleUserTransformation(const QRectF &,
const QRectF &) = 0;
/// @return a pointer to the parent element editor
virtual QETElementEditor *elementEditor() const;
/**
Call the updateCurrentPartEditor() slot of the editor
@see QETElementEditor::updateCurrentPartEditor()
*/
virtual void updateCurrentPartEditor() const;
/// @return a pointer to the parent editing scene
virtual ElementScene *elementScene() const;
/// @return the element editor undo stack
virtual QUndoStack &undoStack() const;
/// @return the name of the primitive
virtual QString name() const = 0;
/// @return the name that will be used as XML tag when exporting the primitive
virtual QString xmlName() const = 0;
virtual QGraphicsItem *toItem();
virtual QGraphicsItem *toItem();
virtual QET::ScalingMethod preferredScalingMethod() const;
virtual QET::ScalingMethod preferredScalingMethod() const;
protected:
QList<QPointF> mapPoints(
const QRectF &,
const QRectF &,
const QList<QPointF> &);
protected:
QList<QPointF> mapPoints(
const QRectF &,
const QRectF &,
const QList<QPointF> &);
};
#endif

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#include "partarc.h"
#include "QPropertyUndoCommand/qpropertyundocommand.h"
@@ -23,173 +23,173 @@
/**
@brief PartArc::PartArc
Constructor
@param editor : QETElementEditor of this part
@param parent : parent item
@brief PartArc::PartArc
Constructor
@param editor : QETElementEditor of this part
@param parent : parent item
*/
PartArc::PartArc(QETElementEditor *editor, QGraphicsItem *parent) :
AbstractPartEllipse(editor, parent)
AbstractPartEllipse(editor, parent)
{
m_start_angle = 0;
m_span_angle = -1440;
m_start_angle = 0;
m_span_angle = -1440;
}
/**
@brief PartArc::~PartArc
Destructor
@brief PartArc::~PartArc
Destructor
*/
PartArc::~PartArc()
{
if(m_undo_command) delete m_undo_command;
removeHandler();
if(m_undo_command) delete m_undo_command;
removeHandler();
}
/**
@brief PartArc::paint
Draw this arc
@param painter
@param options
@param widget
@brief PartArc::paint
Draw this arc
@param painter
@param options
@param widget
*/
void PartArc::paint(QPainter *painter, const QStyleOptionGraphicsItem *options, QWidget *widget)
{
Q_UNUSED(widget)
Q_UNUSED(widget)
applyStylesToQPainter(*painter);
applyStylesToQPainter(*painter);
//Always remove the brush
painter -> setBrush(Qt::NoBrush);
QPen t = painter -> pen();
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
t.setCosmetic(options && options -> levelOfDetail < 1.0);
//Always remove the brush
painter -> setBrush(Qt::NoBrush);
QPen t = painter -> pen();
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
t.setCosmetic(options && options -> levelOfDetail < 1.0);
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
t.setCosmetic(options && options -> levelOfDetailFromTransform(painter->worldTransform()) < 1.0);
t.setCosmetic(options && options -> levelOfDetailFromTransform(painter->worldTransform()) < 1.0);
#endif
painter -> setPen(t);
painter -> setPen(t);
if (isSelected())
{
painter->save();
QPen pen(Qt::DotLine);
pen.setWidth(1);
pen.setCosmetic(true);
painter->setPen(pen);
//Draw the ellipse in black
painter -> drawEllipse(rect());
painter->restore();
if (isSelected())
{
painter->save();
QPen pen(Qt::DotLine);
pen.setWidth(1);
pen.setCosmetic(true);
painter->setPen(pen);
//Draw the ellipse in black
painter -> drawEllipse(rect());
painter->restore();
//Draw the arc in red
t.setColor(Qt::red);
painter -> setPen(t);
}
//Draw the arc in red
t.setColor(Qt::red);
painter -> setPen(t);
}
painter->drawArc(m_rect, m_start_angle, m_span_angle);
painter->drawArc(m_rect, m_start_angle, m_span_angle);
if (m_hovered)
drawShadowShape(painter);
if (m_hovered)
drawShadowShape(painter);
if (isSelected())
drawCross(m_rect.center(), painter);
if (isSelected())
drawCross(m_rect.center(), painter);
}
/**
@brief PartArc::toXml
Export this arc in xml
@param xml_document : Xml document to use for create the xml element.
@return : an xml element that describe this arc
@brief PartArc::toXml
Export this arc in xml
@param xml_document : Xml document to use for create the xml element.
@return : an xml element that describe this arc
*/
QDomElement PartArc::toXml(QDomDocument &xml_document) const {
{
QDomElement xml_element = xml_document.createElement("arc");
QPointF top_left(sceneTopLeft());
QDomElement xml_element = xml_document.createElement("arc");
QPointF top_left(sceneTopLeft());
xml_element.appendChild(createXmlProperty(xml_document, "x", top_left.x()));
xml_element.appendChild(createXmlProperty(xml_document, "y", top_left.y()));
xml_element.appendChild(createXmlProperty(xml_document, "width", rect().width()));
xml_element.appendChild(createXmlProperty(xml_document, "height", rect().height()));
xml_element.appendChild(createXmlProperty(xml_document, "x", top_left.x()));
xml_element.appendChild(createXmlProperty(xml_document, "y", top_left.y()));
xml_element.appendChild(createXmlProperty(xml_document, "width", rect().width()));
xml_element.appendChild(createXmlProperty(xml_document, "height", rect().height()));
//to maintain compatibility with the previous version, we write the angle in degrees.
xml_element.appendChild(createXmlProperty(xml_document, "start", m_start_angle / 16));
xml_element.appendChild(createXmlProperty(xml_document, "angle", m_span_angle / 16));
//to maintain compatibility with the previous version, we write the angle in degrees.
xml_element.appendChild(createXmlProperty(xml_document, "start", m_start_angle / 16));
xml_element.appendChild(createXmlProperty(xml_document, "angle", m_span_angle / 16));
stylesToXml(xml_document, xml_element);
return(xml_element);
stylesToXml(xml_document, xml_element);
return(xml_element);
}
/**
@brief PartArc::fromXml
Import the properties of this arc from a xml element.
@param qde : Xml document to use.
@brief PartArc::fromXml
Import the properties of this arc from a xml element.
@param qde : Xml document to use.
*/
bool PartArc::fromXml(const QDomElement &qde) {
stylesFromXml(qde);
stylesFromXml(qde);
double x=0, y=0, w=0, h=0;
if (propertyDouble(qde, "x", &x) == PropertyFlags::NoValidConversion ||
propertyDouble(qde, "y", &y) == PropertyFlags::NoValidConversion ||
propertyDouble(qde, "width", &w) == PropertyFlags::NoValidConversion ||
propertyDouble(qde, "height", &h) == PropertyFlags::NoValidConversion)
return false;
double x=0, y=0, w=0, h=0;
if (propertyDouble(qde, "x", &x) == PropertyFlags::NoValidConversion ||
propertyDouble(qde, "y", &y) == PropertyFlags::NoValidConversion ||
propertyDouble(qde, "width", &w) == PropertyFlags::NoValidConversion ||
propertyDouble(qde, "height", &h) == PropertyFlags::NoValidConversion)
return false;
m_rect = QRectF(mapFromScene(x, y), QSizeF(w, h) );
m_rect = QRectF(mapFromScene(x, y), QSizeF(w, h) );
m_start_angle = 0;
if (propertyDouble(qde, "start", &m_start_angle) == PropertyFlags::NoValidConversion)
return false;
m_start_angle *= 16;
m_start_angle = 0;
if (propertyDouble(qde, "start", &m_start_angle) == PropertyFlags::NoValidConversion)
return false;
m_start_angle *= 16;
m_span_angle = -1440;
if (propertyDouble(qde, "angle", &m_span_angle) == PropertyFlags::NoValidConversion)
return false;
m_span_angle *= 16;
m_span_angle = -1440;
if (propertyDouble(qde, "angle", &m_span_angle) == PropertyFlags::NoValidConversion)
return false;
m_span_angle *= 16;
return true;
return true;
}
bool PartArc::valideXml(QDomElement& element) {
if (propertyDouble(element, "x") == PropertyFlags::NoValidConversion ||
propertyDouble(element, "y") == PropertyFlags::NoValidConversion ||
propertyDouble(element, "width") == PropertyFlags::NoValidConversion ||
propertyDouble(element, "height") == PropertyFlags::NoValidConversion ||
propertyDouble(element, "start") == PropertyFlags::NoValidConversion ||
propertyDouble(element, "angle") == PropertyFlags::NoValidConversion)
return false;
return true;
if (propertyDouble(element, "x") == PropertyFlags::NoValidConversion ||
propertyDouble(element, "y") == PropertyFlags::NoValidConversion ||
propertyDouble(element, "width") == PropertyFlags::NoValidConversion ||
propertyDouble(element, "height") == PropertyFlags::NoValidConversion ||
propertyDouble(element, "start") == PropertyFlags::NoValidConversion ||
propertyDouble(element, "angle") == PropertyFlags::NoValidConversion)
return false;
return true;
}
/**
@brief PartArc::shape
@return the shape of this item
@brief PartArc::shape
@return the shape of this item
*/
QPainterPath PartArc::shape() const
{
QPainterPath shape;
shape.arcMoveTo(m_rect, m_start_angle/16);
shape.arcTo(m_rect, m_start_angle /16, m_span_angle /16);
QPainterPath shape;
shape.arcMoveTo(m_rect, m_start_angle/16);
shape.arcTo(m_rect, m_start_angle /16, m_span_angle /16);
QPainterPathStroker pps;
pps.setWidth(m_hovered? penWeight()+SHADOWS_HEIGHT : penWeight());
shape = pps.createStroke(shape);
QPainterPathStroker pps;
pps.setWidth(m_hovered? penWeight()+SHADOWS_HEIGHT : penWeight());
shape = pps.createStroke(shape);
return shape;
return shape;
}
QPainterPath PartArc::shadowShape() const
{
QPainterPath shape;
shape.arcMoveTo(m_rect, m_start_angle/16);
shape.arcTo(m_rect, m_start_angle /16, m_span_angle /16);
QPainterPath shape;
shape.arcMoveTo(m_rect, m_start_angle/16);
shape.arcTo(m_rect, m_start_angle /16, m_span_angle /16);
QPainterPathStroker pps;
pps.setWidth(penWeight());
QPainterPathStroker pps;
pps.setWidth(penWeight());
return (pps.createStroke(shape));
return (pps.createStroke(shape));
}
/**
@@ -203,327 +203,327 @@ QPainterPath PartArc::shadowShape() const
*/
QRectF PartArc::sceneGeometricRect() const
{
return mapToScene(QetGraphicsHandlerUtility::rectForArc(m_rect, m_start_angle/16, m_span_angle/16)).boundingRect();
return mapToScene(QetGraphicsHandlerUtility::rectForArc(m_rect, m_start_angle/16, m_span_angle/16)).boundingRect();
}
/**
@brief PartArc::mouseReleaseEvent
Handle mouse release event
@param event
@brief PartArc::mouseReleaseEvent
Handle mouse release event
@param event
*/
void PartArc::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
if (event->button() == Qt::LeftButton && event->buttonDownPos(Qt::LeftButton) == event->pos())
switchResizeMode();
if (event->button() == Qt::LeftButton && event->buttonDownPos(Qt::LeftButton) == event->pos())
switchResizeMode();
CustomElementGraphicPart::mouseReleaseEvent(event);
CustomElementGraphicPart::mouseReleaseEvent(event);
}
/**
@brief PartArc::itemChange
@param change
@param value
@return
@brief PartArc::itemChange
@param change
@param value
@return
*/
QVariant PartArc::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value)
{
if (change == ItemSelectedHasChanged && scene())
{
if (value.toBool() == true)
{
//When item is selected, he must to be up to date whene the selection in the scene change, for display or not the handler,
//according to the number of selected items.
connect(scene(), &QGraphicsScene::selectionChanged, this, &PartArc::sceneSelectionChanged);
if (change == ItemSelectedHasChanged && scene())
{
if (value.toBool() == true)
{
//When item is selected, he must to be up to date whene the selection in the scene change, for display or not the handler,
//according to the number of selected items.
connect(scene(), &QGraphicsScene::selectionChanged, this, &PartArc::sceneSelectionChanged);
if (scene()->selectedItems().size() == 1)
addHandler();
}
else
{
disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartArc::sceneSelectionChanged);
removeHandler();
}
}
else if (change == ItemPositionHasChanged)
{
adjusteHandlerPos();
}
else if (change == ItemSceneChange)
{
if(scene())
disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartArc::sceneSelectionChanged);
if (scene()->selectedItems().size() == 1)
addHandler();
}
else
{
disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartArc::sceneSelectionChanged);
removeHandler();
}
}
else if (change == ItemPositionHasChanged)
{
adjusteHandlerPos();
}
else if (change == ItemSceneChange)
{
if(scene())
disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartArc::sceneSelectionChanged);
setSelected(false); //This is item removed from scene, then we deselect this, and so, the handlers is also removed.
}
setSelected(false); //This is item removed from scene, then we deselect this, and so, the handlers is also removed.
}
return QGraphicsItem::itemChange(change, value);
return QGraphicsItem::itemChange(change, value);
}
/**
@brief PartArc::sceneEventFilter
@param watched
@param event
@return
@brief PartArc::sceneEventFilter
@param watched
@param event
@return
*/
bool PartArc::sceneEventFilter(QGraphicsItem *watched, QEvent *event)
{
//Watched must be an handler
if(watched->type() == QetGraphicsHandlerItem::Type)
{
QetGraphicsHandlerItem *qghi = qgraphicsitem_cast<QetGraphicsHandlerItem *>(watched);
//Watched must be an handler
if(watched->type() == QetGraphicsHandlerItem::Type)
{
QetGraphicsHandlerItem *qghi = qgraphicsitem_cast<QetGraphicsHandlerItem *>(watched);
if(m_handler_vector.contains(qghi)) //Handler must be in m_vector_index, then we can start resize
{
m_vector_index = m_handler_vector.indexOf(qghi);
if (m_vector_index != -1)
{
if(event->type() == QEvent::GraphicsSceneMousePress) //Click
{
handlerMousePressEvent(qghi, static_cast<QGraphicsSceneMouseEvent *>(event));
return true;
}
else if(event->type() == QEvent::GraphicsSceneMouseMove) //Move
{
handlerMouseMoveEvent(qghi, static_cast<QGraphicsSceneMouseEvent *>(event));
return true;
}
else if (event->type() == QEvent::GraphicsSceneMouseRelease) //Release
{
handlerMouseReleaseEvent(qghi, static_cast<QGraphicsSceneMouseEvent *>(event));
return true;
}
}
}
}
if(m_handler_vector.contains(qghi)) //Handler must be in m_vector_index, then we can start resize
{
m_vector_index = m_handler_vector.indexOf(qghi);
if (m_vector_index != -1)
{
if(event->type() == QEvent::GraphicsSceneMousePress) //Click
{
handlerMousePressEvent(qghi, static_cast<QGraphicsSceneMouseEvent *>(event));
return true;
}
else if(event->type() == QEvent::GraphicsSceneMouseMove) //Move
{
handlerMouseMoveEvent(qghi, static_cast<QGraphicsSceneMouseEvent *>(event));
return true;
}
else if (event->type() == QEvent::GraphicsSceneMouseRelease) //Release
{
handlerMouseReleaseEvent(qghi, static_cast<QGraphicsSceneMouseEvent *>(event));
return true;
}
}
}
}
return false;
return false;
}
/**
@brief PartArc::switchResizeMode
@brief PartArc::switchResizeMode
*/
void PartArc::switchResizeMode()
{
if (m_resize_mode == 1)
{
m_resize_mode = 2;
for (QetGraphicsHandlerItem *qghi : m_handler_vector)
qghi->setColor(Qt::darkGreen);
}
else if (m_resize_mode == 2)
{
m_resize_mode = 3;
if (m_resize_mode == 1)
{
m_resize_mode = 2;
for (QetGraphicsHandlerItem *qghi : m_handler_vector)
qghi->setColor(Qt::darkGreen);
}
else if (m_resize_mode == 2)
{
m_resize_mode = 3;
//From rect mode to angle mode, then numbers of handlers change
removeHandler();
addHandler();
//From rect mode to angle mode, then numbers of handlers change
removeHandler();
addHandler();
for (QetGraphicsHandlerItem *qghi : m_handler_vector)
qghi->setColor(Qt::magenta);
}
else
{
m_resize_mode = 1;
for (QetGraphicsHandlerItem *qghi : m_handler_vector)
qghi->setColor(Qt::magenta);
}
else
{
m_resize_mode = 1;
//From angle mode to rect mode, then numbers of handlers change
removeHandler();
addHandler();
//From angle mode to rect mode, then numbers of handlers change
removeHandler();
addHandler();
for (QetGraphicsHandlerItem *qghi : m_handler_vector)
qghi->setColor(Qt::blue);
}
for (QetGraphicsHandlerItem *qghi : m_handler_vector)
qghi->setColor(Qt::blue);
}
}
/**
@brief PartArc::adjusteHandlerPos
@brief PartArc::adjusteHandlerPos
*/
void PartArc::adjusteHandlerPos()
{
if (m_handler_vector.isEmpty())
return;
if (m_handler_vector.isEmpty())
return;
QVector <QPointF> points_vector;
QVector <QPointF> points_vector;
if(m_resize_mode == 3)
points_vector = QetGraphicsHandlerUtility::pointsForArc(m_rect, m_start_angle/16, m_span_angle/16);
else
points_vector = QetGraphicsHandlerUtility::pointsForRect(m_rect);
if(m_resize_mode == 3)
points_vector = QetGraphicsHandlerUtility::pointsForArc(m_rect, m_start_angle/16, m_span_angle/16);
else
points_vector = QetGraphicsHandlerUtility::pointsForRect(m_rect);
if (m_handler_vector.size() == points_vector.size())
{
points_vector = mapToScene(points_vector);
for (int i = 0 ; i < points_vector.size() ; ++i)
m_handler_vector.at(i)->setPos(points_vector.at(i));
}
if (m_handler_vector.size() == points_vector.size())
{
points_vector = mapToScene(points_vector);
for (int i = 0 ; i < points_vector.size() ; ++i)
m_handler_vector.at(i)->setPos(points_vector.at(i));
}
}
/**
@brief PartArc::handlerMousePressEvent
@param qghi
@param event
@brief PartArc::handlerMousePressEvent
@param qghi
@param event
*/
void PartArc::handlerMousePressEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event)
{
Q_UNUSED(qghi)
Q_UNUSED(event)
Q_UNUSED(qghi)
Q_UNUSED(event)
if (m_resize_mode == 3) //Resize angle
{
if (m_vector_index == 0)
{
m_span_point = QetGraphicsHandlerUtility::pointsForArc(m_rect, m_start_angle/16, m_span_angle/16).at(1);
if (m_resize_mode == 3) //Resize angle
{
if (m_vector_index == 0)
{
m_span_point = QetGraphicsHandlerUtility::pointsForArc(m_rect, m_start_angle/16, m_span_angle/16).at(1);
m_undo_command = new QPropertyUndoCommand(this, "startAngle", QVariant(m_start_angle));
m_undo_command->setText(tr("Modifier un arc"));
m_undo_command->enableAnimation();
m_undo_command = new QPropertyUndoCommand(this, "startAngle", QVariant(m_start_angle));
m_undo_command->setText(tr("Modifier un arc"));
m_undo_command->enableAnimation();
m_undo_command2 = new QPropertyUndoCommand(this, "spanAngle", QVariant(m_span_angle), m_undo_command);
m_undo_command2->setText(tr("Modifier un arc"));
m_undo_command2->enableAnimation();
}
else if (m_vector_index == 1)
{
m_undo_command = new QPropertyUndoCommand(this, "spanAngle", QVariant(m_span_angle));
m_undo_command->setText(tr("Modifier un arc"));
m_undo_command->enableAnimation();
}
}
else //resize rect
{
m_undo_command = new QPropertyUndoCommand(this, "rect", QVariant(m_rect));
m_undo_command->setText(tr("Modifier un arc"));
m_undo_command->enableAnimation();
}
m_undo_command2 = new QPropertyUndoCommand(this, "spanAngle", QVariant(m_span_angle), m_undo_command);
m_undo_command2->setText(tr("Modifier un arc"));
m_undo_command2->enableAnimation();
}
else if (m_vector_index == 1)
{
m_undo_command = new QPropertyUndoCommand(this, "spanAngle", QVariant(m_span_angle));
m_undo_command->setText(tr("Modifier un arc"));
m_undo_command->enableAnimation();
}
}
else //resize rect
{
m_undo_command = new QPropertyUndoCommand(this, "rect", QVariant(m_rect));
m_undo_command->setText(tr("Modifier un arc"));
m_undo_command->enableAnimation();
}
}
/**
@brief PartArc::handlerMouseMoveEvent
@param qghi
@param event
@brief PartArc::handlerMouseMoveEvent
@param qghi
@param event
*/
void PartArc::handlerMouseMoveEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event)
{
Q_UNUSED(qghi)
Q_UNUSED(qghi)
QPointF new_pos = event->scenePos();
if (event->modifiers() != Qt::ControlModifier)
new_pos = elementScene()->snapToGrid(event->scenePos());
new_pos = mapFromScene(new_pos);
QPointF new_pos = event->scenePos();
if (event->modifiers() != Qt::ControlModifier)
new_pos = elementScene()->snapToGrid(event->scenePos());
new_pos = mapFromScene(new_pos);
if (m_resize_mode == 1)
setRect(QetGraphicsHandlerUtility::rectForPosAtIndex(m_rect, new_pos, m_vector_index));
else if (m_resize_mode == 2)
setRect(QetGraphicsHandlerUtility::mirrorRectForPosAtIndex(m_rect, new_pos, m_vector_index));
else
{
QLineF line(m_rect.center(), mapFromScene(event->scenePos()));
prepareGeometryChange();
if (m_resize_mode == 1)
setRect(QetGraphicsHandlerUtility::rectForPosAtIndex(m_rect, new_pos, m_vector_index));
else if (m_resize_mode == 2)
setRect(QetGraphicsHandlerUtility::mirrorRectForPosAtIndex(m_rect, new_pos, m_vector_index));
else
{
QLineF line(m_rect.center(), mapFromScene(event->scenePos()));
prepareGeometryChange();
if (m_vector_index == 0) {
setStartAngle(line.angle()*16);
setSpanAngle(line.angleTo(QLineF(m_rect.center(), m_span_point))*16);
}
else if (m_vector_index == 1) {
QLineF line2(m_rect.center(), QetGraphicsHandlerUtility::pointsForArc(m_rect, m_start_angle/16, m_span_angle/16).at(0));
setSpanAngle (line2.angleTo(line)*16);
}
}
if (m_vector_index == 0) {
setStartAngle(line.angle()*16);
setSpanAngle(line.angleTo(QLineF(m_rect.center(), m_span_point))*16);
}
else if (m_vector_index == 1) {
QLineF line2(m_rect.center(), QetGraphicsHandlerUtility::pointsForArc(m_rect, m_start_angle/16, m_span_angle/16).at(0));
setSpanAngle (line2.angleTo(line)*16);
}
}
}
/**
@brief PartArc::handlerMouseReleaseEvent
@param qghi
@param event
@brief PartArc::handlerMouseReleaseEvent
@param qghi
@param event
*/
void PartArc::handlerMouseReleaseEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event)
{
Q_UNUSED(qghi)
Q_UNUSED(event)
Q_UNUSED(qghi)
Q_UNUSED(event)
if (m_resize_mode == 3)
{
if (m_vector_index == 0)
{
m_undo_command->setNewValue(QVariant(m_start_angle));
m_undo_command2->setNewValue(QVariant(m_span_angle));
elementScene()->undoStack().push(m_undo_command);
m_undo_command = nullptr;
m_undo_command2 = nullptr;
m_vector_index = -1;
}
else if (m_vector_index == 1)
{
m_undo_command->setNewValue(QVariant(m_span_angle));
elementScene()->undoStack().push(m_undo_command);
m_undo_command = nullptr;
m_vector_index = -1;
}
}
else
{
if (!m_rect.isValid())
m_rect = m_rect.normalized();
if (m_resize_mode == 3)
{
if (m_vector_index == 0)
{
m_undo_command->setNewValue(QVariant(m_start_angle));
m_undo_command2->setNewValue(QVariant(m_span_angle));
elementScene()->undoStack().push(m_undo_command);
m_undo_command = nullptr;
m_undo_command2 = nullptr;
m_vector_index = -1;
}
else if (m_vector_index == 1)
{
m_undo_command->setNewValue(QVariant(m_span_angle));
elementScene()->undoStack().push(m_undo_command);
m_undo_command = nullptr;
m_vector_index = -1;
}
}
else
{
if (!m_rect.isValid())
m_rect = m_rect.normalized();
m_undo_command->setNewValue(QVariant(m_rect));
elementScene()->undoStack().push(m_undo_command);
m_undo_command = nullptr;
m_vector_index = -1;
}
m_undo_command->setNewValue(QVariant(m_rect));
elementScene()->undoStack().push(m_undo_command);
m_undo_command = nullptr;
m_vector_index = -1;
}
}
/**
@brief PartArc::sceneSelectionChanged
When the scene selection change, if there are several primitive selected, we remove the handler of this item
@brief PartArc::sceneSelectionChanged
When the scene selection change, if there are several primitive selected, we remove the handler of this item
*/
void PartArc::sceneSelectionChanged()
{
if (this->isSelected() && scene()->selectedItems().size() == 1)
addHandler();
else
removeHandler();
if (this->isSelected() && scene()->selectedItems().size() == 1)
addHandler();
else
removeHandler();
}
/**
@brief PartArc::addHandler
Add handlers for this item
@brief PartArc::addHandler
Add handlers for this item
*/
void PartArc::addHandler()
{
if (m_handler_vector.isEmpty() && scene())
{
if(m_resize_mode == 3)
{
m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointsForArc(m_rect, m_start_angle/16, m_span_angle/16)));
}
else
m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointsForRect(m_rect)));
if (m_handler_vector.isEmpty() && scene())
{
if(m_resize_mode == 3)
{
m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointsForArc(m_rect, m_start_angle/16, m_span_angle/16)));
}
else
m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointsForRect(m_rect)));
for(QetGraphicsHandlerItem *handler : m_handler_vector)
{
QColor color = Qt::blue;
if (m_resize_mode == 2)
color = Qt::darkGreen;
else if (m_resize_mode == 3)
color = Qt::magenta;
for(QetGraphicsHandlerItem *handler : m_handler_vector)
{
QColor color = Qt::blue;
if (m_resize_mode == 2)
color = Qt::darkGreen;
else if (m_resize_mode == 3)
color = Qt::magenta;
handler->setColor(color);
scene()->addItem(handler);
handler->installSceneEventFilter(this);
handler->setZValue(this->zValue()+1);
}
}
handler->setColor(color);
scene()->addItem(handler);
handler->installSceneEventFilter(this);
handler->setZValue(this->zValue()+1);
}
}
}
/**
@brief PartArc::removeHandler
Remove the handlers of this item
@brief PartArc::removeHandler
Remove the handlers of this item
*/
void PartArc::removeHandler()
{
if (!m_handler_vector.isEmpty())
{
qDeleteAll(m_handler_vector);
m_handler_vector.clear();
}
if (!m_handler_vector.isEmpty())
{
qDeleteAll(m_handler_vector);
m_handler_vector.clear();
}
}

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PART_ARC_H
#define PART_ARC_H
@@ -24,66 +24,66 @@ class QPropertyUndoCommand;
class QetGraphicsHandlerItem;
/**
@brief The PartArc class
This class represents an elliptical arc primitive which may be used to
compose the drawing of an electrical element within the element editor.
@brief The PartArc class
This class represents an elliptical arc primitive which may be used to
compose the drawing of an electrical element within the element editor.
*/
class PartArc : public AbstractPartEllipse
{
Q_OBJECT
Q_OBJECT
public:
PartArc(QETElementEditor *editor, QGraphicsItem *parent = nullptr);
~PartArc() override;
public:
PartArc(QETElementEditor *editor, QGraphicsItem *parent = nullptr);
~PartArc() override;
private:
PartArc(const PartArc &);
// methods
public:
enum { Type = UserType + 1101 };
/**
Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a PartArc.
@return the QGraphicsItem type
*/
int type() const override { return Type; }
void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget * = nullptr) override;
private:
PartArc(const PartArc &);
// methods
public:
enum { Type = UserType + 1101 };
/**
Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a PartArc.
@return the QGraphicsItem type
*/
int type() const override { return Type; }
void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget * = nullptr) override;
//Name and XML
QString name() const override { return(QObject::tr("arc", "element part name")); }
QString xmlName() const override { return(QString("arc")); }
QDomElement toXml (QDomDocument &) const override;
bool fromXml (const QDomElement &) override;
static bool valideXml(QDomElement& element);
//Name and XML
QString name() const override { return(QObject::tr("arc", "element part name")); }
QString xmlName() const override { return(QString("arc")); }
QDomElement toXml (QDomDocument &) const override;
bool fromXml (const QDomElement &) override;
static bool valideXml(QDomElement& element);
QPainterPath shape() const override;
QPainterPath shadowShape() const override;
void setRect(const QRectF &rect) override {AbstractPartEllipse::setRect(rect); adjusteHandlerPos();}
void setStartAngle(const int &start_angle) override {AbstractPartEllipse::setStartAngle(start_angle); adjusteHandlerPos();}
void setSpanAngle(const int &span_angle) override {AbstractPartEllipse::setSpanAngle(span_angle); adjusteHandlerPos();}
QRectF sceneGeometricRect() const override;
QPainterPath shape() const override;
QPainterPath shadowShape() const override;
void setRect(const QRectF &rect) override {AbstractPartEllipse::setRect(rect); adjusteHandlerPos();}
void setStartAngle(const int &start_angle) override {AbstractPartEllipse::setStartAngle(start_angle); adjusteHandlerPos();}
void setSpanAngle(const int &span_angle) override {AbstractPartEllipse::setSpanAngle(span_angle); adjusteHandlerPos();}
QRectF sceneGeometricRect() const override;
protected:
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;
QVariant itemChange(GraphicsItemChange change, const QVariant &value) override;
bool sceneEventFilter(QGraphicsItem *watched, QEvent *event) override;
protected:
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;
QVariant itemChange(GraphicsItemChange change, const QVariant &value) override;
bool sceneEventFilter(QGraphicsItem *watched, QEvent *event) override;
private:
void switchResizeMode();
void adjusteHandlerPos();
void handlerMousePressEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void handlerMouseMoveEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void handlerMouseReleaseEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void sceneSelectionChanged ();
private:
void switchResizeMode();
void adjusteHandlerPos();
void handlerMousePressEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void handlerMouseMoveEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void handlerMouseReleaseEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void sceneSelectionChanged ();
void addHandler();
void removeHandler();
void addHandler();
void removeHandler();
private:
QPropertyUndoCommand *m_undo_command = nullptr;
QPropertyUndoCommand *m_undo_command2 = nullptr;
int m_resize_mode = 1,
m_vector_index = -1;
QPointF m_span_point;
QVector<QetGraphicsHandlerItem *> m_handler_vector;
private:
QPropertyUndoCommand *m_undo_command = nullptr;
QPropertyUndoCommand *m_undo_command2 = nullptr;
int m_resize_mode = 1,
m_vector_index = -1;
QPointF m_span_point;
QVector<QetGraphicsHandlerItem *> m_handler_vector;
};
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PARTDYNAMICTEXTFIELD_H
#define PARTDYNAMICTEXTFIELD_H
@@ -23,107 +23,107 @@
#include "dynamicelementtextitem.h"
/**
@brief The PartDynamicTextField class
This class represents an editable dynamic text field
which may be used to compose the
drawing of an electrical element within the element editor.
The field will remain editable once the element is added onto
a diagram
@brief The PartDynamicTextField class
This class represents an editable dynamic text field
which may be used to compose the
drawing of an electrical element within the element editor.
The field will remain editable once the element is added onto
a diagram
*/
class PartDynamicTextField : public QGraphicsTextItem, public CustomElementPart
{
Q_OBJECT
Q_OBJECT
Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged)
Q_PROPERTY(DynamicElementTextItem::TextFrom textFrom READ textFrom WRITE setTextFrom NOTIFY textFromChanged)
Q_PROPERTY(QString infoName READ infoName WRITE setInfoName NOTIFY infoNameChanged)
Q_PROPERTY(QString compositeText READ compositeText WRITE setCompositeText NOTIFY compositeTextChanged)
Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged)
Q_PROPERTY(bool frame READ frame WRITE setFrame NOTIFY frameChanged)
Q_PROPERTY(qreal textWidth READ textWidth WRITE setTextWidth NOTIFY textWidthChanged)
Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment NOTIFY alignmentChanged)
Q_PROPERTY(QFont font READ font WRITE setFont NOTIFY fontChanged)
Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged)
Q_PROPERTY(DynamicElementTextItem::TextFrom textFrom READ textFrom WRITE setTextFrom NOTIFY textFromChanged)
Q_PROPERTY(QString infoName READ infoName WRITE setInfoName NOTIFY infoNameChanged)
Q_PROPERTY(QString compositeText READ compositeText WRITE setCompositeText NOTIFY compositeTextChanged)
Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged)
Q_PROPERTY(bool frame READ frame WRITE setFrame NOTIFY frameChanged)
Q_PROPERTY(qreal textWidth READ textWidth WRITE setTextWidth NOTIFY textWidthChanged)
Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment NOTIFY alignmentChanged)
Q_PROPERTY(QFont font READ font WRITE setFont NOTIFY fontChanged)
public:
///PROPERTY
void setProperty(const char *name, const QVariant &value) override {QGraphicsTextItem::setProperty(name, value);}
QVariant property(const char *name) const override {return QGraphicsTextItem::property(name);}
public:
///PROPERTY
void setProperty(const char *name, const QVariant &value) override {QGraphicsTextItem::setProperty(name, value);}
QVariant property(const char *name) const override {return QGraphicsTextItem::property(name);}
signals:
void taggChanged(QString tagg);
void textChanged(QString text);
void textFromChanged(DynamicElementTextItem::TextFrom text_from);
void infoNameChanged(QString info);
void compositeTextChanged(QString text);
void colorChanged(QColor color);
void frameChanged(bool frame);
void textWidthChanged(qreal width);
void alignmentChanged(Qt::Alignment alignment);
void fontChanged(QFont font);
signals:
void taggChanged(QString tagg);
void textChanged(QString text);
void textFromChanged(DynamicElementTextItem::TextFrom text_from);
void infoNameChanged(QString info);
void compositeTextChanged(QString text);
void colorChanged(QColor color);
void frameChanged(bool frame);
void textWidthChanged(qreal width);
void alignmentChanged(Qt::Alignment alignment);
void fontChanged(QFont font);
public:
PartDynamicTextField(QETElementEditor *editor, QGraphicsItem *parent = nullptr);
public:
PartDynamicTextField(QETElementEditor *editor, QGraphicsItem *parent = nullptr);
enum {Type = UserType + 1110};
int type() const override {return Type;}
enum {Type = UserType + 1110};
int type() const override {return Type;}
QString name() const override;
QString xmlName() const override;
static QString xmlTaggName() {return QString("dynamic_text");}
bool isUseless() const override {return false;}
QRectF sceneGeometricRect() const override {return sceneBoundingRect();}
void startUserTransformation(const QRectF &initial_selection_rect) override;
void handleUserTransformation(const QRectF &initial_selection_rect, const QRectF &new_selection_rect) override;
QString name() const override;
QString xmlName() const override;
static QString xmlTaggName() {return QString("dynamic_text");}
bool isUseless() const override {return false;}
QRectF sceneGeometricRect() const override {return sceneBoundingRect();}
void startUserTransformation(const QRectF &initial_selection_rect) override;
void handleUserTransformation(const QRectF &initial_selection_rect, const QRectF &new_selection_rect) override;
QDomElement toXml(QDomDocument &dom_doc) const override;
bool fromXml(const QDomElement &dom_elmt) override;
void fromTextFieldXml(const QDomElement &dom_element);
static bool valideXml(QDomElement& dom_elmt);
QDomElement toXml(QDomDocument &dom_doc) const override;
bool fromXml(const QDomElement &dom_elmt) override;
void fromTextFieldXml(const QDomElement &dom_element);
static bool valideXml(QDomElement& dom_elmt);
DynamicElementTextItem::TextFrom textFrom() const;
void setTextFrom (DynamicElementTextItem::TextFrom text_from);
QString text() const;
void setText(const QString &text);
void setInfoName(const QString &info_name);
QString infoName() const;
void setCompositeText(const QString &text);
QString compositeText() const;
void setColor(const QColor& color);
QColor color() const;
void setFrame(bool frame);
bool frame() const;
void setTextWidth(qreal width);
void setPlainText(const QString &text);
void setAlignment(Qt::Alignment alignment);
Qt::Alignment alignment() const;
void setFont(const QFont &font);
DynamicElementTextItem::TextFrom textFrom() const;
void setTextFrom (DynamicElementTextItem::TextFrom text_from);
QString text() const;
void setText(const QString &text);
void setInfoName(const QString &info_name);
QString infoName() const;
void setCompositeText(const QString &text);
QString compositeText() const;
void setColor(const QColor& color);
QColor color() const;
void setFrame(bool frame);
bool frame() const;
void setTextWidth(qreal width);
void setPlainText(const QString &text);
void setAlignment(Qt::Alignment alignment);
Qt::Alignment alignment() const;
void setFont(const QFont &font);
protected:
void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;
QVariant itemChange(GraphicsItemChange change, const QVariant &value) override;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
protected:
void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;
QVariant itemChange(GraphicsItemChange change, const QVariant &value) override;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
private:
void elementInfoChanged();
void prepareAlignment();
void finishAlignment();
private:
void elementInfoChanged();
void prepareAlignment();
void finishAlignment();
private:
QPointF m_origine_pos,
m_saved_point;
QString m_text,
m_info_name,
m_composite_text;
DynamicElementTextItem::TextFrom m_text_from = DynamicElementTextItem::UserText;
QUuid m_uuid{QUuid::createUuid()};
bool m_frame = false,
m_first_add = true,
m_block_alignment = false;
qreal m_text_width = -1;
Qt::Alignment m_alignment = Qt::AlignTop|Qt::AlignLeft;
QRectF m_alignment_rect;
private:
QPointF m_origine_pos,
m_saved_point;
QString m_text,
m_info_name,
m_composite_text;
DynamicElementTextItem::TextFrom m_text_from = DynamicElementTextItem::UserText;
QUuid m_uuid{QUuid::createUuid()};
bool m_frame = false,
m_first_add = true,
m_block_alignment = false;
qreal m_text_width = -1;
Qt::Alignment m_alignment = Qt::AlignTop|Qt::AlignLeft;
QRectF m_alignment_rect;
};
#endif // PARTDYNAMICTEXTFIELD_H

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#include "partellipse.h"
#include "QPropertyUndoCommand/qpropertyundocommand.h"
@@ -22,396 +22,396 @@
#include "QetGraphicsItemModeler/qetgraphicshandlerutility.h"
/**
@brief PartEllipse::PartEllipse
Constructor
@param editor : QETElementEditor of this part
@param parent : parent item
@brief PartEllipse::PartEllipse
Constructor
@param editor : QETElementEditor of this part
@param parent : parent item
*/
PartEllipse::PartEllipse(QETElementEditor *editor, QGraphicsItem *parent) :
AbstractPartEllipse(editor, parent),
m_undo_command(nullptr)
AbstractPartEllipse(editor, parent),
m_undo_command(nullptr)
{}
/**
@brief PartEllipse::~PartEllipse
Destructor
@brief PartEllipse::~PartEllipse
Destructor
*/
PartEllipse::~PartEllipse()
{
if(m_undo_command) delete m_undo_command;
removeHandler();
if(m_undo_command) delete m_undo_command;
removeHandler();
}
/**
@brief PartEllipse::paint
Draw this ellpise
@param painter
@param options
@param widget
@brief PartEllipse::paint
Draw this ellpise
@param painter
@param options
@param widget
*/
void PartEllipse::paint(QPainter *painter, const QStyleOptionGraphicsItem *options, QWidget *widget)
{
Q_UNUSED(widget);
applyStylesToQPainter(*painter);
Q_UNUSED(widget);
applyStylesToQPainter(*painter);
QPen t = painter -> pen();
QPen t = painter -> pen();
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
t.setCosmetic(options && options -> levelOfDetail < 1.0);
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
t.setCosmetic(options && options -> levelOfDetail < 1.0);
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
t.setCosmetic(options && options -> levelOfDetailFromTransform(painter->worldTransform()) < 1.0);
t.setCosmetic(options && options -> levelOfDetailFromTransform(painter->worldTransform()) < 1.0);
#endif
if (isSelected())
t.setColor(Qt::red);
if (isSelected())
t.setColor(Qt::red);
painter -> setPen(t);
painter -> drawEllipse(rect());
painter -> setPen(t);
painter -> drawEllipse(rect());
if (m_hovered)
drawShadowShape(painter);
if (m_hovered)
drawShadowShape(painter);
if (isSelected())
drawCross(m_rect.center(), painter);
if (isSelected())
drawCross(m_rect.center(), painter);
}
/**
@brief PartEllipse::toXml
Export this ellipse in xml
@param xml_document : Xml document to use for create the xml element.
@return : an xml element that describe this ellipse
@brief PartEllipse::toXml
Export this ellipse in xml
@param xml_document : Xml document to use for create the xml element.
@return : an xml element that describe this ellipse
*/
QDomElement PartEllipse::toXml(QDomDocument &xml_document) const
{
QDomElement xml_element;
if (qFuzzyCompare(rect().width(), rect().height()))
{
xml_element = xml_document.createElement("circle");
xml_element.appendChild(createXmlProperty(xml_document, "diameter", rect().width()));
}
else
{
xml_element = xml_document.createElement("ellipse");
xml_element.appendChild(createXmlProperty(xml_document, "width", rect().width()));
xml_element.appendChild(createXmlProperty(xml_document, "height", rect().height()));
}
QDomElement xml_element;
if (qFuzzyCompare(rect().width(), rect().height()))
{
xml_element = xml_document.createElement("circle");
xml_element.appendChild(createXmlProperty(xml_document, "diameter", rect().width()));
}
else
{
xml_element = xml_document.createElement("ellipse");
xml_element.appendChild(createXmlProperty(xml_document, "width", rect().width()));
xml_element.appendChild(createXmlProperty(xml_document, "height", rect().height()));
}
QPointF top_left(sceneTopLeft());
xml_element.appendChild(createXmlProperty(xml_document, "x", top_left.x()));
xml_element.appendChild(createXmlProperty(xml_document, "y", top_left.y()));
QPointF top_left(sceneTopLeft());
xml_element.appendChild(createXmlProperty(xml_document, "x", top_left.x()));
xml_element.appendChild(createXmlProperty(xml_document, "y", top_left.y()));
stylesToXml(xml_document, xml_element);
stylesToXml(xml_document, xml_element);
return(xml_element);
return(xml_element);
}
/**
@brief PartEllipse::fromXml
Import the properties of this ellipse from a xml element.
@param qde : Xml document to use.
@brief PartEllipse::fromXml
Import the properties of this ellipse from a xml element.
@param qde : Xml document to use.
*/
bool PartEllipse::fromXml(const QDomElement &qde)
{
stylesFromXml(qde);
double x=0, y=0, width=0, height=0;
stylesFromXml(qde);
double x=0, y=0, width=0, height=0;
if (qde.tagName() == "ellipse")
{
if (propertyDouble(qde, "width", &width) == PropertyFlags::NoValidConversion ||
propertyDouble(qde, "height", &height) == PropertyFlags::NoValidConversion)
return false;
}
else {
if (propertyDouble(qde, "diameter", &width) == PropertyFlags::NoValidConversion)
return false;
height = width;
}
if (qde.tagName() == "ellipse")
{
if (propertyDouble(qde, "width", &width) == PropertyFlags::NoValidConversion ||
propertyDouble(qde, "height", &height) == PropertyFlags::NoValidConversion)
return false;
}
else {
if (propertyDouble(qde, "diameter", &width) == PropertyFlags::NoValidConversion)
return false;
height = width;
}
if (propertyDouble(qde, "x", &x) == PropertyFlags::NoValidConversion ||
propertyDouble(qde, "y", &y) == PropertyFlags::NoValidConversion)
return false;
if (propertyDouble(qde, "x", &x) == PropertyFlags::NoValidConversion ||
propertyDouble(qde, "y", &y) == PropertyFlags::NoValidConversion)
return false;
m_rect = QRectF(mapFromScene(x, y), QSizeF(width, height));
m_rect = QRectF(mapFromScene(x, y), QSizeF(width, height));
return true;
return true;
}
bool PartEllipse::valideXml(QDomElement& element) {
if (element.tagName() == "ellipse")
{
if (propertyDouble(element, "width") & PropertyFlags::NoValidConversion ||
propertyDouble(element, "height") & PropertyFlags::NoValidConversion)
return false;
}
else {
if (propertyDouble(element, "diameter") & PropertyFlags::NoValidConversion)
return false;
}
if (element.tagName() == "ellipse")
{
if (propertyDouble(element, "width") & PropertyFlags::NoValidConversion ||
propertyDouble(element, "height") & PropertyFlags::NoValidConversion)
return false;
}
else {
if (propertyDouble(element, "diameter") & PropertyFlags::NoValidConversion)
return false;
}
if ((propertyDouble(element, "x") & PropertyFlags::NoValidConversion) ||
(propertyDouble(element, "y") & PropertyFlags::NoValidConversion))
return false;
if ((propertyDouble(element, "x") & PropertyFlags::NoValidConversion) ||
(propertyDouble(element, "y") & PropertyFlags::NoValidConversion))
return false;
return true;
return true;
}
/**
@brief PartEllipse::shape
@return the shape of this item
@brief PartEllipse::shape
@return the shape of this item
*/
QPainterPath PartEllipse::shape() const
{
QPainterPath shape;
shape.addEllipse(m_rect);
QPainterPath shape;
shape.addEllipse(m_rect);
QPainterPathStroker pps;
pps.setWidth(m_hovered? penWeight()+SHADOWS_HEIGHT : penWeight());
shape = pps.createStroke(shape);
QPainterPathStroker pps;
pps.setWidth(m_hovered? penWeight()+SHADOWS_HEIGHT : penWeight());
shape = pps.createStroke(shape);
return shape;
return shape;
}
QPainterPath PartEllipse::shadowShape() const
{
QPainterPath shape;
shape.addEllipse(m_rect);
QPainterPath shape;
shape.addEllipse(m_rect);
QPainterPathStroker pps;
pps.setWidth(penWeight());
QPainterPathStroker pps;
pps.setWidth(penWeight());
return (pps.createStroke(shape));
return (pps.createStroke(shape));
}
/**
@brief PartEllipse::mouseReleaseEvent
Handle mouse release event
@param event
@brief PartEllipse::mouseReleaseEvent
Handle mouse release event
@param event
*/
void PartEllipse::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
if (event->button() == Qt::LeftButton && event->buttonDownPos(Qt::LeftButton) == event->pos())
switchResizeMode();
if (event->button() == Qt::LeftButton && event->buttonDownPos(Qt::LeftButton) == event->pos())
switchResizeMode();
CustomElementGraphicPart::mouseReleaseEvent(event);
CustomElementGraphicPart::mouseReleaseEvent(event);
}
/**
@brief PartEllipse::itemChange
@param change
@param value
@return
@brief PartEllipse::itemChange
@param change
@param value
@return
*/
QVariant PartEllipse::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value)
{
if (change == ItemSelectedHasChanged && scene())
{
if (value.toBool() == true)
{
//When item is selected, he must to be up to date whene the selection in the scene change, for display or not the handler,
//according to the number of selected items.
connect(scene(), &QGraphicsScene::selectionChanged, this, &PartEllipse::sceneSelectionChanged);
if (change == ItemSelectedHasChanged && scene())
{
if (value.toBool() == true)
{
//When item is selected, he must to be up to date whene the selection in the scene change, for display or not the handler,
//according to the number of selected items.
connect(scene(), &QGraphicsScene::selectionChanged, this, &PartEllipse::sceneSelectionChanged);
if (scene()->selectedItems().size() == 1)
addHandler();
}
else
{
disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartEllipse::sceneSelectionChanged);
removeHandler();
}
}
else if (change == ItemPositionHasChanged)
{
adjusteHandlerPos();
}
else if (change == ItemSceneChange)
{
if(scene())
disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartEllipse::sceneSelectionChanged);
if (scene()->selectedItems().size() == 1)
addHandler();
}
else
{
disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartEllipse::sceneSelectionChanged);
removeHandler();
}
}
else if (change == ItemPositionHasChanged)
{
adjusteHandlerPos();
}
else if (change == ItemSceneChange)
{
if(scene())
disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartEllipse::sceneSelectionChanged);
setSelected(false); //This item is removed from scene, then we deselect this, and so, the handlers is also removed.
}
setSelected(false); //This item is removed from scene, then we deselect this, and so, the handlers is also removed.
}
return QGraphicsItem::itemChange(change, value);
return QGraphicsItem::itemChange(change, value);
}
/**
@brief PartEllipse::sceneEventFilter
@param watched
@param event
@return
@brief PartEllipse::sceneEventFilter
@param watched
@param event
@return
*/
bool PartEllipse::sceneEventFilter(QGraphicsItem *watched, QEvent *event)
{
//Watched must be an handler
if(watched->type() == QetGraphicsHandlerItem::Type)
{
QetGraphicsHandlerItem *qghi = qgraphicsitem_cast<QetGraphicsHandlerItem *>(watched);
//Watched must be an handler
if(watched->type() == QetGraphicsHandlerItem::Type)
{
QetGraphicsHandlerItem *qghi = qgraphicsitem_cast<QetGraphicsHandlerItem *>(watched);
if(m_handler_vector.contains(qghi)) //Handler must be in m_vector_index, then we can start resize
{
m_vector_index = m_handler_vector.indexOf(qghi);
if (m_vector_index != -1)
{
if(event->type() == QEvent::GraphicsSceneMousePress) //Click
{
handlerMousePressEvent(qghi, static_cast<QGraphicsSceneMouseEvent *>(event));
return true;
}
else if(event->type() == QEvent::GraphicsSceneMouseMove) //Move
{
handlerMouseMoveEvent(qghi, static_cast<QGraphicsSceneMouseEvent *>(event));
return true;
}
else if (event->type() == QEvent::GraphicsSceneMouseRelease) //Release
{
handlerMouseReleaseEvent(qghi, static_cast<QGraphicsSceneMouseEvent *>(event));
return true;
}
}
}
}
if(m_handler_vector.contains(qghi)) //Handler must be in m_vector_index, then we can start resize
{
m_vector_index = m_handler_vector.indexOf(qghi);
if (m_vector_index != -1)
{
if(event->type() == QEvent::GraphicsSceneMousePress) //Click
{
handlerMousePressEvent(qghi, static_cast<QGraphicsSceneMouseEvent *>(event));
return true;
}
else if(event->type() == QEvent::GraphicsSceneMouseMove) //Move
{
handlerMouseMoveEvent(qghi, static_cast<QGraphicsSceneMouseEvent *>(event));
return true;
}
else if (event->type() == QEvent::GraphicsSceneMouseRelease) //Release
{
handlerMouseReleaseEvent(qghi, static_cast<QGraphicsSceneMouseEvent *>(event));
return true;
}
}
}
}
return false;
return false;
}
void PartEllipse::switchResizeMode()
{
if (m_resize_mode == 1)
{
m_resize_mode = 2;
for (QetGraphicsHandlerItem *qghi : m_handler_vector)
qghi->setColor(Qt::darkGreen);
}
else
{
m_resize_mode = 1;
for (QetGraphicsHandlerItem *qghi : m_handler_vector)
qghi->setColor(Qt::blue);
}
if (m_resize_mode == 1)
{
m_resize_mode = 2;
for (QetGraphicsHandlerItem *qghi : m_handler_vector)
qghi->setColor(Qt::darkGreen);
}
else
{
m_resize_mode = 1;
for (QetGraphicsHandlerItem *qghi : m_handler_vector)
qghi->setColor(Qt::blue);
}
}
/**
@brief PartEllipse::adjusteHandlerPos
@brief PartEllipse::adjusteHandlerPos
*/
void PartEllipse::adjusteHandlerPos()
{
if (m_handler_vector.isEmpty())
return;
if (m_handler_vector.isEmpty())
return;
QVector <QPointF> points_vector = QetGraphicsHandlerUtility::pointsForRect(m_rect);
QVector <QPointF> points_vector = QetGraphicsHandlerUtility::pointsForRect(m_rect);
if (m_handler_vector.size() == points_vector.size())
{
points_vector = mapToScene(points_vector);
for (int i = 0 ; i < points_vector.size() ; ++i)
m_handler_vector.at(i)->setPos(points_vector.at(i));
}
if (m_handler_vector.size() == points_vector.size())
{
points_vector = mapToScene(points_vector);
for (int i = 0 ; i < points_vector.size() ; ++i)
m_handler_vector.at(i)->setPos(points_vector.at(i));
}
}
/**
@brief PartEllipse::handlerMousePressEvent
@param qghi
@param event
@brief PartEllipse::handlerMousePressEvent
@param qghi
@param event
*/
void PartEllipse::handlerMousePressEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event)
{
Q_UNUSED(qghi);
Q_UNUSED(event);
Q_UNUSED(qghi);
Q_UNUSED(event);
m_undo_command = new QPropertyUndoCommand(this, "rect", QVariant(m_rect));
m_undo_command->setText(tr("Modifier un rectangle"));
m_undo_command->enableAnimation();
return;
m_undo_command = new QPropertyUndoCommand(this, "rect", QVariant(m_rect));
m_undo_command->setText(tr("Modifier un rectangle"));
m_undo_command->enableAnimation();
return;
}
/**
@brief PartEllipse::handlerMouseMoveEvent
@param qghi
@param event
@brief PartEllipse::handlerMouseMoveEvent
@param qghi
@param event
*/
void PartEllipse::handlerMouseMoveEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event)
{
Q_UNUSED(qghi);
Q_UNUSED(qghi);
QPointF new_pos = event->scenePos();
if (event->modifiers() != Qt::ControlModifier)
new_pos = elementScene()->snapToGrid(event->scenePos());
new_pos = mapFromScene(new_pos);
QPointF new_pos = event->scenePos();
if (event->modifiers() != Qt::ControlModifier)
new_pos = elementScene()->snapToGrid(event->scenePos());
new_pos = mapFromScene(new_pos);
if (m_resize_mode == 1)
setRect(QetGraphicsHandlerUtility::rectForPosAtIndex(m_rect, new_pos, m_vector_index));
else
setRect(QetGraphicsHandlerUtility::mirrorRectForPosAtIndex(m_rect, new_pos, m_vector_index));
if (m_resize_mode == 1)
setRect(QetGraphicsHandlerUtility::rectForPosAtIndex(m_rect, new_pos, m_vector_index));
else
setRect(QetGraphicsHandlerUtility::mirrorRectForPosAtIndex(m_rect, new_pos, m_vector_index));
adjusteHandlerPos();
adjusteHandlerPos();
}
/**
@brief PartEllipse::handlerMouseReleaseEvent
@param qghi
@param event
@brief PartEllipse::handlerMouseReleaseEvent
@param qghi
@param event
*/
void PartEllipse::handlerMouseReleaseEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event)
{
Q_UNUSED(qghi);
Q_UNUSED(event);
Q_UNUSED(qghi);
Q_UNUSED(event);
m_undo_command->setNewValue(QVariant(m_rect));
elementScene()->undoStack().push(m_undo_command);
m_undo_command = nullptr;
m_vector_index = -1;
m_undo_command->setNewValue(QVariant(m_rect));
elementScene()->undoStack().push(m_undo_command);
m_undo_command = nullptr;
m_vector_index = -1;
}
/**
@brief PartEllipse::sceneSelectionChanged
When the scene selection change, if there are several primitive selected, we remove the handler of this item
@brief PartEllipse::sceneSelectionChanged
When the scene selection change, if there are several primitive selected, we remove the handler of this item
*/
void PartEllipse::sceneSelectionChanged()
{
if (this->isSelected() && scene()->selectedItems().size() == 1)
addHandler();
else
removeHandler();
if (this->isSelected() && scene()->selectedItems().size() == 1)
addHandler();
else
removeHandler();
}
/**
@brief PartEllipse::addHandler
Add handlers for this item
@brief PartEllipse::addHandler
Add handlers for this item
*/
void PartEllipse::addHandler()
{
if (m_handler_vector.isEmpty() && scene())
{
m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointsForRect(m_rect)));
if (m_handler_vector.isEmpty() && scene())
{
m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointsForRect(m_rect)));
for(QetGraphicsHandlerItem *handler : m_handler_vector)
{
QColor color = Qt::blue;
if (m_resize_mode == 2)
color = Qt::darkGreen;
for(QetGraphicsHandlerItem *handler : m_handler_vector)
{
QColor color = Qt::blue;
if (m_resize_mode == 2)
color = Qt::darkGreen;
handler->setColor(color);
scene()->addItem(handler);
handler->installSceneEventFilter(this);
handler->setZValue(this->zValue()+1);
}
}
handler->setColor(color);
scene()->addItem(handler);
handler->installSceneEventFilter(this);
handler->setZValue(this->zValue()+1);
}
}
}
/**
@brief PartEllipse::removeHandler
Remove the handlers of this item
@brief PartEllipse::removeHandler
Remove the handlers of this item
*/
void PartEllipse::removeHandler()
{
if (!m_handler_vector.isEmpty())
{
qDeleteAll(m_handler_vector);
m_handler_vector.clear();
}
if (!m_handler_vector.isEmpty())
{
qDeleteAll(m_handler_vector);
m_handler_vector.clear();
}
}

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PART_ELLIPSE_H
#define PART_ELLIPSE_H
@@ -23,61 +23,61 @@
class QPropertyUndoCommand;
/**
@brief The PartEllipse class
This class represents an ellipse primitive which may be used to compose the
drawing of an electrical element within the element editor.
@brief The PartEllipse class
This class represents an ellipse primitive which may be used to compose the
drawing of an electrical element within the element editor.
*/
class PartEllipse : public AbstractPartEllipse
{
Q_OBJECT
Q_OBJECT
// constructors, destructor
public:
PartEllipse(QETElementEditor *editor, QGraphicsItem * parent = nullptr);
~PartEllipse() override;
// constructors, destructor
public:
PartEllipse(QETElementEditor *editor, QGraphicsItem * parent = nullptr);
~PartEllipse() override;
private:
PartEllipse(const PartEllipse &);
private:
PartEllipse(const PartEllipse &);
// methods
public:
enum { Type = UserType + 1103 };
/**
Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a PartEllipse.
@return the QGraphicsItem type
*/
int type() const override { return Type; }
void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget * = nullptr) override;
// methods
public:
enum { Type = UserType + 1103 };
/**
Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a PartEllipse.
@return the QGraphicsItem type
*/
int type() const override { return Type; }
void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget * = nullptr) override;
//Name and XML
QString name() const override { return(QObject::tr("ellipse", "element part name")); }
QString xmlName() const override { return(QString("ellipse")); }
QDomElement toXml (QDomDocument &) const override;
bool fromXml (const QDomElement &) override;
static bool valideXml(QDomElement& element);
QPainterPath shape() const override;
QPainterPath shadowShape() const override;
void setRect(const QRectF &rect) override {AbstractPartEllipse::setRect(rect); adjusteHandlerPos();}
//Name and XML
QString name() const override { return(QObject::tr("ellipse", "element part name")); }
QString xmlName() const override { return(QString("ellipse")); }
QDomElement toXml (QDomDocument &) const override;
bool fromXml (const QDomElement &) override;
static bool valideXml(QDomElement& element);
QPainterPath shape() const override;
QPainterPath shadowShape() const override;
void setRect(const QRectF &rect) override {AbstractPartEllipse::setRect(rect); adjusteHandlerPos();}
protected:
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;
QVariant itemChange(GraphicsItemChange change, const QVariant &value) override;
bool sceneEventFilter(QGraphicsItem *watched, QEvent *event) override;
protected:
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;
QVariant itemChange(GraphicsItemChange change, const QVariant &value) override;
bool sceneEventFilter(QGraphicsItem *watched, QEvent *event) override;
private:
void switchResizeMode();
void adjusteHandlerPos();
void handlerMousePressEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void handlerMouseMoveEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void handlerMouseReleaseEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void sceneSelectionChanged ();
private:
void switchResizeMode();
void adjusteHandlerPos();
void handlerMousePressEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void handlerMouseMoveEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void handlerMouseReleaseEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void sceneSelectionChanged ();
void addHandler();
void removeHandler();
void addHandler();
void removeHandler();
private:
QPropertyUndoCommand *m_undo_command;
int m_resize_mode = 1,
m_vector_index = -1;
private:
QPropertyUndoCommand *m_undo_command;
int m_resize_mode = 1,
m_vector_index = -1;
};
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PART_LINE_H
#define PART_LINE_H
@@ -25,105 +25,105 @@ class QPropertyUndoCommand;
class QetGraphicsHandlerItem;
/**
This class represents a line primitive which may be used to compose the
drawing of an electrical element within the element editor. Lines may have
specific visual ends (e.g. arrows) through the setFirstEndType and
setSecondEndType methods. Their size can be defined using the
setFirstEndLength and setSecondEndLength methods. Please note ends are not
drawn if the required length for their drawing is longer than the line itself.
In case there is room for a single end only, the first one get priority.
This class represents a line primitive which may be used to compose the
drawing of an electrical element within the element editor. Lines may have
specific visual ends (e.g. arrows) through the setFirstEndType and
setSecondEndType methods. Their size can be defined using the
setFirstEndLength and setSecondEndLength methods. Please note ends are not
drawn if the required length for their drawing is longer than the line itself.
In case there is room for a single end only, the first one get priority.
*/
class PartLine : public CustomElementGraphicPart
{
Q_OBJECT
Q_OBJECT
Q_PROPERTY(Qet::EndType end1 READ firstEndType WRITE setFirstEndType)
Q_PROPERTY(Qet::EndType end2 READ secondEndType WRITE setSecondEndType)
Q_PROPERTY(qreal length1 READ firstEndLength WRITE setFirstEndLength)
Q_PROPERTY(qreal length2 READ secondEndLength WRITE setSecondEndLength)
Q_PROPERTY(QLineF line READ line WRITE setLine)
Q_PROPERTY(Qet::EndType end1 READ firstEndType WRITE setFirstEndType)
Q_PROPERTY(Qet::EndType end2 READ secondEndType WRITE setSecondEndType)
Q_PROPERTY(qreal length1 READ firstEndLength WRITE setFirstEndLength)
Q_PROPERTY(qreal length2 READ secondEndLength WRITE setSecondEndLength)
Q_PROPERTY(QLineF line READ line WRITE setLine)
// constructors, destructor
public:
PartLine(QETElementEditor *, QGraphicsItem * = nullptr);
~PartLine() override;
private:
PartLine(const PartLine &);
// constructors, destructor
public:
PartLine(QETElementEditor *, QGraphicsItem * = nullptr);
~PartLine() override;
private:
PartLine(const PartLine &);
signals:
void lineChanged();
void firstEndTypeChanged();
void secondEndTypeChanged();
void firstEndLengthChanged();
void secondEndLengthChanged();
signals:
void lineChanged();
void firstEndTypeChanged();
void secondEndTypeChanged();
void firstEndLengthChanged();
void secondEndLengthChanged();
// methods
public:
enum { Type = UserType + 1104 };
// methods
public:
enum { Type = UserType + 1104 };
/**
Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a PartLine.
@return the QGraphicsItem type
*/
int type() const override { return Type; }
void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget * = nullptr) override;
QString name() const override { return(QObject::tr("ligne", "element part name")); }
QString xmlName() const override { return(QString("line")); }
QDomElement toXml(QDomDocument &) const override;
bool fromXml(const QDomElement &) override;
bool valideXml(QDomElement& element) const;
virtual QPointF sceneP1() const;
virtual QPointF sceneP2() const;
QPainterPath shape() const override;
QPainterPath shadowShape() const override;
QRectF boundingRect() const override;
bool isUseless() const override;
QRectF sceneGeometricRect() const override;
void startUserTransformation(const QRectF &) override;
void handleUserTransformation(const QRectF &, const QRectF &) override;
static uint requiredLengthForEndType(const Qet::EndType &);
static QList<QPointF> fourEndPoints(const QPointF &, const QPointF &, const qreal &);
/**
Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a PartLine.
@return the QGraphicsItem type
*/
int type() const override { return Type; }
void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget * = nullptr) override;
QString name() const override { return(QObject::tr("ligne", "element part name")); }
QString xmlName() const override { return(QString("line")); }
QDomElement toXml(QDomDocument &) const override;
bool fromXml(const QDomElement &) override;
bool valideXml(QDomElement& element) const;
virtual QPointF sceneP1() const;
virtual QPointF sceneP2() const;
QPainterPath shape() const override;
QPainterPath shadowShape() const override;
QRectF boundingRect() const override;
bool isUseless() const override;
QRectF sceneGeometricRect() const override;
void startUserTransformation(const QRectF &) override;
void handleUserTransformation(const QRectF &, const QRectF &) override;
static uint requiredLengthForEndType(const Qet::EndType &);
static QList<QPointF> fourEndPoints(const QPointF &, const QPointF &, const qreal &);
QLineF line() const;
void setLine(const QLineF &line);
Qet::EndType firstEndType() const {return first_end;}
void setFirstEndType(const Qet::EndType &et);
Qet::EndType secondEndType() const {return second_end;}
void setSecondEndType(const Qet::EndType &et);
qreal firstEndLength() const {return first_length;}
void setFirstEndLength(const qreal &l);
qreal secondEndLength() const {return second_length;}
void setSecondEndLength(const qreal &l);
QLineF line() const;
void setLine(const QLineF &line);
Qet::EndType firstEndType() const {return first_end;}
void setFirstEndType(const Qet::EndType &et);
Qet::EndType secondEndType() const {return second_end;}
void setSecondEndType(const Qet::EndType &et);
qreal firstEndLength() const {return first_length;}
void setFirstEndLength(const qreal &l);
qreal secondEndLength() const {return second_length;}
void setSecondEndLength(const qreal &l);
protected:
QVariant itemChange(GraphicsItemChange change, const QVariant &value) override;
bool sceneEventFilter(QGraphicsItem *watched, QEvent *event) override;
protected:
QVariant itemChange(GraphicsItemChange change, const QVariant &value) override;
bool sceneEventFilter(QGraphicsItem *watched, QEvent *event) override;
private:
void adjusteHandlerPos();
void handlerMousePressEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void handlerMouseMoveEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void handlerMouseReleaseEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void sceneSelectionChanged ();
private:
void adjusteHandlerPos();
void handlerMousePressEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void handlerMouseMoveEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void handlerMouseReleaseEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void sceneSelectionChanged ();
void addHandler();
void removeHandler();
void addHandler();
void removeHandler();
QPainterPath path() const;
QRectF firstEndCircleRect() const;
QRectF secondEndCircleRect() const;
QPainterPath path() const;
QRectF firstEndCircleRect() const;
QRectF secondEndCircleRect() const;
/*****************/
Qet::EndType first_end;
qreal first_length{1.5};
/*****************/
Qet::EndType first_end;
qreal first_length{1.5};
Qet::EndType second_end;
qreal second_length{1.5};
QList<QPointF> saved_points_;
QLineF m_line;
int m_vector_index = -1;
QPropertyUndoCommand *m_undo_command;
QVector<QetGraphicsHandlerItem *> m_handler_vector;
Qet::EndType second_end;
qreal second_length{1.5};
QList<QPointF> saved_points_;
QLineF m_line;
int m_vector_index = -1;
QPropertyUndoCommand *m_undo_command;
QVector<QetGraphicsHandlerItem *> m_handler_vector;
};
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PART_POLYGON_H
#define PART_POLYGON_H
@@ -26,95 +26,95 @@ class QetGraphicsHandlerItem;
class QAction;
/**
@brief The PartPolygon class
This class represents a polygon primitive which may be used to compose the
drawing of an electrical element within the element editor.
@brief The PartPolygon class
This class represents a polygon primitive which may be used to compose the
drawing of an electrical element within the element editor.
*/
class PartPolygon : public CustomElementGraphicPart
{
Q_OBJECT
Q_OBJECT
Q_PROPERTY(bool closed READ isClosed WRITE setClosed)
Q_PROPERTY(QPolygonF polygon READ polygon WRITE setPolygon)
Q_PROPERTY(bool closed READ isClosed WRITE setClosed)
Q_PROPERTY(QPolygonF polygon READ polygon WRITE setPolygon)
// constructors, destructor
public:
PartPolygon(QETElementEditor *editor, QGraphicsItem *parent = nullptr);
~PartPolygon() override;
// constructors, destructor
public:
PartPolygon(QETElementEditor *editor, QGraphicsItem *parent = nullptr);
~PartPolygon() override;
private:
PartPolygon(const PartPolygon &);
private:
PartPolygon(const PartPolygon &);
signals:
void closedChange();
void polygonChanged();
signals:
void closedChange();
void polygonChanged();
// methods
public:
enum { Type = UserType + 1105 };
/**
* Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a PartPolygon.
* @return the QGraphicsItem type
*/
int type() const override { return Type; }
void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *) override;
// methods
public:
enum { Type = UserType + 1105 };
/**
* Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a PartPolygon.
* @return the QGraphicsItem type
*/
int type() const override { return Type; }
void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *) override;
QString name() const override { return(QObject::tr("polygone", "element part name")); }
QString xmlName() const override { return(QString("polygon")); }
bool fromXml(const QDomElement &) override;
QDomElement toXml(QDomDocument &) const override;
static bool valideXml(QDomElement& element);
QString name() const override { return(QObject::tr("polygone", "element part name")); }
QString xmlName() const override { return(QString("polygon")); }
bool fromXml(const QDomElement &) override;
QDomElement toXml(QDomDocument &) const override;
static bool valideXml(QDomElement& element);
QPainterPath shape () const override;
QPainterPath shadowShape() const override;
QRectF boundingRect() const override;
bool isUseless() const override;
QRectF sceneGeometricRect() const override;
QPainterPath shape () const override;
QPainterPath shadowShape() const override;
QRectF boundingRect() const override;
bool isUseless() const override;
QRectF sceneGeometricRect() const override;
void startUserTransformation(const QRectF &) override;
void handleUserTransformation(const QRectF &, const QRectF &) override;
QET::ScalingMethod preferredScalingMethod() const override;
void startUserTransformation(const QRectF &) override;
void handleUserTransformation(const QRectF &, const QRectF &) override;
QET::ScalingMethod preferredScalingMethod() const override;
QPolygonF polygon () const;
void setPolygon (const QPolygonF &polygon);
QPolygonF polygon () const;
void setPolygon (const QPolygonF &polygon);
void addPoint (const QPointF &point);
void setLastPoint (const QPointF &point);
void removeLastPoint ();
void addPoint (const QPointF &point);
void setLastPoint (const QPointF &point);
void removeLastPoint ();
bool isClosed () const {return m_closed;}
void setClosed (bool close);
bool isClosed () const {return m_closed;}
void setClosed (bool close);
void setHandlerColor(QPointF pos, const QColor &color) final;
void resetAllHandlerColor() final;
void setHandlerColor(QPointF pos, const QColor &color) final;
void resetAllHandlerColor() final;
protected:
QVariant itemChange(GraphicsItemChange change, const QVariant &value) override;
bool sceneEventFilter(QGraphicsItem *watched, QEvent *event) override;
void contextMenuEvent(QGraphicsSceneContextMenuEvent *event) override;
protected:
QVariant itemChange(GraphicsItemChange change, const QVariant &value) override;
bool sceneEventFilter(QGraphicsItem *watched, QEvent *event) override;
void contextMenuEvent(QGraphicsSceneContextMenuEvent *event) override;
private:
void adjusteHandlerPos();
void handlerMousePressEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void handlerMouseMoveEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void handlerMouseReleaseEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void sceneSelectionChanged ();
private:
void adjusteHandlerPos();
void handlerMousePressEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void handlerMouseMoveEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void handlerMouseReleaseEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void sceneSelectionChanged ();
void addHandler();
void removeHandler();
void insertPoint();
void removePoint();
void addHandler();
void removeHandler();
void insertPoint();
void removePoint();
bool m_closed;
QList<QPointF> saved_points_;
QPolygonF m_polygon;
QPropertyUndoCommand *m_undo_command;
int m_vector_index = -1;
QVector<QetGraphicsHandlerItem *> m_handler_vector;
QAction *m_insert_point,
*m_remove_point;
QPointF m_context_menu_pos;
bool m_closed;
QList<QPointF> saved_points_;
QPolygonF m_polygon;
QPropertyUndoCommand *m_undo_command;
int m_vector_index = -1;
QVector<QetGraphicsHandlerItem *> m_handler_vector;
QAction *m_insert_point,
*m_remove_point;
QPointF m_context_menu_pos;
};
#endif

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#include "partrectangle.h"
#include "elementscene.h"
@@ -22,572 +22,572 @@
#include "QetGraphicsItemModeler/qetgraphicshandlerutility.h"
/**
@brief PartRectangle::PartRectangle
Constructor
@param editor the QETElementEditor of this item
@param parent parent item
@brief PartRectangle::PartRectangle
Constructor
@param editor the QETElementEditor of this item
@param parent parent item
*/
PartRectangle::PartRectangle(QETElementEditor *editor, QGraphicsItem *parent) :
CustomElementGraphicPart(editor, parent)
CustomElementGraphicPart(editor, parent)
{}
/**
@brief PartRectangle::~PartRectangle
@brief PartRectangle::~PartRectangle
*/
PartRectangle::~PartRectangle()
{
removeHandler();
removeHandler();
}
/**
@brief PartRectangle::paint
Draw this Rectangle
@param painter
@param options
@param widget
@brief PartRectangle::paint
Draw this Rectangle
@param painter
@param options
@param widget
*/
void PartRectangle::paint(QPainter *painter, const QStyleOptionGraphicsItem *options, QWidget *widget)
{
Q_UNUSED(widget);
applyStylesToQPainter(*painter);
QPen t = painter -> pen();
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
t.setCosmetic(options && options -> levelOfDetail < 1.0);
Q_UNUSED(widget);
applyStylesToQPainter(*painter);
QPen t = painter -> pen();
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
t.setCosmetic(options && options -> levelOfDetail < 1.0);
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
t.setCosmetic(options && options -> levelOfDetailFromTransform(painter->worldTransform()) < 1.0);
t.setCosmetic(options && options -> levelOfDetailFromTransform(painter->worldTransform()) < 1.0);
#endif
if (isSelected())
t.setColor(Qt::red);
if (isSelected())
t.setColor(Qt::red);
t.setJoinStyle(Qt::MiterJoin);
t.setJoinStyle(Qt::MiterJoin);
//Force the pen to width 0 if one of dimension is null
if (!rect().width() || !rect().height())
t.setWidth(0);
//Force the pen to width 0 if one of dimension is null
if (!rect().width() || !rect().height())
t.setWidth(0);
painter->setPen(t);
painter->drawRoundedRect(m_rect, m_xRadius, m_yRadius);
painter->setPen(t);
painter->drawRoundedRect(m_rect, m_xRadius, m_yRadius);
if (m_hovered)
drawShadowShape(painter);
if (m_hovered)
drawShadowShape(painter);
if (isSelected())
drawCross(m_rect.center(), painter);
if (isSelected())
drawCross(m_rect.center(), painter);
}
/**
@brief PartRectangle::toXml
Export this rectangle in xml
@param xml_document : Xml document to use for create the xml element.
@return an xml element that describe this ellipse
@brief PartRectangle::toXml
Export this rectangle in xml
@param xml_document : Xml document to use for create the xml element.
@return an xml element that describe this ellipse
*/
QDomElement PartRectangle::toXml(QDomDocument &xml_document) const
{
QDomElement xml_element = xml_document.createElement("rect");
QPointF top_left(sceneTopLeft());
QDomElement xml_element = xml_document.createElement("rect");
QPointF top_left(sceneTopLeft());
xml_element.appendChild(createXmlProperty(xml_document, "x", top_left.x()));
xml_element.appendChild(createXmlProperty(xml_document, "y", top_left.y()));
xml_element.appendChild(createXmlProperty(xml_document, "width", m_rect.width()));
xml_element.appendChild(createXmlProperty(xml_document, "height", m_rect.height()));
xml_element.appendChild(createXmlProperty(xml_document, "x", top_left.x()));
xml_element.appendChild(createXmlProperty(xml_document, "y", top_left.y()));
xml_element.appendChild(createXmlProperty(xml_document, "width", m_rect.width()));
xml_element.appendChild(createXmlProperty(xml_document, "height", m_rect.height()));
QRectF rect = m_rect.normalized();
qreal x = m_xRadius;
if (x > rect.width()/2) {
x = rect.width()/2;
}
qreal y = m_yRadius;
if (y > rect.height()/2) {
y = rect.height()/2;
}
QRectF rect = m_rect.normalized();
qreal x = m_xRadius;
if (x > rect.width()/2) {
x = rect.width()/2;
}
qreal y = m_yRadius;
if (y > rect.height()/2) {
y = rect.height()/2;
}
xml_element.setAttribute("rx", QString::number(m_xRadius));
xml_element.setAttribute("ry", QString::number(m_yRadius));
xml_element.setAttribute("rx", QString::number(m_xRadius));
xml_element.setAttribute("ry", QString::number(m_yRadius));
xml_element.appendChild(createXmlProperty(xml_document, "rx", m_xRadius));
xml_element.appendChild(createXmlProperty(xml_document, "ry", m_yRadius));
xml_element.appendChild(createXmlProperty(xml_document, "rx", m_xRadius));
xml_element.appendChild(createXmlProperty(xml_document, "ry", m_yRadius));
stylesToXml(xml_document, xml_element);
return(xml_element);
stylesToXml(xml_document, xml_element);
return(xml_element);
}
/**
@brief PartRectangle::fromXml
Import the properties of this rectangle from a xml element.
@param qde : Xml document to use.
@brief PartRectangle::fromXml
Import the properties of this rectangle from a xml element.
@param qde : Xml document to use.
*/
bool PartRectangle::fromXml(const QDomElement &qde)
{
stylesFromXml(qde);
stylesFromXml(qde);
double x=0, y=0, w=0, h=0, rx=0, ry=0;
if (propertyDouble(qde, "x", &x) == PropertyFlags::NoValidConversion ||
propertyDouble(qde, "y", &y) == PropertyFlags::NoValidConversion)
return false;
double x=0, y=0, w=0, h=0, rx=0, ry=0;
if (propertyDouble(qde, "x", &x) == PropertyFlags::NoValidConversion ||
propertyDouble(qde, "y", &y) == PropertyFlags::NoValidConversion)
return false;
setPos(mapFromScene(x, y));
setPos(mapFromScene(x, y));
if (propertyDouble(qde, "width", &w) == PropertyFlags::NoValidConversion ||
propertyDouble(qde, "width", &h) == PropertyFlags::NoValidConversion)
return false;
if (propertyDouble(qde, "width", &w) == PropertyFlags::NoValidConversion ||
propertyDouble(qde, "width", &h) == PropertyFlags::NoValidConversion)
return false;
QRectF rect(QPointF(x,y), QSizeF(w, h));
QRectF rect(QPointF(x,y), QSizeF(w, h));
setRect(rect.normalized());
setRect(rect.normalized());
if (propertyDouble(qde, "rx", &rx) == PropertyFlags::NoValidConversion ||
propertyDouble(qde, "ry", &ry) == PropertyFlags::NoValidConversion)
return false;
if (propertyDouble(qde, "rx", &rx) == PropertyFlags::NoValidConversion ||
propertyDouble(qde, "ry", &ry) == PropertyFlags::NoValidConversion)
return false;
setXRadius(rx);
setYRadius(ry);
setXRadius(rx);
setYRadius(ry);
return true;
return true;
}
bool PartRectangle::valideXml(QDomElement& element) {
// parameters have default values so no value is not a non valid xml element
if ((propertyDouble(element, "x") & PropertyFlags::NoValidConversion) |
(propertyDouble(element, "y") & PropertyFlags::NoValidConversion) |
(propertyDouble(element, "width") & PropertyFlags::NoValidConversion) |
(propertyDouble(element, "width") & PropertyFlags::NoValidConversion) |
(propertyDouble(element, "rx") & PropertyFlags::NoValidConversion) |
(propertyDouble(element, "ry") & PropertyFlags::NoValidConversion))
return false;
return true;
// parameters have default values so no value is not a non valid xml element
if ((propertyDouble(element, "x") & PropertyFlags::NoValidConversion) |
(propertyDouble(element, "y") & PropertyFlags::NoValidConversion) |
(propertyDouble(element, "width") & PropertyFlags::NoValidConversion) |
(propertyDouble(element, "width") & PropertyFlags::NoValidConversion) |
(propertyDouble(element, "rx") & PropertyFlags::NoValidConversion) |
(propertyDouble(element, "ry") & PropertyFlags::NoValidConversion))
return false;
return true;
}
/**
@brief PartRectangle::rect
@return : Returns the item's rectangle.
@brief PartRectangle::rect
@return : Returns the item's rectangle.
*/
QRectF PartRectangle::rect() const
{
return m_rect;
return m_rect;
}
/**
@brief PartRectangle::setRect
Sets the item's rectangle to be the given rectangle.
@param rect
@brief PartRectangle::setRect
Sets the item's rectangle to be the given rectangle.
@param rect
*/
void PartRectangle::setRect(const QRectF &rect)
{
if (rect == m_rect) return;
prepareGeometryChange();
m_rect = rect;
adjusteHandlerPos();
emit rectChanged();
if (rect == m_rect) return;
prepareGeometryChange();
m_rect = rect;
adjusteHandlerPos();
emit rectChanged();
}
void PartRectangle::setXRadius(qreal X)
{
m_xRadius = X;
update();
adjusteHandlerPos();
emit XRadiusChanged();
m_xRadius = X;
update();
adjusteHandlerPos();
emit XRadiusChanged();
}
void PartRectangle::setYRadius(qreal Y)
{
m_yRadius = Y;
update();
adjusteHandlerPos();
emit YRadiusChanged();
m_yRadius = Y;
update();
adjusteHandlerPos();
emit YRadiusChanged();
}
/**
@brief PartRectangle::sceneGeometricRect
@return the minimum, margin-less rectangle this part can fit into, in scene
coordinates. It is different from boundingRect() because it is not supposed
to imply any margin, and it is different from shape because it is a regular
rectangle, not a complex shape.
@brief PartRectangle::sceneGeometricRect
@return the minimum, margin-less rectangle this part can fit into, in scene
coordinates. It is different from boundingRect() because it is not supposed
to imply any margin, and it is different from shape because it is a regular
rectangle, not a complex shape.
*/
QRectF PartRectangle::sceneGeometricRect() const
{
return(mapToScene(rect()).boundingRect());
return(mapToScene(rect()).boundingRect());
}
/**
@brief PartRectangle::sceneTopLeft
@return the top left of rectangle, in scene coordinate
@brief PartRectangle::sceneTopLeft
@return the top left of rectangle, in scene coordinate
*/
QPointF PartRectangle::sceneTopLeft() const
{
return(mapToScene(rect().topLeft()));
return(mapToScene(rect().topLeft()));
}
/**
@brief PartRectangle::shape
@return the shape of this item
@brief PartRectangle::shape
@return the shape of this item
*/
QPainterPath PartRectangle::shape() const
{
QPainterPath shape;
shape.addRoundedRect(m_rect, m_xRadius, m_yRadius);
QPainterPath shape;
shape.addRoundedRect(m_rect, m_xRadius, m_yRadius);
QPainterPathStroker pps;
pps.setWidth(m_hovered? penWeight()+SHADOWS_HEIGHT : penWeight());
shape = pps.createStroke(shape);
QPainterPathStroker pps;
pps.setWidth(m_hovered? penWeight()+SHADOWS_HEIGHT : penWeight());
shape = pps.createStroke(shape);
return shape;
return shape;
}
QPainterPath PartRectangle::shadowShape() const
{
QPainterPath shape;
shape.addRoundedRect(m_rect, m_xRadius, m_yRadius);
QPainterPath shape;
shape.addRoundedRect(m_rect, m_xRadius, m_yRadius);
QPainterPathStroker pps;
pps.setWidth(penWeight());
QPainterPathStroker pps;
pps.setWidth(penWeight());
return (pps.createStroke(shape));
return (pps.createStroke(shape));
}
/**
@brief PartRectangle::boundingRect
@return Bounding rectangle this part can fit into
@brief PartRectangle::boundingRect
@return Bounding rectangle this part can fit into
*/
QRectF PartRectangle::boundingRect() const
{
qreal adjust = (SHADOWS_HEIGHT + penWeight()) / 2;
//We add 0.5 because CustomElementGraphicPart::drawShadowShape
//draw a shape bigger of 0.5 when pen weight is to 0.
if (penWeight() == 0) adjust += 0.5;
qreal adjust = (SHADOWS_HEIGHT + penWeight()) / 2;
//We add 0.5 because CustomElementGraphicPart::drawShadowShape
//draw a shape bigger of 0.5 when pen weight is to 0.
if (penWeight() == 0) adjust += 0.5;
QRectF r = m_rect.normalized();
r.adjust(-adjust, -adjust, adjust, adjust);
QRectF r = m_rect.normalized();
r.adjust(-adjust, -adjust, adjust, adjust);
return(r);
return(r);
}
/**
@brief PartRectangle::isUseless
@return true if this part is irrelevant and does not deserve to be Retained / registered.
An rectangle is relevant when he's not null.
@brief PartRectangle::isUseless
@return true if this part is irrelevant and does not deserve to be Retained / registered.
An rectangle is relevant when he's not null.
*/
bool PartRectangle::isUseless() const
{
return(rect().isNull());
return(rect().isNull());
}
/**
@brief PartRectangle::startUserTransformation
Start the user-induced transformation, provided this primitive is contained
within the initial_selection_rect bounding rectangle.
@param initial_selection_rect
@brief PartRectangle::startUserTransformation
Start the user-induced transformation, provided this primitive is contained
within the initial_selection_rect bounding rectangle.
@param initial_selection_rect
*/
void PartRectangle::startUserTransformation(const QRectF &initial_selection_rect)
{
Q_UNUSED(initial_selection_rect)
// we keep track of our own rectangle at the moment in scene coordinates too
saved_points_.clear();
saved_points_ << mapToScene(rect().topLeft()) << mapToScene(rect().bottomRight());
Q_UNUSED(initial_selection_rect)
// we keep track of our own rectangle at the moment in scene coordinates too
saved_points_.clear();
saved_points_ << mapToScene(rect().topLeft()) << mapToScene(rect().bottomRight());
}
/**
@brief PartRectangle::handleUserTransformation
Handle the user-induced transformation from \a initial_selection_rect to \a new_selection_rect
@param initial_selection_rect
@param new_selection_rect
@brief PartRectangle::handleUserTransformation
Handle the user-induced transformation from \a initial_selection_rect to \a new_selection_rect
@param initial_selection_rect
@param new_selection_rect
*/
void PartRectangle::handleUserTransformation(const QRectF &initial_selection_rect, const QRectF &new_selection_rect)
{
QList<QPointF> mapped_points = mapPoints(initial_selection_rect, new_selection_rect, saved_points_);
setRect(QRectF(mapFromScene(mapped_points.at(0)), mapFromScene(mapped_points.at(1))));
QList<QPointF> mapped_points = mapPoints(initial_selection_rect, new_selection_rect, saved_points_);
setRect(QRectF(mapFromScene(mapped_points.at(0)), mapFromScene(mapped_points.at(1))));
}
/**
@brief PartRectangle::mouseReleaseEvent
Handle mouse release event
@param event
@brief PartRectangle::mouseReleaseEvent
Handle mouse release event
@param event
*/
void PartRectangle::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
if (event->button() == Qt::LeftButton && event->buttonDownPos(Qt::LeftButton) == event->pos())
switchResizeMode();
if (event->button() == Qt::LeftButton && event->buttonDownPos(Qt::LeftButton) == event->pos())
switchResizeMode();
CustomElementGraphicPart::mouseReleaseEvent(event);
CustomElementGraphicPart::mouseReleaseEvent(event);
}
/**
@brief PartRectangle::itemChange
@param change
@param value
@return
@brief PartRectangle::itemChange
@param change
@param value
@return
*/
QVariant PartRectangle::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value)
{
if (change == ItemSelectedHasChanged && scene())
{
if (value.toBool() == true)
{
//When item is selected, he must to be up to date whene the selection in the scene change, for display or not the handler,
//according to the number of selected items.
connect(scene(), &QGraphicsScene::selectionChanged, this, &PartRectangle::sceneSelectionChanged);
if (change == ItemSelectedHasChanged && scene())
{
if (value.toBool() == true)
{
//When item is selected, he must to be up to date whene the selection in the scene change, for display or not the handler,
//according to the number of selected items.
connect(scene(), &QGraphicsScene::selectionChanged, this, &PartRectangle::sceneSelectionChanged);
if (scene()->selectedItems().size() == 1)
addHandler();
}
else
{
disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartRectangle::sceneSelectionChanged);
removeHandler();
}
}
else if (change == ItemPositionHasChanged)
{
adjusteHandlerPos();
}
else if (change == ItemSceneChange)
{
if(scene())
disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartRectangle::sceneSelectionChanged);
if (scene()->selectedItems().size() == 1)
addHandler();
}
else
{
disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartRectangle::sceneSelectionChanged);
removeHandler();
}
}
else if (change == ItemPositionHasChanged)
{
adjusteHandlerPos();
}
else if (change == ItemSceneChange)
{
if(scene())
disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartRectangle::sceneSelectionChanged);
setSelected(false); //This item is removed from scene, then we deselect this, and so, the handlers is also removed.
}
setSelected(false); //This item is removed from scene, then we deselect this, and so, the handlers is also removed.
}
return QGraphicsItem::itemChange(change, value);
return QGraphicsItem::itemChange(change, value);
}
/**
@brief PartRectangle::sceneEventFilter
@param watched
@param event
@return
@brief PartRectangle::sceneEventFilter
@param watched
@param event
@return
*/
bool PartRectangle::sceneEventFilter(QGraphicsItem *watched, QEvent *event)
{
//Watched must be an handler
if(watched->type() == QetGraphicsHandlerItem::Type)
{
QetGraphicsHandlerItem *qghi = qgraphicsitem_cast<QetGraphicsHandlerItem *>(watched);
//Watched must be an handler
if(watched->type() == QetGraphicsHandlerItem::Type)
{
QetGraphicsHandlerItem *qghi = qgraphicsitem_cast<QetGraphicsHandlerItem *>(watched);
if(m_handler_vector.contains(qghi)) //Handler must be in m_vector_index, then we can start resize
{
m_vector_index = m_handler_vector.indexOf(qghi);
if (m_vector_index != -1)
{
if(event->type() == QEvent::GraphicsSceneMousePress) //Click
{
handlerMousePressEvent(qghi, static_cast<QGraphicsSceneMouseEvent *>(event));
return true;
}
else if(event->type() == QEvent::GraphicsSceneMouseMove) //Move
{
handlerMouseMoveEvent(qghi, static_cast<QGraphicsSceneMouseEvent *>(event));
return true;
}
else if (event->type() == QEvent::GraphicsSceneMouseRelease) //Release
{
handlerMouseReleaseEvent(qghi, static_cast<QGraphicsSceneMouseEvent *>(event));
return true;
}
}
}
}
if(m_handler_vector.contains(qghi)) //Handler must be in m_vector_index, then we can start resize
{
m_vector_index = m_handler_vector.indexOf(qghi);
if (m_vector_index != -1)
{
if(event->type() == QEvent::GraphicsSceneMousePress) //Click
{
handlerMousePressEvent(qghi, static_cast<QGraphicsSceneMouseEvent *>(event));
return true;
}
else if(event->type() == QEvent::GraphicsSceneMouseMove) //Move
{
handlerMouseMoveEvent(qghi, static_cast<QGraphicsSceneMouseEvent *>(event));
return true;
}
else if (event->type() == QEvent::GraphicsSceneMouseRelease) //Release
{
handlerMouseReleaseEvent(qghi, static_cast<QGraphicsSceneMouseEvent *>(event));
return true;
}
}
}
}
return false;
return false;
}
/**
@brief PartRectangle::switchResizeMode
@brief PartRectangle::switchResizeMode
*/
void PartRectangle::switchResizeMode()
{
if (m_resize_mode == 1)
{
m_resize_mode = 2;
for (QetGraphicsHandlerItem *qghi : m_handler_vector)
qghi->setColor(Qt::darkGreen);
}
else if (m_resize_mode == 2)
{
m_resize_mode = 3;
qDeleteAll(m_handler_vector);
m_handler_vector.clear();
addHandler();
for (QetGraphicsHandlerItem *qghi : m_handler_vector) {
qghi->setColor(Qt::magenta);
}
}
else if (m_resize_mode == 3)
{
m_resize_mode = 1;
qDeleteAll(m_handler_vector);
m_handler_vector.clear();
addHandler();
for (QetGraphicsHandlerItem *qghi : m_handler_vector) {
qghi->setColor(Qt::blue);
}
}
if (m_resize_mode == 1)
{
m_resize_mode = 2;
for (QetGraphicsHandlerItem *qghi : m_handler_vector)
qghi->setColor(Qt::darkGreen);
}
else if (m_resize_mode == 2)
{
m_resize_mode = 3;
qDeleteAll(m_handler_vector);
m_handler_vector.clear();
addHandler();
for (QetGraphicsHandlerItem *qghi : m_handler_vector) {
qghi->setColor(Qt::magenta);
}
}
else if (m_resize_mode == 3)
{
m_resize_mode = 1;
qDeleteAll(m_handler_vector);
m_handler_vector.clear();
addHandler();
for (QetGraphicsHandlerItem *qghi : m_handler_vector) {
qghi->setColor(Qt::blue);
}
}
}
/**
@brief PartRectangle::adjusteHandlerPos
@brief PartRectangle::adjusteHandlerPos
*/
void PartRectangle::adjusteHandlerPos()
{
if (m_handler_vector.isEmpty()) {
return;
}
if (m_handler_vector.isEmpty()) {
return;
}
QVector <QPointF> points_vector;
QVector <QPointF> points_vector;
if(m_resize_mode != 3) {
points_vector = QetGraphicsHandlerUtility::pointsForRect(m_rect);
}
else {
points_vector = QetGraphicsHandlerUtility::pointForRadiusRect(m_rect, m_xRadius, m_yRadius);
}
if(m_resize_mode != 3) {
points_vector = QetGraphicsHandlerUtility::pointsForRect(m_rect);
}
else {
points_vector = QetGraphicsHandlerUtility::pointForRadiusRect(m_rect, m_xRadius, m_yRadius);
}
if (m_handler_vector.size() == points_vector.size())
{
points_vector = mapToScene(points_vector);
for (int i = 0 ; i < points_vector.size() ; ++i)
m_handler_vector.at(i)->setPos(points_vector.at(i));
}
else
{
qDeleteAll(m_handler_vector);
m_handler_vector.clear();
addHandler();
}
if (m_handler_vector.size() == points_vector.size())
{
points_vector = mapToScene(points_vector);
for (int i = 0 ; i < points_vector.size() ; ++i)
m_handler_vector.at(i)->setPos(points_vector.at(i));
}
else
{
qDeleteAll(m_handler_vector);
m_handler_vector.clear();
addHandler();
}
}
/**
@brief PartRectangle::handlerMousePressEvent
@param qghi
@param event
@brief PartRectangle::handlerMousePressEvent
@param qghi
@param event
*/
void PartRectangle::handlerMousePressEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event)
{
Q_UNUSED(qghi)
Q_UNUSED(event)
Q_UNUSED(qghi)
Q_UNUSED(event)
m_old_rect = m_rect;
m_old_xRadius = m_xRadius;
m_old_yRadius = m_yRadius;
if(m_xRadius == 0 && m_yRadius == 0) {
m_modifie_radius_equaly = true;
}
m_old_rect = m_rect;
m_old_xRadius = m_xRadius;
m_old_yRadius = m_yRadius;
if(m_xRadius == 0 && m_yRadius == 0) {
m_modifie_radius_equaly = true;
}
}
/**
@brief PartRectangle::handlerMouseMoveEvent
@param qghi
@param event
@brief PartRectangle::handlerMouseMoveEvent
@param qghi
@param event
*/
void PartRectangle::handlerMouseMoveEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event)
{
Q_UNUSED(qghi)
Q_UNUSED(qghi)
QPointF new_pos = event->scenePos();
if (event->modifiers() != Qt::ControlModifier)
new_pos = elementScene()->snapToGrid(event->scenePos());
new_pos = mapFromScene(new_pos);
QPointF new_pos = event->scenePos();
if (event->modifiers() != Qt::ControlModifier)
new_pos = elementScene()->snapToGrid(event->scenePos());
new_pos = mapFromScene(new_pos);
if (m_resize_mode == 1)
setRect(QetGraphicsHandlerUtility::rectForPosAtIndex(m_rect, new_pos, m_vector_index));
else if (m_resize_mode == 2)
setRect(QetGraphicsHandlerUtility::mirrorRectForPosAtIndex(m_rect, new_pos, m_vector_index));
else
{
qreal radius = QetGraphicsHandlerUtility::radiusForPosAtIndex(m_rect, new_pos, m_vector_index);
if(m_modifie_radius_equaly) {
setXRadius(radius);
setYRadius(radius);
}
else if(m_vector_index == 0) {
setXRadius(radius);
}
else {
setYRadius(radius);
}
}
if (m_resize_mode == 1)
setRect(QetGraphicsHandlerUtility::rectForPosAtIndex(m_rect, new_pos, m_vector_index));
else if (m_resize_mode == 2)
setRect(QetGraphicsHandlerUtility::mirrorRectForPosAtIndex(m_rect, new_pos, m_vector_index));
else
{
qreal radius = QetGraphicsHandlerUtility::radiusForPosAtIndex(m_rect, new_pos, m_vector_index);
if(m_modifie_radius_equaly) {
setXRadius(radius);
setYRadius(radius);
}
else if(m_vector_index == 0) {
setXRadius(radius);
}
else {
setYRadius(radius);
}
}
adjusteHandlerPos();
adjusteHandlerPos();
}
void PartRectangle::handlerMouseReleaseEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event)
{
Q_UNUSED(qghi)
Q_UNUSED(event)
Q_UNUSED(qghi)
Q_UNUSED(event)
m_modifie_radius_equaly = false;
m_modifie_radius_equaly = false;
QUndoCommand *undo = new QUndoCommand("Modifier un rectangle");
if (m_old_rect != m_rect) {
QPropertyUndoCommand *u = new QPropertyUndoCommand(this, "rect", QVariant(m_old_rect.normalized()), QVariant(m_rect.normalized()), undo);
u->setAnimated(true, false);
}
if (m_old_xRadius != m_xRadius) {
QPropertyUndoCommand *u = new QPropertyUndoCommand(this, "xRadius", QVariant(m_old_xRadius), QVariant(m_xRadius), undo);
u->setAnimated();
}
if (m_old_yRadius != m_yRadius) {
QPropertyUndoCommand *u = new QPropertyUndoCommand(this, "yRadius", QVariant(m_old_yRadius), QVariant(m_yRadius), undo);
u->setAnimated();
}
QUndoCommand *undo = new QUndoCommand("Modifier un rectangle");
if (m_old_rect != m_rect) {
QPropertyUndoCommand *u = new QPropertyUndoCommand(this, "rect", QVariant(m_old_rect.normalized()), QVariant(m_rect.normalized()), undo);
u->setAnimated(true, false);
}
if (m_old_xRadius != m_xRadius) {
QPropertyUndoCommand *u = new QPropertyUndoCommand(this, "xRadius", QVariant(m_old_xRadius), QVariant(m_xRadius), undo);
u->setAnimated();
}
if (m_old_yRadius != m_yRadius) {
QPropertyUndoCommand *u = new QPropertyUndoCommand(this, "yRadius", QVariant(m_old_yRadius), QVariant(m_yRadius), undo);
u->setAnimated();
}
elementScene()->undoStack().push(undo);
m_vector_index = -1;
elementScene()->undoStack().push(undo);
m_vector_index = -1;
}
/**
@brief PartRectangle::sceneSelectionChanged
When the scene selection change, if there are several primitive selected, we remove the handler of this item
@brief PartRectangle::sceneSelectionChanged
When the scene selection change, if there are several primitive selected, we remove the handler of this item
*/
void PartRectangle::sceneSelectionChanged()
{
if (this->isSelected() && scene()->selectedItems().size() == 1)
addHandler();
else
removeHandler();
if (this->isSelected() && scene()->selectedItems().size() == 1)
addHandler();
else
removeHandler();
}
/**
@brief PartRectangle::addHandler
Add handlers for this item
@brief PartRectangle::addHandler
Add handlers for this item
*/
void PartRectangle::addHandler()
{
if (m_handler_vector.isEmpty() && scene())
{
if (m_resize_mode != 3) {
m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointsForRect(m_rect)));
}
else {
m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointForRadiusRect(m_rect, m_xRadius, m_yRadius)));
}
if (m_handler_vector.isEmpty() && scene())
{
if (m_resize_mode != 3) {
m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointsForRect(m_rect)));
}
else {
m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointForRadiusRect(m_rect, m_xRadius, m_yRadius)));
}
for (QetGraphicsHandlerItem *handler : m_handler_vector)
{
QColor color;
if(m_resize_mode == 1) {color = Qt::blue;}
else if (m_resize_mode == 2) {color = Qt::darkGreen;}
else {color = Qt::magenta;}
for (QetGraphicsHandlerItem *handler : m_handler_vector)
{
QColor color;
if(m_resize_mode == 1) {color = Qt::blue;}
else if (m_resize_mode == 2) {color = Qt::darkGreen;}
else {color = Qt::magenta;}
handler->setColor(color);
scene()->addItem(handler);
handler->installSceneEventFilter(this);
handler->setZValue(this->zValue()+1);
}
}
handler->setColor(color);
scene()->addItem(handler);
handler->installSceneEventFilter(this);
handler->setZValue(this->zValue()+1);
}
}
}
/**
@brief PartRectangle::removeHandler
Remove the handlers of this item
@brief PartRectangle::removeHandler
Remove the handlers of this item
*/
void PartRectangle::removeHandler()
{
if (!m_handler_vector.isEmpty())
{
qDeleteAll(m_handler_vector);
m_handler_vector.clear();
}
if (!m_handler_vector.isEmpty())
{
qDeleteAll(m_handler_vector);
m_handler_vector.clear();
}
}

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PART_RECTANGLE_H
#define PART_RECTANGLE_H
@@ -23,92 +23,92 @@
class QetGraphicsHandlerItem;
/**
This class represents a rectangle primitive which may be used to compose the
drawing of an electrical element within the element editor.
All coordinates is in item coordinate, except pos()
This class represents a rectangle primitive which may be used to compose the
drawing of an electrical element within the element editor.
All coordinates is in item coordinate, except pos()
*/
class PartRectangle : public CustomElementGraphicPart
{
Q_OBJECT
Q_OBJECT
Q_PROPERTY(QRectF rect READ rect WRITE setRect)
Q_PROPERTY(qreal xRadius READ XRadius WRITE setXRadius NOTIFY XRadiusChanged)
Q_PROPERTY(qreal yRadius READ YRadius WRITE setYRadius NOTIFY YRadiusChanged)
Q_PROPERTY(QRectF rect READ rect WRITE setRect)
Q_PROPERTY(qreal xRadius READ XRadius WRITE setXRadius NOTIFY XRadiusChanged)
Q_PROPERTY(qreal yRadius READ YRadius WRITE setYRadius NOTIFY YRadiusChanged)
// constructors, destructor
public:
PartRectangle(QETElementEditor *, QGraphicsItem *parent = nullptr);
~PartRectangle() override;
// constructors, destructor
public:
PartRectangle(QETElementEditor *, QGraphicsItem *parent = nullptr);
~PartRectangle() override;
private:
PartRectangle(const PartRectangle &);
private:
PartRectangle(const PartRectangle &);
signals:
void rectChanged();
void XRadiusChanged();
void YRadiusChanged();
signals:
void rectChanged();
void XRadiusChanged();
void YRadiusChanged();
// methods
public:
enum { Type = UserType + 1109 };
/**
Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a PartRectangle.
@return the QGraphicsItem type
*/
int type () const override { return Type; }
void paint (QPainter *, const QStyleOptionGraphicsItem *, QWidget * = nullptr) override;
QString name () const override { return(QObject::tr("rectangle", "element part name")); }
// methods
public:
enum { Type = UserType + 1109 };
/**
Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a PartRectangle.
@return the QGraphicsItem type
*/
int type () const override { return Type; }
void paint (QPainter *, const QStyleOptionGraphicsItem *, QWidget * = nullptr) override;
QString name () const override { return(QObject::tr("rectangle", "element part name")); }
QString xmlName () const override { return(QString("rect")); }
QDomElement toXml (QDomDocument &) const override;
bool fromXml (const QDomElement &) override;
static bool valideXml(QDomElement& element);
QString xmlName () const override { return(QString("rect")); }
QDomElement toXml (QDomDocument &) const override;
bool fromXml (const QDomElement &) override;
static bool valideXml(QDomElement& element);
QRectF rect() const;
void setRect(const QRectF &rect);
qreal XRadius() const {return m_xRadius;}
void setXRadius(qreal X);
qreal YRadius() const {return m_yRadius;}
void setYRadius(qreal Y);
QRectF rect() const;
void setRect(const QRectF &rect);
qreal XRadius() const {return m_xRadius;}
void setXRadius(qreal X);
qreal YRadius() const {return m_yRadius;}
void setYRadius(qreal Y);
QRectF sceneGeometricRect() const override;
virtual QPointF sceneTopLeft() const;
QRectF sceneGeometricRect() const override;
virtual QPointF sceneTopLeft() const;
QPainterPath shape () const override;
QPainterPath shadowShape() const override;
QRectF boundingRect() const override;
bool isUseless() const override;
QPainterPath shape () const override;
QPainterPath shadowShape() const override;
QRectF boundingRect() const override;
bool isUseless() const override;
void startUserTransformation(const QRectF &) override;
void handleUserTransformation(const QRectF &, const QRectF &) override;
void startUserTransformation(const QRectF &) override;
void handleUserTransformation(const QRectF &, const QRectF &) override;
protected:
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;
QVariant itemChange(GraphicsItemChange change, const QVariant &value) override;
bool sceneEventFilter(QGraphicsItem *watched, QEvent *event) override;
protected:
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;
QVariant itemChange(GraphicsItemChange change, const QVariant &value) override;
bool sceneEventFilter(QGraphicsItem *watched, QEvent *event) override;
private:
void switchResizeMode();
void adjusteHandlerPos();
void handlerMousePressEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void handlerMouseMoveEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void handlerMouseReleaseEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void sceneSelectionChanged ();
private:
void switchResizeMode();
void adjusteHandlerPos();
void handlerMousePressEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void handlerMouseMoveEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void handlerMouseReleaseEvent (QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event);
void sceneSelectionChanged ();
void addHandler();
void removeHandler();
void addHandler();
void removeHandler();
private:
QRectF m_rect,
m_old_rect;
QList<QPointF> saved_points_;
int m_resize_mode = 1,
m_vector_index = -1;
QVector<QetGraphicsHandlerItem *> m_handler_vector;
qreal m_xRadius = 0,
m_yRadius = 0,
m_old_xRadius,
m_old_yRadius;
bool m_modifie_radius_equaly = false;
private:
QRectF m_rect,
m_old_rect;
QList<QPointF> saved_points_;
int m_resize_mode = 1,
m_vector_index = -1;
QVector<QetGraphicsHandlerItem *> m_handler_vector;
qreal m_xRadius = 0,
m_yRadius = 0,
m_old_xRadius,
m_old_yRadius;
bool m_modifie_radius_equaly = false;
};
#endif

View File

@@ -1,39 +1,39 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#include "partterminal.h"
#include "terminal.h"
/**
@brief PartTerminal::PartTerminal
@param editor :
L'editeur d'element concerne
@param parent :
Le QGraphicsItem parent de cette borne
@brief PartTerminal::PartTerminal
@param editor :
L'editeur d'element concerne
@param parent :
Le QGraphicsItem parent de cette borne
*/
PartTerminal::PartTerminal(QETElementEditor *editor, QGraphicsItem *parent) :
CustomElementGraphicPart(editor, parent)
CustomElementGraphicPart(editor, parent)
{
d = new TerminalData(this);
d->m_name = tr("terminal");
d -> m_orientation = Qet::North;
d -> m_uuid = QUuid::createUuid(); // if part is loaded this uuid will be overwritten, but being sure that terminal has a uuid
updateSecondPoint();
setZValue(100000);
d = new TerminalData(this);
d->m_name = tr("terminal");
d -> m_orientation = Qet::North;
d -> m_uuid = QUuid::createUuid(); // if part is loaded this uuid will be overwritten, but being sure that terminal has a uuid
updateSecondPoint();
setZValue(100000);
}
/// Destructeur
@@ -42,208 +42,208 @@ PartTerminal::~PartTerminal()
}
/**
Importe les proprietes d'une borne depuis un element XML
@param xml_elmt Element XML a lire
Importe les proprietes d'une borne depuis un element XML
@param xml_elmt Element XML a lire
*/
bool PartTerminal::fromXml(const QDomElement &xml_elmt) {
QUuid uuid;
// update part and add uuid, which is used in the new version to connect terminals together
// if the attribute not exists, means, the element is created with an older version of qet. So use the legacy approach
// to identify terminals
propertyUuid(xml_elmt, "uuid", &d->m_uuid);
QUuid uuid;
// update part and add uuid, which is used in the new version to connect terminals together
// if the attribute not exists, means, the element is created with an older version of qet. So use the legacy approach
// to identify terminals
propertyUuid(xml_elmt, "uuid", &d->m_uuid);
if (!d->fromXml(xml_elmt))
return false;
if (!d->fromXml(xml_elmt))
return false;
setPos(d -> m_pos);
updateSecondPoint();
setPos(d -> m_pos);
updateSecondPoint();
return true;
return true;
}
/**
Exporte la borne en XML
@param xml_document Document XML a utiliser pour creer l'element XML
@return un element XML decrivant la borne
Exporte la borne en XML
@param xml_document Document XML a utiliser pour creer l'element XML
@return un element XML decrivant la borne
*/
QDomElement PartTerminal::toXml(QDomDocument &xml_document) const {
QDomElement qdo = xml_document.createElement("terminal");
QDomElement qdo = xml_document.createElement("terminal");
qdo.appendChild(createXmlProperty(xml_document, "uuid", d->m_uuid));
qdo.appendChild(createXmlProperty(xml_document, "uuid", d->m_uuid));
d->m_pos = pos();
d->m_pos = pos();
// Do not store terminal data in its own child
QDomElement terminalDataElement = d->toXml(xml_document);
for (int i=0; i < terminalDataElement.childNodes().length(); i++) {
qdo.appendChild(terminalDataElement.childNodes().at(i).cloneNode()); // cloneNode() is important, otherwise no deep clone is made
}
// Do not store terminal data in its own child
QDomElement terminalDataElement = d->toXml(xml_document);
for (int i=0; i < terminalDataElement.childNodes().length(); i++) {
qdo.appendChild(terminalDataElement.childNodes().at(i).cloneNode()); // cloneNode() is important, otherwise no deep clone is made
}
return qdo;
return qdo;
}
bool PartTerminal::valideXml(QDomElement& element) {
return TerminalData::valideXml(element);
return TerminalData::valideXml(element);
}
/**
Dessine la borne
@param painter QPainter a utiliser pour rendre le dessin
@param options Options pour affiner le rendu
@param widget Widget sur lequel le rendu est effectue
Dessine la borne
@param painter QPainter a utiliser pour rendre le dessin
@param options Options pour affiner le rendu
@param widget Widget sur lequel le rendu est effectue
*/
void PartTerminal::paint(
QPainter *painter,
const QStyleOptionGraphicsItem *options,
QWidget *widget)
QPainter *painter,
const QStyleOptionGraphicsItem *options,
QWidget *widget)
{
Q_UNUSED(widget);
painter -> save();
Q_UNUSED(widget);
painter -> save();
// annulation des renderhints
painter -> setRenderHint(QPainter::Antialiasing, false);
painter -> setRenderHint(QPainter::TextAntialiasing, false);
painter -> setRenderHint(QPainter::SmoothPixmapTransform, false);
// annulation des renderhints
painter -> setRenderHint(QPainter::Antialiasing, false);
painter -> setRenderHint(QPainter::TextAntialiasing, false);
painter -> setRenderHint(QPainter::SmoothPixmapTransform, false);
QPen t;
t.setWidthF(1.0);
QPen t;
t.setWidthF(1.0);
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
t.setCosmetic(options && options -> levelOfDetail < 1.0);
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
t.setCosmetic(options && options -> levelOfDetail < 1.0);
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
t.setCosmetic(
options
&& options->levelOfDetailFromTransform(
painter->worldTransform())
< 1.0);
t.setCosmetic(
options
&& options->levelOfDetailFromTransform(
painter->worldTransform())
< 1.0);
#endif
// dessin de la borne en rouge
t.setColor(isSelected() ? Terminal::neutralColor : Qt::red);
painter -> setPen(t);
painter -> drawLine(QPointF(0.0, 0.0), d -> second_point);
// dessin de la borne en rouge
t.setColor(isSelected() ? Terminal::neutralColor : Qt::red);
painter -> setPen(t);
painter -> drawLine(QPointF(0.0, 0.0), d -> second_point);
// dessin du point d'amarrage au conducteur en bleu
t.setColor(isSelected() ? Qt::red : Terminal::neutralColor);
painter -> setPen(t);
painter -> setBrush(Terminal::neutralColor);
painter -> drawPoint(QPointF(0.0, 0.0));
painter -> restore();
// dessin du point d'amarrage au conducteur en bleu
t.setColor(isSelected() ? Qt::red : Terminal::neutralColor);
painter -> setPen(t);
painter -> setBrush(Terminal::neutralColor);
painter -> drawPoint(QPointF(0.0, 0.0));
painter -> restore();
if (m_hovered)
drawShadowShape(painter);
if (m_hovered)
drawShadowShape(painter);
}
/**
@brief PartTerminal::shape
@return the shape of this item
@brief PartTerminal::shape
@return the shape of this item
*/
QPainterPath PartTerminal::shape() const
{
QPainterPath shape;
shape.lineTo(d -> second_point);
QPainterPath shape;
shape.lineTo(d -> second_point);
QPainterPathStroker pps;
pps.setWidth(1);
QPainterPathStroker pps;
pps.setWidth(1);
return (pps.createStroke(shape));
return (pps.createStroke(shape));
}
/**
@brief PartTerminal::boundingRect
@return the bounding rect of this item
@brief PartTerminal::boundingRect
@return the bounding rect of this item
*/
QRectF PartTerminal::boundingRect() const
{
QRectF br(QPointF(0, 0), d -> second_point);
br = br.normalized();
QRectF br(QPointF(0, 0), d -> second_point);
br = br.normalized();
qreal adjust = (SHADOWS_HEIGHT + 1) / 2;
br.adjust(-adjust, -adjust, adjust, adjust);
return(br);
qreal adjust = (SHADOWS_HEIGHT + 1) / 2;
br.adjust(-adjust, -adjust, adjust, adjust);
return(br);
}
/**
Definit l'orientation de la borne
@param ori la nouvelle orientation de la borne
Definit l'orientation de la borne
@param ori la nouvelle orientation de la borne
*/
void PartTerminal::setOrientation(Qet::Orientation ori) {
if (d -> m_orientation == ori) return;
prepareGeometryChange();
d -> m_orientation = ori;
updateSecondPoint();
emit orientationChanged();
if (d -> m_orientation == ori) return;
prepareGeometryChange();
d -> m_orientation = ori;
updateSecondPoint();
emit orientationChanged();
}
/**
@brief PartTerminal::setName
@param name
@brief PartTerminal::setName
@param name
*/
void PartTerminal::setName(QString& name) {
if (d -> m_name == name) return;
d -> m_name = name;
emit nameChanged();
if (d -> m_name == name) return;
d -> m_name = name;
emit nameChanged();
}
void PartTerminal::setNewUuid()
{
d -> m_uuid = QUuid::createUuid();
d -> m_uuid = QUuid::createUuid();
}
/**
Met a jour la position du second point en fonction de la position et de
l'orientation de la borne.
Met a jour la position du second point en fonction de la position et de
l'orientation de la borne.
*/
void PartTerminal::updateSecondPoint()
{
qreal ts = 4.0; // terminal size
switch(d -> m_orientation) {
case Qet::North: d -> second_point = QPointF(0.0, ts); break;
case Qet::East : d -> second_point = QPointF(-ts, 0.0); break;
case Qet::South: d -> second_point = QPointF(0.0, -ts); break;
case Qet::West : d -> second_point = QPointF(ts, 0.0); break;
}
qreal ts = 4.0; // terminal size
switch(d -> m_orientation) {
case Qet::North: d -> second_point = QPointF(0.0, ts); break;
case Qet::East : d -> second_point = QPointF(-ts, 0.0); break;
case Qet::South: d -> second_point = QPointF(0.0, -ts); break;
case Qet::West : d -> second_point = QPointF(ts, 0.0); break;
}
}
/**
@return true si cette partie n'est pas pertinente et ne merite pas d'etre
conservee / enregistree.
Une borne est toujours pertinente ; cette fonction renvoie donc
toujours false
@return true si cette partie n'est pas pertinente et ne merite pas d'etre
conservee / enregistree.
Une borne est toujours pertinente ; cette fonction renvoie donc
toujours false
*/
bool PartTerminal::isUseless() const
{
return(false);
return(false);
}
/**
@return the minimum, margin-less rectangle this part can fit into, in scene
coordinates. It is different from boundingRect() because it is not supposed
to imply any margin, and it is different from shape because it is a regular
rectangle, not a complex shape.
@return the minimum, margin-less rectangle this part can fit into, in scene
coordinates. It is different from boundingRect() because it is not supposed
to imply any margin, and it is different from shape because it is a regular
rectangle, not a complex shape.
*/
QRectF PartTerminal::sceneGeometricRect() const
{
return(sceneBoundingRect());
return(sceneBoundingRect());
}
/**
Start the user-induced transformation, provided this primitive is contained
within the \a initial_selection_rect bounding rectangle.
Start the user-induced transformation, provided this primitive is contained
within the \a initial_selection_rect bounding rectangle.
*/
void PartTerminal::startUserTransformation(const QRectF &initial_selection_rect) {
Q_UNUSED(initial_selection_rect)
saved_position_ = scenePos();
Q_UNUSED(initial_selection_rect)
saved_position_ = scenePos();
}
/**
Handle the user-induced transformation from \a initial_selection_rect to \a new_selection_rect
Handle the user-induced transformation from \a initial_selection_rect to \a new_selection_rect
*/
void PartTerminal::handleUserTransformation(const QRectF &initial_selection_rect, const QRectF &new_selection_rect) {
QPointF mapped_point = mapPoints(
initial_selection_rect, new_selection_rect, QList<QPointF>() << saved_position_).first();
setPos(mapped_point);
QPointF mapped_point = mapPoints(
initial_selection_rect, new_selection_rect, QList<QPointF>() << saved_position_).first();
setPos(mapped_point);
}

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PART_TERMINAL_H
#define PART_TERMINAL_H
@@ -24,62 +24,62 @@
/**
This class represents a terminal which may be used to compose the drawing of
an electrical element within the element editor.
This class represents a terminal which may be used to compose the drawing of
an electrical element within the element editor.
*/
class PartTerminal : public CustomElementGraphicPart {
Q_OBJECT
Q_PROPERTY(Qet::Orientation orientation READ orientation WRITE setOrientation)
Q_PROPERTY(QString name READ name WRITE setName)
Q_OBJECT
Q_PROPERTY(Qet::Orientation orientation READ orientation WRITE setOrientation)
Q_PROPERTY(QString name READ name WRITE setName)
public:
// constructors, destructor
PartTerminal(QETElementEditor *editor, QGraphicsItem *parent = nullptr);
~PartTerminal() override;
private:
PartTerminal(const PartTerminal &);
public:
// constructors, destructor
PartTerminal(QETElementEditor *editor, QGraphicsItem *parent = nullptr);
~PartTerminal() override;
private:
PartTerminal(const PartTerminal &);
signals:
void orientationChanged();
void nameChanged();
signals:
void orientationChanged();
void nameChanged();
// methods
public:
enum { Type = UserType + 1106 };
/**
Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a PartTerminal.
@return the QGraphicsItem type
*/
int type() const override { return Type; }
QString name() const override { return d -> m_name; }
QString xmlName() const override { return(QString("terminal")); }
bool fromXml(const QDomElement &) override;
QDomElement toXml(QDomDocument &) const override;
static bool valideXml(QDomElement& element);
// methods
public:
enum { Type = UserType + 1106 };
/**
Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a PartTerminal.
@return the QGraphicsItem type
*/
int type() const override { return Type; }
QString name() const override { return d -> m_name; }
QString xmlName() const override { return(QString("terminal")); }
bool fromXml(const QDomElement &) override;
QDomElement toXml(QDomDocument &) const override;
static bool valideXml(QDomElement& element);
void paint(
QPainter *painter,
const QStyleOptionGraphicsItem *,
QWidget *) override;
QPainter *painter,
const QStyleOptionGraphicsItem *,
QWidget *) override;
QPainterPath shape() const override;
QPainterPath shadowShape() const override {return shape();}
QRectF boundingRect() const override;
bool isUseless() const override;
QRectF sceneGeometricRect() const override;
void startUserTransformation(const QRectF &) override;
void handleUserTransformation(const QRectF &, const QRectF &) override;
QPainterPath shape() const override;
QPainterPath shadowShape() const override {return shape();}
QRectF boundingRect() const override;
bool isUseless() const override;
QRectF sceneGeometricRect() const override;
void startUserTransformation(const QRectF &) override;
void handleUserTransformation(const QRectF &, const QRectF &) override;
Qet::Orientation orientation() const {return d -> m_orientation;}
void setOrientation(Qet::Orientation ori);
Qet::Orientation orientation() const {return d -> m_orientation;}
void setOrientation(Qet::Orientation ori);
void setName(QString& name);
void setNewUuid();
void setName(QString& name);
void setNewUuid();
private:
void updateSecondPoint();
TerminalData* d; // pointer to the terminal data
private:
void updateSecondPoint();
TerminalData* d; // pointer to the terminal data
private:
QPointF saved_position_;
private:
QPointF saved_position_;
};
#endif

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#include "parttext.h"
#include "texteditor.h"
@@ -23,38 +23,38 @@
#include "QPropertyUndoCommand/qpropertyundocommand.h"
/**
Constructeur
@param editor L'editeur d'element concerne
@param parent Le QGraphicsItem parent de ce texte statique
Constructeur
@param editor L'editeur d'element concerne
@param parent Le QGraphicsItem parent de ce texte statique
*/
PartText::PartText(QETElementEditor *editor, QGraphicsItem *parent) :
QGraphicsTextItem(parent),
CustomElementPart(editor),
previous_text()
QGraphicsTextItem(parent),
CustomElementPart(editor),
previous_text()
{
document() -> setDocumentMargin(1.0);
setDefaultTextColor(Qt::black);
setFont(QETApp::diagramTextsFont());
real_font_size_ = font().pointSize();
setFlags(QGraphicsItem::ItemIsSelectable
| QGraphicsItem::ItemSendsGeometryChanges
| QGraphicsItem::ItemIsMovable);
setAcceptHoverEvents(true);
setDefaultTextColor(Qt::black);
setPlainText(QObject::tr(
"T",
"default text when adding a text in the element editor"));
document() -> setDocumentMargin(1.0);
setDefaultTextColor(Qt::black);
setFont(QETApp::diagramTextsFont());
real_font_size_ = font().pointSize();
setFlags(QGraphicsItem::ItemIsSelectable
| QGraphicsItem::ItemSendsGeometryChanges
| QGraphicsItem::ItemIsMovable);
setAcceptHoverEvents(true);
setDefaultTextColor(Qt::black);
setPlainText(QObject::tr(
"T",
"default text when adding a text in the element editor"));
adjustItemPosition(1);
// adjust textfield position after line additions/deletions
connect(document(),
SIGNAL(blockCountChanged(int)),
this,
SLOT(adjustItemPosition(int)));
connect(document(),
SIGNAL(contentsChanged()),
this,
SLOT(adjustItemPosition()));
adjustItemPosition(1);
// adjust textfield position after line additions/deletions
connect(document(),
SIGNAL(blockCountChanged(int)),
this,
SLOT(adjustItemPosition(int)));
connect(document(),
SIGNAL(contentsChanged()),
this,
SLOT(adjustItemPosition()));
}
/// Destructeur
@@ -63,346 +63,346 @@ PartText::~PartText()
}
/**
Importe les proprietes d'un texte statique depuis un element XML
@param xml_element Element XML a lire
Importe les proprietes d'un texte statique depuis un element XML
@param xml_element Element XML a lire
*/
bool PartText::fromXml(const QDomElement &xml_element)
int size;
QString font;
int size;
QString font;
if (propertyInteger(xml_element, "size", &size) != PropertyFlags::NotFound)
{
if (size < 1) {
size = 20;
}
QFont font_ = this -> font();
font_.setPointSize(size);
setFont(font_);
}
else if (propertyString(xml_element, "font", &font) != PropertyFlags::NotFound)
{
QFont font_;
font_.fromString(font);
setFont(font_);
} else {
return false;
}
if (propertyInteger(xml_element, "size", &size) != PropertyFlags::NotFound)
{
if (size < 1) {
size = 20;
}
QFont font_ = this -> font();
font_.setPointSize(size);
setFont(font_);
}
else if (propertyString(xml_element, "font", &font) != PropertyFlags::NotFound)
{
QFont font_;
font_.fromString(font);
setFont(font_);
} else {
return false;
}
QColor color;
QString text;
propertyColor(xml_element, "color", &color);
setDefaultTextColor(color);
QColor color;
QString text;
propertyColor(xml_element, "color", &color);
setDefaultTextColor(color);
propertyString(xml_element, "text", &text);
setPlainText(text);
propertyString(xml_element, "text", &text);
setPlainText(text);
double x=0, y=0, rot=0;
if (propertyDouble(xml_element, "x", &x) == PropertyFlags::NoValidConversion ||
propertyDouble(xml_element, "y", &y) == PropertyFlags::NoValidConversion)
return false;
setPos(x, y);
double x=0, y=0, rot=0;
if (propertyDouble(xml_element, "x", &x) == PropertyFlags::NoValidConversion ||
propertyDouble(xml_element, "y", &y) == PropertyFlags::NoValidConversion)
return false;
setPos(x, y);
if (propertyDouble(xml_element, "rotation", &rot) == PropertyFlags::NoValidConversion)
return false;
setRotation(rot);
if (propertyDouble(xml_element, "rotation", &rot) == PropertyFlags::NoValidConversion)
return false;
setRotation(rot);
return true;
return true;
}
/**
Exporte le texte statique en XML
@param xml_document Document XML a utiliser pour creer l'element XML
@return un element XML decrivant le texte statique
Exporte le texte statique en XML
@param xml_document Document XML a utiliser pour creer l'element XML
@return un element XML decrivant le texte statique
*/
QDomElement PartText::toXml(QDomDocument &xml_document) const
{
QDomElement xml_element = xml_document.createElement(xmlName());
QDomElement xml_element = xml_document.createElement(xmlName());
xml_element.appendChild(createXmlProperty(xml_document, "x", pos().x()));
xml_element.appendChild(createXmlProperty(xml_document, "y", pos().y()));
xml_element.appendChild(createXmlProperty(xml_document, "text", toPlainText()));
xml_element.appendChild(createXmlProperty(xml_document, "font", font().toString()));
xml_element.appendChild(createXmlProperty(xml_document, "rotation", rotation()));
xml_element.appendChild(createXmlProperty(xml_document, "color", defaultTextColor().name()));
xml_element.appendChild(createXmlProperty(xml_document, "x", pos().x()));
xml_element.appendChild(createXmlProperty(xml_document, "y", pos().y()));
xml_element.appendChild(createXmlProperty(xml_document, "text", toPlainText()));
xml_element.appendChild(createXmlProperty(xml_document, "font", font().toString()));
xml_element.appendChild(createXmlProperty(xml_document, "rotation", rotation()));
xml_element.appendChild(createXmlProperty(xml_document, "color", defaultTextColor().name()));
return(xml_element);
return(xml_element);
}
bool PartText::valideXml(QDomElement& element) {
if (propertyInteger(element, "size") == PropertyFlags::NotFound ||
propertyString(element, "font") == PropertyFlags::NotFound) {
return false;
}
if (propertyInteger(element, "size") == PropertyFlags::NotFound ||
propertyString(element, "font") == PropertyFlags::NotFound) {
return false;
}
if (propertyString(element, "color") == PropertyFlags::NoValidConversion)
return false;
if (propertyString(element, "color") == PropertyFlags::NoValidConversion)
return false;
if (propertyString(element, "text"))
return false;
if (propertyString(element, "text"))
return false;
if (propertyDouble(element, "x") == PropertyFlags::NoValidConversion ||
propertyDouble(element, "y") == PropertyFlags::NoValidConversion)
return false;
if (propertyDouble(element, "x") == PropertyFlags::NoValidConversion ||
propertyDouble(element, "y") == PropertyFlags::NoValidConversion)
return false;
if (propertyDouble(element, "rotation", 0) == PropertyFlags::NoValidConversion)
return false;
if (propertyDouble(element, "rotation", 0) == PropertyFlags::NoValidConversion)
return false;
return true;
return true;
}
/**
@return Les coordonnees du point situe en bas a gauche du texte.
@return Les coordonnees du point situe en bas a gauche du texte.
*/
QPointF PartText::margin() const
{
QFont used_font = font();
QFontMetrics qfm(used_font);
qreal document_margin = document() -> documentMargin();
QFont used_font = font();
QFontMetrics qfm(used_font);
qreal document_margin = document() -> documentMargin();
QPointF margin(
// marge autour du texte
document_margin,
// marge au-dessus du texte + distance entre le plafond du texte et la baseline
document_margin + qfm.ascent()
);
return(margin);
QPointF margin(
// marge autour du texte
document_margin,
// marge au-dessus du texte + distance entre le plafond du texte et la baseline
document_margin + qfm.ascent()
);
return(margin);
}
/**
@brief PartText::focusInEvent
@param e : The QFocusEvent object describing the focus gain.
Start text edition when the item gains focus.
@see QGraphicsItem::focusInEvent(QFocusEvent *)
@brief PartText::focusInEvent
@param e : The QFocusEvent object describing the focus gain.
Start text edition when the item gains focus.
@see QGraphicsItem::focusInEvent(QFocusEvent *)
*/
void PartText::focusInEvent(QFocusEvent *e) {
startEdition();
QGraphicsTextItem::focusInEvent(e);
startEdition();
QGraphicsTextItem::focusInEvent(e);
}
/**
@brief PartText::focusOutEvent
@param e : The QFocusEvent object describing the focus loss.
End text edition when the item loses focus.
@see QGraphicsItem::focusOutEvent(QFocusEvent *)
@brief PartText::focusOutEvent
@param e : The QFocusEvent object describing the focus loss.
End text edition when the item loses focus.
@see QGraphicsItem::focusOutEvent(QFocusEvent *)
*/
void PartText::focusOutEvent(QFocusEvent *e) {
QGraphicsTextItem::focusOutEvent(e);
endEdition();
QGraphicsTextItem::focusOutEvent(e);
endEdition();
}
/**
@brief PartText::keyPressEvent
Used to handle the escape key when the event is delivered to the field,
not to the decorator.
@param event
@see QGraphicsTextItem::keyPressEvent()
@brief PartText::keyPressEvent
Used to handle the escape key when the event is delivered to the field,
not to the decorator.
@param event
@see QGraphicsTextItem::keyPressEvent()
*/
void PartText::keyPressEvent(QKeyEvent *event) {
if (event -> key() == Qt::Key_Escape) {
endEdition();
}
else {
QGraphicsTextItem::keyPressEvent(event);
}
if (event -> key() == Qt::Key_Escape) {
endEdition();
}
else {
QGraphicsTextItem::keyPressEvent(event);
}
}
/**
Permet a l'element texte de devenir editable lorsqu'on double-clique dessus
@param e Le QGraphicsSceneMouseEvent qui decrit le double-clic
Permet a l'element texte de devenir editable lorsqu'on double-clique dessus
@param e Le QGraphicsSceneMouseEvent qui decrit le double-clic
*/
void PartText::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *e) {
QGraphicsTextItem::mouseDoubleClickEvent(e);
if (e -> button() == Qt::LeftButton) {
setEditable(true);
}
QGraphicsTextItem::mouseDoubleClickEvent(e);
if (e -> button() == Qt::LeftButton) {
setEditable(true);
}
}
/**
Gere les changements intervenant sur cette partie
@param change Type de changement
@param value Valeur numerique relative au changement
Gere les changements intervenant sur cette partie
@param change Type de changement
@param value Valeur numerique relative au changement
*/
QVariant PartText::itemChange(GraphicsItemChange change, const QVariant &value) {
if (change == QGraphicsItem::ItemPositionHasChanged ||
change == QGraphicsItem::ItemSceneHasChanged ||
change == QGraphicsItem::ItemSelectedHasChanged) {
updateCurrentPartEditor();
}
return(QGraphicsTextItem::itemChange(change, value));
if (change == QGraphicsItem::ItemPositionHasChanged ||
change == QGraphicsItem::ItemSceneHasChanged ||
change == QGraphicsItem::ItemSelectedHasChanged) {
updateCurrentPartEditor();
}
return(QGraphicsTextItem::itemChange(change, value));
}
/**
@return le rectangle delimitant cette partie.
@return le rectangle delimitant cette partie.
*/
QRectF PartText::boundingRect() const
{
QRectF r = QGraphicsTextItem::boundingRect();
r.adjust(0.0, -1.1, 0.0, 0.0);
return(r);
QRectF r = QGraphicsTextItem::boundingRect();
r.adjust(0.0, -1.1, 0.0, 0.0);
return(r);
}
/**
@return true si cette partie n'est pas pertinente et ne merite pas d'etre
conservee / enregistree.
Un texte statique n'est pas pertinent lorsque son texte est vide.
@return true si cette partie n'est pas pertinente et ne merite pas d'etre
conservee / enregistree.
Un texte statique n'est pas pertinent lorsque son texte est vide.
*/
bool PartText::isUseless() const
{
return(toPlainText().isEmpty());
return(toPlainText().isEmpty());
}
/**
@return the minimum, margin-less rectangle this part can fit into, in scene
coordinates. It is different from boundingRect() because it is not supposed
to imply any margin, and it is different from shape because it is a regular
rectangle, not a complex shape.
@return the minimum, margin-less rectangle this part can fit into, in scene
coordinates. It is different from boundingRect() because it is not supposed
to imply any margin, and it is different from shape because it is a regular
rectangle, not a complex shape.
*/
QRectF PartText::sceneGeometricRect() const
{
return(sceneBoundingRect());
return(sceneBoundingRect());
}
/**
Start the user-induced transformation, provided this primitive is contained
within the \a rect bounding rectangle.
Start the user-induced transformation, provided this primitive is contained
within the \a rect bounding rectangle.
*/
void PartText::startUserTransformation(const QRectF &rect) {
Q_UNUSED(rect)
saved_point_ = pos(); // scene coordinates, no need to mapFromScene()
saved_font_size_ = real_font_size_;
Q_UNUSED(rect)
saved_point_ = pos(); // scene coordinates, no need to mapFromScene()
saved_font_size_ = real_font_size_;
}
/**
Handle the user-induced transformation from \a initial_selection_rect to \a new_selection_rect
Handle the user-induced transformation from \a initial_selection_rect to \a new_selection_rect
*/
void PartText::handleUserTransformation(const QRectF &initial_selection_rect, const QRectF &new_selection_rect) {
// let's try the naive approach
QPointF new_pos = mapPoints(initial_selection_rect, new_selection_rect, QList<QPointF>() << saved_point_).first();
setPos(new_pos);
// let's try the naive approach
QPointF new_pos = mapPoints(initial_selection_rect, new_selection_rect, QList<QPointF>() << saved_point_).first();
setPos(new_pos);
// adjust the font size following the vertical scale factor
qreal sy = new_selection_rect.height() / initial_selection_rect.height();
qreal new_font_size = saved_font_size_ * sy;
setProperty("real_size", qMax(1, qRound(new_font_size)));
// adjust the font size following the vertical scale factor
qreal sy = new_selection_rect.height() / initial_selection_rect.height();
qreal new_font_size = saved_font_size_ * sy;
setProperty("real_size", qMax(1, qRound(new_font_size)));
}
void PartText::setDefaultTextColor(const QColor &color) {
if (color != this -> defaultTextColor()) {
QGraphicsTextItem::setDefaultTextColor(color);
emit colorChanged(color);
}
if (color != this -> defaultTextColor()) {
QGraphicsTextItem::setDefaultTextColor(color);
emit colorChanged(color);
}
}
void PartText::setPlainText(const QString &text) {
if (text != this -> toPlainText()) {
QGraphicsTextItem::setPlainText(text);
emit plainTextChanged(text);
}
if (text != this -> toPlainText()) {
QGraphicsTextItem::setPlainText(text);
emit plainTextChanged(text);
}
}
void PartText::setFont(const QFont &font) {
if (font != this -> font()) {
QGraphicsTextItem::setFont(font);
emit fontChanged(font);
}
if (font != this -> font()) {
QGraphicsTextItem::setFont(font);
emit fontChanged(font);
}
}
void PartText::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
if((event -> buttons() & Qt::LeftButton) && (flags() & QGraphicsItem::ItemIsMovable)) {
QPointF pos = event -> scenePos() + (m_origine_pos - event -> buttonDownScenePos(Qt::LeftButton));
event -> modifiers() == Qt::ControlModifier ? setPos(pos) : setPos(elementScene() -> snapToGrid(pos));
}
else {
QGraphicsObject::mouseMoveEvent(event);
}
if((event -> buttons() & Qt::LeftButton) && (flags() & QGraphicsItem::ItemIsMovable)) {
QPointF pos = event -> scenePos() + (m_origine_pos - event -> buttonDownScenePos(Qt::LeftButton));
event -> modifiers() == Qt::ControlModifier ? setPos(pos) : setPos(elementScene() -> snapToGrid(pos));
}
else {
QGraphicsObject::mouseMoveEvent(event);
}
}
void PartText::mousePressEvent(QGraphicsSceneMouseEvent *event) {
if(event -> button() == Qt::LeftButton)
m_origine_pos = this -> pos();
if(event -> button() == Qt::LeftButton)
m_origine_pos = this -> pos();
QGraphicsObject::mousePressEvent(event);
QGraphicsObject::mousePressEvent(event);
}
void PartText::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
if((event -> button() & Qt::LeftButton) &&
(flags() & QGraphicsItem::ItemIsMovable) &&
m_origine_pos != pos())
{
QPropertyUndoCommand *undo = new QPropertyUndoCommand(this, "pos", QVariant(m_origine_pos), QVariant(pos()));
undo -> setText(tr("Déplacer un texte"));
undo -> enableAnimation();
elementScene() -> undoStack().push(undo);
}
if((event -> button() & Qt::LeftButton) &&
(flags() & QGraphicsItem::ItemIsMovable) &&
m_origine_pos != pos())
{
QPropertyUndoCommand *undo = new QPropertyUndoCommand(this, "pos", QVariant(m_origine_pos), QVariant(pos()));
undo -> setText(tr("Déplacer un texte"));
undo -> enableAnimation();
elementScene() -> undoStack().push(undo);
}
QGraphicsObject::mouseReleaseEvent(event);
QGraphicsObject::mouseReleaseEvent(event);
}
/**
Cette methode s'assure que la position du champ de texte est coherente
en repositionnant son origine (c-a-d le milieu du bord gauche du champ de
texte) a la position originale. Cela est notamment utile lorsque le champ
de texte est agrandi ou retreci verticalement (ajout ou retrait de lignes).
@param new_block_count Nombre de blocs dans le PartText
Cette methode s'assure que la position du champ de texte est coherente
en repositionnant son origine (c-a-d le milieu du bord gauche du champ de
texte) a la position originale. Cela est notamment utile lorsque le champ
de texte est agrandi ou retreci verticalement (ajout ou retrait de lignes).
@param new_block_count Nombre de blocs dans le PartText
*/
void PartText::adjustItemPosition(int new_block_count) {
Q_UNUSED(new_block_count);
QPointF origin_offset = margin();
Q_UNUSED(new_block_count);
QPointF origin_offset = margin();
QTransform base_translation;
base_translation.translate(-origin_offset.x(), -origin_offset.y());
setTransform(base_translation, false);
setTransformOriginPoint(origin_offset);
QTransform base_translation;
base_translation.translate(-origin_offset.x(), -origin_offset.y());
setTransform(base_translation, false);
setTransformOriginPoint(origin_offset);
}
/**
@param editable Whether this text item should be interactively editable.
@param editable Whether this text item should be interactively editable.
*/
void PartText::setEditable(bool editable) {
if (editable) {
setFlag(QGraphicsItem::ItemIsFocusable, true);
setTextInteractionFlags(Qt::TextEditorInteraction);
setFocus(Qt::MouseFocusReason);
}
else {
setTextInteractionFlags(Qt::NoTextInteraction);
setFlag(QGraphicsItem::ItemIsFocusable, false);
}
if (editable) {
setFlag(QGraphicsItem::ItemIsFocusable, true);
setTextInteractionFlags(Qt::TextEditorInteraction);
setFocus(Qt::MouseFocusReason);
}
else {
setTextInteractionFlags(Qt::NoTextInteraction);
setFlag(QGraphicsItem::ItemIsFocusable, false);
}
}
/**
Start text edition by storing the former value of the text.
Start text edition by storing the former value of the text.
*/
void PartText::startEdition()
{
// !previous_text.isNull() means the text is being edited
previous_text = toPlainText();
// !previous_text.isNull() means the text is being edited
previous_text = toPlainText();
}
/**
End text edition, potentially generating a ChangePartCommand if the text
has changed.
End text edition, potentially generating a ChangePartCommand if the text
has changed.
*/
void PartText::endEdition()
{
if (!previous_text.isNull()) {
// the text was being edited
QString new_text = toPlainText();
if (previous_text != new_text) {
QPropertyUndoCommand *undo = new QPropertyUndoCommand(this, "text", previous_text, new_text);
undo -> setText(tr("Modifier un champ texte"));
undoStack().push(undo);
previous_text = QString();
}
}
if (!previous_text.isNull()) {
// the text was being edited
QString new_text = toPlainText();
if (previous_text != new_text) {
QPropertyUndoCommand *undo = new QPropertyUndoCommand(this, "text", previous_text, new_text);
undo -> setText(tr("Modifier un champ texte"));
undoStack().push(undo);
previous_text = QString();
}
}
// deselectionne le texte
QTextCursor qtc = textCursor();
qtc.clearSelection();
setTextCursor(qtc);
// deselectionne le texte
QTextCursor qtc = textCursor();
qtc.clearSelection();
setTextCursor(qtc);
setEditable(false);
setEditable(false);
}

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PART_TEXT_H
#define PART_TEXT_H
@@ -24,82 +24,82 @@
class TextEditor;
class ElementPrimitiveDecorator;
/**
This class represents an static text primitive which may be used to compose
the drawing of an electrical element within the element editor.
This class represents an static text primitive which may be used to compose
the drawing of an electrical element within the element editor.
*/
class PartText : public QGraphicsTextItem, public CustomElementPart {
Q_OBJECT
Q_PROPERTY(qreal real_size READ realSize WRITE setRealSize)
Q_PROPERTY(QColor color READ defaultTextColor WRITE setDefaultTextColor NOTIFY colorChanged)
Q_PROPERTY(QString text READ toPlainText WRITE setPlainText NOTIFY plainTextChanged)
Q_PROPERTY(QFont font READ font WRITE setFont NOTIFY fontChanged)
Q_OBJECT
Q_PROPERTY(qreal real_size READ realSize WRITE setRealSize)
Q_PROPERTY(QColor color READ defaultTextColor WRITE setDefaultTextColor NOTIFY colorChanged)
Q_PROPERTY(QString text READ toPlainText WRITE setPlainText NOTIFY plainTextChanged)
Q_PROPERTY(QFont font READ font WRITE setFont NOTIFY fontChanged)
signals:
void fontChanged(const QFont &font);
void colorChanged(const QColor &color);
void plainTextChanged(const QString &text);
signals:
void fontChanged(const QFont &font);
void colorChanged(const QColor &color);
void plainTextChanged(const QString &text);
// constructors, destructor
public:
PartText(QETElementEditor *, QGraphicsItem * = nullptr);
~PartText() override;
// constructors, destructor
public:
PartText(QETElementEditor *, QGraphicsItem * = nullptr);
~PartText() override;
private:
PartText(const PartText &);
private:
PartText(const PartText &);
// methods
public:
enum { Type = UserType + 1107 };
/**
Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a
PartText.
@return the QGraphicsItem type
*/
int type() const override { return Type; }
QString name() const override { return(QObject::tr("texte", "element part name")); }
QString xmlName() const override { return(QString("text")); }
bool fromXml(const QDomElement &) override;
static bool valideXml(QDomElement& element);
QDomElement toXml(QDomDocument &) const override;
void setRotation(qreal angle) {(QGraphicsObject::setRotation(QET::correctAngle(angle)));}
bool isUseless() const override;
QRectF sceneGeometricRect() const override;
void startUserTransformation(const QRectF &) override;
void handleUserTransformation(const QRectF &, const QRectF &) override;
// methods
public:
enum { Type = UserType + 1107 };
/**
Enable the use of qgraphicsitem_cast to safely cast a QGraphicsItem into a
PartText.
@return the QGraphicsItem type
*/
int type() const override { return Type; }
QString name() const override { return(QObject::tr("texte", "element part name")); }
QString xmlName() const override { return(QString("text")); }
bool fromXml(const QDomElement &) override;
static bool valideXml(QDomElement& element);
QDomElement toXml(QDomDocument &) const override;
void setRotation(qreal angle) {(QGraphicsObject::setRotation(QET::correctAngle(angle)));}
bool isUseless() const override;
QRectF sceneGeometricRect() const override;
void startUserTransformation(const QRectF &) override;
void handleUserTransformation(const QRectF &, const QRectF &) override;
void setProperty(const char *name, const QVariant &value) override {QGraphicsTextItem::setProperty(name, value);}
QVariant property(const char *name) const override {return QGraphicsTextItem::property(name);}
void setProperty(const char *name, const QVariant &value) override {QGraphicsTextItem::setProperty(name, value);}
QVariant property(const char *name) const override {return QGraphicsTextItem::property(name);}
qreal realSize() const {return real_font_size_;}
void setRealSize(qreal rs) {real_font_size_ = rs;}
void setDefaultTextColor(const QColor &color);
void setPlainText(const QString &text);
void setFont(const QFont &font);
qreal realSize() const {return real_font_size_;}
void setRealSize(qreal rs) {real_font_size_ = rs;}
void setDefaultTextColor(const QColor &color);
void setPlainText(const QString &text);
void setFont(const QFont &font);
public slots:
void adjustItemPosition(int = 0);
void setEditable(bool);
void startEdition();
void endEdition();
public slots:
void adjustItemPosition(int = 0);
void setEditable(bool);
void startEdition();
void endEdition();
protected:
void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;
void focusInEvent(QFocusEvent *) override;
void focusOutEvent(QFocusEvent *) override;
void keyPressEvent(QKeyEvent *) override;
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *) override;
QVariant itemChange(GraphicsItemChange, const QVariant &) override;
QRectF boundingRect() const override;
protected:
void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;
void focusInEvent(QFocusEvent *) override;
void focusOutEvent(QFocusEvent *) override;
void keyPressEvent(QKeyEvent *) override;
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *) override;
QVariant itemChange(GraphicsItemChange, const QVariant &) override;
QRectF boundingRect() const override;
private:
QPointF margin() const;
QString previous_text;
qreal real_font_size_;
QPointF saved_point_;
qreal saved_font_size_;
QGraphicsItem *decorator_;
QPointF m_origine_pos;
private:
QPointF margin() const;
QString previous_text;
qreal real_font_size_;
QPointF saved_point_;
qreal saved_font_size_;
QGraphicsItem *decorator_;
QPointF m_origine_pos;
};
#endif

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#include "elementtextpattern.h"
#include "qetapp.h"
@@ -35,238 +35,238 @@
#include <QStringList>
/**
@brief ExportElementTextPattern::ExportElementTextPattern
Constructor
@param elmt
@brief ExportElementTextPattern::ExportElementTextPattern
Constructor
@param elmt
*/
ExportElementTextPattern::ExportElementTextPattern(Element *elmt) :
m_element(elmt)
m_element(elmt)
{
//Create the conf dir if not yet.
QDir dir(QETApp::configDir()+ "/element_texts_pattern");
if(!dir.exists())
{
dir.cdUp();
dir.mkdir("element_texts_pattern");
dir.cd("element_texts_pattern");
}
//Create the conf dir if not yet.
QDir dir(QETApp::configDir()+ "/element_texts_pattern");
if(!dir.exists())
{
dir.cdUp();
dir.mkdir("element_texts_pattern");
dir.cd("element_texts_pattern");
}
//Get the name of conf
bool ok;
m_name = getName(ok);
if(ok == false)
return;
//Get the name of conf
bool ok;
m_name = getName(ok);
if(ok == false)
return;
//Check if a conf with the same name already exist
if (QFileInfo::exists(dir.absoluteFilePath(m_name + ".xml")))
{
bool r = QMessageBox::question(parentWidget(),
QObject::tr("Configuration de textes"),
QObject::tr("Une configuration de textes nommée << %1 >> existe déjà.\n"
"Voulez-vous la remplacer ?").arg(m_name));
//Check if a conf with the same name already exist
if (QFileInfo::exists(dir.absoluteFilePath(m_name + ".xml")))
{
bool r = QMessageBox::question(parentWidget(),
QObject::tr("Configuration de textes"),
QObject::tr("Une configuration de textes nommée << %1 >> existe déjà.\n"
"Voulez-vous la remplacer ?").arg(m_name));
if(r == false)
return;
}
if(r == false)
return;
}
QDomDocument doc = xmlConf();
QET::writeXmlFile(doc, dir.absoluteFilePath(m_name + ".xml"));
QDomDocument doc = xmlConf();
QET::writeXmlFile(doc, dir.absoluteFilePath(m_name + ".xml"));
}
/**
@brief ExportElementTextConf::getName
Open a dialog to let user set the name of the conf and return it
@return
@brief ExportElementTextConf::getName
Open a dialog to let user set the name of the conf and return it
@return
*/
QString ExportElementTextPattern::getName(bool &ok) const
{
QString text = QInputDialog::getText(parentWidget(),
QObject::tr("Nom de la configuration"),
QObject::tr("Entrer le nom de la configuration à créer"),
QLineEdit::Normal,
QString(),
&ok);
QString text = QInputDialog::getText(parentWidget(),
QObject::tr("Nom de la configuration"),
QObject::tr("Entrer le nom de la configuration à créer"),
QLineEdit::Normal,
QString(),
&ok);
text.replace(" ", "_");
text.replace(".","");
return text;
text.replace(" ", "_");
text.replace(".","");
return text;
}
QWidget *ExportElementTextPattern::parentWidget() const
{
QWidget *parent = nullptr;
if(m_element->scene() && !m_element->scene()->views().isEmpty())
parent = m_element->scene()->views().first();
QWidget *parent = nullptr;
if(m_element->scene() && !m_element->scene()->views().isEmpty())
parent = m_element->scene()->views().first();
return parent;
return parent;
}
QDomDocument ExportElementTextPattern::xmlConf() const
{
QDomDocument doc;
QDomElement root = doc.createElement("Element_texts_pattern");
root.setAttribute("name", m_name);
doc.appendChild(root);
QDomDocument doc;
QDomElement root = doc.createElement("Element_texts_pattern");
root.setAttribute("name", m_name);
doc.appendChild(root);
QDomElement elmt = m_element->toXml(doc);
QDomElement texts = elmt.firstChildElement("dynamic_texts");
QDomElement groups = elmt.firstChildElement("texts_groups");
QDomElement elmt = m_element->toXml(doc);
QDomElement texts = elmt.firstChildElement("dynamic_texts");
QDomElement groups = elmt.firstChildElement("texts_groups");
if(texts.tagName() == "dynamic_texts")
root.appendChild(texts);
if(groups.tagName() == "texts_groups")
root.appendChild(groups);
if(texts.tagName() == "dynamic_texts")
root.appendChild(texts);
if(groups.tagName() == "texts_groups")
root.appendChild(groups);
return doc;
return doc;
}
//*******************//
//******IMPORT*******//
//*******************//
ImportElementTextPattern::ImportElementTextPattern(Element *elmt):
m_element(elmt)
m_element(elmt)
{
bool exist = true;
QDir dir(QETApp::configDir()+ "/element_texts_pattern");
bool exist = true;
QDir dir(QETApp::configDir()+ "/element_texts_pattern");
if(!dir.exists())
exist = false;
if(!dir.exists())
exist = false;
QStringList entry = dir.entryList(QDir::Files | QDir::NoDotAndDotDot);
QStringList result = entry.filter(".xml");
if(result.isEmpty())
exist = false;
QStringList entry = dir.entryList(QDir::Files | QDir::NoDotAndDotDot);
QStringList result = entry.filter(".xml");
if(result.isEmpty())
exist = false;
if(!exist)
{
QMessageBox::information(
parentWidget(),
QObject::tr("Configuration de textes"),
QObject::tr("Aucune configuration de textes existante."));
return;
}
if(!exist)
{
QMessageBox::information(
parentWidget(),
QObject::tr("Configuration de textes"),
QObject::tr("Aucune configuration de textes existante."));
return;
}
bool ok=false;
bool erase = false;
//Remove the .xml extention of the files
result.replaceInStrings(".xml", "");
QString name = getName(result, &ok, &erase);
bool ok=false;
bool erase = false;
//Remove the .xml extention of the files
result.replaceInStrings(".xml", "");
QString name = getName(result, &ok, &erase);
if(!ok || name.isEmpty())
return;
else
apply(name, erase);
if(!ok || name.isEmpty())
return;
else
apply(name, erase);
}
/**
@brief ImportElementTextPattern::getName
Open a dialog to let user select a conf
@param list
@param ok
@param erase
@return
@brief ImportElementTextPattern::getName
Open a dialog to let user select a conf
@param list
@param ok
@param erase
@return
*/
QString ImportElementTextPattern::getName(const QStringList& list,
bool *ok,
bool *erase) const
bool *ok,
bool *erase) const
{
return ImportElementTextPatternDialog::getItem(
parentWidget(),
QObject::tr("Sélectionner une configuration de textes"),
QObject::tr("Sélectionner la configuration de textes à ajouter à l'élément"),
list,
ok,
erase);
return ImportElementTextPatternDialog::getItem(
parentWidget(),
QObject::tr("Sélectionner une configuration de textes"),
QObject::tr("Sélectionner la configuration de textes à ajouter à l'élément"),
list,
ok,
erase);
}
QWidget *ImportElementTextPattern::parentWidget() const
{
QWidget *parent = nullptr;
if(m_element->scene() && !m_element->scene()->views().isEmpty())
parent = m_element->scene()->views().first();
QWidget *parent = nullptr;
if(m_element->scene() && !m_element->scene()->views().isEmpty())
parent = m_element->scene()->views().first();
return parent;
return parent;
}
/**
@brief ImportElementTextPattern::apply
Apply the user choice
@param name : the name of the selected pattern
@param erase : erase the existing texts and groups of element.
@brief ImportElementTextPattern::apply
Apply the user choice
@param name : the name of the selected pattern
@param erase : erase the existing texts and groups of element.
*/
void ImportElementTextPattern::apply(QString name, bool erase) const
{
if(!name.endsWith(".xml"))
name.append(".xml");
if(!name.endsWith(".xml"))
name.append(".xml");
QFile conf_file(QETApp::configDir() + "/element_texts_pattern/" + name);
if(!conf_file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QFile conf_file(QETApp::configDir() + "/element_texts_pattern/" + name);
if(!conf_file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
//Load the content of the xml file
QDomDocument xml_conf;
if(!xml_conf.setContent(&conf_file))
return;
//Load the content of the xml file
QDomDocument xml_conf;
if(!xml_conf.setContent(&conf_file))
return;
QDomElement root = xml_conf.firstChildElement("Element_texts_pattern");
QDomElement root = xml_conf.firstChildElement("Element_texts_pattern");
//Get the text
QList <QDomElement> texts = QET::findInDomElement(root, "dynamic_texts", "dynamic_elmt_text");
if (texts.isEmpty())
return;
//Get the text
QList <QDomElement> texts = QET::findInDomElement(root, "dynamic_texts", "dynamic_elmt_text");
if (texts.isEmpty())
return;
//Replace the original uuid of texts in the xml description, by a new one for every texts
QHash<QUuid, QUuid> uuid_hash;
for(QDomElement text : texts)
{
QUuid original_uuid(text.attribute("uuid"));
QUuid new_uuid = QUuid::createUuid();
text.setAttribute("uuid", new_uuid.toString());
//Replace the original uuid of texts in the xml description, by a new one for every texts
QHash<QUuid, QUuid> uuid_hash;
for(QDomElement text : texts)
{
QUuid original_uuid(text.attribute("uuid"));
QUuid new_uuid = QUuid::createUuid();
text.setAttribute("uuid", new_uuid.toString());
uuid_hash.insert(original_uuid, new_uuid);
}
uuid_hash.insert(original_uuid, new_uuid);
}
//In each group of the xml description, replace the original uuids, by the news created upper.
QList <QDomElement> groups = QET::findInDomElement(root, "texts_groups", "texts_group");
for(const QDomElement& group : groups)
{
for(QDomElement text : QET::findInDomElement(group, "texts", "text"))
{
QUuid original_uuid(text.attribute("uuid"));
QUuid new_uuid = uuid_hash.value(original_uuid);
if(!new_uuid.isNull())
text.setAttribute("uuid", new_uuid.toString());
}
}
//In each group of the xml description, replace the original uuids, by the news created upper.
QList <QDomElement> groups = QET::findInDomElement(root, "texts_groups", "texts_group");
for(const QDomElement& group : groups)
{
for(QDomElement text : QET::findInDomElement(group, "texts", "text"))
{
QUuid original_uuid(text.attribute("uuid"));
QUuid new_uuid = uuid_hash.value(original_uuid);
if(!new_uuid.isNull())
text.setAttribute("uuid", new_uuid.toString());
}
}
QUndoStack &undo_stack = m_element->diagram()->undoStack();
undo_stack.beginMacro(QObject::tr("Importer la configuration de texte : %1").arg(name.remove(".xml")));
QUndoStack &undo_stack = m_element->diagram()->undoStack();
undo_stack.beginMacro(QObject::tr("Importer la configuration de texte : %1").arg(name.remove(".xml")));
//erase existing texts and groups
if (erase)
{
for (ElementTextItemGroup *group : m_element->textGroups()) {
undo_stack.push(new RemoveTextsGroupCommand(m_element, group));
}
for (DynamicElementTextItem *deti : m_element->dynamicTextItems())
{
DiagramContent dc;
dc.m_element_texts << deti;
undo_stack.push(new DeleteQGraphicsItemCommand(m_element->diagram(), dc));
}
}
//erase existing texts and groups
if (erase)
{
for (ElementTextItemGroup *group : m_element->textGroups()) {
undo_stack.push(new RemoveTextsGroupCommand(m_element, group));
}
for (DynamicElementTextItem *deti : m_element->dynamicTextItems())
{
DiagramContent dc;
dc.m_element_texts << deti;
undo_stack.push(new DeleteQGraphicsItemCommand(m_element->diagram(), dc));
}
}
//Add the texts to element
for(const QDomElement& text : texts)
{
DynamicElementTextItem *deti = new DynamicElementTextItem(m_element);
undo_stack.push(new AddElementTextCommand(m_element, deti));
deti->fromXml(text);
}
//Add the groups to element
for(const QDomElement& xml_group : groups)
undo_stack.push(new AddTextsGroupCommand(m_element, xml_group));
//Add the texts to element
for(const QDomElement& text : texts)
{
DynamicElementTextItem *deti = new DynamicElementTextItem(m_element);
undo_stack.push(new AddElementTextCommand(m_element, deti));
deti->fromXml(text);
}
//Add the groups to element
for(const QDomElement& xml_group : groups)
undo_stack.push(new AddTextsGroupCommand(m_element, xml_group));
undo_stack.endMacro();
undo_stack.endMacro();
}

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#include "propertiesinterface.h"
@@ -21,99 +21,99 @@
* Available property types
*/
namespace {
const QString integerS = "int";
const QString doubleS = "double";
const QString boolS = "bool";
const QString stringS = "string";
const QString uuidS = "uuid";
const QString colorS = "color";
const QString integerS = "int";
const QString doubleS = "double";
const QString boolS = "bool";
const QString stringS = "string";
const QString uuidS = "uuid";
const QString colorS = "color";
}
/**
@brief PropertiesInterface::PropertiesInterface
@brief PropertiesInterface::PropertiesInterface
*/
PropertiesInterface::PropertiesInterface()
{
}
/**
@brief PropertiesInterface::~PropertiesInterface
@brief PropertiesInterface::~PropertiesInterface
*/
PropertiesInterface::~PropertiesInterface()
{
}
bool PropertiesInterface::valideXml(QDomElement& element) {
qDebug(QString("ValideXml() is not implemented. File: %1, Line: %2").arg(__FILE__).arg(__LINE__).toStdString().data());
return false;
qDebug(QString("ValideXml() is not implemented. File: %1, Line: %2").arg(__FILE__).arg(__LINE__).toStdString().data());
return false;
}
QDomElement PropertiesInterface::createXmlProperty(QDomDocument &doc, const QString& name, const QString value) {
QDomElement p = doc.createElement("property");
p.setAttribute("name", name);
p.setAttribute("type", stringS);
p.setAttribute("value", value);
return p;
QDomElement p = doc.createElement("property");
p.setAttribute("name", name);
p.setAttribute("type", stringS);
p.setAttribute("value", value);
return p;
}
QDomElement PropertiesInterface::createXmlProperty(QDomDocument &doc, const QString& name, const char* value) {
QDomElement p = doc.createElement("property");
p.setAttribute("name", name);
p.setAttribute("type", stringS);
p.setAttribute("value", value);
return p;
QDomElement p = doc.createElement("property");
p.setAttribute("name", name);
p.setAttribute("type", stringS);
p.setAttribute("value", value);
return p;
}
QDomElement PropertiesInterface::createXmlProperty(QDomDocument& doc, const QString& name, const int value) {
QDomElement p = doc.createElement("property");
p.setAttribute("name", name);
p.setAttribute("type", integerS);
p.setAttribute("value", QString::number(value));
return p;
QDomElement p = doc.createElement("property");
p.setAttribute("name", name);
p.setAttribute("type", integerS);
p.setAttribute("value", QString::number(value));
return p;
}
QDomElement PropertiesInterface::createXmlProperty(QDomDocument& doc, const QString& name, const double value) {
QDomElement p = doc.createElement("property");
p.setAttribute("name", name);
p.setAttribute("type", doubleS);
p.setAttribute("value", QString::number(value));
return p;
QDomElement p = doc.createElement("property");
p.setAttribute("name", name);
p.setAttribute("type", doubleS);
p.setAttribute("value", QString::number(value));
return p;
}
QDomElement PropertiesInterface::createXmlProperty(QDomDocument& doc, const QString& name, const bool value) {
QDomElement p = doc.createElement("property");
p.setAttribute("name", name);
p.setAttribute("type", boolS);
p.setAttribute("value", QString::number(value));
return p;
QDomElement p = doc.createElement("property");
p.setAttribute("name", name);
p.setAttribute("type", boolS);
p.setAttribute("value", QString::number(value));
return p;
}
QDomElement PropertiesInterface::createXmlProperty(QDomDocument& doc, const QString& name, const QUuid value) {
QDomElement p = doc.createElement("property");
p.setAttribute("name", name);
p.setAttribute("type", uuidS);
p.setAttribute("value", value.toString());
return p;
QDomElement p = doc.createElement("property");
p.setAttribute("name", name);
p.setAttribute("type", uuidS);
p.setAttribute("value", value.toString());
return p;
}
QDomElement PropertiesInterface::createXmlProperty(QDomDocument& doc, const QString& name, const QColor value) {
QDomElement p = doc.createElement("property");
p.setAttribute("name", name);
p.setAttribute("type", colorS);
p.setAttribute("value", value.name());
return p;
QDomElement p = doc.createElement("property");
p.setAttribute("name", name);
p.setAttribute("type", colorS);
p.setAttribute("value", value.name());
return p;
}
QDomElement PropertiesInterface::property(const QDomElement& e, const QString& name) {
for (int i=0; i < e.childNodes().count(); i++) {
QDomElement child = e.childNodes().at(i).toElement();
if (!validXmlProperty(child))
continue; // there might also non property childs
for (int i=0; i < e.childNodes().count(); i++) {
QDomElement child = e.childNodes().at(i).toElement();
if (!validXmlProperty(child))
continue; // there might also non property childs
if (child.attribute("name") == name)
return child;
}
return QDomElement();
if (child.attribute("name") == name)
return child;
}
return QDomElement();
}
/*!
@@ -126,27 +126,27 @@ QDomElement PropertiesInterface::property(const QDomElement& e, const QString& n
* \return
*/
bool PropertiesInterface::attribute(const QDomElement& e, const QString& attribute_name, const QString& type, QString* attr) {
QDomElement p = property(e, attribute_name);
if (p.isNull()) {
// check if legacy property is available,
// where the property is inside the element as attribute
if (!e.hasAttribute(attribute_name)) {
qDebug() << "\t\t\t" << "Tagname: " << e.tagName() << ". " << "Property " << attribute_name << "is not available";
return false;
}
QDomElement p = property(e, attribute_name);
if (p.isNull()) {
// check if legacy property is available,
// where the property is inside the element as attribute
if (!e.hasAttribute(attribute_name)) {
qDebug() << "\t\t\t" << "Tagname: " << e.tagName() << ". " << "Property " << attribute_name << "is not available";
return false;
}
*attr = e.attribute(attribute_name);
*attr = e.attribute(attribute_name);
} else {
if (p.attribute("type") != type) {
qDebug() << "\t\t\t" << "Tagname: " << e.tagName() << ", Property: " << attribute_name << "(" << p.attribute("type") << ") has not type: " << type;
return false;
}
} else {
if (p.attribute("type") != type) {
qDebug() << "\t\t\t" << "Tagname: " << e.tagName() << ", Property: " << attribute_name << "(" << p.attribute("type") << ") has not type: " << type;
return false;
}
*attr = p.attribute("value");
*attr = p.attribute("value");
}
return true;
}
return true;
}
/*!
@@ -156,132 +156,132 @@ bool PropertiesInterface::attribute(const QDomElement& e, const QString& attribu
* \param attribute_name Name of the attribute
* \param entier Return value if success
* \return True if reading an integer was successful, else False. If the attribute was not found,
* \p entier is not valid and the return value is False
* \p entier is not valid and the return value is False
*/
PropertiesInterface::PropertyFlags PropertiesInterface::propertyInteger(const QDomElement &e, const QString& attribute_name, int* entier) {
QString attr;
QString attr;
if (!attribute(e, attribute_name, integerS, &attr)) {
return PropertyFlags::NotFound;
}
if (!attribute(e, attribute_name, integerS, &attr)) {
return PropertyFlags::NotFound;
}
// verifie la validite de l'attribut
bool ok;
int tmp = attr.toInt(&ok);
if (!ok) {
qDebug() << "\t\t\t" << "Tagname: " << e.tagName() << ". " << "No valid Conversion: " << attribute_name << ". type: " << integerS << ". value: " << attr;
return PropertyFlags::NoValidConversion;
}
// verifie la validite de l'attribut
bool ok;
int tmp = attr.toInt(&ok);
if (!ok) {
qDebug() << "\t\t\t" << "Tagname: " << e.tagName() << ". " << "No valid Conversion: " << attribute_name << ". type: " << integerS << ". value: " << attr;
return PropertyFlags::NoValidConversion;
}
if (entier != nullptr)
*entier = tmp;
if (entier != nullptr)
*entier = tmp;
return PropertyFlags::Success;
return PropertyFlags::Success;
}
PropertiesInterface::PropertyFlags PropertiesInterface::propertyDouble(const QDomElement &e, const QString& attribute_name, double* reel) {
QString attr;
QString attr;
if (!attribute(e, attribute_name, doubleS, &attr)) {
return PropertyFlags::NotFound;
}
if (!attribute(e, attribute_name, doubleS, &attr)) {
return PropertyFlags::NotFound;
}
// verifie la validite de l'attribut
bool ok;
double tmp = attr.toDouble(&ok);
if (!ok) {
qDebug() << "\t\t\t" << "Tagname: " << e.tagName() << ". " << "No valid Conversion: " << attribute_name << ". type: " << doubleS << ". value: " << attr;
return PropertyFlags::NoValidConversion;
}
// verifie la validite de l'attribut
bool ok;
double tmp = attr.toDouble(&ok);
if (!ok) {
qDebug() << "\t\t\t" << "Tagname: " << e.tagName() << ". " << "No valid Conversion: " << attribute_name << ". type: " << doubleS << ". value: " << attr;
return PropertyFlags::NoValidConversion;
}
if (reel != nullptr)
*reel = tmp;
if (reel != nullptr)
*reel = tmp;
return PropertyFlags::Success;
return PropertyFlags::Success;
}
PropertiesInterface::PropertyFlags PropertiesInterface::propertyBool(const QDomElement &e, const QString& attribute_name, bool* boolean) {
QString attr;
QString attr;
if (!attribute(e, attribute_name, boolS, &attr)) {
return PropertyFlags::NotFound;
}
if (!attribute(e, attribute_name, boolS, &attr)) {
return PropertyFlags::NotFound;
}
// verifie la validite de l'attribut
bool ok;
bool tmp = attr.toInt(&ok);
if (!ok) {
if (attr == "true" || attr == "1")
tmp = true;
else if (attr == "false" || attr == "0")
tmp = false;
else {
qDebug() << "\t\t\t" << "Tagname: " << e.tagName() << ". " << "No valid Conversion: " << attribute_name << ". type: " << integerS << ". value: " << attr;
return PropertyFlags::NoValidConversion;
}
}
// verifie la validite de l'attribut
bool ok;
bool tmp = attr.toInt(&ok);
if (!ok) {
if (attr == "true" || attr == "1")
tmp = true;
else if (attr == "false" || attr == "0")
tmp = false;
else {
qDebug() << "\t\t\t" << "Tagname: " << e.tagName() << ". " << "No valid Conversion: " << attribute_name << ". type: " << integerS << ". value: " << attr;
return PropertyFlags::NoValidConversion;
}
}
if (boolean != nullptr)
*boolean = tmp;
if (boolean != nullptr)
*boolean = tmp;
return PropertyFlags::Success;
return PropertyFlags::Success;
}
PropertiesInterface::PropertyFlags PropertiesInterface::propertyColor(const QDomElement &e, const QString& attribute_name, QColor* color) {
QString attr;
QString attr;
if (!attribute(e, attribute_name, colorS, &attr)) {
return PropertyFlags::NotFound;
}
if (!attribute(e, attribute_name, colorS, &attr)) {
return PropertyFlags::NotFound;
}
// verifie la validite de l'attribut
QColor tmp = QColor(attr);
if (!tmp.isValid()) {
qDebug() << "\t\t\t" << "Tagname: " << e.tagName() << ". " << "No valid Conversion: " << attribute_name << ". type: " << colorS << ". value: " << attr;
return PropertyFlags::NoValidConversion;
}
// verifie la validite de l'attribut
QColor tmp = QColor(attr);
if (!tmp.isValid()) {
qDebug() << "\t\t\t" << "Tagname: " << e.tagName() << ". " << "No valid Conversion: " << attribute_name << ". type: " << colorS << ". value: " << attr;
return PropertyFlags::NoValidConversion;
}
if (color != nullptr)
*color = tmp;
if (color != nullptr)
*color = tmp;
return PropertyFlags::Success;
return PropertyFlags::Success;
}
PropertiesInterface::PropertyFlags PropertiesInterface::propertyUuid(const QDomElement &e, const QString& attribute_name, QUuid* uuid) {
QString attr;
QString attr;
if (!attribute(e, attribute_name, uuidS, &attr)) {
return PropertyFlags::NotFound;
}
if (!attribute(e, attribute_name, uuidS, &attr)) {
return PropertyFlags::NotFound;
}
if (QUuid(attr).isNull()){
qDebug() << "\t\t\t" << "Tagname: " << e.tagName() << ". " << "No valid Conversion: " << attribute_name << ". type: " << uuidS << ". value: " << attr;
return PropertyFlags::NoValidConversion;
}
if (QUuid(attr).isNull()){
qDebug() << "\t\t\t" << "Tagname: " << e.tagName() << ". " << "No valid Conversion: " << attribute_name << ". type: " << uuidS << ". value: " << attr;
return PropertyFlags::NoValidConversion;
}
if (uuid != nullptr)
*uuid = QUuid(attr);
if (uuid != nullptr)
*uuid = QUuid(attr);
return PropertyFlags::Success;
return PropertyFlags::Success;
}
PropertiesInterface::PropertyFlags PropertiesInterface::propertyString(const QDomElement& e, const QString& attribute_name, QString* string) {
QString attr;
if (!attribute(e, attribute_name, stringS, &attr)) {
return PropertyFlags::NotFound;
}
QString attr;
if (!attribute(e, attribute_name, stringS, &attr)) {
return PropertyFlags::NotFound;
}
// verifie la validite de l'attribut
if (string != nullptr)
*string = attr;
// verifie la validite de l'attribut
if (string != nullptr)
*string = attr;
return PropertyFlags::Success;
return PropertyFlags::Success;
}
/*!
@@ -291,47 +291,47 @@ PropertiesInterface::PropertyFlags PropertiesInterface::propertyString(const QDo
* \return True if name, type, value attribute are available, else false
*/
bool PropertiesInterface::validXmlProperty(const QDomElement& e) {
if (!e.hasAttribute("name"))
return false;
if (!e.hasAttribute("name"))
return false;
if (!e.hasAttribute("type"))
return false;
if (!e.hasAttribute("type"))
return false;
if (!e.hasAttribute("value"))
return false;
if (!e.hasAttribute("value"))
return false;
return true;
return true;
}
/**
Permet de convertir une chaine de caracteres ("n", "s", "e" ou "w")
en orientation. Si la chaine fait plusieurs caracteres, seul le
premier est pris en compte. En cas d'incoherence, Qet::North est
retourne.
@param s Chaine de caractere cense representer une orientation
@return l'orientation designee par la chaine de caractere
Permet de convertir une chaine de caracteres ("n", "s", "e" ou "w")
en orientation. Si la chaine fait plusieurs caracteres, seul le
premier est pris en compte. En cas d'incoherence, Qet::North est
retourne.
@param s Chaine de caractere cense representer une orientation
@return l'orientation designee par la chaine de caractere
*/
Qet::Orientation PropertiesInterface::orientationFromString(const QString &s) {
QChar c = s[0];
// in some cases/ old projects? (affuteuse_250h.qet) numbers instead of characters are
// used for the orientation
if (c == 'e' || c == '1') return(Qet::East);
else if (c == 's' || c == '2') return(Qet::South);
else if (c == 'w' || c == '3') return (Qet::West);
else return(Qet::North); // c == '0'
QChar c = s[0];
// in some cases/ old projects? (affuteuse_250h.qet) numbers instead of characters are
// used for the orientation
if (c == 'e' || c == '1') return(Qet::East);
else if (c == 's' || c == '2') return(Qet::South);
else if (c == 'w' || c == '3') return (Qet::West);
else return(Qet::North); // c == '0'
}
/**
@param o une orientation
@return une chaine de caractere representant l'orientation
@param o une orientation
@return une chaine de caractere representant l'orientation
*/
QString PropertiesInterface::orientationToString(Qet::Orientation o) {
QString ret;
switch(o) {
case Qet::North: ret = "n"; break;
case Qet::East : ret = "e"; break;
case Qet::South: ret = "s"; break;
case Qet::West : ret = "w"; break;
}
return(ret);
QString ret;
switch(o) {
case Qet::North: ret = "n"; break;
case Qet::East : ret = "e"; break;
case Qet::South: ret = "s"; break;
case Qet::West : ret = "w"; break;
}
return(ret);
}

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PROPERTIESINTERFACE_H
#define PROPERTIESINTERFACE_H
@@ -27,100 +27,100 @@
#include <QUuid>
/**
@brief The PropertiesInterface class
This class is an interface for have common way
to use properties in QElectroTech
@brief The PropertiesInterface class
This class is an interface for have common way
to use properties in QElectroTech
*/
class PropertiesInterface
{
public:
PropertiesInterface();
virtual ~PropertiesInterface();
/**
@brief toSettings
Save properties to setting file.
@param settings : is use for prefix a word
befor the name of each paramètre
@param QString
*/
virtual void toSettings (QSettings &settings,
const QString = QString()) const =0;
/**
@brief fromSettings
load properties to setting file.
@param settings : is use for prefix a word
befor the name of each paramètre
@param QString
*/
virtual void fromSettings (const QSettings &settings,
const QString = QString()) =0;
/**
@brief toXml
Save properties to xml element
@param xml_document
@return QDomElement
*/
virtual QDomElement toXml (QDomDocument &xml_document) const =0;
/**
@brief fromXml
load properties to xml element
@param xml_element
@return true / false
*/
virtual bool fromXml (const QDomElement &xml_element) =0;
static bool valideXml(QDomElement& element);
public:
PropertiesInterface();
virtual ~PropertiesInterface();
/**
@brief toSettings
Save properties to setting file.
@param settings : is use for prefix a word
befor the name of each paramètre
@param QString
*/
virtual void toSettings (QSettings &settings,
const QString = QString()) const =0;
/**
@brief fromSettings
load properties to setting file.
@param settings : is use for prefix a word
befor the name of each paramètre
@param QString
*/
virtual void fromSettings (const QSettings &settings,
const QString = QString()) =0;
/**
@brief toXml
Save properties to xml element
@param xml_document
@return QDomElement
*/
virtual QDomElement toXml (QDomDocument &xml_document) const =0;
/**
@brief fromXml
load properties to xml element
@param xml_element
@return true / false
*/
virtual bool fromXml (const QDomElement &xml_element) =0;
static bool valideXml(QDomElement& element);
/*!
* Use this functions to add properties to the xml document
*/
static QDomElement createXmlProperty(QDomDocument& doc, const QString& name, const QString value);
static QDomElement createXmlProperty(QDomDocument &doc, const QString& name, const char* value);
static QDomElement createXmlProperty(QDomDocument& doc, const QString& name, const int value);
static QDomElement createXmlProperty(QDomDocument& doc, const QString& name, const double value);
static QDomElement createXmlProperty(QDomDocument& doc, const QString& name, const bool value);
static QDomElement createXmlProperty(QDomDocument& doc, const QString& name, const QUuid value);
static QDomElement createXmlProperty(QDomDocument& doc, const QString& name, const QColor value);
/*!
* Use this functions to add properties to the xml document
*/
static QDomElement createXmlProperty(QDomDocument& doc, const QString& name, const QString value);
static QDomElement createXmlProperty(QDomDocument &doc, const QString& name, const char* value);
static QDomElement createXmlProperty(QDomDocument& doc, const QString& name, const int value);
static QDomElement createXmlProperty(QDomDocument& doc, const QString& name, const double value);
static QDomElement createXmlProperty(QDomDocument& doc, const QString& name, const bool value);
static QDomElement createXmlProperty(QDomDocument& doc, const QString& name, const QUuid value);
static QDomElement createXmlProperty(QDomDocument& doc, const QString& name, const QColor value);
static QDomElement property(const QDomElement& e, const QString& name);
static bool attribute(const QDomElement& e, const QString& attribute_name, const QString& type, QString* attr);
static QDomElement property(const QDomElement& e, const QString& name);
static bool attribute(const QDomElement& e, const QString& attribute_name, const QString& type, QString* attr);
enum PropertyFlags {
Success = 0,
NotFound = 1,
NoValidConversion = 2,
// = 4
};
enum PropertyFlags {
Success = 0,
NotFound = 1,
NoValidConversion = 2,
// = 4
};
/*!
* Try not using the default Value feature. It is better to initialize the class members in the class definition!
*/
static PropertyFlags propertyInteger(const QDomElement &e, const QString& attribute_name, int *entier = nullptr);
static PropertyFlags propertyDouble(const QDomElement &e, const QString& attribute_name, double *reel = nullptr);
static PropertyFlags propertyString(const QDomElement& e, const QString& attribute_name, QString* string = nullptr);
static PropertyFlags propertyBool(const QDomElement &e, const QString& attribute_name, bool* boolean = nullptr);
static PropertyFlags propertyUuid(const QDomElement &e, const QString& attribute_name, QUuid* uuid = nullptr);
static PropertyFlags propertyColor(const QDomElement &e, const QString& attribute_name, QColor* color = nullptr);
/*!
* Try not using the default Value feature. It is better to initialize the class members in the class definition!
*/
static PropertyFlags propertyInteger(const QDomElement &e, const QString& attribute_name, int *entier = nullptr);
static PropertyFlags propertyDouble(const QDomElement &e, const QString& attribute_name, double *reel = nullptr);
static PropertyFlags propertyString(const QDomElement& e, const QString& attribute_name, QString* string = nullptr);
static PropertyFlags propertyBool(const QDomElement &e, const QString& attribute_name, bool* boolean = nullptr);
static PropertyFlags propertyUuid(const QDomElement &e, const QString& attribute_name, QUuid* uuid = nullptr);
static PropertyFlags propertyColor(const QDomElement &e, const QString& attribute_name, QColor* color = nullptr);
static bool validXmlProperty(const QDomElement& e);
static bool validXmlProperty(const QDomElement& e);
QVariant XmlProperty(const QDomElement& element);
QVariant XmlProperty(const QDomElement& element);
/**
Permet de convertir une chaine de caracteres ("n", "s", "e" ou "w")
en orientation. Si la chaine fait plusieurs caracteres, seul le
premier est pris en compte. En cas d'incoherence, Qet::North est
retourne.
@param s Chaine de caractere cense representer une orientation
@return l'orientation designee par la chaine de caractere
*/
static Qet::Orientation orientationFromString(const QString &s);
/**
Permet de convertir une chaine de caracteres ("n", "s", "e" ou "w")
en orientation. Si la chaine fait plusieurs caracteres, seul le
premier est pris en compte. En cas d'incoherence, Qet::North est
retourne.
@param s Chaine de caractere cense representer une orientation
@return l'orientation designee par la chaine de caractere
*/
static Qet::Orientation orientationFromString(const QString &s);
/**
@param o une orientation
@return une chaine de caractere representant l'orientation
*/
static QString orientationToString(Qet::Orientation o);
/**
@param o une orientation
@return une chaine de caractere representant l'orientation
*/
static QString orientationToString(Qet::Orientation o);
};
#endif // PROPERTIESINTERFACE_H

View File

@@ -3,16 +3,16 @@
#include <QGraphicsObject>
TerminalData::TerminalData():
PropertiesInterface()
PropertiesInterface()
{
init();
init();
}
TerminalData::TerminalData(QGraphicsObject *parent):
PropertiesInterface(),
q(parent)
PropertiesInterface(),
q(parent)
{
init();
init();
}
void TerminalData::init()
@@ -25,135 +25,135 @@ TerminalData::~TerminalData()
}
/**
@brief TerminalData::setParent
@param parent
@brief TerminalData::setParent
@param parent
*/
void TerminalData::setParent(QGraphicsObject* parent)
{
q = parent;
q = parent;
}
/**
@brief TerminalData::toSettings
Save properties to setting file.
@brief TerminalData::toSettings
Save properties to setting file.
QString is use for prefix a word befor the name of each paramètre
@param settings UNUSED
@param prefix UNUSED
QString is use for prefix a word befor the name of each paramètre
@param settings UNUSED
@param prefix UNUSED
*/
void TerminalData::toSettings(QSettings &settings, const QString prefix) const
{
Q_UNUSED(settings);
Q_UNUSED(prefix);
Q_UNUSED(settings);
Q_UNUSED(prefix);
}
/**
@brief TerminalData::fromSettings
load properties to setting file.
@brief TerminalData::fromSettings
load properties to setting file.
QString is use for prefix a word befor the name of each paramètre
@param settings UNUSED
@param prefix UNUSED
QString is use for prefix a word befor the name of each paramètre
@param settings UNUSED
@param prefix UNUSED
*/
void TerminalData::fromSettings(const QSettings &settings, const QString prefix)
{
Q_UNUSED(settings);
Q_UNUSED(prefix);
Q_UNUSED(settings);
Q_UNUSED(prefix);
}
/**
@brief TerminalData::toXml
Save properties to xml element
write the name, number, position and orientation of the terminal
to xml_element
@brief TerminalData::toXml
Save properties to xml element
write the name, number, position and orientation of the terminal
to xml_element
@note This method is only called from the PartTerminal
and should never called from the Terminal class
@param xml_document
@return xml_element : DomElement with
the name, number, position and orientation of the terminal
@note This method is only called from the PartTerminal
and should never called from the Terminal class
@param xml_document
@return xml_element : DomElement with
the name, number, position and orientation of the terminal
*/
QDomElement TerminalData::toXml(QDomDocument &xml_document) const
{
QDomElement xml_element = xml_document.createElement("terminaldata");
QDomElement xml_element = xml_document.createElement("terminaldata");
// write the position of the terminal
// Write name and number to XML
// m_pos cannot be stored, because in the partterminal it will not be updated.
// In PartTerminal m_pos is the position of the dock, in Terminal m_pos is the second side of the terminal
// This is hold for legacy compability reason
xml_element.appendChild(createXmlProperty(xml_document, "x", m_pos.x()));
xml_element.appendChild(createXmlProperty(xml_document, "y", m_pos.y()));
xml_element.appendChild(createXmlProperty(xml_document, "name", m_name));
xml_element.appendChild(createXmlProperty(xml_document, "orientation", orientationToString(m_orientation)));
// write the position of the terminal
// Write name and number to XML
// m_pos cannot be stored, because in the partterminal it will not be updated.
// In PartTerminal m_pos is the position of the dock, in Terminal m_pos is the second side of the terminal
// This is hold for legacy compability reason
xml_element.appendChild(createXmlProperty(xml_document, "x", m_pos.x()));
xml_element.appendChild(createXmlProperty(xml_document, "y", m_pos.y()));
xml_element.appendChild(createXmlProperty(xml_document, "name", m_name));
xml_element.appendChild(createXmlProperty(xml_document, "orientation", orientationToString(m_orientation)));
return(xml_element);
return(xml_element);
}
/*
@brief TerminalData::fromXml
load properties to xml element
@brief TerminalData::fromXml
load properties to xml element
@note This method is only called from the PartTerminal
and should never called from the Terminal class
@param xml_element
@return true if succeeded / false if the attribute is not real
@note This method is only called from the PartTerminal
and should never called from the Terminal class
@param xml_element
@return true if succeeded / false if the attribute is not real
*/
bool TerminalData::fromXml (const QDomElement &xml_element) // RETURNS True
{
qreal term_x = 0.0;
qreal term_y = 0.0;
qreal term_x = 0.0;
qreal term_y = 0.0;
// reads the position of the terminal
// lit la position de la borne
// reads the position of the terminal
// lit la position de la borne
if (propertyDouble(xml_element, "x", &term_x))
return false;
if (propertyDouble(xml_element, "x", &term_x))
return false;
if (propertyDouble(xml_element, "y", &term_y))
return false;
if (propertyDouble(xml_element, "y", &term_y))
return false;
m_pos = QPointF(term_x, term_y);
m_pos = QPointF(term_x, term_y);
// emit posFromXML(QPointF(term_x, term_y));
// emit posFromXML(QPointF(term_x, term_y));
// do not write uuid from this class, because only PartTerminal::fromXml need
// to write it to xml file. Terminal::fromXml does not need.
// if the attribute not exists, means, the element is created with an
// older version of qet. So use the legacy approach
// do not write uuid from this class, because only PartTerminal::fromXml need
// to write it to xml file. Terminal::fromXml does not need.
// if the attribute not exists, means, the element is created with an
// older version of qet. So use the legacy approach
//if (propertyString(xml_element, "name", &m_name))
// return false;
propertyString(xml_element, "name", &m_name); // some parts do not have a name. Example: affuteuse_250h.qet, Terminal at x="0" y="-20"
//if (propertyString(xml_element, "name", &m_name))
// return false;
propertyString(xml_element, "name", &m_name); // some parts do not have a name. Example: affuteuse_250h.qet, Terminal at x="0" y="-20"
QString o;
if (propertyString(xml_element, "orientation", &o))
return false;
QString o;
if (propertyString(xml_element, "orientation", &o))
return false;
// read the orientation of the terminal
// lit l'orientation de la borne
m_orientation = Qet::orientationFromString(
xml_element.attribute("orientation"));
return true;
// read the orientation of the terminal
// lit l'orientation de la borne
m_orientation = Qet::orientationFromString(
xml_element.attribute("orientation"));
return true;
}
bool TerminalData::valideXml(const QDomElement& xml_element) {
if (propertyDouble(xml_element, "x"))
return false;
if (propertyDouble(xml_element, "x"))
return false;
if (propertyDouble(xml_element, "y"))
return false;
if (propertyDouble(xml_element, "y"))
return false;
// legacy elements do not have an uuid
// if (propertyUuid(xml_element, "uuid"))
// return false;
// legacy elements do not have an uuid
// if (propertyUuid(xml_element, "uuid"))
// return false;
//if (propertyString(xml_element, "name")) // some parts do not have a name. Example: affuteuse_250h.qet, Terminal at x="0" y="-20"
// return false;
//if (propertyString(xml_element, "name")) // some parts do not have a name. Example: affuteuse_250h.qet, Terminal at x="0" y="-20"
// return false;
if (propertyString(xml_element, "orientation"))
return false;
return true;
if (propertyString(xml_element, "orientation"))
return false;
return true;
}

View File

@@ -10,78 +10,78 @@
class QGraphicsObject;
/**
@brief The TerminalData class
Data of the terminal.
Stored in extra class so it can be used by PartTerminal
and Terminal without defining everything again.
@note tis class needs to be work on
@brief The TerminalData class
Data of the terminal.
Stored in extra class so it can be used by PartTerminal
and Terminal without defining everything again.
@note tis class needs to be work on
*/
class TerminalData : public PropertiesInterface
{
public:
TerminalData();
TerminalData(QGraphicsObject* parent);
~TerminalData();
public:
TerminalData();
TerminalData(QGraphicsObject* parent);
~TerminalData();
void init();
void init();
void setParent(QGraphicsObject* parent);
void toSettings(QSettings &settings,
const QString prefix = QString()) const override;
void toSettings(QSettings &settings, const QString& = QString()) const override;
void fromSettings(const QSettings &settings, const QString& = QString()) override;
QDomElement toXml(QDomDocument &xml_element) const override;
bool fromXml(const QDomElement &xml_element) override;
void setParent(QGraphicsObject* parent);
void toSettings(QSettings &settings,
const QString prefix = QString()) const override;
void toSettings(QSettings &settings, const QString& = QString()) const override;
void fromSettings(const QSettings &settings, const QString& = QString()) override;
QDomElement toXml(QDomDocument &xml_element) const override;
bool fromXml(const QDomElement &xml_element) override;
static bool valideXml(const QDomElement &xml_element);
static bool valideXml(const QDomElement &xml_element);
public:
/**
@brief m_orientation
Orientation of the terminal
*/
Qet::Orientation m_orientation{Qet::Orientation::North};
/**
@brief second_point
Position of the second point of the terminal
in scene coordinates
*/
QPointF second_point{0,0};
/**
@brief m_uuid
Uuid of the terminal.
public:
/**
@brief m_orientation
Orientation of the terminal
*/
Qet::Orientation m_orientation{Qet::Orientation::North};
/**
@brief second_point
Position of the second point of the terminal
in scene coordinates
*/
QPointF second_point{0,0};
/**
@brief m_uuid
Uuid of the terminal.
In elementscene.cpp an element gets a new uuid when
saving the element. In the current state
each connection is made by using the local position
of the terminal and a dynamic id. In the new
case, each terminal should have it's own uuid to
identify it uniquely. When changing each time this
uuid, the conductor after updating the part is anymore
valid. So if in the loaded document a uuid exists,
use this one and don't create a new one.
*/
QUuid m_uuid; // default is an invalid uuid.
/**
@brief m_name
Name of the element.
It can be used to create wiring harness tables
*/
QString m_name;
In elementscene.cpp an element gets a new uuid when
saving the element. In the current state
each connection is made by using the local position
of the terminal and a dynamic id. In the new
case, each terminal should have it's own uuid to
identify it uniquely. When changing each time this
uuid, the conductor after updating the part is anymore
valid. So if in the loaded document a uuid exists,
use this one and don't create a new one.
*/
QUuid m_uuid; // default is an invalid uuid.
/**
@brief m_name
Name of the element.
It can be used to create wiring harness tables
*/
QString m_name;
/**
@brief m_pos
Position of the terminal. The second point is calculated
from this position and the orientation
@note
Important: this variable is only updated during read
from xml and not during mouse move!
It is used to store the initial position so that
PartTerminal and Terminal have access to it.
*/
QPointF m_pos{0,0};
private:
QGraphicsObject* q{nullptr};
/**
@brief m_pos
Position of the terminal. The second point is calculated
from this position and the orientation
@note
Important: this variable is only updated during read
from xml and not during mouse move!
It is used to store the initial position so that
PartTerminal and Terminal have access to it.
*/
QPointF m_pos{0,0};
private:
QGraphicsObject* q{nullptr};
};
#endif // TERMINALDATA_H

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QMetaEnum>
#include <QHash>
@@ -22,176 +22,176 @@
#include "qetapp.h"
/**
@brief XRefProperties::XRefProperties
Default Constructor
@brief XRefProperties::XRefProperties
Default Constructor
*/
XRefProperties::XRefProperties()
{
}
/**
@brief XRefProperties::toSettings
Save to settings
@param settings: QSettings to use
@param prefix: prefix before properties name
@brief XRefProperties::toSettings
Save to settings
@param settings: QSettings to use
@param prefix: prefix before properties name
*/
void XRefProperties::toSettings(QSettings &settings,
const QString prefix) const
const QString prefix) const
{
settings.setValue(prefix + "showpowerctc", m_show_power_ctc);
QString display = m_display == Cross? "cross" : "contacts";
settings.setValue(prefix + "displayhas", display);
QString snap = m_snap_to == Bottom? "bottom" : "label";
settings.setValue(prefix + "snapto", snap);
int offset = m_offset;
settings.setValue(prefix + "offset", offset);
QString master_label = m_master_label;
settings.setValue(prefix + "master_label", master_label);
QString slave_label = m_slave_label;
settings.setValue(prefix + "slave_label", slave_label);
settings.setValue(prefix + "showpowerctc", m_show_power_ctc);
QString display = m_display == Cross? "cross" : "contacts";
settings.setValue(prefix + "displayhas", display);
QString snap = m_snap_to == Bottom? "bottom" : "label";
settings.setValue(prefix + "snapto", snap);
int offset = m_offset;
settings.setValue(prefix + "offset", offset);
QString master_label = m_master_label;
settings.setValue(prefix + "master_label", master_label);
QString slave_label = m_slave_label;
settings.setValue(prefix + "slave_label", slave_label);
QMetaEnum var = QMetaEnum::fromType<Qt::Alignment>();
settings.setValue(prefix + "xrefpos", var.valueToKey(m_xref_pos));
QMetaEnum var = QMetaEnum::fromType<Qt::Alignment>();
settings.setValue(prefix + "xrefpos", var.valueToKey(m_xref_pos));
foreach (QString key, m_prefix.keys()) {
settings.setValue(prefix + key + "prefix", m_prefix.value(key));
}
foreach (QString key, m_prefix.keys()) {
settings.setValue(prefix + key + "prefix", m_prefix.value(key));
}
}
/**
@brief XRefProperties::fromSettings
load from settings
@param settings: QSettings to use
@param prefix: prefix before properties name
@brief XRefProperties::fromSettings
load from settings
@param settings: QSettings to use
@param prefix: prefix before properties name
*/
void XRefProperties::fromSettings(const QSettings &settings,
const QString prefix)
const QString prefix)
{
m_show_power_ctc = settings.value(prefix + "showpowerctc", true).toBool();
QString display = settings.value(prefix + "displayhas", "cross").toString();
display == "cross"? m_display = Cross : m_display = Contacts;
QString snap = settings.value(prefix + "snapto", "label").toString();
snap == "bottom"? m_snap_to = Bottom : m_snap_to = Label;
m_offset = settings.value(prefix + "offset", "0").toInt();
m_master_label = settings.value(prefix + "master_label", "%f-%l%c").toString();
m_slave_label = settings.value(prefix + "slave_label", "(%f-%l%c)").toString();
m_show_power_ctc = settings.value(prefix + "showpowerctc", true).toBool();
QString display = settings.value(prefix + "displayhas", "cross").toString();
display == "cross"? m_display = Cross : m_display = Contacts;
QString snap = settings.value(prefix + "snapto", "label").toString();
snap == "bottom"? m_snap_to = Bottom : m_snap_to = Label;
m_offset = settings.value(prefix + "offset", "0").toInt();
m_master_label = settings.value(prefix + "master_label", "%f-%l%c").toString();
m_slave_label = settings.value(prefix + "slave_label", "(%f-%l%c)").toString();
QMetaEnum var = QMetaEnum::fromType<Qt::Alignment>();
m_xref_pos = Qt::AlignmentFlag(var.keyToValue((settings.value(prefix + "xrefpos").toString()).toStdString().data()));
QMetaEnum var = QMetaEnum::fromType<Qt::Alignment>();
m_xref_pos = Qt::AlignmentFlag(var.keyToValue((settings.value(prefix + "xrefpos").toString()).toStdString().data()));
for (QString key : m_prefix_keys) {
m_prefix.insert(key, settings.value(prefix + key + "prefix").toString());
}
for (QString key : m_prefix_keys) {
m_prefix.insert(key, settings.value(prefix + key + "prefix").toString());
}
}
/**
@brief XRefProperties::toXml
Save to xml
@param xml_document : QDomElement to use for saving
@return QDomElement
@brief XRefProperties::toXml
Save to xml
@param xml_document : QDomElement to use for saving
@return QDomElement
*/
QDomElement XRefProperties::toXml(QDomDocument &xml_document) const
{
QDomElement xml_element = xml_document.createElement("xref");
QDomElement xml_element = xml_document.createElement("xref");
xml_element.appendChild(createXmlProperty(xml_document, "type", m_key));
xml_element.appendChild(createXmlProperty(xml_document, "showpowerctc", m_show_power_ctc));
xml_element.appendChild(createXmlProperty(xml_document, "displayhas", m_display == Cross? "cross" : "contacts"));
xml_element.appendChild(createXmlProperty(xml_document, "snapto", m_snap_to == Bottom? "bottom" : "label"));
xml_element.appendChild(createXmlProperty(xml_document, "type", m_key));
xml_element.appendChild(createXmlProperty(xml_document, "showpowerctc", m_show_power_ctc));
xml_element.appendChild(createXmlProperty(xml_document, "displayhas", m_display == Cross? "cross" : "contacts"));
xml_element.appendChild(createXmlProperty(xml_document, "snapto", m_snap_to == Bottom? "bottom" : "label"));
QMetaEnum var = QMetaEnum::fromType<Qt::Alignment>();
xml_element.appendChild(createXmlProperty(xml_document, "xrefpos", var.valueToKey(m_xref_pos)));
xml_element.appendChild(createXmlProperty(xml_document, "offset", m_offset));
xml_element.appendChild(createXmlProperty(xml_document, "master_label", m_master_label));
xml_element.appendChild(createXmlProperty(xml_document, "slave_label", m_slave_label));
QMetaEnum var = QMetaEnum::fromType<Qt::Alignment>();
xml_element.appendChild(createXmlProperty(xml_document, "xrefpos", var.valueToKey(m_xref_pos)));
xml_element.appendChild(createXmlProperty(xml_document, "offset", m_offset));
xml_element.appendChild(createXmlProperty(xml_document, "master_label", m_master_label));
xml_element.appendChild(createXmlProperty(xml_document, "slave_label", m_slave_label));
foreach (QString key, m_prefix.keys()) {
xml_element.appendChild(createXmlProperty(xml_document, key + "prefix", m_prefix.value(key)));
}
foreach (QString key, m_prefix.keys()) {
xml_element.appendChild(createXmlProperty(xml_document, key + "prefix", m_prefix.value(key)));
}
return xml_element;
return xml_element;
}
/** RETURNS True
@brief XRefProperties::fromXml
Load from xml
@param xml_element: QDomElement to use for load
@brief XRefProperties::fromXml
Load from xml
@param xml_element: QDomElement to use for load
*/
bool XRefProperties::fromXml(const QDomElement &xml_element) {
if (propertyBool(xml_element, "showpowerctc", &m_show_power_ctc))
return false;
if (propertyBool(xml_element, "showpowerctc", &m_show_power_ctc))
return false;
QString display;
if (propertyString(xml_element, "displayhas", &display) != PropertyFlags::NotFound) {
display == "cross"? m_display = Cross : m_display = Contacts;
}
QString display;
if (propertyString(xml_element, "displayhas", &display) != PropertyFlags::NotFound) {
display == "cross"? m_display = Cross : m_display = Contacts;
}
QString snap;
if (propertyString(xml_element, "snapto", &snap) != PropertyFlags::NotFound) {
snap == "bottom"? m_snap_to = Bottom : m_snap_to = Label;
}
QString snap;
if (propertyString(xml_element, "snapto", &snap) != PropertyFlags::NotFound) {
snap == "bottom"? m_snap_to = Bottom : m_snap_to = Label;
}
QString xrefpos;
if (propertyString(xml_element, "xrefpos", &xrefpos) != PropertyFlags::NotFound) {
QMetaEnum var = QMetaEnum::fromType<Qt::Alignment>();
m_xref_pos = Qt::AlignmentFlag(var.keyToValue(xrefpos.toStdString().data()));
}
// TODO: why it compiles without this true??
propertyInteger(xml_element, "offset", &m_offset);
propertyString(xml_element, "master_label", &m_master_label);
propertyString(xml_element, "slave_label", &m_slave_label);
QString value;
foreach (QString key, m_prefix_keys) {
if (!propertyString(xml_element, key + "prefix", &value));
m_prefix.insert(key, value);
}
return true;
QString xrefpos;
if (propertyString(xml_element, "xrefpos", &xrefpos) != PropertyFlags::NotFound) {
QMetaEnum var = QMetaEnum::fromType<Qt::Alignment>();
m_xref_pos = Qt::AlignmentFlag(var.keyToValue(xrefpos.toStdString().data()));
}
// TODO: why it compiles without this true??
propertyInteger(xml_element, "offset", &m_offset);
propertyString(xml_element, "master_label", &m_master_label);
propertyString(xml_element, "slave_label", &m_slave_label);
QString value;
foreach (QString key, m_prefix_keys) {
if (!propertyString(xml_element, key + "prefix", &value));
m_prefix.insert(key, value);
}
return true;
}
/**
@brief XRefProperties::defaultProperties
@return the default properties stored in the setting file
For the xref, there is 2 propreties.
For coil, stored with the string "coil" in the returned QHash.
For protection, stored with the string "protection" in the returned QHash.
@brief XRefProperties::defaultProperties
@return the default properties stored in the setting file
For the xref, there is 2 propreties.
For coil, stored with the string "coil" in the returned QHash.
For protection, stored with the string "protection" in the returned QHash.
*/
QHash<QString, XRefProperties> XRefProperties::defaultProperties()
{
QHash <QString, XRefProperties> hash;
QStringList keys;
keys << "coil" << "protection" << "commutator";
QHash <QString, XRefProperties> hash;
QStringList keys;
keys << "coil" << "protection" << "commutator";
QSettings settings;
QSettings settings;
foreach (QString key, keys)
{
XRefProperties properties;
QString str("diagrameditor/defaultxref");
properties.fromSettings(settings, str += key);
hash.insert(key, properties);
}
foreach (QString key, keys)
{
XRefProperties properties;
QString str("diagrameditor/defaultxref");
properties.fromSettings(settings, str += key);
hash.insert(key, properties);
}
return hash;
return hash;
}
bool XRefProperties::operator ==(const XRefProperties &xrp) const{
return (m_show_power_ctc == xrp.m_show_power_ctc &&
m_display == xrp.m_display &&
m_snap_to == xrp.m_snap_to &&
m_prefix == xrp.m_prefix &&
m_master_label == xrp.m_master_label &&
m_offset == xrp.m_offset &&
m_xref_pos == xrp.m_xref_pos );
return (m_show_power_ctc == xrp.m_show_power_ctc &&
m_display == xrp.m_display &&
m_snap_to == xrp.m_snap_to &&
m_prefix == xrp.m_prefix &&
m_master_label == xrp.m_master_label &&
m_offset == xrp.m_offset &&
m_xref_pos == xrp.m_xref_pos );
}
bool XRefProperties::operator !=(const XRefProperties &xrp) const
{
return (! (*this == xrp));
return (! (*this == xrp));
}

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef XREFPROPERTIES_H
#define XREFPROPERTIES_H
@@ -24,72 +24,72 @@
#include "propertiesinterface.h"
/**
@brief The XRefProperties class
this class store properties used by XrefItem
@brief The XRefProperties class
this class store properties used by XrefItem
*/
class XRefProperties : public PropertiesInterface
{
public:
XRefProperties();
public:
XRefProperties();
enum DisplayHas {
Cross,
Contacts
};
enum DisplayHas {
Cross,
Contacts
};
enum SnapTo {
Bottom,
Label
};
enum SnapTo {
Bottom,
Label
};
void toSettings (QSettings &settings, const QString& = QString()) const override;
void fromSettings (const QSettings &settings, const QString& = QString()) override;
void fromSettings (const QSettings &settings,
const QString = QString()) override;
QDomElement toXml (QDomDocument &xml_document) const override;
bool fromXml(const QDomElement &xml_element) override;
void toSettings (QSettings &settings, const QString& = QString()) const override;
void fromSettings (const QSettings &settings, const QString& = QString()) override;
void fromSettings (const QSettings &settings,
const QString = QString()) override;
QDomElement toXml (QDomDocument &xml_document) const override;
bool fromXml(const QDomElement &xml_element) override;
static QHash<QString, XRefProperties> defaultProperties();
static QHash<QString, XRefProperties> defaultProperties();
bool operator == (const XRefProperties &xrp) const;
bool operator != (const XRefProperties &xrp) const;
bool operator == (const XRefProperties &xrp) const;
bool operator != (const XRefProperties &xrp) const;
void setShowPowerContac (const bool a) {m_show_power_ctc = a;}
bool showPowerContact () const {return m_show_power_ctc;}
void setShowPowerContac (const bool a) {m_show_power_ctc = a;}
bool showPowerContact () const {return m_show_power_ctc;}
void setDisplayHas (const DisplayHas dh) {m_display = dh;}
DisplayHas displayHas () const {return m_display;}
void setDisplayHas (const DisplayHas dh) {m_display = dh;}
DisplayHas displayHas () const {return m_display;}
void setSnapTo (const SnapTo st) {m_snap_to = st;}
SnapTo snapTo () const {return m_snap_to;}
void setSnapTo (const SnapTo st) {m_snap_to = st;}
SnapTo snapTo () const {return m_snap_to;}
void setXrefPos(const Qt::AlignmentFlag xref) {m_xref_pos = xref;}
Qt::AlignmentFlag getXrefPos() const {return m_xref_pos;}
void setPrefix (const QString &key, const QString &value) {m_prefix.insert(key, value);}
QString prefix (const QString &key) const {return m_prefix.value(key);}
void setXrefPos(const Qt::AlignmentFlag xref) {m_xref_pos = xref;}
Qt::AlignmentFlag getXrefPos() const {return m_xref_pos;}
void setPrefix (const QString &key, const QString &value) {m_prefix.insert(key, value);}
QString prefix (const QString &key) const {return m_prefix.value(key);}
void setMasterLabel (const QString master) {m_master_label = master;}
QString masterLabel () const {return m_master_label;}
void setMasterLabel (const QString master) {m_master_label = master;}
QString masterLabel () const {return m_master_label;}
void setSlaveLabel(const QString slave) {m_slave_label = slave;}
QString slaveLabel () const {return m_slave_label;}
void setSlaveLabel(const QString slave) {m_slave_label = slave;}
QString slaveLabel () const {return m_slave_label;}
void setOffset(const int offset) {m_offset = offset;}
int offset() const {return m_offset;}
void setOffset(const int offset) {m_offset = offset;}
int offset() const {return m_offset;}
void setKey(QString& key) {m_key = key;}
void setKey(QString& key) {m_key = key;}
private:
bool m_show_power_ctc{true};
DisplayHas m_display{Cross};
SnapTo m_snap_to{Bottom};
Qt::AlignmentFlag m_xref_pos{Qt::AlignBottom};
QHash <QString, QString> m_prefix;
QStringList m_prefix_keys{"power","delay","switch"};
QString m_master_label{"%f-%l%c"};
QString m_slave_label{"(%f-%l%c)"};
int m_offset{0};
QString m_key;
private:
bool m_show_power_ctc{true};
DisplayHas m_display{Cross};
SnapTo m_snap_to{Bottom};
Qt::AlignmentFlag m_xref_pos{Qt::AlignBottom};
QHash <QString, QString> m_prefix;
QStringList m_prefix_keys{"power","delay","switch"};
QString m_master_label{"%f-%l%c"};
QString m_slave_label{"(%f-%l%c)"};
int m_offset{0};
QString m_key;
};
#endif // XREFPROPERTIES_H

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CONDUCTOR_H
#define CONDUCTOR_H
@@ -37,198 +37,198 @@ class QetGraphicsHandlerItem;
typedef QPair<QPointF, Qt::Corner> ConductorBend;
typedef QHash<Qt::Corner, ConductorProfile> ConductorProfilesGroup;
/**
This class represents a conductor, i.e. a wire between two element
terminals.
This class represents a conductor, i.e. a wire between two element
terminals.
*/
class Conductor : public QGraphicsObject, public PropertiesInterface
{
Q_OBJECT
Q_OBJECT
Q_PROPERTY(QPointF pos READ pos WRITE setPos)
Q_PROPERTY(int animPath READ fakePath WRITE updatePathAnimate)
Q_PROPERTY(ConductorProperties properties READ properties WRITE setProperties)
Q_PROPERTY(autonum::sequentialNumbers sequenceNum READ sequenceNum WRITE setSequenceNum)
Q_PROPERTY(QPointF pos READ pos WRITE setPos)
Q_PROPERTY(int animPath READ fakePath WRITE updatePathAnimate)
Q_PROPERTY(ConductorProperties properties READ properties WRITE setProperties)
Q_PROPERTY(autonum::sequentialNumbers sequenceNum READ sequenceNum WRITE setSequenceNum)
signals:
void propertiesChange();
signals:
void propertiesChange();
public:
Conductor(Terminal *, Terminal *);
~Conductor() override;
public:
Conductor(Terminal *, Terminal *);
~Conductor() override;
bool isValid() const;
bool isValid() const;
private:
Conductor(const Conductor &);
private:
Conductor(const Conductor &);
public:
enum { Type = UserType + 1001 };
enum Highlight { None, Normal, Alert };
public:
enum { Type = UserType + 1001 };
enum Highlight { None, Normal, Alert };
Terminal *terminal1;
Terminal *terminal2;
Terminal *terminal1;
Terminal *terminal2;
public:
/**
@brief type
Enable the use of qgraphicsitem_cast
to safely cast a QGraphicsItem into a conductor.
@return the QGraphicsItem type
*/
int type() const override { return Type; }
Diagram *diagram() const;
ConductorTextItem *textItem() const;
void updatePath(const QRectF & = QRectF());
public:
/**
@brief type
Enable the use of qgraphicsitem_cast
to safely cast a QGraphicsItem into a conductor.
@return the QGraphicsItem type
*/
int type() const override { return Type; }
Diagram *diagram() const;
ConductorTextItem *textItem() const;
void updatePath(const QRectF & = QRectF());
//This method do nothing, it's only made to be used with Q_PROPERTY
//It's used to anim the path when is change
void updatePathAnimate(const int = 1) {updatePath();}
int fakePath() {return 1;}
//This method do nothing, it's only made to be used with Q_PROPERTY
//It's used to anim the path when is change
void updatePathAnimate(const int = 1) {updatePath();}
int fakePath() {return 1;}
void paint(
QPainter *,
const QStyleOptionGraphicsItem *,
QWidget *) override;
QRectF boundingRect() const override;
QPainterPath shape() const override;
virtual QPainterPath nearShape() const;
qreal length() const;
ConductorSegment *middleSegment();
QPointF posForText(Qt::Orientations &flag);
void refreshText();
void setPath(const QPainterPath &path);
QPainterPath path() const;
void paint(
QPainter *,
const QStyleOptionGraphicsItem *,
QWidget *) override;
QRectF boundingRect() const override;
QPainterPath shape() const override;
virtual QPainterPath nearShape() const;
qreal length() const;
ConductorSegment *middleSegment();
QPointF posForText(Qt::Orientations &flag);
void refreshText();
void setPath(const QPainterPath &path);
QPainterPath path() const;
public:
static bool valideXml (QDomElement &);
bool fromXml (const QDomElement &) override;
//QDomElement toXml (QDomDocument &, QHash<Terminal *, int> &) const;
QDomElement toXml (QDomDocument &doc) const override;
private:
bool pathFromXml(const QDomElement &);
public:
static bool valideXml (QDomElement &);
bool fromXml (const QDomElement &) override;
//QDomElement toXml (QDomDocument &, QHash<Terminal *, int> &) const;
QDomElement toXml (QDomDocument &doc) const override;
private:
bool pathFromXml(const QDomElement &);
public:
QVector <QPointF> handlerPoints() const;
const QList<ConductorSegment *> segmentsList() const;
public:
QVector <QPointF> handlerPoints() const;
const QList<ConductorSegment *> segmentsList() const;
void setPropertyToPotential(
const ConductorProperties &property,
bool only_text = false);
void setProperties(const ConductorProperties &property);
ConductorProperties properties() const;
void setPropertyToPotential(
const ConductorProperties &property,
bool only_text = false);
void setProperties(const ConductorProperties &property);
ConductorProperties properties() const;
void setProfile(const ConductorProfile &, Qt::Corner);
ConductorProfile profile(Qt::Corner) const;
void setProfiles(const ConductorProfilesGroup &);
ConductorProfilesGroup profiles() const;
void calculateTextItemPosition();
virtual Highlight highlight() const;
virtual void setHighlighted(Highlight);
QSet<Conductor *> relatedPotentialConductors(
const bool all_diagram = true,
QList <Terminal *> *t_list=nullptr);
QETDiagramEditor* diagramEditor() const;
void editProperty ();
void setProfile(const ConductorProfile &, Qt::Corner);
ConductorProfile profile(Qt::Corner) const;
void setProfiles(const ConductorProfilesGroup &);
ConductorProfilesGroup profiles() const;
void calculateTextItemPosition();
virtual Highlight highlight() const;
virtual void setHighlighted(Highlight);
QSet<Conductor *> relatedPotentialConductors(
const bool all_diagram = true,
QList <Terminal *> *t_list=nullptr);
QETDiagramEditor* diagramEditor() const;
void editProperty ();
autonum::sequentialNumbers sequenceNum () const
{return m_autoNum_seq;}
autonum::sequentialNumbers& rSequenceNum()
{return m_autoNum_seq;}
void setSequenceNum(const autonum::sequentialNumbers& sn);
autonum::sequentialNumbers sequenceNum () const
{return m_autoNum_seq;}
autonum::sequentialNumbers& rSequenceNum()
{return m_autoNum_seq;}
void setSequenceNum(const autonum::sequentialNumbers& sn);
QList<QPointF> junctions() const;
QList<QPointF> junctions() const;
private:
void setUpConnectionForFormula(
QString old_formula, QString new_formula);
autonum::sequentialNumbers m_autoNum_seq;
private:
void setUpConnectionForFormula(
QString old_formula, QString new_formula);
autonum::sequentialNumbers m_autoNum_seq;
public:
void setFreezeLabel(bool freeze);
public:
void setFreezeLabel(bool freeze);
public slots:
void displayedTextChanged();
public slots:
void displayedTextChanged();
protected:
void mouseDoubleClickEvent(
QGraphicsSceneMouseEvent *event) override;
void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
void mouseReleaseEvent(
QGraphicsSceneMouseEvent *event) override;
void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override;
void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override;
QVariant itemChange(
GraphicsItemChange, const QVariant &) override;
bool sceneEventFilter(
QGraphicsItem *watched, QEvent *event) override;
protected:
void mouseDoubleClickEvent(
QGraphicsSceneMouseEvent *event) override;
void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
void mouseReleaseEvent(
QGraphicsSceneMouseEvent *event) override;
void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override;
void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override;
QVariant itemChange(
GraphicsItemChange, const QVariant &) override;
bool sceneEventFilter(
QGraphicsItem *watched, QEvent *event) override;
private:
void adjusteHandlerPos();
private:
void adjusteHandlerPos();
void handlerMousePressEvent(
QetGraphicsHandlerItem *qghi,
QGraphicsSceneMouseEvent *event);
void handlerMouseMoveEvent(
QetGraphicsHandlerItem *qghi,
QGraphicsSceneMouseEvent *event);
void handlerMouseReleaseEvent(
QetGraphicsHandlerItem *qghi,
QGraphicsSceneMouseEvent *event);
void addHandler();
void removeHandler();
void handlerMousePressEvent(
QetGraphicsHandlerItem *qghi,
QGraphicsSceneMouseEvent *event);
void handlerMouseMoveEvent(
QetGraphicsHandlerItem *qghi,
QGraphicsSceneMouseEvent *event);
void handlerMouseReleaseEvent(
QetGraphicsHandlerItem *qghi,
QGraphicsSceneMouseEvent *event);
void addHandler();
void removeHandler();
QVector<QetGraphicsHandlerItem *> m_handler_vector;
int m_vector_index = -1;
bool m_mouse_over{false};
/// Functional properties
ConductorProperties m_properties;
/// Text input for non simple, non-singleline conductors
ConductorTextItem *m_text_item{nullptr};
/// Segments composing the conductor
ConductorSegment *segments{nullptr};
/// Attributs related to mouse interaction
bool m_moving_segment{false};
int moved_point;
qreal m_previous_z_value;
ConductorSegment *m_moved_segment;
QPointF before_mov_text_pos_;
/// Whether the conductor was manually modified by users
bool modified_path{false};
/// Whether the current profile should be saved as soon as possible
bool has_to_save_profile{false};
/// conductor profile: "photography" of what the conductor is supposed to look
/// like - there is one profile per kind of traject
ConductorProfilesGroup conductor_profiles;
/// Define whether and how the conductor should be highlighted
Highlight must_highlight_{Conductor::None};
bool m_valid;
bool m_freeze_label = false;
QVector<QetGraphicsHandlerItem *> m_handler_vector;
int m_vector_index = -1;
bool m_mouse_over{false};
/// Functional properties
ConductorProperties m_properties;
/// Text input for non simple, non-singleline conductors
ConductorTextItem *m_text_item{nullptr};
/// Segments composing the conductor
ConductorSegment *segments{nullptr};
/// Attributs related to mouse interaction
bool m_moving_segment{false};
int moved_point;
qreal m_previous_z_value;
ConductorSegment *m_moved_segment;
QPointF before_mov_text_pos_;
/// Whether the conductor was manually modified by users
bool modified_path{false};
/// Whether the current profile should be saved as soon as possible
bool has_to_save_profile{false};
/// conductor profile: "photography" of what the conductor is supposed to look
/// like - there is one profile per kind of traject
ConductorProfilesGroup conductor_profiles;
/// Define whether and how the conductor should be highlighted
Highlight must_highlight_{Conductor::None};
bool m_valid;
bool m_freeze_label = false;
/// QPen et QBrush objects used to draw conductors
static QPen conductor_pen;
static QBrush conductor_brush;
static bool pen_and_brush_initialized;
QPainterPath m_path;
/// QPen et QBrush objects used to draw conductors
static QPen conductor_pen;
static QBrush conductor_brush;
static bool pen_and_brush_initialized;
QPainterPath m_path;
private:
void segmentsToPath();
void saveProfile(bool = true);
void generateConductorPath(const QPointF &, Qet::Orientation, const QPointF &, Qet::Orientation);
void updateConductorPath(const QPointF &, Qet::Orientation, const QPointF &, Qet::Orientation);
uint segmentsCount(QET::ConductorSegmentType = QET::Both) const;
QList<QPointF> segmentsToPoints() const;
QList<ConductorBend> bends() const;
private:
void segmentsToPath();
void saveProfile(bool = true);
void generateConductorPath(const QPointF &, Qet::Orientation, const QPointF &, Qet::Orientation);
void updateConductorPath(const QPointF &, Qet::Orientation, const QPointF &, Qet::Orientation);
uint segmentsCount(QET::ConductorSegmentType = QET::Both) const;
QList<QPointF> segmentsToPoints() const;
QList<ConductorBend> bends() const;
void pointsToSegments(const QList<QPointF>&);
Qt::Corner currentPathType() const;
void deleteSegments();
static int getCoeff(const qreal &, const qreal &);
static int getSign(const qreal &);
QHash<ConductorSegmentProfile *, qreal> shareOffsetBetweenSegments(const qreal &offset, const QList<ConductorSegmentProfile *> &, const qreal & = 0.01) const;
static QPointF extendTerminal(const QPointF &, Qet::Orientation, qreal = 9.0);
static Qt::Corner movementType(const QPointF &, const QPointF &);
static QPointF movePointIntoPolygon(const QPointF &, const QPainterPath &);
void pointsToSegments(const QList<QPointF>&);
Qt::Corner currentPathType() const;
void deleteSegments();
static int getCoeff(const qreal &, const qreal &);
static int getSign(const qreal &);
QHash<ConductorSegmentProfile *, qreal> shareOffsetBetweenSegments(const qreal &offset, const QList<ConductorSegmentProfile *> &, const qreal & = 0.01) const;
static QPointF extendTerminal(const QPointF &, Qet::Orientation, qreal = 9.0);
static Qt::Corner movementType(const QPointF &, const QPointF &);
static QPointF movePointIntoPolygon(const QPointF &, const QPainterPath &);
};
Conductor * longuestConductorInPotential (Conductor *conductor, bool all_diagram = false);
@@ -238,7 +238,7 @@ QList <Conductor *> relatedConductors (const Conductor *conductor);
//return true if @a is between or at @b and @c.
template <typename T>
bool isBetween (const T a, const T b, const T c) {
return (b <= c)? (a >= b && a <= c) : (a <= b && a >= c);
return (b <= c)? (a >= b && a <= c) : (a <= b && a >= c);
}
#endif

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#include "conductortextitem.h"
#include "conductor.h"
@@ -21,258 +21,258 @@
#include "diagram.h"
/**
Constructeur
@param parent_conductor Conducteur auquel ce texte est rattache
Constructeur
@param parent_conductor Conducteur auquel ce texte est rattache
*/
ConductorTextItem::ConductorTextItem(Conductor *parent_conductor) :
DiagramTextItem(parent_conductor),
parent_conductor_(parent_conductor)
DiagramTextItem(parent_conductor),
parent_conductor_(parent_conductor)
{
setAcceptHoverEvents(true);
setAcceptHoverEvents(true);
}
/**
Constructeur
@param text Le texte affiche par le champ de texte
@param parent_conductor Conducteur auquel ce texte est rattache
Constructeur
@param text Le texte affiche par le champ de texte
@param parent_conductor Conducteur auquel ce texte est rattache
*/
ConductorTextItem::ConductorTextItem(
const QString &text, Conductor *parent_conductor) :
DiagramTextItem(text, parent_conductor),
parent_conductor_(parent_conductor),
moved_by_user_(false),
rotate_by_user_(false)
const QString &text, Conductor *parent_conductor) :
DiagramTextItem(text, parent_conductor),
parent_conductor_(parent_conductor),
moved_by_user_(false),
rotate_by_user_(false)
{}
/**
Destructeur
Destructeur
*/
ConductorTextItem::~ConductorTextItem()
{
}
/**
@return le conducteur parent de ce champ de texte, ou 0 si celui-ci n'en a
pas
@return le conducteur parent de ce champ de texte, ou 0 si celui-ci n'en a
pas
*/
Conductor *ConductorTextItem::parentConductor() const
{
return(parent_conductor_);
return(parent_conductor_);
}
void ConductorTextItem::toXml(QDomDocument& doc, QDomElement& e) {
if(moved_by_user_)
{
e.appendChild(PropertiesInterface::createXmlProperty(doc, "userx", pos().x()));
e.appendChild(PropertiesInterface::createXmlProperty(doc, "usery", pos().y()));
}
if(rotate_by_user_)
e.appendChild(PropertiesInterface::createXmlProperty(doc, "rotation", rotation()));
if(moved_by_user_)
{
e.appendChild(PropertiesInterface::createXmlProperty(doc, "userx", pos().x()));
e.appendChild(PropertiesInterface::createXmlProperty(doc, "usery", pos().y()));
}
if(rotate_by_user_)
e.appendChild(PropertiesInterface::createXmlProperty(doc, "rotation", rotation()));
}
/**
@brief ConductorTextItem::fromXml
Read the properties stored in the xml element given in parameter
@param e
@brief ConductorTextItem::fromXml
Read the properties stored in the xml element given in parameter
@param e
*/
void ConductorTextItem::fromXml(const QDomElement &e) {
double userx=0, usery=0;
if (PropertiesInterface::propertyDouble(e, "userx", &userx) == PropertiesInterface::PropertyFlags::Success &&
PropertiesInterface::propertyDouble(e, "usery", &usery) == PropertiesInterface::PropertyFlags::Success) {
setPos(userx, usery);
moved_by_user_ = true;
}
double userx=0, usery=0;
if (PropertiesInterface::propertyDouble(e, "userx", &userx) == PropertiesInterface::PropertyFlags::Success &&
PropertiesInterface::propertyDouble(e, "usery", &usery) == PropertiesInterface::PropertyFlags::Success) {
setPos(userx, usery);
moved_by_user_ = true;
}
double rotation;
if (PropertiesInterface::propertyDouble(e, "rotation", &rotation) == PropertiesInterface::PropertyFlags::Success) {
setRotation(rotation);
rotate_by_user_ = true;
}
double rotation;
if (PropertiesInterface::propertyDouble(e, "rotation", &rotation) == PropertiesInterface::PropertyFlags::Success) {
setRotation(rotation);
rotate_by_user_ = true;
}
}
/**
@return true si ce champ de texte a ete explictement deplace par
l'utilisateur, false sinon
@return true si ce champ de texte a ete explictement deplace par
l'utilisateur, false sinon
*/
bool ConductorTextItem::wasMovedByUser() const
{
return(moved_by_user_);
return(moved_by_user_);
}
/**
@brief ConductorTextItem::wasRotateByUser
@return true if text was explicit moved by user else false
@brief ConductorTextItem::wasRotateByUser
@return true if text was explicit moved by user else false
*/
bool ConductorTextItem::wasRotateByUser() const
{
return(rotate_by_user_);
return(rotate_by_user_);
}
/**
@param moved_by_user true pour que la position du texte soit consideree
comme ayant ete definie par l'utilisateur (et donc soit sauvegardee), false
pour remettre le texte a sa position originelle
@param moved_by_user true pour que la position du texte soit consideree
comme ayant ete definie par l'utilisateur (et donc soit sauvegardee), false
pour remettre le texte a sa position originelle
*/
void ConductorTextItem::forceMovedByUser(bool moved_by_user) {
if (moved_by_user == moved_by_user_) return;
if (moved_by_user == moved_by_user_) return;
moved_by_user_ = moved_by_user;
if (!moved_by_user && parent_conductor_) {
parent_conductor_ -> calculateTextItemPosition();
}
moved_by_user_ = moved_by_user;
if (!moved_by_user && parent_conductor_) {
parent_conductor_ -> calculateTextItemPosition();
}
}
/**
@brief ConductorTextItem::forceRotateByUser
@param rotate_by_user true pour que la rotation du texte soit consideree
comme ayant ete definie par l'utilisateur (et donc soit sauvegardee), false
pour remettre le texte a sont angle originelle
@brief ConductorTextItem::forceRotateByUser
@param rotate_by_user true pour que la rotation du texte soit consideree
comme ayant ete definie par l'utilisateur (et donc soit sauvegardee), false
pour remettre le texte a sont angle originelle
*/
void ConductorTextItem::forceRotateByUser(bool rotate_by_user) {
if (rotate_by_user == rotate_by_user_) return;
if (rotate_by_user == rotate_by_user_) return;
rotate_by_user_ = rotate_by_user;
if (!rotate_by_user && parent_conductor_) {
parent_conductor_ -> calculateTextItemPosition();
}
rotate_by_user_ = rotate_by_user;
if (!rotate_by_user && parent_conductor_) {
parent_conductor_ -> calculateTextItemPosition();
}
}
/**
@brief ConductorTextItem::setPos
@param pos
@brief ConductorTextItem::setPos
@param pos
*/
void ConductorTextItem::setPos(const QPointF &pos)
{
/*
* In some condition the conductor text item is outside the border of folio in the left.
* They cause a margin on the left of folio and in most case this margin is unwanted and annoying the user.
* If the text is empty and the scene position is outside the border (left and top),
* we can say that this position, is unwanted by user.
* So we move this text item to the top left of the bounding rect of parent conductors, because we sure this position is wanted by user.
*/
DiagramTextItem::setPos(pos);
if(toPlainText().isEmpty() && (scenePos().x() < 0 || scenePos().y() < 0))
{
Conductor *cond = parentConductor();
if(cond)
DiagramTextItem::setPos(cond->boundingRect().topLeft());
else
DiagramTextItem::setPos(0,0);
}
/*
* In some condition the conductor text item is outside the border of folio in the left.
* They cause a margin on the left of folio and in most case this margin is unwanted and annoying the user.
* If the text is empty and the scene position is outside the border (left and top),
* we can say that this position, is unwanted by user.
* So we move this text item to the top left of the bounding rect of parent conductors, because we sure this position is wanted by user.
*/
DiagramTextItem::setPos(pos);
if(toPlainText().isEmpty() && (scenePos().x() < 0 || scenePos().y() < 0))
{
Conductor *cond = parentConductor();
if(cond)
DiagramTextItem::setPos(cond->boundingRect().topLeft());
else
DiagramTextItem::setPos(0,0);
}
}
/**
@brief ConductorTextItem::setPos
@param x
@param y
@brief ConductorTextItem::setPos
@param x
@param y
*/
void ConductorTextItem::setPos(qreal x, qreal y)
{
QPointF p(x,y);
setPos(p);
QPointF p(x,y);
setPos(p);
}
/**
@brief ConductorTextItem::mousePressEvent
@param event
@brief ConductorTextItem::mousePressEvent
@param event
*/
void ConductorTextItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
before_mov_pos_ = pos();
DiagramTextItem::mousePressEvent(event);
before_mov_pos_ = pos();
DiagramTextItem::mousePressEvent(event);
}
/**
@brief ConductorTextItem::mouseMoveEvent
@param event
@brief ConductorTextItem::mouseMoveEvent
@param event
*/
void ConductorTextItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
if (textInteractionFlags() & Qt::TextEditable) QGraphicsTextItem::mouseMoveEvent(event);
if (textInteractionFlags() & Qt::TextEditable) QGraphicsTextItem::mouseMoveEvent(event);
else if ((flags() & QGraphicsItem::ItemIsMovable) && (event -> buttons() & Qt::LeftButton)) {
else if ((flags() & QGraphicsItem::ItemIsMovable) && (event -> buttons() & Qt::LeftButton)) {
QPointF intended_pos = event ->scenePos() + m_mouse_to_origin_movement;
QPointF intended_pos = event ->scenePos() + m_mouse_to_origin_movement;
if (parent_conductor_) {
if (parent_conductor_->nearShape().contains(intended_pos)) {
event->modifiers() == Qt::ControlModifier ? setPos(intended_pos) : setPos(Diagram::snapToGrid(intended_pos));
parent_conductor_ -> setHighlighted(Conductor::Normal);
} else {
parent_conductor_ -> setHighlighted(Conductor::Alert);
}
}
if (parent_conductor_) {
if (parent_conductor_->nearShape().contains(intended_pos)) {
event->modifiers() == Qt::ControlModifier ? setPos(intended_pos) : setPos(Diagram::snapToGrid(intended_pos));
parent_conductor_ -> setHighlighted(Conductor::Normal);
} else {
parent_conductor_ -> setHighlighted(Conductor::Alert);
}
}
}
}
else event -> ignore();
else event -> ignore();
}
/**
@brief ConductorTextItem::mouseReleaseEvent
@param e
@brief ConductorTextItem::mouseReleaseEvent
@param e
*/
void ConductorTextItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *e) {
if (flags() & QGraphicsItem::ItemIsMovable) {
if (flags() & QGraphicsItem::ItemIsMovable) {
if (Diagram *diagram_ptr = diagram()) {
QPointF applied_movement = pos() - before_mov_pos_;
if (Diagram *diagram_ptr = diagram()) {
QPointF applied_movement = pos() - before_mov_pos_;
if (!applied_movement.isNull()) {
//Create an undo object
MoveConductorsTextsCommand *undo_object = new MoveConductorsTextsCommand(diagram_ptr);
undo_object -> addTextMovement(this, before_mov_pos_, pos(), moved_by_user_);
if (!applied_movement.isNull()) {
//Create an undo object
MoveConductorsTextsCommand *undo_object = new MoveConductorsTextsCommand(diagram_ptr);
undo_object -> addTextMovement(this, before_mov_pos_, pos(), moved_by_user_);
moved_by_user_ = true;
moved_by_user_ = true;
diagram_ptr -> undoStack().push(undo_object);
}
diagram_ptr -> undoStack().push(undo_object);
}
if (parent_conductor_) {
parent_conductor_ -> setHighlighted(Conductor::None);
}
}
}
if (!(e -> modifiers() & Qt::ControlModifier)) {
QGraphicsTextItem::mouseReleaseEvent(e);
}
if (parent_conductor_) {
parent_conductor_ -> setHighlighted(Conductor::None);
}
}
}
if (!(e -> modifiers() & Qt::ControlModifier)) {
QGraphicsTextItem::mouseReleaseEvent(e);
}
}
/**
When mouse over element
change m_mouse_hover to true (used in paint() function )
@param e QGraphicsSceneHoverEvent
When mouse over element
change m_mouse_hover to true (used in paint() function )
@param e QGraphicsSceneHoverEvent
*/
void ConductorTextItem::hoverEnterEvent(QGraphicsSceneHoverEvent *e) {
Q_UNUSED(e);
Q_UNUSED(e);
m_mouse_hover = true;
QString str_ToolTip = toPlainText();
setToolTip( str_ToolTip );
update();
m_mouse_hover = true;
QString str_ToolTip = toPlainText();
setToolTip( str_ToolTip );
update();
}
/**
When mouse over element leave the position
change m_mouse_hover to false(used in paint() function )
@param e QGraphicsSceneHoverEvent
When mouse over element leave the position
change m_mouse_hover to false(used in paint() function )
@param e QGraphicsSceneHoverEvent
*/
void ConductorTextItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *e)
{
Q_UNUSED(e);
qDebug() << "Leave mouse over";
m_mouse_hover = false;
update();
Q_UNUSED(e);
qDebug() << "Leave mouse over";
m_mouse_hover = false;
update();
}
/**
Do nothing default function .
@param e QGraphicsSceneHoverEvent
Do nothing default function .
@param e QGraphicsSceneHoverEvent
*/
void ConductorTextItem::hoverMoveEvent(QGraphicsSceneHoverEvent *e)
{
QGraphicsTextItem::hoverMoveEvent(e);
QGraphicsTextItem::hoverMoveEvent(e);
}

View File

@@ -1,69 +1,69 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CONDUCTOR_TEXT_ITEM_H
#define CONDUCTOR_TEXT_ITEM_H
#include "diagramtextitem.h"
class Conductor;
/**
This class represents a text item attached to a parent conductor.
It may be moved and edited by users.
It may also be rotated to any angle.
Its movements are however limited to a particular distance around its
parent conductor.
This class represents a text item attached to a parent conductor.
It may be moved and edited by users.
It may also be rotated to any angle.
Its movements are however limited to a particular distance around its
parent conductor.
*/
class ConductorTextItem : public DiagramTextItem
{
Q_OBJECT
Q_OBJECT
// constructors, destructor
public:
ConductorTextItem(Conductor * = nullptr);
ConductorTextItem(const QString &, Conductor * = nullptr);
~ConductorTextItem() override;
private:
ConductorTextItem(const ConductorTextItem &);
// constructors, destructor
public:
ConductorTextItem(Conductor * = nullptr);
ConductorTextItem(const QString &, Conductor * = nullptr);
~ConductorTextItem() override;
private:
ConductorTextItem(const ConductorTextItem &);
public:
enum { Type = UserType + 1006 };
Conductor *parentConductor() const;
void fromXml(const QDomElement &) override;
void toXml(QDomDocument& doc, QDomElement& e);
int type() const override { return Type; }
virtual bool wasMovedByUser() const;
virtual bool wasRotateByUser() const;
virtual void forceMovedByUser(bool);
virtual void forceRotateByUser(bool);
virtual void setPos(const QPointF &pos);
virtual void setPos(qreal x, qreal y);
public:
enum { Type = UserType + 1006 };
Conductor *parentConductor() const;
void fromXml(const QDomElement &) override;
void toXml(QDomDocument& doc, QDomElement& e);
int type() const override { return Type; }
virtual bool wasMovedByUser() const;
virtual bool wasRotateByUser() const;
virtual void forceMovedByUser(bool);
virtual void forceRotateByUser(bool);
virtual void setPos(const QPointF &pos);
virtual void setPos(qreal x, qreal y);
protected:
void mousePressEvent (QGraphicsSceneMouseEvent *event) override;
void mouseMoveEvent (QGraphicsSceneMouseEvent *event) override;
void mouseReleaseEvent (QGraphicsSceneMouseEvent *event) override;
void hoverEnterEvent(QGraphicsSceneHoverEvent *) override;
void hoverLeaveEvent(QGraphicsSceneHoverEvent *) override;
void hoverMoveEvent(QGraphicsSceneHoverEvent *) override;
protected:
void mousePressEvent (QGraphicsSceneMouseEvent *event) override;
void mouseMoveEvent (QGraphicsSceneMouseEvent *event) override;
void mouseReleaseEvent (QGraphicsSceneMouseEvent *event) override;
void hoverEnterEvent(QGraphicsSceneHoverEvent *) override;
void hoverLeaveEvent(QGraphicsSceneHoverEvent *) override;
void hoverMoveEvent(QGraphicsSceneHoverEvent *) override;
// attributes
private:
Conductor *parent_conductor_;
bool moved_by_user_{false};
bool rotate_by_user_{false};
QPointF before_mov_pos_;
// attributes
private:
Conductor *parent_conductor_;
bool moved_by_user_{false};
bool rotate_by_user_{false};
QPointF before_mov_pos_;
};
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef DYNAMICELEMENTTEXTITEM_H
#define DYNAMICELEMENTTEXTITEM_H
@@ -30,136 +30,136 @@ class ElementTextItemGroup;
class CrossRefItem;
/**
@brief The DynamicElementTextItem class
This class provide a simple text field of element who can be added or removed directly from the diagram editor.
This text is created to compensate a big lack of the ElementTextItem : ElementTextItem can't be added or removed directly in the diagram editor
@brief The DynamicElementTextItem class
This class provide a simple text field of element who can be added or removed directly from the diagram editor.
This text is created to compensate a big lack of the ElementTextItem : ElementTextItem can't be added or removed directly in the diagram editor
*/
class DynamicElementTextItem : public DiagramTextItem
{
friend class DynamicTextItemDelegate;
friend class CompositeTextEditDialog;
friend class Element;
friend class DynamicTextItemDelegate;
friend class CompositeTextEditDialog;
friend class Element;
Q_OBJECT
Q_OBJECT
Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged)
Q_PROPERTY(TextFrom textFrom READ textFrom WRITE setTextFrom NOTIFY textFromChanged)
Q_PROPERTY(QString infoName READ infoName WRITE setInfoName NOTIFY infoNameChanged)
Q_PROPERTY(QString compositeText READ compositeText WRITE setCompositeText NOTIFY compositeTextChanged)
Q_PROPERTY(bool frame READ frame WRITE setFrame NOTIFY frameChanged)
Q_PROPERTY(qreal textWidth READ textWidth WRITE setTextWidth NOTIFY textWidthChanged)
Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged)
Q_PROPERTY(TextFrom textFrom READ textFrom WRITE setTextFrom NOTIFY textFromChanged)
Q_PROPERTY(QString infoName READ infoName WRITE setInfoName NOTIFY infoNameChanged)
Q_PROPERTY(QString compositeText READ compositeText WRITE setCompositeText NOTIFY compositeTextChanged)
Q_PROPERTY(bool frame READ frame WRITE setFrame NOTIFY frameChanged)
Q_PROPERTY(qreal textWidth READ textWidth WRITE setTextWidth NOTIFY textWidthChanged)
public:
public:
enum TextFrom {
UserText,
ElementInfo,
CompositeText
};
Q_ENUM (TextFrom)
enum {Type = UserType + 1010};
int type() const override {return Type;}
enum TextFrom {
UserText,
ElementInfo,
CompositeText
};
Q_ENUM (TextFrom)
enum {Type = UserType + 1010};
int type() const override {return Type;}
signals:
void textChanged(QString text);
void textFromChanged(DynamicElementTextItem::TextFrom text_from);
void infoNameChanged(QString info);
void compositeTextChanged(QString text);
void frameChanged(bool frame);
void plainTextChanged();
void textWidthChanged(qreal width);
signals:
void textChanged(QString text);
void textFromChanged(DynamicElementTextItem::TextFrom text_from);
void infoNameChanged(QString info);
void compositeTextChanged(QString text);
void frameChanged(bool frame);
void plainTextChanged();
void textWidthChanged(qreal width);
public:
DynamicElementTextItem(Element *parent_element);
~DynamicElementTextItem() override;
static QMetaEnum textFromMetaEnum();
private:
DynamicElementTextItem ();
DynamicElementTextItem(const DynamicElementTextItem &);
public:
DynamicElementTextItem(Element *parent_element);
~DynamicElementTextItem() override;
static QMetaEnum textFromMetaEnum();
private:
DynamicElementTextItem ();
DynamicElementTextItem(const DynamicElementTextItem &);
public:
QDomElement toXml(QDomDocument &dom_doc) const override;
void fromXml(const QDomElement &dom_elmt) override;
public:
QDomElement toXml(QDomDocument &dom_doc) const override;
void fromXml(const QDomElement &dom_elmt) override;
Element *parentElement() const;
ElementTextItemGroup *parentGroup() const;
Element *elementUseForInfo() const;
void refreshLabelConnection();
Element *parentElement() const;
ElementTextItemGroup *parentGroup() const;
Element *elementUseForInfo() const;
void refreshLabelConnection();
DynamicElementTextItem::TextFrom textFrom() const;
void setTextFrom (DynamicElementTextItem::TextFrom text_from);
QString text() const;
void setText(const QString &text);
static QString xmlTagName() {return QString("dynamic_elmt_text");}
void setInfoName(const QString &info_name);
QString infoName() const;
void setCompositeText(const QString &text);
QString compositeText() const;
void setFrame(const bool frame);
bool frame() const;
QUuid uuid() const;
void updateXref();
void setPlainText(const QString &text);
void setTextWidth(qreal width);
void setXref_item(Qt::AlignmentFlag m_exHrefPos);
DynamicElementTextItem::TextFrom textFrom() const;
void setTextFrom (DynamicElementTextItem::TextFrom text_from);
QString text() const;
void setText(const QString &text);
static QString xmlTagName() {return QString("dynamic_elmt_text");}
void setInfoName(const QString &info_name);
QString infoName() const;
void setCompositeText(const QString &text);
QString compositeText() const;
void setFrame(const bool frame);
bool frame() const;
QUuid uuid() const;
void updateXref();
void setPlainText(const QString &text);
void setTextWidth(qreal width);
void setXref_item(Qt::AlignmentFlag m_exHrefPos);
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override;
void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override;
void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
QVariant itemChange(GraphicsItemChange change, const QVariant &value) override;
bool sceneEventFilter(QGraphicsItem *watched, QEvent *event) override;
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override;
void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override;
void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
QVariant itemChange(GraphicsItemChange change, const QVariant &value) override;
bool sceneEventFilter(QGraphicsItem *watched, QEvent *event) override;
private:
void elementInfoChanged();
void masterChanged();
void reportChanged();
void reportFormulaChanged();
void setConnectionForReportFormula(const QString &formula);
void removeConnectionForReportFormula(const QString &formula);
void setupFormulaConnection();
void clearFormulaConnection();
void updateReportFormulaConnection();
void updateReportText();
void updateLabel();
void conductorWasAdded(Conductor *conductor);
void conductorWasRemoved(Conductor *conductor);
void setPotentialConductor();
void conductorPropertiesChanged();
QString reportReplacedCompositeText() const;
void zoomToLinkedElement();
private:
void elementInfoChanged();
void masterChanged();
void reportChanged();
void reportFormulaChanged();
void setConnectionForReportFormula(const QString &formula);
void removeConnectionForReportFormula(const QString &formula);
void setupFormulaConnection();
void clearFormulaConnection();
void updateReportFormulaConnection();
void updateReportText();
void updateLabel();
void conductorWasAdded(Conductor *conductor);
void conductorWasRemoved(Conductor *conductor);
void setPotentialConductor();
void conductorPropertiesChanged();
QString reportReplacedCompositeText() const;
void zoomToLinkedElement();
private:
QPointer <Element>
m_parent_element,
m_master_element,
m_other_report;
QPointer <Conductor> m_watched_conductor;
QString
m_text,
m_info_name,
m_composite_text,
m_report_formula,
m_F_str;
DynamicElementTextItem::TextFrom m_text_from = UserText;
QUuid m_uuid;
QMetaObject::Connection m_report_formula_con;
QList<QMetaObject::Connection>
m_formula_connection,
m_update_slave_Xref_connection;
QColor m_user_color{QColor()};
bool
m_frame = false,
m_first_scene_change = true;
CrossRefItem *m_Xref_item = nullptr;
QGraphicsTextItem *m_slave_Xref_item = nullptr;
qreal m_text_width = -1;
QPointF m_initial_position;
private:
QPointer <Element>
m_parent_element,
m_master_element,
m_other_report;
QPointer <Conductor> m_watched_conductor;
QString
m_text,
m_info_name,
m_composite_text,
m_report_formula,
m_F_str;
DynamicElementTextItem::TextFrom m_text_from = UserText;
QUuid m_uuid;
QMetaObject::Connection m_report_formula_con;
QList<QMetaObject::Connection>
m_formula_connection,
m_update_slave_Xref_connection;
QColor m_user_color{QColor()};
bool
m_frame = false,
m_first_scene_change = true;
CrossRefItem *m_Xref_item = nullptr;
QGraphicsTextItem *m_slave_Xref_item = nullptr;
qreal m_text_width = -1;
QPointF m_initial_position;
};
#endif // DYNAMICELEMENTTEXTITEM_H

File diff suppressed because it is too large Load Diff

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ELEMENT_H
#define ELEMENT_H
@@ -36,203 +36,203 @@ class DynamicElementTextItem;
class ElementTextItemGroup;
/**
This is the base class for electrical elements.
This is the base class for electrical elements.
*/
class Element : public QetGraphicsItem // TODO: derive from propertiesInterface!
{
friend class DiagramEventAddElement;
friend class DiagramEventAddElement;
Q_OBJECT
public:
/**
@brief The kind enum
Used to know the kind of this element
(master, slave, report ect...)
*/
enum kind {
Simple = 1,
NextReport = 2,
PreviousReport = 4,
AllReport = 6,
Master = 8,
Slave = 16,
Terminale = 32};
Q_OBJECT
public:
/**
@brief The kind enum
Used to know the kind of this element
(master, slave, report ect...)
*/
enum kind {
Simple = 1,
NextReport = 2,
PreviousReport = 4,
AllReport = 6,
Master = 8,
Slave = 16,
Terminale = 32};
Element(const ElementsLocation &location,
QGraphicsItem * = nullptr,
int *state = nullptr,
Element::kind link_type = Element::Simple);
~Element() override;
private:
Element(const Element &);
Element(const ElementsLocation &location,
QGraphicsItem * = nullptr,
int *state = nullptr,
Element::kind link_type = Element::Simple);
~Element() override;
private:
Element(const Element &);
// attributes
public:
/**
Enable the use of qgraphicsitem_cast
to safely cast a QGraphicsItem into an Element.
@return the QGraphicsItem type
*/
enum { Type = UserType + 1000 };
int type() const override { return Type; }
// attributes
public:
/**
Enable the use of qgraphicsitem_cast
to safely cast a QGraphicsItem into an Element.
@return the QGraphicsItem type
*/
enum { Type = UserType + 1000 };
int type() const override { return Type; }
signals:
void linkedElementChanged(); //This signal is emited when the linked elements with this element change
void elementInfoChange(
DiagramContext old_info,
DiagramContext new_info);
void textAdded(DynamicElementTextItem *deti);
void textRemoved(DynamicElementTextItem *deti);
void textsGroupAdded(ElementTextItemGroup *group);
void textsGroupAboutToBeRemoved(ElementTextItemGroup *group);
void textAddedToGroup(
DynamicElementTextItem *text,
ElementTextItemGroup *group);
void textRemovedFromGroup(
DynamicElementTextItem *text,
ElementTextItemGroup *group);
signals:
void linkedElementChanged(); //This signal is emited when the linked elements with this element change
void elementInfoChange(
DiagramContext old_info,
DiagramContext new_info);
void textAdded(DynamicElementTextItem *deti);
void textRemoved(DynamicElementTextItem *deti);
void textsGroupAdded(ElementTextItemGroup *group);
void textsGroupAboutToBeRemoved(ElementTextItemGroup *group);
void textAddedToGroup(
DynamicElementTextItem *text,
ElementTextItemGroup *group);
void textRemovedFromGroup(
DynamicElementTextItem *text,
ElementTextItemGroup *group);
public:
QList<Terminal *> terminals() const;
QList<Conductor *> conductors() const;
QList<QPair<Terminal *,Terminal *>> AlignedFreeTerminals() const;
public:
QList<Terminal *> terminals() const;
QList<Conductor *> conductors() const;
QList<QPair<Terminal *,Terminal *>> AlignedFreeTerminals() const;
//METHODS related to information
DiagramContext elementInformations()const
{return m_element_informations;}
virtual void setElementInformations(DiagramContext dc);
DiagramContext kindInformations() const
{return m_kind_informations;}
//@kind_information_ is used to store more information
//about the herited class like contactelement for know
// kind of contact (simple tempo) or number of contact show by the element.
//METHODS related to information
DiagramContext elementInformations()const
{return m_element_informations;}
virtual void setElementInformations(DiagramContext dc);
DiagramContext kindInformations() const
{return m_kind_informations;}
//@kind_information_ is used to store more information
//about the herited class like contactelement for know
// kind of contact (simple tempo) or number of contact show by the element.
autonum::sequentialNumbers sequenceStruct() const
{return m_autoNum_seq;}
autonum::sequentialNumbers& rSequenceStruct()
{return m_autoNum_seq;}
void setUpFormula(bool code_letter = true);
void setPrefix(QString);
QString getPrefix() const;
void freezeLabel(bool freeze);
bool isFreezeLabel() const {return m_freeze_label;}
void freezeNewAddedElement();
QString actualLabel();
autonum::sequentialNumbers sequenceStruct() const
{return m_autoNum_seq;}
autonum::sequentialNumbers& rSequenceStruct()
{return m_autoNum_seq;}
void setUpFormula(bool code_letter = true);
void setPrefix(QString);
QString getPrefix() const;
void freezeLabel(bool freeze);
bool isFreezeLabel() const {return m_freeze_label;}
void freezeNewAddedElement();
QString actualLabel();
QString name() const override;
ElementsLocation location() const;
virtual void setHighlighted(bool);
void displayHelpLine(bool b = true);
QSize size() const;
QPixmap pixmap();
QPoint setHotspot(QPoint);
QPoint hotspot() const;
void editProperty() override;
static bool valideXml(QDomElement &);
virtual bool fromXml(QDomElement &, QHash<int, Terminal *> &, bool = false);
virtual QDomElement toXml(QDomDocument &) const;
QUuid uuid() const;
int orientation() const;
QString name() const override;
ElementsLocation location() const;
virtual void setHighlighted(bool);
void displayHelpLine(bool b = true);
QSize size() const;
QPixmap pixmap();
QPoint setHotspot(QPoint);
QPoint hotspot() const;
void editProperty() override;
static bool valideXml(QDomElement &);
virtual bool fromXml(QDomElement &, QHash<int, Terminal *> &, bool = false);
virtual QDomElement toXml(QDomDocument &) const;
QUuid uuid() const;
int orientation() const;
//METHODS related to texts
void addDynamicTextItem(DynamicElementTextItem *deti = nullptr);
void removeDynamicTextItem(DynamicElementTextItem *deti);
QList<DynamicElementTextItem *> dynamicTextItems() const;
ElementTextItemGroup *addTextGroup(const QString &name);
void addTextGroup(ElementTextItemGroup *group);
void removeTextGroup(ElementTextItemGroup *group);
ElementTextItemGroup *textGroup(const QString &name) const;
QList<ElementTextItemGroup *> textGroups() const;
bool addTextToGroup(
DynamicElementTextItem *text,
ElementTextItemGroup *group);
bool removeTextFromGroup(
DynamicElementTextItem *text,
ElementTextItemGroup *group);
//METHODS related to texts
void addDynamicTextItem(DynamicElementTextItem *deti = nullptr);
void removeDynamicTextItem(DynamicElementTextItem *deti);
QList<DynamicElementTextItem *> dynamicTextItems() const;
ElementTextItemGroup *addTextGroup(const QString &name);
void addTextGroup(ElementTextItemGroup *group);
void removeTextGroup(ElementTextItemGroup *group);
ElementTextItemGroup *textGroup(const QString &name) const;
QList<ElementTextItemGroup *> textGroups() const;
bool addTextToGroup(
DynamicElementTextItem *text,
ElementTextItemGroup *group);
bool removeTextFromGroup(
DynamicElementTextItem *text,
ElementTextItemGroup *group);
//METHODS related to linked element
bool isFree() const;
virtual void linkToElement(Element *) {}
virtual void unlinkAllElements() {}
virtual void unlinkElement(Element *) {}
virtual void initLink(QETProject *);
QList<Element *> linkedElements ();
virtual kind linkType() const {return m_link_type;} // return the linkable type
QString linkTypeToString() const;
void newUuid() {m_uuid = QUuid::createUuid();} //create new uuid for this element
//METHODS related to linked element
bool isFree() const;
virtual void linkToElement(Element *) {}
virtual void unlinkAllElements() {}
virtual void unlinkElement(Element *) {}
virtual void initLink(QETProject *);
QList<Element *> linkedElements ();
virtual kind linkType() const {return m_link_type;} // return the linkable type
QString linkTypeToString() const;
void newUuid() {m_uuid = QUuid::createUuid();} //create new uuid for this element
protected:
void drawAxes(QPainter *, const QStyleOptionGraphicsItem *);
void setSize(int, int);
protected:
void drawAxes(QPainter *, const QStyleOptionGraphicsItem *);
void setSize(int, int);
private:
void drawSelection(
QPainter *,
const QStyleOptionGraphicsItem *);
void drawHighlight(
QPainter *,
const QStyleOptionGraphicsItem *);
bool buildFromXml(const QDomElement &, int * = nullptr);
bool parseElement(const QDomElement &dom);
bool parseInput(const QDomElement &dom_element);
DynamicElementTextItem *parseDynamicText(
const QDomElement &dom_element);
Terminal *parseTerminal(const QDomElement &dom_element);
private:
void drawSelection(
QPainter *,
const QStyleOptionGraphicsItem *);
void drawHighlight(
QPainter *,
const QStyleOptionGraphicsItem *);
bool buildFromXml(const QDomElement &, int * = nullptr);
bool parseElement(const QDomElement &dom);
bool parseInput(const QDomElement &dom_element);
DynamicElementTextItem *parseDynamicText(
const QDomElement &dom_element);
Terminal *parseTerminal(const QDomElement &dom_element);
//Reimplemented from QGraphicsItem
public:
void paint(
QPainter *,
const QStyleOptionGraphicsItem *,
QWidget *) override;
QRectF boundingRect() const override;
protected:
void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
void mouseReleaseEvent(
QGraphicsSceneMouseEvent *event) override;
void hoverEnterEvent(QGraphicsSceneHoverEvent *) override;
void hoverLeaveEvent(QGraphicsSceneHoverEvent *) override;
//Reimplemented from QGraphicsItem
public:
void paint(
QPainter *,
const QStyleOptionGraphicsItem *,
QWidget *) override;
QRectF boundingRect() const override;
protected:
void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
void mouseReleaseEvent(
QGraphicsSceneMouseEvent *event) override;
void hoverEnterEvent(QGraphicsSceneHoverEvent *) override;
void hoverLeaveEvent(QGraphicsSceneHoverEvent *) override;
protected:
// m_converted_text_from_description,
// when a element is created from his description,
// the old element text item (tagged as 'input' in the xml)
// are converted to dynamic text field,
// the QPointF is the original position of the text item,
// because the origin transformation point of text item
// and dynamic text item are not the same,
// so we must to keep a track of this value,
// to be use in the function element::fromXml
QHash <DynamicElementTextItem *, QPointF>
m_converted_text_from_xml_description;
protected:
// m_converted_text_from_description,
// when a element is created from his description,
// the old element text item (tagged as 'input' in the xml)
// are converted to dynamic text field,
// the QPointF is the original position of the text item,
// because the origin transformation point of text item
// and dynamic text item are not the same,
// so we must to keep a track of this value,
// to be use in the function element::fromXml
QHash <DynamicElementTextItem *, QPointF>
m_converted_text_from_xml_description;
//ATTRIBUTES related to linked element
QList <Element *> connected_elements;
QList <QUuid> tmp_uuids_link;
QUuid m_uuid;
kind m_link_type = Element::Simple;
//ATTRIBUTES related to linked element
QList <Element *> connected_elements;
QList <QUuid> tmp_uuids_link;
QUuid m_uuid;
kind m_link_type = Element::Simple;
//ATTRIBUTES related to informations
DiagramContext m_element_informations, m_kind_informations;
autonum::sequentialNumbers m_autoNum_seq;
bool m_freeze_label = false;
QString m_F_str;
//ATTRIBUTES related to informations
DiagramContext m_element_informations, m_kind_informations;
autonum::sequentialNumbers m_autoNum_seq;
bool m_freeze_label = false;
QString m_F_str;
ElementsLocation m_location;
NamesList m_names;
QList <Terminal *> m_terminals;
const QPicture m_picture;
const QPicture m_low_zoom_picture;
ElementsLocation m_location;
NamesList m_names;
QList <Terminal *> m_terminals;
const QPicture m_picture;
const QPicture m_low_zoom_picture;
private:
bool m_must_highlight = false;
QSize dimensions;
QPoint hotspot_coord;
bool m_mouse_over = false;
QString m_prefix;
QList <DynamicElementTextItem *> m_dynamic_text_list;
QList <ElementTextItemGroup *> m_texts_group;
private:
bool m_must_highlight = false;
QSize dimensions;
QPoint hotspot_coord;
bool m_mouse_over = false;
QString m_prefix;
QList <DynamicElementTextItem *> m_dynamic_text_list;
QList <ElementTextItemGroup *> m_texts_group;
};
@@ -240,40 +240,40 @@ bool comparPos(const Element * elmt1, const Element * elmt2);
inline bool Element::isFree() const
{
return (connected_elements.isEmpty());
return (connected_elements.isEmpty());
}
/**
Indicate the current orientation of this element
O = 0°
1 = 90°
2 = 180°
3 = 270°
@return the current orientation of this element
Indicate the current orientation of this element
O = 0°
1 = 90°
2 = 180°
3 = 270°
@return the current orientation of this element
*/
inline int Element::orientation() const
{
return(QET::correctAngle(rotation())/90);
return(QET::correctAngle(rotation())/90);
}
/**
@brief Element::uuid
@return the uuid of this element
@brief Element::uuid
@return the uuid of this element
*/
inline QUuid Element::uuid() const
{return m_uuid;}
/**
@brief Element::linkedElements
@return the list of linked elements, the list is sorted by position
@brief Element::linkedElements
@return the list of linked elements, the list is sorted by position
*/
inline QList <Element *> Element::linkedElements()
{
std::sort(
connected_elements.begin(),
connected_elements.end(),
comparPos);
return connected_elements;
std::sort(
connected_elements.begin(),
connected_elements.end(),
comparPos);
return connected_elements;
}
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ELEMENTTEXTITEMGROUP_H
#define ELEMENTTEXTITEMGROUP_H
@@ -28,98 +28,98 @@ class Diagram;
class CrossRefItem;
/**
@brief The ElementTextItemGroup class
This class represent a group of element text
Texts in the group can be aligned left / center /right
@brief The ElementTextItemGroup class
This class represent a group of element text
Texts in the group can be aligned left / center /right
*/
class ElementTextItemGroup : public QObject, public QGraphicsItemGroup // TODO: derive from PropertiesInterface
{
Q_OBJECT
Q_OBJECT
Q_PROPERTY(QPointF pos READ pos WRITE setPos)
Q_PROPERTY(qreal rotation READ rotation WRITE setRotation NOTIFY rotationChanged)
Q_PROPERTY(int verticalAdjustment READ verticalAdjustment WRITE setVerticalAdjustment NOTIFY verticalAdjustmentChanged)
Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment NOTIFY alignmentChanged)
Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)
Q_PROPERTY(bool holdToBottomPage READ holdToBottomPage WRITE setHoldToBottomPage NOTIFY holdToBottomPageChanged)
Q_PROPERTY(bool frame READ frame WRITE setFrame NOTIFY frameChanged)
Q_PROPERTY(QPointF pos READ pos WRITE setPos)
Q_PROPERTY(qreal rotation READ rotation WRITE setRotation NOTIFY rotationChanged)
Q_PROPERTY(int verticalAdjustment READ verticalAdjustment WRITE setVerticalAdjustment NOTIFY verticalAdjustmentChanged)
Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment NOTIFY alignmentChanged)
Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)
Q_PROPERTY(bool holdToBottomPage READ holdToBottomPage WRITE setHoldToBottomPage NOTIFY holdToBottomPageChanged)
Q_PROPERTY(bool frame READ frame WRITE setFrame NOTIFY frameChanged)
public:
signals:
void rotationChanged(qreal);
void verticalAdjustmentChanged(int);
void alignmentChanged(Qt::Alignment);
void nameChanged(QString);
void holdToBottomPageChanged(bool);
void xChanged();
void yChanged();
void frameChanged(bool frame);
public:
signals:
void rotationChanged(qreal);
void verticalAdjustmentChanged(int);
void alignmentChanged(Qt::Alignment);
void nameChanged(QString);
void holdToBottomPageChanged(bool);
void xChanged();
void yChanged();
void frameChanged(bool frame);
public:
ElementTextItemGroup(const QString &name, Element *parent);
~ElementTextItemGroup() override;
void addToGroup(QGraphicsItem *item);
void removeFromGroup(QGraphicsItem *item);
void blockAlignmentUpdate(bool block);
public:
ElementTextItemGroup(const QString &name, Element *parent);
~ElementTextItemGroup() override;
void addToGroup(QGraphicsItem *item);
void removeFromGroup(QGraphicsItem *item);
void blockAlignmentUpdate(bool block);
void setAlignment(Qt::Alignment alignement);
Qt::Alignment alignment() const;
void updateAlignment();
int verticalAdjustment() const {return m_vertical_adjustment;}
void setVerticalAdjustment(int v);
void setName(QString name);
QString name() const {return m_name;}
void setHoldToBottomPage(bool hold);
bool holdToBottomPage() const {return m_hold_to_bottom_of_page;}
void setFrame(const bool frame);
bool frame() const;
QList<DynamicElementTextItem *> texts() const;
Diagram *diagram() const;
Element *parentElement() const;
void setAlignment(Qt::Alignment alignement);
Qt::Alignment alignment() const;
void updateAlignment();
int verticalAdjustment() const {return m_vertical_adjustment;}
void setVerticalAdjustment(int v);
void setName(QString name);
QString name() const {return m_name;}
void setHoldToBottomPage(bool hold);
bool holdToBottomPage() const {return m_hold_to_bottom_of_page;}
void setFrame(const bool frame);
bool frame() const;
QList<DynamicElementTextItem *> texts() const;
Diagram *diagram() const;
Element *parentElement() const;
QDomElement toXml(QDomDocument &dom_document) const;
void fromXml(QDomElement &dom_element);
static QString xmlTaggName() {return QString("texts_group");}
QDomElement toXml(QDomDocument &dom_document) const;
void fromXml(QDomElement &dom_element);
static QString xmlTaggName() {return QString("texts_group");}
void paint(QPainter *painter,
const QStyleOptionGraphicsItem *option,
QWidget *widget) override;
QRectF boundingRect() const override;
void setRotation(qreal angle);
void setPos(const QPointF &pos);
void setPos(qreal x, qreal y);
void paint(QPainter *painter,
const QStyleOptionGraphicsItem *option,
QWidget *widget) override;
QRectF boundingRect() const override;
void setRotation(qreal angle);
void setPos(const QPointF &pos);
void setPos(qreal x, qreal y);
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
void mouseReleaseEvent(
QGraphicsSceneMouseEvent *event) override;
void mouseDoubleClickEvent(
QGraphicsSceneMouseEvent *event) override;
void keyPressEvent(QKeyEvent *event) override;
void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override;
void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override;
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
void mouseReleaseEvent(
QGraphicsSceneMouseEvent *event) override;
void mouseDoubleClickEvent(
QGraphicsSceneMouseEvent *event) override;
void keyPressEvent(QKeyEvent *event) override;
void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override;
void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override;
private:
void updateXref();
void adjustSlaveXrefPos();
void autoPos();
private:
void updateXref();
void adjustSlaveXrefPos();
void autoPos();
private:
Qt::Alignment m_alignment = Qt::AlignJustify;
QString m_name;
bool m_first_move = true,
m_hold_to_bottom_of_page = false,
m_block_alignment_update = false,
m_frame = false;
QPointF m_initial_position{QPointF(0,0)};
int m_vertical_adjustment = 0;
CrossRefItem *m_Xref_item = nullptr;
Element *m_parent_element = nullptr;
QList<QMetaObject::Connection> m_update_slave_Xref_connection;
QGraphicsTextItem *m_slave_Xref_item = nullptr;
QMetaObject::Connection m_XrefChanged_timer,
m_linked_changed_timer;
private:
Qt::Alignment m_alignment = Qt::AlignJustify;
QString m_name;
bool m_first_move = true,
m_hold_to_bottom_of_page = false,
m_block_alignment_update = false,
m_frame = false;
QPointF m_initial_position{QPointF(0,0)};
int m_vertical_adjustment = 0;
CrossRefItem *m_Xref_item = nullptr;
Element *m_parent_element = nullptr;
QList<QMetaObject::Connection> m_update_slave_Xref_connection;
QGraphicsTextItem *m_slave_Xref_item = nullptr;
QMetaObject::Connection m_XrefChanged_timer,
m_linked_changed_timer;
};
#endif // ELEMENTTEXTITEMGROUP_H

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#include "independenttextitem.h"
#include "qet.h"
@@ -25,24 +25,24 @@
#include <QSettings>
/**
Constructeur
@param parent_diagram Le schema auquel est rattache le champ de texte
Constructeur
@param parent_diagram Le schema auquel est rattache le champ de texte
*/
IndependentTextItem::IndependentTextItem() :
DiagramTextItem(nullptr)
DiagramTextItem(nullptr)
{
setFont(QETApp::indiTextsItemFont());
QSettings settings;
setRotation(settings.value("diagrameditor/independent_text_rotation", 0).toInt());
setFont(QETApp::indiTextsItemFont());
QSettings settings;
setRotation(settings.value("diagrameditor/independent_text_rotation", 0).toInt());
}
/**
@brief IndependentTextItem::IndependentTextItem
Constructeur
@param text Le texte affiche par le champ de texte
@brief IndependentTextItem::IndependentTextItem
Constructeur
@param text Le texte affiche par le champ de texte
*/
IndependentTextItem::IndependentTextItem(const QString &text) :
DiagramTextItem(text, nullptr)
DiagramTextItem(text, nullptr)
{}
/// Destructeur
@@ -52,43 +52,43 @@ IndependentTextItem::~IndependentTextItem()
// TODO: inherit from PropertiesInterface
/**
Permet de lire le texte a mettre dans le champ a partir d'un element XML.
Cette methode se base sur la position du champ pour assigner ou non la
valeur a ce champ.
@param e L'element XML representant le champ de texte
Permet de lire le texte a mettre dans le champ a partir d'un element XML.
Cette methode se base sur la position du champ pour assigner ou non la
valeur a ce champ.
@param e L'element XML representant le champ de texte
*/
void IndependentTextItem::fromXml(const QDomElement &e) {
setPos(e.attribute("x").toDouble(), e.attribute("y").toDouble());
setHtml(e.attribute("text"));
setRotation(e.attribute("rotation").toDouble());
if (e.hasAttribute("font"))
{
QFont font;
font.fromString(e.attribute("font"));
setFont(font);
}
setPos(e.attribute("x").toDouble(), e.attribute("y").toDouble());
setHtml(e.attribute("text"));
setRotation(e.attribute("rotation").toDouble());
if (e.hasAttribute("font"))
{
QFont font;
font.fromString(e.attribute("font"));
setFont(font);
}
}
/**
@param document Le document XML a utiliser
@return L'element XML representant ce champ de texte
@param document Le document XML a utiliser
@return L'element XML representant ce champ de texte
*/
QDomElement IndependentTextItem::toXml(QDomDocument &document) const
{
QDomElement result = document.createElement("input");
result.setAttribute("x", QString("%1").arg(pos().x()));
result.setAttribute("y", QString("%1").arg(pos().y()));
result.setAttribute("text", toHtml());
result.setAttribute("rotation", QString::number(QET::correctAngle(rotation())));
result.setAttribute("font", font().toString());
QDomElement result = document.createElement("input");
result.setAttribute("x", QString("%1").arg(pos().x()));
result.setAttribute("y", QString("%1").arg(pos().y()));
result.setAttribute("text", toHtml());
result.setAttribute("rotation", QString::number(QET::correctAngle(rotation())));
result.setAttribute("font", font().toString());
return(result);
return(result);
}
void IndependentTextItem::focusOutEvent(QFocusEvent *event)
{
DiagramTextItem::focusOutEvent(event);
if (diagram() && (m_previous_html_text != this->toHtml())) {
diagram()->undoStack().push(new ChangeDiagramTextCommand(this, m_previous_html_text, this->toHtml()));
}
DiagramTextItem::focusOutEvent(event);
if (diagram() && (m_previous_html_text != this->toHtml())) {
diagram()->undoStack().push(new ChangeDiagramTextCommand(this, m_previous_html_text, this->toHtml()));
}
}

View File

@@ -1,153 +1,153 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#include "qetgraphicsitem.h"
#include "diagram.h"
/**
@brief QetGraphicsItem::QetGraphicsItem
Default constructor
@param parent : Parent Item
@brief QetGraphicsItem::QetGraphicsItem
Default constructor
@param parent : Parent Item
*/
QetGraphicsItem::QetGraphicsItem(QGraphicsItem *parent):
QGraphicsObject(parent)
QGraphicsObject(parent)
{}
QetGraphicsItem::~QetGraphicsItem()
{}
/**
@brief QetGraphicsItem::diagram
@brief QetGraphicsItem::diagram
*return the diagram of this item
*/
Diagram* QetGraphicsItem::diagram() const{
return(qobject_cast<Diagram *>(scene()));
return(qobject_cast<Diagram *>(scene()));
}
/**
@brief QetGraphicsItem::setPos
@brief QetGraphicsItem::setPos
*set the position of the item to p
@param p the new position of item
@param p the new position of item
*/
void QetGraphicsItem::setPos(const QPointF &p) {
QPointF pp = Diagram::snapToGrid(p);
if (pp == pos() || !is_movable_)
return;
QGraphicsItem::setPos(pp);
QPointF pp = Diagram::snapToGrid(p);
if (pp == pos() || !is_movable_)
return;
QGraphicsItem::setPos(pp);
}
/**
@brief QetGraphicsItem::setPos
@brief QetGraphicsItem::setPos
*set the position of the item
@param x new abscisse of item
@param y new ordonne of item
@param x new abscisse of item
@param y new ordonne of item
*/
void QetGraphicsItem::setPos(qreal x, qreal y) {
setPos(QPointF(x, y));
setPos(QPointF(x, y));
}
/**
@brief QetGraphicsItem::state
@return the current state of this item
@brief QetGraphicsItem::state
@return the current state of this item
*/
QET::GraphicsItemState QetGraphicsItem::state() const
{
return m_state;
return m_state;
}
/**
@brief QetGraphicsItem::mousePressEvent
@brief QetGraphicsItem::mousePressEvent
*handle the mouse click
@param event
@param event
*/
void QetGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
m_first_move = true;
if (event->modifiers() & Qt::ControlModifier) {
setSelected(!isSelected());
}
}
if (event->button() == Qt::LeftButton)
{
m_first_move = true;
if (event->modifiers() & Qt::ControlModifier) {
setSelected(!isSelected());
}
}
QGraphicsItem::mousePressEvent(event);
QGraphicsItem::mousePressEvent(event);
}
/**
@brief QetGraphicsItem::mouseDoubleClickEvent
@brief QetGraphicsItem::mouseDoubleClickEvent
*handle the mouse double click
@param event
@param event
*/
void QetGraphicsItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
editProperty();
event->accept();
editProperty();
event->accept();
}
/**
@brief QetGraphicsItem::mouseMoveEvent
@brief QetGraphicsItem::mouseMoveEvent
*handle mouse movement
@param event
@param event
*/
void QetGraphicsItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
if (isSelected() && event->buttons() & Qt::LeftButton)
{
//Item is moving
if(diagram() && m_first_move) {
//It's the first movement, we signal it to parent diagram
diagram()->elementsMover().beginMovement(diagram(), this);
}
if (isSelected() && event->buttons() & Qt::LeftButton)
{
//Item is moving
if(diagram() && m_first_move) {
//It's the first movement, we signal it to parent diagram
diagram()->elementsMover().beginMovement(diagram(), this);
}
//we apply the mouse movement
QPointF old_pos = pos();
if (m_first_move) {
m_mouse_to_origin_movement = old_pos - event -> buttonDownScenePos(Qt::LeftButton);
}
QPointF expected_pos = event->scenePos() + m_mouse_to_origin_movement;
setPos(expected_pos); // setPos() will snap the expected position to the grid
//we apply the mouse movement
QPointF old_pos = pos();
if (m_first_move) {
m_mouse_to_origin_movement = old_pos - event -> buttonDownScenePos(Qt::LeftButton);
}
QPointF expected_pos = event->scenePos() + m_mouse_to_origin_movement;
setPos(expected_pos); // setPos() will snap the expected position to the grid
//we calcul the real movement apply by setPos()
QPointF effective_movement = pos() - old_pos;
if (diagram()) {
//we signal the real movement apply to diagram,
//who he apply to other selected item
diagram()->elementsMover().continueMovement(effective_movement);
}
event->accept();
}
else {
event->ignore();
}
//we calcul the real movement apply by setPos()
QPointF effective_movement = pos() - old_pos;
if (diagram()) {
//we signal the real movement apply to diagram,
//who he apply to other selected item
diagram()->elementsMover().continueMovement(effective_movement);
}
event->accept();
}
else {
event->ignore();
}
if (m_first_move) {
m_first_move = false;
}
if (m_first_move) {
m_first_move = false;
}
}
/**
@brief QetGraphicsItem::mouseReleaseEvent
handle mouse release click
@param event
@brief QetGraphicsItem::mouseReleaseEvent
handle mouse release click
@param event
*/
void QetGraphicsItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
if (diagram()) {
diagram()->elementsMover().endMovement();
event->accept();
}
if (diagram()) {
diagram()->elementsMover().endMovement();
event->accept();
}
}

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef QETGRAPHICSITEM_H
#define QETGRAPHICSITEM_H
@@ -25,41 +25,41 @@ class Diagram;
class QetGraphicsItem : public QGraphicsObject
{
Q_OBJECT
Q_OBJECT
public:
//constructor destructor
QetGraphicsItem(QGraphicsItem *parent = nullptr);
~QetGraphicsItem() override = 0;
public:
//constructor destructor
QetGraphicsItem(QGraphicsItem *parent = nullptr);
~QetGraphicsItem() override = 0;
//public methode
Diagram *diagram () const;
virtual void setPos (const QPointF &p);
virtual void setPos (qreal x, qreal y);
//public methode
Diagram *diagram () const;
virtual void setPos (const QPointF &p);
virtual void setPos (qreal x, qreal y);
virtual bool isMovable () const
virtual bool isMovable () const
{return is_movable_;}
virtual void setMovable (bool movable) { is_movable_ = movable;}
virtual void setMovable (bool movable) { is_movable_ = movable;}
virtual void editProperty () {}
virtual QString name ()const
virtual void editProperty () {}
virtual QString name ()const
{return QString("");}
QET::GraphicsItemState state() const;
QET::GraphicsItemState state() const;
//protected method
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override;
void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;
//protected method
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override;
void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;
protected:
bool is_movable_{true};
bool m_first_move{true};
bool snap_to_grid_{true};
QPointF m_mouse_to_origin_movement{QPointF(0,0)};
QET::GraphicsItemState m_state = QET:: GIOK;
protected:
bool is_movable_{true};
bool m_first_move{true};
bool snap_to_grid_{true};
QPointF m_mouse_to_origin_movement{QPointF(0,0)};
QET::GraphicsItemState m_state = QET:: GIOK;
};

File diff suppressed because it is too large Load Diff

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#include "slaveelement.h"
#include "diagramposition.h"
@@ -22,79 +22,79 @@
#include "dynamicelementtextitem.h"
/**
@brief SlaveElement::SlaveElement
Default constructor
@param location location of xml definition
@param qgi parent QGraphicItem
@param state int used to know if the creation of element have error
@brief SlaveElement::SlaveElement
Default constructor
@param location location of xml definition
@param qgi parent QGraphicItem
@param state int used to know if the creation of element have error
*/
SlaveElement::SlaveElement(const ElementsLocation &location,
QGraphicsItem *qgi,
int *state) :
Element(location, qgi, state, Element::Slave)
QGraphicsItem *qgi,
int *state) :
Element(location, qgi, state, Element::Slave)
{
m_xref_item = nullptr;
m_xref_item = nullptr;
}
/**
@brief SlaveElement::~SlaveElement
default destructor
@brief SlaveElement::~SlaveElement
default destructor
*/
SlaveElement::~SlaveElement()
{
unlinkAllElements();
unlinkAllElements();
}
/**
@brief SlaveElement::linkToElement
Link this slave to another element
For this class element must be a master
@param elmt
@brief SlaveElement::linkToElement
Link this slave to another element
For this class element must be a master
@param elmt
*/
void SlaveElement::linkToElement(Element *elmt)
{
// check if element is master and if isn't already linked
if (elmt->linkType() == Master && !connected_elements.contains(elmt))
{
if(!isFree())
unlinkAllElements();
// check if element is master and if isn't already linked
if (elmt->linkType() == Master && !connected_elements.contains(elmt))
{
if(!isFree())
unlinkAllElements();
connected_elements << elmt;
connected_elements << elmt;
elmt -> linkToElement(this);
emit linkedElementChanged();
}
elmt -> linkToElement(this);
emit linkedElementChanged();
}
}
/**
@brief SlaveElement::unlinkAllElements
Unlink all of the element in the QList connected_elements
@brief SlaveElement::unlinkAllElements
Unlink all of the element in the QList connected_elements
*/
void SlaveElement::unlinkAllElements()
{
// if this element is free no need to do something
if (!isFree())
{
foreach(Element *elmt, connected_elements)
unlinkElement(elmt);
emit linkedElementChanged();
}
// if this element is free no need to do something
if (!isFree())
{
foreach(Element *elmt, connected_elements)
unlinkElement(elmt);
emit linkedElementChanged();
}
}
/**
@brief SlaveElement::unlinkElement
Unlink the given elmt in parametre
@param elmt
@brief SlaveElement::unlinkElement
Unlink the given elmt in parametre
@param elmt
*/
void SlaveElement::unlinkElement(Element *elmt)
{
//Ensure elmt is linked to this element
if (connected_elements.contains(elmt))
{
connected_elements.removeOne(elmt);
//Ensure elmt is linked to this element
if (connected_elements.contains(elmt))
{
connected_elements.removeOne(elmt);
elmt -> unlinkElement (this) ;
elmt -> setHighlighted (false);
emit linkedElementChanged();
}
elmt -> unlinkElement (this) ;
elmt -> setHighlighted (false);
emit linkedElementChanged();
}
}

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SLAVEELEMENT_H
#define SLAVEELEMENT_H
@@ -23,19 +23,19 @@
class SlaveElement : public Element
{
Q_OBJECT
public:
explicit SlaveElement (
const ElementsLocation &,
QGraphicsItem * = nullptr,
int * = nullptr);
~SlaveElement() override;
void linkToElement(Element *elmt) override;
void unlinkAllElements() override;
void unlinkElement(Element *elmt) override;
Q_OBJECT
public:
explicit SlaveElement (
const ElementsLocation &,
QGraphicsItem * = nullptr,
int * = nullptr);
~SlaveElement() override;
void linkToElement(Element *elmt) override;
void unlinkAllElements() override;
void unlinkElement(Element *elmt) override;
private:
QGraphicsTextItem *m_xref_item{nullptr};
private:
QGraphicsTextItem *m_xref_item{nullptr};
};
#endif // SLAVEELEMENT_H

File diff suppressed because it is too large Load Diff

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TERMINAL_H
#define TERMINAL_H
@@ -28,165 +28,165 @@ class Element;
class TerminalData;
/**
@brief The Terminal class
This class represents a terminal of an electrical element, i.e. a possible
plug point for conductors.
This class handles all mouse events for connecting conductors
@brief The Terminal class
This class represents a terminal of an electrical element, i.e. a possible
plug point for conductors.
This class handles all mouse events for connecting conductors
*/
class Terminal : public QGraphicsObject, public PropertiesInterface
{
Q_OBJECT
Q_OBJECT
signals:
void conductorWasAdded(Conductor *conductor);
void conductorWasRemoved(Conductor *conductor);
signals:
void conductorWasAdded(Conductor *conductor);
void conductorWasRemoved(Conductor *conductor);
// constructors, destructor
public:
Terminal(QPointF, Qet::Orientation, Element * = nullptr);
Terminal(qreal, qreal, Qet::Orientation, Element * = nullptr);
Terminal(TerminalData* data, Element *e = nullptr);
Terminal(QPointF, Qet::Orientation, QString number,
QString name, bool hiddenName, Element * = nullptr);
~Terminal() override;
// constructors, destructor
public:
Terminal(QPointF, Qet::Orientation, Element * = nullptr);
Terminal(qreal, qreal, Qet::Orientation, Element * = nullptr);
Terminal(TerminalData* data, Element *e = nullptr);
Terminal(QPointF, Qet::Orientation, QString number,
QString name, bool hiddenName, Element * = nullptr);
~Terminal() override;
private:
Terminal(const Terminal &);
private:
Terminal(const Terminal &);
// methods
public:
/**
@brief type
Enable the use of qgraphicsitem_cast to safely
cast a QGraphicsItem into a Terminal
@return the QGraphicsItem type
*/
int type() const override { return Type; }
// methods
public:
/**
@brief type
Enable the use of qgraphicsitem_cast to safely
cast a QGraphicsItem into a Terminal
@return the QGraphicsItem type
*/
int type() const override { return Type; }
void paint(
QPainter *painter,
const QStyleOptionGraphicsItem *,
QWidget *) override;
void drawHelpLine (bool draw = true);
QLineF HelpLine () const;
QRectF boundingRect () const override;
void paint(
QPainter *painter,
const QStyleOptionGraphicsItem *,
QWidget *) override;
void drawHelpLine (bool draw = true);
QLineF HelpLine () const;
QRectF boundingRect () const override;
// methods to manage conductors attached to the terminal
Terminal* alignedWithTerminal () const;
bool addConductor (Conductor *conductor);
void removeConductor (Conductor *conductor);
int conductorsCount () const;
Diagram *diagram () const;
Element *parentElement () const;
QUuid uuid () const;
int ID() const;
QPointF dockPos();
QPointF originPos();
// methods to manage conductors attached to the terminal
Terminal* alignedWithTerminal () const;
bool addConductor (Conductor *conductor);
void removeConductor (Conductor *conductor);
int conductorsCount () const;
Diagram *diagram () const;
Element *parentElement () const;
QUuid uuid () const;
int ID() const;
QPointF dockPos();
QPointF originPos();
QList<Conductor *> conductors() const;
Qet::Orientation orientation() const;
QPointF dockConductor() const;
QString number() const;
QString name() const;
void setNumber(QString number);
void setName(QString name, bool hiddenName);
void updateConductor();
bool isLinkedTo(Terminal *);
bool canBeLinkedTo(Terminal *);
void setID(int id);
QList<Conductor *> conductors() const;
Qet::Orientation orientation() const;
QPointF dockConductor() const;
QString number() const;
QString name() const;
void setNumber(QString number);
void setName(QString name, bool hiddenName);
void updateConductor();
bool isLinkedTo(Terminal *);
bool canBeLinkedTo(Terminal *);
void setID(int id);
// methods related to XML import/export
static bool valideXml(const QDomElement &);
bool fromXml (const QDomElement &) override;
QDomElement toXml (QDomDocument &) const override;
// methods related to XML import/export
static bool valideXml(const QDomElement &);
bool fromXml (const QDomElement &) override;
QDomElement toXml (QDomDocument &) const override;
protected:
// methods related to events management
void hoverEnterEvent (QGraphicsSceneHoverEvent *) override;
void hoverMoveEvent (QGraphicsSceneHoverEvent *) override;
void hoverLeaveEvent (QGraphicsSceneHoverEvent *) override;
void mousePressEvent (QGraphicsSceneMouseEvent *) override;
void mouseMoveEvent (QGraphicsSceneMouseEvent *) override;
void mouseReleaseEvent(QGraphicsSceneMouseEvent *) override;
protected:
// methods related to events management
void hoverEnterEvent (QGraphicsSceneHoverEvent *) override;
void hoverMoveEvent (QGraphicsSceneHoverEvent *) override;
void hoverLeaveEvent (QGraphicsSceneHoverEvent *) override;
void mousePressEvent (QGraphicsSceneMouseEvent *) override;
void mouseMoveEvent (QGraphicsSceneMouseEvent *) override;
void mouseReleaseEvent(QGraphicsSceneMouseEvent *) override;
// attributes
public:
enum { Type = UserType + 1002 };
// attributes
public:
enum { Type = UserType + 1002 };
static const qreal terminalSize;
static const qreal Z;
// Various static colors used for hover effects
// The assignement is in the cpp file
/// default color
static QColor neutralColor;
/// color for legal actions
static QColor allowedColor;
/// color for allowed but fuzzy or not recommended actions
static QColor warningColor;
/// color for forbidden actions
static QColor forbiddenColor;
static const qreal terminalSize;
static const qreal Z;
// Various static colors used for hover effects
// The assignement is in the cpp file
/// default color
static QColor neutralColor;
/// color for legal actions
static QColor allowedColor;
/// color for allowed but fuzzy or not recommended actions
static QColor warningColor;
/// color for forbidden actions
static QColor forbiddenColor;
private:
bool m_draw_help_line{false};
QGraphicsLineItem *m_help_line{nullptr};
QGraphicsLineItem *m_help_line_a{nullptr};
private:
bool m_draw_help_line{false};
QGraphicsLineItem *m_help_line{nullptr};
QGraphicsLineItem *m_help_line_a{nullptr};
TerminalData* d;
TerminalData* d;
/// Parent electrical element
Element *parent_element_{nullptr};
public:
/// docking point for parent element
QPointF dock_elmt_;
private:
/// List of conductors attached to the terminal
QList<Conductor *> conductors_;
/**
Pointer to a rectangle representing the terminal bounding rect;
used to calculate the bounding rect once only;
used a pointer because boundingRect() is supposed to be const.
*/
QRectF *br_{nullptr};
/// Last terminal seen through an attached conductor
Terminal *previous_terminal_{nullptr};
/// Whether the mouse pointer is hovering the terminal
bool hovered_{false};
/// Color used for the hover effect
QColor hovered_color_{Terminal::hovered_color_};
/// Number of Terminal
QString number_terminal_;
bool name_terminal_hidden{true};
/// Parent electrical element
Element *parent_element_{nullptr};
public:
/// docking point for parent element
QPointF dock_elmt_;
private:
/// List of conductors attached to the terminal
QList<Conductor *> conductors_;
/**
Pointer to a rectangle representing the terminal bounding rect;
used to calculate the bounding rect once only;
used a pointer because boundingRect() is supposed to be const.
*/
QRectF *br_{nullptr};
/// Last terminal seen through an attached conductor
Terminal *previous_terminal_{nullptr};
/// Whether the mouse pointer is hovering the terminal
bool hovered_{false};
/// Color used for the hover effect
QColor hovered_color_{Terminal::hovered_color_};
/// Number of Terminal
QString number_terminal_;
bool name_terminal_hidden{true};
/// legacy id used by the conductor to find the terminal. From 0.8x on the uuid is used instead.
int m_id{-1};
/// legacy id used by the conductor to find the terminal. From 0.8x on the uuid is used instead.
int m_id{-1};
private:
void init(QString number, QString name, bool hiddenName);
void init(QPointF pf, Qet::Orientation o, QString number,
QString name, bool hiddenName);
private:
void init(QString number, QString name, bool hiddenName);
void init(QPointF pf, Qet::Orientation o, QString number,
QString name, bool hiddenName);
};
/**
@brief Terminal::conductorsCount
@return the number of conductors attached to the terminal.
@brief Terminal::conductorsCount
@return the number of conductors attached to the terminal.
*/
inline int Terminal::conductorsCount() const
{
return(conductors_.size());
return(conductors_.size());
}
/**
@brief Terminal::number
@return the number of terminal.
@brief Terminal::number
@return the number of terminal.
*/
inline QString Terminal::number() const
{
return(number_terminal_);
return(number_terminal_);
}
{
QList<Terminal *> relatedPotentialTerminal (const Terminal *terminal,
const bool all_diagram = true);
const bool all_diagram = true);
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -1,157 +1,157 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#include "helpercell.h"
/**
Constructor
@param parent Parent QGraphicsItem
Constructor
@param parent Parent QGraphicsItem
*/
HelperCell::HelperCell(QGraphicsItem *parent) :
QGraphicsObject(parent),
QGraphicsLayoutItem(),
background_color(Qt::white),
foreground_color(Qt::black),
label(),
orientation(Qt::Horizontal),
index(-1)
QGraphicsObject(parent),
QGraphicsLayoutItem(),
background_color(Qt::white),
foreground_color(Qt::black),
label(),
orientation(Qt::Horizontal),
index(-1)
{
setGraphicsItem(this);
setFlag(QGraphicsItem::ItemIsSelectable, false);
setGraphicsItem(this);
setFlag(QGraphicsItem::ItemIsSelectable, false);
}
/**
Destructor
Destructor
*/
HelperCell::~HelperCell()
{
}
/**
Ensure geometry changes are handled for both QGraphicsObject and
QGraphicsLayoutItem.
@param g New geometry
Ensure geometry changes are handled for both QGraphicsObject and
QGraphicsLayoutItem.
@param g New geometry
*/
void HelperCell::setGeometry(const QRectF &g) {
prepareGeometryChange();
QGraphicsLayoutItem::setGeometry(g);
setPos(g.topLeft());
prepareGeometryChange();
QGraphicsLayoutItem::setGeometry(g);
setPos(g.topLeft());
}
/**
@param which Size hint to be modified
@param constraint New value for the size hint
@return the size hint for \a which using the width or height of \a constraint
@param which Size hint to be modified
@param constraint New value for the size hint
@return the size hint for \a which using the width or height of \a constraint
*/
QSizeF HelperCell::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const
{
Q_UNUSED(which);
return(constraint);
Q_UNUSED(which);
return(constraint);
}
/**
@return the bounding rect of this helper cell
@return the bounding rect of this helper cell
*/
QRectF HelperCell::boundingRect() const
{
return QRectF(QPointF(0,0), geometry().size());
return QRectF(QPointF(0,0), geometry().size());
}
/**
Handles the helper cell visual rendering
@param painter QPainter to be used for the rendering
@param option Rendering options
@param widget QWidget being painted, if any
Handles the helper cell visual rendering
@param painter QPainter to be used for the rendering
@param option Rendering options
@param widget QWidget being painted, if any
*/
void HelperCell::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
Q_UNUSED(option);
Q_UNUSED(widget);
Q_UNUSED(option);
Q_UNUSED(widget);
QRectF drawing_rectangle(QPointF(0, 0), geometry().size());
QRectF drawing_rectangle(QPointF(0, 0), geometry().size());
painter -> setPen(Qt::black);
painter -> setBrush(background_color);
painter -> drawRect(drawing_rectangle);
painter -> setPen(Qt::black);
painter -> setBrush(background_color);
painter -> drawRect(drawing_rectangle);
painter -> setPen(foreground_color);
painter -> drawText(drawing_rectangle, Qt::AlignHCenter | Qt::AlignVCenter, label);
painter -> setPen(foreground_color);
painter -> drawText(drawing_rectangle, Qt::AlignHCenter | Qt::AlignVCenter, label);
}
/**
@param type new type of this helper cell -- @see QET::TitleBlockColumnLength
@param type new type of this helper cell -- @see QET::TitleBlockColumnLength
*/
void HelperCell::setType(QET::TitleBlockColumnLength type) {
if (type == QET::Absolute) {
background_color = QColor("#C0FFFF");
foreground_color = Qt::black;
} else if (type == QET::RelativeToTotalLength) {
background_color = QColor("#FFA858");
foreground_color = Qt::black;
} else if (type == QET::RelativeToRemainingLength) {
background_color = QColor("#FFC0C0");
foreground_color = Qt::black;
}
if (type == QET::Absolute) {
background_color = QColor("#C0FFFF");
foreground_color = Qt::black;
} else if (type == QET::RelativeToTotalLength) {
background_color = QColor("#FFA858");
foreground_color = Qt::black;
} else if (type == QET::RelativeToRemainingLength) {
background_color = QColor("#FFC0C0");
foreground_color = Qt::black;
}
}
/**
Set the list of actions displayed by the context menu of this helper cell.
Set the list of actions displayed by the context menu of this helper cell.
*/
void HelperCell::setActions(const QList<QAction *> &actions) {
actions_ = actions;
actions_ = actions;
}
/**
@return the list of actions displayed by the context menu of this helper cell.
@return the list of actions displayed by the context menu of this helper cell.
*/
QList<QAction *> HelperCell::actions() const
{
return actions_;
return actions_;
}
/**
@param text New label displayed by this helper cell
@param set_as_tooltip If true, the text is also used as tooltip.
@param text New label displayed by this helper cell
@param set_as_tooltip If true, the text is also used as tooltip.
*/
void HelperCell::setLabel(const QString &text, bool set_as_tooltip) {
label = text;
if (set_as_tooltip) {
setToolTip(text);
}
label = text;
if (set_as_tooltip) {
setToolTip(text);
}
}
/**
Handle context menu events.
@param event Context menu event.
Handle context menu events.
@param event Context menu event.
*/
void HelperCell::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) {
if (actions_.isEmpty()) return;
if (actions_.isEmpty()) return;
QMenu context_menu;
foreach (QAction *action, actions_) {
context_menu.addAction(action);
}
emit(contextMenuTriggered(this));
context_menu.exec(event -> screenPos());
QMenu context_menu;
foreach (QAction *action, actions_) {
context_menu.addAction(action);
}
emit(contextMenuTriggered(this));
context_menu.exec(event -> screenPos());
}
/**
Handle double click events.
Handle double click events.
*/
void HelperCell::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *) {
emit(doubleClicked(this));
emit(doubleClicked(this));
}

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TITLEBLOCK_SLASH_HELPER_CELL_H
#define TITLEBLOCK_SLASH_HELPER_CELL_H
@@ -21,48 +21,48 @@
#include "qet.h"
/**
This class implements a helper widget for cells that indicate the length of
columns and rows.
This class implements a helper widget for cells that indicate the length of
columns and rows.
*/
class HelperCell : public QGraphicsObject, public QGraphicsLayoutItem {
Q_OBJECT
Q_INTERFACES(QGraphicsLayoutItem)
Q_OBJECT
Q_INTERFACES(QGraphicsLayoutItem)
// constructor, destructor
public:
HelperCell(QGraphicsItem * = nullptr);
~HelperCell() override;
private:
HelperCell(const HelperCell &);
// constructor, destructor
public:
HelperCell(QGraphicsItem * = nullptr);
~HelperCell() override;
private:
HelperCell(const HelperCell &);
// attributes
public:
QColor background_color{Qt::white}; ///< Background color when rendering this cell
QColor foreground_color{Qt::black}; ///< Text color when rendering this cell
QString label; ///< Label displayed in this cell
Qt::Orientation orientation{Qt::Horizontal}; ///< Orientation of this cell
int index{-1}; ///< Index of this cell
// attributes
public:
QColor background_color{Qt::white}; ///< Background color when rendering this cell
QColor foreground_color{Qt::black}; ///< Text color when rendering this cell
QString label; ///< Label displayed in this cell
Qt::Orientation orientation{Qt::Horizontal}; ///< Orientation of this cell
int index{-1}; ///< Index of this cell
// methods
public:
void setGeometry(const QRectF &) override;
QSizeF sizeHint(Qt::SizeHint, const QSizeF & = QSizeF()) const override;
QRectF boundingRect() const override;
void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget * = nullptr) override;
virtual void setType(QET::TitleBlockColumnLength);
virtual void setActions(const QList<QAction *> &);
virtual QList<QAction *> actions() const;
virtual void setLabel(const QString &text, bool = true);
// methods
public:
void setGeometry(const QRectF &) override;
QSizeF sizeHint(Qt::SizeHint, const QSizeF & = QSizeF()) const override;
QRectF boundingRect() const override;
void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget * = nullptr) override;
virtual void setType(QET::TitleBlockColumnLength);
virtual void setActions(const QList<QAction *> &);
virtual QList<QAction *> actions() const;
virtual void setLabel(const QString &text, bool = true);
protected:
void contextMenuEvent(QGraphicsSceneContextMenuEvent *) override;
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *) override;
protected:
void contextMenuEvent(QGraphicsSceneContextMenuEvent *) override;
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *) override;
signals:
void contextMenuTriggered(HelperCell *);
void doubleClicked(HelperCell *);
signals:
void contextMenuTriggered(HelperCell *);
void doubleClicked(HelperCell *);
private:
QList<QAction *> actions_; ///< List of actions displayed by the context menu
private:
QList<QAction *> actions_; ///< List of actions displayed by the context menu
};
#endif

View File

@@ -1,46 +1,46 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TITLEBLOCK_SLASH_SPLITTED_HELPER_CELL_H
#define TITLEBLOCK_SLASH_SPLITTED_HELPER_CELL_H
#include "helpercell.h"
/**
This class is a variant of HelperCell having the ability to display two
labels, with a split line between them.
This class is a variant of HelperCell having the ability to display two
labels, with a split line between them.
*/
class SplittedHelperCell : public HelperCell {
Q_OBJECT
public:
SplittedHelperCell(QGraphicsItem * = nullptr);
~SplittedHelperCell() override;
private:
SplittedHelperCell(const SplittedHelperCell &);
Q_OBJECT
public:
SplittedHelperCell(QGraphicsItem * = nullptr);
~SplittedHelperCell() override;
private:
SplittedHelperCell(const SplittedHelperCell &);
// methods
public:
void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget * = nullptr) override;
// methods
public:
void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget * = nullptr) override;
// attributes
// colors are set in the constructor
QColor split_background_color; ///< Background color on the split side
QColor split_foreground_color; ///< Text color on the split side
QString split_label; ///< Text displayed on the split side
int split_size; ///< Length of the split side
// attributes
// colors are set in the constructor
QColor split_background_color; ///< Background color on the split side
QColor split_foreground_color; ///< Text color on the split side
QString split_label; ///< Text displayed on the split side
int split_size; ///< Length of the split side
};
#endif

View File

@@ -1,252 +1,252 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#include "titleblockproperties.h"
#include "qet.h"
#include "qetapp.h"
/**
Constructeur. Initialise un objet TitleBlockProperties avec tous les champs
vides (date vide + useDate a UseDateValue).
Constructeur. Initialise un objet TitleBlockProperties avec tous les champs
vides (date vide + useDate a UseDateValue).
*/
TitleBlockProperties::TitleBlockProperties()
{
}
/**
Destructeur
Destructeur
*/
TitleBlockProperties::~TitleBlockProperties()
{
}
/**
@param ip autre conteneur TitleBlockProperties
@return true si ip et ce conteneur sont identiques, false sinon
@param ip autre conteneur TitleBlockProperties
@return true si ip et ce conteneur sont identiques, false sinon
*/
bool TitleBlockProperties::operator==(const TitleBlockProperties &ip) {
return(
ip.title == title &&\
ip.author == author &&\
ip.date == date &&\
ip.filename == filename &&\
ip.plant == plant &&\
ip.locmach == locmach &&\
ip.indexrev == indexrev &&\
ip.version == version &&\
ip.folio == folio &&\
ip.auto_page_num == auto_page_num &&\
ip.template_name == template_name &&\
ip.context == context &&\
ip.display_at == display_at &&\
ip.collection == collection
);
return(
ip.title == title &&\
ip.author == author &&\
ip.date == date &&\
ip.filename == filename &&\
ip.plant == plant &&\
ip.locmach == locmach &&\
ip.indexrev == indexrev &&\
ip.version == version &&\
ip.folio == folio &&\
ip.auto_page_num == auto_page_num &&\
ip.template_name == template_name &&\
ip.context == context &&\
ip.display_at == display_at &&\
ip.collection == collection
);
}
/**
@param ip autre conteneur TitleBlockProperties
@return false si ip et ce conteneur sont identiques, true sinon
@param ip autre conteneur TitleBlockProperties
@return false si ip et ce conteneur sont identiques, true sinon
*/
bool TitleBlockProperties::operator!=(const TitleBlockProperties &ip) {
return(!(*this == ip));
return(!(*this == ip));
}
/**
Exporte le cartouche sous formes d'attributs XML ajoutes a l'element e.
@param e Element XML auquel seront ajoutes des attributs
Exporte le cartouche sous formes d'attributs XML ajoutes a l'element e.
@param e Element XML auquel seront ajoutes des attributs
*/
void TitleBlockProperties::toXml(QDomElement &e) const
{
e.setAttribute("author", author);
e.setAttribute("title", title);
e.setAttribute("filename", filename);
e.setAttribute("plant", plant);
e.setAttribute("locmach", locmach);
e.setAttribute("indexrev",indexrev);
e.setAttribute("version", version);
e.setAttribute("folio", folio);
e.setAttribute("auto_page_num", auto_page_num);
e.setAttribute("date", exportDate());
e.setAttribute("displayAt", (display_at == Qt::BottomEdge? "bottom" : "right"));
if (!template_name.isEmpty())
{
e.setAttribute("titleblocktemplate", template_name);
e.setAttribute("titleblocktemplateCollection", QET::qetCollectionToString(collection));
}
e.setAttribute("author", author);
e.setAttribute("title", title);
e.setAttribute("filename", filename);
e.setAttribute("plant", plant);
e.setAttribute("locmach", locmach);
e.setAttribute("indexrev",indexrev);
e.setAttribute("version", version);
e.setAttribute("folio", folio);
e.setAttribute("auto_page_num", auto_page_num);
e.setAttribute("date", exportDate());
e.setAttribute("displayAt", (display_at == Qt::BottomEdge? "bottom" : "right"));
if (!template_name.isEmpty())
{
e.setAttribute("titleblocktemplate", template_name);
e.setAttribute("titleblocktemplateCollection", QET::qetCollectionToString(collection));
}
if (context.keys().count()) {
QDomElement properties = e.ownerDocument().createElement("properties");
context.toXml(properties);
e.appendChild(properties);
}
if (context.keys().count()) {
QDomElement properties = e.ownerDocument().createElement("properties");
context.toXml(properties);
e.appendChild(properties);
}
}
QDomElement TitleBlockProperties::toXml(QDomDocument &d) const {
Q_UNUSED(d)
qDebug() << "NOT IMPLEMENTED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!";
return QDomElement();
Q_UNUSED(d)
qDebug() << "NOT IMPLEMENTED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!";
return QDomElement();
}
/** RETURNS True
Importe le cartouche a partir des attributs XML de l'element e
@param e Element XML dont les attributs seront lus
Importe le cartouche a partir des attributs XML de l'element e
@param e Element XML dont les attributs seront lus
*/
bool TitleBlockProperties::fromXml(const QDomElement &e) {
// reads the historical fields
propertyString(e, "author", &author);
propertyString(e, "title", &title);
propertyString(e, "filename", &filename);
propertyString(e, "plant", &plant);
propertyString(e, "locmach", &locmach);
propertyString(e, "indexrev", &indexrev);
propertyString(e, "version", &version);
propertyString(e, "folio", &folio);
propertyString(e, "auto_page_num", &auto_page_num);
QString date;
propertyString(e, "date", &date);
setDateFromString(date);
// reads the historical fields
propertyString(e, "author", &author);
propertyString(e, "title", &title);
propertyString(e, "filename", &filename);
propertyString(e, "plant", &plant);
propertyString(e, "locmach", &locmach);
propertyString(e, "indexrev", &indexrev);
propertyString(e, "version", &version);
propertyString(e, "folio", &folio);
propertyString(e, "auto_page_num", &auto_page_num);
QString date;
propertyString(e, "date", &date);
setDateFromString(date);
QString display_at_temp;
if (propertyString(e, "displayAt", &display_at_temp) == PropertyFlags::Success)
display_at = (display_at_temp == "bottom" ? Qt::BottomEdge : Qt::RightEdge); // otherwise it gets default in header file
QString display_at_temp;
if (propertyString(e, "displayAt", &display_at_temp) == PropertyFlags::Success)
display_at = (display_at_temp == "bottom" ? Qt::BottomEdge : Qt::RightEdge); // otherwise it gets default in header file
// reads the template used to render the title block
if (propertyString(e, "titleblocktemplate", &template_name) == PropertyFlags::Success) {
QString tbc;
if (propertyString(e, "titleblocktemplateCollection", &tbc) == PropertyFlags::Success)
collection = QET::qetCollectionFromString(tbc);
}
// reads the template used to render the title block
if (propertyString(e, "titleblocktemplate", &template_name) == PropertyFlags::Success) {
QString tbc;
if (propertyString(e, "titleblocktemplateCollection", &tbc) == PropertyFlags::Success)
collection = QET::qetCollectionFromString(tbc);
}
// reads the additional fields used to fill the title block
context.clear();
foreach (QDomElement e, QET::findInDomElement(e, "properties")) {
context.fromXml(e);
}
return true;
// reads the additional fields used to fill the title block
context.clear();
foreach (QDomElement e, QET::findInDomElement(e, "properties")) {
context.fromXml(e);
}
return true;
}
/**
@brief TitleBlockProperties::toSettings
Export the TitleBlockProperties into a QSettings
@param settings : setting to use
@param prefix : name to use as prefix for this property
@brief TitleBlockProperties::toSettings
Export the TitleBlockProperties into a QSettings
@param settings : setting to use
@param prefix : name to use as prefix for this property
*/
void TitleBlockProperties::toSettings(QSettings &settings, const QString &prefix) const
{
settings.setValue(prefix + "title", title);
settings.setValue(prefix + "author", author);
settings.setValue(prefix + "filename", filename);
settings.setValue(prefix + "plant", plant);
settings.setValue(prefix + "locmach", locmach);
settings.setValue(prefix + "indexrev", indexrev);
settings.setValue(prefix + "version", version);
settings.setValue(prefix + "folio", folio);
settings.setValue(prefix + "auto_page_num", auto_page_num);
settings.setValue(prefix + "date", exportDate());
settings.setValue(prefix + "displayAt", (display_at == Qt::BottomEdge? "bottom" : "right"));
settings.setValue(prefix + "titleblocktemplate", template_name.isEmpty()? QString() : template_name);
settings.setValue(prefix + "titleblocktemplateCollection", QET::qetCollectionToString(collection));
context.toSettings(settings, prefix + "properties");
settings.setValue(prefix + "title", title);
settings.setValue(prefix + "author", author);
settings.setValue(prefix + "filename", filename);
settings.setValue(prefix + "plant", plant);
settings.setValue(prefix + "locmach", locmach);
settings.setValue(prefix + "indexrev", indexrev);
settings.setValue(prefix + "version", version);
settings.setValue(prefix + "folio", folio);
settings.setValue(prefix + "auto_page_num", auto_page_num);
settings.setValue(prefix + "date", exportDate());
settings.setValue(prefix + "displayAt", (display_at == Qt::BottomEdge? "bottom" : "right"));
settings.setValue(prefix + "titleblocktemplate", template_name.isEmpty()? QString() : template_name);
settings.setValue(prefix + "titleblocktemplateCollection", QET::qetCollectionToString(collection));
context.toSettings(settings, prefix + "properties");
}
/**
Importe le cartouche depuis une configuration.
@param settings Parametres a lire
@param prefix prefixe a ajouter devant les noms des parametres
Importe le cartouche depuis une configuration.
@param settings Parametres a lire
@param prefix prefixe a ajouter devant les noms des parametres
*/
void TitleBlockProperties::fromSettings(const QSettings &settings, const QString &prefix) {
title = settings.value(prefix + "title").toString();
author = settings.value(prefix + "author").toString();
filename = settings.value(prefix + "filename").toString();
plant = settings.value(prefix + "plant").toString();
locmach = settings.value(prefix + "locmach").toString();
indexrev = settings.value(prefix + "indexrev").toString();
version = settings.value(prefix + "version").toString();
folio = settings.value(prefix + "folio", "%id/%total").toString();
auto_page_num = settings.value(prefix + "auto_page_num").toString();
setDateFromString(settings.value(prefix + "date").toString());
display_at = (settings.value(prefix + "displayAt", QVariant("bottom")).toString() == "bottom" ? Qt::BottomEdge : Qt::RightEdge);
template_name = settings.value(prefix + "titleblocktemplate").toString();
collection = QET::qetCollectionFromString(settings.value(prefix + "titleblocktemplateCollection").toString());
context.fromSettings(settings, prefix + "properties");
title = settings.value(prefix + "title").toString();
author = settings.value(prefix + "author").toString();
filename = settings.value(prefix + "filename").toString();
plant = settings.value(prefix + "plant").toString();
locmach = settings.value(prefix + "locmach").toString();
indexrev = settings.value(prefix + "indexrev").toString();
version = settings.value(prefix + "version").toString();
folio = settings.value(prefix + "folio", "%id/%total").toString();
auto_page_num = settings.value(prefix + "auto_page_num").toString();
setDateFromString(settings.value(prefix + "date").toString());
display_at = (settings.value(prefix + "displayAt", QVariant("bottom")).toString() == "bottom" ? Qt::BottomEdge : Qt::RightEdge);
template_name = settings.value(prefix + "titleblocktemplate").toString();
collection = QET::qetCollectionFromString(settings.value(prefix + "titleblocktemplateCollection").toString());
context.fromSettings(settings, prefix + "properties");
}
/**
@brief TitleBlockProperties::defaultProperties
Return the default properties stored in the setting file
@brief TitleBlockProperties::defaultProperties
Return the default properties stored in the setting file
*/
TitleBlockProperties TitleBlockProperties::defaultProperties()
{
QSettings settings;
QSettings settings;
TitleBlockProperties def;
def.fromSettings(settings, "diagrameditor/default");
TitleBlockProperties def;
def.fromSettings(settings, "diagrameditor/default");
return(def);
return(def);
}
/**
@return La date a utiliser
@return La date a utiliser
*/
QDate TitleBlockProperties::finalDate() const
{
if (useDate == UseDateValue) {
return(date);
} else {
return(QDate::currentDate());
}
if (useDate == UseDateValue) {
return(date);
} else {
return(QDate::currentDate());
}
}
/**
@return une chaine de caracteres decrivant comment gerer la date dans le
cartouche : la chaine peut valoir :
* null pour ne pas afficher de date
* now pour afficher la date courante (a la creation du schema)
* une date au format yyyyMMdd pour utiliser une date fixe
@return une chaine de caracteres decrivant comment gerer la date dans le
cartouche : la chaine peut valoir :
* null pour ne pas afficher de date
* now pour afficher la date courante (a la creation du schema)
* une date au format yyyyMMdd pour utiliser une date fixe
*/
QString TitleBlockProperties::exportDate() const
{
QString date_setting_value;
if (useDate == UseDateValue) {
if (date.isNull()) date_setting_value = "null";
else date_setting_value = date.toString("yyyyMMdd");
} else {
date_setting_value = "now";
}
return(date_setting_value);
QString date_setting_value;
if (useDate == UseDateValue) {
if (date.isNull()) date_setting_value = "null";
else date_setting_value = date.toString("yyyyMMdd");
} else {
date_setting_value = "now";
}
return(date_setting_value);
}
/**
Charge les attributs date et useDate a partir d'une chaine de caracteres.
@param date_string Chaine de caracteres a analyser
@see exportDate
Charge les attributs date et useDate a partir d'une chaine de caracteres.
@param date_string Chaine de caracteres a analyser
@see exportDate
*/
void TitleBlockProperties::setDateFromString(const QString &date_string) {
if (date_string == "now") {
date = QDate::currentDate();
useDate = CurrentDate;
} else if (date_string.isEmpty() || date_string == "null") {
date = QDate();
useDate = UseDateValue;
} else {
date = QDate::fromString(date_string, "yyyyMMdd");
useDate = UseDateValue;
}
if (date_string == "now") {
date = QDate::currentDate();
useDate = CurrentDate;
} else if (date_string.isEmpty() || date_string == "null") {
date = QDate();
useDate = UseDateValue;
} else {
date = QDate::fromString(date_string, "yyyyMMdd");
useDate = UseDateValue;
}
}

View File

@@ -1,19 +1,19 @@
/*
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TITLEBLOCK_PROPERTIES_H
#define TITLEBLOCK_PROPERTIES_H
@@ -24,54 +24,54 @@
#include "propertiesinterface.h"
/**
This class provides a container for the properties of a particular title
block, i.e. title, author, date, filename, folio, template, custom
properties, ...
This class provides a container for the properties of a particular title
block, i.e. title, author, date, filename, folio, template, custom
properties, ...
*/
class TitleBlockProperties: public PropertiesInterface {
public:
TitleBlockProperties();
virtual ~TitleBlockProperties();
/// Lists the various ways to handle the date
enum DateManagement {
UseDateValue, ///< use the date attribute
CurrentDate ///< use the current date
};
public:
TitleBlockProperties();
virtual ~TitleBlockProperties();
/// Lists the various ways to handle the date
enum DateManagement {
UseDateValue, ///< use the date attribute
CurrentDate ///< use the current date
};
bool operator==(const TitleBlockProperties &);
bool operator!=(const TitleBlockProperties &);
bool operator==(const TitleBlockProperties &);
bool operator!=(const TitleBlockProperties &);
QDomElement toXml(QDomDocument &e) const override;
void toXml(QDomElement &e) const;
bool fromXml(const QDomElement &) override;
void toSettings(QSettings &, const QString & = QString()) const override;
void fromSettings(const QSettings &, const QString & = QString()) override;
QDomElement toXml(QDomDocument &e) const override;
void toXml(QDomElement &e) const;
bool fromXml(const QDomElement &) override;
void toSettings(QSettings &, const QString & = QString()) const override;
void fromSettings(const QSettings &, const QString & = QString()) override;
void setAutoPageNum(QString autonum) {auto_page_num = autonum;}
void setAutoPageNum(QString autonum) {auto_page_num = autonum;}
static TitleBlockProperties defaultProperties();
static TitleBlockProperties defaultProperties();
QDate finalDate() const ;
QDate finalDate() const ;
// attributes
QString title; ///< Folio title (displayed by the default template)
QString author; ///< Author of the diagram/folio (displayed by the default template)
QDate date; ///< Date (displayed by the default template)
QString filename; ///< Filename (displayed by the default template)
QString plant; ///< Plant (displayed by the default template)
QString locmach; ///< Location(displayed by the default template)
QString indexrev; ///< Revision Index (displayed by the default template)
QString version; ///< Version (displayed by the default template)
QString folio; ///< Folio information (displayed by the default template)
QString auto_page_num;
DateManagement useDate{UseDateValue}; ///< Wheter to use the date attribute
QString template_name; ///< Name of the template used to render the title block - an empty string means "the default template provided by the application"
DiagramContext context; ///< Container for the additional, user-defined fields
Qt::Edge display_at{Qt::Edge::BottomEdge}; ///< Edge to display the titleblock
QET::QetCollection collection{QET::QetCollection::Common}; ///<Specify the location of the title block
// attributes
QString title; ///< Folio title (displayed by the default template)
QString author; ///< Author of the diagram/folio (displayed by the default template)
QDate date; ///< Date (displayed by the default template)
QString filename; ///< Filename (displayed by the default template)
QString plant; ///< Plant (displayed by the default template)
QString locmach; ///< Location(displayed by the default template)
QString indexrev; ///< Revision Index (displayed by the default template)
QString version; ///< Version (displayed by the default template)
QString folio; ///< Folio information (displayed by the default template)
QString auto_page_num;
DateManagement useDate{UseDateValue}; ///< Wheter to use the date attribute
QString template_name; ///< Name of the template used to render the title block - an empty string means "the default template provided by the application"
DiagramContext context; ///< Container for the additional, user-defined fields
Qt::Edge display_at{Qt::Edge::BottomEdge}; ///< Edge to display the titleblock
QET::QetCollection collection{QET::QetCollection::Common}; ///<Specify the location of the title block
private:
QString exportDate() const;
void setDateFromString(const QString &);
private:
QString exportDate() const;
void setDateFromString(const QString &);
};
#endif