Exemplo n.º 1
0
 def _init_camera_vars (self):
     '''
     static method. It initializes the math variables.
     '''
     self.__compo_mtools = MathTools.Tools ()
     
     self.__curr_angles  = QPoint (0,0)
     self.__last_pos     = QPoint (0,0)
     self.__delta        = QPoint (0,0)
     self.__orig         = QVector3D (0.0, 0.0, 0.0)
     self.__cam_dist     = 0.0
     self.__z_near       = 0.1
     self.__z_far        = 2000.0
     self.__fovy         = 45.0
     self.__angle        = self.__compo_mtools.getAngle (self.__fovy)
     
     self.__norm_mtx     = QMatrix4x4 () #(GLdouble * 16)()
     self.__norm_mtx.setToIdentity ()
     
     self.__mtx          = QMatrix4x4 () #(GLdouble * 16)()
     self.__mtx.setToIdentity ()
     
     self.__aspect_ratio = float(self.__w)/float(self.__h)
     
     self.__camera_list  = []
Exemplo n.º 2
0
class NotificationServer(QObject):
    def __init__(self, parent=None):
        QObject.__init__(self, parent)
        self.notifications = set()
        self.size = QSize(300, 100)
        self.margin = QPoint(10, 10)

    def notify(self, html):
        note = Notification(html)
        self.connect(note, SIGNAL("done"), self.noteDestroyed)

        desktop = QApplication.desktop().availableGeometry(note)
        me = QRect(QPoint(0, 0), self.size)
        me.moveBottomRight(desktop.bottomRight() - self.margin)
        while self.notePosTaken(me):
            me.translate(0, 0 - (self.size.height() + (self.margin.y() * 2)))
            if not desktop.contains(me):
                me.moveBottom(desktop.bottom() - self.margin.y())
                me.translate(0 - (self.size.width() + self.margin.x() * 2), 0)

        note.setGeometry(me)
        self.notifications.add(note)
        note.display()

    def notePosTaken(self, rect):
        for note in self.notifications:
            if note.geometry().intersects(rect):
                return True
        return False

    def noteDestroyed(self, note):
        self.notifications.remove(note)
Exemplo n.º 3
0
	def open_link(self, x, y):
		self.__upostda_condition.acquire()
		p = QPoint()
		p.setX(int(x))
		p.setY(int(y))
		self.emit(QtCore.SIGNAL('signalUPosDA(QPoint *)'), p)
		self.__upostda_condition.wait()
		self.__upostda_condition.release()
Exemplo n.º 4
0
 def showPopup(self):
     if not self.popup:
         return
     pos = QPoint(self.width(), self.height())
     pos = self.mapToGlobal(pos)
     size = self.popup.size()
     self.popup.move(pos.x() - size.width(), pos.y())
     self.popup.show()
Exemplo n.º 5
0
 def contains(self, p: QPoint):
     d = self.size * Info.dpi
     pos = self.real_pos()
     dx = pos.x() - p.x()
     dy = pos.y() - p.y()
     if dx * dx + dy * dy <= d * d:
         return True
     return False
Exemplo n.º 6
0
 def get_border(self, p: QPoint):
     if p.x() <= 2:
         return Alignment.Left
     elif p.x() >= self.width() - 2:
         return Alignment.Right
     elif p.y() <= 2:
         return Alignment.Top
     elif p.y() >= self.height() - 2:
         return Alignment.Bottom
     return None
Exemplo n.º 7
0
 def __init__(self, message, str = None, pos = None):
     cfg = Config('messages', message)
     
     if (pos is None):
         self.pos = QPoint(*cfg.get('position'))
     else:
         self.pos = QPoint(*pos)
     
     self.velocity = cfg.get('velocity') 
     
     FadeMessage.__init__(self, message, str)
Exemplo n.º 8
0
    def drawNetwork(self, qp):

    #for each vehicle
        for j in range(len(self.vehicleList)):
        #we check others vehicles
            for k in range(len(self.vehicleList)):
                #if we are testing the current vehicle
                if j == k:
                    continue
                # if we are testing an other vehicle
                else:
                    # calculating the distance between the 2 vehicles
                    xDiff = self.vehicleList[k].position.x() - self.vehicleList[j].position.x()
                    yDiff = self.vehicleList[k].position.y() - self.vehicleList[j].position.y()
                    dist = math.sqrt(math.pow(xDiff, 2) + math.pow(yDiff, 2))
                    if dist < globalvars.msg_distance:
                        # creating a connection between the 2 vehicles
                        qp.drawLine(
                            self.vehicleList[j].position.x(),
                            self.vehicleList[j].position.y(),
                            self.vehicleList[k].position.x(),
                            self.vehicleList[k].position.y()
                        )

            # creating a random movement
            if not self.isPause:
                isPosX = bool(random.getrandbits(1))
                isPosY = bool(random.getrandbits(1))
                if isPosX:
                    if self.vehicleList[j].position.x() < self.size.width() - 50:
                        self.vehicleList[j].position.setX(self.vehicleList[j].position.x() + 1)
                else:
                    if self.vehicleList[j].position.x() > 25:
                        self.vehicleList[j].position.setX(self.vehicleList[j].position.x() - 1)

                if isPosY:
                    if self.vehicleList[j].position.y() < self.size.height() - 50:
                        self.vehicleList[j].position.setY(self.vehicleList[j].position.y() + 1)
                else:
                    if self.vehicleList[j].position.y() > 25:
                       self.vehicleList[j].position.setY(self.vehicleList[j].position.y() - 1)

                
                pos = QPoint(self.vehicleList[j].position.x() - (self.vehicleImg[j].size().width()/2), 
                             self.vehicleList[j].position.y() - (self.vehicleImg[j].size().height()/2))
                self.vehicleImg[j].move(pos.x(), pos.y())


        time.sleep(0.001)
        # calling paintEvent
        self.update()
