示例#1
0
    def paint(self, p, *args):
        # p.setRenderHint(p.Antialiasing)  # only if the data is antialiased.
        opts = self.item.opts

        if opts.get('fillLevel', None) is not None and opts.get(
                'fillBrush', None) is not None:
            p.setBrush(fn.mkBrush(opts['fillBrush']))
            p.setPen(fn.mkPen(None))
            p.drawPolygon(
                QtGui.QPolygonF([
                    QtCore.QPointF(2, 18),
                    QtCore.QPointF(18, 2),
                    QtCore.QPointF(18, 18)
                ]))

        if not isinstance(self.item, ScatterPlotItem):
            p.setPen(fn.mkPen(opts['pen']))
            p.drawLine(2, 18, 18, 2)

        symbol = opts.get('symbol', None)
        if symbol is not None:
            if isinstance(self.item, PlotDataItem):
                opts = self.item.scatter.opts

            pen = fn.mkPen(opts['pen'])
            brush = fn.mkBrush(opts['brush'])
            size = opts['size']

            p.translate(10, 10)
            path = drawSymbol(p, symbol, size, pen, brush)
 def paint(self, p, *args):
     opts = self.opts
     if opts.get('antialias', True):
         p.setRenderHint(p.Antialiasing)
     
     if opts.get('fillLevel', None) is not None and opts.get('fillBrush', None) is not None:
         p.setBrush(fn.mkBrush(opts['fillBrush']))
         p.setPen(fn.mkPen(None))
         p.drawPolygon(QtGui.QPolygonF([
             QtCore.QPointF(2, 18), 
             QtCore.QPointF(18, 2), 
             QtCore.QPointF(18, 18)]))
     
     if opts.get('pen', None) is not None:
         p.setPen(fn.mkPen(opts['pen']))
         p.drawLine(2, 18, 18, 2)
     
     symbol = opts.get('symbol', None)
     if symbol is not None:
             
         pen = fn.mkPen(opts.get('symbolPen', None))
         brush = fn.mkBrush(opts.get('symbolBrush', None))
         size = opts.get('symbolSize', 10)
         
         p.translate(10,10)
         path = drawSymbol(p, symbol, size, pen, brush)
示例#3
0
 def __init__(self, orientation='bottom', allowAdd=True, **kargs):
     """
     ============= =================================================================================
     **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 arguments for :func:`mkPen <pyqtgraph.mkPen>`
     ============= =================================================================================        
     """
     ## public
     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.orientations = {
         'left': (90, 1, 1), 
         'right': (90, 1, 1), 
         'top': (0, 1, -1), 
         'bottom': (0, 1, 1)
     }
     
     self.setOrientation(orientation)
示例#4
0
 def getSpotOpts(self, recs, scale=1.0):
     if recs.ndim == 0:
         rec = recs
         symbol = rec['symbol']
         if symbol is None:
             symbol = self.opts['symbol']
         size = rec['size']
         if size < 0:
             size = self.opts['size']
         pen = rec['pen']
         if pen is None:
             pen = self.opts['pen']
         brush = rec['brush']
         if brush is None:
             brush = self.opts['brush']
         return (symbol, size * scale, fn.mkPen(pen), fn.mkBrush(brush))
     else:
         recs = recs.copy()
         recs['symbol'][np.equal(recs['symbol'],
                                 None)] = self.opts['symbol']
         recs['size'][np.equal(recs['size'], -1)] = self.opts['size']
         recs['size'] *= scale
         recs['pen'][np.equal(recs['pen'],
                              None)] = fn.mkPen(self.opts['pen'])
         recs['brush'][np.equal(recs['brush'],
                                None)] = fn.mkBrush(self.opts['brush'])
         return recs
示例#5
0
    def paint(self, p, *args):
        opts = self.item.opts

        if opts.get('antialias'):
            p.setRenderHint(p.Antialiasing)

        if not isinstance(self.item, ScatterPlotItem):
            p.setPen(fn.mkPen(opts['pen']))
            # p.drawLine(0, 11, 20, 11)
            p.drawLine(0, 15, 20, 15)  # CHANGED THIS LINE

            if (opts.get('fillLevel', None) is not None and
                    opts.get('fillBrush', None) is not None):
                p.setBrush(fn.mkBrush(opts['fillBrush']))
                p.setPen(fn.mkPen(opts['fillBrush']))
                p.drawPolygon(QtGui.QPolygonF(
                    [QtCore.QPointF(2, 18), QtCore.QPointF(18, 2),
                     QtCore.QPointF(18, 18)]))

        symbol = opts.get('symbol', None)
        if symbol is not None:
            if isinstance(self.item, PlotDataItem):
                opts = self.item.scatter.opts
            p.translate(10, 10)
            drawSymbol(p, symbol, opts['size'], fn.mkPen(opts['pen']),
                       fn.mkBrush(opts['brush']))

        if isinstance(self.item, BarGraphItem):
            p.setBrush(fn.mkBrush(opts['brush']))
            p.drawRect(QtCore.QRectF(2, 2, 18, 18))
示例#6
0
    def paint(self, p, *args):
        pen = self.region.lines[0].pen
        rgn = self.getLevels()
        if self.orientation == 'horizontal':
            p1 = self.vb.mapFromViewToItem(
                self, Point(rgn[0],
                            self.vb.viewRect().center().y()))
            p2 = self.vb.mapFromViewToItem(
                self, Point(rgn[1],
                            self.vb.viewRect().center().y()))
            gradRect = self.gradient.mapRectToParent(
                self.gradient.gradRect.rect())
            for pen in [fn.mkPen('k', width=3), pen]:
                p.setPen(pen)
                p.drawLine(p1, gradRect.bottomLeft())
                p.drawLine(p2, gradRect.bottomRight())
                p.drawLine(gradRect.bottomLeft(), gradRect.topLeft())
                p.drawLine(gradRect.bottomRight(), gradRect.topRight())

        elif self.orientation == 'vertical':
            p1 = self.vb.mapFromViewToItem(
                self, Point(self.vb.viewRect().center().x(), rgn[0]))
            p2 = self.vb.mapFromViewToItem(
                self, Point(self.vb.viewRect().center().x(), rgn[1]))
            gradRect = self.gradient.mapRectToParent(
                self.gradient.gradRect.rect())
            for pen in [fn.mkPen('k', width=3), pen]:
                p.setPen(pen)
                p.drawLine(p1, gradRect.bottomLeft())
                p.drawLine(p2, gradRect.topLeft())
                p.drawLine(gradRect.topLeft(), gradRect.topRight())
                p.drawLine(gradRect.bottomLeft(), gradRect.bottomRight())
    def __init__(self, orientation='bottom', allowAdd=True, **kargs):
        """
        ==============  =================================================================================
        **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 arguments for :func:`mkPen <pyqtgraph.mkPen>`
        ==============  =================================================================================
        """
        ## public
        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.orientations = {
            'left': (90, 1, 1),
            'right': (90, 1, 1),
            'top': (0, 1, -1),
            'bottom': (0, 1, 1)
        }

        self.setOrientation(orientation)
