Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Make a QGraphicsItem child moving discretely.



  • Hi, everyone. I have my QGraphicsItem child for flowchart diagram with this flags: @setFlag(QGraphicsItem::ItemIsMovable, true);
    setFlag(QGraphicsItem::ItemIsSelectable, true);@
    But I need to move it discretely, with 20px step. My first idea is
    @void DiagramItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) {
    QPoint pos = this->pos().toPoint();
    int rem = pos.x() % 20;
    if (rem > 10) {
    pos.rx() += 20 - rem;
    } else {
    pos.rx() -= rem;
    }
    rem = pos.y() % 20;
    if (rem > 10) {
    pos.ry() += 20 - rem;
    } else {
    pos.ry() -= rem;
    }
    this->setPos(pos);
    }@
    It works... but with strange effects. Am I doing it right? Or there is better solution?

    /******** SOLVED *********/

    QGraphicsItem::mouseReleaseEvent(event) call must be in mouseReleaseEvent.



  • Hi, I think that you must put that code in the mouseMoveEvent () method.



  • [quote author="issam" date="1381662865"]Hi, I think that you must put that code in the mouseMoveEvent () method. [/quote]
    Unfortunately, it crushes program.
    @void DiagramItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event) {
    DiagramItem::mouseMoveEvent(event);

    QPoint pos = this->pos().toPoint();
    int rem = pos.x() % 20;
    if (rem > 10) {
        pos.rx() += 20 - rem;
    } else {
       pos.rx() -= rem;
    }
    rem = pos.y() % 20;
    if (rem > 10) {
        pos.ry() += 20 - rem;
    } else {
        pos.ry() -= rem;
    }
    this->setPos(pos);
    

    }@


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    You are calling DiagramItem::mouseMoveEvent inside DiagramItem::mouseMoveEvent so it creates an infinite recursion. You must replace that with QGraphicsItem::mouseMoveEvent (i didn't check what the code does, it's just to help you get further)


Log in to reply