Exemplo n.º 9
0
 def drawQuad(self):
     '''change to accept arguments pass'''
     glColor( 0., 0., 1.)
     glLineWidth(4.0)
     pointer_x = self.lastpos.x()/200.#self.corner
     pointer_y = self.lastpos.y()/200.#/(self.corner)
     norm_dx = dx/200.#/(self.corner)
     norm_dy = dy/200.#/(self.corner)
     #print -self.corner, pointer_x, pointer_y, norm_dx, norm_dy
     glBegin(GL_QUADS)
     glVertex3f(-self.corner + pointer_x, 
                -self.corner + pointer_y, 
                -self.near+2*self.corner)
     
     glVertex3f(-self.corner + pointer_x+ norm_dx, 
                -self.corner + pointer_y,
                -self.near+2*self.corner)
                
     glVertex3f(-self.corner + pointer_x+ norm_dx, 
                -self.corner + pointer_y + norm_dy,
                -self.near+2*self.corner)
     
     glVertex3f(-self.corner + pointer_x, 
                -self.corner + pointer_y,
                -self.near+2*self.corner)
     glEnd()
     self.lastpos = QPoint(event.pos())
     #redraw eachtime mouse 's moving
     self.updateGL()   
Exemplo n.º 10
0
    def eventFilter( self, watched, event ):
        if event.type() == QEvent.MouseButtonPress:
            pos = [int(i) for i in self.posModel.cursorPos]
            pos = [self.posModel.time] + pos + [self.posModel.channel]

            if event.button() == Qt.LeftButton:
                self.origin = QPoint(event.pos())
                self.originpos = pos
                self.rubberBand.setGeometry(QRect(self.origin, QSize()))
                self.rubberBand.show()
                gPos = watched.mapToGlobal( event.pos() )
                self.leftClickReceived.emit( pos, gPos )
            if event.button() == Qt.RightButton:
                gPos = watched.mapToGlobal( event.pos() )
                self.rightClickReceived.emit( pos, gPos )                
        if event.type() == QEvent.MouseMove:
            if not self.origin.isNull():
                self.rubberBand.setGeometry(QRect(self.origin,
                                                  event.pos()).normalized())
        if event.type() == QEvent.MouseButtonRelease:
            pos = [int(i) for i in self.posModel.cursorPos]
            pos = [self.posModel.time] + pos + [self.posModel.channel]
            if event.button() == Qt.LeftButton:
                self.rubberBand.hide()
                self.leftClickReleased.emit( self.originpos,pos )                

    

        # Event is always forwarded to the navigation interpreter.
        return self.baseInterpret.eventFilter(watched, event)
Exemplo n.º 11
0
    def mousePressEvent(self, event):

        if event.button() == Qt.LeftButton:

            self.origin = QPoint(event.pos())
            self.rubberBand.setGeometry(QRect(self.origin, QSize()))
            self.rubberBand.show()
Exemplo n.º 12
0
class Window(QMainWindow):

    def __init__(self, parent=None):

        super(Window, self).__init__(parent)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.rubberBand = QRubberBand(QRubberBand.Rectangle, self)
        self.origin = QPoint()
        self.repaint()
    def mousePressEvent(self, event):

        if event.button() == Qt.LeftButton:

            self.origin = QPoint(event.pos())
            self.rubberBand.setGeometry(QRect(self.origin, QSize()))
            self.rubberBand.show()

    def mouseMoveEvent(self, event):

        if not self.origin.isNull():
            self.rubberBand.setGeometry(QRect(self.origin, event.pos()).normalized())

    def mouseReleaseEvent(self, event):

        if event.button() == Qt.LeftButton:
            self.rubberBand.hide()
Exemplo n.º 13
0
    def __init__(self, parent=None):
        """
        Constructor
        """
        self.__image_width = 250
        self.__image_height = 250

        self.__isMouseDown = False
        self.__zoomFactor = 1.0

        self.__scrollOffset = QPoint()

        if hasattr(QGLFormat, "setVersion"):
            # Modern OpenGL
            f = QGLFormat()
            f.setVersion(3, 3)
            f.setProfile(QGLFormat.CoreProfile)
            f.setSampleBuffers(True)
            c = QGLContext(f, None)

            QGLWidget.__init__(self, c, parent)
            print "Version is set to 3.3"
        else:
            QGLWidget.__init__(self, parent)

        # self.__svgItem = QtSvg.QGraphicsSvgItem("circle_star.svg")
        self.__mySvgTool = MySvgTool()

        self.__mySvgWriter = MySvgWriter()
        self.__mySvgWriter.DrawSomething()
        self.__myBufferPainter = MyBufferPainter()
Exemplo n.º 14
0
    def __init__(self, navigationInterpreter, positionModel, BoxContr, widget):
        '''
        Class which interacts directly with the image scene

        :param navigationInterpreter:
        :param positionModel:
        :param BoxContr:
        :param widget: The main widget

        '''


        QObject.__init__(self)


        self.baseInterpret = navigationInterpreter
        self._posModel      = positionModel
        self.rubberBand = RedRubberBand(QRubberBand.Rectangle, widget)

        self.boxController=BoxContr

        self.leftClickReleased.connect(BoxContr.addNewBox)
        self.rightClickReceived.connect(BoxContr.onChangedPos)
        #self.deleteSelectedItemsSignal.connect(BoxContr.deleteSelectedItems)


        self.origin = QPoint()
        self.originpos = object()
Exemplo n.º 15
0
 def __init__(self, navigationInterpreter, positionModel, editor):
     QObject.__init__(self)
     self.baseInterpret = navigationInterpreter
     self.posModel      = positionModel
     self.rubberBand = QRubberBand(QRubberBand.Rectangle, editor)
     self.origin = QPoint()
     self.originpos = object()
Exemplo n.º 16
0
 def mousePressEvent(self, event):
     if self.mode == "ZOOMING":
         self.mode = "None"
         self.computeSelection()
     else: 
         self.lastpos = QPoint(event.pos())
         self.setCursor(QCursor(Qt.ClosedHandCursor))
Exemplo n.º 17
0
    def __init__(self, parent=None):

        super(Window, self).__init__(parent)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.rubberBand = QRubberBand(QRubberBand.Rectangle, self)
        self.origin = QPoint()
        self.repaint()
Exemplo n.º 18
0
    def adjustPosition(self, eventPos):
        '''
        @param eventPos - QPoint
        '''
        prop = MaeMoneyProperties.instance()

        newPos = QPoint(eventPos.x(), eventPos.y())
        if prop.isPortraitMode():
            offset = 50
        else:
            offset = 72

        newY = max(0, eventPos.y() - offset)
        newPos.setY(newY)


        return newPos
