def createPixmap(self): """Creates the pixmap shown when this label is dragged.""" font_metric = QFontMetrics(QFont()) text_size = font_metric.size(Qt.TextSingleLine, self.text) image = QImage(text_size.width() + 4, text_size.height() + 4, QImage.Format_ARGB32_Premultiplied) image.fill(qRgba(240, 240, 120, 255)) painter = QPainter() painter.begin(image) painter.setFont(QFont()) painter.setBrush(Qt.black) painter.drawText(QRect(QPoint(2, 2), text_size), Qt.AlignCenter, self.text) painter.end() return image
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 paintEvent(self, event): painter = QPainter(self) painter.fillRect(event.rect(), Qt.white) painter.setFont(self.displayFont) redrawRect = event.rect() beginRow = redrawRect.top() // self.squareSize endRow = redrawRect.bottom() // self.squareSize beginColumn = redrawRect.left() // self.squareSize endColumn = redrawRect.right() // self.squareSize painter.setPen(Qt.gray) for row in range(beginRow, endRow + 1): for column in range(beginColumn, endColumn + 1): painter.drawRect(column * self.squareSize, row * self.squareSize, self.squareSize, self.squareSize) fontMetrics = QFontMetrics(self.displayFont) painter.setPen(Qt.black) for row in range(beginRow, endRow + 1): for column in range(beginColumn, endColumn + 1): char = chr(row * COLUMNS + column) painter.setClipRect(column * self.squareSize, row * self.squareSize, self.squareSize, self.squareSize) if char == self.currentChar: painter.fillRect(column * self.squareSize + 1, row * self.squareSize + 1, self.squareSize, self.squareSize, Qt.green) painter.drawText( column * self.squareSize + (self.squareSize / 2) - fontMetrics.width(char) / 2, row * self.squareSize + 4 + fontMetrics.ascent(), char)
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 sizeHint(self, option, index): k = "{}x{}".format(index.row(), index.column()) if "{}x{}".format(index.row(), index.column()) in self.last_bbox: s = self.last_bbox[k] # print "reusing ndx={} {}x{}".format(k,s.width(),s.height()) del self.last_bbox[k] return QSize(s.width(), s.height()) s = self.get_displayed_data(index) if s == None: return QSize(-1, -1) fm = QFontMetrics(option.font) w = self.table.columnWidth(index.column()) # if option.rect.width() > 0: # w = option.rect.width() size = fm.boundingRect(0, 0, w, 30000, Qt.AlignTop | Qt.AlignLeft | Qt.TextWordWrap, s, 0, []) # if s and len(s) > 50: # print("[{}] w={} / s.w={} s.h={} txt:{}".format(self.i,w,size.width(),size.height(),s)) # h = max( size.height(), self.last_bbox.height()) # print "using ndx={} {}x{}".format(k, size.width(),size.height()) return QSize(size.width(), size.height()) # FIXME hardcoded value
def __init__(self): """ Constructor. """ super(TextEdit, self).__init__() self.setStyleSheet("font: 10pt \"Liberation Mono\";") # Default dictionary based on the current locale. self.dict = enchant.Dict("de_DE") self.highlighter = Highlighter(self.document()) self.highlighter.setDict(self.dict) self.cursorPositionChanged.connect(self.highlightCurrentLine) # some options option=self.document().defaultTextOption() option.setFlags(option.IncludeTrailingSpaces|option.AddSpaceForLineAndParagraphSeparators) self.document().setDefaultTextOption(option) #Init properties self._spaceTabs=False self._tabSize = int(8) fontMetrics=QFontMetrics(self.font()) self.setTabStopWidth(fontMetrics.width('i')*self._tabSize) option=self.document().defaultTextOption() # option.setFlags(option.flags() | option.ShowLineAndParagraphSeparators) option.setFlags(option.flags() | option.ShowTabsAndSpaces) self.document().setDefaultTextOption(option)
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 __init__(self): """ Constructor. """ super(TextEdit, self).__init__() self.setStyleSheet("font: 10pt \"Liberation Mono\";") # Default dictionary based on the current locale. self.dict = enchant.Dict("de_DE") self.highlighter = Highlighter(self.document()) self.highlighter.setDict(self.dict) self.cursorPositionChanged.connect(self.highlightCurrentLine) # some options option = self.document().defaultTextOption() option.setFlags(option.IncludeTrailingSpaces | option.AddSpaceForLineAndParagraphSeparators) self.document().setDefaultTextOption(option) #Init properties self._spaceTabs = False self._tabSize = int(8) fontMetrics = QFontMetrics(self.font()) self.setTabStopWidth(fontMetrics.width('i') * self._tabSize) option = self.document().defaultTextOption() # option.setFlags(option.flags() | option.ShowLineAndParagraphSeparators) option.setFlags(option.flags() | option.ShowTabsAndSpaces) self.document().setDefaultTextOption(option)
def sizeHint(self, option, index): '''Custom size calculation of our items''' uid = to_str(index.data(role=IDROLE)) + 'x' + str(option.rect.width( )) #Fix Bug #967 (sometime uid have some strange unicode chars ... ?) try: return self.memoized_size[uid] except: tweet = to_str(index.data(Qt.DisplayRole)) # One time is enought sizeHint need to be fast if not self.fm: self.normFont = QFont(option.font) self.normFont.setPointSizeF(option.font.pointSizeF() * self.fsize) self.fm = QFontMetrics(self.normFont) if not self.minifm: self.miniFont = QFont(option.font) self.miniFont.setPointSizeF(option.font.pointSizeF() * 0.8 * self.fsize) self.minifm = QFontMetrics(self.miniFont) height = self.fm.boundingRect( 0, 0, option.rect.width() - 75, 800, int(Qt.AlignTop) | int(Qt.AlignLeft) | int(Qt.TextWordWrap), tweet, ).height() reply_text = to_str(index.data(role=REPLYTEXTROLE)) if reply_text: height += self.minifm.boundingRect( 0, 0, option.rect.width() - 75, 800, int(Qt.AlignTop) | int(Qt.AlignLeft) | int(Qt.TextWordWrap), reply_text, ).height() + 5 height += self.minifm.boundingRect( 0, 0, option.rect.width() - 75, 800, int(Qt.AlignTop) | int(Qt.AlignLeft) | int(Qt.TextWordWrap), 'LpqAT', ).height() height += 10 # Spacer if height < 70: height = 70 self.memoized_size[uid] = QSize(option.rect.width(), height) return self.memoized_size[uid]
def sizeHint(self, option, index): s = self.get_displayed_data(index) fm = QFontMetrics(option.font) # print s,option.rect.width(),option.rect.height() size = fm.size(0, s) # 0 allows Qt to take \n into account (useful for textarea) return size
def sizeHint(self, option, index): '''Custom size calculation of our items''' uid = to_str(index.data(role=IDROLE)) + 'x' + str(option.rect.width()) #Fix Bug #967 (sometime uid have some strange unicode chars ... ?) try: return self.memoized_size[uid] except: tweet = to_str(index.data(Qt.DisplayRole)) # One time is enought sizeHint need to be fast if not self.fm: self.normFont = QFont(option.font) self.normFont.setPointSizeF(option.font.pointSizeF() * self.fsize) self.fm = QFontMetrics(self.normFont) if not self.minifm: self.miniFont = QFont(option.font) self.miniFont.setPointSizeF(option.font.pointSizeF() * 0.8 * self.fsize) self.minifm = QFontMetrics(self.miniFont) height = self.fm.boundingRect( 0, 0, option.rect.width() - 75, 800, int(Qt.AlignTop) | int(Qt.AlignLeft) | int(Qt.TextWordWrap), tweet, ).height() reply_text = to_str(index.data(role=REPLYTEXTROLE)) if reply_text: height += self.minifm.boundingRect( 0, 0, option.rect.width() - 75, 800, int(Qt.AlignTop) | int(Qt.AlignLeft) | int(Qt.TextWordWrap), reply_text, ).height() + 5 height += self.minifm.boundingRect( 0, 0, option.rect.width() - 75, 800, int(Qt.AlignTop) | int(Qt.AlignLeft) | int(Qt.TextWordWrap), 'LpqAT', ).height() height += 10 # Spacer if height < 70: height = 70 self.memoized_size[uid] = QSize(option.rect.width(), height) return self.memoized_size[uid]
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 _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 _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 sizeHint(self, option, index): size = QSqlRelationalDelegate.sizeHint(self, option, index) if index.isValid() and index.column() in self.__dates: value = QDate.fromString(index.model().data(index, Qt.DisplayRole), Qt.ISODate) value = value.toString(Qt.SystemLocaleLongDate) fm = QFontMetrics(QApplication.font()) return QSize(fm.width(value) + 5, size.height()) else: return size
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 load(self): # passing None as 2nd arg to QFontMetrics make difference on high DPI self.title.fromString(settings['Font'].get('title')) self.title_m = QFontMetrics(self.title, None) self.datetime.fromString(settings['Font'].get('datetime')) self.datetime_m = QFontMetrics(self.datetime, None) self.text.fromString(settings['Font'].get('text')) self.text_m = QFontMetrics(self.text, None) defaultFont = settings['Font'].get( 'default') or self.getPreferredFont() if defaultFont: self.default.fromString(defaultFont) self.default_m = QFontMetrics(self.default, None) QApplication.instance().setFont(self.default)
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): self.title = QFont() self.datetime = QFont() self.text = QFont() self.default = QApplication.instance().font() self.default_m = QFontMetrics(self.default, None) self.title_m = self.datetime_m = self.text_m = None
def sync_actions(self, has_document, has_rows): "Sync state of actions" debug_print('CookieCutterWidget.sync_ui') current = cookie_cutter_choice().current has_current = cookie_cutter_choice().current is not None name = current.name if current else 'Cookie cutter' # Truncate text to fit button metrics = QFontMetrics(self.button.font()) elided = metrics.elidedText( name, Qt.ElideRight, self.button.width() - 25 ) self.button.setText(elided) self.save_to_new_action.setEnabled(has_rows) self.clear_action.setEnabled(has_current) self.apply_current_action.setEnabled(has_document and has_current)
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 updateSize(self, size): size = int(size) self.displayFont.setPointSize(size) self.squareSize = max(SQUARE_SIZE, QFontMetrics(self.displayFont).xHeight() * 3) self.fontResized.emit(self.squareSize) self.adjustSize() self.update()
def refs_size(self, option, refs, skip_head): if not refs: return 0, 0 metrics = QFontMetrics(option.font) width = 0 height = 0 for ref in refs: if skip_head and posixpath.basename(ref) == 'HEAD': continue ref_text = git_api.parse_ref(ref)[0] text_rect = metrics.boundingRect(0, 0, 0, 0, Qt.AlignLeft | Qt.AlignTop, ref_text) text_rect.setWidth(text_rect.width() + self.ref_padding_x) text_rect.setHeight(text_rect.height() + self.ref_padding_y) width += text_rect.width() width += text_rect.height() * self.ref_arrow_ratio width += self.ref_spacing height = max(height, text_rect.height()) return width, height
def __init__(self, parent=None): super(SettingsDialog, self).__init__(parent) self.setWindowTitle("Settings") main_layout = QVBoxLayout() buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) settings = QSettings() db_group = QGroupBox("Database") grid_layout = QGridLayout() grid_layout.addWidget(QLabel("File"), 0, 0) text = settings.value('DB/File') self.file = QLineEdit(text) self.file.setText(text) grid_layout.addWidget(self.file, 0, 1) browse = QPushButton("Browse") browse.clicked.connect(self.browse) grid_layout.addWidget(browse, 0, 2) db_group.setLayout(grid_layout) main_layout.addWidget(db_group) ip_width = QFontMetrics(QFont(self.font())).width("000.000.000.000 ") smtp_group = QGroupBox("SMTP") grid_layout = QGridLayout() grid_layout.addWidget(QLabel("Server"), 0, 0) text = settings.value('SMTP/Server') self.smtp_server = QLineEdit(text) self.smtp_server.setText(text) grid_layout.addWidget(self.smtp_server, 0, 1) smtp_group.setLayout(grid_layout) main_layout.addWidget(smtp_group) self.http_proxy = QGroupBox("HTTP Proxy") self.http_proxy.setCheckable(True) self.http_proxy.setChecked(bool(settings.value('HTTP Proxy/Enabled'))) grid_layout = QGridLayout() grid_layout.addWidget(QLabel("Server"), 0, 0) self.http_proxy_ip = QLineEdit() self.http_proxy_ip.setText(settings.value('HTTP Proxy/IP')) self.http_proxy_ip.setMinimumWidth(ip_width) grid_layout.addWidget(self.http_proxy_ip, 0, 1) grid_layout.setColumnStretch(0, 1) self.http_proxy.setLayout(grid_layout) main_layout.addWidget(self.http_proxy) main_layout.addWidget(buttonBox) self.setLayout(main_layout) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject)
def __init__(self, text, size = 0): """Construct a DropTextLabel with the given text. If size is positive, the label will be forced to a width representing size characters in the default font. """ super(DropTextLabel, self).__init__(text) self.setAcceptDrops(True) self.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) # FACTORME if size > 0: size_sample = 'M' * size font_metric = QFontMetrics(QFont()) two_size = font_metric.size(Qt.TextSingleLine, size_sample) max_size = max([two_size.width(), two_size.height()]) + 4 self.setMaximumHeight(max_size) self.setMinimumHeight(max_size) self.setMaximumWidth(max_size) self.setMinimumWidth(max_size)
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)
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 __init__(self, text, size=0): """Construct a DropTextLabel with the given text. If size is positive, the label will be forced to a width representing size characters in the default font. """ super(DropTextLabel, self).__init__(text) self.setAcceptDrops(True) self.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) # FACTORME if size > 0: size_sample = 'M' * size font_metric = QFontMetrics(QFont()) two_size = font_metric.size(Qt.TextSingleLine, size_sample) max_size = max([two_size.width(), two_size.height()]) + 4 self.setMaximumHeight(max_size) self.setMinimumHeight(max_size) self.setMaximumWidth(max_size) self.setMinimumWidth(max_size)
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 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 __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 getFontMetrics(self, family, pixelSize): """ @param family str @param pixelSize int @return QFontMetrics """ key = pixelSize, family ret = self.fontMetrics.get(key) if not ret: font = QFont(family) font.setPixelSize(pixelSize) ret = self.fontMetrics[key] = QFontMetrics(font) return ret
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) width = QFontMetrics(font).width(self.edge.get('label', 0)) pos = self.mapFromScene(*self.edge['lp']) #path.addText(pos.x() - width/2, pos.y(), # font, self.edge['label']) 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()) self.text_label.setFont(font) self.text_label.show() except KeyError: # no label pass self.setPath(path)
class DefaultCustomDelegate(QStyledItemDelegate): '''Delegate to do custom draw of the items''' memoized_size = {} def __init__(self, parent): '''Initialization''' QStyledItemDelegate.__init__(self, parent) self.bg_color = QColor('#000000') self.bg_alternate_color = QColor('#333333') self.new_bg_color = QColor('#0044dd') self.new_bg_alternate_color = QColor('#223399') self.user_color = QColor('#7AB4F5') self.time_color = QColor('#7AB4F5') self.replyto_color = QColor('#7AB4F5') self.text_color = QColor('#FFFFFF') self.separator_color = QColor('#000000') self.fsize = 1.0 self.fm = None self.minifm = None self.normFont = None self.miniFont = None # print os.path.join(os.path.dirname(__file__), # 'icons', 'reply.png') self.reply_icon = QPixmap(os.path.join(os.path.dirname(__file__), 'icons', 'reply.png')) # print dir(self.reply_icon) self.retweet_icon = QPixmap(os.path.join(os.path.dirname(__file__), 'icons', 'retweet.png')) self.geoloc_icon = QPixmap(os.path.join(os.path.dirname(__file__), 'icons', 'geoloc.png')) def doZoomRefresh(self): self.memoized_size.clear() self.fm = None self.minifm = None self.normFont = None self.miniFont = None def sizeHint(self, option, index): '''Custom size calculation of our items''' uid = to_str(index.data(role=IDROLE)) + 'x' + str(option.rect.width()) #Fix Bug #967 (sometime uid have some strange unicode chars ... ?) try: return self.memoized_size[uid] except: tweet = to_str(index.data(Qt.DisplayRole)) # One time is enought sizeHint need to be fast if not self.fm: self.normFont = QFont(option.font) self.normFont.setPointSizeF(option.font.pointSizeF() * self.fsize) self.fm = QFontMetrics(self.normFont) if not self.minifm: self.miniFont = QFont(option.font) self.miniFont.setPointSizeF(option.font.pointSizeF() * 0.8 * self.fsize) self.minifm = QFontMetrics(self.miniFont) height = self.fm.boundingRect( 0, 0, option.rect.width() - 75, 800, int(Qt.AlignTop) | int(Qt.AlignLeft) | int(Qt.TextWordWrap), tweet, ).height() reply_text = to_str(index.data(role=REPLYTEXTROLE)) if reply_text: height += self.minifm.boundingRect( 0, 0, option.rect.width() - 75, 800, int(Qt.AlignTop) | int(Qt.AlignLeft) | int(Qt.TextWordWrap), reply_text, ).height() + 5 height += self.minifm.boundingRect( 0, 0, option.rect.width() - 75, 800, int(Qt.AlignTop) | int(Qt.AlignLeft) | int(Qt.TextWordWrap), 'LpqAT', ).height() height += 10 # Spacer if height < 70: height = 70 self.memoized_size[uid] = QSize(option.rect.width(), height) return self.memoized_size[uid] def paint( self, painter, option, index, ): '''Paint our tweet''' (x1, y1, x2, y2) = option.rect.getCoords() # Ugly hack ? if y1 < 0 and y2 < 0: return # Init Font : One time is enough if not self.fm: self.normFont = QFont(option.font) self.normFont.setPointSizeF(option.font.pointSizeF() * self.fsize) if not self.minifm: self.miniFont = QFont(option.font) self.miniFont.setPointSizeF(option.font.pointSizeF() * 0.8 * self.fsize) # Query data tweet = to_str(index.data(Qt.DisplayRole)) screenname = to_str(index.data(SCREENNAMEROLE)) retweet_of = index.data(RETWEETOFROLE) timestamp = to_str(index.data(role=TIMESTAMPROLE)) reply_name = to_str(index.data(role=REPLYTOSCREENNAMEROLE)) reply_text = to_str(index.data(role=REPLYTEXTROLE)) is_new = index.data(role=ISNEWROLE) painter.save() # Draw alternate ? if index.row() % 2 == 0: color = self.bg_color else: color = self.bg_alternate_color painter.fillRect(option.rect, color) # highlight selected items if option.state & QStyle.State_Selected: painter.fillRect(option.rect, option.palette.highlight()) # Draw icon icon = index.data(Qt.DecorationRole) if type(icon) == QPixmap: try: painter.drawPixmap(x1 + 10, y1 + 10, 50, 50, icon) except Exception: logging.exception("Drawing icon") # Draw screenname painter.setFont(self.miniFont) painter.setPen(self.user_color) nrect = painter.drawText(option.rect.adjusted(70, 5, -4, -9), int(Qt.AlignTop) | int(Qt.AlignLeft), screenname) # Reply icon if reply_name: painter.drawPixmap(x1 + 74 + nrect.width(), y1, 26, 26, self.reply_icon) painter.setFont(self.miniFont) painter.setPen(self.replyto_color) painter.drawText(option.rect.adjusted(109 + nrect.width(), 5, -4, -9), int(Qt.AlignTop) | int(Qt.AlignLeft), reply_name) # Retweet icon if retweet_of: painter.drawPixmap(x1 + 74 + nrect.width(), y1, 32, 32, self.retweet_icon) painter.setFont(self.miniFont) painter.setPen(self.replyto_color) painter.drawText(option.rect.adjusted(110 + nrect.width(), 5, -4, -9), int(Qt.AlignTop) | int(Qt.AlignLeft), retweet_of.user.screen_name) # Draw tweet painter.setFont(self.normFont) painter.setPen(self.text_color) new_rect = painter.drawText(option.rect.adjusted(70, nrect.height() + 5, -4, 0), int(Qt.AlignTop) | int(Qt.AlignLeft) | int(Qt.TextWordWrap), tweet) # Draw Timeline painter.setFont(self.miniFont) painter.setPen(self.time_color) painter.drawText(option.rect.adjusted(70, 5, -4, -9), int(Qt.AlignTop) | int(Qt.AlignRight), timestamp) # Draw reply if reply_text: painter.setFont(self.miniFont) painter.setPen(self.replyto_color) painter.drawText(option.rect.adjusted(70, nrect.height() + new_rect.height() + 5, -4, -9), int(Qt.AlignTop) | int(Qt.AlignLeft) | int(Qt.TextWordWrap), reply_text) # Draw line separator painter.setPen(self.separator_color) painter.drawLine(x1, y2, x2, y2) #Use a little tips to say that's a new tweet if is_new: painter.fillRect(x1,y1,8,y2, self.new_bg_alternate_color) # restore painter painter.restore()
def reload(self, order_overview_widget, all_ops, all_operations, sort=1): # mainlog.debug("reload...") progress = QProgressDialog(_("Collecting data..."), None, 0, len(all_ops) + 3, order_overview_widget) progress.setWindowTitle("Horse") progress.setMinimumDuration(0) progress.setWindowModality(Qt.WindowModal) progress.setValue(progress.value() + 1) progress.show() for i in self.items(): self.removeItem(i) self.posts_offsets = dict() self.drawn_operations_data = dict() self.cursor = QGraphicsRectItem(0, 0, 50, 300) self.cursor.setBrush(QBrush(QColor(208, 208, 255, 255))) self.cursor.setPen(QPen(Qt.transparent)) self.addItem(self.cursor) bar_width = 8 bar_height = int(bar_width * 60.0 / 8.0) ascent = QFontMetrics(self.base_font).ascent() ascent_big = QFontMetrics(self.base_font_big).ascent() post_ops = {} # mainlog.debug("reload...2") # z = 0 # for op,order_part,parts in all_operations: # z = op.planned_hours # z = order_part.deadline # z = order_part.qty # z = order_part.human_identifier # all_operations = map(lambda i:i[0],all_operations) y = 0 for opdef in all_ops: progress.setValue(progress.value() + 1) operations = filter( lambda op: op.operation_definition_id == opdef. operation_definition_id, all_operations) # We're only interested in the effort/time that remains # to be put on an operation. We're only interested in # the future. # We want the oeprations that are either # - ongoing # - ready to start. # In all cases we're only interested in operations # that are "active" if sort == 1: operations = sorted( operations, key=lambda op: op.deadline or date(3000, 1, 1)) elif sort == 2: operations = sorted( operations, key=lambda op: op.planned_hours * op.qty - op.done_hours) else: # Don't sort pass maximum = 16.0 #float ! small_hours = 0 op_ndx = 0 current_x = 50 bar_drawn = False total_done_hours = total_estimated = 0 # -------------------------------------------------------------- # Started operations bars_line = BarsLine(16, bar_width, bar_height, current_x, y, self, order_overview_widget) total_hours_to_do = 0 for op in filter(lambda op: op.done_hours > 0, operations): hours_to_do = max( 0, op.planned_hours * op.qty - op.done_hours) # max protects against reporting errors total_hours_to_do += hours_to_do total_estimated += op.planned_hours * op.qty total_done_hours += op.done_hours bars_line.add_bar(hours_to_do, QBrush(Qt.green), self._operation_hoover_description(op), False, None) # op.production_file.order_part) # -------------------------------------------------------------- bars_line_unstarted_operations = BarsLine(16, bar_width, bar_height, current_x + 30, y, self, order_overview_widget) total_hours_to_do_on_unstarted_operations = 0 for op in filter(lambda op: op.done_hours == 0, operations): hours_to_do = op.planned_hours * op.qty total_hours_to_do_on_unstarted_operations += hours_to_do total_estimated += hours_to_do bars_line_unstarted_operations.add_bar( hours_to_do, QBrush(Qt.yellow), self._operation_hoover_description(op), False, None) #op.production_file.order_part) y_start = y total = total_hours_to_do + total_hours_to_do_on_unstarted_operations if total > 0: self.drawn_operations_data[ opdef.operation_definition_id] = "{}h".format( int(round(total_estimated))) gi = QGraphicsSimpleTextItem( _("{} - Estimated to do : {}h; done : {}h").format( opdef.description, int(round(total)), int(round(total_done_hours)))) gi.setFont(self.base_font_big) gi.setPos(0, y - gi.boundingRect().height()) self.addItem(gi) th = gi.boundingRect().height() gi = QGraphicsLineItem(-ascent_big, y, 1024 + 2 * ascent_big, y) gi.setPen(QPen(Qt.black)) self.addItem(gi) y += th else: continue y_bars = y if total_hours_to_do > 0: # There's something to draw head = QGraphicsSimpleTextItem(_("Started")) head.setFont(self.base_font) head.setPos(current_x, y) self.addItem(head) y += head.boundingRect().height() y += bar_height bars_line.set_start_pos(current_x, y) bars_line.finish_bar() foot = QGraphicsSimpleTextItem( _("{}h").format(int(total_hours_to_do + 0.5))) foot.setFont(self.base_font) foot.setPos(current_x, y) self.addItem(foot) y += foot.boundingRect().height() current_x = max(current_x + bars_line.estimate_width(), head.boundingRect().right(), foot.boundingRect().right()) bar_drawn = True if total_hours_to_do_on_unstarted_operations > 0: if bars_line_unstarted_operations.estimate_width( ) + current_x > 1200: x = 50 y += ascent_big else: y = y_bars x = current_x + 50 head = QGraphicsSimpleTextItem(_("Not started yet")) head.setFont(self.base_font) head.setPos(x, y) self.addItem(head) y += head.boundingRect().height() y += bar_height bars_line_unstarted_operations.set_start_pos(x, y) bars_line_unstarted_operations.finish_bar() foot = QGraphicsSimpleTextItem( _("{}h").format( int(total_hours_to_do_on_unstarted_operations + 0.5))) foot.setFont(self.base_font) foot.setPos(x, y) self.addItem(foot) y += foot.boundingRect().height() bar_drawn = True y += 3 * ascent_big r = self.sceneRect() self.posts_offsets[opdef.operation_definition_id] = \ QRectF(r.x() - 2*ascent_big, y_start - 1.5*ascent_big, r.width() + 4*ascent_big, (y - ascent_big) - (y_start - 1.5*ascent_big) ) y += ascent_big # mainlog.debug("reload...3") import functools max_width = functools.reduce(lambda acc, po: max(acc, po.width()), self.posts_offsets.values(), 0) map(lambda po: po.setWidth(max_width), self.posts_offsets.values()) # for r in self.posts_offsets.values(): # gi = QGraphicsLineItem(r.x(),r.y(),r.x()+r.width(),r.y()) # gi.setPen(QPen(Qt.lightGray)) # self.addItem(gi) progress.close()
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_())
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)
def setUp(self): super(QFontMetricsTest, self).setUp() self.font = QFont() self.metrics = QFontMetrics(self.font)
def setup(self): self.dirty = False self.def_cfg = copy.deepcopy(self.config) self.config.update_from_user_file() self.base_cfg = copy.deepcopy(self.config) self.categories = QListWidget() #self.categories.setSizePolicy(QSizePolicy.Fixed,QSizePolicy.Expanding) self.settings = QStackedWidget() #self.categories.setSizePolicy(QSizePolicy.MinimumExpanding,QSizePolicy.Expanding) QObject.connect(self.categories, SIGNAL('itemSelectionChanged()'), self.category_selected) self.widget_list = {} for cat in self.config.get_categories(): self.widget_list[cat] = {} longest_cat = 0 for cat in self.config.get_categories(): if len(cat) > longest_cat: longest_cat = len(cat) self.categories.addItem(cat) settings_layout = QGridLayout() r = 0 c = 0 for setting in self.config.get_settings(cat): info = self.config.get_setting(cat, setting, True) s = QWidget() s.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Fixed) sl = QVBoxLayout() label = QLabel() if info.has_key('alias'): label.setText(info['alias']) else: label.setText(setting) if info.has_key('about'): label.setToolTip(info['about']) sl.addWidget(label) if info['type'] == constants.CT_LINEEDIT: w = LineEdit(self, self.config,cat,setting,info) elif info['type'] == constants.CT_CHECKBOX: w = CheckBox(self, self.config,cat,setting,info) elif info['type'] == constants.CT_SPINBOX: w = SpinBox(self, self.config,cat,setting,info) elif info['type'] == constants.CT_DBLSPINBOX: w = DoubleSpinBox(self, self.config,cat,setting,info) elif info['type'] == constants.CT_COMBO: w = ComboBox(self, self.config,cat,setting,info) w.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Fixed) self.widget_list[cat][setting] = w sl.addWidget(w) s.setLayout(sl) c = self.config.config[cat].index(setting) % 2 settings_layout.addWidget(s, r, c) if c == 1: r += 1 settings = QWidget() settings.setLayout(settings_layout) settings_scroller = QScrollArea() settings_scroller.setWidget(settings) settings_scroller.setWidgetResizable(True) self.settings.addWidget(settings_scroller) font = self.categories.font() fm = QFontMetrics(font) self.categories.setMaximumWidth(fm.widthChar('X')*(longest_cat+4)) self.main = QWidget() self.main_layout = QVBoxLayout() self.config_layout = QHBoxLayout() self.config_layout.addWidget(self.categories) self.config_layout.addWidget(self.settings) self.mainButtons = QDialogButtonBox(QDialogButtonBox.RestoreDefaults | QDialogButtonBox.Reset | QDialogButtonBox.Apply) self.main_apply = self.mainButtons.button(QDialogButtonBox.StandardButton.Apply) self.main_reset = self.mainButtons.button(QDialogButtonBox.StandardButton.Reset) self.main_defaults = self.mainButtons.button(QDialogButtonBox.StandardButton.LastButton) QObject.connect(self.mainButtons, SIGNAL('clicked(QAbstractButton *)'), self.mainbutton_clicked) self.dirty_check() self.main_layout.addLayout(self.config_layout) self.main_layout.addWidget(self.mainButtons) self.main.setLayout(self.main_layout) self.setCentralWidget(self.main) self.setWindowTitle(self.title) self.setUnifiedTitleAndToolBarOnMac(True) self.categories.setCurrentItem(self.categories.item(0)) self.menuBar = QMenuBar() self.filemenu = QMenu('&File') self.quitAction = QAction(self) self.quitAction.setText('&Quit') if platform.system() != 'Darwin': self.quitAction.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_Q)) QObject.connect(self.quitAction, SIGNAL('triggered()'), self.quitApp) self.filemenu.addAction(self.quitAction) self.menuBar.addMenu(self.filemenu) self.setMenuBar(self.menuBar) self.show() self.activateWindow() self.raise_() self.setMinimumWidth(self.geometry().width()*1.2) screen = QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)
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'])
def __init__(self, parent = None): super(MainWindow, self).__init__(parent) self.setWindowTitle('Basic Drawing') self.app = QCoreApplication.instance() self.setGeometry(self.app.myRectangle) st = self.app.style() self.params = ( ('ButtonMargin', st.pixelMetric(QStyle.PM_ButtonMargin)), ('DockWidgetTitleBarButtonMargin', st.pixelMetric(QStyle.PM_DockWidgetTitleBarButtonMargin)), ('ButtonDefaultIndicator', st.pixelMetric(QStyle.PM_ButtonDefaultIndicator)), ('MenuButtonIndicator', st.pixelMetric(QStyle.PM_MenuButtonIndicator)), ('ButtonShiftHorizontal', st.pixelMetric(QStyle.PM_ButtonShiftHorizontal)), ('ButtonShiftVertical', st.pixelMetric(QStyle.PM_ButtonShiftVertical)), ('DefaultFrameWidth', st.pixelMetric(QStyle.PM_DefaultFrameWidth)), ('SpinBoxFrameWidth', st.pixelMetric(QStyle.PM_SpinBoxFrameWidth)), ('ComboBoxFrameWidth', st.pixelMetric(QStyle.PM_ComboBoxFrameWidth)), ('MdiSubWindowFrameWidth', st.pixelMetric(QStyle.PM_MdiSubWindowFrameWidth)), ('MdiSubWindowMinimizedWidth', st.pixelMetric(QStyle.PM_MdiSubWindowMinimizedWidth)), ('LayoutLeftMargin', st.pixelMetric(QStyle.PM_LayoutLeftMargin)), ('LayoutTopMargin', st.pixelMetric(QStyle.PM_LayoutTopMargin)), ('LayoutRightMargin', st.pixelMetric(QStyle.PM_LayoutRightMargin)), ('LayoutBottomMargin', st.pixelMetric(QStyle.PM_LayoutBottomMargin)), ('LayoutHorizontalSpacing', st.pixelMetric(QStyle.PM_LayoutHorizontalSpacing)), ('LayoutVerticalSpacing', st.pixelMetric(QStyle.PM_LayoutVerticalSpacing)), ('MaximumDragDistance', st.pixelMetric(QStyle.PM_MaximumDragDistance)), ('ScrollBarExtent', st.pixelMetric(QStyle.PM_ScrollBarExtent)), ('ScrollBarSliderMin', st.pixelMetric(QStyle.PM_ScrollBarSliderMin)), ('SliderThickness', st.pixelMetric(QStyle.PM_SliderThickness)), ('SliderControlThickness', st.pixelMetric(QStyle.PM_SliderControlThickness)), ('SliderLength', st.pixelMetric(QStyle.PM_SliderLength)), ('SliderTickmarkOffset', st.pixelMetric(QStyle.PM_SliderTickmarkOffset)), ('SliderSpaceAvailable', st.pixelMetric(QStyle.PM_SliderSpaceAvailable)), ('DockWidgetSeparatorExtent', st.pixelMetric(QStyle.PM_DockWidgetSeparatorExtent)), ('DockWidgetHandleExtent', st.pixelMetric(QStyle.PM_DockWidgetHandleExtent)), ('DockWidgetFrameWidth', st.pixelMetric(QStyle.PM_DockWidgetFrameWidth)), ('DockWidgetTitleMargin', st.pixelMetric(QStyle.PM_DockWidgetTitleMargin)), ('MenuBarPanelWidth', st.pixelMetric(QStyle.PM_MenuBarPanelWidth)), ('MenuBarItemSpacing', st.pixelMetric(QStyle.PM_MenuBarItemSpacing)), ('MenuBarHMargin', st.pixelMetric(QStyle.PM_MenuBarHMargin)), ('MenuBarVMargin', st.pixelMetric(QStyle.PM_MenuBarVMargin)), ('ToolBarFrameWidth', st.pixelMetric(QStyle.PM_ToolBarFrameWidth)), ('ToolBarHandleExtent', st.pixelMetric(QStyle.PM_ToolBarHandleExtent)), ('ToolBarItemMargin', st.pixelMetric(QStyle.PM_ToolBarItemMargin)), ('ToolBarItemSpacing', st.pixelMetric(QStyle.PM_ToolBarItemSpacing)), ('ToolBarSeparatorExtent', st.pixelMetric(QStyle.PM_ToolBarSeparatorExtent)), ('ToolBarExtensionExtent', st.pixelMetric(QStyle.PM_ToolBarExtensionExtent)), ('TabBarTabOverlap', st.pixelMetric(QStyle.PM_TabBarTabOverlap)), ('TabBarTabHSpace', st.pixelMetric(QStyle.PM_TabBarTabHSpace)), ('TabBarTabVSpace', st.pixelMetric(QStyle.PM_TabBarTabVSpace)), ('TabBarBaseHeight', st.pixelMetric(QStyle.PM_TabBarBaseHeight)), ('TabBarBaseOverlap', st.pixelMetric(QStyle.PM_TabBarBaseOverlap)), ('TabBarScrollButtonWidth', st.pixelMetric(QStyle.PM_TabBarScrollButtonWidth)), ('TabBarTabShiftHorizontal', st.pixelMetric(QStyle.PM_TabBarTabShiftHorizontal)), ('TabBarTabShiftVertical', st.pixelMetric(QStyle.PM_TabBarTabShiftVertical)), ('ProgressBarChunkWidth', st.pixelMetric(QStyle.PM_ProgressBarChunkWidth)), ('SplitterWidth', st.pixelMetric(QStyle.PM_SplitterWidth)), ('TitleBarHeight', st.pixelMetric(QStyle.PM_TitleBarHeight)), ('IndicatorWidth', st.pixelMetric(QStyle.PM_IndicatorWidth)), ('IndicatorHeight', st.pixelMetric(QStyle.PM_IndicatorHeight)), ('ExclusiveIndicatorWidth', st.pixelMetric(QStyle.PM_ExclusiveIndicatorWidth)), ('ExclusiveIndicatorHeight', st.pixelMetric(QStyle.PM_ExclusiveIndicatorHeight)), ('MenuPanelWidth', st.pixelMetric(QStyle.PM_MenuPanelWidth)), ('MenuHMargin', st.pixelMetric(QStyle.PM_MenuHMargin)), ('MenuVMargin', st.pixelMetric(QStyle.PM_MenuVMargin)), ('MenuScrollerHeight', st.pixelMetric(QStyle.PM_MenuScrollerHeight)), ('MenuTearoffHeight', st.pixelMetric(QStyle.PM_MenuTearoffHeight)), ('MenuDesktopFrameWidth', st.pixelMetric(QStyle.PM_MenuDesktopFrameWidth)), ('CheckListButtonSize', st.pixelMetric(QStyle.PM_CheckListButtonSize)), ('CheckListControllerSize', st.pixelMetric(QStyle.PM_CheckListControllerSize)), ('HeaderMarkSize', st.pixelMetric(QStyle.PM_HeaderMarkSize)), ('HeaderGripMargin', st.pixelMetric(QStyle.PM_HeaderGripMargin)), ('HeaderMargin', st.pixelMetric(QStyle.PM_HeaderMargin)), ('SpinBoxSliderHeight', st.pixelMetric(QStyle.PM_SpinBoxSliderHeight)), ('ToolBarIconSize', st.pixelMetric(QStyle.PM_ToolBarIconSize)), ('SmallIconSize', st.pixelMetric(QStyle.PM_SmallIconSize)), ('LargeIconSize', st.pixelMetric(QStyle.PM_LargeIconSize)), ('FocusFrameHMargin', st.pixelMetric(QStyle.PM_FocusFrameHMargin)), ('FocusFrameVMargin', st.pixelMetric(QStyle.PM_FocusFrameVMargin)), ('IconViewIconSize', st.pixelMetric(QStyle.PM_IconViewIconSize)), ('ListViewIconSize', st.pixelMetric(QStyle.PM_ListViewIconSize)), ('ToolTipLabelFrameWidth', st.pixelMetric(QStyle.PM_ToolTipLabelFrameWidth)), ('CheckBoxLabelSpacing', st.pixelMetric(QStyle.PM_CheckBoxLabelSpacing)), ('RadioButtonLabelSpacing', st.pixelMetric(QStyle.PM_RadioButtonLabelSpacing)), ('TabBarIconSize', st.pixelMetric(QStyle.PM_TabBarIconSize)), ('SizeGripSize', st.pixelMetric(QStyle.PM_SizeGripSize)), ('MessageBoxIconSize', st.pixelMetric(QStyle.PM_MessageBoxIconSize)), ('ButtonIconSize', st.pixelMetric(QStyle.PM_ButtonIconSize)), ('TextCursorWidth', st.pixelMetric(QStyle.PM_TextCursorWidth)), ('TabBar_ScrollButtonOverlap', st.pixelMetric(QStyle.PM_TabBar_ScrollButtonOverlap)), ('TabCloseIndicatorWidth', st.pixelMetric(QStyle.PM_TabCloseIndicatorWidth)), ('TabCloseIndicatorHeight', st.pixelMetric(QStyle.PM_TabCloseIndicatorHeight)), ('CustomBase', st.pixelMetric(QStyle.PM_CustomBase)) ) self.tw = QTableWidget(len(self.params), 2) length = 0 strin = '' for i in range(len(self.params)): item1 = QTableWidgetItem (self.params[i][0]) item2 = QTableWidgetItem (str(self.params[i][1])) self.tw.setItem(i, 0, item1) self.tw.setItem(i, 1, item2) self.setCentralWidget(self.tw) #fm = QFontMetrics(self.tw.font()) fm = QFontMetrics(self.tw.item(1,1).font()) #fm = self.tw.fontMetrics() for param in self.params: l = fm.size(1, self.tr(param[0])).width() if l > length: length = l strin = self.tr(param[0]) print 'MaxWidth: {0}, for string: {1}'.format(length, strin) self.tw.setColumnWidth(0, length) appFont = self.app.font() cellFont = self.tw.item(1,1).font() tableFont = self.tw.font() print appFont print cellFont print tableFont print fm
def add_labels_internal(self, gl, render_state, draw_to_canvas, labels): ''' call to add a list of labels ''' text_paint = QPainter() if draw_to_canvas: text_paint.begin(self.bitmap) text_paint.setRenderHints(QPainter.Antialiasing) u = 0 v = 0 line_height = 0 for label in labels: ascent = 0 descent = 0 measured_text_width = 0 height = 0 width = 0 font_size = label.font_size while True: metrics = None if draw_to_canvas: mask = 0x000000FF b = (label.color >> 16) & mask g = (label.color >> 8) & mask r = label.color & mask ######################################################################## LINE CHANGED text_paint.setPen(QColor(0, 0, 0)) #text_paint.setPen(QColor(r, g, b)) # The value 0.75 is hard coded representing phone pixel density text_paint.setFont(QFont('Veranda', font_size * 0.75)) # Paint.ascent is negative, so negate it. metrics = text_paint.fontMetrics() else: # The value 0.75 is hard coded representing phone pixel density metrics = QFontMetrics(QFont('Veranda', font_size * 0.75)) ascent = math.ceil(metrics.ascent()) descent = math.ceil(metrics.descent()) measured_text_width = math.ceil(metrics.boundingRect(label.string).width()) height = int(ascent) + int(descent) width = int(measured_text_width) # If it's wider than the screen, try it again with a font size of 1 # smaller. font_size -= 1 if font_size < 0 or width < render_state.screen_width: break next_u = 0 # Is there room for this string on the current line? if u + width > self.strike_width: # No room, go to the next line: u = 0 next_u = width v += line_height line_height = 0 else: next_u = u + width line_height = max(line_height, height) if (v + line_height > self.strike_height) and draw_to_canvas: raise Exception("out of texture space.") v_base = v + ascent if draw_to_canvas: text_paint.drawText(int(u), int(v_base), label.string) label.set_texture_data(width, height, u, v + height, width, -height, self.texel_width, self.texel_height) u = next_u if draw_to_canvas: text_paint.end() return v + line_height
class DefaultCustomDelegate(QStyledItemDelegate): '''Delegate to do custom draw of the items''' memoized_size = {} def __init__(self, parent): '''Initialization''' QStyledItemDelegate.__init__(self, parent) self.bg_color = QColor('#000000') self.bg_alternate_color = QColor('#333333') self.new_bg_color = QColor('#0044dd') self.new_bg_alternate_color = QColor('#223399') self.user_color = QColor('#7AB4F5') self.time_color = QColor('#7AB4F5') self.replyto_color = QColor('#7AB4F5') self.text_color = QColor('#FFFFFF') self.separator_color = QColor('#000000') self.fsize = 1.0 self.fm = None self.minifm = None self.normFont = None self.miniFont = None # print os.path.join(os.path.dirname(__file__), # 'icons', 'reply.png') self.reply_icon = QPixmap( os.path.join(os.path.dirname(__file__), 'icons', 'reply.png')) # print dir(self.reply_icon) self.retweet_icon = QPixmap( os.path.join(os.path.dirname(__file__), 'icons', 'retweet.png')) self.geoloc_icon = QPixmap( os.path.join(os.path.dirname(__file__), 'icons', 'geoloc.png')) def doZoomRefresh(self): self.memoized_size.clear() self.fm = None self.minifm = None self.normFont = None self.miniFont = None def sizeHint(self, option, index): '''Custom size calculation of our items''' uid = to_str(index.data(role=IDROLE)) + 'x' + str(option.rect.width( )) #Fix Bug #967 (sometime uid have some strange unicode chars ... ?) try: return self.memoized_size[uid] except: tweet = to_str(index.data(Qt.DisplayRole)) # One time is enought sizeHint need to be fast if not self.fm: self.normFont = QFont(option.font) self.normFont.setPointSizeF(option.font.pointSizeF() * self.fsize) self.fm = QFontMetrics(self.normFont) if not self.minifm: self.miniFont = QFont(option.font) self.miniFont.setPointSizeF(option.font.pointSizeF() * 0.8 * self.fsize) self.minifm = QFontMetrics(self.miniFont) height = self.fm.boundingRect( 0, 0, option.rect.width() - 75, 800, int(Qt.AlignTop) | int(Qt.AlignLeft) | int(Qt.TextWordWrap), tweet, ).height() reply_text = to_str(index.data(role=REPLYTEXTROLE)) if reply_text: height += self.minifm.boundingRect( 0, 0, option.rect.width() - 75, 800, int(Qt.AlignTop) | int(Qt.AlignLeft) | int(Qt.TextWordWrap), reply_text, ).height() + 5 height += self.minifm.boundingRect( 0, 0, option.rect.width() - 75, 800, int(Qt.AlignTop) | int(Qt.AlignLeft) | int(Qt.TextWordWrap), 'LpqAT', ).height() height += 10 # Spacer if height < 70: height = 70 self.memoized_size[uid] = QSize(option.rect.width(), height) return self.memoized_size[uid] def paint( self, painter, option, index, ): '''Paint our tweet''' (x1, y1, x2, y2) = option.rect.getCoords() # Ugly hack ? if y1 < 0 and y2 < 0: return # Init Font : One time is enough if not self.fm: self.normFont = QFont(option.font) self.normFont.setPointSizeF(option.font.pointSizeF() * self.fsize) if not self.minifm: self.miniFont = QFont(option.font) self.miniFont.setPointSizeF(option.font.pointSizeF() * 0.8 * self.fsize) # Query data tweet = to_str(index.data(Qt.DisplayRole)) screenname = to_str(index.data(SCREENNAMEROLE)) retweet_of = index.data(RETWEETOFROLE) timestamp = to_str(index.data(role=TIMESTAMPROLE)) reply_name = to_str(index.data(role=REPLYTOSCREENNAMEROLE)) reply_text = to_str(index.data(role=REPLYTEXTROLE)) is_new = index.data(role=ISNEWROLE) painter.save() # Draw alternate ? if index.row() % 2 == 0: color = self.bg_color else: color = self.bg_alternate_color painter.fillRect(option.rect, color) # highlight selected items if option.state & QStyle.State_Selected: painter.fillRect(option.rect, option.palette.highlight()) # Draw icon icon = index.data(Qt.DecorationRole) if type(icon) == QPixmap: try: painter.drawPixmap(x1 + 10, y1 + 10, 50, 50, icon) except Exception: logging.exception("Drawing icon") # Draw screenname painter.setFont(self.miniFont) painter.setPen(self.user_color) nrect = painter.drawText(option.rect.adjusted(70, 5, -4, -9), int(Qt.AlignTop) | int(Qt.AlignLeft), screenname) # Reply icon if reply_name: painter.drawPixmap(x1 + 74 + nrect.width(), y1, 26, 26, self.reply_icon) painter.setFont(self.miniFont) painter.setPen(self.replyto_color) painter.drawText( option.rect.adjusted(109 + nrect.width(), 5, -4, -9), int(Qt.AlignTop) | int(Qt.AlignLeft), reply_name) # Retweet icon if retweet_of: painter.drawPixmap(x1 + 74 + nrect.width(), y1, 32, 32, self.retweet_icon) painter.setFont(self.miniFont) painter.setPen(self.replyto_color) painter.drawText( option.rect.adjusted(110 + nrect.width(), 5, -4, -9), int(Qt.AlignTop) | int(Qt.AlignLeft), retweet_of.user.screen_name) # Draw tweet painter.setFont(self.normFont) painter.setPen(self.text_color) new_rect = painter.drawText( option.rect.adjusted(70, nrect.height() + 5, -4, 0), int(Qt.AlignTop) | int(Qt.AlignLeft) | int(Qt.TextWordWrap), tweet) # Draw Timeline painter.setFont(self.miniFont) painter.setPen(self.time_color) painter.drawText(option.rect.adjusted(70, 5, -4, -9), int(Qt.AlignTop) | int(Qt.AlignRight), timestamp) # Draw reply if reply_text: painter.setFont(self.miniFont) painter.setPen(self.replyto_color) painter.drawText( option.rect.adjusted(70, nrect.height() + new_rect.height() + 5, -4, -9), int(Qt.AlignTop) | int(Qt.AlignLeft) | int(Qt.TextWordWrap), reply_text) # Draw line separator painter.setPen(self.separator_color) painter.drawLine(x1, y2, x2, y2) #Use a little tips to say that's a new tweet if is_new: painter.fillRect(x1, y1, 8, y2, self.new_bg_alternate_color) # restore painter painter.restore()