2

I'm novice in programming and need a help.

I have a class Station, which contains X and Y fields:

Class Station {
int x
int y
...
}

All the stations are drawing on a QGraphicsScene as a circles and text:

this->scene.addEllipse(x1, y1, diam, diam, pen, QBrush(...));

I need a function getClickedStation, which is waiting for click on a QGraphicsScene, finding the circle and returns the station appropiate of its coordinates:

Station* getClickedStation(...) { ... }

Is there any ways to do it?

I've tried this just to get coordinates:

QList<QGraphicsItem*> listSelectedItems = scene.selectedItems();
QGraphicsItem* item = listSelectedItems.first();
ui->textBrowserMenu->append(QString::number(item->boundingRect().x()));
ui->textBrowserMenu->append(QString::number(item->boundingRect().y()));

but the program crashes with it...

Jablonski
  • 18,083
  • 2
  • 46
  • 47
Chernyavski.aa
  • 1,153
  • 1
  • 9
  • 16

1 Answers1

2

No, you do it wrong. I wrote small example. You should subclass QGraphicsScene and reimplement mousePressEvent and process clicks in it. For example:

*.h

#ifndef GRAPHICSSCENE_H
#define GRAPHICSSCENE_H

#include <QGraphicsScene>
#include <QPoint>
#include <QMouseEvent>
class GraphicsScene : public QGraphicsScene
{
    Q_OBJECT
public:
    explicit GraphicsScene(QObject *parent = 0);

protected:
    void mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent);
};

#endif // GRAPHICSSCENE_H

In cpp

void GraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
    //qDebug() << "in";
    if (mouseEvent->button() == Qt::LeftButton)
    {
        QGraphicsItem *item = itemAt(mouseEvent->scenePos(), QTransform());// it is your clicked item, you can do everything what you want. for example send it somewhere
        QGraphicsEllipseItem *ell = qgraphicsitem_cast<QGraphicsEllipseItem *>(item);
        if(ell)
        {
            ell->setBrush(QBrush(Qt::black));
        }
        else
            qDebug() << "not ell" << mouseEvent->scenePos();
        }

}

On the scene there are a few ellipses, when you click somewhere in scene we get item under cursor and check it is it ellipse for example. If is, then we set new background to it.

Main idea are itemAt method and qgraphicsitem_cast

Jablonski
  • 18,083
  • 2
  • 46
  • 47