def paintEvent(self, e): super().paintEvent(e) if not self._results: return painter = QPainter(self.viewport()) option = self.viewOptions() painter.setRenderHint(QPainter.Antialiasing) fm = QFontMetrics(option.font) for row, result in self._results.items(): index, state = result rect = self.rectForIndex(index) if state is None: text = '⇵' elif state is True: text = '👋' else: text = '🙁' x = rect.width() - 20 + rect.x() # 让字垂直居中 y = (rect.height() + fm.ascent() - fm.descent()) / 2 + rect.y() topleft = QPoint(x, y) painter.drawText(topleft, text)
def __init__(self, parent, panel): QWidget.__init__(self, parent) self.parent = parent self.panel = panel self.lines = 1 self.self_layout = QHBoxLayout(self) self.self_layout.setContentsMargins(HierarchyTitle.TITLE_MARGIN, HierarchyTitle.TITLE_MARGIN, HierarchyTitle.TITLE_MARGIN, HierarchyTitle.TITLE_MARGIN) self.self_layout.setSpacing(0) self.setLayout(self.self_layout) self.text_holder = QWidget(self) # calculate text_holder height self.text_holder.setFont( QFont(LINK_TILE_FONT_TYPE, LINK_TILE_FONT_SIZE, weight=QFont.Normal)) self.fm = QFontMetrics(self.text_holder.font()) # self.text_holder.setMinimumHeight(self.fm.height() + 2 * HierarchyTitle.TITLE_MARGIN) self.setMinimumHeight(self.fm.height() + 2 * HierarchyTitle.TITLE_MARGIN) self.self_layout.addWidget(self.text_holder) #self.text_layout = FlowLayout(self.text_holder) self.text_layout = QVBoxLayout(self.text_holder) self.text_layout.setContentsMargins(0, 0, 0, 0) self.text_layout.setSpacing(HierarchyTitle.TITLE_SPACING) self.text_holder.setLayout(self.text_layout) self.setBackgroundColor( QColor(HierarchyTitle.DEFAULT_BACKGROUND_COLOR), False) self.setBorderRadius(HierarchyTitle.DEFAULT_BORDER_RADIUS, False)
def paintEvent(self, event): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) # 背景白色 painter.fillRect(event.rect(), QBrush(Qt.white)) # 绘制边缘虚线框 painter.setPen(Qt.DashLine) painter.setBrush(Qt.NoBrush) painter.drawRect(self.rect()) # 随机画条线 for _ in range(3): painter.setPen(QPen(QTCOLORLIST[qrand() % 5], 1, Qt.SolidLine)) painter.setBrush(Qt.NoBrush) painter.drawLine(QPoint(0, qrand() % self.height()), QPoint(self.width(), qrand() % self.height())) painter.drawLine(QPoint(qrand() % self.width(), 0), QPoint(qrand() % self.width(), self.height())) # 绘制噪点 painter.setPen(Qt.DotLine) painter.setBrush(Qt.NoBrush) for _ in range(self.width()): # 绘制噪点 painter.drawPoint( QPointF(qrand() % self.width(), qrand() % self.height())) # super(WidgetCode, self).paintEvent(event) # 绘制文字 # 绘制跳动文字 metrics = QFontMetrics(self.font()) x = (self.width() - metrics.width(self.text())) / 2 y = (self.height() + metrics.ascent() - metrics.descent()) / 2 for i, ch in enumerate(self.text()): index = (self.step + i) % 16 painter.setPen(TCOLORLIST[qrand() % 6]) painter.drawText(x, y - ((SINETABLE[index] * metrics.height()) / 400), ch) x += metrics.width(ch)
def draw_adjusted_text( painter: QPainter, label: str, font: QFont, center_x: int, center_y: int, color: QBrush = QBrush(QColor(0, 0, 0, 255)) ): """ Draw a string text with a particular format in the screen :param painter: :param label: :param font: :param center_x: :param center_y: :param color: """ painter.save() painter.setRenderHints(QPainter.TextAntialiasing) painter.setFont(font) pen = QPen() pen.setBrush(color) painter.setPen(pen) metrics = QFontMetrics(font) label_width = metrics.boundingRect(label).width() label_height = metrics.boundingRect(label).height() painter.drawText( QRectF( center_x - label_width / 2, center_y - label_height / 2, label_width, label_height ), Qt.AlignHCenter, label ) painter.restore()
def __init__(self, parent=None): super(CodeEditor, self).__init__(parent) # Set the default font font = QFont() font.setFamily('Courier') font.setFixedPitch(True) font.setPointSize(10) self.setFont(font) self.setMarginsFont(font) self.setTabWidth(4) # Margin 0 is used for line numbers fontmetrics = QFontMetrics(font) self.setMarginsFont(font) self.setMarginWidth(0, fontmetrics.width("00000") + 6) self.setMarginLineNumbers(0, True) self.setMarginsBackgroundColor(QColor("#90FF90")) # Clickable margin 1 for showing markers self.setMarginSensitivity(1, True) self.marginClicked.connect(self.on_margin_clicked) # Brace matching: enable for a brace immediately before or after the current position self.setBraceMatching(QsciScintilla.SloppyBraceMatch) # Set Python lexer # Set style for Python comments (style number 1) to a fixed-width courier. lexer = QsciLexerPython() lexer.setDefaultFont(font) self.setLexer(lexer) text = bytearray(str.encode("Arial")) # 32, "Courier New" self.SendScintilla(QsciScintilla.SCI_STYLESETFONT, 1, text) # Don't want to see the horizontal scrollbar at all self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0)
def mousePressEvent(self, event): if self.foldArea > 0: xofs = self.width() - self.foldArea font_metrics = QFontMetrics(self.edit.document().defaultFont()) fh = font_metrics.lineSpacing() ys = event.posF().y() lineNumber = 0 if event.pos().x() > xofs: pattern = self.pat if self.edit.lang != "python": pattern = self.patNotPython block = self.edit.firstVisibleBlock() viewport_offset = self.edit.contentOffset() page_bottom = self.edit.viewport().height() while block.isValid(): position = self.edit.blockBoundingGeometry( block).topLeft() + viewport_offset if position.y() > page_bottom: break if (position.y() < ys and (position.y() + fh) > ys and pattern.match(str(block.text()))): if not block.blockNumber() in self._endDocstringBlocks: lineNumber = block.blockNumber() + 1 break if (position.y() < ys and (position.y() + fh) > ys and event.button() == Qt.LeftButton): line = block.blockNumber() self.set_breakpoint(line) break elif (position.y() < ys and (position.y() + fh) > ys and event.button() == Qt.RightButton): line = block.blockNumber() self.set_bookmark(line) break block = block.next() if lineNumber > 0: self.code_folding_event(lineNumber)
def headerData(self, section, orientation, role): """ Public method to get header data from the model. @param section section number (integer) @param orientation orientation (Qt.Orientation) @param role role of the data to retrieve (integer) @return requested data """ if role == Qt.SizeHintRole: fm = QFontMetrics(QFont()) height = fm.height() + fm.height() // 3 width = \ fm.width(self.headerData(section, orientation, Qt.DisplayRole)) return QSize(width, height) if orientation == Qt.Horizontal and role == Qt.DisplayRole: try: return self.__headers[section] except IndexError: return None return QAbstractTableModel.headerData(self, section, orientation, role)
def updateSelectionStats(self): highlightsPerClass = {} for s in self.plot.highlightedRings: highlightsPerClass[s.dataClassLabel] = highlightsPerClass.get( s.dataClassLabel, 0) + 1 for b in self.selectionStatBars: num = self.plot.relation.numDatasetsForClass(b.dataClassLabel) if 0 != num: b.setValue( highlightsPerClass.get(b.dataClassLabel, 0) / num * 100) color = self._plotPalette[b.dataClassLabel] pal = b.palette() pal.setColor(QPalette.Highlight, color) b.setPalette(pal) margin = QFontMetrics(b.font()).width("100%") + 5 # thank you Windows, for letting me re-style the full progress bar instead of just using the palette color!! b.setStyleSheet( "QProgressBar {{ text-align: right; border: 1px solid lightgray;" "background:none; border-radius: 2px; margin-right: {}px; }}" "QProgressBar::chunk {{ background-color: rgba({}, {}, {}, {}); }}" .format(margin, color.red(), color.green(), color.blue(), color.alpha()))
def paint(self, painter, option, qidx): painter.save() try: painter.setClipRect(option.rect) painter.translate(option.rect.topLeft()) fm = QFontMetrics(option.font) if option.state & QStyle.State_Selected: painter.setPen(QPen(option.palette.highlightedText(), 1)) else: painter.setPen(QPen(option.palette.text(), 1)) x = self.xmargin for sz, tag in self._positions(option, qidx): painter.drawRoundedRect(x, self.ymargin, sz.width() + 2 * self.xpadding, fm.height(), self.radius, self.radius) painter.drawText(x + self.xpadding, self.ymargin + fm.ascent(), tag) x += sz.width() + self.xmargin + 2 * self.xpadding finally: painter.restore()
def __init__(self, edit): #redraw lock self.locked = False super().__init__() self.lines = 0 self.width = 0 self.minWidth = 3 self.setMinimumSize(QSize(100, 15)) self.edit = edit self.font = self.edit.font() self.fm = QFontMetrics(self.font) self.fontHeight = self.fm.height() self.fontWidth = self.fm.width('0') self.adjustWidth(1)
def draw_text(self, pos, text, font, fg): if not text: return qfont = QFont(font.family) qfont.setPixelSize(font.size) qfont.setBold(FontStyle.bold in font.style) qfont.setItalic(FontStyle.italic in font.style) qfont.setStrikeOut(FontStyle.strike in font.style) qfont.setUnderline(FontStyle.underline in font.style) qfont.setStyleStrategy(QFont.PreferAntialias) metrics = QFontMetrics(qfont) self.__painter.setFont(qfont) self.__set_pen(fg) x = pos.x y = pos.y + metrics.ascent() if '\n' in text: height = metrics.height() for line in text.split('\n'): self.__painter.drawText(QPoint(x, y), line) y += height else: self.__painter.drawText(QPoint(x, y), text)
def paint_name(self, painter: QPainter): """ Paints the name of this gene. """ if not misc_helper.coalesce( groot.data.config.options().lego_view_names, any(x.is_selected for x in self.domain_views.values())): return leftmost_domain = sorted(self.domain_views.values(), key=lambda xx: xx.pos().x())[0] text = str(self.gene) # Add a sigil for outgroups if self.gene.position == gr.EPosition.OUTGROUP: text = "←" + text r = leftmost_domain.window_rect() x = r.left() - DRAWING.TEXT_MARGIN - QFontMetrics( painter.font()).width(text) y = r.top() + r.height() / 2 painter.setPen(DRAWING.DARK_TEXT) painter.drawText(QPointF(x, y), text)
def lineNumberAreaPaintEvent(self, event): painter = QPainter(self.lineNumberArea) painter.fillRect(event.rect(), Qt.lightGray) block = self.firstVisibleBlock() blockNumber = block.blockNumber() top = self.blockBoundingGeometry(block).translated( self.contentOffset()).top() bottom = top + self.blockBoundingRect(block).height() # Just to make sure I use the right font height = QFontMetrics(self.font()).height() while block.isValid() and (top <= event.rect().bottom()): if block.isVisible() and (bottom >= event.rect().top()): number = str(blockNumber + 1) painter.setPen(Qt.black) painter.drawText(0, top, self.lineNumberArea.width(), height, Qt.AlignRight, number) block = block.next() top = bottom bottom = top + self.blockBoundingRect(block).height() blockNumber += 1
def test_node_shape_set_label(mod): """Check that shape is modified when label is changed""" node = mod.Node(226, "") assert node.shape().boundingRect().width() > mod.RADIUS * 2 fm = QFontMetrics(node.font()) label = "very long label" node.setLabel(label) assert(node.label() == label) width = fm.width(label) assert node.boundingRect().width() >= width label = "really really loooooooooooooong label" node.setLabel(label) assert(node.label() == label) assert node.boundingRect().width() >= fm.width(label) assert node.boundingRect().width() > width label = "1" node.setLabel(label) assert node.label() == label assert node.boundingRect().width() < width
def __init__(self, text, parent): QLabel.__init__(self, parent=parent) font = QFont() metric = QFontMetrics(font) size = metric.size(Qt.TextSingleLine, text) image = QImage(size.width() + 12, size.height() + 12, QImage.Format_ARGB32_Premultiplied) image.fill(QColor(0, 0, 0, 0)) font.setStyleStrategy(QFont.ForceOutline) gradient = QLinearGradient(0, 0, 0, image.height() - 1) gradient.setColorAt(0.0, Qt.white) gradient.setColorAt(0.2, QColor(200, 200, 255)) gradient.setColorAt(0.8, QColor(200, 200, 255)) gradient.setColorAt(1.0, QColor(127, 127, 200)) painter = QPainter() painter.begin(image) painter.setRenderHint(QPainter.Antialiasing) painter.setBrush(gradient) painter.drawRoundedRect( QRectF(0.5, 0.5, image.width() - 1, image.height() - 1), 25, 25, Qt.RelativeSize) painter.setFont(font) painter.setBrush(Qt.black) painter.drawText(QRect(QPoint(6, 6), size), Qt.AlignCenter | Qt.AlignVCenter, text) painter.end() self.setPixmap(QPixmap.fromImage(image)) self._label_text = text
def __init__(self, send_tab: 'SendTab'): CompletionTextEdit.__init__(self) ScanQRTextEdit.__init__(self, config=send_tab.config, setText=self._on_input_btn) Logger.__init__(self) self.send_tab = send_tab self.win = send_tab.window self.app = QApplication.instance() self.amount_edit = self.send_tab.amount_e self.setFont(QFont(MONOSPACE_FONT)) document = self.document() document.contentsChanged.connect(self.update_size) fontMetrics = QFontMetrics(document.defaultFont()) self.fontSpacing = fontMetrics.lineSpacing() margins = self.contentsMargins() documentMargin = document.documentMargin() self.verticalMargins = margins.top() + margins.bottom() self.verticalMargins += self.frameWidth() * 2 self.verticalMargins += documentMargin * 2 self.heightMin = self.fontSpacing + self.verticalMargins self.heightMax = (self.fontSpacing * 10) + self.verticalMargins self.c = None self.addPasteButton(setText=self._on_input_btn) self.textChanged.connect(self._on_text_changed) self.outputs = [] # type: List[PartialTxOutput] self.errors = [] # type: List[PayToLineError] self.disable_checks = False self.is_alias = False self.update_size() self.payto_scriptpubkey = None # type: Optional[bytes] self.lightning_invoice = None self.previous_payto = ''
def on_player_media_changed(cls, music_model): artists = music_model['artists'] artists_name = '' for artist in artists: artists_name += artist['name'] title = music_model['name'] + ' - ' + artists_name ControllerApi.desktop_mini.content.set_song_name(music_model['name']) ControllerApi.desktop_mini.content.set_song_singer(artists_name) metrics = QFontMetrics(ViewOp.ui.TOP_WIDGET.font()) title = metrics.elidedText(title, Qt.ElideRight, 300 - 40) ViewOp.ui.SONG_NAME_LABEL.setText(title) ControllerApi.lyric_widget.reset_lyric() ViewOp.ui.SONG_COUNTDOWN_LABEL.setText('00:00') ViewOp.ui.SONG_PROGRESS_SLIDER.setRange(0, ControllerApi.player.duration() / 1000) ControllerApi.desktop_mini.content.set_duration(ControllerApi.player.duration() / 1000) ControllerApi.network_manager.get(QNetworkRequest(QUrl(music_model['album']['picUrl'] + "?param=200y200"))) ControllerApi.network_manager.network_queue.put(ViewOp.set_music_icon) ControllerApi.current_playlist_widget.add_item_from_model(music_model) ControllerApi.current_playlist_widget.focus_cell_by_mid(music_model['id']) ControllerApi.state['current_mid'] = music_model['id'] if MusicModel.mv_available(music_model): ViewOp.ui.PLAY_MV_BTN.show() else: ViewOp.ui.PLAY_MV_BTN.close() if ControllerApi.state['is_login']: if ControllerApi.api.is_favorite_music(music_model['id']): ViewOp.ui.LOVE_SONG_BTN.setChecked(True) ControllerApi.desktop_mini.content.is_song_like = True else: ViewOp.ui.LOVE_SONG_BTN.setChecked(False) ControllerApi.desktop_mini.content.is_song_like = False
def paintEvent(self, event): painter = QPainter(self) painter.fillRect(event.rect(), Qt.white) painter.setFont(self.displayFont) redrawRect = event.rect() beginRow = redrawRect.top() // self.squareSize endRow = redrawRect.bottom() // self.squareSize beginColumn = redrawRect.left() // self.squareSize endColumn = redrawRect.right() // self.squareSize painter.setPen(Qt.gray) for row in range(beginRow, endRow + 1): for column in range(beginColumn, endColumn + 1): painter.drawRect(column * self.squareSize, row * self.squareSize, self.squareSize, self.squareSize) fontMetrics = QFontMetrics(self.displayFont) painter.setPen(Qt.black) for row in range(beginRow, endRow + 1): for column in range(beginColumn, endColumn + 1): key = row * self.columns + column painter.setClipRect(column * self.squareSize, row * self.squareSize, self.squareSize, self.squareSize) if key == self.lastKey: painter.fillRect(column * self.squareSize + 1, row * self.squareSize + 1, self.squareSize, self.squareSize, Qt.red) key_ch = self._chr(key) painter.drawText( column * self.squareSize + (self.squareSize / 2) - fontMetrics.width(key_ch) / 2, row * self.squareSize + 4 + fontMetrics.ascent(), key_ch)
def __init__(self, **kwargs): super().__init__(**kwargs) self.setLayout(QVBoxLayout()) self.layout().setAlignment(Qt.AlignTop) self.groupBox = QGroupBox(self) self.groupBox.resize(self.size()) self.groupBox.setTitle( translate('Equalizer10Settings', '10 Bands Equalizer (IIR)')) self.groupBox.setLayout(QGridLayout()) self.groupBox.layout().setVerticalSpacing(0) self.layout().addWidget(self.groupBox) self.sliders = {} for n in range(10): label = QLabel(self.groupBox) label.setMinimumWidth(QFontMetrics(label.font()).width('000')) label.setAlignment(QtCore.Qt.AlignCenter) label.setNum(0) self.groupBox.layout().addWidget(label, 0, n) slider = QSlider(self.groupBox) slider.setRange(-24, 12) slider.setPageStep(1) slider.setValue(0) slider.setOrientation(QtCore.Qt.Vertical) slider.valueChanged.connect(label.setNum) self.groupBox.layout().addWidget(slider, 1, n) self.groupBox.layout().setAlignment(slider, QtCore.Qt.AlignHCenter) self.sliders['band' + str(n)] = slider fLabel = QLabel(self.groupBox) fLabel.setStyleSheet('font-size: 8pt;') fLabel.setAlignment(QtCore.Qt.AlignCenter) fLabel.setText(self.FREQ[n]) self.groupBox.layout().addWidget(fLabel, 2, n)
def __init__(self, *args): QTextEdit.__init__(self) # Set text to be monospace doc = self.document() font = doc.defaultFont() font.setFamily("Courier New") doc.setDefaultFont(font) # Set the background color to green palette = self.palette() palette.setColor(self.backgroundRole(), QColor(200, 255, 200)) self.setPalette(palette) self.setAutoFillBackground(True) # Set the height of the box # 10 Lines tall nRows = 10 doc = self.document() fm = QFontMetrics(doc.defaultFont()) margins = self.contentsMargins() height = fm.lineSpacing() * nRows + 2 * (doc.documentMargin( ) + self.frameWidth()) + margins.top() + margins.bottom() self.setFixedHeight(height)
def setText(self, txt): self.sourceText = self.getWordWrap(txt) self.text.setText(self.sourceText) QF = QFont() QFM = QFontMetrics(QF) elidedText = QFM.elidedText(self.sourceText, Qt.TextWordWrap | Qt.ElideRight, 50) self.text.setText(elidedText) #bound = QFM.boundingRect(0, 0, 64, 300, Qt.TextWordWrap | Qt.AlignCenter, self.getWordWrap(txt)) self.text.move(0, self.icon.height()) """ if bound.size().width() > 100: self.text.setFixedSize(100, bound.size().height()+2) else: self.text.setFixedSize(bound.size().width()+15, bound.size().height()+2) """ #print(bound.width()) self.leaveEvent(None) self.update()
def paint(self, painter, option, index): extra = index.data(Qt.UserRole + 1) if not extra: return QStyledItemDelegate.paint(self, painter, option, index) else: if option.state & QStyle.State_Selected: painter.fillRect( option.rect, option.palette.color(QPalette.Inactive, QPalette.Highlight)) title = index.data() extra = " - {}".format(extra) painter.drawText(option.rect, Qt.AlignLeft, title) fm = QFontMetrics(option.font) w = fm.width(title) r = QRect(option.rect) r.setLeft(r.left() + w) painter.save() painter.setPen(Qt.gray) painter.drawText(r, Qt.AlignLeft, extra) painter.restore()
def build_labels(self): font = QFont('Verdana', 10) fm = QFontMetrics(font) for count in range(LAST_ROW + 1): number = str(count + 1) number_label = QGraphicsSimpleTextItem(number) x = -fm.width(number) - SQUARE_SIZE / 8 y = count * SQUARE_SIZE + (SQUARE_SIZE - fm.height()) / 2 number_label.setPos(x, y) number_label.setFont(font) number_label.setBrush(QBrush(Qt.white)) self._labels[(x, y)] = number_label letter = chr(count + ord('A')) letter_label = QGraphicsSimpleTextItem(letter) x = count * SQUARE_SIZE + (SQUARE_SIZE - fm.width(letter)) / 2 y = -fm.height() - SQUARE_SIZE / 8 letter_label.setPos(x, y) letter_label.setFont(font) letter_label.setBrush(QBrush(Qt.white)) self._labels[(x, y)] = letter_label self.scene.addItem(number_label) self.scene.addItem(letter_label)
def init_ui(self): for x in range(0, self.grid_size): self.tiles.append([]) for y in range(0, self.grid_size): # Make tile textbox = LineEdit(self) textbox.setGeometry(x * self.cell_size, y * self.cell_size, self.cell_size, self.cell_size) textbox.setAlignment(QtCore.Qt.AlignCenter) font = textbox.font() font.setPointSize(4 * self.cell_size / self.grid_size) # Resize font to fit 3 characters metrics = QFontMetrics(font) factor = textbox.rect().width() / metrics.width("999") font.setPointSize(font.pointSize() * factor - 5) textbox.setFont(font) textbox.textChanged.connect(self.update_tiles) self.tiles[x].append(textbox) self.tiles[0][0].setText("1")
def redraw_legend(self, force_show=False): if not (force_show or self.always_show_symbols_legend): self.hide_legend() return num_captions = len(self.centers) + 1 if num_captions != len(self.captions): self.clear_legend() fmt = "{0:0" + str(self.bits_per_symbol) + "b}" for i in range(num_captions): font = QFont() font.setPointSize(16) font.setBold(True) self.captions.append(self.addSimpleText(fmt.format(i), font)) view_rect = self.parent().view_rect() # type: QRectF padding = 0 fm = QFontMetrics(self.captions[0].font()) for i, caption in enumerate(self.captions): caption.show() scale_x, scale_y = util.calc_x_y_scale( self.separation_areas[i].rect(), self.parent()) try: caption.setPos( view_rect.x() + view_rect.width() - fm.width(caption.text()) * scale_x, self.centers[i] + padding) except IndexError: caption.setPos( view_rect.x() + view_rect.width() - fm.width(caption.text()) * scale_x, self.centers[i - 1] - padding - fm.height() * scale_y) caption.setTransform(QTransform.fromScale(scale_x, scale_y), False)
def __init__(self, scene, parent=None, show_info=True): super(HVView, self).__init__(scene, parent) self.parent = parent self.show_info = show_info self.setDragMode(QGraphicsView.ScrollHandDrag) self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse) self.setResizeAnchor(QGraphicsView.AnchorUnderMouse) self.setMouseTracking(True) self.zoom = 1 self.rotate = 0 self.font = QFont('times', 15) font_metrics = QFontMetrics(self.font) self.text_height = font_metrics.height() # For selection rect (using rubber band) self.rubber_band = QRubberBand(QRubberBand.Rectangle, self) # the origin position of rubber band self.rubber_band_origin = QPoint() # indicate whether rubber band could be changed under mouseMoveEvent self.rubber_band_changable = False self.rect_top_left = (0, 0) self.setViewportUpdateMode(0)
def splash_screen(): path = pkg_resources.resource_filename( __name__, "icons/orange-splash-screen.png") pm = QPixmap(path) version = QCoreApplication.applicationVersion() size = 21 if len(version) < 5 else 16 font = QFont("Helvetica") font.setPixelSize(size) font.setBold(True) font.setItalic(True) font.setLetterSpacing(QFont.AbsoluteSpacing, 2) metrics = QFontMetrics(font) br = metrics.boundingRect(version).adjusted(-5, 0, 5, 0) br.moveCenter(QPoint(436, 224)) p = QPainter(pm) p.setRenderHint(QPainter.Antialiasing) p.setRenderHint(QPainter.TextAntialiasing) p.setFont(font) p.setPen(QColor("#231F20")) p.drawText(br, Qt.AlignCenter, version) p.end() return pm, QRect(88, 193, 200, 20)
def enterEvent(self, event): self.hover = True self.mouseHover.emit() self.opacity = 1 self.btn_update = True self.text.setText(self.sourceText) QF = QFont() QFM = QFontMetrics(QF) bound = QFM.boundingRect(0, 0, 100, 0, Qt.TextWordWrap | Qt.AlignCenter, self.text.text()) self.setFixedHeight(80 + bound.height()) self.main.setFixedHeight(self.height() - 5) self.text.setFixedHeight(bound.height()) #self.setFixedHeight(320) self.raise_() self.update() self.triggering()
def getMinimumWidth(self, items=None): fm = QFontMetrics(self.font()) opt = QStyleOptionComboBox() style = self.style() mw = self.maxWidth if items is not None: for str in items: opt.currentText = str sz = QSize(fm.width(opt.currentText), fm.height()) mw = max( mw, style.sizeFromContents(QStyle.CT_ComboBox, opt, sz, self).width()) elif mw == 0 and self.count() > 0: for i in range(0, self.count()): opt.currentText = self.itemText(i) sz = QSize(fm.width(opt.currentText), fm.height()) mw = max( mw, style.sizeFromContents(QStyle.CT_ComboBox, opt, sz, self).width()) elif mw == 0: opt.currentText = ' ' sz = QSize(fm.width(opt.currentText), fm.height()) mw = max( mw, style.sizeFromContents(QStyle.CT_ComboBox, opt, sz, self).width()) self.maxWidth = mw return mw
def drawDigitalValue(self): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) painter.translate(self.width() / 2, self.height() / 2) font = QFont(self.digitalValueFontName, self.digitalValueFontSize) fm = QFontMetrics(font) penShadow = QPen() penShadow.setBrush(self.digitalValueColor) painter.setPen(penShadow) digitalValueRadius = self.widgetDiameter / 2 * self.digitalValueRadius text = str(int(self.gaugeValue)) w = fm.width(text) + 1 h = fm.height() painter.setFont( QFont(self.digitalValueFontName, self.digitalValueFontSize)) angleEnd = float(self.gaugeRotation + self.gaugeArcAngle - 360) angle = (angleEnd - self.gaugeRotation) / 2 + self.gaugeRotation x = digitalValueRadius * math.cos(math.radians(angle)) y = digitalValueRadius * math.sin(math.radians(angle)) offset = 20 if self.gaugeValueUnits else 0 text = [ x - int(w / 2) - offset, y - int(h / 2), int(w), int(h), Qt.AlignCenter, text ] painter.drawText(text[0], text[1], text[2], text[3], text[4], text[5]) self.drawDigitalValueUnits()