猿问

如何在Python中使用PyQt5绘制折线?

我想用鼠标事件绘制折线。但我无法通过单击或选择笔类型来设置终结点。我想画线性线,但是当我写这段代码时,它只显示点而不是画一条线。这是我的代码:


import sys

from PyQt5 import QtWidgets, QtCore

from PyQt5.QtGui import QPainter, QBrush, QColor, QPen, QPainterPath

from PyQt5.QtWidgets import QLabel, QGraphicsScene, QGraphicsView



class MyWidget(QtWidgets.QWidget):

def __init__(self):

    super().__init__()

    self.begin = QtCore.QPoint()

    self.end = QtCore.QPoint()

    self.beginList = []

    self.endList = []

    self.initUI()


def initUI(self):

    self.setGeometry(200, 200, 1000, 500)

    self.label = QLabel(self)

    self.label.resize(500, 40)

    self.show()


def paintEvent(self, event):

    qp = QPainter(self)

    for i,j in zip(self.beginList, self.endList):

        qp.drawLines(QtCore.QLineF(i,j))



def mouseMoveEvent(self, event):

    self.begin = event.pos()

    self.end = event.pos()

    self.beginList.append(self.begin)

    self.endList.append(self.end)

    self.label.setText('Coordinates: ( %d : %d )' % (event.x(), event.y()))

    self.update()


def mouseReleaseEvent(self, event):

    self.begin = event.pos()

    self.end = event.pos()


if __name__ == '__main__':

app = QtWidgets.QApplication(sys.argv)

window = MyWidget()

window.resize(800,600)

sys.exit(app.exec_())


慕虎7371278
浏览 203回答 1
1回答

jeck猫

如果分析OP码,起点和终点重合,因此在同一位置的2个点之间绘制一条线时,只会绘制一个点。逻辑是将第 i 步中获得的点与 (i+1) 个点连接起来。要执行上述操作,最简单的方法是使用QPainterPath:import sysfrom PyQt5 import QtWidgets, QtGui, QtCoreclass MyWidget(QtWidgets.QWidget):    def __init__(self):        super().__init__()        self.initUI()        self.paths = []    def initUI(self):        self.setGeometry(200, 200, 1000, 500)        self.label = QtWidgets.QLabel(self)        self.show()    def paintEvent(self, event):        qp = QtGui.QPainter(self)        for path in self.paths:            qp.drawPath(path)    def mousePressEvent(self, event):        path = QtGui.QPainterPath()        path.moveTo(event.pos())        self.paths.append(path)        super().mousePressEvent(event)    def mouseMoveEvent(self, event):        self.paths[-1].lineTo(event.pos())        self.label.setText('Coordinates: ( %d : %d )' % (event.x(), event.y()))        self.label.adjustSize()        self.update()        super().mouseMoveEvent(event)    def mouseReleaseEvent(self, event):        self.paths[-1].lineTo(event.pos())        self.update()        super().mouseReleaseEvent(event)if __name__ == "__main__":    app = QtWidgets.QApplication(sys.argv)    window = MyWidget()    window.resize(800, 600)    sys.exit(app.exec_())
随时随地看视频慕课网APP

相关分类

Python
我要回答