class CharIconEngine(QIconEngine): """Subclass of QIconEngine that is designed to draw characters from icon fonts.""" def __init__(self, icon_font, char, color=None): super(CharIconEngine, self).__init__() self.icon_font = icon_font self.char = char if color is None: self._base_color = QColor(90, 90, 90) else: self._base_color = color self._disabled_color = QColor.fromHslF(self._base_color.hueF(), self._base_color.saturationF(), max(min(self._base_color.lightnessF() + 0.25, 1.0), 0.0)) def paint(self, painter, rect, mode, state): painter.save() if mode == QIcon.Disabled: color = self._disabled_color else: color = self._base_color painter.setPen(color) scale_factor = 1.0 draw_size = 0.875 * qRound(rect.height() * scale_factor) painter.setFont(self.icon_font.font(draw_size)) painter.setOpacity(1.0) painter.drawText(rect, Qt.AlignCenter | Qt.AlignVCenter, self.char) painter.restore() def pixmap(self, size, mode, state): pm = QPixmap(size) pm.fill(Qt.transparent) self.paint(QPainter(pm), QRect(QPoint(0, 0), size), mode, state) return pm
def get_bgcolor(self, index): """Background color depending on value""" column = index.column() if column == 0: color = QColor(Qt.lightGray) color.setAlphaF(.8) return color if not self.bgcolor_enabled: return value = self.get_value(index.row(), column-1) if isinstance(value, _sup_com): color_func = abs else: color_func = float if isinstance(value, _sup_nr+_sup_com) and self.bgcolor_enabled: vmax, vmin = self.return_max(self.max_min_col, column-1) hue = self.hue0 + self.dhue*(vmax-color_func(value)) / (vmax-vmin) hue = float(abs(hue)) if hue > 1: hue = 1 color = QColor.fromHsvF(hue, self.sat, self.val, self.alp) elif is_text_string(value): color = QColor(Qt.lightGray) color.setAlphaF(.05) else: color = QColor(Qt.lightGray) color.setAlphaF(.3) return color
def get_color(value, alpha): """Return color depending on value type""" color = QColor() for typ in COLORS: if isinstance(value, typ): color = QColor(COLORS[typ]) color.setAlphaF(alpha) return color
def __init__(self, icon_font, char, color=None): super(CharIconEngine, self).__init__() self.icon_font = icon_font self.char = char if color is None: self._base_color = QColor(90, 90, 90) else: self._base_color = color self._disabled_color = QColor.fromHslF(self._base_color.hueF(), self._base_color.saturationF(), max(min(self._base_color.lightnessF() + 0.25, 1.0), 0.0))
def get_bgcolor(self, index): """Background color depending on value""" column = index.column() if column == 0: color = QColor(BACKGROUND_NONNUMBER_COLOR) color.setAlphaF(BACKGROUND_INDEX_ALPHA) return color if not self.bgcolor_enabled: return value = self.get_value(index.row(), column-1) if self.max_min_col[column - 1] is None: color = QColor(BACKGROUND_NONNUMBER_COLOR) if is_text_string(value): color.setAlphaF(BACKGROUND_STRING_ALPHA) else: color.setAlphaF(BACKGROUND_MISC_ALPHA) else: if isinstance(value, COMPLEX_NUMBER_TYPES): color_func = abs else: color_func = float vmax, vmin = self.return_max(self.max_min_col, column-1) hue = (BACKGROUND_NUMBER_MINHUE + BACKGROUND_NUMBER_HUERANGE * (vmax - color_func(value)) / (vmax - vmin)) hue = float(abs(hue)) if hue > 1: hue = 1 color = QColor.fromHsvF(hue, BACKGROUND_NUMBER_SATURATION, BACKGROUND_NUMBER_VALUE, BACKGROUND_NUMBER_ALPHA) return color
def paintEvent(self, event): """Override Qt method.""" painter = QPainter(self) color = QColor(self.color) color.setAlphaF(.5) painter.setPen(color) offset = self.editor.document().documentMargin() + \ self.editor.contentOffset().x() for _, line_number, block in self.editor.visible_blocks: indentation = TextBlockHelper.get_fold_lvl(block) ref_lvl = indentation block = block.next() last_line = block.blockNumber() lvl = TextBlockHelper.get_fold_lvl(block) if ref_lvl == lvl: # for zone set programmatically such as imports # in pyqode.python ref_lvl -= 1 while (block.isValid() and TextBlockHelper.get_fold_lvl(block) > ref_lvl): last_line = block.blockNumber() block = block.next() end_of_sub_fold = block if last_line: block = block.document().findBlockByNumber(last_line) while ((block.blockNumber()) and (block.text().strip() == '' or block.text().strip().startswith('#'))): block = block.previous() last_line = block.blockNumber() block = self.editor.document().findBlockByNumber(line_number) top = int(self.editor.blockBoundingGeometry(block).translated( self.editor.contentOffset()).top()) bottom = top + int(self.editor.blockBoundingRect(block).height()) indentation = TextBlockHelper.get_fold_lvl(block) for i in range(1, indentation): if (line_number > last_line and TextBlockHelper.get_fold_lvl(end_of_sub_fold) <= i): continue else: x = self.editor.fontMetrics().width(i * self.i_width * '9') + offset painter.drawLine(x, top, x, bottom)
def paintEvent(self, event): """Override Qt method.""" painter = QPainter(self) color = QColor(self.color) color.setAlphaF(.5) painter.setPen(color) for top, line_number, block in self.editor.visible_blocks: bottom = top + int(self.editor.blockBoundingRect(block).height()) indentation = TextBlockHelper.get_fold_lvl(block) for i in range(1, indentation): x = self.editor.fontMetrics().width(i * self.i_width * '9') painter.drawLine(x, top, x, bottom)
def data(self, index, role=Qt.DisplayRole): """Cell content""" if not index.isValid(): return to_qvariant() value = self.get_value(index) if is_binary_string(value): try: value = to_text_string(value, 'utf8') except: pass if role == Qt.DisplayRole: if value is np.ma.masked: return '' else: return to_qvariant(self._format % value) elif role == Qt.TextAlignmentRole: return to_qvariant(int(Qt.AlignCenter|Qt.AlignVCenter)) elif role == Qt.BackgroundColorRole and self.bgcolor_enabled \ and value is not np.ma.masked: hue = self.hue0+\ self.dhue*(self.vmax-self.color_func(value)) \ /(self.vmax-self.vmin) hue = float(np.abs(hue)) color = QColor.fromHsvF(hue, self.sat, self.val, self.alp) return to_qvariant(color) elif role == Qt.FontRole: return to_qvariant(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) return to_qvariant()
def text_to_qcolor(text): """ Create a QColor from specified string Avoid warning from Qt when an invalid QColor is instantiated """ color = QColor() text = str(text) if not is_text_string(text): return color if text.startswith('#') and len(text)==7: correct = '#0123456789abcdef' for char in text: if char.lower() not in correct: return color elif text not in list(QColor.colorNames()): return color color.setNamedColor(text) return color
def update_visual(self, *args, **kwargs): """ Parameters ---------- args kwargs """ plot_data_item = self.plot_data_item if plot_data_item is None: return plot_data_item.visible = self.state.visible plot_data_item.zorder = self.state.zorder plot_data_item.width = self.state.linewidth color = QColor(self.state.layer.style.color) color.setAlphaF(self.state.layer.style.alpha) plot_data_item.color = color
def drift_color(base_color, factor=110): """ Return color that is lighter or darker than the base color. If base_color.lightness is higher than 128, the returned color is darker otherwise is is lighter. :param base_color: The base color to drift from ;:param factor: drift factor (%) :return A lighter or darker color. """ base_color = QColor(base_color) if base_color.lightness() > 128: return base_color.darker(factor) else: if base_color == QColor('#000000'): return drift_color(QColor('#101010'), factor + 20) else: return base_color.lighter(factor + 10)
def data(self, index, role=Qt.DisplayRole): """Return data at table index""" if not index.isValid(): return to_qvariant() dep = self.dependencies[index.row()] if role == Qt.DisplayRole: if index.column() == 0: value = self.get_value(index) return to_qvariant(value) else: value = self.get_value(index) return to_qvariant(value) elif role == Qt.TextAlignmentRole: return to_qvariant(int(Qt.AlignLeft|Qt.AlignVCenter)) elif role == Qt.BackgroundColorRole: from spyder.dependencies import Dependency status = dep.get_status() if status == Dependency.NOK: color = QColor(Qt.red) color.setAlphaF(.25) return to_qvariant(color)
def paintEvent(self, event): """ Override Qt method. Painting the scroll flag area """ make_flag = self.make_flag_qrect make_slider = self.make_slider_range # Filling the whole painting area painter = QPainter(self) painter.fillRect(event.rect(), self.editor.sideareas_color) block = self.editor.document().firstBlock() # Painting warnings and todos for line_number in range(1, self.editor.document().blockCount()+1): data = block.userData() if data: position = self.value_to_position(line_number) if data.code_analysis: # Warnings color = self.editor.warning_color for _message, error in data.code_analysis: if error: color = self.editor.error_color break self.set_painter(painter, color) painter.drawRect(make_flag(position)) if data.todo: # TODOs self.set_painter(painter, self.editor.todo_color) painter.drawRect(make_flag(position)) if data.breakpoint: # Breakpoints self.set_painter(painter, self.editor.breakpoint_color) painter.drawRect(make_flag(position)) block = block.next() # Occurrences if self.editor.occurrences: self.set_painter(painter, self.editor.occurrence_color) for line_number in self.editor.occurrences: position = self.value_to_position(line_number) painter.drawRect(make_flag(position)) # Found results if self.editor.found_results: self.set_painter(painter, self.editor.found_results_color) for line_number in self.editor.found_results: position = self.value_to_position(line_number) painter.drawRect(make_flag(position)) # Painting the slider range pen_color = QColor(Qt.white) pen_color.setAlphaF(.8) painter.setPen(pen_color) brush_color = QColor(Qt.white) brush_color.setAlphaF(.5) painter.setBrush(QBrush(brush_color)) painter.drawRect(make_slider(self.editor.firstVisibleBlock().blockNumber()))
""" import copy import json import os import sys from typing import List, Dict, Tuple, Union, TYPE_CHECKING, Type from pmgwidgets import PMGPanel from pmgwidgets.flowchart.core.flow_content import FlowContentForFunction from pmgwidgets.flowchart.core.flow_items import CustomPort from pmgwidgets.flowchart.core.flow_node import Node from qtpy.QtCore import Signal from qtpy.QtGui import QColor from qtpy.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QListWidget, QPushButton, QDialog, QToolBox, QTextEdit COLOR_NORMAL = QColor(212, 227, 242) COLOR_HOVER = QColor(255, 200, 00) COLOR_HOVER_PORT = QColor(0, 0, 50) if TYPE_CHECKING: from pmgwidgets.flowchart.core.flowchart_widget import PMGraphicsScene from pmgwidgets.flowchart.core.flow_content import PMGBaseFlowContent, PMGFlowContent class NodeManagerWidget(QWidget): signal_new_node = Signal(Node) def __init__(self, parent: QWidget = None, scene: 'PMGraphicsScene' = None): super().__init__(parent)
def __init__(self, linelist, parent=None, *args): QAbstractTableModel.__init__(self, parent, *args) self._linelist = linelist #TODO move entire table contents to an array of QVector # instances that will store the columns. This should # speed up the sorting (as far as some indications in # the net suggest: # http://www.qtforum.org/article/30638/qsortfilterproxymodel-qtreeview-sort-performance.html). # Bummer... this is C++ only; PyQt never went to the trouble # of converting QVector to python. # # get rid entirely of astropy table and store its contents in # a 2-D list of lists. By using python lists instead of an # astropy table, and storing the QVariant instances instead # of the raw content, we can speed up sorting by a factor > 10X. # we have to do this here because some lists may # have no lines at all. self._nrows = 0 self._ncols = 0 self._row_cells = [] for row in self._linelist: cells = [] for rindex in range(len(row)): cell = row[rindex] # handling of a color object can be tricky. Color names # returned by QColor.colorNames() are inconsistent with # color names in Qt.GlobalColor. We just go to the basics # and compare color equality (or closeness) using a distance # criterion in r,g,b coordinates. # Although costly, this would be a CPU burden only when # sorting columns with color information. For now, only # the Plotted Lines line list has such information, and # the number of actually plotted lines tends to be small # anyway. if isinstance(cell, QColor): r = cell.red() g = cell.green() b = cell.blue() min_dist = 100000 result = cell for color_name, orig_color in ID_COLORS.items(): orig_rgb = QColor(orig_color) dist = abs(orig_rgb.red() - r) + abs(orig_rgb.green() - g) + abs(orig_rgb.blue() - b) if dist < min_dist: min_dist = dist result = orig_color key = [k for k,value in ID_COLORS.items() if value == result][0] cells.append(QVariant(key)) else: cells.append(QVariant(str(cell))) self._row_cells.append(cells) self._nrows = len(self._row_cells) self._ncols = len(self._row_cells[0])
def __init__(self, parent, opacity, duration, easing_curve): super(FadingTipBox, self).__init__(parent, opacity, duration, easing_curve) self.holder = self.anim # needed for qt to work self.parent = parent self.frames = None self.color_top = QColor.fromRgb(230, 230, 230) self.color_back = QColor.fromRgb(255, 255, 255) self.offset_shadow = 0 self.fixed_width = 300 self.key_pressed = None self.setAttribute(Qt.WA_TranslucentBackground) self.setWindowFlags(Qt.Dialog | Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) self.setModal(False) # Widgets self.button_home = QPushButton("<<") self.button_close = QPushButton("X") self.button_previous = QPushButton(" < ") self.button_end = QPushButton(">>") self.button_next = QPushButton(" > ") self.button_run = QPushButton(_("Run code")) self.button_disable = None self.button_current = QToolButton() self.label_image = QLabel() self.label_title = QLabel() self.combo_title = QComboBox() self.label_current = QLabel() self.label_content = QLabel() self.label_content.setMinimumWidth(self.fixed_width) self.label_content.setMaximumWidth(self.fixed_width) self.label_current.setAlignment(Qt.AlignCenter) self.label_content.setWordWrap(True) self.widgets = [ self.label_content, self.label_title, self.label_current, self.combo_title, self.button_close, self.button_run, self.button_next, self.button_previous, self.button_end, self.button_home, self.button_current, ] arrow = get_image_path("hide.png") self.stylesheet = ( """QPushButton { background-color: rgbs(200,200,200,100%); color: rgbs(0,0,0,100%); border-style: outset; border-width: 1px; border-radius: 3px; border-color: rgbs(100,100,100,100%); padding: 2px; } QPushButton:hover { background-color: rgbs(150, 150, 150, 100%); } QPushButton:disabled { background-color: rgbs(230,230,230,100%); color: rgbs(200,200,200,100%); border-color: rgbs(200,200,200,100%); } QComboBox { padding-left: 5px; background-color: rgbs(230,230,230,100%); border-width: 0px; border-radius: 0px; min-height:20px; max-height:20px; } QComboBox::drop-down { subcontrol-origin: padding; subcontrol-position: top left; border-width: 0px; } QComboBox::down-arrow { image: url(""" + arrow + """); } """ ) # Windows fix, slashes should be always in unix-style self.stylesheet = self.stylesheet.replace("\\", "/") for widget in self.widgets: widget.setFocusPolicy(Qt.NoFocus) widget.setStyleSheet(self.stylesheet) layout_top = QHBoxLayout() layout_top.addWidget(self.combo_title) layout_top.addStretch() layout_top.addWidget(self.button_close) layout_top.addSpacerItem(QSpacerItem(self.offset_shadow, self.offset_shadow)) layout_content = QHBoxLayout() layout_content.addWidget(self.label_content) layout_content.addWidget(self.label_image) layout_content.addSpacerItem(QSpacerItem(5, 5)) layout_run = QHBoxLayout() layout_run.addStretch() layout_run.addWidget(self.button_run) layout_run.addStretch() layout_run.addSpacerItem(QSpacerItem(self.offset_shadow, self.offset_shadow)) layout_navigation = QHBoxLayout() layout_navigation.addWidget(self.button_home) layout_navigation.addWidget(self.button_previous) layout_navigation.addStretch() layout_navigation.addWidget(self.label_current) layout_navigation.addStretch() layout_navigation.addWidget(self.button_next) layout_navigation.addWidget(self.button_end) layout_navigation.addSpacerItem(QSpacerItem(self.offset_shadow, self.offset_shadow)) layout = QVBoxLayout() layout.addLayout(layout_top) layout.addStretch() layout.addSpacerItem(QSpacerItem(15, 15)) layout.addLayout(layout_content) layout.addLayout(layout_run) layout.addStretch() layout.addSpacerItem(QSpacerItem(15, 15)) layout.addLayout(layout_navigation) layout.addSpacerItem(QSpacerItem(self.offset_shadow, self.offset_shadow)) layout.setSizeConstraint(QLayout.SetFixedSize) self.setLayout(layout) self.set_funcs_before_fade_in([self._disable_widgets]) self.set_funcs_after_fade_in([self._enable_widgets]) self.set_funcs_before_fade_out([self._disable_widgets]) self.setContextMenuPolicy(Qt.CustomContextMenu)
def __init__(self, *args, pen=pg.mkPen(QColor(0, 255, 255)), **kwargs): super(LineROI, self).__init__(*args, pen=pen, **kwargs) self._update_state()
def paintEvent(self, event): """ Override Qt method. Painting the scroll flag area """ make_flag = self.make_flag_qrect # Fill the whole painting area painter = QPainter(self) painter.fillRect(event.rect(), self.editor.sideareas_color) # Paint warnings and todos block = self.editor.document().firstBlock() for line_number in range(self.editor.document().blockCount()+1): data = block.userData() if data: if data.code_analysis: # Paint the warnings color = self.editor.warning_color for source, code, severity, message in data.code_analysis: error = severity == DiagnosticSeverity.ERROR if error: color = self.editor.error_color break self.set_painter(painter, color) painter.drawRect(make_flag(line_number)) if data.todo: # Paint the todos self.set_painter(painter, self.editor.todo_color) painter.drawRect(make_flag(line_number)) if data.breakpoint: # Paint the breakpoints self.set_painter(painter, self.editor.breakpoint_color) painter.drawRect(make_flag(line_number)) block = block.next() # Paint the occurrences if self.editor.occurrences: self.set_painter(painter, self.editor.occurrence_color) for line_number in self.editor.occurrences: painter.drawRect(make_flag(line_number)) # Paint the found results if self.editor.found_results: self.set_painter(painter, self.editor.found_results_color) for line_number in self.editor.found_results: painter.drawRect(make_flag(line_number)) # Paint the slider range if not self._unit_testing: alt = QApplication.queryKeyboardModifiers() & Qt.AltModifier else: alt = self._alt_key_is_down cursor_pos = self.mapFromGlobal(QCursor().pos()) is_over_self = self.rect().contains(cursor_pos) is_over_editor = self.editor.rect().contains( self.editor.mapFromGlobal(QCursor().pos())) # We use QRect.contains instead of QWidget.underMouse method to # determined if the cursor is over the editor or the flag scrollbar # because the later gives a wrong result when a mouse button # is pressed. if ((is_over_self or (alt and is_over_editor)) and self.slider): pen_color = QColor(Qt.gray) pen_color.setAlphaF(.85) painter.setPen(pen_color) brush_color = QColor(Qt.gray) brush_color.setAlphaF(.5) painter.setBrush(QBrush(brush_color)) painter.drawRect(self.make_slider_range(cursor_pos)) self._range_indicator_is_visible = True else: self._range_indicator_is_visible = False
# Linux packagers, please set this to True if you want to make qtawesome # use system fonts SYSTEM_FONTS = False # MD5 Hashes for font files bundled with qtawesome: MD5_HASHES = { 'fontawesome4.7-webfont.ttf': 'b06871f281fee6b241d60582ae9369b9', 'fontawesome5-regular-webfont.ttf': '6a745dc6a0871f350b0219f5a2678838', 'fontawesome5-solid-webfont.ttf': 'acf50f59802f20d8b45220eaae532a1c', 'fontawesome5-brands-webfont.ttf': 'ed2b8bf117160466ba6220a8f1da54a4', 'elusiveicons-webfont.ttf': '207966b04c032d5b873fd595a211582e', 'materialdesignicons-webfont.ttf': 'b0fd91bb29dcb296a9a37f8bda0a2d85', } _default_options = { 'color': QColor(50, 50, 50), 'color_disabled': QColor(150, 150, 150), 'opacity': 1.0, 'scale_factor': 1.0, } def set_global_defaults(**kwargs): """Set global defaults for the options passed to the icon painter.""" valid_options = [ 'active', 'selected', 'disabled', 'on', 'off', 'on_active', 'on_selected', 'on_disabled', 'off_active', 'off_selected', 'off_disabled', 'color', 'color_on', 'color_off', 'color_active', 'color_selected', 'color_disabled',
from qtpy.QtWidgets import QMenu, QTreeView from spyder.config.base import get_translation from spyder.utils.qthelpers import create_action # Local imports from spyder_unittest.backend.abbreviator import Abbreviator from spyder_unittest.backend.runnerbase import Category try: _ = get_translation("unittest", dirname="spyder_unittest") except KeyError: import gettext _ = gettext.gettext COLORS = { Category.OK: QBrush(QColor("#C1FFBA")), Category.FAIL: QBrush(QColor("#FF5050")), Category.SKIP: QBrush(QColor("#C5C5C5")), Category.PENDING: QBrush(QColor("#C5C5C5")) } COLORS_DARK = { Category.OK: QBrush(QColor("#008000")), Category.FAIL: QBrush(QColor("#C6001E")), Category.SKIP: QBrush(QColor("#505050")), Category.PENDING: QBrush(QColor("#505050")) } STATUS_COLUMN = 0 NAME_COLUMN = 1 MESSAGE_COLUMN = 2
def set_margin_background_color(self, color): self.setMarginsBackgroundColor(QColor(color))
def set_background_color(self, color): self.SendScintilla(QsciScintilla.SCI_STYLESETBACK, QsciScintilla.STYLE_DEFAULT, QColor(color)) self.lexer.setPaperBackground(QColor(color))
from qtpy.QtCore import QPointF from qtpy.QtGui import QColor, QFont, QPen, QPainterPath from .shape import Shape, DEFAULT_LINE_COLOR TEXT_COLOR = QColor(0, 255, 0, 128) class PoseShape(Shape): forced_type = 'linestrip' forced_label = 'person' body_segs = [ [1, 2, 3, 4], [1, 5, 6, 7], [1, 8, 9, 10], [1, 11, 12, 13], [1, 0], [0, 14, 16, 2], [0, 15, 17, 5] ] n_pose_points = 18 def __init__(self, maybe_points): points = [p for p in maybe_points if p is not None] super(PoseShape, self).__init__( points, form=[ [PoseShape.forced_label, None, None] ], # dummy form for navigation of label dialog shape_type=PoseShape.forced_type ) # self.maybe_points = maybe_points self.point_to_label = self.make_point_to_label(maybe_points) @staticmethod def make_point_to_label(maybe_points):
def setColor(self, color=Qt.black): """""" self._color = QColor(color)
def on_edit_color(self): c = [int(255 * i) for i in self.text_col] #print('c =', c) col = QColorDialog.getColor(QColor(*c), self, "Choose a text color") self.color.SetColor(col)
def __init__(self, parent=None): QPushButton.__init__(self, parent) self.setFixedSize(20, 20) self.setIconSize(QSize(12, 12)) self.clicked.connect(self.choose_color) self._color = QColor()
def color(self, value): self._color = QColor(value).toRgb() self.color_changed.emit(self._color) self.data_item.emitDataChanged()
StringTimeSeriesProperty, StringFilteredTimeSeriesProperty, logger) from mantid.api import MultipleExperimentInfos from mantid.kernel import PropertyManager from qtpy.QtGui import QStandardItemModel, QStandardItem, QColor from qtpy.QtCore import Qt TimeSeriesProperties = (BoolTimeSeriesProperty, FloatTimeSeriesProperty, Int32TimeSeriesProperty, Int64TimeSeriesProperty, StringTimeSeriesProperty) FilteredTimeSeriesProperties = (BoolFilteredTimeSeriesProperty, FloatFilteredTimeSeriesProperty, Int32FilteredTimeSeriesProperty, Int64FilteredTimeSeriesProperty, StringFilteredTimeSeriesProperty) DEEP_RED = QColor.fromHsv(0, 180, 255) def get_type(log): """Convert type to something readable""" dtype_map = {'i': 'int', 'f': 'float', 's': 'string', 'b': 'bool'} if isinstance(log, TimeSeriesProperties): return "{} series".format(dtype_map[log.dtype()[0].lower()]) else: return log.type def get_value(log): """Returns the either the value or the number of entries """ MAX_LOG_SIZE = 20 # the maximum log length to try to show in the value column
# Copyright © 2019 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source # & Institut Laue - Langevin # SPDX - License - Identifier: GPL - 3.0 + # This file is part of the mantidqt package from __future__ import absolute_import from qtpy.QtCore import Qt from qtpy.QtGui import QColor from qtpy.QtWidgets import QAction, QHBoxLayout, QMenu, QPushButton, QSizePolicy, QTabWidget, QWidget from mantidqt.icons import get_icon from mantidqt.utils.qt import add_actions, create_action from mantidqt.widgets.codeeditor.tab_widget.codeeditor_tab_presenter import CodeEditorTabPresenter ABORT_BUTTON_RED_COLOR = QColor(230, 84, 80).name() PLAY_BUTTON_GREEN_COLOR = QColor(73, 156, 84).name() class CodeEditorTabWidget(QTabWidget): ABORT_BUTTON_OBJECT_NAME = "abort-button" NEW_EDITOR_PLUS_BTN_OBJECT_NAME = "plus-button" OPTIONS_BUTTON_OBJECT_NAME = "options-button" RUN_BUTTON_OBJECT_NAME = "run-button" SHOW_IN_EXPLORER_ACTION_OBJECT_NAME = "show-in-explorer-action" def __init__(self, parent=None, presenter=None): self.presenter = presenter if presenter else CodeEditorTabPresenter( self) super(CodeEditorTabWidget, self).__init__(parent)
def __init__(self, config_file, run_model, simulation_arguments, parent=None): QDialog.__init__(self, parent) self.setWindowFlags(Qt.Window) self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint) self.setModal(True) self.setWindowModality(Qt.WindowModal) self.setWindowTitle("Simulations - {}".format(config_file)) self._run_model = run_model ert = None if isinstance(run_model, BaseRunModel): ert = run_model.ert() self._simulations_argments = simulation_arguments self.simulations_tracker = create_tracker( run_model, qtimer_cls=QTimer, event_handler=self._on_tracker_event, num_realizations=self._simulations_argments["active_realizations"]. count(), ee_config=self._simulations_argments.get("ee_config", None)) self._ticker = QTimer(self) self._ticker.timeout.connect(self._on_ticker) states = self.simulations_tracker.get_states() self.state_colors = {state.name: state.color for state in states} self.state_colors['Success'] = self.state_colors["Finished"] self.state_colors['Failure'] = self.state_colors["Failed"] self.total_progress = SimpleProgress() status_layout = QHBoxLayout() status_layout.addStretch() self.__status_label = QLabel() status_layout.addWidget(self.__status_label) status_layout.addStretch() status_widget_container = QWidget() status_widget_container.setLayout(status_layout) self.progress = Progress() self.progress.setIndeterminateColor(self.total_progress.color) for state in states: self.progress.addState(state.state, QColor(*state.color), 100.0 * state.count / state.total_count) legend_layout = QHBoxLayout() self.legends = {} for state in states: self.legends[state] = Legend("%s (%d/%d)", QColor(*state.color)) self.legends[state].updateLegend(state.name, 0, 0) legend_layout.addWidget(self.legends[state]) legend_widget_container = QWidget() legend_widget_container.setLayout(legend_layout) self.running_time = QLabel("") self.plot_tool = PlotTool(config_file) self.plot_tool.setParent(self) self.plot_button = QPushButton(self.plot_tool.getName()) self.plot_button.clicked.connect(self.plot_tool.trigger) self.plot_button.setEnabled(ert is not None) self.kill_button = QPushButton("Kill simulations") self.done_button = QPushButton("Done") self.done_button.setHidden(True) self.restart_button = QPushButton("Restart") self.restart_button.setHidden(True) self.show_details_button = QPushButton("Details") self.show_details_button.setCheckable(True) size = 20 spin_movie = resourceMovie("ide/loading.gif") spin_movie.setSpeed(60) spin_movie.setScaledSize(QSize(size, size)) spin_movie.start() self.processing_animation = QLabel() self.processing_animation.setMaximumSize(QSize(size, size)) self.processing_animation.setMinimumSize(QSize(size, size)) self.processing_animation.setMovie(spin_movie) button_layout = QHBoxLayout() button_layout.addWidget(self.processing_animation) button_layout.addWidget(self.running_time) button_layout.addStretch() button_layout.addWidget(self.show_details_button) button_layout.addWidget(self.plot_button) button_layout.addWidget(self.kill_button) button_layout.addWidget(self.done_button) button_layout.addWidget(self.restart_button) button_widget_container = QWidget() button_widget_container.setLayout(button_layout) self.detailed_progress = DetailedProgressWidget( self, self.state_colors) self.detailed_progress.setVisible(False) self.dummy_widget_container = QWidget( ) #Used to keep the other widgets from stretching layout = QVBoxLayout() layout.addWidget(self.total_progress) layout.addWidget(status_widget_container) layout.addWidget(self.progress) layout.addWidget(legend_widget_container) layout.addWidget(self.detailed_progress) layout.addWidget(self.dummy_widget_container) layout.addWidget(button_widget_container) layout.setStretch(0, 0) layout.setStretch(1, 0) layout.setStretch(2, 0) layout.setStretch(3, 0) layout.setStretch(4, 1) layout.setStretch(5, 1) layout.setStretch(6, 0) self.setLayout(layout) self.kill_button.clicked.connect(self.killJobs) self.done_button.clicked.connect(self.accept) self.restart_button.clicked.connect(self.restart_failed_realizations) self.show_details_button.clicked.connect(self.toggle_detailed_progress) self.simulation_done.connect(self._on_simulation_done)
def _setupUi(self): label = QLabel('<h2>'+self.section+' Tune<h2>', self, alignment=Qt.AlignHCenter) label.setObjectName('label') label.setStyleSheet('#label{min-height: 1.29em; max-height: 1.29em;}') if self.section == 'SI': # Tune self.wid_tune_mon = SITuneMonitor(self, self.prefix) # Settings self.tabCtrl = QTabWidget(self) hcolor = QColor(179, 229, 255) vcolor = QColor(255, 179, 179) self.ctrlH = TuneControls(parent=self, prefix=self.prefix, section=self.section, orientation='H', background=hcolor) self.tabCtrl.addTab(self.ctrlH, 'Horizontal') self.ctrlV = TuneControls(parent=self, prefix=self.prefix, section=self.section, orientation='V', background=vcolor) self.tabCtrl.addTab(self.ctrlV, 'Vertical') self.tabCtrl.setStyleSheet(""" QTabWidget::pane { border-left: 2px solid gray; border-bottom: 2px solid gray; border-right: 2px solid gray; } QTabBar::tab:first { background-color: #B3E5FF; } QTabBar::tab:last { background-color: #FFB3B3; } """) self.settings = QWidget() vbox_sett = QVBoxLayout(self.settings) vbox_sett.addWidget(self.tabCtrl) # Spectra view self.spectra_view = TuneSpectraControls( self, self.prefix, self.section) self.spectra_view.setObjectName('spectra_view') if self.section == 'BO': self.trig_gbox = QGroupBox('Trigger', self) self.trig_gbox.setLayout(QHBoxLayout()) self.trig_gbox.layout().addWidget(HLTriggerSimple( self.trig_gbox, device='BO-Glob:TI-TuneProc', prefix=self.prefix, duration=True, nrpulses=True)) vbox_sett.addWidget(self.trig_gbox) # Sepctrograms self.specH = BOTuneSpectrogramControls( parent=self, prefix=self.prefix, orientation='H', title='<h3>Horizontal</h3>', background=hcolor) self.specH.setObjectName('specH') self.specV = BOTuneSpectrogramControls( parent=self, prefix=self.prefix, orientation='V', title='<h3>Vertical</h3>', background=vcolor) self.specV.setObjectName('specV') vbox_meas = QVBoxLayout() vbox_meas.addWidget(self.specH) vbox_meas.addSpacing(10) vbox_meas.addWidget(self.specV) # Connect signals self.specH.spectrogram.idx2send_changed.connect( self.specV.update_idx2plot) self.specH.sb_idx2plot.editingFinished.connect( self.specV.update_idx2plot) self.specH.pb_resetbuff.clicked.connect( self.specV.spectrogram.resetBuffer) self.specH.sb_buffsz.editingFinished.connect( self.specV.update_buffsize) self.specV.spectrogram.idx2send_changed.connect( self.specH.update_idx2plot) self.specV.sb_idx2plot.editingFinished.connect( self.specH.update_idx2plot) self.specV.pb_resetbuff.clicked.connect( self.specH.spectrogram.resetBuffer) self.specV.sb_buffsz.editingFinished.connect( self.specH.update_buffsize) self.specH.spectrogram.new_data.connect( self.spectra_view.spectra.receiveDataH) self.specV.spectrogram.new_data.connect( self.spectra_view.spectra.receiveDataV) self.pb_showsett = QPushButton('>', self) self.pb_showsett.setObjectName('showsett') self.pb_showsett.setToolTip('Hide settings') self.pb_showsett.setStyleSheet( '#showsett{min-width:0.7em;max-width:0.7em;}') self.pb_showsett.released.connect(self._handle_settings_vis) hbox_vis = QHBoxLayout() hbox_vis.addWidget(self.pb_showsett, alignment=Qt.AlignLeft) self.setStyleSheet( "#specH, #specV {min-width:40em; min-height: 18em;}" "#spectra_view {min-width:40em; min-height: 36em;}" "#wid_tuneh, #wid_tunev {border:2px solid gray;}") cw = QWidget(self) self.setCentralWidget(cw) lay = QVBoxLayout(cw) if self.section == 'BO': hbox = QHBoxLayout() hbox.addWidget(self.settings) hbox.addLayout(vbox_meas) hbox.addWidget(self.spectra_view) hbox.setStretch(0, 1) hbox.setStretch(1, 1) hbox.setStretch(2, 1) lay.addWidget(label) lay.addLayout(hbox) lay.addLayout(hbox_vis) else: hbox = QHBoxLayout() hbox.addWidget(self.settings) hbox.addWidget(self.spectra_view) hbox.setStretch(0, 1) hbox.setStretch(1, 1) lay.addWidget(label) lay.addWidget(self.wid_tune_mon) lay.addLayout(hbox) lay.addLayout(hbox_vis)
QPixmap, QRegion) from qtpy.QtWidgets import (QAction, QApplication, QComboBox, QDialog, QGraphicsOpacityEffect, QHBoxLayout, QLabel, QLayout, QMainWindow, QMenu, QPushButton, QSpacerItem, QToolButton, QVBoxLayout, QWidget) # Local imports from spyder.config.base import _, get_image_path from spyder.config.gui import is_dark_interface from spyder.py3compat import to_binary_string from spyder.utils.qthelpers import add_actions, create_action from spyder.utils import icon_manager as ima if is_dark_interface(): MAIN_TOP_COLOR = MAIN_BG_COLOR = QColor.fromRgb(35, 38, 41) else: MAIN_TOP_COLOR = QColor.fromRgb(230, 230, 230) MAIN_BG_COLOR = QColor.fromRgb(255, 255, 255) # FIXME: Known issues # How to handle if an specific dockwidget does not exists/load, like ipython # on python3.3, should that frame be removed? should it display a warning? class SpyderWidgets(object): """List of supported widgets to highlight/decorate""" # Panes ipython_console = 'ipyconsole' editor = 'editor' editor_line_number_area = 'editor.get_current_editor().linenumberarea' editor_scroll_flag_area = 'editor.get_current_editor().scrollflagarea'
QPixmap, QRegion) from qtpy.QtWidgets import (QAction, QApplication, QComboBox, QDialog, QGraphicsOpacityEffect, QHBoxLayout, QLabel, QLayout, QMainWindow, QMenu, QPushButton, QSpacerItem, QToolButton, QVBoxLayout, QWidget) # Local imports from spyder.config.base import _, get_image_path from spyder.config.gui import is_dark_interface from spyder.py3compat import to_binary_string from spyder.utils.qthelpers import add_actions, create_action from spyder.utils import icon_manager as ima if is_dark_interface(): MAIN_TOP_COLOR = MAIN_BG_COLOR = QColor.fromRgb(25, 35, 45) else: MAIN_TOP_COLOR = QColor.fromRgb(230, 230, 230) MAIN_BG_COLOR = QColor.fromRgb(255, 255, 255) # FIXME: Known issues # How to handle if an specific dockwidget does not exists/load, like ipython # on python3.3, should that frame be removed? should it display a warning? class SpyderWidgets(object): """List of supported widgets to highlight/decorate""" # Panes ipython_console = 'ipyconsole' editor = 'editor' editor_line_number_area = 'editor.get_current_editor().linenumberarea' editor_scroll_flag_area = 'editor.get_current_editor().scrollflagarea'
import gettext _ = gettext.gettext locale_codec = QTextCodec.codecForLocale() COL_NO = 0 COL_HITS = 1 COL_TIME = 2 COL_PERHIT = 3 COL_PERCENT = 4 COL_LINE = 5 COL_POS = 0 # Position is not displayed but set as Qt.UserRole CODE_NOT_RUN_COLOR = QBrush(QColor.fromRgb(128, 128, 128, 200)) WEBSITE_URL = 'http://pythonhosted.org/line_profiler/' def is_lineprofiler_installed(): """ Checks if the program and the library for line_profiler is installed. """ return (programs.is_module_installed('line_profiler') and programs.find_program('kernprof') is not None) class LineProfilerWidget(QWidget): """ Line profiler widget.
def set_painter(self, painter, light_color): """Set scroll flag area painter pen and brush colors""" painter.setPen(QColor(light_color).darker(120)) painter.setBrush(QBrush(QColor(light_color)))
def __init__(self, *args, pen=pg.mkPen(QColor(0, 255, 255)), **kwargs): super(RectROI, self).__init__(*args, pen=pen, **kwargs) self.handle = self.handles[0]
""" 绘制层次: """ from qtpy.QtCore import QLineF, QPointF, Qt, QRectF, Signal from qtpy.QtGui import QPolygonF, QPen, QPainterPath, QColor, QPainter, QBrush from qtpy.QtWidgets import QGraphicsLineItem, QGraphicsItem, QGraphicsSceneMouseEvent, QGraphicsObject, \ QStyleOptionGraphicsItem, QWidget, QGraphicsSceneHoverEvent, QGraphicsTextItem, QTextEdit from qtpy import PYQT5, PYSIDE2 from typing import TYPE_CHECKING, Tuple, List, Callable, Any if TYPE_CHECKING: from .flowchart_widget import Node, PMGraphicsScene COLOR_NORMAL = QColor(212, 227, 242) COLOR_LINE_NORMAL = QColor(30, 30, 30) COLOR_HOVER = QColor(255, 200, 00) COLOR_HOVER_PORT = QColor(0, 0, 50) COLOR_HOVER_MID_POINT = QColor(0, 0, 200) COLOR_SELECTED = QColor(255, 255, 0) def round_position(point: QPointF, pixels=5): x, y = point.x(), point.y() x_cor, y_cor = round(x * 1.0 / pixels) * pixels, round( y * 1.0 / pixels) * pixels return QPointF(x_cor, y_cor) class PMGSimpleSignal():
def paint(self, p, opt, widget): # Enforce constraints on handles r2 = Point(np.cos(np.radians(self.thetacenter)), np.sin(np.radians( self.thetacenter))) # chi center direction vector # constrain innerhandle to be parallel to outerhandle, and shorter than outerhandle self.innerhandle.setPos(r2 * self.innerradius) # constrain widthhandle to be counter-clockwise from innerhandle widthangle = np.radians(self.thetawidth / 2 + self.thetacenter) widthv = Point(np.cos(widthangle), np.sin(widthangle)) if self.thetawidth > 0 else r2 # constrain widthhandle to half way between inner and outerhandles self.widthhandle.setPos(widthv * (self.innerradius + self.outerradius) / 2) # constrain handles to base values self.outerhandle.setPos(r2 * self.outerradius) pen = self.currentPen pen.setColor(QColor(0, 255, 255)) p.setPen(pen) r = self.boundingRect() # p.drawRect(r) p.setRenderHint(QPainter.Antialiasing) p.scale(r.width(), r.height()) # workaround for GL bug centerangle = self.innerhandle.pos().angle(Point(1, 0)) startangle = centerangle - self.thetawidth / 2 endangle = centerangle + self.thetawidth / 2 r = QCircRectF(radius=0.5) if self.innerradius < self.outerradius and self.thetawidth > 0: p.drawArc(r, -startangle * 16, -self.thetawidth * 16) radius = self.innerradius / self.outerradius / 2 r = QCircRectF() r.radius = radius if self.innerradius < self.outerradius and self.thetawidth > 0: p.drawArc(r, -startangle * 16, -self.thetawidth * 16) pen.setStyle(Qt.DashLine) p.setPen(pen) p.drawLine(QPointF(0., 0.), self.widthhandle.pos().norm() / 2) r1v = self.innerhandle.pos().norm() p.drawLine(QPointF(0., 0.), (-1. * self.widthhandle.pos() + 2 * self.widthhandle.pos().dot(r1v) * r1v).norm() / 2) pen.setStyle(Qt.SolidLine) if self.innerradius < self.outerradius and self.thetawidth > 0: path = QPainterPath() path.moveTo((-1. * self.widthhandle.pos() + 2 * self.widthhandle.pos().dot(r1v) * r1v).norm() / 2) path.arcTo(r, -startangle, -self.thetawidth) # inside path.lineTo(self.widthhandle.pos().norm() / 2) # ? side path.arcTo(QCircRectF(radius=0.5), -endangle, self.thetawidth) # outside path.lineTo((-1. * self.widthhandle.pos() + 2 * self.widthhandle.pos().dot(r1v) * r1v).norm() / 2) self.path = path p.fillPath(path, QBrush(QColor(0, 255, 255, 20)))
def __draw_point(self, i: int, vpoint: VPoint) -> None: """Draw a point.""" connected = len(vpoint.links) - 1 if vpoint.type in {VJoint.P, VJoint.RP}: pen = QPen(QColor(*vpoint.color)) pen.setWidth(2) # Draw slot point and pin point for j, (cx, cy) in enumerate(vpoint.c): if not vpoint.links: grounded = False else: grounded = vpoint.links[j] == VLink.FRAME # Slot point if j == 0 or vpoint.type == VJoint.P: if self.monochrome: color = Qt.black else: color = QColor(*vpoint.color) pen.setColor(color) self.painter.setPen(pen) cp = QPointF(cx, -cy) * self.zoom jr = self.joint_size * (2 if j == 0 else 1) rp = QPointF(jr, -jr) self.painter.drawRect(QRectF(cp + rp, cp - rp)) if self.show_point_mark: pen.setColor(Qt.darkGray) self.painter.setPen(pen) text = f"[Point{i}]" if self.show_dimension: text += f":({cx:.02f}, {cy:.02f})" self.painter.drawText(cp + rp, text) else: self.draw_point(i, cx, cy, grounded, vpoint.color, connected) # Slider line pen.setColor(QColor(*vpoint.color).darker()) self.painter.setPen(pen) qline_m = QLineF( QPointF(vpoint.c[1, 0], -vpoint.c[1, 1]) * self.zoom, QPointF(vpoint.c[0, 0], -vpoint.c[0, 1]) * self.zoom) nv = qline_m.normalVector() nv.setLength(self.joint_size) nv.setPoints(nv.p2(), nv.p1()) qline_1 = nv.normalVector() qline_1.setLength(qline_m.length()) self.painter.drawLine(qline_1) nv.setLength(nv.length() * 2) nv.setPoints(nv.p2(), nv.p1()) qline_2 = nv.normalVector() qline_2.setLength(qline_m.length()) qline_2.setAngle(qline_2.angle() + 180) self.painter.drawLine(qline_2) else: self.draw_point(i, vpoint.cx, vpoint.cy, vpoint.grounded(), vpoint.color, connected) # For selects function if self.select_mode == SelectMode.JOINT and (i in self.selections): pen = QPen(QColor(161, 16, 239)) pen.setWidth(3) self.painter.setPen(pen) self.painter.drawRect(vpoint.cx * self.zoom - 12, vpoint.cy * -self.zoom - 12, 24, 24)
from mantidqt.io import open_a_file_dialog from mantidqt.widgets.codeeditor.codecommenter import CodeCommenter from mantidqt.widgets.codeeditor.completion import CodeCompleter from mantidqt.widgets.codeeditor.editor import CodeEditor from mantidqt.widgets.codeeditor.errorformatter import ErrorFormatter from mantidqt.widgets.codeeditor.execution import PythonCodeExecution from mantidqt.widgets.embedded_find_replace_dialog.presenter import EmbeddedFindReplaceDialog IDLE_STATUS_MSG = "Status: Idle." LAST_JOB_MSG_TEMPLATE = "Last job completed {} at {} in {:.3f}s" RUNNING_STATUS_MSG = "Status: Running" ABORTED_STATUS_MSG = "Status: Aborted" # Editor CURRENTLINE_BKGD_COLOR = QColor(247, 236, 248) TAB_WIDTH = 4 TAB_CHAR = '\t' SPACE_CHAR = " " class EditorIO(object): def __init__(self, editor, confirm_on_exit=True): self.editor = editor self.confirm_on_exit = confirm_on_exit def ask_for_filename(self): filename = open_a_file_dialog(parent=self.editor, default_suffix=".py", file_filter="Python Files (*.py)", accept_mode=QFileDialog.AcceptSave,
def paintEvent(self, event: QPaintEvent) -> None: """Drawing functions.""" width = self.width() height = self.height() if self.width_old is None: self.width_old = width if self.height_old is None: self.height_old = height if self.width_old != width or self.height_old != height: self.ox += (width - self.width_old) / 2 self.oy += (height - self.height_old) / 2 # 'self' is the instance of 'DynamicCanvas'. BaseCanvas.paintEvent(self, event) # Draw links except ground for vlink in self.vlinks[1:]: self.__draw_link(vlink) # Draw path if self.path.show != -2: self.__draw_path() # Draw solving path if self.show_target_path: self.painter.setFont(QFont("Arial", self.font_size + 5)) self.draw_slvs_ranges() self.draw_target_path() self.painter.setFont(QFont("Arial", self.font_size)) # Draw points for i, vpoint in enumerate(self.vpoints): self.__draw_point(i, vpoint) # Draw solutions if self.select_mode == SelectMode.SOLUTION: for i, expr in enumerate(self.exprs): func = expr[0] params = expr[1:-1] target = expr[-1] self.draw_solution(func, params, target, self.vpoints) if i in self.selections: pos, _ = self.solution_polygon(func, params, target, self.vpoints) pen = QPen() pen.setWidth(self.link_width + 3) pen.setColor(QColor(161, 16, 239)) self.painter.setPen(pen) self.painter.drawPolygon(QPolygonF(pos)) # Draw a colored frame for free move mode if self.free_move != FreeMode.NO_FREE_MOVE: pen = QPen() if self.free_move == FreeMode.TRANSLATE: pen.setColor(QColor(161, 16, 229)) elif self.free_move == FreeMode.ROTATE: pen.setColor(QColor(219, 162, 6)) elif self.free_move == FreeMode.REFLECT: pen.setColor(QColor(79, 249, 193)) pen.setWidth(8) self.painter.setPen(pen) self.__draw_frame() # Rectangular selection if self.selector.picking: pen = QPen(Qt.gray) pen.setWidth(1) self.painter.setPen(pen) self.painter.drawRect(self.selector.to_rect(self.zoom)) # Show FPS self.fps_updated.emit() self.painter.end() # Record the widget size. self.width_old = width self.height_old = height
def _show_message(self, text): """Show message on splash screen.""" self.splash.showMessage( text, Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.white))
def populate_tree(self, parentItem, children_list): """Recursive method to create each item (and associated data) in the tree.""" for child_key in children_list: self.item_depth += 1 (filename, line_number, function_name, file_and_line, node_type ) = self.function_info(child_key) ((total_calls, total_calls_dif), (loc_time, loc_time_dif), (cum_time, cum_time_dif)) = self.format_output(child_key) child_item = TreeWidgetItem(parentItem) self.item_list.append(child_item) self.set_item_data(child_item, filename, line_number) # FIXME: indexes to data should be defined by a dictionary on init child_item.setToolTip(0, _('Function or module name')) child_item.setData(0, Qt.DisplayRole, function_name) child_item.setIcon(0, self.icon_list[node_type]) child_item.setToolTip(1, _('Time in function '\ '(including sub-functions)')) child_item.setData(1, Qt.DisplayRole, cum_time) child_item.setTextAlignment(1, Qt.AlignRight) child_item.setData(2, Qt.DisplayRole, cum_time_dif[0]) child_item.setForeground(2, QColor(cum_time_dif[1])) child_item.setTextAlignment(2, Qt.AlignLeft) child_item.setToolTip(3, _('Local time in function '\ '(not in sub-functions)')) child_item.setData(3, Qt.DisplayRole, loc_time) child_item.setTextAlignment(3, Qt.AlignRight) child_item.setData(4, Qt.DisplayRole, loc_time_dif[0]) child_item.setForeground(4, QColor(loc_time_dif[1])) child_item.setTextAlignment(4, Qt.AlignLeft) child_item.setToolTip(5, _('Total number of calls '\ '(including recursion)')) child_item.setData(5, Qt.DisplayRole, total_calls) child_item.setTextAlignment(5, Qt.AlignRight) child_item.setData(6, Qt.DisplayRole, total_calls_dif[0]) child_item.setForeground(6, QColor(total_calls_dif[1])) child_item.setTextAlignment(6, Qt.AlignLeft) child_item.setToolTip(7, _('File:line '\ 'where function is defined')) child_item.setData(7, Qt.DisplayRole, file_and_line) #child_item.setExpanded(True) if self.is_recursive(child_item): child_item.setData(7, Qt.DisplayRole, '(%s)' % _('recursion')) child_item.setDisabled(True) else: callees = self.find_callees(child_key) if self.item_depth < 3: self.populate_tree(child_item, callees) elif callees: child_item.setChildIndicatorPolicy(child_item.ShowIndicator) self.items_to_be_shown[id(child_item)] = callees self.item_depth -= 1
def drawContents(self, painter): """ @type painter: QPainter """ w = self.width() h = self.height() margin = 10 background = QColor(210, 211, 215) text_color = QColor(0, 0, 0) foreground = QColor(255, 255, 255) painter.setBrush(background) painter.fillRect(0, 0, w, h, background) pen = QPen() pen.setWidth(2) pen.setColor(foreground) painter.setPen(pen) painter.drawRect(0, 0, w - 1, h - 1) image_width = self.splash_image.width() image_height = self.splash_image.height() aspect = 1.0 if image_height: aspect = float(image_width) / float(image_height) scaled_height = h - 2 * margin scaled_width = scaled_height * aspect painter.drawRect(margin, margin, scaled_width, scaled_height) painter.drawPixmap(margin, margin, scaled_width, scaled_height, self.splash_image) text_x = scaled_width + 2 * margin top_offset = margin text_area_width = w - scaled_width - 2 * margin painter.setPen(text_color) text_size = 150 font = QFont("Serif") font.setStyleHint(QFont.Serif) font.setPixelSize(text_size) painter.setFont(font) painter.drawText(text_x, margin + top_offset, text_area_width, text_size, Qt.AlignHCenter | Qt.AlignCenter, self.ert) top_offset += text_size + 2 * margin text_size = 25 font.setPixelSize(text_size) painter.setFont(font) painter.drawText(text_x, top_offset, text_area_width, text_size, Qt.AlignHCenter | Qt.AlignCenter, self.ert_title) top_offset += text_size + 4 * margin text_size = 20 font.setPixelSize(text_size) painter.setFont(font) painter.drawText(text_x, top_offset, text_area_width, text_size, Qt.AlignHCenter | Qt.AlignCenter, self.version)
def paintEvent(self, event): """ Override Qt method. Painting the scroll flag area """ make_flag = self.make_flag_qrect # Fill the whole painting area painter = QPainter(self) painter.fillRect(event.rect(), self.editor.sideareas_color) # Paint warnings and todos block = self.editor.document().firstBlock() for line_number in range(self.editor.document().blockCount() + 1): data = block.userData() if data: if data.code_analysis: # Paint the warnings color = self.editor.warning_color for source, code, severity, message in data.code_analysis: error = severity == DiagnosticSeverity.ERROR if error: color = self.editor.error_color break self.set_painter(painter, color) painter.drawRect(make_flag(line_number)) if data.todo: # Paint the todos self.set_painter(painter, self.editor.todo_color) painter.drawRect(make_flag(line_number)) if data.breakpoint: # Paint the breakpoints self.set_painter(painter, self.editor.breakpoint_color) painter.drawRect(make_flag(line_number)) block = block.next() # Paint the occurrences if self.editor.occurrences: self.set_painter(painter, self.editor.occurrence_color) for line_number in self.editor.occurrences: painter.drawRect(make_flag(line_number)) # Paint the found results if self.editor.found_results: self.set_painter(painter, self.editor.found_results_color) for line_number in self.editor.found_results: painter.drawRect(make_flag(line_number)) # Paint the slider range if not self._unit_testing: alt = QApplication.queryKeyboardModifiers() & Qt.AltModifier else: alt = self._alt_key_is_down cursor_pos = self.mapFromGlobal(QCursor().pos()) is_over_self = self.rect().contains(cursor_pos) is_over_editor = self.editor.rect().contains( self.editor.mapFromGlobal(QCursor().pos())) # We use QRect.contains instead of QWidget.underMouse method to # determined if the cursor is over the editor or the flag scrollbar # because the later gives a wrong result when a mouse button # is pressed. if ((is_over_self or (alt and is_over_editor)) and self.slider): pen_color = QColor(Qt.gray) pen_color.setAlphaF(.85) painter.setPen(pen_color) brush_color = QColor(Qt.gray) brush_color.setAlphaF(.5) painter.setBrush(QBrush(brush_color)) painter.drawRect(self.make_slider_range(cursor_pos)) self._range_indicator_is_visible = True else: self._range_indicator_is_visible = False
def getActiveWidget(self): if not hasattr(self, '_widget'): self._widget = QColor() return self._widget
def getColor(self): if not hasattr(self, '_color'): self._color = QColor() return self._color
def populate_tree(self): """Create each item (and associated data) in the tree""" if not self.stats: warn_item = QTreeWidgetItem(self) warn_item.setData( 0, Qt.DisplayRole, _('No timings to display. ' 'Did you forget to add @profile decorators ?') .format(url=WEBSITE_URL)) warn_item.setFirstColumnSpanned(True) warn_item.setTextAlignment(0, Qt.AlignCenter) font = warn_item.font(0) font.setStyle(QFont.StyleItalic) warn_item.setFont(0, font) return try: monospace_font = self.window().editor.get_plugin_font() except AttributeError: # If run standalone for testing monospace_font = QFont("Courier New") monospace_font.setPointSize(10) for func_info, func_data in self.stats.items(): # Function name and position filename, start_line_no, func_name = func_info func_stats, func_total_time = func_data func_item = QTreeWidgetItem(self) func_item.setData( 0, Qt.DisplayRole, _('{func_name} ({time_ms:.3f}ms) in file "{filename}", ' 'line {line_no}').format( filename=filename, line_no=start_line_no, func_name=func_name, time_ms=func_total_time * 1e3)) func_item.setFirstColumnSpanned(True) func_item.setData(COL_POS, Qt.UserRole, (osp.normpath(filename), start_line_no)) # For sorting by time func_item.setData(COL_TIME, Qt.DisplayRole, func_total_time * 1e3) func_item.setData(COL_PERCENT, Qt.DisplayRole, func_total_time * 1e3) if self.parent().use_colors: # Choose deteministic unique color for the function md5 = hashlib.md5((filename + func_name).encode("utf8")).hexdigest() hue = (int(md5[:2], 16) - 68) % 360 # avoid blue (unreadable) func_color = QColor.fromHsv(hue, 200, 255) else: # Red color only func_color = QColor.fromRgb(255, 0, 0) # Lines of code for line_info in func_stats: line_item = QTreeWidgetItem(func_item) (line_no, code_line, line_total_time, time_per_hit, hits, percent) = line_info self.fill_item( line_item, filename, line_no, code_line, line_total_time, percent, time_per_hit, hits) # Color background if line_total_time is not None: alpha = percent color = QColor(func_color) color.setAlphaF(alpha) # Returns None color = QBrush(color) for col in range(self.columnCount()): line_item.setBackground(col, color) else: for col in range(self.columnCount()): line_item.setForeground(col, CODE_NOT_RUN_COLOR) # Monospace font for code line_item.setFont(COL_LINE, monospace_font)
def drawContents(self, painter): """@type painter: QPainter""" w = self.width() h = self.height() margin = 10 background = QColor(210, 211, 215) text_color = QColor(0, 0, 0) foreground = QColor(255, 255, 255) painter.setBrush(background) painter.fillRect(0, 0, w, h, background) pen = QPen() pen.setWidth(2) pen.setColor(foreground) painter.setPen(pen) painter.drawRect(0, 0, w - 1, h - 1) text_x = 2 * margin top_offset = margin text_area_width = w - 2 * margin painter.setPen(text_color) text_size = 150 font = QFont("Serif") font.setStyleHint(QFont.Serif) font.setPixelSize(text_size) painter.setFont(font) painter.drawText( text_x, margin + top_offset, text_area_width, text_size, int(Qt.AlignHCenter | Qt.AlignCenter), self.ert, ) top_offset += text_size + 2 * margin text_size = 25 font.setPixelSize(text_size) painter.setFont(font) painter.drawText( text_x, top_offset, text_area_width, text_size, int(Qt.AlignHCenter | Qt.AlignCenter), self.ert_title, ) top_offset += text_size + 4 * margin text_size = 20 font.setPixelSize(text_size) painter.setFont(font) painter.drawText( text_x, top_offset, text_area_width, text_size, int(Qt.AlignHCenter | Qt.AlignCenter), self.version, )
def __init__(self, parent, opacity, duration, easing_curve, tour=None): super(FadingTipBox, self).__init__(parent, opacity, duration, easing_curve) self.holder = self.anim # needed for qt to work self.parent = parent self.tour = tour self.frames = None self.color_top = QColor.fromRgb(230, 230, 230) self.color_back = QColor.fromRgb(255, 255, 255) self.offset_shadow = 0 self.fixed_width = 300 self.key_pressed = None self.setAttribute(Qt.WA_TranslucentBackground) self.setWindowFlags(Qt.Dialog | Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) self.setModal(False) # Widgets def toolbutton(icon): bt = QToolButton() bt.setAutoRaise(True) bt.setIcon(icon) return bt self.button_close = toolbutton(ima.icon("tour.close")) self.button_home = toolbutton(ima.icon("tour.home")) self.button_previous = toolbutton(ima.icon("tour.previous")) self.button_end = toolbutton(ima.icon("tour.end")) self.button_next = toolbutton(ima.icon("tour.next")) self.button_run = QPushButton(_('Run code')) self.button_disable = None self.button_current = QToolButton() self.label_image = QLabel() self.label_title = QLabel() self.combo_title = QComboBox() self.label_current = QLabel() self.label_content = QLabel() self.label_content.setMinimumWidth(self.fixed_width) self.label_content.setMaximumWidth(self.fixed_width) self.label_current.setAlignment(Qt.AlignCenter) self.label_content.setWordWrap(True) self.widgets = [self.label_content, self.label_title, self.label_current, self.combo_title, self.button_close, self.button_run, self.button_next, self.button_previous, self.button_end, self.button_home, self.button_current] arrow = get_image_path('hide.png') self.stylesheet = '''QComboBox { padding-left: 5px; background-color: rgbs(230,230,230,100%); border-width: 0px; border-radius: 0px; min-height:20px; max-height:20px; } QComboBox::drop-down { subcontrol-origin: padding; subcontrol-position: top left; border-width: 0px; } QComboBox::down-arrow { image: url(''' + arrow + '''); } ''' # Windows fix, slashes should be always in unix-style self.stylesheet = self.stylesheet.replace('\\', '/') self.setFocusPolicy(Qt.StrongFocus) for widget in self.widgets: widget.setFocusPolicy(Qt.NoFocus) widget.setStyleSheet(self.stylesheet) layout_top = QHBoxLayout() layout_top.addWidget(self.combo_title) layout_top.addStretch() layout_top.addWidget(self.button_close) layout_top.addSpacerItem(QSpacerItem(self.offset_shadow, self.offset_shadow)) layout_content = QHBoxLayout() layout_content.addWidget(self.label_content) layout_content.addWidget(self.label_image) layout_content.addSpacerItem(QSpacerItem(5, 5)) layout_run = QHBoxLayout() layout_run.addStretch() layout_run.addWidget(self.button_run) layout_run.addStretch() layout_run.addSpacerItem(QSpacerItem(self.offset_shadow, self.offset_shadow)) layout_navigation = QHBoxLayout() layout_navigation.addWidget(self.button_home) layout_navigation.addWidget(self.button_previous) layout_navigation.addStretch() layout_navigation.addWidget(self.label_current) layout_navigation.addStretch() layout_navigation.addWidget(self.button_next) layout_navigation.addWidget(self.button_end) layout_navigation.addSpacerItem(QSpacerItem(self.offset_shadow, self.offset_shadow)) layout = QVBoxLayout() layout.addLayout(layout_top) layout.addStretch() layout.addSpacerItem(QSpacerItem(15, 15)) layout.addLayout(layout_content) layout.addLayout(layout_run) layout.addStretch() layout.addSpacerItem(QSpacerItem(15, 15)) layout.addLayout(layout_navigation) layout.addSpacerItem(QSpacerItem(self.offset_shadow, self.offset_shadow)) layout.setSizeConstraint(QLayout.SetFixedSize) self.setLayout(layout) self.set_funcs_before_fade_in([self._disable_widgets]) self.set_funcs_after_fade_in([self._enable_widgets, self.setFocus]) self.set_funcs_before_fade_out([self._disable_widgets]) self.setContextMenuPolicy(Qt.CustomContextMenu)
def data(self, index, role=Qt.DisplayRole): if not index.isValid(): return None result = None record = self.records[index.row()] if getattr(record, '_cutelog', False): return self.data_internal(index, record, role) if role == Qt.DisplayRole: column_name = self.table_header[index.column()].name if self.extra_mode and column_name == "message": result = self.get_extra(record.message, record) else: result = getattr(record, column_name, None) elif role == Qt.SizeHintRole: if self.extra_mode and self.table_header[ index.column()].name == 'message': return QSize( 1, CONFIG.logger_row_height * (1 + len(self.get_fields_for_extra(record)))) else: return QSize(1, CONFIG.logger_row_height) elif role == Qt.DecorationRole: if self.table_header[index.column()].name == 'message': if record.exc_text: mode = CONFIG['exception_indication'] should = mode in (Exc_Indication.MSG_ICON, Exc_Indication.ICON_AND_RED_BG) if should: result = self.parent_widget.style().standardIcon( QStyle.SP_BrowserStop) elif role == Qt.FontRole: level = self.levels.get(record.levelname, NO_LEVEL) styles = level.styles if not self.dark_theme else level.stylesDark result = QFont(CONFIG.logger_table_font, CONFIG.logger_table_font_size) if styles: if 'bold' in styles: result.setBold(True) if 'italic' in styles: result.setItalic(True) if 'underline' in styles: result.setUnderline(True) elif role == Qt.ForegroundRole: level = self.levels.get(record.levelname, NO_LEVEL) if not self.dark_theme: result = level.fg else: result = level.fgDark elif role == Qt.BackgroundRole: if record.exc_text: mode = CONFIG['exception_indication'] should = mode in (Exc_Indication.RED_BG, Exc_Indication.ICON_AND_RED_BG) if should: if not self.dark_theme: color = QColor(255, 180, 180) else: color = Qt.darkRed result = QBrush(color, Qt.DiagCrossPattern) return result level = self.levels.get(record.levelname, NO_LEVEL) if not self.dark_theme: result = level.bg else: result = level.bgDark elif role == SearchRole: result = record.message return result