How to show the position and color of a pixel from a QGraphicsPixmapItem object

I am developing my own widget with QGraphicsScene / View, and I have no previous experience.

A custom widget is an image viewer that should track the movement of the mouse and send him (her) a signal from the parent dialog / window. The signal (s) will be the pixel position under the mouse cursor and color (in RGB). The status bar will use this information.

I am using QGraphicsPixmapItem to display a loading image from a file in a scene.

Thanks.

+4
source share
2 answers

First of all, you must implement mouseMoveEvent in your custom element. In this function, you can easily get the mouse position calling the pos function. You can get the rgb value if you convert the pixmap element to an image and call the pixel function. You should consider storing the QImage variable as a member to avoid multiple conversions. Finally, you must emit your own signal. Code example:

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

Please note that QGraphicsItems does not inherit from QObject , therefore, signals / slots are not supported by default. You must inherit from QObject . This is what QGraphicsObject does. Last but not least, I would suggest enabling mouse tracking on your QGraphicsView

+5
source

I found that the mouseMoveEvent approach does not work at all, at least not with Qt5.5. However, turning on hover events using setAcceptHoverEvents (true) in the element and re-executing the hoverMoveEvent event (QGraphicsSceneHoverEvent *) worked like a charm. Qt docs on mouseMoveEvent () provide a key:

"If you received this event, you can be sure that this element also received a mouse click event."

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

+1
source

Source: https://habr.com/ru/post/1395049/


All Articles