Thomas
Thomas

Reputation: 1706

In Qt tell the main class that an item was clicked

Situation:

I have a Dialog class in QT on which I draw a raster of squares. The squares are implemented in the MySquare class (MySquare: QGraphicsItem).

Inside the MySquare there are a number of functions (mysquare.h protected: )

    void mousePressEvent(QGraphicsSceneMouseEvent *event);
    void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
    void keyPressEvent(QKeyEvent *event);
    void mouseMoveEvent(QGraphicsSceneMouseEvent *event);

When I click on a square it gives me the relative coordinates of the square using the following function.

void MySquare::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    update();
    QGraphicsItem::mousePressEvent(event);
    qDebug() << "mouse Pressed";
    qDebug() << "coordinates:";
    qDebug() << "X:"<< x/w << " Y:" << y/h ;
}

enter image description here

Where x and y are the x and y position in the raster and w and h stand for width and height

However my question is how can I let my Dialog class know what square was clicked on?

Upvotes: 2

Views: 580

Answers (1)

Bart van Ingen Schenau
Bart van Ingen Schenau

Reputation: 15768

You can communicate between MySquare and and your Dialog by means of the signal/slot mechanism of Qt. When a square gets clicked, it emits a signal, and the Dialog has a slot that is connected to that signal.

To identify which square sent the signal, there are several possibilities:

  • The coordinates of the square are passed along in the signal
  • The this pointer of the MySquare that emits the signal is passed along
  • In the slot, you can use the sender function to determine who emitted the signal.

Upvotes: 1

Related Questions