コード例 #1
0
    def writeSvg(self, fileName=None):
        if fileName is None:
            fileName = QtGui.QFileDialog.getSaveFileName()
        fileName = str(fileName)
        PlotItem.lastFileDir = os.path.dirname(fileName)

        self.svg = QtSvg.QSvgGenerator()
        self.svg.setFileName(fileName)
        res = 120.
        view = self.scene().views()[0]
        bounds = view.viewport().rect()
        bounds = QtCore.QRectF(0, 0, bounds.width(), bounds.height())

        self.svg.setResolution(res)
        self.svg.setViewBox(bounds)

        self.svg.setSize(QtCore.QSize(bounds.width(), bounds.height()))

        painter = QtGui.QPainter(self.svg)
        view.render(painter, bounds)

        painter.end()

        ## Workaround to set pen widths correctly
        import re
        data = open(fileName).readlines()
        for i in range(len(data)):
            line = data[i]
            m = re.match(
                r'(<g .*)stroke-width="1"(.*transform="matrix\(([^\)]+)\)".*)',
                line)
            if m is not None:
                #print "Matched group:", line
                g = m.groups()
                matrix = list(map(float, g[2].split(',')))
                #print "matrix:", matrix
                scale = max(abs(matrix[0]), abs(matrix[3]))
                if scale == 0 or scale == 1.0:
                    continue
                data[i] = g[0] + ' stroke-width="%0.2g" ' % (
                    1.0 / scale) + g[1] + '\n'
                #print "old line:", line
                #print "new line:", data[i]
        open(fileName, 'w').write(''.join(data))
コード例 #2
0
ファイル: ExLegendItem.py プロジェクト: kif/Py2DeX
    def __init__(self,
                 size=None,
                 offset=None,
                 horSpacing=25,
                 verSpacing=0,
                 box=True):
        """
        ==============  ===============================================================
        **Arguments:**
        size            Specifies the fixed size (width, height) of the legend. If
                        this argument is omitted, the legend will autimatically resize
                        to fit its contents.
        offset          Specifies the offset position relative to the legend's parent.
                        Positive values offset from the left or top; negative values
                        offset from the right or bottom. If offset is None, the
                        legend must be anchored manually by calling anchor() or
                        positioned by calling setPos().
        horSpacing      Specifies the spacing between the line symbol and the label.
        verSpacing      Specifies the spacing between individual entries of the legend
                        vertically. (Can also be negative to have them really close)
        box             Specifies if the Legend should will be drawn with a rectangle
                        around it.
        ==============  ===============================================================

        """

        GraphicsWidget.__init__(self)
        GraphicsWidgetAnchor.__init__(self)
        self.setFlag(self.ItemIgnoresTransformations)
        self.layout = QtGui.QGraphicsGridLayout()
        self.layout.setVerticalSpacing(verSpacing)
        self.layout.setHorizontalSpacing(horSpacing)
        self.setLayout(self.layout)
        self.legendItems = []
        self.plotItems = []
        self.size = size
        self.offset = offset
        self.box = box
        #A numItems variable needs to be introduced, because chaining removeItem and addItem function in random order,
        # will otherwise lead to writing in the same layout row. Idea here is to always insert LabelItems on larger
        # and larger layout row numbers. The GraphicsGridlayout item will not care about empty rows.
        self.numItems = 0
        if size is not None:
            self.setGeometry(QtCore.QRectF(0, 0, self.size[0], self.size[1]))
コード例 #3
0
    def __init__(self,
                 text='',
                 color=(200, 200, 200),
                 html=None,
                 anchor=(0, 0),
                 border=None,
                 fill=None,
                 angle=0):
        """
        ===========  =================================================================================
        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. A value of (0,0) sets the upper-left corner
                     of the text box to be at the position specified by setPos(), while a value of (1,1)
                     sets the lower-right corner.
        *border*     A pen to use when drawing the border
        *fill*       A brush to use when filling within the border
        ===========  =================================================================================
        """

        ## not working yet
        #*angle*      Angle in degrees to rotate text (note that the rotation assigned in this item's
        #transformation will be ignored)

        self.anchor = pg.Point(anchor)
        #self.angle = 0
        UIGraphicsItem.__init__(self)
        self.textItem = QtGui.QGraphicsTextItem()
        self.textItem.setParentItem(self)
        self.lastTransform = None
        self._bounds = QtCore.QRectF()
        if html is None:
            self.setText(text, color)
        else:
            self.setHtml(html)
        self.fill = pg.mkBrush(fill)
        self.border = pg.mkPen(border)
        self.rotate(angle)
        self.setFlag(
            self.ItemIgnoresTransformations
        )  ## This is required to keep the text unscaled inside the viewport
