我有一個(gè)帶QLayout的QWidget,其上有一個(gè)QLabel. 我在標(biāo)簽上設(shè)置了一個(gè)QPixmap.無論用戶點(diǎn)擊圖像,我想繪制一個(gè)點(diǎn).我定義了mouseReleaseEvent(可以工作)和paintEvent(但是沒有繪制點(diǎn)).我已經(jīng)閱讀了所有類似的問題,但沒有一個(gè)解決方案適合我.有幫助嗎?我的相關(guān)代碼:
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()
解決方法: 當(dāng)您使用QtGui.QCursor.pos()獲取光標(biāo)相對(duì)于屏幕的坐標(biāo)時(shí),但是當(dāng)您想要繪制小部件時(shí),您必須位于小部件的坐標(biāo)中,因?yàn)樾〔考哂衜apToGlobal()方法:
self.mapFromGlobal(QtGui.QCursor.pos())
但在這種情況下還有另一種解決方案,您必須使用返回具有pos()方法中信息的mouseReleaseEvent的事件:
cursor_event.pos()
另一個(gè)問題是您創(chuàng)建的標(biāo)簽位于小部件上方,因此您看不到這些點(diǎn),最簡(jiǎn)單的方法是使用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_())
 來源:https://www./content-1-495401.html
|