def rebuild( self ): """ Rebuilds the path for this connection based on the given connection \ style parameters that have been set. :return <QPainterPath> """ # create the path path = self.rebuildPath() self._polygons = self.rebuildPolygons(path) if ( self._textItem ): point = path.pointAtPercent(0.5) metrics = QFontMetrics(self._textItem.font()) point.setY(point.y() - metrics.height() / 2.0) self._textItem.setPos(point) # create the path for the item for poly in self._polygons: path.addPolygon(poly) # unmark as dirty self.setDirty(False) return path
def paintEvent( self, event ): painter = QPainter(self) metrics = QFontMetrics(self.font()) elided = metrics.elidedText(self.text(), QtCore.Qt.ElideLeft, self.width()) painter.drawText(self.rect(), self.alignment(), elided)
def adjustFont(self): # --- fetch current parameters ---- f = self.font() cr = self.contentsRect() if self.maxFont is not None: maximum = self.maxFont.pointSize() else: maximum = self.font().pointSize() # --- find the font size that fits the contentsRect --- fs = 1 while True: f.setPointSize(fs) br = QFontMetrics(f).boundingRect(self.text()) if br.height() <= cr.height() and br.width() <= cr.width(): fs += 1 else: if self.wordWrap() == False: wouldfit = (max(fs - 1, 1)) # if the length have to fit into the label if wouldfit > maximum: wouldfit = maximum f.setPointSize(wouldfit) # if wordwrap is wanted by the user... he expects wordwrap. else: wouldfit = max(fs - 1, 1)*1.5 if wouldfit > maximum: wouldfit = maximum f.setPointSize(wouldfit) # if wordwrap is wanted by the user... he expects wordwrap. #f.setPointSize(max(fs - 1, 1)*1.5) # if wordwrap is wanted by the user... he expects wordwrap. break # --- update font size --- self.setFont(f)
def text_size ( self, text ): """ Returns the size (dx,dy) of the specified text using the current font. """ rect = QFontMetrics( self.font ).boundingRect( text ) return ( rect.width(), rect.height() )
def paintEvent(self, event): painter = QPainter(self) metrics = QFontMetrics(self.font()) elided = metrics.elidedText(self.text(), Qt.ElideRight, self.width()) painter.drawText(self.rect(), self.alignment(), elided)
def splash_screen(): """ """ pm = QPixmap( pkg_resources.resource_filename( __name__, "icons/orange-splash-screen.png") ) 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 _open_refinement_folder(self, path): """ Reads the refinement folder, setup the folder daemon and signals :param path: Path to refinement folder """ if path != '': #for i in reversed(range(self.root.childCount())): # self.root.removeChild(self.root.child(i)) name = os.path.basename(path) qname = QString(name) root = QtGui.QTreeWidgetItem([str(path)]) self.root_items_path_dictionary[str(path)] = root self.tree.addTopLevelItem(root) fm = QFontMetrics(self.font) w = fm.width(path) self.tree.setMinimumWidth(w + 150) #self.root.setText(0, qname) self.reader.sig_readfolders.emit(path) self.monitor = MonitorRefinementFolder(path, self.sig_update_tree, self) self.timer = QTimer(self) self.timer.timeout.connect(self.monitor.update) self.timer.start(2000)
def _updateFontSize(self): from ..app import APP_INSTANCE font = self.view.font() font.setPointSize(APP_INSTANCE.prefs.tableFontSize) self.view.setFont(font) fm = QFontMetrics(font) self.view.verticalHeader().setDefaultSectionSize(fm.height()+2)
def setup(self): # Set the default font font = QFont() font.setFamily('Courier') font.setFixedPitch(True) font.setPointSize(10) self.setFont(font) self.setMarginsFont(font) fontmetrics = QFontMetrics(font) self.setMarginsFont(font) self.setMarginWidth(0, fontmetrics.width('0000')) self.setMarginLineNumbers(0, True) self.setMarginsBackgroundColor(QColor('#cccccc')) self.setMarginSensitivity(1, True) self.marginClicked.connect(self.on_margin_clicked) self.markerDefine(QsciScintilla.RightTriangle, self.ARROW_MARKER_NUM) self.setMarkerBackgroundColor(QColor('#ee1111'), self.ARROW_MARKER_NUM) self.markerDefine(QsciScintilla.Circle, self.REC_MARKER_NUM) self.setMarkerBackgroundColor(QColor('#87CEEB'), self.REC_MARKER_NUM) self.setBraceMatching(QsciScintilla.SloppyBraceMatch) self.setCaretLineVisible(True) self.setCaretLineBackgroundColor(QColor('#FFA07A')) self.my_lexer = OrLexer(self) self.setLexer(self.my_lexer) self.setAutoCompletionThreshold(1) self.setAutoCompletionSource(QsciScintilla.AcsAPIs) self.tracking_marker = None
def __init__(self,parent, font_name, font_size, cols, rows, colorscheme): super().__init__(parent) self.callback_scrollbar= None # # determine font metrics and terminal window size in pixel # font= QFont(font_name) font.setPixelSize(font_size) metrics= QFontMetrics(font) font_width=metrics.width("A") font_height=metrics.height() width= font_width*cols height= int(font_height* rows) # # create terminal window and scrollbar # self.hbox= QHBoxLayout() self.terminalwidget= QTerminalWidget(self,font_name,font_size,font_height, width,height, colorscheme) self.hbox.addWidget(self.terminalwidget) self.hbox.setAlignment(self.terminalwidget,Qt.AlignLeft) self.scrollbar= QScrollBar() self.hbox.addWidget(self.scrollbar) self.hbox.setAlignment(self.scrollbar,Qt.AlignLeft) self.setLayout(self.hbox) # # initialize scrollbar # self.scrollbar.valueChanged.connect(self.do_scrollbar) self.scrollbar.setEnabled(False)
def show_completions(self, completions, parent): self.last_completions = completions self.parent = parent self.clear() if not completions: self.hide() return maxcomp = max(map(len, completions)) total = sum(map(len, completions)) rowcol = math.ceil(math.sqrt(maxcomp)) log.debug("completions=%s max completion has len %d, total %d, rowcol=%d", completions, maxcomp, total, rowcol) the_completions = self.last_completions[:] if self.cur_position >= len(the_completions): self.cur_position = len(the_completions) - 1 if len(the_completions) > 0: the_completions[self.cur_position] = "<b>" + the_completions[self.cur_position] + "</b>" self.setText('<br>'.join(the_completions)) p = parent.mapToGlobal(QPoint(0,0)) self.show() ph = parent.height() pw = parent.width() mh = self.height() mw = self.width() self.move(QPoint(p.x() + (pw-mw)/2, p.y() + (ph-mh)/2)) font = self.font() metrics = QFontMetrics(font) log.debug("chwidth=%d h=%d", metrics.averageCharWidth(), metrics.height())
def updateAlexaLogCoords(self): self.edit._alexaLogIconsCoords = [] # block = self.edit.document().findBlock(0) block = self.edit.firstVisibleBlock() line_count = block.blockNumber() pat = re.compile("\s*#Alexa Log") viewport_offset = self.edit.contentOffset() while block.isValid(): line_count += 1 # maxLine = math.ceil(math.log10(self.edit.blockCount())) font_metrics = QFontMetrics(self.edit.document().defaultFont()) position = self.edit.blockBoundingGeometry(block).topLeft() + viewport_offset width = self.edit.blockBoundingGeometry(block).width() x = 2 + viewport_offset.x() if pat.match(block.text()): try: if self.edit.useTabs: # x += block.text().index("#") * (font_metrics.width('.') * self.edit.indent) x += block.text().index(" #") * (font_metrics.width(".") * self.edit.indent) else: # x += block.text().index("#") * font_metrics.width('.') x += block.text().index(" #") * font_metrics.width(".") except: pass if block.isVisible(): # da notare che il blocco è la riga e non il blocco compreso tra i tag di Al'exa self.edit._alexaLogIconsCoords.append((x, position.y(), width, line_count)) block = block.next()
def paint_text(self, QPainter): """ Render the node text (commit sha and label) :param QPainter: interface to the canvas """ # Set up font and text settings text_font = QFont() text_font.setPointSize(NODE_TEXT_FONT_SIZE) QPainter.setFont(text_font) QPainter.setPen(NODE_TEXT_COLOR) # Measure size of strings so they can be positioned properly font_metrics = QFontMetrics(text_font) label_text_width = font_metrics.width(NODE_LABEL_TEXT) sha_text_width = font_metrics.width(self.commit.sha.get_string_of_length(NODE_SHA_LENGTH)) # Position and render text label_margin = (NODE_WIDTH - label_text_width) / 2 label_position = QPointF(label_margin, 15) QPainter.drawText(label_position, NODE_LABEL_TEXT) sha_margin = (NODE_WIDTH - sha_text_width) / 2 sha_position = QPointF(sha_margin, 25) QPainter.drawText(sha_position, self.commit.sha.get_string_of_length(NODE_SHA_LENGTH))
def __draw(self, start_page, simulate=False): vpos = 0 vpos += self.printer.drawHCenteredTitle(tr('Table of contents'), vpos) vpos += 10 for row in self.table: if row['section']: vpos += 2 size = row['size'] fontmetrics = QFontMetrics(QFont(self.printer.FONT_NAME, size)) if vpos + fontmetrics.height() >= self.printer.height(): vpos = 10 if not simulate: self.printer.newPage() else: start_page += 1 if not simulate: page_num = row['page_num'] + start_page title = row['title'] num_w = fontmetrics.width(unicode(page_num)) self.printer.drawText(title + '.' * 300, vpos, halign=Qt.AlignLeft, size=size, width=self.printer.width() - num_w) self.printer.drawText(unicode(page_num), vpos, halign=Qt.AlignRight, size=size) vpos += fontmetrics.height() return start_page
def init_gui(self): """ Initializes form widgets """ source_names = self.prefix_source_names() self.populate_source_cbo(source_names) self.populate_leading_zero() self.populate_separator() if self._source: self.prefix_source_cbo.setCurrentIndex( self.prefix_source_cbo.findText(self._source) ) if self._leading_zero: self.leading_zero_cbo.setCurrentIndex( self.leading_zero_cbo.findData(self._leading_zero) ) if self._separator: self.separator_cbo.setCurrentIndex( self.separator_cbo.findData(self._separator) ) longest_item = max(source_names, key=len) font_meter = QFontMetrics(self.fontMetrics()) item_width = font_meter.width(longest_item) + 18 self.prefix_source_cbo.setStyleSheet( '''* QComboBox QAbstractItemView{ min-width: 150px; width: %spx; } ''' % item_width )
def create_scale_marker_values_text(self): painter = QPainter(self) # painter.setRenderHint(QPainter.HighQualityAntialiasing) painter.setRenderHint(QPainter.Antialiasing) # Koordinatenursprung in die Mitte der Flaeche legen painter.translate(self.width() / 2, self.height() / 2) # painter.save() font = QFont(self.scale_fontname, self.scale_fontsize) fm = QFontMetrics(font) pen_shadow = QPen() pen_shadow.setBrush(self.ScaleValueColor) painter.setPen(pen_shadow) text_radius_factor = 0.8 text_radius = self.widget_diameter/2 * text_radius_factor scale_per_div = int((self.value_max - self.value_min) / self.scala_main_count) angle_distance = (float(self.scale_angle_size) / float(self.scala_main_count)) for i in range(self.scala_main_count + 1): # text = str(int((self.value_max - self.value_min) / self.scala_main_count * i)) text = str(int(self.value_min + scale_per_div * i)) w = fm.width(text) + 1 h = fm.height() painter.setFont(QFont(self.scale_fontname, self.scale_fontsize)) angle = angle_distance * i + float(self.scale_angle_start_value - self.angle_offset) x = text_radius * math.cos(math.radians(angle)) y = text_radius * math.sin(math.radians(angle)) # print(w, h, x, y, text) text = [x - int(w/2), 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])
def paint(self, painter, option, widget=None): rect = self.rect() if self.isSelected(): option.state ^= QStyle.State_Selected font = self.document().defaultFont() painter.setFont(font) if self.parent: draw_text = self.node_inst.description if self.parent.x() > self.x(): # node is to the left fm = QFontMetrics(font) x = rect.width() / 2 - fm.width(draw_text) - 4 else: x = rect.width() / 2 + 4 painter.drawText(QPointF(x, -self.line_descent - 1), draw_text) painter.save() painter.setBrush(self.backgroundBrush) painter.setPen(QPen(Qt.black, 3 if self.isSelected() else 0)) adjrect = rect.adjusted(-3, 0, 0, 0) if not self.node_inst.children: painter.drawRoundedRect(adjrect, 4, 4) else: painter.drawRect(adjrect) painter.restore() painter.setClipRect(rect) return QGraphicsTextItem.paint(self, painter, option, widget)
def adjustFont(self): # --- fetch current parameters ---- f = self.font() cr = self.contentsRect() if self.maxFont is not None: maximum = self.maxFont.pointSize() else: maximum = self.font().pointSize() # --- find the font size that fits the contentsRect --- fs = 1 while True: f.setPointSize(fs) br = QFontMetrics(f).boundingRect(self.text()) if br.height() <= cr.height() and br.width() <= cr.width(): fs += 1 else: if self.wordWrap() == False: wouldfit = (max(fs - 1, 1) ) # if the length have to fit into the label if wouldfit > maximum: wouldfit = maximum f.setPointSize( wouldfit ) # if wordwrap is wanted by the user... he expects wordwrap. else: wouldfit = max(fs - 1, 1) * 1.5 if wouldfit > maximum: wouldfit = maximum f.setPointSize( wouldfit ) # if wordwrap is wanted by the user... he expects wordwrap. #f.setPointSize(max(fs - 1, 1)*1.5) # if wordwrap is wanted by the user... he expects wordwrap. break # --- update font size --- self.setFont(f)
def custom_resize_columns_to_contents(view): model = view.model() font = view.font() MAGIC_NUMBERS = {"hexsha": 1.4, "authored_date" : 1.1, "committed_date" : 1.1} for column, field in enumerate(model.get_columns()): # Use QFontMetrics to find out the proper size. if "name" in field: width_set = [] for row in xrange(30): item = model.data(model.createIndex(row, column), Qt.DisplayRole) metrics = QFontMetrics(font) width = metrics.width(item.toString()) width_set.append(width) width = max(width_set) else: item = model.data(model.createIndex(0, column), Qt.DisplayRole) metrics = QFontMetrics(font) width = metrics.width(item.toString()) if field in MAGIC_NUMBERS: magic = MAGIC_NUMBERS[field] else: magic = 1.2 view.setColumnWidth(column, int(width * magic))
def updateAlexaLogCoords(self): self.edit._alexaLogIconsCoords = [] #block = self.edit.document().findBlock(0) block = self.edit.firstVisibleBlock() line_count = block.blockNumber() pat = re.compile('\s*#Alexa Log') viewport_offset = self.edit.contentOffset() while block.isValid(): line_count += 1 #maxLine = math.ceil(math.log10(self.edit.blockCount())) font_metrics = QFontMetrics(self.edit.document().defaultFont()) position = self.edit.blockBoundingGeometry(block).topLeft() + viewport_offset width = self.edit.blockBoundingGeometry(block).width() x = 2 + viewport_offset.x() if pat.match(block.text()): try: if self.edit.useTabs: #x += block.text().index("#") * (font_metrics.width('.') * self.edit.indent) x += block.text().index(" #") * (font_metrics.width('.') * self.edit.indent) else: #x += block.text().index("#") * font_metrics.width('.') x += block.text().index(" #") * font_metrics.width('.') except: pass if block.isVisible(): # da notare che il blocco è la riga e non il blocco compreso tra i tag di Al'exa self.edit._alexaLogIconsCoords.append((x, position.y(), width, line_count)) block = block.next()
def paintEvent(self, event): """ Reimplements the :meth:`QWidget.paintEvent` method. :param event: Event. :type event: QEvent """ def __setBold(state): """ Sets the current painter font bold state. :return: Definiton success. :rtype: bool """ font = painter.font() font.setBold(state) painter.setFont(font) return True painter = QPainter(self) painter.fillRect(event.rect(), self.__backgroundColor) pen = QPen(QBrush(), self.__separatorWidth) pen.setColor(self.__separatorColor) painter.setPen(pen) topRightCorner = event.rect().topRight() bottomRightCorner = event.rect().bottomRight() painter.drawLine(topRightCorner.x(), topRightCorner.y(), bottomRightCorner.x(), bottomRightCorner.y()) painter.setPen(self.__color) viewportHeight = self.__editor.viewport().height() metrics = QFontMetrics(self.__editor.document().defaultFont()) currentBlock = self.__editor.document().findBlock( self.__editor.textCursor().position()) block = self.__editor.firstVisibleBlock() blockNumber = block.blockNumber() painter.setFont(self.__editor.document().defaultFont()) while block.isValid(): blockNumber += 1 position = self.__editor.blockBoundingGeometry(block).topLeft() + self.__editor.contentOffset() if position.y() > viewportHeight: break if not block.isVisible(): continue block == currentBlock and __setBold(True) or __setBold(False) painter.drawText(self.width() - metrics.width(foundations.strings.toString(blockNumber)) - self.__margin / 3, round(position.y() + metrics.ascent() + metrics.descent() - \ (self.__editor.blockBoundingRect(block).height() * 8.0 / 100)), foundations.strings.toString(blockNumber)) block = block.next() painter.end() QWidget.paintEvent(self, event)
def __init__(self, parent): Qwt.QwtPlot.__init__(self, parent) self.RGBMap = 0 self.IndexMap = 1 self.HueMap = 2 self.AlphaMap = 3 self.d_alpha = 255 self.d_spectrogram = Qwt.QwtPlotSpectrogram() self.d_spectrogram.setRenderThreadCount( 0) # use system specific thread count self.d_spectrogram.setCachePolicy(Qwt.QwtPlotRasterItem.PaintCache) contourLevels = [] for level in range(1, 20, 2): contourLevels.append(0.5 * level) self.d_spectrogram.setContourLevels(contourLevels) self.d_spectrogram.setData(SpectrogramData()) self.d_spectrogram.attach(self) zInterval = self.d_spectrogram.data().interval(Qt.ZAxis) # A color bar on the right axis self.rightAxis = self.axisWidget(Qwt.QwtPlot.yRight) self.rightAxis.setTitle("Intensity") self.rightAxis.setColorBarEnabled(True) self.setAxisScale(Qwt.QwtPlot.yRight, zInterval.minValue(), zInterval.maxValue()) self.enableAxis(Qwt.QwtPlot.yRight) self.plotLayout().setAlignCanvasToScales(True) self.setColorMap(self.RGBMap) # LeftButton for the zooming # MidButton for the panning # RightButton: zoom out by 1 # Ctrl+RighButton: zoom out to full size self.zoomer = MyZoomer(self.canvas()) self.zoomer.setMousePattern(Qwt.QwtEventPattern.MouseSelect2, Qt.RightButton, Qt.ControlModifier) self.zoomer.setMousePattern(Qwt.QwtEventPattern.MouseSelect3, Qt.RightButton) self.panner = Qwt.QwtPlotPanner(self.canvas()) self.panner.setAxisEnabled(Qwt.QwtPlot.yRight, False) self.panner.setMouseButton(Qt.MidButton) # Avoid jumping when labels with more/less digits # appear/disappear when scrolling vertically fm = QFontMetrics(self.axisWidget(Qwt.QwtPlot.yLeft).font()) sd = self.axisScaleDraw(Qwt.QwtPlot.yLeft) sd.setMinimumExtent(fm.width("100.00")) c = QColor(Qt.darkBlue) self.zoomer.setRubberBandPen(c) self.zoomer.setTrackerPen(c)
def detectRevisionMarginWidth(self): """ Caculates the margin width depending on the margin font and the current zoom """ skin = GlobalData().skin font = QFont(skin.lineNumFont) font.setPointSize(font.pointSize() + self.getZoom()) fontMetrics = QFontMetrics(font, self) return fontMetrics.width('W' * self.__maxLength) + 3
def detectRevisionMarginWidth( self ): """ Caculates the margin width depending on the margin font and the current zoom """ skin = GlobalData().skin font = QFont( skin.lineNumFont ) font.setPointSize( font.pointSize() + self.getZoom() ) fontMetrics = QFontMetrics( font, self ) return fontMetrics.width( 'W' * self.__maxLength ) + 3
def minimumLabelHeight(self): """ Returns the minimum height that will be required based on this font size and labels list. """ metrics = QFontMetrics(self.labelFont()) return max(self._minimumLabelHeight, metrics.height() + self.verticalLabelPadding())
def update_sidebar(self): """ Ajusta el ancho del sidebar """ fmetrics = QFontMetrics(self._font) lines = str(self.lines()) + '0' line_number = settings.get_setting('editor/show-line-number') width = fmetrics.width(lines) if line_number else 0 self.setMarginWidth(0, width)
def __getElidedText(self,font,s,maxWidth): ''' ''' fontWidth = QFontMetrics(font) width = fontWidth.width(s) if width >= maxWidth: s = fontWidth.elidedText(s,Qt.ElideRight,maxWidth) return s
def paintEvent(self,event): titleHeight = 40 bottomHeight = 50 #画标题背景 painter = QPainter(self) painter.save() linearGradient = QLinearGradient(0, 0,0,titleHeight) linearGradient.setColorAt(0, QColor(60,150,255)) linearGradient.setColorAt(0.1, QColor(6,88,200)) linearGradient.setColorAt(1, QColor(80,150,255)) painter.setBrush(QBrush(linearGradient)) contenRect = QRect(0, 0, self.width(), titleHeight) painter.fillRect(contenRect, QBrush(linearGradient)) painter.restore() #画标题内容 painter.save() painter.setPen(QPen(QColor(255, 255, 255),1)) font = painter.font() font.setPointSize(12) painter.setFont(font) painter.drawText(QPoint(10,25), self.title) painter.restore() #画中间白色背景 painter.save() painter.setPen(QPen(QColor(255, 255, 255),1)) brush = QBrush(QColor(242,242,242)) painter.setBrush(brush) contenRect = QRect(0, titleHeight, self.width()-1, self.height() - titleHeight - bottomHeight) # painter.fillRect(contenRect, brush) painter.drawRect(contenRect) painter.restore() #画提示信息内容 painter.save() painter.setPen(QPen(QColor(1, 1, 1),1)) font = painter.font() font.setPointSize(15) painter.setFont(font) fm = QFontMetrics(font) infoWidth = fm.width(self.hintInfo) painter.drawText(QPoint((self.width() - infoWidth - 10)/2, 150), self.hintInfo) painter.restore() #画底层背景 painter.save() brush = QBrush(QColor(219,234,255)) painter.setBrush(brush) contenRect = QRect(0, self.height() - bottomHeight, self.width(), bottomHeight) painter.fillRect(contenRect, brush) painter.restore()
def __init__(self, parent=None, mainWindow=None, showDetailsButton=True, animatable=True): super(PackageDelegate, self).__init__(parent) self.webDialog = WebDialog(mainWindow) self.show_details_button = showDetailsButton self.rowAnimator = RowAnimator(parent.packageList) self.defaultIcon = KIcon(('package-x-generic', 'package_applications'), 32) self.defaultInstalledIcon = QIcon( KIconLoader.loadOverlayed( ('package-x-generic', 'package_applications'), CHECK_ICON, 32)) self.animatable = animatable self._max_height = ROW_HEIGHT self._rt_0 = QIcon(":/data/star_0.png") self._rt_1 = QIcon(":/data/star_1.png") self.types = { 'critical': (RED, i18n('critical')), 'security': (DARKRED, i18n('security')) } self.font = Pds.settings('font', 'Sans,10').split(',')[0] self.normalFont = QFont(self.font, 10, QFont.Normal) self.boldFont = QFont(self.font, 11, QFont.Bold) self.normalDetailFont = QFont(self.font, 9, QFont.Normal) self.boldDetailFont = QFont(self.font, 9, QFont.Bold) self.tagFont = QFont(self.font, 7, QFont.Normal) self.tagFontFM = QFontMetrics(self.tagFont) self.boldFontFM = QFontMetrics(self.boldFont) self.boldDetailFontFM = QFontMetrics(self.boldDetailFont) self.normalFontFM = QFontMetrics(self.normalFont) self.normalDetailFontFM = QFontMetrics(self.normalDetailFont) self._titles = { 'description': i18n("Description:"), 'website': i18n("Website:"), 'release': i18n("Release:"), 'repository': i18n("Repository:"), 'size': i18n("Package Size:"), 'installVers': i18n("Installed Version:") } self._titleFM = {} for key, value in self._titles.items(): self._titleFM[key] = self.boldDetailFontFM.width( value) + ICON_SIZE + 3 self.baseWidth = self.boldFontFM.width( max(self._titles.values(), key=len)) + ICON_SIZE self.parent = parent.packageList
def __init__(self, view: Amendment('view/', lambda v: hasattr(v, 'mode') and (v.mode.name == 'ipython') and (v.widget is None))): #, orig_editor=None): if view.widget is None: self.globals = {} self.globals['ddic'] = ddic for a in ddic['actions']: self.globals[a] = ddic['actions'][a] self.locals = {} # ddic.provide('interactive', -1) else: self.globals = view.widget.globals self.locals = view.widget.locals super().__init__(view) # Set the default font font = QFont() font.setFamily('DejaVu Sans Mono') font.setFixedPitch(True) font.setPointSize(10) self.setFont(font) # self.parser = Parser(self, 'python3') # self.ca = PyInterpretContentAssist() fontmetrics = QFontMetrics(font) # Brace matching: enable for a brace immediately before or after # the current position # self.setBraceMatching(QsciScintilla.SloppyBraceMatch) # Current line visible with special background color self.setCaretLineVisible(True) self.setCaretLineBackgroundColor(QColor("#ffe4e4")) # Set Python lexer # Set style for Python comments (style number 1) to a fixed-width # courier. # # self.SendScintilla(QsciScintilla.SCI_STYLESETFONT, 1, 'DejaVu Sans Mono'.encode()) # Don't want to see the horizontal scrollbar at all # Use raw message to Scintilla here (all messages are documented # here: http://www.scintilla.org/ScintillaDoc.html) self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0) self.SendScintilla(QsciScintilla.SCI_SETVSCROLLBAR, 0) self.setMinimumSize(fontmetrics.width("00000"), fontmetrics.height()+4) self.markerDefine(QsciScintilla.RightArrow, self.ARROW_MARKER_NUM) # self.setMarkerBackgroundColor(QColor("#ee1111"), # self.ARROW_MARKER_NUM) self.prompt_begin = 0 self.focus_view = None self.interactive = False
def setFont(self, f): # recalculate all of our metrics/offsets fm = QFontMetrics(f) self.font_width = fm.width('X') self.font_height = fm.height() self.updateScrollbars() # TODO: assert that we are using a fixed font & find out if we care? QAbstractScrollArea.setFont(self,f) return
def setListMaximumWidth(self, theList): "Sets the MaximumWidth of the given list according to its items." maxW = 0 for i in range(theList.count()): it = theList.item(i) fm = QFontMetrics(it.font()) w = fm.width(it.text()) maxW = max(w, maxW) theList.setMaximumWidth(maxW + 20)
def actualizar_sidebar(self): """ Ajusta el ancho del sidebar """ fmetrics = QFontMetrics(self._fuente) lineas = str(self.lineas) + '00' if len(lineas) != 1: ancho = fmetrics.width(lineas) self.setMarginWidth(0, ancho)
def calcitems(): font = painter.font() metrices = QFontMetrics(font) maxwidth = 0 maxheight = 0 for item, _ in itemlist(self.items): maxwidth = max(metrices.boundingRect(item).width(), maxwidth) maxheight = max(metrices.boundingRect(item).height(), maxheight) return maxwidth, maxheight
def __updateShape(self): fBBox = QFontMetrics(self.Font).boundingRect(self.Name) if self.__polygon.boundingRect().width() < fBBox.width(): self.__polygon = QPolygonF(QRectF(fBBox).normalized().adjusted(-fBBox.width() / 4, -fBBox.height() / 4, fBBox.height(), fBBox.height() / 2))
def initFont(self): self.setDefaultTextColor(QColor(Qt.darkCyan)) self.font = QFont("Gothic") self.font.setFixedPitch(1) self.font.setBold(False) self.font.setPixelSize(self.fontPixel) self.setFont(self.font) self.metric = QFontMetrics(self.font)
def __calcMaxTextSize(self, font, hodnoty): fm = QFontMetrics(font); x = 0 y = fm.height() for hodnota in hodnoty: w = fm.width(hodnota) if w > x: x = w return (x, y)
def __createLayout( self ): " Creates the widget layout " self.__messageLabel = QLabel( "This file has been modified " "outside of codimension. What " "would you like to do?" ) self.__messageLabel.setWordWrap( True ) self.__messageLabel.setAlignment( Qt.AlignHCenter ) palette = self.__messageLabel.palette() palette.setColor( self.foregroundRole(), QColor( 255, 255, 255, 255 ) ) self.__messageLabel.setPalette( palette ) self.__leaveAsIsButton = QPushButton( "Continue editing", self ) self.__leaveAsIsButton.setToolTip( "ESC" ) self.__leaveAsIsButton.clicked.connect( self.hide ) self.__reloadButton = QPushButton( self ) self.__reloadButton.clicked.connect( self.__reload ) txt = "Reload all non-modified buffers" self.__reloadAllNonChangedButton = QPushButton( txt, self ) self.__reloadAllNonChangedButton.clicked.connect( self.__reloadAllNonModified ) # This will prevent the buttons growing wider than necessary fontMetrics = QFontMetrics( self.__reloadAllNonChangedButton.font() ) buttonWidth = fontMetrics.width( txt ) + 20 self.__reloadAllNonChangedButton.setFixedWidth( buttonWidth ) gridLayout = QGridLayout( self ) gridLayout.setMargin( 3 ) gridLayout.addWidget( self.__messageLabel, 0, 0, 1, 1 ) gridLayout.addWidget( self.__leaveAsIsButton, 0, 1, 1, 1 ) gridLayout.addWidget( self.__reloadButton, 1, 1, 1, 1 ) gridLayout.addWidget( self.__reloadAllNonChangedButton, 2, 1, 1, 1 ) self.setSizePolicy( QSizePolicy.Fixed, QSizePolicy.Fixed ) self.move( 5, 5 ) self.__markers.append( QFrame( self.parent() ) ) self.__markers.append( QFrame( self.parent() ) ) self.__markers.append( QFrame( self.parent() ) ) self.__markers.append( QFrame( self.parent() ) ) markerColor = QColor( 224, 0, 0, 255 ) for item in self.__markers: pal = item.palette() pal.setColor( item.backgroundRole(), markerColor ) item.setPalette( pal ) item.setFrameShape( QFrame.StyledPanel ) item.setLineWidth( 1 ) item.setAutoFillBackground( True ) item.setSizePolicy( QSizePolicy.Fixed, QSizePolicy.Fixed ) return
def __init__(self, parent=None): super(MyQTextBrowser, 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.setUtf8(True) # Margin 0 is used for line numbers font_metrics = QFontMetrics(font) self.setMarginsFont(font) self.setMarginWidth(0, font_metrics.width("000") + 4) self.setMarginLineNumbers(0, True) self.setMarginsBackgroundColor(QColor("#cccccc")) # Clickable margin 1 for showing markers self.setMarginSensitivity(1, True) self.connect(self, SIGNAL('marginClicked(int, int, Qt::KeyboardModifiers)'), self.on_margin_clicked) self.markerDefine(QsciScintilla.RightArrow, self.ARROW_MARKER_NUM) self.setMarkerBackgroundColor(QColor("#ee1111"), self.ARROW_MARKER_NUM) # Brace matching: enable for a brace immediately before or after # the current position # self.setBraceMatching(QsciScintilla.SloppyBraceMatch) # Current line visible with special background color self.setCaretLineVisible(True) self.setCaretLineBackgroundColor(QColor("#ffe4e4")) # Set Python lexer # Set style for Python comments (style number 1) to a fixed-width # courier. # lexer = QsciLexerXML() lexer.setDefaultFont(font) self.setLexer(lexer) self.SendScintilla(QsciScintilla.SCI_STYLESETFONT, 1, 'Courier') # Don't want to see the horizontal scrollbar at all # Use raw message to Scintilla here (all messages are documented # here: http://www.scintilla.org/ScintillaDoc.html) self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0) self.setHorizontalScrollBar(QScrollBar(self)) self.fp = None self.item = None self.html_mapper = dict() self.setReadOnly(True)
def sizeHint(self): size = QToolBar.sizeHint(self) fm = QFontMetrics(self.font()) if self.dock.features() & QDockWidget.DockWidgetVerticalTitleBar: size.setHeight(size.height() + fm.width(self.dock.windowTitle())) else: size.setWidth(size.width() + fm.width(self.dock.windowTitle())) return size
def calcitems(): font = painter.font() metrices = QFontMetrics(font) maxwidth = 0 maxheight = 0 for item, _ in itemlist(): maxwidth = max(metrices.boundingRect(item).width(), maxwidth) maxheight = max( metrices.boundingRect(item).height(), maxheight) return maxwidth, maxheight
def paintEvent(self, event): painter = QPainter(self) font_metrics = QFontMetrics(self.font()) if font_metrics.width(self.text()) > self.contentsRect().width(): label_width = self.size().width() gradient = QLinearGradient(0, 0, label_width, 0) gradient.setColorAt(1-50.0/label_width, self.palette().color(self.foregroundRole())) gradient.setColorAt(1.0, Qt.transparent) painter.setPen(QPen(QBrush(gradient), 1.0)) painter.drawText(self.contentsRect(), Qt.TextSingleLine | int(self.alignment()), self.text())
def sizeHint(self): size = super(PopupButton, self).sizeHint() fm = QFontMetrics(QApplication.instance().font()) width = fm.width(self.text()) opts = QStyleOptionButton() self.initStyleOption(opts) style = self.style() dw = style.pixelMetric(QStyle.PM_MenuButtonIndicator, opts, self) size.setWidth(width + dw + 10) return size
def __createLayout(self): " Creates the widget layout " self.__messageLabel = QLabel("This file has been modified " "outside of codimension. What " "would you like to do?") self.__messageLabel.setWordWrap(True) self.__messageLabel.setAlignment(Qt.AlignHCenter) palette = self.__messageLabel.palette() palette.setColor(self.foregroundRole(), QColor(255, 255, 255, 255)) self.__messageLabel.setPalette(palette) self.__leaveAsIsButton = QPushButton("Continue editing", self) self.__leaveAsIsButton.setToolTip("ESC") self.__leaveAsIsButton.clicked.connect(self.hide) self.__reloadButton = QPushButton(self) self.__reloadButton.clicked.connect(self.__reload) txt = "Reload all non-modified buffers" self.__reloadAllNonChangedButton = QPushButton(txt, self) self.__reloadAllNonChangedButton.clicked.connect( self.__reloadAllNonModified) # This will prevent the buttons growing wider than necessary fontMetrics = QFontMetrics(self.__reloadAllNonChangedButton.font()) buttonWidth = fontMetrics.width(txt) + 20 self.__reloadAllNonChangedButton.setFixedWidth(buttonWidth) gridLayout = QGridLayout(self) gridLayout.setMargin(3) gridLayout.addWidget(self.__messageLabel, 0, 0, 1, 1) gridLayout.addWidget(self.__leaveAsIsButton, 0, 1, 1, 1) gridLayout.addWidget(self.__reloadButton, 1, 1, 1, 1) gridLayout.addWidget(self.__reloadAllNonChangedButton, 2, 1, 1, 1) self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.move(5, 5) self.__markers.append(QFrame(self.parent())) self.__markers.append(QFrame(self.parent())) self.__markers.append(QFrame(self.parent())) self.__markers.append(QFrame(self.parent())) markerColor = QColor(224, 0, 0, 255) for item in self.__markers: pal = item.palette() pal.setColor(item.backgroundRole(), markerColor) item.setPalette(pal) item.setFrameShape(QFrame.StyledPanel) item.setLineWidth(1) item.setAutoFillBackground(True) item.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) return
def init_gui(self): """ Initializes form widgets """ source_names = self.prefix_source_names() self.populate_source_cbo(source_names) self.populate_leading_zero() self.populate_separator(self.separator_cbo) self.populate_columns_list() column_header = QApplication.translate('CodeProperty', 'Columns') separator_header = QApplication.translate('CodeProperty', 'Separator') self.column_code_view.model().setHorizontalHeaderLabels( [column_header, separator_header] ) header = self.column_code_view.horizontalHeader() header.setResizeMode(0, QHeaderView.Stretch) header.setResizeMode(1, QHeaderView.ResizeToContents) if self._source: self.prefix_source_cbo.setCurrentIndex( self.prefix_source_cbo.findText(self._source) ) if self._columns: self.set_columns() self.set_disable_auto_increment() self.set_enable_editing() self.set_hide_prefix() if self._leading_zero: self.leading_zero_cbo.setCurrentIndex( self.leading_zero_cbo.findData(self._leading_zero) ) if self._separator: self.separator_cbo.setCurrentIndex( self.separator_cbo.findData(self._separator) ) longest_item = max(source_names, key=len) font_meter = QFontMetrics(self.fontMetrics()) item_width = font_meter.width(longest_item) + 18 self.prefix_source_cbo.setStyleSheet( '''* QComboBox QAbstractItemView{ min-width: 150px; width: %spx; } ''' % item_width ) # Link checkbox and label self.disable_auto_increment_lbl.setBuddy(self.disable_auto_increment_chk) self.enable_editing_lbl.setBuddy(self.enable_editing_chk) self.hide_prefix_lbl.setBuddy(self.hide_prefix_chk)
def _load_code_editor_settings(self): """ Load settings on the code editor like, font style, margins, scroll, etc. Based on the example from http://eli.thegreenplace.net/2011/04/01/sample-using-qscintilla-with-pyqt/ """ item = self.form.font_size.currentText() size = int(item) # Set the default font font = QFont() font.setFamily('Courier') font.setFixedPitch(True) font.setPointSize(size) self._code_editor.setFont(font) self._code_editor.setMarginsFont(font) # Margin 0 is used for line numbers fontmetrics = QFontMetrics(font) self._code_editor.setMarginsFont(font) self._code_editor.setMarginWidth(0, fontmetrics.width("00000") + 6) self._code_editor.setMarginLineNumbers(0, True) self._code_editor.setMarginsBackgroundColor(QColor("#cccccc")) # Clickable margin 1 for showing markers self._code_editor.setMarginSensitivity(1, True) self._code_editor.marginClicked.connect(self.on_margin_clicked) self._code_editor.markerDefine(QsciScintilla.RightArrow, self.ARROW_MARKER_NUM) self._code_editor.setMarkerBackgroundColor(QColor("#ee1111"), self.ARROW_MARKER_NUM) # Detect changes to text self._code_editor.modificationChanged.connect( self.on_modification_changed) # Brace matching: enable for a brace immediately before or after the current position self._code_editor.setBraceMatching(QsciScintilla.SloppyBraceMatch) # Current line visible with special background color self._code_editor.setCaretLineVisible(True) self._code_editor.setCaretLineBackgroundColor(QColor("#ffe4e4")) # Set Python lexer # Set style for Python comments (style number 1) to a fixed-width Courier. lexer = self.lexer() lexer.setDefaultFont(font) self._code_editor.setLexer(lexer) self._code_editor.setIndentationWidth(4) # self._code_editor.SendScintilla(QsciScintilla.SCI_STYLESETFONT, 1, 'Courier') self._code_editor.SendScintilla(QsciScintilla.SCI_STYLESETFONT, 1) # Don't want to see the horizontal scrollbar at all # Use raw message to Scintilla here (all messages are documented here: http://www.scintilla.org/ScintillaDoc.html) self._code_editor.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0)
def __init__(self, template, character, parent=None): super(AdvantagesWidget, self).__init__(parent) self.ui = Ui_AdvantagesWidget() self.ui.setupUi(self) self.__character = character self.__storage = template fontMetrics = QFontMetrics(self.font()) textRect = fontMetrics.boundingRect("0") iconGeneral = QIcon(":/items/images/svg/shield.svg") pixmapGeneral = iconGeneral.pixmap(textRect.height(), 10 * textRect.height()) self.ui.label_armorGeneralSign.setPixmap(pixmapGeneral) iconFirearms = QIcon(":/items/images/svg/uzi.svg") pixmapFirearms = iconFirearms.pixmap(textRect.height(), 10 * textRect.height()) self.ui.label_armorFirearmsSign.setPixmap(pixmapFirearms) self.ui.dots_health.setReadOnly(True) self.ui.dots_willpower.setMaximum(Config.TRAIT_WILLPOWER_VALUE_MAX) self.ui.dots_willpower.setReadOnly(True) self.ui.dots_powerstat.setMaximum(Config.TRAIT_POWERSTAT_VALUE_MAX) self.ui.dots_powerstat.setMinimum(Config.TRAIT_POWERSTAT_VALUE_MIN) # Damit später der Wert stimmt muß ich irgendeinen Wert != 1 geben, sonst wird kein Signal gesandt. self.ui.dots_powerstat.setValue(9) self.ui.squares_fuel.columnMax = 10 self.__character.speciesChanged.connect(self.setShapeSize) self.sizeChanged.connect(self.setShapeSize) self.__character.speciesChanged.connect(self.setShapeInitiaitve) self.initiativeChanged.connect(self.setShapeInitiaitve) self.__character.speciesChanged.connect(self.setShapeSpeed) self.speedChanged.connect(self.setShapeSpeed) self.__character.speciesChanged.connect(self.setShapeDefense) self.__character.traits["Attribute"]["Mental"][ "Wits"].valueChanged.connect(self.setShapeDefense) self.__character.traits["Attribute"]["Physical"][ "Dexterity"].valueChanged.connect(self.setShapeDefense) self.__character.speciesChanged.connect(self.setShapeHealth) self.healthChanged.connect(self.setShapeHealth) self.__character.armorChanged.connect(self.updateArmor) self.ui.dots_powerstat.valueChanged.connect( self.__character.setPowerstat) self.__character.powerstatChanged.connect( self.ui.dots_powerstat.setValue) self.__character.powerstatChanged.connect(self.setFuel) self.__character.speciesChanged.connect(self.setFuel) self.__character.speciesChanged.connect(self.renamePowerstatHeading) self.__character.speciesChanged.connect(self.hideSuper)
def paintEvent(self, event): """ Overloads the paint event to paint additional \ hint information if no text is set on the \ editor. :param event | <QPaintEvent> """ super(XLineEdit, self).paintEvent(event) # paint the hint text if not text is set if self.text() and not (self.icon() and not self.icon().isNull()): return # paint the hint text painter = QPainter(self) painter.setPen(self.hintColor()) icon = self.icon() left, top, right, bottom = self.getTextMargins() w = self.width() h = self.height() - 2 w -= (right + left) h -= (bottom + top) if icon and not icon.isNull(): size = icon.actualSize(self.iconSize()) x = 5 + left y = (self.height() - size.height()) / 2.0 painter.drawPixmap(x, y, icon.pixmap(size.width(), size.height())) w -= size.width() - 2 else: x = 6 + left w -= sum([btn.width() for btn in self.buttons()]) y = 2 + top # create the elided hint if not self.text() and self.hint(): rect = self.cursorRect() metrics = QFontMetrics(self.font()) hint = metrics.elidedText(self.hint(), Qt.ElideRight, w) align = self.alignment() if align & Qt.AlignHCenter: x = 0 else: x = rect.center().x() painter.drawText(x, y, w, h, align, hint)
def __textLayout(self): fm = QFontMetrics(self.font()) text = str(self.defaultAction().text()) words = deque(text.split()) lines = [] curr_line = "" curr_line_word_count = 0 option = QStyleOptionToolButton() option.initFrom(self) margin = self.style().pixelMetric(QStyle.PM_ButtonMargin, option, self) width = self.width() - 2 * margin while words: w = words.popleft() if curr_line_word_count: line_extended = " ".join([curr_line, w]) else: line_extended = w line_w = fm.boundingRect(line_extended).width() if line_w >= width: if curr_line_word_count == 0 or len(lines) == 1: # A single word that is too long must be elided. # Also if the text overflows 2 lines # Warning: hardcoded max lines curr_line = fm.elidedText(line_extended, Qt.ElideRight, width) curr_line = str(curr_line) else: # Put the word back words.appendleft(w) lines.append(curr_line) curr_line = "" curr_line_word_count = 0 if len(lines) == 2: break else: curr_line = line_extended curr_line_word_count += 1 if curr_line: lines.append(curr_line) text = "\n".join(lines) text = text.replace('&', '&&') # Need escaped ampersand to show self.__text = text
def _updateSpacing(self): fm = QFontMetrics(self.noteFont) maxWidth = 0 maxHeight = 0 for ch in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-+=/?\\{}[]:;'\",<.>~`": br = fm.tightBoundingRect(ch) if br.height() > maxHeight: maxHeight = br.height() if br.width() > maxWidth: maxWidth = br.width() self.xSpacing = maxWidth self.ySpacing = maxHeight
def setRect(self, fm=None): if fm is None: font = self.font() if font is None: return fm = QFontMetrics(font) lineHeight = fm.height() height = lineHeight * self._dataLen() * 1.1 width = max(fm.width(data) for data in self._iterData()) + 10 if height != self._rect.height() or width != self._rect.width(): self.prepareGeometryChange() self._rect.setBottomRight(QPointF(width, height))
def update_contents(self): self.prepareGeometryChange() self.setTextWidth(-1) self.setTextWidth(self.document().idealWidth()) self.droplet.setPos(self.rect().center().x(), self.rect().height()) self.droplet.setVisible(bool(self.branches)) fm = QFontMetrics(self.document().defaultFont()) attr = self.node_inst.attr self.attr_text_w = fm.width(attr.name if attr else "") self.attr_text_h = fm.lineSpacing() self.line_descent = fm.descent() if self.pie is not None: self.pie.setPos(self.rect().right(), self.rect().center().y())
def setText(self, text): """ Sets the text for this item and resizes it to fit the text and the remove button. :param text | <str> """ super(XMultiTagItem, self).setText(text) metrics = QFontMetrics(self.font()) hint = QSize(metrics.width(text) + 24, 18) self.setSizeHint(hint)
def paintEvent(self, event): painter = QPainter(self) font_metrics = QFontMetrics(self.font()) if font_metrics.width(self.text()) > self.contentsRect().width(): label_width = self.size().width() gradient = QLinearGradient(0, 0, label_width, 0) gradient.setColorAt(1 - 50.0 / label_width, self.palette().color(self.foregroundRole())) gradient.setColorAt(1.0, Qt.transparent) painter.setPen(QPen(QBrush(gradient), 1.0)) painter.drawText(self.contentsRect(), Qt.TextSingleLine | int(self.alignment()), self.text())