示例#8
0
    def paint(self, p, *args):
        opts = self.opts
        if opts.get('antialias', True):
            p.setRenderHint(p.Antialiasing)

        if opts.get('fillLevel', None) is not None and opts.get(
                'fillBrush', None) is not None:
            p.setBrush(fn.mkBrush(opts['fillBrush']))
            p.setPen(fn.mkPen(None))
            p.drawPolygon(
                QtGui.QPolygonF([
                    QtCore.QPointF(2, 18),
                    QtCore.QPointF(18, 2),
                    QtCore.QPointF(18, 18)
                ]))

        if opts.get('pen', None) is not None:
            p.setPen(fn.mkPen(opts['pen']))
            p.drawLine(2, 18, 18, 2)

        symbol = opts.get('symbol', None)
        if symbol is not None:

            pen = fn.mkPen(opts.get('symbolPen', None))
            brush = fn.mkBrush(opts.get('symbolBrush', None))
            size = opts.get('symbolSize', 10)

            p.translate(10, 10)
            path = drawSymbol(p, symbol, size, pen, brush)
示例#9
0
    def __init__(self, node):
        #QtGui.QGraphicsItem.__init__(self)
        GraphicsObject.__init__(self)
        #QObjectWorkaround.__init__(self)
        
        #self.shadow = QtGui.QGraphicsDropShadowEffect()
        #self.shadow.setOffset(5,5)
        #self.shadow.setBlurRadius(10)
        #self.setGraphicsEffect(self.shadow)
        
        self.pen = fn.mkPen(0,0,0)
        self.selectPen = fn.mkPen(200,200,200,width=2)
        self.brush = fn.mkBrush(200, 200, 200, 150)
        self.hoverBrush = fn.mkBrush(200, 200, 200, 200)
        self.selectBrush = fn.mkBrush(200, 200, 255, 200)
        self.hovered = False
        
        self.node = node
        flags = self.ItemIsMovable | self.ItemIsSelectable | self.ItemIsFocusable |self.ItemSendsGeometryChanges
        #flags =  self.ItemIsFocusable |self.ItemSendsGeometryChanges

        self.setFlags(flags)
        self.bounds = QtCore.QRectF(0, 0, 100, 100)
        self.nameItem = QtGui.QGraphicsTextItem(self.node.name(), self)
        self.nameItem.setDefaultTextColor(QtGui.QColor(50, 50, 50))
        self.nameItem.moveBy(self.bounds.width()/2. - self.nameItem.boundingRect().width()/2., 0)
        self.nameItem.setTextInteractionFlags(QtCore.Qt.TextEditorInteraction)
        self.updateTerminals()
        #self.setZValue(10)

        self.nameItem.focusOutEvent = self.labelFocusOut
        self.nameItem.keyPressEvent = self.labelKeyPress
        
        self.menu = None
        self.buildMenu()
    def __init__(self, view, pos, color, movable=True, removable=True, scale=10, pen='w'):
#        logging.info(f'MTFTick::init: removable={removable}')
        self.movable = movable
        self.moving = False
        self.removeAllowed = removable
        self.view = weakref.ref(view)
        self.scale = scale
        self.color = color
        self.pen = fn.mkPen(pen)
        self.hoverPen = fn.mkPen(255,255,0)
        self.currentPen = self.pen
#        self.pg = QtGui.QPainterPath(QtCore.QPointF(0,0))
#        self.pg.lineTo(QtCore.QPointF(-scale/3**0.5, scale))
#        self.pg.lineTo(QtCore.QPointF(scale/3**0.5, scale))
        self.pg = QtGui.QPainterPath(QtCore.QPointF(0,0))
        self.pg.lineTo(QtCore.QPointF(-scale/9**0.5, scale))
        self.pg.lineTo(QtCore.QPointF(scale/9**0.5, scale))
        self.pg.closeSubpath()

        QtGui.QGraphicsWidget.__init__(self)
        self.setPos(pos[0], pos[1])
        if self.movable:
            self.setZValue(1)
        else:
            self.setZValue(0)
示例#11
0
文件: Node.py 项目: robertsj/poropy
    def __init__(self, node):
        #QtGui.QGraphicsItem.__init__(self)
        GraphicsObject.__init__(self)
        #QObjectWorkaround.__init__(self)
        
        #self.shadow = QtGui.QGraphicsDropShadowEffect()
        #self.shadow.setOffset(5,5)
        #self.shadow.setBlurRadius(10)
        #self.setGraphicsEffect(self.shadow)
        
        self.pen = fn.mkPen(0,0,0)
        self.selectPen = fn.mkPen(200,200,200,width=2)
        self.brush = fn.mkBrush(200, 200, 200, 150)
        self.hoverBrush = fn.mkBrush(200, 200, 200, 200)
        self.selectBrush = fn.mkBrush(200, 200, 255, 200)
        self.hovered = False
        
        self.node = node
        flags = self.ItemIsMovable | self.ItemIsSelectable | self.ItemIsFocusable |self.ItemSendsGeometryChanges
        #flags =  self.ItemIsFocusable |self.ItemSendsGeometryChanges

        self.setFlags(flags)
        self.bounds = QtCore.QRectF(0, 0, 100, 100)
        self.nameItem = QtGui.QGraphicsTextItem(self.node.name(), self)
        self.nameItem.setDefaultTextColor(QtGui.QColor(50, 50, 50))
        self.nameItem.moveBy(self.bounds.width()/2. - self.nameItem.boundingRect().width()/2., 0)
        self.nameItem.setTextInteractionFlags(QtCore.Qt.TextEditorInteraction)
        self.updateTerminals()
        #self.setZValue(10)

        self.nameItem.focusOutEvent = self.labelFocusOut
        self.nameItem.keyPressEvent = self.labelKeyPress
        
        self.menu = None
        self.buildMenu()
