Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing a polygon in PyQt

Background

I would like to draw a simple shape on the screen, and I have selected PyQt as the package to use, as it seems to be the most established. I am not locked to it in any way.

Problem

It seems to be over complicated to just draw a simple shape like for example a polygon on the screen. All examples I find try to do a lot of extra things and I am not sure what is actually relevant.

Question

What is the absolute minimal way in PyQt to draw a polygon on the screen?

I use version 5 of PyQt and version 3 of Python if it makes any difference.

like image 766
firelynx Avatar asked Feb 10 '16 13:02

firelynx


1 Answers

i am not sure, what you mean with

on the screen

you can use QPainter, to paint a lot of shapes on any subclass of QPaintDevice e.g. QWidget and all subclasses.

the minimum is to set a pen for lines and text and a brush for fills. Then create a polygon, set all points of polygon and paint in the 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_())
like image 178
a_manthey_67 Avatar answered Oct 02 '22 13:10

a_manthey_67