我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用PyQt5.QtGui.QPainter()。
def paintEvent(self, event): """ Overrides the QLabel method. Shouldn't need to be called directly. """ super().paintEvent(event) if self._pixmap_src is None: return self._pixmap = self._pixmap_src.scaled( self.size(), QtCore.Qt.KeepAspectRatio) x = (self.width() - self._pixmap.width())/2 y = (self.height() - self._pixmap.height())/2 painter = QtGui.QPainter(self) painter.drawPixmap(x, y, self._pixmap)
def asama_ciz(asama,tum_asama): #Amac?m?z pencerenin üzerinde gözüken ad?m k?sm? için gerekli resmi olu?turmak resim = QImage(950,10,QImage.Format_RGB32) boyayici = QPainter() boyayici.begin(resim) mavi_kalem = QPen(QColor("#00bbf2")) mavi_firca = QBrush(QColor("#00bbf2")) beyaz_kalem = QPen(QColor("#ffffff")) beyaz_firca = QBrush(QColor("#ffffff")) boyayici.setPen(beyaz_kalem) boyayici.setBrush(beyaz_firca) boyayici.drawRect(0,0,950,10) boyayici.setPen(mavi_kalem) boyayici.setBrush(mavi_firca) en_hesabi = (asama/tum_asama)*950 boyayici.drawRect(0,0,int(en_hesabi),10) boyayici.end() return resim
def draw_progress_bar(plex_item, pixmap, height=6): """draw a progress indicator on the bottom of pixmap with height pixels""" if not hasattr(plex_item, 'in_progress'): return if not plex_item.in_progress: return progress_color = QtGui.QColor(204, 123, 25) progress = plex_item.view_offset / max(1, plex_item.duration) p = QtGui.QPainter(pixmap) rect = p.window() progress_rect = QtCore.QRect(rect.bottomLeft() - QtCore.QPoint(0, height), rect.bottomRight()) progress_fill = QtCore.QRect(progress_rect) progress_fill.setWidth(rect.width() * progress) p.fillRect(progress_rect, QtGui.QBrush(QtCore.Qt.black)) p.fillRect(progress_fill, QtGui.QBrush(progress_color))
def draw_unwatched_indicator(plex_item, pixmap, size=0.20): """draw a triangle on the top right of pixmap""" if not hasattr(plex_item, 'watched') and not hasattr(plex_item, 'in_progress'): return if plex_item.watched or plex_item.in_progress: return p = QtGui.QPainter(pixmap) rect = p.window() top_right = rect.topRight() size = pixmap.height() * size color = QtGui.QColor(204, 123, 25) triangle = QtGui.QPolygon([top_right, top_right - QtCore.QPoint(size, 0), top_right + QtCore.QPoint(0, size)]) p.setPen(QtGui.QPen(QtGui.QBrush(QtGui.QColor(0, 0, 0, 120)), 6)) p.drawLine(triangle.point(1), triangle.point(2)) p.setBrush(QtGui.QBrush(color)) p.setPen(color) p.drawPolygon(triangle)
def __init__(self, parent=None, ui_widget=None, home=None, window=None, logr=None): global ui, MainWindow, logger QtWidgets.QSystemTrayIcon.__init__(self, parent) ui = parent MainWindow = window logger = logr icon_img = os.path.join(home, 'src', 'tray.png') self.right_menu = RightClickMenuIndicator(ui_widget=ui_widget, window=window, logr=logr) self.setContextMenu(self.right_menu) self.activated.connect(self.onTrayIconActivated) self.p = QtGui.QPixmap(24, 24) self.p.fill(QtGui.QColor("transparent")) painter = QtGui.QPainter(self.p) if os.path.exists(icon_img): self.setIcon(QtGui.QIcon(icon_img)) else: self.setIcon(QtGui.QIcon("")) self.full_scr = 1 del painter
def capture(self, url): print('--load') self.load(QUrl(url)) self.wait_load() self.show() size = self.page().contentsSize() self.page().view().resize(*[int(s) for s in [size.width(), size.height()]]) print('--take image') image = QImage(800, 800, QImage.Format_ARGB32) painter = QPainter(image) print('--render') self.page().view().render(painter) painter.end() print('Saving QImage') img_bytes = QByteArray() bio = QBuffer(img_bytes) bio.open(QIODevice.WriteOnly) image.save(bio, 'PNG') return img_bytes
def paintEvent(self, QPaintEvent): y_offset=100 x_offset=50 painter = QPainter() painter.begin(self) if self.load_type.sim_mode.currentText()=="load": painter.drawPixmap(x_offset,y_offset, self.diode) painter.drawPixmap(x_offset+620,y_offset+67, self.load) elif self.load_type.sim_mode.currentText()=="ideal_diode_ideal_load": painter.drawPixmap(x_offset,y_offset, self.ideal_diode) painter.drawPixmap(x_offset+620,y_offset+68, self.ideal_load) else: painter.drawPixmap(x_offset,y_offset, self.diode) painter.drawPixmap(x_offset+620,y_offset+57, self.voc) painter.end()
def updateColor(self, item): pixmap = QPixmap(16, 16) color = QColor() if item: color = item.backgroundColor() if not color.isValid(): color = self.palette().base().color() painter = QPainter(pixmap) painter.fillRect(0, 0, 16, 16, color) lighter = color.lighter() painter.setPen(lighter) # light frame painter.drawPolyline(QPoint(0, 15), QPoint(0, 0), QPoint(15, 0)) painter.setPen(color.darker()) # dark frame painter.drawPolyline(QPoint(1, 15), QPoint(15, 15), QPoint(15, 1)) painter.end() self.colorAction.setIcon(QIcon(pixmap))
def showNextPiece(self): if self.nextPieceLabel is None: return dx = self.nextPiece.maxX() - self.nextPiece.minX() + 1 dy = self.nextPiece.maxY() - self.nextPiece.minY() + 1 pixmap = QPixmap(dx * self.squareWidth(), dy * self.squareHeight()) painter = QPainter(pixmap) painter.fillRect(pixmap.rect(), self.nextPieceLabel.palette().window()) for i in range(4): x = self.nextPiece.x(i) - self.nextPiece.minX() y = self.nextPiece.y(i) - self.nextPiece.minY() self.drawSquare(painter, x * self.squareWidth(), y * self.squareHeight(), self.nextPiece.shape()) painter.end() self.nextPieceLabel.setPixmap(pixmap)
def createData(self, mimeType): if mimeType != 'image/png': return image = QImage(self.imageLabel.size(), QImage.Format_RGB32) painter = QPainter() painter.begin(image) self.imageLabel.renderer().render(painter) painter.end() data = QByteArray() buffer = QBuffer(data) buffer.open(QIODevice.WriteOnly) image.save(buffer, 'PNG') buffer.close() self.mimeData.setData('image/png', data)
def paintEvent(self, event): painter = QPainter(self) if len(self.m_histogram) == 0: painter.fillRect(0, 0, self.width(), self.height(), QColor.fromRgb(0, 0, 0)) return barWidth = self.width() / float(len(self.m_histogram)) for i, value in enumerate(self.m_histogram): h = value * self.height() # Draw the level. painter.fillRect(barWidth * i, self.height() - h, barWidth * (i + 1), self.height(), Qt.red) # Clear the rest of the control. painter.fillRect(barWidth * i, 0, barWidth * (i + 1), self.height() - h, Qt.black)
def __init__(self,parent=None): global name,home QtWidgets.QSystemTrayIcon.__init__(self, parent) icon_img = os.path.join(home,'src','tray.png') self.right_menu = RightClickMenuIndicator() self.setContextMenu(self.right_menu) self.activated.connect(self.onTrayIconActivated) self.p = QtGui.QPixmap(24,24) self.p.fill(QtGui.QColor("transparent")) painter = QtGui.QPainter(self.p) if os.path.exists(icon_img): self.setIcon(QtGui.QIcon(icon_img)) else: self.setIcon(QtGui.QIcon("")) self.full_scr = 1 del painter
def updateColor(self, item): pixmap = QPixmap(16, 16) color = QColor() if item: if hasattr(item, 'backgroundColor'): color = item.backgroundColor() if not color.isValid(): color = self.palette().base().color() painter = QPainter(pixmap) painter.fillRect(0, 0, 16, 16, color) lighter = color.lighter() painter.setPen(lighter) # light frame painter.drawPolyline(QPoint(0, 15), QPoint(0, 0), QPoint(15, 0)) painter.setPen(color.darker()) # dark frame painter.drawPolyline(QPoint(1, 15), QPoint(15, 15), QPoint(15, 1)) painter.end() self.colorAction.setIcon(QIcon(pixmap))
def draw_box(self, n, box, color, style, num): x1, y1, x2, y2 = box.left(), box.top(), box.right(), box.bottom() x1 = int(x1 * self.i_scale[n]) y1 = int(y1 * self.i_scale[n]) x2 = int(x2 * self.i_scale[n]) y2 = int(y2 * self.i_scale[n]) width = BASEWIDTH if style == 'match': width *= 2 painter = QPainter(self.i_pixmap[n]) painter.setPen(QPen(QBrush(color), width)) painter.drawRect(x1, y1, x2 - x1, y2 - y1) painter.setPen(QPen(QBrush(TEXTCOLOR), TEXTWIDTH)) painter.setFont(TEXTFONT) painter.drawText(x1, y2 + TEXTSIZE + 2 * BASEWIDTH, '{}: {}'.format(n + 1, num)) painter.end() self.i_lbl[n].setPixmap(self.i_pixmap[n])
def saveImage(self, fname): # noqa: N802 """ Saves current viewport as a png file of the given fname. """ rect = self.viewport() rgb = QtGui.QImage.Format_RGB32 image = QtGui.QImage(rect.width(), rect.height(), rgb) image.fill(QtGui.QColor(255, 255, 255)) painter = QtGui.QPainter(image) self.render(painter) if not image.save(fname): raise ValueError('could not save image %s' % fname) del painter
def draw_edges(image, edges): p = QPainter() p.begin(image) p.setPen(QPen(col_one)) for ed in edges: p.drawLine(ed[0], ed[1], ed[2], ed[3]) p.end()
def draw_edges(image, edges): p = QPainter() p.begin(image) p.setPen(QPen(QColor(0, 0, 255))) for ed in edges: p.drawLine(ed[0], ed[1], ed[2], ed[3]) p.end()
def draw_circle(image, rad, point): p = QPainter() p.begin(image) p.setPen(QPen(QColor(0, 0, 255))) p.drawEllipse(point.x() - rad, point.y() - rad, rad * 2, rad * 2) p.end()
def paintEvent(self, event): super().paintEvent(event) painter = QtGui.QPainter() painter.begin(self) self.draw_ticks(painter) painter.end()
def paintEvent(self, event): painter = QtGui.QPainter(self) w = self.width() h = self.height() # background painter.setPen(QtCore.Qt.gray) painter.setBrush(QtCore.Qt.lightGray) painter.drawRect(2, 2, w-4, h-4) # range bar painter.setPen(QtCore.Qt.darkGray) painter.setBrush(QtCore.Qt.darkGray) painter.drawRect(self.display_min-1, 5, self.display_max-self.display_min+2, h-10) # min & max tabs painter.setPen(QtCore.Qt.black) painter.setBrush(QtCore.Qt.gray) painter.drawRect(self.display_min-self.bar_width, 1, self.bar_width, h-2) painter.setPen(QtCore.Qt.black) painter.setBrush(QtCore.Qt.gray) painter.drawRect(self.display_max, 1, self.bar_width, h-2) ## rangeSliderSize # # @return The current width of the slider widget. #
def paintEvent(self, event): painter = QtGui.QPainter(self) w = self.width() h = self.height() # background painter.setPen(QtCore.Qt.gray) painter.setBrush(QtCore.Qt.lightGray) painter.drawRect(2, 2, w-4, h-4) # range bar painter.setPen(QtCore.Qt.darkGray) painter.setBrush(QtCore.Qt.darkGray) painter.drawRect(5, h-self.display_max-1, w-10, self.display_max-self.display_min+1) # min & max tabs painter.setPen(QtCore.Qt.black) painter.setBrush(QtCore.Qt.gray) painter.drawRect(1, h-self.display_max-self.bar_width-1, w-2, self.bar_width) painter.setPen(QtCore.Qt.black) painter.setBrush(QtCore.Qt.gray) painter.drawRect(1, h-self.display_min-1, w-2, self.bar_width) ## rangeSliderSize # # @return The current height of the slider widget. #
def paintEvent(self, event): qp = QPainter(self) qp.setPen(Qt.black) size = self.size() for i in range(1024): x = random.randint(1, size.width()-1) y = random.randint(1, size.height()-1) qp.drawPoint(x, y)
def paintEvent(self, event): qp = QPainter(self) qp.setPen(Qt.black) size = self.size() # Colored rectangles qp.setBrush(QColor(200, 0, 0)) qp.drawRect(0, 0, 100, 100) qp.setBrush(QColor(0, 200, 0)) qp.drawRect(100, 0, 100, 100) qp.setBrush(QColor(0, 0, 200)) qp.drawRect(200, 0, 100, 100) # Color Effect for i in range(0,100): qp.setBrush(QColor(i*10, 0, 0)) qp.drawRect(10*i, 100, 10, 32) qp.setBrush(QColor(i*10, i*10, 0)) qp.drawRect(10*i, 100+32, 10, 32) qp.setBrush(QColor(i*2, i*10, i*1)) qp.drawRect(10*i, 100+64, 10, 32)
def draw(self, painter: QPainter) -> None: if self.sourceIsPixmap(): pixmap, offset = self.sourcePixmap(Qt.LogicalCoordinates, QGraphicsEffect.PadToEffectiveBoundingRect) else: pixmap, offset = self.sourcePixmap(Qt.DeviceCoordinates, QGraphicsEffect.PadToEffectiveBoundingRect) painter.setWorldTransform(QTransform()) painter.setBrush(Qt.black) painter.drawRect(pixmap.rect()) painter.setOpacity(self.opacity) painter.drawPixmap(offset, pixmap)
def captureFrame(source: str, frametime: str, thumbsize: QSize=ThumbSize.INDEX.value, external: bool=False) -> QPixmap: # print('[captureFrame] frametime: {0} thumbsize: {1}'.format(frametime, thumbsize)) capres = QPixmap() img = QTemporaryFile(os.path.join(QDir.tempPath(), 'XXXXXX.jpg')) if img.open(): imagecap = img.fileName() cmd = VideoService.findBackends().ffmpeg args = '-hide_banner -ss {0} -i "{1}" -vframes 1 -s {2:d}x{3:d} -y "{4}"' \ .format(frametime, source, thumbsize.width(), thumbsize.height(), imagecap) proc = VideoService.initProc() if proc.state() == QProcess.NotRunning: # if os.getenv('DEBUG', False): # logging.getLogger(__name__).info('"%s %s"' % (cmd, args)) proc.start(cmd, shlex.split(args)) proc.waitForFinished(-1) if proc.exitStatus() == QProcess.NormalExit and proc.exitCode() == 0: capres = QPixmap(imagecap, 'JPG') if external: painter = QPainter(capres) painter.drawPixmap(0, 0, QPixmap(':/images/external.png', 'PNG')) painter.end() img.remove() return capres # noinspection PyBroadException
def paint(self, painter: QPainter, option: QStyleOptionViewItem, index: QModelIndex) -> None: r = option.rect pencolor = Qt.white if self.theme == 'dark' else Qt.black if self.parent.isEnabled(): if option.state & QStyle.State_Selected: painter.setBrush(QColor(150, 190, 78, 150)) elif option.state & QStyle.State_MouseOver: painter.setBrush(QColor(227, 212, 232)) pencolor = Qt.black else: brushcolor = QColor(79, 85, 87, 175) if self.theme == 'dark' else QColor('#EFF0F1') painter.setBrush(Qt.transparent if index.row() % 2 == 0 else brushcolor) painter.setPen(Qt.NoPen) painter.drawRect(r) thumb = QIcon(index.data(Qt.DecorationRole + 1)) starttime = index.data(Qt.DisplayRole + 1) endtime = index.data(Qt.UserRole + 1) externalPath = index.data(Qt.UserRole + 2) r = option.rect.adjusted(5, 0, 0, 0) thumb.paint(painter, r, Qt.AlignVCenter | Qt.AlignLeft) painter.setPen(QPen(pencolor, 1, Qt.SolidLine)) r = option.rect.adjusted(110, 8, 0, 0) painter.setFont(QFont('Noto Sans UI', 10 if sys.platform == 'darwin' else 8, QFont.Bold)) painter.drawText(r, Qt.AlignLeft, 'FILENAME' if len(externalPath) else 'START') r = option.rect.adjusted(110, 20, 0, 0) painter.setFont(QFont('Noto Sans UI', 11 if sys.platform == 'darwin' else 9, QFont.Normal)) if len(externalPath): painter.drawText(r, Qt.AlignLeft, self.clipText(os.path.basename(externalPath), painter)) else: painter.drawText(r, Qt.AlignLeft, starttime) if len(endtime) > 0: r = option.rect.adjusted(110, 45, 0, 0) painter.setFont(QFont('Noto Sans UI', 10 if sys.platform == 'darwin' else 8, QFont.Bold)) painter.drawText(r, Qt.AlignLeft, 'RUNTIME' if len(externalPath) else 'END') r = option.rect.adjusted(110, 60, 0, 0) painter.setFont(QFont('Noto Sans UI', 11 if sys.platform == 'darwin' else 9, QFont.Normal)) painter.drawText(r, Qt.AlignLeft, endtime) if self.parent.verticalScrollBar().isVisible(): self.parent.setFixedWidth(210) else: self.parent.setFixedWidth(190)
def clipText(self, text: str, painter: QPainter) -> str: metrics = painter.fontMetrics() return metrics.elidedText(text, Qt.ElideRight, (self.parent.width() - 100 - 10))
def paintEvent(self, event): painter = QtGui.QPainter(self) pixmap = self.movie.currentPixmap() self.setMask(pixmap.mask()) painter.drawPixmap(0, 0, pixmap)
def paintEvent(self, event): qp = QtGui.QPainter() qp.begin(self) if self.image: qp.drawImage(QtCore.QPoint(0, 0), self.image) qp.end()
def placeholder_thumb_generator(title, size=150): """Returns a QPixmap of size with the first letter of each word in title""" initials = ' '.join([x[0] for x in title.split(' ') if len(x) > 2]) key = 'placeholder' + initials img = QtGui.QPixmapCache.find(key) if img: return img qsize = QtCore.QSize(size, size) circle_color = QtGui.QColor(50, 50, 50) text_color = QtGui.QColor(75, 75, 75) rect = QtCore.QRect(QtCore.QPoint(0, 0), QtCore.QPoint(size, size)) center = QtCore.QPoint(size / 2, size / 2) img = QtGui.QPixmap(qsize) img.fill(QtCore.Qt.transparent) p = QtGui.QPainter(img) p.setFont(QtGui.QFont('Open Sans', size / 4, weight=QtGui.QFont.Bold)) p.setBrush(QtGui.QBrush(circle_color)) p.setPen(circle_color) p.setRenderHint(QtGui.QPainter.Antialiasing, True) p.drawEllipse(center, size / 2 - 1, size / 2 - 1) p.setPen(text_color) p.drawText(rect, QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter, initials) QtGui.QPixmapCache.insert(key, img) return img
def drawBackground(self, painter: QPainter, rect: QRectF): backgroundColor = QColor(10, 10, 255, 30) painter.setBrush(backgroundColor) painter.setPen(backgroundColor) for i in range(-5, self.width + 20 + 1, 20): painter.drawLine(i, 5, i, self.height + 5) for i in range(-5, self.height + 20 + 1, 20): painter.drawLine(5, i, self.width + 5, i)
def paintEvent(self, q_paint_event): # board background color painter = QtGui.QPainter(self) bg_path = QtGui.QPainterPath() bg_path.addRect(0, 0, self.width(), self.height()) painter.fillPath(bg_path, GREEN) # draw the board lines for i in range(8): x_pos = self.width() / 8 * i painter.drawLine(x_pos, 0, x_pos, self.height()) y_pos = self.height() / 8 * i painter.drawLine(0, y_pos, self.width(), y_pos) if self.board is not None and len(self.board) >= 8 * 8: for h in range(8): for w in range(8): pieces_path = QtGui.QPainterPath() w_dist = self.width() / 8 h_dist = self.height() / 8 x_pos = w_dist * w y_pos = h_dist * h bounding_rect = QtCore.QRectF(x_pos, y_pos, w_dist, h_dist) index = (h * 8) + w piece = self.board[index] if piece == 'O': pieces_path.addEllipse(bounding_rect) painter.fillPath(pieces_path, WHITE) elif piece == 'X': pieces_path.addEllipse(bounding_rect) painter.fillPath(pieces_path, BLACK)
def paintEvent(self, event): # pylint: disable=unused-argument painter = QPainter(self) painter.setPen(Qt.black) widgets = {w.get_id(): (self.top_point(w.geometry()), self.bottom_point(w.geometry())) for w in self.children() if isinstance(w, GoalWidget)} for widget_id, points in widgets.items(): line_start = points[0] for parent_widget in self.dependencies[widget_id]: line_end = widgets[parent_widget][1] painter.drawLine(line_start, line_end)
def paintEvent(self, paint_event): # pylint: disable=unused-argument painter = QPainter(self) painter.setRenderHint(painter.Antialiasing) painter.setPen(QColor(Qt.black)) for upper, lower in self.lines: x1, y1 = self._lower_bound(upper) x2, y2 = self._upper_bound(lower) painter.drawLine(x1, y1, x2, y2)
def paintEvent(self, QPaintEvent): painter = QPainter() painter.begin(self) painter.drawPixmap(100,10, self.mQImage) painter.end()
def paintEvent(self, e): qp = QPainter() qp.begin(self) self.drawWidget(qp) qp.end()
def paintEvent(self,event): painter=QPainter(self) painter.drawPixmap(0,0,QPixmap("images/board.jpg").scaled(BOARD_WIDTH,BOARD_WIDTH)) self.move(UI_WIDTH * 0.201 ,UI_HEIGHT * 0.1 )
def render_pdf(self, pages, path): """Render the document to a pdf file. Args: pages (iter[int]): The page numbers to render path (str): An output file path. Warning: If the file at `path` already exists, it will be overwritten. """ printer = QPrinter() printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(os.path.realpath(path)) printer.setResolution(config.PRINT_DPI) printer.setPageLayout(self.document.paper._to_interface()) painter = QtGui.QPainter() painter.begin(printer) # Scaling ratio for Qt point 72dpi -> config.PRINT_DPI ratio = (config.PRINT_DPI / 72) target_rect_unscaled = printer.paperRect(QPrinter.Point) target_rect_scaled = QtCore.QRectF( target_rect_unscaled.x() * ratio, target_rect_unscaled.y() * ratio, target_rect_unscaled.width() * ratio, target_rect_unscaled.height() * ratio, ) for page_number in pages: source_rect = rect_to_qt_rect_f( self.document.paper_bounding_rect(page_number)) self.scene.render(painter, target=target_rect_scaled, source=source_rect) printer.newPage() painter.end()
def paintEvent(self, pe): opt = QStyleOption() opt.initFrom(self) p = QPainter(self) s = self.style() s.drawPrimitive(QStyle.PE_Widget, opt, p, self)