def _labelscale(self, scene, font, offset, scalelen, label1, label10): metrics = QFontMetrics(font) pen = QPen(self._color()) y = offset * 0.2 w = scalelen * abs(offsets[N][1]) h = metrics.height() * 0.2 lines = [] lines.append(scene.addLine(0, y, 0, y + h, pen)) lines.append(scene.addLine(0, y + h, w, y + h, pen)) lines.append(scene.addLine(w, y + h, w, y + h/2.0, pen)) lines.append(scene.addLine(w, y + h, 10 * w, y + h, pen)) lines.append(scene.addLine(10 * w, y + h, 10 * w, y, pen)) text = self._addtext(scene, font, label1, (0, offset * 0.2), 0) text10 = self._addtext(scene, font, label10, (0, offset * 0.2), 0) x1 = 5 * w - metrics.width(label1) * 0.1 x10 = 50 * w - metrics.width(label10) * 0.1 overlap = x1 + text10.boundingRect().width() - x10 if overlap > 0: x1 -= overlap/2 x10 += overlap/2 text.translate(x1, y + h + metrics.height()) text10.translate(x10, y + h + metrics.height()) return [text, text10] + lines
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 set(self, U=None, vmin=None, vmax=None): # normalize U fm = QFontMetrics(self.font()) self.vmin = vmin if vmin is not None else ( np.min(U) if U is not None else 0.) self.vmax = vmax if vmax is not None else ( np.max(U) if U is not None else 1.) difference = abs(self.vmin - self.vmax) if difference == 0: precision = 3 else: precision = m.log( max(abs(self.vmin), abs(self.vmax)) / difference, 10) + 1 precision = int(min(max(precision, 3), 8)) self.vmin_str = format( ('{:.' + str(precision) + '}').format(self.vmin)) self.vmax_str = format( ('{:.' + str(precision) + '}').format(self.vmax)) self.vmin_width = fm.width(self.vmin_str) self.vmax_width = fm.width(self.vmax_str) self.text_height = fm.height() * 1.5 self.text_ascent = fm.ascent() * 1.5 self.text_descent = fm.descent() * 1.5 self.setMinimumSize( max(self.vmin_width, self.vmax_width) + 20, 300) self.update()
def text_size ( self, text ): """ Returns the size (dx,dy) of the specified text string (using the current control font). """ rect = QFontMetrics( self.control.font() ).boundingRect( text ) return ( rect.width(), rect.height() )
def _addglyph(self, scene, font, glyph, item): offset = item.boundingRect().center().toTuple() text = scene.addText(glyph, font) metrics = QFontMetrics(font) text.translate(offset[0] - metrics.width(glyph) * 0.2, offset[1] - metrics.height() * 0.2) text.scale(0.2, 0.2) return text
def _addtext(self, scene, font, content, offset, rotation): text = scene.addText(content, font) text.setDefaultTextColor(self._color()) metrics = QFontMetrics(font) text.translate(offset[0] - 2, offset[1] - sqrt(3)/2 - metrics.height() * 0.1) text.scale(0.2, 0.2) text.setTransformOriginPoint(*text.boundingRect().center().toTuple()) text.setRotation(rotation) return text
def innerSize(self): fontmetrics = QFontMetrics(self.scene().font()) height = fontmetrics.height() width = fontmetrics.width(self.name) if self.m_portFlags == 0: width = width + self.widgetWidth return QSize(width, height)
def innerSize(self): fontmetrics = QFontMetrics(self.scene().font()) height = fontmetrics.height() width = fontmetrics.width(self.name) if self.m_portFlags == 0: width = width + self.widgetWidth return QSize(width, height)
def _init_ui(self, txt): self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.FramelessWindowHint) pal = QPalette() color = QColor() color.setNamedColor(self._window_bgcolor) color.setAlpha(255 * self._opacity) pal.setColor(QPalette.Background, color) self.setAutoFillBackground(True) self.setPalette(pal) wm, hm = 5, 5 spacing = 8 layout = QVBoxLayout() layout.setSpacing(spacing) layout.setContentsMargins(wm, hm, wm, hm) nlines, ts = self._generate_text(txt) qlabel = QLabel('\n'.join(ts)) ss = 'QLabel {{color: {}; font-family:{}, sans-serif; font-size: {}px}}'.format(self._color, self._font, self._fontsize) qlabel.setStyleSheet(ss) layout.addWidget(qlabel) hlabel = QLabel('double click to dismiss') hlabel.setStyleSheet('QLabel {font-size: 10px}') hlayout = QHBoxLayout() hlayout.addStretch() hlayout.addWidget(hlabel) hlayout.addStretch() layout.addLayout(hlayout) self.setLayout(layout) font = QFont(self._font, self._fontsize) fm = QFontMetrics(font) pw = max([fm.width(ti) for ti in ts]) ph = (fm.height() + 2) * nlines w = pw + wm * 2 h = ph + (hm + spacing + 1) * 2 self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.setFixedWidth(w) self.setFixedHeight(h) self.setMask(mask(self.rect(), 10))
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', '') or '' 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 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', '') or '' 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 set(self, U=None, vmin=None, vmax=None): # normalize U fm = QFontMetrics(self.font()) self.vmin = vmin if vmin is not None else (np.min(U) if U is not None else 0.) self.vmax = vmax if vmax is not None else (np.max(U) if U is not None else 1.) precision = m.log(max(abs(self.vmin), abs(self.vmax) / abs(self.vmin - self.vmax)), 10) + 1 precision = int(min(max(precision, 3), 8)) self.vmin_str = format(('{:.' + str(precision) + '}').format(self.vmin)) self.vmax_str = format(('{:.' + str(precision) + '}').format(self.vmax)) self.vmin_width = fm.width(self.vmin_str) self.vmax_width = fm.width(self.vmax_str) self.text_height = fm.height() * 1.5 self.text_ascent = fm.ascent() * 1.5 self.text_descent = fm.descent() * 1.5 self.setMinimumSize(max(self.vmin_width, self.vmax_width) + 20, 300) self.update()
def __init__(self, *args, **kw): super(myTableView, self).__init__(*args, **kw) editor = self._editor self.clear_selection_on_dclicked = editor.factory.clear_selection_on_dclicked font = editor.factory.cell_font if font is not None: fnt = QFont(font) size = QFontMetrics(fnt) vheader = self.verticalHeader() hheader = self.horizontalHeader() vheader.setDefaultSectionSize(size.height() + 2) #hheader.setStretchLastSection(editor.factory.stretch_last_section) hheader.setFont(fnt)
def __init__(self, *args, **kw): super(_myTableView, self).__init__(*args, **kw) self.setDragDropMode(QAbstractItemView.DragDrop) self.setup_consumer() editor = self._editor # # reimplement row height vheader = self.verticalHeader() size = vheader.minimumSectionSize() font = editor.adapter.get_font(editor.object, editor.name, 0) if font is not None: fnt = QFont(font) size = QFontMetrics(fnt) vheader.setDefaultSectionSize(size.height() + 2) hheader = self.horizontalHeader() #hheader.setStretchLastSection(editor.factory.stretch_last_section) hheader.setFont(fnt)
def resize_font(self): """ Resize the label's font size to the maximum that will fit within the boundaries of the widget. """ width = self.width() height = self.height() font = self.font() text = self.text() size = 1 font.setPointSize(size) bounds = QFontMetrics(font).boundingRect(text) while bounds.width() <= width and bounds.height() <= height: size += 1 font.setPointSize(size) bounds = QFontMetrics(font).boundingRect(text) self.setFont(font)
class ClassyNode(QGraphicsItem): def __init__(self, name): QGraphicsItem.__init__(self) self.label = name self.edges_in = [] self.edges_out = [] self.metrics = QFontMetrics(nodes_font) self._b_width = 0 self._b_height = 0 self._x = 0 self._y = 0 self.margin = 5 self.node_pen = QPen(QColor(30, 30, 30)) self.selected_pen = QPen(QColor(200, 200, 30)) self.node_brush = QBrush(QColor(120, 120, 30)) self._update_size() self.setFlags(QGraphicsItem.ItemIsMovable | QGraphicsItem.ItemIsSelectable) def boundingRect(self): return QRect(self._x, self._y, self._b_width, self._b_height) def _update_size(self): self._b_width = self.metrics.width(self.label + "XXX") + (self.margin * 2) + 15 self._b_height = self.metrics.height() + (self.margin * 2) self._x = -(self._b_width / 2) - self.margin self._y = -(self._b_height / 2) - self.margin def paint(self, painter, option, widget=None): """ Override of QGraphicsItem.paint method. Implement this in your child classes to make nodes with the look you want. :param QPainter painter: :param option: :param widget: """ painter.setRenderHint(QPainter.Antialiasing) # --- Distinguish the selected nodes from the unselected ones. if self.isSelected(): painter.setPen(self.selected_pen) else: painter.setPen(self.node_pen) painter.setBrush(self.node_brush) r = self.boundingRect() painter.drawRect(r) # --- Draw name of the node painter.setPen(self.node_pen) painter.setFont(nodes_font) painter.drawText(r.bottomLeft().x() + self.margin, r.bottomLeft().y() - self.margin, self.label) def itemChange(self, change, value): if change == QGraphicsItem.ItemPositionChange and self.scene(): for e in self.edges_in: e.update() for e in self.edges_out: e.update() return QGraphicsItem.itemChange(self, change, value)
from sys import argv, exit from PySide.QtGui import QApplication, QFont, QFontMetrics, QX11Info from mainwindow import MainWindow app = QApplication(argv) font = QFont(QApplication.font()) font.setPointSize(9) QApplication.setFont(font) w = MainWindow() metrics = QFontMetrics(font) w.resize(metrics.width('M') * 80, metrics.height() * 24) w.show() exit(app.exec_())
def print_(self, printer): painter = QPainter(printer) pageRect = printer.pageRect() w = pageRect.width() * 0.85 h = pageRect.height() painter.drawPixmap(0, 0, w, h, './template/image.png') sansFont = QFont("Helvetica", 10) painter.setFont(sansFont) fm = QFontMetrics(sansFont) height = fm.height() + 10 vmargin = 40 x0 = w + 1 y = 25 width = fm.width(u"测试编号") + 25 x1 = x0 + width painter.drawText(x0, y, u"报告编号") painter.drawText(x1, y, self.report['SERIAL']) y += height painter.drawText(x0, y, u"测试类型") painter.drawText(x1, y, self.report['TYPE']) y += height painter.drawText(x0, y, u"触发方式") painter.drawText(x1, y, self.report['TRIGGER']) y += height painter.drawText(x0, y, u"测试人员") painter.drawText(x1, y, self.report['PERSON']) y += height painter.drawText(x0, y, u"测试日期") painter.drawText(x1, y, self.report['DATE']) y += vmargin width = fm.width(u"通道1") + 50 x1 = x0 + width space = 0 painter.drawText(x0 + 20, y, u"压力通道(Mpa)") for i, j in enumerate(self.group_press): if j[1]: y += height if j[0]: painter.drawText(x0, y, j[0]) else: painter.drawText(x0, y, '通道%d'.decode("utf-8") % (i + 1)) painter.drawText(x1, y, self.report['PRESS'][i + 1]) else: space += height y += (vmargin + space) width = fm.width(u"通道计量1") + 15 x1 = x0 + width #x2 = x1 + width painter.drawText(x0 + 20, y, u"数字量计时通道(s)") y += height painter.drawText(x0, y, u"通道") painter.drawText(x1, y, u"开启时间") #painter.drawText(x2, y, u"关闭") space = 0 for i, j in enumerate(self.group_digital): if j[1]: y += height if j[0]: painter.drawText(x0, y, j[0]) else: painter.drawText(x0, y, '通道%d'.decode("utf-8") % (i + 1)) painter.drawText(x1, y, self.report['DIGITAL'][i + 1][0]) #painter.drawText(x2, y, self.report['DIGITAL'][i + 1][1]) else: space += height y += (vmargin + space) width = fm.width(u"出管速度(m/s)") + 25 x1 = x0 + width painter.drawText(x0, y, u"加速度(g)") painter.drawText(x1, y, self.report['ACCELERATION']) y += height painter.drawText(x0, y, u"出管速度(m/s)") painter.drawText(x1, y, self.report['SPEED']) y += height painter.drawText(x0, y, u"延迟时间(s)") painter.drawText(x1, y, self.report['DELAY']) y += height painter.drawText(x0, y, u"发射时间(s)") painter.drawText(x1, y, self.report['SHOOT']) y += height painter.drawText(x0, y, u"发射深度(s)") painter.drawText(x1, y, self.report['DEEP']) width = fm.width(u"泄放装置泄放时间(s)") + 5 y += height painter.drawText(x0, y, u"泄放阀开启时机(m)") x1 = x0 + width painter.drawText(x1, y, self.report['BLEED']) y += height painter.drawText(x0, y, u"泄放阀开启时间(s)") x1 = x0 + width + 1 painter.drawText(x1, y, self.report['OPEN'])