如何显示 QGraphicsPixmapItem 中的像素位置和颜色
我正在使用 QGraphicsScene/View 开发一个自定义小部件,但我之前没有任何经验。
自定义小部件是一个图像查看器,需要跟踪鼠标移动并向其父对话框/窗口发送信号。信号将是鼠标光标下像素的位置及其颜色(RGB)。状态栏将使用该信息。
我使用 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您必须实现
mouseMoveEvent
在您的自定义项目中。在此函数中,您可以通过调用
pos
函数。如果将项目的像素图转换为图像并调用像素
函数。您应该考虑将 QImage 存储为成员变量,以避免多次转换。最后你必须发出一个自定义信号。示例代码如下:注意,
QGraphicsItems
不继承自QObject
,因此默认情况下不支持信号/槽。您还应该继承QObject
。这就是QGraphicsObject
的作用。最后但并非最不重要的一点是,我建议您启用 鼠标跟踪 在你的QGraphicsView
上First of all you have to implement the
mouseMoveEvent
in your custom item. In this function you can easily get the mouse position calling thepos
function. You can get the rgb value if you transform the item's pixmap into image and call thepixel
function. You should consider storing theQImage
as member variable in order to avoid multiple transformations. Finally you have to emit a custom signal. Sample code follows:Notice that
QGraphicsItems
do not inherit fromQObject
so by default signals/slots are not supported. You should inherit fromQObject
as well. This is whatQGraphicsObject
does. Last but not least I would advise you to enable mouse tracking on yourQGraphicsView
我发现 mouseMoveEvent 方法根本不起作用,至少在 Qt5.5 中不起作用。然而,在项目上使用 setAcceptHoverEvents(true) 启用悬停事件并重新实现hoverMoveEvent(QGraphicsSceneHoverEvent * event) 非常有效。
mouseMoveEvent() 上的 Qt 文档提供了线索:
“如果您确实收到此事件,则可以确定该项目也收到了鼠标按下事件”
http://doc.qt.io/qt-5.5/qgraphicsitem.html#mouseMoveEvent
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