Exemplo n.º 19
0
 def tryMove(self, oldPos, newPos, directions):
     p = QPoint(oldPos)
     if directions & 1: #X轴方向
         gridX = self.parent().width() / 40
         delta = newPos.x() - oldPos.x()
         if abs(delta) / gridX > 0.5:
             newX = oldPos.x() + delta / abs(delta) * gridX * round(abs(delta) / gridX)
             newX = gridX * round(newX / gridX)
             p.setX(newX)
     if directions & 2:
         gridY = self.parent().height() / 30
         delta = newPos.y() - oldPos.y()
         if abs(delta) / gridY > 0.5:
             newY = oldPos.y() + delta / abs(delta) * gridY * round(abs(delta) / gridY)
             newY = gridY * round(newY / gridY)
             p.setY(newY)
     return p
Exemplo n.º 20
0
	def readSettings(self):
		self.imageFolder = os.path.normpath(str(self.settings.value("imageFolder").toString()))
		self.ui.actionIgnore_Transparent_Pixels.setChecked( self.settings.value("ignoreAlpha", True).toBool())
		self.ui.actionCheck_for_update_at_start.setChecked( self.settings.value("checkupdate", True).toBool())
		self.ui.tolerance_le.setText( self.settings.value("tolerance").toString())
		self.settings.beginGroup("/geometry")
		p = QPoint()  # position
		s = QSize()  # size

		x = self.settings.value("X", -1).toInt()[0]
		y = self.settings.value("Y", -1).toInt()[0]
		# don't position outside current screen
		qRect = QtGui.QDesktopWidget.availableGeometry(app.desktop())
		if x > qRect.right():
			x = 10
		if y > qRect.bottom():
			y = 10
		p.setX(x)
		p.setY(y)
		s.setWidth(self.settings.value("W", -1).toInt()[0])
		s.setHeight(self.settings.value("H", -1).toInt()[0])
		self.settings.endGroup()
		if p.x() > 0 and p.y() > 0 and s.width() > 0 and s.height() > 0:
			self.resize(s)  # restore size
			self.move(p)  # restore position
Exemplo n.º 21
0
 def mousePressEvent(self, event):
     """ Calls deselectAllWidgets.
     """
     multiSelectEnabled = self.multiSelectEnabled()
     if event.modifiers() != Qt.ControlModifier:
         self.deselectAllWidgets()
     if multiSelectEnabled:
         self._selectionRectStartPos = QPoint(event.pos())
         self._selectionRect = None
