How to show pixel position and color from a QGraphicsPixmapItem

百般思念 提交于 2019-12-04 10:36:27

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

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

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