コード例 #4
0
    def __init__(self,
                 buffer_size=0,
                 data_buffer=[],
                 graph_title="",
                 parent=None):
        super(App, self).__init__(parent)

        #### Create Gui Elements ###########
        self.mainbox = QtGui.QWidget()
        self.setCentralWidget(self.mainbox)
        self.mainbox.setLayout(QtGui.QVBoxLayout())

        self.canvas = pg.GraphicsLayoutWidget()
        self.mainbox.layout().addWidget(self.canvas)

        self.label = QtGui.QLabel()
        self.mainbox.layout().addWidget(self.label)

        self.view = self.canvas.addViewBox()
        self.view.setAspectLocked(True)
        self.view.setRange(QtCore.QRectF(0, 0, 100, 100))

        self.numDstreams = 1
        self.bufferLength = buffer_size
        self.graphTitle = graph_title

        self.otherplot = [
            [self.canvas.addPlot(row=i, col=0, title=self.graphTitle)
             ]  # , repeat line for more
            for i in range(0, self.numDstreams)
        ]
        self.h2 = [
            [self.otherplot[i][0].plot(pen='r')]
            for i in range(0, self.numDstreams)
        ]  # , self.otherplot[i][1].plot(pen='g'), self.otherplot[i][2].plot(pen='b')
        self.ydata = [
            [np.zeros((1, self.bufferLength))]
            for i in range(0, self.numDstreams)
        ]  # ,np.zeros((1,self.bufferLength)),np.zeros((1,self.bufferLength))

        for i in range(0, self.numDstreams):
            self.otherplot[i][0].setYRange(min=-100, max=100)
        self.update_plot(data_buffer)
コード例 #5
0
ファイル: plotter_qt2d.py プロジェクト: tpgillam/streamcanvas
    def __init__(self, controller):
        super().__init__()
        self._controller = controller
        self._frame_data = ''

        GraphicsScene.registerObject(self)

        # This will be a list of function calls that expect to be called with the painter object only
        self._painter_function_calls = []

        # The current view rectangle should increase as things are drawn. This is also used as the bounding rectangle,
        # since pyqtgraph setRange appears to do strange things if the bounding rect varies independently of the
        # view rect.
        # We *must* have a default bounding rectangle before we have any data, otherwise Qt will fall over.
        self._current_view_rect = QtCore.QRectF(0, 0, 1, 1)

        # Specify the point extent as a QPoint - think of this as a delta that we add and subtract
        self._point_extent = QtCore.QPointF(OPTIONS.point_extent,
                                            OPTIONS.point_extent)
コード例 #6
0
    def paintEvent(self, ev):
        QtGui.QPushButton.paintEvent(self, ev)
        margin = 7
        geom = QtCore.QRectF(0, 0, self.width(),
                             self.height()).adjusted(margin, margin, -margin,
                                                     -margin)
        rect = self.path.boundingRect()
        scale = min(geom.width() / float(rect.width()),
                    geom.height() / float(rect.height()))

        p = QtGui.QPainter(self)
        p.setRenderHint(p.Antialiasing)
        p.translate(geom.center())
        p.scale(scale, scale)
        p.translate(-rect.center())
        p.setPen(self.pen)
        p.setBrush(self.brush)
        p.drawPath(self.path)
        p.end()
コード例 #7
0
    def scaleBy(self, s, center=None):
        """
        Scale by *s* around given center point (or center of view).
        *s* may be a Point or tuple (x, y)
        """
        scale = Point(s)
        if self.state['aspectLocked'] is not False:
            scale[0] = self.state['aspectLocked'] * scale[1]

        vr = self.targetRect()
        if center is None:
            center = Point(vr.center())
        else:
            center = Point(center)

        tl = center + (vr.topLeft() - center) * scale
        br = center + (vr.bottomRight() - center) * scale

        self.setRange(QtCore.QRectF(tl, br), padding=0)
コード例 #8
0
    def paint(self, p, *args):
        profile = debug.Profiler()
        if self.image is None:
            return
        if self.qimage is None:
            self.render()
            if self.qimage is None:
                return
            profile('render QImage')
        if self.paintMode is not None:
            p.setCompositionMode(self.paintMode)
            profile('set comp mode')

        shape = self.image.shape[:2] if self.axisOrder == 'col-major' else self.image.shape[:2][::-1]
        p.drawImage(QtCore.QRectF(0,0,*shape), self.qimage)
        profile('p.drawImage')
        if self.border is not None:
            p.setPen(self.border)
            p.drawRect(self.boundingRect())
