def updateColor(self): """ Update the color on the sampleModel modify to fit to the actual view """ if not self.view.sampleTableView.selectedIndexes():#not self.acTree.selectedIndexes(): return idx = self.view.sampleTableView.selectedIndexes()[0] sample = self.model.sample(idx.data().toString(), fullNameEntry=False) if sample is None: self.view.showErrorMessage('Error', 'Please choose only one file...') return color = QColorDialog.getColor() if not color.isValid(): return sample.color=color.getRgbF()[:-1] #make the gradient color here to color =QColor.fromRgbF(*(sample.color+(1.,))) colorr=QColor.fromRgbF(*(sample.color+(.5,))) gradient=QLinearGradient(-100, -100, 100, 100) gradient.setColorAt(0.7, colorr) gradient.setColorAt(1, color) #for m in (self.view.sampleModel, self.view.spectraModel, self.view.peakModel, # self.view.clusterModel):#self.view.chromaModel, for i in xrange(self.view.sampleModel.rowCount()): item=self.view.sampleModel.item(i,0) if item.text()== sample.shortName(): item.setBackground(QBrush(gradient))
def draw_color_bar(self, painter, rect): h1, s1, v1, _ = self.light.getHsv() h2, s2, v2, _ = self.dark.getHsv() painter.save() painter.setClipRect(rect) painter.setClipping(True) # painter.fillRect(rect, QBrush(self.dark)) if self.orientation == Qt.Horizontal: num_intervalls = rect.width() else: num_intervalls = rect.height() section = QRect() num_intervalls_shown = num_intervalls * self.height / 100 l = range(num_intervalls - num_intervalls_shown, num_intervalls) l.reverse() for i in l: if self.orientation == Qt.Horizontal: section.setRect(rect.x() + i, rect.y(), 1, rect.heigh()) else: section.setRect(rect.x(), rect.y() + i, rect.width(), 1) ratio = float(i) / float(num_intervalls) color = QColor() color.setHsv( h1 + int(ratio * (h2 - h1) + 0.5), s1 + int(ratio * (s2 - s1) + 0.5), v1 + int(ratio * (v2 - v1) + 0.5) ) painter.fillRect(section, color) painter.restore()
def __qcolor(color): """Returns qcolor for a given ARGB color """ c = QColor(color) if color > 0xFFFFFF: c.setAlpha((color >> 24) & 0xFF) return c
class ColorBar(QWidget): def __init__(self, orientation, *args): QWidget.__init__(self, *args) self.orientation = orientation self.light = QColor(Qt.gray) self.dark = QColor(Qt.black) self.height = 100 def paintEvent(self, _): painter = QPainter(self) self.draw_color_bar(painter, self.rect()) def grey(self): self.light = QColor(Qt.gray) self.dark = QColor(Qt.black) self.update() def color(self): self.light = QColor(Qt.red) self.dark = QColor(Qt.green) self.update() def set_height(self, height): self.height = height self.update() def draw_color_bar(self, painter, rect): h1, s1, v1, _ = self.light.getHsv() h2, s2, v2, _ = self.dark.getHsv() painter.save() painter.setClipRect(rect) painter.setClipping(True) # painter.fillRect(rect, QBrush(self.dark)) if self.orientation == Qt.Horizontal: num_intervalls = rect.width() else: num_intervalls = rect.height() section = QRect() num_intervalls_shown = num_intervalls * self.height / 100 l = range(num_intervalls - num_intervalls_shown, num_intervalls) l.reverse() for i in l: if self.orientation == Qt.Horizontal: section.setRect(rect.x() + i, rect.y(), 1, rect.heigh()) else: section.setRect(rect.x(), rect.y() + i, rect.width(), 1) ratio = float(i) / float(num_intervalls) color = QColor() color.setHsv( h1 + int(ratio * (h2 - h1) + 0.5), s1 + int(ratio * (s2 - s1) + 0.5), v1 + int(ratio * (v2 - v1) + 0.5) ) painter.fillRect(section, color) painter.restore()
def __init__(self, i, mu1, mu2, sigma1, sigma2, phi, color): OWPlotItem.__init__(self) self.outer_box = QGraphicsPolygonItem(self) self.inner_box = QGraphicsPolygonItem(self) self.i = i self.mu1 = mu1 self.mu2 = mu2 self.sigma1 = sigma1 self.sigma2 = sigma2 self.phi = phi self.twosigmapolygon = QPolygonF([ QPointF(i, mu1 - sigma1), QPointF(i, mu1 + sigma1), QPointF(i + 1, mu2 + sigma2), QPointF(i + 1, mu2 - sigma2), QPointF(i, mu1 - sigma1) ]) self.sigmapolygon = QPolygonF([ QPointF(i, mu1 - .5 * sigma1), QPointF(i, mu1 + .5 * sigma1), QPointF(i + 1, mu2 + .5 * sigma2), QPointF(i + 1, mu2 - .5 * sigma2), QPointF(i, mu1 - .5 * sigma1) ]) if isinstance(color, tuple): color = QColor(*color) color.setAlphaF(.3) self.outer_box.setBrush(color) self.outer_box.setPen(QColor(0, 0, 0, 0)) self.inner_box.setBrush(color) self.inner_box.setPen(color)
def __updatePen(self): self.prepareGeometryChange() self.__boundingRect = None if self.__dynamic: if self.__dynamicEnabled: color = QColor(0, 150, 0, 150) else: color = QColor(150, 0, 0, 150) normal = QPen(QBrush(color), 2.0) hover = QPen(QBrush(color.darker(120)), 2.1) else: normal = QPen(QBrush(QColor("#9CACB4")), 2.0) hover = QPen(QBrush(QColor("#7D7D7D")), 2.1) if self.__state & LinkItem.Active: pen_style = Qt.SolidLine else: pen_style = Qt.DashLine normal.setStyle(pen_style) hover.setStyle(pen_style) if self.hover: pen = hover else: pen = normal self.curveItem.setPen(pen)
def update_visible_area(self): block = self._parent.firstVisibleBlock() first_line = block.blockNumber() max_count = self.blockCount() parent_cursor = self._parent.textCursor() parent_cursor.setPosition(block.position()) self.setTextCursor(parent_cursor) lines_count = self.max_line if (first_line + self.max_line) > max_count: lines_count = max_count - first_line extraSelections = [] for i in xrange(lines_count): selection = QTextEdit.ExtraSelection() lineColor = QColor(resources.CUSTOM_SCHEME.get('current-line', resources.COLOR_SCHEME['current-line'])) lineColor.setAlpha(100) selection.format.setBackground(lineColor) selection.format.setProperty(QTextFormat.FullWidthSelection, True) cursor = self.textCursor() cursor.setPosition(block.position()) selection.cursor = cursor selection.cursor.clearSelection() extraSelections.append(selection) block = block.next() self.setExtraSelections(extraSelections)
def make_color_legend(self): color_index = self.get_color_index() if color_index == -1: return color_var = self.data_domain[color_index] use_shape = self.get_shape_index() == color_index if color_var.is_discrete: if not self.legend: self.create_legend() palette = self.discrete_palette for i, value in enumerate(color_var.values): color = QColor(*palette.getRGB(i)) brush = color.lighter(self.DarkerValue) self.legend.addItem( ScatterPlotItem( pen=color, brush=brush, size=10, symbol=self.CurveSymbols[i] if use_shape else "o"), escape(value)) else: legend = self.color_legend = LegendItem() legend.setParentItem(self.plot_widget.getViewBox()) legend.restoreAnchor(self.__color_legend_anchor) label = PaletteItemSample(self.continuous_palette, self.scale) legend.addItem(label, "") legend.setGeometry(label.boundingRect())
def _getColorForProgress(self,progress): """calculate which color to use to represent a given progress""" red = QColor(Qt.red) hue, sat, val, alpha = red.getHsv() # progress : 100 = x : 120 color = QColor.fromHsv(hue + int(progress * 6 / 5), sat, val) return color
def addNewLabel(self): """ Add a new label to the label list GUI control. Return the new number of labels in the control. """ numLabels = len(self._labelControlUi.labelListModel) if numLabels >= len(self._colorTable16)-1: # If the color table isn't large enough to handle all our labels, # append a random color randomColor = QColor(numpy.random.randint(0,255), numpy.random.randint(0,255), numpy.random.randint(0,255)) self._colorTable16.append( randomColor.rgba() ) color = QColor() color.setRgba(self._colorTable16[numLabels+1]) # First entry is transparent (for zero label) label = Label(self.getNextLabelName(), color) label.nameChanged.connect(self._updateLabelShortcuts) self._labelControlUi.labelListModel.insertRow( self._labelControlUi.labelListModel.rowCount(), label ) nlabels = self._labelControlUi.labelListModel.rowCount() # Make the new label selected selectedRow = nlabels-1 self._labelControlUi.labelListModel.select(selectedRow) self._updateLabelShortcuts()
def highlight_selected_word(self): #Highlight selected variable if not self.isReadOnly() and not self.textCursor().hasSelection(): word = self._text_under_cursor() if self._patIsWord.match(word): lineColor = QColor( resources.CUSTOM_SCHEME.get('selected-word', resources.COLOR_SCHEME['selected-word'])) lineColor.setAlpha(100) block = self.document().findBlock(0) cursor = self.document().find(word, block.position(), QTextDocument.FindCaseSensitively or \ QTextDocument.FindWholeWords) while block.isValid() and \ block.blockNumber() <= self._sidebarWidget.highest_line \ and cursor.position() != -1: selection = QTextEdit.ExtraSelection() selection.format.setBackground(lineColor) selection.cursor = cursor self.extraSelections.append(selection) cursor = self.document().find(word, cursor.position(), QTextDocument.FindCaseSensitively or \ QTextDocument.FindWholeWords) block = block.next() self.setExtraSelections(self.extraSelections)
def paintEvent(self, event): if not self.displayedWhenStopped and not self.isAnimated(): return width = min(self.width(), self.height()) p = QPainter(self) p.setRenderHint(QPainter.Antialiasing) outerRadius = (width-1) * 0.5 innerRadius = (width-1) * 0.5 * 0.38 capsuleHeight = outerRadius - innerRadius capsuleWidth = capsuleHeight * 0.23 if width > 32 else capsuleHeight * 0.35 capsuleRadius = capsuleWidth / 2 for i in range(12): color = QColor(self.color) color.setAlphaF(float(1.0 - float(i / 12.0))) p.setPen(Qt.NoPen) p.setBrush(color) p.save() p.translate(self.rect().center()) p.rotate(self.angle - float(i * 30.0)) p.drawRoundedRect(-capsuleWidth * 0.5,\ -(innerRadius + capsuleHeight),\ capsuleWidth,\ capsuleHeight,\ capsuleRadius,\ capsuleRadius) p.restore()
def _collect_colors(document): '''Scan a given document and collect unique colors Returns a list of QColor objects. ''' result = [] # Iterate over document's lines trying to find #colors for l in range(0, document.lines()): line = document.line(l) # Get the current line start = 0 # Set initial position to 0 (line start) while start < len(line): # Repeat 'till the line end start = line.find('#', start) # Try to find a '#' character (start of #color) if start == -1: # Did we found smth? break # No! Nothing to do... # Try to get a word right after the '#' char end = start + 1 for c in line[end:]: if not (c in string.hexdigits or c in string.ascii_letters): break end += 1 color_range = KTextEditor.Range(l, start, l, end) color_str = document.text(color_range) color = QColor(color_str) if color.isValid() and color not in result: result.append(color) kate.kDebug('ColorUtils: scan for #colors found {}'.format(color_str)) start = end return result
def setData(self, index, value, role=Qt.EditRole): if role == Qt.EditRole and index.column() == self.ColumnID.Color: row = index.row() color = QColor(value["color"][0]) colorglobal=value["color"][1] fontsize,fontsizeglobal = value["fontsize"] linewidth,linewidthglobal = value["linewidth"] fontcolor = QColor(value["fontcolor"][0]) fontcolorglobal = value["fontcolor"][1] if color.isValid(): if not colorglobal: self._elements[row].color=color self.dataChanged.emit(index, index) else: for row,el in enumerate(self._elements): el.color=color ind=self.createIndex(row, self.ColumnID.Color, object=0) self.dataChanged.emit(ind, ind) if fontcolor.isValid(): if not fontcolorglobal: self._elements[row].fontcolor=fontcolor else: for row,el in enumerate(self._elements): el.fontcolor=fontcolor if not linewidthglobal: self._elements[row].linewidth=linewidth else: for row,el in enumerate(self._elements): el.linewidth=linewidth if not fontsizeglobal: self._elements[row].fontsize=fontsize else: for row,el in enumerate(self._elements): el.fontsize=fontsize return True if index.column()==self.ColumnID.Fix: try: value=float(value.toString()) self._elements[index.row()].isFixed=True row=index.row() self._elements[row].fixvalue=QString("%.1f"%value) self.dataChanged.emit(index,index) return True except: return False
def onContentsChange(self, a, b, c): #print(a, b, c) try: tokens = self.tokenizer.tokenize(self.toPlainText()) except tokenize.TokenError: return for tok in tokens: if tok.type == python_tokens['NAME']: for words, weight, color in TOKEN_CLASSES: if tok.string in words: cursor = self.select_token(tok) fmt = cursor.charFormat() fmt.setFontWeight(weight) fmt.setForeground(color) cursor.setCharFormat(fmt) elif tok.type == python_tokens['COMMENT']: cursor = self.select_token(tok) fmt = cursor.charFormat() fmt.setForeground(QColor.fromRgbF(0.0, 0.0, 0.9)) cursor.setCharFormat(fmt) elif tok.type == python_tokens['STRING']: cursor = self.select_token(tok) fmt = cursor.charFormat() fmt.setForeground(QColor.fromRgbF(0.0, 0.0, 0.9)) cursor.setCharFormat(fmt) elif tok.type in IGNORE_TOKENS: pass else: pass
def paintEvent(self, e): Part.paintEvent(self, e) painter = QPainter(self) color = QColor(self._base) color.setAlpha(200) painter.setPen(color.dark(150)) painter.setBrush(color.dark(115)) painter.setRenderHint(QPainter.Antialiasing) painter.drawEllipse(11, 22, 10, 10) rect = QRectF(25, 17, 7, 20) painter.drawChord(rect, 270 * 16, 180 * 16) rect = QRectF(40, 11, 10, 30) painter.drawChord(rect, 270 * 16, 180 * 16) painter.drawEllipse(63, 14, 5, 5) painter.drawEllipse(63, 35, 5, 5) painter.drawEllipse(81, 14, 5, 5) painter.drawEllipse(81, 35, 5, 5) painter = None if self.data is None: text = None else: text = self.data.name self.drawText(text)
def paintEvent(self, e): painter = QPainter(self) brush = QBrush(painter.brush()) self.bgcolor.setAlpha(20) painter.setBrush(self.bgcolor) painter.drawRect(0, 0, self.width(), self.height()) self.bgcolor.setAlpha(15) painter.setBrush(self.bgcolor) painter.drawRect(0, 20, self.width(), self.height()-40) painter.setBrush(brush) frame = self.clock.last_beat_frame x = self.x_for_frametime(frame) while x < self.width(): x = self.x_for_frametime(frame) painter.drawLine(x, 0, x, 15) painter.drawLine(x, self.height(), x, self.height() - 15) #painter.drawText(QPoint(x+5, 13), str(frame)) frame += self.clock.frames_per_beat() self.items = [i for i in self.items if i.endtime > self.frametime] for item in self.items: x = self.x_for_frametime(item.starttime) w = self.x_for_frametime(item.endtime) - x color = QColor(item.color) color.setAlpha(150) painter.setPen(color) pen = painter.pen() pen.setWidth(3) painter.setPen(pen) color.setAlpha(100) painter.setBrush(color) painter.drawRect(x, 0, w, self.height())
def makeBrush( **option ): brush = QtGui.QBrush() brush.setStyle( option.get( 'style', Qt.SolidPattern ) ) color = QColor( option.get( 'color', '#ffffff' ) ) color.setAlphaF( option.get( 'alpha', 1 ) ) brush.setColor( color ) return brush
def canvasMoveEvent(self, e): super(ArkMapToolInteractive, self).canvasMoveEvent(e) if not self._active: return e.ignore() if (self._panningEnabled and e.buttons() & Qt.LeftButton): # Pan map mode if not self._dragging: self._dragging = True self.setCursor(QCursor(Qt.ClosedHandCursor)) self.canvas().panAction(e) e.accept() elif (self._zoomingEnabled and e.buttons() & Qt.RightButton): # Zoom map mode if not self._dragging: self._dragging = True self.setCursor(QCursor(Qt.ClosedHandCursor)) self._zoomRubberBand = QgsRubberBand(self.canvas(), QGis.Polygon) color = QColor(Qt.blue) color.setAlpha(63) self._zoomRubberBand.setColor(color) self._zoomRect = QRect(0, 0, 0, 0) self._zoomRect.setTopLeft(e.pos()) self._zoomRect.setBottomRight(e.pos()) if self._zoomRubberBand is not None: self._zoomRubberBand.setToCanvasRectangle(self._zoomRect) self._zoomRubberBand.show() e.accept() elif self._snappingEnabled: mapPoint, snapped = self._snapCursorPoint(e.pos()) if (snapped): self._createSnappingMarker(mapPoint) else: self._deleteSnappingMarker()
def __init__(self, message, str = None): cfg = Config('messages', message) if (str is None): self.str = cfg.get('message') else: self.str = str self.duration = cfg.get('duration') self.fade_duration = cfg.get('fade_duration') self.color = QColor.fromRgb(*cfg.get('color')) self.alpha_final = self.color.alpha() self.color.setAlpha(0) self.font = FontManager.getFont(cfg.get('font')) self.font.setPointSize(cfg.get('font_size')) self.font_color = QColor.fromRgb(*cfg.get('font_color')) self.font_alpha_final = self.font_color.alpha() self.font_color.setAlpha(0) self.elapsed = 0.0 self.state = 0 self.tick_funcs = [self.tick_fade_in, self.tick_message, self.tick_fade_out]
def getWidget(self): val = getattr(self.edw, self.attr) max = getattr(self.edw, self.attr_max) min = getattr(self.edw, self.attr_min) if isinstance(val, int) and isinstance(max, int) and isinstance(min, int) and min >= 0: col_min = QColor(self.col_min) col_max = QColor(self.col_max) if min != max: r_min, g_min, b_min, a_min = col_min.getRgb() r_max, g_max, b_max, a_max = col_max.getRgb() c_r = ((val - min) * (r_max - r_min) / (max - min)) + r_min c_g = ((val - min) * (g_max - g_min) / (max - min)) + g_min c_b = ((val - min) * (b_max - b_min) / (max - min)) + b_min # If the min / max values has not yet been refreshed, then we could get weird colors if c_r < 0: c_r = 0 if c_g < 0: c_g = 0 if c_b < 0: c_b = 0 if c_r > 255: c_r = 255 if c_g > 255: c_g = 255 if c_b > 255: c_b = 255 color = "#%02x%02x%02x" % (c_r, c_g, c_b) else: color = col_min return EdwProgressBarCell(val, max, color, self.format) return EdwBlankCell()
def paintEvent( self, event ): painter = QtGui.QPainter( self ) painter.setPen( Qt.NoPen ) w = self.width() h = self.height() painter.setBrush( self.originalColor ) painter.drawRect( 0, 0, w, h/2 ) cSolid = QColor( self.previewColor ) cSolid.setAlphaF( 1 ) #left 1/2 for solid color painter.setBrush( cSolid ) painter.drawRect( 0, h/2, w/2, h/2 + 1 ) #draw chekerGrid x0 = w/2 y0 = h/2 w2 = w/2 h2 = h/2 painter.setBrush( Qt.white ) painter.drawRect( x0, y0, w2, h2 ) painter.setBrush( QColor.fromRgbF( 0.5, 0.5, 0.5 ) ) for y in range( 4 ): for x in range( w2/10 ): if (x % 2) == (y % 2): painter.drawRect( x0 + x * 10, y0 + y * 10, 10, 10 ) #right 2/3 for color with alpha painter.setBrush( self.previewColor ) painter.drawRect( x0, y0, w2+1, h2 + 1 )
def onTextHexChanged( self, value ): if self.updating: return hexText = value color = QColor( value ) color.setAlphaF( self.currentColor.alphaF() ) self.setColor( color ) self.updateColorPlane()
def __call__(self, imageid, cid): fct = self.parameters.transfer_function if fct is None: return QColor() values = self.result.cells[imageid][cid] ka = values[1] + values[0] area = self.cellArea(imageid, cid) is_fwd = True for p in self.result.method_params: if 'Backward' in p: is_fwd = False break data = self.result.data base_id = imageid if is_fwd else imageid - 1 dt = data.images_time[base_id + 1] - data.images_time[base_id] print("area = {2}, ka = {0}, dt = {1}".format(ka, dt, area)) if np.sqrt(area * np.exp(ka * dt)) < self.parameters.min_displacement: return QColor() if values[0] == 0: value = 0 else: value = 1 - values[1] / values[0] col = QColor() col.setRgbF(*fct.rgba(value)) return col
def generateRandomColors(M=256, colormodel="hsv", clamp=None, zeroIsTransparent=False): """Generate a colortable with M entries. colormodel: currently only 'hsv' is supported clamp: A dictionary stating which parameters of the color in the colormodel are clamped to a certain value. For example: clamp = {'v': 1.0} will ensure that the value of any generated HSV color is 1.0. All other parameters (h,s in the example) are selected randomly to lie uniformly in the allowed range. """ r = numpy.random.random((M, 3)) if clamp is not None: for k,v in clamp.iteritems(): idx = colormodel.index(k) r[:,idx] = v colors = [] if colormodel == "hsv": for i in range(M): if zeroIsTransparent and i == 0: colors.append(QColor(0, 0, 0, 0).rgba()) else: h, s, v = r[i,:] color = numpy.asarray(colorsys.hsv_to_rgb(h, s, v)) * 255 qColor = QColor(*color) colors.append(qColor.rgba()) return colors else: raise RuntimeError("unknown color model '%s'" % colormodel)
def pixel_color_in_area(self, rectangle, color): """ Searches the rectangle area 'rectangle' for the color 'color'. If the 'color' is found inside 'rectangle' then it returns True as first argument and the point where the pixel was found as the 2nd argument If nothing is found then it simply returns False. The rectangle is a tuple [x, y, width, height], where x, y the coordinates of the top left corner and width, height the width and the height of the rectangle. The color is a string with a hexadecimal representation of a color (e.g. #000000) """ x = rectangle[0] y = rectangle[1] width = rectangle[2] height = rectangle[3] color = to_lower(color) img = QPixmap.grabWindow(QApplication.desktop().winId()).toImage().copy(x, y, width + 1, height + 1) cur_y = cur_x = 0 while cur_y <= height: cur_x = 0 while cur_x <= width: cur_color = QColor(img.pixel(QPoint(cur_x, cur_y))) if str(color) == str(cur_color.name()): return True, [cur_x + x, cur_y + y] cur_x += self.pixel_search_speed cur_y += 1 return False, [-1, -1]
def make_color_legend(self): color_index = self.get_color_index() if color_index == -1: return color_var = self.data_domain[color_index] use_shape = self.get_shape_index() == color_index if isinstance(color_var, DiscreteVariable): if not self.legend: self.create_legend() palette = self.discrete_palette for i, value in enumerate(color_var.values): color = QColor(*palette.getRGB(i)) brush = color.lighter(self.DarkerValue) self.legend.addItem( ScatterPlotItem( pen=color, brush=brush, size=10, symbol=self.CurveSymbols[i] if use_shape else "o"), value) else: legend = self.color_legend = PositionedLegendItem( self.plot_widget.plotItem, self, legend_id="colors", at_bottom=True) label = PaletteItemSample(self.continuous_palette, self.scale) legend.addItem(label, "") legend.setGeometry(label.boundingRect())
def paintEvent( self, event ): painter = QtGui.QPainter() color = self.color painter.begin( self ) margin = 2 x = margin y = margin w = self.width() - margin * 2 h = self.height() - margin * 2 gridSize = 5 gridPart = gridSize * 1 painter.translate( margin, margin ) painter.setPen( Qt.black ) painter.setBrush( Qt.white ) painter.drawRect( 0,0,w,h ) painter.setPen( Qt.NoPen ) painter.setBrush( Qt.black ) painter.setClipRect( 0,0,w,h ) for y in range( int(h/gridSize+1) ): for x in range( int(w/gridSize+1) ): if (x % 2) == (y % 2): painter.drawRect( x * gridSize, y * gridSize, gridSize, gridSize ) painter.setBrush( color ) painter.drawRect( 0,0,w,h ) colorFull = QColor( color ) colorFull.setAlpha( 255 ) painter.setBrush( colorFull ) painter.drawRect( 0,0, w/2, h ) painter.end()
def pixel_color_in_area_counter(self, rectangle, color): """ Searches the rectangle area 'rectangle' for the color 'color'. It returns an integer indicating the times that the 'color' was found inside the 'rectangle'. The rectangle is a tuple [x, y, width, height], where x, y the coordinates of the top left corner and width, height the width and the height of the rectangle. The color is a string with a hexadecimal representation of a color (e.g. #000000) """ x = rectangle[0] y = rectangle[1] width = rectangle[2] height = rectangle[3] color = to_lower(color) img = QPixmap.grabWindow(QApplication.desktop().winId()).toImage().copy(x, y, width + 1, height + 1) counter = cur_y = cur_x = 0 while cur_y <= height: cur_x = 0 while cur_x <= width: cur_color = QColor(img.pixel(QPoint(cur_x, cur_y))) if str(color) == str(cur_color.name()): counter += 1 cur_x += self.pixel_search_speed cur_y += 1 return counter
def init(self): self._text = None self._quoteParser = QuoteParser(self.package().path()) # set configuration self.conf = self.config('startrekfortune-plasmoid') # parse or initialize configurations self._textColor = QColor(self.conf.readEntry("textColor", "#000000")) self._shadowColor = QColor(self.conf.readEntry("shadowColor", "#FFFFFF")) self._font = QFont(self.conf.readEntry("font", QFont("Sans-Serif", 12, QFont.Bold))) self._showBackground = self.conf.readEntry("showBackground", "False").toBool() self._showSVG = self.conf.readEntry("showSVG", "True").toBool() self._updateInterval = self.conf.readEntry("updateInterval", 5).toInt()[0] # set timer self._updateTimer = QTimer() self.setTimer() self.setPlasmaBackground() # set layout and initial size self.layout = QGraphicsLinearLayout(Qt.Horizontal, self.applet) self.setAspectRatioMode(Plasma.KeepAspectRatio) self.setHasConfigurationInterface(True) if self.conf.readEntry("size_initialized", "0").toString() == "0": self.resize(385, 277) self.conf.writeEntry("size_initialized", "1")
def render(self): x = 0 for c in self.columns: max_w = self.c2max_w[c] faces = self.column2faces.get(c, []) if self.as_grid: y = 0 else: y = (self.h - self.c2height.get(c, 0)) / 2 for r, f in enumerate(faces): w, h = self.sizes[c][r] if self.as_grid: max_h = self.r2max_h[r] else: max_h = h f.node = self.node if f.type == "text": obj = _TextFaceItem(f, self.node, f.get_text()) font = f._get_font() obj.setFont(font) obj.setBrush(QBrush(QColor(f.fgcolor))) elif f.type == "item": obj = f.item else: # Loads the pre-generated pixmap obj = _ImgFaceItem(f, self.node, f.pixmap) obj.setAcceptsHoverEvents(True) obj.setParentItem(self) x_offset, y_offset = 0, 0 if max_w > w: # Horizontally at the left if f.hz_align == 0: x_offset = 0 elif f.hz_align == 1: # Horizontally centered x_offset = (max_w - w) / 2 elif f.hz_align == 2: # At the right x_offset = (max_w - w) if max_h > h: if f.vt_align == 0: # Vertically on top y_offset = 0 elif f.vt_align == 1: # Vertically centered y_offset = (max_h - h) / 2 elif f.hz_align == 2: # Vertically at bottom y_offset = (max_h - h) # Correct cases in which object faces has negative # starting points #obj_rect = obj.boundingRect() #_pos = obj_rect.topLeft() #_x = abs(_pos.x()) if _pos.x() < 0 else 0 #_y = abs(_pos.y()) if _pos.y() < 0 else 0 text_y_offset = -obj.boundingRect().y( ) if f.type == "text" else 0 obj.setPos(x + f.margin_left + x_offset, y + y_offset + f.margin_top + text_y_offset) if f.rotation and f.rotation != 180: fake_rect = obj.boundingRect() fake_w, fake_h = fake_rect.width(), fake_rect.height() self._rotate_item(obj, f.rotation) #wcorr = fake_w/2.0 - w/2.0 #ycorr = fake_h/2.0 - h/2.0 #print "Correctopm", fake_w/2.0 - w/2.0, fake_h/2.0 - h/2 #obj.moveBy(-wcorr, -ycorr) obj.moveBy(((w / 2) - fake_w / 2.0), (h / 2) - (fake_h / 2.0)) #r = QGraphicsRectItem(0, 0, w, h) #r.setParentItem(self) obj.rotable = f.rotable f.inner_background.apply(obj) f.inner_border.apply(obj) bg = f.background.apply(obj) border = f.border.apply(obj) if border: border.setRect(x, y, max_w, max_h) border.setParentItem(self) if bg: bg.setRect(x, y, max_w, max_h) bg.setParentItem(self) if f.opacity < 1: obj.setOpacity(f.opacity) if self.as_grid: y += max_h else: y += h # set label of the face if possible try: obj.face_label = f.label except AttributeError: pass obj.face_type = str(type(f)).split(".")[-1] x += max_w
def color(self): """ Return the arrow brush color. """ return QColor(self.__color)
def setup(self): for key, value in self.data: # Separate parameter attribute's name and help description label = key[0] help = key[1] if DEBUG: print "value:", value if label is None and value is None: # Separator: (None, None) self.formlayout.addRow(QLabel(" "), QLabel(" ")) self.widgets[None] = None continue elif label is None: # Comment self.formlayout.addRow(QLabel(value)) self.widgets[None] = value 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 isinstance(value, (str, unicode)): if (label == 'Help'): self.help.insert(0, value) continue else: field = QLineEdit(value, self) elif isinstance(value, (list, 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 >>STDERR, "Warning: '%s' index is invalid (label: " \ "%s, value: %s)" % (selindex, label, value) 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) 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) field.setToolTip(QString(help)) self.help.append(label + ' -- ' + help) self.formlayout.addRow(label, field) # Add close button self.widgets[label] = field
from PyQt4.QtCore import QVariant from Data import DrumKit from Data.Drum import Drum from Data.DefaultKits import GHOST_VOLUME, ACCENT_VOLUME from Data import fileUtils from QDefaultKitManager import QDefaultKitManager import copy import os import string #IGNORE:W0402 import DBMidi from QNotationScene import QNotationScene _KIT_FILE_EXT = ".dbk" _KIT_FILTER = "DrumBurp kits (*%s)" % _KIT_FILE_EXT _BAD_ABBR_COLOR = QColor("red") _GOOD_ABBR_COLOR = QColor("black") class QEditKitDialog(QDialog, Ui_editKitDialog): ''' classdocs ''' def __init__(self, kit, emptyDrums = None, parent = None, directory = None): ''' Constructor ''' super(QEditKitDialog, self).__init__(parent) self.setupUi(self) self.muteButton.setChecked(DBMidi.isMuted()) if emptyDrums is None:
def compute_colors(self, keep_colors=False): if not keep_colors: self.pen_colors = self.brush_colors = None color_index = self.get_color_index() def make_pen(color, width): p = QPen(color, width) p.setCosmetic(True) return p subset = None if self.subset_indices: subset = np.array([ ex.id in self.subset_indices for ex in self.raw_data[self.valid_data] ]) if color_index == -1: #color = "Same color" color = self.plot_widget.palette().color(OWPalette.Data) pen = [make_pen(color, 1.5)] * self.n_points if subset is not None: brush = [(QBrush(QColor(128, 128, 128, 0)), QBrush(QColor(128, 128, 128, self.alpha_value)))[s] for s in subset] else: brush = [QBrush(QColor(128, 128, 128))] * self.n_points return pen, brush c_data = self.original_data[color_index, self.valid_data] if self.data_domain[color_index].is_continuous: if self.pen_colors is None: self.scale = DiscretizedScale(np.nanmin(c_data), np.nanmax(c_data)) c_data -= self.scale.offset c_data /= self.scale.width c_data = np.floor(c_data) + 0.5 c_data /= self.scale.bins c_data = np.clip(c_data, 0, 1) palette = self.continuous_palette self.pen_colors = palette.getRGB(c_data) self.brush_colors = np.hstack([ self.pen_colors, np.full((self.n_points, 1), self.alpha_value) ]) self.pen_colors *= 100 / self.DarkerValue self.pen_colors = [ make_pen(QColor(*col), 1.5) for col in self.pen_colors.tolist() ] if subset is not None: self.brush_colors[:, 3] = 0 self.brush_colors[subset, 3] = self.alpha_value else: self.brush_colors[:, 3] = self.alpha_value pen = self.pen_colors brush = np.array( [QBrush(QColor(*col)) for col in self.brush_colors.tolist()]) else: if self.pen_colors is None: palette = self.discrete_palette n_colors = palette.number_of_colors c_data = c_data.copy() c_data[np.isnan(c_data)] = n_colors c_data = c_data.astype(int) colors = np.r_[palette.getRGB(np.arange(n_colors)), [[128, 128, 128]]] pens = np.array([ make_pen(QColor(*col).darker(self.DarkerValue), 1.5) for col in colors ]) self.pen_colors = pens[c_data] self.brush_colors = np.array([[ QBrush(QColor(0, 0, 0, 0)), QBrush(QColor(col[0], col[1], col[2], self.alpha_value)) ] for col in colors]) self.brush_colors = self.brush_colors[c_data] if subset is not None: brush = np.where(subset, self.brush_colors[:, 1], self.brush_colors[:, 0]) else: brush = self.brush_colors[:, 1] pen = self.pen_colors return pen, brush
QVBoxLayout) except ImportError: from PyQt5.QtCore import (pyqtSignal, Qt, QVariant, QSize, QPointF, QRect) from PyQt5.QtWidgets import (QDesktopWidget, QDialog, QPushButton, QProgressBar, QToolButton, QAction, QWidget, QLabel) from PyQt5.QtGui import (QColor, QIcon, QPixmap, QPainter) import os import sys import imp import random import math import time CHART_COLOR_BLUE = QColor(0, 0, 255, 200) CHART_COLOR_RED = QColor(255, 0, 0, 200) CHART_COLOR_BLACK = QColor(9, 0, 0, 200) CHART_COLOR_GREEN = QColor(0, 128, 0, 200) CHART_COLOR_GREY = QColor(176, 176, 176, 200) CHART_COLOR_ORANGE = QColor(237, 189, 45, 200) # unicode = str with python3 if sys.version_info > (3, ): unicode = str def bytes_to_unicode(ob): """ Byte to unicode with exception... Only for py3, will be removed on future version...
def getNextPmapColor(self): return self._getNext(self.topLevelOperatorView.PmapColors, super(CropSelectionGui, self).getNextPmapColor, lambda x: QColor(*x))
def arbitaryColor(amount, max): color = QColor() color.setHsv(240 * amount / float(max - 1), 255, 255) return color
def setup(self): for label, value in self.data: if label is None and value is None: # Separator: (None, None) frame = QFrame() frame.setFrameShape(QFrame.HLine) frame.setFrameShadow(QFrame.Sunken) self.formlayout.addRow(frame) 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 isinstance(value, (str, str)): 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 >> STDERR, "Warning: '%s' index is invalid (label: " \ "%s, value: %s)" % (selindex, label, value) 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) self.connect(field, SIGNAL('textChanged(QString)'), 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 __init__(self, parent=None): QPushButton.__init__(self, parent) self.setFixedSize(22, 22) self.setIconSize(QSize(12, 12)) self.connect(self, SIGNAL("clicked()"), self.choose_color) self._color = QColor()
def choose_color(self): rgba, valid = QColorDialog.getRgba(self._color.rgba(), self.parentWidget()) if valid: color = QColor.fromRgba(rgba) self.set_color(color)
def main(argv=None): if argv is None: argv = sys.argv usage = "usage: %prog [options] [scheme_file]" parser = optparse.OptionParser(usage=usage) parser.add_option("--no-discovery", action="store_true", help="Don't run widget discovery " "(use full cache instead)") parser.add_option("--force-discovery", action="store_true", help="Force full widget discovery " "(invalidate cache)") parser.add_option("--no-welcome", action="store_true", help="Don't show welcome dialog.") parser.add_option("--no-splash", action="store_true", help="Don't show splash screen.") parser.add_option("-l", "--log-level", help="Logging level (0, 1, 2, 3, 4)", type="int", default=1) parser.add_option("--no-redirect", action="store_true", help="Do not redirect stdout/err to canvas output view.") parser.add_option("--style", help="QStyle to use", type="str", default=None) parser.add_option("--stylesheet", help="Application level CSS style sheet to use", type="str", default="orange.qss") parser.add_option("--qt", help="Additional arguments for QApplication", type="str", default=None) (options, args) = parser.parse_args(argv[1:]) levels = [ logging.CRITICAL, logging.ERROR, logging.WARN, logging.INFO, logging.DEBUG ] # Fix streams before configuring logging (otherwise it will store # and write to the old file descriptors) fix_win_pythonw_std_stream() # Try to fix fonts on OSX Mavericks fix_osx_10_9_private_font() # File handler should always be at least INFO level so we need # the application root level to be at least at INFO. root_level = min(levels[options.log_level], logging.INFO) rootlogger = logging.getLogger(OrangeCanvas.__name__) rootlogger.setLevel(root_level) # Standard output stream handler at the requested level stream_hander = logging.StreamHandler() stream_hander.setLevel(level=levels[options.log_level]) rootlogger.addHandler(stream_hander) log.info("Starting 'Orange Canvas' application.") qt_argv = argv[:1] if options.style is not None: qt_argv += ["-style", options.style] if options.qt is not None: qt_argv += shlex.split(options.qt) qt_argv += args log.debug("Starting CanvasApplicaiton with argv = %r.", qt_argv) app = CanvasApplication(qt_argv) # NOTE: config.init() must be called after the QApplication constructor config.init() file_handler = logging.FileHandler(filename=os.path.join( config.log_dir(), "canvas.log"), mode="w") file_handler.setLevel(root_level) rootlogger.addHandler(file_handler) # intercept any QFileOpenEvent requests until the main window is # fully initialized. # NOTE: The QApplication must have the executable ($0) and filename # arguments passed in argv otherwise the FileOpen events are # triggered for them (this is done by Cocoa, but QApplicaiton filters # them out if passed in argv) open_requests = [] def onrequest(url): log.info("Received an file open request %s", url) open_requests.append(url) app.fileOpenRequest.connect(onrequest) settings = QSettings() stylesheet = options.stylesheet stylesheet_string = None if stylesheet != "none": if os.path.isfile(stylesheet): stylesheet_string = open(stylesheet, "rb").read() else: if not os.path.splitext(stylesheet)[1]: # no extension stylesheet = os.path.extsep.join([stylesheet, "qss"]) pkg_name = OrangeCanvas.__name__ resource = "styles/" + stylesheet if pkg_resources.resource_exists(pkg_name, resource): stylesheet_string = \ pkg_resources.resource_string(pkg_name, resource) base = pkg_resources.resource_filename(pkg_name, "styles") pattern = re.compile( r"^\s@([a-zA-Z0-9_]+?)\s*:\s*([a-zA-Z0-9_/]+?);\s*$", flags=re.MULTILINE) matches = pattern.findall(stylesheet_string) for prefix, search_path in matches: QDir.addSearchPath(prefix, os.path.join(base, search_path)) log.info("Adding search path %r for prefix, %r", search_path, prefix) stylesheet_string = pattern.sub("", stylesheet_string) else: log.info("%r style sheet not found.", stylesheet) # Add the default canvas_icons search path dirpath = os.path.abspath(os.path.dirname(OrangeCanvas.__file__)) QDir.addSearchPath("canvas_icons", os.path.join(dirpath, "icons")) canvas_window = CanvasMainWindow() canvas_window.setWindowIcon(config.application_icon()) if stylesheet_string is not None: canvas_window.setStyleSheet(stylesheet_string) if not options.force_discovery: reg_cache = cache.registry_cache() else: reg_cache = None widget_discovery = qt.QtWidgetDiscovery(cached_descriptions=reg_cache) widget_registry = qt.QtWidgetRegistry() widget_discovery.found_category.connect(widget_registry.register_category) widget_discovery.found_widget.connect(widget_registry.register_widget) want_splash = \ settings.value("startup/show-splash-screen", True, type=bool) and \ not options.no_splash if want_splash: pm, rect = config.splash_screen() splash_screen = SplashScreen(pixmap=pm, textRect=rect) splash_screen.setFont(QFont("Helvetica", 12)) color = QColor("#FFD39F") def show_message(message): splash_screen.showMessage(message, color=color) widget_discovery.discovery_start.connect(splash_screen.show) widget_discovery.discovery_process.connect(show_message) widget_discovery.discovery_finished.connect(splash_screen.hide) log.info("Running widget discovery process.") cache_filename = os.path.join(cache_dir(), "widget-registry.pck") if options.no_discovery: widget_registry = cPickle.load(open(cache_filename, "rb")) widget_registry = qt.QtWidgetRegistry(widget_registry) else: widget_discovery.run(config.widgets_entry_points()) # Store cached descriptions cache.save_registry_cache(widget_discovery.cached_descriptions) cPickle.dump(WidgetRegistry(widget_registry), open(cache_filename, "wb")) set_global_registry(widget_registry) canvas_window.set_widget_registry(widget_registry) canvas_window.show() canvas_window.raise_() want_welcome = \ settings.value("startup/show-welcome-screen", True, type=bool) \ and not options.no_welcome # Process events to make sure the canvas_window layout has # a chance to activate (the welcome dialog is modal and will # block the event queue, plus we need a chance to receive open file # signals when running without a splash screen) app.processEvents() app.fileOpenRequest.connect(canvas_window.open_scheme_file) if want_welcome and not args and not open_requests: canvas_window.welcome_dialog() elif args: log.info("Loading a scheme from the command line argument %r", args[0]) canvas_window.load_scheme(args[0]) elif open_requests: log.info("Loading a scheme from an `QFileOpenEvent` for %r", open_requests[-1]) canvas_window.load_scheme(open_requests[-1].toLocalFile()) stdout_redirect = \ settings.value("output/redirect-stdout", True, type=bool) stderr_redirect = \ settings.value("output/redirect-stderr", True, type=bool) # cmd line option overrides settings / no redirect is possible # under ipython if options.no_redirect or running_in_ipython(): stderr_redirect = stdout_redirect = False output_view = canvas_window.output_view() if stdout_redirect: stdout = TextStream() stdout.stream.connect(output_view.write) # also connect to original fd stdout.stream.connect(sys.stdout.write) else: stdout = sys.stdout if stderr_redirect: error_writer = output_view.formated(color=Qt.red) stderr = TextStream() stderr.stream.connect(error_writer.write) # also connect to original fd stderr.stream.connect(sys.stderr.write) else: stderr = sys.stderr if stderr_redirect: sys.excepthook = ExceptHook() sys.excepthook.handledException.connect(output_view.parent().show) with nested(redirect_stdout(stdout), redirect_stderr(stderr)): log.info("Entering main event loop.") try: status = app.exec_() except BaseException: log.error("Error in main event loop.", exc_info=True) canvas_window.deleteLater() app.processEvents() app.flush() del canvas_window # Collect any cycles before deleting the QApplication instance gc.collect() del app return status
class ScheduleVisualizer(QWidget): time = 50 proc = 20 scale = 1.5 schedule = None method = None vertices = {} positions = {} procrects = {} colors = { "axis": QColor(255, 255, 255), "task": QColor(255, 255, 0), "delivery": QColor(100, 0, 255), "select": QColor(255, 0, 0) } selectedTask = None addrect = None delrect = None targetPos = None pressed = False def __init__(self, parent=None): QWidget.__init__(self, parent) self.setGeometry(0, 0, (70 + self.time * 10) * self.scale, (40 + self.proc * 20) * self.scale) self.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s self.procicon = QImage(_fromUtf8(":/pics/pics/processor.png")) self.addicon = QImage(_fromUtf8(":/pics/pics/add.png")) self.delicon = QImage(_fromUtf8(":/pics/pics/meenoos.png")) def paintEvent(self, event): if self.schedule: paint = QPainter() paint.begin(self) paint.setPen(self.colors["axis"]) paint.setFont(QtGui.QFont('Decorative', 9 * self.scale)) procX = {} # Draw processor names and axis for i in range(self.proc): paint.drawImage( QRect(15 * self.scale, (10 + i * 20) * self.scale, 24 * self.scale, 24 * self.scale), self.procicon) paint.drawText(40 * self.scale, (25 + i * 20) * self.scale, str(self.schedule.processors[i].reserves)) plus = QRect(5 * self.scale, (10 + i * 20) * self.scale, 10 * self.scale, 10 * self.scale) paint.drawImage(plus, self.addicon) meenoos = QRect(5 * self.scale, (20 + i * 20) * self.scale, 10 * self.scale, 10 * self.scale) paint.drawImage(meenoos, self.delicon) self.procrects[self.schedule.processors[i]] = [plus, meenoos] paint.drawLine(50 * self.scale, (20 + i * 20) * self.scale, (50 + self.time * 10) * self.scale, (20 + i * 20) * self.scale) procX[self.schedule.processors[i].number] = 20 + i * 20 # Draw timeline tdir = self.method.system.tdir paint.drawLine(50 * self.scale, self.height() - 15, (50 + tdir * 10) * self.scale, self.height() - 15) paint.drawLine(50 * self.scale, 10 * self.scale, 50 * self.scale, self.height() - 10) t = 0 paint.setFont(QtGui.QFont('Decorative', 8)) while t < tdir + 10: paint.drawLine((50 + t * 10) * self.scale, self.height() - 20, (50 + t * 10) * self.scale, self.height() - 10) paint.drawText((50 + t * 10 + 1) * self.scale, self.height() - 5, str(t)) t += 10 paint.setPen(self.colors["select"]) paint.drawLine((50 + tdir * 10) * self.scale, 10 * self.scale, (50 + tdir * 10) * self.scale, self.height() - 10) if self.selectedTask: t = self.selectedTask start = self.method.interpreter.executionTimes[t][0] finish = self.method.interpreter.executionTimes[t][1] paint.drawText((50 + start * 10) * self.scale, self.height() - 16, str(start)) paint.drawText((50 + finish * 10) * self.scale, self.height() - 16, str(finish)) # Draw tasks paint.setPen(self.colors["task"]) paint.setFont(QtGui.QFont('Decorative', 9 * self.scale)) self.vertices = {} self.positions = {} for m in self.schedule.vertices.keys(): i = 0 prev = None for t in self.schedule.vertices[m]: start = self.method.interpreter.executionTimes[t][0] finish = self.method.interpreter.executionTimes[t][1] task = QtCore.QRect((50 + start * 10) * self.scale, (procX[t.m.number] - 5) * self.scale, (finish - start) * 10 * self.scale, 10 * self.scale) # TODO: calculate once! self.vertices[t] = task if i == 0: self.positions[(m, i)] = QtCore.QRect( QPoint(50 * self.scale, task.y()), task.bottomLeft()) else: self.positions[(m, i)] = QtCore.QRect( prev.topRight(), task.bottomLeft()) if t != self.selectedTask: paint.fillRect(task, self.colors["task"]) else: paint.fillRect(task, self.colors["select"]) if self.schedule.CanAddVersions(t): self.addrect = QRect(task.topLeft().x(), task.topLeft().y(), 10 * self.scale, 10 * self.scale) paint.drawImage(self.addrect, self.addicon) if self.schedule.CanDeleteVersions(t): self.delrect = QRect( task.topRight().x() - 10 * self.scale, task.topRight().y(), 10 * self.scale, 10 * self.scale) paint.drawImage(self.delrect, self.delicon) paint.setPen(self.colors["axis"]) paint.drawRect(task) paint.setPen(self.colors["task"]) prev = task i += 1 self.positions[(m, i)] = QtCore.QRect( prev.topRight(), QPoint(prev.topRight().x() + 100, prev.bottomRight().y())) if self.targetPos: width = min(self.selectedTask.v.time * 10 * self.scale, self.positions[self.targetPos].width()) rect = QtCore.QRect(self.positions[self.targetPos]) rect.setWidth(width) paint.fillRect(rect, self.colors["select"]) # Draw deliveries paint.setPen(QPen(self.colors["delivery"], 2)) for d in self.method.interpreter.deliveryTimes: self.drawArrow(paint, (50 + d[2] * 10) * self.scale, procX[d[0].number] * self.scale, (50 + d[3] * 10) * self.scale, procX[d[1].number] * self.scale) # Draw captions paint.setPen(self.colors["axis"]) for m in self.schedule.vertices.keys(): for t in self.schedule.vertices[m]: start = self.method.interpreter.executionTimes[t][0] finish = self.method.interpreter.executionTimes[t][1] s = str(t.v.number) if t.k.number > 1: s += " v" + str(t.k.number) paint.drawText((10 + finish + start - int(len(s) / 2)) * 5 * self.scale, (procX[t.m.number] + 5) * self.scale, s) paint.end() def mousePressEvent(self, e): def update(): self.proc = self.schedule.GetProcessorsWithoutDoubles() self.time = self.schedule.Interpret() self.targetPos = None self.pressed = False self.selectedTask = None self.addrect = None self.delrect = None self.emit(SIGNAL("ManualOperation")) self.ResizeCanvas() self.repaint() return if self.selectedTask: if self.addrect: if self.addrect.contains(e.pos()): self.method.ManualStep("AddVersion", v=self.selectedTask.v) update() return if self.delrect: if self.delrect.contains(e.pos()): self.method.ManualStep("DeleteVersion", v=self.selectedTask.v) update() return for p in self.procrects.keys(): if self.procrects[p][0].contains(e.pos()): self.method.ManualStep("AddProcessor", m=p) update() return if self.procrects[p][1].contains(e.pos()): self.method.ManualStep("DeleteProcessor", m=p) update() return for v in self.vertices.keys(): if self.vertices[v].contains(e.pos()): self.selectedTask = v self.repaint() self.pressed = True return self.selectedTask = None self.addrect = None self.delrect = None self.repaint() def mouseMoveEvent(self, e): if self.pressed: for p in self.positions.keys(): if self.positions[p].contains(e.pos()): self.targetPos = p self.repaint() return self.targetPos = None self.repaint() def mouseReleaseEvent(self, e): if self.pressed and self.targetPos: result = self.method.ManualStep( "MoveVertex", v=self.selectedTask, n1=self.schedule.vertices[self.selectedTask.m].index( self.selectedTask), m2=self.schedule.GetProcessor(self.targetPos[0]), n2=self.targetPos[1]) if result == True: self.proc = self.schedule.GetProcessorsWithoutDoubles() self.time = self.method.interpreter.Interpret(self.schedule) self.emit(SIGNAL("ManualOperation")) else: self.emit(SIGNAL("WrongOperation"), result) self.targetPos = None self.pressed = False self.selectedTask = None self.addrect = None self.delrect = None self.ResizeCanvas() self.repaint() return self.pressed = False self.targetPos = None self.repaint() def drawArrow(self, paint, x1, y1, x2, y2): m = paint.worldMatrix() paint.translate(x1, y1) pi = 3.1415926 alpha = math.atan(abs(y2 - y1) / abs(x2 - x1)) * 180 / pi if y2 > y1: if x2 > x1: paint.rotate(alpha) else: paint.rotate(180 - alpha) else: if x2 > x1: paint.rotate(-alpha) else: paint.rotate(alpha - 180) endcoord = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) p1 = QPointF(endcoord, 0) paint.drawLine(0, 0, p1.x(), 0) coord = math.sqrt(12**2 - 6**2) p2 = QPointF(endcoord - coord, 6) p3 = QPointF(endcoord - coord, -6) path = QPainterPath() path.moveTo(p1) path.lineTo(p2) path.lineTo(p3) path.lineTo(p1) paint.fillPath(path, paint.pen().color()) paint.setWorldMatrix(m) def SetScale(self, d): self.scale = d self.ResizeCanvas() self.repaint() def Visualize(self, m): self.schedule = m.system.schedule self.method = m # TODO: get rid of this self.proc = self.schedule.GetProcessorsWithoutDoubles() self.time = self.method.interpreter.Interpret(self.schedule) self.ResizeCanvas() self.repaint() def ResizeCanvas(self): self.setGeometry( 0, 0, max(int((70 + self.time * 10) * self.scale), self.parent().width()), max(int((40 + self.proc * 20) * self.scale), self.parent().height()))
def setup(self): for name, label, value in self.data: if DEBUG: print("value:", value) if not name is None: self.names.append(name) if name is None and 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 isinstance(value, str): field = QLineEdit(value, self) elif isinstance(value, (list, 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 = QDoubleSpinBox(self) # field.setRange(-1e9, 1e9) # field.setValue(value) 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 colorFromStringTuple(self, tuple): return QColor(int(tuple[0]), int(tuple[1]), int(tuple[2]))
def generateScheme(self, apply=True, monochromeText=True): """Generate color palette By default the generated palette is also applied to the whole application To override supply the apply=False argument """ BASE_COLOR = self.baseColor HIGHLIGHT_COLOR = self.highlightColor BRIGHTNESS_SPREAD = self.spread if self.__lightness(BASE_COLOR) > 0.5: SPREAD = 100 / BRIGHTNESS_SPREAD else: SPREAD = 100 * BRIGHTNESS_SPREAD if self.__lightness(HIGHLIGHT_COLOR) > 0.6: HIGHLIGHTEDTEXT_COLOR = BASE_COLOR.darker(SPREAD * 2) else: HIGHLIGHTEDTEXT_COLOR = BASE_COLOR.lighter(SPREAD * 2) self.palette.setBrush(QPalette.Window, QBrush(BASE_COLOR)) self.palette.setBrush(QPalette.WindowText, QBrush(BASE_COLOR.lighter(SPREAD))) self.palette.setBrush(QPalette.Foreground, QBrush(BASE_COLOR.lighter(SPREAD))) self.palette.setBrush(QPalette.Base, QBrush(BASE_COLOR)) self.palette.setBrush(QPalette.AlternateBase, QBrush(BASE_COLOR.darker(SPREAD))) self.palette.setBrush(QPalette.ToolTipBase, QBrush(BASE_COLOR)) self.palette.setBrush(QPalette.ToolTipText, QBrush(BASE_COLOR.lighter(SPREAD))) self.palette.setBrush(QPalette.Text, QBrush(BASE_COLOR.lighter(SPREAD * 1.2))) self.palette.setBrush(QPalette.Button, QBrush(BASE_COLOR)) self.palette.setBrush(QPalette.ButtonText, QBrush(BASE_COLOR.lighter(SPREAD))) self.palette.setBrush(QPalette.BrightText, QBrush(QColor(240, 240, 240))) self.palette.setBrush(QPalette.Light, QBrush(BASE_COLOR.lighter(SPREAD))) self.palette.setBrush(QPalette.Midlight, QBrush(BASE_COLOR.lighter(SPREAD / 2))) self.palette.setBrush(QPalette.Dark, QBrush(BASE_COLOR.darker(SPREAD))) self.palette.setBrush(QPalette.Mid, QBrush(BASE_COLOR)) self.palette.setBrush(QPalette.Shadow, QBrush(BASE_COLOR.darker(SPREAD * 2))) self.palette.setBrush(QPalette.Highlight, QBrush(HIGHLIGHT_COLOR)) self.palette.setBrush(QPalette.HighlightedText, QBrush(HIGHLIGHTEDTEXT_COLOR)) if monochromeText: lightness = self.__lightness(BASE_COLOR.lighter(SPREAD * 1.2)) textColor = QColor(lightness * 255, lightness * 255, lightness * 255) self.palette.setBrush(QPalette.WindowText, QBrush(textColor)) self.palette.setBrush(QPalette.Text, QBrush(textColor)) self.palette.setBrush(QPalette.ButtonText, QBrush(textColor)) self.palette.setBrush(QPalette.ToolTipText, QBrush(textColor)) if apply: QApplication.setPalette(self.palette)
def setAllowedStyleSnapRubberBand(self): self.rubberBand.setLineStyle(Qt.PenStyle(Qt.SolidLine)) self.rubberBand.setBorderColor(QColor(255, 0, 0, 200)) self.rubberBand.setFillColor(QColor(255, 0, 0, 40))
def setAvoidStyleSnapRubberBand(self): self.rubberBand.setLineStyle(Qt.PenStyle(Qt.DashDotLine)) self.rubberBand.setBorderColor(QColor(255, 255, 0, 200)) self.rubberBand.setFillColor(QColor(255, 0, 0, 40))
self.ySpinBox.setMaximum(shape5Dmax[2]-1) self.zSpinBox.setMaximum(shape5Dmax[3]-1) self.timeSlider.setMaximum(shape5Dmax[0]-1) self.timeSpinBox.setValue(shape5DcropMin[0]) self.xSpinBox.setValue(shape5DcropMin[1]) self.ySpinBox.setValue(shape5DcropMin[2]) self.zSpinBox.setValue(shape5DcropMin[3]) self.timeSlider.setValue(shape5DcropMin[0]) def setMouseCoords(self, x, y, z): self.xSpinBox.setValueWithoutSignal(x) self.ySpinBox.setValueWithoutSignal(y) self.zSpinBox.setValueWithoutSignal(z) if __name__ == "__main__": import sys from PyQt4.QtGui import QDialog, QApplication #make the program quit on Ctrl+C import signal signal.signal(signal.SIGINT, signal.SIG_DFL) app = QApplication(sys.argv) widget = QDialog() ex1 = ImageView2DHud(widget) ex1.createImageView2DHud("X", 12, QColor("red"), QColor("white")) widget.show() widget.raise_() app.exec_()
from PyQt4.QtGui import QColor WEEKS_IN_MONTH = 4 MONTHS_IN_YEAR = 12 WINDOW_SIZE_X = 1024 WINDOW_SIZE_Y = 640 QT_FULL_CRICLE_DEGREE = 5760 BIG_FOR_CAPTION_RADIUS = 50 GRAPHICS_ILL_COLORS = [ QColor(255, 0, 0, 255), QColor(255, 100, 0, 255), QColor(255, 150, 0, 255), QColor(255, 200, 0, 255), ] GRAPHICS_VACCINATED_COLORS = [ QColor(0, 255, 0, 255), QColor(0, 255, 255, 255), QColor(0, 100, 255, 255), QColor(0, 0, 255, 255), ]
def color_for_cell(self, row, col): return QBrush(QColor.fromHsv(120, self.colors[row, col], 255))
def _setup_plot(self): """Setup the plot with new curve data.""" assert self.data is not None data, domain = self.data, self.data.domain if is_discrete(domain.class_var): class_col_data, _ = data.get_column_view(domain.class_var) group_indices = [ np.flatnonzero(class_col_data == i) for i in range(len(domain.class_var.values)) ] else: group_indices = [np.arange(len(data))] X = np.arange(1, len(domain.attributes) + 1) groups = [] for i, indices in enumerate(group_indices): if self.classes: color = self.class_colors[i] else: color = QColor(Qt.darkGray) group_data = data[indices, :] plot_x, plot_y, connect = disconnected_curve_data(group_data.X, x=X) color.setAlpha(200) lightcolor = QColor(color.lighter(factor=150)) lightcolor.setAlpha(150) pen = QPen(color, 2) pen.setCosmetic(True) lightpen = QPen(lightcolor, 1) lightpen.setCosmetic(True) hoverpen = QPen(pen) hoverpen.setWidth(2) curve = pg.PlotCurveItem( x=plot_x, y=plot_y, connect=connect, pen=lightpen, symbolSize=2, antialias=True, ) self.graph.addItem(curve) hovercurves = [] for index, profile in zip(indices, group_data.X): hcurve = HoverCurve(x=X, y=profile, pen=hoverpen, antialias=True) hcurve.setToolTip('{}'.format(index)) hcurve._data_index = index hovercurves.append(hcurve) self.graph.addItem(hcurve) mean = np.nanmean(group_data.X, axis=0) meancurve = pg.PlotDataItem(x=X, y=mean, pen=pen, size=5, symbol="o", pxMode=True, symbolSize=5, antialias=True) hoverpen = QPen(hoverpen) hoverpen.setWidth(5) hc = HoverCurve(x=X, y=mean, pen=hoverpen, antialias=True) hc.setFlag(QGraphicsItem.ItemIsSelectable, False) self.graph.addItem(hc) self.graph.addItem(meancurve) q1, q2, q3 = np.nanpercentile(group_data.X, [25, 50, 75], axis=0) # TODO: implement and use a box plot item errorbar = pg.ErrorBarItem(x=X, y=mean, bottom=np.clip(mean - q1, 0, mean - q1), top=np.clip(q3 - mean, 0, q3 - mean), beam=0.5) self.graph.addItem(errorbar) groups.append( namespace(data=group_data, indices=indices, profiles=curve, hovercurves=hovercurves, mean=meancurve, boxplot=errorbar)) self.__groups = groups self.__update_visibility() self.__update_tooltips()
def setLayerColor(layer, color_name): renderer = layer.rendererV2() symbol = renderer.symbol() symbol.setColor(QColor(color_name))
def setupLayers(self): layers = [] op = self.topLevelOperatorView ravelerLabelsSlot = op.RavelerLabels if ravelerLabelsSlot.ready(): colortable = [] for _ in range(256): r, g, b = numpy.random.randint(0, 255), numpy.random.randint( 0, 255), numpy.random.randint(0, 255) colortable.append(QColor(r, g, b).rgba()) ravelerLabelLayer = ColortableLayer( LazyflowSource(ravelerLabelsSlot), colortable, direct=True) ravelerLabelLayer.name = "Raveler Labels" ravelerLabelLayer.visible = False ravelerLabelLayer.opacity = 0.4 layers.append(ravelerLabelLayer) supervoxelsSlot = op.Supervoxels if supervoxelsSlot.ready(): colortable = [] for i in range(256): r, g, b = numpy.random.randint(0, 255), numpy.random.randint( 0, 255), numpy.random.randint(0, 255) colortable.append(QColor(r, g, b).rgba()) supervoxelsLayer = ColortableLayer(LazyflowSource(supervoxelsSlot), colortable) supervoxelsLayer.name = "Input Supervoxels" supervoxelsLayer.visible = False supervoxelsLayer.opacity = 1.0 layers.append(supervoxelsLayer) def addFragmentSegmentationLayers(mslot, name): if mslot.ready(): for index, slot in enumerate(mslot): if slot.ready(): raveler_label = slot.meta.selected_label colortable = [] for i in range(256): r, g, b = numpy.random.randint( 0, 255), numpy.random.randint( 0, 255), numpy.random.randint(0, 255) colortable.append(QColor(r, g, b).rgba()) colortable[0] = QColor(0, 0, 0, 0).rgba() fragSegLayer = ColortableLayer(LazyflowSource(slot), colortable, direct=True) fragSegLayer.name = "{} #{} ({})".format( name, index, raveler_label) fragSegLayer.visible = False fragSegLayer.opacity = 1.0 layers.append(fragSegLayer) addFragmentSegmentationLayers(op.MaskedSupervoxels, "Masked Supervoxels") addFragmentSegmentationLayers(op.FilteredMaskedSupervoxels, "Filtered Masked Supervoxels") addFragmentSegmentationLayers(op.HoleFilledSupervoxels, "Hole Filled Supervoxels") addFragmentSegmentationLayers(op.RelabeledSupervoxels, "Relabeled Supervoxels") mslot = op.EditedRavelerBodies for index, slot in enumerate(mslot): if slot.ready(): raveler_label = slot.meta.selected_label # 0=Black, 1=Transparent colortable = [ QColor(0, 0, 0).rgba(), QColor(0, 0, 0, 0).rgba() ] bodyMaskLayer = ColortableLayer(LazyflowSource(slot), colortable, direct=True) bodyMaskLayer.name = "Raveler Body Mask #{} ({})".format( index, raveler_label) bodyMaskLayer.visible = False bodyMaskLayer.opacity = 1.0 layers.append(bodyMaskLayer) finalSegSlot = op.FinalSupervoxels if finalSegSlot.ready(): colortable = [] for _ in range(256): r, g, b = numpy.random.randint(0, 255), numpy.random.randint( 0, 255), numpy.random.randint(0, 255) colortable.append(QColor(r, g, b).rgba()) finalLayer = ColortableLayer(LazyflowSource(finalSegSlot), colortable) finalLayer.name = "Final Supervoxels" finalLayer.visible = False finalLayer.opacity = 0.4 layers.append(finalLayer) inputSlot = op.InputData if inputSlot.ready(): layer = GrayscaleLayer(LazyflowSource(inputSlot)) layer.name = "WS Input" layer.visible = False layer.opacity = 1.0 layers.append(layer) #raw data rawSlot = self.topLevelOperatorView.RawData if rawSlot.ready(): raw5D = self.topLevelOperatorView.RawData.value layer = GrayscaleLayer(ArraySource(raw5D), direct=True) #layer = GrayscaleLayer( LazyflowSource(rawSlot) ) layer.name = "raw" layer.visible = True layer.opacity = 1.0 layers.append(layer) return layers
def showLoadFiles(self,inputsArray): pedigrees={} if self.dialog is None: self.dialog= inFilesDialog() self.ui.consoleTextEdit.setText(self.ui.consoleTextEdit.toPlainText()+"\nEditing Input files...") res=self.dialog.exec_() self.inFilesArray=self.dialog.getDataFiles() errorMsg="" outRes=self.inFilesArray for el in outRes: if(len(outRes[el])== 0 and (el != 'mapfile')): errorMsg+=el +" file cannot be empty\n" else: if(el=='mapfile' and len(outRes[el])==0): continue if( not os.path.exists(outRes[el])): errorMsg+=el +" file \'"+outRes[el]+"' does not exist!\n" if(errorMsg== ""): self.ui.consoleTextEdit.setText(self.ui.consoleTextEdit.toPlainText()+" done.\nFiles looking OK.") #LOAD the pedigree file into a suitable data structure [pedigrees,msg]=self.dialog.parsePedigreesFile() if(len(msg)==0): self.ui.paramButton.setEnabled(True) self.ui.actionSetParameters.setEnabled(True) self.ui.paramLabel.setEnabled(True) self.ui.consoleTextEdit.setText(self.ui.consoleTextEdit.toPlainText()+"\nCan now proceed to setting parameters.") self.ui.runButton.setEnabled(False) self.ui.runLabel.setEnabled(False) self.ui.exportButton.setEnabled(False) self.ui.exportLabel.setEnabled(False) self.ui.actionRunAnalysis.setEnabled(False) else: self.ui.consoleTextEdit.setText(self.ui.consoleTextEdit.toPlainText()+"\n"+msg) self.ui.paramButton.setEnabled(False) self.ui.paramLabel.setEnabled(False) self.ui.inFilesLabel.setEnabled(False) self.ui.runButton.setEnabled(False) self.ui.runLabel.setEnabled(False) self.ui.exportButton.setEnabled(False) self.ui.exportLabel.setEnabled(False) self.ui.actionRunAnalysis.setEnabled(False) self.ui.actionExport.setEnabled(False) else: self.ui.consoleTextEdit.setText(self.ui.consoleTextEdit.toPlainText()+" done.\n") cc = self.ui.consoleTextEdit.textColor() self.ui.consoleTextEdit.setTextColor(QColor("red")) self.ui.consoleTextEdit.append("ERRORS FOUND.\n"+errorMsg) self.ui.consoleTextEdit.setTextColor(cc) self.ui.consoleTextEdit.append("") self.ui.paramButton.setEnabled(False) self.ui.actionSetParameters.setEnabled(False) self.ui.runButton.setEnabled(False) self.ui.runLabel.setEnabled(False) self.ui.actionRunAnalysis.setEnabled(False) self.ui.exportButton.setEnabled(False) self.ui.exportLabel.setEnabled(False) self.ui.actionExportResults.setEnabled(False) self.ui.actionRunAnalysis.setEnabled(False) self.ui.consoleTextEdit.moveCursor(QTextCursor.End) self.pedigrees=pedigrees
def updateTable(self): QgsMessageLog.logMessage("Updating Table") global distPop print(distPop) for p in range(0, self.districts + 1): self.attrdockwidget.tblPop.setItem( p, 0, QTableWidgetItem(str(districtName[p]))) self.attrdockwidget.tblPop.setItem( p, 2, QTableWidgetItem(str(distPop[p]))) self.attrdockwidget.tblPop.setItem( p, 3, QTableWidgetItem(str(self.targetpop - distPop[p]))) self.attrdockwidget.tblPop.item(p, 0).setBackground( QColor(255, 255, 255)) self.attrdockwidget.tblPop.item(p, 2).setBackground( QColor(255, 255, 255)) self.attrdockwidget.tblPop.item(p, 3).setBackground( QColor(255, 255, 255)) if distPop[p] >= self.targetpoplower and distPop[ p] <= self.targetpophigher: self.attrdockwidget.tblPop.item(p, 0).setBackground( QColor(0, 200, 0)) self.attrdockwidget.tblPop.item(p, 2).setBackground( QColor(0, 200, 0)) self.attrdockwidget.tblPop.item(p, 3).setBackground( QColor(0, 200, 0)) rowNum = 0 for d in dataFieldList: rowNum = rowNum + 1 if d.type == 1: self.attrdockwidget.tblPop.setItem( p, 3 + rowNum, QTableWidgetItem(str(d.field_sum[p]))) elif d.type == 2: if distPop[p] > 0: QgsMessageLog.logMessage( str(d.field_sum[p]) + " " + str(distPop[p])) self.attrdockwidget.tblPop.setItem( p, 3 + rowNum, QTableWidgetItem( str( round( float( float(d.field_sum[p]) / float(distPop[p])) * 100, 2)) + '%')) else: self.attrdockwidget.tblPop.setItem( p, 3 + rowNum, QTableWidgetItem('0.00%')) elif d.type == 3: if self.totalpop > 0: QgsMessageLog.logMessage( str(d.field_sum[p]) + " " + str(self.totalpop)) self.attrdockwidget.tblPop.setItem( p, 3 + rowNum, QTableWidgetItem( str( round( float( float(d.field_sum[p]) / float(self.totalpop)) * 100, 2)) + '%')) else: self.attrdockwidget.tblPop.setItem( p, 3 + rowNum, QTableWidgetItem('0.00%')) elif d.type == 4: if d.total_sum > 0: QgsMessageLog.logMessage( str(d.field_sum[p]) + " " + str(d.total_sum)) self.attrdockwidget.tblPop.setItem( p, 3 + rowNum, QTableWidgetItem( str( round( float( float(d.field_sum[p]) / float(d.total_sum)) * 100, 2)) + '%')) else: self.attrdockwidget.tblPop.setItem( p, 3 + rowNum, QTableWidgetItem('0.00%')) self.attrdockwidget.tblPop.resizeColumnToContents(0) self.attrdockwidget.tblPop.resizeColumnToContents(1) self.attrdockwidget.tblPop.resizeColumnToContents(2) self.attrdockwidget.tblPop.resizeColumnToContents(3)
def realtime_highlight(self, text): """Highlight each line while it is being edited. This function apply the proper highlight to the line being edited by the user, this is a really fast process for each line once you already have the document highlighted, but slow to do it the first time to highlight all the lines together.""" hls = [] block = self.currentBlock() user_data = block.userData() if user_data is None: user_data = SyntaxUserData(False) user_data.clear_data() block_number = block.blockNumber() highlight_errors = lambda cf, ud: cf if self.errors and (block_number in self.errors.errorsSummary): highlight_errors = self.__highlight_lint elif self.pep8 and (block_number in self.pep8.pep8checks): highlight_errors = self.__highlight_pep8 char_format = block.charFormat() char_format = highlight_errors(char_format, user_data) self.setFormat(0, len(block.text()), char_format) for expression, nth, char_format in self.rules: index = expression.indexIn(text, 0) while index >= 0: # We actually want the index of the nth match index = expression.pos(nth) length = len(expression.cap(nth)) char_format = highlight_errors(char_format, user_data) if (self.format(index) != STYLES['string']): self.setFormat(index, length, char_format) if char_format == STYLES['string']: hls.append((index, index + length)) user_data.add_str_group(index, index + length) elif char_format == STYLES['comment']: user_data.comment_start_at(index) index = expression.indexIn(text, index + length) self.setCurrentBlockState(0) if not self.multi_start: # Do multi-line strings in_multiline = self.match_multiline( text, *self.tri_single, hls=hls, highlight_errors=highlight_errors, user_data=user_data) if not in_multiline: in_multiline = self.match_multiline( text, *self.tri_double, hls=hls, highlight_errors=highlight_errors, user_data=user_data) else: # Do multi-line comment self.comment_multiline(text, self.multi_end[0], *self.multi_start) #Highlight selected word if self.selected_word_pattern is not None: index = self.selected_word_pattern.indexIn(text, 0) while index >= 0: index = self.selected_word_pattern.pos(0) length = len(self.selected_word_pattern.cap(0)) char_format = self.format(index) color = QColor() color.setNamedColor(STYLES['selectedWord']) color.setAlpha(100) char_format.setBackground(color) self.setFormat(index, length, char_format) index = self.selected_word_pattern.indexIn( text, index + length) #Spaces expression = QRegExp('\s+') index = expression.indexIn(text, 0) while index >= 0: index = expression.pos(0) length = len(expression.cap(0)) char_format = STYLES['spaces'] if settings.HIGHLIGHT_WHOLE_LINE: char_format = highlight_errors(char_format, user_data) self.setFormat(index, length, char_format) index = expression.indexIn(text, index + length) block.setUserData(user_data)
class ArrowAnnotation(Annotation): def __init__(self, parent=None, line=None, **kwargs): Annotation.__init__(self, parent, **kwargs) self.setFlag(QGraphicsItem.ItemIsMovable) self.setFlag(QGraphicsItem.ItemIsSelectable) self.setFocusPolicy(Qt.ClickFocus) if line is None: line = QLineF(0, 0, 20, 0) self.__line = line self.__color = QColor(Qt.red) self.__arrowItem = ArrowItem(self) self.__arrowItem.setLine(line) self.__arrowItem.setBrush(self.__color) self.__arrowItem.setPen(QPen(Qt.NoPen)) self.__arrowItem.setArrowStyle(ArrowItem.Concave) self.__arrowItem.setLineWidth(5) self.__shadow = QGraphicsDropShadowEffect( blurRadius=5, offset=QPointF(1.0, 2.0), ) self.__arrowItem.setGraphicsEffect(self.__shadow) self.__shadow.setEnabled(True) self.__autoAdjustGeometry = True def setAutoAdjustGeometry(self, autoAdjust): """ If set to `True` then the geometry will be adjusted whenever the arrow is changed with `setLine`. Otherwise the geometry of the item is only updated so the `line` lies within the `geometry()` rect (i.e. it only grows). True by default """ self.__autoAdjustGeometry = autoAdjust if autoAdjust: self.adjustGeometry() def autoAdjustGeometry(self): """ Should the geometry of the item be adjusted automatically when `setLine` is called. """ return self.__autoAdjustGeometry def setLine(self, line): """ Set the arrow base line (a `QLineF` in object coordinates). """ if self.__line != line: self.__line = line # local item coordinate system geom = self.geometry().translated(-self.pos()) if geom.isNull() and not line.isNull(): geom = QRectF(0, 0, 1, 1) arrow_shape = arrow_path_concave(line, self.lineWidth()) arrow_rect = arrow_shape.boundingRect() if not (geom.contains(arrow_rect)): geom = geom.united(arrow_rect) if self.__autoAdjustGeometry: # Shrink the geometry if required. geom = geom.intersected(arrow_rect) # topLeft can move changing the local coordinates. diff = geom.topLeft() line = QLineF(line.p1() - diff, line.p2() - diff) self.__arrowItem.setLine(line) self.__line = line # parent item coordinate system geom.translate(self.pos()) self.setGeometry(geom) def line(self): """ Return the arrow base line (`QLineF` in object coordinates). """ return QLineF(self.__line) def setColor(self, color): """ Set arrow brush color. """ if self.__color != color: self.__color = QColor(color) self.__updateBrush() def color(self): """ Return the arrow brush color. """ return QColor(self.__color) def setLineWidth(self, lineWidth): """ Set the arrow line width. """ self.__arrowItem.setLineWidth(lineWidth) def lineWidth(self): """ Return the arrow line width. """ return self.__arrowItem.lineWidth() def adjustGeometry(self): """ Adjust the widget geometry to exactly fit the arrow inside while preserving the arrow path scene geometry. """ # local system coordinate geom = self.geometry().translated(-self.pos()) line = self.__line arrow_rect = self.__arrowItem.shape().boundingRect() if geom.isNull() and not line.isNull(): geom = QRectF(0, 0, 1, 1) if not (geom.contains(arrow_rect)): geom = geom.united(arrow_rect) geom = geom.intersected(arrow_rect) diff = geom.topLeft() line = QLineF(line.p1() - diff, line.p2() - diff) geom.translate(self.pos()) self.setGeometry(geom) self.setLine(line) def shape(self): arrow_shape = self.__arrowItem.shape() return self.mapFromItem(self.__arrowItem, arrow_shape) def itemChange(self, change, value): if change == QGraphicsItem.ItemSelectedHasChanged: self.__updateBrush() return Annotation.itemChange(self, change, value) def __updateBrush(self): """ Update the arrow brush. """ if self.isSelected(): color = self.__color.darker(150) else: color = self.__color self.__arrowItem.setBrush(color)
def __addSimilarity(self, similarity, titleText): " Adds a similarity " # Label title = QLabel(titleText) title.setFont(self.__headerFont) self.__vLayout.addWidget(title) self.__widgets.append(title) # List of files simTable = QTreeWidget(self.bodyWidget) simTable.setAlternatingRowColors(True) simTable.setRootIsDecorated(False) simTable.setItemsExpandable(False) simTable.setSortingEnabled(False) simTable.setItemDelegate(NoOutlineHeightDelegate(4)) simTable.setUniformRowHeights(True) simTable.itemActivated.connect(self.__similarityActivated) simTable.setHeaderLabels(["File name", "Line"]) for item in similarity.files: values = [item[0], str(item[1])] simTable.addTopLevelItem(QTreeWidgetItem(values)) # Resizing simTable.header().resizeSections(QHeaderView.ResizeToContents) simTable.header().setStretchLastSection(True) # Height self.__setTableHeight(simTable) self.__vLayout.addWidget(simTable) self.__widgets.append(simTable) # The fragment itself if len(similarity.fragment) > 10: # Take first 9 lines text = "\n".join(similarity.fragment[:9]) + "\n ..." toolTip = "\n".join(similarity.fragment) else: text = "\n".join(similarity.fragment) toolTip = "" fragmentLabel = QLabel("<pre>" + self.__htmlEncode(text) + "</pre>") if toolTip != "": fragmentLabel.setToolTip("<pre>" + self.__htmlEncode(toolTip) + "</pre>") palette = fragmentLabel.palette() palette.setColor(QPalette.Background, QColor(250, 250, 175)) palette.setColor(QPalette.Foreground, QColor(0, 0, 0)) fragmentLabel.setPalette(palette) fragmentLabel.setFrameShape(QFrame.StyledPanel) fragmentLabel.setAutoFillBackground(True) labelFont = fragmentLabel.font() labelFont.setFamily(GlobalData().skin.baseMonoFontFace) fragmentLabel.setFont(labelFont) self.__vLayout.addWidget(fragmentLabel) self.__widgets.append(fragmentLabel) return
def def_pref(prm): prm["pref"] = {} prm["pref"]["general"] = {} #prm["pref"]["phones"] = {} prm["pref"]["sound"] = {} prm["pref"]["email"] = {} prm["pref"]["exp"] = {} prm["pref"]["interface"] = {} prm["pref"]["resp_box"] = {} prm["pref"]["appearance"] = {} prm["pref"]["general"]["triggerONOFF"] = False prm["pref"]["general"]["ONTrigger"] = 254 prm["pref"]["general"]["OFFTrigger"] = 253 prm["pref"]["general"]["triggerDur"] = 1 prm["pref"]["general"]["defaultISI"] = "500" prm["pref"]["general"]["preTrialSilence"] = "200" prm["pref"]["general"]["responseLightDuration"] = "500" prm["pref"]["general"]["maxRecursionDepth"] = sys.getrecursionlimit() prm["pref"]["general"]["startupCommand"] = "" prm["pref"]["general"]["showBlockProgBar"] = True prm["pref"]["general"]["endMessageFiles"] = [] prm["pref"]["general"]["endMessageFilesID"] = [] prm["pref"]["general"]["endMessageFilesUse"] = [] prm["pref"]["general"]["endMessageLevels"] = [] prm["pref"]["general"]["defaultShuffle"] = QApplication.translate( "", "Ask", "") prm["pref"]["general"]["defaultResponseMode"] = QApplication.translate( "", "Real Listener", "") prm["pref"]["general"]["listenerNameWarn"] = True prm["pref"]["general"]["sessionLabelWarn"] = True prm["pref"]["general"]["playEndMessage"] = False prm["pref"]["general"]["processResultsEnd"] = True prm["pref"]["interface"]["responseButtonSize"] = 20 prm['pref']["general"]['resFileFormat'] = 'fixed' prm['pref']["general"]['resFileFixedString'] = 'test.txt' prm['pref']["general"]["csvSeparator"] = ';' prm['pref']["general"]["fullFileSuffix"] = '_trial' prm['pref']["general"]["sessSummResFileSuffix"] = '_sess' prm['pref']["general"]["resTableFileSuffix"] = '_table' prm['pref']["general"]["automaticFileExtension"] = True prm["pref"]["general"]["nBlocksCustomCommand"] = "" prm["pref"]["general"]["atEndCustomCommand"] = "" prm["pref"]["general"]["dprimeCorrection"] = True prm["pref"]["general"]["precision"] = 12 # 'variable' prm["pref"]["email"]["notifyEnd"] = False prm["pref"]["email"]["nBlocksNotify"] = 1 prm["pref"]["email"]['sendData'] = False prm["pref"]["email"]['SMTPServer'] = 'localhost' prm["pref"]["email"]['SMTPServerPort'] = 25 prm["pref"]["email"]['SMTPServerSecurity'] = "TLS/SSL (a)" prm["pref"]["email"]["serverRequiresAuthentication"] = True prm["pref"]["email"]['fromUsername'] = '' if sys.version_info[0] == 2: #with python2.x there are problems here passwd = "" encoded_passwd = "" elif sys.version_info[0] == 3: passwd = bytes('default', 'utf-8') encoded_passwd = base64.b64encode(passwd) encoded_passwd = str(encoded_passwd, "utf-8") prm["pref"]["email"]['fromPassword'] = encoded_passwd prm['pref']['language'] = QApplication.translate("", "en", "") prm['pref']['country'] = QApplication.translate("", "US", "") prm['pref']['responseBoxLanguage'] = QApplication.translate("", "en", "") prm['pref']['responseBoxCountry'] = QApplication.translate("", "US", "") #Appearance #prm["pref"]["appearance"]["style"] = QApplication.translate("","Default","") #Sound preferences prm["pref"]["sound"]["defaultNBits"] = "32" prm["pref"]["sound"]["defaultSampleRate"] = "48000" prm["pref"]["sound"]["writewav"] = True prm["pref"]["sound"]["writeSndSeqSegments"] = False prm["pref"]["sound"]["wavmanager"] = "scipy" prm["pref"]["sound"]["bufferSize"] = 1024 prm["pref"]["sound"]["appendSilence"] = 0 if platform.system() == 'Windows': prm["pref"]["sound"]["playCommand"] = "winsound" prm["pref"]["sound"]["playCommandType"] = "winsound" elif platform.system() == 'Darwin': prm["pref"]["sound"]["playCommand"] = "afplay" prm["pref"]["sound"]["playCommandType"] = QApplication.translate( "", "custom", "") else: prm["pref"]["sound"]["playCommand"] = "aplay" prm["pref"]["sound"]["playCommandType"] = QApplication.translate( "", "custom", "") if alsaaudioAvailable == True: prm["pref"]["sound"]["alsaaudioDevice"] = "default" if pyaudioAvailable == True: prm["pref"]["sound"]["pyaudioDevice"] = 0 prm["pref"]["resp_box"]["responseBoxButtonFont"] = QFont( 'Sans Serif', 24, QFont.Bold, False).toString() prm["pref"]["resp_box"]["correctLightColor"] = QColor(0, 255, 0) prm["pref"]["resp_box"]["incorrectLightColor"] = QColor(255, 0, 0) prm["pref"]["resp_box"]["neutralLightColor"] = QColor(255, 255, 255) prm["pref"]["resp_box"]["offLightColor"] = QColor(0, 0, 0) prm["pref"]["resp_box"]["responseLightFont"] = QFont( 'Sans Serif', 20, QFont.Bold, False).toString() prm["pref"]["resp_box"][ "correctTextFeedback"] = "CORRECT" #QApplication.translate("","Yes","") #self.tr("CORRECT") prm["pref"]["resp_box"]["incorrectTextFeedback"] = "INCORRECT" prm["pref"]["resp_box"]["neutralTextFeedback"] = "DONE" prm["pref"]["resp_box"]["offTextFeedback"] = "" prm["pref"]["resp_box"]["correctTextColor"] = QColor(255, 255, 255) prm["pref"]["resp_box"]["incorrectTextColor"] = QColor(255, 255, 255) prm["pref"]["resp_box"]["neutralTextColor"] = QColor(255, 255, 255) prm["pref"]["resp_box"]["offTextColor"] = QColor(255, 255, 255) prm["pref"]["resp_box"]["correctTextFeedbackUserSet"] = False prm["pref"]["resp_box"]["incorrectTextFeedbackUserSet"] = False prm["pref"]["resp_box"]["neutralTextFeedbackUserSet"] = False prm["pref"]["resp_box"]["offTextFeedbackUserSet"] = False prm["pref"]["resp_box"]["userSetCorrectTextFeedback"] = "" prm["pref"]["resp_box"]["userSetIncorrectTextFeedback"] = "" prm["pref"]["resp_box"]["userSetNeutralTextFeedback"] = "" prm["pref"]["resp_box"]["userSetOffTextFeedback"] = "" #PHONES prm["phones"] = {} prm["phones"]["phonesChoices"] = ["Phones 1", "Phones 2"] prm["phones"]["phonesMaxLevel"] = [100, 100] prm["phones"]["phonesID"] = ['0', '1'] prm["phones"]["defaultPhones"] = ["\u2713", "\u2012"] #EXPERIMENTERS prm["experimenter"] = {} prm["experimenter"]["defaultExperimenter"] = ["\u2713", "\u2012"] prm["experimenter"]["experimenter_id"] = [ "Experimenter 1", "Experimenter 2" ] prm["experimenter"]["experimenter_name"] = ["", ""] prm["experimenter"]["experimenter_surname"] = ["", ""] prm["experimenter"]["experimenter_email"] = ["", ""] prm["experimenter"]["experimenter_address"] = ["", ""] prm["experimenter"]["experimenter_address2"] = ["", ""] prm["experimenter"]["experimenter_telephone"] = ["", ""] prm["experimenter"]["experimenter_mobile"] = ["", ""] prm["warningInterval"] = False prm["preTrialInterval"] = False prm["precursorInterval"] = False prm["postcursorInterval"] = False prm["intervalLights"] = QApplication.translate("", "Yes", "") return prm