示例#12
0
    def __init__(self, node, brush=None):
        super().__init__()

        self.pen = fn.mkPen(0, 0, 0)
        self.selectPen = fn.mkPen(200, 200, 200, width=2)

        if brush:
            self.brush = brush
        else:
            self.brush = fn.mkBrush(255, 255, 255, 255)

        self.hoverBrush = fn.mkBrush(200, 200, 200, 200)
        self.selectBrush = fn.mkBrush(200, 200, 255, 200)
        self.hovered = False

        self.node = node
        flags = self.ItemIsMovable | self.ItemIsSelectable | self.ItemSendsGeometryChanges

        self.setFlags(flags)
        self.bounds = QtCore.QRectF(0, 0, 100, 100)
        self.nameItem = QtGui.QGraphicsTextItem(self.node.name(), self)
        self.nameItem.setDefaultTextColor(QtGui.QColor(50, 50, 50))
        self.nameItem.moveBy(
            self.bounds.width() / 2. -
            self.nameItem.boundingRect().width() / 2., 0)

        self.updateTerminals()

        self.menu = None
        self.add_condition = None
        self.enabled = QtGui.QAction("Enabled",
                                     self.menu,
                                     checkable=True,
                                     checked=True)
        self.buildMenu()
示例#13
0
 def plotAutomaticLineOnGraph(self, plot=True, w_l=694.26, _label='PV'):
     ''' Plotting line on graph '''
     try:
         if (plot):
             if self.ui.chkDark.isChecked():
                 self.ui.wvRaw.plotItem.removeItem(self.line)
                 self.ui.wvDark.plotItem.removeItem(self.line)
                 self.line = InfiniteLine(pos=w_l,
                                          angle=90,
                                          pen=mkPen('r', width=2),
                                          label=_label)
                 self.ui.wvDark.plotItem.addItem(self.line)
             else:
                 self.ui.wvRaw.plotItem.removeItem(self.line)
                 self.ui.wvDark.plotItem.removeItem(self.line)
                 self.line = InfiniteLine(pos=w_l,
                                          angle=90,
                                          pen=mkPen('r', width=2),
                                          label=_label)
                 self.ui.wvRaw.plotItem.addItem(self.line)
         else:
             self.ui.wvRaw.plotItem.removeItem(self.line)
             self.ui.wvDark.plotItem.removeItem(self.line)
     except:
         self.showDialog("Error on pressure data processing",
                         "Mode Automatic: Error on pressure data plotting")
示例#14
0
    def plotLine_nm_OnGraph(self,
                            plot=True,
                            w_l=694.26,
                            _label='PV',
                            _angle=90):
        try:
            if (plot):
                if ((w_l > 600) and (w_l < 800)):
                    if self.ui.chkDark.isChecked():
                        self.ui.wvRaw.plotItem.removeItem(self.line_calc)
                        self.ui.wvDark.plotItem.removeItem(self.line_calc)
                        self.line_calc = InfiniteLine(pos=w_l,
                                                      angle=_angle,
                                                      pen=mkPen('g', width=2),
                                                      label=_label)
                        self.ui.wvDark.plotItem.addItem(self.line_calc)
                    else:
                        self.ui.wvRaw.plotItem.removeItem(self.line_calc)
                        self.ui.wvDark.plotItem.removeItem(self.line_calc)
                        self.line_calc = InfiniteLine(pos=w_l,
                                                      angle=_angle,
                                                      pen=mkPen('g', width=2),
                                                      label=_label)
                        self.ui.wvRaw.plotItem.addItem(self.line_calc)
                else:
                    self.showDialog("Error plotting procedure",
                                    "Wavelength is out of range")
            else:
                self.ui.wvRaw.plotItem.removeItem(self.line_calc)
                self.ui.wvDark.plotItem.removeItem(self.line_calc)

        except:
            self.showDialog("Error on pressure data processing",
                            "Mode Automatic: Error on pressure data plotting")
示例#15
0
 def buildQuaternion(self):
     self.pQuat = self.win.addPlot(title="Quaternion")
     self.pQuat.showGrid(x=True, y=True)
     self.pQuatCurves[0] = self.pQuat.plot(pen="r")
     self.pQuatCurves[1] = self.pQuat.plot(pen="g")
     self.pQuatCurves[2] = self.pQuat.plot(pen="b")
     self.pQuatCurves[3] = self.pQuat.plot(pen=mkPen(color="r", style=QtCore.Qt.DotLine))
     self.pQuatCurves[4] = self.pQuat.plot(pen=mkPen(color="b", style=QtCore.Qt.DotLine))
     self.pQuatCurves[5] = self.pQuat.plot(pen=mkPen(color="g", style=QtCore.Qt.DotLine))
示例#16
0
 def buildTorque(self):
     self.pTorque = self.win.addPlot(title="Torque")
     self.pTorque.showGrid(x=True, y=True)
     self.pTorqueCurves[0] = self.pTorque.plot(pen="r")
     self.pTorqueCurves[1] = self.pTorque.plot(pen="b")
     self.pTorqueCurves[2] = self.pTorque.plot(pen="g")
     self.pTorqueCurves[3] = self.pTorque.plot(pen=mkPen(color="r", style=QtCore.Qt.DotLine))
     self.pTorqueCurves[4] = self.pTorque.plot(pen=mkPen(color="b", style=QtCore.Qt.DotLine))
     self.pTorqueCurves[5] = self.pTorque.plot(pen=mkPen(color="g", style=QtCore.Qt.DotLine))
示例#17
0
 def paint(self, p, *args):
     if self.isSelected():
         p.setPen(fn.mkPen(200, 200, 0, width=3))
     else:
         if self.hovered:
             p.setPen(fn.mkPen(150, 150, 250, width=1))
         else:
             p.setPen(fn.mkPen(100, 100, 250, width=1))
             
     p.drawLine(0, 0, 0, self.length)
示例#18
0
    def paint(self, p, *args):
        if self.isSelected():
            p.setPen(fn.mkPen(200, 200, 0, width=3))
        else:
            if self.hovered:
                p.setPen(fn.mkPen(150, 150, 250, width=1))
            else:
                p.setPen(fn.mkPen(100, 100, 250, width=1))

        p.drawLine(0, 0, 0, self.length)
示例#19
0
 def __init__(self):
     self.penActive = fn.mkPen(0, 255, 0)
     self.penInactive = fn.mkPen(255, 0, 0)
     self.penHover = fn.mkPen(255, 255, 0)
     self.penActive.setWidth(1)
     self.penInactive.setWidth(1)
     self.penHover.setWidth(1)
     self.setName()
     self.isSelected = False
     self.menu = None
     self.setActive(True)
示例#20
0
    def setMouseHover(self, hover):
        '''Inform the ROI that the mouse is(not) hovering over it'''
        if self.mouseHovering == hover:
            return
        self.mouseHovering = hover
        if hover:
            self.currentPen = fn.mkPen(255, 255, 0)

        else:
            self.currentPen = fn.mkPen(255, 0, 0)
        self.update()
示例#21
0
 def __init__(self):
     self.penActive   = fn.mkPen(  0, 255, 0)
     self.penInactive = fn.mkPen(255,   0, 0) 
     self.penHover    = fn.mkPen(255, 255, 0)   
     self.penActive.setWidth(1)
     self.penInactive.setWidth(1) 
     self.penHover.setWidth(1)   
     self.setName()
     self.isSelected = False
     self.menu = None
     self.setActive(True)
