Merge branch 'QT6' into master

initial release to Qt6

TODO:
 -remove KCoreAddons
 -remove KWidgetsAddons

* QT6: (24 commits)
  QT6: No Qt::AA_EnableHighDpiScaling in QT6
  QT6: TeDo mod QList for DeleteQGraphicsItemCommand
  QT6: Todo Fix QtConcurrent (remove KCoreAddons?)
  QT6: Todo QVariant::setValue
  QT6: std::min needs further tweaking
  QPrinting class needs further tweaking
  QT6: QStyleOptionGraphicsItem
  Add QActionGroup
  QT6: QStyleOptionGraphicsItem
  QT6: QLibraryInfo
  Totest QRegularExpression ok?
  QT6: QStyleOptionGraphicsItem
  QT6: QMouseEvent
  QT6: QDropEvent
  QT6: Fix deprecated QRegExp
  QT6: hooks added
  QT6: Mod unused function put in comments
  Add missing include QActionGroup
  QT6: set C++17
  QT6: diagramitemweight set val to Font::Weight
  ...
This commit is contained in:
Simon De Backer
2020-10-03 16:18:03 +02:00
32 changed files with 1124 additions and 691 deletions

View File

@@ -1,5 +1,5 @@
QT += core network QT += core network
CONFIG += c++11 CONFIG += c++17
HEADERS += $$PWD/singleapplication.h \ HEADERS += $$PWD/singleapplication.h \
$$PWD/singleapplication_p.h $$PWD/singleapplication_p.h

View File

