Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. QML and Qt Quick
  4. PDFWriter : offset after element rotation
Qt 6.12 LTS is out! See what's new in the release blog

PDFWriter : offset after element rotation

Scheduled Pinned Locked Moved Unsolved QML and Qt Quick
2 Posts 1 Posters 90 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • GilboonetG Offline
    GilboonetG Offline
    Gilboonet
    wrote last edited by
    #1

    Capture d’écran 2026-12-04 à 10.29.05.jpeg
    Hello, my application is a graphical editor where the user moves and rotates 2D elements in order to create a printable/cutable pattern that I export to PDF. When I only move elements it works fine, but as soon as I rotate an element, its PDF output has an offset. On the screen capture, I rotated the element with the big '27' and it has now an offset. My pdf export code is straightforward, but maybe I forgot something. QML Elements are dragged and rotated using a MouseArea with drag.target = their parent and a WheelHandler with "rotation" as property, then their position X and Y and rotation angle are stored using on..Changed to the DataModel. The PDF output code uses that same datamodel. On my previous version using Widgets I used my own code for element drag and rotation, so it was easier to obtain WYSIWYG, but with QML that handles all that by itself, I don't see where I can intervene to correct the offset due to rotation.
    Here's my export to PDF code :

    void Donnees::exportePDF() {
        QBuffer buffer;
        buffer.open(QIODevice::WriteOnly);
        QPdfWriter pdfWriter(&buffer);
        pdfWriter.setPageSize(QPageSize(QPageSize::A4));
        QPainter painter(&pdfWriter);
        painter.setWindow(0, 0, 210, 297);
        painter.setViewport(0, 0, 9727, 13757);
        QPen pen(Qt::red, 0.2);
        pen.setJoinStyle(Qt::SvgMiterJoin);
        pen.setCapStyle(Qt::SquareCap);
        painter.setPen(pen);
        QPen penPli = pen;
        penPli.setColor(Qt::black);
        penPli.setStyle(Qt::DashLine);
        QList<qreal> dashes;
        dashes << 8 << 16;
        penPli.setDashPattern(dashes);
    
        QFont pf("Arial");
        pf.setPointSizeF(0.4f);
        painter.setFont(pf);
        QFontMetrics fm = painter.fontMetrics();
    
        // tri des pièces par page
        std::vector<int> pp;
        int pMin = 1000, pMax = 0;
        for (int i = 0; i < m_pieces->rowCount(); i++) {
            int np = pageCalcNum((int)m_pieces->getPosX(i), (int)m_pieces->getPosY(i));
            pp.push_back(np);
        }
    
        std::sort(pp.begin(), pp.end());
        auto it = std::unique(pp.begin(), pp.end());
        pp.erase(it, pp.end());
    
        int n = 0;
        for (const auto np : pp) {
            bool npok = false;
            for (int i = 0; i < m_pieces->rowCount(); i++) {
                int x = (int)m_pieces->getPosX(i);
                int y = (int)m_pieces->getPosY(i);
                int npi = pageCalcNum(x, y);
                if (npi == np) {
                    if (n  > 0) {
                        if (!npok) {
                            pdfWriter.newPage();
                            npok = true;
                        }
                    }
    
                    QPolygonF p = contourToPolygon(m_pieces->getContour(i));
                    QPointF c = centroid(p);
                    painter.save();
                    painter.translate(c.x() + (x % 210), c.y() + (y % 297));
                    painter.rotate(m_pieces->getAngle(i));
                    painter.translate(-c.x(), -c.y());
                    painter.setPen(pen);
                    painter.drawPolygon(p);
    
                    QString sPlis = m_pieces->getPlis(i);
                    QStringList plis1 = sPlis.split(";");
                    QList<QLine> pli;
                    for (const auto& pl : std::as_const(plis1)) {
                        QStringList plis = pl.split(" ");
                        pli.push_back(QLine(
                            plis[0].toInt(), plis[1].toInt(),
                            plis[2].toInt(), plis[3].toInt()
                        ));
                    }
                    painter.setPen(penPli);
                    painter.drawLines(pli);
    
    
                    std::vector<NTxt> nT = m_pieces->getnT(i);
                    for (const auto nTi : nT) {
                        QString txt = QString("%1").arg(nTi.num);
                        int dh = fm.horizontalAdvance(txt);
                        painter.save();
                        painter.translate(nTi.x, nTi.y);
                        painter.rotate(nTi.a - 180);
                        painter.drawText(- dh/2, -2, txt);
                        painter.restore();
                    }
                    painter.restore();
                }
            }
            n++;
        }
    
        painter.end();
        QByteArray pdfData = buffer.data();
        QDir::setCurrent(QDir::homePath().append("/Documents"));
        QFileDialog::saveFileContent(pdfData, "monProjet.pdf");
    }
    
    
    1 Reply Last reply
    0
    • GilboonetG Offline
      GilboonetG Offline
      Gilboonet
      wrote last edited by
      #2

      Apparently, the gap lies into the QML code that uses property bindings. when an element is rotated, I tried to also change its position, but if I do so all elements become jammed, so I tried to use a bool to prevent X and Y OnChanged to fire during such updates, but without any effect. I also tried to add a C++ member to change at the same time X, Y and Rotation, but it still doesn't work. Maybe do I need to momentarily disable the property binding (thing that I'm not sure can be done).
      here's my QML Code

                          MouseArea { // DRAG pour déplacer la vue
                              anchors.fill : parent
                              acceptedButtons: Qt.LeftButton
                              drag.target: vue2D
                              cursorShape: Qt.ArrowCursor
                          }
      
                          Repeater { // UNE PIECE COMPLETE
                              model: pieces
                              delegate : Shape { id : pieceRoot
                                  containsMode: Shape.FillContains
                                  DragHandler {cursorShape: Qt.ClosedHandCursor}
                                  states: [
                                           State {
                                               name: ""
                                               PropertyChanges { pieceSP.strokeWidth: -1 }
                                           },
                                           State {
                                               name: "selected"
                                               PropertyChanges { pieceSP.strokeWidth: 2 }
                                           }
                                       ]
                                  ShapePath { id: pieceSP // POLYGONE FORMANT LA PIECE
                                      fillRule: ShapePath.WindingFill
                                      fillColor: iToC[coul]
                                      strokeColor:"yellow"
                                      PathSvg { path: contour }
                                  }
      
                                  property real tmpPosX : posX
                                  property real tmpPosY : posY
                                  property real tmpAngle : angle
                                  property bool rotEnCours : false
      
                                  x: tmpPosX
                                  y: tmpPosY
                                  rotation: tmpAngle
      
                                  onXChanged: {
                                      if (!rotEnCours)
                                          pieces.setPosX(index, x);
                                  }
                                  onYChanged: {
                                      if (!rotEnCours)
                                          pieces.setPosY(index, y);
                                  }
                                  onRotationChanged: {
                                      rotEnCours = true;
                                      pieces.setAngle(index, rotation);
                                      rotEnCours = false;
                                      // pieces.setPosX(index, x);
                                      // pieces.setPosY(index, y);
                                  }
      
                                  Text { // NUMERO DE LA PIECE (aka n° de sa première facette)
                                      font.pointSize: 10
                                      color: "black"
                                      text: num
                                      horizontalAlignment: Qt.AlignHCenter
                                      verticalAlignment: Qt.AlignVCenter
                                      x: centre.x - (contentWidth /2)
                                      y: centre.y - (contentHeight /2)
                                  }
                                  Repeater { // CHAQUE NUMERO D'ARETE (ENTRE 2 FACETTES)
                                      model: ListModel {id: tliste}
                                      Text {
                                          text: model.txt
                                          font.pointSize: 6
                                          horizontalAlignment: Qt.AlignHCenter
                                          verticalAlignment: Qt.AlignVCenter
                                          color: "#1500ff"
                                          transform: [
                                              Translate { x: 0; y: -7 },
                                              Rotation { angle: 180+model.a },
                                              Translate { x: model.x; y: model.y }
                                          ]
                                      }
                                  }
                                  Component.onCompleted: creeNums(tliste, nTxt)
      
                                  Repeater { // CHAQUE LIGNE DE CONTOUR
                                      model: ListModel {id: cliste}
                                      Shape {
                                          containsMode: Shape.FillContains
                                          HoverHandler { id: mouseCont
                                              cursorShape: Qt.CrossCursor
                                          }
                                          property int f1: model.f1
                                          property int f2: model.f2
                                          property var c: mouseCont.hovered ? "yellow" : "black"
                                          ShapePath {
                                              strokeWidth: 0.25
                                              strokeColor: c
                                              fillColor: c
                                              startX: model.x1
                                              startY: model.y1
                                              PathPolyline {
                                                  path: [
                                                      Qt.point(model.x2, model.y2),
                                                      Qt.point(model.x3, model.y3),
                                                      Qt.point(model.x4, model.y4),
                                                      Qt.point(model.x1, model.y1),
                                                  ]
                                              }
                                              pathHints: ShapePath.PathSolid || ShapePath.PathLinear || ShapePath.PathConvex;
                                          }
                                          TapHandler {
                                              onTapped: {
                                                  faces.attache(num, f1, f2);
                                              }
                                          }
                                      }
                                      Component.onCompleted: creeLignes(lcont, cliste)
                                  }
      
                                  Repeater { // CHAQUE LIGNE DE PLI
                                      model: ListModel {id: pliste}
                                      Shape {
                                          containsMode: Shape.FillContains
                                          HoverHandler { id: mousePlis
                                              cursorShape: Qt.CrossCursor
                                          }
                                          property int f1: model.f1
                                          property int f2: model.f2
                                          property var c: mousePlis.hovered ? "red" : "white"
                                          ShapePath {
                                              strokeWidth: 0.25
                                              strokeColor: c
                                              fillColor: c
                                              startX: model.x1
                                              startY: model.y1
                                              PathPolyline {
                                                  path: [
                                                      Qt.point(model.x2, model.y2),
                                                      Qt.point(model.x3, model.y3),
                                                      Qt.point(model.x4, model.y4),
                                                      Qt.point(model.x1, model.y1),
                                                  ]
                                              }
                                              pathHints: ShapePath.PathSolid || ShapePath.PathLinear || ShapePath.PathConvex;
                                          }
                                          TapHandler {
                                              onTapped: {
                                                  faces.detache(num, f1, f2);
                                              }
                                          }
                                      }
                                      Component.onCompleted: creeLignes(plis, pliste)
                                  }
      
                                  WheelHandler { // ALT + roulette pour tourner la pièce
                                      acceptedModifiers: Qt.AltModifier
                                      property: "rotation"
                                      //rotationScale: 0.25
                                  }
      
                                  /*MouseArea { // clic gauche sur une pièce -> selection / déselection
                                      anchors.fill: pieceRoot
                                      acceptedButtons: Qt.LeftButton
                                      onClicked: {
                                          pieceRoot.state = pieceRoot.state === "" ? "selected" : "";
                                      }
                                  }*/
                              }
                          }
      
      1 Reply Last reply
      0

      • Login

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • Users
      • Groups
      • Search
      • Get Qt
      • Unsolved