示例#22
0
 def setPen(self, *args, **kargs):
     if len(args) == 1 and (isinstance(args[0], np.ndarray) or isinstance(args[0], list)):
         pens = args[0]
         if self.data is None:
             raise Exception("Must set data before setting multiple pens.")
         if len(pens) != len(self.data):
             raise Exception("Number of pens does not match number of points (%d != %d)" % (len(pens), len(self.data)))
         for i in xrange(len(pens)):
             self.data[i]['pen'] = fn.mkPen(pens[i])
     else:
         self.opts['pen'] = fn.mkPen(*args, **kargs)
     self.updateSpots()
示例#23
0
 def paint(self, p, *args):
     if self.isSelected():
         p.setPen(fn.mkPen(self.style['selectedColor'], width=self.style['selectedWidth']))
     else:
         if self.hovered:
             p.setPen(fn.mkPen(self.style['hoverColor'], width=self.style['hoverWidth']))
         else:
             p.setPen(fn.mkPen(self.style['color'], width=self.style['width']))
             
     #p.drawLine(0, 0, 0, self.length)
     
     p.drawPath(self.path)
示例#24
0
    def add_curve_to_chart(self, item):
        """
        Adds the item to teh chart and corresponding data to the worksheet

        Parameters
        ----------
        item: pyqtgraph CurveItem

        Returns
        -------

        """

        # Get data
        x, y = item.getData()
        # Get headers
        name = None
        if hasattr(item, 'implements') and item.implements('plotData') and item.name() is not None:
            name = item.name()
            x_header = "{}_x".format(name)
            y_header = "{}_y".format(name)
        else:
            x_header = "{:04d}_x".format(int(self.data_icol / 2))
            y_header = "{:04d}_x".format(int(self.data_icol / 2))

        # Write to data worksheet
        x_column, y_column = self.add_xy_to_worksheet(x, y, x_header=x_header, y_header=y_header)

        # Add series to Excel Chart
        series = self.chart.SeriesCollection().NewSeries()
        series.XValues = x_column
        series.Values = y_column
        if name is not None:
            series.Name = name

        pen = item.opts["pen"]
        symbol = item.opts["symbol"]

        if pen is not None:
            line_color = qcolor_to_long(fn.mkPen(pen).color())
            series.Border.Color = line_color
            series.Format.Line.ForeColor.RGB = line_color
            series.Format.Fill.BackColor.RGB = line_color

        if symbol is not None:
            series.MarkerStyle = self.symbol_map.get(symbol, 1)
            series.MarkerSize = item.opts["symbolSize"]
            series.MarkerBackgroundColor = qcolor_to_long(fn.mkPen(item.opts["symbolPen"]).color())
            series.MarkerForegroundColor = qcolor_to_long(fn.mkBrush(item.opts["symbolBrush"]).color())

        if name is None:
            last_index = self.chart.Legend.LegendEntries().Count
            self.chart.Legend.LegendEntries(last_index).Delete()
示例#25
0
 def setPen(self, *args, **kargs):
     if len(args) == 1 and (isinstance(args[0], np.ndarray) or isinstance(args[0], list)):
         pens = args[0]
         if self.data is None:
             raise Exception("Must set data before setting multiple pens.")
         if len(pens) != len(self.data):
             raise Exception("Number of pens does not match number of points (%d != %d)" % (len(pens), len(self.data)))
         for i in xrange(len(pens)):
             self.data[i]['pen'] = fn.mkPen(pens[i])
     else:
         self.opts['pen'] = fn.mkPen(*args, **kargs)
     self.updateSpots()
示例#26
0
    def addAvgCurve(self, curve):
        ## Add a single curve into the pool of curves averaged together

        ## If there are plot parameters, then we need to determine which to average together.
        remKeys = []
        addKeys = []
        if self.ctrl.avgParamList.count() > 0:

            ### First determine the key of the curve to which this new data should be averaged
            for i in range(self.ctrl.avgParamList.count()):
                item = self.ctrl.avgParamList.item(i)
                if item.checkState() == QtCore.Qt.Checked:
                    remKeys.append(str(item.text()))
                else:
                    addKeys.append(str(item.text()))

            if len(
                    remKeys
            ) < 1:  ## In this case, there would be 1 average plot for each data plot; not useful.
                return

        p = self.itemMeta.get(curve, {}).copy()
        for k in p:
            if type(k) is tuple:
                p['.'.join(k)] = p[k]
                del p[k]
        for rk in remKeys:
            if rk in p:
                del p[rk]
        for ak in addKeys:
            if ak not in p:
                p[ak] = None
        key = tuple(p.items())

        ### Create a new curve if needed
        if key not in self.avgCurves:
            plot = PlotDataItem()
            plot.setPen(fn.mkPen([0, 200, 0]))
            plot.setShadowPen(fn.mkPen([0, 0, 0, 100], width=3))
            plot.setAlpha(1.0, False)
            plot.setZValue(100)
            self.addItem(plot, skipAverage=True)
            self.avgCurves[key] = [0, plot]
        self.avgCurves[key][0] += 1
        (n, plot) = self.avgCurves[key]

        ### Average data together
        (x, y) = curve.getData()
        if plot.yData is not None:
            newData = plot.yData * (n - 1) / float(n) + y * 1.0 / float(n)
            plot.setData(plot.xData, newData)
        else:
            plot.setData(x, y)
示例#27
0
 def addAvgCurve(self, curve):
     ## Add a single curve into the pool of curves averaged together
     
     ## If there are plot parameters, then we need to determine which to average together.
     remKeys = []
     addKeys = []
     if self.ctrl.avgParamList.count() > 0:
     
         ### First determine the key of the curve to which this new data should be averaged
         for i in range(self.ctrl.avgParamList.count()):
             item = self.ctrl.avgParamList.item(i)
             if item.checkState() == QtCore.Qt.Checked:
                 remKeys.append(str(item.text()))
             else:
                 addKeys.append(str(item.text()))
                 
         if len(remKeys) < 1:  ## In this case, there would be 1 average plot for each data plot; not useful.
             return
             
     p = self.itemMeta.get(curve,{}).copy()
     for k in p:
         if type(k) is tuple:
             p['.'.join(k)] = p[k]
             del p[k]
     for rk in remKeys:
         if rk in p:
             del p[rk]
     for ak in addKeys:
         if ak not in p:
             p[ak] = None
     key = tuple(p.items())
     
     ### Create a new curve if needed
     if key not in self.avgCurves:
         plot = PlotDataItem()
         plot.setPen(fn.mkPen([0, 200, 0]))
         plot.setShadowPen(fn.mkPen([0, 0, 0, 100], width=3))
         plot.setAlpha(1.0, False)
         plot.setZValue(100)
         self.addItem(plot, skipAverage=True)
         self.avgCurves[key] = [0, plot]
     self.avgCurves[key][0] += 1
     (n, plot) = self.avgCurves[key]
     
     ### Average data together
     (x, y) = curve.getData()
     if plot.yData is not None:
         newData = plot.yData * (n-1) / float(n) + y * 1.0 / float(n)
         plot.setData(plot.xData, newData)
     else:
         plot.setData(x, y)