コード例 #9
0
ファイル: LightboxItem.py プロジェクト: azlau/picachooser
def newColorbar(view, left, top, impixpervoxx, impixpervoxy, imgsize):
    cb_xdim = imgsize // 10
    cb_ydim = imgsize
    theviewbox = pg.ViewBox(enableMouse=False)
    theviewbox.setRange(QtCore.QRectF(0, 0, cb_xdim, cb_ydim),
                        xRange=(0, cb_xdim - 1), yRange=(0, cb_ydim - 1), padding=0.0,
                        disableAutoRange=False)
    theviewbox.setAspectLocked()

    thecolorbarwin = pg.ImageItem()
    theviewbox.addItem(thecolorbarwin)
    thecolorbarwin.translate(left, top)
    thecolorbarwin.scale(impixpervoxx, impixpervoxy)

    colorbarvals = np.zeros((cb_xdim, cb_ydim), dtype=np.float64)
    for i in range(0, cb_ydim):
        colorbarvals[:, i] = i * (1.0 / (cb_ydim - 1.0))
    thecolorbarwin.setImage(colorbarvals, levels=[0.0, 1.0])
    return thecolorbarwin, theviewbox
コード例 #10
0
    def __init__(self, qnt_pontos=10):
        self.qnt_pontos = qnt_pontos

        self.app = QtGui.QApplication([])
        self.plot = pg.plot()

        self.plot.setBackgroundBrush(QBrush(QColor.fromRgb(255, 255, 255)))
        #self.plot.windowTitle().
        #self.plot.setForegroundBrush(QBrush(QColor.fromRgb(250,0,0,30)))
        self.plot.setWindowTitle('PlotterHandler')
        self.plot.setRange(QtCore.QRectF(0, -10, 5000, 20))
        self.plot.setLabel('bottom', 'Index', units='un')
        self.plot.setLabel('left', 'Valor', units='V')
        self.curve = self.plot.plot(pen='b')
        # self.plot.enableAutoRange('xy', True)
        self.plot.enableAutoRange('xy', False)
        self.plot.setXRange(0, 5000)
        self.plot.setYRange(0, 5)

        #self.plot.enableAutoRange('xy', True)
        #grade = pg.GridItem()
        #self.plot.addItem(grade)
        self.plot.showGrid(True, True)
        #self.plot.showAxis('top', False)
        #self.plot.showAxis('bottom', False)
        #self.plot.showAxis('left', False)
        #self.plot.showAxis('right', False)
        self.plot.getAxis('left').setPen(QPen(QColor.fromRgb(0, 0, 0)))
        self.plot.getAxis('bottom').setPen(QPen(QColor.fromRgb(0, 0, 0)))
        #print self.plot.getRange
        #self.plot.
        # self.plot.showGrid(2,3)
        #self.plot.hideAxis(ax)
        #

        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.update_y_points)

        self.lastTime = time()
        self.fps = None

        self.y_values = [0] * self.qnt_pontos
        self.plot_buffer = Queue(qnt_pontos)
コード例 #11
0
 def mkPath(self):
     self.prepareGeometryChange()
     r = self.r
     d = self.d
     h2 = d/2.
     self.path = QtGui.QPainterPath()
     if r == 0:  ## flat surface
         self.path.moveTo(0, h2)
         self.path.lineTo(0, -h2)
     else:
         ## half-height of surface can't be larger than radius
         h2 = min(h2, abs(r))
         arc = QtCore.QRectF(0, -r, r*2, r*2)
         a1 = np.arcsin(h2/r) * 180. / np.pi
         a2 = -2*a1
         a1 += 180.
         self.path.arcMoveTo(arc, a1)
         self.path.arcTo(arc, a1, a2)
     self.h2 = h2
コード例 #12
0
    def __init__(self, walls, obs, goal, start, parent=None):
        super(App, self).__init__(parent)
        w, o, g, m = -100, -5000, 1e5, -2
        self.start = start
        self.map = np.zeros((*obs.shape,3))
        self.map[:,:,2] = walls * g
        self.map[:,:,0] = obs * g
        self.map[:,:,1] = goal * g
        self.mask = (walls + obs + goal) == 0
        self.mask[0] = self.mask[-1] = self.mask[:,0] = self.mask[:,-1] = False
        self.mdp = MDPPlanner(walls, obs, goal, w, o, g, m)
        self.idx = 0
        self.running = True
        self.min_delta = obs.size / 2

        #### Create Gui Elements ###########
        self.mainbox = QtGui.QWidget()
        self.setCentralWidget(self.mainbox)
        self.mainbox.setLayout(QtGui.QVBoxLayout())

        self.canvas = pg.GraphicsLayoutWidget()
        self.mainbox.layout().addWidget(self.canvas)

        self.label = QtGui.QLabel()
        self.mainbox.layout().addWidget(self.label)

        self.view = self.canvas.addViewBox()
        self.view.setAspectLocked(True)
        self.view.setRange(QtCore.QRectF(0,0,*self.mask.T.shape )) #size screen

        #  image plot
        self.img = pg.ImageItem(border='w')
        self.view.addItem(self.img)


        #### Set Data  #####################

        self.counter = 0
        self.fps = 0.
        self.lastupdate = time.time()

        #### Start  #####################
        self._update()
