首页 > 解决方案 > 使用 PyQt5,如何将点与线连接起来?

问题描述

我可以通过单击将点放在屏幕上,并且我想在每次选择点后将它们与线连接起来。我怎样才能添加这部分?

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_())

标签: pythonpyqtpyqt5

解决方案


您必须在前一点与当前点之间画一条线:

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)

推荐阅读