Example #1
0
    def __init__(self, model, title = None):
        super(GraphWidget, self).__init__()

        self.timerId = 0
        
        scene = QGraphicsScene(self)
        scene.setItemIndexMethod(QtGui.QGraphicsScene.NoIndex)
        scene.setSceneRect(-200, -200, 640, 400)
        self.gscene = scene;
        self.setScene(scene)
        self.setCacheMode(QtGui.QGraphicsView.CacheBackground)
        self.setViewportUpdateMode(QtGui.QGraphicsView.BoundingRectViewportUpdate)
        self.setRenderHint(QtGui.QPainter.Antialiasing)
        self.setTransformationAnchor(QtGui.QGraphicsView.AnchorUnderMouse)
        self.setResizeAnchor(QtGui.QGraphicsView.AnchorViewCenter)
        self.model = model;
        self.whitebrush = QBrush(Qt.white);
        self.redbrush = QBrush(Qt.red)
        self.drawNetwork(self.gscene, self.model);
        
        #setttings of the window
        self.scale(1.2,1.2);
        self.setMinimumSize(640, 480);
        
        
        if title == None:
            self.setWindowTitle("Network Visualisation");
        else:
            self.setWindowTitle("Network Visualisation -" + title);
Example #2
0
    def __init__(self, tileSource, parent=None):
        """Constructor.

        Args:
            tileSource(MapTileSource): Source for loading the tiles.
            parent(QObject): Parent object, default `None`
        """
        QGraphicsScene.__init__(self)

        self._zoom = 15

        self._tileSource = tileSource
        self._tileSource.setParent(self)
        self._tileSource.tileReceived.connect(self.setTilePixmap)
        tdim = self._tileSource.tileSize()

        self._emptyTile = QPixmap(tdim, tdim)
        self._emptyTile.fill(Qt.lightGray)

        self._tilesRect = QRect()
        self._tilePixmaps = {}

        self._tileInDownload = list()

        self.setSceneRect(0.0, 0.0, 400, 300)
        self.sceneRectChanged.connect(self.onSceneRectChanged)
Example #3
0
class MainWindow(QMainWindow):

    def __init__(self):

        super(MainWindow, self).__init__()

        self.scene = QGraphicsScene()

        # Scene is the parent of the view in order to show the graphical items.
        # the View must also be the parent of the scene in order to avoid
        # bizarre segmentation faults with GTK
        self.view = InteractiveView(self.scene)
        self.scene.setParent(self.view)

        self.setCentralWidget(self.view)
        self.view.setSceneRect(INT_MIN/2, INT_MIN/2, INT_MAX, INT_MAX)
        self.view.centerOn(0, 0)

        self.visualizer = Visualizer(self.scene)
        self.visualizer.update_processes_data()

        # Set a dark background color
        back_color = QColor(25, 20, 45)
        self.view.setBackgroundBrush(QBrush(back_color))

    def keyPressEvent(self, event):
        super(MainWindow, self).keyPressEvent(event)

        # Quit via escape key.
        if event.key() == Qt.Key_Escape:
            self.close()

        if event.key() == Qt.Key_R:
            self.visualizer.showRootTasks = not self.visualizer.showRootTasks
class StartSelectView(QGraphicsView):

    def __init__(self, *args):
        QGraphicsView.__init__(self, *args)
        self.move(2, 250)
        self.btnSize = 28
        self.setMaximumHeight(self.btnSize * 2)
        self.setMaximumWidth(334)
        self.setMinimumHeight(self.btnSize * 2)
        self.setMinimumWidth(334)
        self.adjustSize()
        self.scene = QGraphicsScene(self)
        self.setStyleSheet('background-color:transparent; border-width: 0px; border: 0px;')
        self.psButtons = QPixmap(os.getcwd() + '/../icons/controller-sprite.png')
        self.select = self.psButtons.copy(696, 120, 45, 30)
        self.select = self.select.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio)
        self.selectItem = QGraphicsPixmapItem(self.select)
        self.selectItem.setOffset(QPointF(0, 0))
        self.scene.addItem(self.selectItem)
        self.start = self.psButtons.copy(754, 120, 45, 30)
        self.start = self.start.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio)
        self.startItem = QGraphicsPixmapItem(self.start)
        self.startItem.setOffset(QPointF(86, 0))
        self.scene.addItem(self.startItem)
        self.setScene(self.scene)
Example #5
0
class Ventana(Ui_MainWindow, QMainWindow):
    
    def __init__(self):
        QMainWindow.__init__(self)
        self.setupUi(self)        
        self.actionOpenImgA.triggered.connect(self.cargarImgA)
        self.actionOpenImgB.triggered.connect(self.cargarImgB)
        self.actionOperate.triggered.connect(self.operar)
        
        self.escenaA = QGraphicsScene()
        self.imgA.setScene(self.escenaA)
        
        self.escenaB = QGraphicsScene()
        self.imgB.setScene(self.escenaB)
        
        self.escenaC = QGraphicsScene()
        self.imgC.setScene(self.escenaC)
        
        self.operacion.addItem("suma")
        self.operacion.addItem("multiplicacion")
        self.operacion.addItem("promedio")
    
    def cargarImgA(self):
        self.imagenA = self.cargarImg(self.escenaA)
        
    def cargarImgB(self):
        self.imagenB = self.cargarImg(self.escenaB)
    
    def cargarImg(self, escena):
        ruta =QFileDialog.getOpenFileName(parent=self, caption="Archivo")
        imagen = QImage()
        imagen.load(ruta)
        pixmap = QPixmap(imagen)
        escena.addItem(QGraphicsPixmapItem(pixmap))
        return imagen

    def operar(self):
        ancho = min(self.imagenA.width(), self.imagenB.width())
        alto  = min(self.imagenA.height(), self.imagenB.height())
        
        oper = getattr(self,str(self.operacion.currentText()))
        
        self.imagenC = QImage(ancho, alto, QImage.Format_RGB32 )
        
        for i in range(ancho):
            for j in range(alto):
                pix = oper(self.imagenA.pixel(i,j), self.imagenB.pixel(i,j))
                self.imagenC.setPixel(i, j, pix)
        
        pixmap = QPixmap(self.imagenC)
        self.escenaC.addItem(QGraphicsPixmapItem(pixmap))
        
    def suma(self, pixA, pixB):
        return pixA + pixB
    
    def multiplicacion(self, pixA, pixB):
        return pixA * pixB
    
    def promedio(self, pixA, pixB):
        return (pixA + pixB) / 2
Example #6
0
 def drawStationName(self):
     """Draw station name snippet to station_name_img"""
     res = self.current_result
     name = res.station.name
     #self.station_name.setText('')
     #self.station_name.clear()
     #self.station_name.addItems(name.optional_values)
     if not self.file_list.currentItem().station is None:
             self.station_name.setText(self.file_list.currentItem().station)
     else:
         self.station_name.setText(name.value)
     #font = QFont("Consolas", 11)
     #self.station_name.lineEdit().setFont(font)
     #self.setConfidenceColor(self.station_name, name)
     img = self.cutImage(res.contrast_station_img, name)
     if self.dark_theme: 
         img = 255 - img
     processedimage = array2qimage(img)
     pix = QPixmap()
     pix.convertFromImage(processedimage)
     if self.station_name_img.height() < pix.height():
         pix = pix.scaled(self.station_name_img.size(),
                          Qt.KeepAspectRatio,
                          Qt.SmoothTransformation)
     scene = QGraphicsScene()
     scene.addPixmap(pix)
     
     self.station_name_img.setScene(scene)
     self.station_name_img.show()
