Python PyQt5.QtGui 模块,QPainterPath() 实例源码
我们从Python开源项目中,提取了以下47个代码示例,用于说明如何使用PyQt5.QtGui.QPainterPath()。
def update(self, pos=None):
path = QPainterPath()
if pos is not None:
if self.ioend is None:
startpos = self.iostart.pos() + self.iostart.parent.pos()
endpos = pos
elif self.iostart is None:
startpos = pos
endpos = self.ioend.pos() + self.ioend.parent.pos()
else:
startpos = self.iostart.pos() + self.iostart.parent.pos()
endpos = self.ioend.pos() + self.ioend.parent.pos()
controlpoint = QPointF(abs((endpos - startpos).x()) * 0.8, 0)
path.moveto(startpos)
path.cubicTo(startpos + controlpoint,
endpos - controlpoint,
endpos)
self.setPath(path)
def paint(
self,
painter: QPainter,
option: qstyleOptionGraphicsItem,
widget: QWidget):
pen = QPen()
pen.setWidth(3)
painter.setRenderHint(QPainter.Antialiasing)
pen.setColor(QColor(61, 61, 255))
painter.setPen(pen)
painter.setBrush(QBrush(QColor(61, 255), Qt.SolidPattern))
painter.drawRect(
QRectF(-self.maxWidth / 2, -10, self.maxWidth, 20))
painter.setBrush(QBrush(QColor(240, 217, 108, self.displayWidth, 20))
path = QPainterPath()
path.addText(-self.maxWidth / 2, 35, QFont('monospace', 18, QFont.Bold), f'{self.name} Lv.{self.level} Exp. {self.actualExperience:{len(str(self.maxExperience))}}/{self.maxExperience}')
# pen.setColor(Qt.white)
pen.setWidth(2)
painter.setPen(pen)
painter.setBrush(QBrush(QColor(0, 0, 61), Qt.SolidPattern))
painter.drawPath(path)
def paint(
self,
widget: QWidget):
pen = QPen()
pen.setWidth(1)
painter.setRenderHint(QPainter.Antialiasing)
pen.setColor(QColor(81, 81, 255))
painter.setPen(pen)
painter.setBrush(QBrush(QColor(81, Qt.SolidPattern))
path = QPainterPath()
path.addText(
-self.width,
self.height,
QFont('monospace', 13, QFont.PreferNoHinting),
self.text)
painter.drawPath(path)
def paint_shape(self, shape):
"""
Create all plotting related parts of one shape.
@param shape: The shape to be plotted.
"""
start, start_ang = shape.get_start_end_points(True, True)
shape.path = QPainterPath()
shape.path.moveto(start.x, -start.y)
drawHorLine = lambda caller, start, end: shape.path.lineto(end.x, -end.y)
drawVerLine = lambda caller, start: None # Not used in 2D mode
shape.make_path(drawHorLine, drawVerLine)
self.BB = self.BB.joinBB(shape.BB)
shape.stmove = self.createstmove(shape)
shape.starrow = self.createstarrow(shape)
shape.enarrow = self.createenarrow(shape)
shape.stmove.setParentItem(shape)
shape.starrow.setParentItem(shape)
shape.enarrow.setParentItem(shape)
def __init__(self, text='S', startp=Point(x=0.0, y=0.0),):
"""
Initialisation of the class.
"""
QGraphicsItem.__init__(self)
self.setFlag(QGraphicsItem.ItemIsSelectable, False)
self.text = text
self.sc = 1.0
self.startp = QtCore.QPointF(startp.x, -startp.y)
pencolor = QColor(0, 200, 255)
self.brush = QColor(0, 100, 255)
self.pen = QPen(pencolor, 1, QtCore.Qt.SolidLine)
self.pen.setCosmetic(True)
self.path = QPainterPath()
self.path.addText(QtCore.QPointF(0, 0),
QFont("Arial", 10/self.sc),
self.text)
def __init__(self, brown_object, pos, pen, brush,
clip_start_x=None, clip_width=None):
"""
Args:
brown_object (Path): The path this interface belongs to
pos (Point[GraphicUnit] or tuple): The position of the path root
relative to the document.
pen (PenInterface): The pen to draw outlines with.
brush (BrushInterface): The brush to draw outlines with.
clip_start_x (Unit or None): The local starting position for the
path clipping region. Use `None` to render from the start.
clip_width (Unit or None): The width of the path clipping region.
Use `None` to render to the end
"""
super().__init__(brown_object)
self.qt_path = QtGui.QPainterPath()
self.qt_object = QClippingPath(self.qt_path,
clip_start_x, clip_width)
self.pos = pos
self.pen = pen
self.brush = brush
self.clip_start_x = clip_start_x
self.clip_width = clip_width
######## PUBLIC PROPERTIES ########
def paint(self, painter, option, widget):
srcPoint = self.mapFromScene(self.__srcPortCircle.centerInSceneCoords())
dstPoint = self.mapFromScene(self.__dstPortCircle.centerInSceneCoords())
dist_between = dstPoint - srcPoint
self.__path = QtGui.QPainterPath()
self.__path.moveto(srcPoint)
self.__path.cubicTo(
srcPoint + QtCore.QPointF(0,
dstPoint - QtCore.QPointF(0,
dstPoint
)
self.setPath(self.__path)
super(Connection, self).paint(painter, widget)
def __init__(self, shape):
QGraphicslineItem.__init__(self)
StMove.__init__(self, shape)
self.allwaysshow = False
self.path = QPainterPath()
self.setFlag(QGraphicsItem.ItemIsSelectable, False)
self.pen = QPen(QColor(50, QtCore.Qt.SolidLine,
QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin)
self.pen.setCosmetic(True)
self.make_papath()
def make_papath(self):
"""
To be called if a Shape shall be printed to the canvas
@param canvas: The canvas to be printed in
@param pospro: The color of the shape
"""
self.path = QPainterPath()
if len(self.geos):
start = self.geos.abs_el(0).get_start_end_points(True)
self.path.moveto(start.x, end: self.path.lineto(end.x, start: None # Not used in 2D mode
self.make_path(drawHorLine, drawVerLine)
def paintEvent(self, q_paint_event):
# board background color
painter = QtGui.QPainter(self)
bg_path = QtGui.QPainterPath()
bg_path.addRect(0, self.width(), self.height())
painter.fillPath(bg_path, GREEN)
# draw the board lines
for i in range(8):
x_pos = self.width() / 8 * i
painter.drawLine(x_pos, x_pos, self.height())
y_pos = self.height() / 8 * i
painter.drawLine(0, y_pos, y_pos)
if self.board is not None and len(self.board) >= 8 * 8:
for h in range(8):
for w in range(8):
pieces_path = QtGui.QPainterPath()
w_dist = self.width() / 8
h_dist = self.height() / 8
x_pos = w_dist * w
y_pos = h_dist * h
bounding_rect = QtCore.QRectF(x_pos, w_dist, h_dist)
index = (h * 8) + w
piece = self.board[index]
if piece == 'O':
pieces_path.addEllipse(bounding_rect)
painter.fillPath(pieces_path, WHITE)
elif piece == 'X':
pieces_path.addEllipse(bounding_rect)
painter.fillPath(pieces_path, BLACK)
def draw_photon(self,qp,start_x,start_y,up):
wx=np.arange(0, 100.0 , 0.1)
wy=np.sin(wx*3.14159*0.1)*15
pen=QPen()
pen.setWidth(2)
if up==True:
pen.setColor(QColor(0,0,255))
else:
pen.setColor(QColor(0,255,0))
qp.setPen(pen)
for i in range(1,len(wx)):
qp.drawLine((int)(start_x-wy[i-1]),(int)(start_y+wx[i-1]),(int)(start_x-wy[i]),(int)(start_y+wx[i]))
if up==True:
path=QPainterPath()
path.moveto (start_x-10, start_y);
path.lineto (start_x-10, start_y);
path.lineto (start_x+10, start_y);
path.lineto (start_x, start_y-20);
qp.fillPath (path, QBrush (QColor (0,255)))
else:
path=QPainterPath()
path.moveto (start_x-10, start_y+100.0);
path.lineto (start_x-10, start_y+100.0);
path.lineto (start_x+10, start_y+100.0);
path.lineto (start_x, start_y+100.0+20);
qp.setPen (Qt.nopen);
qp.fillPath (path,0)))
def __init__(self):
QGraphicsView.__init__(self)
self.setScene(GraphicsScene())
self.setSceneRect(QRectF(self.viewport().rect()))
self.PIX = Qpixmap()
self.timer = QTimer()
self.timer.timeout.connect(self.proccessImage)
self.path = QPainterPath()
self.item = GraphicsPathItem()
self.scene().addItem(self.item)
def switch_to_text(self, text):
font = QFont()
font.setPointSize(self.__height_to_point(self.PIX.height()))
graphics_text_item = qgraphicstextitem(text)
graphics_text_item.setFlag(QGraphicsItem.ItemIsMovable)
graphics_text_item.setFont(font)
self.scene().addItem(graphics_text_item)
graphics_text_item.setPos(
QPoint(self.item.boundingRect().x(), self.item.boundingRect().y()))
self.path = QPainterPath()
self.item = GraphicsPathItem()
self.scene().addItem(self.item)
def clear(self):
self.scene().clear()
self.path = QPainterPath()
self.item = GraphicsPathItem()
self.item.setPath(self.path)
self.scene().addItem(self.item)
def test_calculate_clipping_area_covering_full_path(self):
painter_path = QtGui.QPainterPath()
painter_path.lineto(100, 200)
expected_rect = painter_path.boundingRect()
result_rect = QClippingPath.calculate_clipping_area(
painter_path.boundingRect(), None, 0)
assert(result_rect.x() == expected_rect.x())
assert(result_rect.y() == expected_rect.y())
assert(result_rect.width() == expected_rect.width())
assert(result_rect.height() == expected_rect.height())
def test_calculate_clipping_area_starting_in_path(self):
painter_path = QtGui.QPainterPath()
painter_path.lineto(100, 200)
result_rect = QClippingPath.calculate_clipping_area(
painter_path.boundingRect(), 50, 0)
assert(result_rect.x() == 50)
assert(result_rect.y() == painter_path.boundingRect().y())
assert(result_rect.width() == 50)
assert(result_rect.height() == painter_path.boundingRect().height())
def test_calculate_clipping_area_ending_in_path(self):
painter_path = QtGui.QPainterPath()
painter_path.lineto(100, 0)
assert(result_rect.x() == 0)
assert(result_rect.y() == painter_path.boundingRect().y())
assert(result_rect.width() == 50)
assert(result_rect.height() == painter_path.boundingRect().height())
def test_calculate_clipping_area_starting_and_ending_in_path(self):
painter_path = QtGui.QPainterPath()
painter_path.lineto(100, 25, 30, 0)
assert(result_rect.x() == 25)
assert(result_rect.y() == painter_path.boundingRect().y())
assert(result_rect.width() == 30)
assert(result_rect.height() == painter_path.boundingRect().height())
def __init__(self, parent=None):
super(RenderArea, self).__init__(parent)
newFont = self.font()
newFont.setPixelSize(12)
self.setFont(newFont)
fontMetrics = QFontMetrics(newFont)
self.xBoundingRect = fontMetrics.boundingRect("x")
self.yBoundingRect = fontMetrics.boundingRect("y")
self.shape = QPainterPath()
self.operations = []
def createPath(self):
self.path = QPainterPath()
angle = 2*math.pi/self._sides
self.path.moveto(self._outerRadius, 0)
for step in range(1, self._sides + 1):
self.path.lineto(
self._innerRadius * math.cos((step - 0.5) * angle),
self._innerRadius * math.sin((step - 0.5) * angle)
)
self.path.lineto(
self._outerRadius * math.cos(step * angle),
self._outerRadius * math.sin(step * angle)
)
self.path.closeSubpath()
def __init__(self):
self.myPath = QPainterPath()
self.myPosition = QPoint()
self.myColor = QColor()
self.myToolTip = ''
def createPath(self):
self.path = QPainterPath()
angle = 2*math.pi/self._sides
self.path.moveto(self._outerRadius,
self._outerRadius * math.sin(step * angle)
)
self.path.closeSubpath()
def __init__(self):
self.myPath = QPainterPath()
self.myPosition = QPoint()
self.myColor = QColor()
self.myToolTip = ''
def shape(self):
"""Qt Function
Return a more accurate shape for this item so that
mouse hovering is more accurate"""
path = QtGui.QPainterPath()
path.addRect(QtCore.QRectF(-3, -1/2 * constantsAndConfigs.trackHeight, 9, constantsAndConfigs.trackHeight)) #this is directly related to inits parameter x,y,w,h
return path
def shape(self):
"""Return a more accurate shape for this item so that
mouse hovering is more accurate"""
path = QtGui.QPainterPath()
path.addEllipse(QtCore.QRectF(-5, -5, 14, 14)) #this is directly related to inits parameter. -3,-3,6,6.
return path
def shape(self):
"""Return a more accurate shape for this item so that
mouse hovering is more accurate"""
path = QtGui.QPainterPath()
path.addRect(QtCore.QRectF(-2, -2, 4, self.parentCCPath.rect().height() + 4 )) #this is directly related to inits parameter x,h
return path
def draw(self):
lengthInPixel = self.noteExportObject["tiedistanceInTicks"] / constantsAndConfigs.ticksToPixelRatio
path = QtGui.QPainterPath()
path.cubicTo(0, lengthInPixel/2, constantsAndConfigs.stafflineGap, lengthInPixel, 0) # ctrlPt1x,ctrlPt1y,ctrlPt2x,ctrlPt2y,endPtx,endPty
self.setPath(path) #set path edits the old one in place
def shape(self):
"""Return a more accurate shape for this item so that
mouse hovering is more accurate"""
path = QtGui.QPainterPath()
path.addRect(QtCore.QRectF(-2, 5, self.parentTransparentBlock.rect().height()+2 )) #this is directly related to inits parameter x,h
return path
def modify(self, img: QtGui.Qpixmap, mult: float=1.0, rounding: int=0, cut: int=5):
if img.width() == 0 or img.height() == 0:
log.info("Fatal error: IMG NOT LOADED")
return img
img = QtGui.Qpixmap(img)
h = img.height()
w = img.width()
color = QtGui.QColor(0, 0) # (r,g,b,density)
pix = QtGui.Qpixmap(QtCore.QSize(w, h))
pix.fill(color)
if not rounding > 0:
cut = 0
rect = QtCore.QRectF(-1 + cut, -1 + cut, 2 + w - cut * 2, 2 + h - cut * 2)
painter = QtGui.QPainter()
painter.begin(pix)
painter.setRenderHints(QtGui.QPainter.Antialiasing, True)
path = QtGui.QPainterPath()
path.addRoundedRect(rect, rounding, rounding)
painter.drawPath(path)
brush = QtGui.QBrush()
brush.setTexture(img)
painter.fillPath(path, brush)
painter.end()
return pix.scaledToWidth(pix.width() * mult)
# credits to: http://python.6.x6.nabble.com/Rounded-corners-td4716825.html
def clear_peak(self):
self.peak = []
if self.peak_item:
self.peak_item.setPath(QPainterPath())
def createPath(self):
self.path = QPainterPath()
angle = 2*math.pi/self._sides
self.path.moveto(self._outerRadius,
self._outerRadius * math.sin(step * angle)
)
self.path.closeSubpath()
def __init__(self):
self.myPath = QPainterPath()
self.myPosition = QPoint()
self.myColor = QColor()
self.myToolTip = ''
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
self._optionsRects = {}
w, h = self.width(), self.height()
metrics = self.fontMetrics()
hPHP = 2 * _hPad
painter.save()
path = QPainterPath()
path.addRoundedRect(.5, .5, w - 1, h - 1, 4)
painter.fillPath(path, QColor(250, 250, 250))
x = 0
linePath = QPainterPath()
for text in self._options[:-1]:
x += hPHP + metrics.width(text)
linePath.moveto(x, 0)
linePath.lineto(x, h)
pen = painter.pen()
pen.setColor(QColor(218, 218, 218))
pen.setWidth(0)
painter.setPen(pen)
painter.drawPath(path)
painter.setRenderHint(QPainter.Antialiasing, False)
painter.drawPath(linePath)
painter.restore()
painter.translate(_hPad, _vPad + metrics.ascent())
left = 0
for index, text in enumerate(self._options):
if index in self._selection:
color = QColor(20, 146, 230)
else:
color = QColor(63, 63, 63)
painter.setPen(color)
painter.drawText(0, text)
textWidth = metrics.width(text)
rectWidth = textWidth + hPHP
rect = (left, rectWidth, h)
self._optionsRects[index] = rect
painter.translate(rectWidth, 0)
left += rectWidth
def setupShapes(self):
truck = QPainterPath()
truck.setFillRule(Qt.WindingFill)
truck.moveto(0.0, 87.0)
truck.lineto(0.0, 60.0)
truck.lineto(10.0, 60.0)
truck.lineto(35.0, 35.0)
truck.lineto(100.0, 87.0)
truck.moveto(17.0, 60.0)
truck.lineto(55.0, 40.0)
truck.lineto(37.0, 40.0)
truck.lineto(17.0, 60.0)
truck.addEllipse(17.0, 75.0, 25.0, 25.0)
truck.addEllipse(63.0, 25.0)
clock = QPainterPath()
clock.addEllipse(-50.0, -50.0, 100.0, 100.0)
clock.addEllipse(-48.0, -48.0, 96.0, 96.0)
clock.moveto(0.0, 0.0)
clock.lineto(-2.0, -2.0)
clock.lineto(0.0, -42.0)
clock.lineto(2.0, 0.0)
clock.moveto(0.0, 0.0)
clock.lineto(2.732, -0.732)
clock.lineto(24.495, 14.142)
clock.lineto(0.732, 2.732)
clock.lineto(0.0, 0.0)
house = QPainterPath()
house.moveto(-45.0, -20.0)
house.lineto(0.0, -45.0)
house.lineto(45.0, -20.0)
house.lineto(45.0, 45.0)
house.lineto(-45.0, -20.0)
house.addRect(15.0, 5.0, 20.0, 35.0)
house.addRect(-35.0, -15.0, 25.0)
text = QPainterPath()
font = QFont()
font.setPixelSize(50)
fontBoundingRect = QFontMetrics(font).boundingRect("Qt")
text.addText(-QPointF(fontBoundingRect.center()), font, "Qt")
self.shapes = (clock, house, text, truck)
self.shapeComboBox.activated.connect(self.shapeSelected)
def __init__(self):
super(SortingBox, self).__init__()
self.circlePath = QPainterPath()
self.squarePath = QPainterPath()
self.trianglePath = QPainterPath()
self.shapeItems = []
self.prevIoUsPosition = QPoint()
self.setMouseTracking(True)
self.setBackgroundRole(QPalette.Base)
self.itemInMotion = None
self.newCircleButton = self.createtoolButton("New Circle",
QIcon(':/images/circle.png'), self.createNewCircle)
self.newSquareButton = self.createtoolButton("New Square",
QIcon(':/images/square.png'), self.createNewSquare)
self.newTriangleButton = self.createtoolButton("New Triangle",
QIcon(':/images/triangle.png'), self.createNewTriangle)
self.circlePath.addEllipse(0, 100)
self.squarePath.addRect(0, 100)
x = self.trianglePath.currentPosition().x()
y = self.trianglePath.currentPosition().y()
self.trianglePath.moveto(x + 120 / 2, y)
self.trianglePath.lineto(0, 100)
self.trianglePath.lineto(120, 100)
self.trianglePath.lineto(x + 120 / 2, y)
self.setwindowTitle("Tooltips")
self.resize(500, 300)
self.createShapeItem(self.circlePath, "Circle",
self.initialItemPosition(self.circlePath),
self.initialItemColor())
self.createShapeItem(self.squarePath, "Square",
self.initialItemPosition(self.squarePath),
self.initialItemColor())
self.createShapeItem(self.trianglePath, "Triangle",
self.initialItemPosition(self.trianglePath),
self.initialItemColor())
def __init__(self, noteExportObject):
#Dimensions and Position
x = noteExportObject["leftModInTicks"] / constantsAndConfigs.ticksToPixelRatio
y = -1 * constantsAndConfigs.stafflineGap / 2 + 1
w = (noteExportObject["rightModInTicks"] + noteExportObject["completeDuration"] - noteExportObject["leftModInTicks"]) / constantsAndConfigs.ticksToPixelRatio
h = constantsAndConfigs.stafflineGap - 2 #2 pixel to make room for the pen-width.
super().__init__(x, y, w, h)
self.setPos(0, constantsAndConfigs.stafflineGap * noteExportObject["dotOnLine"] / 2)
self.setParentItem(parent)
#Prepare self.shape()
#NOTE: this was from a time when mouse modification was possible. Leave for later use.
#self.path = QtGui.QPainterPath()
#self.pathRect = QtCore.QRectF(x,y-1,h+4) #this is directly related to inits parameter x,h
#self.path.addRect(self.pathRect)
#self.setCursor(QtCore.Qt.SizeHorCursor)
#Different color when the duration was modified by the user
inactive = "green" if noteExportObject["manualoverride"] else "black"
self.inactiveColor = QtGui.QColor(inactive)
self.setBrush(self.inactiveColor)
#Pen for the borders
pen = QtGui.QPen()
pen.setCapStyle(QtCore.Qt.RoundCap)
pen.setJoinStyle(QtCore.Qt.RoundJoin)
pen.setWidth(1)
pen.setColor(QtGui.QColor("darkGrey"))
self.setPen(pen)
#Since accidentals are part of the notehead we need one here. It doesn't matter if the Traditional notehead already has one
if noteExportObject["accidental"]: #0 means no difference to keysig
self.accidental = GuiNote.createAccidentalGraphicsItem(self, noteExportObject["accidental"])
self.accidental.setPos(0, 0) #not analogue to the notehead acciental position because here we choose the rectangle as parent
self.accidental.setParentItem(self)
#NOTE: this was from a time when mouse modification was possible. Leave for later use.
#def shape(self):
# """Qt Function
# Return a more accurate shape for this item so that
# mouse hovering is more accurate.
#
# Must be within the bounding rect."""
# return self.path
#def boundingRect(self,*args):
# """Keep in syn with self.shape()"""
# return self.pathRect
#def paint(self,*args):
#Do NOT implement this. This actually works already. The parent item needs this.
def keyPressEvent(self, event):
self.keylist.append(event.key())
if Qt.Key_Control in self.keylist and Qt.Key_A in self.keylist:
paintRect = QtGui.QPainterPath()
paintRect.addRect(0, -(26.5 * globals.TileWidth), 241 * globals.TileWidth, 27.5 * globals.TileWidth)
self.scene.setSelectionArea(paintRect)
event.accept()
return
elif event.key() in [Qt.Key_Delete, Qt.Key_Backspace]:
try:
sel = self.scene.selectedItems()
except RuntimeError:
return
if len(sel) > 0:
for obj in sel:
index = globals.Area.objects.index(obj)
del globals.Area.objects[index]
self.scene.update(obj.boundRect)
obj.setSelected(False)
obj.delete()
self.scene.removeItem(obj)
self.scene.update()
del obj
event.accept()
return
elif event.key() == Qt.Key_G:
globals.GridShown = not globals.GridShown
self.scene.update()
event.accept()
return
super().keyPressEvent(event)