Solved How to remove QGraphicsItem caught in a certain area on QGraphicsScene
-
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); // Добавляем элемент на графическую сцену }
-
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.
-
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 codevoid MoveItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { this->setCursor(QCursor(Qt::ArrowCursor)); Q_UNUSED(event); qDebug()<<"MoveItem"; }
-
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(); }
-
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.