コード例 #13
0
def test_setRect():
    def assert_equal_transforms(tr1, tr2):
        dic = {  # there seems to be no easy way to get the matrix in one call:
            'tr11': (tr1.m11(), tr2.m11()),
            'tr12': (tr1.m12(), tr2.m12()),
            'tr13': (tr1.m13(), tr2.m13()),
            'tr21': (tr1.m21(), tr2.m21()),
            'tr22': (tr1.m22(), tr2.m22()),
            'tr23': (tr1.m23(), tr2.m23()),
            'tr31': (tr1.m31(), tr2.m31()),
            'tr32': (tr1.m32(), tr2.m32()),
            'tr33': (tr1.m33(), tr2.m33())
        }
        log_string = 'Matrix element mismatch\n'
        good = True
        for key, values in dic.items():
            val1, val2 = values
            if val1 != val2:
                good = False
                log_string += f'{key}: {val1} != {val2}\n'
        assert good, log_string

    tr = QtGui.QTransform()  # construct a reference transform
    tr.scale(2, 4)  # scale 2x2 image to 4x8
    tr.translate(-1, -1)  # after shifting by -1, -1
    # the transformed 2x2 image would cover (-2,-4) to (2,4).
    # Now have setRect construct the same transform:
    imgitem = pg.ImageItem(np.eye(2),
                           rect=(-2, -4, 4, 8))  # test tuple of floats
    assert_equal_transforms(tr, imgitem.transform())

    imgitem = pg.ImageItem(np.eye(2), rect=QtCore.QRectF(-2, -4, 4,
                                                         8))  # test QRectF
    assert_equal_transforms(tr, imgitem.transform())

    imgitem = pg.ImageItem(np.eye(2))
    imgitem.setRect(-2, -4, 4, 8)  # test individual parameters
    assert_equal_transforms(tr, imgitem.transform())

    imgitem = pg.ImageItem(np.eye(2))
    imgitem.setRect(QtCore.QRect(-2, -4, 4, 8))  # test QRect argument
    assert_equal_transforms(tr, imgitem.transform())
コード例 #14
0
	def resize_to_scaling_factor(self, image):
		"""
		Handles loading of image according to scaling_factor
		"""
		self.update_scaling_factor()

		if self.ui.spot_radioButton.isChecked() and self.ui.resize_image_checkBox.isChecked():
			image = self.original_image.resize((round(image.size[0]*self.scaling_factor), round(image.size[1]*self.scaling_factor)))
			self.image_plot.getAxis("bottom").setScale(scale = 1)
			self.image_plot.getAxis("left").setScale(scale = 1)
		else:
			image = self.original_image
			self.image_plot.getAxis("bottom").setScale(scale = self.scaling_factor)
			self.image_plot.getAxis("left").setScale(scale = self.scaling_factor)
			
		if self.ui.greyscale_checkBox.isChecked():
			image = image.convert("L") #convert to greyscale

		self.image_array = np.array(image)
		width = self.image_array.shape[0]
		height = self.image_array.shape[1]
		
		try:
			#set image bounds with qrect
			self.img_item_rect = QtCore.QRectF(0, 0, width, height)
			self.img_item.setImage(image=self.image_array)
			self.img_item.setRect(self.img_item_rect)

			# if self.ui.greyscale_checkBox.isChecked():
			# 	self.hist_lut.setImageItem(self.img_item)
			
			if self.ui.vertical_radioButton.isChecked():
				roi_height = self.scaling_factor * height
				self.roi.setSize([width, roi_height])
			elif self.ui.horizontal_radioButton.isChecked():
				roi_height = self.scaling_factor * width
				self.roi.setSize([roi_height, height])
			self.roi.setAngle(0)
			self.roi.setPos(0, 0)
			self.line_profile_update_plot()
		except:
			pass
