How to show pixel position and color from a QGraphicsPixmapItem

◇◆丶佛笑我妖孽 提交于 2019-12-06 05:51:32

问题


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.


回答1:


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(), mousePostion.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




回答2:


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



来源:https://stackoverflow.com/questions/9163271/how-to-show-pixel-position-and-color-from-a-qgraphicspixmapitem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!