def convert_to_color(object, name, value): """ Converts a number into a QColor object. """ # Try the toolkit agnostic format. try: tup = eval(value) except: tup = value if isinstance(tup, tuple): if 3 <= len(tup) <= 4: try: color = QtGui.QColor(*tup) except TypeError: raise TraitError else: raise TraitError else: if isinstance(value, str): # Allow for spaces in the string value. value = value.replace(' ', '') # Let the standard ctors handle the value. try: color = QtGui.QColor(value) except TypeError: raise TraitError if not color.isValid(): raise TraitError return color
def as_qcolor(color): """ Convert a color specification (maybe a tuple) into a QColor. """ if isinstance(color, SequenceTypes): return QtGui.QColor(*color) else: return QtGui.QColor(color)
def _view_trait_error(self): # check if we're getting called on the local or remote process if self.info is None or self.info.ui is None: return for ed in self.info.ui._editors: if ed.name == self.context.view_error_trait: err_state = True else: err_state = False if not ed.label_control: continue item = ed.label_control if not err_state and not hasattr(item, '_ok_color'): continue pal = QtGui.QPalette(item.palette()) # @UndefinedVariable if err_state: setattr(item, '_ok_color', QtGui.QColor(pal.color(item.backgroundRole()))) # @UndefinedVariable pal.setColor(item.backgroundRole(), QtGui.QColor(255, 145, 145)) # @UndefinedVariable item.setAutoFillBackground(True) item.setPalette(pal) else: pal.setColor(item.backgroundRole(), item._ok_color) delattr(item, '_ok_color') item.setAutoFillBackground(False) item.setPalette(pal)
def data(self, mi, role): """Reimplemented to return the data.""" editor = self._editor adapter = editor.adapter index = mi.row() if role == QtCore.Qt.ItemDataRole.DisplayRole or role == QtCore.Qt.ItemDataRole.EditRole: if editor.is_auto_add(index): text = adapter.get_default_text(editor.object, editor.name) else: text = adapter.get_text(editor.object, editor.name, index) if role == QtCore.Qt.ItemDataRole.DisplayRole and text == "": # FIXME: This is a hack to make empty strings editable. text = " " return text elif role == QtCore.Qt.ItemDataRole.DecorationRole: if editor.is_auto_add(index): image = adapter.get_default_image(editor.object, editor.name) else: image = adapter.get_image(editor.object, editor.name, index) image = editor.get_image(image) if image is not None: return image elif role == QtCore.Qt.ItemDataRole.ToolTipRole: tooltip = adapter.get_tooltip(editor.object, editor.name, index) if tooltip: return tooltip elif role == QtCore.Qt.ItemDataRole.BackgroundRole: if editor.is_auto_add(index): color = adapter.get_default_bg_color(editor.object, editor.name) else: color = adapter.get_bg_color(editor.object, editor.name, index) if color is not None: if isinstance(color, SequenceTypes): q_color = QtGui.QColor(*color) else: q_color = QtGui.QColor(color) return QtGui.QBrush(q_color) elif role == QtCore.Qt.ItemDataRole.ForegroundRole: if editor.is_auto_add(index): color = adapter.get_default_text_color(editor.object, editor.name) else: color = adapter.get_text_color(editor.object, editor.name, index) if color is not None: if isinstance(color, SequenceTypes): q_color = QtGui.QColor(*color) else: q_color = QtGui.QColor(color) return QtGui.QBrush(q_color) return None
def data(self, mi, role=None): """ Reimplemented to return the data. """ if role is None: role = QtCore.Qt.DisplayRole editor = self._editor adapter = editor.adapter obj, name = editor.object, editor.name row, column = mi.row(), mi.column() if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole: return adapter.get_text(obj, name, row, column) elif role == QtCore.Qt.DecorationRole: image = editor._get_image(adapter.get_image(obj, name, row, column)) if image is not None: return image elif role == QtCore.Qt.ToolTipRole: tooltip = adapter.get_tooltip(obj, name, row, column) if tooltip: return tooltip elif role == QtCore.Qt.FontRole: font = adapter.get_font(obj, name, row, column) if font is not None: return QtGui.QFont(font) elif role == QtCore.Qt.TextAlignmentRole: string = adapter.get_alignment(obj, name, column) alignment = alignment_map.get(string, QtCore.Qt.AlignLeft) return int(alignment | QtCore.Qt.AlignVCenter) elif role == QtCore.Qt.BackgroundRole: color = adapter.get_bg_color(obj, name, row, column) if color is not None: if isinstance(color, SequenceTypes): q_color = QtGui.QColor(*color) else: q_color = QtGui.QColor(color) return QtGui.QBrush(q_color) elif role == QtCore.Qt.ForegroundRole: color = adapter.get_text_color(obj, name, row, column) if color is not None: if isinstance(color, SequenceTypes): q_color = QtGui.QColor(*color) else: q_color = QtGui.QColor(color) return QtGui.QBrush(q_color) return None
def to_qt4_color(self, editor): """ Gets the PyQt color equivalent of the object trait. """ try: color = getattr(editor.object, editor.name + '_') except AttributeError: color = getattr(editor.object, editor.name) if type(color) in SequenceTypes: c = QtGui.QColor() c.setRgbF(color[0], color[1], color[2], color[3]) else: c = QtGui.QColor(color) return c
def test_qcolor(self): obj = ObjectWithColor(color=QtGui.QColor(0, 128, 255, 64)) self.assertIsInstance(obj.color, QtGui.QColor) self.assertEqual(obj.color.getRgb(), (0, 128, 255, 64)) self.assertIsInstance(obj.color_, QtGui.QColor) self.assertEqual(obj.color_.getRgb(), (0, 128, 255, 64))
def set_error_state(self, state=None, control=None): """ Sets the editor's current error state. """ if state is None: state = self.invalid state = state or self.in_error_state() if control is None: control = self.get_error_control() if not isinstance(control, list): control = [control] for item in control: if item is None: continue pal = QtGui.QPalette(item.palette()) if state: color = ErrorColor if getattr(item, '_ok_color', None) is None: item._ok_color = QtGui.QColor( pal.color(QtGui.QPalette.Base)) else: color = getattr(item, '_ok_color', OKColor) pal.setColor(QtGui.QPalette.Base, color) item.setPalette(pal)
def _get_color(self, color): qcolor = QtGui.QColor() qcolor.setRgb( int(color[:2], base=16), int(color[2:4], base=16), int(color[4:6], base=16), ) return qcolor
def _create_contents(self, parent): panel = QtGui.QWidget(parent) palette = QtGui.QPalette(panel.palette()) palette.setColor(QtGui.QPalette.Window, QtGui.QColor("blue")) panel.setPalette(palette) panel.setAutoFillBackground(True) return panel
def __init__(self, parent, should_highlight_current_line=True, font=None, lexer=None): super(CodeWidget, self).__init__(parent) self.highlighter = PygmentsHighlighter(self.document(), lexer) self.line_number_widget = LineNumberWidget(self) self.status_widget = StatusGutterWidget(self) if font is None: # Set a decent fixed width font for this platform. font = QtGui.QFont() if sys.platform == 'win32': # Prefer Consolas, but fall back to Courier if necessary. font.setFamily('Consolas') if not font.exactMatch(): font.setFamily('Courier') elif sys.platform == 'darwin': font.setFamily('Monaco') else: font.setFamily('Monospace') font.setStyleHint(QtGui.QFont.TypeWriter) self.set_font(font) # Whether we should highlight the current line or not. self.should_highlight_current_line = should_highlight_current_line # What that highlight color should be. self.line_highlight_color = QtGui.QColor(QtCore.Qt.yellow).lighter(160) # Auto-indentation behavior self.auto_indent = True self.smart_backspace = True # Tab settings self.tabs_as_spaces = True self.tab_width = 4 self.indent_character = ':' self.comment_character = '#' # Set up gutter widget and current line highlighting self.blockCountChanged.connect(self.update_line_number_width) self.updateRequest.connect(self.update_line_numbers) self.cursorPositionChanged.connect(self.highlight_current_line) self.update_line_number_width() self.highlight_current_line() # Don't wrap text self.setLineWrapMode(QtGui.QPlainTextEdit.NoWrap) # Key bindings self.indent_key = QtGui.QKeySequence(QtCore.Qt.Key_Tab) self.unindent_key = QtGui.QKeySequence(QtCore.Qt.SHIFT + QtCore.Qt.Key_Backtab) self.comment_key = QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_Slash) self.backspace_key = QtGui.QKeySequence(QtCore.Qt.Key_Backspace)
def setTabTextColor(self, w, color=None): """ Set the tab text color on a particular widget w """ tw, tidx = self._tab_widget(w) if tw is not None: if color is None: # null color reverts to foreground role color color = QtGui.QColor() tw.tabBar().setTabTextColor(tidx, color)
def _create_dialog_area(self, parent): panel = QtGui.QWidget(parent) panel.setMinimumSize(QtCore.QSize(100, 200)) palette = panel.palette() palette.setColor(QtGui.QPalette.ColorRole.Window, QtGui.QColor("red")) panel.setPalette(palette) panel.setAutoFillBackground(True) return panel
def paintEvent(self, event): super(QFunctionControl, self).paintEvent(event) painter = QtGui.QPainter(self) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) painter.setBrush(brush) width, height = self.size().width(), self.size().height() painter.drawRect(0, 0, width, height) for channel in self.channels: channel.paint(painter)
def to_qt4_color(self, editor): """Gets the PyQt color equivalent of the object trait.""" try: color = getattr(editor.object, editor.name + "_") except AttributeError: color = getattr(editor.object, editor.name) c = QtGui.QColor() c.setRgbF(color[0], color[1], color[2]) return c
def _add_emphasis(self, control): """Adds emphasis to a specified control's font.""" # Set the foreground colour. pal = QtGui.QPalette(control.palette()) pal.setColor(QtGui.QPalette.ColorRole.WindowText, QtGui.QColor(0, 0, 127)) control.setPalette(pal) # Set the font. font = QtGui.QFont(control.font()) font.setBold(True) font.setPointSize(font.pointSize()) control.setFont(font)
def to_qt4_color(self, editor): if self.mapped: retval = getattr(editor.object, editor.name + "_") else: retval = getattr(editor.object, editor.name) if isinstance(retval, tuple): col = QtGui.QColor() col.setRgbF(*retval) retval = col return retval
def _create_page_content(self, parent): """ Creates the actual page content. """ # Dummy implementation - override! control = QtGui.QWidget(parent) palette = control.palette() palette.setColor(QtGui.QPalette.Window, QtGui.QColor('yellow')) control.setPalette(palette) control.setAutoFillBackground(True) return control
def recalculateCubes(self): # delete cubes for I in list(self.tdense_cubes.keys()): self.tableStates.setItem(I, self.tableStates.columnCount() - 1, QtGui.QTableWidgetItem("")) self.tableStates.item(I, self.tableStates.columnCount() - 1).setBackground(QtGui.QColor(255, 255, 255)) self.tdense_cubes = {} self.difdense_cubes = {} self.calculateCubes()
def _op_trait_error(self, event): # check if we're getting called from the local or remote process # if self.info is None or self.info.ui is None: # return for ed in self.info.ui._editors: if ed.name == self.context.op_error_trait: err_state = True else: err_state = False if not ed.label_control: continue item = ed.label_control if not err_state and not hasattr(item, '_ok_color'): continue pal = QtGui.QPalette(item.palette()) # @UndefinedVariable if err_state: # TODO - this worked in Qt4 but not in Qt5. at least on linux, # the color isn't changing. i wonder if it has to do with the # fixed theme engine we're using... setattr(item, '_ok_color', QtGui.QColor(pal.color( item.backgroundRole()))) # @UndefinedVariable pal.setColor(item.backgroundRole(), QtGui.QColor(255, 145, 145)) # @UndefinedVariable item.setAutoFillBackground(True) item.setPalette(pal) item.repaint() else: pal.setColor(item.backgroundRole(), item._ok_color) delattr(item, '_ok_color') item.setAutoFillBackground(False) item.setPalette(pal) item.repaint()
def recalculateCubes(self): # delete cubes for i in list(self.mo_cubes.keys()): self.tableMOs.setItem(i, self.tableMOs.columnCount() - 1, QtGui.QTableWidgetItem("")) self.tableMOs.item(i, self.tableMOs.columnCount() - 1).setBackground( QtGui.QColor(255, 255, 255)) self.mo_cubes = {} delattr(Cube.orbital_amplitude, "cached_grid") # cached grid has wrong resolution self.calculateCubes()
def _color_to_brush(color): """ Returns a QBrush with the color specified in **color** """ brush = QtGui.QBrush() if isinstance(color, str) and hasattr(QtCore.Qt, color): col = getattr(QtCore.Qt, color) elif isinstance(color, tuple): col = QtGui.QColor() col.setRgb(*color[:4]) else: raise RuntimeError("Invalid color specification '%r'" % color) brush.setColor(col) return brush
def _qt4_create_control(self, parent, color): """ Create a Qt4 version of the control. """ from pyface.qt import QtGui widget = QtGui.QWidget(parent) palette = widget.palette() palette.setColor(QtGui.QPalette.ColorRole.Window, QtGui.QColor(color)) widget.setPalette(palette) widget.setAutoFillBackground(True) return widget
def create_control(self, parent): """ Create the toolkit-specific control that represents the part. """ from pyface.qt import QtGui control = QtGui.QWidget(parent) palette = control.palette() palette.setColor(QtGui.QPalette.Window, QtGui.QColor("red")) control.setPalette(palette) control.setAutoFillBackground(True) return control
def __init__(self, text_edit): """ Create a call tip manager that is attached to the specified Qt text edit widget. """ assert isinstance(text_edit, (QtGui.QTextEdit, QtGui.QPlainTextEdit)) super(BracketMatcher, self).__init__() # The format to apply to matching brackets. self.format = QtGui.QTextCharFormat() self.format.setBackground(QtGui.QColor("silver")) self._text_edit = text_edit text_edit.cursorPositionChanged.connect(self._cursor_position_changed)
def paintEvent(self, event): """Paint handler.""" super(QGradientControl, self).paintEvent(event) painter = QtGui.QPainter(self) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) painter.setBrush(brush) painter.setBackgroundMode(QtCore.Qt.OpaqueMode) sz = self.size() width, height = sz.width(), sz.height() xform = self.gradient_table.scaling_function start_y = 0 end_y = height if xform: # if a scaling transformation is provided, paint the original # gradient under the scaled gradient. start_y = height / 2 # paint the original gradient as it stands in the table. color = QtGui.QColor() for x in range(width): (r, g, b, a) = self.gradient_table.get_pos_rgba_color_lerped( float(x) / (width - 1)) color.setRgb(int(255 * r), int(255 * g), int(255 * b)) painter.setPen(color) brush.setColor(color) painter.drawLine(x, start_y, x, end_y) if xform: # paint the scaled gradient below end_y = start_y start_y = 0 for x in range(width): f = float(x) / (width - 1) (r, g, b, a) = self.gradient_table.get_pos_rgba_color_lerped(xform(f)) color.set(int(255 * r), int(255 * g), int(255 * b)) brush.setColor(color) painter.drawLine(x, start_y, x, end_y)
def _qt4_show_message(self, control): """ Set the message text for a splash screen control. """ if self.text_font is not None: control.setFont(self.text_font) if self.text_color is None: text_color = QtCore.Qt.black else: # Until we get the type of this trait finalised (ie. when TraitsUI # supports PyQt) convert it explcitly to a colour. text_color = QtGui.QColor(self.text_color) control.showMessage(self.text, QtCore.Qt.AlignLeft, text_color)
def convert_to_color(object, name, value): """Converts a number into a QColor object.""" # Try the toolkit agnostic format. try: tup = literal_eval(value) except Exception: tup = value if isinstance(value, str): # Allow for spaces in the string value. value = value.replace(" ", "") # is it in the color table? if value in color_table: tup = channels_to_ints(color_table[value]) if isinstance(tup, tuple): if 3 <= len(tup) <= 4 and all(isinstance(x, int) for x in tup): try: color = QtGui.QColor(*tup) except Exception: raise TraitError else: raise TraitError elif isinstance(value, PyfaceColor): color = value.to_toolkit() else: # Let the standard ctors handle the value. try: color = QtGui.QColor(value) except TypeError: raise TraitError if not color.isValid(): raise TraitError return color
def active_icon(self): """ Return the QIcon to be used to indicate an active tab page. """ if _TabWidget._active_icon is None: # The gradient start and stop colours. start = QtGui.QColor(0, 255, 0) stop = QtGui.QColor(0, 63, 0) size = self.iconSize() width = size.width() height = size.height() pm = QtGui.QPixmap(size) p = QtGui.QPainter() p.begin(pm) # Fill the image background from the tab background. p.initFrom(self.tabBar()) p.fillRect(0, 0, width, height, p.background()) # Create the colour gradient. rg = QtGui.QRadialGradient(width / 2, height / 2, width) rg.setColorAt(0.0, start) rg.setColorAt(1.0, stop) # Draw the circle. p.setBrush(rg) p.setPen(QtCore.Qt.NoPen) p.setRenderHint(QtGui.QPainter.Antialiasing) p.drawEllipse(0, 0, width, height) p.end() _TabWidget._active_icon = QtGui.QIcon(pm) return _TabWidget._active_icon
def __init__(self, parent, commands=None, font=None): QtGui.QWidget.__init__(self, parent) self.setAcceptDrops(True) self.commands = commands self.code = myCodeWidget(self, font=font) #set lexer manually instead of by name lexer = PyScriptLexer(commands) self.code.highlighter._lexer = lexer self.code.setMouseTracking(True) #AdvanceCodeWidget # ===================================== self.find = FindWidget(self) self.find.hide() self.replace = ReplaceWidget(self) self.replace.hide() self.replace.replace_button.setEnabled(False) self.replace.replace_all_button.setEnabled(False) self.active_find_widget = None self.previous_find_widget = None self.code.selectionChanged.connect(self._update_replace_enabled) self.find.line_edit.returnPressed.connect(self.find_next) self.find.next_button.clicked.connect(self.find_next) self.find.prev_button.clicked.connect(self.find_prev) self.replace.line_edit.returnPressed.connect(self.find_next) self.replace.line_edit.textChanged.connect( self._update_replace_all_enabled) self.replace.next_button.clicked.connect(self.find_next) self.replace.prev_button.clicked.connect(self.find_prev) self.replace.replace_button.clicked.connect(self.replace_next) self.replace.replace_all_button.clicked.connect(self.replace_all) layout = QtGui.QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(0) layout.addWidget(self.code) layout.addWidget(self.find) layout.addWidget(self.replace) self.setLayout(layout) self.edit_color = QtGui.QColor('blue').lighter(175)