python - 使用 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_())
解决方案
您必须在前一点与当前点之间画一条线:
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)
推荐阅读
- abap - 填充动态itab中的任意列?
- jasper-reports - 如何让jasper报表上显示不同的图片?
- powershell - 如何使用 PowerShell 启用 Windows 功能“MSMQ 服务器”和“MSMQ 服务器核心”?
- docker - 从 dockerfile 访问 docker-compose.yml 中设置的卷
- javascript - 上传json中的图片发送api请求
- windows - 在没有安装任何东西的情况下运行程序?
- reactjs - ReactJS 在依赖项更改时在 UseEffect 上遇到 setState 问题
- python - 从多表继承模型迁移到 Django 中的抽象基类
- android - 有没有办法从 Dart 访问 Android 存储访问框架(SAF)?
- javascript - Fullcalendar eventLimittext 日值