7#include <QtWidgets/qwidget.h>
8#include <QtWidgets/qapplication.h>
9#include <QtCore/qstack.h>
12#include <QtCore/qfile.h>
19using namespace Qt::StringLiterals;
27const qreal g_offset = (
sizeof(qreal) ==
sizeof(
double)) ? QWIDGETSIZE_MAX : QWIDGETSIZE_MAX / 32;
31 sizePolicy(QSizePolicy::Fixed), preferredSize(0),
41 data->graphicsAnchor =
nullptr;
49 if (sizePolicy != policy) {
58 qWarning(
"QGraphicsAnchor::setSpacing: The anchor does not exist.");
62 if (hasSize && (preferredSize == value))
67 preferredSize = value;
75 qWarning(
"QGraphicsAnchor::setSpacing: The anchor does not exist.");
88 qWarning(
"QGraphicsAnchor::setSpacing: The anchor does not exist.");
97 qreal minSizeHint, qreal prefSizeHint, qreal maxSizeHint,
98 qreal *minSize, qreal *prefSize,
114 if (policy & QSizePolicy::ShrinkFlag)
115 *minSize = minSizeHint;
117 *minSize = prefSizeHint;
119 if (policy & QSizePolicy::GrowFlag)
120 *maxSize = maxSizeHint;
122 *maxSize = prefSizeHint;
125 if (policy & QSizePolicy::IgnoreFlag)
126 *prefSize = *minSize;
128 *prefSize = prefSizeHint;
133 if (graphicsAnchor) {
136 QGraphicsAnchorPrivate::get(graphicsAnchor)->data =
nullptr;
138 delete graphicsAnchor;
145 QSizePolicy::Policy policy;
152 if (isLayoutAnchor) {
155 maxSize = QWIDGETSIZE_MAX;
159 minPrefSize = prefSize;
160 maxPrefSize = maxSize;
164 policy =
item->sizePolicy().horizontalPolicy();
165 minSizeHint =
item->effectiveSizeHint(Qt::MinimumSize).width();
166 prefSizeHint =
item->effectiveSizeHint(Qt::PreferredSize).width();
167 maxSizeHint =
item->effectiveSizeHint(Qt::MaximumSize).width();
169 policy =
item->sizePolicy().verticalPolicy();
170 minSizeHint =
item->effectiveSizeHint(Qt::MinimumSize).height();
171 prefSizeHint =
item->effectiveSizeHint(Qt::PreferredSize).height();
172 maxSizeHint =
item->effectiveSizeHint(Qt::MaximumSize).height();
175 if (isCenterAnchor) {
183 Q_ASSERT(graphicsAnchor);
187 policy = anchorPrivate->sizePolicy;
189 maxSizeHint = QWIDGETSIZE_MAX;
192 if (anchorPrivate->hasSize) {
194 prefSizeHint = anchorPrivate->preferredSize;
195 }
else if (styleInfo) {
197 const Qt::Orientation orient = QGraphicsAnchorLayoutPrivate::edgeOrientation(from->m_edge);
198 qreal s = styleInfo->defaultSpacing(orient);
200 QSizePolicy::ControlType controlTypeFrom =
from->m_item->sizePolicy().controlType();
201 QSizePolicy::ControlType controlTypeTo =
to->m_item->sizePolicy().controlType();
202 s = styleInfo->perItemSpacing(controlTypeFrom, controlTypeTo, orient);
217 applySizePolicy(policy, minSizeHint, prefSizeHint, maxSizeHint,
218 &minSize, &prefSize, &maxSize);
220 minPrefSize = prefSize;
221 maxPrefSize = maxSize;
230 sizeAtMinimum = prefSize;
231 sizeAtPreferred = prefSize;
232 sizeAtMaximum = prefSize;
237 firstEdge->sizeAtMinimum = sizeAtMinimum;
238 firstEdge->sizeAtPreferred = sizeAtPreferred;
239 firstEdge->sizeAtMaximum = sizeAtMaximum;
243 secondEdge->sizeAtPreferred = sizeAtPreferred;
247 secondEdge->sizeAtPreferred = -sizeAtPreferred;
256
257
258
259
260
261
262
263
264
290 minSize = qMax(firstEdge->minSize, secondMin);
291 maxSize = qMin(firstEdge->maxSize, secondMax);
296 if (minSize > maxSize) {
330 prefSize = qBound(minSize, secondPref, maxSize);
331 minPrefSize = qBound(minSize, secondMinPref, maxSize);
332 maxPrefSize = qBound(minSize, secondMaxPref, maxSize);
334 prefSize = qBound(minSize, firstEdge->prefSize, maxSize);
335 minPrefSize = qBound(minSize, firstEdge->minPrefSize, maxSize);
336 maxPrefSize = qBound(minSize, firstEdge->maxPrefSize, maxSize);
339 const qreal lowerBoundary =
340 qBound(minSize, qMax(
firstEdge->minPrefSize, secondMinPref), maxSize);
341 const qreal upperBoundary =
342 qBound(minSize, qMin(
firstEdge->maxPrefSize, secondMaxPref), maxSize);
343 const qreal prefMean =
344 qBound(minSize, (
firstEdge->prefSize + secondPref) / 2, maxSize);
346 if (lowerBoundary < upperBoundary) {
351 prefSize = qBound(lowerBoundary, prefMean, upperBoundary);
352 minPrefSize = lowerBoundary;
353 maxPrefSize = upperBoundary;
361 prefSize = qBound(upperBoundary, prefMean, lowerBoundary);
362 minPrefSize = upperBoundary;
363 maxPrefSize = lowerBoundary;
368 sizeAtMinimum = prefSize;
369 sizeAtPreferred = prefSize;
370 sizeAtMaximum = prefSize;
376
377
378
379
380
381
383 qreal minPref, qreal pref,
384 qreal maxPref, qreal max)
386 QGraphicsAnchorLayoutPrivate::Interval interval;
390 if (value < minPref) {
391 interval = QGraphicsAnchorLayoutPrivate::MinimumToMinPreferred;
394 }
else if (value < pref) {
395 interval = QGraphicsAnchorLayoutPrivate::MinPreferredToPreferred;
398 }
else if (value < maxPref) {
399 interval = QGraphicsAnchorLayoutPrivate::PreferredToMaxPreferred;
403 interval = QGraphicsAnchorLayoutPrivate::MaxPreferredToMaximum;
409 if (upper == lower) {
412 progress = (value - lower) / (upper - lower);
415 return std::pair(interval, progress);
418static qreal interpolate(
const std::pair<QGraphicsAnchorLayoutPrivate::Interval, qreal> &factor,
419 qreal min, qreal minPref, qreal pref, qreal maxPref, qreal max)
424 switch (factor.first) {
425 case QGraphicsAnchorLayoutPrivate::MinimumToMinPreferred:
429 case QGraphicsAnchorLayoutPrivate::MinPreferredToPreferred:
433 case QGraphicsAnchorLayoutPrivate::PreferredToMaxPreferred:
437 case QGraphicsAnchorLayoutPrivate::MaxPreferredToMaximum:
443 return lower + factor.second * (upper - lower);
451 const std::pair<QGraphicsAnchorLayoutPrivate::Interval, qreal> minFactor =
452 getFactor(sizeAtMinimum, minSize, minPrefSize, prefSize, maxPrefSize, maxSize);
453 const std::pair<QGraphicsAnchorLayoutPrivate::Interval, qreal> prefFactor =
454 getFactor(sizeAtPreferred, minSize, minPrefSize, prefSize, maxPrefSize, maxSize);
455 const std::pair<QGraphicsAnchorLayoutPrivate::Interval, qreal> maxFactor =
456 getFactor(sizeAtMaximum, minSize, minPrefSize, prefSize, maxPrefSize, maxSize);
463 for (AnchorData *e : m_edges) {
464 const bool edgeIsForward = (e->from == prev);
466 e->sizeAtMinimum = interpolate(minFactor, e->minSize, e->minPrefSize,
467 e->prefSize, e->maxPrefSize, e->maxSize);
468 e->sizeAtPreferred = interpolate(prefFactor, e->minSize, e->minPrefSize,
469 e->prefSize, e->maxPrefSize, e->maxSize);
470 e->sizeAtMaximum = interpolate(maxFactor, e->minSize, e->minPrefSize,
471 e->prefSize, e->maxPrefSize, e->maxSize);
474 Q_ASSERT(prev == e->to);
475 e->sizeAtMinimum = interpolate(minFactor, e->maxSize, e->maxPrefSize,
476 e->prefSize, e->minPrefSize, e->minSize);
477 e->sizeAtPreferred = interpolate(prefFactor, e->maxSize, e->maxPrefSize,
478 e->prefSize, e->minPrefSize, e->minSize);
479 e->sizeAtMaximum = interpolate(maxFactor, e->maxSize, e->maxPrefSize,
480 e->prefSize, e->minPrefSize, e->minSize);
484 e->updateChildrenSizes();
498 for (AnchorData *edge : m_edges) {
499 const bool edgeIsForward = (edge->from == prev);
501 minSize += edge->minSize;
502 prefSize += edge->prefSize;
503 maxSize += edge->maxSize;
504 minPrefSize += edge->minPrefSize;
505 maxPrefSize += edge->maxPrefSize;
508 Q_ASSERT(prev == edge->to);
509 minSize -= edge->maxSize;
510 prefSize -= edge->prefSize;
511 maxSize -= edge->minSize;
512 minPrefSize -= edge->maxPrefSize;
513 maxPrefSize -= edge->minPrefSize;
519 sizeAtMinimum = prefSize;
520 sizeAtPreferred = prefSize;
521 sizeAtMaximum = prefSize;
525void AnchorData::dump(
int indent) {
526 if (type == Parallel) {
527 qDebug(
"%*s type: parallel:", indent,
"");
528 ParallelAnchorData *p =
static_cast<ParallelAnchorData *>(
this);
529 p->firstEdge->dump(indent+2);
530 p->secondEdge->dump(indent+2);
531 }
else if (type == Sequential) {
532 const auto *s =
static_cast<SequentialAnchorData *>(
this);
533 qDebug(
"%*s type: sequential(%lld):", indent,
"", qint64(s->m_edges.size()));
534 for (AnchorData *e : s->m_edges)
537 qDebug(
"%*s type: Normal:", indent,
"");
546 QSet<AnchorData *> cPositives;
547 QSet<AnchorData *> cNegatives;
548 QSet<AnchorData *> intersection;
550 cPositives = positives + path.negatives;
551 cNegatives = negatives + path.positives;
553 intersection = cPositives & cNegatives;
555 cPositives -= intersection;
556 cNegatives -= intersection;
560 for (AnchorData *ad : std::as_const(cPositives))
561 c->variables.insert(ad, 1.0);
563 for (AnchorData *ad : std::as_const(cNegatives))
564 c->variables.insert(ad, -1.0);
570QString GraphPath::toString()
const
573 string +=
"Path: "_L1;
575 for (AnchorData *edge : positives)
576 string += QString::fromLatin1(
" (+++) %1").arg(edge->toString());
578 for (AnchorData *edge : negatives)
579 string += QString::fromLatin1(
" (---) %1").arg(edge->toString());
585QGraphicsAnchorLayoutPrivate::QGraphicsAnchorLayoutPrivate()
586 : calculateGraphCacheDirty(
true), styleInfoDirty(
true)
590Qt::AnchorPoint QGraphicsAnchorLayoutPrivate::oppositeEdge(Qt::AnchorPoint edge)
594 edge = Qt::AnchorRight;
596 case Qt::AnchorRight:
597 edge = Qt::AnchorLeft;
600 edge = Qt::AnchorBottom;
602 case Qt::AnchorBottom:
603 edge = Qt::AnchorTop;
613
614
615
616
617
618
619
620
621
622
623
624
625AnchorData *QGraphicsAnchorLayoutPrivate::addAnchorMaybeParallel(AnchorData *newAnchor,
bool *feasible)
627 const Qt::Orientation orientation = newAnchor->isVertical ? Qt::Vertical : Qt::Horizontal;
628 Graph<AnchorVertex, AnchorData> &g = graph[orientation];
633 if (AnchorData *oldAnchor = g.takeEdge(newAnchor->from, newAnchor->to)) {
634 ParallelAnchorData *parallel =
new ParallelAnchorData(oldAnchor, newAnchor);
641 QList<QSimplexConstraint *> &constraints = itemCenterConstraints[orientation];
642 const std::array<AnchorData *, 2> children = { oldAnchor, newAnchor };
643 const std::array<QList<QSimplexConstraint *> *, 2> childrenConstraints = {
644 ¶llel->m_firstConstraints, ¶llel->m_secondConstraints
647 for (
int i = 0; i < 2; ++i) {
648 AnchorData *child = children[i];
649 QList<QSimplexConstraint *> *childConstraints = childrenConstraints[i];
656 const bool needsReverse = i == 1 && !parallel->secondForward();
658 if (!child->isCenterAnchor)
661 parallel->isCenterAnchor =
true;
663 for (QSimplexConstraint *c : constraints) {
664 if (c->variables.contains(child)) {
665 childConstraints->append(c);
666 qreal v = c->variables.take(child);
669 c->variables.insert(parallel, v);
676 *feasible = parallel->calculateSizeHints();
677 newAnchor = parallel;
680 g.createEdge(newAnchor->from, newAnchor->to, newAnchor);
685
686
687
688
689
690
691
692
693
695 const QList<AnchorVertex *> &vertices,
AnchorVertex *after)
697#if defined(QT_DEBUG) && 0
699 for (
const AnchorVertex *vertex : vertices)
700 strVertices += QString::fromLatin1(
"%1 - ").arg(vertex->toString());
701 QString strPath = QString::fromLatin1(
"%1 - %2%3").arg(before->toString(), strVertices, after->toString());
702 qDebug(
"simplifying [%s] to [%s - %s]", qPrintable(strPath), qPrintable(before->toString()), qPrintable(after->toString()));
706 QList<AnchorData *> edges;
707 edges.reserve(vertices.size() + 1);
710 for (AnchorVertex *next : vertices) {
711 AnchorData *ad = graph->takeEdge(prev, next);
718 AnchorData *ad = graph->takeEdge(vertices.last(), after);
724 sequence->from = before;
725 sequence->to = after;
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769bool QGraphicsAnchorLayoutPrivate::simplifyGraph(Qt::Orientation orientation)
774#if defined(QT_DEBUG) && 0
775 qDebug(
"Simplifying Graph for %s",
776 orientation == Horizontal ?
"Horizontal" :
"Vertical");
778 static int count = 0;
779 if (orientation == Horizontal) {
781 dumpGraph(QString::fromLatin1(
"%1-full").arg(count));
786 if (!simplifyVertices(orientation)) {
787 restoreVertices(orientation);
793 bool feasible =
true;
795 dirty = simplifyGraphIteration(orientation, &feasible);
796 }
while (dirty && feasible);
800 restoreSimplifiedGraph(orientation);
801 restoreVertices(orientation);
805#if defined(QT_DEBUG) && 0
806 dumpGraph(QString::fromLatin1(
"%1-simplified-%2").arg(count).arg(
807 QString::fromLatin1(orientation == Horizontal ?
"Horizontal" :
"Vertical")));
826bool QGraphicsAnchorLayoutPrivate::replaceVertex(Qt::Orientation orientation, AnchorVertex *oldV,
827 AnchorVertex *newV,
const QList<AnchorData *> &edges)
829 Graph<AnchorVertex, AnchorData> &g = graph[orientation];
830 bool feasible =
true;
832 for (AnchorData *ad : edges) {
833 AnchorVertex *otherV = replaceVertex_helper(ad, oldV, newV);
836 ad->name = QString::fromLatin1(
"%1 --to--> %2").arg(ad->from->toString(), ad->to->toString());
840 AnchorData *newAnchor = addAnchorMaybeParallel(ad, &newFeasible);
841 feasible &= newFeasible;
843 if (newAnchor != ad) {
847 anchorsFromSimplifiedVertices[orientation].append(newAnchor);
850 g.takeEdge(oldV, otherV);
857
858
859bool QGraphicsAnchorLayoutPrivate::simplifyVertices(Qt::Orientation orientation)
861 Q_Q(QGraphicsAnchorLayout);
862 Graph<AnchorVertex, AnchorData> &g = graph[orientation];
865 QStack<AnchorVertex *> stack;
866 stack.push(layoutFirstVertex[orientation]);
867 QSet<AnchorVertex *> visited;
869 while (!stack.isEmpty()) {
870 AnchorVertex *v = stack.pop();
876 QList<AnchorVertex *> adjacents = g.adjacentVertices(v);
879 while (index < adjacents.size()) {
880 AnchorVertex *next = adjacents.at(index);
883 AnchorData *data = g.edgeData(v, next);
884 const bool bothLayoutVertices = v->m_item == q && next->m_item == q;
885 const bool zeroSized = !data->minSize && !data->maxSize;
887 if (!bothLayoutVertices && zeroSized) {
891 AnchorVertexPair *newV =
new AnchorVertexPair(v, next, data);
892 simplifiedVertices[orientation].append(newV);
896 const QList<AnchorVertex *> &vAdjacents = g.adjacentVertices(v);
897 const QList<AnchorVertex *> &nextAdjacents = g.adjacentVertices(next);
899 for (AnchorVertex *adjacent : vAdjacents) {
900 if (adjacent != next) {
901 AnchorData *ad = g.edgeData(v, adjacent);
902 newV->m_firstAnchors.append(ad);
906 for (AnchorVertex *adjacent : nextAdjacents) {
908 AnchorData *ad = g.edgeData(next, adjacent);
909 newV->m_secondAnchors.append(ad);
913 if (!adjacents.contains(adjacent))
914 adjacents.append(adjacent);
920 bool feasible = replaceVertex(orientation, v, newV, newV->m_firstAnchors);
921 feasible &= replaceVertex(orientation, next, newV, newV->m_secondAnchors);
924 AnchorVertex *layoutVertex =
nullptr;
927 else if (next->m_item == q)
933 changeLayoutVertex(orientation, layoutVertex, newV);
943 visited.insert(newV);
945 }
else if (!visited.contains(next) && !stack.contains(next)) {
957
958
959
960
961
962
963
964
965
966
967
968
969
970bool QGraphicsAnchorLayoutPrivate::simplifyGraphIteration(Qt::Orientation orientation,
973 Q_Q(QGraphicsAnchorLayout);
974 Graph<AnchorVertex, AnchorData> &g = graph[orientation];
976 QSet<AnchorVertex *> visited;
977 QStack<std::pair<AnchorVertex *, AnchorVertex *> > stack;
978 stack.push(std::pair(
static_cast<AnchorVertex *>(
nullptr), layoutFirstVertex[orientation]));
979 QList<AnchorVertex *> candidates;
983 while (!stack.isEmpty()) {
984 std::pair<AnchorVertex *, AnchorVertex *> pair = stack.pop();
985 AnchorVertex *beforeSequence = pair.first;
986 AnchorVertex *v = pair.second;
998 const QList<AnchorVertex *> &adjacents = g.adjacentVertices(v);
999 const bool isLayoutVertex = v->m_item == q;
1000 AnchorVertex *afterSequence = v;
1001 bool endOfSequence =
false;
1008 endOfSequence = isLayoutVertex || adjacents.size() != 2;
1010 if (!endOfSequence) {
1020 AnchorVertex *after;
1021 if (candidates.isEmpty())
1022 after = (beforeSequence == adjacents.last() ? adjacents.first() : adjacents.last());
1024 after = (candidates.constLast() == adjacents.last() ? adjacents.first() : adjacents.last());
1028 Q_ASSERT(!candidates.contains(after));
1030 const AnchorData *data = g.edgeData(v, after);
1032 const bool cycleFound = visited.contains(after);
1035 endOfSequence = cycleFound || data->isCenterAnchor;
1037 if (!endOfSequence) {
1040 candidates.append(v);
1041 }
else if (cycleFound && (beforeSequence != after)) {
1042 afterSequence = after;
1043 candidates.append(v);
1050 for (AnchorVertex *next : adjacents) {
1051 if (visited.contains(next))
1059 stack.push(std::pair(v, next));
1061 stack.push(std::pair(beforeSequence, next));
1066 if (!endOfSequence || candidates.isEmpty())
1075 const AnchorData *firstAnchor = g.edgeData(beforeSequence, candidates.constFirst());
1076 if (firstAnchor->isCenterAnchor) {
1077 beforeSequence = candidates.constFirst();
1078 candidates.remove(0);
1081 if (candidates.isEmpty())
1085 const AnchorData *lastAnchor = g.edgeData(candidates.constLast(), afterSequence);
1086 if (lastAnchor->isCenterAnchor) {
1087 afterSequence = candidates.constLast();
1088 candidates.remove(candidates.size() - 1);
1090 if (candidates.isEmpty())
1098 AnchorData *sequence = createSequence(&g, beforeSequence, candidates, afterSequence);
1103 AnchorData *newAnchor = addAnchorMaybeParallel(sequence, &newFeasible);
1114 if (newAnchor != sequence)
1125void QGraphicsAnchorLayoutPrivate::restoreSimplifiedAnchor(AnchorData *edge)
1127 const Qt::Orientation orientation = edge->isVertical ? Qt::Vertical : Qt::Horizontal;
1129 static const char *anchortypes[] = {
"Normal",
1132 qDebug(
"Restoring %s edge.", anchortypes[
int(edge->type)]);
1135 Graph<AnchorVertex, AnchorData> &g = graph[orientation];
1137 if (edge->type == AnchorData::Normal) {
1138 g.createEdge(edge->from, edge->to, edge);
1140 }
else if (edge->type == AnchorData::Sequential) {
1141 const auto *sequence =
static_cast<SequentialAnchorData *>(edge);
1143 for (AnchorData *data : sequence->m_edges)
1144 restoreSimplifiedAnchor(data);
1148 }
else if (edge->type == AnchorData::Parallel) {
1153 if (anchorsFromSimplifiedVertices[orientation].contains(edge))
1156 ParallelAnchorData* parallel =
static_cast<ParallelAnchorData*>(edge);
1157 restoreSimplifiedConstraints(parallel);
1162 Q_ASSERT(parallel->firstEdge->type == AnchorData::Sequential
1163 || parallel->secondEdge->type == AnchorData::Sequential);
1164 restoreSimplifiedAnchor(parallel->firstEdge);
1165 restoreSimplifiedAnchor(parallel->secondEdge);
1171void QGraphicsAnchorLayoutPrivate::restoreSimplifiedConstraints(ParallelAnchorData *parallel)
1173 if (!parallel->isCenterAnchor)
1176 for (QSimplexConstraint *c : std::as_const(parallel->m_firstConstraints)) {
1177 qreal v = c->variables[parallel];
1178 c->variables.remove(parallel);
1179 c->variables.insert(parallel->firstEdge, v);
1184 const bool needsReverse = !parallel->secondForward();
1186 for (QSimplexConstraint *c : std::as_const(parallel->m_secondConstraints)) {
1187 qreal v = c->variables[parallel];
1190 c->variables.remove(parallel);
1191 c->variables.insert(parallel->secondEdge, v);
1195void QGraphicsAnchorLayoutPrivate::restoreSimplifiedGraph(Qt::Orientation orientation)
1198 qDebug(
"Restoring Simplified Graph for %s",
1199 orientation == Horizontal ?
"Horizontal" :
"Vertical");
1203 Graph<AnchorVertex, AnchorData> &g = graph[orientation];
1204 const QList<std::pair<AnchorVertex *, AnchorVertex *>> connections = g.connections();
1205 for (
const auto &connection : connections) {
1206 AnchorVertex *v1 = connection.first;
1207 AnchorVertex *v2 = connection.second;
1208 AnchorData *edge = g.edgeData(v1, v2);
1212 if (edge->type == AnchorData::Sequential
1213 || (edge->type == AnchorData::Parallel &&
1214 !anchorsFromSimplifiedVertices[orientation].contains(edge))) {
1217 restoreSimplifiedAnchor(edge);
1221 restoreVertices(orientation);
1224void QGraphicsAnchorLayoutPrivate::restoreVertices(Qt::Orientation orientation)
1226 Q_Q(QGraphicsAnchorLayout);
1228 Graph<AnchorVertex, AnchorData> &g = graph[orientation];
1229 QList<AnchorVertexPair *> &toRestore = simplifiedVertices[orientation];
1239 QList<AnchorData *> ¶llelAnchors = anchorsFromSimplifiedVertices[orientation];
1241 for (
auto it = parallelAnchors.crbegin(); it != parallelAnchors.crend(); ++it) {
1242 ParallelAnchorData *parallel =
static_cast<ParallelAnchorData *>(*it);
1243 restoreSimplifiedConstraints(parallel);
1248 for (
auto it = toRestore.crbegin(); it != toRestore.crend(); ++it) {
1250 const QList<AnchorVertex *> adjacents = g.adjacentVertices(pair);
1254 AnchorVertex *first = pair->m_first;
1255 AnchorVertex *second = pair->m_second;
1256 g.createEdge(first, second, pair->m_removedAnchor);
1259 for (AnchorData *ad : std::as_const(pair->m_firstAnchors)) {
1260 Q_ASSERT(ad->from == pair || ad->to == pair);
1262 replaceVertex_helper(ad, pair, first);
1263 g.createEdge(ad->from, ad->to, ad);
1267 for (AnchorData *ad : std::as_const(pair->m_secondAnchors)) {
1268 Q_ASSERT(ad->from == pair || ad->to == pair);
1270 replaceVertex_helper(ad, pair, second);
1271 g.createEdge(ad->from, ad->to, ad);
1274 for (AnchorVertex *adjacent : adjacents)
1275 g.takeEdge(pair, adjacent);
1279 if (pair->m_item == q) {
1280 AnchorVertex *layoutVertex = first->m_item == q ? first : second;
1281 Q_ASSERT(layoutVertex->m_item == q);
1282 changeLayoutVertex(orientation, pair, layoutVertex);
1287 qDeleteAll(parallelAnchors);
1288 parallelAnchors.clear();
1293QGraphicsAnchorLayoutPrivate::edgeOrientation(Qt::AnchorPoint edge)
noexcept
1295 return edge > Qt::AnchorRight ? Qt::Vertical : Qt::Horizontal;
1299
1300
1301
1302
1303
1304
1305
1306
1307void QGraphicsAnchorLayoutPrivate::createLayoutEdges()
1309 Q_Q(QGraphicsAnchorLayout);
1310 QGraphicsLayoutItem *layout = q;
1313 AnchorData *data =
new AnchorData;
1314 addAnchor_helper(layout, Qt::AnchorLeft, layout,
1315 Qt::AnchorRight, data);
1316 data->maxSize = QWIDGETSIZE_MAX;
1319 layoutFirstVertex[Qt::Horizontal] = internalVertex(layout, Qt::AnchorLeft);
1320 layoutCentralVertex[Qt::Horizontal] =
nullptr;
1321 layoutLastVertex[Qt::Horizontal] = internalVertex(layout, Qt::AnchorRight);
1324 data =
new AnchorData;
1325 addAnchor_helper(layout, Qt::AnchorTop, layout,
1326 Qt::AnchorBottom, data);
1327 data->maxSize = QWIDGETSIZE_MAX;
1330 layoutFirstVertex[Qt::Vertical] = internalVertex(layout, Qt::AnchorTop);
1331 layoutCentralVertex[Qt::Vertical] =
nullptr;
1332 layoutLastVertex[Qt::Vertical] = internalVertex(layout, Qt::AnchorBottom);
1335void QGraphicsAnchorLayoutPrivate::deleteLayoutEdges()
1337 Q_Q(QGraphicsAnchorLayout);
1339 Q_ASSERT(!internalVertex(q, Qt::AnchorHorizontalCenter));
1340 Q_ASSERT(!internalVertex(q, Qt::AnchorVerticalCenter));
1342 removeAnchor_helper(internalVertex(q, Qt::AnchorLeft),
1343 internalVertex(q, Qt::AnchorRight));
1344 removeAnchor_helper(internalVertex(q, Qt::AnchorTop),
1345 internalVertex(q, Qt::AnchorBottom));
1348void QGraphicsAnchorLayoutPrivate::createItemEdges(QGraphicsLayoutItem *item)
1354 AnchorData *data =
new AnchorData;
1355 addAnchor_helper(item, Qt::AnchorLeft, item, Qt::AnchorRight, data);
1356 data->refreshSizeHints();
1358 data =
new AnchorData;
1359 addAnchor_helper(item, Qt::AnchorTop, item, Qt::AnchorBottom, data);
1360 data->refreshSizeHints();
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374void QGraphicsAnchorLayoutPrivate::createCenterAnchors(
1375 QGraphicsLayoutItem *item, Qt::AnchorPoint centerEdge)
1377 Q_Q(QGraphicsAnchorLayout);
1379 Qt::Orientation orientation;
1380 switch (centerEdge) {
1381 case Qt::AnchorHorizontalCenter:
1382 orientation = Qt::Horizontal;
1384 case Qt::AnchorVerticalCenter:
1385 orientation = Qt::Vertical;
1393 if (internalVertex(item, centerEdge))
1397 Qt::AnchorPoint firstEdge;
1398 Qt::AnchorPoint lastEdge;
1400 if (orientation == Qt::Horizontal) {
1401 firstEdge = Qt::AnchorLeft;
1402 lastEdge = Qt::AnchorRight;
1404 firstEdge = Qt::AnchorTop;
1405 lastEdge = Qt::AnchorBottom;
1408 AnchorVertex *first = internalVertex(item, firstEdge);
1409 AnchorVertex *last = internalVertex(item, lastEdge);
1410 Q_ASSERT(first && last);
1413 QSimplexConstraint *c =
new QSimplexConstraint;
1415 AnchorData *data =
new AnchorData;
1416 c->variables.insert(data, 1.0);
1417 addAnchor_helper(item, firstEdge, item, centerEdge, data);
1418 data->isCenterAnchor =
true;
1419 data->dependency = AnchorData::Master;
1420 data->refreshSizeHints();
1422 data =
new AnchorData;
1423 c->variables.insert(data, -1.0);
1424 addAnchor_helper(item, centerEdge, item, lastEdge, data);
1425 data->isCenterAnchor =
true;
1426 data->dependency = AnchorData::Slave;
1427 data->refreshSizeHints();
1429 itemCenterConstraints[orientation].append(c);
1432 removeAnchor_helper(first, last);
1435 layoutCentralVertex[orientation] = internalVertex(q, centerEdge);
1439void QGraphicsAnchorLayoutPrivate::removeCenterAnchors(
1440 QGraphicsLayoutItem *item, Qt::AnchorPoint centerEdge,
1443 Q_Q(QGraphicsAnchorLayout);
1445 Qt::Orientation orientation;
1446 switch (centerEdge) {
1447 case Qt::AnchorHorizontalCenter:
1448 orientation = Qt::Horizontal;
1450 case Qt::AnchorVerticalCenter:
1451 orientation = Qt::Vertical;
1459 Qt::AnchorPoint firstEdge;
1460 Qt::AnchorPoint lastEdge;
1462 if (orientation == Qt::Horizontal) {
1463 firstEdge = Qt::AnchorLeft;
1464 lastEdge = Qt::AnchorRight;
1466 firstEdge = Qt::AnchorTop;
1467 lastEdge = Qt::AnchorBottom;
1470 AnchorVertex *center = internalVertex(item, centerEdge);
1473 AnchorVertex *first = internalVertex(item, firstEdge);
1478 Graph<AnchorVertex, AnchorData> &g = graph[orientation];
1481 AnchorData *oldData = g.edgeData(first, center);
1483 for (
int i = itemCenterConstraints[orientation].size() - 1; i >= 0; --i) {
1484 if (itemCenterConstraints[orientation].at(i)->variables.contains(oldData)) {
1485 delete itemCenterConstraints[orientation].takeAt(i);
1492 AnchorData *data =
new AnchorData;
1493 addAnchor_helper(item, firstEdge, item, lastEdge, data);
1494 data->refreshSizeHints();
1497 removeAnchor_helper(first, center);
1498 removeAnchor_helper(center, internalVertex(item, lastEdge));
1503 const QList<AnchorVertex*> adjacents = g.adjacentVertices(center);
1504 for (AnchorVertex *v : adjacents) {
1505 if (v->m_item != item)
1506 removeAnchor_helper(center, internalVertex(v->m_item, v->m_edge));
1511 removeAnchor_helper(first, internalVertex(item, lastEdge));
1515 layoutCentralVertex[orientation] =
nullptr;
1520void QGraphicsAnchorLayoutPrivate::removeCenterConstraints(QGraphicsLayoutItem *item,
1521 Qt::Orientation orientation)
1528 AnchorVertex *first = internalVertex(item, orientation == Qt::Horizontal ?
1531 AnchorVertex *center = internalVertex(item, orientation == Qt::Horizontal ?
1532 Qt::AnchorHorizontalCenter :
1533 Qt::AnchorVerticalCenter);
1540 AnchorData *internalAnchor = graph[orientation].edgeData(first, center);
1543 for (
int i = 0; i < itemCenterConstraints[orientation].size(); ++i) {
1544 if (itemCenterConstraints[orientation].at(i)->variables.contains(internalAnchor)) {
1545 delete itemCenterConstraints[orientation].takeAt(i);
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563QGraphicsAnchor *QGraphicsAnchorLayoutPrivate::addAnchor(QGraphicsLayoutItem *firstItem,
1564 Qt::AnchorPoint firstEdge,
1565 QGraphicsLayoutItem *secondItem,
1566 Qt::AnchorPoint secondEdge,
1569 Q_Q(QGraphicsAnchorLayout);
1570 if ((firstItem ==
nullptr) || (secondItem ==
nullptr)) {
1571 qWarning(
"QGraphicsAnchorLayout::addAnchor(): "
1572 "Cannot anchor NULL items");
1576 if (firstItem == secondItem) {
1577 qWarning(
"QGraphicsAnchorLayout::addAnchor(): "
1578 "Cannot anchor the item to itself");
1582 if (edgeOrientation(secondEdge) != edgeOrientation(firstEdge)) {
1583 qWarning(
"QGraphicsAnchorLayout::addAnchor(): "
1584 "Cannot anchor edges of different orientations");
1588 const QGraphicsLayoutItem *parentWidget = q->parentLayoutItem();
1589 if (firstItem == parentWidget || secondItem == parentWidget) {
1590 qWarning(
"QGraphicsAnchorLayout::addAnchor(): "
1591 "You cannot add the parent of the layout to the layout.");
1603 if (firstItem != q && !items.contains(firstItem)) {
1604 createItemEdges(firstItem);
1605 addChildLayoutItem(firstItem);
1607 if (secondItem != q && !items.contains(secondItem)) {
1608 createItemEdges(secondItem);
1609 addChildLayoutItem(secondItem);
1613 createCenterAnchors(firstItem, firstEdge);
1614 createCenterAnchors(secondItem, secondEdge);
1617 correctEdgeDirection(firstItem, firstEdge, secondItem, secondEdge);
1619 AnchorData *data =
new AnchorData;
1620 QGraphicsAnchor *graphicsAnchor = acquireGraphicsAnchor(data);
1622 addAnchor_helper(firstItem, firstEdge, secondItem, secondEdge, data);
1625 graphicsAnchor->setSpacing(*spacing);
1637 || pickEdge(firstEdge, Qt::Horizontal) == Qt::AnchorHorizontalCenter
1638 || oppositeEdge(firstEdge) != secondEdge) {
1639 graphicsAnchor->setSpacing(0);
1641 graphicsAnchor->unsetSpacing();
1645 return graphicsAnchor;
1649
1650
1651
1652
1653
1654
1655
1656
1657void QGraphicsAnchorLayoutPrivate::addAnchor_helper(QGraphicsLayoutItem *firstItem,
1658 Qt::AnchorPoint firstEdge,
1659 QGraphicsLayoutItem *secondItem,
1660 Qt::AnchorPoint secondEdge,
1663 Q_Q(QGraphicsAnchorLayout);
1665 const Qt::Orientation orientation = edgeOrientation(firstEdge);
1668 AnchorVertex *v1 = addInternalVertex(firstItem, firstEdge);
1669 AnchorVertex *v2 = addInternalVertex(secondItem, secondEdge);
1672 if (graph[orientation].edgeData(v1, v2)) {
1673 removeAnchor_helper(v1, v2);
1677 if (firstItem == secondItem)
1678 data->item = firstItem;
1680 data->isVertical = orientation == Qt::Vertical;
1688 data->name = QString::fromLatin1(
"%1 --to--> %2").arg(v1->toString(), v2->toString());
1692 data->isLayoutAnchor = (data->item == q);
1694 graph[orientation].createEdge(v1, v2, data);
1697QGraphicsAnchor *QGraphicsAnchorLayoutPrivate::getAnchor(QGraphicsLayoutItem *firstItem,
1698 Qt::AnchorPoint firstEdge,
1699 QGraphicsLayoutItem *secondItem,
1700 Qt::AnchorPoint secondEdge)
1703 if (firstItem == secondItem)
1706 const Qt::Orientation orientation = edgeOrientation(firstEdge);
1707 AnchorVertex *v1 = internalVertex(firstItem, firstEdge);
1708 AnchorVertex *v2 = internalVertex(secondItem, secondEdge);
1710 QGraphicsAnchor *graphicsAnchor =
nullptr;
1712 AnchorData *data = graph[orientation].edgeData(v1, v2);
1720 Q_ASSERT(data->graphicsAnchor);
1721 graphicsAnchor = data->graphicsAnchor;
1723 return graphicsAnchor;
1727
1728
1729
1730
1731
1732void QGraphicsAnchorLayoutPrivate::removeAnchor(AnchorVertex *firstVertex,
1733 AnchorVertex *secondVertex)
1735 Q_Q(QGraphicsAnchorLayout);
1738 QGraphicsLayoutItem *firstItem = firstVertex->m_item;
1739 QGraphicsLayoutItem *secondItem = secondVertex->m_item;
1742 removeAnchor_helper(firstVertex, secondVertex);
1745 firstVertex = secondVertex =
nullptr;
1748 bool keepFirstItem =
false;
1749 bool keepSecondItem =
false;
1751 std::pair<AnchorVertex *,
int> v;
1754 if (firstItem != q) {
1755 for (
int i = Qt::AnchorLeft; i <= Qt::AnchorBottom; ++i) {
1756 v = m_vertexList.value(std::pair(firstItem,
static_cast<Qt::AnchorPoint>(i)));
1758 if (i == Qt::AnchorHorizontalCenter || i == Qt::AnchorVerticalCenter)
1763 if (v.second > refcount) {
1764 keepFirstItem =
true;
1770 keepFirstItem =
true;
1772 if (secondItem != q) {
1773 for (
int i = Qt::AnchorLeft; i <= Qt::AnchorBottom; ++i) {
1774 v = m_vertexList.value(std::pair(secondItem,
static_cast<Qt::AnchorPoint>(i)));
1776 if (i == Qt::AnchorHorizontalCenter || i == Qt::AnchorVerticalCenter)
1781 if (v.second > refcount) {
1782 keepSecondItem =
true;
1788 keepSecondItem =
true;
1791 q->removeAt(items.indexOf(firstItem));
1793 if (!keepSecondItem)
1794 q->removeAt(items.indexOf(secondItem));
1801
1802
1803
1804
1805
1806void QGraphicsAnchorLayoutPrivate::removeAnchor_helper(AnchorVertex *v1, AnchorVertex *v2)
1811 const Qt::Orientation o = edgeOrientation(v1->m_edge);
1812 graph[o].removeEdge(v1, v2);
1815 removeInternalVertex(v1->m_item, v1->m_edge);
1816 removeInternalVertex(v2->m_item, v2->m_edge);
1819AnchorVertex *QGraphicsAnchorLayoutPrivate::addInternalVertex(QGraphicsLayoutItem *item,
1820 Qt::AnchorPoint edge)
1822 std::pair<QGraphicsLayoutItem *, Qt::AnchorPoint> pair(item, edge);
1823 std::pair<AnchorVertex *,
int> v = m_vertexList.value(pair);
1826 Q_ASSERT(v.second == 0);
1827 v.first =
new AnchorVertex(item, edge);
1830 m_vertexList.insert(pair, v);
1835
1836
1837
1838
1839
1840void QGraphicsAnchorLayoutPrivate::removeInternalVertex(QGraphicsLayoutItem *item,
1841 Qt::AnchorPoint edge)
1843 std::pair<QGraphicsLayoutItem *, Qt::AnchorPoint> pair(item, edge);
1844 std::pair<AnchorVertex *,
int> v = m_vertexList.value(pair);
1847 qWarning(
"This item with this edge is not in the graph");
1852 if (v.second == 0) {
1854 m_vertexList.remove(pair);
1858 m_vertexList.insert(pair, v);
1860 if ((v.second == 2) &&
1861 ((edge == Qt::AnchorHorizontalCenter) ||
1862 (edge == Qt::AnchorVerticalCenter))) {
1863 removeCenterAnchors(item, edge,
true);
1868void QGraphicsAnchorLayoutPrivate::removeVertex(QGraphicsLayoutItem *item, Qt::AnchorPoint edge)
1870 if (AnchorVertex *v = internalVertex(item, edge)) {
1871 Graph<AnchorVertex, AnchorData> &g = graph[edgeOrientation(edge)];
1872 const auto allVertices = g.adjacentVertices(v);
1873 for (
auto *v2 : allVertices) {
1874 g.removeEdge(v, v2);
1875 removeInternalVertex(item, edge);
1876 removeInternalVertex(v2->m_item, v2->m_edge);
1881void QGraphicsAnchorLayoutPrivate::removeAnchors(QGraphicsLayoutItem *item)
1884 removeCenterAnchors(item, Qt::AnchorHorizontalCenter,
false);
1885 removeVertex(item, Qt::AnchorLeft);
1886 removeVertex(item, Qt::AnchorRight);
1888 removeCenterAnchors(item, Qt::AnchorVerticalCenter,
false);
1889 removeVertex(item, Qt::AnchorTop);
1890 removeVertex(item, Qt::AnchorBottom);
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917void QGraphicsAnchorLayoutPrivate::correctEdgeDirection(QGraphicsLayoutItem *&firstItem,
1918 Qt::AnchorPoint &firstEdge,
1919 QGraphicsLayoutItem *&secondItem,
1920 Qt::AnchorPoint &secondEdge)
1922 Q_Q(QGraphicsAnchorLayout);
1924 if ((firstItem != q) && (secondItem != q)) {
1927 if (firstEdge < secondEdge) {
1928 qSwap(firstItem, secondItem);
1929 qSwap(firstEdge, secondEdge);
1931 }
else if (firstItem == q) {
1934 if ((firstEdge == Qt::AnchorRight) || (firstEdge == Qt::AnchorBottom)) {
1935 qSwap(firstItem, secondItem);
1936 qSwap(firstEdge, secondEdge);
1938 }
else if ((secondEdge != Qt::AnchorRight) && (secondEdge != Qt::AnchorBottom)) {
1941 qSwap(firstItem, secondItem);
1942 qSwap(firstEdge, secondEdge);
1946QLayoutStyleInfo &QGraphicsAnchorLayoutPrivate::styleInfo()
const
1948 if (styleInfoDirty) {
1949 Q_Q(
const QGraphicsAnchorLayout);
1951 QWidget *wid =
nullptr;
1953 QGraphicsLayoutItem *parent = q->parentLayoutItem();
1954 while (parent && parent->isLayout()) {
1955 parent = parent->parentLayoutItem();
1957 QGraphicsWidget *w =
nullptr;
1959 QGraphicsItem *parentItem = parent->graphicsItem();
1960 if (parentItem && parentItem->isWidget())
1961 w =
static_cast<QGraphicsWidget*>(parentItem);
1964 QStyle *style = w ? w->style() : QApplication::style();
1965 cachedStyleInfo = QLayoutStyleInfo(style, wid);
1966 cachedStyleInfo.setDefaultSpacing(Qt::Horizontal, spacings[Qt::Horizontal]);
1967 cachedStyleInfo.setDefaultSpacing(Qt::Vertical, spacings[Qt::Vertical]);
1969 styleInfoDirty =
false;
1971 return cachedStyleInfo;
1975
1976
1977
1978
1979
1980
1981void QGraphicsAnchorLayoutPrivate::calculateGraphs()
1983 if (!calculateGraphCacheDirty)
1985 calculateGraphs(Qt::Horizontal);
1986 calculateGraphs(Qt::Vertical);
1987 calculateGraphCacheDirty =
false;
1994 QSet<AnchorData *> variableSet;
1995 for (QSimplexConstraint *c : constraints) {
1996 for (
auto it = c->variables.cbegin(), end = c->variables.cend(); it != end; ++it)
1997 variableSet.insert(
static_cast<AnchorData *>(it.key()));
1999 return variableSet.values();
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025void QGraphicsAnchorLayoutPrivate::calculateGraphs(Qt::Orientation orientation)
2027#if defined(QT_DEBUG) || defined(QT_BUILD_INTERNAL)
2028 lastCalculationUsedSimplex[orientation] =
false;
2031 static bool simplificationEnabled = qEnvironmentVariableIsEmpty(
"QT_ANCHORLAYOUT_NO_SIMPLIFICATION");
2034 refreshAllSizeHints(orientation);
2037 if (simplificationEnabled && !simplifyGraph(orientation)) {
2038 qWarning(
"QGraphicsAnchorLayout: anchor setup is not feasible.");
2039 graphHasConflicts[orientation] =
true;
2044 findPaths(orientation);
2048 constraintsFromPaths(orientation);
2060 const auto parts = getGraphParts(orientation);
2065 const QList<AnchorData *> trunkVariables = getVariables(parts.trunkConstraints);
2069 AnchorVertex *v = layoutLastVertex[orientation];
2070 GraphPath trunkPath = graphPaths[orientation].value(v);
2072 bool feasible = calculateTrunk(orientation, trunkPath, parts.trunkConstraints, trunkVariables);
2078 if (feasible && !parts.nonTrunkConstraints.isEmpty()) {
2079 const QList<AnchorData *> partVariables = getVariables(parts.nonTrunkConstraints);
2080 Q_ASSERT(!partVariables.isEmpty());
2081 feasible = calculateNonTrunk(parts.nonTrunkConstraints, partVariables);
2086 updateAnchorSizes(orientation);
2088 graphHasConflicts[orientation] = !feasible;
2092 qDeleteAll(constraints[orientation]);
2093 constraints[orientation].clear();
2094 graphPaths[orientation].clear();
2096 if (simplificationEnabled)
2097 restoreSimplifiedGraph(orientation);
2101
2102
2103
2104
2105
2106
2109 for (QSimplexConstraint *c : constraints) {
2110 const qreal multiplier = std::accumulate(c->variables.cbegin(), c->variables.cend(), qreal(0));
2111 c->constant += multiplier * amount;
2116
2117
2118
2119
2120
2121bool QGraphicsAnchorLayoutPrivate::calculateTrunk(Qt::Orientation orientation,
const GraphPath &path,
2122 const QList<QSimplexConstraint *> &constraints,
2123 const QList<AnchorData *> &variables)
2125 bool feasible =
true;
2126 bool needsSimplex = !constraints.isEmpty();
2129 qDebug(
"Simplex %s for trunk of %s", needsSimplex ?
"used" :
"NOT used",
2130 orientation == Qt::Horizontal ?
"Horizontal" :
"Vertical");
2135 QList<QSimplexConstraint *> sizeHintConstraints = constraintsFromSizeHints(variables);
2136 QList<QSimplexConstraint *> allConstraints = constraints + sizeHintConstraints;
2138 shiftConstraints(allConstraints, g_offset);
2142 feasible = solveMinMax(allConstraints, path, &min, &max);
2145 solvePreferred(constraints, variables);
2150 for (
const AnchorData *ad : path.positives)
2151 pref += ad->sizeAtPreferred;
2152 for (
const AnchorData *ad : path.negatives)
2153 pref -= ad->sizeAtPreferred;
2155 sizeHints[orientation][Qt::MinimumSize] = min;
2156 sizeHints[orientation][Qt::PreferredSize] = pref;
2157 sizeHints[orientation][Qt::MaximumSize] = max;
2160 qDeleteAll(sizeHintConstraints);
2161 shiftConstraints(constraints, -g_offset);
2166 Q_ASSERT(path.positives.size() == 1);
2167 Q_ASSERT(path.negatives.size() == 0);
2169 AnchorData *ad = *path.positives.cbegin();
2170 ad->sizeAtMinimum = ad->minSize;
2171 ad->sizeAtPreferred = ad->prefSize;
2172 ad->sizeAtMaximum = ad->maxSize;
2174 sizeHints[orientation][Qt::MinimumSize] = ad->sizeAtMinimum;
2175 sizeHints[orientation][Qt::PreferredSize] = ad->sizeAtPreferred;
2176 sizeHints[orientation][Qt::MaximumSize] = ad->sizeAtMaximum;
2179#if defined(QT_DEBUG) || defined(QT_BUILD_INTERNAL)
2180 lastCalculationUsedSimplex[orientation] = needsSimplex;
2187
2188
2189bool QGraphicsAnchorLayoutPrivate::calculateNonTrunk(
const QList<QSimplexConstraint *> &constraints,
2190 const QList<AnchorData *> &variables)
2192 shiftConstraints(constraints, g_offset);
2193 bool feasible = solvePreferred(constraints, variables);
2198 for (AnchorData *ad : variables) {
2200 ad->sizeAtMinimum = ad->sizeAtPreferred;
2201 ad->sizeAtMaximum = ad->sizeAtPreferred;
2205 shiftConstraints(constraints, -g_offset);
2210
2211
2212
2213
2214
2215void QGraphicsAnchorLayoutPrivate::refreshAllSizeHints(Qt::Orientation orientation)
2217 Graph<AnchorVertex, AnchorData> &g = graph[orientation];
2218 const QList<std::pair<AnchorVertex *, AnchorVertex *>> vertices = g.connections();
2220 QLayoutStyleInfo styleInf = styleInfo();
2221 for (
const auto &p : vertices) {
2222 AnchorData *data = g.edgeData(p.first, p.second);
2223 data->refreshSizeHints(&styleInf);
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237void QGraphicsAnchorLayoutPrivate::findPaths(Qt::Orientation orientation)
2239 QQueue<std::pair<AnchorVertex *, AnchorVertex *> > queue;
2241 QSet<AnchorData *> visited;
2243 AnchorVertex *root = layoutFirstVertex[orientation];
2245 graphPaths[orientation].insert(root, GraphPath());
2247 const auto adjacentVertices = graph[orientation].adjacentVertices(root);
2248 for (AnchorVertex *v : adjacentVertices)
2249 queue.enqueue(std::pair(root, v));
2251 while(!queue.isEmpty()) {
2252 std::pair<AnchorVertex *, AnchorVertex *> pair = queue.dequeue();
2253 AnchorData *edge = graph[orientation].edgeData(pair.first, pair.second);
2255 if (visited.contains(edge))
2258 visited.insert(edge);
2259 GraphPath current = graphPaths[orientation].value(pair.first);
2261 if (edge->from == pair.first)
2262 current.positives.insert(edge);
2264 current.negatives.insert(edge);
2266 graphPaths[orientation].insert(pair.second, current);
2268 const auto adjacentVertices = graph[orientation].adjacentVertices(pair.second);
2269 for (AnchorVertex *v : adjacentVertices)
2270 queue.enqueue(std::pair(pair.second, v));
2276 identifyFloatItems(visited, orientation);
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289void QGraphicsAnchorLayoutPrivate::constraintsFromPaths(Qt::Orientation orientation)
2291 const auto vertices = graphPaths[orientation].uniqueKeys();
2292 for (AnchorVertex *vertex : vertices) {
2293 const qsizetype valueCount = graphPaths[orientation].count(vertex);
2294 if (valueCount == 1)
2297 QList<GraphPath> pathsToVertex = graphPaths[orientation].values(vertex);
2298 for (qsizetype i = 1; i < valueCount; ++i)
2299 constraints[orientation] += pathsToVertex[0].constraint(pathsToVertex.at(i));
2304
2305
2306void QGraphicsAnchorLayoutPrivate::updateAnchorSizes(Qt::Orientation orientation)
2308 Graph<AnchorVertex, AnchorData> &g = graph[orientation];
2309 const QList<std::pair<AnchorVertex *, AnchorVertex *>> &vertices = g.connections();
2311 for (
const auto &p :vertices) {
2312 AnchorData *ad = g.edgeData(p.first, p.second);
2313 ad->updateChildrenSizes();
2318
2319
2320
2321
2322
2323QList<QSimplexConstraint *> QGraphicsAnchorLayoutPrivate::constraintsFromSizeHints(
2324 const QList<AnchorData *> &anchors)
2326 if (anchors.isEmpty())
2327 return QList<QSimplexConstraint *>();
2331 const Qt::Orientation orient = anchors.first()->isVertical ? Qt::Vertical : Qt::Horizontal;
2332 AnchorData *layoutEdge =
nullptr;
2333 if (layoutCentralVertex[orient]) {
2334 layoutEdge = graph[orient].edgeData(layoutFirstVertex[orient], layoutCentralVertex[orient]);
2336 layoutEdge = graph[orient].edgeData(layoutFirstVertex[orient], layoutLastVertex[orient]);
2343 const qreal expectedMax = layoutCentralVertex[orient] ? QWIDGETSIZE_MAX / 2 : QWIDGETSIZE_MAX;
2345 if (layoutEdge->from == layoutFirstVertex[orient]) {
2346 actualMax = layoutEdge->maxSize;
2348 actualMax = -layoutEdge->minSize;
2350 if (actualMax != expectedMax) {
2351 layoutEdge =
nullptr;
2355 QList<QSimplexConstraint *> anchorConstraints;
2356 bool unboundedProblem =
true;
2357 for (AnchorData *ad : anchors) {
2362 if (ad->dependency == AnchorData::Slave)
2368 qreal boundedMin = qBound(-g_offset, ad->minSize, g_offset);
2369 qreal boundedMax = qBound(-g_offset, ad->maxSize, g_offset);
2371 if ((boundedMin == boundedMax) || qFuzzyCompare(boundedMin, boundedMax)) {
2372 QSimplexConstraint *c =
new QSimplexConstraint;
2373 c->variables.insert(ad, 1.0);
2374 c->constant = boundedMin;
2375 c->ratio = QSimplexConstraint::Equal;
2376 anchorConstraints += c;
2377 unboundedProblem =
false;
2379 QSimplexConstraint *c =
new QSimplexConstraint;
2380 c->variables.insert(ad, 1.0);
2381 c->constant = boundedMin;
2382 c->ratio = QSimplexConstraint::MoreOrEqual;
2383 anchorConstraints += c;
2388 if (ad == layoutEdge)
2391 c =
new QSimplexConstraint;
2392 c->variables.insert(ad, 1.0);
2393 c->constant = boundedMax;
2394 c->ratio = QSimplexConstraint::LessOrEqual;
2395 anchorConstraints += c;
2396 unboundedProblem =
false;
2401 if (unboundedProblem) {
2402 QSimplexConstraint *c =
new QSimplexConstraint;
2403 c->variables.insert(layoutEdge, 1.0);
2405 c->constant = g_offset;
2406 c->ratio = QSimplexConstraint::LessOrEqual;
2407 anchorConstraints += c;
2410 return anchorConstraints;
2414
2415
2416QGraphicsAnchorLayoutPrivate::GraphParts
2417QGraphicsAnchorLayoutPrivate::getGraphParts(Qt::Orientation orientation)
2421 Q_ASSERT(layoutFirstVertex[orientation] && layoutLastVertex[orientation]);
2423 AnchorData *edgeL1 =
nullptr;
2424 AnchorData *edgeL2 =
nullptr;
2428 if (layoutCentralVertex[orientation]) {
2429 edgeL1 = graph[orientation].edgeData(layoutFirstVertex[orientation], layoutCentralVertex[orientation]);
2430 edgeL2 = graph[orientation].edgeData(layoutCentralVertex[orientation], layoutLastVertex[orientation]);
2432 edgeL1 = graph[orientation].edgeData(layoutFirstVertex[orientation], layoutLastVertex[orientation]);
2435 result.nonTrunkConstraints = constraints[orientation] + itemCenterConstraints[orientation];
2437 QSet<QSimplexVariable *> trunkVariables;
2439 trunkVariables += edgeL1;
2441 trunkVariables += edgeL2;
2444 auto end = result.nonTrunkConstraints.end();
2448 auto isMatch = [&result, &trunkVariables](QSimplexConstraint *c) ->
bool {
2453 for (QSimplexVariable *ad : std::as_const(trunkVariables)) {
2454 if (c->variables.contains(ad)) {
2463 result.trunkConstraints += c;
2464 for (
auto jt = c->variables.cbegin(), end = c->variables.cend(); jt != end; ++jt)
2465 trunkVariables.insert(jt.key());
2479 const auto newEnd = std::remove_if(result.nonTrunkConstraints.begin(), end, isMatch);
2480 dirty = newEnd != end;
2484 result.nonTrunkConstraints.erase(end, result.nonTrunkConstraints.end());
2490
2491
2492
2493
2494void QGraphicsAnchorLayoutPrivate::identifyFloatItems(
const QSet<AnchorData *> &visited, Qt::Orientation orientation)
2496 QSet<QGraphicsLayoutItem *> nonFloating;
2498 for (
const AnchorData *ad : visited)
2499 identifyNonFloatItems_helper(ad, &nonFloating);
2501 QSet<QGraphicsLayoutItem *> floatItems;
2502 for (QGraphicsLayoutItem *item : std::as_const(items)) {
2503 if (!nonFloating.contains(item))
2504 floatItems.insert(item);
2506 m_floatItems[orientation] = std::move(floatItems);
2511
2512
2513
2514
2515
2516
2517void QGraphicsAnchorLayoutPrivate::identifyNonFloatItems_helper(
const AnchorData *ad, QSet<QGraphicsLayoutItem *> *nonFloatingItemsIdentifiedSoFar)
2519 Q_Q(QGraphicsAnchorLayout);
2522 case AnchorData::Normal:
2523 if (ad->item && ad->item != q)
2524 nonFloatingItemsIdentifiedSoFar->insert(ad->item);
2526 case AnchorData::Sequential:
2527 for (
const AnchorData *d :
static_cast<
const SequentialAnchorData *>(ad)->m_edges)
2528 identifyNonFloatItems_helper(d, nonFloatingItemsIdentifiedSoFar);
2530 case AnchorData::Parallel:
2531 identifyNonFloatItems_helper(
static_cast<
const ParallelAnchorData *>(ad)->firstEdge, nonFloatingItemsIdentifiedSoFar);
2532 identifyNonFloatItems_helper(
static_cast<
const ParallelAnchorData *>(ad)->secondEdge, nonFloatingItemsIdentifiedSoFar);
2538
2539
2540
2541
2542
2543void QGraphicsAnchorLayoutPrivate::setItemsGeometries(
const QRectF &geom)
2545 Q_Q(QGraphicsAnchorLayout);
2546 AnchorVertex *firstH, *secondH, *firstV, *secondV;
2552 q->getContentsMargins(&left, &top, &right,
nullptr);
2553 const Qt::LayoutDirection visualDir = visualDirection();
2554 if (visualDir == Qt::RightToLeft)
2557 left += geom.left();
2559 right = geom.right() - right;
2561 for (QGraphicsLayoutItem *item : std::as_const(items)) {
2563 QSizeF itemPreferredSize = item->effectiveSizeHint(Qt::PreferredSize);
2564 if (m_floatItems[Qt::Horizontal].contains(item)) {
2566 newGeom.setRight(itemPreferredSize.width());
2568 firstH = internalVertex(item, Qt::AnchorLeft);
2569 secondH = internalVertex(item, Qt::AnchorRight);
2571 if (visualDir == Qt::LeftToRight) {
2572 newGeom.setLeft(left + firstH->distance);
2573 newGeom.setRight(left + secondH->distance);
2575 newGeom.setLeft(right - secondH->distance);
2576 newGeom.setRight(right - firstH->distance);
2580 if (m_floatItems[Qt::Vertical].contains(item)) {
2582 newGeom.setBottom(itemPreferredSize.height());
2584 firstV = internalVertex(item, Qt::AnchorTop);
2585 secondV = internalVertex(item, Qt::AnchorBottom);
2587 newGeom.setTop(top + firstV->distance);
2588 newGeom.setBottom(top + secondV->distance);
2591 item->setGeometry(newGeom);
2596
2597
2598
2599
2600
2601void QGraphicsAnchorLayoutPrivate::calculateVertexPositions(Qt::Orientation orientation)
2603 QQueue<std::pair<AnchorVertex *, AnchorVertex *> > queue;
2604 QSet<AnchorVertex *> visited;
2607 AnchorVertex *root = layoutFirstVertex[orientation];
2610 visited.insert(root);
2613 const auto adjacentVertices = graph[orientation].adjacentVertices(root);
2614 for (AnchorVertex *v : adjacentVertices)
2615 queue.enqueue(std::pair(root, v));
2618 setupEdgesInterpolation(orientation);
2621 while (!queue.isEmpty()) {
2622 std::pair<AnchorVertex *, AnchorVertex *> pair = queue.dequeue();
2623 AnchorData *edge = graph[orientation].edgeData(pair.first, pair.second);
2625 if (visited.contains(pair.second))
2628 visited.insert(pair.second);
2629 interpolateEdge(pair.first, edge);
2631 const QList<AnchorVertex *> adjacents = graph[orientation].adjacentVertices(pair.second);
2632 for (AnchorVertex *av : adjacents) {
2633 if (!visited.contains(av))
2634 queue.enqueue(std::pair(pair.second, av));
2640
2641
2642
2643
2644
2645
2646void QGraphicsAnchorLayoutPrivate::setupEdgesInterpolation(
2647 Qt::Orientation orientation)
2649 Q_Q(QGraphicsAnchorLayout);
2652 current = (orientation == Qt::Horizontal) ? q->contentsRect().width() : q->contentsRect().height();
2654 std::pair<Interval, qreal> result;
2655 result = getFactor(current,
2656 sizeHints[orientation][Qt::MinimumSize],
2657 sizeHints[orientation][Qt::PreferredSize],
2658 sizeHints[orientation][Qt::PreferredSize],
2659 sizeHints[orientation][Qt::PreferredSize],
2660 sizeHints[orientation][Qt::MaximumSize]);
2662 interpolationInterval[orientation] = result.first;
2663 interpolationProgress[orientation] = result.second;
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681void QGraphicsAnchorLayoutPrivate::interpolateEdge(AnchorVertex *base, AnchorData *edge)
2683 const Qt::Orientation orientation = edge->isVertical ? Qt::Vertical : Qt::Horizontal;
2684 const std::pair<Interval, qreal> factor(interpolationInterval[orientation],
2685 interpolationProgress[orientation]);
2687 qreal edgeDistance = interpolate(factor, edge->sizeAtMinimum, edge->sizeAtPreferred,
2688 edge->sizeAtPreferred, edge->sizeAtPreferred,
2689 edge->sizeAtMaximum);
2691 Q_ASSERT(edge->from == base || edge->to == base);
2694 if (edge->from == base) {
2695 edge->to->distance = base->distance + edgeDistance;
2697 edge->from->distance = base->distance - edgeDistance;
2701bool QGraphicsAnchorLayoutPrivate::solveMinMax(
const QList<QSimplexConstraint *> &constraints,
2702 const GraphPath &path, qreal *min, qreal *max)
2705 bool feasible = simplex.setConstraints(constraints);
2708 QSimplexConstraint objective;
2709 for (AnchorData * ad: path.positives)
2710 objective.variables.insert(ad, 1.0);
2712 for (AnchorData *ad : path.negatives)
2713 objective.variables.insert(ad, -1.0);
2715 const qreal objectiveOffset = (path.positives.size() - path.negatives.size()) * g_offset;
2716 simplex.setObjective(&objective);
2719 *min = simplex.solveMin() - objectiveOffset;
2722 const QList<AnchorData *> variables = getVariables(constraints);
2723 for (AnchorData *ad : variables)
2724 ad->sizeAtMinimum = ad->result - g_offset;
2727 *max = simplex.solveMax() - objectiveOffset;
2730 for (AnchorData *ad : variables)
2731 ad->sizeAtMaximum = ad->result - g_offset;
2740 QConcreteSimplexVariable *slack;
2744 auto slack =
new QConcreteSimplexVariable;
2745 sizeConstraint->variables.insert(slack, type);
2748 limit->variables.insert(slack, 1.0);
2750 limit->constant = interval;
2752 return R{slack, limit};
2755bool QGraphicsAnchorLayoutPrivate::solvePreferred(
const QList<QSimplexConstraint *> &constraints,
2756 const QList<AnchorData *> &variables)
2758 QList<QSimplexConstraint *> preferredConstraints;
2759 QList<QConcreteSimplexVariable *> preferredVariables;
2760 QSimplexConstraint objective;
2780 for (AnchorData *ad : variables) {
2782 if (ad->isLayoutAnchor)
2787 QSimplexConstraint *sizeConstraint =
new QSimplexConstraint;
2788 preferredConstraints += sizeConstraint;
2789 sizeConstraint->variables.insert(ad, 1.0);
2790 sizeConstraint->constant = ad->prefSize + g_offset;
2793 const qreal softShrinkInterval = ad->prefSize - ad->minPrefSize;
2794 if (softShrinkInterval) {
2795 auto r = createSlack(sizeConstraint, softShrinkInterval, Shrinker);
2796 preferredVariables += r.slack;
2797 preferredConstraints += r.limit;
2800 objective.variables.insert(r.slack, 1.0);
2804 const qreal softGrowInterval = ad->maxPrefSize - ad->prefSize;
2805 if (softGrowInterval) {
2806 auto r = createSlack(sizeConstraint, softGrowInterval, Grower);
2807 preferredVariables += r.slack;
2808 preferredConstraints += r.limit;
2811 objective.variables.insert(r.slack, 1.0);
2815 const qreal hardShrinkInterval = ad->minPrefSize - ad->minSize;
2816 if (hardShrinkInterval) {
2817 auto r = createSlack(sizeConstraint, hardShrinkInterval, Shrinker);
2818 preferredVariables += r.slack;
2819 preferredConstraints += r.limit;
2822 objective.variables.insert(r.slack, variables.size());
2826 const qreal hardGrowInterval = ad->maxSize - ad->maxPrefSize;
2827 if (hardGrowInterval) {
2828 auto r = createSlack(sizeConstraint, hardGrowInterval, Grower);
2829 preferredVariables += r.slack;
2830 preferredConstraints += r.limit;
2833 objective.variables.insert(r.slack, variables.size());
2837 QSimplex *simplex =
new QSimplex;
2838 bool feasible = simplex->setConstraints(constraints + preferredConstraints);
2840 simplex->setObjective(&objective);
2843 simplex->solveMin();
2846 for (AnchorData *ad : variables)
2847 ad->sizeAtPreferred = ad->result - g_offset;
2855 qDeleteAll(preferredConstraints);
2856 qDeleteAll(preferredVariables);
2862
2863
2864
2865
2866
2867
2868bool QGraphicsAnchorLayoutPrivate::hasConflicts()
const
2870 QGraphicsAnchorLayoutPrivate *that =
const_cast<QGraphicsAnchorLayoutPrivate*>(
this);
2871 that->calculateGraphs();
2873 bool floatConflict = !m_floatItems[Qt::Horizontal].isEmpty() || !m_floatItems[Qt::Vertical].isEmpty();
2875 return graphHasConflicts[Qt::Horizontal] || graphHasConflicts[Qt::Vertical] || floatConflict;
2879void QGraphicsAnchorLayoutPrivate::dumpGraph(
const QString &name)
2881 QFile file(QString::fromLatin1(
"anchorlayout.%1.dot").arg(name));
2882 if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate))
2883 qWarning(
"Could not write to %ls", qUtf16Printable(file.fileName()));
2885 QString str = QString::fromLatin1(
"digraph anchorlayout {\nnode [shape=\"rect\"]\n%1}");
2886 QString dotContents = graph[Qt::Horizontal].serializeToDot();
2887 dotContents += graph[Qt::Vertical].serializeToDot();
2888 file.write(str.arg(dotContents).toLocal8Bit());
void setSizePolicy(QSizePolicy::Policy policy)
~QGraphicsAnchorPrivate()
QGraphicsAnchorLayoutPrivate * layoutPrivate
void setSpacing(qreal value)
QSimplexConstraint * constraint(const GraphPath &path) const
static auto createSlack(QSimplexConstraint *sizeConstraint, qreal interval, slackType type)
static AnchorData * createSequence(Graph< AnchorVertex, AnchorData > *graph, AnchorVertex *before, const QList< AnchorVertex * > &vertices, AnchorVertex *after)
static void applySizePolicy(QSizePolicy::Policy policy, qreal minSizeHint, qreal prefSizeHint, qreal maxSizeHint, qreal *minSize, qreal *prefSize, qreal *maxSize)
static AnchorVertex * replaceVertex_helper(AnchorData *data, AnchorVertex *oldV, AnchorVertex *newV)
static void shiftConstraints(const QList< QSimplexConstraint * > &constraints, qreal amount)
static qreal interpolate(const std::pair< QGraphicsAnchorLayoutPrivate::Interval, qreal > &factor, qreal min, qreal minPref, qreal pref, qreal maxPref, qreal max)
static std::pair< QGraphicsAnchorLayoutPrivate::Interval, qreal > getFactor(qreal value, qreal min, qreal minPref, qreal pref, qreal maxPref, qreal max)
QList< AnchorData * > getVariables(const QList< QSimplexConstraint * > &constraints)
virtual void updateChildrenSizes()
void refreshSizeHints(const QLayoutStyleInfo *styleInfo=nullptr)
QGraphicsLayoutItem * item
QGraphicsLayoutItem * m_item
virtual void updateChildrenSizes() override
bool calculateSizeHints()
bool secondForward() const
virtual void updateChildrenSizes() override
void calculateSizeHints()