desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'By default, the positive x-axis points rightward on the screen. Use invertX(True) to reverse the x-axis.'
| def invertX(self, b=True):
| self._invertAxis(0, b)
|
'If the aspect ratio is locked, view scaling must always preserve the aspect ratio.
By default, the ratio is set to 1; x and y both have the same scaling.
This ratio can be overridden (xScale/yScale), or use None to lock in the current ratio.'
| def setAspectLocked(self, lock=True, ratio=1):
| if (not lock):
if (self.state['aspectLocked'] == False):
return
self.state['aspectLocked'] = False
else:
rect = self.rect()
vr = self.viewRect()
if ((rect.height() == 0) or (vr.width() == 0) or (vr.height() == 0)):
currentRatio = 1.0
else:
... |
'Return the transform that maps from child(item in the childGroup) coordinates to local coordinates.
(This maps from inside the viewbox to outside)'
| def childTransform(self):
| self.updateMatrix()
m = self.childGroup.transform()
return m
|
'Maps from the local coordinates of the ViewBox to the coordinate system displayed inside the ViewBox'
| def mapToView(self, obj):
| m = fn.invertQTransform(self.childTransform())
return m.map(obj)
|
'Maps from the coordinate system displayed inside the ViewBox to the local coordinates of the ViewBox'
| def mapFromView(self, obj):
| m = self.childTransform()
return m.map(obj)
|
'Maps from scene coordinates to the coordinate system displayed inside the ViewBox'
| def mapSceneToView(self, obj):
| return self.mapToView(self.mapFromScene(obj))
|
'Maps from the coordinate system displayed inside the ViewBox to scene coordinates'
| def mapViewToScene(self, obj):
| return self.mapToScene(self.mapFromView(obj))
|
'Maps *obj* from the local coordinate system of *item* to the view coordinates'
| def mapFromItemToView(self, item, obj):
| return self.childGroup.mapFromItem(item, obj)
|
'Maps *obj* from view coordinates to the local coordinate system of *item*.'
| def mapFromViewToItem(self, item, obj):
| return self.childGroup.mapToItem(item, obj)
|
'Return the (width, height) of a screen pixel in view coordinates.'
| def viewPixelSize(self):
| o = self.mapToView(Point(0, 0))
(px, py) = [Point((self.mapToView(v) - o)) for v in self.pixelVectors()]
return (px.length(), py.length())
|
'Return the bounding rect of the item in view coordinates'
| def itemBoundingRect(self, item):
| return self.mapSceneToView(item.sceneBoundingRect()).boundingRect()
|
'This routine should capture key presses in the current view box.
Key presses are used only when mouse mode is RectMode
The following events are implemented:
ctrl-A : zooms out to the default "full" view of the plot
ctrl-+ : moves forward in the zooming stack (if it exists)
ctrl-- : moves backward in the zooming stack ... | def keyPressEvent(self, ev):
| ev.accept()
if (ev.text() == '-'):
self.scaleHistory((-1))
elif (ev.text() in ['+', '=']):
self.scaleHistory(1)
elif (ev.key() == QtCore.Qt.Key_Backspace):
self.scaleHistory(len(self.axHistory))
else:
ev.ignore()
|
'Return a list of all children and grandchildren of this ViewBox'
| def allChildren(self, item=None):
| if (item is None):
item = self.childGroup
children = [item]
for ch in item.childItems():
children.extend(self.allChildren(ch))
return children
|
'Return the bounding range of all children.
[[xmin, xmax], [ymin, ymax]]
Values may be None if there are no specific bounds for an axis.'
| def childrenBounds(self, frac=None, orthoRange=(None, None), items=None):
| profiler = debug.Profiler()
if (items is None):
items = self.addedItems
(px, py) = [(v.length() if (v is not None) else 0) for v in self.childGroup.pixelVectors()]
itemBounds = []
for item in items:
if (not item.isVisible()):
continue
useX = True
useY = Tr... |
'Temporarily display the bounding rect of an item and lines connecting to the center of the view.
This is useful for determining the location of items that may be out of the range of the ViewBox.
if allChildren is True, then the bounding rect of all item\'s children will be shown instead.'
| def locate(self, item, timeout=3.0, children=False):
| self.clearLocate()
if (item.scene() is not self.scene()):
raise Exception('Item does not share a scene with this ViewBox.')
c = self.viewRect().center()
if children:
br = self.mapFromItemToView(item, item.childrenBoundingRect()).boundingRect()
else:
br... |
'**Arguments:**
*text* The text to display
*color* The color of the text (any format accepted by pg.mkColor)
*html* If specified, this overrides both *text* and *color*
*anchor* A QPointF or (x,y) sequence indicating what region of the text box will
be anchored to the item\'s position. ... | def __init__(self, text='', color=(200, 200, 200), html=None, anchor=(0, 0), border=None, fill=None, angle=0, rotateAxis=None):
| self.anchor = Point(anchor)
self.rotateAxis = (None if (rotateAxis is None) else Point(rotateAxis))
GraphicsObject.__init__(self)
self.textItem = QtGui.QGraphicsTextItem()
self.textItem.setParentItem(self)
self._lastTransform = None
self._lastScene = None
self._bounds = QtCore.QRectF()
... |
'Set the text of this item.
This method sets the plain text of the item; see also setHtml().'
| def setText(self, text, color=None):
| if (color is not None):
self.setColor(color)
self.textItem.setPlainText(text)
self.updateTextPos()
|
'Set the plain text to be rendered by this item.
See QtGui.QGraphicsTextItem.setPlainText().'
| def setPlainText(self, *args):
| self.textItem.setPlainText(*args)
self.updateTextPos()
|
'Set the HTML code to be rendered by this item.
See QtGui.QGraphicsTextItem.setHtml().'
| def setHtml(self, *args):
| self.textItem.setHtml(*args)
self.updateTextPos()
|
'Set the width of the text.
If the text requires more space than the width limit, then it will be
wrapped into multiple lines.
See QtGui.QGraphicsTextItem.setTextWidth().'
| def setTextWidth(self, *args):
| self.textItem.setTextWidth(*args)
self.updateTextPos()
|
'Set the font for this text.
See QtGui.QGraphicsTextItem.setFont().'
| def setFont(self, *args):
| self.textItem.setFont(*args)
self.updateTextPos()
|
'Set the color for this text.
See QtGui.QGraphicsItem.setDefaultTextColor().'
| def setColor(self, color):
| self.color = fn.mkColor(color)
self.textItem.setDefaultTextColor(self.color)
|
'If *image* (ImageItem) is provided, then the control will be automatically linked to the image and changes to the control will be immediately reflected in the image\'s appearance.
By default, the histogram is rendered with a fill. For performance, set *fillHistogram* = False.'
| def __init__(self, image=None, fillHistogram=True):
| GraphicsWidget.__init__(self)
self.lut = None
self.imageItem = (lambda : None)
self.layout = QtGui.QGraphicsGridLayout()
self.setLayout(self.layout)
self.layout.setContentsMargins(1, 1, 1, 1)
self.layout.setSpacing(0)
self.vb = ViewBox(parent=self)
self.vb.setMaximumWidth(152)
se... |
'Set the Y range on the histogram plot. This disables auto-scaling.'
| def setHistogramRange(self, mn, mx, padding=0.1):
| self.vb.enableAutoRange(self.vb.YAxis, False)
self.vb.setYRange(mn, mx, padding)
|
'Enable auto-scaling on the histogram plot.'
| def autoHistogramRange(self):
| self.vb.enableAutoRange(self.vb.XYAxes)
|
'Set an ImageItem to have its levels and LUT automatically controlled
by this HistogramLUTItem.'
| def setImageItem(self, img):
| self.imageItem = weakref.ref(img)
img.sigImageChanged.connect(self.imageChanged)
img.setLookupTable(self.getLookupTable)
self.regionChanged()
self.imageChanged(autoLevel=True)
|
'Return a lookup table from the color gradient defined by this
HistogramLUTItem.'
| def getLookupTable(self, img=None, n=None, alpha=None):
| if (n is None):
if (img.dtype == np.uint8):
n = 256
else:
n = 512
if (self.lut is None):
self.lut = self.gradient.getLookupTable(n, alpha=alpha)
return self.lut
|
'Return the min and max levels.'
| def getLevels(self):
| return self.region.getRegion()
|
'Set the min and max levels.'
| def setLevels(self, mn, mx):
| self.region.setRegion([mn, mx])
|
'Return the state of the widget in a format suitable for storing to
disk. (Points are converted to tuple)
Combined with setState(), this allows ROIs to be easily saved and
restored.'
| def saveState(self):
| state = {}
state['pos'] = tuple(self.state['pos'])
state['size'] = tuple(self.state['size'])
state['angle'] = self.state['angle']
return state
|
'Set the state of the ROI from a structure generated by saveState() or
getState().'
| def setState(self, state, update=True):
| self.setPos(state['pos'], update=False)
self.setSize(state['size'], update=False)
self.setAngle(state['angle'], update=update)
|
'Return the bounding rectangle of this ROI in the coordinate system
of its parent.'
| def parentBounds(self):
| return self.mapToParent(self.boundingRect()).boundingRect()
|
'Set the pen to use when drawing the ROI shape.
For arguments, see :func:`mkPen <pyqtgraph.mkPen>`.'
| def setPen(self, *args, **kwargs):
| self.pen = fn.mkPen(*args, **kwargs)
self.currentPen = self.pen
self.update()
|
'Return the size (w,h) of the ROI.'
| def size(self):
| return self.getState()['size']
|
'Return the position (x,y) of the ROI\'s origin.
For most ROIs, this will be the lower-left corner.'
| def pos(self):
| return self.getState()['pos']
|
'Return the angle of the ROI in degrees.'
| def angle(self):
| return self.getState()['angle']
|
'Set the position of the ROI (in the parent\'s coordinate system).
Accepts either separate (x, y) arguments or a single :class:`Point` or
``QPointF`` argument.
By default, this method causes both ``sigRegionChanged`` and
``sigRegionChangeFinished`` to be emitted. If *finish* is False, then
``sigRegionChangeFinished`` w... | def setPos(self, pos, y=None, update=True, finish=True):
| if (y is None):
pos = Point(pos)
else:
if isinstance(y, bool):
raise TypeError('Positional arguments to setPos() must be numerical.')
pos = Point(pos, y)
self.state['pos'] = pos
QtGui.QGraphicsItem.setPos(self, pos)
if update:
self.stateC... |
'Set the size of the ROI. May be specified as a QPoint, Point, or list of two values.
See setPos() for an explanation of the update and finish arguments.'
| def setSize(self, size, update=True, finish=True):
| size = Point(size)
self.prepareGeometryChange()
self.state['size'] = size
if update:
self.stateChanged(finish=finish)
|
'Set the angle of rotation (in degrees) for this ROI.
See setPos() for an explanation of the update and finish arguments.'
| def setAngle(self, angle, update=True, finish=True):
| self.state['angle'] = angle
tr = QtGui.QTransform()
tr.rotate(angle)
self.setTransform(tr)
if update:
self.stateChanged(finish=finish)
|
'Resize the ROI by scaling relative to *center*.
See setPos() for an explanation of the *update* and *finish* arguments.'
| def scale(self, s, center=[0, 0], update=True, finish=True):
| c = self.mapToParent((Point(center) * self.state['size']))
self.prepareGeometryChange()
newSize = (self.state['size'] * s)
c1 = self.mapToParent((Point(center) * newSize))
newPos = ((self.state['pos'] + c) - c1)
self.setSize(newSize, update=False)
self.setPos(newPos, update=update, finish=fi... |
'Move the ROI to a new position.
Accepts either (x, y, snap) or ([x,y], snap) as arguments
If the ROI is bounded and the move would exceed boundaries, then the ROI
is moved to the nearest acceptable position instead.
*snap* can be:
None (default) use self.translateSnap and self.snapSize to determine whether/how to sna... | def translate(self, *args, **kargs):
| if (len(args) == 1):
pt = args[0]
else:
pt = args
newState = self.stateCopy()
newState['pos'] = (newState['pos'] + pt)
snap = kargs.get('snap', None)
if (snap is None):
snap = self.translateSnap
if (snap is not False):
newState['pos'] = self.getSnapPosition(ne... |
'Rotate the ROI by *angle* degrees.
Also accepts *update* and *finish* arguments (see setPos() for a
description of these).'
| def rotate(self, angle, update=True, finish=True):
| self.setAngle((self.angle() + angle), update=update, finish=finish)
|
'Add a new translation handle to the ROI. Dragging the handle will move
the entire ROI without changing its angle or shape.
Note that, by default, ROIs may be moved by dragging anywhere inside the
ROI. However, for larger ROIs it may be desirable to disable this and
instead provide one or more translation handles.
**Ar... | def addTranslateHandle(self, pos, axes=None, item=None, name=None, index=None):
| pos = Point(pos)
return self.addHandle({'name': name, 'type': 't', 'pos': pos, 'item': item}, index=index)
|
'Add a new free handle to the ROI. Dragging free handles has no effect
on the position or shape of the ROI.
**Arguments**
pos (length-2 sequence) The position of the handle
relative to the shape of the ROI. A value of (0,0)
indicates the origin, whereas (1, 1) indicates the
upper-right corner, regardles... | def addFreeHandle(self, pos=None, axes=None, item=None, name=None, index=None):
| if (pos is not None):
pos = Point(pos)
return self.addHandle({'name': name, 'type': 'f', 'pos': pos, 'item': item}, index=index)
|
'Add a new scale handle to the ROI. Dragging a scale handle allows the
user to change the height and/or width of the ROI.
**Arguments**
pos (length-2 sequence) The position of the handle
relative to the shape of the ROI. A value of (0,0)
indicates the origin, whereas (1, 1) indicates the
upper-right cor... | def addScaleHandle(self, pos, center, axes=None, item=None, name=None, lockAspect=False, index=None):
| pos = Point(pos)
center = Point(center)
info = {'name': name, 'type': 's', 'center': center, 'pos': pos, 'item': item, 'lockAspect': lockAspect}
if (pos.x() == center.x()):
info['xoff'] = True
if (pos.y() == center.y()):
info['yoff'] = True
return self.addHandle(info, index=index... |
'Add a new rotation handle to the ROI. Dragging a rotation handle allows
the user to change the angle of the ROI.
**Arguments**
pos (length-2 sequence) The position of the handle
relative to the shape of the ROI. A value of (0,0)
indicates the origin, whereas (1, 1) indicates the
upper-right corner, reg... | def addRotateHandle(self, pos, center, item=None, name=None, index=None):
| pos = Point(pos)
center = Point(center)
return self.addHandle({'name': name, 'type': 'r', 'center': center, 'pos': pos, 'item': item}, index=index)
|
'Add a new scale+rotation handle to the ROI. When dragging a handle of
this type, the user can simultaneously rotate the ROI around an
arbitrary center point as well as scale the ROI by dragging the handle
toward or away from the center point.
**Arguments**
pos (length-2 sequence) The position of the ha... | def addScaleRotateHandle(self, pos, center, item=None, name=None, index=None):
| pos = Point(pos)
center = Point(center)
if ((pos[0] != center[0]) and (pos[1] != center[1])):
raise Exception('Scale/rotate handles must have either the same x or y coordinate as their center point.')
return self.addHandle({'name': name, 'type': 'sr', 'c... |
'Add a new rotation+free handle to the ROI. When dragging a handle of
this type, the user can rotate the ROI around an
arbitrary center point, while moving toward or away from the center
point has no effect on the shape of the ROI.
**Arguments**
pos (length-2 sequence) The position of the handle
relativ... | def addRotateFreeHandle(self, pos, center, axes=None, item=None, name=None, index=None):
| pos = Point(pos)
center = Point(center)
return self.addHandle({'name': name, 'type': 'rf', 'center': center, 'pos': pos, 'item': item}, index=index)
|
'Return the index of *handle* in the list of this ROI\'s handles.'
| def indexOfHandle(self, handle):
| if isinstance(handle, Handle):
index = [i for (i, info) in enumerate(self.handles) if (info['item'] is handle)]
if (len(index) == 0):
raise Exception('Cannot return handle index; not attached to this ROI')
return index[0]
else:
return handle
|
'Remove a handle from this ROI. Argument may be either a Handle
instance or the integer index of the handle.'
| def removeHandle(self, handle):
| index = self.indexOfHandle(handle)
handle = self.handles[index]['item']
self.handles.pop(index)
handle.disconnectROI(self)
if (len(handle.rois) == 0):
self.scene().removeItem(handle)
self.stateChanged()
|
'Replace one handle in the ROI for another. This is useful when
connecting multiple ROIs together.
*oldHandle* may be a Handle instance or the index of a handle to be
replaced.'
| def replaceHandle(self, oldHandle, newHandle):
| index = self.indexOfHandle(oldHandle)
info = self.handles[index]
self.removeHandle(index)
info['item'] = newHandle
info['pos'] = newHandle.pos()
self.addHandle(info, index=index)
|
'Returns the position of handles in the ROI\'s coordinate system.
The format returned is a list of (name, pos) tuples.'
| def getLocalHandlePositions(self, index=None):
| if (index == None):
positions = []
for h in self.handles:
positions.append((h['name'], h['pos']))
return positions
else:
return (self.handles[index]['name'], self.handles[index]['pos'])
|
'Returns the position of handles in the scene coordinate system.
The format returned is a list of (name, pos) tuples.'
| def getSceneHandlePositions(self, index=None):
| if (index == None):
positions = []
for h in self.handles:
positions.append((h['name'], h['item'].scenePos()))
return positions
else:
return (self.handles[index]['name'], self.handles[index]['item'].scenePos())
|
'Return a list of this ROI\'s Handles.'
| def getHandles(self):
| return [h['item'] for h in self.handles]
|
'When handles move, they must ask the ROI if the move is acceptable.
By default, this always returns True. Subclasses may wish override.'
| def checkPointMove(self, handle, pos, modifiers):
| return True
|
'Process changes to the state of the ROI.
If there are any changes, then the positions of handles are updated accordingly
and sigRegionChanged is emitted. If finish is True, then
sigRegionChangeFinished will also be emitted.'
| def stateChanged(self, finish=True):
| changed = False
if (self.lastState is None):
changed = True
else:
state = self.getState()
for k in list(state.keys()):
if (state[k] != self.lastState[k]):
changed = True
self.prepareGeometryChange()
if changed:
for h in self.handles:
... |
'Return a tuple of slice objects that can be used to slice the region
from *data* that is covered by the bounding rectangle of this ROI.
Also returns the transform that maps the ROI into data coordinates.
If returnSlice is set to False, the function returns a pair of tuples with the values that would have
been used to ... | def getArraySlice(self, data, img, axes=(0, 1), returnSlice=True):
| dShape = (data.shape[axes[0]], data.shape[axes[1]])
try:
tr = (self.sceneTransform() * fn.invertQTransform(img.sceneTransform()))
except np.linalg.linalg.LinAlgError:
return None
axisOrder = img.axisOrder
if (axisOrder == 'row-major'):
tr.scale((float(dShape[1]) / img.width()... |
'Use the position and orientation of this ROI relative to an imageItem
to pull a slice from an array.
**Arguments**
data The array to slice from. Note that this array does
*not* have to be the same data that is represented
in *img*.
img (ImageItem or other suitable QGraphicsItem)
Used to ... | def getArrayRegion(self, data, img, axes=(0, 1), returnMappedCoords=False, **kwds):
| fromBR = kwds.pop('fromBoundingRect', False)
(shape, vectors, origin) = self.getAffineSliceParams(data, img, axes, fromBoundingRect=fromBR)
if (not returnMappedCoords):
rgn = fn.affineSlice(data, shape=shape, vectors=vectors, origin=origin, axes=axes, **kwds)
return rgn
else:
kwd... |
'Returns the parameters needed to use :func:`affineSlice <pyqtgraph.affineSlice>`
(shape, vectors, origin) to extract a subset of *data* using this ROI
and *img* to specify the subset.
If *fromBoundingRect* is True, then the ROI\'s bounding rectangle is used
rather than the shape of the ROI.
See :func:`getArrayRegion <... | def getAffineSliceParams(self, data, img, axes=(0, 1), fromBoundingRect=False):
| if (self.scene() is not img.scene()):
raise Exception('ROI and target item must be members of the same scene.')
origin = img.mapToData(self.mapToItem(img, QtCore.QPointF(0, 0)))
vx = (img.mapToData(self.mapToItem(img, QtCore.QPointF(1, 0))) - origin)
vy = (img.mapTo... |
'Return an array of 0.0-1.0 into which the shape of the item has been drawn.
This can be used to mask array selections.'
| def renderShapeMask(self, width, height):
| if ((width == 0) or (height == 0)):
return np.empty((width, height), dtype=float)
im = QtGui.QImage(width, height, QtGui.QImage.Format_ARGB32)
im.fill(0)
p = QtGui.QPainter(im)
p.setPen(fn.mkPen(None))
p.setBrush(fn.mkBrush('w'))
shape = self.shape()
bounds = shape.boundingRect()... |
'Return global transformation (rotation angle+translation) required to move
from relative state to current state. If relative state isn\'t specified,
then we use the state of the ROI when mouse is pressed.'
| def getGlobalTransform(self, relativeTo=None):
| if (relativeTo == None):
relativeTo = self.preMoveState
st = self.getState()
relativeTo['scale'] = relativeTo['size']
st['scale'] = st['size']
t1 = SRTTransform(relativeTo)
t2 = SRTTransform(st)
return (t2 / t1)
|
'Return the positions of all handles in local coordinates.'
| def getHandlePositions(self):
| pos = [self.mapFromScene(self.lines[0].getHandles()[0].scenePos())]
for l in self.lines:
pos.append(self.mapFromScene(l.getHandles()[1].scenePos()))
return pos
|
'Add a new segment to the ROI connecting from the previous endpoint to *pos*.
(pos is specified in the parent coordinate system of the MultiRectROI)'
| def addSegment(self, pos=(0, 0), scaleHandle=False, connectTo=None):
| if (connectTo is None):
connectTo = self.lines[(-1)].getHandles()[1]
newRoi = ROI((0, 0), [1, 5], parent=self, pen=self.pen, **self.roiArgs)
self.lines.append(newRoi)
if isinstance(connectTo, Handle):
self.lines[(-1)].addScaleRotateHandle([0, 0.5], [1, 0.5], item=connectTo)
newRo... |
'Remove a segment from the ROI.'
| def removeSegment(self, index=(-1)):
| roi = self.lines[index]
self.lines.pop(index)
self.scene().removeItem(roi)
roi.sigRegionChanged.disconnect(self.roiChangedEvent)
roi.sigRegionChangeStarted.disconnect(self.roiChangeStartedEvent)
roi.sigRegionChangeFinished.disconnect(self.roiChangeFinishedEvent)
self.sigRegionChanged.emit(se... |
'Return the result of ROI.getArrayRegion() masked by the elliptical shape
of the ROI. Regions outside the ellipse are set to 0.'
| def getArrayRegion(self, arr, img=None, axes=(0, 1), **kwds):
| arr = ROI.getArrayRegion(self, arr, img, axes, **kwds)
if ((arr is None) or (arr.shape[axes[0]] == 0) or (arr.shape[axes[1]] == 0)):
return arr
w = arr.shape[axes[0]]
h = arr.shape[axes[1]]
mask = np.fromfunction((lambda x, y: (((((((x + 0.5) / (w / 2.0)) - 1) ** 2) + ((((y + 0.5) / (h / 2.0... |
'Set the complete sequence of points displayed by this ROI.
**Arguments**
points List of (x,y) tuples specifying handle locations to set.
closed If bool, then this will set whether the ROI is closed
(the last point is connected to the first point). If
None, then the closed mode is left unchanged.'
| def setPoints(self, points, closed=None):
| if (closed is not None):
self.closed = closed
self.clearPoints()
for p in points:
self.addFreeHandle(p)
start = ((-1) if self.closed else 0)
for i in range(start, (len(self.handles) - 1)):
self.addSegment(self.handles[i]['item'], self.handles[(i + 1)]['item'])
|
'Remove all handles and segments.'
| def clearPoints(self):
| while (len(self.handles) > 0):
self.removeHandle(self.handles[0]['item'])
|
'Return the result of ROI.getArrayRegion(), masked by the shape of the
ROI. Values outside the ROI shape are set to 0.'
| def getArrayRegion(self, data, img, axes=(0, 1), **kwds):
| br = self.boundingRect()
if (br.width() > 1000):
raise Exception()
sliced = ROI.getArrayRegion(self, data, img, axes=axes, fromBoundingRect=True, **kwds)
if (img.axisOrder == 'col-major'):
mask = self.renderShapeMask(sliced.shape[axes[0]], sliced.shape[axes[1]])
else:
mask = ... |
'Use the position of this ROI relative to an imageItem to pull a slice
from an array.
Since this pulls 1D data from a 2D coordinate system, the return value
will have ndim = data.ndim-1
See ROI.getArrayRegion() for a description of the arguments.'
| def getArrayRegion(self, data, img, axes=(0, 1), order=1, returnMappedCoords=False, **kwds):
| imgPts = [self.mapToItem(img, h.pos()) for h in self.endpoints]
rgns = []
coords = []
d = Point((imgPts[1] - imgPts[0]))
o = Point(imgPts[0])
rgn = fn.affineSlice(data, shape=(int(d.length()),), vectors=[Point(d.norm())], origin=o, axes=axes, order=order, returnCoords=returnMappedCoords, **kwds)... |
'Change the data displayed by the graph.
**Arguments:**
pos (N,2) array of the positions of each node in the graph.
adj (M,2) array of connection data. Each row contains indexes
of two nodes that are connected.
pen The pen to use when drawing lines between connected
nodes. May be one... | def setData(self, **kwds):
| if ('adj' in kwds):
self.adjacency = kwds.pop('adj')
if (self.adjacency.dtype.kind not in 'iu'):
raise Exception('adjacency array must have int or unsigned type.')
self._update()
if ('pos' in kwds):
self.pos = kwds['pos']
self._update()
... |
'Set the pen used to draw graph lines.
May be:
* None to disable line drawing
* Record array with fields (red, green, blue, alpha, width)
* Any set of arguments and keyword arguments accepted by
:func:`mkPen <pyqtgraph.mkPen>`.
* \'default\' to use the default foreground color.'
| def setPen(self, *args, **kwargs):
| if ((len(args) == 1) and (len(kwargs) == 0)):
self.pen = args[0]
else:
self.pen = fn.mkPen(*args, **kwargs)
self.picture = None
self.update()
|
'**Bases:** :class:`GraphicsItem <pyqtgraph.GraphicsItem>`, :class:`QtGui.QGraphicsWidget`
Extends QGraphicsWidget with several helpful methods and workarounds for PyQt bugs.
Most of the extra functionality is inherited from :class:`GraphicsItem <pyqtgraph.GraphicsItem>`.'
| def __init__(self, *args, **kargs):
| QtGui.QGraphicsWidget.__init__(self, *args, **kargs)
GraphicsItem.__init__(self)
|
'There are many different ways to create a PlotDataItem:
**Data initialization arguments:** (x,y data only)
PlotDataItem(xValues, yValues) x and y values may be any sequence (including ndarray) of real numbers
PlotDataItem(yValues) y values only -- x will be automatically set to range(len(y))
PlotDat... | def __init__(self, *args, **kargs):
| GraphicsObject.__init__(self)
self.setFlag(self.ItemHasNoContents)
self.xData = None
self.yData = None
self.xDisp = None
self.yDisp = None
self.curve = PlotCurveItem()
self.scatter = ScatterPlotItem()
self.curve.setParentItem(self)
self.scatter.setParentItem(self)
self.curve.... |
'| Sets the pen used to draw lines between points.
| *pen* can be a QPen or any argument accepted by :func:`pyqtgraph.mkPen() <pyqtgraph.mkPen>`'
| def setPen(self, *args, **kargs):
| pen = fn.mkPen(*args, **kargs)
self.opts['pen'] = pen
self.updateItems()
|
'| Sets the shadow pen used to draw lines between points (this is for enhancing contrast or
emphacizing data).
| This line is drawn behind the primary pen (see :func:`setPen() <pyqtgraph.PlotDataItem.setPen>`)
and should generally be assigned greater width than the primary pen.
| *pen* can be a QPen or any argument acc... | def setShadowPen(self, *args, **kargs):
| pen = fn.mkPen(*args, **kargs)
self.opts['shadowPen'] = pen
self.updateItems()
|
'Set the downsampling mode of this item. Downsampling reduces the number
of samples drawn to increase performance.
**Arguments:**
ds (int) Reduce visible plot samples by this factor. To disable,
set ds=1.
auto (bool) If True, automatically pick *ds* based on visible range
mode \'subsa... | def setDownsampling(self, ds=None, auto=None, method=None):
| changed = False
if (ds is not None):
if (self.opts['downsample'] != ds):
changed = True
self.opts['downsample'] = ds
if ((auto is not None) and (self.opts['autoDownsample'] != auto)):
self.opts['autoDownsample'] = auto
changed = True
if (method is not None... |
'Clear any data displayed by this item and display new data.
See :func:`__init__() <pyqtgraph.PlotDataItem.__init__>` for details; it accepts the same arguments.'
| def setData(self, *args, **kargs):
| profiler = debug.Profiler()
y = None
x = None
if (len(args) == 1):
data = args[0]
dt = dataType(data)
if (dt == 'empty'):
pass
elif (dt == 'listOfValues'):
y = np.array(data)
elif (dt == 'Nx2array'):
x = data[:, 0]
y... |
'Returns the range occupied by the data (along a specific axis) in this item.
This method is called by ViewBox when auto-scaling.
**Arguments:**
ax (0 or 1) the axis for which to return this item\'s data range
frac (float 0.0-1.0) Specifies what fraction of the total data
range to return. By def... | def dataBounds(self, ax, frac=1.0, orthoRange=None):
| range = [None, None]
if self.curve.isVisible():
range = self.curve.dataBounds(ax, frac, orthoRange)
elif self.scatter.isVisible():
r2 = self.scatter.dataBounds(ax, frac, orthoRange)
range = [(r2[0] if (range[0] is None) else (range[0] if (r2[0] is None) else min(r2[0], range[0]))), (... |
'Return the size in pixels that this item may draw beyond the values returned by dataBounds().
This method is called by ViewBox when auto-scaling.'
| def pixelPadding(self):
| pad = 0
if self.curve.isVisible():
pad = max(pad, self.curve.pixelPadding())
elif self.scatter.isVisible():
pad = max(pad, self.scatter.pixelPadding())
return pad
|
'**Arguments:**
orientation Set the orientation of the gradient. Options are: \'left\', \'right\'
\'top\', and \'bottom\'.
allowAdd Specifies whether ticks can be added to the item by the user.
tickPen Default is white. Specifies the color of the outline of the ticks.
Can be any of the valid argument... | def __init__(self, orientation='bottom', allowAdd=True, **kargs):
| GraphicsWidget.__init__(self)
self.orientation = orientation
self.length = 100
self.tickSize = 15
self.ticks = {}
self.maxDim = 20
self.allowAdd = allowAdd
if ('tickPen' in kargs):
self.tickPen = fn.mkPen(kargs['tickPen'])
else:
self.tickPen = fn.mkPen('w')
self.o... |
'Set the orientation of the TickSliderItem.
**Arguments:**
orientation Options are: \'left\', \'right\', \'top\', \'bottom\'
The orientation option specifies which side of the slider the
ticks are on, as well as whether the slider is vertical (\'right\'
and \'left\') or horizontal (\'top\' and \'bottom\').'
| def setOrientation(self, orientation):
| self.orientation = orientation
self.setMaxDim()
self.resetTransform()
ort = orientation
if (ort == 'top'):
transform = QtGui.QTransform.fromScale(1, (-1))
transform.translate(0, (- self.height()))
self.setTransform(transform)
elif (ort == 'left'):
transform = QtGu... |
'Add a tick to the item.
**Arguments:**
x Position where tick should be added.
color Color of added tick. If color is not specified, the color will be
white.
movable Specifies whether the tick is movable with the mouse.'
| def addTick(self, x, color=None, movable=True):
| if (color is None):
color = QtGui.QColor(255, 255, 255)
tick = Tick(self, [(x * self.length), 0], color, movable, self.tickSize, pen=self.tickPen)
self.ticks[tick] = x
tick.setParentItem(self)
return tick
|
'Removes the specified tick.'
| def removeTick(self, tick):
| del self.ticks[tick]
tick.setParentItem(None)
if (self.scene() is not None):
self.scene().removeItem(tick)
|
'Set the color of the specified tick.
**Arguments:**
tick Can be either an integer corresponding to the index of the tick
or a Tick object. Ex: if you had a slider with 3 ticks and you
wanted to change the middle tick, the index would be 1.
color The color to make the tick. Can be any argument that... | def setTickColor(self, tick, color):
| tick = self.getTick(tick)
tick.color = color
tick.update()
|
'Set the position (along the slider) of the tick.
**Arguments:**
tick Can be either an integer corresponding to the index of the tick
or a Tick object. Ex: if you had a slider with 3 ticks and you
wanted to change the middle tick, the index would be 1.
val The desired position of the tick. If v... | def setTickValue(self, tick, val):
| tick = self.getTick(tick)
val = min(max(0.0, val), 1.0)
x = (val * self.length)
pos = tick.pos()
pos.setX(x)
tick.setPos(pos)
self.ticks[tick] = val
self.updateGradient()
|
'Return the value (from 0.0 to 1.0) of the specified tick.
**Arguments:**
tick Can be either an integer corresponding to the index of the tick
or a Tick object. Ex: if you had a slider with 3 ticks and you
wanted the value of the middle tick, the index would be 1.'
| def tickValue(self, tick):
| tick = self.getTick(tick)
return self.ticks[tick]
|
'Return the Tick object at the specified index.
**Arguments:**
tick An integer corresponding to the index of the desired tick. If the
argument is not an integer it will be returned unchanged.'
| def getTick(self, tick):
| if (type(tick) is int):
tick = self.listTicks()[tick][0]
return tick
|
'Return a sorted list of all the Tick objects on the slider.'
| def listTicks(self):
| ticks = list(self.ticks.items())
sortList(ticks, (lambda a, b: cmp(a[1], b[1])))
return ticks
|
'Create a new GradientEditorItem.
All arguments are passed to :func:`TickSliderItem.__init__ <pyqtgraph.TickSliderItem.__init__>`
**Arguments:**
orientation Set the orientation of the gradient. Options are: \'left\', \'right\'
\'top\', and \'bottom\'.
allowAdd Default is True. Specifies whether ticks can b... | def __init__(self, *args, **kargs):
| self.currentTick = None
self.currentTickColor = None
self.rectSize = 15
self.gradRect = QtGui.QGraphicsRectItem(QtCore.QRectF(0, self.rectSize, 100, self.rectSize))
self.backgroundRect = QtGui.QGraphicsRectItem(QtCore.QRectF(0, (- self.rectSize), 100, self.rectSize))
self.backgroundRect.setBrush... |
'Set the orientation of the GradientEditorItem.
**Arguments:**
orientation Options are: \'left\', \'right\', \'top\', \'bottom\'
The orientation option specifies which side of the gradient the
ticks are on, as well as whether the gradient is vertical (\'right\'
and \'left\') or horizontal (\'top\' and \'bottom\').'... | def setOrientation(self, orientation):
| TickSliderItem.setOrientation(self, orientation)
self.translate(0, self.rectSize)
|
'Load a predefined gradient. Currently defined gradients are:'
| @addGradientListToDocstring()
def loadPreset(self, name):
| self.restoreState(Gradients[name])
|
'Set the color mode for the gradient. Options are: \'hsv\', \'rgb\''
| def setColorMode(self, cm):
| if (cm not in ['rgb', 'hsv']):
raise Exception(("Unknown color mode %s. Options are 'rgb' and 'hsv'." % str(cm)))
try:
self.rgbAction.blockSignals(True)
self.hsvAction.blockSignals(True)
self.rgbAction.setChecked((cm == 'rgb'))
self.hsvAction.setCh... |
'Return a ColorMap object representing the current state of the editor.'
| def colorMap(self):
| if (self.colorMode == 'hsv'):
raise NotImplementedError('hsv colormaps not yet supported')
pos = []
color = []
for (t, x) in self.listTicks():
pos.append(x)
c = t.color
color.append([c.red(), c.green(), c.blue(), c.alpha()])
return ColorMap(np.array(pos), ... |
'Return a QLinearGradient object.'
| def getGradient(self):
| g = QtGui.QLinearGradient(QtCore.QPointF(0, 0), QtCore.QPointF(self.length, 0))
if (self.colorMode == 'rgb'):
ticks = self.listTicks()
g.setStops([(x, QtGui.QColor(t.color)) for (t, x) in ticks])
elif (self.colorMode == 'hsv'):
ticks = self.listTicks()
stops = []
stop... |
'Return a color for a given value.
**Arguments:**
x Value (position on gradient) of requested color.
toQColor If true, returns a QColor object, else returns a (r,g,b,a) tuple.'
| def getColor(self, x, toQColor=True):
| ticks = self.listTicks()
if (x <= ticks[0][1]):
c = ticks[0][0].color
if toQColor:
return QtGui.QColor(c)
else:
return (c.red(), c.green(), c.blue(), c.alpha())
if (x >= ticks[(-1)][1]):
c = ticks[(-1)][0].color
if toQColor:
return ... |
'Return an RGB(A) lookup table (ndarray).
**Arguments:**
nPts The number of points in the returned lookup table.
alpha True, False, or None - Specifies whether or not alpha values are included
in the table.If alpha is None, alpha will be automatically determined.'
| def getLookupTable(self, nPts, alpha=None):
| if (alpha is None):
alpha = self.usesAlpha()
if alpha:
table = np.empty((nPts, 4), dtype=np.ubyte)
else:
table = np.empty((nPts, 3), dtype=np.ubyte)
for i in range(nPts):
x = (float(i) / (nPts - 1))
color = self.getColor(x, toQColor=False)
table[i] = color... |
'Return True if any ticks have an alpha < 255'
| def usesAlpha(self):
| ticks = self.listTicks()
for t in ticks:
if (t[0].color.alpha() < 255):
return True
return False
|
'Return True if the gradient has exactly two stops in it: black at 0.0 and white at 1.0'
| def isLookupTrivial(self):
| ticks = self.listTicks()
if (len(ticks) != 2):
return False
if ((ticks[0][1] != 0.0) or (ticks[1][1] != 1.0)):
return False
c1 = fn.colorTuple(ticks[0][0].color)
c2 = fn.colorTuple(ticks[1][0].color)
if ((c1 != (0, 0, 0, 255)) or (c2 != (255, 255, 255, 255))):
return Fals... |
'Add a tick to the gradient. Return the tick.
**Arguments:**
x Position where tick should be added.
color Color of added tick. If color is not specified, the color will be
the color of the gradient at the specified position.
movable Specifies whether the tick is movable with the mouse.'
| def addTick(self, x, color=None, movable=True, finish=True):
| if (color is None):
color = self.getColor(x)
t = TickSliderItem.addTick(self, x, color=color, movable=movable)
t.colorChangeAllowed = True
t.removeAllowed = True
if finish:
self.sigGradientChangeFinished.emit(self)
return t
|
'Return a dictionary with parameters for rebuilding the gradient. Keys will include:
- \'mode\': hsv or rgb
- \'ticks\': a list of tuples (pos, (r,g,b,a))'
| def saveState(self):
| ticks = []
for t in self.ticks:
c = t.color
ticks.append((self.ticks[t], (c.red(), c.green(), c.blue(), c.alpha())))
state = {'mode': self.colorMode, 'ticks': ticks}
return state
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.