示例#28
0
    def paint(self, p, *args):
        if self.isSelected():
            p.setPen(
                fn.mkPen(self.style['selectedColor'],
                         width=self.style['selectedWidth']))
        else:
            if self.hovered:
                p.setPen(
                    fn.mkPen(self.style['hoverColor'],
                             width=self.style['hoverWidth']))
            else:
                p.setPen(
                    fn.mkPen(self.style['color'], width=self.style['width']))

        p.drawPath(self.path)
示例#29
0
 def setShadowPen(self, *args, **kargs):
     """Set the shadow pen used to draw behind tyhe primary pen.
     This pen must have a larger width than the primary 
     pen to be visible.
     """
     self.opts['shadowPen'] = fn.mkPen(*args, **kargs)
     self.update()
示例#30
0
    def __init__(self, **opts):
        """
        Arrows can be initialized with any keyword arguments accepted by 
        the setStyle() method.
        """
        QtGui.QGraphicsPathItem.__init__(self, opts.get('parent', None))
        if 'size' in opts:
            opts['headLen'] = opts['size']
        if 'width' in opts:
            opts['headWidth'] = opts['width']
        defOpts = {
            'pxMode': True,
            'angle': -150,  ## If the angle is 0, the arrow points left
            'pos': (0, 0),
            'headLen': 20,
            'tipAngle': 25,
            'baseAngle': 0,
            'tailLen': None,
            'tailWidth': 3,
            'pen': (200, 200, 200),
            'brush': (50, 50, 200),
        }
        defOpts.update(opts)

        self.setStyle(**defOpts)

        self.setPen(fn.mkPen(defOpts['pen']))
        self.setBrush(fn.mkBrush(defOpts['brush']))

        self.rotate(self.opts['angle'])
        self.moveBy(*self.opts['pos'])
示例#31
0
    def __init__(self, positions=(None, None), pos=None, handles=(None,None), **args):
        pgROI.LineSegmentROI.__init__(self, positions, pos, handles, **args)
 
        self.penHover     = fn.mkPen(255, 255, 0)        
        self.translatable = False            
        self.setSelectable(True)
        self.setAcceptsHandles(True)
示例#32
0
def test_NonUniformImage_colormap():

    window = pg.GraphicsLayoutWidget()
    viewbox = pg.ViewBox()
    window.setCentralWidget(viewbox)
    window.resize(200, 200)
    window.show()

    x = [1.0, 3.0, 10.0]
    y = [1.0, 2.0, 4.0]
    X, Y = np.meshgrid(x, y, indexing='ij')
    Z = X * Y

    Z[:, 0] = [np.NINF, np.NAN, np.PINF]

    image = NonUniformImage(x, y, Z, border=fn.mkPen('g'))

    cmap = ColorMap(pos=[0.0, 1.0],
                    color=[(0.0, 0.0, 0.0, 1.0), (1.0, 1.0, 1.0, 1.0)])
    image.setColorMap(cmap)

    viewbox.addItem(image)

    QtTest.QTest.qWaitForWindowExposed(window)
    QtTest.QTest.qWait(100)

    assertImageApproved(window, 'nonuniform_image/colormap-3x3')
    def generatePicture(self):
        self.picture = QtGui.QPicture()
        if self.pen is None or self.pos is None or self.adjacency is None:
            return
        p = QtGui.QPainter(self.picture)
        pen = self.pen
        if pen == 'default':
            pen = getConfigOption('foreground')
        p.setPen(fn.mkPen((165, 42, 42), width=3))

        pts = self.pos[self.adjacency]
        pts = pts.reshape((pts.shape[0] * pts.shape[1], pts.shape[2]))
        x = pts[:, 0]
        y = pts[:, 1]
        path = QtGui.QPainterPath()
        path.moveTo(x[0], y[0])
        for i in range(1, y.shape[0]):
            if i % 2 != 0:
                c1x = x[i - 1] + 0.4 * (x[i] - x[i - 1])
                c1y = y[i - 1] + 0.05 * (y[i] - y[i - 1])
                c2x = x[i] + 0.2 * (x[i] - x[i - 1])
                c2y = y[i] - 0.5 * (y[i] - y[i - 1])
                c1 = pg.QtCore.QPointF(c1x, c1y)
                c2 = pg.QtCore.QPointF(c2x, c2y)
                endPoint = pg.QtCore.QPointF(x[i], y[i])
                path.cubicTo(c1, c2, endPoint)
            else:
                path.moveTo(x[i], y[i])
        p.drawPath(path)
示例#34
0
    def addItem(self, item, name):
        """
        Add a new entry to the legend.

        ==============  ========================================================
        **Arguments:**
        item            A PlotDataItem from which the line and point style
                        of the item will be determined or an instance of
                        ItemSample (or a subclass), allowing the item display
                        to be customized.
        title           The title to display for this item. Simple HTML allowed.
        ==============  ========================================================
        """

        # get item color
        pen = fn.mkPen(item.opts['pen'])
        color = pen.color()
        color_str = color.name()

        #create label with same color
        label = LabelItem()
        label.setAttr('color', str(color_str[1:]))
        label.setText(name)

        if isinstance(item, ItemSample):
            sample = item
        else:
            sample = ItemSample(item)

        self.legendItems.append((sample, label))
        self.plotItems.append(item)
        self.layout.addItem(sample, self.numItems, 0)
        self.layout.addItem(label, self.numItems, 1)
        self.numItems += 1
        self.updateSize()
示例#35
0
    def addItem(self, item, name):
        """
        Add a new entry to the legend.

        ==============  ========================================================
        **Arguments:**
        item            A PlotDataItem from which the line and point style
                        of the item will be determined or an instance of
                        ItemSample (or a subclass), allowing the item display
                        to be customized.
        title           The title to display for this item. Simple HTML allowed.
        ==============  ========================================================
        """

        # get item color
        pen = fn.mkPen(item.opts['pen'])
        color = pen.color()
        color_str = color.name()

        #create label with same color
        label = LabelItem()
        label.setAttr('color', str(color_str[1:]))
        label.setText(name)

        if isinstance(item, ItemSample):
            sample = item
        else:
            sample = ItemSample(item)

        self.legendItems.append((sample, label))
        self.plotItems.append(item)
        self.layout.addItem(sample, self.numItems, 0)
        self.layout.addItem(label, self.numItems, 1)
        self.numItems += 1
        self.updateSize()
