Search code examples
qtpositionqgraphicsitemqgraphicsscene

Can't get positions of QGraphicsItems in scene


I am trying to get the positions of the graphicsitems in the scene. But their QPointF value always remains (0,0).

I am painting when mouse-click event occurs. On debugging scene->items(), I get

(QGraphicsItem(this =0x22edff0, parent =0x0, pos =QPointF(0, 0) , z = 0 , flags = ( ) ) )

for each graphics item in scene but with different memory address.

This is my mainwindow.cpp code:

#include "mainwindow.h"
#include <QDebug>
MainWindow::MainWindow()
{
  scene = new QGraphicsScene;
  view = new QGraphicsView;
  view->setScene(scene);
  button = new QPushButton("Item");
  QGridLayout  *layout = new QGridLayout;
  layout->addWidget(button);
  layout->addWidget(view);
  setLayout(layout);
  connect(button, SIGNAL(clicked()), this, SLOT(createItem()));
}

void MainWindow::createItem()
{
  myEntity = new Item;
  scene->addItem(myEntity);
  count_items();
}

void MainWindow::count_items()
{
  qDebug() << scene->items().count();
  qDebug() << scene->items();
}

MainWindow::~MainWindow()
{}

This is my item.cpp code:

#include "item.h"
Item::Item()
{
  ClickFlag = true;
  PaintFlag = false;
} 
Item::~Item(){}

QRectF Item::boundingRect() const
{
  // outer most edges
  return QRectF(0,0,1450,1400);
}
void Item::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
  if(event->button()==Qt::LeftButton){
    if(ClickFlag){
        x = event->pos().x();
        y = event->pos().y();
        PaintFlag = true;
        ClickFlag = false;
       }
   }
}

void Item::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
                              QWidget *widget)
{
  if(PaintFlag){
    QPen paintPen;
    paintPen.setWidth(4);
    pt.setX(x);
    pt.setY(y);
    painter->setPen(paintPen);
    painter->drawPoint(x,y);
    update();              
  }
}

I can't seem to find the position of these items correctly.


Solution

  • This task is supposed to be implemented in another way. For example:

    1. Use QGraphicsScene::addEllipse to add small ellipse (which will look like a point) to the scene. Save the pointer to it in a class variable. The ellipse itself should be at the center, e.g. (-1, -1, 2, 2).
    2. Reimplement QGraphicsScene::mousePressEvent, detect mouse clicks and call setPos for the ellipse item (or add new ellipse each time and immediately call setPos if you need multiple points).
    3. Use QGraphicsItem::pos to get previously set positions.

    Reimplementing QGraphicsItem::paint is usually an over-complication. Qt have plenty of item classes for all common needs. Just build your scene from geometric primitives, pixmaps, etc.