Example #7
0
 def tick_DC(self, u, i):
     self.datau.pop(0)
     self.datai.pop(0)
     self.datau.append(u)
     self.datai.append(i)
     self.scene1 = QGraphicsScene()
     self.scene2 = QGraphicsScene()
     self.setup_scene(self.scene1)
     self.setup_scene(self.scene2)
     self.scene1.addSimpleText('[U/V]').moveBy(-39, 220-10)
     self.scene2.addSimpleText('[I/mA]').moveBy(-39, 220-10)
     self.scene1.addSimpleText('+4.0').moveBy(-40,   0-10)
     self.scene1.addSimpleText('+2.0').moveBy(-40,  50-10)
     self.scene1.addSimpleText('  0.0').moveBy(-40, 100-10)
     self.scene1.addSimpleText('-2.0').moveBy(-40, 150-10)
     self.scene1.addSimpleText('-4.0').moveBy(-40, 200-10)
     self.scene2.addSimpleText('+0.4').moveBy(-40,   0-10)
     self.scene2.addSimpleText('+0.2').moveBy(-40,  50-10)
     self.scene2.addSimpleText('  0.0').moveBy(-40, 100-10)
     self.scene2.addSimpleText('-0.2').moveBy(-40, 150-10)
     self.scene2.addSimpleText('-0.4').moveBy(-40, 200-10)
     path = QPainterPath()
     path.moveTo(0,100-self.datau[0]*25)
     for i in xrange(1,200):
         path.lineTo(3*(i+1), 100-self.datau[i]*25)
     self.scene1.addPath(path, QPen(QColor(0,0,255), 3))
     path = QPainterPath()
     path.moveTo(0,100-self.datai[0]*25)
     for i in xrange(1,200):
         path.lineTo(3*(i+1), 100-self.datai[i]*25)
     self.scene2.addPath(path, QPen(QColor(0,0,255), 3))
     self.ui.graph1.setScene(self.scene1)
     self.ui.graph2.setScene(self.scene2)
    def test_editlinksnode(self):
        from ...registry.tests import small_testing_registry

        reg = small_testing_registry()
        file_desc = reg.widget("Orange.OrangeWidgets.Data.OWFile.OWFile")
        bayes_desc = reg.widget("Orange.OrangeWidgets.Classify.OWNaiveBayes."
                                "OWNaiveBayes")
        source_node = SchemeNode(file_desc, title="This is File")
        sink_node = SchemeNode(bayes_desc)

        scene = QGraphicsScene()
        view = QGraphicsView(scene)

        node = EditLinksNode(node=source_node)
        scene.addItem(node)

        node = EditLinksNode(direction=Qt.RightToLeft)
        node.setSchemeNode(sink_node)

        node.setPos(300, 0)
        scene.addItem(node)

        view.show()
        view.resize(800, 300)
        self.app.exec_()
Example #9
0
 def mouseMoveEvent(self, event):
     if event.buttons() & Qt.LeftButton:
         screenPos = event.screenPos()
         buttonDown = event.buttonDownScreenPos(Qt.LeftButton)
         if (screenPos - buttonDown).manhattanLength() > 2.0:
             self.updateSelectionRect(event)
     QGraphicsScene.mouseMoveEvent(self, event)
Example #10
0
    def Paint(self):
        scene = QGraphicsScene()

        # Draw the graph
        tt = self.ui.graphtype.currentIndex()
        if tt == 0:
            points = self.avgSpeed
        elif tt == 1:
            points = self.avgVolume
        elif tt == 2:
            points = self.avgCapacity
        elif tt == 3:
            points = self.avgRam
        p0 = points[0]
        for p in points[1:]:
            scene.addLine(5 + p0[0] * 2, 205 - p0[1] * 2, 5 + p[0] * 2, 205 - p[1] * 2, QPen(self.settings["graph"]))
            p0 = p

        # Draw the axis
        scene.addLine(5, 5, 5, 208, QPen(self.settings["axis"]))
        scene.addLine(2, 205, self.time * 2 + 5, 205, QPen(self.settings["axis"]))
        t = 0
        while t <= self.time:
            scene.addLine(5 + t * 2, 206, 5 + t * 2, 204, QPen(self.settings["axis"]))
            font = QFont()
            font.setPointSize(6)       
            capt = scene.addText(str(t), font)
            capt.setPos(t * 2, 203)
            t += 10
        self.ui.graph.setScene(scene)
Example #11
0
    def search(self):
        # first set/change the  font of the serach box
        font = self.dlg.search_lineEdit.font()
        font.setItalic(False)
        self.dlg.search_lineEdit.setFont(font)

        # clear description and quicklook
        self.dlg.textEdit.clear()

        # make a new emptey scene to show
        if not self.dlg.graphicsView is None:
            scene = QGraphicsScene()
            pic = QPixmap()
            scene.addItem(QGraphicsPixmapItem(pic))
            self.dlg.graphicsView.setScene(scene)
            self.dlg.graphicsView.show()

        # function the searches for a string in the datasets name, service type and otganization
        text = self.dlg.search_lineEdit.text()
        # convert to lower case and remove greek accents in case of Greek
        text = text.lower()
        text = self.removeGreekAccents(text)
        foundDatasets = []
        for dataset in self.datasets:
            # use lowercase characters and remove greek accents , to make the comparison
            name = self.removeGreekAccents(dataset.getName(self.language).lower())
            source = self.removeGreekAccents(dataset.getSource(self.language).lower())
            serviceType = self.removeGreekAccents(dataset.serviceType.lower())

            if text in name or text in source or text in serviceType:
            #QMessageBox.information(None, "DEBUG:", str(type(dataset.getName(self.language))))
                foundDatasets.append(dataset)
        #fill the table with the found datasets
        self.fill_table(foundDatasets)
