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: if role == Qt.DisplayRole: try: return self.__headers[section] except IndexError: return None return None return QAbstractTableModel.headerData(self, section, orientation, role)
def resizeEvent(self, event): super().resizeEvent(event) f = self.font() cr = self.contentsRect() dw = event.size().width() - event.oldSize().width() # width change dh = event.size().height() - event.oldSize().height() # height change fs = max(f.pixelSize(), 1) while True: f.setPixelSize(fs) text = self.questionAnswerStr() br = QFontMetrics(f).boundingRect(text) # question and answer string if dw >= 0 and dh >= 0: if br.height() <= cr.height() and br.width() <= cr.width(): fs += 1 else: f.setPixelSize(max(fs - 1, 1)) # backtrack break else: if br.height() > cr.height() or br.width() > cr.width(): fs -= 1 else: break if fs < 1: break self.setFont(f)
def __init__(self, parent=None): """ Constructor @param parent reference to the parent widget (QWidget) """ super(UserAgentsDialog, self).__init__(parent) self.setupUi(self) self.removeButton.clicked.connect( self.userAgentsTable.removeSelected) self.removeAllButton.clicked.connect( self.userAgentsTable.removeAll) self.userAgentsTable.verticalHeader().hide() self.__userAgentModel = UserAgentModel( Helpviewer.HelpWindow.HelpWindow.userAgentsManager(), self) self.__proxyModel = QSortFilterProxyModel(self) self.__proxyModel.setSourceModel(self.__userAgentModel) self.searchEdit.textChanged.connect( self.__proxyModel.setFilterFixedString) self.userAgentsTable.setModel(self.__proxyModel) fm = QFontMetrics(QFont()) height = fm.height() + fm.height() // 3 self.userAgentsTable.verticalHeader().setDefaultSectionSize(height) self.userAgentsTable.verticalHeader().setMinimumSectionSize(-1) self.userAgentsTable.resizeColumnsToContents() self.userAgentsTable.horizontalHeader().setStretchLastSection(True)
def __init__(self, parent=None): """ Constructor @param parent reference to the parent widget (QWidget) """ super(UserAgentsDialog, self).__init__(parent) self.setupUi(self) self.removeButton.clicked.connect(self.userAgentsTable.removeSelected) self.removeAllButton.clicked.connect(self.userAgentsTable.removeAll) self.userAgentsTable.verticalHeader().hide() self.__userAgentModel = UserAgentModel( Helpviewer.HelpWindow.HelpWindow.userAgentsManager(), self) self.__proxyModel = QSortFilterProxyModel(self) self.__proxyModel.setSourceModel(self.__userAgentModel) self.searchEdit.textChanged.connect( self.__proxyModel.setFilterFixedString) self.userAgentsTable.setModel(self.__proxyModel) fm = QFontMetrics(QFont()) height = fm.height() + fm.height() // 3 self.userAgentsTable.verticalHeader().setDefaultSectionSize(height) self.userAgentsTable.verticalHeader().setMinimumSectionSize(-1) self.userAgentsTable.resizeColumnsToContents() self.userAgentsTable.horizontalHeader().setStretchLastSection(True)
def text(self, text: str, pos: QRectF, color: QColor=None, size: int=20, shaded: int=0, bold: bool=False,shrinkToFit=10) -> None: if not isinstance(text,str): text = "{}".format(text) self._font.setPointSize(size) if bold: self._font.setWeight(QFont.Black) else: self._font.setWeight(QFont.Bold) self._painter.setFont(self._font) fm = QFontMetrics(self._font) if pos.width() == 0: pos.setWidth(fm.width(text)) if pos.height() == 0: pos.setHeight(fm.height()) if size > shrinkToFit: # if fm.width(text) > pos.width() or fm.height() > pos.height()+2: self.text(text,pos,color,size-1,shaded,bold,shrinkToFit) return if shaded: diff = size//4 if isinstance(shaded,bool) and shaded == True else shaded self._painter.setPen(self._fgs) pos2 = pos.translated(diff, diff) self._painter.drawText(pos2, Qt.AlignCenter, text) p = QPen(color if color is not None else self._fg) self._painter.setPen(p) self._painter.drawText(pos, Qt.AlignCenter, text)
def resizeEvent(self, event): super(MyQLabel, self).resizeEvent(event) if not self.text(): return #--- fetch current parameters ---- f = self.font() cr = self.contentsRect() #--- iterate to find the font size that fits the contentsRect --- dw = event.size().width() - event.oldSize().width() # width change dh = event.size().height() - event.oldSize().height() # height change fs = max(f.pixelSize(), 1) while True: f.setPixelSize(fs) br = QFontMetrics(f).boundingRect(self.text()) if dw >= 0 and dh >= 0: # label is expanding if br.height() <= cr.height() and br.width() <= cr.width(): fs += 1 else: f.setPixelSize(max(fs - 1, 1)) # backtrack break else: # label is shrinking if br.height() > cr.height() or br.width() > cr.width(): fs -= 1 else: break if fs < 1: break #--- update font size --- self.setFont(f)
def __init__(self, parent=None): """ Constructor @param parent reference to the parent widget (QWidget) """ super(ZoomValuesDialog, self).__init__(parent) self.setupUi(self) self.removeButton.clicked.connect( self.zoomValuesTable.removeSelected) self.removeAllButton.clicked.connect(self.zoomValuesTable.removeAll) import Helpviewer.HelpWindow from .ZoomValuesModel import ZoomValuesModel self.zoomValuesTable.verticalHeader().hide() self.__zoomValuesModel = ZoomValuesModel( Helpviewer.HelpWindow.HelpWindow.zoomManager(), self) self.__proxyModel = QSortFilterProxyModel(self) self.__proxyModel.setSourceModel(self.__zoomValuesModel) self.searchEdit.textChanged.connect( self.__proxyModel.setFilterFixedString) self.zoomValuesTable.setModel(self.__proxyModel) fm = QFontMetrics(QFont()) height = fm.height() + fm.height() // 3 self.zoomValuesTable.verticalHeader().setDefaultSectionSize(height) self.zoomValuesTable.verticalHeader().setMinimumSectionSize(-1) self.__calculateHeaderSizes()
def __init__(self, cookieJar, parent=None): """ Constructor @param cookieJar reference to the cookie jar (CookieJar) @param parent reference to the parent widget (QWidget) """ super(CookiesExceptionsDialog, self).__init__(parent) self.setupUi(self) self.__cookieJar = cookieJar self.removeButton.clicked.connect(self.exceptionsTable.removeSelected) self.removeAllButton.clicked.connect(self.exceptionsTable.removeAll) self.exceptionsTable.verticalHeader().hide() self.__exceptionsModel = CookieExceptionsModel(cookieJar) self.__proxyModel = QSortFilterProxyModel(self) self.__proxyModel.setSourceModel(self.__exceptionsModel) self.searchEdit.textChanged.connect( self.__proxyModel.setFilterFixedString) self.exceptionsTable.setModel(self.__proxyModel) self.domainEdit.setCompleter( QCompleter(cookieJar.cookieDomains(), self.domainEdit)) f = QFont() f.setPointSize(10) fm = QFontMetrics(f) height = fm.height() + fm.height() // 3 self.exceptionsTable.verticalHeader().setDefaultSectionSize(height) self.exceptionsTable.verticalHeader().setMinimumSectionSize(-1) for section in range(self.__exceptionsModel.columnCount()): header = self.exceptionsTable.horizontalHeader().sectionSizeHint( section) if section == 0: try: header = fm.horizontalAdvance( "averagebiglonghost.averagedomain.info") except AttributeError: header = fm.width("averagebiglonghost.averagedomain.info") elif section == 1: try: header = fm.horizontalAdvance(self.tr("Allow For Session")) except AttributeError: header = fm.width(self.tr("Allow For Session")) try: buffer = fm.horizontalAdvance("mm") except AttributeError: buffer = fm.width("mm") header += buffer self.exceptionsTable.horizontalHeader().resizeSection( section, header)
def __init__(self, cookieJar, parent=None): """ Constructor @param cookieJar reference to the cookie jar (CookieJar) @param parent reference to the parent widget (QWidget) """ super(CookiesDialog, self).__init__(parent) self.setupUi(self) self.addButton.setEnabled(False) self.__cookieJar = cookieJar self.removeButton.clicked.connect(self.cookiesTable.removeSelected) self.removeAllButton.clicked.connect(self.cookiesTable.removeAll) self.cookiesTable.verticalHeader().hide() model = CookieModel(cookieJar, self) self.__proxyModel = QSortFilterProxyModel(self) self.__proxyModel.setSourceModel(model) self.searchEdit.textChanged.connect( self.__proxyModel.setFilterFixedString) self.cookiesTable.setModel(self.__proxyModel) self.cookiesTable.doubleClicked.connect(self.__showCookieDetails) self.cookiesTable.selectionModel().selectionChanged.connect( self.__tableSelectionChanged) self.cookiesTable.model().modelReset.connect(self.__tableModelReset) fm = QFontMetrics(QFont()) height = fm.height() + fm.height() // 3 self.cookiesTable.verticalHeader().setDefaultSectionSize(height) self.cookiesTable.verticalHeader().setMinimumSectionSize(-1) for section in range(model.columnCount()): header = self.cookiesTable.horizontalHeader()\ .sectionSizeHint(section) if section == 0: header = fm.width("averagebiglonghost.averagedomain.info") elif section == 1: header = fm.width("_session_id") elif section == 4: header = fm.width( QDateTime.currentDateTime().toString(Qt.LocalDate)) buffer = fm.width("mm") header += buffer self.cookiesTable.horizontalHeader().resizeSection(section, header) self.cookiesTable.horizontalHeader().setStretchLastSection(True) self.cookiesTable.model().sort( self.cookiesTable.horizontalHeader().sortIndicatorSection(), Qt.AscendingOrder) self.__detailsDialog = None
def __init__ (self, font): basefont = font boldfont = QFont(basefont) boldfont.setBold(True) italicfont = QFont(basefont) italicfont.setItalic(True) self.basefont = basefont self.boldfont = boldfont self.italicfont = italicfont basemetrics = QFontMetrics(basefont) self.basemetrics = basemetrics baseem = basemetrics.height() baseen = baseem // 2 boldmetrics = QFontMetrics(boldfont) self.boldheight = boldmetrics.height() nodemargin = baseen*3//5 itemmargin = baseen//2 activemargin = baseen*3//4 selectmargin = activemargin//2 self.nodemargin = nodemargin self.itemmargin = itemmargin self.activemargin = activemargin self.selectmargin = selectmargin self.shadowoffset = selectmargin self.nodemargins = QMarginsF(*(nodemargin,)*4) self.banknodemargins = QMarginsF(*(nodemargin//2,)*4) self.itemmargins = QMarginsF(*(itemmargin,)*4) self.activemargins = QMarginsF(*(selectmargin//2,)*4) self.selectmargins = QMarginsF(*(selectmargin//2,)*4) self.nodetextwidth = basemetrics.averageCharWidth()*40 nodewidth = self.nodetextwidth + 2*(activemargin+nodemargin+itemmargin) self.nodewidth = nodewidth rankgap = 7*activemargin self.rankgap = rankgap self.rankwidth = rankgap + nodewidth rowgap = 3*activemargin self.rowgap = rowgap # Edge style self.pensize = self.shadowoffset self.arrowsize = self.pensize * 3.5
class Danmu(QLabel): def __init__(self, parent, dmtext, dmcolor, dmstartx, dmstarty, dmfont="Microsoft YaHei"): super(Danmu, self).__init__(parent) self.dmQfont = QFont(dmfont, 25, 75) #字体、大小、粗细 self.setStyleSheet("color:" + dmcolor) self.dmtext = dmtext self.setText(self.dmtext) self.metrics = QFontMetrics(self.dmQfont) self.height = self.metrics.height() + 5 self.setFixedHeight(self.height) self.width = self.metrics.width(dmtext) + 4 self.setFixedWidth(self.width) self.setFont(self.dmQfont) self.fly = QPropertyAnimation(self, b'pos') #弹幕飞行动画 self.fly.setDuration(10000) #飞行10秒 self.fly.setStartValue(QtCore.QPoint(dmstartx, dmstarty)) self.fly.setEndValue(QtCore.QPoint(0 - self.width, dmstarty)) self.fly.start() self.fly.finished.connect(self.deleteLater) #为文字添加描边 def paintEvent(self, event): painter = QPainter(self) painter.save() path = QPainterPath() pen = QPen(QColor(0, 0, 0, 230)) painter.setRenderHint(QPainter.Antialiasing) #反走样 pen.setWidth(4) length = self.metrics.width(self.dmtext) w = self.width px = (length - w) / 2 if px < 0: px = -px py = (self.height - self.metrics.height()) / 2 + self.metrics.ascent() if py < 0: py = -py path.addText(px - 2, py, self.dmQfont, self.dmtext) painter.strokePath(path, pen) painter.drawPath(path) painter.fillPath(path, QBrush(QColor(255, 255, 255))) painter.restore() QLabel.paintEvent(self, event)
def formatString(self, string, x, y): font = QFont('Microsoft YaHei', 18) #font.setPixelSize(22) self.dialog.setFont(font) self.dialog.setStyleSheet( "QLabel{border-radius:15;padding:15px;background: rgb(0,128,255);color:white;width:auto;height:auto;word-wrap: break-word}" ) self.dialog.setText(string) #字体宽高 metr = QFontMetrics(self.dialog.font()) stringWidth = metr.width(self.dialog.text()) stringHeight = metr.height() lineCount = 1 if stringWidth < 300: dialogWidth = stringWidth + 40 dialogHeight = stringHeight * lineCount + 40 dialogX = x + 248 / 2 - stringWidth + 60 else: lineCount = math.ceil(stringWidth / 300) dialogWidth = 300 + 40 dialogHeight = stringHeight * lineCount + 40 dialogX = x + 248 / 2 - 250 dialogDetail = { 'dialogX': dialogX, 'dialogY': y - stringHeight * lineCount + 20, 'dialogWidth': dialogWidth, 'dialogHeight': dialogHeight } return dialogDetail
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 resizeEvent(self, event): super().resizeEvent(event) if not self.text(): return #--- fetch current parameters ---- f = self.font() cr = self.contentsRect() #--- find the font size that fits the contentsRect --- fs = 1 while True: f.setPixelSize(fs) br = QFontMetrics(f).boundingRect(self.text()) if br.height() <= cr.height() and br.width() <= cr.width(): fs += 1 else: f.setPixelSize(max(fs - 1, 1)) # backtrack break #--- update font size --- self.setFont(f)
def paint(self, painter: QPainter, option: 'QStyleOptionGraphicsItem', widget: Optional[QWidget] = ...) -> None: # painting circle if self.node.isInvalid(): painter.setBrush(self._invalid_brush) text = '!' elif self.node.isDirty(): painter.setBrush(self._dirty_brush) text = '?' else: painter.setBrush(self._valid_brush) text = "\N{CHECK MARK}" painter.setPen(self._pen if not self._hovered else self._pen_hovered) painter.drawEllipse(-self.radius, -self.radius, 2 * self.radius, 2 * self.radius) # Text in the status painter.setPen(self._pen_text) font = QFont('Ubuntu', self.radius * 2 - 6) fm = QFontMetrics(font) painter.setFont(font) painter.drawText(-fm.width(text) / 2, fm.height() / 2 - 4, text)
def build_bonus_fields(self): for bonus_field in self._bonus_fields: brush = bonus_field["Brush"] pen = bonus_field["Pen"] bonus_fields = [] for coords in bonus_field["Coords"]: label = bonus_field["Name"] if coords == Coords.central(): label = '✸' square = self._board_squares[coords] square.setZValue(2) bonus_fields.append(square) field_name = QGraphicsSimpleTextItem(label) font = field_name.font() font.setPointSize(10) if coords == Coords.central(): font.setPointSize(20) fm = QFontMetrics(font) field_name.setZValue(2.1) field_name.setFont(font) x = coords.x * SQUARE_SIZE + (SQUARE_SIZE - fm.width(label)) / 2 y = coords.y * SQUARE_SIZE + (SQUARE_SIZE - fm.height()) / 2 field_name.setPos(x, y) field_name.setBrush(bonus_field["Label brush"]) self._labels[(x, y)] = field_name self.scene.addItem(field_name) paint_graphic_items(bonus_fields, pen, brush)
def updateLabelRect(self): fm = QFontMetrics(self.font()) width = fm.width(self.label()) height = fm.height() self._label_rect = QRectF(-width/2, -height/2, width, height) self.invalidateShape()
def sizeHint(self, option, index): """ Public method to get a size hint for the specified list item. @param option style option used for painting (QStyleOptionViewItem) @param index model index of the item (QModelIndex) @return size hint (QSize) """ if not self.__rowHeight: opt = QStyleOptionViewItem(option) self.initStyleOption(opt, index) widget = opt.widget style = widget.style() if widget is not None \ else QApplication.style() padding = style.pixelMetric(QStyle.PM_FocusFrameHMargin) + 1 titleFont = opt.font titleFont.setBold(True) titleFont.setPointSize(titleFont.pointSize() + 1) self.__padding = padding \ if padding > GreaseMonkeyConfigurationListDelegate.MinPadding \ else GreaseMonkeyConfigurationListDelegate.MinPadding titleMetrics = QFontMetrics(titleFont) self.__rowHeight = 2 * self.__padding + \ opt.fontMetrics.leading() + \ opt.fontMetrics.height() + \ titleMetrics.height() return QSize(GreaseMonkeyConfigurationListDelegate.ItemWidth, self.__rowHeight)
def draw_indicator(indicator: int): pixmap = QPixmap(24, 24) painter = QPainter(pixmap) w, h = pixmap.width(), pixmap.height() painter.fillRect(0, 0, w, h, QBrush((QColor(0, 0, 200, 255)))) pen = QPen(QColor("white")) pen.setWidth(2) painter.setPen(pen) font = util.get_monospace_font() font.setBold(True) font.setPixelSize(16) painter.setFont(font) f = QFontMetrics(painter.font()) indicator_str = str(indicator) if indicator < 10 else "+" fw = f.width(indicator_str) fh = f.height() painter.drawText(math.ceil(w / 2 - fw / 2), math.ceil(h / 2 + fh / 4), indicator_str) painter.end() return QIcon(pixmap)
def paintEvent(self, event): 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 _resize_to_content(self, line_edit): text = line_edit.text() font = QFont('', 0) fm = QFontMetrics(font) pixelsWide = fm.width(text) pixelsHigh = fm.height() line_edit.setFixedSize(pixelsWide, pixelsHigh)
def data(self, index, role=Qt.EditRole): level = 0 i = index while i.parent() != QModelIndex(): i = i.parent() level += 1 if role == Qt.BackgroundRole: if level == 0: return QBrush(lightBlue()) if role == Qt.TextAlignmentRole: if level == 0: return Qt.AlignCenter if role == Qt.FontRole: if level in [0, 1]: f = qApp.font() f.setBold(True) return f if role == Qt.ForegroundRole: if level == 0: return QBrush(Qt.darkBlue) if role == Qt.SizeHintRole: fm = QFontMetrics(qApp.font()) h = fm.height() if level == 0: return QSize(0, h + 12) elif level == 1: return QSize(0, h + 6) return QStandardItemModel.data(self, index, role)
def addPort(self, name, isOutput = False, flags = 0, ptr = None): port = QNEPort(self) port.setName(name) port.setIsOutput(isOutput) port.setNEBlock(self) port.setPortFlags(flags) port.setPtr(ptr) fontmetrics = QFontMetrics(self.scene().font()); width = fontmetrics.width(name) height = fontmetrics.height() if width > self.width - self.horzMargin: self.width = width + self.horzMargin self.height += height path = QPainterPath() path.addRoundedRect(-self.width/2, -self.height/2, self.width, self.height, 5, 5) self.setPath(path) y = -self.height / 2 + self.vertMargin + port.radius() for port_ in self.childItems(): if port_.type() != QNEPort.Type: continue if port_.isOutput(): port_.setPos(self.width/2 + port.radius(), y) else: port_.setPos(-self.width/2 - port.radius(), y) y += height; return port
def data(self, index, role=Qt.EditRole): level = 0 i = index while i.parent() != QModelIndex(): i = i.parent() level += 1 if role == Qt.BackgroundRole: if level == 0: return QBrush(QColor(S.highlightLight)) if role == Qt.TextAlignmentRole: if level == 0: return Qt.AlignCenter if role == Qt.FontRole: if level in [0, 1]: f = qApp.font() f.setBold(True) return f if role == Qt.ForegroundRole: if level == 0: return QBrush(QColor(S.highlightedTextDark)) if role == Qt.SizeHintRole: fm = QFontMetrics(qApp.font()) h = fm.height() if level == 0: return QSize(0, h + 12) elif level == 1: return QSize(0, h + 6) return QStandardItemModel.data(self, index, role)
def changeSize(self, w, h): """ Resize block function """ # Limit the block size: metric = QFontMetrics(self.label.font()) width = metric.width(self.name) height = metric.height() if h < height + 5: h = height + 5 if w < width + 5: w = width + 5 self.setRect(0.0, 0.0, w, h) # center label: rect = self.label.boundingRect() lw, lh = rect.width(), rect.height() lx = (w - lw) / 2 ly = (h - lh) / 2 self.label.setPos(lx, ly) # Update port positions: self.ports[0].setPos(0, h / 2) self.ports[1].setPos(w / 2, 0) self.ports[2].setPos(w, h / 2) self.ports[3].setPos(w / 2, h) return w, h
def highligting(self, color, underline_width): color = QColor(color) color = QColor(color.red(), color.green(), color.blue(), 200) painter = QPainter(self) if config.hover_underline: font_metrics = QFontMetrics(self.font()) text_width = font_metrics.width(self.word) text_height = font_metrics.height() brush = QBrush(color) pen = QPen(brush, underline_width, Qt.SolidLine, Qt.RoundCap) painter.setPen(pen) if not self.skip: painter.drawLine(0, text_height - underline_width, text_width, text_height - underline_width) if config.hover_hightlight: x = y = 0 y += self.fontMetrics().ascent() painter.setPen(color) painter.drawText( x, y + config.outline_top_padding - config.outline_bottom_padding, self.word)
class AccountEditorSectionSeparatorWidget(QWidget): def __init__(self, *args, **kwargs): self.__sectionText = kwargs.pop("sectionName") self.__sectionFont = QFont(QFont('Nimbus Sans L', 12, QFont.Bold)) self.__sectionFontColor = QColor("#777777") self.__sectionLineColor = QColor("#ECECEC") self.__sectionFontMetrics = QFontMetrics(self.__sectionFont) super().__init__(*args, **kwargs) self.setFixedSize(960, 25) def paintEvent(self, _): qp = QPainter() qp.begin(self) self.__drawWidget(qp) qp.end() def __drawWidget(self, painter): width = self.__sectionFontMetrics.width(self.__sectionText) height = self.__sectionFontMetrics.height() painter.setFont(self.__sectionFont) painter.setPen(QPen(self.__sectionFontColor, 1, Qt.SolidLine)) painter.drawText(QRect(480 - (width / 2), 0, width, height), Qt.AlignCenter, self.__sectionText) painter.setPen(QPen(self.__sectionLineColor, 1, Qt.SolidLine)) painter.drawLine(0, (height / 2) + 1, 480 - (width / 2 + 5), (height / 2) + 1) painter.drawLine(485 + (width / 2), (height / 2) + 1, 940, (height / 2) + 1)
def __init__(self, parent): super().__init__(parent) pvMet = QFontMetrics(self.font()) pvLineHeight = pvMet.height() self.setMaximumHeight(pvLineHeight * 12) self.setMinimumHeight(pvLineHeight * 12) self.setWordWrap(True)
def drawDigitalValueUnits(self): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) painter.translate(self.width() / 2, self.height() / 2) font = QFont(self.digitalValueFontName, self.digitalValueUnitsFontSize) fm = QFontMetrics(font) penShadow = QPen() penShadow.setBrush(self.digitalValueColor) painter.setPen(penShadow) digitalValueRadius = self.widgetDiameter / 2 * self.digitalValueRadius text = self.gaugeValueUnits w = fm.width(text) + 1 h = fm.height() painter.setFont( QFont(self.digitalValueFontName, self.digitalValueUnitsFontSize)) 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)) text = [ x - int(w / 2) + 20, 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 setMinSize(self, minfs): f = self.font() f.setPixelSize(minfs) br = QFontMetrics(f).boundingRect(self.text()) self.setMinimumSize(br.width(), br.height())
def get_base_font_size(self): """Gets the base font size for all the UI elements. Returns: int: Base font size. """ self.__logger.info( "Calculating appropriated base font size for UI elements...") font_fits = False # Base font size will be calculated using self.label_password attribute font = self.label_password.font() font_size = font.pointSize() while not font_fits: fm = QFontMetrics(font) pixels_wide = fm.width(self.label_password.text()) pixels_high = fm.height() bound = fm.boundingRect(0, 0, pixels_wide, pixels_high, Qt.TextWordWrap | Qt.AlignLeft, self.label_password.text()) if bound.width() <= self.label_password.width() and \ bound.height() <= self.label_password.height(): font_fits = True else: font.setPointSize(font.pointSize() - 1) font_size = font_size - 1 self.__logger.info("Base font size = " + str(font_size)) return font_size
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 paintEvent(self, ev): super(TagsLabelWidget, self).paintEvent(ev) painter = QPainter(self) painter.save() try: painter.setBackground(self.palette().brush(self.backgroundRole())) painter.eraseRect(ev.rect()) painter.setClipRect(ev.rect()) fm = QFontMetrics(self.font()) # TODO use style x = self.xmargin for sz, tag in self._positions(self.tags): fg, bg = tag_to_colors(tag) painter.setPen(fg.color()) painter.fillRect(x, self.ymargin, sz.width() + 2 * self.xpadding, fm.height(), bg.color()) painter.drawText(x + self.xpadding, self.ymargin + fm.ascent(), tag) x += sz.width() + self.xmargin + 2 * self.xpadding finally: painter.restore()
def _paint_tooltip(self, painter: QPainter, point: QPoint, y: int, x: int, plot_name: str, color: QColor, vertical_offset: int) -> int: painter.setPen(QPen(QColor(40, 40, 40))) res = self._tooltip_func(y, x, plot_name) painter.setBrush(self._default_tooltip_brush) point = QPoint(point.x() + self._tooltip_horizontal_offset, point.y() + vertical_offset) color = QColor(min(color.red() * 1.4, 255), min(color.green() * 1.4, 255), min(color.blue() * 1.4, 255), 200) if res is not None: lines: List = res.split('\n') lengths = [len(l) for l in lines] fm = QFontMetrics(self.font) width = fm.width(lines[lengths.index(max(lengths))]) height = fm.height() * len(lines) path = QPainterPath() path.addRoundedRect( QRectF(QPointF(point.x() - 5, point.y() - 5), QSizeF(width + 10, height + 10)), 10., 10.) painter.fillPath(path, color) painter.drawPath(path) painter.drawText(QRect(point, QSize(width, height)), xor(Qt.AlignLeft, Qt.AlignTop), res) return height + 11 return 0
def mousePressEvent(self, event): fm = QFontMetrics(self.font()) self.selectedRow = event.y() // fm.height() self.update() #self.emit(SIGNAL("clicked(QModelIndex)"), # self.model.index(self.selectedRow, 0)) self.clicked.emit(self.model.index(self.selectedRow, 0))
def set_font(self, font: QFont = None): qfd = QFontDatabase() if font: info = QFontInfo(font) if info.styleHint() != QFont.Monospace: self.logger.warning("font: Please use monospaced font! " f"Unsupported font {info.family}.") font = qfd.systemFont(QFontDatabase.FixedFont) elif "Menlo" in qfd.families(): font = QFont("Menlo") info = QFontInfo(font) else: font = qfd.systemFont(QFontDatabase.FixedFont) info = QFontInfo(font) font.setPointSize(12) self.font = font metrics = QFontMetrics(font) self.char_width = metrics.horizontalAdvance("A") self.char_height = metrics.height() self.line_height = int(self.char_height * 1.2) self.logger.info(f"font: Font {info.family()} selected, character " f"size {self.char_width}x{self.char_height}.") self.row_len = int(self._width / self.char_width) self.col_len = int(self._height / self.line_height)
def drawText(self, qp): heights = 0 widths = 0 for index in xrange(len(self.fonts)): infoFont = self.fonts[index] font = QFont() font.setFamily(infoFont[0]) if infoFont[1] != u'font without family': font.setStyleName(infoFont[1]) font.setPointSize(self.fontSize) if qp is not None: qp.setFont(font) fullname = infoFont[ 2] if infoFont[2] != u'font without fullname' else infoFont[0] unicode = fullname + u': ' + self.text fm = QFontMetrics(font) height = fm.height() width = fm.width(unicode) heights += (height + self.fontVerticalSpace) widths = width if width > widths else width if qp is not None: qp.drawText(10, heights + 0, unicode) self.widths = widths self.heights = heights
def layout(self): cell_width = (self.rect.width()) / 7.0 cell_height = (self.rect.height() - 64) / 7.0 x = self.rect.left() y = self.rect.top() fm = QFontMetrics(self.header.font()) rect = fm.boundingRect(self.header.text()) self.header.setPos(x + self.rect.width() / 2 - rect.width() / 2, y) y += fm.height() for row, day in enumerate(self.weekdays): fm = QFontMetrics(day.font()) rect = fm.boundingRect(day.text()) day.setPos(x + row * cell_width + cell_width / 2 - rect.width() / 2, y) y += fm.height() self.header_line.setLine(x, y, x + self.rect.width() - 3, y) y += 8 for n, widget in enumerate(self.days): col = n % 7 row = n // 7 rect = fm.boundingRect(widget.text()) widget.setPos(x + col * cell_width + cell_width / 2 - rect.width() / 2, y + row * cell_height + cell_height / 2 - fm.height() / 2) # if day.month != self.now.month: # widget.setBrush(self.style.midcolor) # else: if self.cursor_pos is not None: self.cursor.setRect(x + self.cursor_pos[0] * cell_width, y + self.cursor_pos[1] * cell_height, cell_width, cell_height) self.cursor.show() else: self.cursor.hide()
def __init__(self, cookieJar, parent=None): """ Constructor @param cookieJar reference to the cookie jar (CookieJar) @param parent reference to the parent widget (QWidget) """ super(CookiesExceptionsDialog, self).__init__(parent) self.setupUi(self) self.__cookieJar = cookieJar self.removeButton.clicked.connect( self.exceptionsTable.removeSelected) self.removeAllButton.clicked.connect( self.exceptionsTable.removeAll) self.exceptionsTable.verticalHeader().hide() self.__exceptionsModel = CookieExceptionsModel(cookieJar) self.__proxyModel = QSortFilterProxyModel(self) self.__proxyModel.setSourceModel(self.__exceptionsModel) self.searchEdit.textChanged.connect( self.__proxyModel.setFilterFixedString) self.exceptionsTable.setModel(self.__proxyModel) cookieModel = CookieModel(cookieJar, self) self.domainEdit.setCompleter(QCompleter(cookieModel, self.domainEdit)) f = QFont() f.setPointSize(10) fm = QFontMetrics(f) height = fm.height() + fm.height() // 3 self.exceptionsTable.verticalHeader().setDefaultSectionSize(height) self.exceptionsTable.verticalHeader().setMinimumSectionSize(-1) for section in range(self.__exceptionsModel.columnCount()): header = self.exceptionsTable.horizontalHeader()\ .sectionSizeHint(section) if section == 0: header = fm.width("averagebiglonghost.averagedomain.info") elif section == 1: header = fm.width(self.tr("Allow For Session")) buffer = fm.width("mm") header += buffer self.exceptionsTable.horizontalHeader()\ .resizeSection(section, header)
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 sizeHint(self, option, qidx): fm = QFontMetrics(option.font) x = self.xmargin y = 0 for sz, tag in self._positions(option, qidx): x += sz.width() + self.xmargin + 2 * self.xpadding y = self.ymargin * 2 + fm.height() return QSize(x, y)
def __init__(self, parent): super().__init__(parent) font = self.font() font.setPointSize(16) met = QFontMetrics(font) scoreLineHeight = met.height() self.setFont(font) self.setMinimumHeight(scoreLineHeight) self.setMinimumWidth(met.width('30'))
def __init__(self, ds): rowFM = QFontMetrics(ds.rowFont()) self.splitFM = QFontMetrics(ds.splitFont()) headerFM = QFontMetrics(ds.headerFont()) self.rowHeight = rowFM.height() + CELL_MARGIN * 2 self.splitHeight = self.splitFM.height() + CELL_MARGIN * 2 self.headerHeight = headerFM.height() + CELL_MARGIN * 2 spannedRowIndexes = set() for rowIndex in range(ds.rowCount()): extraRole = nonone(ds.data(rowIndex, 0, EXTRA_ROLE), 0) if extraRole & EXTRA_SPAN_ALL_COLUMNS: spannedRowIndexes.add(rowIndex) self.columns = [] for colIndex in range(ds.columnCount()): col = ds.columnAtIndex(colIndex) sumWidth = 0 maxWidth = 0 # We need to have *at least* the width of the header. minWidth = headerFM.width(col.display) + CELL_MARGIN * 2 for rowIndex in range(ds.rowCount()): if rowIndex in spannedRowIndexes: continue data = ds.data(rowIndex, colIndex, Qt.DisplayRole) if data: font = ds.data(rowIndex, colIndex, Qt.FontRole) fm = QFontMetrics(font) if font is not None else rowFM width = fm.width(data) + CELL_MARGIN * 2 width += ds.indentation(rowIndex, colIndex) sumWidth += width maxWidth = max(maxWidth, width) pixmap = ds.data(rowIndex, colIndex, Qt.DecorationRole) if pixmap is not None: width = pixmap.width() + CELL_MARGIN * 2 maxWidth = max(maxWidth, width) avgWidth = sumWidth // ds.rowCount() maxWidth = max(maxWidth, minWidth) if col.cantTruncate: # if it's a "can't truncate" column, we make no concession minWidth = maxWidth cs = ColumnStats(colIndex, col, avgWidth, maxWidth, minWidth) self.columns.append(cs) self.maxWidth = sum(cs.maxWidth for cs in self.columns) self.minWidth = sum(cs.minWidth for cs in self.columns)
def __init__(self, page): font = QFont(QApplication.font()) font.setBold(True) fm = QFontMetrics(font) titleBase = page.viewPrinter.title titleLineCount = len(titleBase.split("\n")) titleHeight = fm.height() * titleLineCount rect = QRect(page.pageRect.topLeft(), QSize(page.pageRect.width(), titleHeight)) LayoutElement.__init__(self, rect) self.page = page self.font = font
def _scaleLenght(self): fmr = QFontMetrics(self._font).boundingRect(self._units) if self._orientation == Qt.Horizontal: w = fmr.width()+2 lenght = self.geometry().width() - w else: h = fmr.height()+1 lenght = self.geometry().height() - h return lenght
def __init__(self, app, view, **kwargs): model = app.model.result_table super().__init__(model, view, **kwargs) view.horizontalHeader().setSortIndicator(1, Qt.AscendingOrder) font = view.font() font.setPointSize(app.prefs.tableFontSize) self.view.setFont(font) fm = QFontMetrics(font) view.verticalHeader().setDefaultSectionSize(fm.height()+2) app.willSavePrefs.connect(self.appWillSavePrefs)
def _updateFontSize(self, prefs): font = self.view.font() font.setPointSize(prefs.tableFontSize) self.view.setFont(font) fm = QFontMetrics(font) self.view.verticalHeader().setDefaultSectionSize(fm.height()+2) # (#14, #15) When a new font was selected in the preferences panel, # the column would redraw but not resize appropriately. A call # to resize(sizeHint()) was added on the update of the size info # in the custom drawing for the amount field. self.view.resize(self.view.sizeHint())
def reshape(self): ''' Update the shape of the edge (redefined function) ''' path = QPainterPath() # If there is a starting point, draw a line to the first curve point if self.start_point: path.moveTo(self.source_connection.center) path.lineTo(self.bezier[0]) else: path.moveTo(self.source_connection.center) # Loop over the curve points: for group in self.bezier[1:]: path.cubicTo(*[point.center for point in group]) # If there is an ending point, draw a line to it if self.end_point: path.lineTo(self.end_connection.center) end_point = path.currentPosition() arrowhead = self.angle_arrow(path) path.lineTo(arrowhead[0]) path.moveTo(end_point) path.lineTo(arrowhead[1]) path.moveTo(end_point) try: # Add the transition label, if any (none for the START edge) font = QFont('arial', pointSize=8) metrics = QFontMetrics(font) label = self.edge.get('label', '') lines = label.split('\n') width = metrics.width(max(lines)) # longest line height = metrics.height() * len(lines) # lp is the position of the center of the text pos = self.mapFromScene(*self.edge['lp']) if not self.text_label: self.text_label = QGraphicsTextItem( self.edge.get('label', ''), parent=self) self.text_label.setX(pos.x() - width / 2) self.text_label.setY(pos.y() - height / 2) self.text_label.setFont(font) # Make horizontal center alignment, as dot does self.text_label.setTextWidth(self.text_label.boundingRect().width()) fmt = QTextBlockFormat() fmt.setAlignment(Qt.AlignHCenter) cursor = self.text_label.textCursor() cursor.select(QTextCursor.Document) cursor.mergeBlockFormat(fmt) cursor.clearSelection() self.text_label.setTextCursor(cursor) self.text_label.show() except KeyError: # no label pass self.setPath(path)
def _drawPlanetTitle(self, painter: QPainter): font = QFont('Tahoma', 10, QFont.Bold) font_coords = QFont('Tahoma', 8) font_metrics = QFontMetrics(font) font_h = font_metrics.height() # logger.debug('font h = {0}'.format(font_h)) font.setStyleStrategy(QFont.ForceOutline) text_color = QColor(255, 255, 255, 255) # rgba self._drawTextShadow(painter, 5, 1+font_h, self._planet.name, font, text_color) # planet coords scoords = '[{0}:{1}:{2}]'.format(self._planet.coords.galaxy, self._planet.coords.system, self._planet.coords.position) self._drawTextShadow(painter, 5, 1+font_h+2+font_h, scoords, font_coords, text_color)
def sizeHint(self): fm = QFontMetrics(self.font()) # FIXME: 暂时不是太懂应该怎样正确的计算 w 和 h # 计算 h 的一个原则是让高度正好能够显示一行 h = max(fm.height() + fm.ascent() - fm.descent(), 14) w = self.width() - 4 opt = QStyleOptionFrame() opt.initFrom(self) return self.style().sizeFromContents( QStyle.CT_LineEdit, opt, QSize(w, h).expandedTo(QApplication.globalStrut()), self )
def _paintVertical(self, painter): """ Paint vertical scale """ fm = QFontMetrics(self._font) fwidth = 25 if self._flip: x0 = fwidth x1 = x0 + 3 x11 = x0 + 5 # x12 = 10 else: x0 = self.geometry().width() - fwidth x1 = x0 - 3 x11 = x0 - 5 x12 = x0 y0 = 0 y1 = self._scaleLenght() lbls = self._labels.replace(' ', '').split(',') if self._show_lines: # base line painter.drawLine(x0, y0, x0, y1) # cent lines for i in range(0, self._scaleLenght() + 1): pos = self._calcPos(self._scale_cent * i) painter.drawLine(x1, pos, x0, pos) for lbl in lbls: pos = self._calcPos(int(lbl)) painter.drawLine(x11, pos, x0, pos) # labels if self._show_labels: for lbl in self._labels.replace(' ', '').split(','): pos = self._calcPos(int(lbl)) if self._flip: x12 = (x0 - fm.boundingRect(lbl).width()) - 4 self._paintLabel(lbl, x12, pos, painter) # draw units label y = self._scaleLenght() + fm.height() + 1 pen = painter.pen() pen.setColor(pen.color().lighter(120)) painter.setPen(pen) painter.drawText( QPoint(x12, y), self._units )
def font_charBmp(font, char): metric = QFontMetrics( font ).boundingRect( char ) char_rect = QRect( 0, 0, metric.width(), metric.height() ) chr_img = QImage( char_rect.width()+1, char_rect.height(), QImage.Format_Mono ) chr_img.fill(0) # set img painter and draw char to bmp painter = QPainter( chr_img ) painter.setPen( QPen(Qt.white) ) painter.setFont( font ) painter.drawText( char_rect, Qt.AlignJustify, char ) painter.end() del(painter) # crop left / right x0 = 0 x1 = char_rect.width() while x0 < x1 - 1: data_col = 0 for col in range( char_rect.height() ): data_col += chr_img.pixel(x0, col) & 0x00FFFFFF if not data_col: x0 += 1 else: break char_rect.setX(x0) while x1 > x0 + 1: x1 -= 1 data_col = 0 for col in range( char_rect.height() ): data_col += chr_img.pixel(x1, col) & 0x00FFFFFF if not data_col: char_rect.setWidth(x1 - x0) else: break # crop bottom y1 = char_rect.height() while y1 > 1: y1 -= 1 data_row = 0 for row in range( char_rect.width() ): data_row += chr_img.pixel(row, y1) & 0x00FFFFFF if not data_row: char_rect.setHeight(y1) else: break chr_img = chr_img.copy( char_rect ) # chr_img.save( '.\\img\\0%s.bmp' % char, 'bmp' ) return chr_img
def _paintHorizontal(self, painter): """ Paint horizontal scale """ if self._show_labels: fm = QFontMetrics(self._font) fheight = fm.height() - fm.descent() else: fheight = 0 if self._flip: y0 = fheight y1 = y0+3 y11 = y0+5 y12 = y0-1 else: y0 = self.geometry().height() - fheight y1 = y0-3 y11 = y0-5 y12 = self.geometry().height() x0 = 0 x1 = self._scaleLenght() lbls = self._labels.replace(' ', '').split(',') if self._show_lines: # base line painter.drawLine(x0, y0, x1, y0) # cent lines for i in range(0, self._scaleLenght() + 1): pos = self._calcPos(self._scale_cent * i) painter.drawLine(pos, y0, pos, y1) for lbl in lbls: pos = self._calcPos(int(lbl)) painter.drawLine(pos, y0, pos, y11) # labels if self._show_labels: for lbl in lbls: pos = self._calcPos(int(lbl)) self._paintLabel(lbl, pos, y12, painter) # draw units label x = self._scaleLenght()+1 pen = painter.pen() pen.setColor(pen.color().lighter(120)) painter.setPen(pen) painter.drawText( QPoint(x, y12), self._units )
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 _tab_size_hint(self, minimum=False): bold_font = self.font() bold_font.setPointSizeF(7.5) bold_font.setBold(True) fm = QFontMetrics(bold_font) spacing = 10 width = 40 + spacing + 2 max_label_width = 0 for tab in self.__tabs: _width = fm.width(tab.text) if _width > max_label_width: max_label_width = _width icon_height = 0 if minimum else 32 return QSize( max(width, max_label_width + 4), icon_height + spacing + fm.height())
def paintEvent(self, evt: QPaintEvent): # default painting, should paint icon super(ButtonTextOverIcon, self).paintEvent(evt) # draw text over it, only if it not empty string if (self._text is not None) and (self._text != ''): # calculate the width of text in pixels font = self.font() font_metrics = QFontMetrics(font) text_width = font_metrics.width(self._text) text_height = font_metrics.height() # calculate text output coordinates centered w = self.width() h = self.height() x = w//2 - text_width//2 y = h//2 - text_height//2 # draw text, centered inside window painter = QPainter(self) y += font_metrics.ascent() # Note: The y-position is used as the baseline of the font. add it self._drawTextShadow(painter, x, y, self._text)