示例#36
0
def test_NonUniformImage_lut():

    window = pg.GraphicsLayoutWidget()
    viewbox = pg.ViewBox()
    window.setCentralWidget(viewbox)
    window.resize(200, 200)
    window.show()

    x = [1.0, 3.0, 10.0]
    y = [1.0, 2.0, 4.0]
    X, Y = np.meshgrid(x, y, indexing='ij')
    Z = X * Y

    image = NonUniformImage(x, y, Z, border=fn.mkPen('g'))
    viewbox.addItem(image)

    lut = pg.HistogramLUTItem()
    window.addItem(lut)

    image.setLookupTable(lut, autoLevel=True)

    h = image.getHistogram()
    lut.plot.setData(*h)

    QtTest.QTest.qWaitForWindowExposed(window)
    QtTest.QTest.qWait(100)

    assertImageApproved(window, 'nonuniform_image/lut-3x3')
示例#37
0
 def paint(self, p, *args):
     if self.border is None:
         return
     p.setPen(fn.mkPen(self.border))
     for i in self.items:
         r = i.mapRectToParent(i.boundingRect())
         p.drawRect(r)
示例#38
0
 def setShadowPen(self, *args, **kargs):
     """Set the shadow pen used to draw behind tyhe primary pen.
     This pen must have a larger width than the primary 
     pen to be visible.
     """
     self.opts['shadowPen'] = fn.mkPen(*args, **kargs)
     self.update()
示例#39
0
 def __init__(self, **opts):
     """
     Arrows can be initialized with any keyword arguments accepted by 
     the setStyle() method.
     """
     QtGui.QGraphicsPathItem.__init__(self, opts.get('parent', None))
     if 'size' in opts:
         opts['headLen'] = opts['size']
     if 'width' in opts:
         opts['headWidth'] = opts['width']
     defOpts = {
         'pxMode': True,
         'angle': -150,   ## If the angle is 0, the arrow points left
         'pos': (0,0),
         'headLen': 20,
         'tipAngle': 25,
         'baseAngle': 0,
         'tailLen': None,
         'tailWidth': 3,
         'pen': (200,200,200),
         'brush': (50,50,200),
     }
     defOpts.update(opts)
     
     self.setStyle(**defOpts)
     
     self.setPen(fn.mkPen(defOpts['pen']))
     self.setBrush(fn.mkBrush(defOpts['brush']))
     
     self.rotate(self.opts['angle'])
     self.moveBy(*self.opts['pos'])
示例#40
0
    def __init__(self, *args, **kargs):
        """
        Forwards all arguments to :func:`setData <pyqtgraph.PlotCurveItem.setData>`.
        
        Some extra arguments are accepted as well:
        
        ==============  =======================================================
        **Arguments:**
        parent          The parent GraphicsObject (optional)
        clickable       If True, the item will emit sigClicked when it is 
                        clicked on. Defaults to False.
        ==============  =======================================================
        """
        GraphicsObject.__init__(self, kargs.get('parent', None))
        self.clear()
        self.path = None
        self.fillPath = None
        self.exportOpts = False
        self.antialias = False

        ## this is disastrous for performance.
        #self.setCacheMode(QtGui.QGraphicsItem.DeviceCoordinateCache)

        self.metaData = {}
        self.opts = {
            'pen': fn.mkPen('w'),
            'shadowPen': None,
            'fillLevel': None,
            'brush': None,
        }
        self.setClickable(kargs.get('clickable', False))
        self.setData(*args, **kargs)
示例#41
0
 def getArrayRegion(self,
                    data,
                    img,
                    axes=(0, 1),
                    returnMappedCoords=False,
                    **kwds):
     sl = self.getArraySlice(data, img, axes=(0, 1))
     if sl is None:
         return None
     sliced = data[sl[0]]
     im = QtGui.QImage(sliced.shape[axes[0]], sliced.shape[axes[1]],
                       QtGui.QImage.Format_ARGB32)
     im.fill(0x0)
     p = QtGui.QPainter(im)
     p.setPen(fn.mkPen(None))
     p.setBrush(fn.mkBrush('w'))
     p.setTransform(self.itemTransform(img)[0])
     bounds = self.mapRectToItem(img, self.boundingRect())
     p.translate(-bounds.left(), -bounds.top())
     p.drawPath(self.shape())
     p.end()
     mask = imageToArray(im)[:, :, 0].astype(float) / 255.
     shape = [1] * data.ndim
     shape[axes[0]] = sliced.shape[axes[0]]
     shape[axes[1]] = sliced.shape[axes[1]]
     return sliced * mask.reshape(shape)
示例#42
0
    def __init__(self,
                 size,
                 width=5,
                 brush=None,
                 pen=None,
                 suffix='m',
                 offset=None):
        GraphicsObject.__init__(self)
        GraphicsWidgetAnchor.__init__(self)
        self.setFlag(self.ItemHasNoContents)
        self.setAcceptedMouseButtons(QtCore.Qt.NoButton)

        if brush is None:
            brush = getConfigOption('foreground')
        self.brush = fn.mkBrush(brush)
        self.pen = fn.mkPen(pen)
        self._width = width
        self.size = size
        if offset == None:
            offset = (0, 0)
        self.offset = offset

        self.bar = QtGui.QGraphicsRectItem()
        self.bar.setPen(self.pen)
        self.bar.setBrush(self.brush)
        self.bar.setParentItem(self)

        self.text = TextItem(text=fn.siFormat(size, suffix=suffix),
                             anchor=(0.5, 1),
                             angle=90,
                             color=(0, 0, 0))
        self.text.setParentItem(self)
示例#43
0
 def setSymbolPen(self, *args, **kargs):
     pen = fn.mkPen(*args, **kargs)
     if self.opts['symbolPen'] == pen:
         return
     self.opts['symbolPen'] = pen
     #self.scatter.setSymbolPen(pen)
     self.updateItems()