Example #12
0
class Video(QWidget):
    def __init__(self):
        # init the widget
        QWidget.__init__(self)

        # set up the scene
        self.scene=QGraphicsScene()
        self.scene.setSceneRect(0,0,800,600)

        # add a view of that scene
        self.view = QGraphicsView()
        self.view.setScene(self.scene)
        self.view.setRenderHint(QPainter.Antialiasing)
        self.view.setFixedSize(800,600)
        self.view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

        # set the screen sync
        val = "1"
        # Set for nVidia linux
        os.environ["__GL_SYNC_TO_VBLANK"] = val
        # Set for recent linux Mesa DRI Radeon
        os.environ["LIBGL_SYNC_REFRESH"] = val

        qglf = QGLFormat()
        qglf.setSampleBuffers(True)
        #qglf.setSwapInterval(1)
        self.glw = QGLWidget(qglf)
        self.glw.setAutoBufferSwap(False)
        self.view.setViewport(self.glw)
        
        QTimer.singleShot(0,self.glw.swapBuffers)

    def swapBuffers(self):
        # first call the swap on the QGLWidget
        self.glw.swapBuffers()

        self.glw.makeCurrent()

        # The following is taken from the PsychToolbox
        # Draw a single pixel in left-top area of back-buffer. 
        # This will wait/stall the rendering pipeline
        # until the buffer flip has happened, aka immediately after the VBL has started.
        # We need the pixel as "synchronization token", so the following glFinish() really
        # waits for VBL instead of just "falling through" due to the asynchronous nature of
        # OpenGL:
        glDrawBuffer(GL_BACK)
        # We draw our single pixel with an alpha-value of zero - so effectively it doesn't
        # change the color buffer - just the z-buffer if z-writes are enabled...
        glColor4f(0.0,0.0,0.0,0.0)
        glBegin(GL_POINTS)
        glVertex2i(10,10)
        glEnd()
        # This glFinish() will wait until point drawing is finished, ergo backbuffer was ready
        # for drawing, ergo buffer swap in sync with start of VBL has happened.
        glFinish()

    def show(self):
        # shows the viewer widget
        self.view.show()
Example #13
0
 def setPreviewImage(self, image):
     """Show image in self.preview."""
     factor = self.factor.value()
     pix = image.scaled(QSize(self.preview.size().width()*factor,self.preview.size().height()*factor), Qt.KeepAspectRatio, Qt.SmoothTransformation)
     scene = QGraphicsScene()
     scene.addPixmap(pix)
     self.previewSetScene(scene)
Example #14
0
class LiteBoxView(QGraphicsView):

    ALPHA = QColor(0, 0, 0, 192)

    closed_signal = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super(LiteBoxView, self).__init__(parent)
        self.setWindowFlags(Qt.Window | Qt.WindowStaysOnTopHint)
        #self.setAttribute(Qt.WA_DeleteOnClose)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setViewportUpdateMode(QGraphicsView.FullViewportUpdate)
        QtGui.QShortcut( Qt.Key_Escape, self, self.close )
        self.desktopshot = None

        # will propagate to children
        self.setRenderHint(QPainter.Antialiasing)
        self.setRenderHint(QPainter.TextAntialiasing)

        self.scene = QGraphicsScene()
        self.setScene(self.scene)

    def close(self):
        self.closed_signal.emit()
        super(LiteBoxView, self).close()

    def drawBackground(self, painter, rect):
        if self.desktopshot is None:
            self.desktopshot = get_desktop_pixmap()

        painter.drawPixmap(self.mapToScene(0, 0), self.desktopshot)
        painter.setBrush(LiteBoxView.ALPHA)
        painter.drawRect(rect)

    def show_fullscreen_svg(self, path):
        """:param path: path to an svg file"""
        from PyQt4 import QtSvg
        item = QtSvg.QGraphicsSvgItem(path)
        self.show_fullscreen_item(item)

    def show_fullscreen_pixmap(self, pixmap):
        """:param pixmap: a QPixmap"""
        item = QGraphicsPixmapItem(pixmap)
        self.show_fullscreen_item(item)
        
    def show_fullscreen_image(self, image):
        """:param image: a QImage"""
        pixmap = QPixmap.fromImage(image)
        self.show_fullscreen_pixmap( pixmap )

    def show_fullscreen_item(self, item):
        """:param item: a QGraphicsItem to be shown fullscreen"""
        item.setFlag(QtGui.QGraphicsItem.ItemIsFocusable, True)
        self.scene.clear()
        self.scene.addItem(item)
        CloseMark(parent=item)
        self.showFullScreen()
        self.setFocus()
Example #15
0
    def mouseReleaseEvent(self, mouseEvent):

        if mouseEvent.button() == Qt.RightButton:
            self.__kDummy.toggleEditMode()

        self.update()

        QGraphicsScene.mouseReleaseEvent(self, mouseEvent)
Example #16
0
    def mousePressEvent(self, mouseEvent):
        QGraphicsScene.mousePressEvent(self, mouseEvent)

        if self.__isControlModifier:
            return

        if mouseEvent.button() == Qt.RightButton:
            self.__kDummy.toggleEditMode()
Example #17
0
 def __init__( self, navBar, parent = None ):
     QGraphicsScene.__init__( self, parent )
     CFSceneContextMenuMixin.__init__( self )
     CFSceneMouseMixin.__init__( self )
     CFSceneKeyboardMixin.__init__( self )
     self.__navBar = navBar
     self.selectionChanged.connect( self.selChanged )
     return
Example #18
0
    def __init__(self, view=None, parent=None):
        QGraphicsScene.__init__(self, parent)

        if view is None:
            raise AttributeError

        self.__view = view
        self.__create__()
Example #19
0
class MyWidget(QGraphicsView):
    def __init__(self):
        super(MyWidget, self).__init__()
        self.setFixedSize(300, 300)
        self.setSceneRect(0, 0, 250, 250)
        self.scene = QGraphicsScene()
        self.setScene(self.scene)
        self.scene.addItem(MyArrow())
Example #20
0
    def addItem(self, QGraphicsItem):

        if self.__isNode(QGraphicsItem):
            QGraphicsItem.setZValue(1.0)
            QGraphicsItem.onPress.connect(self.__onNodePressed)

            self.__nodes[QGraphicsItem.Id] = QGraphicsItem

        QGraphicsScene.addItem(self, QGraphicsItem)
Example #21
0
    def __init__(self, parent=None):
        """Constructor

        Args:
            parent(QObject): Parent object, default None
        """
        QGraphicsScene.__init__(self, parent=parent)

        self._draggedLineItem = None
Example #22
0
 def drawSnippet(self, graphicsview, snippet):
     """Draw single result item to graphicsview"""
     processedimage = array2qimage(snippet)
     pix = QPixmap()
     pix.convertFromImage(processedimage)
     pix = pix.scaled(graphicsview.width(), graphicsview.height()-1, Qt.KeepAspectRatio, Qt.SmoothTransformation)
     scene = QGraphicsScene()
     scene.addPixmap(pix)
     graphicsview.setScene(scene)
     graphicsview.show()
Example #23
0
 def __init__(self, initial_width, initial_height, visible_meters, length, mass):
     QGraphicsScene.__init__(self)
     self.visible_meters = visible_meters
     self.initial_width = initial_width
     self.initial_height = initial_height
     self.pend_radius = min(0.5 * mass, 0.2)
     self.pole_length = length
     self.unit = min(self.initial_width, self.initial_height) / self.visible_meters
     self.__create_scene()
     self.update_state(0.0, 0.0)
Example #24
0
    def mouseMoveEvent(self, mouseEvent):
        """Manage the mouse movement while it is pressed.

        Args:
            event(QMouseEvent): Mouse event.
        """
        QGraphicsScene.mouseMoveEvent(self, mouseEvent)
        if not mouseEvent.isAccepted() and mouseEvent.buttons() == Qt.LeftButton:
            delta = mouseEvent.lastScreenPos() - mouseEvent.screenPos()
            self.translate(delta.x(), delta.y())
