Search code examples
qtsignals-slotsqgraphicsview

How to Delete Item from Graphics scene from Main Window Tool Box?


In Graphic View set the scene, In Graphic scene(subclass od QGraphicscene) class added Delete item slot.In scene class by delete key i able to delete item but when i call from main window it wont delete item . i am getting call in Delete item slot but selectedItems = 0. what may be causing problem?
In Graphic scene class

    void GraphicScene::DeleteItems()//Delete Item slot in scene class
    {
       qDebug()<<"delete items"<< selectedItems().count();
       foreach(QGraphicsItem* item, selectedItems())
       {
            removeItem(item);
            delete item;
       }
    }

    void GraphicScene::keyReleaseEvent(QKeyEvent * keyEvent)// Delete key works fine
    {

         if (selectedItems().isEmpty())
              return;
         if(keyEvent->key() == Qt::Key_Delete)
         {
            DeleteItems();
         }
   }    

In MainWindow class

    MainWindow::MainWindow(QWidget *parent) 
    {
      addToolBar(Qt::TopToolBarArea, mpEditToolbar = new 
                     QToolBar());
      DeleteAction = new QAction(QIcon(":/images/delete.png"),tr("Object 
                                       &Delete"), this);
      DeleteAction->setStatusTip(tr("Delete item"));
      connect(DeleteAction,SIGNAL(triggered()),mpGraphView  , 
              SIGNAL(DeleteObject())); // grpah view connecting to delete slot
      mpEditToolbar->addAction(DeleteAction);
    }

When i do from delete key works fine its not working with tool box delete action. what is the problem?


Solution

  • In Main Window class have private members of GraphicsView and GraphicScene class(subclass) so that it will be easy to call slot.

      class MainWindow : public QMainWindow
      {
        Q_OBJECT
    
        public:
            explicit MainWindow(QWidget *parent = 0);
            ~MainWindow();
    
        private:
            GraphFrame              *mpGraphFrame;
            GraphicScene            *mpScene;
       }  
    

    MainWindow.cpp
    Connect should be in where you creating GraphicScene Object

     MainWindow::MainWindow(QWidget *parent) 
     {
      addToolBar(Qt::TopToolBarArea, mpEditToolbar = new 
                     QToolBar());
      DeleteAction = new QAction(QIcon(":/images/delete.png"),tr("Object 
                                       &Delete"), this);
      DeleteAction->setStatusTip(tr("Delete item"));
      connect(DeleteAction,SIGNAL(triggered()),mpGraphScene  , 
              DeleteItems(); 
      mpEditToolbar->addAction(DeleteAction);
     }