コード例 #15
0
ファイル: ImageExporter.py プロジェクト: robertsj/poropy
    def export(self, fileName=None):
        if fileName is None:
            filter = [
                "*." + str(f)
                for f in QtGui.QImageWriter.supportedImageFormats()
            ]
            preferred = ['*.png', '*.tif', '*.jpg']
            for p in preferred[::-1]:
                if p in filter:
                    filter.remove(p)
                    filter.insert(0, p)
            self.fileSaveDialog(filter=filter)
            return

        targetRect = QtCore.QRect(0, 0, self.params['width'],
                                  self.params['height'])
        sourceRect = self.getSourceRect()
        #self.png = QtGui.QImage(targetRect.size(), QtGui.QImage.Format_ARGB32)
        #self.png.fill(pyqtgraph.mkColor(self.params['background']))
        bg = np.empty((self.params['width'], self.params['height'], 4),
                      dtype=np.ubyte)
        color = self.params['background']
        bg[:, :, 0] = color.blue()
        bg[:, :, 1] = color.green()
        bg[:, :, 2] = color.red()
        bg[:, :, 3] = color.alpha()
        self.png = pg.makeQImage(bg, alpha=True)
        painter = QtGui.QPainter(self.png)
        try:
            self.setExportMode(
                True, {
                    'antialias': self.params['antialias'],
                    'background': self.params['background']
                })
            painter.setRenderHint(QtGui.QPainter.Antialiasing,
                                  self.params['antialias'])
            self.getScene().render(painter, QtCore.QRectF(targetRect),
                                   sourceRect)
        finally:
            self.setExportMode(False)
        self.png.save(fileName)
        painter.end()
コード例 #16
0
    def __init__(self, parent=None):
        super(App, self).__init__(parent)

        #### Create Gui Elements ###########
        self.mainbox = QtGui.QWidget()
        self.setCentralWidget(self.mainbox)
        self.mainbox.setLayout(QtGui.QVBoxLayout())

        self.canvas = pg.GraphicsLayoutWidget()
        self.mainbox.layout().addWidget(self.canvas)

        self.label = QtGui.QLabel()
        self.mainbox.layout().addWidget(self.label)

        self.view = self.canvas.addViewBox()
        self.view.setAspectLocked(True)
        self.view.setRange(QtCore.QRectF(0, 0, 100, 100))

        #  image plot
        #self.img = pg.ImageItem(border='w')
        #self.view.addItem(self.img)

        self.canvas.nextRow()
        #  line plot
        self.otherplot = self.canvas.addPlot()
        self.h2 = self.otherplot.plot(pen='y')
        ### F**k knows what I am doing
        self.arduinoData = serial.Serial(
            'com3', 9600,
            timeout=None)  # Creating our serial object named arduinoData
        self.readSerialLine = ReadLine(self.arduinoData)
        #### Set Data  #####################

        self.x = np.linspace(0, 50., num=100)
        self.X, self.Y = np.meshgrid(self.x, self.x)

        self.counter = 0
        self.fps = 0.
        self.lastupdate = time.time()
        self.ydata = np.zeros([100])
        #### Start  #####################
        self._update()
コード例 #17
0
ファイル: baseitems.py プロジェクト: kairuitouzi/hseng_pyqt
 def generatePicture(self):
     # pre-computing a QPicture object allows paint() to run much more quickly,
     # rather than re-drawing the shapes every time.
     self.picture = QtGui.QPicture()
     p = QtGui.QPainter(self.picture)
     p.setPen(self.WLinePen)
     w = self.PenWidth
     for (i, t, open, high, low, close) in self.data.itertuples():
         p.drawLine(QtCore.QPointF(i, low), QtCore.QPointF(i, high))
         if self.is_current_bar:
             self.hline.setPos(close)
             self.htext.setText(f'{close}', color='w')
         if open > close:
             p.setBrush(self.GreenBrush)
             self.hline.setPen(self.GLinePen)
         else:
             p.setBrush(self.RedBrush)
             self.hline.setPen(self.RLinePen)
         p.drawRect(QtCore.QRectF(i-w, open, w*2, close-open))
     p.end()
コード例 #18
0
 def mouseDragEvent(self, ev):
     
     if ev.button() == QtCore.Qt.RightButton:
         ev.ignore()    
     else:
         pg.ViewBox.mouseDragEvent(self, ev)
      
     ev.accept() 
     pos = ev.pos()
     if ev.button() == QtCore.Qt.RightButton:
         
         if ev.isFinish():  
             self.rbScaleBox.hide()
             self.ax = QtCore.QRectF(Point(ev.buttonDownPos(ev.button())), Point(pos))
             self.ax = self.childGroup.mapRectFromParent(self.ax) 
             self.Coords =  self.ax.getCoords()  
             self.getdataInRect()
             self.changePointsColors()
         else:
             self.updateScaleBox(ev.buttonDownPos(), ev.pos())
