def __init__(self, node): #QtGui.QGraphicsItem.__init__(self) GraphicsObject.__init__(self) #QObjectWorkaround.__init__(self) #self.shadow = QtGui.QGraphicsDropShadowEffect() #self.shadow.setOffset(5,5) #self.shadow.setBlurRadius(10) #self.setGraphicsEffect(self.shadow) self.pen = fn.mkPen(0,0,0) self.selectPen = fn.mkPen(200,200,200,width=2) self.brush = fn.mkBrush(200, 200, 200, 150) self.hoverBrush = fn.mkBrush(200, 200, 200, 200) self.selectBrush = fn.mkBrush(200, 200, 255, 200) self.hovered = False self.node = node flags = self.ItemIsMovable | self.ItemIsSelectable | self.ItemIsFocusable |self.ItemSendsGeometryChanges #flags = self.ItemIsFocusable |self.ItemSendsGeometryChanges self.setFlags(flags) self.bounds = QtCore.QRectF(0, 0, 100, 100) self.nameItem = QtGui.QGraphicsTextItem(self.node.name(), self) self.nameItem.setDefaultTextColor(QtGui.QColor(50, 50, 50)) self.nameItem.moveBy(self.bounds.width()/2. - self.nameItem.boundingRect().width()/2., 0) self.nameItem.setTextInteractionFlags(QtCore.Qt.TextEditorInteraction) self.updateTerminals() #self.setZValue(10) self.nameItem.focusOutEvent = self.labelFocusOut self.nameItem.keyPressEvent = self.labelKeyPress self.menu = None self.buildMenu()
def paint(self, p, *args): opts = self.opts if opts.get('antialias', True): p.setRenderHint(p.Antialiasing) if opts.get('fillLevel', None) is not None and opts.get('fillBrush', None) is not None: p.setBrush(fn.mkBrush(opts['fillBrush'])) p.setPen(fn.mkPen(None)) p.drawPolygon(QtGui.QPolygonF([ QtCore.QPointF(2, 18), QtCore.QPointF(18, 2), QtCore.QPointF(18, 18)])) if opts.get('pen', None) is not None: p.setPen(fn.mkPen(opts['pen'])) p.drawLine(2, 18, 18, 2) symbol = opts.get('symbol', None) if symbol is not None: pen = fn.mkPen(opts.get('symbolPen', None)) brush = fn.mkBrush(opts.get('symbolBrush', None)) size = opts.get('symbolSize', 10) p.translate(10,10) path = drawSymbol(p, symbol, size, pen, brush)
def process(self, In): kwargs = self.CW().prepareInputArguments() if kwargs['closed']: self.graphicsItem().setBrush(fn.mkBrush(self.closed_color)) return {'Out': None} else: self.graphicsItem().setBrush(fn.mkBrush(self.opened_color)) return {'Out': In}
def paintEvent(self, ev): QtGui.QPushButton.paintEvent(self, ev) p = QtGui.QPainter(self) rect = self.rect().adjusted(6, 6, -6, -6) ## draw white base, then texture for indicating transparency, then actual color p.setBrush(functions.mkBrush('w')) p.drawRect(rect) p.setBrush(QtGui.QBrush(QtCore.Qt.DiagCrossPattern)) p.drawRect(rect) p.setBrush(functions.mkBrush(self._color)) p.drawRect(rect) p.end()
def setBrush(self, *args, **kargs): if len(args) == 1 and (isinstance(args[0], np.ndarray) or isinstance(args[0], list)): brushes = args[0] if self.data is None: raise Exception("Must set data before setting multiple brushes.") if len(brushes) != len(self.data): raise Exception("Number of brushes does not match number of points (%d != %d)" % (len(brushes), len(self.data))) for i in xrange(len(brushes)): self.data[i]['brush'] = fn.mkBrush(brushes[i], **kargs) else: self.opts['brush'] = fn.mkBrush(*args, **kargs) self.updateSpots()
def setSymbolBrush(self, *args, **kargs): brush = fn.mkBrush(*args, **kargs) if self.opts['symbolBrush'] == brush: return self.opts['symbolBrush'] = brush #self.scatter.setSymbolBrush(brush) self.updateItems()
def hoverEvent(self, ev): if not ev.isExit() and ev.acceptDrags(QtCore.Qt.LeftButton): ev.acceptClicks(QtCore.Qt.LeftButton) ## we don't use the click, but we also don't want anyone else to use it. self.box.setBrush(fn.mkBrush('w')) else: self.box.setBrush(self.brush) self.update()
def __init__(self, parent=None, useOpenGL=None, background='k'): """Re-implementation of QGraphicsView that removes scrollbars and allows unambiguous control of the viewed coordinate range. Also automatically creates a QGraphicsScene and a central QGraphicsWidget that is automatically scaled to the full view geometry. By default, the view coordinate system matches the widget's pixel coordinates and automatically updates when the view is resized. This can be overridden by setting autoPixelRange=False. The exact visible range can be set with setRange(). The view can be panned using the middle mouse button and scaled using the right mouse button if enabled via enableMouse() (but ordinarily, we use ViewBox for this functionality).""" self.closed = False QtGui.QGraphicsView.__init__(self, parent) if useOpenGL is None: useOpenGL = pyqtgraph.getConfigOption('useOpenGL') self.useOpenGL(useOpenGL) self.setCacheMode(self.CacheBackground) if background is not None: brush = fn.mkBrush(background) self.setBackgroundBrush(brush) self.setFocusPolicy(QtCore.Qt.StrongFocus) self.setFrameShape(QtGui.QFrame.NoFrame) self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.setTransformationAnchor(QtGui.QGraphicsView.NoAnchor) self.setResizeAnchor(QtGui.QGraphicsView.AnchorViewCenter) self.setViewportUpdateMode(QtGui.QGraphicsView.MinimalViewportUpdate) #self.setSceneRect(QtCore.QRectF(-1e10, -1e10, 2e10, 2e10)) self.lockedViewports = [] self.lastMousePos = None self.setMouseTracking(True) self.aspectLocked = False #self.yInverted = True self.range = QtCore.QRectF(0, 0, 1, 1) self.autoPixelRange = True self.currentItem = None self.clearMouse() self.updateMatrix() self.sceneObj = GraphicsScene() self.setScene(self.sceneObj) ## by default we set up a central widget with a grid layout. ## this can be replaced if needed. self.centralWidget = None self.setCentralItem(QtGui.QGraphicsWidget()) self.centralLayout = QtGui.QGraphicsGridLayout() self.centralWidget.setLayout(self.centralLayout) self.mouseEnabled = False self.scaleCenter = False ## should scaling center around view center (True) or mouse click (False) self.clickAccepted = False
def __init__(self, **opts): """ Arrows can be initialized with any keyword arguments accepted by the setStyle() method. """ QtGui.QGraphicsPathItem.__init__(self, opts.get('parent', None)) if 'size' in opts: opts['headLen'] = opts['size'] if 'width' in opts: opts['headWidth'] = opts['width'] defOpts = { 'pxMode': True, 'angle': -150, ## If the angle is 0, the arrow points left 'pos': (0,0), 'headLen': 20, 'tipAngle': 25, 'baseAngle': 0, 'tailLen': None, 'tailWidth': 3, 'pen': (200,200,200), 'brush': (50,50,200), } defOpts.update(opts) self.setStyle(**defOpts) self.setPen(fn.mkPen(defOpts['pen'])) self.setBrush(fn.mkBrush(defOpts['brush'])) self.rotate(self.opts['angle']) self.moveBy(*self.opts['pos'])
def updateBackground(self): bg = self.state['background'] if bg is None: self.background.hide() else: self.background.show() self.background.setBrush(fn.mkBrush(bg))
def __init__(self, size, width=5, color=(100, 100, 255)): UIGraphicsItem.__init__(self) self.setAcceptedMouseButtons(QtCore.Qt.NoButton) self.brush = fn.mkBrush(color) self.pen = fn.mkPen((0,0,0)) self._width = width self.size = size
def buildAtlas(self): # get rendered array for all symbols, keep track of avg/max width rendered = {} avgWidth = 0.0 maxWidth = 0 images = [] for key, coords in self.symbolMap.items(): if len(coords) == 0: pen = fn.mkPen(color=key[2], width=key[3], style=key[4]) brush = fn.mkBrush(color=key[5]) img = renderSymbol(key[0], key[1], pen, brush) images.append(img) ## we only need this to prevent the images being garbage collected immediately arr = fn.imageToArray(img, copy=False, transpose=False) else: (x,y,w,h) = self.symbolMap[key] arr = self.atlasData[x:x+w, y:y+w] rendered[key] = arr w = arr.shape[0] avgWidth += w maxWidth = max(maxWidth, w) nSymbols = len(rendered) if nSymbols > 0: avgWidth /= nSymbols width = max(maxWidth, avgWidth * (nSymbols**0.5)) else: avgWidth = 0 width = 0 # sort symbols by height symbols = sorted(rendered.keys(), key=lambda x: rendered[x].shape[1], reverse=True) self.atlasRows = [] x = width y = 0 rowheight = 0 for key in symbols: arr = rendered[key] w,h = arr.shape[:2] if x+w > width: y += rowheight x = 0 rowheight = h self.atlasRows.append([y, rowheight, 0]) self.symbolMap[key][:] = x, y, w, h x += w self.atlasRows[-1][2] = x height = y + rowheight self.atlasData = np.zeros((width, height, 4), dtype=np.ubyte) for key in symbols: x, y, w, h = self.symbolMap[key] self.atlasData[x:x+w, y:y+h] = rendered[key] self.atlas = None self.atlasValid = True
def setBackground(self, background): """ Set the background color of the GraphicsView. To use the defaults specified py pyqtgraph.setConfigOption, use background='default'. To make the background transparent, use background=None. """ self._background = background if background == 'default': background = pyqtgraph.getConfigOption('background') brush = fn.mkBrush(background) self.setBackgroundBrush(brush)
def __init__(self, name, parent=None): terms = {'coord': {'io': 'in'}, 'data': {'io': 'in'}, 'this': {'io': 'out'}, 'All': {'io': 'out'}} super(hydraulicGradientNode, self).__init__(name, terminals=terms) self.graphicsItem().setBrush(fn.mkBrush(250, 250, 150, 150)) self._ctrlWidget = hydraulicGradientNodeCtrlWidget(self) self._coords_id = None
def __init__(self, term, parent=None): self.term = term GraphicsObject.__init__(self, parent) self.brush = fn.mkBrush(0, 0, 0) self.box = QtGui.QGraphicsRectItem(0, 0, 10, 10, self) self.label = QtGui.QGraphicsTextItem(self.term.name(), self) self.label.scale(0.7, 0.7) self.newConnection = None self.setFiltersChildEvents( True) # to pick up mouse events on the rectitem self.setZValue(1) self.menu = None
def setMouseHover(self, hover): ## Inform the item that the mouse is(not) hovering over it if self.mouseHovering == hover: return self.mouseHovering = hover if hover: c = self.brush.color() c.setAlpha(c.alpha() * 2) self.currentBrush = fn.mkBrush(c) else: self.currentBrush = self.brush self.update()
def setMouseHover(self, hover): # Inform the item that the mouse is(not) hovering over it if self.mouseHovering == hover: return self.mouseHovering = hover if hover: c = self.brush.color() c.setAlpha(c.alpha() * 1) self.currentBrush = fn.mkBrush(c) else: self.currentBrush = self.brush self.update()
def display(self, topics, terms, addr, win, **kwargs): super().display(topics, terms, addr, win, ScatterWidget, **kwargs) if self.widget: self.roi = pg.LinearRegionItem( (self.values['origin'], self.values['extent']), swapMode='sort', brush=fn.mkBrush(255, 0, 0, 100)) self.widget.plot_view.addItem(self.roi) self.roi.sigRegionChangeFinished.connect(self.set_values) return self.widget
def __init__(self, name, color=(200, 200, 200, 150), ui=None, parent=None, **kwargs): self._parent = parent kwargs['terminals'] = kwargs.get('terminals', {'In': {'io': 'in'}, 'Out': {'io': 'out'}}) super(NodeWithCtrlWidget, self).__init__(name, **kwargs) logger.debug("about to create node [{0}] of type [{1}]".format(self.name(), self.nodeName)) self._init_at_first() self.graphicsItem().setBrush(fn.mkBrush(color)) if ui is None: ui = getattr(self, 'uiTemplate', []) self._ctrlWidget = self._createCtrlWidget(parent=self, ui=ui) logger.info("node [{0}] of type [{1}] created".format(self.name(), self.nodeName))
def paint(self, p, *args): # p.setBrush(QtGui.QBrush()) # p.setPen(fn.mkPen('r')) # p.drawRect(self.boundingRect()) # p.setRenderHint(p.Antialiasing) # only if the data is antialiased. opts = self.item.opts if opts.get('fillLevel', None) is not None and opts.get('fillBrush', None) is not None: p.setBrush(fn.mkBrush(opts['fillBrush'])) p.setPen(fn.mkPen(None)) p.drawPolygon( QtGui.QPolygonF([ QtCore.QPointF(2, 18), QtCore.QPointF(18, 2), QtCore.QPointF(18, 18) ])) if not isinstance(self.item, ScatterPlotItem): p.setPen(fn.mkPen(opts['pen'])) p.drawLine(2, 18, 18, 2) symbol = opts.get('symbol', None) if symbol is not None: if isinstance(self.item, PlotDataItem): opts = self.item.scatter.opts pen = fn.mkPen(opts['pen']) brush = fn.mkBrush(opts['brush']) size = opts['size'] size = int(3 * size / 4) # save and reset to undo the forced resize that # drawSymbol causes p.save() p.translate(2, 18) path = drawSymbol(p, symbol, size, pen, brush) p.restore() p.translate(18, 2) path = drawSymbol(p, symbol, size, pen, brush)
def qgo_draw_markers( markers: list, color: Color, p: QtGui.QPainter, left: float, right: float, right_offset: float, ) -> float: """Paint markers in ``pg.GraphicsItem`` style by first removing the view transform for the painter, drawing the markers in scene coords, then restoring the view coords. """ # paint markers in native coordinate system orig_tr = p.transform() start = orig_tr.map(Point(left, 0)) end = orig_tr.map(Point(right, 0)) up = orig_tr.map(Point(left, 1)) dif = end - start # length = Point(dif).length() angle = np.arctan2(dif.y(), dif.x()) * 180 / np.pi p.resetTransform() p.translate(start) p.rotate(angle) up = up - start det = up.x() * dif.y() - dif.x() * up.y() p.scale(1, 1 if det > 0 else -1) p.setBrush(fn.mkBrush(color)) # p.setBrush(fn.mkBrush(self.currentPen.color())) tr = p.transform() sizes = [] for path, pos, size in markers: p.setTransform(tr) # XXX: we drop the "scale / %" placement # x = length * pos x = right_offset p.translate(x, 0) p.scale(size, size) p.drawPath(path) sizes.append(size) p.setTransform(orig_tr) return max(sizes)
def __init__(self, node, brush=None): super().__init__() self.pen = fn.mkPen(0, 0, 0) self.selectPen = fn.mkPen(200, 200, 200, width=2) if brush: self.brush = brush else: self.brush = fn.mkBrush(255, 255, 255, 255) self.hoverBrush = fn.mkBrush(200, 200, 200, 200) self.selectBrush = fn.mkBrush(200, 200, 255, 200) self.hovered = False self.node = node flags = self.ItemIsMovable | self.ItemIsSelectable | self.ItemSendsGeometryChanges self.setFlags(flags) self.bounds = QtCore.QRectF(0, 0, 100, 100) self.nameItem = QtGui.QGraphicsTextItem(self.node.name(), self) self.nameItem.setDefaultTextColor(QtGui.QColor(50, 50, 50)) self.nameItem.moveBy( self.bounds.width() / 2. - self.nameItem.boundingRect().width() / 2., 0) self.updateTerminals() self.menu = None self.connectedTo = None self.enabled = QtGui.QAction("Enabled", self.menu, checkable=True, checked=True) self.optional = QtGui.QAction("Optional Inputs", self.menu, checkable=True, checked=False) self.buildMenu()
def __init__(self, name, parent=None): super(QuickViewNode, self).__init__(name, terminals={'In': {'io': 'in'}}) self.graphicsItem().setBrush(fn.mkBrush(150, 150, 250, 200)) self._pandasDataModel = PandasDataModel(parent=self) self._pandasHeaderModel = PandasHeaderModel(parent=self) self._ctrlWidget = QuickViewCtrlWidget(self) # connect show/hide signals self._pandasHeaderModel.row_hidden.connect(self._ctrlWidget.tableView.horizontalHeader().hideSection) #argumnent [int] self._pandasHeaderModel.row_showed.connect(self._ctrlWidget.tableView.horizontalHeader().showSection) #argumnent [int] self._pandasDataModel.modelReset.connect(self._ctrlWidget.update) #no argument self._id = None
def setBackground(self, background): """ Set the background color of the GraphicsView. To use the defaults specified py pyqtgraph.setConfigOption, use background='default'. To make the background transparent, use background=None. """ self._background = background if background == 'default': background = pyqtgraph.getConfigOption('background') if background is None: self.setBackgroundRole(QtGui.QPalette.NoRole) else: brush = fn.mkBrush(background) self.setBackgroundBrush(brush)
def setBackground(self, background): """ Set the background color of the GraphicsView. To use the defaults specified py pyqtgraph.setConfigOption, use background='default'. To make the background transparent, use background=None. """ self._background = background if background == "default": background = pyqtgraph.getConfigOption("background") if background is None: self.setBackgroundRole(QtGui.QPalette.NoRole) else: brush = fn.mkBrush(background) self.setBackgroundBrush(brush)
def mkSpot(self, pos, size, pxMode, brush, pen, data, symbol=None, index=None): ## Make and return a SpotItem (or PixmapSpotItem if in pxMode) brush = fn.mkBrush(brush) pen = fn.mkPen(pen) if pxMode: img = self.spotPixmap() ## returns None if not using identical mode #item = PixmapSpotItem(size, brush, pen, data, image=img, symbol=symbol, index=index) item = SpotItem(size, pxMode, brush, pen, data, symbol=symbol, image=img, index=index) else: item = SpotItem(size, pxMode, brush, pen, data, symbol=symbol, index=index) item.setParentItem(self) item.setPos(pos) #item.sigClicked.connect(self.pointClicked) return item
def __init__(self, node): #QtGui.QGraphicsItem.__init__(self) GraphicsObject.__init__(self) #QObjectWorkaround.__init__(self) #self.shadow = QtGui.QGraphicsDropShadowEffect() #self.shadow.setOffset(5,5) #self.shadow.setBlurRadius(10) #self.setGraphicsEffect(self.shadow) self.pen = fn.mkPen(0, 0, 0) self.selectPen = fn.mkPen(200, 200, 200, width=2) self.brush = fn.mkBrush(200, 200, 200, 150) self.hoverBrush = fn.mkBrush(200, 200, 200, 200) self.selectBrush = fn.mkBrush(200, 200, 255, 200) self.hovered = False self.node = node flags = self.ItemIsMovable | self.ItemIsSelectable | self.ItemIsFocusable | self.ItemSendsGeometryChanges #flags = self.ItemIsFocusable |self.ItemSendsGeometryChanges self.setFlags(flags) self.bounds = QtCore.QRectF(0, 0, 100, 100) self.nameItem = QtGui.QGraphicsTextItem(self.node.name(), self) self.nameItem.setDefaultTextColor(QtGui.QColor(50, 50, 50)) self.nameItem.moveBy( self.bounds.width() / 2. - self.nameItem.boundingRect().width() / 2., 0) self.nameItem.setTextInteractionFlags(QtCore.Qt.TextEditorInteraction) self.updateTerminals() #self.setZValue(10) self.nameItem.focusOutEvent = self.labelFocusOut self.nameItem.keyPressEvent = self.labelKeyPress self.menu = None self.buildMenu()
def getSpotOpts(self, recs, scale=1.0): if recs.ndim == 0: rec = recs symbol = rec['symbol'] if symbol is None: symbol = self.opts['symbol'] size = rec['size'] if size < 0: size = self.opts['size'] pen = rec['pen'] if pen is None: pen = self.opts['pen'] brush = rec['brush'] if brush is None: brush = self.opts['brush'] return (symbol, size*scale, fn.mkPen(pen), fn.mkBrush(brush)) else: recs = recs.copy() recs['symbol'][np.equal(recs['symbol'], None)] = self.opts['symbol'] recs['size'][np.equal(recs['size'], -1)] = self.opts['size'] recs['size'] *= scale recs['pen'][np.equal(recs['pen'], None)] = fn.mkPen(self.opts['pen']) recs['brush'][np.equal(recs['brush'], None)] = fn.mkBrush(self.opts['brush']) return recs
def paint(self, p, *args): #p.setRenderHint(p.Antialiasing) # only if the data is antialiased. opts = self.item.opts if opts.get('fillLevel',None) is not None and opts.get('fillBrush',None) is not None: p.setBrush(fn.mkBrush(opts['fillBrush'])) p.setPen(fn.mkPen(None)) p.drawPolygon(QtGui.QPolygonF([QtCore.QPointF(2,18), QtCore.QPointF(18,2), QtCore.QPointF(18,18)])) if not isinstance(self.item, ScatterPlotItem): p.setPen(fn.mkPen(opts['pen'])) p.drawLine(2, 10, 18, 10) symbol = opts.get('symbol', None) if symbol is not None: if isinstance(self.item, PlotDataItem): opts = self.item.scatter.opts pen = fn.mkPen(opts['pen']) brush = fn.mkBrush(opts['brush']) size = opts['size'] p.translate(10,10) path = drawSymbol(p, symbol, size, pen, brush)
def plot_complex_event(self, complex_event, line_color=None, brush_color=None,with_text=True): '''Plots a single event''' name = complex_event['name'] start = complex_event['start'] / self.scaling_factor stop = complex_event['stop'] / self.scaling_factor region = labelRegion(name, start, stop, parent=self) if line_color is not None: for line,color in zip(region.lines,line_color): line.setPen(fn.mkPen(color)) if brush_color is not None: region.setBrush(fn.mkBrush(brush_color)) return region
def __init__(self, term, parent=None): self.term = term #QtGui.QGraphicsItem.__init__(self, parent) GraphicsObject.__init__(self, parent) self.brush = fn.mkBrush(0,0,0) self.box = QtGui.QGraphicsRectItem(0, 0, 10, 10, self) self.label = QtGui.QGraphicsTextItem(self.term.name(), self) self.label.scale(0.7, 0.7) #self.setAcceptHoverEvents(True) self.newConnection = None self.setFiltersChildEvents(True) ## to pick up mouse events on the rectitem if self.term.isRenamable(): self.label.setTextInteractionFlags(QtCore.Qt.TextEditorInteraction) self.label.focusOutEvent = self.labelFocusOut self.label.keyPressEvent = self.labelKeyPress self.setZValue(1) self.menu = None
def add_marker( self, path: QtWidgets.QGraphicsPathItem, ) -> QtWidgets.QGraphicsPathItem: self._marker = path self._marker.setPen(self.currentPen) self._marker.setBrush(fn.mkBrush(self.currentPen.color())) # add path to scene self.getViewBox().scene().addItem(path) # place to just-left of L1 labels rsc = self._chart.pre_l1_xs()[0] path.setPos(QPointF(rsc, self.scene_y())) return path
def __init__(self, pen='l', brush='s', symbol='o', size=7): self.size = size self.symbol = symbol if isinstance(pen, QtGui.QPen): self.pen = pen else: self.pen = fn.mkPen(pen) if isinstance(brush, QtGui.QBrush): self.brush = brush else: self.brush = fn.mkBrush(brush) self.pixmap = QtGui.QPixmap( renderSymbol(self.symbol, self.size, self.pen, self.brush)) self.width = self.pixmap.width()
def __init__(self, term, parent=None): self.term = term #QtGui.QGraphicsItem.__init__(self, parent) GraphicsObject.__init__(self, parent) self.brush = fn.mkBrush(0, 0, 0) self.box = QtGui.QGraphicsRectItem(0, 0, 10, 10, self) self.label = QtGui.QGraphicsTextItem(self.term.name(), self) self.label.scale(0.7, 0.7) #self.setAcceptHoverEvents(True) self.newConnection = None self.setFiltersChildEvents( True) ## to pick up mouse events on the rectitem if self.term.isRenamable(): self.label.setTextInteractionFlags(QtCore.Qt.TextEditorInteraction) self.label.focusOutEvent = self.labelFocusOut self.label.keyPressEvent = self.labelKeyPress self.setZValue(1) self.menu = None
def setStyle(self, **opts): self.opts.update(opts) opt = dict([ (k, self.opts[k]) for k in ['headLen', 'tipAngle', 'baseAngle', 'tailLen', 'tailWidth'] ]) self.path = makeArrowPath(opt['headLen'], opt['tipAngle'], opt['tailLen'], opt['tailWidth']) self.setPath(self.path) self.setPen(fn.mkPen(self.opts['pen'])) self.setBrush(fn.mkBrush(self.opts['brush'])) if self.opts['pxMode']: self.setFlags(self.flags() | self.ItemIgnoresTransformations) else: self.setFlags(self.flags() & ~self.ItemIgnoresTransformations)
def setStyle(self, **opts): """ Changes the appearance of the arrow. All arguments are optional: ====================== ================================================= **Keyword Arguments:** angle Orientation of the arrow in degrees. Default is 0; arrow pointing to the left. headLen Length of the arrow head, from tip to base. default=20 headWidth Width of the arrow head at its base. tipAngle Angle of the tip of the arrow in degrees. Smaller values make a 'sharper' arrow. If tipAngle is specified, ot overrides headWidth. default=25 baseAngle Angle of the base of the arrow head. Default is 0, which means that the base of the arrow head is perpendicular to the arrow tail. tailLen Length of the arrow tail, measured from the base of the arrow head to the end of the tail. If this value is None, no tail will be drawn. default=None tailWidth Width of the tail. default=3 pen The pen used to draw the outline of the arrow. brush The brush used to fill the arrow. ====================== ================================================= """ self.opts.update(opts) opt = dict([(k,self.opts[k]) for k in ['headLen', 'tipAngle', 'baseAngle', 'tailLen', 'tailWidth']]) tr = QtGui.QTransform() tr.rotate(self.opts['angle']) self.path = tr.map(fn.makeArrowPath(**opt)) self.setPath(self.path) self.setPen(fn.mkPen(self.opts['pen'])) self.setBrush(fn.mkBrush(self.opts['brush'])) if self.opts['pxMode']: self.setFlags(self.flags() | self.ItemIgnoresTransformations) else: self.setFlags(self.flags() & ~self.ItemIgnoresTransformations)
def __init__( self, viewbox: ViewBox, color: str = 'dad_blue', ) -> None: super().__init__(0, 0, 1, 1) # self.rbScaleBox = QtGui.QGraphicsRectItem(0, 0, 1, 1) self.vb = viewbox self._chart: 'ChartPlotWidget' = None # noqa # override selection box color color = QtGui.QColor(hcolor(color)) self.setPen(fn.mkPen(color, width=1)) color.setAlpha(66) self.setBrush(fn.mkBrush(color)) self.setZValue(1e9) self.hide() self._label = None label = self._label = QtGui.QLabel() label.setTextFormat(0) # markdown label.setFont(_font.font) label.setMargin(0) label.setAlignment( QtCore.Qt.AlignLeft # | QtCore.Qt.AlignVCenter ) # proxy is created after containing scene is initialized self._label_proxy = None self._abs_top_right = None # TODO: "swing %" might be handy here (data's max/min # % change) self._contents = [ 'change: {pchng:.2f} %', 'range: {rng:.2f}', 'bars: {nbars}', 'max: {dmx}', 'min: {dmn}', # 'time: {nbars}m', # TODO: compute this per bar size 'sigma: {std:.2f}', ]
def getArrayRegion(self, data, img, axes=(0,1), returnMappedCoords=False, **kwds): sl = self.getArraySlice(data, img, axes=(0,1)) if sl is None: return None sliced = data[sl[0]] im = QtGui.QImage(sliced.shape[axes[0]], sliced.shape[axes[1]], QtGui.QImage.Format_ARGB32) im.fill(0x0) p = QtGui.QPainter(im) p.setPen(fn.mkPen(None)) p.setBrush(fn.mkBrush('w')) p.setTransform(self.itemTransform(img)[0]) bounds = self.mapRectToItem(img, self.boundingRect()) p.translate(-bounds.left(), -bounds.top()) p.drawPath(self.shape()) p.end() mask = imageToArray(im)[:,:,0].astype(float) / 255. shape = [1] * data.ndim shape[axes[0]] = sliced.shape[axes[0]] shape[axes[1]] = sliced.shape[axes[1]] return sliced * mask.reshape(shape)
def __init__(self, size, width=5, brush=None, pen=None, suffix='m'): GraphicsObject.__init__(self) GraphicsWidgetAnchor.__init__(self) self.setFlag(self.ItemHasNoContents) self.setAcceptedMouseButtons(QtCore.Qt.NoButton) if brush is None: brush = pg.getConfigOption('foreground') self.brush = fn.mkBrush(brush) self.pen = fn.mkPen(pen) self._width = width self.size = size self.bar = QtGui.QGraphicsRectItem() self.bar.setPen(self.pen) self.bar.setBrush(self.brush) self.bar.setParentItem(self) self.text = TextItem(text=fn.siFormat(size, suffix=suffix), anchor=(0.5,1)) self.text.setParentItem(self)
def setStyle(self, **opts): # http://www.pyqtgraph.org/documentation/_modules/pyqtgraph/graphicsItems/ArrowItem.html#ArrowItem.setStyle self.opts.update(opts) opt = dict([(k,self.opts[k]) for k in ['headLen', 'tipAngle', 'baseAngle', 'tailLen', 'tailWidth']]) tr = QtGui.QTransform() path = fn.makeArrowPath(**opt) tr.rotate(self.opts['angle']) p = -path.boundingRect().center() tr.translate(p.x(), p.y()) self.path = tr.map(path) self.setPath(self.path) self.setPen(fn.mkPen(self.opts['pen'])) self.setBrush(fn.mkBrush(self.opts['brush'])) if self.opts['pxMode']: self.setFlags(self.flags() | self.ItemIgnoresTransformations) else: self.setFlags(self.flags() & ~self.ItemIgnoresTransformations)
def __init__(self, name, parent=None): super(QuickViewNode, self).__init__(name, terminals={'In': { 'io': 'in' }}) self.graphicsItem().setBrush(fn.mkBrush(150, 150, 250, 200)) self._pandasDataModel = PandasDataModel(parent=self) self._pandasHeaderModel = PandasHeaderModel(parent=self) self._ctrlWidget = QuickViewCtrlWidget(self) # connect show/hide signals self._pandasHeaderModel.row_hidden.connect( self._ctrlWidget.tableView.horizontalHeader( ).hideSection) #argumnent [int] self._pandasHeaderModel.row_showed.connect( self._ctrlWidget.tableView.horizontalHeader( ).showSection) #argumnent [int] self._pandasDataModel.modelReset.connect( self._ctrlWidget.update) #no argument self._id = None
def paint(self, p, *args): opts = self.item.opts if opts['antialias']: p.setRenderHint(p.Antialiasing) if not isinstance(self.item, ScatterPlotItem): p.setPen(fn.mkPen(opts['pen'])) p.drawLine(-7, 11, 7, 11) symbol = opts.get('symbol', None) if symbol is not None: if isinstance(self.item, PlotDataItem): opts = self.item.scatter.opts pen = fn.mkPen(opts['pen']) brush = fn.mkBrush(opts['brush']) size = opts['size'] p.translate(10, 10) path = drawSymbol(p, symbol, size, pen, brush)
def getSymbolCoords(self, opts): """ Given a list of spot records, return an object representing the coordinates of that symbol within the atlas """ coords = np.empty(len(opts), dtype=object) for i, rec in enumerate(opts): symbol, size, pen, brush = rec['symbol'], rec['size'], rec['pen'], rec['brush'] pen = fn.mkPen(pen) if not isinstance(pen, QtGui.QPen) else pen brush = fn.mkBrush(brush) if not isinstance(pen, QtGui.QBrush) else brush key = (symbol, size, fn.colorTuple(pen.color()), pen.widthF(), pen.style(), fn.colorTuple(brush.color())) if key not in self.symbolMap: newCoords = SymbolAtlas.SymbolCoords() self.symbolMap[key] = newCoords self.atlasValid = False #try: #self.addToAtlas(key) ## squeeze this into the atlas if there is room #except: #self.buildAtlas() ## otherwise, we need to rebuild coords[i] = self.symbolMap[key] return coords
def __init__(self, name, parent=None): terms = { 'coord': { 'io': 'in' }, 'data': { 'io': 'in' }, 'this': { 'io': 'out' }, 'All': { 'io': 'out' } } super(hydraulicGradientNode, self).__init__(name, terminals=terms) self.graphicsItem().setBrush(fn.mkBrush(250, 250, 150, 150)) self._ctrlWidget = hydraulicGradientNodeCtrlWidget(self) self._coords_id = None
def getSymbolCoords(self, opts): """ Given a list of spot records, return an object representing the coordinates of that symbol within the atlas """ coords = np.empty(len(opts), dtype=object) for i, rec in enumerate(opts): symbol, size, pen, brush = rec['symbol'], rec['size'], rec['pen'], rec['brush'] pen = fn.mkPen(pen) if not isinstance(pen, QtGui.QPen) else pen brush = fn.mkBrush(brush) if not isinstance(pen, QtGui.QBrush) else brush key = (symbol, size, fn.colorTuple(pen.color()), pen.width(), pen.style(), fn.colorTuple(brush.color())) if key not in self.symbolMap: newCoords = SymbolAtlas.SymbolCoords() self.symbolMap[key] = newCoords self.atlasValid = False #try: #self.addToAtlas(key) ## squeeze this into the atlas if there is room #except: #self.buildAtlas() ## otherwise, we need to rebuild coords[i] = self.symbolMap[key] return coords
def __init__(self, x, y, line_colour, brush=None, hoverBrush=None): pg.GraphicsObject.__init__(self) self.blockLineSignal = False self.moving = False self.mouseHovering = False self._boundingRectCache = None penBase = pg.mkPen(line_colour) h, s, v = penBase.color().hue(), penBase.color().saturation( ), penBase.color().value() invcol = [((h + 128) % 255) / 255.0, s / 255.0, v / 255.0] # lineKwds = dict( movable=True, pen=penBase, hoverPen=pg.mkPen(QtGui.QColor.fromHsvF(*invcol)), ) self.lines = [ pg.InfiniteLine(QtCore.QPointF(x, 0), angle=90, **lineKwds), pg.InfiniteLine(QtCore.QPointF(0, y), angle=0, **lineKwds) ] # for l in self.lines: l.setParentItem(self) l.sigPositionChangeFinished.connect(self.lineMoveFinished) self.lines[0].sigPositionChanged.connect(self._line0Moved) self.lines[1].sigPositionChanged.connect(self._line1Moved) if brush is None: brush = QtGui.QBrush(QtGui.QColor(0, 0, 255, 50)) self.setBrush(brush) if hoverBrush is None: c = self.brush.color() c.setAlpha(min(c.alpha() * 2, 255)) hoverBrush = fn.mkBrush(c) self.setHoverBrush(hoverBrush) self.setAcceptHoverEvents(True)
def setBrush(self, *args, **kargs): """Set the brush(es) used to fill the interior of each spot. If a list or array is provided, then the brush for each spot will be set separately. Otherwise, the arguments are passed to pg.mkBrush and used as the default brush for all spots which do not have a brush explicitly set.""" update = kargs.pop('update', True) dataSet = kargs.pop('dataSet', self.data) if len(args) == 1 and (isinstance(args[0], np.ndarray) or isinstance(args[0], list)): brushes = args[0] if len(brushes) != len(dataSet): raise Exception("Number of brushes does not match number of points (%d != %d)" % (len(brushes), len(dataSet))) #for i in xrange(len(brushes)): #self.data[i]['brush'] = fn.mkBrush(brushes[i], **kargs) dataSet['brush'] = brushes else: self.opts['brush'] = fn.mkBrush(*args, **kargs) #self._spotPixmap = None dataSet['fragCoords'] = None if update: self.updateSpots(dataSet)
def getArrayRegion(self, data, img, axes=(0,1), returnMappedCoords=False, **kwds): import pyqtgraph.functions as fn sl = self.getArraySlice(data, img, axes=(0,1)) if sl is None: return None sliced = data[sl[0]] im = QtGui.QImage(sliced.shape[axes[0]], sliced.shape[axes[1]], QtGui.QImage.Format_ARGB32) im.fill(0x0) p = QtGui.QPainter(im) p.setPen(fn.mkPen(None)) p.setBrush(fn.mkBrush('w')) p.setTransform(self.itemTransform(img)[0]) bounds = self.mapRectToItem(img, self.boundingRect()) p.translate(-bounds.left(), -bounds.top()) p.drawPath(self.shape()) p.end() mask = fn.imageToArray(im)[:,:,0].astype(float) / 255. shape = [1] * data.ndim shape[axes[0]] = sliced.shape[axes[0]] shape[axes[1]] = sliced.shape[axes[1]] return sliced, mask.reshape(shape)
def __init__(self, **opts): QtGui.QGraphicsPolygonItem.__init__(self, opts.get('parent', None)) defOpts = { 'style': 'tri', 'pxMode': True, 'size': 20, 'angle': -150, ## If the angle is 0, the arrow points left 'pos': (0,0), 'width': None, ## width is automatically size / 2. 'tipAngle': 25, 'baseAngle': 90, 'pen': (200,200,200), 'brush': (50,50,200), } defOpts.update(opts) self.setStyle(**defOpts) self.setPen(fn.mkPen(defOpts['pen'])) self.setBrush(fn.mkBrush(defOpts['brush'])) self.rotate(self.opts['angle']) self.moveBy(*self.opts['pos'])
def setBrush(self, *args, **kargs): """Set the brush(es) used to fill the interior of each spot. If a list or array is provided, then the brush for each spot will be set separately. Otherwise, the arguments are passed to pg.mkBrush and used as the default brush for all spots which do not have a brush explicitly set.""" update = kargs.pop('update', True) dataSet = kargs.pop('dataSet', self.data) if len(args) == 1 and (isinstance(args[0], np.ndarray) or isinstance(args[0], list)): brushes = args[0] if kargs['mask'] is not None: brushes = brushes[kargs['mask']] if len(brushes) != len(dataSet): raise Exception("Number of brushes does not match number of points (%d != %d)" % (len(brushes), len(dataSet))) #for i in xrange(len(brushes)): #self.data[i]['brush'] = fn.mkBrush(brushes[i], **kargs) dataSet['brush'] = brushes else: self.opts['brush'] = fn.mkBrush(*args, **kargs) #self._spotPixmap = None dataSet['fragCoords'] = None if update: self.updateSpots(dataSet)
def paint(self, p, *args): profile = debug.Profiler() if self.image is None: return if self.qimage is None: self.render() if self.qimage is None: return profile('render QImage') if self.paintMode is not None: p.setCompositionMode(self.paintMode) profile('set comp mode') self.setTransform(self.dataTransform()) for pol, color in zip(self.qimage['polygons'], self.qimage['values']): p.setPen(fn.mkPen(255, 255, 255, 100, width=0.75)) p.setBrush(fn.mkBrush(*color)) p.drawPolygon(pol) profile('p.drawImage') if self.border is not None: p.setPen(self.border) p.drawRect(self.boundingRect())
def updatePlot(self): self.plot.clear() if self.data is None: return if self.filtered is None: self.filtered = self.filter.filterData(self.data) data = self.filtered if len(data) == 0: return colors = np.array([fn.mkBrush(*x) for x in self.colorMap.map(data)]) style = self.style.copy() ## Look up selected columns and units sel = list([str(item.text()) for item in self.fieldList.selectedItems()]) units = list([item.opts.get('units', '') for item in self.fieldList.selectedItems()]) if len(sel) == 0: self.plot.setTitle('') return if len(sel) == 1: self.plot.setLabels(left=('N', ''), bottom=(sel[0], units[0]), title='') if len(data) == 0: return x = data[sel[0]] #if x.dtype.kind == 'f': #mask = ~np.isnan(x) #else: #mask = np.ones(len(x), dtype=bool) #x = x[mask] #style['symbolBrush'] = colors[mask] y = None elif len(sel) == 2: self.plot.setLabels(left=(sel[1],units[1]), bottom=(sel[0],units[0])) if len(data) == 0: return xydata = [] for ax in [0,1]: d = data[sel[ax]] ## scatter catecorical values just a bit so they show up better in the scatter plot. #if sel[ax] in ['MorphologyBSMean', 'MorphologyTDMean', 'FIType']: #d += np.random.normal(size=len(cells), scale=0.1) xydata.append(d) x,y = xydata #mask = np.ones(len(x), dtype=bool) #if x.dtype.kind == 'f': #mask |= ~np.isnan(x) #if y.dtype.kind == 'f': #mask |= ~np.isnan(y) #x = x[mask] #y = y[mask] #style['symbolBrush'] = colors[mask] ## convert enum-type fields to float, set axis labels xy = [x,y] for i in [0,1]: axis = self.plot.getAxis(['bottom', 'left'][i]) if xy[i] is not None and xy[i].dtype.kind in ('S', 'O'): vals = self.fields[sel[i]].get('values', list(set(xy[i]))) xy[i] = np.array([vals.index(x) if x in vals else None for x in xy[i]], dtype=float) axis.setTicks([list(enumerate(vals))]) else: axis.setTicks(None) # reset to automatic ticking x,y = xy ## mask out any nan values mask = np.ones(len(x), dtype=bool) if x.dtype.kind == 'f': mask &= ~np.isnan(x) if y is not None and y.dtype.kind == 'f': mask &= ~np.isnan(y) x = x[mask] style['symbolBrush'] = colors[mask] ## Scatter y-values for a histogram-like appearance if y is None: y = fn.pseudoScatter(x) else: y = y[mask] self.plot.plot(x, y, **style)
def setBrush(self, *args, **kargs): """Set the fill brush for this spot""" brush = fn.mkBrush(*args, **kargs) self._data['brush'] = brush self.updateItem()
def paint(self, p, *args): if self.box: p.setPen(fn.mkPen(255, 255, 255, 100)) p.setBrush(fn.mkBrush(100, 100, 100, 50)) p.drawRect(self.boundingRect())
def setBrush(self, *args, **kargs): """Set the brush used when filling the area under the curve""" self.opts['brush'] = fn.mkBrush(*args, **kargs) self.update()