Example #25
0
 def loadFileFromFile(self,path):
     global image
     
     image = QImage(path) 
     
     scene = QGraphicsScene()
     scene.addPixmap(QPixmap(path))
     
     self.graphicsView.setScene(scene)
     print 'loading ' + path
Example #26
0
    def test(self):
        if not self.winManager:
            return
        from PyQt4.QtGui import QGraphicsScene, QGraphicsItem, QGraphicsLineItem
        from PyQt4.QtCore import QRectF, QLineF
        w = self.winManager.newWindow()
        scene = QGraphicsScene(w.graphicsView)
        scene.addItem(Items.Grid())
        scene.addItem(Items.Axes())

        line = scene.addLine(QLineF(0, 0, 0, 0))

        cross = Items.NodeCross(movable=True)
        cross.addEdge(line, 1)
        scene.addItem(cross)

        help = scene.addText(QCoreApplication.translate('Graphics', 'Press "h" for help!'))
        help.moveBy(-50, 80)

        text = Items.NodeText(QCoreApplication.translate('Graphics', 'Drag Me!'))
        text.setFlag(QGraphicsItem.ItemIsMovable, True)
        text.setFlag(QGraphicsItem.ItemIsSelectable, True)
        text.addEdge(line, 2)
        scene.addItem(text)
        w.graphicsView.setScene(scene)
Example #27
0
    def __init__(self, parent=None, back_image=None, width=100, heigth=100):
        super(ToastWidget, self).__init__(parent)
        self.setWindowFlags(Qt.SplashScreen)
        self.scene = QGraphicsScene(self)

        self.timer = QTimer(self)

        self.setScene(self.scene)
        self.set_image(back_image)
        self.setGeometry(QRect(self.x(), self.y(), width, heigth))
        self.show()
Example #28
0
 def drawPoints(self):
     img = qrcode.make('TestCode 001',image_factory=qrcode.image.svg.SvgImage )
     type(img)
     gitem =  QGraphicsScene()
     self.graphicsView.setScene(gitem)
     #gitem.addLine(0, 0, 2, 2)
     qbrush = QBrush()
     qbrush.setStyle(Qt.SolidPattern)
     qbrush.setColor(Qt.black)
     gitem.addRect(0, 0, 2, 2, brush=qbrush )
     self.graphicsView.show()
Example #29
0
 def __init__(self):
     QGraphicsScene.__init__(self)
     self.__disableFocusRect = False
     self._focusBoard = None
     self.focusRect = QGraphicsRectItem()
     pen = QPen(QColor(Qt.blue))
     pen.setWidth(6)
     self.focusRect.setPen(pen)
     self.addItem(self.focusRect)
     self.focusRect.setZValue(ZValues.marker)
     self.focusRect.hide()
Example #30
0
    def test_graphicstextwidget(self):
        scene = QGraphicsScene()
        view = QGraphicsView(scene)

        text = GraphicsTextWidget()
        text.setHtml("<center><b>a text</b></center><p>paragraph</p>")
        scene.addItem(text)
        view.show()
        view.resize(400, 300)

        self.app.exec_()
Example #31
0
    def keyPressEvent(self, event):
        """ Handles the key press event """
        key = event.key()
        modifiers = int(event.modifiers())
        if modifiers in self.__hotKeys:
            if key in self.__hotKeys[modifiers]:
                self.__hotKeys[modifiers][key]()
                event.accept()
                return

        QGraphicsScene.keyPressEvent(self, event)
        return
Example #32
0
 def __init__(self, undo_stack, delete_act, sel_actions, *args):
     """
     Constructor
     """
     params = parameters.instance
     QGraphicsScene.__init__(self, *args)
     self.delete_act = delete_act
     self.undo_stack = undo_stack
     self.data_manager = None
     self._mode = None
     self.link = None
     self.image_path = None
     self.image_name = None
     self.background_image = None
     self.template = TemplateItem()
     self.template.setPos(QPointF(0, 0))
     self.template.setVisible(params.show_template)
     self.show_template = False
     self.points = {}
     self.cells = {}
     self._real_scene_rect = QRectF()
     params.pointParameterChange.connect(self.updatePoints)
     params.cellParameterChange.connect(self.updateCells)
     params.searchParameterChange.connect(self.updateTemplate)
     self.had_selection = None
     self.selectionChanged.connect(self.updateSelectionActions)
     self.current_data = None
     self.back_matrix = QTransform()
     self.invert_back_matrix = QTransform()
     self.clear()
     popup = QMenu("Scene menu")
     validate_cell_act = popup.addAction("Validate cell", self.validateCell)
     validate_cell_act.setVisible(False)
     self._validate_cell_act = validate_cell_act
     lifespan_act = popup.addAction("Change cell lifespan", self.changeLifespan)
     lifespan_act.setVisible(False)
     self.lifespan_act = lifespan_act
     make_starshape_act = popup.addAction("Make cell star shaped", self.makeCellStarshaped)
     make_starshape_act.setVisible(False)
     self.make_starshape_act = make_starshape_act
     sel = popup.addMenu("Selection")
     for act in sel_actions:
         if act == "-":
             sel.addSeparator()
         else:
             sel.addAction(act)
     popup.addAction(delete_act)
     self._popup = popup
     self._sel_rect = None
     self._sel_first_pt = None
     self._current_cell = None
     self._first_point = None
     self.mode = TrackingScene.Pan
Example #33
0
    def keyPressEvent(self, event):
        """ Handles the key press event """
        key = event.key()
        modifiers = int(event.modifiers())
        if modifiers in self.__hotKeys:
            if key in self.__hotKeys[modifiers]:
                self.__hotKeys[modifiers][key]()
                event.accept()
                return

        QGraphicsScene.keyPressEvent(self, event)
        return
Example #34
0
 def __init__(self, initial_width, initial_height, visible_meters, length,
              mass):
     QGraphicsScene.__init__(self)
     self.visible_meters = visible_meters
     self.initial_width = initial_width
     self.initial_height = initial_height
     self.pend_radius = min(0.5 * mass, 0.2)
     self.pole_length = length
     self.unit = min(self.initial_width,
                     self.initial_height) / self.visible_meters
     self.__create_scene()
     self.update_state(0.0, 0.0)
Example #35
0
    def __init__(self,
                 posModel,
                 along,
                 preemptive_fetch_number=5,
                 parent=None,
                 name="Unnamed Scene",
                 swapped_default=False):
        """
        * preemptive_fetch_number -- number of prefetched slices; 0 turns the feature off
        * swapped_default -- whether axes should be swapped by default.

        """
        QGraphicsScene.__init__(self, parent=parent)

        self._along = along
        self._posModel = posModel

        # QGraphicsItems can change this if they are in a state that should temporarily forbid brushing
        # (For example, when the slice intersection marker is in 'draggable' state.)
        self.allow_brushing = True

        self._dataShape = (0, 0)
        self._dataRect = None  #A QGraphicsRectItem (or None)
        self._offsetX = 0
        self._offsetY = 0
        self.name = name

        self._stackedImageSources = StackedImageSources(LayerStackModel())
        self._showTileOutlines = False

        # FIXME: We don't show the red 'progress pies' because they look terrible.
        #        If we could fix their timing, maybe it would be worth it.
        self._showTileProgress = False

        self._tileProvider = None
        self._dirtyIndicator = None
        self._prefetching_enabled = False

        self._swappedDefault = swapped_default
        self.reset()

        # BowWave preemptive caching
        self.setPreemptiveFetchNumber(preemptive_fetch_number)
        self._course = (1, 1)  # (along, pos or neg direction)
        self._time = self._posModel.time
        self._channel = self._posModel.channel
        self._posModel.timeChanged.connect(self._onTimeChanged)
        self._posModel.channelChanged.connect(self._onChannelChanged)
        self._posModel.slicingPositionChanged.connect(
            self._onSlicingPositionChanged)

        self._allTilesCompleteEvent = threading.Event()
        self.dirty = False