示例#44
0
    def process(self, df):
        if df is None:
            del self.item
            self.item = None
            return {'Curve': None, 'pd.Series': None }
        if self.item is None:
            self.item = PlotDataItem(clipToView=False)

        colname = [col for col in df.columns if isNumpyNumeric(df[col].dtype)]
        self._ctrlWidget.param('Y:signal').setLimits(colname)
        colname = [col for col in df.columns if isNumpyDatetime(df[col].dtype)]
        self._ctrlWidget.param('X:datetime').setLimits(colname)

        with BusyCursor():
            kwargs = self.ctrlWidget().prepareInputArguments()
            
            #self.item = PlotDataItem(clipToView=False)
            t = df[kwargs['X:datetime']].values
            # part 1
            timeSeries = pd.DataFrame(data=df[kwargs['Y:signal']].values, index=t, columns=[kwargs['Y:signal']])

            # part 2
            #   convert time
            b = t.astype(np.dtype('datetime64[s]'))
            timeStamps = b.astype(np.int64)-kwargs['tz correct']*60*60+time.timezone
            #   now create curve
            pen = fn.mkPen(color=kwargs['color'], width=kwargs['width'], style=kwargs['style'])
            self.item.setData(timeStamps, df[kwargs['Y:signal']].values, pen=pen, name=kwargs['Y:signal'])
            
            self.item.setSymbol(kwargs['symbol'])
            if kwargs['symbol'] is not None:
                self.item.setSymbolPen(kwargs['color'])
                self.item.setSymbolBrush(kwargs['color'])
                self.item.setSymbolSize(kwargs['symbolSize'])
        return {'Curve': self.item, 'pd.Series': timeSeries }
示例#45
0
 def __init__(self, *args, **kargs):
     """
     Forwards all arguments to :func:`setData <pyqtgraph.PlotCurveItem.setData>`.
     
     Some extra arguments are accepted as well:
     
     ==============  =======================================================
     **Arguments:**
     parent          The parent GraphicsObject (optional)
     clickable       If True, the item will emit sigClicked when it is 
                     clicked on. Defaults to False.
     ==============  =======================================================
     """
     GraphicsObject.__init__(self, kargs.get('parent', None))
     self.clear()
     self.path = None
     self.fillPath = None
     self._boundsCache = [None, None]
         
     ## this is disastrous for performance.
     #self.setCacheMode(QtGui.QGraphicsItem.DeviceCoordinateCache)
     
     self.metaData = {}
     self.opts = {
         'pen': fn.mkPen('w'),
         'shadowPen': None,
         'fillLevel': None,
         'brush': None,
         'stepMode': False,
         'name': None,
         'antialias': pg.getConfigOption('antialias'),
     }
     self.setClickable(kargs.get('clickable', False))
     self.setData(*args, **kargs)
示例#46
0
 def paint(self, p, *args):
     if self.border is None:
         return
     p.setPen(fn.mkPen(self.border))
     for i in self.items:
         r = i.mapRectToParent(i.boundingRect())
         p.drawRect(r)
示例#47
0
 def paintGL(self, p, opt, widget):
     p.beginNativePainting()
     import OpenGL.GL as gl
     
     ## set clipping viewport
     view = self.getViewBox()
     if view is not None:
         rect = view.mapRectToItem(self, view.boundingRect())
         #gl.glViewport(int(rect.x()), int(rect.y()), int(rect.width()), int(rect.height()))
         
         #gl.glTranslate(-rect.x(), -rect.y(), 0)
         
         gl.glEnable(gl.GL_STENCIL_TEST)
         gl.glColorMask(gl.GL_FALSE, gl.GL_FALSE, gl.GL_FALSE, gl.GL_FALSE) # disable drawing to frame buffer
         gl.glDepthMask(gl.GL_FALSE)  # disable drawing to depth buffer
         gl.glStencilFunc(gl.GL_NEVER, 1, 0xFF)  
         gl.glStencilOp(gl.GL_REPLACE, gl.GL_KEEP, gl.GL_KEEP)  
         
         ## draw stencil pattern
         gl.glStencilMask(0xFF);
         gl.glClear(gl.GL_STENCIL_BUFFER_BIT)
         gl.glBegin(gl.GL_TRIANGLES)
         gl.glVertex2f(rect.x(), rect.y())
         gl.glVertex2f(rect.x()+rect.width(), rect.y())
         gl.glVertex2f(rect.x(), rect.y()+rect.height())
         gl.glVertex2f(rect.x()+rect.width(), rect.y()+rect.height())
         gl.glVertex2f(rect.x()+rect.width(), rect.y())
         gl.glVertex2f(rect.x(), rect.y()+rect.height())
         gl.glEnd()
                    
         gl.glColorMask(gl.GL_TRUE, gl.GL_TRUE, gl.GL_TRUE, gl.GL_TRUE)
         gl.glDepthMask(gl.GL_TRUE)
         gl.glStencilMask(0x00)
         gl.glStencilFunc(gl.GL_EQUAL, 1, 0xFF)
         
     try:
         x, y = self.getData()
         pos = np.empty((len(x), 2))
         pos[:,0] = x
         pos[:,1] = y
         gl.glEnableClientState(gl.GL_VERTEX_ARRAY)
         try:
             gl.glVertexPointerf(pos)
             pen = fn.mkPen(self.opts['pen'])
             color = pen.color()
             gl.glColor4f(color.red()/255., color.green()/255., color.blue()/255., color.alpha()/255.)
             width = pen.width()
             if pen.isCosmetic() and width < 1:
                 width = 1
             gl.glPointSize(width)
             gl.glEnable(gl.GL_LINE_SMOOTH)
             gl.glEnable(gl.GL_BLEND)
             gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
             gl.glHint(gl.GL_LINE_SMOOTH_HINT, gl.GL_NICEST);
             gl.glDrawArrays(gl.GL_LINE_STRIP, 0, pos.size / pos.shape[-1])
         finally:
             gl.glDisableClientState(gl.GL_VERTEX_ARRAY)
     finally:
         p.endNativePainting()
示例#48
0
 def __init__(self, size, width=5, color=(100, 100, 255)):
     UIGraphicsItem.__init__(self)
     self.setAcceptedMouseButtons(QtCore.Qt.NoButton)
     
     self.brush = fn.mkBrush(color)
     self.pen = fn.mkPen((0,0,0))
     self._width = width
     self.size = size
示例#49
0
 def __init__(self, pos):
     super().__init__()
     self.pos = pos
     self.pen = fn.mkPen((255, 255, 100), width=1)
     self.y1 = 5000
     self.picture = None
     self._boundingRect = None
     self._line = None
