在 PyQt 中绘制多边形 [英] Drawing a polygon in PyQt

查看:267
本文介绍了在 PyQt 中绘制多边形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景

我想在屏幕上画一个简单的形状,我选择了 PyQt 作为使用的包,因为它似乎是最成熟的.我没有以任何方式锁定它.

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.

问题

在屏幕上绘制一个简单的形状(例如多边形)似乎过于复杂.我发现的所有示例都试图做很多额外的事情,但我不确定什么是真正相关的.

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.

问题

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

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

我使用 PyQt 的第 5 版和 Python 的第 3 版(如果有任何区别).

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

推荐答案

我不确定,你对

在屏幕上

你可以使用 QPainter,在 QPaintDevice 的任何子类上绘制很多形状,例如QWidget 和所有子类.

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

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

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

这篇关于在 PyQt 中绘制多边形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