Element files: anchor="alignment" puts a static text's x at its alignment (#1251)

A static text's x/y in an .elmt file are the baseline-left of the text.
A program writing an element (a pinout generator, dxf2elmt) then has to
measure the text with QET's font metrics to right-align or centre it.

With the opt-in anchor="alignment", x is the left edge, centre or right
edge selected by Halignment; y stays the baseline. The box is the text
without the document margin, as ElementPictureFactory draws it, so the
editor and the folio agree. Rotation pivots on x/y as before.

The element editor reads it and writes it back for the texts that had
it; it does not add it to other texts. Files without anchor draw and
save as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ispyisail
2026-10-09 16:31:16 +13:00
parent bdeef6d306
commit 1db025ceae
6 changed files with 199 additions and 7 deletions
+29 -2
View File
@@ -164,6 +164,10 @@ void PartText::fromXml(const QDomElement &xml_element) {
setPos(xml_element.attribute("x").toDouble(),
xml_element.attribute("y").toDouble());
QGraphicsObject::setRotation(QET::correctAngle(xml_element.attribute("rotation", QString::number(0)).toDouble()));
m_anchor_to_alignment = xml_element.attribute("anchor") == QLatin1String("alignment");
if (m_anchor_to_alignment)
setPos(pos() - anchorOffset());
}
/**
@@ -175,8 +179,10 @@ const QDomElement PartText::toXml(QDomDocument &xml_document) const
{
QDomElement xml_element = xml_document.createElement(xmlName());
qreal x = (qRound(pos().x() * 100.0) / 100.0);
qreal y = (qRound(pos().y() * 100.0) / 100.0);
const QPointF anchor = m_anchor_to_alignment ? pos() + anchorOffset()
: pos();
qreal x = (qRound(anchor.x() * 100.0) / 100.0);
qreal y = (qRound(anchor.y() * 100.0) / 100.0);
qreal rot = (qRound(rotation() * 10.0) / 10.0);
xml_element.setAttribute("x", QString::number(x));
xml_element.setAttribute("y", QString::number(y));
@@ -197,6 +203,8 @@ const QDomElement PartText::toXml(QDomDocument &xml_document) const
xml_element.setAttribute("Valignment", me.valueToKey(Qt::AlignBottom));
else if (m_alignment & Qt::AlignVCenter)
xml_element.setAttribute("Valignment", me.valueToKey(Qt::AlignVCenter));
if (m_anchor_to_alignment)
xml_element.setAttribute("anchor", "alignment");
return(xml_element);
}
@@ -444,6 +452,25 @@ void PartText::finishAlignment()
setPos(pos() - (pa - p));
}
/**
@brief PartText::anchorOffset
@return the vector from the baseline-left of the text to the point
written as x/y with anchor="alignment" (#1251): the left edge, centre or
right edge of the text, without the document margin, on the baseline.
Same width as ElementPictureFactory::parseText, which draws without
a margin.
*/
QPointF PartText::anchorOffset() const
{
qreal width = document()->idealWidth() - 2 * document()->documentMargin();
qreal dx = 0;
if (m_alignment & Qt::AlignRight)
dx = width;
else if (m_alignment & Qt::AlignHCenter)
dx = width / 2;
return QTransform().rotate(rotation()).map(QPointF(dx, 0));
}
void PartText::setFont(const QFont &font) {
if (font != this -> font()) {
prepareAlignment();
+4
View File
@@ -109,6 +109,7 @@ class PartText : public QGraphicsTextItem, public CustomElementPart {
void applyLineAlignment();
void prepareAlignment();
void finishAlignment();
QPointF anchorOffset() const;
QString previous_text;
qreal real_font_size_;
QPointF saved_point_;
@@ -117,5 +118,8 @@ class PartText : public QGraphicsTextItem, public CustomElementPart {
QPointF m_origin_pos;
Qt::Alignment m_alignment = (Qt::AlignTop | Qt::AlignLeft);
QRectF m_alignment_rect;
/// x/y in the .elmt are the aligned point, not the
/// baseline-left (anchor="alignment", #1251)
bool m_anchor_to_alignment = false;
};
#endif
+12 -5
View File
@@ -704,10 +704,11 @@ void ElementPictureFactory::parseText(const QDomElement &dom, QPainter &painter,
//adjusts the offset by the margin of the text document
text_document.setDocumentMargin(0.0);
//Optional line alignment of multi-line texts (the anchor behaviour
//of the alignment is handled in the element editor; the saved x/y
//always stay the baseline-left of the text block). The document
//only honors the text option once a text width is set.
//Optional line alignment of multi-line texts. The document only
//honors the text option once a text width is set.
//x/y are the baseline-left of the text block, unless
//anchor="alignment": x is then the left edge, centre or right edge
//selected by Halignment, and y stays the baseline (#1251).
if (dom.hasAttribute("Halignment")) {
const QMetaEnum me = QMetaEnum::fromType<Qt::Alignment>();
const Qt::Alignment h_alignment = Qt::Alignment(
@@ -717,12 +718,18 @@ void ElementPictureFactory::parseText(const QDomElement &dom, QPainter &painter,
option.setAlignment(h_alignment & Qt::AlignHorizontal_Mask);
text_document.setDefaultTextOption(option);
text_document.setTextWidth(text_document.idealWidth());
if (dom.attribute("anchor") == QLatin1String("alignment"))
qpainter_offset.rx() -= h_alignment & Qt::AlignRight
? text_document.idealWidth()
: text_document.idealWidth() / 2;
}
}
QTransform text_transform;
text_transform.translate(dom.attribute("x").toDouble(), dom.attribute("y").toDouble());
text_transform.rotate(dom.attribute("rotation", "0").toDouble());
//baseline-left of the text block, for the dxf export below
const QPointF baseline_left = text_transform.map(QPointF(qpainter_offset.x(), 0));
text_transform.translate(qpainter_offset.x(), qpainter_offset.y());
if (!m_build_texts_undo.isIdentity())
@@ -748,7 +755,7 @@ void ElementPictureFactory::parseText(const QDomElement &dom, QPainter &painter,
QGraphicsSimpleTextItem *qgsti = new QGraphicsSimpleTextItem();
qgsti->setText(dom.attribute("text"));
qgsti->setFont(font_);
qgsti->setPos(dom.attribute("x").toDouble(), dom.attribute("y").toDouble());
qgsti->setPos(baseline_left);
qgsti->setRotation(dom.attribute("rotation", "0").toDouble());
prim.m_texts << qgsti;
+11
View File
@@ -619,6 +619,17 @@ target_link_libraries(tst_dxfcurves PRIVATE Qt::Test)
target_compile_definitions(tst_dxfcurves PRIVATE
"QET_TEST_BINARY_PATH=\"$<TARGET_FILE:qelectrotech>\"")
# A static text with anchor="alignment" has its x at the edge or centre its
# Halignment selects, not at its left edge (#1251).
add_executable(
tst_statictextanchor
tst_statictextanchor.cpp)
add_test(NAME tst_statictextanchor COMMAND tst_statictextanchor)
add_dependencies(tst_statictextanchor qelectrotech)
target_link_libraries(tst_statictextanchor PRIVATE Qt::Test)
target_compile_definitions(tst_statictextanchor PRIVATE
"QET_TEST_BINARY_PATH=\"$<TARGET_FILE:qelectrotech>\"")
# --export-dxf --dxf-blocks: a symbol placed twice is one BLOCK and two
# INSERTs (issue #1339).
add_executable(
@@ -0,0 +1,59 @@
<project title="Anchored static texts" uuid="{6c1a2b3d-1251-4c1e-9e57-3f0d0f0a7b10}" version="0.200.1">
<properties>
<property name="saveddate" show="1">10/2/26</property>
<property name="saveddate-eu" show="1">02-10-2026</property>
<property name="saveddate-us" show="1">2026-10-02</property>
<property name="savedfilename" show="1">static_text_anchor</property>
<property name="savedtime" show="1">18:39</property>
</properties>
<usage enabled="true" time_spent="0"/>
<newdiagrams>
<border cols="17" colsize="60" displaycols="true" displayrows="true" rows="8" rowsize="80"/>
<inset author="" auto_page_num="" date="null" displayAt="bottom" filename="" folio="" indexrev="" locmach="" plant="" title="" version=""/>
<conductors bicolor="false" bus="" cable="" color2="#000000" condsize="1" conductor_color="" conductor_section="" dash-size="1" displaytext="1" formula="" function="" horizontal-alignment="AlignBottom" horizrotatetext="0" num="_" numsize="7" onetextperfolio="0" tension_protocol="" text_color="#000000" type="multi" vertical-alignment="AlignRight" vertirotatetext="270"/>
<report label="%f-%l%c"/>
<xrefs>
<xref delayprefix="" displayhas="cross" master_label="%f-%l%c" offset="0" powerprefix="" showallconfiguredslaves="false" showpowerctc="true" showterminalname="true" slave_label="(%f-%l%c)" slave_offset="0" snapto="label" switchprefix="" type="coil" xrefpos="AlignBottom"/>
<xref delayprefix="" displayhas="cross" master_label="%f-%l%c" offset="0" powerprefix="" showallconfiguredslaves="false" showpowerctc="true" showterminalname="true" slave_label="(%f-%l%c)" slave_offset="0" snapto="label" switchprefix="" type="commutator" xrefpos="AlignBottom"/>
<xref delayprefix="" displayhas="cross" master_label="%f-%l%c" offset="0" powerprefix="" showallconfiguredslaves="false" showpowerctc="true" showterminalname="true" slave_label="(%f-%l%c)" slave_offset="0" snapto="label" switchprefix="" type="plc" xrefpos="AlignBottom"/>
<xref delayprefix="" displayhas="cross" master_label="%f-%l%c" offset="0" powerprefix="" showallconfiguredslaves="false" showpowerctc="true" showterminalname="true" slave_label="(%f-%l%c)" slave_offset="0" snapto="label" switchprefix="" type="protection" xrefpos="AlignBottom"/>
</xrefs>
<conductors_autonums auto_break_conductors="false" current_autonum="" freeze_new_conductors="false"/>
<folio_autonums/>
<element_autonums current_autonum="" freeze_new_elements="false"/>
<guides/>
</newdiagrams>
<diagram author="" auto_page_num="" cols="17" colsize="60" date="null" displayAt="bottom" displaycols="true" displayrows="true" filename="" folio="" freezeNewConductor="false" freezeNewElement="false" height="660" indexrev="" locmach="" order="1" plant="" rows="8" rowsize="80" title="" uuid="{6c1a2b3d-1251-4c1e-9e57-3f0d0f0a7a01}" version="0.200.1-dev">
<elements>
<element freezeLabel="false" is_movable="1" orientation="0" prefix="" type="embed://import/anchor.elmt" uuid="{6c1a2b3d-1251-4c1e-9e57-3f0d0f0a7a02}" x="300" y="300" z="10">
<terminals/>
<inputs/>
<dynamic_texts/>
<texts_groups/>
</element>
</elements>
</diagram>
<collection>
<category name="import">
<names>
<name lang="en">Imported elements</name>
</names>
<element name="anchor.elmt">
<definition height="80" hotspot_x="100" hotspot_y="10" link_type="simple" type="element" version="0.100.0" width="200">
<uuid uuid="{6c1a2b3d-1251-4c1e-9e57-3f0d0f0a7a05}"/>
<names>
<name lang="en">Anchored static texts</name>
</names>
<description>
<line antialias="false" end1="none" end2="none" length1="1.5" length2="1.5" style="line-style:normal;line-weight:normal;filling:none;color:black" x1="0" x2="0" y1="0" y2="60"/>
<text text="GPIO21 PCM_DOUT" x="0" y="10" font="Liberation Sans,9,-1,5,50,0,0,0,0,0,Regular" color="#000000" rotation="0"/>
<text text="GPIO21 PCM_DOUT" x="0" y="20" Halignment="AlignRight" anchor="alignment" font="Liberation Sans,9,-1,5,50,0,0,0,0,0,Regular" color="#000000" rotation="0"/>
<text text="GPIO21 PCM_DOUT" x="0" y="30" Halignment="AlignHCenter" anchor="alignment" font="Liberation Sans,9,-1,5,50,0,0,0,0,0,Regular" color="#000000" rotation="0"/>
<text text="GPIO21 PCM_DOUT" x="0" y="40" Halignment="AlignRight" font="Liberation Sans,9,-1,5,50,0,0,0,0,0,Regular" color="#000000" rotation="0"/>
<text text="GPIO21 PCM_DOUT" x="0" y="50" anchor="alignment" font="Liberation Sans,9,-1,5,50,0,0,0,0,0,Regular" color="#000000" rotation="0"/>
</description>
</definition>
</element>
</category>
</collection>
</project>
+84
View File
@@ -0,0 +1,84 @@
/*
Copyright 2006-2026 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QtTest>
#include <QProcess>
#include <QTemporaryDir>
/**
A static text with anchor="alignment" has its x at the edge or centre
its Halignment selects, instead of its left edge (#1251). The symbol in
fixtures/static_text_anchor.qet has the same text five times, all at
x = 0: left, right and centre anchored, right aligned without anchor,
and anchored without Halignment. --export-dxf writes where each is drawn.
*/
class tst_statictextanchor : public QObject
{
Q_OBJECT
private slots:
void anchoredX()
{
const QString project = QFINDTESTDATA("fixtures/static_text_anchor.qet");
QVERIFY2(!project.isEmpty(), "fixture project not found");
QTemporaryDir dir;
QVERIFY(dir.isValid());
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
env.insert(QStringLiteral("QT_QPA_PLATFORM"), QStringLiteral("offscreen"));
QProcess proc;
proc.setProcessEnvironment(env);
proc.start(QStringLiteral(QET_TEST_BINARY_PATH), {QStringLiteral("--export-dxf"), project, dir.path()});
QVERIFY2(proc.waitForFinished(60000), "--export-dxf timed out");
QCOMPARE(proc.exitCode(), 0);
QFile file(dir.filePath(QStringLiteral("01_diagram.dxf")));
QVERIFY(file.open(QIODevice::ReadOnly | QIODevice::Text));
const QStringList values = QString::fromUtf8(file.readAll()).split(QLatin1Char('\n'));
//x (group code 10) of each TEXT entity of the symbol, in order
QList<qreal> xs;
for (int i = 0 ; i + 1 < values.size() ; i += 2) {
if (values.at(i).trimmed() != QLatin1String("0") || values.at(i + 1).trimmed() != QLatin1String("TEXT"))
continue;
qreal x = 0;
QString text;
for (int j = i + 2 ; j + 1 < values.size() && values.at(j).trimmed() != QLatin1String("0") ; j += 2) {
if (values.at(j).trimmed() == QLatin1String("10"))
x = values.at(j + 1).trimmed().toDouble();
else if (values.at(j).trimmed() == QLatin1String("1"))
text = values.at(j + 1).trimmed();
}
if (text == QLatin1String("GPIO21 PCM_DOUT"))
xs << x;
}
QCOMPARE(xs.size(), 5);
const qreal left = xs.at(0), right = xs.at(1), centre = xs.at(2);
//anchored on the right edge: drawn one text width to the left
QVERIFY2(left - right > 20, qPrintable(QStringLiteral("left %1 right %2").arg(left).arg(right)));
//anchored on the centre: half as far
QVERIFY(qAbs(2 * (left - centre) - (left - right)) < 0.01);
//without anchor, x stays the left edge whatever the alignment
QCOMPARE(xs.at(3), left);
//anchor without Halignment is the left edge too
QCOMPARE(xs.at(4), left);
}
};
QTEST_APPLESS_MAIN(tst_statictextanchor)
#include "tst_statictextanchor.moc"