@@ -43,9 +43,9 @@
#include "singleapplication_p.h" #include "singleapplication_p.h"
#ifdef Q_OS_UNIX #ifdef Q_OS_UNIX
#include <unistd.h> #include <unistd.h>
#include <sys/types.h> #include <sys/types.h>
#include <pwd.h> #include <pwd.h>
#endif #endif
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
@@ -68,7 +68,7 @@ SingleApplicationPrivate::~SingleApplicationPrivate()
socket->close(); socket->close();
delete socket; delete socket;
} }
memory->lock(); memory->lock();
InstancesInfo* inst = static_cast<InstancesInfo*>(memory->data()); InstancesInfo* inst = static_cast<InstancesInfo*>(memory->data());
if( server != nullptr ) { if( server != nullptr ) {
@@ -79,7 +79,7 @@ SingleApplicationPrivate::~SingleApplicationPrivate()
inst->checksum = blockChecksum(); inst->checksum = blockChecksum();
} }
memory->unlock(); memory->unlock();
delete memory; delete memory;
} }
@@ -90,11 +90,11 @@ void SingleApplicationPrivate::genBlockServerName()
appData.addData( SingleApplication::app_t::applicationName().toUtf8() ); appData.addData( SingleApplication::app_t::applicationName().toUtf8() );
appData.addData( SingleApplication::app_t::organizationName().toUtf8() ); appData.addData( SingleApplication::app_t::organizationName().toUtf8() );
appData.addData( SingleApplication::app_t::organizationDomain().toUtf8() ); appData.addData( SingleApplication::app_t::organizationDomain().toUtf8() );
if( ! (options & SingleApplication::Mode::ExcludeAppVersion) ) { if( ! (options & SingleApplication::Mode::ExcludeAppVersion) ) {
appData.addData( SingleApplication::app_t::applicationVersion().toUtf8() ); appData.addData( SingleApplication::app_t::applicationVersion().toUtf8() );
} }
if( ! (options & SingleApplication::Mode::ExcludeAppPath) ) { if( ! (options & SingleApplication::Mode::ExcludeAppPath) ) {
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
appData.addData( SingleApplication::app_t::applicationFilePath().toLower().toUtf8() ); appData.addData( SingleApplication::app_t::applicationFilePath().toLower().toUtf8() );
@@ -102,7 +102,7 @@ void SingleApplicationPrivate::genBlockServerName()
appData.addData( SingleApplication::app_t::applicationFilePath().toUtf8() ); appData.addData( SingleApplication::app_t::applicationFilePath().toUtf8() );
#endif #endif
} }
// User level block requires a user specific data in the hash // User level block requires a user specific data in the hash
if( options & SingleApplication::Mode::User ) { if( options & SingleApplication::Mode::User ) {
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
@@ -128,7 +128,7 @@ void SingleApplicationPrivate::genBlockServerName()
appData.addData(username); appData.addData(username);
#endif #endif
} }
// Replace the backslash in RFC 2045 Base64 [a-zA-Z0-9+/=] to comply with // Replace the backslash in RFC 2045 Base64 [a-zA-Z0-9+/=] to comply with
// server naming requirements. // server naming requirements.
blockServerName = appData.result().toBase64().replace("/", "_"); blockServerName = appData.result().toBase64().replace("/", "_");
@@ -146,12 +146,12 @@ void SingleApplicationPrivate::initializeMemoryBlock()
void SingleApplicationPrivate::startPrimary() void SingleApplicationPrivate::startPrimary()
{ {
Q_Q(SingleApplication); Q_Q(SingleApplication);
// Successful creation means that no main process exists // Successful creation means that no main process exists
// So we start a QLocalServer to listen for connections // So we start a QLocalServer to listen for connections
QLocalServer::removeServer( blockServerName ); QLocalServer::removeServer( blockServerName );
server = new QLocalServer(); server = new QLocalServer();
// Restrict access to the socket according to the // Restrict access to the socket according to the
// SingleApplication::Mode::User flag on User level or no restrictions // SingleApplication::Mode::User flag on User level or no restrictions
if( options & SingleApplication::Mode::User ) { if( options & SingleApplication::Mode::User ) {
@@ -159,7 +159,7 @@ void SingleApplicationPrivate::startPrimary()
} else { } else {
server->setSocketOptions( QLocalServer::WorldAccessOption ); server->setSocketOptions( QLocalServer::WorldAccessOption );
} }
server->listen( blockServerName ); server->listen( blockServerName );
QObject::connect( QObject::connect(
server, server,
@@ -167,14 +167,14 @@ void SingleApplicationPrivate::startPrimary()
this, this,
&SingleApplicationPrivate::slotConnectionEstablished &SingleApplicationPrivate::slotConnectionEstablished
); );
// Reset the number of connections // Reset the number of connections
InstancesInfo* inst = static_cast <InstancesInfo*>( memory->data() ); InstancesInfo* inst = static_cast <InstancesInfo*>( memory->data() );
inst->primary = true; inst->primary = true;
inst->primaryPid = q->applicationPid(); inst->primaryPid = q->applicationPid();
inst->checksum = blockChecksum(); inst->checksum = blockChecksum();
instanceNumber = 0; instanceNumber = 0;
} }
@@ -189,47 +189,62 @@ void SingleApplicationPrivate::connectToPrimary( int msecs, ConnectionType conne
if( socket == nullptr ) { if( socket == nullptr ) {
socket = new QLocalSocket(); socket = new QLocalSocket();
} }
// If already connected - we are done; // If already connected - we are done;
if( socket->state() == QLocalSocket::ConnectedState ) if( socket->state() == QLocalSocket::ConnectedState )
return; return;
// If not connect // If not connect
if( socket->state() == QLocalSocket::UnconnectedState || if( socket->state() == QLocalSocket::UnconnectedState ||
socket->state() == QLocalSocket::ClosingState ) { socket->state() == QLocalSocket::ClosingState ) {
socket->connectToServer( blockServerName ); socket->connectToServer( blockServerName );
} }
// Wait for being connected // Wait for being connected
if( socket->state() == QLocalSocket::ConnectingState ) { if( socket->state() == QLocalSocket::ConnectingState ) {
socket->waitForConnected( msecs ); socket->waitForConnected( msecs );
} }
// Initialisation message according to the SingleApplication protocol // Initialisation message according to the SingleApplication protocol
if( socket->state() == QLocalSocket::ConnectedState ) { if( socket->state() == QLocalSocket::ConnectedState ) {
// Notify the parent that a new instance had been started; // Notify the parent that a new instance had been started;
QByteArray initMsg; QByteArray initMsg;
QDataStream writeStream(&initMsg, QIODevice::WriteOnly); QDataStream writeStream(&initMsg, QIODevice::WriteOnly);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)) #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
writeStream.setVersion(QDataStream::Qt_5_6); writeStream.setVersion(QDataStream::Qt_5_6);
#endif #endif
writeStream << blockServerName.toLatin1(); writeStream << blockServerName.toLatin1();
writeStream << static_cast<quint8>(connectionType); writeStream << static_cast<quint8>(connectionType);
writeStream << instanceNumber; writeStream << instanceNumber;
quint16 checksum = qChecksum(initMsg.constData(), static_cast<quint32>(initMsg.length()));
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
quint16 checksum =
qChecksum(
initMsg.constData(),
static_cast<quint32>(initMsg.length()));
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
quint16 checksum =
qChecksum(
QByteArrayView(
initMsg.constData(),
static_cast<quint32>(initMsg.length())));
#endif
writeStream << checksum; writeStream << checksum;
// The header indicates the message length that follows // The header indicates the message length that follows
QByteArray header; QByteArray header;
QDataStream headerStream(&header, QIODevice::WriteOnly); QDataStream headerStream(&header, QIODevice::WriteOnly);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)) #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
headerStream.setVersion(QDataStream::Qt_5_6); headerStream.setVersion(QDataStream::Qt_5_6);
#endif #endif
headerStream << static_cast <quint64>( initMsg.length() ); headerStream << static_cast <quint64>( initMsg.length() );
socket->write( header ); socket->write( header );
socket->write( initMsg ); socket->write( initMsg );
socket->flush(); socket->flush();
@@ -239,21 +254,32 @@ void SingleApplicationPrivate::connectToPrimary( int msecs, ConnectionType conne
quint16 SingleApplicationPrivate::blockChecksum() quint16 SingleApplicationPrivate::blockChecksum()
{ {
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
return qChecksum( return qChecksum(
static_cast <const char *>( memory->data() ), static_cast <const char *>( memory->data() ),
offsetof( InstancesInfo, checksum ) offsetof( InstancesInfo, checksum )
); );
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
return qChecksum(
QByteArrayView(
static_cast <const char *>( memory->data() ),
offsetof( InstancesInfo, checksum )));
#endif
} }
qint64 SingleApplicationPrivate::primaryPid() qint64 SingleApplicationPrivate::primaryPid()
{ {
qint64 pid; qint64 pid;
memory->lock(); memory->lock();
InstancesInfo* inst = static_cast<InstancesInfo*>( memory->data() ); InstancesInfo* inst = static_cast<InstancesInfo*>( memory->data() );
pid = inst->primaryPid; pid = inst->primaryPid;
memory->unlock(); memory->unlock();
return pid; return pid;
} }
@@ -264,21 +290,21 @@ void SingleApplicationPrivate::slotConnectionEstablished()
{ {
QLocalSocket *nextConnSocket = server->nextPendingConnection(); QLocalSocket *nextConnSocket = server->nextPendingConnection();
connectionMap.insert(nextConnSocket, ConnectionInfo()); connectionMap.insert(nextConnSocket, ConnectionInfo());
QObject::connect(nextConnSocket, &QLocalSocket::aboutToClose, QObject::connect(nextConnSocket, &QLocalSocket::aboutToClose,
[nextConnSocket, this]() { [nextConnSocket, this]() {
auto &info = connectionMap[nextConnSocket]; auto &info = connectionMap[nextConnSocket];
Q_EMIT this->slotClientConnectionClosed( nextConnSocket, info.instanceId ); Q_EMIT this->slotClientConnectionClosed( nextConnSocket, info.instanceId );
} }
); );
QObject::connect(nextConnSocket, &QLocalSocket::disconnected, QObject::connect(nextConnSocket, &QLocalSocket::disconnected,
[nextConnSocket, this](){ [nextConnSocket, this](){
connectionMap.remove(nextConnSocket); connectionMap.remove(nextConnSocket);
nextConnSocket->deleteLater(); nextConnSocket->deleteLater();
} }
); );
QObject::connect(nextConnSocket, &QLocalSocket::readyRead, QObject::connect(nextConnSocket, &QLocalSocket::readyRead,
[nextConnSocket, this]() { [nextConnSocket, this]() {
auto &info = connectionMap[nextConnSocket]; auto &info = connectionMap[nextConnSocket];
@@ -304,24 +330,24 @@ void SingleApplicationPrivate::readInitMessageHeader( QLocalSocket *sock )
if (!connectionMap.contains( sock )) { if (!connectionMap.contains( sock )) {
return; return;
} }
if( sock->bytesAvailable() < ( qint64 )sizeof( quint64 ) ) { if( sock->bytesAvailable() < ( qint64 )sizeof( quint64 ) ) {
return; return;
} }
QDataStream headerStream( sock ); QDataStream headerStream( sock );
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)) #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
headerStream.setVersion( QDataStream::Qt_5_6 ); headerStream.setVersion( QDataStream::Qt_5_6 );
#endif #endif
// Read the header to know the message length // Read the header to know the message length
quint64 msgLen = 0; quint64 msgLen = 0;
headerStream >> msgLen; headerStream >> msgLen;
ConnectionInfo &info = connectionMap[sock]; ConnectionInfo &info = connectionMap[sock];
info.stage = StageBody; info.stage = StageBody;
info.msgLen = msgLen; info.msgLen = msgLen;
if ( sock->bytesAvailable() >= (qint64) msgLen ) { if ( sock->bytesAvailable() >= (qint64) msgLen ) {
readInitMessageBody( sock ); readInitMessageBody( sock );
} }
@@ -330,63 +356,76 @@ void SingleApplicationPrivate::readInitMessageHeader( QLocalSocket *sock )
void SingleApplicationPrivate::readInitMessageBody( QLocalSocket *sock ) void SingleApplicationPrivate::readInitMessageBody( QLocalSocket *sock )
{ {
Q_Q(SingleApplication); Q_Q(SingleApplication);
if (!connectionMap.contains( sock )) { if (!connectionMap.contains( sock )) {
return; return;
} }
ConnectionInfo &info = connectionMap[sock]; ConnectionInfo &info = connectionMap[sock];
if( sock->bytesAvailable() < ( qint64 )info.msgLen ) { if( sock->bytesAvailable() < ( qint64 )info.msgLen ) {
return; return;
} }
// Read the message body // Read the message body
QByteArray msgBytes = sock->read(info.msgLen); QByteArray msgBytes = sock->read(info.msgLen);
QDataStream readStream(msgBytes); QDataStream readStream(msgBytes);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)) #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
readStream.setVersion( QDataStream::Qt_5_6 ); readStream.setVersion( QDataStream::Qt_5_6 );
#endif #endif
// server name // server name
QByteArray latin1Name; QByteArray latin1Name;
readStream >> latin1Name; readStream >> latin1Name;
// connection type // connection type
ConnectionType connectionType = InvalidConnection; ConnectionType connectionType = InvalidConnection;
quint8 connTypeVal = InvalidConnection; quint8 connTypeVal = InvalidConnection;
readStream >> connTypeVal; readStream >> connTypeVal;
connectionType = static_cast <ConnectionType>( connTypeVal ); connectionType = static_cast <ConnectionType>( connTypeVal );
// instance id // instance id
quint32 instanceId = 0; quint32 instanceId = 0;
readStream >> instanceId; readStream >> instanceId;
// checksum // checksum
quint16 msgChecksum = 0; quint16 msgChecksum = 0;
readStream >> msgChecksum; readStream >> msgChecksum;
const quint16 actualChecksum = qChecksum( msgBytes.constData(), static_cast<quint32>( msgBytes.length() - sizeof( quint16 ) ) ); #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
const quint16 actualChecksum =
qChecksum(
msgBytes.constData(),
static_cast<quint32>( msgBytes.length() - sizeof( quint16 ) ) );
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
const quint16 actualChecksum =
qChecksum(
QByteArrayView(
msgBytes.constData(),
static_cast<quint32>(msgBytes.length() - sizeof(quint16))));
#endif
bool isValid = readStream.status() == QDataStream::Ok && bool isValid = readStream.status() == QDataStream::Ok &&
QLatin1String(latin1Name) == blockServerName && QLatin1String(latin1Name) == blockServerName &&
msgChecksum == actualChecksum; msgChecksum == actualChecksum;
if( !isValid ) { if( !isValid ) {
sock->close(); sock->close();
return; return;
} }
info.instanceId = instanceId; info.instanceId = instanceId;
info.stage = StageConnected; info.stage = StageConnected;
if( connectionType == NewInstance || if( connectionType == NewInstance ||
( connectionType == SecondaryInstance && ( connectionType == SecondaryInstance &&
options & SingleApplication::Mode::SecondaryNotification ) ) options & SingleApplication::Mode::SecondaryNotification ) )
{ {
Q_EMIT q->instanceStarted(); Q_EMIT q->instanceStarted();
} }
if (sock->bytesAvailable() > 0) { if (sock->bytesAvailable() > 0) {
Q_EMIT this->slotDataAvailable( sock, instanceId ); Q_EMIT this->slotDataAvailable( sock, instanceId );
} }

View File

@@ -220,7 +220,7 @@ UI_SOURCES_DIR = sources/ui/
UI_HEADERS_DIR = sources/ui/ UI_HEADERS_DIR = sources/ui/
# Configuration de la compilation # Configuration de la compilation
CONFIG += c++11 debug_and_release warn_on CONFIG += c++17 debug_and_release warn_on
# Nom du binaire genere par la compilation # Nom du binaire genere par la compilation
TARGET = qelectrotech TARGET = qelectrotech
@@ -229,8 +229,8 @@ TARGET = qelectrotech
unix:QMAKE_LIBS_THREAD -= -lpthread unix:QMAKE_LIBS_THREAD -= -lpthread
unix|win32: LIBS += -lsqlite3 unix|win32: LIBS += -lsqlite3
# Enable C++11 # Enable C++17
QMAKE_CXXFLAGS += -std=c++11 QMAKE_CXXFLAGS += -std=c++17
# Description de l'installation # Description de l'installation
target.path = $$join(INSTALL_PREFIX,,,$${QET_BINARY_PATH}) target.path = $$join(INSTALL_PREFIX,,,$${QET_BINARY_PATH})

View File

@@ -144,11 +144,23 @@ bool ElementsLocation::operator!=(const ElementsLocation &other) const
*/ */
QString ElementsLocation::baseName() const QString ElementsLocation::baseName() const
{ {
QRegExp regexp("^.*([^/]+)\\.elmt$"); QRegularExpression regexp("^.*(?<name>[^/]+)\\.elmt$");
if (regexp.exactMatch(m_collection_path)) { if (!regexp.isValid())
return(regexp.capturedTexts().at(1)); {
qWarning() <<"this is an error in the code"
<< regexp.errorString()
<< regexp.patternErrorOffset();
return QString();
} }
return(QString());
QRegularExpressionMatch match = regexp.match(m_collection_path);
if (!match.hasMatch())
{
qDebug()<<"no Match => return"
<<m_collection_path;
return QString();
}
return match.captured("name");
} }
/** /**
@@ -183,9 +195,9 @@ QString ElementsLocation::projectCollectionPath() const
return QString(); return QString();
else else
return QString("project" return QString("project"
+ QString::number(QETApp::projectId(m_project)) + QString::number(QETApp::projectId(m_project))
+ "+" + "+"
+ collectionPath()); + collectionPath());
} }
/** /**
@@ -254,7 +266,7 @@ void ElementsLocation::setPath(const QString &path)
if (!match.hasMatch()) if (!match.hasMatch())
{ {
qDebug()<<"no Match => return" qDebug()<<"no Match => return"
<<tmp_path; <<tmp_path;
return; return;
} }
bool conv_ok; bool conv_ok;
@@ -344,7 +356,7 @@ bool ElementsLocation::addToPath(const QString &string)
if (m_collection_path.endsWith(".elmt", Qt::CaseInsensitive)) if (m_collection_path.endsWith(".elmt", Qt::CaseInsensitive))
{ {
qDebug() << "ElementsLocation::addToPath :" qDebug() << "ElementsLocation::addToPath :"
" Can't add string to the path of an element"; " Can't add string to the path of an element";
return(false); return(false);
} }
@@ -368,12 +380,22 @@ bool ElementsLocation::addToPath(const QString &string)
ElementsLocation ElementsLocation::parent() const ElementsLocation ElementsLocation::parent() const
{ {
ElementsLocation copy(*this); ElementsLocation copy(*this);
QRegExp re1("^([a-z]+://)(.*)/*$"); QRegularExpression re ("^(?<path_proto>[a-z]+://.*)/.*$");
if (re1.exactMatch(m_collection_path)) { if (!re.isValid())
QString path_proto = re1.capturedTexts().at(1); {
QString path_path = re1.capturedTexts().at(2); qWarning()
QString parent_path = path_path.remove(QRegExp("/*[^/]+$")); <<QObject::tr("this is an error in the code")
copy.setPath(path_proto + parent_path); << re.errorString()
<< re.patternErrorOffset();
}
QRegularExpressionMatch match = re.match(m_collection_path);
if (!match.hasMatch())
{
qDebug()
<<"no Match => return"
<<m_collection_path;
}else {
copy.setPath(match.captured("path_proto"));
} }
return(copy); return(copy);
} }
@@ -700,7 +722,7 @@ bool ElementsLocation::setXml(const QDomDocument &xml_document) const
if (xml_document.documentElement().tagName() != "definition") if (xml_document.documentElement().tagName() != "definition")
{ {
qDebug() << "ElementsLocation::setXml :" qDebug() << "ElementsLocation::setXml :"
" tag name of document element isn't 'definition'"; " tag name of document element isn't 'definition'";
return false; return false;
} }
@@ -734,6 +756,7 @@ bool ElementsLocation::setXml(const QDomDocument &xml_document) const
//Element doesn't exist, we create the element //Element doesn't exist, we create the element
else else
{ {
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
QString path_ = collectionPath(false); QString path_ = collectionPath(false);
QRegExp rx ("^(.*)/(.*\\.elmt)$"); QRegExp rx ("^(.*)/(.*\\.elmt)$");
@@ -748,9 +771,14 @@ bool ElementsLocation::setXml(const QDomDocument &xml_document) const
} }
else { else {
qDebug() << "ElementsLocation::setXml :" qDebug() << "ElementsLocation::setXml :"
" rx don't match"; " rx don't match";
} }
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
qDebug()<<"Help code for QT 6 or later";
#endif
} }
} }
@@ -863,7 +891,7 @@ QDebug operator<< (QDebug debug, const ElementsLocation &location)
QString msg; QString msg;
msg += "ElementsLocation("; msg += "ElementsLocation(";
msg += (location.isProject()? location.projectCollectionPath() msg += (location.isProject()? location.projectCollectionPath()
: location.collectionPath(true)); : location.collectionPath(true));
msg += location.exist()? ", true" : ", false"; msg += location.exist()? ", true" : ", false";
msg +=")"; msg +=")";

View File

@@ -439,11 +439,11 @@ int Createdxf::getcolorCode (const long red, const long green, const long blue)
} }
int Createdxf::dxfColor(QColor color) { int Createdxf::dxfColor(QColor color) {
return Createdxf::getcolorCode(color.red(), color.green(), color.blue()); return Createdxf::getcolorCode(color.red(), color.green(), color.blue());
} }
int Createdxf::dxfColor(QPen pen) { int Createdxf::dxfColor(QPen pen) {
return Createdxf::dxfColor(pen.color()); return Createdxf::dxfColor(pen.color());
} }
void Createdxf::drawArcEllipse( void Createdxf::drawArcEllipse(
@@ -613,9 +613,9 @@ void Createdxf::drawRectangle (
double height, double height,
const int &colour) const int &colour)
{ {
QRectF rect(x1,y1,width,height); QRectF rect(x1,y1,width,height);
QPolygonF poly(rect); QPolygonF poly(rect);
drawPolyline(fileName,poly,colour,true); drawPolyline(fileName,poly,colour,true);
} }
@@ -678,16 +678,16 @@ void Createdxf::drawArc(
} }
/** /**
@brief Createdxf::drawText @brief Createdxf::drawText
draw simple text in dxf format without any alignment specified draw simple text in dxf format without any alignment specified
@param fileName @param fileName
@param text @param text
@param x @param x
@param y @param y
@param height @param height
@param rotation @param rotation
@param colour @param colour
@param xScaleW = 1 @param xScaleW = 1
*/ */
void Createdxf::drawText( void Createdxf::drawText(
const QString& fileName, const QString& fileName,
@@ -699,40 +699,40 @@ void Createdxf::drawText(
int colour, int colour,
double xScaleW) double xScaleW)
{ {
if (!fileName.isEmpty()) { if (!fileName.isEmpty()) {
QFile file(fileName); QFile file(fileName);
if (!file.open(QFile::Append)) { if (!file.open(QFile::Append)) {
// error message // error message
QMessageBox errorFileOpen; QMessageBox errorFileOpen;
errorFileOpen.setText("Error: File "+fileName+" was not written correctly."); errorFileOpen.setText("Error: File "+fileName+" was not written correctly.");
errorFileOpen.setInformativeText("Close all Files and Re-Run"); errorFileOpen.setInformativeText("Close all Files and Re-Run");
errorFileOpen.exec(); errorFileOpen.exec();
} else { } else {
QTextStream To_Dxf(&file); QTextStream To_Dxf(&file);
// Draw the text // Draw the text
To_Dxf << 0 << "\r\n"; To_Dxf << 0 << "\r\n";
To_Dxf << "TEXT" << "\r\n"; To_Dxf << "TEXT" << "\r\n";
To_Dxf << 8 << "\r\n"; To_Dxf << 8 << "\r\n";
To_Dxf << 0 << "\r\n"; // Layer number (default layer in autocad) To_Dxf << 0 << "\r\n"; // Layer number (default layer in autocad)
To_Dxf << 62 << "\r\n"; To_Dxf << 62 << "\r\n";
To_Dxf << colour << "\r\n"; // Colour Code To_Dxf << colour << "\r\n"; // Colour Code
To_Dxf << 10 << "\r\n"; // XYZ To_Dxf << 10 << "\r\n"; // XYZ
To_Dxf << x << "\r\n"; // X in UCS (User Coordinate System)coordinates To_Dxf << x << "\r\n"; // X in UCS (User Coordinate System)coordinates
To_Dxf << 20 << "\r\n"; To_Dxf << 20 << "\r\n";
To_Dxf << y << "\r\n"; // Y in UCS (User Coordinate System)coordinates To_Dxf << y << "\r\n"; // Y in UCS (User Coordinate System)coordinates
To_Dxf << 30 << "\r\n"; To_Dxf << 30 << "\r\n";
To_Dxf << 0.0 << "\r\n"; // Z in UCS (User Coordinate System)coordinates To_Dxf << 0.0 << "\r\n"; // Z in UCS (User Coordinate System)coordinates
To_Dxf << 40 << "\r\n"; To_Dxf << 40 << "\r\n";
To_Dxf << height << "\r\n"; // Text Height To_Dxf << height << "\r\n"; // Text Height
To_Dxf << 41 << "\r\n"; To_Dxf << 41 << "\r\n";
To_Dxf << xScaleW << "\r\n"; // X Scale To_Dxf << xScaleW << "\r\n"; // X Scale
To_Dxf << 1 << "\r\n"; To_Dxf << 1 << "\r\n";
To_Dxf << text << "\r\n"; // Text Value To_Dxf << text << "\r\n"; // Text Value
To_Dxf << 50 << "\r\n"; To_Dxf << 50 << "\r\n";
To_Dxf << rotation << "\r\n"; // Text Rotation To_Dxf << rotation << "\r\n"; // Text Rotation
file.close(); file.close();
}
} }
}
} }
/* draw aligned text in DXF Format */ /* draw aligned text in DXF Format */
@@ -778,7 +778,7 @@ void Createdxf::drawTextAligned(
To_Dxf << 40 << "\r\n"; To_Dxf << 40 << "\r\n";
To_Dxf << height << "\r\n"; // Text Height To_Dxf << height << "\r\n"; // Text Height
To_Dxf << 41 << "\r\n"; To_Dxf << 41 << "\r\n";
To_Dxf << xScaleW << "\r\n"; // X Scale To_Dxf << xScaleW << "\r\n"; // X Scale
To_Dxf << 1 << "\r\n"; To_Dxf << 1 << "\r\n";
To_Dxf << text << "\r\n"; // Text Value To_Dxf << text << "\r\n"; // Text Value
To_Dxf << 50 << "\r\n"; To_Dxf << 50 << "\r\n";
@@ -832,42 +832,42 @@ void Createdxf::drawPolyline(const QString &filepath,
const QPolygonF &poly, const QPolygonF &poly,
const int &colorcode, bool preScaled) const int &colorcode, bool preScaled)
{ {
qreal x,y; qreal x,y;
if (!filepath.isEmpty()) { if (!filepath.isEmpty()) {
QFile file(filepath); QFile file(filepath);
if (!file.open(QFile::Append)) { if (!file.open(QFile::Append)) {
// error message // error message
QMessageBox errorFileOpen; QMessageBox errorFileOpen;
errorFileOpen.setText("Error: File "+filepath+" was not written correctly."); errorFileOpen.setText("Error: File "+filepath+" was not written correctly.");
errorFileOpen.setInformativeText("Close all Files and Re-Run"); errorFileOpen.setInformativeText("Close all Files and Re-Run");
errorFileOpen.exec(); errorFileOpen.exec();
} else { } else {
QTextStream To_Dxf(&file); QTextStream To_Dxf(&file);
// Draw the Line // Draw the Line
To_Dxf << 0 << "\r\n"; To_Dxf << 0 << "\r\n";
To_Dxf << "POLYLINE" << "\r\n"; To_Dxf << "POLYLINE" << "\r\n";
To_Dxf << 8 << "\r\n"; To_Dxf << 8 << "\r\n";
To_Dxf << 0 << "\r\n"; // Layer number (default layer in autocad) To_Dxf << 0 << "\r\n"; // Layer number (default layer in autocad)
To_Dxf << 62 << "\r\n"; To_Dxf << 62 << "\r\n";
To_Dxf << colorcode << "\r\n"; // Colour Code To_Dxf << colorcode << "\r\n"; // Colour Code
To_Dxf << 66 << "\r\n"; To_Dxf << 66 << "\r\n";
To_Dxf << 1 << "\r\n"; To_Dxf << 1 << "\r\n";
To_Dxf << 70 << "\r\n"; To_Dxf << 70 << "\r\n";
To_Dxf << 8 << "\r\n"; To_Dxf << 8 << "\r\n";
To_Dxf << 10 << "\r\n"; To_Dxf << 10 << "\r\n";
To_Dxf << 0 << "\r\n"; To_Dxf << 0 << "\r\n";
To_Dxf << 20 << "\r\n"; To_Dxf << 20 << "\r\n";
To_Dxf << 0 << "\r\n"; To_Dxf << 0 << "\r\n";
To_Dxf << 30 << "\r\n"; To_Dxf << 30 << "\r\n";
To_Dxf << 0 << "\r\n"; To_Dxf << 0 << "\r\n";
foreach(QPointF p, poly) foreach(QPointF p, poly)
{ {
if(preScaled) { if(preScaled) {
x = p.x(); x = p.x();
y = p.y(); y = p.y();
} else { } else {
x = p.x() * xScale; x = p.x() * xScale;
y = sheetHeight - (p.y() * yScale); y = sheetHeight - (p.y() * yScale);
} }
To_Dxf << 0 << "\r\n"; To_Dxf << 0 << "\r\n";
@@ -882,16 +882,16 @@ void Createdxf::drawPolyline(const QString &filepath,
To_Dxf << y << "\r\n"; // Y in UCS (User Coordinate System)coordinates To_Dxf << y << "\r\n"; // Y in UCS (User Coordinate System)coordinates
To_Dxf << 30 << "\r\n"; To_Dxf << 30 << "\r\n";
To_Dxf << 0.0 << "\r\n"; // Z in UCS (User Coordinate System)coordinates To_Dxf << 0.0 << "\r\n"; // Z in UCS (User Coordinate System)coordinates
} }
To_Dxf << 0 << "\r\n"; To_Dxf << 0 << "\r\n";
To_Dxf << "SEQEND" << "\r\n"; To_Dxf << "SEQEND" << "\r\n";
To_Dxf << 8 << "\r\n"; To_Dxf << 8 << "\r\n";
To_Dxf << 0 << "\r\n"; // Layer number (default layer in autocad) To_Dxf << 0 << "\r\n"; // Layer number (default layer in autocad)
file.close(); file.close();
}
} }
}
} }
/* ================================================ /* ================================================
@@ -951,7 +951,7 @@ void Createdxf::drawEllipse(
const QRectF &rect, const QRectF &rect,
const int &colorcode) const int &colorcode)
{ {
drawArcEllipse( drawArcEllipse(
filepath, filepath,
rect.topLeft().x() * xScale, rect.topLeft().x() * xScale,
sheetHeight - (rect.topLeft().y() * yScale), sheetHeight - (rect.topLeft().y() * yScale),
@@ -961,38 +961,38 @@ void Createdxf::drawEllipse(
} }
/** /**
@brief Createdxf::drawRectangle @brief Createdxf::drawRectangle
Convenience function for draw rectangle Convenience function for draw rectangle
@param filepath @param filepath
@param rect @param rect
@param colorcode @param colorcode
*/ */
void Createdxf::drawRectangle( void Createdxf::drawRectangle(
const QString &filepath, const QString &filepath,
const QRectF &rect, const QRectF &rect,
const int &colorcode) { const int &colorcode) {
//QPolygonF poly(scaleRect(rect)); //QPolygonF poly(scaleRect(rect));
QPolygonF poly(rect); QPolygonF poly(rect);
drawPolyline(filepath,poly,colorcode); drawPolyline(filepath,poly,colorcode);
} }
/** /**
@brief Createdxf::drawPolygon @brief Createdxf::drawPolygon
Convenience function for draw polygon Convenience function for draw polygon
@param filepath @param filepath
@param poly @param poly
@param colorcode @param colorcode
*/ */
void Createdxf::drawPolygon( void Createdxf::drawPolygon(
const QString &filepath, const QString &filepath,
const QPolygonF &poly, const QPolygonF &poly,
const int &colorcode) const int &colorcode)
{ {
QPolygonF pg = poly; QPolygonF pg = poly;
if(!poly.isClosed()) { if(!poly.isClosed()) {
pg << poly.at(0); // Close it pg << poly.at(0); // Close it
} }
drawPolyline(filepath,pg,colorcode); drawPolyline(filepath,pg,colorcode);
} }
/** /**
@@ -1015,9 +1015,9 @@ void Createdxf::drawText(
int colour, int colour,
double xScaleW) double xScaleW)
{ {
qreal x = point.x() * xScale; qreal x = point.x() * xScale;
qreal y = sheetHeight - (point.y() * yScale); qreal y = sheetHeight - (point.y() * yScale);
drawText(fileName,text,x,y,height * yScale,rotation,colour,xScaleW); drawText(fileName,text,x,y,height * yScale,rotation,colour,xScaleW);
} }
void Createdxf::drawArcEllipse( void Createdxf::drawArcEllipse(
const QString &file_path, const QString &file_path,
@@ -1028,23 +1028,23 @@ void Createdxf::drawArcEllipse(
qreal rotation_angle, qreal rotation_angle,
const int &colorcode) const int &colorcode)
{ {
qreal x = rect.x() * xScale; qreal x = rect.x() * xScale;
qreal y = sheetHeight - rect.y() * yScale; qreal y = sheetHeight - rect.y() * yScale;
qreal w = rect.width() * xScale; qreal w = rect.width() * xScale;
qreal h = rect.height() * yScale; qreal h = rect.height() * yScale;
qreal hotspot_x = hotspot.x() * xScale; qreal hotspot_x = hotspot.x() * xScale;
qreal hotspot_y = sheetHeight - hotspot.y() * yScale; qreal hotspot_y = sheetHeight - hotspot.y() * yScale;
drawArcEllipse(file_path,x,y,w,h,startAngle,spanAngle,hotspot_x,hotspot_y,rotation_angle,colorcode); drawArcEllipse(file_path,x,y,w,h,startAngle,spanAngle,hotspot_x,hotspot_y,rotation_angle,colorcode);
} }
/* /*
* Utility functions * Utility functions
*/ */
static QRectF scaleRect(QRectF rect) //static QRectF scaleRect(QRectF rect)
{ //{
QRectF ro(rect.bottomLeft().x() * Createdxf::xScale, // QRectF ro(rect.bottomLeft().x() * Createdxf::xScale,
Createdxf::sheetHeight - (rect.bottomLeft().y() * Createdxf::yScale), // Createdxf::sheetHeight - (rect.bottomLeft().y() * Createdxf::yScale),
rect.width() * Createdxf::xScale, // rect.width() * Createdxf::xScale,
rect.height() * Createdxf::yScale); // rect.height() * Createdxf::yScale);
return ro; // return ro;
} //}

View File

@@ -34,6 +34,8 @@
#include "changetitleblockcommand.h" #include "changetitleblockcommand.h"
#include "conductorcreator.h" #include "conductorcreator.h"
#include <QDropEvent>
/** /**
Constructeur Constructeur
@param diagram Schema a afficher ; si diagram vaut 0, un nouveau Diagram est utilise @param diagram Schema a afficher ; si diagram vaut 0, un nouveau Diagram est utilise
@@ -200,7 +202,19 @@ void DiagramView::handleElementDrop(QDropEvent *event)
return; return;
} }
diagram()->setEventInterface(new DiagramEventAddElement(location, diagram(), mapToScene(event->pos()))); #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
diagram()->setEventInterface(
new DiagramEventAddElement(
location, diagram(), mapToScene(event->pos())));
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
diagram()->setEventInterface(
new DiagramEventAddElement(
location, diagram(), event->position()));
#endif
//Set focus to the view to get event //Set focus to the view to get event
this->setFocus(); this->setFocus();
} }
@@ -268,7 +282,19 @@ void DiagramView::handleTextDrop(QDropEvent *e) {
iti -> setHtml (e -> mimeData() -> text()); iti -> setHtml (e -> mimeData() -> text());
} }
m_diagram -> undoStack().push(new AddItemCommand<IndependentTextItem *>(iti, m_diagram, mapToScene(e->pos()))); #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
m_diagram -> undoStack().push(
new AddItemCommand<IndependentTextItem *>(
iti, m_diagram, mapToScene(e->pos())));
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
m_diagram -> undoStack().push(
new AddItemCommand<IndependentTextItem *>(
iti, m_diagram, e->position()));
#endif
} }
/** /**
@@ -423,7 +449,14 @@ void DiagramView::mousePressEvent(QMouseEvent *e)
if (m_event_interface && m_event_interface->mousePressEvent(e)) return; if (m_event_interface && m_event_interface->mousePressEvent(e)) return;
//Start drag view when hold the middle button //Start drag view when hold the middle button
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
if (e->button() == Qt::MidButton) if (e->button() == Qt::MidButton)
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
if (e->button() == Qt::MiddleButton)
#endif
{ {
m_drag_last_pos = e->pos(); m_drag_last_pos = e->pos();
viewport()->setCursor(Qt::ClosedHandCursor); viewport()->setCursor(Qt::ClosedHandCursor);
@@ -473,7 +506,14 @@ void DiagramView::mouseMoveEvent(QMouseEvent *e)
if (m_event_interface && m_event_interface->mouseMoveEvent(e)) return; if (m_event_interface && m_event_interface->mouseMoveEvent(e)) return;
//Drag the view //Drag the view
if (e->buttons() == Qt::MidButton) #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
if (e->button() == Qt::MidButton)
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
if (e->button() == Qt::MiddleButton)
#endif
{ {
QScrollBar *h = horizontalScrollBar(); QScrollBar *h = horizontalScrollBar();
QScrollBar *v = verticalScrollBar(); QScrollBar *v = verticalScrollBar();
@@ -534,7 +574,14 @@ void DiagramView::mouseReleaseEvent(QMouseEvent *e)
if (m_event_interface && m_event_interface->mouseReleaseEvent(e)) return; if (m_event_interface && m_event_interface->mouseReleaseEvent(e)) return;
//Stop drag view //Stop drag view
if (e -> button() == Qt::MidButton) #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
if (e->button() == Qt::MidButton)
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
if (e->button() == Qt::MiddleButton)
#endif
{ {
viewport()->setCursor(Qt::ArrowCursor); viewport()->setCursor(Qt::ArrowCursor);
} }
@@ -567,7 +614,15 @@ void DiagramView::mouseReleaseEvent(QMouseEvent *e)
}); });
QMenu *menu = new QMenu(this); QMenu *menu = new QMenu(this);
menu->addAction(act); menu->addAction(act);
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
menu->popup(e->globalPos()); menu->popup(e->globalPos());
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
menu->popup(e->pos());
#endif
} }
m_free_rubberbanding = false; m_free_rubberbanding = false;

View File

@@ -1,17 +1,17 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
@@ -58,14 +58,14 @@ QRectF ElementView::viewedSceneRect() const
{ {
// recupere la taille du widget viewport // recupere la taille du widget viewport
QSize viewport_size = viewport() -> size(); QSize viewport_size = viewport() -> size();
// recupere la transformation viewport -> scene // recupere la transformation viewport -> scene
QTransform view_to_scene = viewportTransform().inverted(); QTransform view_to_scene = viewportTransform().inverted();
// mappe le coin superieur gauche et le coin inferieur droit de la viewport sur la scene // mappe le coin superieur gauche et le coin inferieur droit de la viewport sur la scene
QPointF scene_left_top = view_to_scene.map(QPointF(0.0, 0.0)); QPointF scene_left_top = view_to_scene.map(QPointF(0.0, 0.0));
QPointF scene_right_bottom = view_to_scene.map(QPointF(viewport_size.width(), viewport_size.height())); QPointF scene_right_bottom = view_to_scene.map(QPointF(viewport_size.width(), viewport_size.height()));
// en deduit le rectangle visualise par la scene // en deduit le rectangle visualise par la scene
return(QRectF(scene_left_top, scene_right_bottom)); return(QRectF(scene_left_top, scene_right_bottom));
} }
@@ -213,10 +213,10 @@ void ElementView::paste()
{ {
QString clipboard_text = QApplication::clipboard() -> text(); QString clipboard_text = QApplication::clipboard() -> text();
if (clipboard_text.isEmpty()) return; if (clipboard_text.isEmpty()) return;
QDomDocument document_xml; QDomDocument document_xml;
if (!document_xml.setContent(clipboard_text)) return; if (!document_xml.setContent(clipboard_text)) return;
if (m_scene -> wasCopiedFromThisElement(clipboard_text)) { if (m_scene -> wasCopiedFromThisElement(clipboard_text)) {
// copier/coller avec decalage // copier/coller avec decalage
pasteWithOffset(document_xml); pasteWithOffset(document_xml);
@@ -224,7 +224,7 @@ void ElementView::paste()
// copier/coller par choix de la zone de collage // copier/coller par choix de la zone de collage
QRectF pasted_content_bounding_rect = m_scene -> boundingRectFromXml(document_xml); QRectF pasted_content_bounding_rect = m_scene -> boundingRectFromXml(document_xml);
if (pasted_content_bounding_rect.isEmpty()) return; if (pasted_content_bounding_rect.isEmpty()) return;
to_paste_in_area_ = clipboard_text; to_paste_in_area_ = clipboard_text;
getPasteArea(pasted_content_bounding_rect); getPasteArea(pasted_content_bounding_rect);
} }
@@ -238,13 +238,13 @@ void ElementView::pasteInArea()
{ {
QString clipboard_text = QApplication::clipboard() -> text(); QString clipboard_text = QApplication::clipboard() -> text();
if (clipboard_text.isEmpty()) return; if (clipboard_text.isEmpty()) return;
QDomDocument document_xml; QDomDocument document_xml;
if (!document_xml.setContent(clipboard_text)) return; if (!document_xml.setContent(clipboard_text)) return;
QRectF pasted_content_bounding_rect = m_scene -> boundingRectFromXml(document_xml); QRectF pasted_content_bounding_rect = m_scene -> boundingRectFromXml(document_xml);
if (pasted_content_bounding_rect.isEmpty()) return; if (pasted_content_bounding_rect.isEmpty()) return;
// copier/coller par choix de la zone de collage // copier/coller par choix de la zone de collage
to_paste_in_area_ = clipboard_text; to_paste_in_area_ = clipboard_text;
getPasteArea(pasted_content_bounding_rect); getPasteArea(pasted_content_bounding_rect);
@@ -260,10 +260,10 @@ void ElementView::pasteInArea()
ElementContent ElementView::paste(const QPointF &position) { ElementContent ElementView::paste(const QPointF &position) {
QString clipboard_text = QApplication::clipboard() -> text(); QString clipboard_text = QApplication::clipboard() -> text();
if (clipboard_text.isEmpty()) return(ElementContent()); if (clipboard_text.isEmpty()) return(ElementContent());
QDomDocument document_xml; QDomDocument document_xml;
if (!document_xml.setContent(clipboard_text)) return(ElementContent()); if (!document_xml.setContent(clipboard_text)) return(ElementContent());
// objet pour recuperer le contenu ajoute au schema par le coller // objet pour recuperer le contenu ajoute au schema par le coller
return(paste(document_xml, position)); return(paste(document_xml, position));
} }
@@ -274,7 +274,7 @@ ElementContent ElementView::paste(const QPointF &position) {
void ElementView::getPasteArea(const QRectF &to_paste) { void ElementView::getPasteArea(const QRectF &to_paste) {
// on copie le rectangle fourni - on s'interesse a ses dimensions, pas a sa position // on copie le rectangle fourni - on s'interesse a ses dimensions, pas a sa position
QRectF used_rect(to_paste); QRectF used_rect(to_paste);
// on lui attribue pour centre l'origine du repere // on lui attribue pour centre l'origine du repere
if (underMouse()) { if (underMouse()) {
used_rect.moveCenter(mapToScene(mapFromGlobal(QCursor::pos()))); used_rect.moveCenter(mapToScene(mapFromGlobal(QCursor::pos())));
@@ -290,7 +290,7 @@ void ElementView::getPasteArea(const QRectF &to_paste) {
*/ */
ElementContent ElementView::pasteAreaDefined(const QRectF &target_rect) { ElementContent ElementView::pasteAreaDefined(const QRectF &target_rect) {
if (to_paste_in_area_.isEmpty()) return(ElementContent()); if (to_paste_in_area_.isEmpty()) return(ElementContent());
QDomDocument xml_document; QDomDocument xml_document;
if (!xml_document.setContent(to_paste_in_area_)) { if (!xml_document.setContent(to_paste_in_area_)) {
to_paste_in_area_.clear(); to_paste_in_area_.clear();
@@ -309,7 +309,7 @@ ElementContent ElementView::paste(const QDomDocument &xml_document, const QPoint
// objet pour recuperer le contenu ajoute au schema par le coller // objet pour recuperer le contenu ajoute au schema par le coller
ElementContent content_pasted; ElementContent content_pasted;
m_scene -> fromXml(xml_document, pos, false, &content_pasted); m_scene -> fromXml(xml_document, pos, false, &content_pasted);
// si quelque chose a effectivement ete ajoute au schema, on cree un objet d'annulation // si quelque chose a effectivement ete ajoute au schema, on cree un objet d'annulation
if (content_pasted.count()) { if (content_pasted.count()) {
m_scene -> clearSelection(); m_scene -> clearSelection();
@@ -326,11 +326,11 @@ ElementContent ElementView::paste(const QDomDocument &xml_document, const QPoint
ElementContent ElementView::pasteWithOffset(const QDomDocument &xml_document) { ElementContent ElementView::pasteWithOffset(const QDomDocument &xml_document) {
// objet pour recuperer le contenu ajoute au schema par le coller // objet pour recuperer le contenu ajoute au schema par le coller
ElementContent content_pasted; ElementContent content_pasted;
// rectangle source // rectangle source
QRectF pasted_content_bounding_rect = m_scene -> boundingRectFromXml(xml_document); QRectF pasted_content_bounding_rect = m_scene -> boundingRectFromXml(xml_document);
if (pasted_content_bounding_rect.isEmpty()) return(content_pasted); if (pasted_content_bounding_rect.isEmpty()) return(content_pasted);
// copier/coller avec decalage // copier/coller avec decalage
QRectF final_pasted_content_bounding_rect; QRectF final_pasted_content_bounding_rect;
++ offset_paste_count_; ++ offset_paste_count_;
@@ -346,7 +346,7 @@ ElementContent ElementView::pasteWithOffset(const QDomDocument &xml_document) {
} else { } else {
pasted_content_bounding_rect.moveTopLeft(start_top_left_corner_); pasted_content_bounding_rect.moveTopLeft(start_top_left_corner_);
} }
// on applique le decalage qui convient // on applique le decalage qui convient
final_pasted_content_bounding_rect = applyMovement( final_pasted_content_bounding_rect = applyMovement(
pasted_content_bounding_rect, pasted_content_bounding_rect,
@@ -356,7 +356,7 @@ ElementContent ElementView::pasteWithOffset(const QDomDocument &xml_document) {
QPointF old_start_top_left_corner = start_top_left_corner_; QPointF old_start_top_left_corner = start_top_left_corner_;
start_top_left_corner_ = final_pasted_content_bounding_rect.topLeft(); start_top_left_corner_ = final_pasted_content_bounding_rect.topLeft();
m_scene -> fromXml(xml_document, start_top_left_corner_, false, &content_pasted); m_scene -> fromXml(xml_document, start_top_left_corner_, false, &content_pasted);
// si quelque chose a effectivement ete ajoute au schema, on cree un objet d'annulation // si quelque chose a effectivement ete ajoute au schema, on cree un objet d'annulation
if (content_pasted.count()) { if (content_pasted.count()) {
m_scene -> clearSelection(); m_scene -> clearSelection();
@@ -373,7 +373,14 @@ ElementContent ElementView::pasteWithOffset(const QDomDocument &xml_document) {
@param e QMouseEvent decrivant l'evenement souris @param e QMouseEvent decrivant l'evenement souris
*/ */
void ElementView::mousePressEvent(QMouseEvent *e) { void ElementView::mousePressEvent(QMouseEvent *e) {
if (e->buttons() == Qt::MidButton) #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
if (e->button() == Qt::MidButton)
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
if (e->button() == Qt::MiddleButton)
#endif
{ {
setCursor( (Qt::ClosedHandCursor)); setCursor( (Qt::ClosedHandCursor));
reference_view_ = e->pos(); reference_view_ = e->pos();
@@ -387,7 +394,14 @@ void ElementView::mousePressEvent(QMouseEvent *e) {
Manage the event move mouse Manage the event move mouse
*/ */
void ElementView::mouseMoveEvent(QMouseEvent *e) { void ElementView::mouseMoveEvent(QMouseEvent *e) {
if (e->buttons() == Qt::MidButton) #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
if (e->button() == Qt::MidButton)
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
if (e->button() == Qt::MiddleButton)
#endif
{ {
QScrollBar *h = horizontalScrollBar(); QScrollBar *h = horizontalScrollBar();
QScrollBar *v = verticalScrollBar(); QScrollBar *v = verticalScrollBar();
@@ -405,7 +419,15 @@ void ElementView::mouseMoveEvent(QMouseEvent *e) {
Manage event release click mouse Manage event release click mouse
*/ */
void ElementView::mouseReleaseEvent(QMouseEvent *e) { void ElementView::mouseReleaseEvent(QMouseEvent *e) {
if (e -> button() == Qt::MidButton) { #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
if (e->button() == Qt::MidButton)
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
if (e->button() == Qt::MiddleButton)
#endif
{
setCursor(Qt::ArrowCursor); setCursor(Qt::ArrowCursor);
adjustSceneRect(); adjustSceneRect();
return; return;
@@ -484,20 +506,20 @@ bool ElementView::gestureEvent(QGestureEvent *event){
*/ */
void ElementView::drawBackground(QPainter *p, const QRectF &r) { void ElementView::drawBackground(QPainter *p, const QRectF &r) {
p -> save(); p -> save();
// desactive tout antialiasing, sauf pour le texte // desactive tout antialiasing, sauf pour le texte
p -> setRenderHint(QPainter::Antialiasing, false); p -> setRenderHint(QPainter::Antialiasing, false);
p -> setRenderHint(QPainter::TextAntialiasing, true); p -> setRenderHint(QPainter::TextAntialiasing, true);
p -> setRenderHint(QPainter::SmoothPixmapTransform, false); p -> setRenderHint(QPainter::SmoothPixmapTransform, false);
// dessine un fond blanc // dessine un fond blanc
p -> setPen(Qt::NoPen); p -> setPen(Qt::NoPen);
p -> setBrush(Qt::white); p -> setBrush(Qt::white);
p -> drawRect(r); p -> drawRect(r);
// determine le zoom en cours // determine le zoom en cours
qreal zoom_factor = transform().m11(); qreal zoom_factor = transform().m11();
// choisit la granularite de la grille en fonction du zoom en cours // choisit la granularite de la grille en fonction du zoom en cours
int drawn_x_grid = 1;//scene_ -> xGrid(); int drawn_x_grid = 1;//scene_ -> xGrid();
int drawn_y_grid = 1;//scene_ -> yGrid(); int drawn_y_grid = 1;//scene_ -> yGrid();
@@ -516,13 +538,13 @@ void ElementView::drawBackground(QPainter *p, const QRectF &r) {
} else if (zoom_factor < 10.0) { //< grid 2*2 } else if (zoom_factor < 10.0) { //< grid 2*2
drawn_x_grid *= 2; drawn_x_grid *= 2;
drawn_y_grid *= 2; drawn_y_grid *= 2;
draw_cross = true; draw_cross = true;
} else { //< grid 1*1 } else { //< grid 1*1
draw_cross = true; draw_cross = true;
} }
m_scene->setGrid(drawn_x_grid, drawn_y_grid); m_scene->setGrid(drawn_x_grid, drawn_y_grid);
if (draw_grid) { if (draw_grid) {
// draw the dot of the grid // draw the dot of the grid
QPen pen(Qt::black); QPen pen(Qt::black);
@@ -531,12 +553,12 @@ void ElementView::drawBackground(QPainter *p, const QRectF &r) {
p -> setBrush(Qt::NoBrush); p -> setBrush(Qt::NoBrush);
qreal limite_x = r.x() + r.width(); qreal limite_x = r.x() + r.width();
qreal limite_y = r.y() + r.height(); qreal limite_y = r.y() + r.height();
int g_x = (int)ceil(r.x()); int g_x = (int)ceil(r.x());
while (g_x % drawn_x_grid) ++ g_x; while (g_x % drawn_x_grid) ++ g_x;
int g_y = (int)ceil(r.y()); int g_y = (int)ceil(r.y());
while (g_y % drawn_y_grid) ++ g_y; while (g_y % drawn_y_grid) ++ g_y;
for (int gx = g_x ; gx < limite_x ; gx += drawn_x_grid) { for (int gx = g_x ; gx < limite_x ; gx += drawn_x_grid) {
for (int gy = g_y ; gy < limite_y ; gy += drawn_y_grid) { for (int gy = g_y ; gy < limite_y ; gy += drawn_y_grid) {
if (draw_cross) { if (draw_cross) {

View File

@@ -1,17 +1,17 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
@@ -61,9 +61,16 @@ void PartArc::paint(QPainter *painter, const QStyleOptionGraphicsItem *options,
//Always remove the brush //Always remove the brush
painter -> setBrush(Qt::NoBrush); painter -> setBrush(Qt::NoBrush);
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); 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);
#endif
painter -> setPen(t); painter -> setPen(t);
if (isSelected()) if (isSelected())
{ {
painter->save(); painter->save();
@@ -79,7 +86,7 @@ void PartArc::paint(QPainter *painter, const QStyleOptionGraphicsItem *options,
t.setColor(Qt::red); t.setColor(Qt::red);
painter -> setPen(t); 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) if (m_hovered)
@@ -196,8 +203,8 @@ QVariant PartArc::itemChange(QGraphicsItem::GraphicsItemChange change, const QVa
{ {
//When item is selected, he must to be up to date whene the selection in the scene change, for display or not the handler, //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. //according to the number of selected items.
connect(scene(), &QGraphicsScene::selectionChanged, this, &PartArc::sceneSelectionChanged); connect(scene(), &QGraphicsScene::selectionChanged, this, &PartArc::sceneSelectionChanged);
if (scene()->selectedItems().size() == 1) if (scene()->selectedItems().size() == 1)
addHandler(); addHandler();
} }
@@ -215,10 +222,10 @@ QVariant PartArc::itemChange(QGraphicsItem::GraphicsItemChange change, const QVa
{ {
if(scene()) if(scene())
disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartArc::sceneSelectionChanged); 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);
} }
@@ -234,7 +241,7 @@ bool PartArc::sceneEventFilter(QGraphicsItem *watched, QEvent *event)
if(watched->type() == QetGraphicsHandlerItem::Type) if(watched->type() == QetGraphicsHandlerItem::Type)
{ {
QetGraphicsHandlerItem *qghi = qgraphicsitem_cast<QetGraphicsHandlerItem *>(watched); QetGraphicsHandlerItem *qghi = qgraphicsitem_cast<QetGraphicsHandlerItem *>(watched);
if(m_handler_vector.contains(qghi)) //Handler must be in m_vector_index, then we can start resize 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); m_vector_index = m_handler_vector.indexOf(qghi);
@@ -258,7 +265,7 @@ bool PartArc::sceneEventFilter(QGraphicsItem *watched, QEvent *event)
} }
} }
} }
return false; return false;
} }
@@ -266,7 +273,7 @@ bool PartArc::sceneEventFilter(QGraphicsItem *watched, QEvent *event)
@brief PartArc::switchResizeMode @brief PartArc::switchResizeMode
*/ */
void PartArc::switchResizeMode() void PartArc::switchResizeMode()
{ {
if (m_resize_mode == 1) if (m_resize_mode == 1)
{ {
m_resize_mode = 2; m_resize_mode = 2;
@@ -274,24 +281,24 @@ void PartArc::switchResizeMode()
qghi->setColor(Qt::darkGreen); qghi->setColor(Qt::darkGreen);
} }
else if (m_resize_mode == 2) else if (m_resize_mode == 2)
{ {
m_resize_mode = 3; m_resize_mode = 3;
//From rect mode to angle mode, then numbers of handlers change //From rect mode to angle mode, then numbers of handlers change
removeHandler(); removeHandler();
addHandler(); addHandler();
for (QetGraphicsHandlerItem *qghi : m_handler_vector) for (QetGraphicsHandlerItem *qghi : m_handler_vector)
qghi->setColor(Qt::magenta); qghi->setColor(Qt::magenta);
} }
else else
{ {
m_resize_mode = 1; m_resize_mode = 1;
//From angle mode to rect mode, then numbers of handlers change //From angle mode to rect mode, then numbers of handlers change
removeHandler(); removeHandler();
addHandler(); addHandler();
for (QetGraphicsHandlerItem *qghi : m_handler_vector) for (QetGraphicsHandlerItem *qghi : m_handler_vector)
qghi->setColor(Qt::blue); qghi->setColor(Qt::blue);
} }
@@ -304,21 +311,21 @@ void PartArc::adjusteHandlerPos()
{ {
if (m_handler_vector.isEmpty()) if (m_handler_vector.isEmpty())
return; return;
QVector <QPointF> points_vector; QVector <QPointF> points_vector;
if(m_resize_mode == 3) if(m_resize_mode == 3)
points_vector = QetGraphicsHandlerUtility::pointsForArc(m_rect, m_start_angle/16, m_span_angle/16); points_vector = QetGraphicsHandlerUtility::pointsForArc(m_rect, m_start_angle/16, m_span_angle/16);
else else
points_vector = QetGraphicsHandlerUtility::pointsForRect(m_rect); points_vector = QetGraphicsHandlerUtility::pointsForRect(m_rect);
if (m_handler_vector.size() == points_vector.size()) if (m_handler_vector.size() == points_vector.size())
{ {
points_vector = mapToScene(points_vector); points_vector = mapToScene(points_vector);
for (int i = 0 ; i < points_vector.size() ; ++i) for (int i = 0 ; i < points_vector.size() ; ++i)
m_handler_vector.at(i)->setPos(points_vector.at(i)); m_handler_vector.at(i)->setPos(points_vector.at(i));
} }
} }
/** /**
@@ -330,7 +337,7 @@ void PartArc::handlerMousePressEvent(QetGraphicsHandlerItem *qghi, QGraphicsScen
{ {
Q_UNUSED(qghi) Q_UNUSED(qghi)
Q_UNUSED(event) Q_UNUSED(event)
if (m_resize_mode == 3) //Resize angle if (m_resize_mode == 3) //Resize angle
{ {
if (m_vector_index == 0) if (m_vector_index == 0)
@@ -368,12 +375,12 @@ void PartArc::handlerMousePressEvent(QetGraphicsHandlerItem *qghi, QGraphicsScen
void PartArc::handlerMouseMoveEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event) void PartArc::handlerMouseMoveEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event)
{ {
Q_UNUSED(qghi) Q_UNUSED(qghi)
QPointF new_pos = event->scenePos(); QPointF new_pos = event->scenePos();
if (event->modifiers() != Qt::ControlModifier) if (event->modifiers() != Qt::ControlModifier)
new_pos = elementScene()->snapToGrid(event->scenePos()); new_pos = elementScene()->snapToGrid(event->scenePos());
new_pos = mapFromScene(new_pos); new_pos = mapFromScene(new_pos);
if (m_resize_mode == 1) if (m_resize_mode == 1)
setRect(QetGraphicsHandlerUtility::rectForPosAtIndex(m_rect, new_pos, m_vector_index)); setRect(QetGraphicsHandlerUtility::rectForPosAtIndex(m_rect, new_pos, m_vector_index));
else if (m_resize_mode == 2) else if (m_resize_mode == 2)
@@ -403,7 +410,7 @@ void PartArc::handlerMouseReleaseEvent(QetGraphicsHandlerItem *qghi, QGraphicsSc
{ {
Q_UNUSED(qghi) Q_UNUSED(qghi)
Q_UNUSED(event) Q_UNUSED(event)
if (m_resize_mode == 3) if (m_resize_mode == 3)
{ {
if (m_vector_index == 0) if (m_vector_index == 0)
@@ -461,7 +468,7 @@ void PartArc::addHandler()
} }
else else
m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointsForRect(m_rect))); m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointsForRect(m_rect)));
for(QetGraphicsHandlerItem *handler : m_handler_vector) for(QetGraphicsHandlerItem *handler : m_handler_vector)
{ {
QColor color = Qt::blue; QColor color = Qt::blue;
@@ -469,7 +476,7 @@ void PartArc::addHandler()
color = Qt::darkGreen; color = Qt::darkGreen;
else if (m_resize_mode == 3) else if (m_resize_mode == 3)
color = Qt::magenta; color = Qt::magenta;
handler->setColor(color); handler->setColor(color);
scene()->addItem(handler); scene()->addItem(handler);
handler->installSceneEventFilter(this); handler->installSceneEventFilter(this);

View File

@@ -1,17 +1,17 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
@@ -55,8 +55,15 @@ void PartEllipse::paint(QPainter *painter, const QStyleOptionGraphicsItem *optio
applyStylesToQPainter(*painter); applyStylesToQPainter(*painter);
QPen t = painter -> pen(); QPen t = painter -> pen();
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);
#endif
if (isSelected()) if (isSelected())
t.setColor(Qt::red); t.setColor(Qt::red);
@@ -159,7 +166,7 @@ void PartEllipse::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{ {
if (event->button() == Qt::LeftButton && event->buttonDownPos(Qt::LeftButton) == event->pos()) if (event->button() == Qt::LeftButton && event->buttonDownPos(Qt::LeftButton) == event->pos())
switchResizeMode(); switchResizeMode();
CustomElementGraphicPart::mouseReleaseEvent(event); CustomElementGraphicPart::mouseReleaseEvent(event);
} }
@@ -177,8 +184,8 @@ QVariant PartEllipse::itemChange(QGraphicsItem::GraphicsItemChange change, const
{ {
//When item is selected, he must to be up to date whene the selection in the scene change, for display or not the handler, //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. //according to the number of selected items.
connect(scene(), &QGraphicsScene::selectionChanged, this, &PartEllipse::sceneSelectionChanged); connect(scene(), &QGraphicsScene::selectionChanged, this, &PartEllipse::sceneSelectionChanged);
if (scene()->selectedItems().size() == 1) if (scene()->selectedItems().size() == 1)
addHandler(); addHandler();
} }
@@ -196,10 +203,10 @@ QVariant PartEllipse::itemChange(QGraphicsItem::GraphicsItemChange change, const
{ {
if(scene()) if(scene())
disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartEllipse::sceneSelectionChanged); 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);
} }
@@ -215,7 +222,7 @@ bool PartEllipse::sceneEventFilter(QGraphicsItem *watched, QEvent *event)
if(watched->type() == QetGraphicsHandlerItem::Type) if(watched->type() == QetGraphicsHandlerItem::Type)
{ {
QetGraphicsHandlerItem *qghi = qgraphicsitem_cast<QetGraphicsHandlerItem *>(watched); QetGraphicsHandlerItem *qghi = qgraphicsitem_cast<QetGraphicsHandlerItem *>(watched);
if(m_handler_vector.contains(qghi)) //Handler must be in m_vector_index, then we can start resize 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); m_vector_index = m_handler_vector.indexOf(qghi);
@@ -239,7 +246,7 @@ bool PartEllipse::sceneEventFilter(QGraphicsItem *watched, QEvent *event)
} }
} }
} }
return false; return false;
} }
@@ -266,9 +273,9 @@ void PartEllipse::adjusteHandlerPos()
{ {
if (m_handler_vector.isEmpty()) if (m_handler_vector.isEmpty())
return; 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()) if (m_handler_vector.size() == points_vector.size())
{ {
points_vector = mapToScene(points_vector); points_vector = mapToScene(points_vector);
@@ -290,7 +297,7 @@ void PartEllipse::handlerMousePressEvent(QetGraphicsHandlerItem *qghi, QGraphics
m_undo_command = new QPropertyUndoCommand(this, "rect", QVariant(m_rect)); m_undo_command = new QPropertyUndoCommand(this, "rect", QVariant(m_rect));
m_undo_command->setText(tr("Modifier un rectangle")); m_undo_command->setText(tr("Modifier un rectangle"));
m_undo_command->enableAnimation(); m_undo_command->enableAnimation();
return; return;
} }
/** /**
@@ -301,17 +308,17 @@ void PartEllipse::handlerMousePressEvent(QetGraphicsHandlerItem *qghi, QGraphics
void PartEllipse::handlerMouseMoveEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event) void PartEllipse::handlerMouseMoveEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event)
{ {
Q_UNUSED(qghi); Q_UNUSED(qghi);
QPointF new_pos = event->scenePos(); QPointF new_pos = event->scenePos();
if (event->modifiers() != Qt::ControlModifier) if (event->modifiers() != Qt::ControlModifier)
new_pos = elementScene()->snapToGrid(event->scenePos()); new_pos = elementScene()->snapToGrid(event->scenePos());
new_pos = mapFromScene(new_pos); new_pos = mapFromScene(new_pos);
if (m_resize_mode == 1) if (m_resize_mode == 1)
setRect(QetGraphicsHandlerUtility::rectForPosAtIndex(m_rect, new_pos, m_vector_index)); setRect(QetGraphicsHandlerUtility::rectForPosAtIndex(m_rect, new_pos, m_vector_index));
else else
setRect(QetGraphicsHandlerUtility::mirrorRectForPosAtIndex(m_rect, new_pos, m_vector_index)); setRect(QetGraphicsHandlerUtility::mirrorRectForPosAtIndex(m_rect, new_pos, m_vector_index));
adjusteHandlerPos(); adjusteHandlerPos();
} }
@@ -324,7 +331,7 @@ void PartEllipse::handlerMouseReleaseEvent(QetGraphicsHandlerItem *qghi, QGraphi
{ {
Q_UNUSED(qghi); Q_UNUSED(qghi);
Q_UNUSED(event); Q_UNUSED(event);
m_undo_command->setNewValue(QVariant(m_rect)); m_undo_command->setNewValue(QVariant(m_rect));
elementScene()->undoStack().push(m_undo_command); elementScene()->undoStack().push(m_undo_command);
m_undo_command = nullptr; m_undo_command = nullptr;
@@ -350,15 +357,15 @@ void PartEllipse::sceneSelectionChanged()
void PartEllipse::addHandler() void PartEllipse::addHandler()
{ {
if (m_handler_vector.isEmpty() && scene()) if (m_handler_vector.isEmpty() && scene())
{ {
m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointsForRect(m_rect))); m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointsForRect(m_rect)));
for(QetGraphicsHandlerItem *handler : m_handler_vector) for(QetGraphicsHandlerItem *handler : m_handler_vector)
{ {
QColor color = Qt::blue; QColor color = Qt::blue;
if (m_resize_mode == 2) if (m_resize_mode == 2)
color = Qt::darkGreen; color = Qt::darkGreen;
handler->setColor(color); handler->setColor(color);
scene()->addItem(handler); scene()->addItem(handler);
handler->installSceneEventFilter(this); handler->installSceneEventFilter(this);

View File

@@ -1,17 +1,17 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
@@ -42,7 +42,7 @@ PartLine::~PartLine()
{ {
if(m_undo_command) if(m_undo_command)
delete m_undo_command; delete m_undo_command;
removeHandler(); removeHandler();
} }
@@ -79,12 +79,19 @@ void PartLine::paint(QPainter *painter, const QStyleOptionGraphicsItem *options,
applyStylesToQPainter(*painter); applyStylesToQPainter(*painter);
QPen t = painter -> pen(); QPen t = painter -> pen();
t.setJoinStyle(Qt::MiterJoin); t.setJoinStyle(Qt::MiterJoin);
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);
#endif
if (isSelected()) t.setColor(Qt::red); if (isSelected()) t.setColor(Qt::red);
painter -> setPen(t); painter -> setPen(t);
if (first_end || second_end) if (first_end || second_end)
painter -> drawPath(path()); painter -> drawPath(path());
else else
@@ -106,7 +113,7 @@ const QDomElement PartLine::toXml(QDomDocument &xml_document) const
{ {
QPointF p1(sceneP1()); QPointF p1(sceneP1());
QPointF p2(sceneP2()); QPointF p2(sceneP2());
QDomElement xml_element = xml_document.createElement("line"); QDomElement xml_element = xml_document.createElement("line");
xml_element.setAttribute("x1", QString("%1").arg(p1.x())); xml_element.setAttribute("x1", QString("%1").arg(p1.x()));
xml_element.setAttribute("y1", QString("%1").arg(p1.y())); xml_element.setAttribute("y1", QString("%1").arg(p1.y()));
@@ -116,7 +123,7 @@ const QDomElement PartLine::toXml(QDomDocument &xml_document) const
xml_element.setAttribute("length1", QString("%1").arg(first_length)); xml_element.setAttribute("length1", QString("%1").arg(first_length));
xml_element.setAttribute("end2", Qet::endTypeToString(second_end)); xml_element.setAttribute("end2", Qet::endTypeToString(second_end));
xml_element.setAttribute("length2", QString("%1").arg(second_length)); xml_element.setAttribute("length2", QString("%1").arg(second_length));
stylesToXml(xml_element); stylesToXml(xml_element);
return(xml_element); return(xml_element);
} }
@@ -153,8 +160,8 @@ QVariant PartLine::itemChange(QGraphicsItem::GraphicsItemChange change, const QV
{ {
//When item is selected, he must to be up to date whene the selection in the scene change, for display or not the handler, //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. //according to the number of selected items.
connect(scene(), &QGraphicsScene::selectionChanged, this, &PartLine::sceneSelectionChanged); connect(scene(), &QGraphicsScene::selectionChanged, this, &PartLine::sceneSelectionChanged);
if (scene()->selectedItems().size() == 1) if (scene()->selectedItems().size() == 1)
addHandler(); addHandler();
} }
@@ -172,10 +179,10 @@ QVariant PartLine::itemChange(QGraphicsItem::GraphicsItemChange change, const QV
{ {
if(scene()) if(scene())
disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartLine::sceneSelectionChanged); disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartLine::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);
} }
@@ -191,7 +198,7 @@ bool PartLine::sceneEventFilter(QGraphicsItem *watched, QEvent *event)
if(watched->type() == QetGraphicsHandlerItem::Type) if(watched->type() == QetGraphicsHandlerItem::Type)
{ {
QetGraphicsHandlerItem *qghi = qgraphicsitem_cast<QetGraphicsHandlerItem *>(watched); QetGraphicsHandlerItem *qghi = qgraphicsitem_cast<QetGraphicsHandlerItem *>(watched);
if(m_handler_vector.contains(qghi)) //Handler must be in m_vector_index, then we can start resize 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); m_vector_index = m_handler_vector.indexOf(qghi);
@@ -215,7 +222,7 @@ bool PartLine::sceneEventFilter(QGraphicsItem *watched, QEvent *event)
} }
} }
} }
return false; return false;
} }
@@ -227,10 +234,10 @@ void PartLine::adjusteHandlerPos()
{ {
if(m_handler_vector.isEmpty()) if(m_handler_vector.isEmpty())
return; return;
QVector<QPointF> points_vector; QVector<QPointF> points_vector;
points_vector << m_line.p1() << m_line.p2(); points_vector << m_line.p1() << m_line.p2();
if (m_handler_vector.size() == points_vector.size()) if (m_handler_vector.size() == points_vector.size())
{ {
points_vector = mapToScene(points_vector); points_vector = mapToScene(points_vector);
@@ -248,7 +255,7 @@ void PartLine::handlerMousePressEvent(QetGraphicsHandlerItem *qghi, QGraphicsSce
{ {
Q_UNUSED(qghi) Q_UNUSED(qghi)
Q_UNUSED(event) Q_UNUSED(event)
m_undo_command = new QPropertyUndoCommand(this, "line", QVariant(m_line)); m_undo_command = new QPropertyUndoCommand(this, "line", QVariant(m_line));
m_undo_command->setText(tr("Modifier une ligne")); m_undo_command->setText(tr("Modifier une ligne"));
m_undo_command->enableAnimation(); m_undo_command->enableAnimation();
@@ -263,12 +270,12 @@ void PartLine::handlerMousePressEvent(QetGraphicsHandlerItem *qghi, QGraphicsSce
void PartLine::handlerMouseMoveEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event) void PartLine::handlerMouseMoveEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event)
{ {
Q_UNUSED(qghi) Q_UNUSED(qghi)
QPointF new_pos = event->scenePos(); QPointF new_pos = event->scenePos();
if (event->modifiers() != Qt::ControlModifier) if (event->modifiers() != Qt::ControlModifier)
new_pos = elementScene()->snapToGrid(event->scenePos()); new_pos = elementScene()->snapToGrid(event->scenePos());
new_pos = mapFromScene(new_pos); new_pos = mapFromScene(new_pos);
prepareGeometryChange(); prepareGeometryChange();
if (m_vector_index == 0) if (m_vector_index == 0)
m_line.setP1(new_pos); m_line.setP1(new_pos);
@@ -276,7 +283,7 @@ void PartLine::handlerMouseMoveEvent(QetGraphicsHandlerItem *qghi, QGraphicsScen
m_line.setP2(new_pos); m_line.setP2(new_pos);
emit lineChanged(); emit lineChanged();
adjusteHandlerPos(); adjusteHandlerPos();
} }
@@ -289,7 +296,7 @@ void PartLine::handlerMouseReleaseEvent(QetGraphicsHandlerItem *qghi, QGraphicsS
{ {
Q_UNUSED(qghi) Q_UNUSED(qghi)
Q_UNUSED(event) Q_UNUSED(event)
m_undo_command->setNewValue(QVariant(m_line)); m_undo_command->setNewValue(QVariant(m_line));
elementScene()->undoStack().push(m_undo_command); elementScene()->undoStack().push(m_undo_command);
m_undo_command = nullptr; m_undo_command = nullptr;
@@ -318,9 +325,9 @@ void PartLine::addHandler()
{ {
QVector<QPointF> points_vector; QVector<QPointF> points_vector;
points_vector << m_line.p1() << m_line.p2(); points_vector << m_line.p1() << m_line.p2();
m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(points_vector)); m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(points_vector));
for(QetGraphicsHandlerItem *handler : m_handler_vector) for(QetGraphicsHandlerItem *handler : m_handler_vector)
{ {
handler->setColor(Qt::blue); handler->setColor(Qt::blue);
@@ -416,12 +423,12 @@ QRectF PartLine::firstEndCircleRect() const
QList<QPointF> interesting_points = fourEndPoints(m_line.p1(), QList<QPointF> interesting_points = fourEndPoints(m_line.p1(),
m_line.p2(), m_line.p2(),
first_length); first_length);
QRectF end_rect( QRectF end_rect(
interesting_points[0] - QPointF(first_length, first_length), interesting_points[0] - QPointF(first_length, first_length),
QSizeF(2.0 * first_length, 2.0 * first_length) QSizeF(2.0 * first_length, 2.0 * first_length)
); );
return(end_rect); return(end_rect);
} }
@@ -434,12 +441,12 @@ QRectF PartLine::secondEndCircleRect() const
QList<QPointF> interesting_points = fourEndPoints(m_line.p2(), QList<QPointF> interesting_points = fourEndPoints(m_line.p2(),
m_line.p1(), m_line.p1(),
second_length); second_length);
QRectF end_rect( QRectF end_rect(
interesting_points[0] - QPointF(second_length, second_length), interesting_points[0] - QPointF(second_length, second_length),
QSizeF(2.0 * second_length, 2.0 * second_length) QSizeF(2.0 * second_length, 2.0 * second_length)
); );
return(end_rect); return(end_rect);
} }
@@ -448,7 +455,7 @@ QRectF PartLine::secondEndCircleRect() const
@return the bounding rect of this part @return the bounding rect of this part
*/ */
QRectF PartLine::boundingRect() const QRectF PartLine::boundingRect() const
{ {
QRectF bound; QRectF bound;
if (first_end || second_end) if (first_end || second_end)
bound = path().boundingRect(); bound = path().boundingRect();
@@ -537,13 +544,13 @@ QList<QPointF> PartLine::fourEndPoints(const QPointF &end_point, const QPointF &
//Unitary vector and perpendicular vector //Unitary vector and perpendicular vector
QPointF u(line_vector / line_length * length); QPointF u(line_vector / line_length * length);
QPointF v(-u.y(), u.x()); QPointF v(-u.y(), u.x());
// points O, A, B, C // points O, A, B, C
QPointF o(end_point - u); QPointF o(end_point - u);
QPointF a(o - u); QPointF a(o - u);
QPointF b(o + v); QPointF b(o + v);
QPointF c(o - v); QPointF c(o - v);
return(QList<QPointF>() << o << a << b << c); return(QList<QPointF>() << o << a << b << c);
} }

View File

@@ -1,17 +1,17 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
@@ -66,7 +66,14 @@ void PartPolygon::paint(QPainter *painter, const QStyleOptionGraphicsItem *optio
applyStylesToQPainter(*painter); 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); 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);
#endif
if (isSelected()) t.setColor(Qt::red); if (isSelected()) t.setColor(Qt::red);
painter -> setPen(t); painter -> setPen(t);
@@ -95,7 +102,7 @@ void PartPolygon::fromXml(const QDomElement &qde)
else break; else break;
} }
QPolygonF temp_polygon; QPolygonF temp_polygon;
for (int j = 1 ; j < i ; ++ j) for (int j = 1 ; j < i ; ++ j)
{ {
@@ -103,7 +110,7 @@ void PartPolygon::fromXml(const QDomElement &qde)
qde.attribute(QString("y%1").arg(j)).toDouble()); qde.attribute(QString("y%1").arg(j)).toDouble());
} }
m_polygon = temp_polygon; m_polygon = temp_polygon;
m_closed = qde.attribute("closed") != "false"; m_closed = qde.attribute("closed") != "false";
} }
@@ -290,7 +297,7 @@ void PartPolygon::resetAllHandlerColor()
@brief PartPolygon::itemChange @brief PartPolygon::itemChange
@param change @param change
@param value @param value
@return @return
*/ */
QVariant PartPolygon::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value) QVariant PartPolygon::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value)
{ {
@@ -300,8 +307,8 @@ QVariant PartPolygon::itemChange(QGraphicsItem::GraphicsItemChange change, const
{ {
//When item is selected, he must to be up to date whene the selection in the scene change, for display or not the handler, //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. //according to the number of selected items.
connect(scene(), &QGraphicsScene::selectionChanged, this, &PartPolygon::sceneSelectionChanged); connect(scene(), &QGraphicsScene::selectionChanged, this, &PartPolygon::sceneSelectionChanged);
if (scene()->selectedItems().size() == 1) if (scene()->selectedItems().size() == 1)
addHandler(); addHandler();
} }
@@ -319,10 +326,10 @@ QVariant PartPolygon::itemChange(QGraphicsItem::GraphicsItemChange change, const
{ {
if(scene()) if(scene())
disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartPolygon::sceneSelectionChanged); disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartPolygon::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);
} }
@@ -330,7 +337,7 @@ QVariant PartPolygon::itemChange(QGraphicsItem::GraphicsItemChange change, const
@brief PartPolygon::sceneEventFilter @brief PartPolygon::sceneEventFilter
@param watched @param watched
@param event @param event
@return @return
*/ */
bool PartPolygon::sceneEventFilter(QGraphicsItem *watched, QEvent *event) bool PartPolygon::sceneEventFilter(QGraphicsItem *watched, QEvent *event)
{ {
@@ -338,7 +345,7 @@ bool PartPolygon::sceneEventFilter(QGraphicsItem *watched, QEvent *event)
if(watched->type() == QetGraphicsHandlerItem::Type) if(watched->type() == QetGraphicsHandlerItem::Type)
{ {
QetGraphicsHandlerItem *qghi = qgraphicsitem_cast<QetGraphicsHandlerItem *>(watched); QetGraphicsHandlerItem *qghi = qgraphicsitem_cast<QetGraphicsHandlerItem *>(watched);
if(m_handler_vector.contains(qghi)) //Handler must be in m_vector_index, then we can start resize 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); m_vector_index = m_handler_vector.indexOf(qghi);
@@ -362,7 +369,7 @@ bool PartPolygon::sceneEventFilter(QGraphicsItem *watched, QEvent *event)
} }
} }
} }
return false; return false;
} }
@@ -397,7 +404,7 @@ void PartPolygon::adjusteHandlerPos()
{ {
if(m_handler_vector.isEmpty()) if(m_handler_vector.isEmpty())
return; return;
if (m_handler_vector.size() == m_polygon.size()) if (m_handler_vector.size() == m_polygon.size())
{ {
QVector <QPointF> points_vector = mapToScene(m_polygon); QVector <QPointF> points_vector = mapToScene(m_polygon);
@@ -421,7 +428,7 @@ void PartPolygon::handlerMousePressEvent(QetGraphicsHandlerItem *qghi, QGraphics
{ {
Q_UNUSED(qghi); Q_UNUSED(qghi);
Q_UNUSED(event); Q_UNUSED(event);
m_undo_command = new QPropertyUndoCommand(this, "polygon", QVariant(m_polygon)); m_undo_command = new QPropertyUndoCommand(this, "polygon", QVariant(m_polygon));
m_undo_command->setText(tr("Modifier un polygone")); m_undo_command->setText(tr("Modifier un polygone"));
} }
@@ -434,12 +441,12 @@ void PartPolygon::handlerMousePressEvent(QetGraphicsHandlerItem *qghi, QGraphics
void PartPolygon::handlerMouseMoveEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event) void PartPolygon::handlerMouseMoveEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event)
{ {
Q_UNUSED(qghi); Q_UNUSED(qghi);
QPointF new_pos = event->scenePos(); QPointF new_pos = event->scenePos();
if (event->modifiers() != Qt::ControlModifier) if (event->modifiers() != Qt::ControlModifier)
new_pos = elementScene()->snapToGrid(event->scenePos()); new_pos = elementScene()->snapToGrid(event->scenePos());
new_pos = mapFromScene(new_pos); new_pos = mapFromScene(new_pos);
prepareGeometryChange(); prepareGeometryChange();
m_polygon.replace(m_vector_index, new_pos); m_polygon.replace(m_vector_index, new_pos);
adjusteHandlerPos(); adjusteHandlerPos();
@@ -455,7 +462,7 @@ void PartPolygon::handlerMouseReleaseEvent(QetGraphicsHandlerItem *qghi, QGraphi
{ {
Q_UNUSED(qghi); Q_UNUSED(qghi);
Q_UNUSED(event); Q_UNUSED(event);
m_undo_command->setNewValue(QVariant(m_polygon)); m_undo_command->setNewValue(QVariant(m_polygon));
elementScene()->undoStack().push(m_undo_command); elementScene()->undoStack().push(m_undo_command);
m_undo_command = nullptr; m_undo_command = nullptr;
@@ -481,9 +488,9 @@ void PartPolygon::sceneSelectionChanged()
void PartPolygon::addHandler() void PartPolygon::addHandler()
{ {
if (m_handler_vector.isEmpty() && scene()) if (m_handler_vector.isEmpty() && scene())
{ {
m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(m_polygon)); m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(m_polygon));
for(QetGraphicsHandlerItem *handler : m_handler_vector) for(QetGraphicsHandlerItem *handler : m_handler_vector)
{ {
handler->setColor(Qt::blue); handler->setColor(Qt::blue);
@@ -514,7 +521,7 @@ void PartPolygon::removeHandler()
void PartPolygon::insertPoint() void PartPolygon::insertPoint()
{ {
QPolygonF new_polygon = QetGraphicsHandlerUtility::polygonForInsertPoint(m_polygon, m_closed, elementScene()->snapToGrid(m_context_menu_pos)); QPolygonF new_polygon = QetGraphicsHandlerUtility::polygonForInsertPoint(m_polygon, m_closed, elementScene()->snapToGrid(m_context_menu_pos));
if(new_polygon != m_polygon) if(new_polygon != m_polygon)
{ {
//Wrap the undo for avoid to merge the undo commands when user add several points. //Wrap the undo for avoid to merge the undo commands when user add several points.
@@ -532,7 +539,7 @@ void PartPolygon::removePoint()
{ {
if (m_handler_vector.size() == 2) if (m_handler_vector.size() == 2)
return; return;
QPointF point = mapToScene(m_context_menu_pos); QPointF point = mapToScene(m_context_menu_pos);
int index = -1; int index = -1;
for (int i=0 ; i<m_handler_vector.size() ; i++) for (int i=0 ; i<m_handler_vector.size() ; i++)
@@ -549,13 +556,13 @@ void PartPolygon::removePoint()
QPolygonF polygon = this->polygon(); QPolygonF polygon = this->polygon();
qDebug() << index; qDebug() << index;
polygon.removeAt(index); polygon.removeAt(index);
//Wrap the undo for avoid to merge the undo commands when user add several points. //Wrap the undo for avoid to merge the undo commands when user add several points.
QUndoCommand *undo = new QUndoCommand(tr("Supprimer un point d'un polygone")); QUndoCommand *undo = new QUndoCommand(tr("Supprimer un point d'un polygone"));
new QPropertyUndoCommand(this, "polygon", this->polygon(), polygon, undo); new QPropertyUndoCommand(this, "polygon", this->polygon(), polygon, undo);
elementScene()->undoStack().push(undo); elementScene()->undoStack().push(undo);
} }
} }
/** /**

View File

@@ -1,17 +1,17 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
@@ -51,17 +51,23 @@ void PartRectangle::paint(QPainter *painter, const QStyleOptionGraphicsItem *opt
Q_UNUSED(widget); Q_UNUSED(widget);
applyStylesToQPainter(*painter); 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); 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);
#endif
if (isSelected()) if (isSelected())
t.setColor(Qt::red); t.setColor(Qt::red);
t.setJoinStyle(Qt::MiterJoin); t.setJoinStyle(Qt::MiterJoin);
//Force the pen to width 0 if one of dimension is null //Force the pen to width 0 if one of dimension is null
if (!rect().width() || !rect().height()) if (!rect().width() || !rect().height())
t.setWidth(0); t.setWidth(0);
painter->setPen(t); painter->setPen(t);
painter->drawRoundedRect(m_rect, m_xRadius, m_yRadius); painter->drawRoundedRect(m_rect, m_xRadius, m_yRadius);
@@ -86,7 +92,7 @@ const QDomElement PartRectangle::toXml(QDomDocument &xml_document) const
xml_element.setAttribute("y", QString("%1").arg(top_left.y())); xml_element.setAttribute("y", QString("%1").arg(top_left.y()));
xml_element.setAttribute("width", QString("%1").arg(m_rect.width())); xml_element.setAttribute("width", QString("%1").arg(m_rect.width()));
xml_element.setAttribute("height", QString("%1").arg(m_rect.height())); xml_element.setAttribute("height", QString("%1").arg(m_rect.height()));
QRectF rect = m_rect.normalized(); QRectF rect = m_rect.normalized();
qreal x = m_xRadius; qreal x = m_xRadius;
if (x > rect.width()/2) { if (x > rect.width()/2) {
@@ -96,10 +102,10 @@ const QDomElement PartRectangle::toXml(QDomDocument &xml_document) const
if (y > rect.height()/2) { if (y > rect.height()/2) {
y = rect.height()/2; y = rect.height()/2;
} }
xml_element.setAttribute("rx", QString::number(m_xRadius)); xml_element.setAttribute("rx", QString::number(m_xRadius));
xml_element.setAttribute("ry", QString::number(m_yRadius)); xml_element.setAttribute("ry", QString::number(m_yRadius));
stylesToXml(xml_element); stylesToXml(xml_element);
return(xml_element); return(xml_element);
} }
@@ -272,7 +278,7 @@ void PartRectangle::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{ {
if (event->button() == Qt::LeftButton && event->buttonDownPos(Qt::LeftButton) == event->pos()) if (event->button() == Qt::LeftButton && event->buttonDownPos(Qt::LeftButton) == event->pos())
switchResizeMode(); switchResizeMode();
CustomElementGraphicPart::mouseReleaseEvent(event); CustomElementGraphicPart::mouseReleaseEvent(event);
} }
@@ -280,7 +286,7 @@ void PartRectangle::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
@brief PartRectangle::itemChange @brief PartRectangle::itemChange
@param change @param change
@param value @param value
@return @return
*/ */
QVariant PartRectangle::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value) QVariant PartRectangle::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value)
{ {
@@ -290,8 +296,8 @@ QVariant PartRectangle::itemChange(QGraphicsItem::GraphicsItemChange change, con
{ {
//When item is selected, he must to be up to date whene the selection in the scene change, for display or not the handler, //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. //according to the number of selected items.
connect(scene(), &QGraphicsScene::selectionChanged, this, &PartRectangle::sceneSelectionChanged); connect(scene(), &QGraphicsScene::selectionChanged, this, &PartRectangle::sceneSelectionChanged);
if (scene()->selectedItems().size() == 1) if (scene()->selectedItems().size() == 1)
addHandler(); addHandler();
} }
@@ -309,10 +315,10 @@ QVariant PartRectangle::itemChange(QGraphicsItem::GraphicsItemChange change, con
{ {
if(scene()) if(scene())
disconnect(scene(), &QGraphicsScene::selectionChanged, this, &PartRectangle::sceneSelectionChanged); 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);
} }
@@ -320,7 +326,7 @@ QVariant PartRectangle::itemChange(QGraphicsItem::GraphicsItemChange change, con
@brief PartRectangle::sceneEventFilter @brief PartRectangle::sceneEventFilter
@param watched @param watched
@param event @param event
@return @return
*/ */
bool PartRectangle::sceneEventFilter(QGraphicsItem *watched, QEvent *event) bool PartRectangle::sceneEventFilter(QGraphicsItem *watched, QEvent *event)
{ {
@@ -328,7 +334,7 @@ bool PartRectangle::sceneEventFilter(QGraphicsItem *watched, QEvent *event)
if(watched->type() == QetGraphicsHandlerItem::Type) if(watched->type() == QetGraphicsHandlerItem::Type)
{ {
QetGraphicsHandlerItem *qghi = qgraphicsitem_cast<QetGraphicsHandlerItem *>(watched); QetGraphicsHandlerItem *qghi = qgraphicsitem_cast<QetGraphicsHandlerItem *>(watched);
if(m_handler_vector.contains(qghi)) //Handler must be in m_vector_index, then we can start resize 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); m_vector_index = m_handler_vector.indexOf(qghi);
@@ -352,7 +358,7 @@ bool PartRectangle::sceneEventFilter(QGraphicsItem *watched, QEvent *event)
} }
} }
} }
return false; return false;
} }
@@ -397,16 +403,16 @@ void PartRectangle::adjusteHandlerPos()
if (m_handler_vector.isEmpty()) { if (m_handler_vector.isEmpty()) {
return; return;
} }
QVector <QPointF> points_vector; QVector <QPointF> points_vector;
if(m_resize_mode != 3) { if(m_resize_mode != 3) {
points_vector = QetGraphicsHandlerUtility::pointsForRect(m_rect); points_vector = QetGraphicsHandlerUtility::pointsForRect(m_rect);
} }
else { else {
points_vector = QetGraphicsHandlerUtility::pointForRadiusRect(m_rect, m_xRadius, m_yRadius); points_vector = QetGraphicsHandlerUtility::pointForRadiusRect(m_rect, m_xRadius, m_yRadius);
} }
if (m_handler_vector.size() == points_vector.size()) if (m_handler_vector.size() == points_vector.size())
{ {
points_vector = mapToScene(points_vector); points_vector = mapToScene(points_vector);
@@ -430,7 +436,7 @@ void PartRectangle::handlerMousePressEvent(QetGraphicsHandlerItem *qghi, QGraphi
{ {
Q_UNUSED(qghi) Q_UNUSED(qghi)
Q_UNUSED(event) Q_UNUSED(event)
m_old_rect = m_rect; m_old_rect = m_rect;
m_old_xRadius = m_xRadius; m_old_xRadius = m_xRadius;
m_old_yRadius = m_yRadius; m_old_yRadius = m_yRadius;
@@ -447,12 +453,12 @@ void PartRectangle::handlerMousePressEvent(QetGraphicsHandlerItem *qghi, QGraphi
void PartRectangle::handlerMouseMoveEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event) void PartRectangle::handlerMouseMoveEvent(QetGraphicsHandlerItem *qghi, QGraphicsSceneMouseEvent *event)
{ {
Q_UNUSED(qghi) Q_UNUSED(qghi)
QPointF new_pos = event->scenePos(); QPointF new_pos = event->scenePos();
if (event->modifiers() != Qt::ControlModifier) if (event->modifiers() != Qt::ControlModifier)
new_pos = elementScene()->snapToGrid(event->scenePos()); new_pos = elementScene()->snapToGrid(event->scenePos());
new_pos = mapFromScene(new_pos); new_pos = mapFromScene(new_pos);
if (m_resize_mode == 1) if (m_resize_mode == 1)
setRect(QetGraphicsHandlerUtility::rectForPosAtIndex(m_rect, new_pos, m_vector_index)); setRect(QetGraphicsHandlerUtility::rectForPosAtIndex(m_rect, new_pos, m_vector_index));
else if (m_resize_mode == 2) else if (m_resize_mode == 2)
@@ -471,7 +477,7 @@ void PartRectangle::handlerMouseMoveEvent(QetGraphicsHandlerItem *qghi, QGraphic
setYRadius(radius); setYRadius(radius);
} }
} }
adjusteHandlerPos(); adjusteHandlerPos();
} }
@@ -479,9 +485,9 @@ void PartRectangle::handlerMouseReleaseEvent(QetGraphicsHandlerItem *qghi, QGrap
{ {
Q_UNUSED(qghi) Q_UNUSED(qghi)
Q_UNUSED(event) Q_UNUSED(event)
m_modifie_radius_equaly = false; m_modifie_radius_equaly = false;
QUndoCommand *undo = new QUndoCommand("Modifier un rectangle"); QUndoCommand *undo = new QUndoCommand("Modifier un rectangle");
if (m_old_rect != m_rect) { if (m_old_rect != m_rect) {
QPropertyUndoCommand *u = new QPropertyUndoCommand(this, "rect", QVariant(m_old_rect.normalized()), QVariant(m_rect.normalized()), undo); QPropertyUndoCommand *u = new QPropertyUndoCommand(this, "rect", QVariant(m_old_rect.normalized()), QVariant(m_rect.normalized()), undo);
@@ -495,7 +501,7 @@ void PartRectangle::handlerMouseReleaseEvent(QetGraphicsHandlerItem *qghi, QGrap
QPropertyUndoCommand *u = new QPropertyUndoCommand(this, "yRadius", QVariant(m_old_yRadius), QVariant(m_yRadius), undo); QPropertyUndoCommand *u = new QPropertyUndoCommand(this, "yRadius", QVariant(m_old_yRadius), QVariant(m_yRadius), undo);
u->setAnimated(); u->setAnimated();
} }
elementScene()->undoStack().push(undo); elementScene()->undoStack().push(undo);
m_vector_index = -1; m_vector_index = -1;
} }
@@ -519,21 +525,21 @@ void PartRectangle::sceneSelectionChanged()
void PartRectangle::addHandler() void PartRectangle::addHandler()
{ {
if (m_handler_vector.isEmpty() && scene()) if (m_handler_vector.isEmpty() && scene())
{ {
if (m_resize_mode != 3) { if (m_resize_mode != 3) {
m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointsForRect(m_rect))); m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointsForRect(m_rect)));
} }
else { else {
m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointForRadiusRect(m_rect, m_xRadius, m_yRadius))); m_handler_vector = QetGraphicsHandlerItem::handlerForPoint(mapToScene(QetGraphicsHandlerUtility::pointForRadiusRect(m_rect, m_xRadius, m_yRadius)));
} }
for (QetGraphicsHandlerItem *handler : m_handler_vector) for (QetGraphicsHandlerItem *handler : m_handler_vector)
{ {
QColor color; QColor color;
if(m_resize_mode == 1) {color = Qt::blue;} if(m_resize_mode == 1) {color = Qt::blue;}
else if (m_resize_mode == 2) {color = Qt::darkGreen;} else if (m_resize_mode == 2) {color = Qt::darkGreen;}
else {color = Qt::magenta;} else {color = Qt::magenta;}
handler->setColor(color); handler->setColor(color);
scene()->addItem(handler); scene()->addItem(handler);
handler->installSceneEventFilter(this); handler->installSceneEventFilter(this);

View File

@@ -1,17 +1,17 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
@@ -62,37 +62,52 @@ const QDomElement PartTerminal::toXml(QDomDocument &xml_document) const
/** /**
Dessine la borne Dessine la borne
@param p QPainter a utiliser pour rendre le dessin @param painter QPainter a utiliser pour rendre le dessin
@param options Options pour affiner le rendu @param options Options pour affiner le rendu
@param widget Widget sur lequel le rendu est effectue @param widget Widget sur lequel le rendu est effectue
*/ */
void PartTerminal::paint(QPainter *p, const QStyleOptionGraphicsItem *options, QWidget *widget) { void PartTerminal::paint(
QPainter *painter,
const QStyleOptionGraphicsItem *options,
QWidget *widget)
{
Q_UNUSED(widget); Q_UNUSED(widget);
p -> save(); painter -> save();
// annulation des renderhints // annulation des renderhints
p -> setRenderHint(QPainter::Antialiasing, false); painter -> setRenderHint(QPainter::Antialiasing, false);
p -> setRenderHint(QPainter::TextAntialiasing, false); painter -> setRenderHint(QPainter::TextAntialiasing, false);
p -> setRenderHint(QPainter::SmoothPixmapTransform, false); painter -> setRenderHint(QPainter::SmoothPixmapTransform, false);
QPen t; QPen t;
t.setWidthF(1.0); t.setWidthF(1.0);
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
t.setCosmetic(options && options -> levelOfDetail < 1.0); 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);
#endif
// dessin de la borne en rouge // dessin de la borne en rouge
t.setColor(isSelected() ? Terminal::neutralColor : Qt::red); t.setColor(isSelected() ? Terminal::neutralColor : Qt::red);
p -> setPen(t); painter -> setPen(t);
p -> drawLine(QPointF(0.0, 0.0), d -> second_point); painter -> drawLine(QPointF(0.0, 0.0), d -> second_point);
// dessin du point d'amarrage au conducteur en bleu // dessin du point d'amarrage au conducteur en bleu
t.setColor(isSelected() ? Qt::red : Terminal::neutralColor); t.setColor(isSelected() ? Qt::red : Terminal::neutralColor);
p -> setPen(t); painter -> setPen(t);
p -> setBrush(Terminal::neutralColor); painter -> setBrush(Terminal::neutralColor);
p -> drawPoint(QPointF(0.0, 0.0)); painter -> drawPoint(QPointF(0.0, 0.0));
p -> restore(); painter -> restore();
if (m_hovered) if (m_hovered)
drawShadowShape(p); drawShadowShape(painter);
} }
/** /**

View File

@@ -1,17 +1,17 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
@@ -55,7 +55,10 @@ class PartTerminal : public CustomElementGraphicPart {
QString xmlName() const override { return(QString("terminal")); } QString xmlName() const override { return(QString("terminal")); }
void fromXml(const QDomElement &) override; void fromXml(const QDomElement &) override;
const QDomElement toXml(QDomDocument &) const override; const QDomElement toXml(QDomDocument &) const override;
void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *) override; void paint(
QPainter *painter,
const QStyleOptionGraphicsItem *,
QWidget *) override;
QPainterPath shape() const override; QPainterPath shape() const override;
QPainterPath shadowShape() const override {return shape();} QPainterPath shadowShape() const override {return shape();}
@@ -70,7 +73,7 @@ class PartTerminal : public CustomElementGraphicPart {
void setName(QString& name); void setName(QString& name);
void setNewUuid(); void setNewUuid();
private: private:
void updateSecondPoint(); void updateSecondPoint();
TerminalData* d; // pointer to the terminal data TerminalData* d; // pointer to the terminal data

View File

@@ -1471,7 +1471,14 @@ void QETElementEditor::slot_createPartsList()
QString part_desc = cep -> name(); QString part_desc = cep -> name();
QListWidgetItem *qlwi = new QListWidgetItem(part_desc); QListWidgetItem *qlwi = new QListWidgetItem(part_desc);
QVariant v; QVariant v;
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
v.setValue<QGraphicsItem *>(qgi); v.setValue<QGraphicsItem *>(qgi);
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
qDebug()<<"Help code for QT 6 or later";
#endif
qlwi -> setData(42, v); qlwi -> setData(42, v);
m_parts_list -> addItem(qlwi); m_parts_list -> addItem(qlwi);
qlwi -> setSelected(qgi -> isSelected()); qlwi -> setSelected(qgi -> isSelected());

View File

@@ -46,9 +46,9 @@ void Machine_info::send_info_to_debug()
{ {
qInfo()<<"debugging enabled:" qInfo()<<"debugging enabled:"
<< QLibraryInfo::isDebugBuild(); << QLibraryInfo::isDebugBuild();
qInfo()<< "Qt library version:" qInfo()<< "Qt library version:"
<< QLibraryInfo::version(); << QLibraryInfo::version();
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
qInfo()<< "Qt library location default prefix:" qInfo()<< "Qt library location default prefix:"
<< QLibraryInfo::location(QLibraryInfo::PrefixPath); << QLibraryInfo::location(QLibraryInfo::PrefixPath);
qInfo()<< "Qt library location documentation:" qInfo()<< "Qt library location documentation:"
@@ -80,6 +80,43 @@ void Machine_info::send_info_to_debug()
#ifndef Q_OS_WIN #ifndef Q_OS_WIN
qInfo()<< "Qt library location Qt settings:" qInfo()<< "Qt library location Qt settings:"
<< QLibraryInfo::location(QLibraryInfo::SettingsPath); << QLibraryInfo::location(QLibraryInfo::SettingsPath);
#endif
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
qInfo()<< "Qt library path default prefix:"
<< QLibraryInfo::path(QLibraryInfo::PrefixPath);
qInfo()<< "Qt library path documentation:"
<< QLibraryInfo::path(QLibraryInfo::DocumentationPath);
qInfo()<< "Qt library path headers:"
<< QLibraryInfo::path(QLibraryInfo::HeadersPath);
qInfo()<< "Qt library path libraries:"
<< QLibraryInfo::path(QLibraryInfo::LibrariesPath);
qInfo()<< "Qt library path executables:"
<< QLibraryInfo::path(QLibraryInfo::LibraryExecutablesPath);
qInfo()<< "Qt library path Qt binaries:"
<< QLibraryInfo::path(QLibraryInfo::BinariesPath);
qInfo()<< "Qt library path Qt plugins:"
<< QLibraryInfo::path(QLibraryInfo::PluginsPath);
// qInfo()<< "Qt library path installed QML extensions:"
// << QLibraryInfo::path(QLibraryInfo::ImportsPath);
qInfo()<< "Qt library path installed QML extensions:"
<< QLibraryInfo::path(QLibraryInfo::Qml2ImportsPath);
qInfo()<< "Qt library path dependent Qt data:"
<< QLibraryInfo::path(QLibraryInfo::ArchDataPath);
qInfo()<< "Qt library path independent Qt data:"
<< QLibraryInfo::path(QLibraryInfo::DataPath);
qInfo()<< "Qt library path translation:"
<< QLibraryInfo::path(QLibraryInfo::TranslationsPath);
qInfo()<< "Qt library path examples:"
<< QLibraryInfo::path(QLibraryInfo::ExamplesPath);
qInfo()<< "Qt library path Qt testcases:"
<< QLibraryInfo::path(QLibraryInfo::TestsPath);
#ifndef Q_OS_WIN
qInfo()<< "Qt library path Qt settings:"
<< QLibraryInfo::path(QLibraryInfo::SettingsPath);
#endif
#endif #endif
qInfo()<< "GitRevision " + QString(GIT_COMMIT_SHA); qInfo()<< "GitRevision " + QString(GIT_COMMIT_SHA);
qInfo()<< "QElectroTech V " + QET::displayedVersion; qInfo()<< "QElectroTech V " + QET::displayedVersion;
@@ -224,17 +261,17 @@ void Machine_info::init_get_cpu_info_winnt()
QProcess wingpuraminfo; QProcess wingpuraminfo;
wingpuraminfo.start("wmic", wingpuraminfo.start("wmic",
QStringList() QStringList()
<< "PATH" << "PATH"
<< "Win32_videocontroller" << "Win32_videocontroller"
<< "get" << "get"
<< "AdapterRAM "); << "AdapterRAM ");
wingpuraminfo.waitForFinished(); wingpuraminfo.waitForFinished();
QString WinGPURAMOutput = wingpuraminfo.readAllStandardOutput(); QString WinGPURAMOutput = wingpuraminfo.readAllStandardOutput();
pc.gpu.RAM=QString("RAM Total : %1 B").arg( pc.gpu.RAM=QString("RAM Total : %1 B").arg(
WinGPURAMOutput.toLocal8Bit().constData()); WinGPURAMOutput.toLocal8Bit().constData());
wingpuraminfo.close(); wingpuraminfo.close();
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
MEMORYSTATUSEX memory_status; MEMORYSTATUSEX memory_status;
ZeroMemory(&memory_status, sizeof(MEMORYSTATUSEX)); ZeroMemory(&memory_status, sizeof(MEMORYSTATUSEX));
@@ -266,7 +303,7 @@ void Machine_info::init_get_cpu_info_macos()
macoscpuinfo.waitForFinished(); macoscpuinfo.waitForFinished();
QString macosOutput = macoscpuinfo.readAllStandardOutput(); QString macosOutput = macoscpuinfo.readAllStandardOutput();
pc.cpu.info=QString(macosOutput.toLocal8Bit().constData()); pc.cpu.info=QString(macosOutput.toLocal8Bit().constData());
QProcess macosraminfo; QProcess macosraminfo;
macosraminfo.start("bash", macosraminfo.start("bash",
QStringList() QStringList()

View File

@@ -1,17 +1,17 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
@@ -30,8 +30,8 @@
@param msg : Message @param msg : Message
*/ */
void myMessageOutput(QtMsgType type, void myMessageOutput(QtMsgType type,
const QMessageLogContext &context, const QMessageLogContext &context,
const QString &msg) const QString &msg)
{ {
QString txt=QTime::currentTime().toString("hh:mm:ss.zzz"); QString txt=QTime::currentTime().toString("hh:mm:ss.zzz");
@@ -110,8 +110,8 @@ void myMessageOutput(QtMsgType type,
txt+=")\n"; txt+=")\n";
} }
QFile outFile(QETApp::configDir() QFile outFile(QETApp::configDir()
+QDate::currentDate().toString("yyyyMMdd") +QDate::currentDate().toString("yyyyMMdd")
+".log"); +".log");
if(outFile.open(QIODevice::WriteOnly | QIODevice::Append)) if(outFile.open(QIODevice::WriteOnly | QIODevice::Append))
{ {
QTextStream ts(&outFile); QTextStream ts(&outFile);
@@ -166,7 +166,13 @@ int main(int argc, char **argv)
QCoreApplication::setApplicationName("QElectroTech"); QCoreApplication::setApplicationName("QElectroTech");
//Creation and execution of the application //Creation and execution of the application
//HighDPI //HighDPI
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
#endif
SingleApplication app(argc, argv, true); SingleApplication app(argc, argv, true);
#ifdef Q_OS_MACOS #ifdef Q_OS_MACOS
//Handle the opening of QET when user double click on a .qet .elmt .tbt file //Handle the opening of QET when user double click on a .qet .elmt .tbt file

View File

@@ -23,7 +23,13 @@
#include "qeticons.h" #include "qeticons.h"
#include <QPrintPreviewWidget> #include <QPrintPreviewWidget>
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
#include <QDesktopWidget> #include <QDesktopWidget>
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
#endif
#include <QScreen> #include <QScreen>
#include <QPainter> #include <QPainter>
#include <QPageSetupDialog> #include <QPageSetupDialog>
@@ -45,7 +51,14 @@ void ProjectPrintWindow::launchDialog(QETProject *project, QWidget *parent)
} }
auto printer_ = new QPrinter(); auto printer_ = new QPrinter();
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
printer_->setOrientation(QPrinter::Landscape); printer_->setOrientation(QPrinter::Landscape);
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
qDebug()<<"Help code for QT 6 or later";
#endif
printer_->setDocName(doc_name); printer_->setDocName(doc_name);
printer_->setOutputFileName(file_name); printer_->setOutputFileName(file_name);
printer_->setCreator(QString("QElectroTech %1").arg(QET::displayedVersion)); printer_->setCreator(QString("QElectroTech %1").arg(QET::displayedVersion));
@@ -55,7 +68,14 @@ void ProjectPrintWindow::launchDialog(QETProject *project, QWidget *parent)
print_dialog.setWindowFlags(Qt::Sheet); print_dialog.setWindowFlags(Qt::Sheet);
#endif #endif
print_dialog.setWindowTitle(tr("Options d'impression", "window title")); print_dialog.setWindowTitle(tr("Options d'impression", "window title"));
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
print_dialog.setEnabledOptions(QAbstractPrintDialog::PrintToFile | QAbstractPrintDialog::PrintShowPageSize); print_dialog.setEnabledOptions(QAbstractPrintDialog::PrintToFile | QAbstractPrintDialog::PrintShowPageSize);
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
qDebug()<<"Help code for QT 6 or later";
#endif
if (print_dialog.exec() == QDialog::Rejected) { if (print_dialog.exec() == QDialog::Rejected) {
delete printer_; delete printer_;
return; return;
@@ -95,7 +115,7 @@ QString ProjectPrintWindow::docName(QETProject *project)
* @param parent * @param parent
*/ */
ProjectPrintWindow::ProjectPrintWindow(QETProject *project, QPrinter *printer, QWidget *parent) : ProjectPrintWindow::ProjectPrintWindow(QETProject *project, QPrinter *printer, QWidget *parent) :
QMainWindow(parent), QMainWindow(parent),
ui(new Ui::ProjectPrintWindow), ui(new Ui::ProjectPrintWindow),
m_project(project), m_project(project),
m_printer(printer) m_printer(printer)
@@ -213,8 +233,15 @@ void ProjectPrintWindow::printDiagram(Diagram *diagram, bool fit_page, QPainter
diagram->render(painter, QRectF(), diagram_rect, Qt::KeepAspectRatio); diagram->render(painter, QRectF(), diagram_rect, Qt::KeepAspectRatio);
} else { } else {
//Print on one or several pages //Print on one or several pages
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
auto printed_rect = full_page ? printer->paperRect() : printer->pageRect(); auto printed_rect = full_page ? printer->paperRect() : printer->pageRect();
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
qDebug()<<"Help code for QT 6 or later";
auto printed_rect = full_page ? printer->paperRect(QPrinter::Millimeter) : printer->pageRect(QPrinter::Millimeter);
#endif
auto used_width = printed_rect.width(); auto used_width = printed_rect.width();
auto used_height = printed_rect.height(); auto used_height = printed_rect.height();
auto h_pages_count = horizontalPagesCount(diagram, option, full_page); auto h_pages_count = horizontalPagesCount(diagram, option, full_page);
@@ -231,9 +258,16 @@ void ProjectPrintWindow::printDiagram(Diagram *diagram, bool fit_page, QPainter
auto x_offset = 0; auto x_offset = 0;
for (auto j=0 ; j<h_pages_count ; ++j) for (auto j=0 ; j<h_pages_count ; ++j)
{ {
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
page_grid.last() << QRect(QPoint(x_offset, y_offset), page_grid.last() << QRect(QPoint(x_offset, y_offset),
QSize(qMin(used_width, diagram_rect.width() - x_offset), QSize(qMin(used_width, diagram_rect.width() - x_offset),
qMin(used_height, diagram_rect.height() - y_offset))); qMin(used_height, diagram_rect.height() - y_offset)));
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
qDebug()<<"Help code for QT 6 or later";
#endif
x_offset += used_width; x_offset += used_width;
} }
y_offset += used_height; y_offset += used_height;
@@ -294,9 +328,18 @@ QRect ProjectPrintWindow::diagramRect(Diagram *diagram, const ExportProperties &
* @return The width of the "poster" in number of page for print the diagram * @return The width of the "poster" in number of page for print the diagram
* with the orientation and the paper format used by the actual printer * with the orientation and the paper format used by the actual printer
*/ */
int ProjectPrintWindow::horizontalPagesCount(Diagram *diagram, const ExportProperties &option, bool full_page) const int ProjectPrintWindow::horizontalPagesCount(
Diagram *diagram, const ExportProperties &option, bool full_page) const
{ {
QRect printable_area = full_page ? m_printer-> paperRect() : m_printer-> pageRect(); QRect printable_area;
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
printable_area = full_page ? m_printer-> paperRect() : m_printer-> pageRect();
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
qDebug()<<"Help code for QT 6 or later";
#endif
QRect diagram_rect = diagramRect(diagram, option); QRect diagram_rect = diagramRect(diagram, option);
int h_pages_count = int(ceil(qreal(diagram_rect.width()) / qreal(printable_area.width()))); int h_pages_count = int(ceil(qreal(diagram_rect.width()) / qreal(printable_area.width())));
@@ -311,9 +354,18 @@ int ProjectPrintWindow::horizontalPagesCount(Diagram *diagram, const ExportPrope
* @return The height of the "poster" in number of pages for print the diagram * @return The height of the "poster" in number of pages for print the diagram
* with the orientation and paper format used by the actual printer * with the orientation and paper format used by the actual printer
*/ */
int ProjectPrintWindow::verticalPagesCount(Diagram *diagram, const ExportProperties &option, bool full_page) const int ProjectPrintWindow::verticalPagesCount(
Diagram *diagram, const ExportProperties &option, bool full_page) const
{ {
QRect printable_area = full_page ? m_printer->paperRect() : m_printer->pageRect(); QRect printable_area;
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
printable_area = full_page ? m_printer->paperRect() : m_printer->pageRect();
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
qDebug()<<"Help code for QT 6 or later";
#endif
QRect diagram_rect = diagramRect(diagram, option); QRect diagram_rect = diagramRect(diagram, option);
int v_pages_count = int(ceil(qreal(diagram_rect.height()) / qreal(printable_area.height()))); int v_pages_count = int(ceil(qreal(diagram_rect.height()) / qreal(printable_area.height())));
@@ -371,6 +423,7 @@ QString ProjectPrintWindow::settingsSectionName(const QPrinter *printer)
void ProjectPrintWindow::loadPageSetupForCurrentPrinter() void ProjectPrintWindow::loadPageSetupForCurrentPrinter()
{ {
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
QSettings settings; QSettings settings;
QString printer_section = settingsSectionName(m_printer); QString printer_section = settingsSectionName(m_printer);
@@ -413,10 +466,17 @@ void ProjectPrintWindow::loadPageSetupForCurrentPrinter()
settings.endGroup(); settings.endGroup();
settings.endGroup(); settings.endGroup();
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
qDebug()<<"Help code for QT 6 or later";
#endif
} }
void ProjectPrintWindow::savePageSetupForCurrentPrinter() void ProjectPrintWindow::savePageSetupForCurrentPrinter()
{ {
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
QSettings settings; QSettings settings;
QString printer_section = settingsSectionName(m_printer); QString printer_section = settingsSectionName(m_printer);
@@ -444,6 +504,12 @@ void ProjectPrintWindow::savePageSetupForCurrentPrinter()
settings.endGroup(); settings.endGroup();
settings.endGroup(); settings.endGroup();
settings.sync(); settings.sync();
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
qDebug()<<"Help code for QT 6 or later";
#endif
} }
/** /**

View File

@@ -25,6 +25,7 @@
#include <QSaveFile> #include <QSaveFile>
#include <QTextStream> #include <QTextStream>
#include <QRegularExpression> #include <QRegularExpression>
#include <QActionGroup>
/** /**
Permet de convertir une chaine de caracteres ("n", "s", "e" ou "w") Permet de convertir une chaine de caracteres ("n", "s", "e" ou "w")
@@ -164,9 +165,9 @@ bool QET::lineContainsPoint(const QLineF &line, const QPointF &point) {
@return true si le projete orthogonal du point sur la droite appartient au @return true si le projete orthogonal du point sur la droite appartient au
segment de droite. segment de droite.
*/ */
bool QET::orthogonalProjection(const QPointF &point, bool QET::orthogonalProjection(
const QLineF &line, const QPointF &point,const QLineF &line,QPointF *intersection)
QPointF *intersection) { {
// recupere le vecteur normal de `line' // recupere le vecteur normal de `line'
QLineF line_normal_vector(line.normalVector()); QLineF line_normal_vector(line.normalVector());
QPointF normal_vector(line_normal_vector.dx(), line_normal_vector.dy()); QPointF normal_vector(line_normal_vector.dx(), line_normal_vector.dy());
@@ -210,9 +211,9 @@ bool QET::orthogonalProjection(const QPointF &point,
@param entier Pointeur facultatif vers un entier @param entier Pointeur facultatif vers un entier
@return true si l'attribut est bien un entier, false sinon @return true si l'attribut est bien un entier, false sinon
*/ */
bool QET::attributeIsAnInteger(const QDomElement &e, bool QET::attributeIsAnInteger(
const QString& nom_attribut, const QDomElement &e,const QString& nom_attribut,int *entier)
int *entier) { {
// verifie la presence de l'attribut // verifie la presence de l'attribut
if (!e.hasAttribute(nom_attribut)) return(false); if (!e.hasAttribute(nom_attribut)) return(false);
// verifie la validite de l'attribut // verifie la validite de l'attribut
@@ -231,9 +232,9 @@ bool QET::attributeIsAnInteger(const QDomElement &e,
@param reel Pointeur facultatif vers un double @param reel Pointeur facultatif vers un double
@return true si l'attribut est bien un reel, false sinon @return true si l'attribut est bien un reel, false sinon
*/ */
bool QET::attributeIsAReal(const QDomElement &e, bool QET::attributeIsAReal(
const QString& nom_attribut, const QDomElement &e,const QString& nom_attribut,qreal *reel)
qreal *reel) { {
// verifie la presence de l'attribut // verifie la presence de l'attribut
if (!e.hasAttribute(nom_attribut)) return(false); if (!e.hasAttribute(nom_attribut)) return(false);
// verifie la validite de l'attribut // verifie la validite de l'attribut
@@ -258,13 +259,14 @@ bool QET::attributeIsAReal(const QDomElement &e,
@return la proposition decrivant le nombre d'elements, de conducteurs et de @return la proposition decrivant le nombre d'elements, de conducteurs et de
textes textes
*/ */
QString QET::ElementsAndConductorsSentence(int elements_count, QString QET::ElementsAndConductorsSentence(
int conductors_count, int elements_count,
int texts_count, int conductors_count,
int images_count, int texts_count,
int shapes_count, int images_count,
int element_text_count, int shapes_count,
int tables_count) int element_text_count,
int tables_count)
{ {
QString text; QString text;
if (elements_count) { if (elements_count) {
@@ -333,9 +335,14 @@ QString QET::ElementsAndConductorsSentence(int elements_count,
/** /**
@return the list of \a tag_name elements directly under the \a e XML element. @return the list of \a tag_name elements directly under the \a e XML element.
*/ */
QList<QDomElement> QET::findInDomElement(const QDomElement &e, const QString &tag_name) { QList<QDomElement> QET::findInDomElement(
const QDomElement &e, const QString &tag_name)
{
QList<QDomElement> return_list; QList<QDomElement> return_list;
for (QDomNode node = e.firstChild() ; !node.isNull() ; node = node.nextSibling()) { for (QDomNode node = e.firstChild() ;
!node.isNull() ;
node = node.nextSibling())
{
if (!node.isElement()) continue; if (!node.isElement()) continue;
QDomElement element = node.toElement(); QDomElement element = node.toElement();
if (element.isNull() || element.tagName() != tag_name) continue; if (element.isNull() || element.tagName() != tag_name) continue;
@@ -352,18 +359,24 @@ QList<QDomElement> QET::findInDomElement(const QDomElement &e, const QString &ta
@param children tag XML a rechercher @param children tag XML a rechercher
@return La liste des elements XML children @return La liste des elements XML children
*/ */
QList<QDomElement> QET::findInDomElement(const QDomElement &e, QList<QDomElement> QET::findInDomElement(
const QString &parent, const QDomElement &e,const QString &parent,const QString &children)
const QString &children) { {
QList<QDomElement> return_list; QList<QDomElement> return_list;
// parcours des elements parents // parcours des elements parents
for (QDomNode enfant = e.firstChild() ; !enfant.isNull() ; enfant = enfant.nextSibling()) { for (QDomNode enfant = e.firstChild() ;
!enfant.isNull() ;
enfant = enfant.nextSibling())
{
// on s'interesse a l'element XML "parent" // on s'interesse a l'element XML "parent"
QDomElement parents = enfant.toElement(); QDomElement parents = enfant.toElement();
if (parents.isNull() || parents.tagName() != parent) continue; if (parents.isNull() || parents.tagName() != parent) continue;
// parcours des enfants de l'element XML "parent" // parcours des enfants de l'element XML "parent"
for (QDomNode node_children = parents.firstChild() ; !node_children.isNull() ; node_children = node_children.nextSibling()) { for (QDomNode node_children = parents.firstChild() ;
!node_children.isNull() ;
node_children = node_children.nextSibling())
{
// on s'interesse a l'element XML "children" // on s'interesse a l'element XML "children"
QDomElement n_children = node_children.toElement(); QDomElement n_children = node_children.toElement();
if (!n_children.isNull() && n_children.tagName() == children) return_list.append(n_children); if (!n_children.isNull() && n_children.tagName() == children) return_list.append(n_children);
@@ -404,8 +417,8 @@ QString QET::license()
*/ */
QList<QChar> QET::forbiddenCharacters() QList<QChar> QET::forbiddenCharacters()
{ {
return(QList<QChar>() << '\\' << '/' << ':' << '*' << '?' << '"' return(QList<QChar>()
<< '<' << '>' << '|'); << '\\' << '/' << ':' << '*' << '?' << '"'<< '<' << '>' << '|');
} }
/** /**
@@ -614,7 +627,14 @@ bool QET::writeXmlFile(QDomDocument &xml_doc, const QString &filepath, QString *
} }
QTextStream out(&file); QTextStream out(&file);
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
out.setCodec("UTF-8"); out.setCodec("UTF-8");
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
out.setEncoding(QStringConverter::Utf8);
#endif
out.setGenerateByteOrderMark(false); out.setGenerateByteOrderMark(false);
out << xml_doc.toString(4); out << xml_doc.toString(4);
if (!file.commit()) if (!file.commit())
@@ -741,7 +761,14 @@ bool QET::writeToFile(QDomDocument &xml_doc, QFile *file, QString *error_message
QTextStream out(file); QTextStream out(file);
out.seek(0); out.seek(0);
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
out.setCodec("UTF-8"); out.setCodec("UTF-8");
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
out.setEncoding(QStringConverter::Utf8);
#endif
out.setGenerateByteOrderMark(false); out.setGenerateByteOrderMark(false);
out << xml_doc.toString(4); out << xml_doc.toString(4);
if (opened_here) { if (opened_here) {

View File

@@ -105,12 +105,12 @@ QETApp::QETApp() :
if (qet_arguments_.files().isEmpty()) if (qet_arguments_.files().isEmpty())
{ {
setSplashScreenStep(tr("Chargement... Éditeur de schéma", setSplashScreenStep(tr("Chargement... Éditeur de schéma",
"splash screen caption")); "splash screen caption"));
new QETDiagramEditor(); new QETDiagramEditor();
} else } else
{ {
setSplashScreenStep(tr("Chargement... Ouverture des fichiers", setSplashScreenStep(tr("Chargement... Ouverture des fichiers",
"splash screen caption")); "splash screen caption"));
openFiles(qet_arguments_); openFiles(qet_arguments_);
} }
@@ -167,7 +167,14 @@ void QETApp::setLanguage(const QString &desired_language) {
QString languages_path = languagesPath(); QString languages_path = languagesPath();
// load Qt library translations // load Qt library translations
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
QString qt_l10n_path = QLibraryInfo::location(QLibraryInfo::TranslationsPath); QString qt_l10n_path = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
QString qt_l10n_path = QLibraryInfo::path(QLibraryInfo::TranslationsPath);
#endif
if (!qtTranslator.load("qt_" + desired_language, qt_l10n_path)) { if (!qtTranslator.load("qt_" + desired_language, qt_l10n_path)) {
qtTranslator.load("qt_" + desired_language, languages_path); qtTranslator.load("qt_" + desired_language, languages_path);
} }
@@ -549,7 +556,7 @@ TitleBlockTemplatesFilesCollection *QETApp::customTitleBlockTemplatesCollection(
new TitleBlockTemplatesFilesCollection( new TitleBlockTemplatesFilesCollection(
QETApp::customTitleBlockTemplatesDir()); QETApp::customTitleBlockTemplatesDir());
m_custom_tbt_collection -> setTitle(tr("Cartouches utilisateur", m_custom_tbt_collection -> setTitle(tr("Cartouches utilisateur",
"title of the user's \ "title of the user's \
title block templates collection")); title block templates collection"));
m_custom_tbt_collection -> setProtocol(QETAPP_CUSTOM_TBT_PROTOCOL); m_custom_tbt_collection -> setProtocol(QETAPP_CUSTOM_TBT_PROTOCOL);
m_custom_tbt_collection -> setCollection(QET::QetCollection::Custom); m_custom_tbt_collection -> setCollection(QET::QetCollection::Custom);
@@ -651,7 +658,7 @@ QString QETApp::commonElementsDir()
* relatif au dossier contenant le binaire executable * relatif au dossier contenant le binaire executable
*/ */
return(QCoreApplication::applicationDirPath() return(QCoreApplication::applicationDirPath()
+ "/" + QUOTE(QET_COMMON_COLLECTION_PATH)); + "/" + QUOTE(QET_COMMON_COLLECTION_PATH));
#endif #endif
#endif #endif
} }
@@ -752,7 +759,7 @@ QString QETApp::commonTitleBlockTemplatesDir()
* to the directory that contains the executable binary * to the directory that contains the executable binary
*/ */
return(QCoreApplication::applicationDirPath() return(QCoreApplication::applicationDirPath()
+ "/" + QUOTE(QET_COMMON_TBT_PATH)); + "/" + QUOTE(QET_COMMON_TBT_PATH));
#endif #endif
#endif #endif
} }
@@ -860,7 +867,7 @@ QString QETApp::realPath(const QString &sym_path) {
directory = customTitleBlockTemplatesDir(); directory = customTitleBlockTemplatesDir();
} else return(QString()); } else return(QString());
return(directory return(directory
+ QDir::toNativeSeparators(sym_path.right(sym_path.length() - 9))); + QDir::toNativeSeparators(sym_path.right(sym_path.length() - 9)));
} }
@@ -1081,7 +1088,7 @@ QString QETApp::languagesPath()
* au dossier contenant le binaire executable * au dossier contenant le binaire executable
*/ */
return(QCoreApplication::applicationDirPath() return(QCoreApplication::applicationDirPath()
+ "/" + QUOTE(QET_LANG_PATH)); + "/" + QUOTE(QET_LANG_PATH));
#endif #endif
#endif #endif
} }
@@ -1126,9 +1133,9 @@ QFont QETApp::diagramTextsFont(qreal size)
//Font to use //Font to use
QString diagram_texts_family = settings.value("diagramfont", QString diagram_texts_family = settings.value("diagramfont",
"Sans Serif").toString(); "Sans Serif").toString();
qreal diagram_texts_size = settings.value("diagramsize", qreal diagram_texts_size = settings.value("diagramsize",
9.0).toDouble(); 9.0).toDouble();
if (size != -1.0) { if (size != -1.0) {
diagram_texts_size = size; diagram_texts_size = size;
@@ -1155,8 +1162,9 @@ QFont QETApp::diagramTextsItemFont(qreal size)
"Sans Serif").toString(); "Sans Serif").toString();
qreal diagram_texts_item_size = settings.value("diagramitemsize", qreal diagram_texts_item_size = settings.value("diagramitemsize",
9.0).toDouble(); 9.0).toDouble();
qreal diagram_texts_item_weight = settings.value("diagramitemweight" auto diagram_texts_item_weight =
).toDouble(); static_cast<QFont::Weight>(
settings.value("diagramitemweight").toInt());
QString diagram_texts_item_style = settings.value("diagramitemstyle", QString diagram_texts_item_style = settings.value("diagramitemstyle",
"normal").toString(); "normal").toString();
@@ -1290,15 +1298,15 @@ QTextOrientationSpinBoxWidget *QETApp::createTextOrientationSpinBoxWidget()
widget -> orientationWidget() -> setFont(QETApp::diagramTextsFont()); widget -> orientationWidget() -> setFont(QETApp::diagramTextsFont());
widget -> orientationWidget() -> setUsableTexts(QList<QString>() widget -> orientationWidget() -> setUsableTexts(QList<QString>()
<< QETApp::tr("Q", << QETApp::tr("Q",
"Single-letter example text - translate length, not meaning") "Single-letter example text - translate length, not meaning")
<< QETApp::tr("QET", << QETApp::tr("QET",
"Small example text - translate length, not meaning") "Small example text - translate length, not meaning")
<< QETApp::tr("Schema", << QETApp::tr("Schema",
"Normal example text - translate length, not meaning") "Normal example text - translate length, not meaning")
<< QETApp::tr("Electrique", << QETApp::tr("Electrique",
"Normal example text - translate length, not meaning") "Normal example text - translate length, not meaning")
<< QETApp::tr("QElectroTech", << QETApp::tr("QElectroTech",
"Long example text - translate length, not meaning") "Long example text - translate length, not meaning")
); );
return(widget); return(widget);
} }
@@ -1699,7 +1707,7 @@ void QETApp::openElementLocations(const QList<ElementsLocation> &locations_list)
@see QETTitleBlockTemplateEditor::setOpenForDuplication() @see QETTitleBlockTemplateEditor::setOpenForDuplication()
*/ */
void QETApp::openTitleBlockTemplate(const TitleBlockTemplateLocation &location, void QETApp::openTitleBlockTemplate(const TitleBlockTemplateLocation &location,
bool duplicate) { bool duplicate) {
QETTitleBlockTemplateEditor *qet_template_editor = new QETTitleBlockTemplateEditor(); QETTitleBlockTemplateEditor *qet_template_editor = new QETTitleBlockTemplateEditor();
qet_template_editor -> setOpenForDuplication(duplicate); qet_template_editor -> setOpenForDuplication(duplicate);
qet_template_editor -> edit(location); qet_template_editor -> edit(location);
@@ -1822,7 +1830,7 @@ QList<QWidget *> QETApp::floatingToolbarsAndDocksForMainWindow(
foreach(QWidget *qw, qApp->topLevelWidgets()) { foreach(QWidget *qw, qApp->topLevelWidgets()) {
if (!qw -> isWindow()) continue; if (!qw -> isWindow()) continue;
if (qobject_cast<QToolBar *>(qw) if (qobject_cast<QToolBar *>(qw)
|| qobject_cast<QDockWidget *>(qw)) { || qobject_cast<QDockWidget *>(qw)) {
if (qw -> parent() == window) widgets << qw; if (qw -> parent() == window) widgets << qw;
} }
} }
@@ -1935,7 +1943,7 @@ void QETApp::setSplashScreenStep(const QString &message) {
if (!m_splash_screen) return; if (!m_splash_screen) return;
if (!message.isEmpty()) { if (!message.isEmpty()) {
m_splash_screen -> showMessage(message, m_splash_screen -> showMessage(message,
Qt::AlignBottom | Qt::AlignLeft); Qt::AlignBottom | Qt::AlignLeft);
} }
qApp->processEvents(); qApp->processEvents();
} }
@@ -2016,7 +2024,7 @@ void QETApp::initConfiguration()
void QETApp::initSystemTray() void QETApp::initSystemTray()
{ {
setSplashScreenStep(tr("Chargement... icône du systray", setSplashScreenStep(tr("Chargement... icône du systray",
"splash screen caption")); "splash screen caption"));
// initialization of the icon menus in the systray // initialization of the icon menus in the systray
// initialisation des menus de l'icone dans le systray // initialisation des menus de l'icone dans le systray
menu_systray = new QMenu(tr("QElectroTech", "systray menu title")); menu_systray = new QMenu(tr("QElectroTech", "systray menu title"));
@@ -2118,7 +2126,7 @@ int QETApp::projectIdFromString(const QString &url) {
if (!match.hasMatch()) if (!match.hasMatch())
{ {
qDebug()<<"no Match => return" qDebug()<<"no Match => return"
<<url; <<url;
return(-1); return(-1);
} }
bool conv_ok = false; bool conv_ok = false;
@@ -2240,8 +2248,8 @@ void QETApp::checkBackupFiles()
text.append(tr("<b>Les fichiers de restauration suivant on été trouvé,<br>" text.append(tr("<b>Les fichiers de restauration suivant on été trouvé,<br>"
"Voulez-vous les ouvrir ?</b><br>")); "Voulez-vous les ouvrir ?</b><br>"));
} }
for(const KAutoSaveFile *kasf : stale_files) for(const KAutoSaveFile *kasf : stale_files)
{ {
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
//Remove the first character '/' before the name of the drive //Remove the first character '/' before the name of the drive
text.append("<br>" + kasf->managedFile().path().remove(0,1)); text.append("<br>" + kasf->managedFile().path().remove(0,1));
@@ -2329,19 +2337,19 @@ void QETApp::fetchWindowStats(
#ifdef Q_OS_DARWIN #ifdef Q_OS_DARWIN
/** /**
Gere les evenements, en particulier l'evenement FileOpen sous MacOs. Gere les evenements, en particulier l'evenement FileOpen sous MacOs.
@param e Evenement a gerer @param e Evenement a gerer
*/ */
bool QETApp::eventFiltrer(QObject *object, QEvent *e) { bool QETApp::eventFiltrer(QObject *object, QEvent *e) {
// gere l'ouverture de fichiers (sous MacOs) // gere l'ouverture de fichiers (sous MacOs)
if (e -> type() == QEvent::FileOpen) { if (e -> type() == QEvent::FileOpen) {
// nom du fichier a ouvrir // nom du fichier a ouvrir
QString filename = static_cast<QFileOpenEvent *>(e) -> file(); QString filename = static_cast<QFileOpenEvent *>(e) -> file();
openFiles(QStringList() << filename); openFiles(QStringList() << filename);
return(true); return(true);
} else { } else {
return QObject::eventFilter(object, e); return QObject::eventFilter(object, e);
} }
} }
#endif #endif

View File

@@ -436,7 +436,7 @@ void QetGraphicsTableItem::setPreviousTable(QetGraphicsTableItem *table)
setModel(m_previous_table->m_model); setModel(m_previous_table->m_model);
} }
else //Copie the model of old previous table else //Copie the model of old previous table
{ {
setModel(new ProjectDBModel(*static_cast<ProjectDBModel *>(old_previous_table->model()))); setModel(new ProjectDBModel(*static_cast<ProjectDBModel *>(old_previous_table->model())));
} }
@@ -657,7 +657,7 @@ bool QetGraphicsTableItem::toDXF(const QString &filepath)
//QRectF rect = boundingRect(); //QRectF rect = boundingRect();
QRectF rect(0,0, m_header_item->rect().width(), m_current_size.height()); QRectF rect(0,0, m_header_item->rect().width(), m_current_size.height());
QPolygonF poly(rect); QPolygonF poly(rect);
Createdxf::drawPolygon(filepath,mapToScene(poly),0); Createdxf::drawPolygon(filepath,mapToScene(poly),0);
//Draw vertical lines //Draw vertical lines
auto offset= 0; auto offset= 0;
@@ -970,6 +970,7 @@ void QetGraphicsTableItem::adjustColumnsWidth()
int sum_=0; int sum_=0;
for(auto i= 0 ; i<m_model->columnCount() ; ++i) for(auto i= 0 ; i<m_model->columnCount() ; ++i)
{ {
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
auto at_a = std::min(m_minimum_column_width.size()-1, i); //In case of the I is higher than m_minimum_column_width or auto at_a = std::min(m_minimum_column_width.size()-1, i); //In case of the I is higher than m_minimum_column_width or
auto at_b = std::min(m_header_item->minimumSectionWidth().size()-1, i); //m_header_item->minimumSectionWidth().size() auto at_b = std::min(m_header_item->minimumSectionWidth().size()-1, i); //m_header_item->minimumSectionWidth().size()
m_header_item->resizeSection( m_header_item->resizeSection(
@@ -978,6 +979,12 @@ void QetGraphicsTableItem::adjustColumnsWidth()
m_minimum_column_width.at(at_a), m_minimum_column_width.at(at_a),
m_header_item->minimumSectionWidth().at(at_b))+b); m_header_item->minimumSectionWidth().at(at_b))+b);
sum_+= m_header_item->sectionSize(i); sum_+= m_header_item->sectionSize(i);
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
qDebug()<<"Help code for QT 6 or later";
#endif
} }

View File

@@ -470,15 +470,15 @@ QPointF Conductor::extendTerminal(const QPointF &terminal, Qet::Orientation term
/** /**
Dessine le conducteur sans antialiasing. Dessine le conducteur sans antialiasing.
@param qp Le QPainter a utiliser pour dessiner le conducteur @param painter Le QPainter a utiliser pour dessiner le conducteur
@param options Les options de style pour le conducteur @param options Les options de style pour le conducteur
@param qw Le QWidget sur lequel on dessine @param qw Le QWidget sur lequel on dessine
*/ */
void Conductor::paint(QPainter *qp, const QStyleOptionGraphicsItem *options, QWidget *qw) void Conductor::paint(QPainter *painter, const QStyleOptionGraphicsItem *options, QWidget *qw)
{ {
Q_UNUSED(qw); Q_UNUSED(qw);
qp -> save(); painter -> save();
qp -> setRenderHint(QPainter::Antialiasing, false); painter -> setRenderHint(QPainter::Antialiasing, false);
// Set the color of conductor // Set the color of conductor
QColor final_conductor_color(m_properties.color); QColor final_conductor_color(m_properties.color);
@@ -500,7 +500,7 @@ void Conductor::paint(QPainter *qp, const QStyleOptionGraphicsItem *options, QWi
conductor_pen.setWidthF(m_mouse_over? (m_properties.cond_size) +4 : (m_properties.cond_size)); conductor_pen.setWidthF(m_mouse_over? (m_properties.cond_size) +4 : (m_properties.cond_size));
//Set the QPen and QBrush to the QPainter //Set the QPen and QBrush to the QPainter
qp -> setBrush(conductor_brush); painter -> setBrush(conductor_brush);
QPen final_conductor_pen = conductor_pen; QPen final_conductor_pen = conductor_pen;
//Set the conductor style //Set the conductor style
@@ -509,14 +509,22 @@ void Conductor::paint(QPainter *qp, const QStyleOptionGraphicsItem *options, QWi
final_conductor_pen.setJoinStyle(Qt::SvgMiterJoin); // better rendering with dot final_conductor_pen.setJoinStyle(Qt::SvgMiterJoin); // better rendering with dot
//Use a cosmetique line, below a certain zoom //Use a cosmetique line, below a certain zoom
if (options && options -> levelOfDetail < 1.0) { #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
if (options && options -> levelOfDetail < 1.0)
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
if (options && options->levelOfDetailFromTransform(painter->worldTransform()) < 1.0)
#endif
{
final_conductor_pen.setCosmetic(true); final_conductor_pen.setCosmetic(true);
} }
qp -> setPen(final_conductor_pen); painter -> setPen(final_conductor_pen);
//Draw the conductor //Draw the conductor
qp -> drawPath(path()); painter -> drawPath(path());
//Draw the second color //Draw the second color
if(m_properties.m_bicolor) if(m_properties.m_bicolor)
{ {
@@ -525,20 +533,20 @@ void Conductor::paint(QPainter *qp, const QStyleOptionGraphicsItem *options, QWi
QVector<qreal> dash_pattern; QVector<qreal> dash_pattern;
dash_pattern << m_properties.m_dash_size-2 << m_properties.m_dash_size; dash_pattern << m_properties.m_dash_size-2 << m_properties.m_dash_size;
final_conductor_pen.setDashPattern(dash_pattern); final_conductor_pen.setDashPattern(dash_pattern);
qp->save(); painter->save();
qp->setPen(final_conductor_pen); painter->setPen(final_conductor_pen);
qp->drawPath(path()); painter->drawPath(path());
qp->restore(); painter->restore();
} }
if (m_properties.type == ConductorProperties::Single) { if (m_properties.type == ConductorProperties::Single) {
qp -> setBrush(final_conductor_color); painter -> setBrush(final_conductor_color);
m_properties.singleLineProperties.draw( m_properties.singleLineProperties.draw(
qp, painter,
middleSegment() -> isHorizontal() ? QET::Horizontal : QET::Vertical, middleSegment() -> isHorizontal() ? QET::Horizontal : QET::Vertical,
QRectF(middleSegment() -> middle() - QPointF(12.0, 12.0), QSizeF(24.0, 24.0)) QRectF(middleSegment() -> middle() - QPointF(12.0, 12.0), QSizeF(24.0, 24.0))
); );
if (isSelected()) qp -> setBrush(Qt::NoBrush); if (isSelected()) painter -> setBrush(Qt::NoBrush);
} }
//Draw the junctions //Draw the junctions
@@ -546,15 +554,15 @@ void Conductor::paint(QPainter *qp, const QStyleOptionGraphicsItem *options, QWi
if (!junctions_list.isEmpty()) { if (!junctions_list.isEmpty()) {
final_conductor_pen.setStyle(Qt::SolidLine); final_conductor_pen.setStyle(Qt::SolidLine);
QBrush junction_brush(final_conductor_color, Qt::SolidPattern); QBrush junction_brush(final_conductor_color, Qt::SolidPattern);
qp -> setPen(final_conductor_pen); painter -> setPen(final_conductor_pen);
qp -> setBrush(junction_brush); painter -> setBrush(junction_brush);
qp -> setRenderHint(QPainter::Antialiasing, true); painter -> setRenderHint(QPainter::Antialiasing, true);
foreach(QPointF point, junctions_list) { foreach(QPointF point, junctions_list) {
qp -> drawEllipse(QRectF(point.x() - 1.5, point.y() - 1.5, 3.0, 3.0)); painter -> drawEllipse(QRectF(point.x() - 1.5, point.y() - 1.5, 3.0, 3.0));
} }
} }
qp -> restore(); painter -> restore();
} }
/// @return le Diagram auquel ce conducteur appartient, ou 0 si ce conducteur est independant /// @return le Diagram auquel ce conducteur appartient, ou 0 si ce conducteur est independant
@@ -1014,8 +1022,8 @@ bool Conductor::fromXml(QDomElement &dom_element)
@return Un element XML representant le conducteur @return Un element XML representant le conducteur
*/ */
QDomElement Conductor::toXml(QDomDocument &dom_document, QDomElement Conductor::toXml(QDomDocument &dom_document,
QHash<Terminal *, QHash<Terminal *,
int> &table_adr_id) const int> &table_adr_id) const
{ {
QDomElement dom_element = dom_document.createElement("conductor"); QDomElement dom_element = dom_document.createElement("conductor");
@@ -1514,7 +1522,7 @@ QPainterPath Conductor::path() const
the other values of property stay unmodified the other values of property stay unmodified
*/ */
void Conductor::setPropertyToPotential(const ConductorProperties &property, void Conductor::setPropertyToPotential(const ConductorProperties &property,
bool only_text) bool only_text)
{ {
setProperties(property); setProperties(property);
QSet <Conductor *> potential_list = relatedPotentialConductors(); QSet <Conductor *> potential_list = relatedPotentialConductors();

View File

@@ -33,6 +33,7 @@
#include "elementtextitemgroup.h" #include "elementtextitemgroup.h"
#include "elementpicturefactory.h" #include "elementpicturefactory.h"
#include "iostream" #include "iostream"
#include <QDomElement>
class ElementXmlRetroCompatibility class ElementXmlRetroCompatibility
{ {
@@ -45,11 +46,11 @@ class ElementXmlRetroCompatibility
{ {
int i = 0; int i = 0;
while (!dom_element.attribute(seq + while (!dom_element.attribute(seq +
QString::number(i+1)).isEmpty()) QString::number(i+1)).isEmpty())
{ {
list->append(dom_element.attribute( list->append(dom_element.attribute(
seq + seq +
QString::number(i+1))); QString::number(i+1)));
i++; i++;
} }
} }
@@ -210,7 +211,15 @@ void Element::paint(
drawHighlight(painter, options); drawHighlight(painter, options);
} }
if (options && options -> levelOfDetail < 1.0) { #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
if (options && options -> levelOfDetail < 1.0)
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
if (options && options->levelOfDetailFromTransform(painter->worldTransform()) < 1.0)
#endif
{
painter->drawPicture(0, 0, m_low_zoom_picture); painter->drawPicture(0, 0, m_low_zoom_picture);
} else { } else {
painter->drawPicture(0, 0, m_picture); painter->drawPicture(0, 0, m_picture);
@@ -228,7 +237,7 @@ void Element::paint(
QRectF Element::boundingRect() const QRectF Element::boundingRect() const
{ {
return(QRectF(QPointF(-hotspot_coord.x(), -hotspot_coord.y()), return(QRectF(QPointF(-hotspot_coord.x(), -hotspot_coord.y()),
dimensions)); dimensions));
} }
/** /**
@@ -357,7 +366,7 @@ void Element::drawHighlight(
painter -> save(); painter -> save();
qreal gradient_radius = qMin(boundingRect().width(), qreal gradient_radius = qMin(boundingRect().width(),
boundingRect().height()) / 2.0; boundingRect().height()) / 2.0;
QRadialGradient gradient( QRadialGradient gradient(
boundingRect().center(), boundingRect().center(),
gradient_radius, gradient_radius,
@@ -457,8 +466,8 @@ bool Element::buildFromXml(const QDomElement &xml_def_elmt, int *state)
//scroll of the Children of the Definition: Parts of the Drawing //scroll of the Children of the Definition: Parts of the Drawing
int parsed_elements_count = 0; int parsed_elements_count = 0;
for (QDomNode node = xml_def_elmt.firstChild() ; for (QDomNode node = xml_def_elmt.firstChild() ;
!node.isNull() ; !node.isNull() ;
node = node.nextSibling()) node = node.nextSibling())
{ {
QDomElement elmts = node.toElement(); QDomElement elmts = node.toElement();
if (elmts.isNull()) if (elmts.isNull())
@@ -471,8 +480,8 @@ bool Element::buildFromXml(const QDomElement &xml_def_elmt, int *state)
QList <QDomElement> input_field; QList <QDomElement> input_field;
bool have_label = false; bool have_label = false;
for (QDomElement input_node = node.firstChildElement("input") ; for (QDomElement input_node = node.firstChildElement("input") ;
!input_node.isNull() ; !input_node.isNull() ;
input_node = input_node.nextSiblingElement("input")) input_node = input_node.nextSiblingElement("input"))
{ {
if (!input_node.isNull()) if (!input_node.isNull())
{ {
@@ -488,8 +497,8 @@ bool Element::buildFromXml(const QDomElement &xml_def_elmt, int *state)
//Parse the definition //Parse the definition
for (QDomNode n = node.firstChild() ; for (QDomNode n = node.firstChild() ;
!n.isNull() ; !n.isNull() ;
n = n.nextSibling()) n = n.nextSibling())
{ {
QDomElement qde = n.toElement(); QDomElement qde = n.toElement();
if (qde.isNull()) if (qde.isNull())
@@ -588,7 +597,7 @@ bool Element::parseInput(const QDomElement &dom_element)
QTransform transform; QTransform transform;
//First make the rotation //First make the rotation
transform.rotate(dom_element.attribute("rotation", transform.rotate(dom_element.attribute("rotation",
"0").toDouble()); "0").toDouble());
QPointF pos = transform.map( QPointF pos = transform.map(
QPointF(0, QPointF(0,
-deti->boundingRect().height()/2)); -deti->boundingRect().height()/2));
@@ -753,17 +762,23 @@ bool Element::fromXml(
// copie des associations id / adr // copie des associations id / adr
foreach(int id_trouve, priv_id_adr.keys()) { foreach(int id_trouve, priv_id_adr.keys()) {
table_id_adr.insert(id_trouve, table_id_adr.insert(id_trouve,
priv_id_adr.value(id_trouve)); priv_id_adr.value(id_trouve));
} }
} }
//load uuid of connected elements //load uuid of connected elements
QList <QDomElement> uuid_list = QET::findInDomElement(e, QList <QDomElement> uuid_list = QET::findInDomElement(e,
"links_uuids", "links_uuids",
"link_uuid"); "link_uuid");
foreach (QDomElement qdo, uuid_list) foreach (QDomElement qdo, uuid_list)
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
tmp_uuids_link << qdo.attribute("uuid"); tmp_uuids_link << qdo.attribute("uuid");
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
qDebug()<<"Help code for QT 6 or later";
#endif
//uuid of this element //uuid of this element
m_uuid= QUuid(e.attribute("uuid", QUuid::createUuid().toString())); m_uuid= QUuid(e.attribute("uuid", QUuid::createUuid().toString()));
@@ -810,9 +825,9 @@ bool Element::fromXml(
//***Dynamic texts item***// //***Dynamic texts item***//
//************************// //************************//
for (const QDomElement& qde : QET::findInDomElement( for (const QDomElement& qde : QET::findInDomElement(
e, e,
"dynamic_texts", "dynamic_texts",
DynamicElementTextItem::xmlTagName())) DynamicElementTextItem::xmlTagName()))
{ {
DynamicElementTextItem *deti = new DynamicElementTextItem(this); DynamicElementTextItem *deti = new DynamicElementTextItem(this);
addDynamicTextItem(deti); addDynamicTextItem(deti);
@@ -842,7 +857,7 @@ bool Element::fromXml(
if (qFuzzyCompare(qreal(dom_input.attribute("x").toDouble()), if (qFuzzyCompare(qreal(dom_input.attribute("x").toDouble()),
m_converted_text_from_xml_description.value(deti).x()) && m_converted_text_from_xml_description.value(deti).x()) &&
qFuzzyCompare(qreal(dom_input.attribute("y").toDouble()), qFuzzyCompare(qreal(dom_input.attribute("y").toDouble()),
m_converted_text_from_xml_description.value(deti).y())) m_converted_text_from_xml_description.value(deti).y()))
{ {
//Once again this 'if', is only for retrocompatibility with old old old project //Once again this 'if', is only for retrocompatibility with old old old project
//when element text with tagg "label" is not null, but the element information "label" is. //when element text with tagg "label" is not null, but the element information "label" is.
@@ -913,9 +928,9 @@ bool Element::fromXml(
m_converted_text_from_xml_description.clear(); m_converted_text_from_xml_description.clear();
for (QDomElement qde : QET::findInDomElement( for (QDomElement qde : QET::findInDomElement(
e, e,
"texts_groups", "texts_groups",
ElementTextItemGroup::xmlTaggName())) ElementTextItemGroup::xmlTaggName()))
{ {
ElementTextItemGroup *group = ElementTextItemGroup *group =
addTextGroup("loaded_from_xml_group"); addTextGroup("loaded_from_xml_group");
@@ -991,11 +1006,11 @@ bool Element::fromXml(
{ {
if(!label.isEmpty() && la && if(!label.isEmpty() && la &&
((!comment.isEmpty() && c) ((!comment.isEmpty() && c)
|| (!location.isEmpty() && lo))) || (!location.isEmpty() && lo)))
{ {
//#2 in the converted list one text must have text from = element info and info name = label //#2 in the converted list one text must have text from = element info and info name = label
for(DynamicElementTextItem *deti for(DynamicElementTextItem *deti
: successfully_converted) : successfully_converted)
{ {
if(deti->textFrom()== DynamicElementTextItem::ElementInfo if(deti->textFrom()== DynamicElementTextItem::ElementInfo
&& deti->infoName() == "label") && deti->infoName() == "label")
@@ -1058,10 +1073,10 @@ bool Element::fromXml(
addTextToGroup(deti, group); addTextToGroup(deti, group);
if(comment_text) if(comment_text)
addTextToGroup(comment_text, addTextToGroup(comment_text,
group); group);
if(location_text) if(location_text)
addTextToGroup(location_text, addTextToGroup(location_text,
group); group);
group->setAlignment(Qt::AlignVCenter); group->setAlignment(Qt::AlignVCenter);
group->setVerticalAdjustment(-4); group->setVerticalAdjustment(-4);
group->setRotation(rotation); group->setRotation(rotation);
@@ -1354,7 +1369,7 @@ ElementTextItemGroup *Element::addTextGroup(const QString &name)
if(m_texts_group.isEmpty()) if(m_texts_group.isEmpty())
{ {
ElementTextItemGroup *group = new ElementTextItemGroup(name, ElementTextItemGroup *group = new ElementTextItemGroup(name,
this); this);
m_texts_group << group; m_texts_group << group;
emit textsGroupAdded(group); emit textsGroupAdded(group);
return group; return group;
@@ -1454,7 +1469,7 @@ QList<ElementTextItemGroup *> Element::textGroups() const
@return : true if the text was succesfully added to the group. @return : true if the text was succesfully added to the group.
*/ */
bool Element::addTextToGroup(DynamicElementTextItem *text, bool Element::addTextToGroup(DynamicElementTextItem *text,
ElementTextItemGroup *group) ElementTextItemGroup *group)
{ {
if(!m_dynamic_text_list.contains(text)) if(!m_dynamic_text_list.contains(text))
return false; return false;
@@ -1643,7 +1658,7 @@ void Element::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
*/ */
void Element::hoverEnterEvent(QGraphicsSceneHoverEvent *e) void Element::hoverEnterEvent(QGraphicsSceneHoverEvent *e)
{ {
Q_UNUSED(e) Q_UNUSED(e)
foreach (Element *elmt, linkedElements()) foreach (Element *elmt, linkedElements())
elmt -> setHighlighted(true); elmt -> setHighlighted(true);
@@ -1661,7 +1676,7 @@ void Element::hoverEnterEvent(QGraphicsSceneHoverEvent *e)
*/ */
void Element::hoverLeaveEvent(QGraphicsSceneHoverEvent *e) void Element::hoverLeaveEvent(QGraphicsSceneHoverEvent *e)
{ {
Q_UNUSED(e) Q_UNUSED(e)
foreach (Element *elmt, linkedElements()) foreach (Element *elmt, linkedElements())
elmt -> setHighlighted(false); elmt -> setHighlighted(false);
@@ -1703,10 +1718,10 @@ void Element::setUpFormula(bool code_letter)
m_autoNum_seq.clear(); m_autoNum_seq.clear();
autonum::setSequential(formula, autonum::setSequential(formula,
m_autoNum_seq, m_autoNum_seq,
nc, nc,
diagram(), diagram(),
element_currentAutoNum); element_currentAutoNum);
diagram()->project()->addElementAutoNum(element_currentAutoNum, diagram()->project()->addElementAutoNum(element_currentAutoNum,
ncc.next()); ncc.next());

View File

@@ -262,23 +262,30 @@ void Terminal::removeConductor(Conductor *conductor)
/** /**
@brief Terminal::paint @brief Terminal::paint
Fonction de dessin des bornes Fonction de dessin des bornes
@param p Le QPainter a utiliser @param painter Le QPainter a utiliser
@param options Les options de dessin @param options Les options de dessin
*/ */
void Terminal::paint( void Terminal::paint(
QPainter *p, QPainter *painter,
const QStyleOptionGraphicsItem *options, const QStyleOptionGraphicsItem *options,
QWidget *) QWidget *)
{ {
// en dessous d'un certain zoom, les bornes ne sont plus dessinees // en dessous d'un certain zoom, les bornes ne sont plus dessinees
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
if (options && options -> levelOfDetail < 0.5) return; if (options && options -> levelOfDetail < 0.5) return;
#else
p -> save(); #if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
if (options && options->levelOfDetailFromTransform(painter->worldTransform()) < 0.5)
return;
#endif
painter -> save();
//annulation des renderhints //annulation des renderhints
p -> setRenderHint(QPainter::Antialiasing, false); painter -> setRenderHint(QPainter::Antialiasing, false);
p -> setRenderHint(QPainter::TextAntialiasing, false); painter -> setRenderHint(QPainter::TextAntialiasing, false);
p -> setRenderHint(QPainter::SmoothPixmapTransform, false); painter -> setRenderHint(QPainter::SmoothPixmapTransform, false);
// on travaille avec les coordonnees de l'element parent // on travaille avec les coordonnees de l'element parent
QPointF c = mapFromParent(d->m_pos); QPointF c = mapFromParent(d->m_pos);
@@ -287,23 +294,31 @@ void Terminal::paint(
QPen t; QPen t;
t.setWidthF(1.0); t.setWidthF(1.0);
if (options && options -> levelOfDetail < 1.0) { #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
if (options && options -> levelOfDetail < 1.0)
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
if (options && options->levelOfDetailFromTransform(painter->worldTransform()) < 1.0)
#endif
{
t.setCosmetic(true); t.setCosmetic(true);
} }
// dessin de la borne en rouge // dessin de la borne en rouge
t.setColor(Qt::red); t.setColor(Qt::red);
p -> setPen(t); painter -> setPen(t);
p -> drawLine(c, e); painter -> drawLine(c, e);
// dessin du point d'amarrage au conducteur en bleu // dessin du point d'amarrage au conducteur en bleu
t.setColor(hovered_color_); t.setColor(hovered_color_);
p -> setPen(t); painter -> setPen(t);
p -> setBrush(hovered_color_); painter -> setBrush(hovered_color_);
if (hovered_) { if (hovered_) {
p -> setRenderHint(QPainter::Antialiasing, true); painter -> setRenderHint(QPainter::Antialiasing, true);
p -> drawEllipse(QRectF(c.x() - 2.5, c.y() - 2.5, 5.0, 5.0)); painter -> drawEllipse(QRectF(c.x() - 2.5, c.y() - 2.5, 5.0, 5.0));
} else p -> drawPoint(c); } else painter -> drawPoint(c);
//Draw help line if needed, //Draw help line if needed,
if (diagram() && m_draw_help_line) if (diagram() && m_draw_help_line)
@@ -365,7 +380,7 @@ void Terminal::paint(
m_help_line_a -> setLine(line); m_help_line_a -> setLine(line);
} }
p -> restore(); painter -> restore();
} }
/** /**

View File

@@ -1,17 +1,17 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
@@ -38,7 +38,7 @@ class Terminal : public QGraphicsObject
signals: signals:
void conductorWasAdded(Conductor *conductor); void conductorWasAdded(Conductor *conductor);
void conductorWasRemoved(Conductor *conductor); void conductorWasRemoved(Conductor *conductor);
// constructors, destructor // constructors, destructor
public: public:
Terminal(QPointF, Qet::Orientation, Element * = nullptr); Terminal(QPointF, Qet::Orientation, Element * = nullptr);
@@ -47,10 +47,10 @@ class Terminal : public QGraphicsObject
Terminal(QPointF, Qet::Orientation, QString number, Terminal(QPointF, Qet::Orientation, QString number,
QString name, bool hiddenName, Element * = nullptr); QString name, bool hiddenName, Element * = nullptr);
~Terminal() override; ~Terminal() override;
private: private:
Terminal(const Terminal &); Terminal(const Terminal &);
// methods // methods
public: public:
/** /**
@@ -60,13 +60,15 @@ class Terminal : public QGraphicsObject
@return the QGraphicsItem type @return the QGraphicsItem type
*/ */
int type() const override { return Type; } int type() const override { return Type; }
void paint (QPainter *,const QStyleOptionGraphicsItem *, void paint(
QWidget *) override; QPainter *painter,
const QStyleOptionGraphicsItem *,
QWidget *) override;
void drawHelpLine (bool draw = true); void drawHelpLine (bool draw = true);
QLineF HelpLine () const; QLineF HelpLine () const;
QRectF boundingRect () const override; QRectF boundingRect () const override;
// methods to manage conductors attached to the terminal // methods to manage conductors attached to the terminal
Terminal* alignedWithTerminal () const; Terminal* alignedWithTerminal () const;
bool addConductor (Conductor *conductor); bool addConductor (Conductor *conductor);
@@ -75,7 +77,7 @@ class Terminal : public QGraphicsObject
Diagram *diagram () const; Diagram *diagram () const;
Element *parentElement () const; Element *parentElement () const;
QUuid uuid () const; QUuid uuid () const;
QList<Conductor *> conductors() const; QList<Conductor *> conductors() const;
Qet::Orientation orientation() const; Qet::Orientation orientation() const;
QPointF dockConductor() const; QPointF dockConductor() const;
@@ -86,12 +88,12 @@ class Terminal : public QGraphicsObject
void updateConductor(); void updateConductor();
bool isLinkedTo(Terminal *); bool isLinkedTo(Terminal *);
bool canBeLinkedTo(Terminal *); bool canBeLinkedTo(Terminal *);
// methods related to XML import/export // methods related to XML import/export
static bool valideXml(QDomElement &); static bool valideXml(QDomElement &);
bool fromXml (QDomElement &); bool fromXml (QDomElement &);
QDomElement toXml (QDomDocument &) const; QDomElement toXml (QDomDocument &) const;
protected: protected:
// methods related to events management // methods related to events management
void hoverEnterEvent (QGraphicsSceneHoverEvent *) override; void hoverEnterEvent (QGraphicsSceneHoverEvent *) override;
@@ -100,7 +102,7 @@ class Terminal : public QGraphicsObject
void mousePressEvent (QGraphicsSceneMouseEvent *) override; void mousePressEvent (QGraphicsSceneMouseEvent *) override;
void mouseMoveEvent (QGraphicsSceneMouseEvent *) override; void mouseMoveEvent (QGraphicsSceneMouseEvent *) override;
void mouseReleaseEvent(QGraphicsSceneMouseEvent *) override; void mouseReleaseEvent(QGraphicsSceneMouseEvent *) override;
// attributes // attributes
public: public:
enum { Type = UserType + 1002 }; enum { Type = UserType + 1002 };
@@ -116,7 +118,7 @@ class Terminal : public QGraphicsObject
static QColor warningColor; static QColor warningColor;
/// color for forbidden actions /// color for forbidden actions
static QColor forbiddenColor; static QColor forbiddenColor;
private: private:
bool m_draw_help_line{false}; bool m_draw_help_line{false};
QGraphicsLineItem *m_help_line{nullptr}; QGraphicsLineItem *m_help_line{nullptr};
@@ -127,10 +129,10 @@ class Terminal : public QGraphicsObject
/// Parent electrical element /// Parent electrical element
Element *parent_element_{nullptr}; Element *parent_element_{nullptr};
public: public:
/// docking point for parent element /// docking point for parent element
QPointF dock_elmt_; QPointF dock_elmt_;
private: private:
/// List of conductors attached to the terminal /// List of conductors attached to the terminal
QList<Conductor *> conductors_; QList<Conductor *> conductors_;
/** /**
@@ -150,7 +152,7 @@ class Terminal : public QGraphicsObject
/// Name of Terminal /// Name of Terminal
QString name_terminal_; QString name_terminal_;
bool name_terminal_hidden; bool name_terminal_hidden;
private: private:
void init(QString number, QString name, bool hiddenName); void init(QString number, QString name, bool hiddenName);
void init(QPointF pf, Qet::Orientation o, QString number, void init(QPointF pf, Qet::Orientation o, QString number,
@@ -185,6 +187,6 @@ inline QString Terminal::name() const
} }
QList<Terminal *> relatedPotentialTerminal (const Terminal *terminal, QList<Terminal *> relatedPotentialTerminal (const Terminal *terminal,
const bool all_diagram = true); const bool all_diagram = true);
#endif #endif

View File

@@ -16,11 +16,6 @@
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include <QTimer>
#include <QStandardPaths>
#include <utility>
#include <QtConcurrent>
#include <QHash>
#include "qetproject.h" #include "qetproject.h"
#include "diagram.h" #include "diagram.h"
@@ -37,6 +32,13 @@
#include "numerotationcontextcommands.h" #include "numerotationcontextcommands.h"
#include "assignvariables.h" #include "assignvariables.h"
#include <QTimer>
#include <QStandardPaths>
#include <utility>
#include <QtConcurrent>
#include <QHash>
#include <QtDebug>
static int BACKUP_INTERVAL = 120000; //interval in ms of backup = 2min static int BACKUP_INTERVAL = 120000; //interval in ms of backup = 2min
/** /**
@@ -178,7 +180,7 @@ QETProject::ProjectState QETProject::openFile(QFile *file)
bool opened_here = file->isOpen() ? false : true; bool opened_here = file->isOpen() ? false : true;
if (!file->isOpen() if (!file->isOpen()
&& !file->open(QIODevice::ReadOnly && !file->open(QIODevice::ReadOnly
| QIODevice::Text)) { | QIODevice::Text)) {
return FileOpenFailed; return FileOpenFailed;
} }
QFileInfo fi(*file); QFileInfo fi(*file);
@@ -887,7 +889,7 @@ QDomDocument QETProject::toXml()
for(Diagram *diagram : diagrams_list) for(Diagram *diagram : diagrams_list)
{ {
qDebug() << QString("exporting diagram \"%1\"" qDebug() << QString("exporting diagram \"%1\""
).arg(diagram -> title()) ).arg(diagram -> title())
<< "[" << "["
<< diagram << diagram
<< "]"; << "]";
@@ -1080,7 +1082,7 @@ ElementsLocation QETProject::importElement(ElementsLocation &location)
//Element doesn't exist in the collection, we just import it //Element doesn't exist in the collection, we just import it
else { else {
ElementsLocation loc(m_elements_collection->addElement( ElementsLocation loc(m_elements_collection->addElement(
location), this); location), this);
if (!loc.exist()) { if (!loc.exist()) {
qDebug() << "failed to import location. " qDebug() << "failed to import location. "
@@ -1370,8 +1372,8 @@ void QETProject::readDiagramsXml(QDomDocument &xml_project)
int diagram_order = -1; int diagram_order = -1;
if (!QET::attributeIsAnInteger(diagram_xml_element, if (!QET::attributeIsAnInteger(diagram_xml_element,
"order", "order",
&diagram_order)) &diagram_order))
diagram_order = 500000; diagram_order = 500000;
addDiagram(diagram, diagram_order-1); addDiagram(diagram, diagram_order-1);
@@ -1691,11 +1693,16 @@ NamesList QETProject::namesListForIntegrationCategory()
*/ */
void QETProject::writeBackup() void QETProject::writeBackup()
{ {
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
QDomDocument xml_project(toXml()); QDomDocument xml_project(toXml());
QtConcurrent::run(QET::writeToFile, QtConcurrent::run(
xml_project, QET::writeToFile,xml_project,&m_backup_file,nullptr);
&m_backup_file, #else
nullptr); #if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
qDebug()<<"Help code for QT 6 or later";
#endif
} }
/** /**

View File

@@ -274,7 +274,14 @@ bool QETXML::writeXmlFile(
} }
QTextStream out(&file); QTextStream out(&file);
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
out.setCodec("UTF-8"); out.setCodec("UTF-8");
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
out.setEncoding(QStringConverter::Utf8);
#endif
out.setGenerateByteOrderMark(false); out.setGenerateByteOrderMark(false);
out << xml_document.toString(4); out << xml_document.toString(4);
file.close(); file.close();
@@ -314,9 +321,9 @@ QVector<QDomElement> QETXML::directChild(
{ {
QVector<QDomElement> return_list; QVector<QDomElement> return_list;
for ( for (
QDomNode node = element.firstChild() ; QDomNode node = element.firstChild() ;
!node.isNull() ; !node.isNull() ;
node = node.nextSibling()) node = node.nextSibling())
{ {
if (!node.isElement()) continue; if (!node.isElement()) continue;
QDomElement element = node.toElement(); QDomElement element = node.toElement();
@@ -345,18 +352,18 @@ QVector<QDomElement> QETXML::subChild(
QVector<QDomElement> return_list; QVector<QDomElement> return_list;
for ( for (
QDomNode child = element.firstChild() ; QDomNode child = element.firstChild() ;
!child.isNull() ; !child.isNull() ;
child = child.nextSibling()) child = child.nextSibling())
{ {
QDomElement parents = child.toElement(); QDomElement parents = child.toElement();
if (parents.isNull() || parents.tagName() != parent_tag_name) if (parents.isNull() || parents.tagName() != parent_tag_name)
continue; continue;
for ( for (
QDomNode node_children = parents.firstChild() ; QDomNode node_children = parents.firstChild() ;
!node_children.isNull() ; !node_children.isNull() ;
node_children = node_children.nextSibling()) node_children = node_children.nextSibling())
{ {
QDomElement n_children = node_children.toElement(); QDomElement n_children = node_children.toElement();
if (!n_children.isNull() && n_children.tagName() == children_tag_name) if (!n_children.isNull() && n_children.tagName() == children_tag_name)

View File

@@ -1,28 +1,29 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "qtextorientationwidget.h" #include "qtextorientationwidget.h"
#include <algorithm> #include <algorithm>
#include <QMouseEvent>
/** /**
Constructeur Constructeur
Par defaut, ce widget met en valeur les angles multiples de 45 degres Par defaut, ce widget met en valeur les angles multiples de 45 degres
et presente un texte oriente a 0 degre, avec la police par defaut de et presente un texte oriente a 0 degre, avec la police par defaut de
l'application. Le texte affiche est l'application. Le texte affiche est
@param parent Widget parent @param parent Widget parent
*/ */
QTextOrientationWidget::QTextOrientationWidget(QWidget *parent) : QTextOrientationWidget::QTextOrientationWidget(QWidget *parent) :
@@ -36,14 +37,14 @@ QTextOrientationWidget::QTextOrientationWidget(QWidget *parent) :
// chaines par defaut // chaines par defaut
text_size_hash_.insert(tr("Ex.", "Short example string"), -1); text_size_hash_.insert(tr("Ex.", "Short example string"), -1);
text_size_hash_.insert(tr("Exemple", "Longer example string"), -1); text_size_hash_.insert(tr("Exemple", "Longer example string"), -1);
// definit la politique de gestion de la taille de ce widget : // definit la politique de gestion de la taille de ce widget :
// on prefere la sizeHint() // on prefere la sizeHint()
QSizePolicy size_policy(QSizePolicy::Minimum, QSizePolicy::Minimum); QSizePolicy size_policy(QSizePolicy::Minimum, QSizePolicy::Minimum);
// on souhaite conserver le rapport entre sa hauteur et sa largeur // on souhaite conserver le rapport entre sa hauteur et sa largeur
size_policy.setHeightForWidth(true); size_policy.setHeightForWidth(true);
setSizePolicy(size_policy); setSizePolicy(size_policy);
// suivi de la souris : permet de recevoir les evenements relatifs aux // suivi de la souris : permet de recevoir les evenements relatifs aux
// mouvement de la souris sans que l'utilisateur n'ait a cliquer // mouvement de la souris sans que l'utilisateur n'ait a cliquer
setMouseTracking(true); setMouseTracking(true);
@@ -82,7 +83,7 @@ double QTextOrientationWidget::orientation() const
*/ */
void QTextOrientationWidget::setFont(const QFont &font) { void QTextOrientationWidget::setFont(const QFont &font) {
text_font_ = font; text_font_ = font;
// invalide le cache contenant les longueurs des textes a disposition // invalide le cache contenant les longueurs des textes a disposition
foreach(QString text, text_size_hash_.keys()) { foreach(QString text, text_size_hash_.keys()) {
text_size_hash_[text] = -1; text_size_hash_[text] = -1;
@@ -121,7 +122,7 @@ bool QTextOrientationWidget::textDisplayed() const
*/ */
void QTextOrientationWidget::setUsableTexts(const QStringList &texts_list) { void QTextOrientationWidget::setUsableTexts(const QStringList &texts_list) {
if (texts_list.isEmpty()) return; if (texts_list.isEmpty()) return;
// on oublie les anciennes chaines // on oublie les anciennes chaines
foreach(QString text, text_size_hash_.keys()) { foreach(QString text, text_size_hash_.keys()) {
// il faut oublier les anciennes chaines // il faut oublier les anciennes chaines
@@ -129,7 +130,7 @@ void QTextOrientationWidget::setUsableTexts(const QStringList &texts_list) {
text_size_hash_.remove(text); text_size_hash_.remove(text);
} }
} }
// on ajoute les nouvelles, sans les calculer (on met -1 en guise de longueur) // on ajoute les nouvelles, sans les calculer (on met -1 en guise de longueur)
foreach(QString text, texts_list) { foreach(QString text, texts_list) {
if (!text_size_hash_.contains(text)) { if (!text_size_hash_.contains(text)) {
@@ -185,31 +186,31 @@ int QTextOrientationWidget::heightForWidth(int w) const
*/ */
void QTextOrientationWidget::paintEvent(QPaintEvent *event) { void QTextOrientationWidget::paintEvent(QPaintEvent *event) {
Q_UNUSED(event); Q_UNUSED(event);
// rectangle de travail avec son centre et son rayon // rectangle de travail avec son centre et son rayon
QRect drawing_rectangle(QPoint(0, 0), size()); QRect drawing_rectangle(QPoint(0, 0), size());
drawing_rectangle.adjust(5, 5, -5, -5); drawing_rectangle.adjust(5, 5, -5, -5);
QPointF drawing_rectangle_center(drawing_rectangle.center()); QPointF drawing_rectangle_center(drawing_rectangle.center());
qreal drawing_rectangle_radius = drawing_rectangle.width() / 2.0; qreal drawing_rectangle_radius = drawing_rectangle.width() / 2.0;
QPainter p; QPainter p;
p.begin(this); p.begin(this);
p.setRenderHint(QPainter::Antialiasing, true); p.setRenderHint(QPainter::Antialiasing, true);
p.setRenderHint(QPainter::TextAntialiasing, true); p.setRenderHint(QPainter::TextAntialiasing, true);
// cercle gris a fond jaune // cercle gris a fond jaune
p.setPen(QPen(QBrush(QColor("#9FA8A8")), 2.0)); p.setPen(QPen(QBrush(QColor("#9FA8A8")), 2.0));
p.setBrush(QBrush(QColor("#ffffaa"))); p.setBrush(QBrush(QColor("#ffffaa")));
p.drawEllipse(drawing_rectangle); p.drawEllipse(drawing_rectangle);
// ligne rouge indiquant l'angle actuel // ligne rouge indiquant l'angle actuel
p.setPen(QPen(QBrush(Qt::red), 1.0)); p.setPen(QPen(QBrush(Qt::red), 1.0));
p.translate(drawing_rectangle_center); p.translate(drawing_rectangle_center);
p.rotate(current_orientation_); p.rotate(current_orientation_);
p.drawLine(QLineF(QPointF(), QPointF(drawing_rectangle_radius, 0.0))); p.drawLine(QLineF(QPointF(), QPointF(drawing_rectangle_radius, 0.0)));
// texte optionnel // texte optionnel
if (display_text_) { if (display_text_) {
// determine le texte a afficher // determine le texte a afficher
@@ -223,7 +224,7 @@ void QTextOrientationWidget::paintEvent(QPaintEvent *event) {
p.drawText(QPoint(), chosen_text); p.drawText(QPoint(), chosen_text);
} }
} }
// carres verts a fond vert // carres verts a fond vert
qreal squares_size = size().width() / 15.0; qreal squares_size = size().width() / 15.0;
qreal square_offset = - squares_size / 2.0; qreal square_offset = - squares_size / 2.0;
@@ -244,7 +245,7 @@ void QTextOrientationWidget::paintEvent(QPaintEvent *event) {
p.setBrush(QBrush(QColor("#248A34"))); p.setBrush(QBrush(QColor("#248A34")));
} }
} }
p.end(); p.end();
} }
@@ -254,9 +255,15 @@ void QTextOrientationWidget::paintEvent(QPaintEvent *event) {
*/ */
void QTextOrientationWidget::mouseMoveEvent(QMouseEvent *event) { void QTextOrientationWidget::mouseMoveEvent(QMouseEvent *event) {
if (read_only_) return; if (read_only_) return;
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
bool drawn_angle_hovered = positionIsASquare(event -> localPos(), &highlight_angle_); bool drawn_angle_hovered = positionIsASquare(event -> localPos(), &highlight_angle_);
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
bool drawn_angle_hovered = positionIsASquare(event -> position(), &highlight_angle_);
#endif
if (must_highlight_angle_ != drawn_angle_hovered) { if (must_highlight_angle_ != drawn_angle_hovered) {
must_highlight_angle_ = drawn_angle_hovered; must_highlight_angle_ = drawn_angle_hovered;
update(); update();
@@ -269,10 +276,16 @@ void QTextOrientationWidget::mouseMoveEvent(QMouseEvent *event) {
*/ */
void QTextOrientationWidget::mouseReleaseEvent(QMouseEvent *event) { void QTextOrientationWidget::mouseReleaseEvent(QMouseEvent *event) {
if (read_only_) return; if (read_only_) return;
double clicked_angle; double clicked_angle;
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
bool drawn_angle_clicked = positionIsASquare(event -> localPos(), &clicked_angle); bool drawn_angle_clicked = positionIsASquare(event -> localPos(), &clicked_angle);
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
bool drawn_angle_clicked = positionIsASquare(event -> position(), &clicked_angle);
#endif
if (drawn_angle_clicked) { if (drawn_angle_clicked) {
setOrientation(clicked_angle); setOrientation(clicked_angle);
emit(orientationChanged(clicked_angle)); emit(orientationChanged(clicked_angle));
@@ -288,7 +301,7 @@ void QTextOrientationWidget::mouseReleaseEvent(QMouseEvent *event) {
QString QTextOrientationWidget::getMostUsableStringForRadius(const qreal &radius) { QString QTextOrientationWidget::getMostUsableStringForRadius(const qreal &radius) {
// s'assure que l'on connait la longueur de chaque texte a disposition // s'assure que l'on connait la longueur de chaque texte a disposition
generateTextSizeHash(); generateTextSizeHash();
// recupere les longueurs a disposition // recupere les longueurs a disposition
QList<qreal> available_lengths = text_size_hash_.values(); QList<qreal> available_lengths = text_size_hash_.values();
// trie les longueurs par ordre croissant // trie les longueurs par ordre croissant
@@ -297,7 +310,7 @@ QString QTextOrientationWidget::getMostUsableStringForRadius(const qreal &radius
QList<qreal>::const_iterator i = std::upper_bound(available_lengths.begin(), QList<qreal>::const_iterator i = std::upper_bound(available_lengths.begin(),
available_lengths.end(), available_lengths.end(),
radius); radius);
// la valeur precedent cette position est donc celle qui nous interesse // la valeur precedent cette position est donc celle qui nous interesse
if (i == available_lengths.begin()) { if (i == available_lengths.begin()) {
// nous sommes au debut de la liste - nous ne pouvons donc pas afficher de chaine // nous sommes au debut de la liste - nous ne pouvons donc pas afficher de chaine
@@ -335,27 +348,27 @@ bool QTextOrientationWidget::positionIsASquare(const QPointF &pos, double *angle
// rectangle de travail avec son centre et son rayon // rectangle de travail avec son centre et son rayon
QRect drawing_rectangle(QPoint(0, 0), size()); QRect drawing_rectangle(QPoint(0, 0), size());
drawing_rectangle.adjust(5, 5, -5, -5); drawing_rectangle.adjust(5, 5, -5, -5);
QPointF drawing_rectangle_center(drawing_rectangle.center()); QPointF drawing_rectangle_center(drawing_rectangle.center());
qreal drawing_rectangle_radius = drawing_rectangle.width() / 2.0; qreal drawing_rectangle_radius = drawing_rectangle.width() / 2.0;
qreal squares_size = size().width() / 15.0; qreal squares_size = size().width() / 15.0;
qreal square_offset = - squares_size / 2.0; qreal square_offset = - squares_size / 2.0;
QRectF square_qrect = QRect(square_offset, square_offset, squares_size, squares_size); QRectF square_qrect = QRect(square_offset, square_offset, squares_size, squares_size);
for (double drawing_angle = 0.0 ; drawing_angle < 360.0 ; drawing_angle += squares_interval_) { for (double drawing_angle = 0.0 ; drawing_angle < 360.0 ; drawing_angle += squares_interval_) {
QTransform transform = QTransform() QTransform transform = QTransform()
.translate(drawing_rectangle_center.x(), drawing_rectangle_center.y()) .translate(drawing_rectangle_center.x(), drawing_rectangle_center.y())
.rotate(drawing_angle) .rotate(drawing_angle)
.translate(drawing_rectangle_radius - 1.0, 0.0) .translate(drawing_rectangle_radius - 1.0, 0.0)
.rotate(-45.0); .rotate(-45.0);
QRectF mapped_rectangle = transform.mapRect(square_qrect); QRectF mapped_rectangle = transform.mapRect(square_qrect);
if (mapped_rectangle.contains(pos)) { if (mapped_rectangle.contains(pos)) {
if (angle_value_ptr) *angle_value_ptr = drawing_angle; if (angle_value_ptr) *angle_value_ptr = drawing_angle;
return(true); return(true);
} }
} }
return(false); return(false);
} }

View File

@@ -75,6 +75,7 @@
#include <QHBoxLayout> #include <QHBoxLayout>
#include <QPushButton> #include <QPushButton>
#include <QDialogButtonBox> #include <QDialogButtonBox>
#include <QActionGroup>
QT_BEGIN_NAMESPACE QT_BEGIN_NAMESPACE
@@ -86,14 +87,14 @@ QT_BEGIN_NAMESPACE
namespace qdesigner_internal { namespace qdesigner_internal {
// Richtext simplification filter helpers: Elements to be discarded // Richtext simplification filter helpers: Elements to be discarded
static inline bool filterElement(const QStringRef &name) static inline bool filterElement(const QStringView &name)
{ {
return name != QLatin1String("meta") && name != QLatin1String("style"); return name != QLatin1String("meta") && name != QLatin1String("style");
} }
// Richtext simplification filter helpers: Filter attributes of elements // Richtext simplification filter helpers: Filter attributes of elements
static inline void filterAttributes( static inline void filterAttributes(
const QStringRef &name, const QStringView &name,
QXmlStreamAttributes *atts, QXmlStreamAttributes *atts,
bool *paragraphAlignmentFound) bool *paragraphAlignmentFound)
{ {
@@ -122,8 +123,8 @@ namespace qdesigner_internal {
} }
} }
// Richtext simplification filter helpers: Check for blank QStringRef. // Richtext simplification filter helpers: Check for blank QStringView.
static inline bool isWhiteSpace(const QStringRef &in) static inline bool isWhiteSpace(const QStringView &in)
{ {
const int count = in.size(); const int count = in.size();
for (int i = 0; i < count; i++) for (int i = 0; i < count; i++)
@@ -150,7 +151,7 @@ namespace qdesigner_internal {
case QXmlStreamReader::StartElement: case QXmlStreamReader::StartElement:
elementCount++; elementCount++;
if (filterElement(reader.name())) { if (filterElement(reader.name())) {
const QStringRef name = reader.name(); const QStringView name = reader.name();
QXmlStreamAttributes attributes = reader.attributes(); QXmlStreamAttributes attributes = reader.attributes();
filterAttributes(name, &attributes, &paragraphAlignmentFound); filterAttributes(name, &attributes, &paragraphAlignmentFound);
writer.writeStartElement(name.toString()); writer.writeStartElement(name.toString());

View File

@@ -56,7 +56,7 @@ TitleBlockCell *TitleBlockTemplate::createCell(
const TitleBlockCell *existing_cell) { const TitleBlockCell *existing_cell) {
TitleBlockCell *new_cell = TitleBlockCell *new_cell =
existing_cell ? new TitleBlockCell(*existing_cell) existing_cell ? new TitleBlockCell(*existing_cell)
: new TitleBlockCell(); : new TitleBlockCell();
registered_cells_ << new_cell; registered_cells_ << new_cell;
return(new_cell); return(new_cell);
} }
@@ -260,8 +260,8 @@ TitleBlockTemplate *TitleBlockTemplate::clone() const
*/ */
void TitleBlockTemplate::loadInformation(const QDomElement &xml_element) { void TitleBlockTemplate::loadInformation(const QDomElement &xml_element) {
for (QDomNode n = xml_element.firstChild() ; for (QDomNode n = xml_element.firstChild() ;
!n.isNull() ; !n.isNull() ;
n = n.nextSibling()) { n = n.nextSibling()) {
if (n.isElement() && n.toElement().tagName() == "information") { if (n.isElement() && n.toElement().tagName() == "information") {
setInformation(n.toElement().text()); setInformation(n.toElement().text());
} }
@@ -291,12 +291,12 @@ bool TitleBlockTemplate::loadLogos(const QDomElement &xml_element, bool reset) {
// we look for //logos/logo elements // we look for //logos/logo elements
for (QDomNode n = xml_element.firstChild() ; for (QDomNode n = xml_element.firstChild() ;
!n.isNull() ; !n.isNull() ;
n = n.nextSibling()) { n = n.nextSibling()) {
if (n.isElement() && n.toElement().tagName() == "logos") { if (n.isElement() && n.toElement().tagName() == "logos") {
for (QDomNode p = n.firstChild() ; for (QDomNode p = n.firstChild() ;
!p.isNull() ; !p.isNull() ;
p = p.nextSibling()) { p = p.nextSibling()) {
if (p.isElement() && p.toElement().tagName() if (p.isElement() && p.toElement().tagName()
== "logo") { == "logo") {
loadLogo(p.toElement()); loadLogo(p.toElement());
@@ -357,8 +357,8 @@ bool TitleBlockTemplate::loadGrid(const QDomElement &xml_element) {
// we parse the first available "grid" XML element // we parse the first available "grid" XML element
QDomElement grid_element; QDomElement grid_element;
for (QDomNode n = xml_element.firstChild() ; for (QDomNode n = xml_element.firstChild() ;
!n.isNull() ; !n.isNull() ;
n = n.nextSibling()) { n = n.nextSibling()) {
if (n.isElement() && n.toElement().tagName() == "grid") { if (n.isElement() && n.toElement().tagName() == "grid") {
grid_element = n.toElement(); grid_element = n.toElement();
break; break;
@@ -430,10 +430,10 @@ void TitleBlockTemplate::parseColumns(const QString &cols_string) {
QRegularExpression abs_col_size_format,rel_col_size_format; QRegularExpression abs_col_size_format,rel_col_size_format;
abs_col_size_format.setPattern("^([0-9]+)(?:px)?$"); abs_col_size_format.setPattern("^([0-9]+)(?:px)?$");
abs_col_size_format.setPatternOptions(QRegularExpression::CaseInsensitiveOption); abs_col_size_format.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
//QRegExp rel_col_size_format("^([rt])([0-9]+)%$", Qt::CaseInsensitive);
rel_col_size_format.setPattern("^([rt])([0-9]+)%$"); rel_col_size_format.setPattern("^([rt])([0-9]+)%$");
rel_col_size_format.setPatternOptions(QRegularExpression::CaseInsensitiveOption); rel_col_size_format.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
bool conv_ok; bool conv_ok;
qDebug() <<"is QRegularExpression ok?";
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) // ### Qt 6: remove #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) // ### Qt 6: remove
QStringList cols_descriptions = QStringList cols_descriptions =
@@ -471,7 +471,7 @@ void TitleBlockTemplate::parseColumns(const QString &cols_string) {
foreach (TitleBlockColDimension icd, columns_width_) { foreach (TitleBlockColDimension icd, columns_width_) {
qDebug() << Q_FUNC_INFO qDebug() << Q_FUNC_INFO
<< QString("%1 [%2]").arg(icd.value).arg( << QString("%1 [%2]").arg(icd.value).arg(
QET::titleBlockColumnLengthToString(icd.type)); QET::titleBlockColumnLengthToString(icd.type));
} }
#endif #endif
} }
@@ -487,8 +487,8 @@ bool TitleBlockTemplate::loadCells(const QDomElement &xml_element) {
// we are interested by the "logo" and "field" elements // we are interested by the "logo" and "field" elements
QDomElement grid_element; QDomElement grid_element;
for (QDomNode n = xml_element.firstChild() ; for (QDomNode n = xml_element.firstChild() ;
!n.isNull() ; !n.isNull() ;
n = n.nextSibling()) { n = n.nextSibling()) {
if (!n.isElement()) continue; if (!n.isElement()) continue;
QDomElement cell_element = n.toElement(); QDomElement cell_element = n.toElement();
if (cell_element.tagName() == "field" if (cell_element.tagName() == "field"
@@ -648,9 +648,9 @@ void TitleBlockTemplate::saveCell(TitleBlockCell *cell,
cell_elmt.setAttribute("row", cell -> num_row); cell_elmt.setAttribute("row", cell -> num_row);
cell_elmt.setAttribute("col", cell -> num_col); cell_elmt.setAttribute("col", cell -> num_col);
if (cell -> row_span) cell_elmt.setAttribute("rowspan", if (cell -> row_span) cell_elmt.setAttribute("rowspan",
cell -> row_span); cell -> row_span);
if (cell -> col_span) cell_elmt.setAttribute("colspan", if (cell -> col_span) cell_elmt.setAttribute("colspan",
cell -> col_span); cell -> col_span);
// save other information // save other information
cell -> saveContentToXml(cell_elmt); cell -> saveContentToXml(cell_elmt);
@@ -1134,8 +1134,8 @@ void TitleBlockTemplate::addColumn(int i) {
@return true @return true
*/ */
bool TitleBlockTemplate::insertColumn(const TitleBlockDimension &dimension, bool TitleBlockTemplate::insertColumn(const TitleBlockDimension &dimension,
const QList<TitleBlockCell *> &column, const QList<TitleBlockCell *> &column,
int i) { int i) {
int index = (i == -1) ? columns_width_.count() : i; int index = (i == -1) ? columns_width_.count() : i;
cells_.insert(index, column); cells_.insert(index, column);
columns_width_.insert(index, dimension); columns_width_.insert(index, dimension);
@@ -1213,11 +1213,11 @@ QSet<TitleBlockCell *> TitleBlockTemplate::spannedCells(
if (!final_row_span && !final_col_span) return(set); if (!final_row_span && !final_col_span) return(set);
for (int i = given_cell -> num_col ; for (int i = given_cell -> num_col ;
i <= given_cell -> num_col + final_col_span ; i <= given_cell -> num_col + final_col_span ;
++ i) { ++ i) {
for (int j = given_cell -> num_row ; for (int j = given_cell -> num_row ;
j <= given_cell -> num_row + final_row_span ; j <= given_cell -> num_row + final_row_span ;
++ j) { ++ j) {
if (i == given_cell -> num_col && j if (i == given_cell -> num_col && j
== given_cell -> num_row) == given_cell -> num_row)
continue; continue;
@@ -1257,7 +1257,7 @@ QHash<TitleBlockCell *, QPair<int, int> > TitleBlockTemplate::getAllSpans(
@param spans : @param spans :
*/ */
void TitleBlockTemplate::setAllSpans(const QHash<TitleBlockCell *, void TitleBlockTemplate::setAllSpans(const QHash<TitleBlockCell *,
QPair<int, int> > &spans) { QPair<int, int> > &spans) {
foreach (TitleBlockCell *cell, spans.keys()) { foreach (TitleBlockCell *cell, spans.keys()) {
cell -> row_span = spans[cell].first; cell -> row_span = spans[cell].first;
cell -> col_span = spans[cell].second; cell -> col_span = spans[cell].second;
@@ -1344,9 +1344,9 @@ bool TitleBlockTemplate::addLogoFromFile(const QString &filepath,
// we then try to add it as a bitmap image // we then try to add it as a bitmap image
return addLogo(filename, return addLogo(filename,
&file_content, &file_content,
filepath_info.suffix(), filepath_info.suffix(),
"base64"); "base64");
} }
/** /**
@@ -1405,7 +1405,7 @@ bool TitleBlockTemplate::removeLogo(const QString &logo_name) {
@return @return
*/ */
bool TitleBlockTemplate::renameLogo(const QString &logo_name, bool TitleBlockTemplate::renameLogo(const QString &logo_name,
const QString &new_name) { const QString &new_name) {
if (!data_logos_.contains(logo_name) if (!data_logos_.contains(logo_name)
|| data_logos_.contains(new_name)) { || data_logos_.contains(new_name)) {
return(false); return(false);
@@ -1531,8 +1531,8 @@ void TitleBlockTemplate::render(QPainter &painter,
// calculate the border rect of the current cell // calculate the border rect of the current cell
int x = lengthRange(0, cells_[i][j] -> num_col, widths); int x = lengthRange(0, cells_[i][j] -> num_col, widths);
int y = lengthRange(0, int y = lengthRange(0,
cells_[i][j] -> num_row, cells_[i][j] -> num_row,
rows_heights_); rows_heights_);
int row_span = 0, col_span = 0; int row_span = 0, col_span = 0;
if (cells_[i][j] -> span_state if (cells_[i][j] -> span_state
@@ -1541,11 +1541,11 @@ void TitleBlockTemplate::render(QPainter &painter,
col_span = cells_[i][j] -> applied_col_span; col_span = cells_[i][j] -> applied_col_span;
} }
int w = lengthRange(cells_[i][j] -> num_col, int w = lengthRange(cells_[i][j] -> num_col,
cells_[i][j] -> num_col + 1 + col_span, cells_[i][j] -> num_col + 1 + col_span,
widths); widths);
int h = lengthRange(cells_[i][j] -> num_row, int h = lengthRange(cells_[i][j] -> num_row,
cells_[i][j] -> num_row + 1 + row_span, cells_[i][j] -> num_row + 1 + row_span,
rows_heights_); rows_heights_);
QRect cell_rect(x, y, w, h); QRect cell_rect(x, y, w, h);
renderCell(painter, *cells_[i][j], renderCell(painter, *cells_[i][j],
@@ -1576,7 +1576,7 @@ void TitleBlockTemplate::renderDxf(QRectF &title_block_rect,
QList<int> widths = columnsWidth(titleblock_width); QList<int> widths = columnsWidth(titleblock_width);
// draw the titleblock border // draw the titleblock border
double xCoord = title_block_rect.topLeft().x()*Createdxf::xScale; double xCoord = title_block_rect.topLeft().x()*Createdxf::xScale;
double yCoord = double yCoord =
Createdxf::sheetHeight Createdxf::sheetHeight
- title_block_rect.bottomLeft().y() - title_block_rect.bottomLeft().y()
@@ -1600,9 +1600,9 @@ void TitleBlockTemplate::renderDxf(QRectF &title_block_rect,
// calculate the border rect of the current cell // calculate the border rect of the current cell
double x = lengthRange(0, cells_[i][j] -> num_col, double x = lengthRange(0, cells_[i][j] -> num_col,
widths); widths);
double y = lengthRange(0, cells_[i][j] -> num_row, double y = lengthRange(0, cells_[i][j] -> num_row,
rows_heights_); rows_heights_);
int row_span = 0, col_span = 0; int row_span = 0, col_span = 0;
if (cells_[i][j] -> span_state if (cells_[i][j] -> span_state
@@ -1611,11 +1611,11 @@ void TitleBlockTemplate::renderDxf(QRectF &title_block_rect,
col_span = cells_[i][j] -> applied_col_span; col_span = cells_[i][j] -> applied_col_span;
} }
double w = lengthRange(cells_[i][j] -> num_col, double w = lengthRange(cells_[i][j] -> num_col,
cells_[i][j] -> num_col + 1 + col_span, cells_[i][j] -> num_col + 1 + col_span,
widths); widths);
double h = lengthRange(cells_[i][j] -> num_row, double h = lengthRange(cells_[i][j] -> num_row,
cells_[i][j] -> num_row + 1 + row_span, cells_[i][j] -> num_row + 1 + row_span,
rows_heights_); rows_heights_);
x = xCoord + x*Createdxf::xScale; x = xCoord + x*Createdxf::xScale;
h *= Createdxf::yScale; h *= Createdxf::yScale;
@@ -1655,9 +1655,9 @@ void TitleBlockTemplate::renderDxf(QRectF &title_block_rect,
Rectangle the cell must be rendered into. Rectangle the cell must be rendered into.
*/ */
void TitleBlockTemplate::renderCell(QPainter &painter, void TitleBlockTemplate::renderCell(QPainter &painter,
const TitleBlockCell &cell, const TitleBlockCell &cell,
const DiagramContext &diagram_context, const DiagramContext &diagram_context,
const QRect &cell_rect) const const QRect &cell_rect) const
{ {
// draw the border rect of the current cell // draw the border rect of the current cell
QPen pen(QBrush(), 0.0, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin); QPen pen(QBrush(), 0.0, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin);
@@ -1819,7 +1819,7 @@ void TitleBlockTemplate::renderTextCell(QPainter &painter,
QRectF new_world_cell_rect(cell_rect); QRectF new_world_cell_rect(cell_rect);
new_world_cell_rect.moveTo(0, 0.0); new_world_cell_rect.moveTo(0, 0.0);
new_world_cell_rect.setWidth(new_world_cell_rect.width() new_world_cell_rect.setWidth(new_world_cell_rect.width()
/ ratio); / ratio);
painter.drawText(new_world_cell_rect, painter.drawText(new_world_cell_rect,
cell.alignment, cell.alignment,
text); text);
@@ -2014,11 +2014,11 @@ bool TitleBlockTemplate::checkCellSpan(TitleBlockCell *cell) {
// ensure cells that will be spanned are either empty or free // ensure cells that will be spanned are either empty or free
for (int i = cell -> num_col ; for (int i = cell -> num_col ;
i <= cell -> num_col + cell -> applied_col_span ; i <= cell -> num_col + cell -> applied_col_span ;
++ i) { ++ i) {
for (int j = cell -> num_row ; for (int j = cell -> num_row ;
j <= cell -> num_row + cell -> applied_row_span ; j <= cell -> num_row + cell -> applied_row_span ;
++ j) { ++ j) {
if (i == cell -> num_col && j == cell -> num_row) if (i == cell -> num_col && j == cell -> num_row)
continue; continue;
#ifdef TITLEBLOCK_TEMPLATE_DEBUG #ifdef TITLEBLOCK_TEMPLATE_DEBUG
@@ -2031,8 +2031,8 @@ bool TitleBlockTemplate::checkCellSpan(TitleBlockCell *cell) {
current_cell -> spanner_cell current_cell -> spanner_cell
&& current_cell -> spanner_cell && current_cell -> spanner_cell
!= cell != cell
) )
) { ) {
cell -> span_state = TitleBlockCell::Disabled; cell -> span_state = TitleBlockCell::Disabled;
return(true); return(true);
} }
@@ -2058,11 +2058,11 @@ void TitleBlockTemplate::applyCellSpan(TitleBlockCell *cell)
// goes through every spanned cell // goes through every spanned cell
for (int i = cell -> num_col ; for (int i = cell -> num_col ;
i <= cell -> num_col + cell -> applied_col_span ; i <= cell -> num_col + cell -> applied_col_span ;
++ i) { ++ i) {
for (int j = cell -> num_row ; for (int j = cell -> num_row ;
j <= cell -> num_row + cell -> applied_row_span ; j <= cell -> num_row + cell -> applied_row_span ;
++ j) { ++ j) {
// avoid the spanning cell itself // avoid the spanning cell itself
if (i == cell -> num_col && j == cell -> num_row) if (i == cell -> num_col && j == cell -> num_row)
continue; continue;

View File

@@ -1,17 +1,17 @@
/* /*
Copyright 2006-2020 The QElectroTech Team Copyright 2006-2020 The QElectroTech Team
This file is part of QElectroTech. This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or the Free Software Foundation, either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
QElectroTech is distributed in the hope that it will be useful, QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>. along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/ */
@@ -49,9 +49,9 @@ DeleteQGraphicsItemCommand::DeleteQGraphicsItemCommand(
{ {
if (m_removed_contents.m_elements.contains(deti->parentElement())) if (m_removed_contents.m_elements.contains(deti->parentElement()))
m_removed_contents.m_element_texts.remove(deti); m_removed_contents.m_element_texts.remove(deti);
} }
//When remove a deti we must to know his parent item, for re-add deti as child of the parent //When remove a deti we must to know his parent item, for re-add deti as child of the parent
//when undo this command //when undo this command
for(DynamicElementTextItem *deti : m_removed_contents.m_element_texts) for(DynamicElementTextItem *deti : m_removed_contents.m_element_texts)
@@ -61,7 +61,7 @@ DeleteQGraphicsItemCommand::DeleteQGraphicsItemCommand(
else else
m_elmt_text_hash.insert(deti, deti->parentElement()); m_elmt_text_hash.insert(deti, deti->parentElement());
} }
//If parent element of ElementTextItemGroup is also in m_removed_content, //If parent element of ElementTextItemGroup is also in m_removed_content,
//we remove it, because when the element will be removed from the scene every child's will also be removed. //we remove it, because when the element will be removed from the scene every child's will also be removed.
const QSet<ElementTextItemGroup *> group_set = m_removed_contents.m_texts_groups; const QSet<ElementTextItemGroup *> group_set = m_removed_contents.m_texts_groups;
@@ -70,12 +70,12 @@ DeleteQGraphicsItemCommand::DeleteQGraphicsItemCommand(
if(m_removed_contents.m_elements.contains(group->parentElement())) if(m_removed_contents.m_elements.contains(group->parentElement()))
m_removed_contents.m_texts_groups.remove(group); m_removed_contents.m_texts_groups.remove(group);
} }
//The deletion of the groups is not managed by this undo, but by a RemoveTextsGroupCommand //The deletion of the groups is not managed by this undo, but by a RemoveTextsGroupCommand
for(ElementTextItemGroup *group : m_removed_contents.m_texts_groups) { for(ElementTextItemGroup *group : m_removed_contents.m_texts_groups) {
new RemoveTextsGroupCommand(group->parentElement(), group, this); new RemoveTextsGroupCommand(group->parentElement(), group, this);
} }
m_removed_contents.m_texts_groups.clear(); m_removed_contents.m_texts_groups.clear();
setPotentialsOfRemovedElements(); setPotentialsOfRemovedElements();
@@ -98,7 +98,7 @@ DeleteQGraphicsItemCommand::DeleteQGraphicsItemCommand(
m_table_scene_hash.insert(current_table, current_table->scene()); m_table_scene_hash.insert(current_table, current_table->scene());
} }
} }
setText(QString(QObject::tr( setText(QString(QObject::tr(
"supprimer %1", "supprimer %1",
"undo caption - %1 is a sentence listing the removed content")) "undo caption - %1 is a sentence listing the removed content"))
@@ -133,17 +133,17 @@ void DeleteQGraphicsItemCommand::setPotentialsOfRemovedElements()
if (terminals_list.isEmpty()) { if (terminals_list.isEmpty()) {
continue; continue;
} }
for (Terminal *t : terminals_list) for (Terminal *t : terminals_list)
{ {
//All new created conductors will be docked to hub_terminal //All new created conductors will be docked to hub_terminal
Terminal *hub_terminal = nullptr; Terminal *hub_terminal = nullptr;
QList<Terminal *> terminals_to_connect_list; QList<Terminal *> terminals_to_connect_list;
for (Conductor *c : t->conductors()) for (Conductor *c : t->conductors())
{ {
Terminal *other_terminal = c->terminal1 == t ? c->terminal2 : c->terminal1; Terminal *other_terminal = c->terminal1 == t ? c->terminal2 : c->terminal1;
if (m_removed_contents.items(DiagramContent::Elements).contains(other_terminal->parentElement())) if (m_removed_contents.items(DiagramContent::Elements).contains(other_terminal->parentElement()))
{ {
other_terminal = terminalInSamePotential(other_terminal, c); other_terminal = terminalInSamePotential(other_terminal, c);
@@ -151,7 +151,7 @@ void DeleteQGraphicsItemCommand::setPotentialsOfRemovedElements()
continue; continue;
} }
} }
terminals_to_connect_list.append(other_terminal); terminals_to_connect_list.append(other_terminal);
if (hub_terminal == nullptr) { if (hub_terminal == nullptr) {
hub_terminal = other_terminal; hub_terminal = other_terminal;
@@ -166,12 +166,12 @@ void DeleteQGraphicsItemCommand::setPotentialsOfRemovedElements()
} }
} }
} }
terminals_to_connect_list.removeAll(hub_terminal); terminals_to_connect_list.removeAll(hub_terminal);
if (hub_terminal == nullptr || terminals_to_connect_list.isEmpty()) { if (hub_terminal == nullptr || terminals_to_connect_list.isEmpty()) {
continue; continue;
} }
ConductorProperties properties = hub_terminal->conductors().first()->properties(); ConductorProperties properties = hub_terminal->conductors().first()->properties();
for (Terminal *t : terminals_to_connect_list) for (Terminal *t : terminals_to_connect_list)
{ {
@@ -188,10 +188,17 @@ void DeleteQGraphicsItemCommand::setPotentialsOfRemovedElements()
continue; continue;
} }
} }
if (exist_ == false) if (exist_ == false)
{ {
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
m_connected_terminals.append(qMakePair<Terminal *, Terminal *>(hub_terminal, t)); m_connected_terminals.append(qMakePair<Terminal *, Terminal *>(hub_terminal, t));
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
qDebug()<<"Help code for QT 6 or later";
#endif
Conductor *new_cond = new Conductor(hub_terminal, t); Conductor *new_cond = new Conductor(hub_terminal, t);
new_cond->setProperties(properties); new_cond->setProperties(properties);
new AddItemCommand<Conductor*>(new_cond, t->diagram(), QPointF(), this); new AddItemCommand<Conductor*>(new_cond, t->diagram(), QPointF(), this);
@@ -210,7 +217,7 @@ void DeleteQGraphicsItemCommand::setPotentialsOfRemovedElements()
Return nullptr if a terminal can't be found. Return nullptr if a terminal can't be found.
@param terminal - terminal from search @param terminal - terminal from search
@param conductor_to_exclude - a conductor to exlcude from search. @param conductor_to_exclude - a conductor to exlcude from search.
@return @return
*/ */
Terminal *DeleteQGraphicsItemCommand::terminalInSamePotential( Terminal *DeleteQGraphicsItemCommand::terminalInSamePotential(
Terminal *terminal, Terminal *terminal,
@@ -234,7 +241,7 @@ Terminal *DeleteQGraphicsItemCommand::terminalInSamePotential(
return terminal_to_return; return terminal_to_return;
} }
} }
return nullptr; return nullptr;
} }
@@ -253,7 +260,7 @@ void DeleteQGraphicsItemCommand::undo()
for(Element *e : m_removed_contents.m_elements) for(Element *e : m_removed_contents.m_elements)
for(Element *elmt : m_link_hash[e]) for(Element *elmt : m_link_hash[e])
e->linkToElement(elmt); e->linkToElement(elmt);
for(DynamicElementTextItem *deti : m_removed_contents.m_element_texts) for(DynamicElementTextItem *deti : m_removed_contents.m_element_texts)
{ {
if(m_elmt_text_hash.keys().contains(deti)) if(m_elmt_text_hash.keys().contains(deti))
@@ -272,7 +279,7 @@ void DeleteQGraphicsItemCommand::undo()
m_table_scene_hash.value(table)->addItem(table); m_table_scene_hash.value(table)->addItem(table);
} }
} }
QUndoCommand::undo(); QUndoCommand::undo();
} }
@@ -298,14 +305,14 @@ void DeleteQGraphicsItemCommand::redo()
conductor_list.first() -> calculateTextItemPosition(); conductor_list.first() -> calculateTextItemPosition();
} }
} }
for(Element *e : m_removed_contents.m_elements) for(Element *e : m_removed_contents.m_elements)
{ {
//Get linked element, for relink it at undo //Get linked element, for relink it at undo
if (!e->linkedElements().isEmpty()) if (!e->linkedElements().isEmpty())
m_link_hash.insert(e, e->linkedElements()); m_link_hash.insert(e, e->linkedElements());
} }
for(DynamicElementTextItem *deti : m_removed_contents.m_element_texts) for(DynamicElementTextItem *deti : m_removed_contents.m_element_texts)
{ {
if(deti->parentGroup() && deti->parentGroup()->parentElement()) if(deti->parentGroup() && deti->parentGroup()->parentElement())
@@ -321,9 +328,9 @@ void DeleteQGraphicsItemCommand::redo()
m_table_scene_hash.value(table)->removeItem(table); m_table_scene_hash.value(table)->removeItem(table);
} }
} }
for(QGraphicsItem *item : m_removed_contents.items()) for(QGraphicsItem *item : m_removed_contents.items())
m_diagram->removeItem(item); m_diagram->removeItem(item);
QUndoCommand::redo(); QUndoCommand::redo();
} }

View File

@@ -285,6 +285,10 @@ void LinkElementCommand::makeLink(const QList<Element *> &element_list)
//All elements stored in to_unlink is unwanted we unlink it from m_element //All elements stored in to_unlink is unwanted we unlink it from m_element
if (!to_unlink.isEmpty()) if (!to_unlink.isEmpty())
{
foreach(Element *elmt, to_unlink) foreach(Element *elmt, to_unlink)
{
m_element->unlinkElement(elmt); m_element->unlinkElement(elmt);
}
}
} }