def paintEvent(self, event): if self.display_status: super().paintEvent(event) painter = QPainter(self) painter_path = QPainterPath() qt_pen_1 = QPen(Qt.red, 2, Qt.SolidLine) qt_pen_2 = QPen(Qt.green, 10, Qt.SolidLine) qt_pen_3 = QPen(Qt.red, 2, Qt.DotLine) painter.setPen(qt_pen_1) painter.drawPolygon(QPolygon(self.roi_rect), Qt.WindingFill) painter_path.addPolygon(QPolygonF(self.roi_rect)) painter_path.closeSubpath() # qt_brush = QBrush(Qt.green) qt_brush = QBrush(QColor(0, 255, 0, 64)) painter.setBrush(qt_brush) painter.drawPath(painter_path) # painter.drawPoint(self.tmp_center_pt) painter.setPen(qt_pen_3) painter.drawLine(self.roi_rect[0], self.roi_rect[2]) painter.drawLine(self.roi_rect[1], self.roi_rect[3]) painter.setPen(qt_pen_2) for elem in self.roi_rect: painter.drawPoint(elem) # for elem in self.img_rect: # painter.drawPoint(elem) if self.default_rect: self.update()
def mouseMoveEvent(self, event): super(CBlueprintView, self).mouseMoveEvent(event) self.setTransformationAnchor(QGraphicsView.NoAnchor) pos = event.pos() if self.m_StartPos: offsetX, offsetY = pos.x() - self.m_StartPos.x(), pos.y( ) - self.m_StartPos.y() offsetX /= self.m_Scale offsetY /= self.m_Scale self.translate(offsetX, offsetY) self.m_StartPos = pos self.m_IsHasMove = True if self.m_SelectPos: rect = QRect(min(self.m_SelectPos.x(), pos.x()), min(self.m_SelectPos.y(), pos.y()), abs(self.m_SelectPos.x() - pos.x()), abs(self.m_SelectPos.y() - pos.y())) path = QPainterPath() path.addPolygon(self.mapToScene(rect)) path.closeSubpath() self.m_Scene.RubberBandSelecNodeUI(path, self.rubberBandSelectionMode(), self.viewportTransform()) self.m_RubberBand.setGeometry(rect)
def itemRegion(self, index): if not index.isValid(): return QRegion() if index.column() != 1: return QRegion(self.itemRect(index)) if self.model().data(index) <= 0.0: return QRegion() startAngle = 0.0 for row in range(self.model().rowCount(self.rootIndex())): sliceIndex = self.model().index(row, 1, self.rootIndex()) value = self.model().data(sliceIndex) if value > 0.0: angle = 360*value/self.totalValue if sliceIndex == index: slicePath = QPainterPath() slicePath.moveTo(self.totalSize/2, self.totalSize/2) slicePath.arcTo(self.margin, self.margin, self.margin+self.pieSize, self.margin+self.pieSize, startAngle, angle) slicePath.closeSubpath() return QRegion(slicePath.toFillPolygon().toPolygon()) startAngle += angle return QRegion()
def itemRegion(self, index): if not index.isValid(): return QRegion() if index.column() != 1: return QRegion(self.itemRect(index)) if self.model().data(index) <= 0.0: return QRegion() startAngle = 0.0 for row in range(self.model().rowCount(self.rootIndex())): sliceIndex = self.model().index(row, 1, self.rootIndex()) value = self.model().data(sliceIndex) if value > 0.0: angle = 360 * value / self.totalValue if sliceIndex == index: slicePath = QPainterPath() slicePath.moveTo(self.totalSize / 2, self.totalSize / 2) slicePath.arcTo(self.margin, self.margin, self.margin + self.pieSize, self.margin + self.pieSize, startAngle, angle) slicePath.closeSubpath() return QRegion(slicePath.toFillPolygon().toPolygon()) startAngle += angle return QRegion()
def get_path(self): path = QPainterPath() rect = QRectF(self.rect()) path.arcMoveTo(rect, 0) path.arcTo(rect, 0, 360) path.closeSubpath() return path
def paintEvent(self, event): # Draw backgrounds according to css styleOpt = QStyleOption() styleOpt.initFrom(self) p = QPainter(self) p.setRenderHint(QPainter.Antialiasing) self.style().drawPrimitive(QStyle.PE_Widget, styleOpt, p, self) if self.values == None or len(self.values) == 0: return # print(len(self.values)) r = self.rect() dx = r.width() / float(self.datapoints - 1) # Build a path from the readings path = QPainterPath() path.moveTo(r.bottomRight()) i = 0 for reading in reversed(self.values): pt = QPointF(r.width() - i*dx, (1.0 - reading) * r.height()) path.lineTo(pt) i = i + 1 path.lineTo(path.currentPosition().x(), r.height()) path.closeSubpath() # Use foreground color for graph gcolor = styleOpt.palette.color(QPalette.Text) p.setBrush(gcolor) p.setPen(gcolor) p.drawPath(path)
def paintEvent(self, event): painter = QPainter(self) drawColor = Qt.gray if not self.file_over else Qt.blue pen = QPen() pen.setDashPattern([4, 2]) pen.setWidth(3) pen.setColor(drawColor) painter.setPen(pen) painter.setRenderHint(QPainter.Antialiasing) # Rounded dashed rect painter.translate(self.width() / 2 - 60, self.height() / 2 - 60) painter.drawRoundedRect(0, 0, 120, 120, 25.0, 25.0) # Arrow painter.translate(22, 30) arrow = QPainterPath() arrow.moveTo(20, 40) arrow.lineTo(30, 40) arrow.lineTo(30, 1) arrow.lineTo(50, 1) arrow.lineTo(50, 40) arrow.lineTo(60, 40) arrow.lineTo(40, 60) arrow.closeSubpath() painter.setPen(Qt.NoPen) painter.setBrush(drawColor) painter.drawPath(arrow)
def createRotateArrow(): arrowHeadPos = 12 arrowHeadLength = 4.5 arrowHeadWidth = 5 bodyWidth = 1.5 outerArcSize = arrowHeadPos + bodyWidth - arrowHeadLength innerArcSize = arrowHeadPos - bodyWidth - arrowHeadLength path = QPainterPath() path.moveTo(arrowHeadPos, 0) path.lineTo(arrowHeadPos + arrowHeadWidth, arrowHeadLength) path.lineTo(arrowHeadPos + bodyWidth, arrowHeadLength) path.arcTo(QRectF(arrowHeadLength - outerArcSize, arrowHeadLength - outerArcSize, outerArcSize * 2, outerArcSize * 2), 0, -90) path.lineTo(arrowHeadLength, arrowHeadPos + arrowHeadWidth) path.lineTo(0, arrowHeadPos) path.lineTo(arrowHeadLength, arrowHeadPos - arrowHeadWidth) path.lineTo(arrowHeadLength, arrowHeadPos - bodyWidth) path.arcTo(QRectF(arrowHeadLength - innerArcSize, arrowHeadLength - innerArcSize, innerArcSize * 2, innerArcSize * 2), -90, 90) path.lineTo(arrowHeadPos - arrowHeadWidth, arrowHeadLength) path.closeSubpath() return path
def set_strategy(self, strategy): greenium = QColor.fromCmykF(0.7,0,0.9,0) #greenium.setAlphaF(0.2) for id_, pos in strategy['strategy']['map']['waypoints'].items(): wp = self._scene.addEllipse(QRectF(pos[0]-10,pos[1]-10,20,20),QPen(), QBrush(greenium)) self._waypoints.append(wp) for id_, pose in strategy['strategy']['map']['poses'].items(): p = strategy['strategy']['map']['waypoints'][pose[0]] path = QPainterPath() cos_ = math.cos(pose[1] * math.pi / 180) sin_ = math.sin(pose[1] * math.pi / 180) l = 40 w = 20 path.moveTo(p[0] + l * cos_, p[1] + l * sin_) path.lineTo(p[0] -l * cos_ + w * sin_, p[1] - l * sin_ - w * cos_) path.lineTo(p[0] -l * cos_ - w * sin_, p[1] - l * sin_ + w * cos_) path.closeSubpath() itm = self._scene.addPath(path, QPen(), QBrush(greenium)) for id_, area in strategy['strategy']['map']['areas'].items(): path = QPainterPath() v = area['vertices'][0] path.moveTo(v[0], v[1]) for v in area['vertices'][1:]: path.lineTo(v[0], v[1]) path.closeSubpath() itm = self._scene.addPath(path, QPen(), QBrush(greenium)) self._waypoints.append(wp)
def drawTanks(self, qp): for tankKey in self.plan.tankList.keys(): qp.setPen(Qt.black) tank = self.plan.tankList[tankKey] if tank.use == False: continue x1 = tank.useFromTime / self.totalTime *self.plot_width x2 = tank.useUntilTime / self.totalTime *self.plot_width yTxt = tank.changeDepth / self.depthMax * self.plot_height bgPath = QPainterPath() bgPath.moveTo(x1, self.plot_height+10) bgPath.lineTo(x1, self.plot_height+20) bgPath.lineTo(x2, self.plot_height+20) bgPath.lineTo(x2, self.plot_height+10) bgPath.closeSubpath() gradient = QLinearGradient(0, 0, 0, 100) gradient.setColorAt(0.0, tank.color) gradient.setColorAt(1.0, tank.color) qp.setBrush(QBrush(gradient)) qp.drawPath(bgPath) text = '{} ({}/{})'.format(tank.name, tank.o2, tank.he) text2 = '{:.0f} m {:.0f} min'.format(tank.changeDepth, tank.useFromTime/60.0) qp.drawText(x1+3, self.plot_height+20, text) qp.drawText(x1+3, yTxt + 10, text) qp.drawText(x1+3, yTxt + 20, text2) qp.setPen(QPen(Qt.black, 1, Qt.DotLine)) if x1 != 0 : qp.drawLine(x1, self.plot_height, x1, yTxt) qp.drawLine(x1, yTxt, self.plot_width, yTxt)
def setPath(self): path = QPainterPath() thickw = self._thick * self._wrs thickh = self._thick * self._hrs pw1 = self._wrs * 0.2 pw2 = pw1 + thickw * 0.851 pw4 = self._wrs / 2 pw7 = self._wrs * 0.8 pw3 = pw4 - 0.851 * thickw pw5 = pw4 + 0.851 * thickw pw6 = pw7 - thickw * 0.851 ph1 = self._hrs * 0.2 ph2 = ph1 + thickh * 0.851 ph4 = self._hrs / 2 ph7 = self._hrs * 0.8 ph3 = ph4 - 0.851 * thickh ph5 = ph4 + 0.851 * thickh ph6 = ph7 - thickh * 0.851 sequence = [(pw2, ph1), (pw4, ph3), (pw6, ph1), (pw7, ph2), (pw5, ph4), (pw7, ph6), (pw6, ph7), (pw4, ph5), (pw2, ph7), (pw1, ph6), (pw3, ph4), (pw1, ph2)] path.moveTo(pw1, ph2) for point in sequence: path.lineTo(*point) path.closeSubpath() return path
def setPath(self): path = QPainterPath() path.moveTo(self._wrs * 0.5, self._hrs * 0.2) path.lineTo(self._wrs * 0.8, self._hrs * 0.8) path.lineTo(self._wrs * 0.2, self._hrs * 0.8) path.closeSubpath() return path
def paint(self, painter, styleOption, modelIndex): """Paint the Data Edit Cells with support for rich text. Other cells are painted with the base class default. Also paints an error rectangle if the format error flag is set. Arguments: painter -- the painter instance styleOption -- the data for styles and geometry modelIndex -- the index of the cell to be painted """ cell = self.parent().item(modelIndex.row(), modelIndex.column()) if isinstance(cell, DataEditCell): painter.save() doc = cell.doc doc.setTextWidth(styleOption.rect.width()) painter.translate(styleOption.rect.topLeft()) paintRect = QRectF(0, 0, styleOption.rect.width(), styleOption.rect.height()) painter.setClipRect(paintRect) painter.fillRect(paintRect, QApplication.palette().base()) painter.setPen(QPen(QApplication.palette().text(), 1)) painter.drawRect(paintRect.adjusted(0, 0, -1, -1)) doc.drawContents(painter) if cell.errorFlag: path = QPainterPath(QPointF(0, 0)) path.lineTo(0, 10) path.lineTo(10, 0) path.closeSubpath() painter.fillPath(path, QApplication.palette().highlight()) painter.restore() else: super().paint(painter, styleOption, modelIndex)
def FOV(self, Robo): view = QPainterPath() xPos = math.cos(math.radians(Robo.alpha + (Robo.FOV / 2))) * Robo.radius yPos = math.sin(math.radians(Robo.alpha + (Robo.FOV / 2))) * Robo.radius xPos2 = math.cos(math.radians(Robo.alpha - (Robo.FOV / 2))) * Robo.radius yPos2 = math.sin(math.radians(Robo.alpha - (Robo.FOV / 2))) * Robo.radius x1 = QPoint( int(round(Robo.position.x())) + Robo.radius, int(round(Robo.position.y())) + Robo.radius) x2 = x1 + QPoint( (int(round(Robo.position.x())) + Robo.radius) + 1000 * xPos, (int(round(Robo.position.y())) + Robo.radius) - 1000 * yPos) x3 = x1 + QPoint( (int(round(Robo.position.x())) + Robo.radius) + 1000 * xPos2, (int(round(Robo.position.y())) + Robo.radius) - 1000 * yPos2) view.addPolygon(QPolygonF([x1, x2, x3])) view.closeSubpath() return view
def createResizeArrow(straight): if straight: arrowLength = 14 else: arrowLength = 16 arrowHeadLength = 4.5 arrowHeadWidth = 5 bodyWidth = 1.5 path = QPainterPath() path.lineTo(arrowHeadWidth, arrowHeadLength) path.lineTo(0 + bodyWidth, arrowHeadLength) path.lineTo(0 + bodyWidth, arrowLength - arrowHeadLength) path.lineTo(arrowHeadWidth, arrowLength - arrowHeadLength) path.lineTo(0, arrowLength) path.lineTo(-arrowHeadWidth, arrowLength - arrowHeadLength) path.lineTo(0 - bodyWidth, arrowLength - arrowHeadLength) path.lineTo(0 - bodyWidth, arrowHeadLength) path.lineTo(-arrowHeadWidth, arrowHeadLength) path.closeSubpath() if straight: x = 2 else: x = 3 path.translate(0, x) return path
def vertices_to_path(vertices, closed=True): ''' Generate QPainterPath from vertices. Args: vertices (n x 2 numpy array): vertices, (x,y) closed (bool): whether the polygon is closed; if polygon has only one vertex, count as open Returns: QPainterPath: the output path ''' path = QPainterPath() for i, (x, y) in enumerate(vertices): if i == 0: path.moveTo(x, y) else: path.lineTo(x, y) if len(vertices) == 1: closed = False # if polygon has only one vertex, count as open if closed: path.closeSubpath() return path
class ModCrossButton(QPushButton): def __init__(self,parent,path=None): QPushButton.__init__(self,parent) self.parent=parent #self.setAttribute(Qt.WA_TranslucentBackground, True) self.backgroundColor = QPalette().light().color() self.backgroundColor.setRgb(157,157,157) #(220,203,231) #self.backgroundColor.setAlpha(100) self.brush=QBrush(Qt.SolidPattern) def paintEvent(self,event): self.wide=self.width() self.high=self.height() self.xdis=self.wide/7 self.ydis=self.xdis self.path=QPainterPath() self.path.setFillRule(Qt.OddEvenFill) self.path.moveTo(self.wide/2, self.high/2-self.xdis) self.path.arcTo(0,0, self.wide, self.high,0,360) #self.path.closeSubpath() self.path.moveTo(self.wide/2-self.xdis/2, self.ydis) self.path.lineTo(self.wide/2-self.xdis/2, self.high/2-self.xdis/2) self.path.lineTo(self.ydis, self.high/2-self.xdis/2) self.path.lineTo(self.ydis, self.high/2+self.xdis/2) self.path.lineTo(self.wide/2-self.xdis/2, self.high/2+self.xdis/2) self.path.lineTo(self.wide/2-self.xdis/2, self.high-self.ydis) self.path.lineTo(self.wide/2+self.xdis/2, self.high-self.ydis) self.path.lineTo(self.wide/2+self.xdis/2, self.high/2+self.xdis/2) self.path.lineTo(self.wide-self.ydis, self.high/2+self.xdis/2) self.path.lineTo(self.wide-self.ydis, self.high/2-self.xdis/2) self.path.lineTo(self.wide/2+self.xdis/2, self.high/2-self.xdis/2) self.path.lineTo(self.wide/2+self.xdis/2, self.ydis) self.path.closeSubpath() self.brush.setColor(self.backgroundColor) self.painter=QPainter(self) self.painter.setRenderHint(QPainter.Antialiasing) self.painter.setPen(Qt.NoPen) self.painter.setBrush(self.brush) self.painter.drawPath(self.path) self.painter.end() #def mousePressEvent(self,ev): # self.parent.close() def enterEvent(self,ev): self.backgroundColor.setRgb(242,146,52) self.update() def leaveEvent(self,ev): self.backgroundColor.setRgb(157,157,157) self.update()
def drawFace(self, qp): #画脸外轮廓 path = QPainterPath() outdiameter = 376.0 outre = QRectF(261.0, 30.0, outdiameter, outdiameter) outre_right_x = 261 + outdiameter / 2 + outdiameter / 2 / math.sqrt(2) outre_right_y = 30 + outdiameter / 2 + outdiameter / 2 / math.sqrt(2) path.moveTo(outre_right_x, outre_right_y) # 将painter路径的起始位置迁移到我们指定的坐标。 path.arcTo(outre, -45, 270) # arcTo()创建一个占据给定矩形的弧,从指定的startAngle(-45度)开始并逆时针延伸sweepLength(270度) path.closeSubpath() # 通过在子路径的开头绘制一条线来关闭当前子路径,自动启动一个新路径 qp.setBrush(QColor(156, 214, 239)) # 给这个图形填充我们设置的颜色 qp.drawPath(path) # 画出我们刚才设置的图形 #画脸内轮廓 path2 = QPainterPath() indiameter = 311.0 inre = QRectF(301.0, 86.0, indiameter, indiameter) # 画矩形 inre_right_x = 301 + indiameter / 2 + indiameter / 2 / math.sqrt(2) inre_right_y = 86 + indiameter / 2 + indiameter / 2 / math.sqrt(2) path2.moveTo(inre_right_x, inre_right_y) path2.arcTo(inre, -45, 270) path2.closeSubpath() qp.setBrush(Qt.white) qp.drawPath(path2)
def createResizeArrow(straight): if straight: arrowLength = 14 else: arrowLength = 16 arrowHeadLength = 4.5 arrowHeadWidth = 5 bodyWidth = 1.5 path = QPainterPath() path.lineTo(arrowHeadWidth, arrowHeadLength) path.lineTo(0 + bodyWidth, arrowHeadLength) path.lineTo(0 + bodyWidth, arrowLength - arrowHeadLength) path.lineTo(arrowHeadWidth, arrowLength - arrowHeadLength) path.lineTo(0, arrowLength) path.lineTo(-arrowHeadWidth, arrowLength - arrowHeadLength) path.lineTo(0 - bodyWidth, arrowLength - arrowHeadLength) path.lineTo(0 - bodyWidth, arrowHeadLength) path.lineTo(-arrowHeadWidth, arrowHeadLength) path.closeSubpath() if straight: x = 2 else: x =3 path.translate(0, x) return path
def setPath(self): path = QPainterPath() path.moveTo(self._wrs * 0.5, self._hrs * 0.1) path.lineTo(self._wrs * 0.9, self._hrs * 0.5) path.lineTo(self._wrs * 0.5, self._hrs * 0.9) path.lineTo(self._wrs * 0.1, self._hrs * 0.5) path.closeSubpath() return path
def create_circle_path(x_center: int, y_center: int, radius: int) -> QPainterPath: rect = QRectF(x_center - radius, y_center - radius, radius * 2, radius * 2) circle_path = QPainterPath() circle_path.arcMoveTo(rect, 0) circle_path.arcTo(rect, 0, 360) circle_path.closeSubpath() return circle_path
def get_circle_path(center_pos: list, radius: int): rect = QRectF(center_pos[0] - radius, center_pos[1] - radius, radius * 2, radius * 2) seed_path = QPainterPath() seed_path.arcMoveTo(rect, 0) seed_path.arcTo(rect, 0, 360) seed_path.closeSubpath() return seed_path
class Segment(QGraphicsItem): def __init__(self, color, offset, parent): super(Segment, self).__init__(parent) self.color = color # 每节的身体段 self.rect = QRectF(offset, -20, 30, 40) self.path = QPainterPath() self.path.addEllipse(self.rect) # 每节的左腿 x = offset + 15 y = -20 self.path.addPolygon( QPolygonF( [QPointF(x, y), QPointF(x - 5, y - 18), QPointF(x - 5, y)])) self.path.closeSubpath() # 每节的右腿 y = 20 self.path.addPolygon( QPolygonF( [QPointF(x, y), QPointF(x - 5, y + 18), QPointF(x - 5, y)])) self.path.closeSubpath() self.change = 1 self.angle = 0 def boundingRect(self): return self.path.boundingRect() def shape(self): return self.path def paint(self, painter, option, widget=None): painter.setPen(Qt.NoPen) painter.setBrush(QBrush(self.color)) if option.levelOfDetailFromTransform(self.transform()) < 0.9: painter.drawEllipse(self.rect) else: painter.drawPath(self.path) def advance(self, phase): if phase == 0: matrix = self.transform() matrix.reset() self.setTransform(matrix) self.angle += self.change * random.random() if self.angle > 6: self.change = -1 # self.angle -= 0.00001 elif self.angle < -6: self.change = 1 # self.angle += 0.00001 elif phase == 1: self.setRotation(self.angle)
def lozengePath(x, y, size): halfSize = size / 2 path = QPainterPath() path.moveTo(x - halfSize, y) path.lineTo(x, y + halfSize) path.lineTo(x + halfSize, y) path.lineTo(x, y - halfSize) path.closeSubpath() return path
def get_circle_seed_path(circle_seed) -> QPainterPath: rect = QRectF(circle_seed.position.x() - circle_seed.radius, circle_seed.position.y() - circle_seed.radius, circle_seed.radius * 2, circle_seed.radius * 2) seed_path = QPainterPath() seed_path.arcMoveTo(rect, 0) seed_path.arcTo(rect, 0, 360) seed_path.closeSubpath() return seed_path
class Segment(QGraphicsItem): def __init__(self, color, offset, parent): super(Segment, self).__init__(parent) self.color = color self.rect = QRectF(offset, -20, 30, 40) self.path = QPainterPath() self.path.addEllipse(self.rect) x = offset + 15 y = -20 self.path.addPolygon( QPolygonF( [QPointF(x, y), QPointF(x - 5, y - 12), QPointF(x - 5, y)])) self.path.closeSubpath() y = 20 self.path.addPolygon( QPolygonF( [QPointF(x, y), QPointF(x - 5, y + 12), QPointF(x - 5, y)])) self.path.closeSubpath() self.change = 1 self.angle = 0 self.timer = QTimer() self.timer.timeout.connect(self.timeout) self.timer.start(INTERVAL) def boundingRect(self): return self.path.boundingRect() def shape(self): return self.path def paint(self, painter, option, widget=None): painter.setPen(Qt.NoPen) painter.setBrush(QBrush(self.color)) if option.levelOfDetailFromTransform(self.transform()) < 0.9: painter.drawEllipse(self.rect) else: painter.drawPath(self.path) def timeout(self): if not Running: return matrix = self.transform() matrix.reset() self.setTransform(matrix) self.angle += self.change * random.random() if self.angle > 4.5: self.change = -1 self.angle -= 0.00001 elif self.angle < -4.5: self.change = 1 self.angle += 0.00001 self.setRotation(self.angle)
def mousePressEvent(self, event): pos = self.magnetPos(event.localPos()) x, y = pos.x(), pos.y() path = QPainterPath() path.moveTo(x, y) path.lineTo(x + 1, y) path.lineTo(x + 1, y + 1) path.closeSubpath() text = "0" self._rulerObject = (path, text)
def pathForPointH(self, p, scene, rsize=7): """ point shape - horizantal rectangular """ dx, dy = self.size_points_on_scene(scene, rsize) path = QPainterPath(p + dx + dy) path.lineTo(p - dx + dy) path.lineTo(p - dx - dy) path.lineTo(p + dx - dy) path.closeSubpath() return path
def pathForPointV(self, p, scene, rsize=7): """ rombic - shaped point """ dx, dy = self.size_points_on_scene(scene, rsize) path = QPainterPath(p + dx) path.lineTo(p + dy) path.lineTo(p - dx) path.lineTo(p - dy) path.closeSubpath() return path
def pathForPointV1(self, point, scene, rsize=3): view = scene.views()[0] pc = view.mapFromScene(point) dp = QPoint(rsize, rsize) recv = QRect(pc - dp, pc + dp) poly = view.mapToScene(recv) path = QPainterPath() path.addPolygon(poly) path.closeSubpath() return path
def view_cone(self): path = QPainterPath() a = self.pos.toPointF() b = a + QPointF(5000 * math.cos(math.radians(self.alpha + self.aov)), 5000 * math.sin(math.radians(self.alpha + self.aov))) c = a + QPointF(5000 * math.cos(math.radians(self.alpha - self.aov)), 5000 * math.sin(math.radians(self.alpha - self.aov))) path.addPolygon(QPolygonF([a, b, c])) path.closeSubpath() return path
class Spline(QGraphicsPathItem): """Class that describes a spline""" def __init__(self, points, color): self.setKnotPoints(points) if color == 'y': self.setPen(QPen(Qt.yellow, 2)) elif color == "r": self.setPen(QPen(Qt.red, 2)) else: self.setPen(QPen(Qt.blue, 2)) def setKnotPoints(self, knotPoints): """KnotPoints is a list of points""" p1 = QPointF(knotPoints[0][0], knotPoints[1][0]) self.path = QPainterPath(p1) super(Spline, self).__init__(self.path) self.points = self.interpolate(knotPoints) for i in range(0, len(self.points[0])): self.path.lineTo(self.points[0][i], self.points[1][i]) self.setPath(self.path) self.path.closeSubpath() self.knotPoints = knotPoints def interpolate(self, pts): """Interpolates the spline points at 500 points along spline""" pts = np.array(pts) tck, u = splprep(pts, u=None, s=0.0, per=1) u_new = np.linspace(u.min(), u.max(), 500) x_new, y_new = splev(u_new, tck, der=0) return (x_new, y_new) def update(self, pos, idx): """Updates the stored spline everytime it is moved Args: pos: new points coordinates idx: index on spline of updated point """ if idx == len(self.knotPoints[0]) + 1: self.knotPoints[0].append(pos.x()) self.knotPoints[1].append(pos.y()) else: self.knotPoints[0][idx] = pos.x() self.knotPoints[1][idx] = pos.y() self.points = self.interpolate(self.knotPoints) for i in range(0, len(self.points[0])): self.path.setElementPositionAt(i, self.points[0][i], self.points[1][i]) self.setPath(self.path)
def p_skew(): path1 = QPainterPath() path1.moveTo(11, 2) path1.lineTo(18, 2) path1.lineTo(10, 18) path1.lineTo(3, 18) path1.closeSubpath() path2 = QPainterPath(path1) path2.moveTo(8, 2) path2.lineTo(2, 2) path2.lineTo(2, 14) return path1, path2
def i_warning(): icon = PathIcon(20, 20) path = QPainterPath() path.moveTo(4, 16) path.lineTo(16, 16) path.lineTo(10, 5) path.closeSubpath() path_ = QPainterPath() path_.addRect(9, 8, 2, 4) path_.addRect(9, 13, 2, 2) icon.addFillPath(path - path_, QColor(230, 20, 20), antialiasing=True) return icon
def pathForPointC(self, p, scene, rsize=7): """ C-center point """ dx, dy = self.size_points_on_scene(scene, rsize) path = QPainterPath(p - dy) path.lineTo(p + dy) path.lineTo(p - dx / 5 + dy / 5) path.lineTo(p - dx) path.lineTo(p + dx) path.lineTo(p) path.closeSubpath() return path
def outline(self): """Return a QPainterPath that outlines the element.""" r1, r2 = self.walls p0, p1 = self.endpoints() proj2D = self.plan.projection.dot vec0 = normalize(np.dot(rot90, proj2D(list(self.rotate[0](0, 0, 1))))) vec1 = normalize(np.dot(rot90, proj2D(list(self.rotate[1](0, 0, 1))))) path = QPainterPath() path.moveTo(*(p0 - r2*vec0)) path.lineTo(*(p1 - r2*vec1)) path.lineTo(*(p1 + r1*vec1)) path.lineTo(*(p0 + r1*vec0)) path.closeSubpath() return path
class ModCloseButton(QPushButton): def __init__(self,parent,wide,high,ppath=None): QPushButton.__init__(self,parent) self.parent=parent self.wide=wide self.high=high self.resize(self.wide,self.high) self.xdis=self.wide/10 #self.setAttribute(Qt.WA_TranslucentBackground, True) self.backgroundColor = QPalette().light().color() self.backgroundColor.setRgb(157,157,157) #(220,203,231) #self.backgroundColor.setAlpha(100) self.brush=QBrush(Qt.SolidPattern) if ppath : self.path=ppath else : self.path=QPainterPath() self.path.moveTo(self.wide/2, self.high/2-self.xdis) self.path.arcTo(0,0, self.wide-2*self.xdis, self.high-2*self.xdis,45,90) self.path.closeSubpath() self.path.moveTo(self.wide/2-self.xdis, self.high/2) self.path.arcTo(0,0,self.wide-2*self.xdis,self.high-2*self.xdis,135,90) self.path.closeSubpath() self.path.moveTo(self.wide/2, self.high/2+self.xdis) self.path.arcTo(0,0,self.wide-2*self.xdis, self.high-2*self.xdis,225,90) self.path.closeSubpath() self.path.moveTo(self.wide/2+self.xdis, self.high/2) self.path.arcTo(0,0,self.wide-2*self.xdis, self.high-2*self.xdis,315,90) self.path.closeSubpath() def paintEvent(self,event): self.brush.setColor(self.backgroundColor) self.painter=QPainter(self) self.painter.setRenderHint(QPainter.Antialiasing) self.painter.setPen(Qt.NoPen) self.painter.setBrush(self.brush) self.painter.drawPath(self.path) self.painter.end() def mousePressEvent(self,ev): self.parent.close() def enterEvent(self,ev): self.backgroundColor.setRgb(234,39,13) self.update() def leaveEvent(self,ev): self.backgroundColor.setRgb(157,157,157) self.update()
def drawCellBackground(self, painter, rect): if self.shouldDrawMarkColor: markColor = self.glyph.markColor if markColor is not None: color = colorToQColor(markColor) color.setAlphaF(.7 * color.alphaF()) painter.fillRect(*(rect+(color,))) if self.shouldDrawHeader: if self.glyph.dirty: x, y, w, h = rect painter.fillRect(*(rect+(cellDirtyColor,))) path = QPainterPath() path.moveTo(x + w - 12, 0) path.lineTo(x + w, 0) path.lineTo(x + w, 12) path.closeSubpath() painter.fillPath(path, QColor(255, 0, 0, 170))
def paintEvent(self, evt): """ Protected method handling a paint event. @param evt reference to the paint event (QPaintEvent) """ painter = QPainter(self) if self.__image is not None and not self.__image.isNull(): x = (self.width() - self.__image.width()) // 2 - 1 y = (self.height() - self.__image.height()) // 2 - 1 painter.drawImage(x, y, self.__image) if self.__menu is not None: triagPath = QPainterPath() startPos = QPointF(self.width() - 5, self.height() - 3) triagPath.moveTo(startPos) triagPath.lineTo(startPos.x() + 4, startPos.y()) triagPath.lineTo(startPos.x() + 2, startPos.y() + 2) triagPath.closeSubpath() painter.setPen(Qt.black) painter.setBrush(Qt.black) painter.setRenderHint(QPainter.Antialiasing, False) painter.drawPath(triagPath)
def paint(self, painter, option, index): assert isinstance(painter, QPainter) if index.data(Qt.UserRole+1): if app_constants.HIGH_QUALITY_THUMBS: painter.setRenderHint(QPainter.SmoothPixmapTransform) painter.setRenderHint(QPainter.Antialiasing) gallery = index.data(Qt.UserRole+1) title = gallery.title artist = gallery.artist title_color = app_constants.GRID_VIEW_TITLE_COLOR artist_color = app_constants.GRID_VIEW_ARTIST_COLOR label_color = app_constants.GRID_VIEW_LABEL_COLOR # Enable this to see the defining box #painter.drawRect(option.rect) # define font size if 20 > len(title) > 15: title_size = "font-size:{}px;".format(self.font_size) elif 30 > len(title) > 20: title_size = "font-size:{}px;".format(self.font_size-1) elif 40 > len(title) >= 30: title_size = "font-size:{}px;".format(self.font_size-2) elif 50 > len(title) >= 40: title_size = "font-size:{}px;".format(self.font_size-3) elif len(title) >= 50: title_size = "font-size:{}px;".format(self.font_size-4) else: title_size = "font-size:{}px;".format(self.font_size) if 30 > len(artist) > 20: artist_size = "font-size:{}px;".format(self.font_size) elif 40 > len(artist) >= 30: artist_size = "font-size:{}px;".format(self.font_size-1) elif len(artist) >= 40: artist_size = "font-size:{}px;".format(self.font_size-2) else: artist_size = "font-size:{}px;".format(self.font_size) #painter.setPen(QPen(Qt.NoPen)) #option.rect = option.rect.adjusted(11, 10, 0, 0) option.rect.setWidth(self.W) option.rect.setHeight(self.H) rec = option.rect.getRect() x = rec[0] y = rec[1] w = rec[2] h = rec[3] text_area = QTextDocument() text_area.setDefaultFont(option.font) text_area.setHtml(""" <head> <style> #area {{ display:flex; width:{6}px; height:{7}px }} #title {{ position:absolute; color: {4}; font-weight:bold; {0} }} #artist {{ position:absolute; color: {5}; top:20px; right:0; {1} }} </style> </head> <body> <div id="area"> <center> <div id="title">{2} </div> <div id="artist">{3} </div> </div> </center> </body> """.format(title_size, artist_size, title, artist, title_color, artist_color, 130+app_constants.SIZE_FACTOR, 1+app_constants.SIZE_FACTOR)) text_area.setTextWidth(w) #chapter_area = QTextDocument() #chapter_area.setDefaultFont(option.font) #chapter_area.setHtml(""" #<font color="black">{}</font> #""".format("chapter")) #chapter_area.setTextWidth(w) def center_img(width): new_x = x if width < w: diff = w - width offset = diff//2 new_x += offset return new_x def img_too_big(start_x): txt_layout = misc.text_layout("Image is too big!", w, self.title_font, self.title_font_m) clipping = QRectF(x, y+h//4, w, app_constants.GRIDBOX_LBL_H - 10) txt_layout.draw(painter, QPointF(x, y+h//4), clip=clipping) # if we can't find a cached image pix_cache = QPixmapCache.find(self.key(gallery.profile)) if isinstance(pix_cache, QPixmap): self.image = pix_cache img_x = center_img(self.image.width()) if self.image.width() > w or self.image.height() > h: img_too_big(img_x) else: if self.image.height() < self.image.width(): #to keep aspect ratio painter.drawPixmap(QPoint(img_x,y), self.image) else: painter.drawPixmap(QPoint(img_x,y), self.image) else: self.image = QPixmap(gallery.profile) img_x = center_img(self.image.width()) QPixmapCache.insert(self.key(gallery.profile), self.image) if self.image.width() > w or self.image.height() > h: img_too_big(img_x) else: if self.image.height() < self.image.width(): #to keep aspect ratio painter.drawPixmap(QPoint(img_x,y), self.image) else: painter.drawPixmap(QPoint(img_x,y), self.image) # draw ribbon type painter.save() painter.setPen(Qt.NoPen) if app_constants.DISPLAY_GALLERY_RIBBON: type_ribbon_w = type_ribbon_l = w*0.11 rib_top_1 = QPointF(x+w-type_ribbon_l-type_ribbon_w, y) rib_top_2 = QPointF(x+w-type_ribbon_l, y) rib_side_1 = QPointF(x+w, y+type_ribbon_l) rib_side_2 = QPointF(x+w, y+type_ribbon_l+type_ribbon_w) ribbon_polygon = QPolygonF([rib_top_1, rib_top_2, rib_side_1, rib_side_2]) ribbon_path = QPainterPath() ribbon_path.setFillRule(Qt.WindingFill) ribbon_path.addPolygon(ribbon_polygon) ribbon_path.closeSubpath() painter.setBrush(QBrush(QColor(self._ribbon_color(gallery.type)))) painter.drawPath(ribbon_path) # draw if favourited if gallery.fav == 1: star_ribbon_w = star_ribbon_l = w*0.08 rib_top_1 = QPointF(x+star_ribbon_l, y) rib_side_1 = QPointF(x, y+star_ribbon_l) rib_top_2 = QPointF(x+star_ribbon_l+star_ribbon_w, y) rib_side_2 = QPointF(x, y+star_ribbon_l+star_ribbon_w) rib_star_mid_1 = QPointF((rib_top_1.x()+rib_side_1.x())/2, (rib_top_1.y()+rib_side_1.y())/2) rib_star_factor = star_ribbon_l/4 rib_star_p1_1 = rib_star_mid_1 + QPointF(rib_star_factor, -rib_star_factor) rib_star_p1_2 = rib_star_p1_1 + QPointF(-rib_star_factor, -rib_star_factor) rib_star_p1_3 = rib_star_mid_1 + QPointF(-rib_star_factor, rib_star_factor) rib_star_p1_4 = rib_star_p1_3 + QPointF(-rib_star_factor, -rib_star_factor) crown_1 = QPolygonF([rib_star_p1_1, rib_star_p1_2, rib_star_mid_1, rib_star_p1_4, rib_star_p1_3]) painter.setBrush(QBrush(QColor("yellow"))) painter.drawPolygon(crown_1) ribbon_polygon = QPolygonF([rib_top_1, rib_side_1, rib_side_2, rib_top_2]) ribbon_path = QPainterPath() ribbon_path.setFillRule(Qt.WindingFill) ribbon_path.addPolygon(ribbon_polygon) ribbon_path.closeSubpath() painter.drawPath(ribbon_path) #painter.setPen(QColor("#d35400")) #painter.drawPolyline(rib_top_1, rib_star_p1_1, rib_star_p1_2, rib_star_mid_1, rib_star_p1_4, rib_star_p1_3, rib_side_1) #painter.drawLine(rib_top_1, rib_top_2) #painter.drawLine(rib_top_2, rib_side_2) #painter.drawLine(rib_side_1, rib_side_2) painter.restore() if app_constants._REFRESH_EXTERNAL_VIEWER: if app_constants.USE_EXTERNAL_VIEWER: self.external_icon = self.file_icons.get_external_file_icon() else: self.external_icon = self.file_icons.get_default_file_icon() if gallery.state == self.G_DOWNLOAD: painter.save() dl_box = QRect(x, y, w, 20) painter.setBrush(QBrush(QColor(0,0,0,123))) painter.setPen(QColor('white')) painter.drawRect(dl_box) painter.drawText(dl_box, Qt.AlignCenter, 'Downloading...') painter.restore() else: if app_constants.DISPLAY_GALLERY_TYPE: self.type_icon = self.file_icons.get_file_icon(gallery.path) if self.type_icon and not self.type_icon.isNull(): self.type_icon.paint(painter, QRect(x+2, y+app_constants.THUMB_H_SIZE-16, 16, 16)) if app_constants.USE_EXTERNAL_PROG_ICO: if self.external_icon and not self.external_icon.isNull(): self.external_icon.paint(painter, QRect(x+w-30, y+app_constants.THUMB_H_SIZE-28, 28, 28)) def draw_text_label(lbl_h): #draw the label for text painter.save() painter.translate(x, y+app_constants.THUMB_H_SIZE) box_color = QBrush(QColor(label_color))#QColor(0,0,0,123)) painter.setBrush(box_color) rect = QRect(0, 0, w, lbl_h) #x, y, width, height painter.fillRect(rect, box_color) painter.restore() return rect if option.state & QStyle.State_MouseOver or\ option.state & QStyle.State_Selected: title_layout = misc.text_layout(title, w, self.title_font, self.title_font_m) artist_layout = misc.text_layout(artist, w, self.artist_font, self.artist_font_m) t_h = title_layout.boundingRect().height() a_h = artist_layout.boundingRect().height() if app_constants.GALLERY_FONT_ELIDE: lbl_rect = draw_text_label(min(t_h+a_h+3, app_constants.GRIDBOX_LBL_H)) else: lbl_rect = draw_text_label(app_constants.GRIDBOX_LBL_H) clipping = QRectF(x, y+app_constants.THUMB_H_SIZE, w, app_constants.GRIDBOX_LBL_H - 10) painter.setPen(QColor(title_color)) title_layout.draw(painter, QPointF(x, y+app_constants.THUMB_H_SIZE), clip=clipping) painter.setPen(QColor(artist_color)) artist_layout.draw(painter, QPointF(x, y+app_constants.THUMB_H_SIZE+t_h), clip=clipping) #painter.fillRect(option.rect, QColor) else: if app_constants.GALLERY_FONT_ELIDE: lbl_rect = draw_text_label(self.text_label_h) else: lbl_rect = draw_text_label(app_constants.GRIDBOX_LBL_H) # draw text painter.save() alignment = QTextOption(Qt.AlignCenter) alignment.setUseDesignMetrics(True) title_rect = QRectF(0,0,w, self.title_font_m.height()) artist_rect = QRectF(0,self.artist_font_m.height(),w, self.artist_font_m.height()) painter.translate(x, y+app_constants.THUMB_H_SIZE) if app_constants.GALLERY_FONT_ELIDE: painter.setFont(self.title_font) painter.setPen(QColor(title_color)) painter.drawText(title_rect, self.title_font_m.elidedText(title, Qt.ElideRight, w-10), alignment) painter.setPen(QColor(artist_color)) painter.setFont(self.artist_font) alignment.setWrapMode(QTextOption.NoWrap) painter.drawText(artist_rect, self.title_font_m.elidedText(artist, Qt.ElideRight, w-10), alignment) else: text_area.setDefaultFont(QFont(self.font_name)) text_area.drawContents(painter) ##painter.resetTransform() painter.restore() if option.state & QStyle.State_Selected: painter.save() selected_rect = QRectF(x, y, w, lbl_rect.height()+app_constants.THUMB_H_SIZE) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(QColor(164,164,164,120))) painter.drawRoundedRect(selected_rect, 5, 5) #painter.fillRect(selected_rect, QColor(164,164,164,120)) painter.restore() if gallery.dead_link: painter.save() selected_rect = QRectF(x, y, w, lbl_rect.height()+app_constants.THUMB_H_SIZE) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(QColor(255,0,0,120))) p_path = QPainterPath() p_path.setFillRule(Qt.WindingFill) p_path.addRoundedRect(selected_rect, 5,5) p_path.addRect(x,y, 20, 20) p_path.addRect(x+w-20,y, 20, 20) painter.drawPath(p_path.simplified()) painter.setPen(QColor("white")) txt_layout = misc.text_layout("Cannot find gallery source!", w, self.title_font, self.title_font_m) txt_layout.draw(painter, QPointF(x, y+h*0.3)) painter.restore() if app_constants.DEBUG: painter.save() painter.setBrush(QBrush(QColor("red"))) painter.setPen(QColor("white")) txt_l = self.title_font_m.width(str(gallery.id)) painter.drawRect(x, y+40, txt_l*2, self.title_font_m.height()) painter.drawText(x+1, y+51, str(gallery.id)) painter.restore() if option.state & QStyle.State_Selected: painter.setPen(QPen(option.palette.highlightedText().color())) else: super().paint(painter, option, index)
def drawGlyphPoints( painter, glyph, scale, rect, drawStartPoints=True, drawOnCurves=True, drawOffCurves=True, drawCoordinates=False, drawSelection=True, onCurveColor=None, otherColor=None, backgroundColor=None): if onCurveColor is None: layer = glyph.layer if layer is not None and layer.color is not None: onCurveColor = colorToQColor(layer.color) else: onCurveColor = defaultColor("glyphOnCurvePoints") if otherColor is None: otherColor = defaultColor("glyphOtherPoints") if backgroundColor is None: backgroundColor = defaultColor("background") # get the outline data outlineData = glyph.getRepresentation("defconQt.OutlineInformation") points = [] # start points if drawStartPoints and outlineData["startPoints"]: startWidth = startHeight = 15 * scale startHalf = startWidth / 2.0 path = QPainterPath() for point, angle in outlineData["startPoints"]: x, y = point if angle is not None: path.moveTo(x, y) path.arcTo(x - startHalf, y - startHalf, startWidth, startHeight, 180 - angle, 180) path.closeSubpath() else: path.addEllipse( x - startHalf, y - startHalf, startWidth, startHeight) startPointColor = QColor(otherColor) aF = startPointColor.alphaF() startPointColor.setAlphaF(aF * .3) painter.fillPath(path, startPointColor) # handles if drawOffCurves and outlineData["offCurvePoints"]: painter.save() painter.setPen(otherColor) for pt1, pt2 in outlineData["bezierHandles"]: x1, y1 = pt1 x2, y2 = pt2 # TODO: should lineWidth account scale by default drawLine(painter, x1, y1, x2, y2, 1.0 * scale) painter.restore() # on curve if drawOnCurves and outlineData["onCurvePoints"]: width = 7 * scale half = width / 2.0 smoothWidth = 8 * scale smoothHalf = smoothWidth / 2.0 painter.save() path = QPainterPath() selectedPath = QPainterPath() for point in outlineData["onCurvePoints"]: x, y = point["point"] points.append((x, y)) pointPath = QPainterPath() if point["smooth"]: x -= smoothHalf y -= smoothHalf pointPath.addEllipse(x, y, smoothWidth, smoothWidth) else: x -= half y -= half pointPath.addRect(x, y, width, width) if drawSelection and point["selected"]: selectedPath.addPath(pointPath) path.addPath(pointPath) pen = QPen(onCurveColor) pen.setWidthF(1.5 * scale) painter.setPen(pen) painter.fillPath(selectedPath, onCurveColor) painter.drawPath(path) painter.restore() # off curve if drawOffCurves and outlineData["offCurvePoints"]: # lines # points offWidth = 5 * scale offHalf = offWidth / 2.0 path = QPainterPath() selectedPath = QPainterPath() for point in outlineData["offCurvePoints"]: x, y = point["point"] points.append((x, y)) pointPath = QPainterPath() x -= offHalf y -= offHalf pointPath.addEllipse(x, y, offWidth, offWidth) if drawSelection and point["selected"]: selectedPath.addPath(pointPath) else: path.addPath(pointPath) pen = QPen(otherColor) pen.setWidthF(3.0 * scale) painter.save() painter.setPen(pen) painter.drawPath(path) painter.fillPath(path, QBrush(backgroundColor)) painter.drawPath(selectedPath) painter.fillPath(selectedPath, QBrush(otherColor)) painter.restore() # coordinates if drawCoordinates: otherColor = QColor(otherColor) otherColor.setAlphaF(otherColor.alphaF() * .6) painter.save() painter.setPen(otherColor) # TODO: decision + color font = painter.font() font.setPointSize(7) painter.setFont(font) for x, y in points: posX = x # TODO: We use + here because we align on top. Consider abstracting # yOffset. posY = y + 3 x = round(x, 1) if int(x) == x: x = int(x) y = round(y, 1) if int(y) == y: y = int(y) text = "%d %d" % (x, y) drawTextAtPoint(painter, text, posX, posY, scale, xAlign="center", yAlign="top") painter.restore()
class PolygonWidget(QWidget): """PolygonWidget(QWidget) Provides a custom widget to display a polygon with properties and slots that can be used to customize its appearance. """ def __init__(self, parent=None): super(PolygonWidget, self).__init__(parent) self._sides = 5 self._innerRadius = 20 self._outerRadius = 50 self._angle = 0 self.createPath() self._innerColor = QColor(255, 255, 128) self._outerColor = QColor(255, 0, 128) self.createGradient() def paintEvent(self, event): painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.Antialiasing) painter.setBrush(QBrush(QColor(192, 192, 255))) painter.drawRect(event.rect()) painter.translate(self.width()/2.0, self.height()/2.0) painter.rotate(self._angle) painter.setBrush(QBrush(self.gradient)) painter.drawPath(self.path) painter.end() def sizeHint(self): return QSize(2*self._outerRadius + 20, 2*self._outerRadius + 20) 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 createGradient(self): center = QPointF(0, 0) self.gradient = QRadialGradient(center, self._outerRadius, center) self.gradient.setColorAt(0.5, QColor(self._innerColor)) self.gradient.setColorAt(1.0, QColor(self._outerColor)) # The angle property is implemented using the getAngle() and setAngle() # methods. def getAngle(self): return self._angle # The setAngle() setter method is also a slot. @pyqtSlot(int) def setAngle(self, angle): self._angle = min(max(0, angle), 360) self.update() angle = pyqtProperty(int, getAngle, setAngle) # The innerRadius property is implemented using the getInnerRadius() and # setInnerRadius() methods. def getInnerRadius(self): return self._innerRadius # The setInnerRadius() setter method is also a slot. @pyqtSlot(int) def setInnerRadius(self, radius): self._innerRadius = radius self.createPath() self.createGradient() self.update() innerRadius = pyqtProperty(int, getInnerRadius, setInnerRadius) # The outerRadius property is implemented using the getOuterRadius() and # setOuterRadius() methods. def getOuterRadius(self): return self._outerRadius # The setOuterRadius() setter method is also a slot. @pyqtSlot(int) def setOuterRadius(self, radius): self._outerRadius = radius self.createPath() self.createGradient() self.update() outerRadius = pyqtProperty(int, getOuterRadius, setOuterRadius) # The numberOfSides property is implemented using the getNumberOfSides() # and setNumberOfSides() methods. def getNumberOfSides(self): return self._sides # The setNumberOfSides() setter method is also a slot. @pyqtSlot(int) def setNumberOfSides(self, sides): self._sides = max(3, sides) self.createPath() self.update() numberOfSides = pyqtProperty(int, getNumberOfSides, setNumberOfSides) # The innerColor property is implemented using the getInnerColor() and # setInnerColor() methods. def getInnerColor(self): return self._innerColor def setInnerColor(self, color): self._innerColor = max(3, color) self.createGradient() self.update() innerColor = pyqtProperty(QColor, getInnerColor, setInnerColor) # The outerColor property is implemented using the getOuterColor() and # setOuterColor() methods. def getOuterColor(self): return self._outerColor def setOuterColor(self, color): self._outerColor = color self.createGradient() self.update() outerColor = pyqtProperty(QColor, getOuterColor, setOuterColor)
def paintEvent(self, pe): p = QPainter(self) p.setRenderHint(QPainter.Antialiasing) pen = QPen() pen.setWidth(1) pen.setColor(QColor(0x8c, 0xa3, 0xb0)) p.setPen(pen) p.setBrush(QColor(0xe4, 0xec, 0xf4)) rx = 6 space = self.space w = self.usable_width kw = self.key_w def drawRow(row, sx, sy, last_end=False): x = sx y = sy keys = row rw = w - sx i = 0 for k in keys: rect = QRectF(x, y, kw, kw) if i == len(keys) - 1 and last_end: rect.setWidth(rw) p.drawRoundedRect(rect, rx, rx) p.setPen(Qt.black) rect.adjust(5, 1, 0, 0) p.setFont(self.lowerFont) p.drawText( rect, Qt.AlignLeft | Qt.AlignBottom, self.regular_text(k)) p.setFont(self.upperFont) p.drawText( rect, Qt.AlignLeft | Qt.AlignTop, self.shift_text(k)) rw = rw - space - kw x = x + space + kw i = i + 1 p.setPen(pen) return (x, rw) x = .5 y = .5 keys = self.kb["keys"] ext_return = self.kb["extended_return"] first_key_w = 0 rows = 4 remaining_x = [0, 0, 0, 0] remaining_widths = [0, 0, 0, 0] for i in range(0, rows): if first_key_w > 0: first_key_w = first_key_w * 1.375 if self.kb == self.kb_105 and i == 3: first_key_w = kw * 1.275 rect = QRectF(x, y, first_key_w, kw) p.drawRoundedRect(rect, rx, rx) x = x + first_key_w + space else: first_key_w = kw x, rw = drawRow(keys[i], x, y, i == 1 and not ext_return) remaining_x[i] = x remaining_widths[i] = rw if i != 1 and i != 2: rect = QRectF(x, y, rw, kw) p.drawRoundedRect(rect, rx, rx) x = .5 y = y + space + kw if ext_return: rx = rx * 2 x1 = remaining_x[1] y1 = .5 + kw * 1 + space * 1 w1 = remaining_widths[1] x2 = remaining_x[2] y2 = .5 + kw * 2 + space * 2 # this is some serious crap... but it has to be so # maybe one day keyboards won't look like this... # one can only hope pp = QPainterPath() pp.moveTo(x1, y1 + rx) pp.arcTo(x1, y1, rx, rx, 180, -90) pp.lineTo(x1 + w1 - rx, y1) pp.arcTo(x1 + w1 - rx, y1, rx, rx, 90, -90) pp.lineTo(x1 + w1, y2 + kw - rx) pp.arcTo(x1 + w1 - rx, y2 + kw - rx, rx, rx, 0, -90) pp.lineTo(x2 + rx, y2 + kw) pp.arcTo(x2, y2 + kw - rx, rx, rx, -90, -90) pp.lineTo(x2, y1 + kw) pp.lineTo(x1 + rx, y1 + kw) pp.arcTo(x1, y1 + kw - rx, rx, rx, -90, -90) pp.closeSubpath() p.drawPath(pp) else: x = remaining_x[2] y = .5 + kw * 2 + space * 2 rect = QRectF(x, y, remaining_widths[2], kw) p.drawRoundedRect(rect, rx, rx) QWidget.paintEvent(self, pe)
def __init__(self): super(Window, self).__init__() rectPath = QPainterPath() rectPath.moveTo(20.0, 30.0) rectPath.lineTo(80.0, 30.0) rectPath.lineTo(80.0, 70.0) rectPath.lineTo(20.0, 70.0) rectPath.closeSubpath() roundRectPath = QPainterPath() roundRectPath.moveTo(80.0, 35.0) roundRectPath.arcTo(70.0, 30.0, 10.0, 10.0, 0.0, 90.0) roundRectPath.lineTo(25.0, 30.0) roundRectPath.arcTo(20.0, 30.0, 10.0, 10.0, 90.0, 90.0) roundRectPath.lineTo(20.0, 65.0) roundRectPath.arcTo(20.0, 60.0, 10.0, 10.0, 180.0, 90.0) roundRectPath.lineTo(75.0, 70.0) roundRectPath.arcTo(70.0, 60.0, 10.0, 10.0, 270.0, 90.0) roundRectPath.closeSubpath() ellipsePath = QPainterPath() ellipsePath.moveTo(80.0, 50.0) ellipsePath.arcTo(20.0, 30.0, 60.0, 40.0, 0.0, 360.0) piePath = QPainterPath() piePath.moveTo(50.0, 50.0) piePath.lineTo(65.0, 32.6795) piePath.arcTo(20.0, 30.0, 60.0, 40.0, 60.0, 240.0) piePath.closeSubpath() polygonPath = QPainterPath() polygonPath.moveTo(10.0, 80.0) polygonPath.lineTo(20.0, 10.0) polygonPath.lineTo(80.0, 30.0) polygonPath.lineTo(90.0, 70.0) polygonPath.closeSubpath() groupPath = QPainterPath() groupPath.moveTo(60.0, 40.0) groupPath.arcTo(20.0, 20.0, 40.0, 40.0, 0.0, 360.0) groupPath.moveTo(40.0, 40.0) groupPath.lineTo(40.0, 80.0) groupPath.lineTo(80.0, 80.0) groupPath.lineTo(80.0, 40.0) groupPath.closeSubpath() textPath = QPainterPath() timesFont = QFont('Times', 50) timesFont.setStyleStrategy(QFont.ForceOutline) textPath.addText(10, 70, timesFont, "Qt") bezierPath = QPainterPath() bezierPath.moveTo(20, 30) bezierPath.cubicTo(80, 0, 50, 50, 80, 80) starPath = QPainterPath() starPath.moveTo(90, 50) for i in range(1, 5): starPath.lineTo(50 + 40 * cos(0.8 * i * pi), 50 + 40 * sin(0.8 * i * pi)) starPath.closeSubpath() self.renderAreas = [RenderArea(rectPath), RenderArea(roundRectPath), RenderArea(ellipsePath), RenderArea(piePath), RenderArea(polygonPath), RenderArea(groupPath), RenderArea(textPath), RenderArea(bezierPath), RenderArea(starPath)] assert len(self.renderAreas) == 9 self.fillRuleComboBox = QComboBox() self.fillRuleComboBox.addItem("Odd Even", Qt.OddEvenFill) self.fillRuleComboBox.addItem("Winding", Qt.WindingFill) fillRuleLabel = QLabel("Fill &Rule:") fillRuleLabel.setBuddy(self.fillRuleComboBox) self.fillColor1ComboBox = QComboBox() self.populateWithColors(self.fillColor1ComboBox) self.fillColor1ComboBox.setCurrentIndex( self.fillColor1ComboBox.findText("mediumslateblue")) self.fillColor2ComboBox = QComboBox() self.populateWithColors(self.fillColor2ComboBox) self.fillColor2ComboBox.setCurrentIndex( self.fillColor2ComboBox.findText("cornsilk")) fillGradientLabel = QLabel("&Fill Gradient:") fillGradientLabel.setBuddy(self.fillColor1ComboBox) fillToLabel = QLabel("to") fillToLabel.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.penWidthSpinBox = QSpinBox() self.penWidthSpinBox.setRange(0, 20) penWidthLabel = QLabel("&Pen Width:") penWidthLabel.setBuddy(self.penWidthSpinBox) self.penColorComboBox = QComboBox() self.populateWithColors(self.penColorComboBox) self.penColorComboBox.setCurrentIndex( self.penColorComboBox.findText('darkslateblue')) penColorLabel = QLabel("Pen &Color:") penColorLabel.setBuddy(self.penColorComboBox) self.rotationAngleSpinBox = QSpinBox() self.rotationAngleSpinBox.setRange(0, 359) self.rotationAngleSpinBox.setWrapping(True) self.rotationAngleSpinBox.setSuffix(u'\N{DEGREE SIGN}') rotationAngleLabel = QLabel("&Rotation Angle:") rotationAngleLabel.setBuddy(self.rotationAngleSpinBox) self.fillRuleComboBox.activated.connect(self.fillRuleChanged) self.fillColor1ComboBox.activated.connect(self.fillGradientChanged) self.fillColor2ComboBox.activated.connect(self.fillGradientChanged) self.penColorComboBox.activated.connect(self.penColorChanged) for i in range(Window.NumRenderAreas): self.penWidthSpinBox.valueChanged.connect(self.renderAreas[i].setPenWidth) self.rotationAngleSpinBox.valueChanged.connect(self.renderAreas[i].setRotationAngle) topLayout = QGridLayout() for i in range(Window.NumRenderAreas): topLayout.addWidget(self.renderAreas[i], i / 3, i % 3) mainLayout = QGridLayout() mainLayout.addLayout(topLayout, 0, 0, 1, 4) mainLayout.addWidget(fillRuleLabel, 1, 0) mainLayout.addWidget(self.fillRuleComboBox, 1, 1, 1, 3) mainLayout.addWidget(fillGradientLabel, 2, 0) mainLayout.addWidget(self.fillColor1ComboBox, 2, 1) mainLayout.addWidget(fillToLabel, 2, 2) mainLayout.addWidget(self.fillColor2ComboBox, 2, 3) mainLayout.addWidget(penWidthLabel, 3, 0) mainLayout.addWidget(self.penWidthSpinBox, 3, 1, 1, 3) mainLayout.addWidget(penColorLabel, 4, 0) mainLayout.addWidget(self.penColorComboBox, 4, 1, 1, 3) mainLayout.addWidget(rotationAngleLabel, 5, 0) mainLayout.addWidget(self.rotationAngleSpinBox, 5, 1, 1, 3) self.setLayout(mainLayout) self.fillRuleChanged() self.fillGradientChanged() self.penColorChanged() self.penWidthSpinBox.setValue(2) self.setWindowTitle("Painter Paths")