示例#50
0
    def buildAtlas(self):
        # get rendered array for all symbols, keep track of avg/max width
        rendered = {}
        avgWidth = 0.0
        maxWidth = 0
        images = []
        for key, coords in self.symbolMap.items():
            if len(coords) == 0:
                pen = fn.mkPen(color=key[2], width=key[3], style=key[4])
                brush = fn.mkBrush(color=key[5])
                img = renderSymbol(key[0], key[1], pen, brush)
                images.append(img)  ## we only need this to prevent the images being garbage collected immediately
                arr = fn.imageToArray(img, copy=False, transpose=False)
            else:
                (x,y,w,h) = self.symbolMap[key]
                arr = self.atlasData[x:x+w, y:y+w]
            rendered[key] = arr
            w = arr.shape[0]
            avgWidth += w
            maxWidth = max(maxWidth, w)
            
        nSymbols = len(rendered)
        if nSymbols > 0:
            avgWidth /= nSymbols
            width = max(maxWidth, avgWidth * (nSymbols**0.5))
        else:
            avgWidth = 0
            width = 0
        
        # sort symbols by height
        symbols = sorted(rendered.keys(), key=lambda x: rendered[x].shape[1], reverse=True)
        
        self.atlasRows = []

        x = width
        y = 0
        rowheight = 0
        for key in symbols:
            arr = rendered[key]
            w,h = arr.shape[:2]
            if x+w > width:
                y += rowheight
                x = 0
                rowheight = h
                self.atlasRows.append([y, rowheight, 0])
            self.symbolMap[key][:] = x, y, w, h
            x += w
            self.atlasRows[-1][2] = x
        height = y + rowheight

        self.atlasData = np.zeros((width, height, 4), dtype=np.ubyte)
        for key in symbols:
            x, y, w, h = self.symbolMap[key]
            self.atlasData[x:x+w, y:y+h] = rendered[key]
        self.atlas = None
        self.atlasValid = True
示例#51
0
 def setMouseHover(self, hover):
     ## Inform the item that the mouse is(not) hovering over it
     if self.mouseHovering == hover:
         return
     self.mouseHovering = hover
     if hover:
         self.currentPen = fn.mkPen(255, 0,0)
     else:
         self.currentPen = self.pen
     self.update()
示例#52
0
文件: SpinBox.py 项目: a-stark/qudi
    def paintEvent(self, ev):
        QtGui.QAbstractSpinBox.paintEvent(self, ev)

        ## draw red border if text is invalid
        if not self.textValid:
            p = QtGui.QPainter(self)
            p.setRenderHint(p.Antialiasing)
            p.setPen(fn.mkPen((200,50,50), width=2))
            p.drawRoundedRect(self.rect().adjusted(2, 2, -2, -2), 4, 4)
            p.end()
示例#53
0
 def __init__(self, view, pos, color, movable=True, scale=10, pen='w'):
     self.movable = movable
     self.moving = False
     self.view = weakref.ref(view)
     self.scale = scale
     self.color = color
     self.pen = fn.mkPen(pen)
     self.hoverPen = fn.mkPen(255,255,0)
     self.currentPen = self.pen
     self.pg = QtGui.QPainterPath(QtCore.QPointF(0,0))
     self.pg.lineTo(QtCore.QPointF(-scale/3**0.5, scale))
     self.pg.lineTo(QtCore.QPointF(scale/3**0.5, scale))
     self.pg.closeSubpath()
     
     QtGui.QGraphicsObject.__init__(self)
     self.setPos(pos[0], pos[1])
     if self.movable:
         self.setZValue(1)
     else:
         self.setZValue(0)
示例#54
0
 def locate(self, item, timeout=3.0, children=False):
     """
     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.
     """
     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 = self.mapFromItemToView(item, item.boundingRect()).boundingRect()
     
     g = ItemGroup()
     g.setParentItem(self.childGroup)
     self.locateGroup = g
     g.box = QtGui.QGraphicsRectItem(br)
     g.box.setParentItem(g)
     g.lines = []
     for p in (br.topLeft(), br.bottomLeft(), br.bottomRight(), br.topRight()):
         line = QtGui.QGraphicsLineItem(c.x(), c.y(), p.x(), p.y())
         line.setParentItem(g)
         g.lines.append(line)
         
     for item in g.childItems():
         item.setPen(fn.mkPen(color='y', width=3))
     g.setZValue(1000000)
     
     if children:
         g.path = QtGui.QGraphicsPathItem(g.childrenShape())
     else:
         g.path = QtGui.QGraphicsPathItem(g.shape())
     g.path.setParentItem(g)
     g.path.setPen(fn.mkPen('g'))
     g.path.setZValue(100)
     
     QtCore.QTimer.singleShot(timeout*1000, self.clearLocate)
示例#55
0
 def setPen(self, *args, **kargs):
     """
     | Sets the pen used to draw lines between points.
     | *pen* can be a QPen or any argument accepted by :func:`pyqtgraph.mkPen() <pyqtgraph.mkPen>`
     """
     pen = fn.mkPen(*args, **kargs)
     self.opts['pen'] = pen
     #self.curve.setPen(pen)
     #for c in self.curves:
         #c.setPen(pen)
     #self.update()
     self.updateItems()
示例#56
0
 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.orientations = {
         'left': (90, 1, 1), 
         'right': (90, 1, 1), 
         'top': (0, 1, -1), 
         'bottom': (0, 1, 1)
     }
     
     self.setOrientation(orientation)
示例#57
0
 def paint(self, p, *args):
     pen = self.region.lines[0].pen
     rgn = self.getLevels()
     p1 = self.vb.mapFromViewToItem(self, Point(self.vb.viewRect().center().x(), rgn[0]))
     p2 = self.vb.mapFromViewToItem(self, Point(self.vb.viewRect().center().x(), rgn[1]))
     gradRect = self.gradient.mapRectToParent(self.gradient.gradRect.rect())
     for pen in [fn.mkPen('k', width=3), pen]:
         p.setPen(pen)
         p.drawLine(p1, gradRect.bottomLeft())
         p.drawLine(p2, gradRect.topLeft())
         p.drawLine(gradRect.topLeft(), gradRect.topRight())
         p.drawLine(gradRect.bottomLeft(), gradRect.bottomRight())
示例#58
0
 def setShadowPen(self, *args, **kargs):
     """
     | 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 accepted by :func:`pyqtgraph.mkPen() <pyqtgraph.mkPen>`
     """
     pen = fn.mkPen(*args, **kargs)
     self.opts['shadowPen'] = pen
     #for c in self.curves:
         #c.setPen(pen)
     #self.update()
     self.updateItems()
示例#59
0
 def mkSpot(self, pos, size, pxMode, brush, pen, data, symbol=None, index=None):
     ## Make and return a SpotItem (or PixmapSpotItem if in pxMode)
     brush = fn.mkBrush(brush)
     pen = fn.mkPen(pen)
     if pxMode:
         img = self.spotPixmap()  ## returns None if not using identical mode
         #item = PixmapSpotItem(size, brush, pen, data, image=img, symbol=symbol, index=index)
         item = SpotItem(size, pxMode, brush, pen, data, symbol=symbol, image=img, index=index)
     else:
         item = SpotItem(size, pxMode, brush, pen, data, symbol=symbol, index=index)
     item.setParentItem(self)
     item.setPos(pos)
     #item.sigClicked.connect(self.pointClicked)
     return item