desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Remove an item from the internal ViewBox.'
def removeItem(self, item):
if (not (item in self.items)): return self.items.remove(item) if (item in self.dataItems): self.dataItems.remove(item) if (item.scene() is not None): self.vb.removeItem(item) if (item in self.curves): self.curves.remove(item) self.updateDecimation() self.updateParamList()
'Remove all items from the ViewBox.'
def clear(self):
for i in self.items[:]: self.removeItem(i) self.avgCurves = {}
'Add and return a new plot. See :func:`PlotDataItem.__init__ <pyqtgraph.PlotDataItem.__init__>` for data arguments Extra allowed arguments are: clear - clear all plots before displaying new data params - meta-parameters to associate with this data'
def plot(self, *args, **kargs):
clear = kargs.get('clear', False) params = kargs.get('params', None) if clear: self.clear() item = PlotDataItem(*args, **kargs) if (params is None): params = {} self.addItem(item, params=params) return item
'Create a new LegendItem and anchor it over the internal ViewBox. Plots will be automatically displayed in the legend if they are created with the \'name\' argument.'
def addLegend(self, size=None, offset=(30, 30)):
self.legend = LegendItem(size, offset) self.legend.setParentItem(self.vb) return self.legend
'Change the default downsampling mode for all PlotDataItems managed by this plot. **Arguments:** ds (int) Reduce visible plot samples by this factor, or (bool) To enable/disable downsampling without changing the value. auto (bool) If True, automatically pick *ds* based on visible range mode \'subsample\': Downsample by taking the first of N samples. This method is fastest and least accurate. \'mean\': Downsample by taking the mean of N samples. \'peak\': Downsample by drawing a saw wave that follows the min and max of the original data. This method produces the best visual representation of the data but is slower.'
def setDownsampling(self, ds=None, auto=None, mode=None):
if (ds is not None): if (ds is False): self.ctrl.downsampleCheck.setChecked(False) elif (ds is True): self.ctrl.downsampleCheck.setChecked(True) else: self.ctrl.downsampleCheck.setChecked(True) self.ctrl.downsampleSpin.setValue(ds) if (auto is not None): if (auto and (ds is not False)): self.ctrl.downsampleCheck.setChecked(True) self.ctrl.autoDownsampleCheck.setChecked(auto) if (mode is not None): if (mode == 'subsample'): self.ctrl.subsampleRadio.setChecked(True) elif (mode == 'mean'): self.ctrl.meanRadio.setChecked(True) elif (mode == 'peak'): self.ctrl.peakRadio.setChecked(True) else: raise ValueError("mode argument must be 'subsample', 'mean', or 'peak'.")
'Set the default clip-to-view mode for all PlotDataItems managed by this plot. If *clip* is True, then PlotDataItems will attempt to draw only points within the visible range of the ViewBox.'
def setClipToView(self, clip):
self.ctrl.clipToViewCheck.setChecked(clip)
'Enable or disable the context menu for this PlotItem. By default, the ViewBox\'s context menu will also be affected. (use enableViewBoxMenu=None to leave the ViewBox unchanged)'
def setMenuEnabled(self, enableMenu=True, enableViewBoxMenu='same'):
self._menuEnabled = enableMenu if (enableViewBoxMenu is None): return if (enableViewBoxMenu is 'same'): enableViewBoxMenu = enableMenu self.vb.setMenuEnabled(enableViewBoxMenu)
'Return the specified AxisItem. *name* should be \'left\', \'bottom\', \'top\', or \'right\'.'
def getAxis(self, name):
self._checkScaleKey(name) return self.axes[name]['item']
'Set the label for an axis. Basic HTML formatting is allowed. **Arguments:** axis must be one of \'left\', \'bottom\', \'right\', or \'top\' text text to display along the axis. HTML allowed. units units to display after the title. If units are given, then an SI prefix will be automatically appended and the axis values will be scaled accordingly. (ie, use \'V\' instead of \'mV\'; \'m\' will be added automatically)'
def setLabel(self, axis, text=None, units=None, unitPrefix=None, **args):
self.getAxis(axis).setLabel(text=text, units=units, **args) self.showAxis(axis)
'Convenience function allowing multiple labels and/or title to be set in one call. Keyword arguments can be \'title\', \'left\', \'bottom\', \'right\', or \'top\'. Values may be strings or a tuple of arguments to pass to setLabel.'
def setLabels(self, **kwds):
for (k, v) in kwds.items(): if (k == 'title'): self.setTitle(v) else: if isinstance(v, basestring): v = (v,) self.setLabel(k, *v)
'Show or hide one of the plot\'s axis labels (the axis itself will be unaffected). axis must be one of \'left\', \'bottom\', \'right\', or \'top\''
def showLabel(self, axis, show=True):
self.getScale(axis).showLabel(show)
'Set the title of the plot. Basic HTML formatting is allowed. If title is None, then the title will be hidden.'
def setTitle(self, title=None, **args):
if (title is None): self.titleLabel.setVisible(False) self.layout.setRowFixedHeight(0, 0) self.titleLabel.setMaximumHeight(0) else: self.titleLabel.setMaximumHeight(30) self.layout.setRowFixedHeight(0, 30) self.titleLabel.setVisible(True) self.titleLabel.setText(title, **args)
'Show or hide one of the plot\'s axes. axis must be one of \'left\', \'bottom\', \'right\', or \'top\''
def showAxis(self, axis, show=True):
s = self.getScale(axis) p = self.axes[axis]['pos'] if show: s.show() else: s.hide()
'Hide one of the PlotItem\'s axes. (\'left\', \'bottom\', \'right\', or \'top\')'
def hideAxis(self, axis):
self.showAxis(axis, False)
'Causes auto-scale button (\'A\' in lower-left corner) to be hidden for this PlotItem'
def hideButtons(self):
self.buttonsHidden = True self.updateButtons()
'Causes auto-scale button (\'A\' in lower-left corner) to be visible for this PlotItem'
def showButtons(self):
self.buttonsHidden = False self.updateButtons()
'Valid keyword options are: x, x0, x1, y, y0, y1, width, height, pen, brush x specifies the x-position of the center of the bar. x0, x1 specify left and right edges of the bar, respectively. width specifies distance from x0 to x1. You may specify any combination: x, width x0, width x1, width x0, x1 Likewise y, y0, y1, and height. If only height is specified, then y0 will be set to 0 Example uses: BarGraphItem(x=range(5), height=[1,5,2,4,3], width=0.5)'
def __init__(self, **opts):
GraphicsObject.__init__(self) self.opts = dict(x=None, y=None, x0=None, y0=None, x1=None, y1=None, height=None, width=None, pen=None, brush=None, pens=None, brushes=None) self._shape = None self.picture = None self.setOpts(**opts)
'**Arguments:** pos Position of the line. This can be a QPointF or a single value for vertical/horizontal lines. angle Angle of line in degrees. 0 is horizontal, 90 is vertical. pen Pen to use when drawing line. Can be any arguments that are valid for :func:`mkPen <pyqtgraph.mkPen>`. Default pen is transparent yellow. movable If True, the line can be dragged to a new position by the user. hoverPen Pen to use when drawing line when hovering over it. Can be any arguments that are valid for :func:`mkPen <pyqtgraph.mkPen>`. Default pen is red. bounds Optional [min, max] bounding values. Bounds are only valid if the line is vertical or horizontal. label Text to be displayed in a label attached to the line, or None to show no label (default is None). May optionally include formatting strings to display the line value. labelOpts A dict of keyword arguments to use when constructing the text label. See :class:`InfLineLabel`. name Name of the item'
def __init__(self, pos=None, angle=90, pen=None, movable=False, bounds=None, hoverPen=None, label=None, labelOpts=None, name=None):
self._boundingRect = None self._line = None self._name = name GraphicsObject.__init__(self) if (bounds is None): self.maxRange = [None, None] else: self.maxRange = bounds self.moving = False self.setMovable(movable) self.mouseHovering = False self.p = [0, 0] self.setAngle(angle) if (pos is None): pos = Point(0, 0) self.setPos(pos) if (pen is None): pen = (200, 200, 100) self.setPen(pen) if (hoverPen is None): self.setHoverPen(color=(255, 0, 0), width=self.pen.width()) else: self.setHoverPen(hoverPen) self.currentPen = self.pen if (label is not None): labelOpts = ({} if (labelOpts is None) else labelOpts) self.label = InfLineLabel(self, text=label, **labelOpts)
'Set whether the line is movable by the user.'
def setMovable(self, m):
self.movable = m self.setAcceptHoverEvents(m)
'Set the (minimum, maximum) allowable values when dragging.'
def setBounds(self, bounds):
self.maxRange = bounds self.setValue(self.value())
'Set the pen for drawing the line. Allowable arguments are any that are valid for :func:`mkPen <pyqtgraph.mkPen>`.'
def setPen(self, *args, **kwargs):
self.pen = fn.mkPen(*args, **kwargs) if (not self.mouseHovering): self.currentPen = self.pen self.update()
'Set the pen for drawing the line while the mouse hovers over it. Allowable arguments are any that are valid for :func:`mkPen <pyqtgraph.mkPen>`. If the line is not movable, then hovering is also disabled. Added in version 0.9.9.'
def setHoverPen(self, *args, **kwargs):
self.hoverPen = fn.mkPen(*args, **kwargs) if self.mouseHovering: self.currentPen = self.hoverPen self.update()
'Takes angle argument in degrees. 0 is horizontal; 90 is vertical. Note that the use of value() and setValue() changes if the line is not vertical or horizontal.'
def setAngle(self, angle):
self.angle = (((angle + 45) % 180) - 45) self.resetTransform() self.rotate(self.angle) self.update()
'Return the value of the line. Will be a single number for horizontal and vertical lines, and a list of [x,y] values for diagonal lines.'
def value(self):
if ((self.angle % 180) == 0): return self.getYPos() elif ((self.angle % 180) == 90): return self.getXPos() else: return self.getPos()
'Set the position of the line. If line is horizontal or vertical, v can be a single value. Otherwise, a 2D coordinate must be specified (list, tuple and QPointF are all acceptable).'
def setValue(self, v):
self.setPos(v)
'Called whenever the transformation matrix of the view has changed. (eg, the view range has changed or the view was resized)'
def viewTransformChanged(self):
self._invalidateCache()
'Set whether this label is movable by dragging along the line.'
def setMovable(self, m):
self.movable = m self.setAcceptHoverEvents(m)
'Set the relative position (0.0-1.0) of this label within the view box and along the line. For horizontal (angle=0) and vertical (angle=90) lines, a value of 0.0 places the text at the bottom or left of the view, respectively.'
def setPosition(self, p):
self.orthoPos = p self.updatePosition()
'Set the text format string for this label. May optionally contain "{value}" to include the lines current value (the text will be reformatted whenever the line is moved).'
def setFormat(self, text):
self.format = text self.valueChanged()
'Return the view widget for this item. If the scene has multiple views, only the first view is returned. The return value is cached; clear the cached value with forgetViewWidget(). If the view has been deleted by Qt, return None.'
def getViewWidget(self):
if (self._viewWidget is None): scene = self.scene() if (scene is None): return None views = scene.views() if (len(views) < 1): return None self._viewWidget = weakref.ref(self.scene().views()[0]) v = self._viewWidget() if ((v is not None) and (not isQObjectAlive(v))): return None return v
'Return the first ViewBox or GraphicsView which bounds this item\'s visible space. If this item is not contained within a ViewBox, then the GraphicsView is returned. If the item is contained inside nested ViewBoxes, then the inner-most ViewBox is returned. The result is cached; clear the cache with forgetViewBox()'
def getViewBox(self):
if (self._viewBox is None): p = self while True: try: p = p.parentItem() except RuntimeError: return None if (p is None): vb = self.getViewWidget() if (vb is None): return None else: self._viewBox = weakref.ref(vb) break if (hasattr(p, 'implements') and p.implements('ViewBox')): self._viewBox = weakref.ref(p) break return self._viewBox()
'Return the transform that converts local item coordinates to device coordinates (usually pixels). Extends deviceTransform to automatically determine the viewportTransform.'
def deviceTransform(self, viewportTransform=None):
if ((self._exportOpts is not False) and ('painter' in self._exportOpts)): return (self._exportOpts['painter'].deviceTransform() * self.sceneTransform()) if (viewportTransform is None): view = self.getViewWidget() if (view is None): return None viewportTransform = view.viewportTransform() dt = self._qtBaseClass.deviceTransform(self, viewportTransform) if (dt.determinant() == 0): return None else: return dt
'Return the transform that maps from local coordinates to the item\'s ViewBox coordinates If there is no ViewBox, return the scene transform. Returns None if the item does not have a view.'
def viewTransform(self):
view = self.getViewBox() if (view is None): return None if (hasattr(view, 'implements') and view.implements('ViewBox')): tr = self.itemTransform(view.innerSceneItem()) if isinstance(tr, tuple): tr = tr[0] return tr else: return self.sceneTransform()
'Return a list of parents to this item that have child clipping enabled.'
def getBoundingParents(self):
p = self parents = [] while True: p = p.parentItem() if (p is None): break if (p.flags() & self.ItemClipsChildrenToShape): parents.append(p) return parents
'Return the bounds (in item coordinates) of this item\'s ViewBox or GraphicsWidget'
def viewRect(self):
view = self.getViewBox() if (view is None): return None bounds = self.mapRectFromView(view.viewRect()) if (bounds is None): return None bounds = bounds.normalized() return bounds
'Return vectors in local coordinates representing the width and height of a view pixel. If direction is specified, then return vectors parallel and orthogonal to it. Return (None, None) if pixel size is not yet defined (usually because the item has not yet been displayed) or if pixel size is below floating-point precision limit.'
def pixelVectors(self, direction=None):
dt = self.deviceTransform() if (dt is None): return (None, None) dt.setMatrix(dt.m11(), dt.m12(), 0, dt.m21(), dt.m22(), 0, 0, 0, 1) if ((direction is None) and (dt == self._pixelVectorCache[0])): return tuple(map(Point, self._pixelVectorCache[1])) key = (dt.m11(), dt.m21(), dt.m12(), dt.m22()) pv = self._pixelVectorGlobalCache.get(key, None) if ((direction is None) and (pv is not None)): self._pixelVectorCache = [dt, pv] return tuple(map(Point, pv)) if (direction is None): direction = QtCore.QPointF(1, 0) if (direction.manhattanLength() == 0): raise Exception('Cannot compute pixel length for 0-length vector.') directionr = direction dirLine = QtCore.QLineF(QtCore.QPointF(0, 0), directionr) viewDir = dt.map(dirLine) if (viewDir.length() == 0): return (None, None) try: normView = viewDir.unitVector() normOrtho = normView.normalVector() except: raise Exception(('Invalid direction %s' % directionr)) dti = fn.invertQTransform(dt) pv = (Point(dti.map(normView).p2()), Point(dti.map(normOrtho).p2())) self._pixelVectorCache[1] = pv self._pixelVectorCache[0] = dt self._pixelVectorGlobalCache[key] = pv return self._pixelVectorCache[1]
'Return the length of one pixel in the direction indicated (in local coordinates) If ortho=True, then return the length of one pixel orthogonal to the direction indicated. Return None if pixel size is not yet defined (usually because the item has not yet been displayed).'
def pixelLength(self, direction, ortho=False):
(normV, orthoV) = self.pixelVectors(direction) if ((normV == None) or (orthoV == None)): return None if ortho: return orthoV.length() return normV.length()
'Return *obj* mapped from local coordinates to device coordinates (pixels). If there is no device mapping available, return None.'
def mapToDevice(self, obj):
vt = self.deviceTransform() if (vt is None): return None return vt.map(obj)
'Return *obj* mapped from device coordinates (pixels) to local coordinates. If there is no device mapping available, return None.'
def mapFromDevice(self, obj):
vt = self.deviceTransform() if (vt is None): return None if isinstance(obj, QtCore.QPoint): obj = QtCore.QPointF(obj) vt = fn.invertQTransform(vt) return vt.map(obj)
'Return *rect* mapped from local coordinates to device coordinates (pixels). If there is no device mapping available, return None.'
def mapRectToDevice(self, rect):
vt = self.deviceTransform() if (vt is None): return None return vt.mapRect(rect)
'Return *rect* mapped from device coordinates (pixels) to local coordinates. If there is no device mapping available, return None.'
def mapRectFromDevice(self, rect):
vt = self.deviceTransform() if (vt is None): return None vt = fn.invertQTransform(vt) return vt.mapRect(rect)
'Return the rotation produced by this item\'s transform (this assumes there is no shear in the transform) If relativeItem is given, then the angle is determined relative to that item.'
def transformAngle(self, relativeItem=None):
if (relativeItem is None): relativeItem = self.parentItem() tr = self.itemTransform(relativeItem) if isinstance(tr, tuple): tr = tr[0] vec = tr.map(QtCore.QLineF(0, 0, 1, 0)) return vec.angleTo(QtCore.QLineF(vec.p1(), (vec.p1() + QtCore.QPointF(1, 0))))
'Called when the item\'s parent has changed. This method handles connecting / disconnecting from ViewBox signals to make sure viewRangeChanged works properly. It should generally be extended, not overridden.'
def parentChanged(self):
self._updateView()
'Called when this item\'s view has changed (ie, the item has been added to or removed from a ViewBox)'
def viewChanged(self, view, oldView):
pass
'Called whenever the view coordinates of the ViewBox containing this item have changed.'
def viewRangeChanged(self):
pass
'Called whenever the transformation matrix of the view has changed. (eg, the view range has changed or the view was resized)'
def viewTransformChanged(self):
pass
'Inform this item\'s container ViewBox that the bounds of this item have changed. This is used by ViewBox to react if auto-range is enabled.'
def informViewBoundsChanged(self):
view = self.getViewBox() if ((view is not None) and hasattr(view, 'implements') and view.implements('ViewBox')): view.itemBoundsChanged(self)
'Return the union of the shapes of all descendants of this item in local coordinates.'
def childrenShape(self):
childs = self.allChildItems() shapes = [self.mapFromItem(c, c.shape()) for c in self.allChildItems()] return reduce(operator.add, shapes)
'Return list of the entire item tree descending from this item.'
def allChildItems(self, root=None):
if (root is None): root = self tree = [] for ch in root.childItems(): tree.append(ch) tree.extend(self.allChildItems(ch)) return tree
'This method is called by exporters to inform items that they are being drawn for export with a specific set of options. Items access these via self._exportOptions. When exporting is complete, _exportOptions is set to False.'
def setExportMode(self, export, opts=None):
if (opts is None): opts = {} if export: self._exportOpts = opts else: self._exportOpts = False
'Set default text properties. See setText() for accepted parameters.'
def setAttr(self, attr, value):
self.opts[attr] = value
'Set the text and text properties in the label. Accepts optional arguments for auto-generating a CSS style string: **Style Arguments:** color (str) example: \'CCFF00\' size (str) example: \'8pt\' bold (bool) italic (bool)'
def setText(self, text, **args):
self.text = text opts = self.opts for k in args: opts[k] = args[k] optlist = [] color = self.opts['color'] if (color is None): color = getConfigOption('foreground') color = fn.mkColor(color) optlist.append(('color: #' + fn.colorStr(color)[:6])) if ('size' in opts): optlist.append(('font-size: ' + opts['size'])) if (('bold' in opts) and (opts['bold'] in [True, False])): optlist.append(('font-weight: ' + {True: 'bold', False: 'normal'}[opts['bold']])) if (('italic' in opts) and (opts['italic'] in [True, False])): optlist.append(('font-style: ' + {True: 'italic', False: 'normal'}[opts['italic']])) full = ("<span style='%s'>%s</span>" % ('; '.join(optlist), text)) self.item.setHtml(full) self.updateMin() self.resizeEvent(None) self.updateGeometry()
'Given a list of spot records, return an object representing the coordinates of that symbol within the atlas'
def getSymbolCoords(self, opts):
sourceRect = np.empty(len(opts), dtype=object) keyi = None sourceRecti = None for (i, rec) in enumerate(opts): key = (rec[3], rec[2], id(rec[4]), id(rec[5])) if (key == keyi): sourceRect[i] = sourceRecti else: try: sourceRect[i] = self.symbolMap[key] except KeyError: newRectSrc = QtCore.QRectF() newRectSrc.pen = rec['pen'] newRectSrc.brush = rec['brush'] self.symbolMap[key] = newRectSrc self.atlasValid = False sourceRect[i] = newRectSrc keyi = key sourceRecti = newRectSrc return sourceRect
'Accepts the same arguments as setData()'
def __init__(self, *args, **kargs):
profiler = debug.Profiler() GraphicsObject.__init__(self) self.picture = None self.fragmentAtlas = SymbolAtlas() self.data = np.empty(0, dtype=[('x', float), ('y', float), ('size', float), ('symbol', object), ('pen', object), ('brush', object), ('data', object), ('item', object), ('sourceRect', object), ('targetRect', object), ('width', float)]) self.bounds = [None, None] self._maxSpotWidth = 0 self._maxSpotPxWidth = 0 self.opts = {'pxMode': True, 'useCache': True, 'antialias': getConfigOption('antialias'), 'compositionMode': None, 'name': None} self.setPen(fn.mkPen(getConfigOption('foreground')), update=False) self.setBrush(fn.mkBrush(100, 100, 150), update=False) self.setSymbol('o', update=False) self.setSize(7, update=False) profiler() self.setData(*args, **kargs) profiler('setData')
'**Ordered Arguments:** * If there is only one unnamed argument, it will be interpreted like the \'spots\' argument. * If there are two unnamed arguments, they will be interpreted as sequences of x and y values. **Keyword Arguments:** *spots* Optional list of dicts. Each dict specifies parameters for a single spot: {\'pos\': (x,y), \'size\', \'pen\', \'brush\', \'symbol\'}. This is just an alternate method of passing in data for the corresponding arguments. *x*,*y* 1D arrays of x,y values. *pos* 2D structure of x,y pairs (such as Nx2 array or list of tuples) *pxMode* If True, spots are always the same size regardless of scaling, and size is given in px. Otherwise, size is in scene coordinates and the spots scale with the view. Default is True *symbol* can be one (or a list) of: * \'o\' circle (default) * \'s\' square * \'t\' triangle * \'d\' diamond * \'+\' plus * any QPainterPath to specify custom symbol shapes. To properly obey the position and size, custom symbols should be centered at (0,0) and width and height of 1.0. Note that it is also possible to \'install\' custom shapes by setting ScatterPlotItem.Symbols[key] = shape. *pen* The pen (or list of pens) to use for drawing spot outlines. *brush* The brush (or list of brushes) to use for filling spots. *size* The size (or list of sizes) of spots. If *pxMode* is True, this value is in pixels. Otherwise, it is in the item\'s local coordinate system. *data* a list of python objects used to uniquely identify each spot. *identical* *Deprecated*. This functionality is handled automatically now. *antialias* Whether to draw symbols with antialiasing. Note that if pxMode is True, symbols are always rendered with antialiasing (since the rendered symbols can be cached, this incurs very little performance cost) *compositionMode* If specified, this sets the composition mode used when drawing the scatter plot (see QPainter::CompositionMode in the Qt documentation). *name* The name of this item. Names are used for automatically generating LegendItem entries and by some exporters.'
def setData(self, *args, **kargs):
oldData = self.data self.clear() self.addPoints(*args, **kargs)
'Add new points to the scatter plot. Arguments are the same as setData()'
def addPoints(self, *args, **kargs):
if (len(args) == 1): kargs['spots'] = args[0] elif (len(args) == 2): kargs['x'] = args[0] kargs['y'] = args[1] elif (len(args) > 2): raise Exception('Only accepts up to two non-keyword arguments.') if ('pos' in kargs): pos = kargs['pos'] if isinstance(pos, np.ndarray): kargs['x'] = pos[:, 0] kargs['y'] = pos[:, 1] else: x = [] y = [] for p in pos: if isinstance(p, QtCore.QPointF): x.append(p.x()) y.append(p.y()) else: x.append(p[0]) y.append(p[1]) kargs['x'] = x kargs['y'] = y if ('spots' in kargs): numPts = len(kargs['spots']) elif (('y' in kargs) and (kargs['y'] is not None)): numPts = len(kargs['y']) else: kargs['x'] = [] kargs['y'] = [] numPts = 0 oldData = self.data self.data = np.empty((len(oldData) + numPts), dtype=self.data.dtype) self.data[:len(oldData)] = oldData newData = self.data[len(oldData):] newData['size'] = (-1) if ('spots' in kargs): spots = kargs['spots'] for i in range(len(spots)): spot = spots[i] for k in spot: if (k == 'pos'): pos = spot[k] if isinstance(pos, QtCore.QPointF): (x, y) = (pos.x(), pos.y()) else: (x, y) = (pos[0], pos[1]) newData[i]['x'] = x newData[i]['y'] = y elif (k == 'pen'): newData[i][k] = fn.mkPen(spot[k]) elif (k == 'brush'): newData[i][k] = fn.mkBrush(spot[k]) elif (k in ['x', 'y', 'size', 'symbol', 'brush', 'data']): newData[i][k] = spot[k] else: raise Exception(('Unknown spot parameter: %s' % k)) elif ('y' in kargs): newData['x'] = kargs['x'] newData['y'] = kargs['y'] if ('pxMode' in kargs): self.setPxMode(kargs['pxMode']) if ('antialias' in kargs): self.opts['antialias'] = kargs['antialias'] for k in ['pen', 'brush', 'symbol', 'size']: if (k in kargs): setMethod = getattr(self, (('set' + k[0].upper()) + k[1:])) setMethod(kargs[k], update=False, dataSet=newData, mask=kargs.get('mask', None)) if ('data' in kargs): self.setPointData(kargs['data'], dataSet=newData) self.prepareGeometryChange() self.informViewBoundsChanged() self.bounds = [None, None] self.invalidate() self.updateSpots(newData) self.sigPlotChanged.emit(self)
'Set the pen(s) used to draw the outline around each spot. If a list or array is provided, then the pen for each spot will be set separately. Otherwise, the arguments are passed to pg.mkPen and used as the default pen for all spots which do not have a pen explicitly set.'
def setPen(self, *args, **kargs):
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))): pens = args[0] if (('mask' in kargs) and (kargs['mask'] is not None)): pens = pens[kargs['mask']] if (len(pens) != len(dataSet)): raise Exception(('Number of pens does not match number of points (%d != %d)' % (len(pens), len(dataSet)))) dataSet['pen'] = pens else: self.opts['pen'] = fn.mkPen(*args, **kargs) dataSet['sourceRect'] = None if update: self.updateSpots(dataSet)
'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.'
def setBrush(self, *args, **kargs):
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 (('mask' in kargs) and (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)))) dataSet['brush'] = brushes else: self.opts['brush'] = fn.mkBrush(*args, **kargs) dataSet['sourceRect'] = None if update: self.updateSpots(dataSet)
'Set the symbol(s) used to draw each spot. If a list or array is provided, then the symbol for each spot will be set separately. Otherwise, the argument will be used as the default symbol for all spots which do not have a symbol explicitly set.'
def setSymbol(self, symbol, update=True, dataSet=None, mask=None):
if (dataSet is None): dataSet = self.data if (isinstance(symbol, np.ndarray) or isinstance(symbol, list)): symbols = symbol if (mask is not None): symbols = symbols[mask] if (len(symbols) != len(dataSet)): raise Exception(('Number of symbols does not match number of points (%d != %d)' % (len(symbols), len(dataSet)))) dataSet['symbol'] = symbols else: self.opts['symbol'] = symbol self._spotPixmap = None dataSet['sourceRect'] = None if update: self.updateSpots(dataSet)
'Set the size(s) used to draw each spot. If a list or array is provided, then the size for each spot will be set separately. Otherwise, the argument will be used as the default size for all spots which do not have a size explicitly set.'
def setSize(self, size, update=True, dataSet=None, mask=None):
if (dataSet is None): dataSet = self.data if (isinstance(size, np.ndarray) or isinstance(size, list)): sizes = size if (mask is not None): sizes = sizes[mask] if (len(sizes) != len(dataSet)): raise Exception(('Number of sizes does not match number of points (%d != %d)' % (len(sizes), len(dataSet)))) dataSet['size'] = sizes else: self.opts['size'] = size self._spotPixmap = None dataSet['sourceRect'] = None if update: self.updateSpots(dataSet)
'Remove all spots from the scatter plot'
def clear(self):
self.data = np.empty(0, dtype=self.data.dtype) self.bounds = [None, None] self.invalidate()
'Return the user data associated with this spot.'
def data(self):
return self._data['data']
'Return the size of this spot. If the spot has no explicit size set, then return the ScatterPlotItem\'s default size instead.'
def size(self):
if (self._data['size'] == (-1)): return self._plot.opts['size'] else: return self._data['size']
'Set the size of this spot. If the size is set to -1, then the ScatterPlotItem\'s default size will be used instead.'
def setSize(self, size):
self._data['size'] = size self.updateItem()
'Return the symbol of this spot. If the spot has no explicit symbol set, then return the ScatterPlotItem\'s default symbol instead.'
def symbol(self):
symbol = self._data['symbol'] if (symbol is None): symbol = self._plot.opts['symbol'] try: n = int(symbol) symbol = list(Symbols.keys())[(n % len(Symbols))] except: pass return symbol
'Set the symbol for this spot. If the symbol is set to \'\', then the ScatterPlotItem\'s default symbol will be used instead.'
def setSymbol(self, symbol):
self._data['symbol'] = symbol self.updateItem()
'Set the outline pen for this spot'
def setPen(self, *args, **kargs):
pen = fn.mkPen(*args, **kargs) self._data['pen'] = pen self.updateItem()
'Remove the pen set for this spot; the scatter plot\'s default pen will be used instead.'
def resetPen(self):
self._data['pen'] = None self.updateItem()
'Set the fill brush for this spot'
def setBrush(self, *args, **kargs):
brush = fn.mkBrush(*args, **kargs) self._data['brush'] = brush self.updateItem()
'Remove the brush set for this spot; the scatter plot\'s default brush will be used instead.'
def resetBrush(self):
self._data['brush'] = None self.updateItem()
'Set the user-data associated with this spot'
def setData(self, data):
self._data['data'] = data
'**Arguments:** *parent* (QGraphicsWidget) Optional parent widget *border* (QPen) Do draw a border around the view, give any single argument accepted by :func:`mkPen <pyqtgraph.mkPen>` *lockAspect* (False or float) The aspect ratio to lock the view coorinates to. (or False to allow the ratio to change) *enableMouse* (bool) Whether mouse can be used to scale/pan the view *invertY* (bool) See :func:`invertY <pyqtgraph.ViewBox.invertY>` *invertX* (bool) See :func:`invertX <pyqtgraph.ViewBox.invertX>` *enableMenu* (bool) Whether to display a context menu when right-clicking on the ViewBox background. *name* (str) Used to register this ViewBox so that it appears in the "Link axis" dropdown inside other ViewBox context menus. This allows the user to manually link the axes of any other view to this one.'
def __init__(self, parent=None, border=None, lockAspect=False, enableMouse=True, invertY=False, enableMenu=True, name=None, invertX=False):
GraphicsWidget.__init__(self, parent) self.name = None self.linksBlocked = False self.addedItems = [] self._matrixNeedsUpdate = True self._autoRangeNeedsUpdate = True self._lastScene = None self.state = {'targetRange': [[0, 1], [0, 1]], 'viewRange': [[0, 1], [0, 1]], 'yInverted': invertY, 'xInverted': invertX, 'aspectLocked': False, 'autoRange': [True, True], 'autoPan': [False, False], 'autoVisibleOnly': [False, False], 'linkedViews': [None, None], 'mouseEnabled': [enableMouse, enableMouse], 'mouseMode': (ViewBox.PanMode if getConfigOption('leftButtonPan') else ViewBox.RectMode), 'enableMenu': enableMenu, 'wheelScaleFactor': ((-1.0) / 8.0), 'background': None, 'limits': {'xLimits': [None, None], 'yLimits': [None, None], 'xRange': [None, None], 'yRange': [None, None]}} self._updatingRange = False self._itemBoundsCache = weakref.WeakKeyDictionary() self.locateGroup = None self.setFlag(self.ItemClipsChildrenToShape) self.setFlag(self.ItemIsFocusable, True) self.childGroup = ChildGroup(self) self.childGroup.itemsChangedListeners.append(self) self.background = QtGui.QGraphicsRectItem(self.rect()) self.background.setParentItem(self) self.background.setZValue((-1000000.0)) self.background.setPen(fn.mkPen(None)) self.updateBackground() self.rbScaleBox = QtGui.QGraphicsRectItem(0, 0, 1, 1) self.rbScaleBox.setPen(fn.mkPen((255, 255, 100), width=1)) self.rbScaleBox.setBrush(fn.mkBrush(255, 255, 0, 100)) self.rbScaleBox.setZValue(1000000000.0) self.rbScaleBox.hide() self.addItem(self.rbScaleBox, ignoreBounds=True) self.target = QtGui.QGraphicsRectItem(0, 0, 1, 1) self.target.setPen(fn.mkPen('r')) self.target.setParentItem(self) self.target.hide() self.axHistory = [] self.axHistoryPointer = (-1) self.setZValue((-100)) self.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)) self.setAspectLocked(lockAspect) self.border = fn.mkPen(border) self.menu = ViewBoxMenu(self) self.register(name) if (name is None): self.updateViewLists()
'Add this ViewBox to the registered list of views. This allows users to manually link the axes of any other ViewBox to this one. The specified *name* will appear in the drop-down lists for axis linking in the context menus of all other views. The same can be accomplished by initializing the ViewBox with the *name* attribute.'
def register(self, name):
ViewBox.AllViews[self] = None if (self.name is not None): del ViewBox.NamedViews[self.name] self.name = name if (name is not None): ViewBox.NamedViews[name] = self ViewBox.updateAllViewLists() sid = id(self) self.destroyed.connect((lambda : (ViewBox.forgetView(sid, name) if ((ViewBox is not None) and ('sid' in locals()) and ('name' in locals())) else None)))
'Remove this ViewBox from the list of linkable views. (see :func:`register() <pyqtgraph.ViewBox.register>`)'
def unregister(self):
del ViewBox.AllViews[self] if (self.name is not None): del ViewBox.NamedViews[self.name]
'Return the current state of the ViewBox. Linked views are always converted to view names in the returned state.'
def getState(self, copy=True):
state = self.state.copy() views = [] for v in state['linkedViews']: if isinstance(v, weakref.ref): v = v() if ((v is None) or isinstance(v, basestring)): views.append(v) else: views.append(v.name) state['linkedViews'] = views if copy: return deepcopy(state) else: return state
'Restore the state of this ViewBox. (see also getState)'
def setState(self, state):
state = state.copy() self.setXLink(state['linkedViews'][0]) self.setYLink(state['linkedViews'][1]) del state['linkedViews'] self.state.update(state) self.updateViewRange() self.sigStateChanged.emit(self)
'Set the background color of the ViewBox. If color is None, then no background will be drawn. Added in version 0.9.9'
def setBackgroundColor(self, color):
self.background.setVisible((color is not None)) self.state['background'] = color self.updateBackground()
'Set the mouse interaction mode. *mode* must be either ViewBox.PanMode or ViewBox.RectMode. In PanMode, the left mouse button pans the view and the right button scales. In RectMode, the left button draws a rectangle which updates the visible region (this mode is more suitable for single-button mice)'
def setMouseMode(self, mode):
if (mode not in [ViewBox.PanMode, ViewBox.RectMode]): raise Exception('Mode must be ViewBox.PanMode or ViewBox.RectMode') self.state['mouseMode'] = mode self.sigStateChanged.emit(self)
'Set whether each axis is enabled for mouse interaction. *x*, *y* arguments must be True or False. This allows the user to pan/scale one axis of the view while leaving the other axis unchanged.'
def setMouseEnabled(self, x=None, y=None):
if (x is not None): self.state['mouseEnabled'][0] = x if (y is not None): self.state['mouseEnabled'][1] = y self.sigStateChanged.emit(self)
'Add a QGraphicsItem to this view. The view will include this item when determining how to set its range automatically unless *ignoreBounds* is True.'
def addItem(self, item, ignoreBounds=False):
if (item.zValue() < self.zValue()): item.setZValue((self.zValue() + 1)) scene = self.scene() if ((scene is not None) and (scene is not item.scene())): scene.addItem(item) item.setParentItem(self.childGroup) if (not ignoreBounds): self.addedItems.append(item) self.updateAutoRange()
'Remove an item from this view.'
def removeItem(self, item):
try: self.addedItems.remove(item) except: pass self.scene().removeItem(item) self.updateAutoRange()
'Return a the view\'s visible range as a list: [[xmin, xmax], [ymin, ymax]]'
def viewRange(self):
return [x[:] for x in self.state['viewRange']]
'Return a QRectF bounding the region visible within the ViewBox'
def viewRect(self):
try: vr0 = self.state['viewRange'][0] vr1 = self.state['viewRange'][1] return QtCore.QRectF(vr0[0], vr1[0], (vr0[1] - vr0[0]), (vr1[1] - vr1[0])) except: print ('make qrectf failed:', self.state['viewRange']) raise
'Return the region which has been requested to be visible. (this is not necessarily the same as the region that is *actually* visible-- resizing and aspect ratio constraints can cause targetRect() and viewRect() to differ)'
def targetRect(self):
try: tr0 = self.state['targetRange'][0] tr1 = self.state['targetRange'][1] return QtCore.QRectF(tr0[0], tr1[0], (tr0[1] - tr0[0]), (tr1[1] - tr1[0])) except: print ('make qrectf failed:', self.state['targetRange']) raise
'Set the visible range of the ViewBox. Must specify at least one of *rect*, *xRange*, or *yRange*. **Arguments:** *rect* (QRectF) The full range that should be visible in the view box. *xRange* (min,max) The range that should be visible along the x-axis. *yRange* (min,max) The range that should be visible along the y-axis. *padding* (float) Expand the view by a fraction of the requested range. By default, this value is set between 0.02 and 0.1 depending on the size of the ViewBox. *update* (bool) If True, update the range of the ViewBox immediately. Otherwise, the update is deferred until before the next render. *disableAutoRange* (bool) If True, auto-ranging is diabled. Otherwise, it is left unchanged.'
def setRange(self, rect=None, xRange=None, yRange=None, padding=None, update=True, disableAutoRange=True):
changes = {} setRequested = [False, False] if (rect is not None): changes = {0: [rect.left(), rect.right()], 1: [rect.top(), rect.bottom()]} setRequested = [True, True] if (xRange is not None): changes[0] = xRange setRequested[0] = True if (yRange is not None): changes[1] = yRange setRequested[1] = True if (len(changes) == 0): print rect raise Exception(('Must specify at least one of rect, xRange, or yRange. (gave rect=%s)' % str(type(rect)))) changed = [False, False] for (ax, range) in changes.items(): mn = min(range) mx = max(range) if (mn == mx): dy = (self.state['viewRange'][ax][1] - self.state['viewRange'][ax][0]) if (dy == 0): dy = 1 mn -= (dy * 0.5) mx += (dy * 0.5) xpad = 0.0 if (not all(np.isfinite([mn, mx]))): raise Exception(('Cannot set range [%s, %s]' % (str(mn), str(mx)))) if (padding is None): xpad = self.suggestPadding(ax) else: xpad = padding p = ((mx - mn) * xpad) mn -= p mx += p if (self.state['targetRange'][ax] != [mn, mx]): self.state['targetRange'][ax] = [mn, mx] changed[ax] = True (lockX, lockY) = setRequested if (lockX and lockY): lockX = False lockY = False self.updateViewRange(lockX, lockY) if disableAutoRange: xOff = (False if setRequested[0] else None) yOff = (False if setRequested[1] else None) self.enableAutoRange(x=xOff, y=yOff) changed.append(True) if any(changed): self.sigStateChanged.emit(self) if self.target.isVisible(): self.target.setRect(self.mapRectFromItem(self.childGroup, self.targetRect())) if (changed[0] and self.state['autoVisibleOnly'][1] and (self.state['autoRange'][0] is not False)): self._autoRangeNeedsUpdate = True elif (changed[1] and self.state['autoVisibleOnly'][0] and (self.state['autoRange'][1] is not False)): self._autoRangeNeedsUpdate = True
'Set the visible Y range of the view to [*min*, *max*]. The *padding* argument causes the range to be set larger by the fraction specified. (by default, this value is between 0.02 and 0.1 depending on the size of the ViewBox)'
def setYRange(self, min, max, padding=None, update=True):
self.setRange(yRange=[min, max], update=update, padding=padding)
'Set the visible X range of the view to [*min*, *max*]. The *padding* argument causes the range to be set larger by the fraction specified. (by default, this value is between 0.02 and 0.1 depending on the size of the ViewBox)'
def setXRange(self, min, max, padding=None, update=True):
self.setRange(xRange=[min, max], update=update, padding=padding)
'Set the range of the view box to make all children visible. Note that this is not the same as enableAutoRange, which causes the view to automatically auto-range whenever its contents are changed. **Arguments:** padding The fraction of the total data range to add on to the final visible range. By default, this value is set between 0.02 and 0.1 depending on the size of the ViewBox. items If specified, this is a list of items to consider when determining the visible range.'
def autoRange(self, padding=None, items=None, item=None):
if (item is None): bounds = self.childrenBoundingRect(items=items) else: print "Warning: ViewBox.autoRange(item=__) is deprecated. Use 'items' argument instead." bounds = self.mapFromItemToView(item, item.boundingRect()).boundingRect() if (bounds is not None): self.setRange(bounds, padding=padding)
'Set limits that constrain the possible view ranges. **Panning limits**. The following arguments define the region within the viewbox coordinate system that may be accessed by panning the view. xMin Minimum allowed x-axis value xMax Maximum allowed x-axis value yMin Minimum allowed y-axis value yMax Maximum allowed y-axis value **Scaling limits**. These arguments prevent the view being zoomed in or out too far. minXRange Minimum allowed left-to-right span across the view. maxXRange Maximum allowed left-to-right span across the view. minYRange Minimum allowed top-to-bottom span across the view. maxYRange Maximum allowed top-to-bottom span across the view. Added in version 0.9.9'
def setLimits(self, **kwds):
update = False allowed = ['xMin', 'xMax', 'yMin', 'yMax', 'minXRange', 'maxXRange', 'minYRange', 'maxYRange'] for kwd in kwds: if (kwd not in allowed): raise ValueError(("Invalid keyword argument '%s'." % kwd)) for axis in [0, 1]: for mnmx in [0, 1]: kwd = [['xMin', 'xMax'], ['yMin', 'yMax']][axis][mnmx] lname = ['xLimits', 'yLimits'][axis] if ((kwd in kwds) and (self.state['limits'][lname][mnmx] != kwds[kwd])): self.state['limits'][lname][mnmx] = kwds[kwd] update = True kwd = [['minXRange', 'maxXRange'], ['minYRange', 'maxYRange']][axis][mnmx] lname = ['xRange', 'yRange'][axis] if ((kwd in kwds) and (self.state['limits'][lname][mnmx] != kwds[kwd])): self.state['limits'][lname][mnmx] = kwds[kwd] update = True if update: self.updateViewRange()
'Scale by *s* around given center point (or center of view). *s* may be a Point or tuple (x, y). Optionally, x or y may be specified individually. This allows the other axis to be left unaffected (note that using a scale factor of 1.0 may cause slight changes due to floating-point error).'
def scaleBy(self, s=None, center=None, x=None, y=None):
if (s is not None): scale = Point(s) else: scale = [x, y] affect = [True, True] if ((scale[0] is None) and (scale[1] is None)): return elif (scale[0] is None): affect[0] = False scale[0] = 1.0 elif (scale[1] is None): affect[1] = False scale[1] = 1.0 scale = Point(scale) if (self.state['aspectLocked'] is not False): scale[0] = scale[1] vr = self.targetRect() if (center is None): center = Point(vr.center()) else: center = Point(center) tl = (center + ((vr.topLeft() - center) * scale)) br = (center + ((vr.bottomRight() - center) * scale)) if (not affect[0]): self.setYRange(tl.y(), br.y(), padding=0) elif (not affect[1]): self.setXRange(tl.x(), br.x(), padding=0) else: self.setRange(QtCore.QRectF(tl, br), padding=0)
'Translate the view by *t*, which may be a Point or tuple (x, y). Alternately, x or y may be specified independently, leaving the other axis unchanged (note that using a translation of 0 may still cause small changes due to floating-point error).'
def translateBy(self, t=None, x=None, y=None):
vr = self.targetRect() if (t is not None): t = Point(t) self.setRange(vr.translated(t), padding=0) else: if (x is not None): x = ((vr.left() + x), (vr.right() + x)) if (y is not None): y = ((vr.top() + y), (vr.bottom() + y)) if ((x is not None) or (y is not None)): self.setRange(xRange=x, yRange=y, padding=0)
'Enable (or disable) auto-range for *axis*, which may be ViewBox.XAxis, ViewBox.YAxis, or ViewBox.XYAxes for both (if *axis* is omitted, both axes will be changed). When enabled, the axis will automatically rescale when items are added/removed or change their shape. The argument *enable* may optionally be a float (0.0-1.0) which indicates the fraction of the data that should be visible (this only works with items implementing a dataRange method, such as PlotDataItem).'
def enableAutoRange(self, axis=None, enable=True, x=None, y=None):
if ((x is not None) or (y is not None)): if (x is not None): self.enableAutoRange(ViewBox.XAxis, x) if (y is not None): self.enableAutoRange(ViewBox.YAxis, y) return if (enable is True): enable = 1.0 if (axis is None): axis = ViewBox.XYAxes needAutoRangeUpdate = False if ((axis == ViewBox.XYAxes) or (axis == 'xy')): axes = [0, 1] elif ((axis == ViewBox.XAxis) or (axis == 'x')): axes = [0] elif ((axis == ViewBox.YAxis) or (axis == 'y')): axes = [1] else: raise Exception('axis argument must be ViewBox.XAxis, ViewBox.YAxis, or ViewBox.XYAxes.') for ax in axes: if (self.state['autoRange'][ax] != enable): if ((enable is False) and self._autoRangeNeedsUpdate): self.updateAutoRange() self.state['autoRange'][ax] = enable self._autoRangeNeedsUpdate |= (enable is not False) self.update() self.sigStateChanged.emit(self)
'Disables auto-range. (See enableAutoRange)'
def disableAutoRange(self, axis=None):
self.enableAutoRange(axis, enable=False)
'Set whether automatic range will only pan (not scale) the view.'
def setAutoPan(self, x=None, y=None):
if (x is not None): self.state['autoPan'][0] = x if (y is not None): self.state['autoPan'][1] = y if (None not in [x, y]): self.updateAutoRange()
'Set whether automatic range uses only visible data when determining the range to show.'
def setAutoVisible(self, x=None, y=None):
if (x is not None): self.state['autoVisibleOnly'][0] = x if (x is True): self.state['autoVisibleOnly'][1] = False if (y is not None): self.state['autoVisibleOnly'][1] = y if (y is True): self.state['autoVisibleOnly'][0] = False if ((x is not None) or (y is not None)): self.updateAutoRange()
'Link this view\'s X axis to another view. (see LinkView)'
def setXLink(self, view):
self.linkView(self.XAxis, view)
'Link this view\'s Y axis to another view. (see LinkView)'
def setYLink(self, view):
self.linkView(self.YAxis, view)
'Link X or Y axes of two views and unlink any previously connected axes. *axis* must be ViewBox.XAxis or ViewBox.YAxis. If view is None, the axis is left unlinked.'
def linkView(self, axis, view):
if isinstance(view, basestring): if (view == ''): view = None else: view = ViewBox.NamedViews.get(view, view) if (hasattr(view, 'implements') and view.implements('ViewBoxWrapper')): view = view.getViewBox() if (axis == ViewBox.XAxis): signal = 'sigXRangeChanged' slot = self.linkedXChanged else: signal = 'sigYRangeChanged' slot = self.linkedYChanged oldLink = self.linkedView(axis) if (oldLink is not None): try: getattr(oldLink, signal).disconnect(slot) oldLink.sigResized.disconnect(slot) except (TypeError, RuntimeError): pass if ((view is None) or isinstance(view, basestring)): self.state['linkedViews'][axis] = view else: self.state['linkedViews'][axis] = weakref.ref(view) getattr(view, signal).connect(slot) view.sigResized.connect(slot) if (view.autoRangeEnabled()[axis] is not False): self.enableAutoRange(axis, False) slot() elif (self.autoRangeEnabled()[axis] is False): slot() self.sigStateChanged.emit(self)
'return the screen geometry of the viewbox'
def screenGeometry(self):
v = self.getViewWidget() if (v is None): return None b = self.sceneBoundingRect() wr = v.mapFromScene(b).boundingRect() pos = v.mapToGlobal(v.pos()) wr.adjust(pos.x(), pos.y(), pos.x(), pos.y()) return wr
'By default, the positive y-axis points upward on the screen. Use invertY(True) to reverse the y-axis.'
def invertY(self, b=True):
self._invertAxis(1, b)