Example #36
0
    def keyPressEvent(self, keyEvent):
        QGraphicsScene.keyPressEvent(self, keyEvent)

        if keyEvent.key() == Qt.Key_Control:
            self.__view.setDragMode(QGraphicsView.ScrollHandDrag)
            self.__isControlModifier = True

        if keyEvent.key() == Qt.Key_Alt:
            self.__isAltModifier = True
            self.__previousSelectedNode = None

        if keyEvent.key() == 88:
            self.__kDummy.setSnapMode(True)
Example #37
0
    def keyReleaseEvent(self, keyEvent):
        QGraphicsScene.keyReleaseEvent(self, keyEvent)

        if keyEvent.key() == Qt.Key_Control:
            self.__view.setDragMode(QGraphicsView.NoDrag)
            self.__isControlModifier = False

        if keyEvent.key() == Qt.Key_Alt:
            self.__isAltModifier = False
            self.__previousSelectedNode = None

        if keyEvent.key() == 88:
            self.__kDummy.setSnapMode(False)
Example #38
0
 def focusInEvent(self, event):
     """work around a qt bug. See https://bugreports.qt-project.org/browse/QTBUG-32890
     This can be reproduced as follows:
        ./kajongg.py --game=whatever --autoplay=SomeRuleset
            such that the human player is the first one to discard a tile.
        wait until the main screen has been built
        click with the mouse into the middle of that window
        press left arrow key
        this will violate the assertion in GraphicsTileItem.keyPressEvent """
     prev = self.focusItem()
     QGraphicsScene.focusInEvent(self, event)
     if prev and bool(prev.flags() & QGraphicsItem.ItemIsFocusable) and prev != self.focusItem():
         self.setFocusItem(prev)
Example #39
0
	def __init__ (self):
		QMainWindow.__init__ (self)

		self.controller = Controller ()
		self.listener = LeapListener (self)
		self.controller.add_listener (self.listener)

		self.mode = "gallery"
		self.scroll = False
		self.direction = ""
		self.direction_x = 0
		self.scroll_velocity = 0
		self.current_index = 0

		# List containing images for the gallery
		self.list_view = QListWidget ()
		self.list_view.setFlow (0)
		self.list_view.setHorizontalScrollMode (1)
		self.list_view.setMouseTracking (True)
		self.list_view.itemClicked.connect (self.show_image)

		# Setting the style of the ListView, background, item selected, etc
		self.list_view.setStyleSheet ("""
				QListWidget::item:hover {background: transparent;}
				QListWidget::item:disabled:hover {background: transparent;}
				QListWidget::item:hover:!active {background: transparent;}
				QListWidget::item:selected:active {background: transparent;}
	            QListWidget::item:selected:!active {background: transparent;}
	            QListWidget::item:selected:disabled {background: transparent;}
	            QListWidget::item:selected:!disabled {background: transparent;}
	            QListWidget {background: #2C3539}
			""")

		# Image viewer
		self.scene = QGraphicsScene ()
		self.viewer = QGraphicsView (self.scene)

		self.stackedWidget = QStackedWidget ()
		self.stackedWidget.addWidget (self.list_view)
		self.stackedWidget.addWidget (self.viewer)

		self.setCentralWidget (self.stackedWidget)
		self.resize (500, 400)
		self.showMaximized ()

		scan = ScanLibrary ("/home/chris/Example")
		threads.append (scan)
		self.connect (scan, SIGNAL (scan.signal), self.add_images_to_list)
		scan.start ()

		self.connect (self, SIGNAL ("scrollChanged(bool)"), self.scroll_view)
Example #40
0
    def __init__(self, selfwindow):
        QGraphicsView.__init__(self)

        self.selfwindow = selfwindow
        self.panSelect = False
        self.zoomSelect = False

        self.zoom_data = []
        self.scene = QGraphicsScene()
        self.setScene(self.scene)
        self.setMouseTracking(False)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setDragMode(QGraphicsView.NoDrag)
Example #41
0
 def __init__(self, logger, opts):
     QGraphicsScene.__init__(self)
     self.logger, self.opts = logger, opts
     self.pages = []
     self.chapters = []
     self.chapter_layout = None
     self.current_screen = None
     self.current_page = 0
     self.link_map = {}
     self.chapter_map = {}
     self.history = History()
     self.last_search = iter([])
     if not opts.white_background:
         self.setBackgroundBrush(QBrush(QColor(0xee, 0xee, 0xee)))
Example #42
0
    def drawOCRPreview(self):
        if self.current_result is None:
            self.setPreviewImage(self.preview_image)
            return
        factor = self.factor.value()
        res = self.current_result
        name = res.station
        img = self.preview_image
        
        old_h = img.height()
        old_w = img.width()
        
        pix = img.scaled(QSize(self.preview.size().width()*factor,self.preview.size().height()*factor), Qt.KeepAspectRatio, Qt.SmoothTransformation)
        #pix = img.scaled(self.preview.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)
        
        new_h = pix.height()
        new_w = pix.width()
        
        ratio_h = old_h/float(new_h)
        ratio_w = old_w/float(new_w)
        
        self.scene = QGraphicsScene()
        self.scene.addPixmap(pix)
        #self.scene.addPixmap(img)
        
        self.previewRects = []

        pen = QPen(Qt.yellow)
        redpen = QPen(Qt.red)
        bluepen = QPen(Qt.blue)
        greenpen = QPen(Qt.green)
        
        rect = self.addRect(self.scene, name, ratio_w, ratio_h, greenpen)
        
        counter = 0
        for line in res.commodities:
            if counter < self.OCRline:
                rect = self.addRect(self.scene, line, ratio_w, ratio_h, greenpen)
            elif counter == self.OCRline:
                rect = self.addRect(self.scene, line, ratio_w, ratio_h, bluepen)
            else:
                if line.w < (0.02*old_w):
                    rect = self.addRect(self.scene, line, ratio_w, ratio_h, redpen)
                else:
                    rect = self.addRect(self.scene, line, ratio_w, ratio_h, pen)
            
            counter += 1
            self.previewRects.append(rect)
            
        self.previewSetScene(self.scene)