コード例 #19
0
ファイル: ui.py プロジェクト: afcarl/ccfviewer
    def paint(self, p, *args):
        pg.ROI.paint(self, p, *args)
        h1 = self.handles[0]['item'].pos()
        h2 = self.handles[1]['item'].pos()
        h4 = self.handles[3]['item']
        h5 = self.handles[4]['item']
        h4.setVisible(False)
        h5.setVisible(False)
        p1 = p.transform().map(h1)
        p2 = p.transform().map(h2)

        vec = pg.Point(h2) - pg.Point(h1)
        length = vec.length()

        pvec = p2 - p1
        pvecT = pg.Point(pvec.y(), -pvec.x())
        pos = 0.5 * (p1 + p2) + pvecT * 40 / pvecT.length()

        angle = pg.Point(1, 0).angle(pg.Point(pvec))
        self.ab_angle = angle

        # Overlay a line to signal which side of the ROI is the back.
        if self.ac_angle > 0:
            self.newRoi.setVisible(True)
            self.newRoi.setPos(h5.pos())
        elif self.ac_angle < 0:
            self.newRoi.setVisible(True)
            self.newRoi.setPos(h4.pos())
        else:
            self.newRoi.setVisible(False)

        self.newRoi.setSize(pg.Point(self.size()[0], 0))

        p.resetTransform()

        txt = pg.siFormat(
            length,
            suffix='m') + '\n%0.1f deg' % angle + '\n%0.1f deg' % self.ac_angle
        p.drawText(QtCore.QRectF(pos.x() - 50,
                                 pos.y() - 50, 100, 100),
                   QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter, txt)
コード例 #20
0
ファイル: Cursor_Cross.py プロジェクト: sqdlab/SQDViz
    def boundingRect(self):
        br = QtCore.QRectF(self.viewRect(
        ))  # bounds of containing ViewBox mapped to local coords.

        nominalBoxSizePx = 20
        #
        lenX = self.pixelLength(pg.Point([1, 0])) * nominalBoxSizePx
        lenY = self.pixelLength(pg.Point([0, 1])) * nominalBoxSizePx

        br.setTop(self.lines[1].value() + lenY * 0.5)
        br.setBottom(self.lines[1].value() - lenY * 0.5)
        br.setLeft(self.lines[0].value() - lenX * 0.5)
        br.setRight(self.lines[0].value() + lenX * 0.5)

        br = br.normalized()

        if self._boundingRectCache != br:
            self._boundingRectCache = br
            self.prepareGeometryChange()

        return br
