Pyqt获取鼠标点击图像时的像素位置和值
在 pixMapItem 上覆盖鼠标事件对我来说不起作用; pixMapItem 未检测到鼠标单击事件。这是我的代码:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class DrawImage( QMainWindow ):
def __init__(self, path):
QMainWindow.__init__(self)
self.setWindowTitle('Select Window')
self.local_image = QImage(path)
self.local_grview = QGraphicsView()
self.setCentralWidget( self.local_grview )
self.local_scene = QGraphicsScene()
self.image_format = self.local_image.format()
self.pixMapItem = self.local_scene.addPixmap( QPixmap(self.local_image) )
self.local_grview.setScene( self.local_scene )
self.pixMapItem.mousePressEvent = self.pixelSelect
self.show()
sys.exit(app.exec_())
def pixelSelect( self, event ):
print 'hello'
position = QPoint( event.pos().x(), event.pos().y())
color = QColor.fromRgb(self.local_image.pixel( position ) )
if color.isValid():
rgbColor = '('+str(color.red())+','+str(color.green())+','+str(color.blue())+','+str(color.alpha())+')'
self.setWindowTitle( 'Pixel position = (' + str( event.pos().x() ) + ' , ' + str( event.pos().y() )+ ') - Value (R,G,B,A)= ' + rgbColor)
else:
self.setWindowTitle( 'Pixel position = (' + str( event.pos().x() ) + ' , ' + str( event.pos().y() )+ ') - color not valid')
Overwriting mouse event on pixMapItem didn't work for me ; the mouse click event is not detected by the pixMapItem. Here is my code :
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class DrawImage( QMainWindow ):
def __init__(self, path):
QMainWindow.__init__(self)
self.setWindowTitle('Select Window')
self.local_image = QImage(path)
self.local_grview = QGraphicsView()
self.setCentralWidget( self.local_grview )
self.local_scene = QGraphicsScene()
self.image_format = self.local_image.format()
self.pixMapItem = self.local_scene.addPixmap( QPixmap(self.local_image) )
self.local_grview.setScene( self.local_scene )
self.pixMapItem.mousePressEvent = self.pixelSelect
self.show()
sys.exit(app.exec_())
def pixelSelect( self, event ):
print 'hello'
position = QPoint( event.pos().x(), event.pos().y())
color = QColor.fromRgb(self.local_image.pixel( position ) )
if color.isValid():
rgbColor = '('+str(color.red())+','+str(color.green())+','+str(color.blue())+','+str(color.alpha())+')'
self.setWindowTitle( 'Pixel position = (' + str( event.pos().x() ) + ' , ' + str( event.pos().y() )+ ') - Value (R,G,B,A)= ' + rgbColor)
else:
self.setWindowTitle( 'Pixel position = (' + str( event.pos().x() ) + ' , ' + str( event.pos().y() )+ ') - color not valid')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你可以让它工作
我已经尝试过你的代码,我相信如果将下面的行
更改为对我来说效果很好的代码的完整版本,
:希望这有帮助,问候
I've tried your code, I believe you could get it working if change
line to
below is a full version of your code which worked fine for me:
hope this helps, regards