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')

person polyBrain    schedule 19.08.2010    source источник
comment
Отвечает ли это на ваш вопрос? Pyqt получает положение и значение пикселя при нажатии мыши нажмите на изображение   -  person sophros    schedule 10.04.2020


Ответы (1)


Я пробовал ваш код, я думаю, вы могли бы заставить его работать, если изменить

self.pixMapItem = self.local_scene.addPixmap( QPixmap(self.local_image) )

линия к

self.pixMapItem = QGraphicsPixmapItem(QPixmap(self.local_image), None, self.local_scene)

ниже приведена полная версия вашего кода, которая отлично сработала для меня:

import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import *
from PyQt4.QtCore import * 

class DrawImage(QMainWindow): 
    def __init__(self, parent=None):
        super(QMainWindow, self).__init__(parent)

        self.setWindowTitle('Select Window')
        self.local_image = QImage('image_file_name.JPG')

        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.pixMapItem = QGraphicsPixmapItem(QPixmap(self.local_image), None, self.local_scene)

        self.local_grview.setScene( self.local_scene )

        self.pixMapItem.mousePressEvent = self.pixelSelect

    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')


def main():
    app = QtGui.QApplication(sys.argv)
    form = DrawImage()
    form.show()
    app.exec_()

if __name__ == '__main__':
    main()

надеюсь, это поможет, с уважением

person serge_gubenko    schedule 29.08.2010
comment
Знаете ли вы, существует ли версия pixMapItem для QWidget? - person kthouz; 30.10.2016