2017-10-20 129 views
0

我有一個QLidget,上面有一個QLabel,上面有一個QLabel。 我在標籤上設置了一個QPixmap。無論用戶點擊圖像,我想畫一個點。我定義了mouseReleaseEvent(哪個工作)和paintEvent(但沒有繪製點)。我已閱讀所有類似的問題,但沒有任何解決方案適用於我。任何幫助?我的相關代碼:在QWidget上繪製QPixmap上的點(pyqt5)

class ImageScroller(QtWidgets.QWidget): 

    def __init__(self, img): 
     QtWidgets.QWidget.__init__(self) 
     main_layout = QtWidgets.QVBoxLayout() 
     self._image_label = QtWidgets.QLabel() 
     self._set_image(img) 
     main_layout.addWidget(self._image_label) 
     main_layout.addStretch() 
     self.setLayout(main_layout) 

    def _set_image(self, img): 
     img = qimage2ndarray.array2qimage(img) 
     qimg = QtGui.QPixmap.fromImage(img) 
     self._img_pixmap = QtGui.QPixmap(qimg) 
     self._image_label.show() 

    def paintEvent(self, paint_event): 
     painter = QtGui.QPainter(self) 
     painter.begin(self) 
     painter.setPen(QtGui.QPen(QtCore.Qt.red)) 
     pen = QtGui.QPen() 
     pen.setWidth(20) 
     painter.setPen(pen) 
     painter.setRenderHint(QtGui.QPainter.Antialiasing, True) 
     painter.drawPoint(300,300) 
     painter.drawLine(100, 100, 400, 400) 
     for pos in self.chosen_points: 
      painter.drawPoint(pos) 
     painter.end() 

    def mouseReleaseEvent(self, cursor_event): 
     self.chosen_points.append(QtGui.QCursor().pos()) 
     self.update() 
+0

哪裏是你'mouseReleaseEvent'實現?你有沒有調用'update()'方法? – eyllanesc

+0

是的,我有。我使用mouseReleaseEvent實現編輯了帖子 –

回答

0

當您使用QtGui.QCursor.pos()越來越光標的座標相對於屏幕,但是當你要畫你必須在widget的座標的部件,它的部件有mapToGlobal()方法:

self.mapFromGlobal(QtGui.QCursor.pos()) 

但在這種情況下,有另一種解決方案,您必須使用返回mouseReleaseEvent已在pos()方法的信息事件:

cursor_event.pos() 

另一個問題是您創建的標籤位於小部件上方,因此您看不到點,最簡單的方法是直接使用drawPixmap()方法繪製QPixmap

完整代碼:

from PyQt5 import QtWidgets, QtGui, QtCore 


class ImageScroller(QtWidgets.QWidget): 
    def __init__(self): 
     self.chosen_points = [] 
     QtWidgets.QWidget.__init__(self) 
     self._image = QtGui.QPixmap("image.png") 

    def paintEvent(self, paint_event): 
     painter = QtGui.QPainter(self) 
     painter.drawPixmap(self.rect(), self._image) 
     pen = QtGui.QPen() 
     pen.setWidth(20) 
     painter.setPen(pen) 
     painter.setRenderHint(QtGui.QPainter.Antialiasing, True) 
     painter.drawPoint(300, 300) 
     painter.drawLine(100, 100, 400, 400) 
     for pos in self.chosen_points: 
      painter.drawPoint(pos) 

    def mouseReleaseEvent(self, cursor_event): 
     self.chosen_points.append(cursor_event.pos()) 
     # self.chosen_points.append(self.mapFromGlobal(QtGui.QCursor.pos())) 
     self.update() 


if __name__ == '__main__': 
    import sys 

    app = QtWidgets.QApplication(sys.argv) 
    w = ImageScroller() 
    w.resize(640, 480) 
    w.show() 
    sys.exit(app.exec_()) 

enter image description here