Example #43
0
 def drawSnippet(self, graphicsview, item):
     """Draw single result item to graphicsview"""
     res = self.current_result
     snippet = self.cutImage(res.contrast_commodities_img, item)
     #cv2.imwrite('snippets/'+unicode(self.currentsnippet)+'.png',snippet)
     #self.currentsnippet += 1
     processedimage = array2qimage(snippet)
     pix = QPixmap()
     pix.convertFromImage(processedimage)
     if graphicsview.height() < pix.height():
         pix = pix.scaled(graphicsview.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)
     scene = QGraphicsScene()
     scene.addPixmap(pix)
     graphicsview.setScene(scene)
     graphicsview.show()
Example #44
0
    def __init__(self):
        super().__init__()

        self.data = None
        self.input_features = None
        self.attrs = []

        self.attr_box = gui.hBox(self.mainArea)
        model = VariableListModel()
        model.wrap(self.attrs)
        self.attrXCombo = gui.comboBox(self.attr_box,
                                       self,
                                       value="attrX",
                                       contentsLength=12,
                                       callback=self.change_attr,
                                       sendSelectedValue=True,
                                       valueType=str)
        self.attrXCombo.setModel(model)
        gui.widgetLabel(self.attr_box, "\u2715").\
            setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.attrYCombo = gui.comboBox(self.attr_box,
                                       self,
                                       value="attrY",
                                       contentsLength=12,
                                       callback=self.change_attr,
                                       sendSelectedValue=True,
                                       valueType=str)
        self.attrYCombo.setModel(model)

        self.canvas = QGraphicsScene()
        self.canvasView = ViewWithPress(self.canvas,
                                        self.mainArea,
                                        handler=self.reset_selection)
        self.mainArea.layout().addWidget(self.canvasView)
        self.canvasView.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.canvasView.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

        box = gui.hBox(self.mainArea)
        gui.button(box,
                   None,
                   "&Save Graph",
                   callback=self.save_graph,
                   autoDefault=False)
        gui.button(box,
                   None,
                   "&Report",
                   callback=self.show_report,
                   autoDefault=False)
Example #45
0
    def __init__(self, *args, **kwargs):
        QGraphicsScene.__init__(self, *args, **kwargs)

        self.scheme = None
        self.registry = None

        # All node items
        self.__node_items = []
        # Mapping from SchemeNodes to canvas items
        self.__item_for_node = {}
        # All link items
        self.__link_items = []
        # Mapping from SchemeLinks to canvas items.
        self.__item_for_link = {}

        # All annotation items
        self.__annotation_items = []
        # Mapping from SchemeAnnotations to canvas items.
        self.__item_for_annotation = {}

        # Is the scene editable
        self.editable = True

        # Anchor Layout
        self.__anchor_layout = AnchorLayout()
        self.addItem(self.__anchor_layout)

        self.__channel_names_visible = True
        self.__node_animation_enabled = True

        self.user_interaction_handler = None

        self.activated_mapper = NodeItemSignalMapper(self)
        self.activated_mapper.pyMapped.connect(
            self.node_item_activated
        )

        self.hovered_mapper = NodeItemSignalMapper(self)
        self.hovered_mapper.pyMapped.connect(
            self.node_item_hovered
        )

        self.position_change_mapper = NodeItemSignalMapper(self)
        self.position_change_mapper.pyMapped.connect(
            self._on_position_change
        )

        log.info("'%s' intitialized." % self)
Example #46
0
    def event(self, event):
        # TODO: change the base class of Node/LinkItem to QGraphicsWidget.
        # It already handles font changes.
        if event.type() == QEvent.FontChange:
            self.__update_font()

        return QGraphicsScene.event(self, event)
Example #47
0
    def __init__( self, what, options, path = "", buf = "", parent = None ):
        QDialog.__init__( self, parent )
        self.__cancelRequest = False
        self.__inProgress = False

        self.__what = what
        self.__options = options
        self.__path = path          # could be a dir or a file
        self.__buf = buf            # content in case of a modified file

        # Working process data
        self.__participantFiles = []    # Collected list of files
        self.__projectImportDirs = []
        self.__projectImportsCache = {} # utils.settings -> /full/path/to.py
        self.__dirsToImportsCache = {}  # /dir/path -> { my.mod: path.py, ... }

        self.dataModel = ImportDiagramModel()
        self.scene = QGraphicsScene()

        # Avoid pylint complains
        self.progressBar = None
        self.infoLabel = None

        self.__createLayout()
        self.setWindowTitle( 'Imports/dependencies diagram generator' )
        QTimer.singleShot( 0, self.__process )
        return
Example #48
0
    def __init__(self, theCanvas, theLayer, selFeatureIds, parent=None):
        super(CautionShowInfoDlg, self).__init__(parent)
        self.setupUi(self)
        self.mTheCanvas = theCanvas
        self.mTheLayer = theLayer
        self.mSelFeatureIds = selFeatureIds
        self.mAllFeatureIds = []
        self.highlightList = []
        self.setWindowTitle("Caution")
        self.labelOutlinkid.setText("Inlinkid:")
        self.graphicsViewCaution.setScene(QGraphicsScene())

        featureIter = self.mTheLayer.getFeatures(QgsFeatureRequest().setFlags(
            QgsFeatureRequest.NoGeometry))
        inti = 0
        theFeature = QgsFeature()
        while (featureIter.nextFeature(theFeature) and inti < 512):
            inti += 1
            self.mAllFeatureIds.append(theFeature.id())
        self.spinBoxFeatureIndex.setValue(1)
        self.spinBoxFeatureIndex.setMinimum(1)
        self.spinBoxFeatureIndex.setMaximum(inti)

        errMsg = ['']
        self.initComboBoxOutlinkid()
        self.comboBoxOutlinkid.setFocus()
        self.selectFeatureById(errMsg,
                               self.mSelFeatureIds[0],
                               bZoomToSelected=False)

        self.pushButtonPrev.clicked.connect(self.onPushButtonPrev)
        self.pushButtonNext.clicked.connect(self.onPushButtonNext)
        self.connect(self.comboBoxOutlinkid,
                     QtCore.SIGNAL('activated(QString)'),
                     self.comboBoxOutlinkidChanged)
Example #49
0
    def __init__(self, parent=None):
        super(LiteBoxView, self).__init__(parent)
        self.setWindowFlags(Qt.Window | Qt.WindowStaysOnTopHint)
        #self.setAttribute(Qt.WA_DeleteOnClose)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setViewportUpdateMode(QGraphicsView.FullViewportUpdate)
        QtGui.QShortcut(Qt.Key_Escape, self, self.close)
        self.desktopshot = None

        # will propagate to children
        self.setRenderHint(QPainter.Antialiasing)
        self.setRenderHint(QPainter.TextAntialiasing)

        self.scene = QGraphicsScene()
        self.setScene(self.scene)
