desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Return the terminal with the given name'
| def __getitem__(self, item):
| if (item not in self.terminals):
raise KeyError(item)
else:
return self.terminals[item]
|
'Return the name of this node.'
| def name(self):
| return self._name
|
'Rename this node. This will cause sigRenamed to be emitted.'
| def rename(self, name):
| oldName = self._name
self._name = name
self.sigRenamed.emit(self, oldName)
|
'Return the list of nodes which provide direct input to this node'
| def dependentNodes(self):
| nodes = set()
for t in self.inputs().values():
nodes |= set([i.node() for i in t.inputTerminals()])
return nodes
|
'Return this Node\'s control widget.
By default, Nodes have no control widget. Subclasses may reimplement this
method to provide a custom widget. This method is called by Flowcharts
when they are constructing their Node list.'
| def ctrlWidget(self):
| return None
|
'Set whether this node should be bypassed.
When bypassed, a Node\'s process() method is never called. In some cases,
data is automatically copied directly from specific input nodes to
output nodes instead (see the bypass argument to Terminal.__init__).
This is usually called when the user disables a node from the flowchart
control panel.'
| def bypass(self, byp):
| self._bypass = byp
if (self.bypassButton is not None):
self.bypassButton.setChecked(byp)
self.update()
|
'Return True if this Node is currently bypassed.'
| def isBypassed(self):
| return self._bypass
|
'Set the values on input terminals. For most nodes, this will happen automatically through Terminal.inputChanged.
This is normally only used for nodes with no connected inputs.'
| def setInput(self, **args):
| changed = False
for (k, v) in args.items():
term = self._inputs[k]
oldVal = term.value()
if (not fn.eq(oldVal, v)):
changed = True
term.setValue(v, process=False)
if (changed and ('_updatesHandled_' not in args)):
self.update()
|
'Return a dict of all input values currently assigned to this node.'
| def inputValues(self):
| vals = {}
for (n, t) in self.inputs().items():
vals[n] = t.value()
return vals
|
'Return a dict of all output values currently generated by this node.'
| def outputValues(self):
| vals = {}
for (n, t) in self.outputs().items():
vals[n] = t.value()
return vals
|
'Called whenever one of this node\'s terminals is connected elsewhere.'
| def connected(self, localTerm, remoteTerm):
| pass
|
'Called whenever one of this node\'s terminals is disconnected from another.'
| def disconnected(self, localTerm, remoteTerm):
| pass
|
'Collect all input values, attempt to process new output values, and propagate downstream.
Subclasses should call update() whenever thir internal state has changed
(such as when the user interacts with the Node\'s control widget). Update
is automatically called when the inputs to the node are changed.'
| def update(self, signal=True):
| vals = self.inputValues()
try:
if self.isBypassed():
out = self.processBypassed(vals)
else:
out = self.process(**strDict(vals))
if (out is not None):
if signal:
self.setOutput(**out)
else:
self.setOutputNoSignal(**out)
for (n, t) in self.inputs().items():
t.setValueAcceptable(True)
self.clearException()
except:
for (n, t) in self.outputs().items():
t.setValue(None)
self.setException(sys.exc_info())
if signal:
self.sigOutputChanged.emit(self)
|
'Called when the flowchart would normally call Node.process, but this node is currently bypassed.
The default implementation looks for output terminals with a bypass connection and returns the
corresponding values. Most Node subclasses will _not_ need to reimplement this method.'
| def processBypassed(self, args):
| result = {}
for term in list(self.outputs().values()):
byp = term.bypassValue()
if (byp is None):
result[term.name()] = None
else:
result[term.name()] = args.get(byp, None)
return result
|
'Return a dictionary representing the current state of this node
(excluding input / output values). This is used for saving/reloading
flowcharts. The default implementation returns this Node\'s position,
bypass state, and information about each of its terminals.
Subclasses may want to extend this method, adding extra keys to the returned
dict.'
| def saveState(self):
| pos = self.graphicsItem().pos()
state = {'pos': (pos.x(), pos.y()), 'bypass': self.isBypassed()}
termsEditable = (self._allowAddInput | self._allowAddOutput)
for term in (self._inputs.values() + self._outputs.values()):
termsEditable |= ((term._renamable | term._removable) | term._multiable)
if termsEditable:
state['terminals'] = self.saveTerminals()
return state
|
'Restore the state of this node from a structure previously generated
by saveState().'
| def restoreState(self, state):
| pos = state.get('pos', (0, 0))
self.graphicsItem().setPos(*pos)
self.bypass(state.get('bypass', False))
if ('terminals' in state):
self.restoreTerminals(state['terminals'])
|
'Cleans up after the node--removes terminals, graphicsItem, widget'
| def close(self):
| self.disconnectAll()
self.clearTerminals()
item = self.graphicsItem()
if (item.scene() is not None):
item.scene().removeItem(item)
self._graphicsItem = None
w = self.ctrlWidget()
if (w is not None):
w.setParent(None)
self.sigClosed.emit(self)
|
'Define what happens when the node is connected to a plot'
| def connectToPlot(self, node):
| raise Exception('Must be re-implemented in subclass')
|
'Define what happens when the node is disconnected from a plot'
| def disconnectFromPlot(self, plot):
| raise Exception('Must be re-implemented in subclass')
|
'Specify the set of plots (PlotWidget or PlotItem) that the user may
select from.
*plots* must be a dictionary of {name: plot} pairs.'
| def setPlotList(self, plots):
| self.plots = plots
self.updateUi()
|
'Define what happens when the node is connected to a plot'
| def connectToPlot(self, node):
| if (node.plot is None):
return
node.getPlot().addItem(self.line)
|
'Define what happens when the node is disconnected from a plot'
| def disconnectFromPlot(self, plot):
| plot.removeItem(self.line)
|
'Return a list of Point() where the x position is set to the nearest x value in *data* for each point in *pts*.'
| def adjustXPositions(self, pts, data):
| points = []
timeIndices = []
for p in pts:
x = np.argwhere((abs((data - p.x())) == abs((data - p.x())).min()))
points.append(Point(data[x], p.y()))
timeIndices.append(x)
return (points, timeIndices)
|
'Construct a new terminal.
**Arguments:**
node the node to which this terminal belongs
name string, the name of the terminal
io \'in\' or \'out\'
optional bool, whether the node may process without connection to this terminal
multi bool, for inputs: whether this terminal may make multiple connections
for outputs: whether this terminal creates a different value for each connection
pos [x, y], the position of the terminal within its node\'s boundaries
renamable (bool) Whether the terminal can be renamed by the user
removable (bool) Whether the terminal can be removed by the user
multiable (bool) Whether the user may toggle the *multi* option for this terminal
bypass (str) Name of the terminal from which this terminal\'s value is derived
when the Node is in bypass mode.'
| def __init__(self, node, name, io, optional=False, multi=False, pos=None, renamable=False, removable=False, multiable=False, bypass=None):
| self._io = io
self._optional = optional
self._multi = multi
self._node = weakref.ref(node)
self._name = name
self._renamable = renamable
self._removable = removable
self._multiable = multiable
self._connections = {}
self._graphicsItem = TerminalGraphicsItem(self, parent=self._node().graphicsItem())
self._bypass = bypass
if multi:
self._value = {}
else:
self._value = None
self.valueOk = None
self.recolor()
|
'Return the value this terminal provides for the connected terminal'
| def value(self, term=None):
| if (term is None):
return self._value
if self.isMultiValue():
return self._value.get(term, None)
else:
return self._value
|
'If this is a single-value terminal, val should be a single value.
If this is a multi-value terminal, val should be a dict of terminal:value pairs'
| def setValue(self, val, process=True):
| if (not self.isMultiValue()):
if fn.eq(val, self._value):
return
self._value = val
else:
if (not isinstance(self._value, dict)):
self._value = {}
if (val is not None):
self._value.update(val)
self.setValueAcceptable(None)
if (self.isInput() and process):
self.node().update()
self.recolor()
|
'Called whenever this terminal has been connected to another. (note--this function is called on both terminals)'
| def connected(self, term):
| if (self.isInput() and term.isOutput()):
self.inputChanged(term)
if (self.isOutput() and self.isMultiValue()):
self.node().update()
self.node().connected(self, term)
|
'Called whenever this terminal has been disconnected from another. (note--this function is called on both terminals)'
| def disconnected(self, term):
| if (self.isMultiValue() and (term in self._value)):
del self._value[term]
self.node().update()
elif self.isInput():
self.setValue(None)
self.node().disconnected(self, term)
|
'Called whenever there is a change to the input value to this terminal.
It may often be useful to override this function.'
| def inputChanged(self, term, process=True):
| if self.isMultiValue():
self.setValue({term: term.value(self)}, process=process)
else:
self.setValue(term.value(self), process=process)
|
'Returns True->acceptable None->unknown False->Unacceptable'
| def valueIsAcceptable(self):
| return self.valueOk
|
'Set whether this is a multi-value terminal.'
| def setMultiValue(self, multi):
| self._multi = multi
if ((not multi) and (len(self.inputTerminals()) > 1)):
self.disconnectAll()
for term in self.inputTerminals():
self.inputChanged(term)
|
'Return the terminal(s) that give input to this one.'
| def inputTerminals(self):
| return [t for t in self.connections() if t.isOutput()]
|
'Return the list of nodes which receive input from this terminal.'
| def dependentNodes(self):
| return set([t.node() for t in self.connections() if t.isInput()])
|
'Register a new node type. If the type\'s name is already in use,
an exception will be raised (unless override=True).
**Arguments:**
nodeClass a subclass of Node (must have typ.nodeName)
paths list of tuples specifying the location(s) this
type will appear in the library tree.
override if True, overwrite any class having the same name'
| def addNodeType(self, nodeClass, paths, override=False):
| if (not isNodeClass(nodeClass)):
raise Exception(('Object %s is not a Node subclass' % str(nodeClass)))
name = nodeClass.nodeName
if ((not override) and (name in self.nodeList)):
raise Exception(("Node type name '%s' is already registered." % name))
self.nodeList[name] = nodeClass
for path in paths:
root = self.nodeTree
for n in path:
if (n not in root):
root[n] = OrderedDict()
root = root[n]
root[name] = nodeClass
|
'Return a copy of this library.'
| def copy(self):
| lib = NodeLibrary()
lib.nodeList = self.nodeList.copy()
lib.nodeTree = self.treeCopy(self.nodeTree)
return lib
|
'Reload Node classes in this library.'
| def reload(self):
| raise NotImplementedError()
|
'Returns the vector length of this Point.'
| def length(self):
| return (((self[0] ** 2) + (self[1] ** 2)) ** 0.5)
|
'Returns a vector in the same direction with unit length.'
| def norm(self):
| return (self / self.length())
|
'Returns the angle in degrees between this vector and the vector a.'
| def angle(self, a):
| n1 = self.length()
n2 = a.length()
if ((n1 == 0.0) or (n2 == 0.0)):
return None
ang = np.arccos(clip((self.dot(a) / (n1 * n2)), (-1.0), 1.0))
c = self.cross(a)
if (c > 0):
ang *= (-1.0)
return ((ang * 180.0) / np.pi)
|
'Returns the dot product of a and this Point.'
| def dot(self, a):
| a = Point(a)
return ((self[0] * a[0]) + (self[1] * a[1]))
|
'Return the projection of this vector onto the vector b'
| def proj(self, b):
| b1 = (b / b.length())
return (self.dot(b1) * b1)
|
'Returns the angle in degrees between this vector and the vector a.'
| def angle(self, a):
| n1 = self.length()
n2 = a.length()
if ((n1 == 0.0) or (n2 == 0.0)):
return None
ang = np.arccos(np.clip((QtGui.QVector3D.dotProduct(self, a) / (n1 * n2)), (-1.0), 1.0))
return ((ang * 180.0) / np.pi)
|
'**Arguments:**
pos Array of positions where each color is defined
color Array of RGBA colors.
Integer data types are interpreted as 0-255; float data types
are interpreted as 0.0-1.0
mode Array of color modes (ColorMap.RGB, HSV_POS, or HSV_NEG)
indicating the color space that should be used when
interpolating between stops. Note that the last mode value is
ignored. By default, the mode is entirely RGB.'
| def __init__(self, pos, color, mode=None):
| self.pos = np.array(pos)
order = np.argsort(self.pos)
self.pos = self.pos[order]
self.color = np.array(color)[order]
if (mode is None):
mode = np.ones(len(pos))
self.mode = mode
self.stopsCache = {}
|
'Return an array of colors corresponding to the values in *data*.
Data must be either a scalar position or an array (any shape) of positions.
The *mode* argument determines the type of data returned:
byte (default) Values are returned as 0-255 unsigned bytes.
float Values are returned as 0.0-1.0 floats.
qcolor Values are returned as an array of QColor objects.'
| def map(self, data, mode='byte'):
| if isinstance(mode, basestring):
mode = self.enumMap[mode.lower()]
if (mode == self.QCOLOR):
(pos, color) = self.getStops(self.BYTE)
else:
(pos, color) = self.getStops(mode)
if np.isscalar(data):
interp = np.empty((color.shape[1],), dtype=color.dtype)
else:
if (not isinstance(data, np.ndarray)):
data = np.array(data)
interp = np.empty((data.shape + (color.shape[1],)), dtype=color.dtype)
for i in range(color.shape[1]):
interp[..., i] = np.interp(data, pos, color[:, i])
if (mode == self.QCOLOR):
if np.isscalar(data):
return QtGui.QColor(*interp)
else:
return [QtGui.QColor(*x) for x in interp]
else:
return interp
|
'Convenience function; see :func:`map() <pyqtgraph.ColorMap.map>`.'
| def mapToQColor(self, data):
| return self.map(data, mode=self.QCOLOR)
|
'Convenience function; see :func:`map() <pyqtgraph.ColorMap.map>`.'
| def mapToByte(self, data):
| return self.map(data, mode=self.BYTE)
|
'Convenience function; see :func:`map() <pyqtgraph.ColorMap.map>`.'
| def mapToFloat(self, data):
| return self.map(data, mode=self.FLOAT)
|
'Return a QLinearGradient object spanning from QPoints p1 to p2.'
| def getGradient(self, p1=None, p2=None):
| if (p1 == None):
p1 = QtCore.QPointF(0, 0)
if (p2 == None):
p2 = QtCore.QPointF((self.pos.max() - self.pos.min()), 0)
g = QtGui.QLinearGradient(p1, p2)
(pos, color) = self.getStops(mode=self.BYTE)
color = [QtGui.QColor(*x) for x in color]
g.setStops(zip(pos, color))
return g
|
'Return list of all color stops converted to the specified mode.
If mode is None, then no conversion is done.'
| def getColors(self, mode=None):
| if isinstance(mode, basestring):
mode = self.enumMap[mode.lower()]
color = self.color
if ((mode in [self.BYTE, self.QCOLOR]) and (color.dtype.kind == 'f')):
color = (color * 255).astype(np.ubyte)
elif ((mode == self.FLOAT) and (color.dtype.kind != 'f')):
color = (color.astype(float) / 255.0)
if (mode == self.QCOLOR):
color = [QtGui.QColor(*x) for x in color]
return color
|
'Return an RGB(A) lookup table (ndarray).
**Arguments:**
start The starting value in the lookup table (default=0.0)
stop The final value in the lookup table (default=1.0)
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, it will be automatically determined.
mode Determines return type: \'byte\' (0-255), \'float\' (0.0-1.0), or \'qcolor\'.
See :func:`map() <pyqtgraph.ColorMap.map>`.'
| def getLookupTable(self, start=0.0, stop=1.0, nPts=512, alpha=None, mode='byte'):
| if isinstance(mode, basestring):
mode = self.enumMap[mode.lower()]
if (alpha is None):
alpha = self.usesAlpha()
x = np.linspace(start, stop, nPts)
table = self.map(x, mode)
if (not alpha):
return table[:, :3]
else:
return table
|
'Return True if any stops have an alpha < 255'
| def usesAlpha(self):
| max = (1.0 if (self.color.dtype.kind == 'f') else 255)
return np.any((self.color[:, 3] != max))
|
'Return True if the gradient has exactly two stops in it: black at 0.0 and white at 1.0.'
| def isMapTrivial(self):
| if (len(self.pos) != 2):
return False
if ((self.pos[0] != 0.0) or (self.pos[1] != 1.0)):
return False
if (self.color.dtype.kind == 'f'):
return np.all((self.color == np.array([[0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0]])))
else:
return np.all((self.color == np.array([[0, 0, 0, 255], [255, 255, 255, 255]])))
|
'Adds a dock to this area.
**Arguments:**
dock The new Dock object to add. If None, then a new Dock will be
created.
position \'bottom\', \'top\', \'left\', \'right\', \'above\', or \'below\'
relativeTo If relativeTo is None, then the new Dock is added to fill an
entire edge of the window. If relativeTo is another Dock, then
the new Dock is placed adjacent to it (or in a tabbed
configuration for \'above\' and \'below\').
All extra keyword arguments are passed to Dock.__init__() if *dock* is
None.'
| def addDock(self, dock=None, position='bottom', relativeTo=None, **kwds):
| if (dock is None):
dock = Dock(**kwds)
if ((relativeTo is None) or (relativeTo is self)):
if (self.topContainer is None):
container = self
neighbor = None
else:
container = self.topContainer
neighbor = None
else:
if isinstance(relativeTo, basestring):
relativeTo = self.docks[relativeTo]
container = self.getContainer(relativeTo)
neighbor = relativeTo
neededContainer = {'bottom': 'vertical', 'top': 'vertical', 'left': 'horizontal', 'right': 'horizontal', 'above': 'tab', 'below': 'tab'}[position]
if ((neededContainer != container.type()) and (container.type() == 'tab')):
neighbor = container
container = container.container()
if (neededContainer != container.type()):
if (neighbor is None):
container = self.addContainer(neededContainer, self.topContainer)
else:
container = self.addContainer(neededContainer, neighbor)
insertPos = {'bottom': 'after', 'top': 'before', 'left': 'before', 'right': 'after', 'above': 'before', 'below': 'after'}[position]
old = dock.container()
container.insert(dock, insertPos, neighbor)
dock.area = self
self.docks[dock.name()] = dock
if (old is not None):
old.apoptose()
return dock
|
'Move an existing Dock to a new location.'
| def moveDock(self, dock, position, neighbor):
| if ((position in ['left', 'right', 'top', 'bottom']) and (neighbor is not None) and (neighbor.container() is not None) and (neighbor.container().type() == 'tab')):
neighbor = neighbor.container()
self.addDock(dock, position, neighbor)
|
'Add a new container around obj'
| def addContainer(self, typ, obj):
| new = self.makeContainer(typ)
container = self.getContainer(obj)
container.insert(new, 'before', obj)
if (obj is not None):
new.insert(obj)
self.raiseOverlay()
return new
|
'Removes *dock* from this DockArea and places it in a new window.'
| def floatDock(self, dock):
| area = self.addTempArea()
area.win.resize(dock.size())
area.moveDock(dock, 'top', None)
|
'Return a serialized (storable) representation of the state of
all Docks in this DockArea.'
| def saveState(self):
| if (self.topContainer is None):
main = None
else:
main = self.childState(self.topContainer)
state = {'main': main, 'float': []}
for a in self.tempAreas:
geo = a.win.geometry()
geo = (geo.x(), geo.y(), geo.width(), geo.height())
state['float'].append((a.saveState(), geo))
return state
|
'Restore Dock configuration as generated by saveState.
Note that this function does not create any Docks--it will only
restore the arrangement of an existing set of Docks.'
| def restoreState(self, state):
| (containers, docks) = self.findAll()
oldTemps = self.tempAreas[:]
if (state['main'] is not None):
self.buildFromState(state['main'], docks, self)
for s in state['float']:
a = self.addTempArea()
a.buildFromState(s[0]['main'], docks, a)
a.win.setGeometry(*s[1])
for d in docks.values():
self.moveDock(d, 'below', None)
for c in containers:
c.close()
for a in oldTemps:
a.apoptose()
|
'Set the \'target\' size for this Dock.
The actual size will be determined by comparing this Dock\'s
stretch value to the rest of the docks it shares space with.'
| def setStretch(self, x=None, y=None):
| if (x is None):
x = 0
if (y is None):
y = 0
self._stretch = (x, y)
self.sigStretchChanged.emit()
|
'Hide the title bar for this Dock.
This will prevent the Dock being moved by the user.'
| def hideTitleBar(self):
| self.label.hide()
self.labelHidden = True
if ('center' in self.allowedAreas):
self.allowedAreas.remove('center')
self.updateStyle()
|
'Show the title bar for this Dock.'
| def showTitleBar(self):
| self.label.show()
self.labelHidden = False
self.allowedAreas.add('center')
self.updateStyle()
|
'Gets the text displayed in the title bar for this dock.'
| def title(self):
| return asUnicode(self.label.text())
|
'Sets the text displayed in title bar for this Dock.'
| def setTitle(self, text):
| self.label.setText(text)
|
'Sets the orientation of the title bar for this Dock.
Must be one of \'auto\', \'horizontal\', or \'vertical\'.
By default (\'auto\'), the orientation is determined
based on the aspect ratio of the Dock.'
| def setOrientation(self, o='auto', force=False):
| if ((o == 'auto') and self.autoOrient):
if (self.container().type() == 'tab'):
o = 'horizontal'
elif (self.width() > (self.height() * 1.5)):
o = 'vertical'
else:
o = 'horizontal'
if (force or (self.orientation != o)):
self.orientation = o
self.label.setOrientation(o)
self.updateStyle()
|
'Add a new widget to the interior of this Dock.
Each Dock uses a QGridLayout to arrange widgets within.'
| def addWidget(self, widget, row=None, col=0, rowspan=1, colspan=1):
| if (row is None):
row = self.currentRow
self.currentRow = max((row + 1), self.currentRow)
self.widgets.append(widget)
self.layout.addWidget(widget, row, col, rowspan, colspan)
self.raiseOverlay()
|
'If this Dock is stacked underneath others, raise it to the top.'
| def raiseDock(self):
| self.container().raiseDock(self)
|
'Remove this dock from the DockArea it lives inside.'
| def close(self):
| self.setParent(None)
self.label.setParent(None)
self._container.apoptose()
self._container = None
self.sigClosed.emit(self)
|
'Return the stretch factors for this container'
| def stretch(self):
| return self._stretch
|
'Move *dock* to the top of the stack'
| def raiseDock(self, dock):
| self.stack.currentWidget().label.setDim(True)
self.stack.setCurrentWidget(dock)
dock.label.setDim(False)
|
'**Arguments:**
parent (QWidget) An optional parent widget
showHeader (bool) If True, then the QTreeView header is displayed.'
| def __init__(self, parent=None, showHeader=True):
| TreeWidget.__init__(self, parent)
self.setVerticalScrollMode(self.ScrollPerPixel)
self.setHorizontalScrollMode(self.ScrollPerPixel)
self.setAnimated(False)
self.setColumnCount(2)
self.setHeaderLabels(['Parameter', 'Value'])
self.setAlternatingRowColors(True)
self.paramSet = None
self.header().setResizeMode(QtGui.QHeaderView.ResizeToContents)
self.setHeaderHidden((not showHeader))
self.itemChanged.connect(self.itemChangedEvent)
self.lastSel = None
self.setRootIsDecorated(False)
|
'Set the top-level :class:`Parameter <pyqtgraph.parametertree.Parameter>`
to be displayed in this ParameterTree.
If *showTop* is False, then the top-level parameter is hidden and only
its children will be visible. This is a convenience method equivalent
to::
tree.clear()
tree.addParameters(param, showTop)'
| def setParameters(self, param, showTop=True):
| self.clear()
self.addParameters(param, showTop=showTop)
|
'Adds one top-level :class:`Parameter <pyqtgraph.parametertree.Parameter>`
to the view.
**Arguments:**
param The :class:`Parameter <pyqtgraph.parametertree.Parameter>`
to add.
root The item within the tree to which *param* should be added.
By default, *param* is added as a top-level item.
showTop If False, then *param* will be hidden, and only its
children will be visible in the tree.'
| def addParameters(self, param, root=None, depth=0, showTop=True):
| item = param.makeTreeItem(depth=depth)
if (root is None):
root = self.invisibleRootItem()
if (not showTop):
item.setText(0, '')
item.setSizeHint(0, QtCore.QSize(1, 1))
item.setSizeHint(1, QtCore.QSize(1, 1))
depth -= 1
root.addChild(item)
item.treeWidgetChanged()
for ch in param:
self.addParameters(ch, root=item, depth=(depth + 1))
|
'Remove all parameters from the tree.'
| def clear(self):
| self.invisibleRootItem().takeChildren()
|
'Give input focus to the next (or previous) item after *item*'
| def focusNext(self, item, forward=True):
| while True:
parent = item.parent()
if (parent is None):
return
nextItem = self.nextFocusableChild(parent, item, forward=forward)
if (nextItem is not None):
nextItem.setFocus()
self.setCurrentItem(nextItem)
return
item = parent
|
'Static method that creates a new Parameter (or subclass) instance using
opts[\'type\'] to select the appropriate class.
All options are passed directly to the new Parameter\'s __init__ method.
Use registerParameterType() to add new class types.'
| @staticmethod
def create(**opts):
| typ = opts.get('type', None)
if (typ is None):
cls = Parameter
else:
cls = PARAM_TYPES[opts['type']]
return cls(**opts)
|
'Initialize a Parameter object. Although it is rare to directly create a
Parameter instance, the options available to this method are also allowed
by most Parameter subclasses.
**Keyword Arguments:**
name The name to give this Parameter. This is the name that
will appear in the left-most column of a ParameterTree
for this Parameter.
value The value to initially assign to this Parameter.
default The default value for this Parameter (most Parameters
provide an option to \'reset to default\').
children A list of children for this Parameter. Children
may be given either as a Parameter instance or as a
dictionary to pass to Parameter.create(). In this way,
it is possible to specify complex hierarchies of
Parameters from a single nested data structure.
readonly If True, the user will not be allowed to edit this
Parameter. (default=False)
enabled If False, any widget(s) for this parameter will appear
disabled. (default=True)
visible If False, the Parameter will not appear when displayed
in a ParameterTree. (default=True)
renamable If True, the user may rename this Parameter.
(default=False)
removable If True, the user may remove this Parameter.
(default=False)
expanded If True, the Parameter will appear expanded when
displayed in a ParameterTree (its children will be
visible). (default=True)
title (str or None) If specified, then the parameter will be
displayed to the user using this string as its name.
However, the parameter will still be referred to
internally using the *name* specified above. Note that
this option is not compatible with renamable=True.
(default=None; added in version 0.9.9)'
| def __init__(self, **opts):
| QtCore.QObject.__init__(self)
self.opts = {'type': None, 'readonly': False, 'visible': True, 'enabled': True, 'renamable': False, 'removable': False, 'strictNaming': False, 'expanded': True, 'title': None}
self.opts.update(opts)
self.childs = []
self.names = {}
self.items = weakref.WeakKeyDictionary()
self._parent = None
self.treeStateChanges = []
self.blockTreeChangeEmit = 0
if ('value' not in self.opts):
self.opts['value'] = None
if (('name' not in self.opts) or (not isinstance(self.opts['name'], basestring))):
raise Exception('Parameter must have a string name specified in opts.')
self.setName(opts['name'])
self.addChildren(self.opts.get('children', []))
if (('value' in self.opts) and ('default' not in self.opts)):
self.opts['default'] = self.opts['value']
self.sigValueChanged.connect((lambda param, data: self.emitStateChanged('value', data)))
self.sigChildAdded.connect((lambda param, *data: self.emitStateChanged('childAdded', data)))
self.sigChildRemoved.connect((lambda param, data: self.emitStateChanged('childRemoved', data)))
self.sigParentChanged.connect((lambda param, data: self.emitStateChanged('parent', data)))
self.sigLimitsChanged.connect((lambda param, data: self.emitStateChanged('limits', data)))
self.sigDefaultChanged.connect((lambda param, data: self.emitStateChanged('default', data)))
self.sigNameChanged.connect((lambda param, data: self.emitStateChanged('name', data)))
self.sigOptionsChanged.connect((lambda param, data: self.emitStateChanged('options', data)))
|
'Return the name of this Parameter.'
| def name(self):
| return self.opts['name']
|
'Attempt to change the name of this parameter; return the actual name.
(The parameter may reject the name change or automatically pick a different name)'
| def setName(self, name):
| if self.opts['strictNaming']:
if ((len(name) < 1) or re.search('\\W', name) or re.match('\\d', name[0])):
raise Exception(("Parameter name '%s' is invalid. (Must contain only alphanumeric and underscore characters and may not start with a number)" % name))
parent = self.parent()
if (parent is not None):
name = parent._renameChild(self, name)
if (self.opts['name'] != name):
self.opts['name'] = name
self.sigNameChanged.emit(self, name)
return name
|
'Return the type string for this Parameter.'
| def type(self):
| return self.opts['type']
|
'Return True if this parameter type matches the name *typ*.
This can occur either of two ways:
- If self.type() == *typ*
- If this parameter\'s class is registered with the name *typ*'
| def isType(self, typ):
| if (self.type() == typ):
return True
global PARAM_TYPES
cls = PARAM_TYPES.get(typ, None)
if (cls is None):
raise Exception(("Type name '%s' is not registered." % str(typ)))
return (self.__class__ is cls)
|
'Return the path of parameter names from self to child.
If child is not a (grand)child of self, return None.'
| def childPath(self, child):
| path = []
while (child is not self):
path.insert(0, child.name())
child = child.parent()
if (child is None):
return None
return path
|
'Set the value of this Parameter; return the actual value that was set.
(this may be different from the value that was requested)'
| def setValue(self, value, blockSignal=None):
| try:
if (blockSignal is not None):
self.sigValueChanged.disconnect(blockSignal)
value = self._interpretValue(value)
if (self.opts['value'] == value):
return value
self.opts['value'] = value
self.sigValueChanged.emit(self, value)
finally:
if (blockSignal is not None):
self.sigValueChanged.connect(blockSignal)
return value
|
'Return the value of this Parameter.'
| def value(self):
| return self.opts['value']
|
'Return a tree of all values that are children of this parameter'
| def getValues(self):
| vals = OrderedDict()
for ch in self:
vals[ch.name()] = (ch.value(), ch.getValues())
return vals
|
'Return a structure representing the entire state of the parameter tree.
The tree state may be restored from this structure using restoreState().
If *filter* is set to \'user\', then only user-settable data will be included in the
returned state.'
| def saveState(self, filter=None):
| if (filter is None):
state = self.opts.copy()
if (state['type'] is None):
global PARAM_NAMES
state['type'] = PARAM_NAMES.get(type(self), None)
elif (filter == 'user'):
state = {'value': self.value()}
else:
raise ValueError(("Unrecognized filter argument: '%s'" % filter))
ch = OrderedDict([(ch.name(), ch.saveState(filter=filter)) for ch in self])
if (len(ch) > 0):
state['children'] = ch
return state
|
'Restore the state of this parameter and its children from a structure generated using saveState()
If recursive is True, then attempt to restore the state of child parameters as well.
If addChildren is True, then any children which are referenced in the state object will be
created if they do not already exist.
If removeChildren is True, then any children which are not referenced in the state object will
be removed.
If blockSignals is True, no signals will be emitted until the tree has been completely restored.
This prevents signal handlers from responding to a partially-rebuilt network.'
| def restoreState(self, state, recursive=True, addChildren=True, removeChildren=True, blockSignals=True):
| state = state.copy()
childState = state.pop('children', [])
if isinstance(childState, dict):
cs = []
for (k, v) in childState.items():
cs.append(v.copy())
cs[(-1)].setdefault('name', k)
childState = cs
if blockSignals:
self.blockTreeChangeSignal()
try:
self.setOpts(**state)
if (not recursive):
return
ptr = 0
foundChilds = set()
for ch in childState:
name = ch['name']
gotChild = False
for (i, ch2) in enumerate(self.childs[ptr:]):
if (ch2.name() != name):
continue
gotChild = True
if (i != 0):
self.insertChild(ptr, ch2)
ch2.restoreState(ch, recursive=recursive, addChildren=addChildren, removeChildren=removeChildren)
foundChilds.add(ch2)
break
if (not gotChild):
if (not addChildren):
continue
ch2 = Parameter.create(**ch)
self.insertChild(ptr, ch2)
foundChilds.add(ch2)
ptr += 1
if removeChildren:
for ch in self.childs[:]:
if (ch not in foundChilds):
self.removeChild(ch)
finally:
if blockSignals:
self.unblockTreeChangeSignal()
|
'Return the default value for this parameter.'
| def defaultValue(self):
| return self.opts['default']
|
'Set the default value for this parameter.'
| def setDefault(self, val):
| if (self.opts['default'] == val):
return
self.opts['default'] = val
self.sigDefaultChanged.emit(self, val)
|
'Set this parameter\'s value to the default.'
| def setToDefault(self):
| if self.hasDefault():
self.setValue(self.defaultValue())
|
'Returns True if this parameter has a default value.'
| def hasDefault(self):
| return ('default' in self.opts)
|
'Returns True if this parameter\'s value is equal to the default value.'
| def valueIsDefault(self):
| return (self.value() == self.defaultValue())
|
'Set limits on the acceptable values for this parameter.
The format of limits depends on the type of the parameter and
some parameters do not make use of limits at all.'
| def setLimits(self, limits):
| if (('limits' in self.opts) and (self.opts['limits'] == limits)):
return
self.opts['limits'] = limits
self.sigLimitsChanged.emit(self, limits)
return limits
|
'Returns True if this parameter\'s value can be changed by the user.
Note that the value of the parameter can *always* be changed by
calling setValue().'
| def writable(self):
| return (not self.readonly())
|
'Set whether this Parameter should be editable by the user. (This is
exactly the opposite of setReadonly).'
| def setWritable(self, writable=True):
| self.setOpts(readonly=(not writable))
|
'Return True if this parameter is read-only. (this is the opposite of writable())'
| def readonly(self):
| return self.opts.get('readonly', False)
|
'Set whether this Parameter\'s value may be edited by the user
(this is the opposite of setWritable()).'
| def setReadonly(self, readonly=True):
| self.setOpts(readonly=readonly)
|
'Set any arbitrary options on this parameter.
The exact behavior of this function will depend on the parameter type, but
most parameters will accept a common set of options: value, name, limits,
default, readonly, removable, renamable, visible, enabled, and expanded.
See :func:`Parameter.__init__ <pyqtgraph.parametertree.Parameter.__init__>`
for more information on default options.'
| def setOpts(self, **opts):
| changed = OrderedDict()
for k in opts:
if (k == 'value'):
self.setValue(opts[k])
elif (k == 'name'):
self.setName(opts[k])
elif (k == 'limits'):
self.setLimits(opts[k])
elif (k == 'default'):
self.setDefault(opts[k])
elif ((k not in self.opts) or (self.opts[k] != opts[k])):
self.opts[k] = opts[k]
changed[k] = opts[k]
if (len(changed) > 0):
self.sigOptionsChanged.emit(self, changed)
|
'Return a TreeWidgetItem suitable for displaying/controlling the content of
this parameter. This is called automatically when a ParameterTree attempts
to display this Parameter.
Most subclasses will want to override this function.'
| def makeTreeItem(self, depth):
| if hasattr(self, 'itemClass'):
return self.itemClass(self, depth)
else:
return ParameterItem(self, depth=depth)
|
'Add another parameter to the end of this parameter\'s child list.
See insertChild() for a description of the *autoIncrementName*
argument.'
| def addChild(self, child, autoIncrementName=None):
| return self.insertChild(len(self.childs), child, autoIncrementName=autoIncrementName)
|
'Add a list or dict of children to this parameter. This method calls
addChild once for each value in *children*.'
| def addChildren(self, children):
| if isinstance(children, dict):
ch2 = []
for (name, opts) in children.items():
if (isinstance(opts, dict) and ('name' not in opts)):
opts = opts.copy()
opts['name'] = name
ch2.append(opts)
children = ch2
for chOpts in children:
self.addChild(chOpts)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.