我们从Python开源项目中,提取了以下25个代码示例,用于说明如何使用PyQt5.QtGui.QFontMetrics()。
def paintEvent(self, event): sineTable = (0, 38, 71, 92, 100, 92, 71, 38, 0, -38, -71, -92, -100, -92, -71, -38) metrics = QFontMetrics(self.font()) x = (self.width() - metrics.width(self.text)) / 2 y = (self.height() + metrics.ascent() - metrics.descent()) / 2 color = QColor() painter = QPainter(self) for i, ch in enumerate(self.text): index = (self.step + i) % 16 color.setHsv((15 - index) * 16, 255, 191) painter.setPen(color) painter.drawText(x, y - ((sineTable[index] * metrics.height()) / 400), ch) x += metrics.width(ch)
def on_table_selection_changed(self): min_row, max_row, start, end = self.ui.tableMessages.selection_range() if min_row == -1: self.ui.lEncodingValue.setText("-") # self.ui.lEncodingValue.setToolTip("") self.label_list_model.message = None return container = self.table_model.protocol message = container.messages[min_row] self.label_list_model.message = message decoder_name = message.decoder.name metrics = QFontMetrics(self.ui.lEncodingValue.font()) elidedName = metrics.elidedText(decoder_name, Qt.ElideRight, self.ui.lEncodingValue.width()) self.ui.lEncodingValue.setText(elidedName) self.ui.lEncodingValue.setToolTip(decoder_name) self.ui.cBoxModulations.blockSignals(True) self.ui.cBoxModulations.setCurrentIndex(message.modulator_index) self.show_modulation_info() self.ui.cBoxModulations.blockSignals(False)
def setFont(self, font): """Sets the font to use in the hex editor. :param font: Font to use. :type font: QFont """ # Set font super().setFont(font) # Calculate font width and height fm = QFontMetrics(font) self.font_width = fm.width(" ") self.font_height = int(fm.height()/2) - 1 # Recalc vars since font has changed self._adjust() self.viewport().update()
def adjust_size(self): """ A way to reduce the height of the TextEdit. Could be implemented better. Based on: https://stackoverflow.com/questions/9506586/qtextedit-resize-to-fit """ font = self.document().defaultFont() # or another font if you change it fontMetrics = QtGui.QFontMetrics(font) # a QFontMetrics based on our font textSize = fontMetrics.size(0, self._before) # textWidth = textSize.width() + 30 # constant may need to be tweaked textHeight = textSize.height() + 30 # constant may need to be tweaked self.setMaximumHeight(textHeight) # print('TextEdit Width/Height: {}/{}'.format(self.width(), self.height())) # print('Text Width/Height: {}/{}'.format(textWidth, textHeight)) # print('DocSize:', self.document().size())
def __init__( self, app, parent, name=None ): super().__init__( parent ) self.name = name self.style_normal = self.STYLE_DEFAULT self.style_line_numbers = self.STYLE_LASTPREDEFINED + 1 self.style_line_numbers_for_diff = self.STYLE_LASTPREDEFINED self.emptyUndoBuffer() self.setMarginWidth( 0, 0 ) self.setMarginWidth( 1, 0 ) self.setMarginWidth( 2, 0 ) # make some styles self.styleSetFromSpec( self.style_normal, 'size:%d,face:%s,fore:#000000,back:#e0e0e0' % (wb_config.point_size, wb_config.face) ) self.styleSetFromSpec( self.style_line_numbers, 'size:%d,face:%s,fore:#000000,back:#f0f0f0' % (wb_config.point_size, wb_config.face) ) self.styleSetFromSpec( self.style_line_numbers_for_diff, 'size:%d,face:%s,fore:#000000,back:#d0d0d0' % (wb_config.point_size, wb_config.face) ) # Calculate space for 6 digits font = QtGui.QFont( wb_config.face, wb_config.point_size ) self.setFont( font ) fontmetrics = QtGui.QFontMetrics( font ) width = fontmetrics.width( '123456' ) self.setScrollWidth( width ) self.setMaximumWidth( width ) self.setMinimumWidth( width ) # no scroll bars on the line number control self.setVScrollBar( False ) self.setHScrollBar( False )
def __init__(self, scene=None): if scene is None: scene = TurtleScene() self._scene = scene super().__init__(scene) transform = QtGui.QTransform( 1, 0, 0, -1, # Revert y, so it uses the standard axis convention in maths 0, 0 ) self.setTransform(transform) self._zoomfactor = 1.2 # This will crash if I put it in the module namespace, probably # because the QApplication instance does not exist yet _LABEL_HEIGHT = QtGui.QFontMetrics( _LABEL_FONT).height() + 2 * _LABEL_PADDING w = self._posLabel = QtWidgets.QLabel(self) # http://stackoverflow.com/questions/7928519/how-to-make-the-qlabel-background-semi-transparent # Fourth parameter in color tuple is alpha: 0-transparent; 255-opaque w.setStyleSheet('color: rgba(0, 0, 0, 196); ' 'background-color: rgba(0, 0, 0, 0);' 'padding: %d' % _LABEL_PADDING) w.setAlignment(QtCore.Qt.AlignRight) w.setFont(_LABEL_FONT) w.setGeometry(0, 0, 100, _LABEL_HEIGHT) self._updatePosLabelText((0, 0)) self._updatePosLabelPosition()
def lock(self): """ Sets the default properties for the Python lexer. """ # Lexer Initialization lexer = QsciLexerPython(self.ui.code_editor) lexer.setDefaultFont(self.font) self.ui.code_editor.setLexer(lexer) # Auto Completion api = QsciAPIs(lexer) for var in dir(builtins): if not (var[0] == "_"): api.add(var) api.prepare() self.ui.code_editor.setAutoCompletionThreshold(1) self.ui.code_editor.setAutoCompletionSource(QsciScintilla.AcsAPIs) # Indentation self.ui.code_editor.setIndentationWidth(4) # Font Settings font_metrics = QFontMetrics(self.font) self.ui.code_editor.setMinimumSize( int(font_metrics.width("0" * 80)), 0 )
def __init__(self, controller, parent=None): super(MapSpecificOptions, self).__init__(parent) self.setupUi(self) self._controller = controller current_model = self._controller.get_model() self._current_map = None self.colormap.addItems(['-- Use global --'] + current_model.get_config().get_available_colormaps()) self.colormap.currentIndexChanged.connect(self._update_colormap) self.data_clipping_min.valueChanged.connect(self._update_clipping_min) self.data_clipping_max.valueChanged.connect(self._update_clipping_max) self.data_scale_min.valueChanged.connect(self._update_scale_min) self.data_scale_max.valueChanged.connect(self._update_scale_max) self.data_set_use_scale.stateChanged.connect(self._set_use_scale) self.use_data_scale_min.stateChanged.connect(self._set_use_data_scale_min) self.use_data_scale_max.stateChanged.connect(self._set_use_data_scale_max) self.data_set_use_clipping.stateChanged.connect(self._set_use_clipping) self.use_data_clipping_min.stateChanged.connect(self._set_use_data_clipping_min) self.use_data_clipping_max.stateChanged.connect(self._set_use_data_clipping_max) self._title_timer = TimedUpdate(self._update_map_title) self.map_title.textChanged.connect(lambda: self._title_timer.add_delayed_callback(500)) self.map_title.setFixedHeight(QFontMetrics(self.map_title.font()).lineSpacing() * 3) self._colorbar_label_timer = TimedUpdate(self._update_colorbar_label) self.data_colorbar_label.textChanged.connect(lambda : self._colorbar_label_timer.add_delayed_callback(500)) self.data_colorbar_label.setFixedHeight(QFontMetrics(self.data_colorbar_label.font()).lineSpacing() * 3) self.info_Clipping.set_collapse(True) self._auto_enable_scale_min = False self._auto_enable_scale_max = False self._auto_enable_clipping_min = False self._auto_enable_clipping_max = False self.reset() self._update_scaling_delays()
def __init__(self, parent=None): super().__init__(parent) s = Settings() browser_font_size = int(s.value('browser_font', 9)) self.title_font = QtGui.QFont('Open Sans Extrabold', browser_font_size) self.summary_font = QtGui.QFont('Open Sans', browser_font_size * 0.95, QtGui.QFont.Bold) self.title_font_metrics = QtGui.QFontMetrics(self.title_font) self.summary_font_metrics = QtGui.QFontMetrics(self.title_font) self.last_icon_size = self.parent().iconSize().height()
def _set_building_text(self, labelCtrl, text): metrics = QtGui.QFontMetrics(labelCtrl.font()) elidedText = metrics.elidedText(text, Qt.ElideRight, labelCtrl.width()) labelCtrl.setText(elidedText)
def __init__(self, parent=None): super(RenderArea, self).__init__(parent) newFont = self.font() newFont.setPixelSize(12) self.setFont(newFont) fontMetrics = QFontMetrics(newFont) self.xBoundingRect = fontMetrics.boundingRect("x") self.yBoundingRect = fontMetrics.boundingRect("y") self.shape = QPainterPath() self.operations = []
def __init__(self, parent=None): self.draw_grid = False self.font_metrics = QFontMetrics(QFont()) self.center_freq = 433.92e6 self.frequencies = [] self.frequency_marker = None super().__init__(parent) self.setSceneRect(0,0,10,10)
def draw_frequency_marker(self, x_pos, frequency): if frequency is None: self.clear_frequency_marker() return y1 = self.sceneRect().y() y2 = self.sceneRect().y() + self.sceneRect().height() if self.frequency_marker is None: pen = QPen(constants.LINECOLOR, Qt.FlatCap) self.frequency_marker = [None, None] self.frequency_marker[0] = self.addLine(x_pos, y1, x_pos, y2, pen) self.frequency_marker[1] = self.addSimpleText("") self.frequency_marker[1].setBrush(QBrush(constants.LINECOLOR)) font = QFont() font.setBold(True) font.setPointSize(int(font.pointSize() * 1.25)+1) self.frequency_marker[1].setFont(font) self.frequency_marker[0].setLine(x_pos, y1, x_pos, y2) scale_x, scale_y = self.__calc_x_y_scale(self.sceneRect()) self.frequency_marker[1].setTransform(QTransform.fromScale(scale_x, scale_y), False) self.frequency_marker[1].setText("Tune to " + Formatter.big_value_with_suffix(frequency, decimals=3)) font_metric = QFontMetrics(self.frequency_marker[1].font()) text_width = font_metric.width("Tune to") * scale_x text_width += (font_metric.width(" ") * scale_x) / 2 self.frequency_marker[1].setPos(x_pos-text_width, 0.95*y1)
def resize_columns(self): if not self.isVisible(): return f = QFontMetrics(self.font()) w = f.widthChar("0") + 2 for i in range(10): self.setColumnWidth(i, 3 * w) QApplication.instance().processEvents() for i in range(9, self.model().columnCount()): self.setColumnWidth(i, w * (len(str(i + 1)) + 1)) if i % 10 == 0: QApplication.instance().processEvents()
def setAllFonts(self, family='monospace', size=10, fixedpitch=True): """Set the font of all visible elements in the text editor. This syncronizes the font in the main text area with the margins and calltips. """ self.fontfamily = family self.fontsize = size self.fontfixedpitch = True # Configure editor font size font = QFont() font.setFamily(family) font.setFixedPitch(fixedpitch) font.setPointSize(size) self.setFont(font) # Margin 0 is used for line numbers fontmetrics = QtGui.QFontMetrics(font) self.setMarginsFont(font) self.setMarginWidth(0, fontmetrics.width('___') + 0) self.setMarginWidth(1, 0) self.setMarginLineNumbers(0, True) # Change lexer font bfamily = bytes(family, encoding='utf8') lexer = self.lexer() if lexer is not None: font_bold = QFont(font) font_bold.setBold(True) for style in self.LEXER_STYLES.values(): if style in self.BOLD_STYLES: lexer.setFont(font_bold, style) else: lexer.setFont(font, style) self.SendScintilla(Qsci.QsciScintilla.SCI_STYLESETFONT, 1, bfamily)
def __init__(self, parent=None, width=5, height=0.4): fig = mpl.figure.Figure(figsize=(width, height), dpi=96) self.fig = fig Canvas.__init__(self, fig) bg = self.palette().window().color() cl = (bg.redF(), bg.greenF(), bg.blueF()) # fig.set_edgecolor(cl) fig.set_facecolor(cl) self.setParent(parent) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) self.updateGeometry() fm = QtGui.QFontMetrics(self.font()) self.fontsize = int(fm.height()) / 1.25
def __init__(self, parent=None, width=6, height=5): fig = mpl.figure.Figure(figsize=(width, height), dpi=96) self.fig = fig self.axes = fig.add_subplot(111) self.fig.subplots_adjust(left=0.15, right=0.97, bottom=0.15, top=0.97) # self.axes.hold(False) # clear axes every time plot() is called Canvas.__init__(self, fig) self.setParent(parent) self.updateGeometry() fm = QtGui.QFontMetrics(self.font()) self.fontsize = int(fm.height()) / 1.25
def __init__(self, parent, model): super(ExtractorWidget, self).__init__(parent) self.setAttribute(Qt.WA_DeleteOnClose) # This is required to stop background timers! self.on_remove = lambda: None self._model = model self._update_timer = QTimer(self) self._update_timer.setSingleShot(False) self._update_timer.timeout.connect(self._update) self._update_timer.start(200) self._delete_button = make_icon_button('trash-o', 'Remove this extractor', self, on_clicked=self._do_remove) self._color_button = make_icon_button('paint-brush', 'Change plot color', self, on_clicked=self._change_color) self._color_button.setFlat(True) _set_color(self._color_button, QPalette.Button, model.color) self._extraction_expression_box = QLineEdit(self) self._extraction_expression_box.setToolTip('Extraction expression') self._extraction_expression_box.setFont(get_monospace_font()) self._extraction_expression_box.setText(model.extraction_expression.source) self._extraction_expression_box.textChanged.connect(self._on_extraction_expression_changed) self._extraction_expression_box.setCompleter( _make_expression_completer(self._extraction_expression_box, model.data_type_name)) self._error_label = make_icon_button('warning', 'Extraction error count; click to reset', self, on_clicked=self._reset_errors) self._reset_errors() def box(text, tool_tip): w = QLineEdit(self) w.setReadOnly(True) w.setFont(get_monospace_font()) w.setText(str(text)) w.setToolTip(tool_tip) fm = QFontMetrics(w.font()) magic_number = 10 text_size = fm.size(0, w.text()) w.setMinimumWidth(text_size.width() + magic_number) return w layout = QHBoxLayout(self) layout.addWidget(self._delete_button) layout.addWidget(self._color_button) layout.addWidget(box(model.data_type_name, 'Message type name')) layout.addWidget(box(' AND '.join([x.source for x in model.filter_expressions]), 'Filter expressions')) layout.addWidget(self._extraction_expression_box, 1) layout.addWidget(self._error_label) layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout)
def setupShapes(self): truck = QPainterPath() truck.setFillRule(Qt.WindingFill) truck.moveTo(0.0, 87.0) truck.lineTo(0.0, 60.0) truck.lineTo(10.0, 60.0) truck.lineTo(35.0, 35.0) truck.lineTo(100.0, 35.0) truck.lineTo(100.0, 87.0) truck.lineTo(0.0, 87.0) truck.moveTo(17.0, 60.0) truck.lineTo(55.0, 60.0) truck.lineTo(55.0, 40.0) truck.lineTo(37.0, 40.0) truck.lineTo(17.0, 60.0) truck.addEllipse(17.0, 75.0, 25.0, 25.0) truck.addEllipse(63.0, 75.0, 25.0, 25.0) clock = QPainterPath() clock.addEllipse(-50.0, -50.0, 100.0, 100.0) clock.addEllipse(-48.0, -48.0, 96.0, 96.0) clock.moveTo(0.0, 0.0) clock.lineTo(-2.0, -2.0) clock.lineTo(0.0, -42.0) clock.lineTo(2.0, -2.0) clock.lineTo(0.0, 0.0) clock.moveTo(0.0, 0.0) clock.lineTo(2.732, -0.732) clock.lineTo(24.495, 14.142) clock.lineTo(0.732, 2.732) clock.lineTo(0.0, 0.0) house = QPainterPath() house.moveTo(-45.0, -20.0) house.lineTo(0.0, -45.0) house.lineTo(45.0, -20.0) house.lineTo(45.0, 45.0) house.lineTo(-45.0, 45.0) house.lineTo(-45.0, -20.0) house.addRect(15.0, 5.0, 20.0, 35.0) house.addRect(-35.0, -15.0, 25.0, 25.0) text = QPainterPath() font = QFont() font.setPixelSize(50) fontBoundingRect = QFontMetrics(font).boundingRect("Qt") text.addText(-QPointF(fontBoundingRect.center()), font, "Qt") self.shapes = (clock, house, text, truck) self.shapeComboBox.activated.connect(self.shapeSelected)