Symbiosoft
Symbiosoft

Reputation: 4711

How to show pixel position and color from a QGraphicsPixmapItem

I'm developing a custom widget with QGraphicsScene/View and I have no prior experience with it.

The custom widget is an image viewer that needs to track mouse movement and send signal(s) to it's parent dialog / window. The signal(s) will be the position of the pixel under the mouse cursor and it's color (in RGB). A status bar will use that information.

I use a QGraphicsPixmapItem to display the image I load from a file in the scene.

Thanks.

Upvotes: 4

Views: 5836

Answers (2)

pnezis
pnezis

Reputation: 12331

First of all you have to implement the mouseMoveEvent in your custom item. In this function you can easily get the mouse position calling the pos function. You can get the rgb value if you transform the item's pixmap into image and call the pixel function. You should consider storing the QImage as member variable in order to avoid multiple transformations. Finally you have to emit a custom signal. Sample code follows:

void MyPixmapItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event)
{
    QPointF mousePosition = event->pos(); 
    QRgb rgbValue = pixmap().toImage().pixel(mousePosition.x(), mousePosition.y());
    
    emit currentPositionRgbChanged(mousePosition, rgbValue);
}

Notice that QGraphicsItems do not inherit from QObject so by default signals/slots are not supported. You should inherit from QObject as well. This is what QGraphicsObject does. Last but not least I would advise you to enable mouse tracking on your QGraphicsView

Upvotes: 5

lemon339
lemon339

Reputation: 17

I found the mouseMoveEvent approach to not work at all, at least not with Qt5.5. However, enabling hover events with setAcceptHoverEvents(true) on the item and reimplementing hoverMoveEvent(QGraphicsSceneHoverEvent * event) worked like a charm. The Qt docs on mouseMoveEvent() provide the clue:

"If you do receive this event, you can be certain that this item also received a mouse press event"

http://doc.qt.io/qt-5.5/qgraphicsitem.html#mouseMoveEvent

Upvotes: 1

Related Questions