def createPixmap(self): """Creates the pixmap shown when this label is dragged.""" font_metric = QFontMetrics(QFont()) text_size = font_metric.size(Qt.TextSingleLine, self.text) image = QImage(text_size.width() + 4, text_size.height() + 4, QImage.Format_ARGB32_Premultiplied) image.fill(qRgba(240, 240, 120, 255)) painter = QPainter() painter.begin(image) painter.setFont(QFont()) painter.setBrush(Qt.black) painter.drawText(QRect(QPoint(2, 2), text_size), Qt.AlignCenter, self.text) painter.end() return image
def paint(self, canvas, is_secondary_color=False, additional_flag=False): pen = QPen() if is_secondary_color: pen.setColor(self.data_singleton.secondary_color) else: pen.setColor(self.data_singleton.primary_color) painter = QPainter(canvas.image) painter.setRenderHint(QPainter.Antialiasing) pen.setWidth(self.data_singleton.pen_size) pen.setStyle(Qt.SolidLine) pen.setCapStyle(Qt.RoundCap) pen.setJoinStyle(Qt.RoundJoin) painter.setPen(pen) if is_secondary_color: painter.setBrush(self.data_singleton.primary_color) else: painter.setBrush(self.data_singleton.secondary_color) if self._start_point != self._end_point: painter.drawRect(QRect(self._start_point, self._end_point)) painter.end() canvas.edited = True canvas.update()
def saveAsPdf(self, fn, force=False): """ Save bar image as a eps file. Args: fn: Filename force: if True, overwrites an existing file. If false, raises a RuntimeError if file already exists. """ printer = QPrinter(QPrinter.HighResolution) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(fn) printer.setFullPage(True) printer.setPageSize(QPrinter.Custom) printer.setPaperSize(QSizeF(*self.size), QPrinter.Millimeter) printer.setPageMargins(0, 0, 0, 0, QPrinter.Millimeter) painter = QPainter(printer) painter.setRenderHint(QPainter.Antialiasing) painter.setBrush(Qt.white) painter.setPen(Qt.white) painter.drawRect(QRect(0, 0, *self.size)) targetrect = QRectF(0, 0, printer.width(), printer.height()) sourcerect = QRectF(0, 0, *self.size) self.render(painter, targetrect, sourcerect) painter.end() return True
def paintEvent(self, pe): painter = QPainter(self) painter.save() gradient = QLinearGradient() gradient.setStart(self._grad_start) gradient.setFinalStop(self._grad_end) gradient.setColorAt(0, QColor(230, 230, 230)) gradient.setColorAt(1, QColor(247, 247, 247)) brush = QBrush(gradient) painter.setBrush(brush) pen = QPen(Qt.black) pen.setWidth(1) painter.setPen(pen) painter.drawPath(self._painter_path) painter.restore() font = QFont() font.setFamily("Tahoma") font.setPixelSize(11) font.setBold(True) pen = QPen(Qt.darkGray) painter.setPen(pen) painter.setFont(font) self_rect = QRect(self.rect()) self_rect.moveTo(self._hor_margin, self._ver_margin // 2) painter.drawText(self_rect, Qt.AlignLeft, self._text)
def saveAsBitmap(self, fn): """ Save bar image as a jpg file. Overwrites a file already existing in filesystem. https://stackoverflow.com/questions/7451183/how-to-create-image-file\ -from-qgraphicsscene-qgraphicsview#11642517 Args: fn: Filename Returns: True on success """ size = self.size pixelsx = max(1200, size[0]) pixelsy = int(pixelsx*size[1]/size[0]) imagesize = (pixelsx, pixelsy) image = QImage(pixelsx, pixelsy, QImage.Format_ARGB32_Premultiplied) painter = QPainter(image) painter.setRenderHint(QPainter.Antialiasing) painter.setBrush(Qt.white) painter.setPen(Qt.white) painter.drawRect(QRect(0, 0, *imagesize)) targetrect = QRectF(0, 0, *imagesize) sourcerect = QRectF(0, 0, *size) self.render(painter, targetrect, sourcerect) painter.end() return image.save(fn)
def paintEvent(self, pe): if self._drop_zones_shown: painter = QPainter(self.viewport( )) # See documentation to know why I draw on the viewport painter.setFont(self._titles_font) vr = self.rect() nb_drop_zones = len(self._drop_zones_titles) subr = QRect(vr) subr.setHeight(vr.height() / nb_drop_zones) for i in range(nb_drop_zones): c = self._drop_zones_colors[i] text_pen = QPen() text_pen.setColor(inverse_colors(c)) painter.setPen(text_pen) if i == self._selected_drop_zone: # mainlog.debug("selected drop zone is {}".format(i)) c = c.lighter(200) painter.setBrush(c) subr.moveTop(int(i * vr.height() / nb_drop_zones)) painter.drawRect(subr) painter.drawText( QPoint(10, int((i + 0.5) * vr.height() / nb_drop_zones)), self._drop_zones_titles[i]) return None else: return super(AnimatedTableView, self).paintEvent(pe)
def paintEvent(self, ev): if self.isEnabled(): color = self.color colorBorder = [0.4, 0.4, 0.4] else: color = [0.8, 0.8, 0.8] colorBorder = [0.7, 0.7, 0.7] painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) painter.setRenderHint(QPainter.HighQualityAntialiasing) if self.isChecked(): pen = QPen(QColor.fromRgbF(0.2, 0.2, 0.2)) pen.setWidth(2.0) else: pen = QPen( QColor.fromRgbF(colorBorder[0], colorBorder[1], colorBorder[2])) pen.setWidth(1.0) size = self.size() sizeCircle = 12.0 x = size.width() / 2.0 - (sizeCircle / 2.0) y = size.height() / 2.0 - (sizeCircle / 2.0) rect = QRectF(x, y, sizeCircle, sizeCircle) painter.setPen(pen) painter.setBrush(QColor.fromRgbF(color[0], color[1], color[2])) painter.drawEllipse(rect)
def paintEvent(self, event): paintRegion = event.region() painter = QPainter(self) pal = self.palette() for shape in self._shapeList: rect = shape.rect if not paintRegion.contains(rect): continue shapeType = shape.type painter.setBrush(shape.color) if shapeType == ShapeType.Rectangle: print "rectangle" painter.drawRect(rect) elif shapeType == ShapeType.Circle: print "circle" painter.drawEllipse(rect) # paint the shape name painter.setBrush(pal.text()) painter.drawText(rect, Qt.AlignCenter, shape.name)
def paintEvent(self, ev): if self.isEnabled(): color = self.color colorBorder = [0.4, 0.4, 0.4] else: color = [0.8, 0.8, 0.8] colorBorder = [0.7, 0.7, 0.7] painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) painter.setRenderHint(QPainter.HighQualityAntialiasing) if self.isChecked(): pen = QPen(QColor.fromRgbF(0.2, 0.2, 0.2)) pen.setWidth(2.0) else: pen = QPen(QColor.fromRgbF(colorBorder[0], colorBorder[1], colorBorder[2])) pen.setWidth(1.0) size = self.size() sizeCircle = 12.0 x = size.width() / 2.0 - (sizeCircle / 2.0) y = size.height() / 2.0 - (sizeCircle / 2.0) rect = QRectF(x, y, sizeCircle, sizeCircle) painter.setPen(pen) painter.setBrush(QColor.fromRgbF(color[0], color[1], color[2])) painter.drawEllipse(rect)
def paintEvent(self, pe): # make an arrow polygon right in the middle painter = QPainter(self) painter.setPen(Qt.NoPen) # draw the background transparent rect painter.save() painter.setOpacity(self.BACKGROUND_OPACITY) # get the rectangle coordinates it should extend over the whole width with only a portion at the center painter.setBrush(Qt.black) empty_space_percent = 1 - self.BACKROUND_HEIGHT_PERCENT rect_top = empty_space_percent / 2 * self.height() rect_height = self.BACKROUND_HEIGHT_PERCENT * self.height() painter.drawRect(0, rect_top, self.width(), rect_height) painter.restore() painter.setRenderHint(QPainter.Antialiasing) pen = QPen() pen.setWidth(self.ARROW_LINE_WIDTH) pen.setCapStyle(Qt.RoundCap) if self._mouse_inside: pen.setColor(self._hover_color) else: pen.setColor(self._normal_color) # get the arrow coords painter.setPen(pen) self_center = QPointF(self.width() / 2, self.height() / 2) # use this as the arrow tip for now if self._direction == self.LEFT: h_shift = self._arrow_width elif self._direction == self.RIGHT: h_shift = - self._arrow_width v_shift = self._arrow_height / 2 top_point = self_center + QPointF(h_shift, - v_shift) bottom_point = self_center + QPointF(h_shift, v_shift) painter.drawLine(top_point, self_center) painter.drawLine(self_center, bottom_point)
def paintEvent(self, event): painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.HighQualityAntialiasing) painter.setRenderHint(QPainter.Antialiasing) painter.setRenderHint(QPainter.SmoothPixmapTransform) painter.setBrush(QColor(self.color)) painter.drawRect(self.window().x() + 4, self.window().y() + 4, self.window().width(), self._height) painter.end()
def paintEvent(self, evt): # print 'paint', self.color, self.text(), self.width(), self.height(), evt.rect().width() qp = QPainter() qp.begin(self) qp.setBrush(QColor('#{}'.format(self.color[:-2]))) qp.drawRect(0, 0, self.width(), self.height()) qp.end() qp.begin(self) qp.setPen(self._get_text_color()) qp.drawText(evt.rect(), QtCore.Qt.AlignCenter, self.text()) qp.end()
def paintEvent(self, event): painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.HighQualityAntialiasing) painter.setRenderHint(QPainter.Antialiasing) painter.setRenderHint(QPainter.SmoothPixmapTransform) painter.setBrush(self.color) if self.effect_size == self.radius: painter.drawEllipse(1, 1, self.radius - 1, self.radius - 1) painter.drawPixmap(QRect(14, 14, self.radius / 2, self.radius / 2), self.pixmap) else: painter.drawEllipse(self.width() / 2, self.height() / 2, self.effect_size, self.effect_size) painter.end()
def paintEvent(self,e): painter = QPainter(self) for rect in self.rectangles: try: xa,ya,xb,yb = rect rect = xa,ya,xb-xa,yb-ya painter.setBrush(randomColor()) painter.drawRect(QRect(*rect)) except: print('rect was foul')
def paintEvent(self, event): painter = QPainter(self) painter.setBrush(Qt.white) painter.drawRect(self.rect()) painter.translate(self.width()/2, self.height()/2) if self.pixReady: grammarPix = QPixmap("/tmp/grammar.png") pw = grammarPix.width() ph = grammarPix.height() painter.drawPixmap(-pw/2, -ph/2, grammarPix)
def paintEvent(self, event): painter = QPainter(self) painter.setBrush(self.brush) painter.setPen(self.pen) painter.setRenderHint(QPainter.Antialiasing) rect = self.geometry() from_point = QPointF(0, rect.height() / 2) to_point = QPointF(rect.width(), rect.height() / 2) # from_point = QPointF(0, 0) # to_point = QPointF(rect.width(), rect.height()) # noinspection PyProtectedMember ClassyEdge._draw_arrow(painter, from_point, to_point, 10)
def paintEvent(self, event): painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.HighQualityAntialiasing) painter.setRenderHint(QPainter.Antialiasing) painter.setRenderHint(QPainter.SmoothPixmapTransform) # change the look for on/off if self.isChecked(): # blue fill brush = QBrush(self.color1) painter.setBrush(brush) painter.drawRoundedRect(0, 7, self.width() - 2, self.height() - 15, self.height() / 2 - 10, self.height() / 2) brush = QBrush(self.lighter(self.color1)) painter.setBrush(brush) painter.drawEllipse(self.width() - self.height(), 0, self.height(), self.height()) else: # gray fill brush = QBrush(self.color2) painter.setBrush(brush) painter.drawRoundedRect(1, 7, self.width() - 3, self.height() - 15, self.height() / 2 - 10, self.height() / 2) brush = QBrush(QColor(100, 100, 100)) painter.setBrush(brush) painter.drawEllipse(0, 0, self.height(), self.height()) painter.end()
def paintEvent(self, ev): size = self.size() height = size.height()-5 width = size.width()-5 offset = 0.5 rect = QRectF(2.0+offset, 2.0+offset, width, height) painter = QPainter(self) painter.setPen(self._pen) painter.setBrush(QColor(self._color[0], self._color[1], self._color[2])) painter.setRenderHint(QPainter.Antialiasing) painter.setRenderHint(QPainter.HighQualityAntialiasing) painter.drawRoundedRect(rect, 4, 4)
def paintEvent(self, ev): size = self.size() height = size.height() - 5 width = size.width() - 5 offset = 0.5 rect = QRectF(2.0 + offset, 2.0 + offset, width, height) painter = QPainter(self) painter.setPen(self._pen) painter.setBrush(QColor(self._color[0], self._color[1], self._color[2])) painter.setRenderHint(QPainter.Antialiasing) painter.setRenderHint(QPainter.HighQualityAntialiasing) painter.drawRoundedRect(rect, 4, 4)
def paintEvent(self, event): painter = QPainter() painter.begin(self) colour = self._colour if not self._lit: colour = self._colour.darker(300) painter.setPen(QPen(Qt.black, 1)) painter.setBrush(QBrush(colour)) rect = event.rect() radius = min(rect.width(), rect.height()) / 3 painter.drawEllipse(rect.center(), radius, radius) painter.end()
def paintEvent(self, event): painter = QPainter() painter.begin(self) if self._lit: self._colour.setAlphaF(1) else: self._colour.setAlphaF(.25) painter.setPen(QPen(self._colour, 1)) painter.setBrush(QBrush(self._colour)) rect = event.rect() radius = min(rect.width(), rect.height()) / 3 painter.drawEllipse(rect.center(), radius, radius) painter.end()
def svg2icon(path, img_type=QImage): img = QImage(64, 64, QImage.Format_ARGB32) svgrenderer = QSvgRenderer(path) paint = QPainter(img) paint.setRenderHint(QPainter.HighQualityAntialiasing) paint.setRenderHint(QPainter.SmoothPixmapTransform) paint.setBrush(QColor(255, 255, 255, 255)) paint.drawRect(QRect(-1, -1, 65, 65)) svgrenderer.render(paint) paint.end() if img_type == QImage: return img elif img_type == QPixmap: pix = QPixmap pix = pix.fromImage(img) return pix
def paint(self, painter, option, widget=None): """@reimp @public virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0) """ #Q_UNUSED(option) #Q_UNUSED(widget) d = self.__d key = d.hash pm = QPixmap() if not QPixmapCache.find(key, pm): # Set up a convenient path path = QPainterPath() path.setFillRule(Qt.OddEvenFill) path.addEllipse(QPointF(d.actualOuterRadius, d.actualOuterRadius), d.actualOuterRadius, d.actualOuterRadius) path.addEllipse(QPointF(d.actualOuterRadius, d.actualOuterRadius), d.actualInnerRadius, d.actualInnerRadius) nActualDiameter = 2.0 * d.actualOuterRadius pm = QPixmap(nActualDiameter, nActualDiameter) pm.fill(Qt.transparent) p = QPainter(pm) # Draw the ring background p.setPen(Qt.NoPen) p.setBrush(d.backgroundColor) p.setRenderHint(QPainter.Antialiasing) p.drawPath(path) # Draw the ring foreground # TODO: Expose this gradient as Qml Property gradient = QConicalGradient(d.actualOuterRadius, d.actualOuterRadius, 0.0) gradient.setColorAt(0.0, Qt.transparent) gradient.setColorAt(0.05, d.foregroundColor) gradient.setColorAt(0.8, Qt.transparent) p.setBrush(gradient) p.drawPath(path) p.end() QPixmapCache.insert(key, pm) # Draw pixmap at center of item w, h = self.width(), self.height() sz = min(w, h) painter.drawPixmap(0.5 * (w - sz), 0.5 * (h - sz), pm)
def paintEvent(self, event): ''' Method to run on paint events ''' painter = QPainter() # Get a QPainter object painter.begin(self) # Begin painting painter.setRenderHint(QPainter.Antialiasing) # Set a rendering option painter.setBrush(Qt.transparent) # Set the paint brush to transparent painter.drawRect(0, 0, 20, 20) # Draw a rectangle with width = height = 20 painter.setBrush(Qt.green) # Set the paint brush color to green painter.drawEllipse(QPoint(10, 10), 9, 9) # Draw a circle that fills most of the rectangle painter.end()
def paintEvent(self, event): mouse_pos = self.mapFromGlobal(QCursor.pos()) is_hover = self.contentsRect().contains(mouse_pos) if not self.new_ui: QPushButton.paintEvent(self, event) painter = QPainter(self) if self.new_ui and self.isChecked(): painter.setRenderHint(QPainter.Antialiasing) painter.setPen(QPen(Qt.NoPen)) painter.setBrush(self.highlight) painter.drawRoundedRect(event.rect(), 2, 2) painter.drawPixmap(2, 2, self.icon) if is_hover: painter.setCompositionMode(QPainter.CompositionMode_Screen) painter.drawPixmap(2, 2, self.icon)
def paintEvent(self, event): """ This function handles the low level painting of component. :param event: :return: """ painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.Antialiasing) if self.__flag == 1: painter.end() return # setting the masking ellipse painter.setClipRegion(self.__clip) self.__color.setAlpha(self.__maxOpacity) painter.setBrush(QBrush(self.__color)) painter.setPen(QPen(QColor(0, 0, 0, 0))) painter.drawEllipse(self.__origin, self.__r, self.__r) painter.end()
def paintEvent(self, event): painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.HighQualityAntialiasing) painter.setRenderHint(QPainter.SmoothPixmapTransform) painter.setBrush(QColor(255, 255, 255)) painter.drawRect(QRect(0, -1, self.window().width(), 76)) if self.icon: painter.drawPixmap(QRect(16, 16, 32, 32), self.icon) if self.title: painter.setFont(QFont("Roboto\\Roboto-Regular.ttf", 20)) if qt_ver() != "PySide": painter.drawText(QRect(56, 0, 64, 48),0, self.title) else: painter.drawText(QRect(56, 0, 64, 48), self.title) if self.text: painter.setFont(QFont("Roboto\\Roboto-Regular.ttf", 13)) if qt_ver() != "PySide": painter.drawText(QRect(56, self.height() / 2, self.window().width() - 56, 36),0, self.text) painter.end()
def paintEvent(self, pe): if self.left_view and self.right_view and self.right_view.model(): vr = self.left_view.visualRect(self.left_view.currentIndex()) self.left_top = self.mapFromGlobal( self.left_view.viewport().mapToGlobal(vr.topRight())).y() self.left_bottom = self.mapFromGlobal( self.left_view.viewport().mapToGlobal(vr.bottomRight())).y() vr_top = self.right_view.visualRect(self.right_view.model().index( 0, 0)) vr = self.right_view.visualRect(self.right_view.model().index( self.right_view.model().rowCount() - 1, 0)) self.right_top = self.mapFromGlobal( self.left_view.viewport().mapToGlobal(vr_top.topLeft())).y() self.right_bottom = self.mapFromGlobal( self.left_view.viewport().mapToGlobal(vr.bottomLeft())).y() w = self.minimumWidth() - 1 p = QPainter(self) p.setBrush(QBrush(QColor(210, 255, 210))) pen = QPen() pen.setColor(Qt.transparent) p.setPen(pen) poly = QPolygon() poly.append(QPoint(0, self.left_top)) poly.append(QPoint(w, self.right_top)) poly.append(QPoint(w, self.right_bottom)) poly.append(QPoint(0, self.left_bottom)) p.drawConvexPolygon(poly) p.setRenderHint(QPainter.Antialiasing) pen.setColor(Qt.GlobalColor.black) pen.setWidth(2) p.setPen(pen) p.drawLine(0, self.left_top, w, self.right_top) p.drawLine(0, self.left_bottom, w, self.right_bottom)
def paintEvent(self, event): painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.HighQualityAntialiasing) painter.setRenderHint(QPainter.Antialiasing) painter.setRenderHint(QPainter.SmoothPixmapTransform) self.img = QPixmap() if self.isChecked(): painter.setBrush(self.color1) painter.drawRoundedRect(QRect(-1, -1, 31, 31), 7, 7) painter.drawPixmap(QRect(-2, -5, 35, 40), self.img.fromImage(self.check)) else: pen = QPen() pen.setWidth(2) painter.setPen(pen) # hand draw rect painter.drawLine(QPoint(0, 0), QPoint(30, 0)) painter.drawLine(QPoint(30, 0), QPoint(30, 30)) painter.drawLine(QPoint(0, 0), QPoint(0, 30)) painter.drawLine(QPoint(0, 30), QPoint(30, 30)) painter.end()
def createPixmapIcon(self): self.markerIcon = QPixmap(MARKER_WIDTH, MARKER_HEIGHT) self.markerIcon.fill(Qt.transparent) painter = QPainter(self.markerIcon) p1 = QPoint(MARKER_WIDTH / 2, MARKER_HEIGHT - 1) p2 = QPoint(MARKER_WIDTH / 2, MARKER_HEIGHT - 1 - MARKER_PIN_LEN) pen = QPen(Qt.black) pen.setWidth(2) pen.setCosmetic(True) painter.setPen(pen) painter.drawLine(p1, p2) ellipse = QRect(0, 0, MARKER_WIDTH - 1, MARKER_HEIGHT - 1) pen.setWidth(1) painter.setPen(pen) color = QColor(Qt.green) color.setAlpha(127) brush = QBrush(color) painter.setBrush(brush) painter.drawEllipse(ellipse)
def paintEvent(self, pe): painter = QPainter(self) painter.save() background = QColor(55, 55, 55) brush = QBrush(background) painter.setOpacity(self._opacity) painter.setBrush(brush) painter.setPen(Qt.NoPen) painter.drawRect(self.rect()) painter.restore() # draw a bottom border painter.setPen(Qt.black) painter.drawLine(0, self.height(), self.width(), self.height()) # now the text pen = QPen(Qt.white) pen.setWidth(16) painter.setPen(pen) painter.setFont(QFont("Trebuchet MS", 16, QFont.Bold)) text_rect = QRect(self.rect()) text_rect.adjust(self._margin, self._margin, self._margin, self._margin) painter.drawText(text_rect, Qt.AlignLeft, self._message_str)
def paintEvent(self, event): painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.HighQualityAntialiasing) painter.setRenderHint(QPainter.SmoothPixmapTransform) painter.setBrush(QColor(255, 255, 255)) painter.drawRect(QRect(0, -1, self.window().width(), 76)) if self.icon: painter.drawPixmap(QRect(16, 16, 32, 32), self.icon) if self.title: painter.setFont(QFont("Roboto\\Roboto-Regular.ttf", 20)) if qt_ver() != "PySide": painter.drawText(QRect(56, 0, 64, 48), 0, self.title) else: painter.drawText(QRect(56, 0, 64, 48), self.title) if self.text: painter.setFont(QFont("Roboto\\Roboto-Regular.ttf", 13)) if qt_ver() != "PySide": painter.drawText( QRect(56, self.height() / 2, self.window().width() - 56, 36), 0, self.text) painter.end()
def paintEvent(self, pe): if not self.enlightened.isVisible() or not self.enabled: return g = self.enlightened.mapToGlobal(QPoint(0, 0)) pos = self.parent().mapFromGlobal(g) self.setGeometry( QRect(pos.x(), pos.y(), self.minimumWidth(), self.minimumHeight())) p = QPainter(self) p.setRenderHint(QPainter.Antialiasing) pen = QPen() pen.setColor(QColor(128, 128, 255)) pen.setWidth(2) p.setBrush(QBrush(QColor(225 + math.sin(self.progress) * 30, 225, 255))) self.progress += 0.09 * 2 self.progress2 += 0.109 * 2 p.setPen(pen) s = 10 sz = 7 w = s * 1.1 + sz p.drawEllipse(0 + s * math.sin(self.progress + 0.5) + w, s * math.cos(self.progress) + w, sz, sz) p.drawEllipse(s * 1.1 * math.sin(self.progress2) + w, s * math.cos(self.progress + 0.5) + w, sz - 2, sz - 2) p.drawEllipse( s * math.sin(self.progress + 1) + w, s * 1.1 * math.cos(self.progress2 / 2 + self.progress / 2) + w, sz - 4, sz - 4)
def paintEvent(self, e): qp = QPainter() qp.begin(self) qp.setBrush(self.value) qp.drawRect(0, 5, self.width, self.height) qp.end()
def paintEvent( self, event ): painter = QPainter() painter.begin(self) painter.setRenderHint(painter.Antialiasing) font = painter.font() font.setBold(True) painter.setFont(font) x = self.rect().x() y = self.rect().y() w = self.rect().width() - 1 h = self.rect().height() - 1 r = 8 # draw a rounded style if self._rolloutStyle == 2: # draw the text painter.drawText(x + 33, y + 3, w, 16, Qt.AlignLeft | Qt.AlignTop, self.title()) # draw the triangle self.__drawTriangle(painter, x, y) # draw the borders pen = QPen(self.palette().color(QPalette.Light)) pen.setWidthF(0.6) painter.setPen(pen) painter.drawRoundedRect(x + 1, y + 1, w - 1, h - 1, r, r) pen.setColor(self.palette().color(QPalette.Shadow)) painter.setPen(pen) painter.drawRoundedRect(x, y, w - 1, h - 1, r, r) # draw a square style if self._rolloutStyle == 3: # draw the text painter.drawText(x + 33, y + 3, w, 16, Qt.AlignLeft | Qt.AlignTop, self.title()) self.__drawTriangle(painter, x, y) # draw the borders pen = QPen(self.palette().color(QPalette.Light)) pen.setWidthF(0.6) painter.setPen(pen) painter.drawRect(x + 1, y + 1, w - 1, h - 1) pen.setColor(self.palette().color(QPalette.Shadow)) painter.setPen(pen) painter.drawRect(x, y, w - 1, h - 1) # draw a Maya style if self._rolloutStyle == 4: # draw the text painter.drawText(x + 33, y + 3, w, 16, Qt.AlignLeft | Qt.AlignTop, self.title()) painter.setRenderHint(QPainter.Antialiasing, False) self.__drawTriangle(painter, x, y) # draw the borders - top headerHeight = 20 headerRect = QRect(x + 1, y + 1, w - 1, headerHeight) headerRectShadow = QRect(x - 1, y - 1, w + 1, headerHeight + 2) # Highlight pen = QPen(self.palette().color(QPalette.Light)) pen.setWidthF(0.4) painter.setPen(pen) painter.drawRect(headerRect) painter.fillRect(headerRect, QColor(255, 255, 255, 18)) # Shadow pen.setColor(self.palette().color(QPalette.Dark)) painter.setPen(pen) painter.drawRect(headerRectShadow) if not self.isCollapsed(): # draw the lover border pen = QPen(self.palette().color(QPalette.Dark)) pen.setWidthF(0.8) painter.setPen(pen) offSet = headerHeight + 3 bodyRect = QRect(x, y + offSet, w, h - offSet) bodyRectShadow = QRect(x + 1, y + offSet, w + 1, h - offSet + 1) painter.drawRect(bodyRect) pen.setColor(self.palette().color(QPalette.Light)) pen.setWidthF(0.4) painter.setPen(pen) painter.drawRect(bodyRectShadow) # draw a boxed style elif self._rolloutStyle == 1: if self.isCollapsed(): arect = QRect(x + 1, y + 9, w - 1, 4) brect = QRect(x, y + 8, w - 1, 4) text = '+' else: arect = QRect(x + 1, y + 9, w - 1, h - 9) brect = QRect(x, y + 8, w - 1, h - 9) text = '-' # draw the borders pen = QPen(self.palette().color(QPalette.Light)) pen.setWidthF(0.6) painter.setPen(pen) painter.drawRect(arect) pen.setColor(self.palette().color(QPalette.Shadow)) painter.setPen(pen) painter.drawRect(brect) painter.setRenderHint(painter.Antialiasing, False) painter.setBrush(self.palette().color(QPalette.Window).darker(120)) painter.drawRect(x + 10, y + 1, w - 20, 16) painter.drawText(x + 16, y + 1, w - 32, 16, Qt.AlignLeft | Qt.AlignVCenter, text) painter.drawText(x + 10, y + 1, w - 20, 16, Qt.AlignCenter, self.title()) if self.dragDropMode(): rect = self.dragDropRect() # draw the lines l = rect.left() r = rect.right() cy = rect.center().y() for y in (cy - 3, cy, cy + 3): painter.drawLine(l, y, r, y) painter.end()
def paintEvent(self, e): qp = QPainter() qp.begin(self) qp.setBrush(QColor(*self.value)) qp.drawRect(0, 0, self.bar_width, 20) qp.end()
def paintEvent(self, event): super().paintEvent(event) painter = QPainter(self) # Рисование цифр в ячейки таблицы for i in range(self.matrix_size): for j in range(self.matrix_size): # Если текущая ячейка относится к дефолтной судоку if self.def_num_matrix[i][j]: painter.save() # painter.setPen() painter.setBrush(Qt.yellow) x = i * self.cell_size y = j * self.cell_size w, h = self.cell_size, self.cell_size painter.drawRect(x, y, w, h) painter.restore() # TODO: Закомментировано # Если индекс ячейки под курсором валидный if 0 <= self.x_highlight_cell < self.matrix_size and 0 <= self.y_highlight_cell < self.matrix_size: # # Выделение всего столбца и строки пересекающих ячейку под курсором # painter.save() # painter.setBrush(Qt.lightGray) # # # Выделение строки # for i in range(self.matrix_size): # painter.drawRect(i * self.cell_size, # self.y_highlight_cell * self.cell_size, # self.cell_size, # self.cell_size) # # # Выделение столбца # for j in range(self.matrix_size): # painter.drawRect(self.x_highlight_cell * self.cell_size, # j * self.cell_size, # self.cell_size, # self.cell_size) # # painter.restore() x, y = self.x_highlight_cell, self.y_highlight_cell # Не подсвечиваем дефолтную ячейку if not self.def_num_matrix[x][y]: # Выделение ячейки под курсором painter.save() painter.setBrush(Qt.darkYellow) painter.drawRect(x * self.cell_size, y * self.cell_size, self.cell_size, self.cell_size) painter.restore() # Рисование цифр в ячейки таблицы for i in range(self.matrix_size): for j in range(self.matrix_size): num = self.matrix[i][j] if not num: continue num = str(num) # Алгоритм изменения размера текста взят из http://stackoverflow.com/a/2204501 # Для текущего пришлось немного адаптировать factor = (self.cell_size / 2) / painter.fontMetrics().width(num) if factor < 1 or factor > 1.25: f = painter.font() point_size = f.pointSizeF() * factor if point_size > 0: f.setPointSizeF(point_size) painter.setFont(f) x = i * self.cell_size y = j * self.cell_size w, h = self.cell_size, self.cell_size painter.drawText(x, y, w, h, Qt.AlignCenter, num) # Рисование сетки таблицы y1, y2 = 0, 0 factor = min(self.width(), self.height()) / self.default_size size = self.default_pen_size_1 size2 = self.default_pen_size_2 if factor < 1 or factor > 1.25: size *= factor if size < self.min_default_pen_size_2: size = self.min_default_pen_size_2 painter.save() for i in range(self.matrix_size + 1): painter.setPen(QPen(Qt.black, size2 if i % 3 == 0 and i and i < self.matrix_size else size)) painter.drawLine(0, y1, self.cell_size * self.matrix_size, y2) y1 += self.cell_size y2 += self.cell_size x1, x2 = 0, 0 for i in range(self.matrix_size + 1): painter.setPen(QPen(Qt.black, size2 if i % 3 == 0 and i and i < self.matrix_size else size)) painter.drawLine(x1, 0, x2, self.cell_size * self.matrix_size) x1 += self.cell_size x2 += self.cell_size painter.restore()
def testSetBrushGradient(self): painter = QPainter() gradient = QLinearGradient(0, 0, 0, 0) painter.setBrush(gradient)
def paintEvent(self, event): qp = QPainter() qp.begin(self) qp.setRenderHint(QPainter.Antialiasing) qp.setBrush(self.color) qp.setPen(self.color) rect = event.rect() x = rect.x() w = rect.width() lineheight = 16 print '-------------------' print 'lefts', self.lefts print 'rights', self.rights print '-------------------' ly = self._left_y + 5 ry = self._right_y + 5 rs=self.rights[:] # offset=1 for i, l in enumerate(self.lefts): path = QPainterPath() sl, el = l[0], l[-1] try: r=rs[i] sr, er = r[0], r[-1] rs.pop(i) # offset+=1 except IndexError: sr, er = l[-1], l[-1]-1 y = ly + lineheight * sl y2 = ry + lineheight * sr path.moveTo(x, y) path.lineTo(x, y + lineheight * (el - sl + 1)) path.lineTo(x + w, y2 + lineheight * (er - sr + 1)) path.lineTo(x + w, y2) qp.drawPath(path) for i, r in enumerate(rs): path = QPainterPath() sr, er = r[0], r[-1] # try: l=self.lefts[i] sl, el = r[-1], r[-1]-1 # except IndexError: # sl, el = l[-1]+2, l[-1]+1 # print sl, el y = ly + lineheight * (sl) y2 = ry + lineheight * (sr) path.moveTo(x, y) path.lineTo(x, y + lineheight * (el - sl + 1)) path.lineTo(x + w, y2 + lineheight * (er - sr + 1)) path.lineTo(x + w, y2) qp.drawPath(path) qp.end()
class pyimp_ui(QWidget): def __init__(self,training_network): super(pyimp_ui, self).__init__() self.current_network = training_network # Maintain a list of created widgets for the remove buttons self.button_list = [] #Create a list of Grid Positions for the Edit Snapshots Window self.pos_list = [] self.dsNumber = QtGui.QLabel() self.initUI() self.timer = QtCore.QTimer(self) self.timer.timeout.connect(self.QUpdate) self.timer.start(50) def initUI(self): self.setStyle(QtGui.QStyleFactory.create('Cleanlooks')) #Load UI created in QT Designer self.loadCustomWidget("PyImpMainWindowSnapShot.ui") self.setAutoFillBackground(1) widgets = self.findChildren(QWidget) #print "WIDGETS", widgets # Button Widgets in the Main Interface self.loadDataButton = self.findChild(QWidget,"loadDataButton") # self.loadDataButton.setColor("#FFC673") self.saveDataButton = self.findChild(QWidget,"saveDataButton") self.loadMappingButton = self.findChild(QWidget,"loadMappingButton") self.saveMappingButton = self.findChild(QWidget,"saveMappingButton") self.getDataButton = self.findChild(QWidget,"getDataButton") self.trainMappingButton = self.findChild(QWidget,"trainMappingButton") self.resetClassifierButton = self.findChild(QWidget,"resetClassifierButton") self.clearDataButton = self.findChild(QWidget,"clearDataButton") self.processOutputButton = self.findChild(QWidget,"processOutputButton") self.processOutputButton.setCheckable(True) self.middleLayerEnable = self.findChild(QWidget,"middleLayerEnable") self.setSlidersButton = self.findChild(QWidget,"setSlidersButton") self.setSlidersButton.hide() self.chooseClassifier = self.findChild(QWidget,"chooseClassifierComboBox") self.numberOfSnapshots = self.findChild(QtGui.QLabel,"noSnapshots") self.editSnapshots = self.findChild(QWidget,"editSnapshots") #Graphics Views for the Signals self.inputPlot = self.findChild(QWidget,"inputSignals") self.outputPlot = self.findChild(QWidget,"outputSignals") self.middlePlot = self.findChild(QWidget,"middleSignals") self.middlePlot.hide() self.midLabel = self.findChild(QtGui.QLabel,"midlabel") print self.midLabel self.midLabel.hide() self.processResultsText = self.findChild(QtGui.QLabel, "processResultsText") # Activate the Buttons in the Main Interface self.loadDataButton.clicked.connect(self.loadQDataset) self.saveDataButton.clicked.connect(self.saveQDataset) self.loadMappingButton.clicked.connect(self.loadQNetwork) self.saveMappingButton.clicked.connect(self.saveQNetwork) self.getDataButton.clicked.connect(self.learnQCallback) self.trainMappingButton.clicked.connect(self.trainQCallback) self.resetClassifierButton.clicked.connect(self.clearQNetwork) self.clearDataButton.clicked.connect(self.clearQDataSet) self.processOutputButton.clicked[bool].connect(self.computeQCallback) self.editSnapshots.clicked.connect(self.openEditSnapshotsWindow) self.middleLayerEnable.toggle() self.middleLayerEnable.stateChanged.connect(self.enableSliders) self.middleLayerEnable.setCheckState(QtCore.Qt.Unchecked) self.snapshotWindow = QtGui.QMainWindow() self.show() def QUpdate(self): self.current_network.learnMapperDevice.poll(0) self.current_network.update() self.update() def loadCustomWidget(self,UIfile): loader = QUiLoader() file_ui = QtCore.QFile(UIfile) file_ui.open(QtCore.QFile.ReadOnly) self.mainWidget = loader.load(file_ui, self) self.setWindowTitle("Implicit Mapper") file_ui.close() def enableSliders(self,state): if state == Qt.Checked: #print "Middle Sliders Now Enabled" self.setSlidersButton.show() self.midLabel.show() self.middlePlot.show() self.setSlidersButton.clicked.connect(self.openEditSlidersWindow) else: #print "Middle Sliders Now Disabled" self.setSlidersButton.hide() self.middlePlot.hide() self.midLabel.hide() def openEditSlidersWindow(self): self.slidersWindow = QMainWindow() self.slidersWindow.setGeometry(300,200,500,400) self.slidersWindow.setWindowTitle("Middle Layer Values") self.chooseNSliders = QLineEdit() self.chooseNSliders.setGeometry(10,32,100,25) self.chooseNSliders.setParent(self.slidersWindow) self.setButton = QPushButton("OK") self.setButton.setGeometry(self.chooseNSliders.width()+self.chooseNSliders.x()+5,32,50,25) self.setButton.setDisabled(1) self.setButton.setParent(self.slidersWindow) self.layoutNo = QHBoxLayout() self.layoutNo.addWidget(self.chooseNSliders) self.layoutNo.addWidget(self.setButton) self.chooseNSlidersLabel = QtGui.QLabel("Set The Number of Middle Sliders") self.chooseNSlidersLabel.setGeometry(10,10,300,25) self.chooseNSlidersLabel.setParent(self.slidersWindow) self.layoutTop = QVBoxLayout() self.layoutTop.addLayout(self.layoutNo) self.layoutTop.addWidget(self.chooseNSlidersLabel) self.layoutSliders = QVBoxLayout() self.layoutSliders.secontSpacing(5) self.layoutSliders.addLayout(self.layoutTop) self.chooseNSliders.textChanged.connect(self.setNumQSliders) self.slidersWindow.show() def setNumQSliders(self): self.NoSlides = int(self.chooseNSliders.text()) self.setButton.setEnabled(1) self.setButton.clicked.connect(self.createQSliders) def createQSliders(self): self.slidersWindow.hide() num_outputs = self.NoSlides sliders={} # If number of sliders is re-entered if (len(self.slidersWindow.findChildren(QSlider)) != 0): #print len(self.slidersWindow.findChildren(QSlider)) for key in sliders.iterkeys(): sliders[key].setParent(None) self.layoutSliders.removeWidget(sliders[key]) del sliders[key] for s_index in range(self.NoSlides): #print range(self.NoSlides) sliders[s_index] = QSlider() if s_index == 0: sliders[s_index].setGeometry(10,70,self.slidersWindow.width()-20,10) else: sliders[s_index].setGeometry(10,sliders[s_index-1].y()+20,self.slidersWindow.width()-20,10) sliders[s_index].setObjectName("Slider%s"%s_index) sliders[s_index].setOrientation(Qt.Horizontal) sliders[s_index].setRange(0,100) sliders[s_index].setParent(self.slidersWindow) sliders[s_index].valueChanged.connect(self.getSliderValue) sliders[s_index].setSliderPosition(5) self.current_network.data_middle["Slider%s"%s_index] = 5 self.layoutSliders.addWidget(sliders[s_index]) self.slidersWindow.show() self.setButton.setDisabled(1) def getSliderValue(self): sender = self.sender() sender_name = sender.objectName() self.current_network.data_middle[sender_name] = sender.value() #print "Middle Slider Values", self.current_network.data_middle.values() def loadQDataset(self): # Create Dialog to load the dataset from the directory loadDialog = QFileDialog() loadDialog.setFileMode(QFileDialog.ExistingFile) loadDialog.setAcceptMode(QFileDialog.AcceptOpen) loadDialog.setWindowTitle("Load Dataset") loadDialog.show() filename = loadDialog.getOpenFileName() self.current_network.load_dataset(filename) def saveQDataset(self): # Create Dialog to save the file in directory saveDialog = QFileDialog() saveDialog.setFileMode(QFileDialog.AnyFile) saveDialog.setAcceptMode(QFileDialog.AcceptSave) saveDialog.setWindowTitle("Save Dataset") saveDialog.show() filename = saveDialog.getSaveFileName() PyImpNetwork.save_dataset(self.current_network,filename) def clearQDataSet(self): self.current_network.clear_dataset() self.numberOfSnapshots.setText(str(len(self.current_network.temp_ds.keys()))) def loadQNetwork(self): # Create Dialog to load the dataset from the directory loadDialog = QFileDialog() loadDialog.setFileMode(QFileDialog.ExistingFile) loadDialog.setAcceptMode(QFileDialog.AcceptOpen) loadDialog.setWindowTitle("Load Network") loadDialog.show() filename = loadDialog.getOpenFileName() self.current_network.load_dataset() def saveQNetwork(self): # Create Dialog to save the file in directory saveDialog = QFileDialog() saveDialog.setFileMode(QFileDialog.AnyFile) saveDialog.setAcceptMode(QFileDialog.AcceptSave) saveDialog.setWindowTitle("Save Network") saveDialog.show() filename = saveDialog.getSaveFileName() self.current_network.save_net() def clearQNetwork(self): # clear the previously calculated weights and start over self.current_network.clear_network() def learnQCallback(self): self.current_network.learn_callback() self.numberOfSnapshots.setText(str(self.current_network.snapshot_count)) self.dsNumber.setText(str(self.current_network.snapshot_count)) # Create the buttons in the edit snapshots screen s_button = QPushButton("Remove Snapshot %s"%self.current_network.snapshot_count) s_button.resize(140,20) s_button.setObjectName("Dataset%d"%self.current_network.snapshot_count) s_button.setStyleSheet("QWidget {background-color:#DAFDE0;}") s_button.setParent(self.snapshotWindow) #This list contains the actual QWidget QPushButtons print "Button Added, total length", len(self.button_list) self.button_list.append(s_button) # Update the Grid positions for the list of buttons self.pos_list.append((self.current_network.snapshot_count/3,self.current_network.snapshot_count%3)) print self.pos_list if self.current_network.learning == 1: self.getDataButton.setDown(1) self.getDataButton.setText("Taking Snapshot") elif self.current_network.learning == 0: self.getDataButton.setDown(0) self.getDataButton.setText("Snapshot") def trainQCallback(self): self.current_network.train_callback() def computeQCallback(self,pressed): if pressed: #self.processOutputButton.isChecked() == 1: print "Processing Output Now" self.processResultsText.setText("Computing Results is ON") self.current_network.compute = 1 #self.current_network.compute_callback() else: print "Process output stopped" self.processResultsText.setText("Click to Compute Results") self.current_network.compute = 0 def openEditSnapshotsWindow(self): self.addtoDsButton = QPushButton("Update Dataset") self.addtoDsButton.setGeometry(320,350,170,40) self.addtoDsButton.setStyleSheet("QWidget { background-color:#3AD76F;}") self.addtoDsButton.setParent(self.snapshotWindow) self.addtoDsButton.clicked.connect(self.updateQDataSet) self.dsLabel = QtGui.QLabel("Number of Single Sets in Database:") self.dsLabel.setGeometry(30,350,270,40) self.dsLabel.setParent(self.snapshotWindow) self.dsNumber.setGeometry(270,350,100,40) self.dsNumber.setText(str(self.current_network.snapshot_count)) self.dsNumber.setParent(self.snapshotWindow) self.snapshotGrid = QGridLayout() self.snapshotGrid.setHorizontalSpacing(10) self.snapshotGrid.setVerticalSpacing(10) #Display labels on Grid j = 0 for button in self.button_list: button.setParent(self.snapshotWindow) self.snapshotGrid.addWidget(button,self.pos_list[j][0],self.pos_list[j][1],Qt.AlignCenter) button.move((self.pos_list[j][1])*(button.width()+5)+10,(self.pos_list[j][0])*(button.height()+10)+10) button.clicked.connect(self.removeTempDataSet) j = j+1 self.snapshotWindow.setLayout(self.snapshotGrid) self.snapshotWindow.setGeometry(300,200,550,400) self.snapshotWindow.setWindowTitle("Edit Existing Snapshots") self.snapshotWindow.show() def updateQDataSet(self): self.current_network.update_ds() self.dsNumber.setText(str(self.current_network.snapshot_count)) def removeTempDataSet(self): sender = self.sender() sender_name = sender.objectName() sender_id = sender_name.split("Dataset") sender_id = int(sender_id[1]) print "Sender ID", sender_id self.current_network.remove_tempds(sender_id) print "Number of Items", self.snapshotGrid.count(), range(1,self.snapshotGrid.count()+1) sender.setParent(None) for button in sorted(self.button_list): if button.objectName() == sender.objectName(): print "Found button to remove" self.button_list.remove(button) self.dsNumber.setText(str(self.current_network.snapshot_count)) self.numberOfSnapshots.setText(str(self.current_network.snapshot_count)) self.snapshotWindow.update() ############################################## Graph Drawing Methods Here ##################################################### def paintEvent(self, event): self.qp = QPainter() self.qp.begin(self) self.qp.setRenderHint(QPainter.Antialiasing) self.paintSignals() self.qp.end() # # Paint a single bar as part of a bar-graph def paintBar(self,x,y,barwidth,barheight): brush = QBrush(QColor("#9D0D02"),QtCore.Qt.SolidPattern) rect = QRect(x,y,barwidth,barheight) self.qp.setBrush(brush) self.qp.drawRect(rect) # This function plots the individual signals coming into implicit mapper from both the input and the output def paintSignals(self): # # Overall Rectangle #brush1 = QBrush(QColor("#FFDE99"),Qt.Dense3Pattern) #self.qp.setBrush(brush1) self.qp.drawRect(self.inputPlot.x(),self.inputPlot.y(),self.outputPlot.width()*3+20,self.outputPlot.height()) # self.qp.drawLine(self.inputPlot.x(),self.inputPlot.y(),self.outputPlot.x()+self.outputPlot.width(),self.outputPlot.y()) # self.qp.drawLine(self.inputPlot.x(),self.inputPlot.y()+self.inputPlot.height(),self.outputPlot.x()+self.outputPlot.width(),self.outputPlot.y()+self.outputPlot.height()) # self.qp.drawLine(self.inputPlot.x(),self.inputPlot.y(),self.inputPlot.x(),self.inputPlot.y()+self.inputPlot.height()) # self.qp.drawLine(self.outputPlot.x()+self.outputPlot.width(),self.outputPlot.y(),self.outputPlot.x()+self.outputPlot.width(),self.outputPlot.y()+self.outputPlot.height()) # Input Plot Background # self.inputRect = QRect(self.inputPlot.x(),self.inputPlot.y(),self.inputPlot.width(), self.inputPlot.height()) #brush1 = QBrush(QColor("#FFDE99"),Qt.Dense3Pattern) #self.qp.setBrush(brush1) #self.qp.drawRect(20,65,300,220) #self.qp.drawRect(330,15,490,180) # # Middle Plot Background # self.middleRect = QRect(self.middlePlot.x(),self.middlePlot.y(),self.middlePlot.width(),self.middlePlot.height()) # brush = QBrush(QColor("#FFDE99"),Qt.Dense3Pattern) # self.qp.setBrush(brusneth) # self.qp.drawRect(self.middleRect) # # Output Plot Background # self.outputRect = QRect(self.outputPlot.x(),self.outputPlot.y(),self.outputPlot.width(),self.outputPlot.height()) # brush2 = QBrush(QColor("#FFDE99"),Qt.Dense3Pattern) # self.qp.setBrush(brush2) # self.qp.drawRect(self.outputRect) # Input Bars if len(self.current_network.data_input.keys())>1: barwidth_in = float(self.inputPlot.width())/len(self.current_network.data_input.keys())-5 else: barwidth_in = 1 cnt = 0 for inputsig, sigvalue in sorted(self.current_network.data_input.iteritems()): #print "input rectangle %s"%inputsig, sigvalue sigmax = 1 if (sigvalue > sigmax): sigmax = sigvalue sigvalue = (sigvalue/sigmax) self.paintBar(self.inputPlot.x()+10+cnt*barwidth_in,self.inputPlot.y() + self.inputPlot.height(),barwidth_in,(-1)*abs(sigvalue*self.inputPlot.height())) cnt = cnt+1 # Output Bars if len(self.current_network.data_output.keys())>1: barwidth_out = self.outputPlot.width()/len(self.current_network.data_output.keys())-5 else: barwidth_out = 1 cnt2 = 0 for outputsig, outvalue in sorted(self.current_network.data_output.iteritems()): #print "output rectangle %s"%outputsig, outvalue sigmax2 = 1 if (outvalue > sigmax2): sigmax2 = outvalue outvalue = (outvalue/sigmax2) self.paintBar(self.outputPlot.x()+10+cnt2*barwidth_out,self.outputPlot.y() + self.outputPlot.height(),barwidth_out,(-1)*abs(outvalue*self.outputPlot.height())) cnt2 = cnt2+1 # Middle Bars if len(self.current_network.data_middle.keys())>=1: barwidth_mid = self.middlePlot.width()/len(self.current_network.data_middle.keys())-5 cnt3 = 0 for midsig, midval in sorted(self.current_network.data_middle.iteritems()): #print "output rectangle %s"%outputsig, outvalue # if (midval > sigmax2): # sigmax2 = outvalue # outvalue = (outvalue/sigmax2) self.paintBar(self.middlePlot.x()+10+cnt3*barwidth_mid,self.middlePlot.y() + self.middlePlot.height(),barwidth_mid,(-1)*abs(midval)) cnt3 = cnt3+1
def drawArrow(element, painter, option): # From windows style but modified to enable AA if option.rect.width() <= 1 or option.rect.height() <= 1: return r = option.rect size = min(r.height(), r.width()) pixmap = QPixmap() pixmapName = "arrow-{0}-{1}-{2}-{3}-{4}".format( "$qt_ia", int(option.state), element, size, option.palette.cacheKey() ) if not QPixmapCache.find(pixmapName, pixmap): border = size / 5 sqsize = 2 * (size / 2) image = QImage(sqsize, sqsize, QImage.Format_ARGB32) image.fill(Qt.transparent) imagePainter = QPainter(image) imagePainter.setRenderHint(QPainter.Antialiasing, True) imagePainter.translate(0.5, 0.5) a = QPolygon() if element == QStyle.PE_IndicatorArrowUp: a.setPoints(3, border, sqsize / 2, sqsize / 2, border, sqsize - border, sqsize / 2) elif element == QStyle.PE_IndicatorArrowDown: a.setPoints(3, border, sqsize / 2, sqsize / 2, sqsize - border, sqsize - border, sqsize / 2) elif element == QStyle.PE_IndicatorArrowRight: a.setPoints(3, sqsize - border, sqsize / 2, sqsize / 2, border, sqsize / 2, sqsize - border) elif element == QStyle.PE_IndicatorArrowLeft: a.setPoints(3, border, sqsize / 2, sqsize / 2, border, sqsize / 2, sqsize - border) else: pass bsx = 0 bsy = 0 if option.state & QStyle.State_Sunken: bsx = qApp.style().pixelMetric(QStyle.PM_ButtonShiftHorizontal) bsy = qApp.style().pixelMetric(QStyle.PM_ButtonShiftVertical) bounds = a.boundingRect() sx = sqsize / 2 - bounds.center().x() - 1 sy = sqsize / 2 - bounds.center().y() - 1 imagePainter.translate(sx + bsx, sy + bsy) if not (option.state & QStyle.State_Enabled): imagePainter.setBrush(option.palette.mid().color()) imagePainter.setPen(option.palette.mid().color()) else: shadow = QColor(0, 0, 0, 100) imagePainter.translate(0, 1) imagePainter.setPen(shadow) imagePainter.setBrush(shadow) foreGround = QColor(255, 255, 255, 210) imagePainter.drawPolygon(a) imagePainter.translate(0, -1) imagePainter.setPen(foreGround) imagePainter.setBrush(foreGround) imagePainter.drawPolygon(a) imagePainter.end() pixmap = QPixmap.fromImage(image) QPixmapCache.insert(pixmapName, pixmap) xOffset = r.x() + (r.width() - size) / 2 yOffset = r.y() + (r.height() - size) / 2 painter.drawPixmap(xOffset, yOffset, pixmap)
def paintEvent(self, event): qp = QPainter() qp.begin(self) qp.setRenderHint(QPainter.Antialiasing) qp.setBrush(self.color) qp.setPen(self.color) rect = event.rect() x = rect.x() w = rect.width() lineheight = 16 print '-------------------' print 'lefts', self.lefts print 'rights', self.rights print '-------------------' ly = self._left_y + 5 ry = self._right_y + 5 rs = self.rights[:] # offset=1 for i, l in enumerate(self.lefts): path = QPainterPath() sl, el = l[0], l[-1] try: r = rs[i] sr, er = r[0], r[-1] rs.pop(i) # offset+=1 except IndexError: sr, er = l[-1], l[-1] - 1 y = ly + lineheight * sl y2 = ry + lineheight * sr path.moveTo(x, y) path.lineTo(x, y + lineheight * (el - sl + 1)) path.lineTo(x + w, y2 + lineheight * (er - sr + 1)) path.lineTo(x + w, y2) qp.drawPath(path) for i, r in enumerate(rs): path = QPainterPath() sr, er = r[0], r[-1] # try: l = self.lefts[i] sl, el = r[-1], r[-1] - 1 # except IndexError: # sl, el = l[-1]+2, l[-1]+1 # print sl, el y = ly + lineheight * (sl) y2 = ry + lineheight * (sr) path.moveTo(x, y) path.lineTo(x, y + lineheight * (el - sl + 1)) path.lineTo(x + w, y2 + lineheight * (er - sr + 1)) path.lineTo(x + w, y2) qp.drawPath(path) qp.end()