Example #50
0
 def setupUi(self, document):
     super(NodeBoxDocumentBaseClass, self).setupUi(document)
     superView = self.graphicsSuperView
     self.BACKGROUND_COLOR = QColor(superView.palette().color(
         QPalette.Window).name())
     self.setupStyleSpecificUI()
     self.verticalSplitter.setStyleSheet(superView.styleSheet())
     self.graphicsView = graphicsView = self.app.newNodeBoxGraphicsView()
     superView._scene = scene = QGraphicsScene()
     scene.setItemIndexMethod(QGraphicsScene.NoIndex)
     superView.setScene(scene)
     scene.addItem(graphicsView)
     graphicsView._scene = scene
     graphicsView.superView = superView
     graphicsView._viewPort = superView.viewport()
     self._initSizeAndPosition()
     self.horizontalSplitter.setSizes(split(self.width(), 0.466))
     self.verticalSplitter.setSizes(split(self.height(), 0.767))
     self.outputView.setFont(self.textView.font())
     self.textView.setFocus()
     if self.styleName not in ("windowsxp", "windowsvista", "mac"):
         self.app.setPalette(self.app.style().standardPalette())
         self.setPalette(self.style().standardPalette())
     if sys.platform == "darwin":
         self.setWindowIcon(QIcon())
Example #51
0
    def __init__(self, master, *args):
        QGraphicsView.__init__(self, *args)
        self.master = master

        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)

        self.setRenderHints(QPainter.Antialiasing)
        scene = QGraphicsScene(self)
        self.pixmapGraphicsItem = QGraphicsPixmapItem(None)
        scene.addItem(self.pixmapGraphicsItem)
        self.setScene(scene)

        self.setMouseTracking(True)
        self.viewport().setMouseTracking(True)

        self.setFocusPolicy(Qt.WheelFocus)
    def setupUi_custom(self, ):
        self.scene = QGraphicsScene()
        self.scene2 = QGraphicsScene()
        self.pushButton.clicked.connect(self.selectFile)
        self.horizontalSlider.valueChanged.connect(self.updateLCD)
        self.pushButton_2.clicked.connect(self.disp_graph)
        self.pushButton_3.clicked.connect(self.selectFile_from_folder)
        self.stop_button.clicked.connect(self.set_stop)
        #TODO [WEIRD PROBLEM] QPixmap needs to be called at least once with JPG image before tensorFlow, otherwise program crashes
        self.scene.addPixmap(
            QPixmap(os.getcwd() + "/images/demo.jpg").scaled(
                self.graphicsView.size(), QtCore.Qt.KeepAspectRatio))
        self.graphicsView.setScene(self.scene)

        #Add blank canvas initially
        fig1 = Figure()
        self.addmpl(fig1)
Example #53
0
 def close(self):
     #clear everything
     self.init_table()
     # clear description and quicklook
     self.dlg.textEdit.clear()
     # clear search box
     #text = self.dlg.search_lineEdit.setText("")
     self.init_searchBox()
     # make a new emptey scene to show
     if not self.dlg.graphicsView is None:
         scene = QGraphicsScene()
         pic = QPixmap()
         scene.addItem(QGraphicsPixmapItem(pic))
         self.dlg.graphicsView.setScene(scene)        
         self.dlg.graphicsView.show()
     """close the dialog"""
     self.dlg.close()
Example #54
0
    def __init__(self,
                 posModel,
                 along,
                 preemptive_fetch_number=5,
                 parent=None,
                 name="Unnamed Scene",
                 swapped_default=False):
        """
        * preemptive_fetch_number -- number of prefetched slices; 0 turns the feature off
        * swapped_default -- whether axes should be swapped by default.

        """
        QGraphicsScene.__init__(self, parent=parent)

        self._along = along
        self._posModel = posModel

        self._dataShape = (0, 0)
        self._dataRect = None  #A QGraphicsRectItem (or None)
        self._offsetX = 0
        self._offsetY = 0
        self.name = name

        self._stackedImageSources = StackedImageSources(LayerStackModel())
        self._showTileOutlines = False
        self._showTileProgress = True

        self._tileProvider = None
        self._dirtyIndicator = None
        self._prefetching_enabled = False

        self._swappedDefault = swapped_default
        self.reset()

        # BowWave preemptive caching
        self.setPreemptiveFetchNumber(preemptive_fetch_number)
        self._course = (1, 1)  # (along, pos or neg direction)
        self._time = self._posModel.time
        self._channel = self._posModel.channel
        self._posModel.timeChanged.connect(self._onTimeChanged)
        self._posModel.channelChanged.connect(self._onChannelChanged)
        self._posModel.slicingPositionChanged.connect(
            self._onSlicingPositionChanged)

        self._allTilesCompleteEvent = threading.Event()
Example #55
0
 def drawSnippet(self, graphicsview, snippet):
     """Draw single result item to graphicsview"""
     try:
         h, w = snippet.shape
     except:
         h, w, c = snippet.shape
     if h < 1 or w < 1:
         return
     processedimage = array2qimage(snippet)
     pix = QPixmap()
     pix.convertFromImage(processedimage)
     pix = pix.scaled(graphicsview.width(),
                      graphicsview.height() - 1, Qt.KeepAspectRatio,
                      Qt.SmoothTransformation)
     scene = QGraphicsScene()
     scene.addPixmap(pix)
     graphicsview.setScene(scene)
     graphicsview.show()