Exemplo n.º 22
0
    def setupUi (self, MainWindow):
        '''sets up the Maya UI.
        
        @param MainWindow
        '''
        MainWindow.setObjectName ('MainWindow')
        MainWindow.resize (800, 1396)
        sizePolicy = QSizePolicy (QSizePolicy.Preferred, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch (0)
        sizePolicy.setVerticalStretch (0)
        sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
        MainWindow.setSizePolicy(sizePolicy)
        font = QFont ()
        font.setPointSize (11)
        MainWindow.setFont (font)
        MainWindow.setWindowTitle (QApplication.translate("MainWindow", "Location Tool", None, QApplication.UnicodeUTF8))
        MainWindow.setTabShape (QTabWidget.Rounded)
        MainWindow.setDockOptions (QMainWindow.AllowTabbedDocks|QMainWindow.AnimatedDocks)
        
        self.scrollAreaWidgetContents_3 = QWidget (MainWindow)
        self.scrollAreaWidgetContents_3.setGeometry (QRect(10, 10, 900, 940))
        self.scrollAreaWidgetContents_3.setObjectName ('scrollAreaWidgetContents_3')
        self._view = View0.View ("JADEview", self.graph_view, self.scene, self.scrollAreaWidgetContents_3)
        self._view.setObjectName ('JADEview')  # real ui name
        self._view.graphicsView.setObjectName ('JADEInnerView')
        self.connect (self.scene, SIGNAL("selectionChanged()"), self._view.selectionChanged)
        
        self._view.wireViewItemsUp ()
        self._view.getGraphicsView().setScene (self.scene)
        self._view.setToolboxCSSColorScheme ('background-color: rgb(68,68,68);color: rgb(200,200,200)') # this needs to be done since the toolbox's background didn't have a uniform colour otherwise.
        #self._view.setGraphicsViewCSSBackground () # the CSS background doesn't seem to work in Maya as there seems to be a problem with cleaning QGraphicsLineItems when they move, that doesn't happen when there's no CSS applied to the background.

        self.graphicsView = self._view.getGraphicsView ()
        self.node_coords = QPoint (0,0)
        
        layout = QHBoxLayout (self.scrollAreaWidgetContents_3)
        layout.setContentsMargins (QMargins(0,0,0,0));
        layout.addWidget (self._view)
        
        QMetaObject.connectSlotsByName (MainWindow)
        
        """
        cmds.control('JADEInnerView', edit=True, ebg=True, bgc=[.5,.5,.9])
        print cmds.control('JADEInnerView', query=True, p=True)
        """
        
        # wiring the Maya Contextual pop-up Menus - yes, in Maya we've split the pop-up menu definition in three pop-up menus although only one will be present at any time.
        self.menu        = cmds.popupMenu ('JADEmenu',        parent='JADEInnerView', button=3, pmc = 'ClientMaya.ui.ctxMenu()',        aob=True)
        self.menuAddOuts = cmds.popupMenu ('JADEmenuAddOuts', parent='JADEInnerView', button=3, pmc = 'ClientMaya.ui.ctxMenuAddOuts()', aob=True, alt=True)
        self.menuAddIns  = cmds.popupMenu ('JADEmenuAddIns',  parent='JADEInnerView', button=3, pmc = 'ClientMaya.ui.ctxMenuAddIns()',  aob=True, ctl=True)
        
        # this class property is used to keep track of the mouse position.
        self._mouse = QCursor
        
        # self._view's zoom slider (we need this to correct the bias added to sort the mouse position when the zoom changes - ONLY in Maya)
        self._zoom_slider = self._view.getZoomSlider()
Exemplo n.º 23
0
    def __init__(self, parent,contentPage,args):
      super(ControllerPage, self).__init__(parent)
      self.phantom = parent
      self.contentPage = contentPage
      self.evaljsSignalSent.connect(self.onEval)
      self.avaljsSignalSent.connect(self.onAval)
      self.mainFrame().addToJavaScriptWindowObject('page', self)
      self.m_scrollPosition = QPoint()

      self.contentFrame = self.contentPage.mainFrame()
Exemplo n.º 24
0
    def __init__(self, parent = None):

        QLabel.__init__(self, parent)
        self.rubberBand = QRubberBand(QRubberBand.Rectangle, self)
        self.origin = QPoint()
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setGeometry(100,100,100,100)
        self.setAutoFillBackground(True)

        self.screenshot_close.connect(Fotbalek.load_pix)
Exemplo n.º 25
0
 def __init__(self, iface):
   canvas = iface.mapCanvas()
   super(MapSwipeTool, self).__init__( canvas )
   self.view = iface.layerTreeView()
   self.msgBar = iface.messageBar()
   self.swipe = SwipeMap( canvas )
   self.checkDirection =  self.hasSwipe = self.disabledSwipe = None
   self.firstPoint = QPoint()
   self.cursorV = QCursor( Qt.SplitVCursor )
   self.cursorH = QCursor( Qt.SplitHCursor )
Exemplo n.º 26
0
 def __init__(self, level_number, level):
     self.level_number = level_number
     
     self.info = {}
     self.fields = set()
     
     self.level = level
     self.player_state = Player.get_instance()
             
     cfg = Config('interface', 'Settings')
     font_name = cfg.get('field_font')
     font_size = cfg.get('field_font_sz')
     self.field_font = FontManager.getFont(font_name)
     self.field_font.setPointSize(font_size)
     self.field_color = QColor.fromRgb(*cfg.get('field_color'))
     
     for f_name in ConfigManager.getOptions('interface', 'Fields'):
         s = ConfigManager.getVal('interface', 'Fields', f_name)
         s = map(str.strip, s.split('||'))
         
         img = QImage('resources/images/'+s[0])
         img_pos = QPoint(*eval(s[1]))
         info_rect = QRect(*eval(s[2]))
         scale = float(s[3])
         
         if (len(s) >= 5):
             font = QFont(self.field_font)
             font.setPointSize(int(s[4]))
         else:
             font = self.field_font
         
         img_w, img_h = img.width(), img.height()
         img_rect = QRect(
             img_pos.x(), img_pos.y(),
             int(img_w*scale), int(img_h*scale)
         )
         
         self.info[f_name] = ''
         
         self.fields.add(Field(f_name, img, img_rect, info_rect, font))
     
     self.radar = Radar.from_config('E-Radar', self)
     self.missile = GuidedMissile.from_config('GuidedMissile', self)
Exemplo n.º 27
0
 def scrollPosition(self, size):
     positions = {'left': 0, 'top': 0}
     for item in positions:
         try:
             positions[item] = int(size[item])
             if positions[item] < 0:
                 positions[item] = 0
         except (KeyError, ValueError):
             positions[item] = self.scrollPosition[item]
     self.m_scrollPosition = QPoint(positions['left'], positions['top'])
     self.m_mainFrame.setScrollPosition(self.m_scrollPosition)
Exemplo n.º 28
0
 def startBounce(self):
     """
      Button starts to bounce requiring attention.
     """
     if self.__bouncing:
         return
     self.__startPos = QPoint(self.pos().x(), self.pos().y())
     self.__animationUp.setStartValue(QPoint(self.__startPos.x(), self.__startPos.y()))
     self.__animationUp.setEndValue(QPoint(self.__startPos.x(), self.__startPos.y() - self.geometry().height()))
     self.__animationUp.start()
     self.__bouncing = True
Exemplo n.º 29
0
 def __init__(self, container, parent: QWidget=None):
     QWidget.__init__(self, parent)
     self.setWindowTitle('Container')
     self.__b_widgets = []
     self.__container = container
     self.__translation = QPoint(0, 0)
     self.setMouseTracking(True)
     self.setFocusPolicy(Qt.ClickFocus)
     self.setFocus()
     for b in container.blocks:
         w = b.get_widget(self)
         self.__b_widgets.append(w)
     pal = QPalette(self.palette())
     pal.setColor(QPalette.Background, QColor(55, 50, 47))
     self.setAutoFillBackground(True)
     self.setPalette(pal)
     container.block_added.connect(self.add_block)
     container.block_removed.connect(self.remove_block)
     self.__moving = False
     self.__origin = QPoint()
Exemplo n.º 30
0
 def resizeEvent(self, ev):
     super(View, self).resizeEvent(ev)
     # Adjust the size of the document if desired
     if self.viewMode() and any(self.surface().pageLayout().pages()):
         if self._centerPos is False:
             self._centerPos = QPoint(0, 0)
         elif self._centerPos is None:
             # store the point currently in the center
             self._centerPos = self.viewport().rect().center() - self.surface().pos()
         if not self._resizeTimer.isActive():
             self._resizeTimeout()
         self._resizeTimer.start(150)
Exemplo n.º 31
0
    def paintEvent( self, ev ):
        painter = QPainter(self)

        # calc bar offset
        y_offset =(self.height() - self._barHeight()) // 2
        ## prevent negative offset
        y_offset = 0 if y_offset < 0 else y_offset

        # frame around fraction indicator
        painter.setBrush(self.palette().dark())
        painter.save()
        ## no fill color
        b = painter.brush(); b.setStyle(Qt.NoBrush); painter.setBrush(b)
        painter.drawRect(
            QRect(QPoint(0, y_offset),
                  QSize(self._barWidth(), self._barHeight())))
        painter.restore()

        # fraction indicator
        painter.drawRect(
            QRect(QPoint(0, y_offset),
                  QSize(self._barWidth()*self._fraction, self._barHeight())))
Exemplo n.º 32
0
 def _resizeTimeout(self):
     if self._centerPos is None:
         return
     oldSize = self.surface().size()
     # resize the layout
     self.fit()
     # restore our position
     newSize = self.surface().size()
     newx = self._centerPos.x() * newSize.width() // oldSize.width()
     newy = self._centerPos.y() * newSize.height() // oldSize.height()
     # we explicitly want the non-kinetic centering function regardless of kinetic state.
     self.fastCenter(QPoint(newx, newy))
     self._centerPos = None
Exemplo n.º 33
0
 def event(self, ev):
     if self._textedit:
         if ((ev.type()
              in (QEvent.MouseButtonPress, QEvent.MouseButtonRelease)
              and ev.button() == Qt.LeftButton)
                 or (ev.type() == QEvent.MouseMove
                     and ev.buttons() & Qt.LeftButton)):
             new = QMouseEvent(ev.type(), QPoint(0, ev.y()), ev.button(),
                               ev.buttons(), ev.modifiers())
             return QApplication.sendEvent(self._textedit.viewport(), new)
         elif ev.type() == QEvent.Wheel:
             return QApplication.sendEvent(self._textedit.viewport(), ev)
     return super(LineNumberArea, self).event(ev)
Exemplo n.º 34
0
    def __showTimestampTooltip(self, position, x, y):
        " Shows a tooltip on the timestamp margin "
        # Calculate the line
        pos = self.SendScintilla(self.SCI_POSITIONFROMPOINT, x, y)
        line, _ = self.lineIndexFromPosition(pos)

        tooltip = self.__getTimestampMarginTooltip(line)
        if not tooltip:
            return

        QToolTip.showText(self.mapToGlobal(QPoint(x, y)), tooltip)
        self.__timestampTooltipShown = True
        return
Exemplo n.º 35
0
def popup_position_from_source(popup, source, orientation=Qt.Vertical):
    popup.ensurePolished()
    source.ensurePolished()

    if popup.testAttribute(Qt.WA_Resized):
        size = popup.size()
    else:
        size = popup.sizeHint()

    desktop = QApplication.desktop()
    screen_geom = desktop.availableGeometry(source)
    source_rect = QRect(source.mapToGlobal(QPoint(0, 0)), source.size())

    if orientation == Qt.Vertical:
        if source_rect.right() + size.width() < screen_geom.right():
            x = source_rect.right()
        else:
            x = source_rect.left() - size.width()

        # bottom overflow
        dy = source_rect.top() + size.height() - screen_geom.bottom()
        if dy < 0:
            y = source_rect.top()
        else:
            y = source_rect.top() - dy
    else:
        # right overflow
        dx = source_rect.left() + size.width() - screen_geom.right()
        if dx < 0:
            x = source_rect.left()
        else:
            x = source_rect.left() - dx

        if source_rect.bottom() + size.height() < screen_geom.bottom():
            y = source_rect.bottom()
        else:
            y = source_rect.top() - size.height()

    return QPoint(x, y)
Exemplo n.º 36
0
 def check_sync1(self):
     """Test that web-to-text sync occurs on clicks to the web pane.
     A click at 0, height (top left corner) should produce
     an index of 0. It doesn't; I'm not sure I understand how
     the WebView x, y coordinate system works. For now, skip
     checking the resulting index.
     """
     self._doBasicTest('rst')
     self.assertEmits(
       lambda: QTest.mouseClick(self._widget().webView,
         Qt.LeftButton, Qt.NoModifier, QPoint(0, self._widget().webView.height())),
       self._dock().previewSync.jsClick,
       200)
Exemplo n.º 37
0
    def __init__(self):

        Interfaceable.__init__(self)

        self.setProperty("ipv4", "")
        self.setProperty("port", "")
        self.setProperty("mac", "")
        self.setProperty("filetype", "cow")
        self.setProperty("filesystem", "root_fs_beta2")
        self.hostIndex = 0
        # self.properties["Hosts"] = ["default","change"]
        # self.hostsproperty={"default":ConnectM("1","2","3","4"),"change":ConnectM("name","ip","mac","port")}
        self.lightPoint = QPoint(-10, 3)
Exemplo n.º 38
0
    def getIconData(self):
        width = self.image.width()
        height = self.image.height()

        matrix = list()
        for y in range(height):
            row = list()
            for x in range(width):
                opaque = 1 if QColor.fromRgba(
                        self.image.pixel(QPoint(x, y))).red() != 255 else 0
                row.append(opaque)
            matrix.append(row)
        return np.array(matrix)
Exemplo n.º 39
0
 def centerViewMenuButtonClicked(self, point=None):
     popup = QMenu(self.tab().centerViewMenuButton())
     popup.addAction(self.plugin()._boxContentAction)
     popup.addAction(self.plugin()._saveImageAction)
     popup.addAction(self.plugin()._zoomAction)
     popup.addSeparator()
     for action in self.plugin().viewMenu().actions():
         if action.data().toString() != "":
             popup.addAction(action)
     if not isinstance(point, QPoint):
         point = self.tab().centerViewMenuButton().mapToGlobal(
             QPoint(self.tab().centerViewMenuButton().width(), 0))
     popup.exec_(point)
Exemplo n.º 40
0
    def __init__(self, editor):
        super(GoToLineDialog, self).__init__(editor)
        box = QVBoxLayout(self)
        box.setContentsMargins(5, 5, 5, 5)
        self.line = QLineEdit()
        self.line.setText(self.tr("<línea>:<columna>"))
        self.line.setSelection(0, len(self.line.text()))
        self.line.setObjectName("popup")
        self.line.setMinimumWidth(200)
        box.addWidget(self.line)
        self.move(self.global_point - QPoint(self.width() + 130, 0))

        self.connect(self.line, SIGNAL("returnPressed()"), self._go)
Exemplo n.º 41
0
 def updateSize(self):
     if self.type != 'SHAPE':
         return
     s = self.canvas.mapSettings()
     self.distArea.setSourceCrs(s.destinationCrs())
     try:
         p1 = self.toMapCoordinates(QPoint(0, 0))
         p2 = self.toMapCoordinates(QPoint(0, 100))
         l = self.distArea.measureLine(p1, p2)
         f = 100 / l
     except:
         f = s.outputDpi() / 0.0254 / s.scale()
     paintLength = max(self.length * f, 50)
     paintWidth = paintLength * self.width / self.length
     offsY = self.offsetX / self.length * paintLength
     offsX = self.offsetY / self.width * paintWidth
     self.paintShape.clear()
     for v in self.shape:
         self.paintShape << QPointF(v[0] * paintWidth - offsX,
                                    v[1] * paintLength + offsY)
     self.size = max(paintLength, paintWidth)
     self.bounding = self.paintShape.boundingRect()
Exemplo n.º 42
0
    def canvasReleaseEvent(self, event):

        if event.button() == Qt.RightButton:
            self.cancel_map_tool()
            return

        # Get the click
        x = event.pos().x()
        y = event.pos().y()
        event_point = QPoint(x, y)
        snapped_feat = None

        # Snapping
        (retval,
         result) = self.snapper.snapToCurrentLayer(event_point,
                                                   2)  # @UnusedVariable

        # That's the snapped features
        if result:
            # Get the first feature
            snapped_feat = result[0]
            point = QgsPoint(snapped_feat.snappedVertex)  #@UnusedVariable
            snapped_feat = next(
                snapped_feat.layer.getFeatures(
                    QgsFeatureRequest().setFilterFid(
                        snapped_feat.snappedAtGeometry)))

        if snapped_feat:
            self.node_id = snapped_feat.attribute('node_id')
            self.dlg_fusion = ArcFusion()
            self.load_settings(self.dlg_fusion)

            # Fill ComboBox workcat_id_end
            sql = ("SELECT id FROM " + self.schema_name +
                   ".cat_work ORDER BY id")
            rows = self.controller.get_rows(sql)
            utils_giswater.fillComboBox(self.dlg_fusion, "workcat_id_end",
                                        rows, False)

            # Set QDateEdit to current date
            current_date = QDate.currentDate()
            utils_giswater.setCalendarDate(self.dlg_fusion, "enddate",
                                           current_date)

            # Set signals
            self.dlg_fusion.btn_accept.clicked.connect(self.exec_fusion)
            self.dlg_fusion.btn_cancel.clicked.connect(
                partial(self.close_dialog, self.dlg_fusion))

            self.dlg_fusion.setWindowFlags(Qt.WindowStaysOnTopHint)
            self.dlg_fusion.open()
Exemplo n.º 43
0
    def __init__(o, widget, accepts, drag_threshold=8):
        o.widget = widget
        o.accepts = accepts
        o.drag_threshold = drag_threshold

        # determine which handlers to autowire
        for key in 'MP,MM,MR,KP,KR'.split(','):
            # generate handler name
            method = ({
                'M': 'mouse',
                'K': 'key'
            }[key[0]] + {
                'P': 'Press',
                'M': 'Move',
                'R': 'Release'
            }[key[1]] + 'Event')

            # setup forwarding of widget.<method> to o.<method>

            def forward(method):
                def handle(ev):
                    if isinstance(widget, QGraphicsScene):
                        #getattr(QGraphicsScene, method)(widget, ev)
                        pass
                    elif isinstance(widget, QGraphicsView):
                        getattr(QGraphicsView, method)(widget, ev)
                    else:
                        print('dont know superclass')
                    getattr(o, method)(ev)

                setattr(widget, method, handle)

            if not hasattr(widget, method) or isinstance(
                    getattr(widget, method), types.BuiltinFunctionType):
                L().debug('inputTracker: autoforward widget.' + method)
                forward(method)
            else:
                m = getattr(widget, method)
                L().debug('inputTracker: already there: %r' %
                          getattr(widget, method))

        # create empty event handlers for my events if not there.
        for name in 'onInputDown', 'onInputUp', 'onInputMove':
            if not hasattr(widget, name):
                setattr(widget, name, lambda o, ev: None)

        # map of currently active events, by key
        o.active_events = {}
        o._last_mouse_pos = QPointF()
        o._last_mouse_screen_pos = QPoint()
        o._last_mouse_scene_pos = QPointF()
Exemplo n.º 44
0
    def canvasReleaseEvent(self, e):
        
        self.is_emitting_point = False
        rectangle = self.get_rectangle()
        selected_rectangle = None
        key = QApplication.keyboardModifiers()                

        if e.button() != Qt.LeftButton:
            self.rubber_band.hide()            
            return
        
        # Disconnect signal to enhance process
        # We will reconnect it when processing last layer of the group
        if self.parent_manage: 
            self.parent_manage.disconnect_signal_selection_changed()           
        
        for i in range(len(self.layers)):
            layer = self.layers[i]
            if self.iface.legendInterface().isLayerVisible(layer):
                # if (i == len(self.layers) - 1):
                if self.parent_manage:
                    self.parent_manage.connect_signal_selection_changed(self.table_object)

                # Selection by rectangle
                if rectangle:
                    if selected_rectangle is None:
                        selected_rectangle = self.canvas.mapSettings().mapToLayerCoordinates(layer, rectangle)
                    # If Ctrl+Shift clicked: remove features from selection
                    if key == (Qt.ControlModifier | Qt.ShiftModifier):
                        layer.selectByRect(selected_rectangle, layer.RemoveFromSelection)
                    # If Ctrl clicked: add features to selection
                    elif key == Qt.ControlModifier:
                        layer.selectByRect(selected_rectangle, layer.AddToSelection)
                    # If Ctrl not clicked: add features to selection
                    else:
                        layer.selectByRect(selected_rectangle, layer.AddToSelection)

                # Selection one by one
                else:
                    x = e.pos().x()
                    y = e.pos().y()
                    eventPoint = QPoint(x, y)
                    (retval, result) = self.snapper.snapToBackgroundLayers(eventPoint)  #@UnusedVariable
                    if result:
                        # Check feature
                        for snap_point in result:
                            # Get the point. Leave selection
                            snapp_feat = next(snap_point.layer.getFeatures(QgsFeatureRequest().setFilterFid(snap_point.snappedAtGeometry)))   #@UnusedVariable
                            snap_point.layer.select([snap_point.snappedAtGeometry])

        self.rubber_band.hide()
Exemplo n.º 45
0
    def drawSprite(self, qp):
        pos = self._sprite.pos
        dra = self._sprite.drawable()
        p = qp.pen()
        p.setWidth(10)
        nx = pos.x - 5
        ny = 580-pos.y

        # images
        url = dra
        qi = QPixmap(url)
        pnt = QPoint(nx,ny)

        qp.drawPixmap(pnt, qi);
 def loadApplicationSettings(self):
     settings = QSettings()
     size = settings.value("MainWindow/Size", QSize(800, 600))
     pos = settings.value("MainWindow/Position", QPoint(10, 10))
     state = settings.value("MainWindow/State")
     locked = settings.value("MainWindow/ViewsLocked", False)
     if isinstance(size, QVariant): size = size.toSize()
     if isinstance(pos, QVariant): pos = pos.toPoint()
     if isinstance(state, QVariant): state = state.toByteArray()
     if isinstance(locked, QVariant): locked = locked.toBool()
     self.resize(size)
     self.move(pos)
     self.restoreState(state)
     self.ui.actionLocked.setChecked(bool(locked))
Exemplo n.º 47
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.mCenter = QPoint(0, 0)
        self.mRadius = 0
        self.mEchoLines = []
        self.mEchoLinesIndex = 0

        self.SetCenter(QPoint(0, 0))
        self.SetRadius(0)
        self.SetRange("50m")
        self.SetHdt(0)

        # 制作回波线角度表,用于提升性能
        step = 2.0 * gPI / gEchoLineCountAFrame
        self.mCosAngleTable = []
        self.mSinAngleTable = []
        for i in range(0, gEchoLineCountAFrame):
            self.mCosAngleTable.append(0)
            self.mSinAngleTable.append(0)
        for i in range(0, gEchoLineCountAFrame):
            angle = i * step - 90 * g1Deg
            self.mCosAngleTable[i] = math.cos(angle)
            self.mSinAngleTable[i] = math.sin(angle)
Exemplo n.º 48
0
    def paintEvent(self, event):
        if self.__pixmap.isNull():
            return

        sourcerect = QRect(QPoint(0, 0), self.__pixmap.size())
        pixsize = QSizeF(self.__pixmap.size())
        rect = self.contentsRect()
        pixsize.scale(QSizeF(rect.size()), Qt.KeepAspectRatio)
        targetrect = QRectF(QPointF(0, 0), pixsize)
        targetrect.moveCenter(QPointF(rect.center()))
        painter = QPainter(self)
        painter.setRenderHint(QPainter.SmoothPixmapTransform)
        painter.drawPixmap(targetrect, self.__pixmap, QRectF(sourcerect))
        painter.end()
Exemplo n.º 49
0
    def paint(self, painter, option, index):
        if index.model() is None:
            return
        image = index.model().clusters[index.row()].image
        painter.save()

        if option.state & QStyle.State_Selected:
            pen = QPen(Qt.black, 2)
            painter.setPen(pen)
            painter.drawRect(option.rect.adjusted(+2, +2, -2, -2))

        painter.drawPixmap(QPoint(option.rect.x() + 5,
                                  option.rect.y() + 5), image)
        painter.restore()
Exemplo n.º 50
0
	def mousePressEvent(self, event):
		if event.buttons() == Qt.LeftButton:
			comps=self.targetComps(event.pos())
			if not comps:
				return
			comp = comps[-1]
			index=self.components.index(comp)
			comp=copy.copy(comp)
			### delete the component
			del self.components[index]
			### delete broken snappoints
			brokensnapIndexes=[]
			for sp in comp.snapPoints:
				for i in range(len(self.snapped)):
					s = self.snapped[i]
					if sp.pos() == s.pos():
						brokensnapIndexes.append(i)
			# assert: brokensnapIndexes is a sorted list, ascending
			for i in brokensnapIndexes[::-1]: # descending iteration
				del self.snapped[i]
			### deletions done, erase the images
			self.update(comp.rect)

			comp.hotspot=QPoint(event.pos() - comp.rect.topLeft())
			drag=comp.makeDrag(self)

			if drag.exec_(Qt.MoveAction) != Qt.MoveAction:
				# the drag failed, restore the previous state
				self.components.insert(index, comp)
				self.connectSnaps()
				self.update()
			else:
				self.blocksChanged.emit()

		elif event.buttons() == Qt.RightButton:
			b=self.blockAt(event.pos())
			if b:
				i = self.components.index(b)
				if isinstance(b, InputComponent):
					box=self.boxModel
					if isinstance(b, TimeComponent):
						d=InputDialog(self, box=box)
						d.manageTime(b, self)
					elif isinstance(b, VoltageComponent):
						d=InputDialog(self, box=box)
						d.manageVoltage(b, self)
					elif isinstance(b, TransmitComponent):
						d=TransmitDialog(self)
						d.manageTransmit(b, self)
		return
Exemplo n.º 51
0
 def select_unscaled(self):
     '''Selects, if possible, a 96 x 96 square centered around the original
     image. In this way the image won't be scaled but won't take up all the 
     96 x 96 area.'''
     # pylint: disable=C0103
     pix_size = self._pixmap.size()
     if pix_size.width() <= 96 and pix_size.height() <= 96:
         viewport_size = self.size()
         x = (viewport_size.width() - 96) / 2
         y = (viewport_size.height() - 96) / 2
         self._selection_rect.setTopLeft(QPoint(x, y))
         self._selection_rect.setSize(QSize(96, 96))
         self.update()
         self.selection_changed.emit()
Exemplo n.º 52
0
 def restoreGuiSettings(self):
     settings = QSettings('sim.informatik.tu-darmstadt.de', 'Servo Tool')
     settings.beginGroup('MainWindow')
     self.restoreState(
         settings.value('state', QVariant(QByteArray())).toByteArray())
     self.resize(settings.value('size', QVariant(QSize(800, 600))).toSize())
     self.move(settings.value('pos', QVariant(QPoint(200, 200))).toPoint())
     self.splitter.restoreState(
         settings.value('splitter', QVariant(QByteArray())).toByteArray())
     self.splitter_2.restoreState(
         settings.value('splitter_2', QVariant(QByteArray())).toByteArray())
     self.spinLogLevel.setValue(
         settings.value('logLevel', QVariant(3)).toInt()[0])
     settings.endGroup()
Exemplo n.º 53
0
    def adjust_image_origin(self):
        '''Recalculates the top left corner's image position, so the
        image is painted centered'''
        # pylint: disable=C0103
        new_size = self.size() / self._zoom
        pix_size = self._pixmap.size()

        dx = (new_size.width() - pix_size.width()) / 2
        dy = (new_size.height() - pix_size.height()) / 2

        new_image_origin = QPoint(dx, dy)
        self._selection_rect.translate(new_image_origin - self._image_origin)
        self._image_origin = new_image_origin
        log.info('image origin: %s' % new_image_origin)
Exemplo n.º 54
0
    def nextPointByTarget(self, route, target, orientation):
        """ Adds a point to 'route', so the route approaches to the 'target' point in a specific 'orientation'.
        
        This means that the added point and 'target' have one coordinate in common.
        If 'orientation' points in horizontal direction (left or right) the x components will be equal.
        If 'orientation' points in vertical direction (up or down) the y components will be equal.
        """
        if len(route) < 1:
            logging.error(
                "PointToPointConnection.nextPointByTarget() - Can not calculate next point for empty route."
            )
            return

        start = route[len(route) - 1]

        if orientation == self.DrawOrientation.HORIZONTAL:
            return QPoint(target.x(), start.y())
        elif orientation == self.DrawOrientation.VERTICAL:
            return QPoint(start.x(), target.y())
        else:
            logging.error(
                "PointToPointConnection.nextPointByTarget() - Unknown DrwaOrientation."
            )
Exemplo n.º 55
0
 def drag(self, tile=None, meld=None):
     """returns a drag object"""
     drag = QDrag(self)
     mimeData = MimeData(tile, meld)
     drag.setMimeData(mimeData)
     tile = tile or meld[0]
     graphics = tile.graphics
     tRect = graphics.boundingRect()
     tRect = self.viewportTransform().mapRect(tRect)
     pmapSize = QSize(tRect.width() * graphics.scale(), tRect.height() * graphics.scale())
     pMap = graphics.pixmapFromSvg(pmapSize)
     drag.setPixmap(pMap)
     drag.setHotSpot(QPoint(pMap.width()/2, pMap.height()/2))
     return drag
Exemplo n.º 56
0
    def handleMousePress(self, event):

        event.ignore()

        if event.button() != Qt.LeftButton:
            return

        if event in self.d.ignoreList:
            self.d.ignoreList.remove(event)
            return

        if self.d.state == FlickablePrivate.Steady:
            event.accept()
            self.d.state = FlickablePrivate.Pressed
            self.d.pressPos = QPoint(event.pos())

        elif self.d.state == FlickablePrivate.AutoScroll:
            event.accept()
            self.d.state = FlickablePrivate.Stop
            self.d.speed = QPoint(0, 0)
            self.d.pressPos = QPoint(event.pos())
            self.d.offset = self.scrollOffset()
            self.d.ticker.stop()
Exemplo n.º 57
0
class Circle():
    def __init__(self, diameter, x, y):
        self.diameter = diameter
        self.radius = math.floor(diameter / 2.0)
        self.center = QPoint(x, y)

    def drawCircle(self, event, qp):
        qp.setBrush(QtGui.QColor(34, 34, 200))
        qp.drawEllipse(self.center, self.radius, self.radius)

    def isClicked(self, pos):
        result = math.pow((pos.x() - self.center.x()), 2) + math.pow(
            (pos.y() - self.center.y()), 2)
        if result <= math.pow(self.radius, 2):
            return True
        else:
            return False

    def x(self):
        return self.center.x()

    def y(self):
        return self.center.y()
Exemplo n.º 58
0
    def handChange(self):

        self.side = min(self.width(), self.height())
        self.hand = (max(self.side / 200, 4), max(self.side / 100,
                                                  8), max(self.side / 40, 30))
        self.hourHand = QPolygon([
            QPoint(self.hand[0], self.hand[1]),
            QPoint(-self.hand[0], self.hand[1]),
            QPoint(0, -self.hand[2])
        ])
        self.minuteHand = QPolygon([
            QPoint(self.hand[0], self.hand[1]),
            QPoint(-self.hand[0], self.hand[1]),
            QPoint(0, -self.hand[2] * 2)
        ])
        self.secondHand = QPolygon([
            QPoint(self.hand[0], self.hand[1]),
            QPoint(-self.hand[0], self.hand[1]),
            QPoint(0, -self.hand[2] * 3)
        ])
Exemplo n.º 59
0
 def getTileRect(self,
                 renderContext,
                 zoom,
                 x,
                 y,
                 sdx=1.0,
                 sdy=1.0,
                 toInt=True):
     """ get tile pixel rect in the render context """
     r = self.layerDef.getTileRect(zoom, x, y)
     map2pix = renderContext.mapToPixel()
     topLeft = map2pix.transform(r.xMinimum(), r.yMaximum())
     bottomRight = map2pix.transform(r.xMaximum(), r.yMinimum())
     if toInt:
         return QRect(
             QPoint(round(topLeft.x() * sdx), round(topLeft.y() * sdy)),
             QPoint(round(bottomRight.x() * sdx),
                    round(bottomRight.y() * sdy)))
     else:
         return QRectF(
             QPointF(topLeft.x() * sdx,
                     topLeft.y() * sdy),
             QPointF(bottomRight.x() * sdx,
                     bottomRight.y() * sdy))
Exemplo n.º 60
0
    def kineticAddDelta(self, delta, orientation=Qt.Vertical):
        """Add a kinetic delta to an already started kinetic move."""
        if orientation == Qt.Vertical:
            s = self._kineticData._speed.y()
        else:
            s = self._kineticData._speed.x()

        # Get the remaining scroll amount.
        currentSpeed = abs(s)
        leftToScroll = (currentSpeed + 1) * currentSpeed // 2
        if s < 0:
            leftToScroll *= -1
        leftToScroll += delta

        s = (sqrt(1 + 8 * abs(leftToScroll)) - 1) / 2
        if leftToScroll < 0:
            s = -s

        if orientation == Qt.Vertical:
            speed = QPoint(self._kineticData._speed.x(), s)
        else:
            speed = QPoint(s, self._kineticData._speed.y())

        self.kineticStart(speed)