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)) 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 set_light_background(self, state): self.light_background = state if state: self.set_palette(background=QColor(Qt.white), foreground=QColor(Qt.darkGray)) else: self.set_palette(background=QColor(Qt.black), foreground=QColor(Qt.lightGray)) self.ansi_handler.set_light_background(state) self.set_pythonshell_font()
def create_scedit(self, text, option, default=NoDefault, tip=None, without_layout=False): label = QLabel(text) clayout = ColorLayout(QColor(Qt.black), self) clayout.lineedit.setMaximumWidth(80) if tip is not None: clayout.setToolTip(tip) cb_bold = QCheckBox() cb_bold.setIcon(ima.icon('bold')) cb_bold.setToolTip(_("Bold")) cb_italic = QCheckBox() cb_italic.setIcon(ima.icon('italic')) cb_italic.setToolTip(_("Italic")) self.scedits[(clayout, cb_bold, cb_italic)] = (option, default) if without_layout: return label, clayout, cb_bold, cb_italic layout = QHBoxLayout() layout.addWidget(label) layout.addLayout(clayout) layout.addSpacing(10) layout.addWidget(cb_bold) layout.addWidget(cb_italic) layout.addStretch(1) layout.setContentsMargins(0, 0, 0, 0) widget = QWidget(self) widget.setLayout(layout) return widget
def apply_style(self, font, light_background, is_default): self.format = QTextCharFormat() self.format.setFont(font) foreground = QColor(self.foregroundcolor) if not light_background and is_default: inverse_color(foreground) self.format.setForeground(foreground) background = QColor(self.backgroundcolor) if not light_background: inverse_color(background) self.format.setBackground(background) font = self.format.font() font.setBold(self.bold) font.setItalic(self.italic) font.setUnderline(self.underline) self.format.setFont(font)
def __init__(self, parent=None): QPlainTextEdit.__init__(self, parent) BaseEditMixin.__init__(self) self.setAttribute(Qt.WA_DeleteOnClose) self.extra_selections_dict = {} self.connect(self, SIGNAL('textChanged()'), self.changed) self.connect(self, SIGNAL('cursorPositionChanged()'), self.cursor_position_changed) self.indent_chars = " " * 4 # Code completion / calltips if parent is not None: mainwin = parent while not isinstance(mainwin, QMainWindow): mainwin = mainwin.parent() if mainwin is None: break if mainwin is not None: parent = mainwin self.completion_widget = CompletionWidget(self, parent) self.codecompletion_auto = False self.codecompletion_case = True self.codecompletion_enter = False self.completion_text = "" self.calltip_widget = CallTipWidget(self, hide_timer_on=True) self.calltips = True self.calltip_position = None self.has_cell_separators = False self.highlight_current_cell_enabled = False # The color values may be overridden by the syntax highlighter # Highlight current line color self.currentline_color = QColor(Qt.red).lighter(190) self.currentcell_color = QColor(Qt.red).lighter(194) # Brace matching self.bracepos = None self.matched_p_color = QColor(Qt.green) self.unmatched_p_color = QColor(Qt.red)
def set_style(self): """ Set font style with the following attributes: 'foreground_color', 'background_color', 'italic', 'bold' and 'underline' """ if self.current_format is None: assert self.base_format is not None self.current_format = QTextCharFormat(self.base_format) # Foreground color if self.foreground_color is None: qcolor = self.base_format.foreground() else: cstr = self.ANSI_COLORS[self.foreground_color - 30][self.intensity] qcolor = QColor(cstr) self.current_format.setForeground(qcolor) # Background color if self.background_color is None: qcolor = self.base_format.background() else: cstr = self.ANSI_COLORS[self.background_color - 40][self.intensity] qcolor = QColor(cstr) self.current_format.setBackground(qcolor) font = self.current_format.font() # Italic if self.italic is None: italic = self.base_format.fontItalic() else: italic = self.italic font.setItalic(italic) # Bold if self.bold is None: bold = self.base_format.font().bold() else: bold = self.bold font.setBold(bold) # Underline if self.underline is None: underline = self.base_format.font().underline() else: underline = self.underline font.setUnderline(underline) self.current_format.setFont(font)
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 create_coloredit(self, text, option, default=NoDefault, tip=None, without_layout=False): label = QLabel(text) clayout = ColorLayout(QColor(Qt.black), self) clayout.lineedit.setMaximumWidth(80) if tip is not None: clayout.setToolTip(tip) self.coloredits[clayout] = (option, default) if without_layout: return label, clayout layout = QHBoxLayout() layout.addWidget(label) layout.addLayout(clayout) layout.addStretch(1) layout.setContentsMargins(0, 0, 0, 0) widget = QWidget(self) widget.setLayout(layout) return widget
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 spyderlib.dependencies import Dependency status = dep.get_status() if status == Dependency.NOK: color = QColor(Qt.red) color.setAlphaF(.25) return to_qvariant(color)
def _paint_icon(self, iconic, painter, rect, mode, state, options): """Paint a single icon""" painter.save() color, char = options['color'], options['char'] if mode == QIcon.Disabled: color = options.get('color_disabled', color) char = options.get('disabled', char) elif mode == QIcon.Active: color = options.get('color_active', color) char = options.get('active', char) elif mode == QIcon.Selected: color = options.get('color_selected', color) char = options.get('selected', char) painter.setPen(QColor(color)) # A 16 pixel-high icon yields a font size of 14, which is pixel perfect # for font-awesome. 16 * 0.875 = 14 # The reason for not using full-sized glyphs is the negative bearing of # fonts. draw_size = 0.875 * qRound(rect.height() * options['scale_factor']) prefix = options['prefix'] # Animation setup hook animation = options.get('animation') if animation is not None: animation.setup(self, painter, rect) painter.setFont(iconic.font(prefix, draw_size)) if 'offset' in options: rect = QRect(rect) rect.translate(options['offset'][0] * rect.width(), options['offset'][1] * rect.height()) painter.setOpacity(options.get('opacity', 1.0)) painter.drawText(rect, Qt.AlignCenter | Qt.AlignVCenter, char) painter.restore()
"""Classes handling iconic fonts""" from __future__ import print_function from spyderlib.qt.QtCore import Qt, QObject, QPoint, QRect, qRound, QByteArray from spyderlib.qt.QtGui import (QIcon, QColor, QIconEngine, QPainter, QPixmap, QFontDatabase, QFont) import json import os from six import unichr _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 all icons""" valid_options = ['active', 'animation', 'color', 'color_active', 'color_disabled', 'color_selected', 'disabled', 'offset', 'scale_factor', 'selected'] for kw in kwargs: if kw in valid_options: _default_options[kw] = kwargs[kw] else: error = "Invalid option '{0}'".format(kw) raise KeyError(error)
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) (primcalls, total_calls, loc_time, cum_time, callers) = self.stats[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, get_icon(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 __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 setup(self): for label, value in self.data: if DEBUG_FORMLAYOUT: print("value:", value) if label is None and value is None: # Separator: (None, None) self.formlayout.addRow(QLabel(" "), QLabel(" ")) self.widgets.append(None) continue elif label is None: # Comment self.formlayout.addRow(QLabel(value)) self.widgets.append(None) continue elif tuple_to_qfont(value) is not None: field = FontLayout(value, self) elif text_to_qcolor(value).isValid(): field = ColorLayout(QColor(value), self) elif is_text_string(value): if '\n' in value: for linesep in (os.linesep, '\n'): if linesep in value: value = value.replace(linesep, u("\u2029")) field = QTextEdit(value, self) else: field = QLineEdit(value, self) elif isinstance(value, (list, tuple)): value = list(value) # in case this is a tuple selindex = value.pop(0) field = QComboBox(self) if isinstance(value[0], (list, tuple)): keys = [ key for key, _val in value ] value = [ val for _key, val in value ] else: keys = value field.addItems(value) if selindex in value: selindex = value.index(selindex) elif selindex in keys: selindex = keys.index(selindex) elif not isinstance(selindex, int): print("Warning: '%s' index is invalid (label: "\ "%s, value: %s)" % (selindex, label, value), file=STDERR) selindex = 0 field.setCurrentIndex(selindex) elif isinstance(value, bool): field = QCheckBox(self) field.setCheckState(Qt.Checked if value else Qt.Unchecked) elif isinstance(value, float): field = QLineEdit(repr(value), self) field.setValidator(QDoubleValidator(field)) dialog = self.get_dialog() dialog.register_float_field(field) field.textChanged.connect(lambda text: dialog.update_buttons()) elif isinstance(value, int): field = QSpinBox(self) field.setRange(-1e9, 1e9) field.setValue(value) elif isinstance(value, datetime.datetime): field = QDateTimeEdit(self) field.setDateTime(value) elif isinstance(value, datetime.date): field = QDateEdit(self) field.setDate(value) else: field = QLineEdit(repr(value), self) self.formlayout.addRow(label, field) self.widgets.append(field)
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.iteritems(): # 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).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)