在PyQt中绘制多边形


问题内容

背景

我想在屏幕上绘制一个简单的形状,并且选择了PyQt作为要使用的软件包,因为它似乎是最成熟的。我没有以任何方式被锁定。

问题

仅在屏幕上绘制一个简单的形状(例如多边形)似乎过于复杂。我发现的所有示例都尝试做很多额外的事情,但我不确定实际上有什么意义。

在PyQt中在屏幕上绘制多边形的绝对最小方法是什么?

如果有任何区别,我将使用PyQt的版本5和Python的版本3。


问题答案:

我不确定,你的意思是

屏幕上

您可以使用QPainter在QPaintDevice的任何子类(例如QWidget和所有子类)上绘制很多形状。

最低要求是为线条和文本设置一支笔,为填充设置一支画笔。然后创建一个多边形,设置多边形的所有点并在中绘制paintEvent()

import sys, math
from PyQt5 import QtCore, QtGui, QtWidgets

class MyWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self, parent)
        self.pen = QtGui.QPen(QtGui.QColor(0,0,0))                      # set lineColor
        self.pen.setWidth(3)                                            # set lineWidth
        self.brush = QtGui.QBrush(QtGui.QColor(255,255,255,255))        # set fillColor  
        self.polygon = self.createPoly(8,150,0)                         # polygon with n points, radius, angle of the first point

    def createPoly(self, n, r, s):
        polygon = QtGui.QPolygonF() 
        w = 360/n                                                       # angle per step
        for i in range(n):                                              # add the points of polygon
            t = w*i + s
            x = r*math.cos(math.radians(t))
            y = r*math.sin(math.radians(t))
            polygon.append(QtCore.QPointF(self.width()/2 +x, self.height()/2 + y))

        return polygon

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.setPen(self.pen)
        painter.setBrush(self.brush)  
        painter.drawPolygon(self.polygon)

app = QtWidgets.QApplication(sys.argv)

widget = MyWidget()
widget.show()

sys.exit(app.exec_())