コード例 #21
0
    def __init__(self, X, z, parent=None):
        super(App, self).__init__(parent)
        self.X = X
        self.z = z
        self.idx = 0
        self.running = True
        grid_size = 1
        self.map = OccupancyGridMap(100//grid_size, 100//grid_size, grid_size)

        #### Create Gui Elements ###########
        self.mainbox = QtGui.QWidget()
        self.setCentralWidget(self.mainbox)
        self.mainbox.setLayout(QtGui.QVBoxLayout())

        self.canvas = pg.GraphicsLayoutWidget()
        self.mainbox.layout().addWidget(self.canvas)

        self.label = QtGui.QLabel()
        self.mainbox.layout().addWidget(self.label)

        self.view = self.canvas.addViewBox()
        self.view.setAspectLocked(True)
        self.view.setRange(QtCore.QRectF(0,0, 100, 100))

        #  image plot
        self.img = pg.ImageItem(border='w')
        self.turtlebot = TurtleBotItem(self.X[:,self.idx], 1.5) 
        self.view.addItem(self.img)
        self.view.addItem(self.turtlebot)


        #### Set Data  #####################

        self.counter = 0
        self.fps = 0.
        self.lastupdate = time.time()

        #### Start  #####################
        self._update()
コード例 #22
0
ファイル: Node.py プロジェクト: slac-lcls/ami
    def __init__(self, node, brush=None):
        super().__init__()

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

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

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

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

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

        self.updateTerminals()

        self.menu = None
        self.connectedTo = None
        self.enabled = QtGui.QAction("Enabled",
                                     self.menu,
                                     checkable=True,
                                     checked=True)
        self.optional = QtGui.QAction("Optional Inputs",
                                      self.menu,
                                      checkable=True,
                                      checked=False)
        self.buildMenu()
コード例 #23
0
    def __init__(self, parent=None):
        super(App, self).__init__(parent)

        #### Create Gui Elements ###########
        self.mainbox = QtGui.QWidget()
        self.setCentralWidget(self.mainbox)
        self.mainbox.setLayout(QtGui.QVBoxLayout())

        self.canvas = pg.GraphicsLayoutWidget()
        self.mainbox.layout().addWidget(self.canvas)

        self.label = QtGui.QLabel()
        self.mainbox.layout().addWidget(self.label)

        self.view = self.canvas.addViewBox()
        self.view.setAspectLocked(True)
        self.view.setRange(QtCore.QRectF(0, 0, 100, 100))

        #### Set Data  #####################
        self.idx = 10
        self.x = np.linspace(0, 50., num=100)
        self.X, self.Y = np.meshgrid(self.x, self.x)

        #  image plot
        self.img = pg.ImageItem(border='w')
        self.turtlebot = TurtleBotItem(self.X[:, self.idx], 1.5)
        self.view.addItem(self.img)
        self.view.addItem(self.turtlebot)

        self.counter = 0
        self.fps = 0.
        self.lastupdate = time.time()

        # Variables used for creating and visualizing the map
        self.grid = OccupancyGrid()
        self.data = self.grid.map * 255

        #### Start  #####################
        self._update()
コード例 #24
0
    def mouseDragEvent(self, ev):
        if ev.button() == QtCore.Qt.LeftButton:
            boundingRect = self.boundingRect()
            width = boundingRect.width()
            height = boundingRect.height()
            rect = QtCore.QRectF(width - 50, height - 50, 50, 50)

            if rect.contains(ev.pos()):
                ev.ignore()
                self.view.commentRect = self
            else:
                ev.accept()
                pos = self.pos()+self.mapToParent(ev.pos())-self.mapToParent(ev.lastPos())
                old_pos = self.pos()

                if ev.isFinish():
                    pos = clamp(pos)
                self.setPos(pos)

                diff = pos - old_pos
                for child in self.childNodes:
                    child.moveBy(*diff)
コード例 #25
0
 def writeImage(self, fileName=None):
     if fileName is None:
         self.fileDialog = FileDialog()
         if PlotItem.lastFileDir is not None:
             self.fileDialog.setDirectory(PlotItem.lastFileDir)
         self.fileDialog.setFileMode(QtGui.QFileDialog.AnyFile)
         self.fileDialog.setAcceptMode(QtGui.QFileDialog.AcceptSave) 
         self.fileDialog.show()
         self.fileDialog.fileSelected.connect(self.writeImage)
         return
     #if fileName is None:
         #fileName = QtGui.QFileDialog.getSaveFileName()
     if isinstance(fileName, tuple):
         raise Exception("Not implemented yet..")
     fileName = str(fileName)
     PlotItem.lastFileDir = os.path.dirname(fileName)
     self.png = QtGui.QImage(int(self.size().width()), int(self.size().height()), QtGui.QImage.Format_ARGB32)
     painter = QtGui.QPainter(self.png)
     painter.setRenderHints(painter.Antialiasing | painter.TextAntialiasing)
     self.scene().render(painter, QtCore.QRectF(), self.mapRectToScene(self.boundingRect()))
     painter.end()
     self.png.save(fileName)
コード例 #26
0
    def __init__(self, parent=None):
        super(App, self).__init__(parent)

        #### Create Gui Elements ###########
        self.mainbox = QtGui.QWidget()
        self.setCentralWidget(self.mainbox)
        self.mainbox.setLayout(QtGui.QVBoxLayout())

        self.canvas = pg.GraphicsLayoutWidget()
        self.mainbox.layout().addWidget(self.canvas)

        self.label = QtGui.QLabel()
        self.mainbox.layout().addWidget(self.label)

        self.view = self.canvas.addViewBox()
        self.view.setAspectLocked(True)
        self.view.setRange(QtCore.QRectF(0,0, 100, 100))

        #  image plot
        self.img = pg.ImageItem(border='w')
        self.view.addItem(self.img)

        self.canvas.nextRow()
        #  line plot
#        self.otherplot = self.canvas.addPlot()
#        self.h2 = self.otherplot.plot(pen='y')


        #### Set Data  #####################

        self.x = np.linspace(0,50., num=1000)
        self.X,self.Y = np.meshgrid(self.x,self.x)

        self.counter = 0
        self.fps = 0.
        self.lastupdate = time.time()

        #### Start  #####################
        self._update()
コード例 #27
0
ファイル: qtimefreq.py プロジェクト: Enchufa2/pyacq
 def initialize_plots(self):
     N = 512
     cmap = vispy.color.get_colormap(self.params['colormap'])
     self.lut = (255*cmap.map(np.arange(N)[:,None]/float(N))).astype('uint8')
     
     tfr_params = self.params.param('timefreq')
     for i in range(self.nb_channel):
         if self.by_channel_params.children()[i]['visible']:
             for item in self.plots[i].items:
                 # remove old images
                 self.plots[i].removeItem(item)
             
             clim = self.by_channel_params.children()[i]['clim']
             f_start, f_stop = tfr_params['f_start'], tfr_params['f_stop']
             
             image = pg.ImageItem()
             image.setImage(np.zeros((self.plot_length,self.wavelet_fourrier.shape[1])), lut=self.lut, levels=[0,clim])
             self.plots[i].addItem(image)
             image.setRect(QtCore.QRectF(-self.wanted_size, f_start,self.wanted_size, f_stop-f_start))
             self.plots[i].setXRange(-self.wanted_size, 0.)
             self.plots[i].setYRange(f_start, f_stop)
             self.images[i] =image
コード例 #28
0
 def boundingRect(self):
     (xmn, xmx) = self.dataBounds(ax=0)
     (ymn, ymx) = self.dataBounds(ax=1)
     if xmn is None or xmx is None:
         xmn = 0
         xmx = 0
     if ymn is None or ymx is None:
         ymn = 0
         ymx = 0
     
     px = py = 0.0
     pxPad = self.pixelPadding()
     if pxPad > 0:
         # determine length of pixel in local x, y directions    
         px, py = self.pixelVectors()
         px = 0 if px is None else px.length() 
         py = 0 if py is None else py.length()
         
         # return bounds expanded by pixel size
         px *= pxPad
         py *= pxPad
     return QtCore.QRectF(xmn-px, ymn-py, (2*px)+xmx-xmn, (2*py)+ymx-ymn)
コード例 #29
0
def newViewWindow(view,
                  xdim,
                  ydim,
                  left,
                  top,
                  impixpervoxx,
                  impixpervoxy,
                  imgsize,
                  enableMouse=False):
    theviewbox = view.addViewBox(enableMouse=enableMouse,
                                 enableMenu=False,
                                 lockAspect=1.0)
    theviewbox.setAspectLocked()
    theviewbox.setRange(QtCore.QRectF(0, 0, imgsize, imgsize),
                        padding=0.0,
                        disableAutoRange=True)
    theviewbox.setBackgroundColor([50, 50, 50])

    theviewfgwin = pg.ImageItem()
    theviewbox.addItem(theviewfgwin)
    theviewfgwin.setZValue(10)
    theviewfgwin.translate(left, top)
    theviewfgwin.scale(impixpervoxx, impixpervoxy)

    theviewbgwin = pg.ImageItem()
    theviewbox.addItem(theviewbgwin)
    theviewbgwin.setZValue(0)
    theviewbgwin.translate(left, top)
    theviewbgwin.scale(impixpervoxx, impixpervoxy)

    theviewvLine = pg.InfiniteLine(angle=90, movable=False, pen="g")
    theviewvLine.setZValue(20)
    theviewbox.addItem(theviewvLine)
    theviewhLine = pg.InfiniteLine(angle=0, movable=False, pen="g")
    theviewhLine.setZValue(20)
    theviewbox.addItem(theviewhLine)

    return theviewfgwin, theviewbgwin, theviewvLine, theviewhLine, theviewbox
コード例 #30
0
ファイル: LightboxItem.py プロジェクト: azlau/picachooser
def newViewWindow(view, imgxsize, imgysize, enableMouse=False):
    theviewbox = view.addViewBox(enableMouse=enableMouse, enableMenu=False)
    theviewbox.setRange(QtCore.QRectF(0, 0, imgxsize, imgysize), padding=0.0, disableAutoRange=False)
    theviewbox.setBackgroundColor([50, 50, 50])
    theviewbox.setAspectLocked()

    theviewfgposwin = pg.ImageItem()
    theviewbox.addItem(theviewfgposwin)
    theviewfgposwin.setZValue(10)

    theviewfgnegwin = pg.ImageItem()
    theviewbox.addItem(theviewfgnegwin)
    theviewfgnegwin.setZValue(5)

    theviewbgwin = pg.ImageItem()
    theviewbox.addItem(theviewbgwin)
    theviewbgwin.setZValue(0)

    thelabel = pg.TextItem(anchor=(0.0,1.0))
    theviewbox.addItem(thelabel)
    thelabel.setZValue(20)

    return theviewfgposwin, theviewfgnegwin, theviewbgwin, thelabel, theviewbox