Example #56
0
    def __init__(self):
        # pylint: disable=missing-docstring
        super().__init__()

        self.data = self.discrete_data = None
        self.attrs = []
        self.input_features = None
        self.areas = []
        self.selection = set()

        self.attr_box = gui.hBox(self.mainArea)
        model = VariableListModel()
        model.wrap(self.attrs)
        combo_args = dict(widget=self.attr_box,
                          master=self,
                          contentsLength=12,
                          callback=self.update_attr,
                          sendSelectedValue=True,
                          valueType=str,
                          model=model)
        fixed_size = (QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.attrXCombo = gui.comboBox(value="attrX", **combo_args)
        gui.widgetLabel(self.attr_box, "\u2715", sizePolicy=fixed_size)
        self.attrYCombo = gui.comboBox(value="attrY", **combo_args)
        self.vizrank = SieveRank(self)
        self.vizrank_button = gui.button(self.attr_box,
                                         self,
                                         "Score Combinations",
                                         sizePolicy=fixed_size,
                                         callback=self.vizrank.reshow,
                                         enabled=False)
        self.vizrank.pairSelected.connect(self.set_attr)

        self.canvas = QGraphicsScene()
        self.canvasView = ViewWithPress(self.canvas,
                                        self.mainArea,
                                        handler=self.reset_selection)
        self.mainArea.layout().addWidget(self.canvasView)
        self.canvasView.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.canvasView.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

        box = gui.hBox(self.mainArea)
        box.layout().addWidget(self.graphButton)
        box.layout().addWidget(self.report_button)
    def updateDescAndQL(self):
        # get the name of the selected dataset
        dataset_name, dataset_serviceType = self.getSelectedNameAndType()

        #custom web service object
        dataset = self.selectdataSets(dataset_name, dataset_serviceType)

        quicklook = os.path.join(self.quicklooks_dir, dataset.QLname + ".jpg")
        desc = dataset.getDescription(self.language)
        name = dataset.getName(self.language)

        #update decription
        self.dlg.textEdit.clear()
        #creation and last update
        if self.language == "EN":
            crDate = "Creation date : " + dataset.creationDate
            update = "Last update : " + dataset.lastUpdate
        elif self.language == "GR":
            crDate = unicode(
                "Ημερομηνια δημιουργιας : " + dataset.creationDate, 'utf-8')
            update = unicode("Τελευταία ενημέρωση : " + dataset.lastUpdate,
                             'utf-8')

        cursor = QTextCursor(self.dlg.textEdit.document())
        cursor.insertHtml("<h3> " + name + " <br><br></h3>")
        cursor.insertHtml("<p> " + desc + " <br><br><br></p>")
        cursor.insertHtml("<p><i> " + crDate + " <br></i></p>")
        #cursor.insertHtml("<p><i> "+update+" <br></i></p>")

        self.dlg.textEdit.setReadOnly(True)
        #update quicklook

        #GET DIMENSIONS OF THE IMAGE
        img = Image.open(quicklook)
        w, h = img.size

        scene = QGraphicsScene()
        pic = QPixmap(quicklook)
        scene.addItem(QGraphicsPixmapItem(pic))

        self.dlg.graphicsView.setScene(scene)
        self.dlg.graphicsView.fitInView(QRectF(0, 0, w, h), Qt.KeepAspectRatio)
        self.dlg.graphicsView.show()
Example #58
0
	def __initializeUi(self):
		"""
		Initializes the Widget ui.
		"""

		LOGGER.debug("> Initializing '{0}' ui.".format(self.__class__.__name__))

		self.Previous_Image_pushButton.setIcon(QIcon(os.path.join(self.__uiResourcesDirectory, self.__uiPreviousImage)))
		self.Next_Image_pushButton.setIcon(QIcon(os.path.join(self.__uiResourcesDirectory, self.__uiNextImage)))
		self.Zoom_In_pushButton.setIcon(QIcon(os.path.join(self.__uiResourcesDirectory, self.__uiZoomInImage)))
		self.Zoom_Out_pushButton.setIcon(QIcon(os.path.join(self.__uiResourcesDirectory, self.__uiZoomOutImage)))
		len(self.__paths) <= 1 and self.Navigation_frame.hide()

		LOGGER.debug("> Initializing graphics View.")
		self.__graphicsView = QGraphicsView()
		self.__graphicsView.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
		self.__graphicsView.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
		self.__graphicsView.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
		self.__graphicsView.setDragMode(QGraphicsView.ScrollHandDrag)
		# Reimplementing QGraphicsView wheelEvent method.
		self.__graphicsView.wheelEvent = self.wheelEvent

		LOGGER.debug("> Initializing graphics scene.")
		self.__graphicsScene = QGraphicsScene(self.__graphicsView)
		self.__graphicsScene.setItemIndexMethod(QGraphicsScene.NoIndex)
		self.__graphicsScene.setSceneRect(-(float(self.__graphicsSceneWidth)) / 2,
										- (float(self.__graphicsSceneHeight)) / 2,
										float(self.__graphicsSceneWidth),
										float(self.__graphicsSceneHeight))

		self.__graphicsView.setScene(self.__graphicsScene)
		self.__graphicsView.setBackgroundBrush(QBrush(self.__graphicsSceneBackgroundColor))

		self.Images_Previewer_frame_gridLayout.addWidget(self.__graphicsView)

		# Signals / Slots.
		self.__container.engine.imagesCaches.QImage.contentAdded.connect(self.__engine_imagesCaches_QImage__contentAdded)
		self.Previous_Image_pushButton.clicked.connect(self.__Previous_Image_pushButton__clicked)
		self.Next_Image_pushButton.clicked.connect(self.__Next_Image_pushButton__clicked)
		self.Zoom_Out_pushButton.clicked.connect(self.__Zoom_Out_pushButton__clicked)
		self.Zoom_In_pushButton.clicked.connect(self.__Zoom_In_pushButton__clicked)
		self.Zoom_Fit_pushButton.clicked.connect(self.__Zoom_Fit_pushButton__clicked)
    def __init__(self, theCanvas, theLayer, selFeatureIds, parent=None):
        super(NostraIllustCheckDlg, self).__init__(parent)
        self.setupUi(self)
        self.mTheCanvas = theCanvas
        self.mTheLayer = theLayer
        self.mSelFeatureIds = selFeatureIds
        self.mAllFeatureIds = []
        self.highlightList = []
        uri = QgsDataSourceURI(self.mTheLayer.source())
        self.conn = psycopg2.connect('''host='%s' dbname='%s' user='******' password='******' ''' %\
            (uri.host(), uri.database(), uri.username(), uri.password()))
        self.pg = self.conn.cursor()

        # members shown in graphic view.
        self.mScene = QGraphicsScene()
        self.graphicsViewShowImage.setScene(self.mScene)
        self.mPixmapList = []

        featureIter = self.mTheLayer.getFeatures(QgsFeatureRequest().setFlags(
            QgsFeatureRequest.NoGeometry))
        inti = 0
        theFeature = QgsFeature()
        while (featureIter.nextFeature(theFeature)):
            inti += 1
            self.mAllFeatureIds.append(theFeature.id())

        self.spinBoxFeatureIndex.setValue(1)
        self.spinBoxFeatureIndex.setMinimum(1)
        self.spinBoxFeatureIndex.setMaximum(inti)

        errMsg = ['']
        self.initComboBoxOutlinkid()
        self.selectFeatureById(errMsg,
                               self.mSelFeatureIds[0],
                               bZoomToSelected=False)
        self.comboBoxOutlinkid.setFocus()

        self.pushButtonPrev.clicked.connect(self.onPushButtonPrev)
        self.pushButtonNext.clicked.connect(self.onPushButtonNext)
        self.connect(self.comboBoxOutlinkid,
                     QtCore.SIGNAL('activated(QString)'),
                     self.comboBoxOutlinkidChanged)
Example #60
0
 def mouseReleaseEvent(self, event):
     items = self.getSelected()
     if items:
         starts = []
         ends = []
         moved_ids = []
         data = self.current_data
         #pt_scale = (self.scale[0]/self.img_scale[0], self.scale[1]/self.scale[1])
         for item in items:
             pos = item.pos()*self.min_scale
             old_pos = data[item.pt_id]
             if pos != old_pos:
                 moved_ids.append(item.pt_id)
                 starts.append(old_pos)
                 ends.append(pos)
         if moved_ids:
             self.planMovePoints(moved_ids, ends, starts)
     elif self.mode == TrackingScene.AddCell:
         QGraphicsScene.mouseReleaseEvent(self, event)
         if event.isAccepted():
             return
         items = self.items(event.scenePos())
         if items:
             pt = items[0]
             if isinstance(pt, PointItem):
                 pt_id = pt.pt_id
                 cells = self.current_data.cells
                 if self.has_current_cell:
                     cid = self.current_cell
                     cell_shape = list(cells[cid])
                     if pt_id in cell_shape:
                         cell_shape.remove(pt_id)
                         self.planChangeCell(cid, cell_shape)
                     else:
                         cell_shape.append(pt_id)
                         self.planChangeCell(cid, cell_shape)
                 else:
                     cid = self.current_cell
                     cell_shape = [pt_id]
                     self.planAddCell(cid, cell_shape)
         return
     QGraphicsScene.mouseReleaseEvent(self, event)