我可以通过单击在屏幕上放置点,并且希望在每次选择点后将它们与线连接起来。如何添加这部分?
import sys
from PyQt5 import QtWidgets, QtGui, QtCore, uic
class GUI(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setFixedSize(self.size())
self.show()
self.points = QtGui.QPolygon()
def mousePressEvent(self, e):
self.points << e.pos()
self.update()
def paintEvent(self, ev):
qp = QtGui.QPainter(self)
qp.setRenderHint(QtGui.QPainter.Antialiasing)
pen = QtGui.QPen(QtCore.Qt.black, 5)
brush = QtGui.QBrush(QtCore.Qt.black)
qp.setPen(pen)
qp.setBrush(brush)
for i in range(self.points.count()):
print(self.points.point(i))
qp.drawEllipse(self.points.point(i), 5, 5)
# qp.drawPoints(self.points)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = GUI()
sys.exit(app.exec_())
答案 0 :(得分:0)
您必须在上一个点和当前点之间画一条线:
def paintEvent(self, ev):
qp = QtGui.QPainter(self)
qp.setRenderHint(QtGui.QPainter.Antialiasing)
pen = QtGui.QPen(QtCore.Qt.black, 5)
brush = QtGui.QBrush(QtCore.Qt.black)
qp.setPen(pen)
qp.setBrush(brush)
lp = QtCore.QPoint()
for i in range(self.points.count()):
cp = self.points.point(i)
qp.drawEllipse(cp, 5, 5)
if not lp.isNull():
qp.drawLine(lp, cp)
lp = cp
可以使用QPainterPath完成另一个类似的解决方案:
class GUI(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.path = QtGui.QPainterPath()
self.setFixedSize(self.size())
self.show()
def mousePressEvent(self, e):
if self.path.elementCount() == 0:
self.path.moveTo(e.pos())
else:
self.path.lineTo(e.pos())
self.update()
super().mousePressEvent(e)
def paintEvent(self, ev):
qp = QtGui.QPainter(self)
qp.setRenderHint(QtGui.QPainter.Antialiasing)
pen = QtGui.QPen(QtCore.Qt.black, 5)
qp.setPen(pen)
qp.drawPath(self.path)
brush = QtGui.QBrush(QtCore.Qt.black)
qp.setBrush(brush)
for i in range(self.path.elementCount()):
e = self.path.elementAt(i)
qp.drawEllipse(QtCore.QPoint(e.x, e.y), 5, 5)