def lineNumberAreaPaintEvent(self, event): painter = QPainter(self.lineNumbers) painter.fillRect(event.rect(), QColor(230, 230, 230)) d = event.rect().topRight() a = event.rect().bottomRight() painter.setPen(Qt.darkGray) painter.drawLine(d.x(), d.y(), a.x(), a.y()) painter.setPen(QColor(100, 100, 100)) painter.setFont(self.font()) block = self.firstVisibleBlock() blockNumber = block.blockNumber() top = int( self.blockBoundingGeometry(block).translated( self.contentOffset()).top()) bottom = top + int(self.blockBoundingRect(block).height()) while block.isValid() and top <= event.rect().bottom(): if block.isVisible() and bottom >= event.rect().top(): number = str(blockNumber + 1) painter.drawText(4, top, self.lineNumbers.width() - 8, self.fontMetrics().height(), Qt.AlignRight, number) block = block.next() top = bottom bottom = top + int(self.blockBoundingRect(block).height()) blockNumber += 1
def paintEvent(self, evt): """ Protected method handling a paint event. @param evt reference to the paint event (QPaintEvent) """ super(E5LineEdit, self).paintEvent(evt) if qVersion() < "4.7.0": if not self.text() and \ self.__inactiveText and \ not self.hasFocus(): panel = QStyleOptionFrame() self.initStyleOption(panel) textRect = self.style().subElementRect( QStyle.SE_LineEditContents, panel, self) textRect.adjust(2, 0, 0, 0) left = self.textMargin(self.LeftSide) right = self.textMargin(self.RightSide) textRect.adjust(left, 0, -right, 0) painter = QPainter(self) painter.setPen(self.palette().brush( QPalette.Disabled, QPalette.Text).color()) painter.drawText( textRect, Qt.AlignLeft | Qt.AlignVCenter, self.__inactiveText)
def paintEvent(self, QPaintEvent): self.updatePosition() painter = QPainter(self) painter.fillRect(self.rect(), Qt.transparent) painter.setRenderHint(QPainter.Antialiasing, True) if self._currentCounter >= self._numberOfLines: self._currentCounter = 0 painter.setPen(Qt.NoPen) for i in range(0, self._numberOfLines): painter.save() painter.translate(self._innerRadius + self._lineLength, self._innerRadius + self._lineLength) rotateAngle = float(360 * i) / float(self._numberOfLines) painter.rotate(rotateAngle) painter.translate(self._innerRadius, 0) distance = self.lineCountDistanceFromPrimary( i, self._currentCounter, self._numberOfLines) color = self.currentLineColor(distance, self._numberOfLines, self._trailFadePercentage, self._minimumTrailOpacity, self._color) painter.setBrush(color) rect = QRect(0, -self._lineWidth/2, self._lineLength, self._lineWidth) painter.drawRoundedRect( rect, self._roundness, self._roundness, Qt.RelativeSize) painter.restore()
def paintEvent(self, ev): """Called when paint is needed, finds out which page to magnify.""" layout = self.parent().surface().pageLayout() pos = self.geometry().center() - self.parent().surface().pos() page = layout.pageAt(pos) if not page: return pagePos = pos - page.pos() max_zoom = self.parent().surface().view().MAX_ZOOM * self.MAX_EXTRA_ZOOM newPage = Page(page, min(max_zoom, self._scale * page.scale())) if not newPage.same_page(self._page): if self._page: self._page.magnifier = None self._page = newPage self._page.magnifier = self relx = pagePos.x() / float(page.width()) rely = pagePos.y() / float(page.height()) image = cache.image(self._page) img_rect = QRect(self.rect()) if not image: cache.generate(self._page) image = cache.image(self._page, False) if image: img_rect.setWidth(self.width() * image.width() / self._page.width()) img_rect.setHeight(self.height() * image.height() / self._page.height()) if image: img_rect.moveCenter(QPoint(relx * image.width(), rely * image.height())) p = QPainter(self) p.drawImage(self.rect(), image, img_rect) p.setRenderHint(QPainter.Antialiasing, True) p.setPen(QPen(QColor(192, 192, 192, 128), 6)) p.drawEllipse(self.rect().adjusted(2, 2, -2, -2))
def draw(self, painter: QPainter): pen = QPen(Layer.color(LayerType.annotate)) pen.setCapStyle(Qt.RoundCap) pen.setJoinStyle(Qt.RoundJoin) pen.setWidth(0) painter.setPen(pen) painter.drawLine(self.pt1, self.pt2)
def paintEvent(self, ev): color = self.palette().color(QPalette.Highlight) painter = QPainter(self) # Filled rectangle. painter.setClipRect(self.rect()) color.setAlpha(50) painter.fillRect(self.rect().adjusted(2,2,-2,-2), color) # Thin rectangle outside. color.setAlpha(150) painter.setPen(color) painter.drawRect(self.rect().adjusted(0,0,-1,-1)) # Pseudo-handles at the corners and sides color.setAlpha(100) pen = QPen(color) pen.setWidth(8) painter.setPen(pen) painter.setBackgroundMode(Qt.OpaqueMode) # Clip at 4 corners region = QRegion(QRect(0,0,20,20)) region += QRect(self.rect().width()-20, 0, 20, 20) region += QRect(self.rect().width()-20, self.rect().height()-20, 20, 20) region += QRect(0, self.rect().height()-20, 20, 20) # Clip middles region += QRect(0, self.rect().height() // 2 - 10, self.rect().width(), 20) region += QRect(self.rect().width() // 2 - 10, 0, 20, self.rect().height()) # Draw thicker rectangles, clipped at corners and sides. painter.setClipRegion(region) painter.drawRect(self.rect())
def paintEvent(self, event): if not self.isDisplayedWhenStopped() and not self.isRunning(): return width = min(self.width(), self.height()) p = QPainter(self) p.setRenderHint(QPainter.Antialiasing) outerRadius = (width-1) * 0.5 innerRadius = (width-1) * 0.5 * 0.38 capsuleHeight = outerRadius - innerRadius capsuleWidth = capsuleHeight * 0.23 if width > 32 else capsuleHeight * 0.35 capsuleRadius = capsuleWidth / 2 for i in range(12): color = QColor(self.color) color.setAlphaF(float(1.0 - float(i / 12.0))) p.setPen(Qt.NoPen) p.setBrush(color) p.save() p.translate(self.rect().center()) p.rotate(self._angle - float(i * 30.0)) p.drawRoundedRect(-capsuleWidth * 0.5, -(innerRadius + capsuleHeight), capsuleWidth, capsuleHeight, capsuleRadius, capsuleRadius) p.restore()
def __grabRegion(self): """ Private method to grab the selected region (i.e. do the snapshot). """ pol = QPolygon(self.__selection) if not pol.isEmpty(): self.__grabbing = True xOffset = self.__pixmap.rect().x() - pol.boundingRect().x() yOffset = self.__pixmap.rect().y() - pol.boundingRect().y() translatedPol = pol.translated(xOffset, yOffset) pixmap2 = QPixmap(pol.boundingRect().size()) pixmap2.fill(Qt.transparent) pt = QPainter() pt.begin(pixmap2) if pt.paintEngine().hasFeature(QPaintEngine.PorterDuff): pt.setRenderHints( QPainter.Antialiasing | QPainter.HighQualityAntialiasing | QPainter.SmoothPixmapTransform, True) pt.setBrush(Qt.black) pt.setPen(QPen(QBrush(Qt.black), 0.5)) pt.drawPolygon(translatedPol) pt.setCompositionMode(QPainter.CompositionMode_SourceIn) else: pt.setClipRegion(QRegion(translatedPol)) pt.setCompositionMode(QPainter.CompositionMode_Source) pt.drawPixmap(pixmap2.rect(), self.__pixmap, pol.boundingRect()) pt.end() self.grabbed.emit(pixmap2)
def setupScene(self): self.m_scene.setSceneRect(-300, -200, 600, 460) linearGrad = QLinearGradient(QPointF(-100, -100), QPointF(100, 100)) linearGrad.setColorAt(0, Qt.darkGreen)#QColor(255, 255, 255)) linearGrad.setColorAt(1, Qt.green)#QQColor(192, 192, 255)) self.setBackgroundBrush(linearGrad) radialGrad = QRadialGradient(30, 30, 30) radialGrad.setColorAt(0, Qt.yellow) radialGrad.setColorAt(0.2, Qt.yellow) radialGrad.setColorAt(1, Qt.transparent) pixmap = QPixmap(60, 60) pixmap.fill(Qt.transparent) painter = QPainter(pixmap) painter.setPen(Qt.NoPen) painter.setBrush(radialGrad) painter.drawEllipse(0, 0, 60, 60) painter.end() self.m_lightSource = self.m_scene.addPixmap(pixmap) self.m_lightSource.setZValue(2) self.proto = ProtoObj(0, 0, 50, 50, self) self.proto.initObj() #self.m_items.append(self.proto.getObj()[0]) self.m_scene.addItem(self.proto.getObj()[0])
def paintEvent(self, event): """QWidget.paintEvent() implementation """ painter = QPainter(self) painter.fillRect(event.rect(), self.palette().color(QPalette.Window)) painter.setPen(Qt.black) block = self._qpart.firstVisibleBlock() blockNumber = block.blockNumber() top = int(self._qpart.blockBoundingGeometry(block).translated(self._qpart.contentOffset()).top()) bottom = top + int(self._qpart.blockBoundingRect(block).height()) singleBlockHeight = self._qpart.cursorRect().height() boundingRect = self._qpart.blockBoundingRect(block) while block.isValid() and top <= event.rect().bottom(): if block.isVisible() and bottom >= event.rect().top(): number = str(blockNumber + 1) painter.drawText(0, top, self.__width - self._RIGHT_MARGIN - self._LEFT_MARGIN, self._qpart.fontMetrics().height(), Qt.AlignRight, number) if boundingRect.height() >= singleBlockHeight * 2: # wrapped block painter.fillRect(1, top + singleBlockHeight, self.__width - 2, boundingRect.height() - singleBlockHeight - 2, Qt.darkGreen) block = block.next() boundingRect = self._qpart.blockBoundingRect(block) top = bottom bottom = top + int(boundingRect.height()) blockNumber += 1
def draw_indicator(indicator: int): pixmap = QPixmap(24, 24) painter = QPainter(pixmap) w, h = pixmap.width(), pixmap.height() painter.fillRect(0, 0, w, h, QBrush((QColor(0, 0, 200, 255)))) pen = QPen(QColor("white")) pen.setWidth(2) painter.setPen(pen) font = util.get_monospace_font() font.setBold(True) font.setPixelSize(16) painter.setFont(font) f = QFontMetrics(painter.font()) indicator_str = str(indicator) if indicator < 10 else "+" fw = f.width(indicator_str) fh = f.height() painter.drawText(math.ceil(w / 2 - fw / 2), math.ceil(h / 2 + fh / 4), indicator_str) painter.end() return QIcon(pixmap)
def paintEvent(self, event): rect = QRect(10, 20, 80, 60) path = QPainterPath() path.moveTo(20, 80) path.lineTo(20, 30) path.cubicTo(80, 0, 50, 50, 80, 80) startAngle = 30 * 16 arcLength = 120 * 16 painter = QPainter(self) painter.setPen(self.pen) painter.setBrush(self.brush) if self.antialiased: painter.setRenderHint(QPainter.Antialiasing) for x in range(0, self.width(), 100): for y in range(0, self.height(), 100): painter.save() painter.translate(x, y) if self.transformed: painter.translate(50, 50) painter.rotate(60.0) painter.scale(0.6, 0.9) painter.translate(-50, -50) if self.shape == RenderArea.Line: painter.drawLine(rect.bottomLeft(), rect.topRight()) elif self.shape == RenderArea.Points: painter.drawPoints(RenderArea.points) elif self.shape == RenderArea.Polyline: painter.drawPolyline(RenderArea.points) elif self.shape == RenderArea.Polygon: painter.drawPolygon(RenderArea.points) elif self.shape == RenderArea.Rect: painter.drawRect(rect) elif self.shape == RenderArea.RoundedRect: painter.drawRoundedRect(rect, 25, 25, Qt.RelativeSize) elif self.shape == RenderArea.Ellipse: painter.drawEllipse(rect) elif self.shape == RenderArea.Arc: painter.drawArc(rect, startAngle, arcLength) elif self.shape == RenderArea.Chord: painter.drawChord(rect, startAngle, arcLength) elif self.shape == RenderArea.Pie: painter.drawPie(rect, startAngle, arcLength) elif self.shape == RenderArea.Path: painter.drawPath(path) elif self.shape == RenderArea.Text: painter.drawText(rect, Qt.AlignCenter, "PyQt by\nRiverbank Computing") elif self.shape == RenderArea.Pixmap: painter.drawPixmap(10, 10, self.pixmap) painter.restore() painter.setPen(self.palette().dark().color()) painter.setBrush(Qt.NoBrush) painter.drawRect(QRect(0, 0, self.width() - 1, self.height() - 1))
def paintEvent(self, event): if not globalSettings.lineNumbersEnabled: return QWidget.paintEvent(self, event) painter = QPainter(self) painter.fillRect(event.rect(), colorValues['lineNumberArea']) painter.setPen(colorValues['lineNumberAreaText']) cursor = self.editor.cursorForPosition(QPoint(0, 0)) atEnd = False fontHeight = self.fontMetrics().height() height = self.editor.height() if globalSettings.relativeLineNumbers: relativeTo = self.editor.textCursor().blockNumber() else: relativeTo = -1 while not atEnd: rect = self.editor.cursorRect(cursor) if rect.top() >= height: break number = str(cursor.blockNumber() - relativeTo).replace('-', '−') painter.drawText(0, rect.top(), self.width() - 2, fontHeight, Qt.AlignRight, number) cursor.movePosition(QTextCursor.EndOfBlock) atEnd = cursor.atEnd() if not atEnd: cursor.movePosition(QTextCursor.NextBlock)
def paintEvent(self, event): super().paintEvent(event) painter = QPainter(self) width = self.width() - self.RIGHT_MARGIN - self.LEFT_MARGIN height = self._neditor.fontMetrics().height() font = self._neditor.font() font_bold = self._neditor.font() font_bold.setBold(True) pen = QPen(self._color_unselected) painter.setPen(pen) painter.setFont(font) sel_start, sel_end = self._neditor.selection_range() has_sel = sel_start != sel_end current_line, _ = self._neditor.cursor_position # Draw visible blocks for top, line, block in self._neditor.visible_blocks: # Set bold to current line and selected lines if ((has_sel and sel_start <= line <= sel_end) or (not has_sel and current_line == line)): painter.fillRect( QRect(0, top, self.width(), height), self._color_selected) else: painter.setPen(pen) painter.setFont(font) painter.drawText(self.LEFT_MARGIN, top, width, height, Qt.AlignRight, str(line + 1))
def drawROIBoxes(self, image): #print(self.frame_data) if not isinstance(self.frame_data, pd.DataFrame) or len(self.frame_data) == 0 \ or not self.label_type in self.frame_data: return self.img_h_ratio = image.height()/self.image_height; self.img_w_ratio = image.width()/self.image_width; painter = QPainter() painter.begin(image) for row_id, row_data in self.frame_data.iterrows(): x = row_data['coord_x']*self.img_h_ratio y = row_data['coord_y']*self.img_w_ratio #check if the coordinates are nan if not (x == x) or not (y == y): continue x = int(x) y = int(y) c = self.wlabC[int(row_data[self.label_type])] painter.setPen(c) painter.setFont(QFont('Decorative', 10)) painter.drawText(x, y, str(int(row_data[self.worm_index_type]))) bb = row_data['roi_size']*self.img_w_ratio painter.drawRect(x-bb/2, y-bb/2, bb, bb); painter.end()
def drawData(self, points=[], color=Qt.black): painter = QPainter(self.image) painter.setPen(QPen(color, self.myPenWidth, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) for n in range(len(points) - 1): painter.drawLine(points[n][0], points[n][1], points[n + 1][0], points[n + 1][1]) self.update()
def lineNumberAreaPaintEvent(self, event): # When text zoomed line number not zoomed """Painting line number area""" painter = QPainter(self.lineNumberArea) painter.fillRect(event.rect(), Qt.lightGray) block = self.firstVisibleBlock() blockNumber = block.blockNumber() top = int(self.blockBoundingGeometry(block).translated(self.contentOffset()).top()) bottom = top + int(self.blockBoundingRect(block).height()) # font_height = self.fontMetrics().height() while block.isValid() and top <= event.rect().bottom(): if block.isVisible() and bottom >= event.rect().top(): font_original = self.document().defaultFont() size = font_original.pointSize() font = painter.font() font.setPointSize(size) painter.setFont(font) number = str(blockNumber + 1) painter.setPen(Qt.black) painter.drawText(0, top, self.lineNumberArea.width(), self.fontMetrics().height(), Qt.AlignRight, number) block = block.next() top = bottom bottom = top + int(self.blockBoundingRect(block).height()) blockNumber += 1
def paintEvent(self, event): """QLineEdit.paintEvent implementation. Draws prompt """ QLineEdit.paintEvent(self, event) if self._promptText and not self.text() and self.isEnabled(): option = QStyleOptionFrameV3() self.initStyleOption(option) left, top, right, bottom = self.getTextMargins() va = self.style().visualAlignment(self.layoutDirection(), self.alignment()) rect = ( self.style() .subElementRect(QStyle.SE_LineEditContents, option, self) .adjusted(2, 0, 0, 0) .adjusted(left, top, -right, -bottom) ) fm = QFontMetrics(self.font()) text = fm.elidedText(self._promptText, Qt.ElideRight, rect.width()) painter = QPainter(self) painter.setPen(self.palette().color(QPalette.Disabled, QPalette.Text)) painter.drawText(rect, va, text)
def paintEvent(self, event): background = QRadialGradient(QPointF(self.rect().topLeft()), 500, QPointF(self.rect().bottomRight())) background.setColorAt(0, self.backgroundColor1) background.setColorAt(1, self.backgroundColor2) painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.Antialiasing) painter.fillRect(event.rect(), QBrush(background)) painter.setPen(self.pen) for bubble in self.bubbles: if QRectF(bubble.position - QPointF(bubble.radius, bubble.radius), QSizeF(2*bubble.radius, 2*bubble.radius)).intersects(QRectF(event.rect())): bubble.drawBubble(painter) if self.newBubble: self.newBubble.drawBubble(painter) painter.end()
class RoundedPushButton1(QPushButton): def __init__(self,parent, default_wide, default_high,text=''): QPushButton.__init__(self, parent) #self.resize(100,80) self.default_high=default_high self.default_wide=default_wide self.xrd=self.default_wide/10 #self.yrd=self.default_high/10 self.yrd=self.xrd #self.resize(self.default_wide,self.default_high) self.backgroundColor = QPalette().light().color() self.backgroundColor.setRgb(157,157,157) #(220,203,231) #self.backgroundColor.setAlpha(0) self.brush=QBrush(Qt.SolidPattern) self.textlabel=textQLabel(self,text) def paintEvent(self,event): #brush.setStyle(Qt.Dense1Pattern) 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.drawRoundedRect(QRect(0,0,self.default_wide,self.default_high), self.xrd, self.yrd) #self.painter.drawPixmap(self.imgx, self.imgy, self.piximg) self.painter.end()
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 paintEvent(self, event): qp = QPainter() qp.begin(self) qp.setPen (QPen(QColor(0,0,0,0))) ysize, xsize = self.layout.shape canvas = self.contentsRect() for y in range(ysize): for x in range(xsize): qp.setBrush(self.colors[self.layout.grid[y][x]]) qp.drawRect(TILE_SIZE * x, TILE_SIZE * y, TILE_SIZE, TILE_SIZE) #Color(rgb=self.colors[self.layout.grid[y][x]]) #Rectangle(pos=(TILE_SIZE * x, TILE_SIZE * y), size=(TILE_SIZE, TILE_SIZE)) pac_x = self.current_game_state.agents[0].position[0] * TILE_SIZE pac_y = self.current_game_state.agents[0].position[1] * TILE_SIZE qp.setBrush(QBrush(QColor(255,255,0))) qp.drawEllipse(pac_x, pac_y, TILE_SIZE, TILE_SIZE) for g in self.current_game_state.agents[1:]: g_x = g.position[0] * TILE_SIZE g_y = g.position[1] * TILE_SIZE qp.setBrush(QBrush(QColor(255,0,0))) qp.drawEllipse(g_x, g_y, TILE_SIZE, TILE_SIZE) for y in range(ysize): for x in range(xsize): if self.current_game_state.food[y][x]: qp.setBrush(QBrush(QColor(255,255,255))) qp.drawEllipse(x * TILE_SIZE + TILE_SIZE / 2, y * TILE_SIZE + TILE_SIZE / 2, TILE_SIZE / 4, TILE_SIZE / 4) qp.end()
def paintEvent(self,event=None): painter = QPainter(self) pixmap=QPixmap(":/images/wheelfinal.png") #painter.begin(self) #painter.drawPixmap(QtCore.QRect(self.left, self.top, self.width, self.height), self.pixmap) painter.drawPixmap(self.rect(), pixmap) self.resize(pixmap.width(),pixmap.height()) pen = QPen(Qt.red, 3) painter.setPen(pen) painter.drawArc (self.disc_center-int(self.distance_from_center(self.points[0])) , self.disc_center - int(self.distance_from_center (self.points[0])) , 2*int(self.distance_from_center(self.points[0])) , 2*int(self.distance_from_center(self.points[0])) , int(16*self.hue_min) , int(16*(self.hue_max-self.hue_min)))#arc joining point 0 and point 1 painter.drawLine(int(self.points[0][0]),int(self.points[0][1]),int(self.points[3][0]),int(self.points[3][1]))#line joining point 0 and point 3 painter.drawArc(self.disc_center-int(self.distance_from_center(self.points[2])) , self.disc_center - int(self.distance_from_center (self.points[2])) , 2*int(self.distance_from_center(self.points[2])) , 2*int(self.distance_from_center(self.points[2])) , int(16*self.hue_min) , int(16*(self.hue_max-self.hue_min)))#arc joining point 2 and 3 painter.drawLine(int(self.points[1][0]),int(self.points[1][1]),int(self.points[2][0]),int(self.points[2][1]))#line joining point 1 and 2 self.update()
def paintEvent(self, event): # Check whether this orb is enhanced if type(self.parent) == Board: enh = self.parent.enhanced[self.position] else: enh = False painter = QPainter(self) painter.drawPixmap(event.rect().adjusted(2,2,-2,-2), self.pixmap()) w = event.rect().width() if enh: path = QPainterPath() pen = QPen() pen.setWidth(1); pen.setBrush(Qt.white) brush = QBrush(Qt.yellow) font = QFont() font.setPointSize(20) font.setWeight(QFont.Black) path.addText(event.rect().x()+w-15,event.rect().y()+w-5,font,'+') painter.setPen(pen) painter.setBrush(brush) painter.setFont(font) painter.drawPath(path)
def image(cls, **kwargs): """ Returns an image suitable for the palette. :rtype: QPixmap """ # INITIALIZATION pixmap = QPixmap(kwargs['w'], kwargs['h']) pixmap.fill(Qt.transparent) painter = QPainter(pixmap) # INIT THE LINE p1 = QPointF(((kwargs['w'] - 54) / 2), kwargs['h'] / 2) p2 = QPointF(((kwargs['w'] - 54) / 2) + 54 - 2, kwargs['h'] / 2) line = QLineF(p1, p2) # CLACULATE HEAD COORDS angle = line.angle() p1 = QPointF(line.p2().x() + 2, line.p2().y()) p2 = p1 - QPointF(sin(angle + M_PI / 3.0) * 8, cos(angle + M_PI / 3.0) * 8) p3 = p1 - QPointF(sin(angle + M_PI - M_PI / 3.0) * 8, cos(angle + M_PI - M_PI / 3.0) * 8) # INITIALIZE HEAD head = QPolygonF([p1, p2, p3]) # DRAW EDGE LINE painter.setRenderHint(QPainter.Antialiasing) painter.setPen(QPen(QColor(0, 0, 0), 1.1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) painter.drawLine(line) # DRAW EDGE HEAD painter.setPen(QPen(QColor(0, 0, 0), 1.1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) painter.setBrush(QColor(0, 0, 0)) painter.drawPolygon(head) return pixmap
def paintEvent(self, event): qp = QPainter(self) qp.setRenderHint(QPainter.Antialiasing) # <- Set anti-aliasing See https://wiki.python.org/moin/PyQt/Painting%20and%20clipping%20demonstration qp.setPen(QPen(Qt.black, 5, Qt.SolidLine)) qp.setBrush(QBrush(Qt.red, Qt.SolidPattern)) qp.drawRect(10, 10, 180, 50) # x_start, y_start, x_length, y_length qp.setBrush(QBrush(Qt.red, Qt.DiagCrossPattern)) qp.drawRect(210, 10, 180, 50) qp.setBrush(QBrush(Qt.red, Qt.Dense1Pattern)) qp.drawRect(410, 10, 180, 50) qp.setBrush(QBrush(Qt.red, Qt.HorPattern)) qp.drawRect(610, 10, 180, 50) qp.setBrush(QBrush(Qt.red, Qt.VerPattern)) qp.drawRect(810, 10, 180, 50) qp.setBrush(QBrush(Qt.red, Qt.BDiagPattern)) qp.drawRect(1010, 10, 180, 50)
def paintEvent(self, event): painter = QPainter(self) if self.pixmap: size = self.pixmap.size() aspect = float(size.width()) / size.height() if aspect > 1: # Image is wider than it is tall - centre vertically left = 0 width = self.width() height = self.height() / aspect top = (self.height() - height) / 2 else: # Image is taller than it is wide - centre horizontally top = 0 height = self.height() width = self.width() * aspect left = (self.width() - width) / 2 painter.drawPixmap(QRect(left, top, width, height), self.pixmap) if self.focus: # self.focus contains coords between 0 and 1 - translate these # to pixels pixels = QRectF(left + self.focus.left() * width, top + self.focus.top() * height, self.focus.width() * width, self.focus.height() * height) # Outer box in white painter.setPen(QPen(Qt.white, 1, Qt.SolidLine)) painter.drawRect(pixels) # Inner box in black painter.setPen(QPen(Qt.black, 1, Qt.SolidLine)) painter.drawRect(pixels.adjusted(1, 1, -1, -1))
def paintEvent(self, event): painter = QPainter(self) icon = self.icon_pressed if self.isDown() else self.icon if icon is not None: x = (self.width() - icon.width()) / 2 y = (self.height() - icon.height()) / 2 painter.drawPixmap(x, y, icon) else: width = self.width() height = self.height() padding = width / 5 radius = width - 2*padding palette = self.palette() # Mid is darker than Dark. Go figure... -Dan bg_color = palette.color(QPalette.Mid) if self.isDown() else palette.color(QPalette.Dark) fg_color = palette.color(QPalette.Window) # or QPalette.Base for white painter.setRenderHint(QPainter.Antialiasing, True) painter.setBrush(bg_color) painter.setPen(bg_color) painter.drawEllipse(padding, padding, radius, radius) padding = padding * 2 painter.setPen(fg_color) painter.drawLine(padding, padding, width-padding, height-padding) painter.drawLine(padding, height-padding, width-padding, padding)
def numPaintEvent(self, event): """ Paint the editor :param event: :return: """ painter = QPainter(self.numArea) painter.fillRect(event.rect(), Qt.lightGray) block = self.firstVisibleBlock() block_num = block.blockNumber() top = self.blockBoundingGeometry(block).translated(self.contentOffset()).top() bottom = top + self.blockBoundingRect(block).height() while block.isValid() and top <= event.rect().bottom(): if block.isVisible() and bottom >= event.rect().top(): number = block_num + 1 painter.setPen(Qt.darkRed) painter.drawText(0, top, self.numArea.width(), self.fontMetrics().height(), Qt.AlignRight, ' %s ' % str(number)) # padding block = block.next() top = bottom bottom = top + self.blockBoundingRect(block).height() block_num += 1
def paintGL(self): from PyQt5.QtGui import QBrush, QPen, QColor, QPainter from PyQt5.QtCore import QPointF painter = QPainter(self) painter.setPen(QPen(QColor(0, 0, 0, 0), 0)) painter.fillRect(0, 0, self.width(), self.height(), QColor(0, 0, 0)) for strand_id, strand in self.scene.strands.items(): if strand is None: continue spacing = 4 if self._blur else 1 instructions = list(zip(self.locations[strand_id][::spacing], strand.all_contents[::spacing])) if self._blur: for (x, y), (r, g, b) in instructions: painter.setBrush(QColor(r, g, b, 50)) painter.drawEllipse(QPointF(x, y), 16, 16) for (x, y), (r, g, b) in instructions: painter.setBrush(QColor(r, g, b, 50)) painter.drawEllipse(QPointF(x, y), 6, 6) painter.setBrush(QColor(r, g, b, 255)) painter.drawEllipse(QPointF(x, y), 3, 3)
def __init__(self): super().__init__() title = "Paint Application" top = 400 left = 400 width = 800 height = 600 self.px_p_meter = 100 icon = "icons/pain.png" self.setWindowTitle(title) self.setGeometry(top, left, width, height) self.setWindowIcon(QIcon(icon)) self.image = QImage(self.size(), QImage.Format_RGB32) self.image.fill(Qt.white) self.waypoints = [] self.drawing = False self.brushSize = 5 self.brushColor = Qt.black self.lastPoint = QPoint() mainMenu = self.menuBar() fileMenu = mainMenu.addMenu("File") brushSize = mainMenu.addMenu("Brush Size") brushColor = mainMenu.addMenu("Brush Color") ''' saveAction = QAction(QIcon("icons/save.png"), "Save",self) saveAction.setShortcut("Ctrl+S") fileMenu.addAction(saveAction) saveAction.triggered.connect(self.save) ''' exportAction = QAction(QIcon("icons/export.png"), "Export Track", self) exportAction.setShortcut("Ctrl+E") fileMenu.addAction(exportAction) exportAction.triggered.connect(self.exportTrack) clearAction = QAction(QIcon("icons/clear.png"), "Clear", self) clearAction.setShortcut("Ctrl+C") fileMenu.addAction(clearAction) clearAction.triggered.connect(self.clear) threepxAction = QAction(QIcon("icons/threepx.png"), "3px", self) brushSize.addAction(threepxAction) threepxAction.triggered.connect(self.threePixel) fivepxAction = QAction(QIcon("icons/fivepx.png"), "5px", self) brushSize.addAction(fivepxAction) fivepxAction.triggered.connect(self.fivePixel) sevenpxAction = QAction(QIcon("icons/sevenpx.png"), "7px", self) brushSize.addAction(sevenpxAction) sevenpxAction.triggered.connect(self.sevenPixel) ninepxAction = QAction(QIcon("icons/ninepx.png"), "9px", self) brushSize.addAction(ninepxAction) ninepxAction.triggered.connect(self.ninePixel) blackAction = QAction(QIcon("icons/black.png"), "Black", self) blackAction.setShortcut("Ctrl+B") brushColor.addAction(blackAction) blackAction.triggered.connect(self.blackColor) whitekAction = QAction(QIcon("icons/white.png"), "White", self) whitekAction.setShortcut("Ctrl+W") brushColor.addAction(whitekAction) whitekAction.triggered.connect(self.whiteColor) redAction = QAction(QIcon("icons/red.png"), "Red", self) redAction.setShortcut("Ctrl+R") brushColor.addAction(redAction) redAction.triggered.connect(self.redColor) greenAction = QAction(QIcon("icons/green.png"), "Green", self) greenAction.setShortcut("Ctrl+G") brushColor.addAction(greenAction) greenAction.triggered.connect(self.greenColor) yellowAction = QAction(QIcon("icons/yellow.png"), "Yellow", self) yellowAction.setShortcut("Ctrl+Y") brushColor.addAction(yellowAction) yellowAction.triggered.connect(self.yellowColor) painter = QPainter(self.image) painter.setBrush(Qt.black) painter.setPen(QPen(Qt.black, 2, Qt.SolidLine)) painter.drawLine(10, 50, 10 + self.px_p_meter, 50) pen = QPen(Qt.black) pen.setWidth(2) painter.setPen(pen) font = QFont() font.setFamily('Times') font.setBold(True) font.setPointSize(12) painter.setFont(font) painter.drawText(20 + self.px_p_meter, 55, "1 m")
class Example(QWidget): overlay: QImage #Overlay(Накладываем) Picture on Window timer: QTimer #Timet init painter: QPainter Colors: list arr_points: list DeltaX: int DeltaY: int SelfHeight: int LastAngle: int LastMousePosition: QPoint def __init__(self): super().__init__() self.initUI() def keyPressEvent(self, event): if event.key() == 16777216: self.FileSaving(FILE_NAME) sys.exit() #Programm Closing def get_station_popularity(station_name, trends_object): kw_list = [station_name] trends_object.build_payload(kw_list, cat=0, timeframe='today 5-y', geo='', gprop='') interest = [1, 2, 3] #trends_object.interest_over_time() plt.plot(interest[station_name]) plt.show() def mousePressEvent(self, event): mousePoint = event.pos() self.LastMousePosition = mousePoint if event.button() == 2: WindowW = self.frameGeometry().width()# WindowSize WindowH = self.frameGeometry().height()# WindowSize imgH = self.overlay.height()# Original Picture Size imgW = self.overlay.width()# Original Picture Size img = self.overlay.scaledToHeight(self.SelfHeight, Qt.FastTransformation) #AdjX = (WindowW-img.width())/2 ResultX = imgW * (mousePoint.x() - self.DeltaX) / img.width() ResultY = imgH / 100 * ((mousePoint.y() - self.DeltaY) / (self.SelfHeight / 100)) #eraser = 7 self.painter.drawEllipse(QPoint(ResultX, ResultY), RADIUS, RADIUS) #self.painter.eraseRect(QRect(QPoint(ResultX-RADIUS/2-eraser, ResultY-RADIUS/2-eraser), QPoint(ResultX+radius/2+eraser, ResultY+radius/2+eraser))) self.arr_points.append((ResultX, ResultY)) #print([(round(x[0]), round(x[1])) for x in self.arr_points]) self.update()#Redraw def FileSaving(self, fileName: str): with open(fileName, 'w') as f: for item in self.arr_points: f.write(';'.join(str(x) for x in item) + '\n') f.close() def FileDrawing(self, fileName: str): penLine = QPen(QColor(Qt.red)) penLine.setWidth(10) #my_file = Path('!StationsLine12.txt') #print(my_file.isfile()) for n in range(28): penEllipse = QPen(self.Colors[int(n/2)]) penEllipse.setWidth(5) data = [] path = fileName + str(n/2 + 1) + '.txt' print(path) my_file = Path(path) #print(os.listdir()) if my_file.is_file(): with open(fileName + str(n/2 + 1) + '.txt', 'r') as f: data = f.read().split('\n') f.close() lastX = None lastY = None Point1 = None Point2 = None Startlen = None x = 0 y = 0 for line in data: x, y = line.split(';') if lastX is not None or lastY is not None: self.painter.setPen(penLine) Point1 = QPoint(lastX, lastY) Point2 = QPoint(float(x), float(y)) #self.painter.drawLine(Point1, Point2) self.painter.setPen(penEllipse) penLine = QPen(QColor(Qt.red)) self.painter.setBrush(QColor(Qt.white)) self.painter.drawEllipse(lastX-RADIUS, lastY-RADIUS, RADIUS*2, RADIUS*2) lastX = float(x) lastY = float(y) self.painter.setPen(penEllipse) self.painter.setBrush(QColor(Qt.white)) self.painter.drawEllipse(float(x)-RADIUS, float(y)-RADIUS, RADIUS*2, RADIUS*2) def mouseReleaseEvent(self, event): self.point = None def closeEvent(self, event): #self.FileSaving(FILE_NAME) sys.exit() #Programm Closing def initUI(self): self.Colors = [ QColor(228, 37, 24),#1 QColor(75, 175, 79),#2 QColor(5, 114, 185),#3 QColor(36, 188, 239),#4 QColor(146, 82, 51),#5 QColor(239, 128, 39),#6 QColor(148, 63, 144),#7 QColor(255, 209, 30),#8 QColor(173, 172, 172),#9 QColor(185, 206, 31),#10 QColor(134, 204, 206),#11 QColor(186, 200, 232),#12 QColor(68, 143, 201),#13 QColor(232, 68, 57),#14 ] self.showMaximized() #self.showNormal() self.arr_points = [] self.LastAngle = 0 self.timer = QTimer() #Timer init self.timer.timeout.connect(self.update)# Timer init self.setWindowTitle('Moscow Metro Map Poppularity')# Title self.point = None self.DeltaX = 0 self.DeltaY = 0 self.SelfHeight = self.frameGeometry().height() self.LastMousePosition = QPoint(0, 0) self.overlay = QImage() self.overlay.load('Moscow Metro Map Stations Popularity\\MainMap.bmp') pen = QPen(QColor(Qt.red)) pen.setWidth(5) self.painter = QPainter(self.overlay) self.painter.setPen(pen) self.painter.Antialiasing = True self.timer.start(1000/50) #50 кадров в секунду self.FileDrawing(FILE_NAME) def paintEvent(self, event): painter = QPainter() painter.begin(self) #windowsWidth = self.frameGeometry().width() windowsHeight = self.frameGeometry().height() img = self.overlay.scaledToHeight(self.SelfHeight, 0) painter.drawImage(self.DeltaX, self.DeltaY, img) painter.end() del painter def mouseMoveEvent(self, event): CurentPos = event.pos() self.DeltaX -= self.LastMousePosition.x()-CurentPos.x() self.DeltaY -= self.LastMousePosition.y()-CurentPos.y() #self.LastMousePosition = mousePoint self.LastMousePosition = event.pos() def wheelEvent(self, event): #print(str(event.angleDelta())) self.SelfHeight += (event.angleDelta().y()) / 10 self.LastAngle = event.angleDelta().y() def resizeEvent(self, event): self.SelfHeight = self.frameGeometry().height() if __name__ == '__main__': #Window Settings: app = QApplication(sys.argv)#Init application ex = Example()#Init programm sys.exit(app.exec_())#Make Programm End when Window is closed
def drawColoredPreviewWaveformPixmap(self): if self.data is None: return None pixmap = QPixmap(self.pixmap_width, self.pixmap_height) pixmap.fill(Qt.black) painter = QPainter() painter.begin(pixmap) painter.setBrush(Qt.SolidPattern) w = 1200 xr = self.pixmap_width / w if self.data and len(self.data) >= w: data = self.data # Get max_height to adjust waveform height max_height = 0 for x in range(w): d3 = data[x * 6 + 3] d4 = data[x * 6 + 4] d5 = data[x * 6 + 5] max_height = max(max_height, d3, d4, d5) max_back_height = 0 max_front_height = 0 hr = 127 / max_height for x in range(w): # d0 & d1: max of d1 and d2 sets the steepness of the ramp of the blueness d0 = data[x * 6 + 0] d1 = data[x * 6 + 1] # d2: ""\__ blueness d2 = data[x * 6 + 2] # d3: "\___ red d3 = data[x * 6 + 3] # d4: _/"\_ green d4 = data[x * 6 + 4] # d5: ___/" blue and height of front waveform d5 = data[x * 6 + 5] # background waveform height is max height of d3, d4 (and d5 as it is foreground) back_height = max(d3, d4, d5) # front waveform height is d5 front_height = d5 if not self.colored_render_blue_only: # color if back_height > 0: red = d3 / back_height * 255 green = d4 / back_height * 255 blue = d5 / back_height * 255 else: red = green = blue = 0 else: # NXS2 blue # NOTE: the whole steepness and zero cutoff just don't seems to make any sense, however it looks as on CDJ # Maybe this is related to the bytes wrongly(?) interpreted as signed bytes instead of unsigned. steepness = max(d0, d1) blueness = d2 color = 0 if steepness > 0 and blueness > 0: color = min(int((blueness * (127 / steepness)) / 16), 7) red, green, blue = blue_map[color] back_height = int(back_height * hr) front_height = int(front_height * hr) max_back_height = max(back_height, max_back_height) max_front_height = max(front_height, max_front_height) xd = int(x * xr) if int((x + 1) * xr) > xd: painter.setPen( QColor(int(red * .75), int(green * .75), int(blue * .75))) painter.drawLine(xd, 31, xd, 31 - int(max_back_height / 4)) painter.setPen(QColor(red, green, blue)) painter.drawLine(xd, 31, xd, 31 - int(max_front_height / 4)) max_back_height = max_front_height = 0 # base line painter.setPen(Qt.white) painter.drawLine(0, 33, 399, 33) painter.end() return pixmap
def circle(self): painter = QPainter(self) painter.setPen(QPen(Qt.green, 5, Qt.SolidLine)) painter.setBrush(QBrush(Qt.green, Qt.SolidPattern)) painter.drawEllipse(40, 40, 400, 200) pass
def overlay_marks(self, img, is_cseed=False, calibration_sheet=False): border_color = Qt.white base_img = QImage(self.f_size.width(), self.f_size.height(), QImage.Format_ARGB32) base_img.fill(border_color) img = QImage(img) painter = QPainter() painter.begin(base_img) total_distance_h = round(base_img.width() / self.abstand_v) dist_v = round(total_distance_h) / 2 dist_h = round(total_distance_h) / 2 img = img.scaledToWidth(base_img.width() - (2 * (total_distance_h))) painter.drawImage(total_distance_h, total_distance_h, img) #frame around image pen = QPen(Qt.black, 2) painter.setPen(pen) #horz painter.drawLine(0, total_distance_h, base_img.width(), total_distance_h) painter.drawLine(0, base_img.height() - (total_distance_h), base_img.width(), base_img.height() - (total_distance_h)) #vert painter.drawLine(total_distance_h, 0, total_distance_h, base_img.height()) painter.drawLine(base_img.width() - (total_distance_h), 0, base_img.width() - (total_distance_h), base_img.height()) #border around img border_thick = 6 Rpath = QPainterPath() Rpath.addRect( QRectF((total_distance_h) + (border_thick / 2), (total_distance_h) + (border_thick / 2), base_img.width() - ((total_distance_h) * 2) - ((border_thick) - 1), (base_img.height() - ((total_distance_h)) * 2) - ((border_thick) - 1))) pen = QPen(Qt.black, border_thick) pen.setJoinStyle(Qt.MiterJoin) painter.setPen(pen) painter.drawPath(Rpath) Bpath = QPainterPath() Bpath.addRect( QRectF((total_distance_h), (total_distance_h), base_img.width() - ((total_distance_h) * 2), (base_img.height() - ((total_distance_h)) * 2))) pen = QPen(Qt.black, 1) painter.setPen(pen) painter.drawPath(Bpath) pen = QPen(Qt.black, 1) painter.setPen(pen) painter.drawLine(0, base_img.height() / 2, total_distance_h, base_img.height() / 2) painter.drawLine(base_img.width() / 2, 0, base_img.width() / 2, total_distance_h) painter.drawLine(base_img.width() - total_distance_h, base_img.height() / 2, base_img.width(), base_img.height() / 2) painter.drawLine(base_img.width() / 2, base_img.height(), base_img.width() / 2, base_img.height() - total_distance_h) #print code f_size = 37 QFontDatabase.addApplicationFont( os.path.join(os.path.dirname(__file__), 'DejaVuSansMono-Bold.ttf')) font = QFont("DejaVu Sans Mono", f_size - 11, QFont.Bold) font.setPixelSize(35) painter.setFont(font) if not calibration_sheet: if is_cseed: #its a secret painter.setPen(QPen(Qt.black, 1, Qt.DashDotDotLine)) painter.drawLine(0, dist_v, base_img.width(), dist_v) painter.drawLine(dist_h, 0, dist_h, base_img.height()) painter.drawLine(0, base_img.height() - dist_v, base_img.width(), base_img.height() - (dist_v)) painter.drawLine(base_img.width() - (dist_h), 0, base_img.width() - (dist_h), base_img.height()) painter.drawImage( ((total_distance_h)) + 11, ((total_distance_h)) + 11, QImage(icon_path('electrumb.png')).scaledToWidth( 2.1 * (total_distance_h), Qt.SmoothTransformation)) painter.setPen(QPen(Qt.white, border_thick * 8)) painter.drawLine( base_img.width() - ((total_distance_h)) - (border_thick * 8) / 2 - (border_thick / 2) - 2, (base_img.height() - ((total_distance_h))) - ((border_thick * 8) / 2) - (border_thick / 2) - 2, base_img.width() - ((total_distance_h)) - (border_thick * 8) / 2 - (border_thick / 2) - 2 - 77, (base_img.height() - ((total_distance_h))) - ((border_thick * 8) / 2) - (border_thick / 2) - 2) painter.setPen(QColor(0, 0, 0, 255)) painter.drawText( QRect( 0, base_img.height() - 107, base_img.width() - total_distance_h - border_thick - 11, base_img.height() - total_distance_h - border_thick), Qt.AlignRight, self.versioned_seed.version + '_' + self.versioned_seed.checksum) painter.end() else: # revealer painter.setPen(QPen(border_color, 17)) painter.drawLine(0, dist_v, base_img.width(), dist_v) painter.drawLine(dist_h, 0, dist_h, base_img.height()) painter.drawLine(0, base_img.height() - dist_v, base_img.width(), base_img.height() - (dist_v)) painter.drawLine(base_img.width() - (dist_h), 0, base_img.width() - (dist_h), base_img.height()) painter.setPen(QPen(Qt.black, 2)) painter.drawLine(0, dist_v, base_img.width(), dist_v) painter.drawLine(dist_h, 0, dist_h, base_img.height()) painter.drawLine(0, base_img.height() - dist_v, base_img.width(), base_img.height() - (dist_v)) painter.drawLine(base_img.width() - (dist_h), 0, base_img.width() - (dist_h), base_img.height()) logo = QImage(icon_path('revealer_c.png')).scaledToWidth( 1.3 * (total_distance_h)) painter.drawImage((total_distance_h) + (border_thick), ((total_distance_h)) + (border_thick), logo, Qt.SmoothTransformation) #frame around logo painter.setPen(QPen(Qt.black, border_thick)) painter.drawLine( total_distance_h + border_thick, total_distance_h + logo.height() + 3 * (border_thick / 2), total_distance_h + logo.width() + border_thick, total_distance_h + logo.height() + 3 * (border_thick / 2)) painter.drawLine( logo.width() + total_distance_h + 3 * (border_thick / 2), total_distance_h + (border_thick), total_distance_h + logo.width() + 3 * (border_thick / 2), total_distance_h + logo.height() + (border_thick)) #frame around code/qr qr_size = 179 painter.drawLine((base_img.width() - ((total_distance_h)) - (border_thick / 2) - 2) - qr_size, (base_img.height() - ((total_distance_h))) - ((border_thick * 8)) - (border_thick / 2) - 2, (base_img.width() / 2 + (total_distance_h / 2) - border_thick - (border_thick * 8) / 2) - qr_size, (base_img.height() - ((total_distance_h))) - ((border_thick * 8)) - (border_thick / 2) - 2) painter.drawLine( (base_img.width() / 2 + (total_distance_h / 2) - border_thick - (border_thick * 8) / 2) - qr_size, (base_img.height() - ((total_distance_h))) - ((border_thick * 8)) - (border_thick / 2) - 2, base_img.width() / 2 + (total_distance_h / 2) - border_thick - (border_thick * 8) / 2 - qr_size, ((base_img.height() - ((total_distance_h))) - (border_thick / 2) - 2)) painter.setPen(QPen(Qt.white, border_thick * 8)) painter.drawLine( base_img.width() - ((total_distance_h)) - (border_thick * 8) / 2 - (border_thick / 2) - 2, (base_img.height() - ((total_distance_h))) - ((border_thick * 8) / 2) - (border_thick / 2) - 2, base_img.width() / 2 + (total_distance_h / 2) - border_thick - qr_size, (base_img.height() - ((total_distance_h))) - ((border_thick * 8) / 2) - (border_thick / 2) - 2) painter.setPen(QColor(0, 0, 0, 255)) painter.drawText( QRect(((base_img.width() / 2) + 21) - qr_size, base_img.height() - 107, base_img.width() - total_distance_h - border_thick - 93, base_img.height() - total_distance_h - border_thick), Qt.AlignLeft, self.versioned_seed.get_ui_string_version_plus_seed()) painter.drawText( QRect( 0, base_img.height() - 107, base_img.width() - total_distance_h - border_thick - 3 - qr_size, base_img.height() - total_distance_h - border_thick), Qt.AlignRight, self.versioned_seed.checksum) # draw qr code qr_qt = self.paintQR( self.versioned_seed.get_ui_string_version_plus_seed() + self.versioned_seed.checksum) target = QRectF(base_img.width() - 65 - qr_size, base_img.height() - 65 - qr_size, qr_size, qr_size) painter.drawImage(target, qr_qt) painter.setPen(QPen(Qt.black, 4)) painter.drawLine(base_img.width() - 65 - qr_size, base_img.height() - 65 - qr_size, base_img.width() - 65 - qr_size, (base_img.height() - ((total_distance_h))) - ((border_thick * 8)) - (border_thick / 2) - 4) painter.drawLine(base_img.width() - 65 - qr_size, base_img.height() - 65 - qr_size, base_img.width() - 65, base_img.height() - 65 - qr_size) painter.end() else: # calibration only painter.end() cal_img = QImage(self.f_size.width() + 100, self.f_size.height() + 100, QImage.Format_ARGB32) cal_img.fill(Qt.white) cal_painter = QPainter() cal_painter.begin(cal_img) cal_painter.drawImage(0, 0, base_img) #black lines in the middle of border top left only cal_painter.setPen(QPen(Qt.black, 1, Qt.DashDotDotLine)) cal_painter.drawLine(0, dist_v, base_img.width(), dist_v) cal_painter.drawLine(dist_h, 0, dist_h, base_img.height()) pen = QPen(Qt.black, 2, Qt.DashDotDotLine) cal_painter.setPen(pen) n = 15 cal_painter.setFont(QFont("DejaVu Sans Mono", 21, QFont.Bold)) for x in range(-n, n): #lines on bottom (vertical calibration) cal_painter.drawLine((((base_img.width()) / (n * 2)) * (x)) + (base_img.width() / 2) - 13, x + 2 + base_img.height() - (dist_v), (((base_img.width()) / (n * 2)) * (x)) + (base_img.width() / 2) + 13, x + 2 + base_img.height() - (dist_v)) num_pos = 9 if x > 9: num_pos = 17 if x < 0: num_pos = 20 if x < -9: num_pos = 27 cal_painter.drawText((((base_img.width()) / (n * 2)) * (x)) + (base_img.width() / 2) - num_pos, 50 + base_img.height() - (dist_v), str(x)) #lines on the right (horizontal calibrations) cal_painter.drawLine( x + 2 + (base_img.width() - (dist_h)), ((base_img.height() / (2 * n)) * (x)) + (base_img.height() / n) + (base_img.height() / 2) - 13, x + 2 + (base_img.width() - (dist_h)), ((base_img.height() / (2 * n)) * (x)) + (base_img.height() / n) + (base_img.height() / 2) + 13) cal_painter.drawText(30 + (base_img.width() - (dist_h)), ((base_img.height() / (2 * n)) * (x)) + (base_img.height() / 2) + 13, str(x)) cal_painter.end() base_img = cal_img return base_img
def paintEvent(self, e): # Horizon green rectangle r = self.size * 2 # Rectangle width r2 = self.size * 2 # Rectangle height painter = QPainter(self) # Blue background painter.setPen(QPen(QColor(30, 144, 255), 0, Qt.SolidLine)) painter.setBrush(QBrush(QColor(30, 144, 255), Qt.SolidPattern)) painter.drawRect(0, 0, self.width(), self.height()) painter.setPen(QPen(QColor(166, 99, 0), 0, Qt.SolidLine)) # Brown horizon painter.setBrush(QBrush(QColor(166, 99, 0), Qt.SolidPattern)) centerX = int(self.width() / 2) centerY = int(self.height() / 2) pitchScaleFactor = (-1 / 50) * (self.height() / 2) painter.translate( centerX, centerY) # Set our coordinate system to be centered on the widget painter.rotate(-self.roll) painter.drawRect(-r, pitchScaleFactor * self.pitch, 2 * r, r2) # Pitch marker lineWidth = int(self.width() / 200) fontSize = max(int(self.width() / 30), 8) shortLength = self.width() / 8 longLength = self.width() / 4 painter.setPen(QPen(Qt.white, lineWidth, Qt.SolidLine)) painter.setBrush(QBrush(Qt.white, Qt.SolidPattern)) spacing = 5 # Draw lines every 5 degrees nearestPitch = spacing * round(self.pitch / spacing) maxToDrawLine = int(abs( (self.width() * 0.5) / (2 * pitchScaleFactor) )) # Figure out the biggest pitch to get a line drawn maxPitch = min(nearestPitch + maxToDrawLine + spacing, 91) minPitch = max(nearestPitch - maxToDrawLine, -90) for i in range(minPitch, maxPitch, spacing): nearestPitchDelta = (self.pitch - i) * pitchScaleFactor if i % 10 != 0: painter.drawLine(-shortLength / 2, nearestPitchDelta, shortLength / 2, nearestPitchDelta) textDistance = shortLength / 2 else: painter.drawLine(-longLength / 2, nearestPitchDelta, longLength / 2, nearestPitchDelta) textDistance = longLength / 2 painter.setFont(QFont("Helvetica", fontSize)) painter.drawText(textDistance * 1.1, nearestPitchDelta + int(fontSize / 2), "{}".format(abs(i))) painter.drawText(-(textDistance * 1.1 + (fontSize - 2) * 2), nearestPitchDelta + int(fontSize / 2), "{:2}".format(abs(i))) self.rollIndicatorImage.setRotation(self.roll) # Set roll image
def paintEvent(self, e): if not len(self.__cluster_container.clusters) or self.width( ) == 0 or self.height() == 0: return painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) painter.setPen(QColor("transparent")) painter.setBrush(QColor("red")) fm = QFontMetricsF(painter.font()) neighbor_id = self.__cluster_container.neighbor_id(self.__active_point) # draw objects for cluster in self.__cluster_container.clusters: try: painter.setBrush( QColor(self.__colors[ self.__cluster_container.clusters.index(cluster)])) except IndexError: print("Run out of colors") exit(1) for obj in cluster.objects: painter.setPen(QColor("transparent")) painter.drawEllipse(obj.x(), obj.y(), ClustersView.PARTICLE_SIZE.width(), ClustersView.PARTICLE_SIZE.height()) painter.setPen(QColor("gray")) painter.drawText(obj.pos - QPointF(0, 2), str(obj.id)) used_cluster_obj, distance = cluster.distance_from_point( self.__active_point) center_of_obj = QPointF( used_cluster_obj.x() + ClustersView.PARTICLE_SIZE.width() / 2, used_cluster_obj.y() + ClustersView.PARTICLE_SIZE.height() / 2) # draw circle painter.setPen(QColor("gray")) painter.setBrush(QColor("transparent")) painter.setOpacity(0.5) painter.drawEllipse(center_of_obj, ClustersView.PARTICLE_SIZE.width() * 2, ClustersView.PARTICLE_SIZE.height() * 2) painter.setOpacity(1) #draw line painter.setPen( QColor("#007ACC" if neighbor_id == cluster.id else "lightGray")) painter.drawLine(self.__active_point, center_of_obj) #draw text formatted_distance = "{:.1f}".format(distance) painter.setPen(QColor("gray")) painter.drawText( center_of_obj - QPointF(fm.width(str(formatted_distance)) / 2, 25), str(formatted_distance)) # draw text at active point coords = "[{:.1f} {:.1f}]".format(self.__active_point.x(), self.__active_point.y()) painter.drawText( self.__active_point - QPointF(fm.width(coords) / 2, 15), coords)
def paintEvent(self, objQPaintEvent): p = QPainter() p.begin(self) pen = QPen(Qt.black, 2, Qt.SolidLine) p.setPen(pen) p.drawLine(20, 15, 150, 15) pen.setStyle(Qt.DashLine) p.setPen(pen) p.drawLine(20, 35, 150, 35) pen.setStyle(Qt.DotLine) p.setPen(pen) p.drawLine(20, 55, 150, 55) pen.setStyle(Qt.DashDotLine) p.setPen(pen) p.drawLine(20, 75, 150, 75) pen.setStyle(Qt.DashDotDotLine) p.setPen(pen) p.drawLine(20, 95, 150, 95) pen.setStyle(Qt.CustomDashLine) pen.setDashPattern([1, 4, 5, 4]) p.setPen(pen) p.drawLine(20, 115, 150, 115) pen.setWidth(1) pen.setStyle(Qt.SolidLine) p.setPen(pen) brush = QBrush(Qt.SolidPattern) p.setBrush(brush) p.drawRect(180, 10, 40, 30) brush = QBrush(Qt.Dense5Pattern) p.setBrush(brush) p.drawRect(240, 10, 40, 30) brush = QBrush(Qt.Dense7Pattern) p.setBrush(brush) p.drawRect(300, 10, 40, 30) brush = QBrush(Qt.green, Qt.HorPattern) p.setBrush(brush) p.drawRect(180, 50, 40, 30) brush = QBrush(Qt.green, Qt.VerPattern) p.setBrush(brush) p.drawRect(240, 50, 40, 30) brush = QBrush(Qt.green, Qt.Dense6Pattern) brush = QBrush(Qt.green, Qt.CrossPattern) p.setBrush(brush) p.drawRect(300, 50, 40, 30) brush = QBrush(Qt.blue, Qt.BDiagPattern) p.setBrush(brush) p.drawRect(180, 90, 40, 30) brush = QBrush(Qt.blue, Qt.FDiagPattern) p.setBrush(brush) p.drawRect(240, 90, 40, 30) brush = QBrush(Qt.blue, Qt.DiagCrossPattern) p.setBrush(brush) p.drawRect(300, 90, 40, 30) g = QLinearGradient(180, 130, 220, 160) g.setColorAt(0, Qt.red) g.setColorAt(1, Qt.blue) brush = QBrush(g) p.setBrush(brush) p.drawRect(180, 130, 40, 30) g = QRadialGradient(260, 145, 20) g.setColorAt(0, Qt.red) g.setColorAt(0.5, Qt.yellow) g.setColorAt(1, Qt.blue) p.setBrush(g) p.drawRect(240, 130, 40, 30) g = QConicalGradient(320, 145, 0) g.setColorAt(0, Qt.red) g.setColorAt(0.4, Qt.yellow) g.setColorAt(0.8, Qt.blue) g.setColorAt(1, Qt.red) p.setBrush(g) p.drawRect(300, 130, 40, 30) brush = QBrush() brush.setTexture(QPixmap(":appres.img/texture.jpg")) p.setBrush(brush) pen.setColor(Qt.transparent) p.setPen(pen) p.drawRect(15, 130, 135, 35) p.end()
class Example(QWidget): overlay: QImage #Overlay(Накладываем) Picture on Window timer: QTimer #Timet init painter: QPainter arr_points: list DeltaX: int DeltaY: int SelfHeight: int LastAngle: int LastMousePosition: QPoint def __init__(self): super().__init__() self.initUI() def mousePressEvent(self, event): mousePoint = event.pos() self.LastMousePosition = mousePoint if event.button() == 2: WindowW = self.frameGeometry().width()# WindowSize WindowH = self.frameGeometry().height()# WindowSize imgH = self.overlay.height()# Original Picture Size imgW = self.overlay.width()# Original Picture Size img = self.overlay.scaledToHeight(self.SelfHeight, Qt.FastTransformation) #AdjX = (WindowW-img.width())/2 ResultX = imgW * (mousePoint.x() - self.DeltaX) / img.width() ResultY = imgH / 100 * ((mousePoint.y() - self.DeltaY) / (self.SelfHeight / 100)) radius = 10 #eraser = 7 self.painter.drawEllipse(QPoint(ResultX, ResultY), radius, radius) #self.painter.eraseRect(QRect(QPoint(ResultX-radius/2-eraser, ResultY-radius/2-eraser), QPoint(ResultX+radius/2+eraser, ResultY+radius/2+eraser))) self.arr_points.append((ResultX, ResultY)) #print([(round(x[0]), round(x[1])) for x in self.arr_points]) self.update()#Redraw def FileSaving(self, fileName: str): with open(fileName, 'w') as f: for item in self.arr_points: f.write(';'.join(str(x) for x in item) + '\n') f.close() def mouseReleaseEvent(self, event): self.point = None def closeEvent(self, event): self.FileSaving(FILE_NAME) sys.exit() #Programm Closing def initUI(self): self.showMaximized() #self.showNormal() self.arr_points = [] self.LastAngle = 0 self.timer = QTimer() #Timer init self.timer.timeout.connect(self.update)# Timer init self.setWindowTitle('Moscow Metro Map Poppularity')# Title self.point = None self.DeltaX = 0 self.DeltaY = 0 self.SelfHeight = self.frameGeometry().height() self.LastMousePosition = QPoint(0, 0) self.overlay = QImage() self.overlay.load('Moscow Metro Map Stations Popularity\\MainMap.bmp') pen = QPen(QColor(Qt.red)) pen.setWidth(5) self.painter = QPainter(self.overlay) self.painter.setPen(pen) self.painter.Antialiasing = True self.timer.start(1000/50) #50 кадров в секунду def paintEvent(self, event): painter = QPainter() painter.begin(self) #windowsWidth = self.frameGeometry().width() windowsHeight = self.frameGeometry().height() img = self.overlay.scaledToHeight(self.SelfHeight, 0) painter.drawImage(self.DeltaX, self.DeltaY, img) painter.end() del painter def mouseMoveEvent(self, event): CurentPos = event.pos() self.DeltaX -= self.LastMousePosition.x()-CurentPos.x() self.DeltaY -= self.LastMousePosition.y()-CurentPos.y() #self.LastMousePosition = mousePoint self.LastMousePosition = event.pos() def wheelEvent(self, event): #print(str(event.angleDelta())) self.SelfHeight += (event.angleDelta().y()) / 10 self.LastAngle = event.angleDelta().y() def resizeEvent(self, event): self.SelfHeight = self.frameGeometry().height()
def paintShape(self, painter: QPainter): painter.setRenderHint(QPainter.Antialiasing) painter.setPen(self.pen()) painter.setBrush(self.brush()) painter.fillRect(self.rect(), self.brush()) painter.drawRect(self.rect())
def paintEvent(self, e=None): # pylint: disable=invalid-name, unused-argument, missing-function-docstring painter = QPainter(self) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(QColor(133, 45, 145), Qt.Dense5Pattern)) painter.drawRect(self.rect())
def paintEvent(self, event): p = QPainter() p.begin(self) self._normalMap.render(p, event.rect()) p.setPen(Qt.black) p.drawText(self.rect(), Qt.AlignBottom | Qt.TextWordWrap, "Map data CCBYSA 2009 OpenStreetMap.org contributors") p.end() if self.zoomed: dim = min(self.width(), self.height()) magnifierSize = min(MAX_MAGNIFIER, dim * 2 / 3) radius = magnifierSize / 2 ring = radius - 15 box = QSize(magnifierSize, magnifierSize) # reupdate our mask if self.maskPixmap.size() != box: self.maskPixmap = QPixmap(box) self.maskPixmap.fill(Qt.transparent) g = QRadialGradient() g.setCenter(radius, radius) g.setFocalPoint(radius, radius) g.setRadius(radius) g.setColorAt(1.0, QColor(255, 255, 255, 0)) g.setColorAt(0.5, QColor(128, 128, 128, 255)) mask = QPainter(self.maskPixmap) mask.setRenderHint(QPainter.Antialiasing) mask.setCompositionMode(QPainter.CompositionMode_Source) mask.setBrush(g) mask.setPen(Qt.NoPen) mask.drawRect(self.maskPixmap.rect()) mask.setBrush(QColor(Qt.transparent)) mask.drawEllipse(g.center(), ring, ring) mask.end() center = self.dragPos - QPoint(0, radius) center += QPoint(0, radius / 2) corner = center - QPoint(radius, radius) xy = center * 2 - QPoint(radius, radius) # only set the dimension to the magnified portion if self.zoomPixmap.size() != box: self.zoomPixmap = QPixmap(box) self.zoomPixmap.fill(Qt.lightGray) if True: p = QPainter(self.zoomPixmap) p.translate(-xy) self._largeMap.render(p, QRect(xy, box)) p.end() clipPath = QPainterPath() clipPath.addEllipse(QPointF(center), ring, ring) p = QPainter(self) p.setRenderHint(QPainter.Antialiasing) p.setClipPath(clipPath) p.drawPixmap(corner, self.zoomPixmap) p.setClipping(False) p.drawPixmap(corner, self.maskPixmap) p.setPen(Qt.gray) p.drawPath(clipPath) if self.invert: p = QPainter(self) p.setCompositionMode(QPainter.CompositionMode_Difference) p.fillRect(event.rect(), Qt.white) p.end()
class Menu(QMainWindow): def __init__(self): super().__init__() self.colors = COLORS self.qp = QPainter() self.init_game() self.size2handler = {} self.previous_size = "small" self.setMouseTracking(True) self.setFixedSize(800, 600) self.setWindowTitle('Cubes') self.setWindowIcon(QIcon('icons/cube.png')) self.menu = self.menuBar() self.statusBar() self.file = self.menu.addMenu('&File') self.settings = self.menu.addMenu('&Settings') self.exit = QAction('Exit', self) self.table_of_records = QAction('Table of records', self) self.table_of_records.setStatusTip('Show table of records') self.exit.setShortcut('Ctrl+Q') self.exit.setStatusTip('Exit application') self.file.addAction(self.table_of_records) self.file.addAction(self.exit) self.init_settings() self.exit.triggered.connect(self.close) self.table_of_records.triggered.connect(self.show_table_of_records) def init_settings(self): self.sizes = QActionGroup(self) self.small = QAction('Small', self, checkable=True) self.small.setChecked(True) self.small.triggered.connect(lambda: self.set_size('small')) self.sizes.addAction(self.small) self.settings.addAction(self.small) self.size2handler['small'] = self.small self.middle1 = QAction('Middle 1', self, checkable=True) self.middle1.triggered.connect(lambda: self.set_size('middle1')) self.sizes.addAction(self.middle1) self.settings.addAction(self.middle1) self.size2handler['middle1'] = self.middle1 self.middle2 = QAction('Middle 2', self, checkable=True) self.middle2.triggered.connect(lambda: self.set_size('middle2')) self.sizes.addAction(self.middle2) self.settings.addAction(self.middle2) self.size2handler['middle2'] = self.middle2 self.big = QAction('Big', self, checkable=True) self.big.triggered.connect(lambda: self.set_size('big')) self.sizes.addAction(self.big) self.settings.addAction(self.big) self.size2handler['big'] = self.big self.small.setStatusTip('A small field. Has 10x10 size and 4 colors') self.middle1.setStatusTip('A middle field. ' 'Has 14x14 size and 5 colors') self.middle2.setStatusTip('A middle field. ' 'Has 14x14 size and 6 colors') self.big.setStatusTip('A big field. Has 25x25 size and 7 colors') def set_size(self, size): if self.game.total_score != 0: if not self.game.exit(): if self.previous_size != size: self.size2handler[self.previous_size].setChecked(True) self.size2handler[size].setChecked(False) return self.size2handler[size].setChecked(True) self.init_game(size) self.previous_size = size def closeEvent(self, event): self.game.exit() event.accept() def init_game(self, size='small'): self.game = Game(self.colors, size) self.setCentralWidget(self.game) def show_table_of_records(self): w = QWidget(self, Qt.Window) w.setWindowModality(Qt.WindowModal) w.setFixedSize(300, 200) w.setWindowTitle('Table of records') w.setWindowIcon(QIcon('icons/trophy.png')) w.move(self.geometry().center() - w.rect().center() - QPoint(0, 30)) table = QTableWidget(self) vbox = QVBoxLayout() table.setColumnCount(4) table.setRowCount(10) sizes = ["small", "middle1", "middle2", "big"] table.setHorizontalHeaderLabels(sizes) with open('texts/best_results.txt') as f: best_results = eval(f.read()) for size in best_results: for item in best_results[size]: row = best_results[size].index(item) column = sizes.index(size) item = item[0], str(item[1]) table.setItem(row, column, QTableWidgetItem(', '.join(item))) vbox.addWidget(table) vbox.addStretch(1) w.setLayout(vbox) w.show() def paintEvent(self, QPaintEvent): self.qp.begin(self) self.draw_rectangles(QPaintEvent) self.drawText(QPaintEvent) self.qp.end() def drawText(self, QPaintEvent): x, y = self.game.width * 22 + 10, 40 self.qp.setPen(QColor(0, 0, 0)) self.qp.setFont(QFont('fonts/ARCADE.ttf', 15)) self.qp.drawText(x, y, "Score: {}".format(self.game.total_score)) self.qp.setFont(QFont('fonts/ARCADE.ttf', 10)) for i in self.game.information_about_colors: y = y + 25 self.qp.drawText(x, y, i) def mousePressEvent(self, event): if event.buttons() == Qt.LeftButton: pos = event.pos().x(), event.pos().y() for (x, y) in self.game.object.blocks2coordinates: if x * 22 < pos[0] < 23 + x * 22 and \ y * 22 < pos[1] < y * 22 + 23: score, color, is_exit = self.game.object.remove((x, y)) self.game.information_about_colors = \ self.game.set_information_about_colors(color, score) self.game.update_score(score) if is_exit: self.game.exit() self.update() def draw_rectangles(self, QPaintEvent): for (x, y) in self.game.object.blocks2coordinates: color = self.game.object.blocks2coordinates[(x, y)][0].color self.qp.setPen(QColor(color[0], color[1], color[2])) self.qp.setBrush(QColor(color[0], color[1], color[2])) self.qp.drawRect(x * 22, y * 22, 20, 20)
def paintEvent(self, _event: QPaintEvent): if not self.crop or not self.resolution: return painter = QPainter(self) # Keep a backup of the transform and create a new one transform = painter.worldTransform() # Set scaling transform transform = transform.scale(self.width() / self.resolution.width(), self.height() / self.resolution.height()) # Compute the transform to flip the coordinate system on the x axis transform_flip = QTransform() if self.flip_x: transform_flip = transform_flip.translate(self.resolution.width(), 0.0) transform_flip = transform_flip.scale(-1.0, 1.0) # Small helper for tuple to QPoint def toqp(point): return QPoint(point[0], point[1]) # Starting from here we care about AA painter.setRenderHint(QPainter.Antialiasing) # Draw the QR code finder overlay painter.setWorldTransform(transform_flip * transform, False) painter.setOpacity(self.QR_FINDER_OPACITY) qr_finder_size = self.crop.size() * self.QR_FINDER_SIZE tmp = (self.crop.size() - qr_finder_size) / 2 qr_finder_pos = QPoint(tmp.width(), tmp.height()) + self.crop.topLeft() qr_finder_rect = QRect(qr_finder_pos, qr_finder_size) self.qr_finder.render(painter, QRectF(qr_finder_rect)) painter.setOpacity(1.0) # Draw all the QR code results for res in self.results: painter.setWorldTransform(transform_flip * transform, False) # Draw lines between all of the QR code points pen = QPen(self.qr_outline_pen) if res in self.validator_results.result_colors: pen.setColor(self.validator_results.result_colors[res]) painter.setPen(pen) num_points = len(res.points) for i in range(0, num_points): i_n = i + 1 line_from = toqp(res.points[i]) line_from += self.crop.topLeft() line_to = toqp( res.points[i_n] if i_n < num_points else res.points[0]) line_to += self.crop.topLeft() painter.drawLine(line_from, line_to) # Draw the QR code data # Note that we reset the world transform to only the scaled transform # because otherwise the text could be flipped. We only use transform_flip # to map the center point of the result. painter.setWorldTransform(transform, False) font_metrics = painter.fontMetrics() data_metrics = QSize(font_metrics.horizontalAdvance(res.data), font_metrics.capHeight()) center_pos = toqp(res.center) center_pos += self.crop.topLeft() center_pos = transform_flip.map(center_pos) text_offset = QPoint(data_metrics.width(), data_metrics.height()) text_offset = text_offset / 2 text_offset.setX(-text_offset.x()) center_pos += text_offset padding = self.BG_RECT_PADDING bg_rect_pos = center_pos - QPoint(padding, data_metrics.height() + padding) bg_rect_size = data_metrics + (QSize(padding, padding) * 2) bg_rect = QRect(bg_rect_pos, bg_rect_size) bg_rect_path = QPainterPath() radius = self.BG_RECT_CORNER_RADIUS bg_rect_path.addRoundedRect(QRectF(bg_rect), radius, radius, Qt.AbsoluteSize) painter.setPen(self.bg_rect_pen) painter.fillPath(bg_rect_path, self.bg_rect_fill) painter.drawPath(bg_rect_path) painter.setPen(self.text_pen) painter.drawText(center_pos, res.data)
class Ui_MainWindow(QWidget): def __init__(self, parent=None): super(Ui_MainWindow, self).__init__(parent) self.setMouseTracking(True) self.setWindowTitle("Second Test") self.lastPoint = QPoint() self.endPoint = QPoint() # 存储b-box坐标信息 self.bbox_list = [] # 辅助画布 self.pp = QPainter() self.paint_frame = None self.tempPix = QPixmap(800, 600) self.tempPix.fill(Qt.white) self.shape = None self.rectList = [] self.perm = False # 是否处于绘制阶段 self.isPainting = False # 是否处于初始化阶段 self.first_frame = False # 目前状态 Suspending|Location|Video|Camera = 0|1|2|3 self.isStatus = 0 self.setupUi() def setupUi(self): self.setObjectName("MainWindow") self.resize(1350, 725) self.centralwidget = QtWidgets.QWidget(self) self.centralwidget.setObjectName("centralwidget") self.label_image = QtWidgets.QLabel(self.centralwidget) self.label_image.setGeometry(QtCore.QRect(0, 0, 800, 600)) self.label_image.setObjectName("label_3") self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget) self.verticalLayoutWidget.setGeometry(QtCore.QRect(825, 25, 500, 700)) self.verticalLayoutWidget.setObjectName("verticalLayoutWidget") self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName("verticalLayout") self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.pushButton_locationLoading = QtWidgets.QPushButton( self.verticalLayoutWidget) self.pushButton_locationLoading.setObjectName( "pushButton_locationLoading") self.horizontalLayout.addWidget(self.pushButton_locationLoading) self.pushButton_videoLoading = QtWidgets.QPushButton( self.verticalLayoutWidget) self.pushButton_videoLoading.setObjectName("pushButton_videoLoading") self.horizontalLayout.addWidget(self.pushButton_videoLoading) self.verticalLayout.addLayout(self.horizontalLayout) self.pushButton_cameraLoading = QtWidgets.QPushButton( self.verticalLayoutWidget) self.pushButton_cameraLoading.setObjectName("pushButton_cameraLoading") self.verticalLayout.addWidget(self.pushButton_cameraLoading) self.pushButton_bboxSetting = QtWidgets.QPushButton( self.verticalLayoutWidget) self.pushButton_bboxSetting.setObjectName("pushButton_bboxSetting") self.verticalLayout.addWidget(self.pushButton_bboxSetting) self.pushButton_algorithmProcessing = QtWidgets.QPushButton( self.verticalLayoutWidget) self.pushButton_algorithmProcessing.setObjectName( "pushButton_algorithmProcessing") self.verticalLayout.addWidget(self.pushButton_algorithmProcessing) self.checkBox = QtWidgets.QCheckBox(self.verticalLayoutWidget) self.checkBox.setObjectName("checkBox") self.verticalLayout.addWidget(self.checkBox) self.horizontalLayout_select = QtWidgets.QHBoxLayout() self.horizontalLayout_select.setObjectName("horizontalLayout_select") self.spinBox = QtWidgets.QSpinBox(self.verticalLayoutWidget) self.spinBox.setObjectName("spinBox") self.horizontalLayout_select.addWidget(self.spinBox) self.label_spinBox = QtWidgets.QLabel(self.verticalLayoutWidget) self.label_spinBox.setMaximumSize(10000, 45) self.label_spinBox.setText('Analysis Object Selecting') self.horizontalLayout_select.addWidget(self.label_spinBox) self.horizontalLayout_select.setStretch(1, 1) self.horizontalLayout_select.setStretch(2, 5) self.verticalLayout.addLayout(self.horizontalLayout_select) self.label_bbox = QtWidgets.QLabel(self.verticalLayoutWidget) self.label_bbox.setAlignment(Qt.AlignCenter) self.label_bbox.setWordWrap(True) self.verticalLayout.addWidget(self.label_bbox) self.label_source = QtWidgets.QLabel(self.verticalLayoutWidget) self.label_source.setAlignment(Qt.AlignCenter) self.label_source.setWordWrap(True) self.verticalLayout.addWidget(self.label_source) self.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(self) self.menubar.setGeometry(QtCore.QRect(0, 0, 826, 20)) self.menubar.setObjectName("menubar") self.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(self) self.statusbar.setObjectName("statusbar") self.setStatusBar(self.statusbar) self.retranslateUi(self) QtCore.QMetaObject.connectSlotsByName(self) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "SiamBOMB")) self.pushButton_locationLoading.setText( _translate("MainWindow", "&Location Loading")) self.pushButton_locationLoading.setDefault(True) self.pushButton_videoLoading.setText( _translate("MainWindow", "&Video Loading")) self.pushButton_videoLoading.setDefault(True) self.pushButton_cameraLoading.setText( _translate("MainWindow", "&Camera Loading")) self.pushButton_cameraLoading.setDefault(True) self.pushButton_bboxSetting.setText( _translate("MainWindow", "&B-box Setting")) self.pushButton_bboxSetting.setDefault(True) self.pushButton_algorithmProcessing.setText( _translate("MainWindow", "&Algorithm Processing")) self.pushButton_algorithmProcessing.setDefault(True) self.checkBox.setText(_translate("MainWindow", "&Data Saving")) def paintEvent(self, event): if self.isPainting and self.perm: self.pp.begin(self.tempPix) pen = QPen(Qt.green, 6, Qt.SolidLine) self.pp.setPen(pen) for shape in self.rectList: shape.paint(self.pp) self.pp.end() label_text = '' for item in self.bbox_list: label_text += '\n' + str(item) self.label_bbox.setText(label_text) self.label_image.setPixmap(self.tempPix) def mousePressEvent(self, event): if self.isPainting: if event.button() == Qt.LeftButton: self.shape = Rect() if self.shape is not None: self.perm = False self.rectList.append(self.shape) self.shape.setStart(event.pos()) self.shape.setEnd(event.pos()) self.update() def mouseReleaseEvent(self, event): if self.isPainting: if event.button() == Qt.LeftButton: self.bbox_list.append( (self.shape.startPoint().x(), self.shape.startPoint().y(), self.shape.endPoint().x() - self.shape.startPoint().x(), self.shape.endPoint().y() - self.shape.startPoint().y())) self.perm = True self.shape = None self.update() def mouseMoveEvent(self, event): if self.isPainting: self.endPoint = event.pos() if event.buttons() & Qt.LeftButton: if self.shape is not None and not self.perm: self.shape.setEnd(event.pos()) self.update()
def change_color(self): p = QPainter(self.pixmap) p.setPen(QColor(0, 0, 255)) p.drawPixmap(self.pixmap.rect(), self.mask, self.mask.rect()) p.end()
def drawValues(self, qp: QtGui.QPainter): if len(self.data) == 0 and len(self.reference) == 0: return pen = QtGui.QPen(self.sweepColor) pen.setWidth(self.pointSize) line_pen = QtGui.QPen(self.sweepColor) line_pen.setWidth(self.lineThickness) highlighter = QtGui.QPen(QtGui.QColor(20, 0, 255)) highlighter.setWidth(1) qp.setPen(pen) for i in range(len(self.data)): x = self.getXPosition(self.data[i]) y = self.height() / 2 + self.data[i].im * -1 * self.chartHeight / 2 qp.drawPoint(int(x), int(y)) if self.drawLines and i > 0: prevx = self.getXPosition(self.data[i - 1]) prevy = self.height() / 2 + self.data[ i - 1].im * -1 * self.chartHeight / 2 qp.setPen(line_pen) qp.drawLine(x, y, prevx, prevy) qp.setPen(pen) pen.setColor(self.referenceColor) line_pen.setColor(self.referenceColor) qp.setPen(pen) if len(self.data) > 0: fstart = self.data[0].freq fstop = self.data[len(self.data) - 1].freq else: fstart = self.reference[0].freq fstop = self.reference[len(self.reference) - 1].freq for i in range(len(self.reference)): data = self.reference[i] if data.freq < fstart or data.freq > fstop: continue x = self.getXPosition(self.reference[i]) y = self.height() / 2 + data.im * -1 * self.chartHeight / 2 qp.drawPoint(int(x), int(y)) if self.drawLines and i > 0: prevx = self.getXPosition(self.reference[i - 1]) prevy = self.height() / 2 + self.reference[ i - 1].im * -1 * self.chartHeight / 2 qp.setPen(line_pen) qp.drawLine(x, y, prevx, prevy) qp.setPen(pen) # Now draw the markers for m in self.markers: if m.location != -1 and m.location < len(self.data): x = self.getXPosition(self.data[m.location]) y = self.height() / 2 + self.data[ m.location].im * -1 * self.chartHeight / 2 self.drawMarker(x, y, qp, m.color, self.markers.index(m) + 1)
def paintEvent(self, event): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) for index in range(self._stick_count): if self.item_index >= index +1: painter.setPen(self.active_color) painter.setBrush(self.active_color) painter.drawRect(56+(index*100), 24, 76, 6) else: painter.setPen(self.passive_color) painter.setBrush(self.passive_color) painter.drawRect(56+(index*100), 24, 76, 6) for index in range(self._item_count): if self.item_index >= index: painter.setPen(self.active_color) painter.setBrush(self.active_color) painter.drawEllipse(32 + (index * 100), 16, 24, 24) painter.setPen(Qt.black) painter.drawText(32 + (index * 100), 16, 24, 84, Qt.AlignCenter | Qt.TextWordWrap | Qt.TextDontClip, self.parent.widget(index).windowTitle()) else: painter.setPen(self.passive_color) painter.setBrush(self.passive_color) painter.drawEllipse(32+(index*100), 16, 24, 24) painter.setPen(Qt.black) painter.drawText(32+(index*100), 16, 24, 84, Qt.AlignCenter | Qt.TextWordWrap | Qt.TextDontClip, self.parent.widget(index).windowTitle())
def paintEvent(self, e): try: plan = self.plan segment = self.plan.beams[self.bi][self.si] except: print("Tried to paint a plan, but no plan was loaded.") return attr = "second" if self.be == 0: attr = "first" w = self.width() #/800 h = self.height() #/800 # print(w,h) qp = QPainter() qp.begin(self) pen = QPen(Qt.black, 1, Qt.SolidLine) h400 = h / 2 # TEST w400 = w / 2 # TEST vert_zoom = w400 / 400. * 20 hor_zoom = h400 / 400. * 20 leafedges = np.linspace(0, h, plan.accelerator.leafs_per_bank + 1) if segment.collimator.mlc.orientation.value == -1: pen.setStyle(Qt.DashLine) else: pen.setStyle(Qt.SolidLine) for l in range(plan.accelerator.leafs_per_bank): bound1 = leafedges[l] bound2 = leafedges[l + 1] #left coord = vert_zoom * getattr(segment.collimator.mlc.leftLeaves[l], attr) pen.setColor(Qt.green) qp.setPen(pen) qp.drawLine(w400 + coord, bound1, w400 + coord, bound2) qp.drawLine( w400 + coord - 50, bound1, w400 + coord, bound1, ) qp.drawLine(w400 + coord - 50, bound2, w400 + coord, bound2) #right coord = vert_zoom * getattr(segment.collimator.mlc.rightLeaves[l], attr) pen.setColor(Qt.blue) qp.setPen(pen) qp.drawLine(w400 + coord, bound1, w400 + coord, bound2) qp.drawLine(w400 + coord + 50, bound1, w400 + coord, bound1) qp.drawLine(w400 + coord + 50, bound2, w400 + coord, bound2) #jaws if segment.collimator.parallelJaw.orientation.value == -1: pen.setStyle(Qt.DashLine) else: pen.setStyle(Qt.SolidLine) # if segment.collimator.parallelJaw.orientation.value is not -1: l, r = vert_zoom * getattr(segment.collimator.parallelJaw.j1, attr), vert_zoom * getattr( segment.collimator.parallelJaw.j2, attr) pen.setColor(Qt.green) pen.setWidth(2) qp.setPen(pen) qp.drawLine(w400 + l, 0, w400 + l, h) pen.setColor(Qt.blue) qp.setPen(pen) qp.drawLine(w400 + r, 0, w400 + r, h) if segment.collimator.perpendicularJaw.orientation.value == -1: pen.setStyle(Qt.DashLine) else: pen.setStyle(Qt.SolidLine) # if segment.collimator.perpendicularJaw.orientation.value is not -1: t, b = hor_zoom * getattr( segment.collimator.perpendicularJaw.j1, attr), hor_zoom * getattr( segment.collimator.perpendicularJaw.j2, attr) pen.setColor(Qt.cyan) qp.setPen(pen) qp.drawLine(0, h400 + t, w, h400 + t) pen.setColor(Qt.magenta) qp.setPen(pen) qp.drawLine(0, h400 + b, w, h400 + b) # fieldsize x1, x2 = vert_zoom * segment.beamInfo.fieldMin.first, vert_zoom * segment.beamInfo.fieldMax.first y1, y2 = hor_zoom * segment.beamInfo.fieldMin.second, hor_zoom * segment.beamInfo.fieldMax.second pen.setColor(Qt.red) qp.setPen(pen) qp.drawLine(w400 + x1, h400 + y1, w400 + x1, h400 + y2) qp.drawLine(w400 + x1, h400 + y1, w400 + x2, h400 + y1) qp.drawLine(w400 + x1, h400 + y2, w400 + x2, h400 + y2) qp.drawLine(w400 + x2, h400 + y1, w400 + x2, h400 + y2) pen.setColor(Qt.black) qp.setPen(pen) qp.drawText(10, 10, "viewport: 40cm x 40cm") qp.drawText( 10, 25, f"isoCenter: {str(self.plan.beams[self.bi][0].beamInfo.isoCenter.x)[:5]},{str(self.plan.beams[self.bi][0].beamInfo.isoCenter.y)[:5]},{str(self.plan.beams[self.bi][0].beamInfo.isoCenter.z)[:5]}" ) qp.drawText(10, 40, f"weight: {str(segment.beamInfo.relativeWeight)}") qp.drawText( 10, 55, f"gantryAngle: {str(getattr(segment.beamInfo.gantryAngle,attr))}") qp.drawText( 10, 70, f"collimatorAngle: {str(getattr(self.plan.beams[self.bi][0].beamInfo.collimatorAngle,attr))}" ) qp.drawText( 10, 85, f"couchAngle: {str(getattr(self.plan.beams[self.bi][0].beamInfo.couchAngle,attr))}" ) qp.end()
def paintEvent(self, event): page_bottom = self.edit.viewport().height() font_metrics = QFontMetrics(self.edit.document().defaultFont()) current_block = self.edit.document().findBlock( self.edit.textCursor().position()) pattern = self.pat if self.edit.lang == "python" else self.patNotPython painter = QPainter(self) background = resources.CUSTOM_SCHEME.get( 'sidebar-background', resources.COLOR_SCHEME['sidebar-background']) foreground = resources.CUSTOM_SCHEME.get( 'sidebar-foreground', resources.COLOR_SCHEME['sidebar-foreground']) background_selected = resources.CUSTOM_SCHEME.get( 'sidebar-selected-background', resources.COLOR_SCHEME['sidebar-selected-background']) foreground_selected = resources.CUSTOM_SCHEME.get( 'sidebar-selected-foreground', resources.COLOR_SCHEME['sidebar-selected-foreground']) painter.fillRect(self.rect(), QColor(background)) block = self.edit.firstVisibleBlock() viewport_offset = self.edit.contentOffset() line_count = block.blockNumber() painter.setFont(self.edit.document().defaultFont()) xofs = self.width() - self.foldArea painter.fillRect(xofs, 0, self.foldArea, self.height(), QColor(resources.CUSTOM_SCHEME.get('fold-area', resources.COLOR_SCHEME['fold-area']))) while block.isValid(): line_count += 1 # The top left position of the block in the document position = self.edit.blockBoundingGeometry(block).topLeft() + \ viewport_offset # Check if the position of the block is outside of the visible area if position.y() > page_bottom: break # Set the Painter Pen depending on special lines painter.setPen(QColor(foreground)) error = False checkers = self._neditable.sorted_checkers for items in checkers: checker, color, _ = items if (line_count - 1) in checker.checks: painter.setPen(QColor(color)) font = painter.font() font.setItalic(True) font.setUnderline(True) painter.setFont(font) error = True break # We want the line number for the selected line to be bold. bold = False if block == current_block: painter.fillRect( 0, round(position.y()) + font_metrics.descent(), self.width(), font_metrics.ascent() + font_metrics.descent(), QColor(background_selected)) bold = True font = painter.font() font.setBold(True) if not error: painter.setPen(QColor(foreground_selected)) painter.setFont(font) # Draw the line number right justified at the y position of the # line. 3 is a magic padding number. drawText(x, y, text). if block.isVisible(): painter.drawText( self.width() - self.foldArea - font_metrics.width(str(line_count)) - 3, round(position.y()) + font_metrics.ascent() + font_metrics.descent() - 1, str(line_count)) # Remove the bold style if it was set previously. if bold: font = painter.font() font.setBold(False) painter.setFont(font) if error: font = painter.font() font.setItalic(False) font.setUnderline(False) painter.setFont(font) block = block.next() self.highest_line = line_count #Code Folding if self.foldArea != self.rightArrowIcon.width(): polygon = QPolygonF() self.rightArrowIcon = QPixmap(self.foldArea, self.foldArea) self.rightArrowIcon.fill(Qt.transparent) self.downArrowIcon = QPixmap(self.foldArea, self.foldArea) self.downArrowIcon.fill(Qt.transparent) polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.25)) polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.75)) polygon.append(QPointF(self.foldArea * 0.8, self.foldArea * 0.5)) iconPainter = QPainter(self.rightArrowIcon) iconPainter.setRenderHint(QPainter.Antialiasing) iconPainter.setPen(Qt.NoPen) iconPainter.setBrush(QColor( resources.CUSTOM_SCHEME.get( 'fold-arrow', resources.COLOR_SCHEME['fold-arrow']))) iconPainter.drawPolygon(polygon) polygon.clear() polygon.append(QPointF(self.foldArea * 0.25, self.foldArea * 0.4)) polygon.append(QPointF(self.foldArea * 0.75, self.foldArea * 0.4)) polygon.append(QPointF(self.foldArea * 0.5, self.foldArea * 0.8)) iconPainter = QPainter(self.downArrowIcon) iconPainter.setRenderHint(QPainter.Antialiasing) iconPainter.setPen(Qt.NoPen) iconPainter.setBrush(QColor( resources.CUSTOM_SCHEME.get( 'fold-arrow', resources.COLOR_SCHEME['fold-arrow']))) iconPainter.drawPolygon(polygon) self.calculate_docstring_block_fold() block = self.edit.firstVisibleBlock() while block.isValid(): position = self.edit.blockBoundingGeometry( block).topLeft() + viewport_offset #Check if the position of the block is outside of the visible area if position.y() > page_bottom: break if pattern.match(block.text()) and block.isVisible(): can_fold = True if self.patComment.match(block.text()) and \ (block.blockNumber() in self._endDocstringBlocks): can_fold = False if can_fold: if block.blockNumber() in self.foldedBlocks: painter.drawPixmap(xofs, round(position.y()), self.rightArrowIcon) else: painter.drawPixmap(xofs, round(position.y()), self.downArrowIcon) #Add Bookmarks and Breakpoint if block.blockNumber() in self.breakpoints: linear_gradient = QLinearGradient( xofs, round(position.y()), xofs + self.foldArea, round(position.y()) + self.foldArea) linear_gradient.setColorAt(0, QColor(255, 11, 11)) linear_gradient.setColorAt(1, QColor(147, 9, 9)) painter.setRenderHints(QPainter.Antialiasing, True) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(linear_gradient)) painter.drawEllipse( xofs + 1, round(position.y()) + 6, self.foldArea - 1, self.foldArea - 1) elif block.blockNumber() in self.bookmarks: linear_gradient = QLinearGradient( xofs, round(position.y()), xofs + self.foldArea, round(position.y()) + self.foldArea) linear_gradient.setColorAt(0, QColor(13, 62, 243)) linear_gradient.setColorAt(1, QColor(5, 27, 106)) painter.setRenderHints(QPainter.Antialiasing, True) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(linear_gradient)) painter.drawRoundedRect( xofs + 1, round(position.y()) + 6, self.foldArea - 2, self.foldArea - 1, 3, 3) block = block.next() painter.end() super(SidebarWidget, self).paintEvent(event)
def draw_primary(self, painter: QPainter) -> None: painter.setPen(self.pen.primary) painter.drawLine(self.primary.line) self.draw_secondary(painter)
def drawValues(self, qp: QtGui.QPainter): if len(self.data) == 0 and len(self.reference) == 0: return pen = QtGui.QPen(Chart.color.sweep) pen.setWidth(self.dim.point) line_pen = QtGui.QPen(Chart.color.sweep) line_pen.setWidth(self.dim.line) self._set_start_stop() # Draw bands if required if self.bands.enabled: self.drawBands(qp, self.fstart, self.fstop) # Find scaling if self.fixedValues: min_val = self.minDisplayValue max_val = self.maxDisplayValue else: min_val = 1000 max_val = -1000 for d in self.data: imp = d.impedance() re, im = imp.real, imp.imag re = re * 10e6 / d.freq im = im * 10e6 / d.freq if re > max_val: max_val = re if re < min_val: min_val = re if im > max_val: max_val = im if im < min_val: min_val = im for d in self.reference: # Also check min/max for the reference sweep if d.freq < self.fstart or d.freq > self.fstop: continue imp = d.impedance() re, im = imp.real, imp.imag re = re * 10e6 / d.freq im = im * 10e6 / d.freq if re > max_val: max_val = re if re < min_val: min_val = re if im > max_val: max_val = im if im < min_val: min_val = im if self.logarithmicY: min_val = max(0.01, min_val) self.max = max_val span = max_val - min_val if span == 0: span = 0.01 self.span = span # We want one horizontal tick per 50 pixels, at most horizontal_ticks = math.floor(self.dim.height / 50) fmt = Format(max_nr_digits=4) for i in range(horizontal_ticks): y = self.topMargin + round(i * self.dim.height / horizontal_ticks) qp.setPen(QtGui.QPen(Chart.color.foreground)) qp.drawLine(self.leftMargin - 5, y, self.leftMargin + self.dim.width + 5, y) qp.setPen(QtGui.QPen(Chart.color.text)) val = Value(self.valueAtPosition(y)[0], fmt=fmt) qp.drawText(3, y + 4, str(val)) qp.drawText(3, self.dim.height + self.topMargin, str(Value(min_val, fmt=fmt))) self.drawFrequencyTicks(qp) primary_pen = pen secondary_pen = QtGui.QPen(Chart.color.sweep_secondary) if len(self.data) > 0: c = QtGui.QColor(Chart.color.sweep) c.setAlpha(255) pen = QtGui.QPen(c) pen.setWidth(2) qp.setPen(pen) qp.drawLine(20, 9, 25, 9) c = QtGui.QColor(Chart.color.sweep_secondary) c.setAlpha(255) pen.setColor(c) qp.setPen(pen) qp.drawLine(self.leftMargin + self.dim.width, 9, self.leftMargin + self.dim.width + 5, 9) primary_pen.setWidth(self.dim.point) secondary_pen.setWidth(self.dim.point) line_pen.setWidth(self.dim.line) for i in range(len(self.data)): x = self.getXPosition(self.data[i]) y_re = self.getReYPosition(self.data[i]) y_im = self.getImYPosition(self.data[i]) qp.setPen(primary_pen) if self.isPlotable(x, y_re): qp.drawPoint(x, y_re) qp.setPen(secondary_pen) if self.isPlotable(x, y_im): qp.drawPoint(x, y_im) if self.flag.draw_lines and i > 0: prev_x = self.getXPosition(self.data[i - 1]) prev_y_re = self.getReYPosition(self.data[i - 1]) prev_y_im = self.getImYPosition(self.data[i - 1]) # Real part first line_pen.setColor(Chart.color.sweep) qp.setPen(line_pen) if self.isPlotable(x, y_re) and self.isPlotable( prev_x, prev_y_re): qp.drawLine(x, y_re, prev_x, prev_y_re) elif self.isPlotable( x, y_re) and not self.isPlotable(prev_x, prev_y_re): new_x, new_y = self.getPlotable(x, y_re, prev_x, prev_y_re) qp.drawLine(x, y_re, new_x, new_y) elif not self.isPlotable(x, y_re) and self.isPlotable( prev_x, prev_y_re): new_x, new_y = self.getPlotable(prev_x, prev_y_re, x, y_re) qp.drawLine(prev_x, prev_y_re, new_x, new_y) # Imag part second line_pen.setColor(Chart.color.sweep_secondary) qp.setPen(line_pen) if self.isPlotable(x, y_im) and self.isPlotable( prev_x, prev_y_im): qp.drawLine(x, y_im, prev_x, prev_y_im) elif self.isPlotable( x, y_im) and not self.isPlotable(prev_x, prev_y_im): new_x, new_y = self.getPlotable(x, y_im, prev_x, prev_y_im) qp.drawLine(x, y_im, new_x, new_y) elif not self.isPlotable(x, y_im) and self.isPlotable( prev_x, prev_y_im): new_x, new_y = self.getPlotable(prev_x, prev_y_im, x, y_im) qp.drawLine(prev_x, prev_y_im, new_x, new_y) primary_pen.setColor(Chart.color.reference) line_pen.setColor(Chart.color.reference) secondary_pen.setColor(Chart.color.reference_secondary) qp.setPen(primary_pen) if len(self.reference) > 0: c = QtGui.QColor(Chart.color.reference) c.setAlpha(255) pen = QtGui.QPen(c) pen.setWidth(2) qp.setPen(pen) qp.drawLine(20, 14, 25, 14) c = QtGui.QColor(Chart.color.reference_secondary) c.setAlpha(255) pen = QtGui.QPen(c) pen.setWidth(2) qp.setPen(pen) qp.drawLine(self.leftMargin + self.dim.width, 14, self.leftMargin + self.dim.width + 5, 14) for i in range(len(self.reference)): if self.reference[i].freq < self.fstart or self.reference[ i].freq > self.fstop: continue x = self.getXPosition(self.reference[i]) y_re = self.getReYPosition(self.reference[i]) y_im = self.getImYPosition(self.reference[i]) qp.setPen(primary_pen) if self.isPlotable(x, y_re): qp.drawPoint(x, y_re) qp.setPen(secondary_pen) if self.isPlotable(x, y_im): qp.drawPoint(x, y_im) if self.flag.draw_lines and i > 0: prev_x = self.getXPosition(self.reference[i - 1]) prev_y_re = self.getReYPosition(self.reference[i - 1]) prev_y_im = self.getImYPosition(self.reference[i - 1]) line_pen.setColor(Chart.color.reference) qp.setPen(line_pen) # Real part first if self.isPlotable(x, y_re) and self.isPlotable( prev_x, prev_y_re): qp.drawLine(x, y_re, prev_x, prev_y_re) elif self.isPlotable( x, y_re) and not self.isPlotable(prev_x, prev_y_re): new_x, new_y = self.getPlotable(x, y_re, prev_x, prev_y_re) qp.drawLine(x, y_re, new_x, new_y) elif not self.isPlotable(x, y_re) and self.isPlotable( prev_x, prev_y_re): new_x, new_y = self.getPlotable(prev_x, prev_y_re, x, y_re) qp.drawLine(prev_x, prev_y_re, new_x, new_y) line_pen.setColor(Chart.color.reference_secondary) qp.setPen(line_pen) # Imag part second if self.isPlotable(x, y_im) and self.isPlotable( prev_x, prev_y_im): qp.drawLine(x, y_im, prev_x, prev_y_im) elif self.isPlotable( x, y_im) and not self.isPlotable(prev_x, prev_y_im): new_x, new_y = self.getPlotable(x, y_im, prev_x, prev_y_im) qp.drawLine(x, y_im, new_x, new_y) elif not self.isPlotable(x, y_im) and self.isPlotable( prev_x, prev_y_im): new_x, new_y = self.getPlotable(prev_x, prev_y_im, x, y_im) qp.drawLine(prev_x, prev_y_im, new_x, new_y) # Now draw the markers for m in self.markers: if m.location != -1: x = self.getXPosition(self.data[m.location]) y_re = self.getReYPosition(self.data[m.location]) y_im = self.getImYPosition(self.data[m.location]) self.drawMarker(x, y_re, qp, m.color, self.markers.index(m) + 1) self.drawMarker(x, y_im, qp, m.color, self.markers.index(m) + 1)
def paintEvent(self, event): painter = QPainter(self) painter.setPen(self.pen) painter.setBrush(self.brush) if self.antialiased: painter.setRenderHint(QPainter.Antialiasing) angle_step = 360 / self.n_states painter.save() #Save_1. Save the state of the system (push matrix) painter.translate( self.dist_center.x(), self.dist_center.y()) # go to the center of the render area painter.rotate( -180 ) #to start painting from the left side of the circle (clockwise) #center of the circumference where through we are going to paint our states x = self.dist_radius * math.cos(0) y = self.dist_radius * math.sin(0) for h in range(self.n_states): rot = angle_step * h # each state is equidistant from the others. We paint them in circles painter.save() #Save_2 painter.rotate( rot) #now our system is pointing to the next state to be drawn painter.translate( x, y ) #now our origin is in the center of the next state to be drawn #if the state is active, fill it green if self.machine.getState(h).isActive(): painter.setBrush(self.greenGradientBrush) painter.drawEllipse(QPoint(0, 0), self.state_radius, self.state_radius) #draw the new state #global position of transformed coordinates (before any transformation, origin at top-left corner) gx = painter.worldTransform().map(QPoint(0, 0)).x() gy = painter.worldTransform().map(QPoint(0, 0)).y() self.machine.getState(h).setPos( gx, gy ) #store the center of the state without any transformation applied # text transformation. Our origin is still in the center of the current state painter.save() #Save_3 painter.rotate(180) #making the text go vertical painter.rotate( -rot ) #undoing the rotation made for painting the state. No the text is horizontal font = painter.font() font.setPixelSize(self.state_radius * .4) painter.setFont(font) rect = QRect(-self.state_radius, -self.state_radius, self.state_radius * 2, self.state_radius * 2) painter.drawText(rect, Qt.AlignCenter, self.machine.getState(h).getName()) painter.restore() #Restore_3 #end text transformation painter.restore() #Restore_2 painter.restore( ) #Restore_1. Restore the state of the system (pop matrix) #drawing transitions. Line between states painter.save() # Save_4 pptv = QTransform( ) #Define a new transformation. Needed to rotate the system along other axis than Z pptv.translate( 0, self.height()) #We are now at the bottom-left corner of the screen pptv.rotate( -180, Qt.XAxis ) #Rotate along the X-axis so now we are in a typical cartesian system. painter.setTransform(pptv) #Apply the transformation states = self.machine.getStates() for state in states: transitions = state.getTransitions() for transition in transitions: #get the center of the origin and destination states in our current system state orig = QPoint(state.getPos()[0], state.getPos()[1]) end = QPoint( self.machine.getState( transition.getStateEnd()).getPos()[0], self.machine.getState( transition.getStateEnd()).getPos()[1]) # get those coordinates without transformation orig2 = QPoint(painter.worldTransform().map(orig)) end2 = QPoint(painter.worldTransform().map(end)) #get the angle between states centers and the horizon angle = math.atan2(end2.y() - orig2.y(), end2.x() - orig2.x()) #get the coordinates of the starting point of the transition (it starts in the bound of the state, not in the center) newX = self.state_radius * math.cos(angle) + orig2.x() newY = self.state_radius * math.sin(angle) + orig2.y() #now the transition starts at the border, not in the center orig2.setX(newX) orig2.setY(newY) #same for the destination state angle2 = math.atan2(orig2.y() - end2.y(), orig2.x() - end2.x()) newX2 = self.state_radius * math.cos(angle2) + end2.x() newY2 = self.state_radius * math.sin(angle2) + end2.y() end2.setX(newX2) end2.setY(newY2) #draw the line between the origin and destination states painter.drawLine(orig2, end2) #get the start and the end of the transition untransformed init = QPoint(painter.worldTransform().map(orig2)) end = QPoint(painter.worldTransform().map(end2)) #store that info transition.setOrig(init.x(), init.y()) transition.setDest(end.x(), end.y()) transition.setAngle(angle) painter.restore() #Restore_4 #Appliying style to the transitions painter.setPen(QPen(QColor(Qt.gray), 3)) for state in self.machine.getStates(): for transition in state.getTransitions(): #get the start and end coordinates of the transition i = QPoint(transition.getOrig()[0], transition.getOrig()[1]) o = QPoint(transition.getDest()[0], transition.getDest()[1]) painter.drawPolyline(i, o) #Drawing the arrow at the end of the transition painter.save() #Save_5 painter.setPen(QPen(QColor(Qt.gray), 2)) painter.translate( transition.getDest()[0], transition.getDest()[1]) #Go to the end of the transition painter.rotate( 90 - transition.getAngle() * 180 / math.pi ) #Rotate to point in the direction of the transition #coordinates of the arrow (triangle) a = QPoint(0, 0) b = QPoint(-5, 10) c = QPoint(5, 10) #coordinates of the arrow untransformed a1 = painter.worldTransform().map(a) b1 = painter.worldTransform().map(b) c1 = painter.worldTransform().map(c) #Drawin the actual arrow pointer = QPolygon([a, b, c]) painter.drawPolygon(pointer) painter.restore() #Restore_5 #For the animation of the transition painter.save() #Save_6 if transition.isActive( ): #if the current transition is the active one the wave function will be running, so it's updating the canvas painter.setPen(QPen(QColor(Qt.green), 3)) painter.drawPolyline(i, o) painter.setPen(QPen(QColor(Qt.gray), 3)) painter.drawPolyline(self.poly(self.pts)) #Draw the arrow in the active state (red arrow) painter.setBrush(QBrush(QColor(255, 0, 0))) painter.setPen(QPen(QColor(Qt.red), 2)) pointer = QPolygon([a1, b1, c1]) painter.drawPolygon(pointer) #Ball that follows the line animation for x, y in self.pts: painter.drawEllipse( QRectF(self.pts[0][0] - 4, self.pts[0][1] - 4, 8, 8)) painter.restore() #Restore_6 #Painting the text of the transition painter.save() #Save_7 pptv = QTransform() painter.setPen(QPen(QColor(Qt.black), 3)) #get the middle point of the transition middleX = (transition.getOrig()[0] + transition.getDest()[0]) / 2 middleY = (transition.getOrig()[1] + transition.getDest()[1]) / 2 pptv.translate(middleX, middleY) #translate to that point painter.setTransform(pptv) #apply the transformation font = painter.font() font.setPixelSize(self.state_radius * .2) painter.setFont(font) rect = QRect(-self.state_radius, -self.state_radius, self.state_radius * 2, self.state_radius * 2) name = str(transition.getId()) + '. ' + transition.getName() painter.drawText(rect, Qt.AlignCenter, name) painter.restore() #Restore_7 #paint the actual canvas painter.setPen(self.palette().dark().color()) painter.setBrush(Qt.NoBrush) painter.drawRect(QRect(0, 0, self.width() - 1, self.height() - 1))
def draw_tertiary(self, painter: QPainter) -> None: painter.setPen(self.pen.secondary) painter.drawLine(self.tertiary.line)
class StripChart(QWidget): """Permits display of a numerical quantitiy as well as a plot of its history.""" def __init__(self, ylim=[-1, 1], buffer_length=ccfg.plot_buffer_length, color=ccfg.plot_line_color, line_width=ccfg.plot_line_width, ytick_interval=None, print_function=lambda val: '%0.1e' % val, hlines=[0.0]): super(StripChart, self).__init__() self.layout = QVBoxLayout() self.lbl = QLabel() self.plot = QLabel() self.pixmap = QPixmap() self.buf = np.zeros(buffer_length) self.buffer_length = buffer_length self.buffer_current_index = 0 self.layout.addWidget(self.lbl) self.layout.addWidget(self.plot) self.setLayout(self.layout) self.x = np.arange(buffer_length) self.hlines = hlines self.data_y_max = ylim[1] self.data_y_min = ylim[0] if ytick_interval is not None: t0 = np.fix(float(self.data_y_min) / float(ytick_interval)) * ytick_interval t1 = np.fix(float(self.data_y_max) / float(ytick_interval)) * ytick_interval self.yticks = np.arange(t0, t1, ytick_interval) else: self.yticks = [] self.plot_width_px = ccfg.plot_width_px self.plot_height_px = ccfg.plot_height_px self.xtick0 = 0 self.xtick1 = ccfg.plot_xtick_length self.plot.setMinimumWidth(ccfg.plot_width_px) self.lbl.setMinimumWidth(ccfg.plot_width_px) self.xscale = float(ccfg.plot_width_px) / float(self.buffer_length - 1) # there's a slight penalty for drawing a 32 bit pixmap instead of an 8 # bit pixmap, but it dowsn't look like it really affects performance # so it's probably safe to make this false permit_only_gray_plots = False if permit_only_gray_plots: self.bmp = np.ones((ccfg.plot_height_px, ccfg.plot_width_px), dtype=np.uint8) * 255 bpl = int(self.bmp.nbytes / ccfg.plot_height_px) self.plot_background = QImage(self.bmp, ccfg.plot_width_px, ccfg.plot_height_px, bpl, QImage.Format_Indexed8) else: A = np.ones((ccfg.plot_height_px, ccfg.plot_width_px), dtype=np.uint32) * ccfg.plot_background_color[3] R = np.ones((ccfg.plot_height_px, ccfg.plot_width_px), dtype=np.uint32) * ccfg.plot_background_color[0] G = np.ones((ccfg.plot_height_px, ccfg.plot_width_px), dtype=np.uint32) * ccfg.plot_background_color[1] B = np.ones((ccfg.plot_height_px, ccfg.plot_width_px), dtype=np.uint32) * ccfg.plot_background_color[2] val = (A << 24 | R << 16 | G << 8 | B).flatten() bpl = int(val.nbytes / ccfg.plot_height_px) self.plot_background = QImage(val, ccfg.plot_width_px, ccfg.plot_height_px, bpl, QImage.Format_ARGB32) self.pixmap.convertFromImage(self.plot_background) self.lbl.setFixedHeight(ccfg.caption_height_px * 2) self.setMinimumWidth(ccfg.plot_width_px) self.setMinimumHeight(ccfg.plot_height_px + ccfg.caption_height_px * 2) self.print_function = print_function self.plot.setFrameShape(QFrame.Box) self.plot.setLineWidth(1) self.pen = QPen() self.pen.setColor(QColor(*color)) self.pen.setWidth(line_width) self.ytick_pen = QPen() self.ytick_pen.setColor(QColor(0, 0, 0, 255)) self.ytick_pen.setWidth(0.5) self.ytick_pen.setStyle(Qt.DotLine) self.xtick_pen = QPen() self.xtick_pen.setColor(QColor(0, 0, 0, 255)) self.xtick_pen.setWidth(2.0) self.xtick_pen.setStyle(Qt.SolidLine) self.hline_pen = QPen() self.hline_pen.setColor(QColor(0, 0, 0, 255)) self.hline_pen.setWidth(1.0) self.hline_pen.setStyle(Qt.SolidLine) self.painter = QPainter() def setText(self, new_text): self.lbl.setText(new_text) def setValue(self, new_value): self.buf[self.buffer_current_index] = new_value self.buffer_current_index = (self.buffer_current_index + 1) % self.buffer_length self.setText('%s\nsmoothed:%s' % (self.print_function(new_value), self.print_function(self.buf.mean()))) def scale_y(self, vec): h = self.plot.height() out = (h - (vec - self.data_y_min) / (self.data_y_max - self.data_y_min) * h) return out def setAlignment(self, new_alignment): self.lbl.setAlignment(new_alignment) def paintEvent(self, ev): pixmap = QPixmap() pixmap.convertFromImage(self.plot_background) self.painter.begin(pixmap) self.painter.setPen(self.ytick_pen) temp = self.scale_y( np.array( list(self.buf[self.buffer_current_index:]) + list(self.buf[:self.buffer_current_index]))) for yt in self.yticks: self.painter.drawLine( QLine(0, self.scale_y(yt), self.buffer_length * self.xscale, self.scale_y(yt))) self.painter.setPen(self.hline_pen) for hline in self.hlines: self.painter.drawLine( QLine(0, self.scale_y(hline), self.buffer_length * self.xscale, self.scale_y(hline))) self.painter.setPen(self.pen) for idx in range(self.buffer_length - 1): x1 = (idx) * self.xscale x2 = (idx + 1) * self.xscale y1 = temp[idx] y2 = temp[idx + 1] self.painter.drawLine(QLine(x1, y1, x2, y2)) interval = self.buffer_length // 10 interval = ccfg.plot_xtick_interval if idx % interval == 0: self.painter.setPen(self.xtick_pen) self.painter.drawLine( QLine((x1 - self.buffer_current_index * self.xscale) % (self.buffer_length * self.xscale), self.xtick0, (x1 - self.buffer_current_index * self.xscale) % (self.buffer_length * self.xscale), self.xtick1)) self.painter.setPen(self.pen) #if True:#20<self.buffer_current_index<80: # painter.drawEllipse(x1,y1,x2,y2) self.painter.end() self.plot.setPixmap(pixmap)
def paintInfoColumn(self, painter, option, index, width_limit=0): left = option.rect.left() + 3 top = option.rect.top() width = option.rect.width() - width_limit pixmap = QPixmap(option.rect.size()) pixmap.fill(Qt.transparent) p = QPainter(pixmap) p.setRenderHint(QPainter.Antialiasing, True) p.translate(-option.rect.topLeft()) textInner = 2 * 0 + ROW_HEIGHT - 10 itemHeight = ROW_HEIGHT + 2 * 0 margin = left + ICON_PADDING - 10 title = QVariant.value(index.model().data(index, NameRole)) summary = QVariant.value(index.model().data(index, SummaryRole)) ptype = QVariant.value(index.model().data(index, TypeRole)) rate = int(QVariant.value(index.model().data( index, RateRole))) if QVariant.value(index.model().data( index, RateRole)) != None else 0 installed = True if QVariant.value(index.model().data( index, InstalledRole)) == "True" else False # We need to request update if its not possible to get meta data about the package try: # Get Package Icon if exists _icon = QVariant.value(index.model().data(index, Qt.DecorationRole)) except: p.end() painter.drawPixmap(option.rect.topLeft(), pixmap) self.parent.requestUpdate() return icon = None if _icon: overlay = [CHECK_ICON] if installed else [] KIconLoader._forceCache = True pix = KIconLoader.loadOverlayed(_icon, overlay, 32) if not pix.isNull(): icon = QIcon( pix.scaled(QSize(32, 32), Qt.KeepAspectRatio, Qt.SmoothTransformation)) KIconLoader._forceCache = False if not icon: icon = self.defaultIcon if not installed else self.defaultInstalledIcon # Paint the Icon icon.paint(p, margin, top + ICON_PADDING, ICON_HEIGHT, ICON_HEIGHT, Qt.AlignCenter) fix_pos = 0 if index.model().columnCount() <= 1: fix_pos = 22 if config.USE_APPINFO: # Rating Stars for _rt_i in range(5): self._rt_0.paint(p, width + 10 * _rt_i - 30 - fix_pos, top + ROW_HEIGHT / 4, 10, 10, Qt.AlignCenter) for _rt_i in range(rate): self._rt_1.paint(p, width + 10 * _rt_i - 30 - fix_pos, top + ROW_HEIGHT / 4, 10, 10, Qt.AlignCenter) foregroundColor = option.palette.color(QPalette.Text) p.setPen(foregroundColor) # Package Name p.setFont(self.boldFont) p.drawText(left + textInner, top, width - textInner, itemHeight / 2, Qt.AlignBottom | Qt.AlignLeft, title) # tagWidth = 0 _component_width = 0 if self.parent.showComponents: component = str( QVariant.value(index.model().data(index, ComponentRole))) widthOfTitle = self.boldFontFM.width(title) + 6 + left + textInner p.setFont(self.tagFont) rect = self.tagFontFM.boundingRect(option.rect, Qt.TextWordWrap, component) p.setPen(LIGHTGREEN) p.setBrush(LIGHTGREEN) p.drawRoundedRect(widthOfTitle, top + 12, rect.width() + 4, rect.height(), 10, 10) p.setPen(DARKGREEN) p.drawText(widthOfTitle + 2, top + 12, rect.width(), rect.height(), Qt.AlignCenter, component) p.setPen(foregroundColor) _component_width = rect.width() + 8 if self.parent.showIsA: isa = str(QVariant.value(index.model().data(index, IsaRole))) if not isa == '': widthOfTitle = self.boldFontFM.width( title) + 6 + left + textInner + _component_width p.setFont(self.tagFont) rect = self.tagFontFM.boundingRect(option.rect, Qt.TextWordWrap, isa) p.setPen(LIGHTBLUE) p.setBrush(LIGHTBLUE) p.drawRoundedRect(widthOfTitle, top + 12, rect.width() + 4, rect.height(), 10, 10) p.setPen(DARKVIOLET) p.drawText(widthOfTitle + 2, top + 12, rect.width(), rect.height(), Qt.AlignCenter, isa) p.setPen(foregroundColor) _component_width += rect.width() + 8 if ptype not in ('None', 'normal'): widthOfTitle = self.boldFontFM.width( title) + 6 + left + textInner + _component_width p.setFont(self.tagFont) rect = self.tagFontFM.boundingRect(option.rect, Qt.TextWordWrap, self.types[ptype][1]) p.setPen(self.types[ptype][0]) p.setBrush(self.types[ptype][0]) p.drawRoundedRect(widthOfTitle, top + 12, rect.width() + 4, rect.height(), 10, 10) p.setPen(WHITE) p.drawText(widthOfTitle + 2, top + 12, rect.width(), rect.height(), Qt.AlignCenter, self.types[ptype][1]) p.setPen(foregroundColor) tagWidth = rect.width() # Package Summary p.setFont(self.normalFont) foregroundColor.setAlpha(160) p.setPen(foregroundColor) elided_summary = self.normalFontFM.elidedText( summary, Qt.ElideRight, width - textInner - tagWidth - 22) p.drawText(left + textInner, top + itemHeight / 2, width - textInner, itemHeight / 2, Qt.TextDontClip, elided_summary) foregroundColor.setAlpha(255) p.setPen(foregroundColor) buttonStyle = None if self.rowAnimator.currentRow() == index.row(): description = str( QVariant.value(index.model().data(index, DescriptionRole))) size = str(QVariant.value(index.model().data(index, SizeRole))) homepage = str( QVariant.value(index.model().data(index, HomepageRole))) installedVersion = str( QVariant.value(index.model().data(index, InstalledVersionRole))) version = str( QVariant.value(index.model().data(index, VersionRole))) # Package Detail Label position = top + ROW_HEIGHT p.setFont(self.normalDetailFont) baseRect = QRect(left, position, width - 8, option.rect.height()) rect = self.normalDetailFontFM.boundingRect( baseRect, Qt.TextWordWrap | Qt.TextDontClip, description) p.drawText(left + 2, position, width - 8, rect.height(), Qt.TextWordWrap | Qt.TextDontClip, description) # Package Detail Homepage position += rect.height() + 4 p.setFont(self.boldDetailFont) p.drawText(left + ICON_SIZE, position, width - textInner, itemHeight / 2, Qt.AlignLeft, self._titles['website']) p.setFont(self.normalDetailFont) homepage = self.normalDetailFontFM.elidedText( homepage, Qt.ElideRight, width - self._titleFM['website']) rect = self.normalDetailFontFM.boundingRect( option.rect, Qt.TextSingleLine, homepage) self.rowAnimator.hoverLinkFilter.link_rect = QRect( left + self._titleFM['website'] + 2, position + 2 + 32, rect.width(), rect.height()) p.setPen(option.palette.color(QPalette.Link)) p.drawText(left + self._titleFM['website'], position, width, rect.height(), Qt.TextSingleLine, homepage) p.setPen(foregroundColor) # Package Detail Version position += rect.height() p.setFont(self.boldDetailFont) p.drawText(left + ICON_SIZE, position, width - textInner, itemHeight / 2, Qt.AlignLeft, self._titles['release']) p.setFont(self.normalDetailFont) rect = self.normalDetailFontFM.boundingRect( option.rect, Qt.TextWordWrap, version) p.drawText(left + self._titleFM['release'], position, width, rect.height(), Qt.TextWordWrap, version) if not installedVersion == '' or not installedVersion == None: position += rect.height() p.setFont(self.boldDetailFont) p.drawText(left + ICON_SIZE, position, width - textInner, itemHeight / 2, Qt.AlignLeft, self._titles['installVers']) p.setFont(self.normalDetailFont) rect = self.normalDetailFontFM.boundingRect( option.rect, Qt.TextWordWrap, installedVersion) p.drawText(left + self._titleFM['installVers'], position, width, rect.height(), Qt.TextWordWrap, installedVersion) # Package Detail Repository repository = QVariant.value(index.model().data( index, RepositoryRole)) if not repository == '': repository = _translate( "Package Manager", 'Unknown') if repository == 'N/A' else repository position += rect.height() p.setFont(self.boldDetailFont) p.drawText(left + ICON_SIZE, position, width - textInner, itemHeight / 2, Qt.AlignLeft, self._titles['repository']) p.setFont(self.normalDetailFont) p.drawText(left + self._titleFM['repository'], position, width, itemHeight / 2, Qt.TextWordWrap, repository) # Package Detail Size position += rect.height() p.setFont(self.boldDetailFont) p.drawText(left + ICON_SIZE, position, width - textInner, itemHeight / 2, Qt.AlignLeft, self._titles['size']) p.setFont(self.normalDetailFont) p.drawText(left + self._titleFM['size'], position, width, itemHeight / 2, Qt.TextWordWrap, size) position += rect.height() self.rowAnimator.max_height = position - top + 8 # Package More info button opt = QStyleOptionViewItem(option) buttonStyle = QStyleOptionButton() if option.state & QStyle.State_MouseOver or option.state & QStyle.State_HasFocus: buttonStyle.state |= QStyle.State_HasFocus buttonStyle.state |= QStyle.State_Enabled buttonStyle.text = _translate("Package Manager", "Details") buttonStyle.rect = QRect(width - 100, position - 22, 100, 22) p.end() # FIXME # if option.state & QStyle.State_HasFocus and self.animatable: # option.state |= QStyle.State_MouseOver # Use Plastique style to draw focus rect like MouseOver effect of Oxygen. # self.plastik.drawPrimitive(QStyle.PE_FrameLineEdit, option, painter, None) if not self.rowAnimator.running() and buttonStyle: if self.show_details_button and (installed or config.USE_APPINFO): PackageDelegate.AppStyle().drawControl(QStyle.CE_PushButton, buttonStyle, painter, None) self.rowAnimator.hoverLinkFilter.button_rect = QRect( buttonStyle.rect) painter.drawPixmap(option.rect.topLeft(), pixmap) del pixmap
def paintEvent(self, event): # print('Paint!!!') painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing, True) xr = self.data_range['x'] yr = self.data_range['y'] w = self.width() h = self.height() w2h_desired_ratio = (xr[1] - xr[0]) / (yr[1] - yr[0]) # self.aspect_ratio = WIDTH/HEIGHT # print('DESIRED', w2h_desired_ratio ) # print('CURRENT', w/h ) if w / h < w2h_desired_ratio: # h = w / w2h_desired_ratio scale = w / (xr[1] - xr[0]) else: # w = h * w2h_desired_ratio scale = h / (yr[1] - yr[0]) # print('FIXED', w/h ) # print('FIXED', w/h, 'w={},h={},scale={}'.format(w,h,scale) ) tform = QTransform() tform.translate(self.width() / 2.0, self.height() / 2.0) tform.scale(1.0, -1.0) painter.setTransform(tform) for color in self.edgeList: c = QColor(color[0], color[1], color[2]) painter.setPen(c) for edge in self.edgeList[color]: ln = QLineF(scale * edge.x1(), scale * edge.y1(), scale * edge.x2(), scale * edge.y2()) painter.drawLine(ln) for color in self.edgeList: c = QColor(color[0], color[1], color[2]) painter.setPen(c) for edge in self.edgeList[color]: # arrow_scale = .015 arrow_scale = 5.0 unit_edge = (edge.x2() - edge.x1(), edge.y2() - edge.y1()) unit_edge_mag = math.sqrt((edge.x2() - edge.x1())**2 + (edge.y2() - edge.y1())**2) unit_edge = (unit_edge[0] / unit_edge_mag, unit_edge[1] / unit_edge_mag) unit_edge_perp = (-unit_edge[1], unit_edge[0]) temp_tform = QTransform() temp_tform.translate(self.width() / 2.0, self.height() / 2.0) temp_tform.scale(1.0, -1.0) temp_tform.translate(scale * edge.x2(), scale * edge.y2()) temp_tform.scale(1.0, -1.0) painter.setTransform(temp_tform) # painter.drawText( RECT, label[1], align ) tri_pts = [] tri_pts.append(QPointF(0, 0)) tri_pts.append( QPointF( -arrow_scale * (2 * unit_edge[0] + unit_edge_perp[0]), arrow_scale * (2 * unit_edge[1] + unit_edge_perp[1]))) tri_pts.append( QPointF( -arrow_scale * (2 * unit_edge[0] - unit_edge_perp[0]), arrow_scale * (2 * unit_edge[1] - unit_edge_perp[1]))) tri = QPolygonF(tri_pts) b = painter.brush() painter.setBrush(c) painter.drawPolygon(tri) painter.setBrush(b) painter.setTransform(tform) font = QFont("Monospace") font.setStyleHint(QFont.TypeWriter) R = 1.0E3 CITY_SIZE = 2.0 # DIAMETER RECT = QRectF(-R, -R, 2.0 * R, 2.0 * R) align = QTextOption(Qt.Alignment(Qt.AlignHCenter | Qt.AlignVCenter)) for color in self.labelList: c = QColor(color[0], color[1], color[2]) painter.setPen(c) for label in self.labelList[color]: temp_tform = QTransform() temp_tform.translate(self.width() / 2.0, self.height() / 2.0) temp_tform.scale(1.0, -1.0) pt = label[0] xoff = label[2] temp_tform.translate(scale * pt.x() + xoff, scale * pt.y()) temp_tform.scale(1.0, -1.0) painter.setTransform(temp_tform) painter.drawText(RECT, label[1], align) painter.setTransform(tform) for color in self.pointList: c = QColor(color[0], color[1], color[2]) painter.setPen(c) b = painter.brush() painter.setBrush(c) for point in self.pointList[color]: # pt = QPointF(w*point.x(), h*point.y()) pt = QPointF(scale * point.x(), scale * point.y()) painter.drawEllipse(pt, CITY_SIZE, CITY_SIZE) painter.setBrush(b)
def paintEvent(self, event): painter = QPainter(self) if self.main_ui.combo_interpolation.currentIndex() == 0: scale_mode = Qt.SmoothTransformation else: scale_mode = Qt.FastTransformation painter.drawImage( event.rect(), self.image.scaledToWidth(self.width * self.image_pixel_size, scale_mode)) if self.agc_roi_from != None and self.agc_roi_to != None and not self.image_is_16bit: from_x, from_y, to_x, to_y = self.agc_roi_from.x( ), self.agc_roi_from.y(), self.agc_roi_to.x(), self.agc_roi_to.y() draw_rect( painter, from_x * self.image_pixel_size + self.image_pixel_size // 2, from_y * self.image_pixel_size + self.image_pixel_size // 2, (to_x - from_x) * self.image_pixel_size + 1, (to_y - from_y) * self.image_pixel_size + 1, 1, Qt.green) self.main_ui.update_agc_roi_label() if self.spotmeter_roi_from != None and self.spotmeter_roi_to != None: pen = QPen() pen.setColor(Qt.white) pen.setWidth(1) painter.setPen(pen) from_x, from_y, to_x, to_y = self.spotmeter_roi_from.x( ), self.spotmeter_roi_from.y(), self.spotmeter_roi_to.x( ), self.spotmeter_roi_to.y() from_x = from_x * self.image_pixel_size + self.image_pixel_size // 2 + 1 from_y = from_y * self.image_pixel_size + self.image_pixel_size // 2 + 1 to_x = to_x * self.image_pixel_size + self.image_pixel_size // 2 - 1 to_y = to_y * self.image_pixel_size + self.image_pixel_size // 2 - 1 cross_x = from_x + (to_x - from_x) / 2.0 cross_y = from_y + (to_y - from_y) / 2.0 if to_x - from_x > self.image_pixel_size or to_y - from_y > self.image_pixel_size: lines = [ QLineF(from_x, from_y, from_x + self.crosshair_width, from_y), QLineF(from_x, from_y, from_x, from_y + self.crosshair_width), QLineF(to_x, to_y, to_x, to_y - self.crosshair_width), QLineF(to_x, to_y, to_x - self.crosshair_width, to_y), QLineF(from_x, to_y, from_x, to_y - self.crosshair_width), QLineF(from_x, to_y, from_x + self.crosshair_width, to_y), QLineF(to_x, from_y, to_x, from_y + self.crosshair_width), QLineF(to_x, from_y, to_x - self.crosshair_width, from_y) ] painter.drawLines(lines) lines = [ QLineF(cross_x - self.crosshair_width, cross_y, cross_x + self.crosshair_width, cross_y), QLineF(cross_x, cross_y - self.crosshair_width, cross_x, cross_y + self.crosshair_width) ] painter.drawLines(lines) self.main_ui.update_spotmeter_roi_label()
def paintEvent(self, event): w, h = self.width(), self.height() painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) blackpen = QPen(Qt.black, 1) nopen = QPen() nopen.setStyle(Qt.NoPen) greypen = QPen(Qt.gray, 1) painter.setPen(blackpen) nofill = QBrush() bfill = QBrush(QColor(0, 0, 0)) wfill = QBrush(QColor(255, 255, 255)) if self._histogram is not None: painter.fillRect(self.rect(), wfill) rect = QRect( 0, 0, max(0, self.minclip - self.min) * w / (self.max - self.min), h) painter.fillRect(rect, bfill) ww = max(0, self.max - self.maxclip) * w / (self.max - self.min) rect = QRect(w - ww, 0, ww, h) painter.fillRect(rect, bfill) fill = QBrush(QColor(*self.color)) poly = QPolygon() path = QPainterPath() pathstarted = False H = log(self._histogram / self._histogram.sum()) / log(2) H = maximum(H, -25) m = self.minclip / 255 M = self.maxclip / 255 for j, k in enumerate(H): x = j * w / (len(self._histogram) - 1) y = min(h * (k + 4) / (-25 + 4), h) poly.append(QPoint(x, y)) u = j / len(self._histogram) if (isinstance(m, ndarray) or isinstance(M, ndarray) or isinstance(self.gamma, ndarray)): continue if m <= u <= M: v = 1 - (1 - (u - m) / (M - m))**self.gamma if u < M or self.gamma >= 1: dvdu = self.gamma * \ (1 - (u - m)/(M - m))**(self.gamma - 1)/(M - m) else: dvdu = 1 if pathstarted: path.lineTo(v * w, y - log(dvdu) / log(2) / (-25 + 4)) else: path.moveTo(v * w, y - log(dvdu) / log(2) / (-25 + 4)) pathstarted = True poly.append(QPoint(w, h)) poly.append(QPoint(0, h)) painter.setPen(nopen) painter.setBrush(fill) painter.drawPolygon(poly) painter.setPen(greypen) painter.setBrush(nofill) painter.drawPath(path)
def paintEvent(self, event): painter = QPainter(self) event.accept() # ------------------------------------------------------------- # Paint clean keys (as background) for octave in range(self.fOctaves): if self.fPixmapMode == self.HORIZONTAL: target = QRectF(self.fWidth * octave, 0, self.fWidth, self.fHeight) elif self.fPixmapMode == self.VERTICAL: target = QRectF(0, self.fHeight * octave, self.fWidth, self.fHeight) else: return source = QRectF(0, 0, self.fWidth, self.fHeight) painter.drawPixmap(target, self.fPixmap, source) if not self.isEnabled(): painter.setBrush(QColor(0, 0, 0, 150)) painter.setPen(QColor(0, 0, 0, 150)) painter.drawRect(0, 0, self.width(), self.height()) return # ------------------------------------------------------------- # Paint (white) pressed keys paintedWhite = False for note in self.fEnabledKeys: pos = self._getRectFromMidiNote(note) if self._isNoteBlack(note): continue if note < 12: octave = 0 elif note < 24: octave = 1 elif note < 36: octave = 2 elif note < 48: octave = 3 elif note < 60: octave = 4 elif note < 72: octave = 5 elif note < 84: octave = 6 elif note < 96: octave = 7 elif note < 108: octave = 8 elif note < 120: octave = 9 elif note < 132: octave = 10 else: # cannot paint this note continue if self.fPixmapMode == self.VERTICAL: octave = self.fOctaves - octave - 1 if self.fPixmapMode == self.HORIZONTAL: target = QRectF(pos.x() + (self.fWidth * octave), 0, pos.width(), pos.height()) source = QRectF(pos.x(), self.fHeight, pos.width(), pos.height()) elif self.fPixmapMode == self.VERTICAL: target = QRectF(pos.x(), pos.y() + (self.fHeight * octave), pos.width(), pos.height()) source = QRectF(self.fWidth, pos.y(), pos.width(), pos.height()) else: return paintedWhite = True painter.drawPixmap(target, self.fPixmap, source) # ------------------------------------------------------------- # Clear white keys border if paintedWhite: for octave in range(self.fOctaves): for note in kBlackNotes: pos = self._getRectFromMidiNote(note) if self.fPixmapMode == self.HORIZONTAL: target = QRectF(pos.x() + (self.fWidth * octave), 0, pos.width(), pos.height()) source = QRectF(pos.x(), 0, pos.width(), pos.height()) elif self.fPixmapMode == self.VERTICAL: target = QRectF(pos.x(), pos.y() + (self.fHeight * octave), pos.width(), pos.height()) source = QRectF(0, pos.y(), pos.width(), pos.height()) else: return painter.drawPixmap(target, self.fPixmap, source) # ------------------------------------------------------------- # Paint (black) pressed keys for note in self.fEnabledKeys: pos = self._getRectFromMidiNote(note) if not self._isNoteBlack(note): continue if note < 12: octave = 0 elif note < 24: octave = 1 elif note < 36: octave = 2 elif note < 48: octave = 3 elif note < 60: octave = 4 elif note < 72: octave = 5 elif note < 84: octave = 6 elif note < 96: octave = 7 elif note < 108: octave = 8 elif note < 120: octave = 9 elif note < 132: octave = 10 else: # cannot paint this note continue if self.fPixmapMode == self.VERTICAL: octave = self.fOctaves - octave - 1 if self.fPixmapMode == self.HORIZONTAL: target = QRectF(pos.x() + (self.fWidth * octave), 0, pos.width(), pos.height()) source = QRectF(pos.x(), self.fHeight, pos.width(), pos.height()) elif self.fPixmapMode == self.VERTICAL: target = QRectF(pos.x(), pos.y() + (self.fHeight * octave), pos.width(), pos.height()) source = QRectF(self.fWidth, pos.y(), pos.width(), pos.height()) else: return painter.drawPixmap(target, self.fPixmap, source) # Paint C-number note info painter.setFont(self.fFont) painter.setPen(Qt.black) for i in range(self.fOctaves): if self.fPixmapMode == self.HORIZONTAL: painter.drawText(i * 168 + (4 if i == 0 else 3), 35, 20, 20, Qt.AlignCenter, "C%i" % (i-1)) elif self.fPixmapMode == self.VERTICAL: painter.drawText(33, (self.fOctaves * 168) - (i * 168) - 20, 20, 20, Qt.AlignCenter, "C%i" % (i-1))