Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. How to remove QGraphicsItem caught in a certain area on QGraphicsScene
Forum Updated to NodeBB v4.3 + New Features

How to remove QGraphicsItem caught in a certain area on QGraphicsScene

Scheduled Pinned Locked Moved Solved General and Desktop
5 Posts 3 Posters 769 Views 2 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.
  • M Offline
    M Offline
    Mikeeeeee
    wrote on last edited by
    #1

    Hi!
    I use this code.
    How to make sure that the object will be deleted if when I release the mouse button, it will be in a certain area on QGraphicsScene?

    MoveItem.h

    #ifndef MOVEITEM_H
    #define MOVEITEM_H
    
    #include <QObject>
    #include <QGraphicsItem>
    #include <QPainter>
    #include <QGraphicsSceneMouseEvent>
    #include <QDebug>
    #include <QCursor>
    #include <QApplication>
    
    class MoveItem : public QObject, public QGraphicsItem
    {
        Q_OBJECT
    public:
        explicit MoveItem(QObject *parent = 0);
        ~MoveItem();
    
    signals:
    
    private:
        QRectF boundingRect() const;
        void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
        void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
        void mousePressEvent(QGraphicsSceneMouseEvent *event);
        void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
    
    public slots:
    };
    
    #endif // MOVEITEM_H
    

    MoveItem.cpp

    #include "moveitem.h"
    
    MoveItem::MoveItem(QObject *parent) :
        QObject(parent), QGraphicsItem()
    {
    
    }
    
    MoveItem::~MoveItem()
    {
    
    }
    
    QRectF MoveItem::boundingRect() const
    {
        return QRectF (-30,-30,60,60);
    }
    
    void MoveItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
    {
        painter->setPen(Qt::black);
        painter->setBrush(Qt::green);
        painter->drawRect(-30,-30,60,60);
        Q_UNUSED(option);
        Q_UNUSED(widget);
    }
    
    void MoveItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
    {
        /* Устанавливаем позицию графического элемента
         * в графической сцене, транслировав координаты
         * курсора внутри графического элемента
         * в координатную систему графической сцены
         * */
        this->setPos(mapToScene(event->pos()));
        qDebug()<<"MoveItem";
    }
    
    void MoveItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
    {
        /* При нажатии мышью на графический элемент
         * заменяем курсор на руку, которая держит этот элемента
         * */
        this->setCursor(QCursor(Qt::ClosedHandCursor));
        Q_UNUSED(event);
    
        //удаление правой кнопкой мыши
        if (QApplication::mouseButtons() == Qt::RightButton)
        {
            qDebug()<<"delete";
            this->deleteLater();
        }
        qDebug()<<"MoveItem";
    }
    
    void MoveItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
    {
        /* При отпускании мышью элемента
         * заменяем на обычный курсор стрелку
         * */
        this->setCursor(QCursor(Qt::ArrowCursor));
        Q_UNUSED(event);
        qDebug()<<"MoveItem";
    }
    
    

    widget.h

    #ifndef WIDGET_H
    #define WIDGET_H
    
    #include <QWidget>
    #include <QGraphicsScene>
    
    #include <moveitem.h>
    
    namespace Ui {
    class Widget;
    }
    
    class Widget : public QWidget
    {
        Q_OBJECT
    
    public:
        explicit Widget(QWidget *parent = 0);
        ~Widget();
    
    private slots:
        void on_pushButton_clicked();
    
    private:
        Ui::Widget *ui;
        QGraphicsScene *scene;
    };
    
    #endif // WIDGET_H
    

    widget.cpp

    #include "widget.h"
    #include "ui_widget.h"
    
    /* Функция для получения рандомного числа
     * в диапазоне от минимального до максимального
     * */
    static int randomBetween(int low, int high)
    {
        return (qrand() % ((high + 1) - low) + low);
    }
    
    Widget::Widget(QWidget *parent) :
        QWidget(parent),
        ui(new Ui::Widget)
    {
        ui->setupUi(this);
    
        // Косметическая подготовка приложения
        this->resize(640,640);          // Устанавливаем размеры окна приложения
        this->setFixedSize(640,640);
    
        scene = new QGraphicsScene(this);   // Инициализируем графическую сцену
        scene->setItemIndexMethod(QGraphicsScene::NoIndex); // настраиваем индексацию элементов
    
        ui->graphicsView->resize(600,600);  // Устанавливаем размер graphicsView
        ui->graphicsView->setScene(scene);  // Устанавливаем графическую сцену в graphicsView
        ui->graphicsView->setRenderHint(QPainter::Antialiasing);    // Настраиваем рендер
        ui->graphicsView->setCacheMode(QGraphicsView::CacheBackground); // Кэш фона
        ui->graphicsView->setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
    
        scene->setSceneRect(0,0,500,500); // Устанавливаем размер сцены
    }
    
    Widget::~Widget()
    {
        delete ui;
    }
    
    void Widget::on_pushButton_clicked()
    {
        MoveItem *item = new MoveItem();        // Создаём графический элемент
        item->setPos(randomBetween(30, 470),    // Устанавливаем случайную позицию элемента
                     randomBetween(30, 470));
        scene->addItem(item);   // Добавляем элемент на графическую сцену
    }
    
    Pl45m4P 1 Reply Last reply
    0
    • M Mikeeeeee

      Hi!
      I use this code.
      How to make sure that the object will be deleted if when I release the mouse button, it will be in a certain area on QGraphicsScene?

      MoveItem.h

      #ifndef MOVEITEM_H
      #define MOVEITEM_H
      
      #include <QObject>
      #include <QGraphicsItem>
      #include <QPainter>
      #include <QGraphicsSceneMouseEvent>
      #include <QDebug>
      #include <QCursor>
      #include <QApplication>
      
      class MoveItem : public QObject, public QGraphicsItem
      {
          Q_OBJECT
      public:
          explicit MoveItem(QObject *parent = 0);
          ~MoveItem();
      
      signals:
      
      private:
          QRectF boundingRect() const;
          void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
          void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
          void mousePressEvent(QGraphicsSceneMouseEvent *event);
          void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
      
      public slots:
      };
      
      #endif // MOVEITEM_H
      

      MoveItem.cpp

      #include "moveitem.h"
      
      MoveItem::MoveItem(QObject *parent) :
          QObject(parent), QGraphicsItem()
      {
      
      }
      
      MoveItem::~MoveItem()
      {
      
      }
      
      QRectF MoveItem::boundingRect() const
      {
          return QRectF (-30,-30,60,60);
      }
      
      void MoveItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
      {
          painter->setPen(Qt::black);
          painter->setBrush(Qt::green);
          painter->drawRect(-30,-30,60,60);
          Q_UNUSED(option);
          Q_UNUSED(widget);
      }
      
      void MoveItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
      {
          /* Устанавливаем позицию графического элемента
           * в графической сцене, транслировав координаты
           * курсора внутри графического элемента
           * в координатную систему графической сцены
           * */
          this->setPos(mapToScene(event->pos()));
          qDebug()<<"MoveItem";
      }
      
      void MoveItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
      {
          /* При нажатии мышью на графический элемент
           * заменяем курсор на руку, которая держит этот элемента
           * */
          this->setCursor(QCursor(Qt::ClosedHandCursor));
          Q_UNUSED(event);
      
          //удаление правой кнопкой мыши
          if (QApplication::mouseButtons() == Qt::RightButton)
          {
              qDebug()<<"delete";
              this->deleteLater();
          }
          qDebug()<<"MoveItem";
      }
      
      void MoveItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
      {
          /* При отпускании мышью элемента
           * заменяем на обычный курсор стрелку
           * */
          this->setCursor(QCursor(Qt::ArrowCursor));
          Q_UNUSED(event);
          qDebug()<<"MoveItem";
      }
      
      

      widget.h

      #ifndef WIDGET_H
      #define WIDGET_H
      
      #include <QWidget>
      #include <QGraphicsScene>
      
      #include <moveitem.h>
      
      namespace Ui {
      class Widget;
      }
      
      class Widget : public QWidget
      {
          Q_OBJECT
      
      public:
          explicit Widget(QWidget *parent = 0);
          ~Widget();
      
      private slots:
          void on_pushButton_clicked();
      
      private:
          Ui::Widget *ui;
          QGraphicsScene *scene;
      };
      
      #endif // WIDGET_H
      

      widget.cpp

      #include "widget.h"
      #include "ui_widget.h"
      
      /* Функция для получения рандомного числа
       * в диапазоне от минимального до максимального
       * */
      static int randomBetween(int low, int high)
      {
          return (qrand() % ((high + 1) - low) + low);
      }
      
      Widget::Widget(QWidget *parent) :
          QWidget(parent),
          ui(new Ui::Widget)
      {
          ui->setupUi(this);
      
          // Косметическая подготовка приложения
          this->resize(640,640);          // Устанавливаем размеры окна приложения
          this->setFixedSize(640,640);
      
          scene = new QGraphicsScene(this);   // Инициализируем графическую сцену
          scene->setItemIndexMethod(QGraphicsScene::NoIndex); // настраиваем индексацию элементов
      
          ui->graphicsView->resize(600,600);  // Устанавливаем размер graphicsView
          ui->graphicsView->setScene(scene);  // Устанавливаем графическую сцену в graphicsView
          ui->graphicsView->setRenderHint(QPainter::Antialiasing);    // Настраиваем рендер
          ui->graphicsView->setCacheMode(QGraphicsView::CacheBackground); // Кэш фона
          ui->graphicsView->setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
      
          scene->setSceneRect(0,0,500,500); // Устанавливаем размер сцены
      }
      
      Widget::~Widget()
      {
          delete ui;
      }
      
      void Widget::on_pushButton_clicked()
      {
          MoveItem *item = new MoveItem();        // Создаём графический элемент
          item->setPos(randomBetween(30, 470),    // Устанавливаем случайную позицию элемента
                       randomBetween(30, 470));
          scene->addItem(item);   // Добавляем элемент на графическую сцену
      }
      
      Pl45m4P Offline
      Pl45m4P Offline
      Pl45m4
      wrote on last edited by
      #2

      @Mikeeeeee

      First remove the item from your GraphicsScene, if your delete-condition is true. After that, you can delete the item with delete / deleteLater(). You also could use QSharedPointers.


      If debugging is the process of removing software bugs, then programming must be the process of putting them in.

      ~E. W. Dijkstra

      1 Reply Last reply
      1
      • M Offline
        M Offline
        Mikeeeeee
        wrote on last edited by
        #3

        The removal works.
        As I understand it, first you need to get the coordinate on the field and the element on this coordinate in this part of the code

        void MoveItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
        {
            this->setCursor(QCursor(Qt::ArrowCursor));
            Q_UNUSED(event);
            qDebug()<<"MoveItem";
        }
        
        1 Reply Last reply
        0
        • M Offline
          M Offline
          Mikeeeeee
          wrote on last edited by
          #4
          void MoveItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
          {
              /* При отпускании мышью элемента
               * заменяем на обычный курсор стрелку
               * */
              if (event->scenePos().x() > 200
                      && event->scenePos().x() < 300
                      && event->scenePos().y() > 200
                      && event->scenePos().y() < 300)
              {this->deleteLater();;}
              this->setCursor(QCursor(Qt::ArrowCursor));
              Q_UNUSED(event);
              //qDebug()<<"MoveItem";
              //qDebug()<<"position:"<<event->pos();
              //qDebug()<<"position:"<<event->screenPos();
              qDebug()<<"position:"<<event->scenePos();
          }
          
          1 Reply Last reply
          0
          • SGaistS Offline
            SGaistS Offline
            SGaist
            Lifetime Qt Champion
            wrote on last edited by
            #5

            Hi,

            This typically something that should be done in the scene rather than the item. You might change the scene geometry such that the calculation here won't be valid anymore or apply that to other items.

            Interested in AI ? www.idiap.ch
            Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

            1 Reply Last reply
            1

            • Login

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