def adjust(self): adjust_w = 2 adjust_h = 0 if self.label != "": rect = QtGui.QFontMetrics(self.font).boundingRect(self.label) self.label_w = rect.width() + adjust_w self.label_h = rect.height() + adjust_h self.descriptor_w = 0 self.descriptor_h = 0 for text in self.descriptors: rect = QtGui.QFontMetrics(self.font).boundingRect(text) self.descriptor_w = max(self.descriptor_w, rect.width() + adjust_w) self.descriptor_h = max(self.descriptor_h, rect.height() + adjust_h) w = max(self.label_w, self.descriptor_w) + 2 * self.text_padding h = self.label_h + 2 * self.text_padding + len(self.descriptors) * ( self.descriptor_h + self.text_padding) + self.text_padding self.selection_polygon = QtGui.QPolygonF(QtCore.QRectF(0, 0, w, h)) self.selection_shape = QtGui.QPainterPath() self.selection_shape.addPolygon(self.selection_polygon)
def data(self, index, role=QtCore.Qt.DisplayRole, parent=QtCore.QModelIndex()): if role == QtCore.Qt.SizeHintRole: if index.column() == 0: metrics = QtGui.QFontMetrics(bold_font()) width = metrics.horizontalAdvance( self.data(index, role=QtCore.Qt.DisplayRole) ) + 12 return QtCore.QSize(width, 18) else: metrics = QtGui.QFontMetrics(QtGui.QFont()) width = metrics.horizontalAdvance( self.data(index, role=QtCore.Qt.DisplayRole) ) + 12 return QtCore.QSize(width, 18) if role == QtCore.Qt.ToolTipRole: v = self.internal_data[index.row()]['shapes'] return '\n'.join(v) if role == QtCore.Qt.TextAlignmentRole and index.column() != 0: return QtCore.Qt.AlignCenter if role == QtCore.Qt.FontRole and index.column() == 0: return bold_font() if not index.isValid(): return None if index.column() == 0 and role == QtCore.Qt.DisplayRole: v = str(self.internal_data[index.row()][QtCore.Qt.DisplayRole]) return elided_text(v) if index.column() == 1 and role == QtCore.Qt.DisplayRole: return str(self.internal_data[index.row()]['type']) if index.column() == 2 and role == QtCore.Qt.DisplayRole: v = self.internal_data[index.row()]['shapes'] return f'{len(v)} shapes' if v else '-' if index.column() == 3 and role == QtCore.Qt.DisplayRole: v = self.internal_data[index.row()]['connections'] return f'{len(v)} cnxs' if v else '-' return None
def paintEvent(self, event): QLabel.paintEvent(self, event) self.resize(self.viewWidth, self.viewHeight) for headInfo in self.headers: name = headInfo['name'] x = headInfo['x'] x = x - self.position if x + self.w < 0: continue if x > self.viewWidth: continue self.headLeftPos = x self.headRightPos = x + self.w self.headTopPos = self.t self.headBottomPos = self.t + self.h qp = QtGui.QPainter() qp.begin(self) qp.setBrush(headInfo['color']) qp.drawRect(x, self.t, self.w, self.h) qp.setPen(QtGui.QColor(20, 20, 30)) qp.setFont(QtGui.QFont('Decorative', 10)) leaf_name = list(reversed(name.split(".")))[0] parent_name = ".".join( list(reversed(list(reversed(name.split(".")))[1:]))) if parent_name == "": qp.setFont(QtGui.QFont('Decorative', 11)) wd = QtGui.QFontMetrics( self.font()).boundingRect(leaf_name).width() align_option = QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter if wd > self.w - 20 else QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter qp.drawText(QtCore.QRect(x + 10, self.t, self.w - 20, self.h), align_option, leaf_name) else: qp.setFont(QtGui.QFont('Decorative', 7)) wd = QtGui.QFontMetrics( self.font()).boundingRect(parent_name).width() align_option = QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter if wd > self.w - 20 else QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter qp.drawText( QtCore.QRect(x + 10, self.t, self.w - 20, self.h / 2), align_option, parent_name) qp.setFont(QtGui.QFont('Decorative', 11)) qp.drawText( QtCore.QRect(x + 10, self.t + self.h / 2, self.w - 20, self.h / 2), QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter, leaf_name) qp.drawLine(x + self.w / 2, self.h + self.t, x + self.w / 2, 90000) qp.end()
def updateFont(self, fontFamily): self.displayFont.setFamily(fontFamily) self.squareSize = max( 24, QtGui.QFontMetrics(self.displayFont).xHeight() * 3) self.adjustSize() self.update()
def __init__(self, parent, command, number, name="", enabled=True, height=None): super(Command, self).__init__(parent) self.command = command self.widget = QtWidgets.QTextBrowser() self.widget.setReadOnly(True) if not height: font_height = QtGui.QFontMetrics( self.widget.document().defaultFont()).height() lines = math.ceil(len(command) / 200) self.setMinimumHeight( int(font_height + ((lines + 2) * (font_height * 1.25)))) else: self.setMinimumHeight(height) self.number = number self.name = name self.label = QtWidgets.QLabel( f"{t('Command')} {self.number}" if not self.name else self.name) self.update_grid() self.widget.setDisabled(not enabled)
def __init__(self): super(TextEditor, self).__init__() self._dirty = False self._first_save = True self._original = None self._basename = None self._is_raw = True # noinspection PyUnresolvedReferences self.textChanged.connect(self._none) self.setReadOnly(True) # create a mono-space font font = QtGui.QFont() font.setFamily("Courier") font.setStyleHint(QtGui.QFont.Monospace) font.setFixedPitch(True) font.setPointSize(9) self.setFont(font) # set the tab size metrics = QtGui.QFontMetrics(font) # noinspection PyArgumentList self.setTabStopWidth(3 * metrics.width(' '))
def paint(self, p, opt, widget): vb = self._view() color = self._cmdp[self._instance_prefix + 'color'] p.resetTransform() vb_rect = vb.geometry() y = self.scene_pos_y() p1 = pg.Point(vb_rect.left(), y) p2 = pg.Point(vb_rect.right(), y) pen = pg.mkPen(color) pen.setWidth(1) p.setPen(pen) p.drawLine(p1, p2) show_stats = self.statistics_show if show_stats != 'off': pen = pg.mkPen([255, 255, 255, 255]) p.setPen(pen) if self.pair is None: txt = three_sig_figs(self.y, self._units) else: dy = abs(self.y - self.pair.y) t1 = three_sig_figs(self.y, self._units) t2 = three_sig_figs(dy, self._units) txt = f'{t1}, Δ={t2}' if show_stats == 'bottom': font = QtGui.QFont() h = QtGui.QFontMetrics(font).height() p1 += pg.Point(0, h) else: p1 += pg.Point(0, -2) p.drawText(p1, txt)
def __init__(self, manager, uuid, parent): super().__init__(parent) self.__manager = manager self.__uuid = uuid self.__name = "" self.__connected = False self.ui = FreeCADGui.PySideUic.loadUi(":/Collaboration/Ui/Document.ui") layout = QtWidgets.QVBoxLayout() layout.setContentsMargins(0,0,0,0) layout.addWidget(self.ui) self.setLayout(layout) # Set the correct sizes dependent on system setting fontSize = 1.2*self.ui.nameLabel.font().pointSize() largeFont = self.ui.nameLabel.font() largeFont.setPointSize(fontSize) self.ui.nameLabel.setFont(largeFont) largeSize = QtGui.QFontMetrics(largeFont).ascent() self.ui.statusIndicator.setMaximumSize(largeSize, largeSize) self.ui.shareButton.clicked.connect(lambda: self.__manager.toggleCollaborateSlot(self.__uuid)) self.ui.docButton.clicked.connect(lambda: self.__manager.toggleOpenSlot(self.__uuid)) self.ui.editButton.clicked.connect(lambda: self.edit.emit(self.__uuid)) self.update()
def __init__(self, parent: Optional[QtWidgets.QWidget] = None, flags: Qt.WindowFlags = Qt.Widget): """Initialise a new instance of the class.""" super().__init__(parent, flags) self._verticalLayout = QtWidgets.QVBoxLayout(self) self._verticalLayout.setObjectName(u"verticalLayout") self._table_view = QtWidgets.QTableView(self) self._table_view.setObjectName("base_table_view") self._table_view.setSizeAdjustPolicy( QtWidgets.QAbstractScrollArea.AdjustToContents) self._table_view.setEditTriggers( QtWidgets.QAbstractItemView.NoEditTriggers) self._table_view.setVerticalScrollMode( QtWidgets.QAbstractItemView.ScrollPerPixel) self._table_view.horizontalHeader().setSectionResizeMode( QtWidgets.QHeaderView.Stretch) self._table_view.verticalHeader().setVisible(False) font_height = QtGui.QFontMetrics(self._table_view.font()).height() self._table_view.verticalHeader().setMinimumSectionSize(font_height + 2) self._table_view.verticalHeader().setDefaultSectionSize(font_height + 2) self._verticalLayout.addWidget(self._table_view)
def __init__(self, source, target, label="", color=None): self.label = label self.color = QtCore.Qt.gray if color is None else color self.source = weakref.ref(source) self.target = weakref.ref(target) self.arrow_size = 20.0 self.font = QtGui.QFont("Calibri", 16) self.source_point = QtCore.QPointF() self.target_point = QtCore.QPointF() self.label_w = 0 self.label_h = 0 self.line = None self.selection_polygon = None self.selection_shape = None QtWidgets.QGraphicsItem.__init__(self) if self.label != "": rect = QtGui.QFontMetrics(self.font).boundingRect(self.label) self.label_w = rect.width() self.label_h = rect.height() self.setFlag(QtWidgets.QGraphicsItem.ItemSendsGeometryChanges) self.setFlag(QtWidgets.QGraphicsItem.ItemIsSelectable, True) self.setFlag(QtWidgets.QGraphicsItem.ItemIsFocusable, True) self.setCacheMode(self.DeviceCoordinateCache) self.setZValue(-2) self.source().add_edge(self) self.target().add_edge(self) self.adjust()
def calculateRect(self, metric=None): if not metric: metric = QtGui.QFontMetrics(QtGui.QFont()) width = metric.width(self.tag) height = metric.height() self.width = width + 2 * self.x_padding self.height = height + 2 * self.y_padding
def paintEvent(self, event): QtWidgets.QSlider.paintEvent(self, event) painter = QtGui.QPainter(self) painter.setPen(QtGui.QPen(QtCore.Qt.white)) rect = self.geometry() curr_value = float(self.value()) / self.maximum() round_value = round(curr_value, 2) font_metrics = QtGui.QFontMetrics(self.font()) font_height = font_metrics.height() horizontal_x_pos = 0 horizontal_y_pos = rect.height() - font_height - 3 painter.drawText(QtCore.QPoint(horizontal_x_pos, horizontal_y_pos), str(round_value)) numTicks = (self.maximum() - self.minimum()) / self.tickInterval() if self.orientation() == QtCore.Qt.Horizontal: for i in range(numTicks + 1): tickX = ((rect.width() / float(numTicks)) * i) if tickX >= rect.width(): tickX = rect.width() - 2 elif tickX == 0: tickX = 2 height = 5 if i == 0 or i == numTicks or i == numTicks / 2: height = 10 painter.drawLine(tickX, rect.height(), tickX, rect.height() - height)
def __init__(self, parent, scene): super(Port, self).__init__(parent) self.radius_ = 5 self.margin = 2 path = QtGui.QPainterPath() path.addEllipse(-self.radius_, -self.radius_, 2 * self.radius_, 2 * self.radius_) self.setPath(path) self.setFlag(QtWidgets.QGraphicsPathItem.ItemSendsScenePositionChanges) self.font = QtGui.QFont() self.font_metrics = QtGui.QFontMetrics(self.font) self.port_text_height = self.font_metrics.height() self.is_output_ = False self._name = None self.margin = 2 self.m_node = None self.m_connections = [] self.text_path = QtGui.QPainterPath()
def set_format(self, fmt: QtGui.QTextCharFormat): cur = self.textCursor() self.selectAll() self.setCurrentCharFormat(fmt) self.setTextCursor(cur) tab_stop = settings.tabstop self.setTabStopWidth(tab_stop * QtGui.QFontMetrics(fmt.font()).width(" "))
def render_warped_line_confidence(pixmap, lines): qp = QtGui.QPainter() qp.begin(pixmap) try: font = QtGui.QFont("Arial Narrow", 48, QtGui.QFont.Bold) qp.setFont(font) fm = QtGui.QFontMetrics(font) for i, (line_path, line) in enumerate(lines.items()): #if line.confidence < 0.5: # continue # ignore path, height = line.warped_path(0.1) qp.setOpacity(1) if line.confidence < 0.75: qp.setPen(default_pen("red")) label = "%.2f" % line.confidence w = fm.horizontalAdvance(label) qp.drawText( np.mean(path[:, 0]) - w / 2, np.mean(path[:, 1]) + fm.descent(), label) finally: qp.end() return pixmap
def paint( self, painter: QtGui.QPainter, option: QtWidgets.QStyleOptionGraphicsItem, widget: QtWidgets.QWidget = None, ): view = self.scene().views()[0] view_width = view.mapToScene(0, 0, self.width, 1).boundingRect().width() width, unit = self.getWidthAndUnit(view_width) # Current scale text = f"{width * self.units[self.unit] / self.units[unit]:.3g} {unit}" width = width * view.transform().m11() fm = QtGui.QFontMetrics(self.font, painter.device()) path = QtGui.QPainterPath() path.addText( self.width / 2.0 - fm.boundingRect(text).width() / 2.0, fm.ascent(), self.font, text, ) painter.strokePath(path, QtGui.QPen(QtCore.Qt.black, 2.0)) painter.fillPath(path, QtGui.QBrush(self.color, QtCore.Qt.SolidPattern)) # Draw the bar rect = QtCore.QRectF(self.width / 2.0 - width / 2.0, fm.height(), width, self.height) painter.setPen(QtGui.QPen(QtCore.Qt.black, 1.0)) painter.setBrush(QtGui.QBrush(self.color, QtCore.Qt.SolidPattern)) painter.drawRect(rect)
def itemRect(self, index): if not index.isValid(): return QtCore.QRect() # Check whether the index's row is in the list of rows represented # by slices. if index.column() != 1: valueIndex = self.model().index(index.row(), 1, self.rootIndex()) else: valueIndex = index if self.model().data(valueIndex) > 0.0: listItem = 0 for row in range(index.row() - 1, -1, -1): if self.model().data(self.model().index( row, 1, self.rootIndex())) > 0.0: listItem += 1 if index.column() == 0: itemHeight = QtGui.QFontMetrics( self.viewOptions().font).height() return QtCore.QRect(self.totalSize, int(self.margin + listItem * itemHeight), self.totalSize - self.margin, int(itemHeight)) elif index.column() == 1: return self.viewport().rect() return QtCore.QRect()
def __init__(self, text, parent): super(DragLabel, self).__init__(parent) metric = QtGui.QFontMetrics(self.font()) size = metric.size(QtCore.Qt.TextSingleLine, text) image = QtGui.QImage(size.width() + 12, size.height() + 12, QtGui.QImage.Format_ARGB32_Premultiplied) image.fill(QtGui.qRgba(0, 0, 0, 0)) font = QtGui.QFont() font.setStyleStrategy(QtGui.QFont.ForceOutline) painter = QtGui.QPainter() painter.begin(image) painter.setRenderHint(QtGui.QPainter.Antialiasing) painter.setBrush(QtCore.Qt.white) painter.drawRoundedRect( QtCore.QRectF(0.5, 0.5, image.width() - 1, image.height() - 1), 25, 25, QtCore.Qt.RelativeSize) painter.setFont(font) painter.setBrush(QtCore.Qt.black) painter.drawText(QtCore.QRect(QtCore.QPoint(6, 6), size), QtCore.Qt.AlignCenter, text) painter.end() self.setPixmap(QtGui.QPixmap.fromImage(image)) self.labelText = text
def resizeEvent(self, event): if hasattr(self, "_vt"): sz = QtGui.QFontMetrics(self.font()).size(0, " ") columns = int(event.size().width() / sz.width()) self._vt.resize(self.defaultLines, columns) self.ShowText() super().resizeEvent(event)
def draw(self, cordinates): painter_path = QtGui.QPainterPath() textItem = QtWidgets.QGraphicsSimpleTextItem(self.name, self.graphics_item) itemFont = QtGui.QFont().setPointSize(10) textItem.setFont(itemFont) textItem.setPos(5, 10) fm = QtGui.QFontMetrics(itemFont) width = 100 if fm.width(self.name) < 100 else fm.width(self.name) fun_size = len(self.functions) * 30 fun_size = 30 if fun_size == 0 else fun_size for i, function in enumerate(self.functions, 1): textItem = QtWidgets.QGraphicsSimpleTextItem( str(function), self.graphics_item) textItem.setFont(itemFont) textItem.setPos(5, 10 + 30 * i) width = fm.width( str(function)) if fm.width(str(function)) > width else width width = width + 10 painter_path.addRect(QtCore.QRect(0, 0, width, 30)) painter_path.addRect(QtCore.QRect(0, 30, width, fun_size)) self.graphics_item.setBrush(QtGui.QBrush(QtGui.QColor( self.item_color))) self.graphics_item.setFlag( QtWidgets.QGraphicsRectItem.ItemIsSelectable) self.graphics_item.setFlag(QtWidgets.QGraphicsRectItem.ItemIsMovable) self.graphics_item.setPath(painter_path) self.graphics_item.setPos(cordinates)
def paintEvent(self, event): p = QtGui.QPainter() p.begin(self) bgColor = QtGui.QColor(44, 44, 44) textBackground = QtGui.QColor(30, 30, 30) textColor = QtGui.QColor(240, 240, 240) hoverColor = QtGui.QColor(255, 255, 255, 40) # Background p.fillRect(self.rect(), bgColor) # Icon p.drawImage(self.rect(), self.image) # Text Background if self.text() != "": textBGRect = QtCore.QRect(0, 16, 28, 12) p.fillRect(textBGRect, textBackground) # Text if self.text() != "": font = QtGui.QFont() font.setPointSize(7) fm = QtGui.QFontMetrics(font) w = (self.width() - fm.width(self.text())) / 2 h = self.height() - 2 p.setPen(textColor) p.setFont(font) p.drawText(QtCore.QPoint(w, h), self.text()) p.end()
def draw_aliased_text(painter, font, rect, text, align, color, elide=None): """Allows drawing aliased text using *QPainterPath*. This is slow to calculate but ensures the rendered text looks *smooth* (on Windows espcially, I noticed a lot of aliasing issues). We're also eliding the given text to the width of the given rectangle. Args: painter (QPainter): The active painter. font (QFont): The font to use to paint. rect (QRect): The rectangle to fit the text in. text (str): The text to paint. align (Qt.AlignmentFlag): The alignment flags. color (QColor): The color to use. Returns: int: The width of the drawn text in pixels. """ painter.save() painter.setRenderHint(QtGui.QPainter.Antialiasing, True) painter.setRenderHint(QtGui.QPainter.SmoothPixmapTransform, False) metrics = QtGui.QFontMetrics(font) if elide is None: elide = QtCore.Qt.ElideLeft if QtCore.Qt.AlignLeft & align: elide = QtCore.Qt.ElideRight if QtCore.Qt.AlignRight & align: elide = QtCore.Qt.ElideLeft if QtCore.Qt.AlignHCenter & align: elide = QtCore.Qt.ElideMiddle text = metrics.elidedText(text, elide, rect.width() * 1.01) width = metrics.horizontalAdvance(text) if QtCore.Qt.AlignLeft & align: x = rect.left() if QtCore.Qt.AlignRight & align: x = rect.right() - width if QtCore.Qt.AlignHCenter & align: x = rect.left() + (rect.width() * 0.5) - (width * 0.5) else: x = rect.left() y = rect.center().y() + (metrics.ascent() * 0.5) - (metrics.descent() * 0.5) # Making sure text fits the rectangle painter.setBrush(color) painter.setPen(QtCore.Qt.NoPen) from ..lists import delegate path = delegate.get_painter_path(x, y, font, text) painter.drawPath(path) painter.restore() return width
def __init__(self, parent=None): QtWidgets.QDialog.__init__(self, parent) self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.WindowContextHelpButtonHint) self.setWindowTitle("SIS4 I/O Info") self.setContentsMargins(0, 0, 0, 0) vbox = QtWidgets.QVBoxLayout() self.setLayout(vbox) vbox.setContentsMargins(5, 5, 5, 5) self.viewer = QtWidgets.QTextBrowser() self.viewer.resize(QtCore.QSize(280, 40)) self.viewer.setTextColor(QtGui.QColor("#4682b4")) self.viewer.ensureCursorVisible() # create a monospace font font = QtGui.QFont("Courier New") font.setStyleHint(QtGui.QFont.TypeWriter) font.setFixedPitch(True) font.setPointSize(9) self.viewer.document().setDefaultFont(font) # set the tab size metrics = QtGui.QFontMetrics(font) self.viewer.setTabStopWidth(3 * metrics.width(' ')) self.viewer.setReadOnly(True) vbox.addWidget(self.viewer)
def indexAt(self, point): if self.validItems == 0: return QtCore.QModelIndex() # Transform the view coordinates into contents widget coordinates. wx = point.x() + self.horizontalScrollBar().value() wy = point.y() + self.verticalScrollBar().value() if wx < self.totalSize: cx = wx - self.totalSize / 2 cy = self.totalSize / 2 - wy # positive cy for items above the center # Determine the distance from the center point of the pie chart. d = (cx**2 + cy**2)**0.5 if d == 0 or d > self.pieSize / 2: return QtCore.QModelIndex() # Determine the angle of the point. angle = (180 / math.pi) * math.acos(cx / d) if cy < 0: angle = 360 - angle # Find the relevant slice of the pie. startAngle = 0.0 for row in range(self.model().rowCount(self.rootIndex())): index = self.model().index(row, 1, self.rootIndex()) value = self.model().data(index) if value > 0.0: sliceAngle = 360 * value / self.totalValue if angle >= startAngle and angle < (startAngle + sliceAngle): return self.model().index(row, 1, self.rootIndex()) startAngle += sliceAngle else: itemHeight = QtGui.QFontMetrics(self.viewOptions().font).height() listItem = int((wy - self.margin) / itemHeight) validRow = 0 for row in range(self.model().rowCount(self.rootIndex())): index = self.model().index(row, 1, self.rootIndex()) if self.model().data(index) > 0.0: if listItem == validRow: return self.model().index(row, 0, self.rootIndex()) # Update the list index that corresponds to the next valid # row. validRow += 1 return QtCore.QModelIndex()
def __init__(self, font=QtGui.QFontMetrics(QtGui.QFont()), screen_size=QtCore.QSize()): super().__init__() self.screen = screen_size self.font_metric = font self.setWindowTitle('OpenMC Plot Explorer')
def __init__(self, *args, **kwargs): QtWidgets.QPushButton.__init__(self, *args, **kwargs) Base.__init__(self) self.setFixedHeight(27) self._radius = 5 self.font_metrics = QtGui.QFontMetrics(self.font())
def updateSize(self, fontSize): fontSize = int(fontSize) self.displayFont.setPointSize(fontSize) self.squareSize = max( 24, QtGui.QFontMetrics(self.displayFont).xHeight() * 3) self.adjustSize() self.update()
def drawBackground(self, painter, rect): background_brush = QtGui.QBrush(QtGui.QColor(255, 255, 255), QtCore.Qt.SolidPattern) painter.fillRect(rect, background_brush) if self.doc is not None: pen = QtGui.QPen(frame_col) # pen.setWidth(5) painter.setPen(pen) painter.setFont(font) first_sample = 0 last_sample = len(self.amp) bg_height = self.height() + self.horizontalScrollBar().height() half_client_height = bg_height / 2 font_metrics = QtGui.QFontMetrics(font) text_width, top_border = font_metrics.width( "Ojyg"), font_metrics.height() * 2 x = first_sample * self.sample_width frame = first_sample / self.samples_per_frame fps = int(round(self.doc.fps)) sample = first_sample self.list_of_lines = [] list_of_textmarkers = [] for i in range(int(first_sample), int(last_sample)): if (i + 1) % self.samples_per_frame == 0: frame_x = (frame + 1) * self.frame_width if (self.frame_width > 2) or ((frame + 1) % fps == 0): self.list_of_lines.append( QtCore.QLineF(frame_x, top_border, frame_x, bg_height)) # draw frame label if (self.frame_width > 30) or ((int(frame) + 1) % 5 == 0): self.list_of_lines.append( QtCore.QLineF(frame_x, 0, frame_x, top_border)) self.list_of_lines.append( QtCore.QLineF(frame_x + 1, 0, frame_x + 1, bg_height)) temp_rect = QtCore.QRectF(int(frame_x + 4), font_metrics.height() - 2, text_width, top_border) # Positioning is a bit different in QT here list_of_textmarkers.append( (temp_rect, str(int(frame + 1)))) x += self.sample_width sample += 1 if sample % self.samples_per_frame == 0: frame += 1 painter.drawLines(self.list_of_lines) for text_marker in list_of_textmarkers: painter.drawText(text_marker[0], QtCore.Qt.AlignLeft, text_marker[1]) if self.first_update: new_scene_rect = QtCore.QRectF(0, 0, self.list_of_lines[-1].p2().x(), self.list_of_lines[0].p2().y()) self.setSceneRect(new_scene_rect) self.scene().setSceneRect(new_scene_rect) self.first_update = False
def __init__(self, text=None, shadow=True, color=(150, 150, 150)): qw.QWidget.__init__(self) self.setMinimumHeight(2) self.setLayout(qw.QHBoxLayout()) self.layout().setContentsMargins(0, 0, 0, 0) self.layout().setSpacing(0) self.layout().setAlignment(qc.Qt.AlignVCenter) # use a frame (basically a styled widget) to create the horizontal line separator first_line = qw.QFrame() first_line.setFrameStyle(qw.QFrame.HLine) self.layout().addWidget(first_line) # In PyQt we can use style sheets which function much like html or css styles to modify attributes like # colors, fonts, etc. Maya's interface has a style sheet of its own, which is what the UI's we build # inherit from by default, and we can then override them if we like main_color = 'rgba( %s, %s, %s, 255)' % color shadow_color = 'rgba(45, 45, 45, 255)' bottom_border = '' if shadow: bottom_border = 'border-bottom:1px solid %s;' % shadow_color style_sheet = "border:0px solid rgba(0,0,0,0); \ background-color: %s; \ max-height:1px; \ %s" % (main_color, bottom_border) first_line.setStyleSheet(style_sheet) # if not using the text label option for our widget, just exit if text is None: return # otherwise, create our font and text attributes for the label first_line.setMaximumWidth(5) font = qg.QFont() font.setBold(True) # Qt has font metrics to get the size of the label text_width = qg.QFontMetrics(font) width = text_width.width( text ) + 6 # little bit of space after the label before the line continues label = qw.QLabel() label.setText(text) label.setFont(font) label.setMaximumWidth(width) label.setAlignment(qc.Qt.AlignHCenter | qc.Qt.AlignVCenter) self.layout().addWidget(label) second_line = qw.QFrame() second_line.setFrameStyle(qw.QFrame.HLine) second_line.setStyleSheet(style_sheet) self.layout().addWidget(second_line)
def mousePressEvent(self, event): if not self.wfv_parent.doc.sound.is_playing(): if event.button() == QtCore.Qt.RightButton and self.is_word(): # manually enter the pronunciation for this word dlg = PronunciationDialog( self, self.wfv_parent.doc.parent.phonemeset.set) dlg.word_label.setText(dlg.word_label.text() + ' ' + self.text()) dlg.setWindowTitle(self.title) prev_phoneme_list = "" for p in self.node.children: prev_phoneme_list += " " + p.name.lipsync_object.text dlg.phoneme_ctrl.setText(prev_phoneme_list) if dlg.exec_(): list_of_new_phonemes = dlg.phoneme_ctrl.text().split() if list_of_new_phonemes: if list_of_new_phonemes != prev_phoneme_list.split(): old_childnodes = self.node.children print(self.wfv_parent.items()) for old_node in old_childnodes: for proxy in self.wfv_parent.items(): try: if proxy.widget() == old_node.name: self.wfv_parent.scene().removeItem( proxy) except AttributeError: pass old_childnodes = [] self.node.children = [] self.lipsync_object.phonemes = [] font_metrics = QtGui.QFontMetrics(font) text_width, text_height = font_metrics.width( "Ojyg"), font_metrics.height() + 6 for phoneme_count, p in enumerate( list_of_new_phonemes): phoneme = LipsyncPhoneme() phoneme.text = p phoneme.frame = self.lipsync_object.start_frame + phoneme_count self.lipsync_object.phonemes.append(phoneme) temp_button = MovableButton( phoneme, self.wfv_parent, phoneme_count % 2) temp_button.node = Node(temp_button, parent=self.node) temp_scene_widget = self.wfv_parent.scene( ).addWidget(temp_button) # temp_scene_widget.setParent(self.wfv_parent) temp_rect = QtCore.QRect( phoneme.frame * self.wfv_parent.frame_width, self.wfv_parent.height() - (self.wfv_parent.horizontalScrollBar(). height() * 1.5) - (text_height + (text_height * (phoneme_count % 2))), self.wfv_parent.frame_width, text_height) temp_scene_widget.setGeometry(temp_rect) temp_scene_widget.setZValue(99)