def mouseMoveEvent(self, ev): if self.model.get_task_mouse_para(): curser_pos = self.mapToGlobal(QtCore.QPoint(ev.x(), ev.y())) curser_pos_x = curser_pos.x() curser_pos_y = curser_pos.y() x, y = self.pointer.filter(curser_pos_x, curser_pos_y) QCursor.setPos(x, y)
def mouseMoveEvent(self, event): """ QWidget.mouseMoveEvent(QMouseEvent) :type event: PyQt5.QtGui.QMouseEvent.QMouseEvent """ if not self.ready: return if self.move_skip: self.move_skip = False return if not self.start_pos: self.start_pos = event.globalPos() if self.left or self.right: self.move_skip = True QCursor.setPos(self.start_pos) else: self.start_pos = None if self.start_pos is not None: self._move_mouse(self.start_pos.x() - event.globalPos().x(), self.start_pos.y() - event.globalPos().y(), str(self.left).lower(), str(self.midle).lower(), str(self.right).lower())
def keyPressEvent(self, event): direction = None key = event.key() if key == Qt.Key_Escape: QCursor.setPos(self.originalCursorPosition) sys.exit() elif key == Qt.Key_Space: self.close() # TODO Do this nicer ... os.system('xdotool click 1') elif key == Qt.Key_H: direction = 'horizontal' choice = 0 elif key == Qt.Key_L: direction = 'horizontal' choice = 1 elif key == Qt.Key_K: direction = 'vertical' choice = 0 elif key == Qt.Key_J: direction = 'vertical' choice = 1 if direction: self.currentChoice.removeEventFilter(self) self.currentChoice = self.currentChoice.split(direction, choice) self.currentChoice.installEventFilter(self)
def recenter(self, pt=None, world=False): if pt is None: pt = self._mousePos ctr = self._transform.inverted()[0].map(self.rect().center()) if not world: pt = self._transform.inverted()[0].map(pt) ctr -= pt self._transform.translate(ctr.x(), ctr.y()) # move cursor to center of window QCursor.setPos(self.mapToGlobal(self.rect().center())) self.update()
def eventFilter(self, viewport, ev): """Handles multiple events from the viewport. * update on View scroll * show the magnifier on left click+modifier """ if ev.type() == QEvent.UpdateRequest: self.update() elif (not self.isVisible() and ev.type() == QEvent.MouseButtonPress and ev.modifiers() == self.showmodifier and ev.button() == self.showbutton): # show and drag while button pressed: DRAG_SHORT self._dragging = DRAG_SHORT self.moveCenter(ev.pos()) self.show() viewport.setCursor(Qt.BlankCursor) return True elif self._dragging == DRAG_SHORT: if ev.type() == QEvent.MouseMove: if ev.buttons() == self.showbutton | self.resizebutton: # DRAG_SHORT is busy, both buttons are pressed: resize! if self._resizepos == None: self._resizepos = ev.pos() self._resizewidth = self.width() dy = 0 else: dy = (ev.pos() - self._resizepos).y() g = self.geometry() w = max(self.MIN_SIZE, self._resizewidth + 2 * dy) self.resize(w, w) self.moveCenter(g.center()) else: # just drag our center self.moveCenter(ev.pos()) view = self.parent().parent() view.scrollForDragging(ev.pos()) return True elif ev.type() == QEvent.MouseButtonRelease: if ev.button() == self.showbutton: # left button is released, stop dragging and/or resizing, hide viewport.unsetCursor() self.hide() self._resizepos = None self._dragging = False view = self.parent().parent() view.stopScrolling() # just if needed elif ev.button() == self.resizebutton: # right button is released, stop resizing, warp cursor to center self._resizepos = None QCursor.setPos(viewport.mapToGlobal(self.geometry().center())) return True return False
def reset_mouse_position(self): import matplotlib as mpl if mpl.get_backend() in ("Qt4Agg", "TkAgg"): pass elif mpl.get_backend() == "Qt5Agg": from PyQt5.QtGui import QCursor import pylab as pl screenCoords = pl.gca().transAxes.transform((0.5, 0.5)).astype(int) screenCoords += pl.get_current_fig_manager().window.geometry( ).getRect()[:2] QCursor.setPos(*tuple(screenCoords))
def setQCursorPos(self): line = self.posF.readline().decode('utf-8') xy = line.strip() xy = xy.split(" ") # print(len(xy)) if len(xy) == 2: print(xy) # self.x = self.move_avg_rate * self.x + (1-self.move_avg_rate) * int(xy[0]) # self.y = self.move_avg_rate * self.y + (1-self.move_avg_rate) * int(xy[1]) # QCursor.setPos(self.x, self.y) QCursor.setPos(int(xy[0]), int(xy[1]))
def eventFilter(self, viewport, ev): """Handles multiple events from the viewport. * update on View scroll * show the magnifier on left click+modifier """ if ev.type() == QEvent.UpdateRequest: self.update() elif (not self.isVisible() and ev.type() == QEvent.MouseButtonPress and ev.modifiers() == self.showmodifier and ev.button() == self.showbutton): # show and drag while button pressed: DRAG_SHORT self._dragging = DRAG_SHORT self.moveCenter(ev.pos()) self.show() viewport.setCursor(Qt.BlankCursor) return True elif self._dragging == DRAG_SHORT: if ev.type() == QEvent.MouseMove: if ev.buttons() == self.showbutton | self.resizebutton: # DRAG_SHORT is busy, both buttons are pressed: resize! if self._resizepos == None: self._resizepos = ev.pos() self._resizewidth = self.width() dy = 0 else: dy = (ev.pos() - self._resizepos).y() g = self.geometry() w = max(self.MIN_SIZE, self._resizewidth + 2 * dy) self.resize(w, w) self.moveCenter(g.center()) else: # just drag our center self.moveCenter(ev.pos()) view = self.parent().parent() view.scrollForDragging(ev.pos()) return True elif ev.type() == QEvent.MouseButtonRelease: if ev.button() == self.showbutton: # left button is released, stop dragging and/or resizing, hide viewport.unsetCursor() self.hide() self._resizepos = None self._dragging = False view = self.parent().parent() view.stopScrolling() # just if needed elif ev.button() == self.resizebutton: # right button is released, stop resizing, warp cursor to center self._resizepos = None QCursor.setPos( viewport.mapToGlobal(self.geometry().center())) return True return False
def TiepTuc(self): self.ui.lineEdit_5.setText(None) self.ui.lineEdit_3.setText(None) self.ui.lineEdit_2.setText(None) self.ui.lineEdit.setText(None) self.ui.lineEdit_4.setText(None) self.ui.label_7.setText(None) pos = self.mapFromGlobal(self.ui.lineEdit_2.pos()) pos1 = abs(pos.x() - 475) pos2 = abs(pos.y() - 80) QCursor.setPos(pos1, pos2) self.ui.lineEdit_2.setFocus()
def toggleGrabMouse(self, grab: bool): self.actionGrabKeyboard.setChecked(grab) self.mouse_grabbed = grab if grab: self.setCursor(Qt.BlankCursor) self.mouse_center = self.getMouseCenter() QCursor.setPos(self.mouse_center) self.setMouseTracking(True) self.grabMouse() else: self.setCursor(Qt.ArrowCursor) self.setMouseTracking(False) self.releaseMouse()
def dragLeaveEvent(self, event): """Implements dragLeaveEvent() method.""" # Keep cursor on the board while dragging cursor = QCursor() position = cursor.pos() topLeft = self.mapToGlobal( self.geometry().topLeft()) - self.geometry().topLeft() bottomRight = self.mapToGlobal( self.geometry().bottomRight()) - self.geometry().topLeft() bound = lambda x, l, u: l if x < l else u if x > u else x x = bound(position.x(), topLeft.x() + 1, bottomRight.x() - 1) y = bound(position.y(), topLeft.y() + 1, bottomRight.y() - 1) if x != position.x() or y != position.y(): cursor.setPos(x, y)
def eventFilter(self, viewport, ev): """Handle events on the viewport of the View.""" view = viewport.parent() if not self.isVisible(): if (ev.type() == QEvent.MouseButtonPress and ev.modifiers() == self.showmodifier and ev.button() == self.showbutton): # show and drag while button pressed: DRAG_SHORT self.startShortDrag(ev.pos()) return True elif ev.type() == QEvent.Paint: # if the viewport is painted, also update self.update() elif self._dragging == DRAG_SHORT: if ev.type() == QEvent.MouseButtonPress: if ev.button() == self.resizebutton: return True elif ev.type() == QEvent.MouseMove: if ev.buttons() == self.showbutton | self.resizebutton: # DRAG_SHORT is busy, both buttons are pressed: resize! if self._resizepos == None: self._resizepos = ev.pos() self._resizewidth = self.width() dy = 0 else: dy = (ev.pos() - self._resizepos).y() g = self.geometry() w = min(max(self.MIN_SIZE, self._resizewidth + 2 * dy), self.MAX_SIZE) self.resize(w, w) self.moveCenter(g.center()) else: # just drag our center self.moveCenter(ev.pos()) view.scrollForDragging(ev.pos()) return True elif ev.type() == QEvent.MouseButtonRelease: if ev.button() == self.showbutton: # left button is released, stop dragging and/or resizing, hide self.endShortDrag() elif ev.button() == self.resizebutton: # right button is released, stop resizing, warp cursor to center self._resizepos = None QCursor.setPos( viewport.mapToGlobal(self.geometry().center())) ev.accept() return True elif ev.type() == QEvent.ContextMenu: self.endShortDrag() return False
def mouseMoved(self, event): az_sensivity = 0.03 pol_sensivity = 0.03 if self.mouse_grabbed: delta = event.globalPos() - self.mouse_center QCursor.setPos(self.mouse_center) if event.buttons() == Qt.RightButton: self.moveCameraAroundCenter(az=delta.y() * az_sensivity, pol=delta.x() * pol_sensivity) else: self.moveCamera(az=delta.y() * az_sensivity, pol=delta.x() * pol_sensivity) else: super().mouseMoveEvent(event)
def GetMousePress(self, event): self.FixOverlays() self.mouseX0 = event.x() self.mouseY0 = event.y() self.mouseX = self.mouseX0 self.mouseY = self.mouseY0 if event.button() == 1 and self.drawing and self.camOpen: self.mouseDrawingDown = True self.DrawMeasOverlay() elif event.button() == 1 and self.marking and self.camOpen: self.mouseMarkingDown = True self.DrawMarkerOverlay(self.markersizeSpin.value()) if event.button() == 2: self.mouseGoDown = True self.mouseX0 = int(self.camView.width() / 2) self.mouseY0 = int(self.camView.height() / 2) self.mouseX = self.mouseX0 self.mouseY = self.mouseY0 dx = self.mouseX - self.mouseX0 dy = self.mouseY - self.mouseY0 self.motors.CalculateContParams( 1, 2 * dx / self.camView.width(), 0.008875 * np.exp(0.04721 * self.multiDial.value())) self.motors.CalculateContParams( 2, 2 * dy / self.camView.height(), 0.008875 * np.exp(0.04721 * self.multiDial.value())) self.movXTimer.setInterval(self.motors.xWait * 1000) self.movYTimer.setInterval(self.motors.yWait * 1000) self.movXTimer.start() self.movYTimer.start() if self.motors.xOK: self.xOK.setPixmap(QPixmap("yellow_led.png")) if self.motors.yOK: self.yOK.setPixmap(QPixmap("yellow_led.png")) self.getcontposTimer.start() self.DrawGoOverlay() cursor = QCursor() cursor.setShape(Qt.SizeAllCursor) cursor.setPos( self.camOverlay.mapToGlobal(QPoint(self.mouseX, self.mouseY))) QApplication.setOverrideCursor(cursor)
def GetMouseMove(self, event): mX = event.x() mY = event.y() lock = False if mX < 0: mX = 0 lock = True if mX > self.camView.width(): mX = self.camView.width() lock = True if mY < 0: mY = 0 lock = True if mY > self.camView.height(): mY = self.camView.height() lock = True if lock: cursor = QCursor() cursor.setPos(self.camOverlay.mapToGlobal(QPoint(mX, mY))) QApplication.setOverrideCursor(cursor) self.mouseX = mX self.mouseY = mY if self.mouseDrawingDown and self.camOpen: self.DrawMeasOverlay() elif self.mouseMarkingDown and self.camOpen: self.DrawMarkerOverlay(self.markersizeSpin.value()) elif self.mouseGoDown: self.DrawGoOverlay() dx = self.mouseX - self.mouseX0 dy = -(self.mouseY - self.mouseY0) self.motors.CalculateContParams( 1, 2 * dx / self.camView.width(), 0.008875 * np.exp(0.04721 * self.multiDial.value())) self.motors.CalculateContParams( 2, 2 * dy / self.camView.height(), 0.008875 * np.exp(0.04721 * self.multiDial.value())) self.movXTimer.setInterval(self.motors.xWait * 1000) self.movYTimer.setInterval(self.motors.yWait * 1000)
def _fix_cursor(self, from_index, to_index): """Fix mouse cursor position to adjust for different tab sizes.""" # The direction is +1 (moving to the right) or -1 (moving to the left) direction = abs(to_index - from_index) / (to_index - from_index) tab_width = self.dock_tabbar.tabRect(to_index).width() tab_x_min = self.dock_tabbar.tabRect(to_index).x() tab_x_max = tab_x_min + tab_width previous_width = self.dock_tabbar.tabRect(to_index - direction).width() delta = previous_width - tab_width if delta > 0: delta = delta * direction else: delta = 0 cursor = QCursor() pos = self.dock_tabbar.mapFromGlobal(cursor.pos()) x, y = pos.x(), pos.y() if x < tab_x_min or x > tab_x_max: new_pos = self.dock_tabbar.mapToGlobal(QPoint(x + delta, y)) cursor.setPos(new_pos)
def mouseMoveEvent(self, event): if self.restraining_mouse: # update global center in case window moved # int casting protects from stray .5 from odd screen sizes self.center_x = self.geometry().x() + int(self.width() / 2) self.center_y = self.geometry().y() + int(self.height() / 2) cursor_pos = event.globalPos() if self.center_x == cursor_pos.x() and self.center_y == cursor_pos.y(): return # cursor was re-centered. else: # get & normalize mouse movement move = [int(cursor_pos.x() - self.center_x), int(cursor_pos.y() - self.center_y)] # copy gpu values look = self.cam_quat.apply(*[0, 0, 1]) # pointer = mm.Quaternion.from_position(move[0],0,move[1]).normalize() norm = m.sqrt(move[0] * move[0] + move[1] * move[1]) x_p = -move[0] / norm y_p = move[1] / norm pointer = self.cam_quat.apply(*[x_p, y_p, 0]) # side = self.cam_quat.apply(1,0,0) mouse_look_prod = np.cross(look, pointer) mouse_norm = np.linalg.norm(mouse_look_prod) if mouse_norm != 0: mouse_look_prod = (mouse_look_prod / mouse_norm).tolist() else: mouse_look_prod = mouse_look_prod.tolist() # print(norm) angle = norm * (self.fov_y / self.height() / 2) self.cam_quat = self.cam_quat * mm.Quaternion.from_axis(*mouse_look_prod, angle) self.cam_quat.normalize() QCursor.setPos(self.center_x, self.center_y) self.repaint()
def move_mouse(self, x, y): QCursor.setPos(x, y) self.delay(self.MOUSE_MOVE_DELAY)
def mouseMoveEvent(self, e): if self._drag_button: dx = self._last_pos.x() - e.x() if dx > self.width() / 2: dx = -self.width() + dx elif dx < -self.width() / 2: dx = self.width() + dx dy = self._last_pos.y() - e.y() if dy > self.height() / 2: dy = -self.height() + dy elif dy < -self.height() / 2: dy = self.height() + dy if (QApplication.keyboardModifiers() & Qt.ControlModifier) == Qt.ControlModifier: f = 25 dx = quantized_floor(abs(dx), f) * sign(dx) dy = quantized_floor(abs(dy), f) * sign(dy) self._last_pos = QPoint(self._last_pos.x() - dx, self._last_pos.y() - dy) else: self._last_pos = e.pos() if self._drag_button == Qt.RightButton: if self._shift_down: # spin self._view[:3, :3] = rotz( dy / 100 * pi / 4)[:3, :3] * self._view[:3, :3] else: # zoom in/out dy = max(-10, dy) dy = min(10, dy) self._view *= scale([(100 - dy) / 100] * 3) self.update() elif (self._drag_button == Qt.LeftButton and self._shift_down) or self._drag_button == Qt.MiddleButton: # pan self._view = translate([-dx / 200, dy / 200, 0]) * self._view self.update() elif self._drag_button == Qt.LeftButton and not self._shift_down: # tilt self._view[:3, :3] = roty(-dx / 50 * pi / 4)[:3, :3] * rotx( -dy / 50 * pi / 4)[:3, :3] * self._view[:3, :3] self.update() wrap = [None, None] if e.x() + 1 >= self.width(): wrap[0] = e.x() - self.width() + 2 elif e.x() <= 0: wrap[0] = e.x() + self.width() - 2 if e.y() + 1 >= self.height(): wrap[1] = e.y() - self.height() + 2 elif e.y() <= 0: wrap[1] = e.y() + self.height() - 2 if wrap[0] is not None or wrap[1] is not None: if wrap[0] is None: wrap[0] = e.x() if wrap[1] is None: wrap[1] = e.y() self._last_pos = QPoint(*wrap) QCursor.setPos(self.mapToGlobal(self._last_pos))
def mouseMoveEvent(self, QMouseEvent): # Transform position into scene position scenePos = self.view.mapToScene(QMouseEvent.pos()) if self.leftMouseButtonHold: if self.dragMode == "Drag": # Set the new mouse cursor self.view.setCursor(QCursor(Qt.ClosedHandCursor)) # Calculate the movement for the view translation offset = self.previousGlobalMousePos - QMouseEvent.pos() self.previousGlobalMousePos = QMouseEvent.pos() offset *= 1 / self.view.getScale() self.view.translate(-offset.x(), -offset.y()) elif self.dragMode == "Selection": # Check if the user has left the scene with the mouse, if yes, translate accordingly if QMouseEvent.pos().x() > self.view.viewport().width( ) and QMouseEvent.pos().y() > self.view.viewport().height(): QCursor.setPos( self.view.mapToGlobal( QPoint(self.view.viewport().width(), self.view.viewport().height()))) self.view.translate(-3 * self.view.getScale(), -3 * self.view.getScale()) elif QMouseEvent.pos().x() < 0 and QMouseEvent.pos().y() < 0: QCursor.setPos(self.view.mapToGlobal(QPoint(1, 1))) self.view.translate(3 * self.view.getScale(), 3 * self.view.getScale()) elif QMouseEvent.pos().x() > self.view.viewport().width( ) and QMouseEvent.pos().y() < 0: QCursor.setPos( self.view.mapToGlobal( QPoint(self.view.viewport().width(), 1))) self.view.translate(-3 * self.view.getScale(), 3 * self.view.getScale()) elif QMouseEvent.pos().x() < 0 and QMouseEvent.pos().y( ) > self.view.viewport().height(): QCursor.setPos( self.view.mapToGlobal( QPoint(1, self.view.viewport().height()))) self.view.translate(3 * self.view.getScale(), -3 * self.view.getScale()) elif QMouseEvent.pos().x() > self.view.viewport().width(): QCursor.setPos( self.view.mapToGlobal( QPoint(self.view.viewport().width(), QMouseEvent.pos().y()))) self.view.translate(-3 * self.view.getScale(), 0) elif QMouseEvent.pos().y() > self.view.viewport().height(): QCursor.setPos( self.view.mapToGlobal( QPoint(QMouseEvent.pos().x(), self.view.viewport().height()))) self.view.translate(0, -3 * self.view.getScale()) elif QMouseEvent.pos().x() < -1: QCursor.setPos( self.view.mapToGlobal(QPoint(1, QMouseEvent.pos().y()))) self.view.translate(3 * self.view.getScale(), 0) elif QMouseEvent.pos().y() < -1: QCursor.setPos( self.view.mapToGlobal(QPoint(QMouseEvent.pos().x(), 1))) self.view.translate(0, 3 * self.view.getScale()) # Map origin coordinates to current view coordinates clickOriginView = self.view.mapFromScene(self.clickOrigin) # Calculate the new top left point as well as width and height topLeft = QPoint( min(clickOriginView.x(), self.view.mapFromGlobal(QCursor.pos()).x()), min(clickOriginView.y(), self.view.mapFromGlobal(QCursor.pos()).y())) size = QSize( abs(clickOriginView.x() - self.view.mapFromGlobal(QCursor.pos()).x()), abs(clickOriginView.y() - self.view.mapFromGlobal(QCursor.pos()).y())) self.rubberBand.setGeometry(QRect(topLeft, size)) elif self.dragMode == "Items": if self.scene.currentlyConnecting is not None and not self.disabled: self.scene.currentlyConnecting.updateMousePosition( scenePos) else: # Moving should only be enabled for node items if isinstance(self.pressedItem, NodeItem): if self.pressedItem.isSelected(): # Cancel the selection clearing if self.clearSelection: self.clearSelection = False elif self.removeFromSelection: self.removeFromSelection = False self.removeFromSelectionItemID = None elif self.setSelectionToItem is not None: self.setSelectionToItem = None else: # if the selected item was not selected before self.networkManager.clearSelection() self.networkManager.setSelection( self.scene.itemAt(self.setSelectionToItem, QTransform()).getLayerID()) self.clearSelection = False self.removeFromSelection = False self.removeFromSelectionItemID = None self.setSelectionToItem = None # Calculate the change in mouse position currentLocalMousePos = scenePos translation = currentLocalMousePos - self.previousLocalMousePos self.previousLocalMousePos = currentLocalMousePos # Move all selected Elements according to mouse movement resetMouse = self.translateItems( translation.x(), translation.y()) if resetMouse: QCursor.setPos(QCursor.pos().x() - translation.x(), QCursor.pos().y() - translation.y()) else: if self.lastHoveredItem != self.scene.itemAt( scenePos, QTransform()): # If no button is held down, change mouse pointer according to item it hovers over if self.scene.itemAt(scenePos, QTransform()) is None: if QMouseEvent.modifiers() & Qt.ControlModifier: self.view.setCursor(QCursor(Qt.CrossCursor)) self.dragMode = "Selection" else: self.view.setCursor(QCursor(Qt.OpenHandCursor)) self.dragMode = "Drag" else: self.view.setCursor(QCursor(Qt.ArrowCursor)) self.dragMode = "Items" # Set a new last hovered item self.lastHoveredItem = self.scene.itemAt(scenePos, QTransform())
def mousePressEvent(self, event): if not self.restraining_mouse: self.restraining_mouse = True self.center_x = self.geometry().x() + int(self.width() / 2) self.center_y = self.geometry().y() + int(self.height() / 2) QCursor.setPos(self.center_x, self.center_y)
class Tracker(QDialog): def __init__(self, parent=None, hidden=True): super(Tracker, self).__init__(parent) self.hidden = hidden self.mouseController = MouseController() self.origMouseSpeed = self.mouseController.getSpeed() self.origAcceleration = self.mouseController.getAcceleration() self.zeroVariables() self.cursor = QCursor() self.initUI() def initUI(self): ''' Setup GUI elements of mouse tracker screen. ''' grid = QGridLayout() grid.setContentsMargins(80, 80, 80, 80) self.displayBox = ScaleDisplayWidget() grid.addWidget(self.displayBox, 0, 0, Qt.AlignTop) grid.addWidget(QLabel(''), 0, 1, Qt.AlignTop) self.setLayout(grid) self.setWindowTitle('Scale') self.showFullScreen() self.setModal(True) QMessageBox.information(self, 'Tracing Prompt', 'Begin tracing scale', QMessageBox.Ok) def getCenter(self): ''' Find the center point of the window by adding half the distance of the height and width to the absolute x, y location of the window. ''' #Reference to geometry of screen and cursor geo = self.geometry() cur = self.cursor #Get x, y coords of the screen, left upper corner x_pos = geo.x() y_pos = geo.y() #Get width and height of screen distances from left upper corner width = geo.width() height = geo.height() #Find center point of screen x_center = x_pos + (width // 2) y_center = y_pos + (height // 2) return Point(x_center, y_center) def getCursorPos(self): ''' Return the current position of the cursor relative to the upper left corner of the window. ''' x = self.cursor.pos().x() y = self.cursor.pos().y() return Point(x, y) def getDX(self): ''' Calculate distance from center in x direction ''' center = self.getCenter() curPos = self.getCursorPos() return curPos.x - center.x def getDY(self): ''' Calculate distance from center in y direction ''' center = self.getCenter() curPos = self.getCursorPos() #reverse y for inverted y-axis return center.y - curPos.y def getDistance(self, dx, dy): ''' Calculate straight line distance from point a to b using net distance in x and y direction Args: dx (float): total distance in pixels traveled in x direction dy (float): total distance in pixels traveled in y direction Returns: Total distance ''' try: return round(math.sqrt(dx**2 + dy**2), 6) except: return 0 def getBearing(self, dx, dy): ''' Calculate the bearing of the mouse movement Args: dx (float): total distance in pixels traveled in x direction dy (float): total distance in pixels traveled in y direction Returns: bearing (float): bearing in degrees ''' try: bearing = math.degrees(math.atan2(dy, dx)) except Exception as e: print('Error: getBearing:', e.__class__.__name__) #do something to handle error return 1 else: #shift bearing so 0 degrees is now grid north bearing = (360 + (90 - bearing)) % 360 return round(bearing, 6) def convert(self, dist, scale): ''' Convert distance in pixels to unit of measurement (km, mi, etc...) Args: dist (float): Euclidean distances from start to end point scale (int): scale to convert pixels to proper units Returns: convDist (float): converted mouse movement in correct unit of measurement ''' try: convDist = dist / scale except Exception as e: print('Error: convert:', e.__class__.__name__) #do something to handle error return 1 else: return round(convDist, 6) def newLocation(self, ref, dist, bearing): ''' Computes the latitude and longitude using mouse movements distance and bearing from a reference point Args: ref (tuple): latitude and longitude of the reference point dist (float): converted euclidean distance of mouse movement bearing (float): bearing in degrees of mouse movement Returns: coords.latitude (float): latitude of new location coords.longitude(float): longitude of new location ''' #kilometers if self.units == 'km': coords = geodesic(kilometers=dist).destination(ref, bearing) #miles elif self.units == 'mi': coords = geodesic(miles=dist).destination(ref, bearing) #meters elif self.units == 'm': coords = geodesic(meters=dist).destination(ref, bearing) #feet elif self.units == 'ft': coords = geodesic(feet=dist).destination(ref, bearing) return Point(round(coords.latitude, 6), round(coords.longitude, 6)) def zeroVariables(self): ''' Zero out all instance variables after mouse has been released. ''' self.dx = 0 self.dy = 0 self.temp_dx = 0 self.temp_dy = 0 self.dist = 0 self.dist_px = 0 self.bearing = 0 self.newLoc = Point(0, 0) def resetTrace(self): ''' Reset reference points if user needs to trace again ''' self.zeroVariables() self.updateLabel() def updateLabel(self): ''' Constantly update data on window label ''' dx_update = self.dx + self.temp_dx dy_update = self.dy + self.temp_dy dist_update = self.dist_px self.displayBox.update(dx_update, dy_update, dist_update) def update(self): ''' Tracks current x and y distance and updates label ''' geo = self.geometry() cur = self.cursor center = self.getCenter() #Get current x, y, and straight line distance from center self.temp_dx = self.getDX() self.temp_dy = self.getDY() self.dist_px = self.getDistance(self.dx + self.temp_dx, self.dy + self.temp_dy) #Check if cursor is within window boundaries #Only update dx, dy instance variables when border has been reached curLoc = {cur.pos().x(), cur.pos().y()} boundaries = {0, geo.width() - 1, geo.height() - 1} if curLoc.intersection(boundaries): self.dx += self.temp_dx self.dy += self.temp_dy cur.setPos(center.x, center.y) self.updateLabel() def mousePressEvent(self, e): ''' When mouse is pressed cursor will be repositioned at the center of the window and tracking will start. ''' center = self.getCenter() self.cursor.setPos(center.x, center.y) #Max out mouse pointer speed #self.mouseController.setSpeed(20) #turn mouse acceleration off self.mouseController.setAcceleration(False) if self.hidden: QApplication.setOverrideCursor(Qt.CrossCursor) else: QApplication.setOverrideCursor(Qt.CrossCursor) def mouseReleaseEvent(self, e): ''' When mouse is released cursor type will be reset or shown again if hidden. ''' #update net dx, dy one more time self.dx += self.temp_dx self.dy += self.temp_dy #restore cursor type and zero out variables QApplication.restoreOverrideCursor() #Reset mouse speed to original setting self.mouseController.setSpeed(self.origMouseSpeed) #Reset mouse acceleration self.mouseController.setAcceleration(self.origAcceleration) self.parent().confirmScale(self.dist_px) return def mouseMoveEvent(self, e): ''' When mouse button is pressed and moving all fields will be actively updated. The current distance x, y, and total from the center will be added to the overall distance to track current bearing, distance, and current location. ''' self.update()
def centerCursor(self): center = self.currentChoice.size() / 2 QCursor.setPos(self.currentChoice.parentWidget().mapToGlobal( self.currentChoice.pos() + QPoint(center.width(), center.height())))
def start_experiment(self): self.model.start_experiment() QCursor.setPos(self.mapToGlobal(QtCore.QPoint(self.screen_width / 2, self.screen_height / 2))) self.update()
def mouseMoveEvent(self, event): cursor = QCursor() if (event.y() < 10): cursor.setPos(1920, 1080)
def reset_mouse_position(): if get_backend() == "Qt5Agg": from PyQt5.QtGui import QCursor # https://stackoverflow.com/questions/29702424/how-to-get-matplotlib-figure-size w_win, h_win = Cursor.fig.get_size_inches() * Cursor.fig.dpi QCursor.setPos(w_win // 2, h_win // 2)
class Microprocessor(QtWidgets.QMainWindow): keyboard = QtCore.pyqtSignal(QtCore.QEvent) def __init__(self): QtWidgets.QWidget.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.microprocessor = Microprocesor_cal(self) self.keyboard.connect(self.on_key) self.key = 53 self.wait_key = False self.split_code = [] self.line_no = 0 self.cursor = QCursor() self.key_pressed = False self.ui.AXH.clicked.connect(self.show_registers_data) self.ui.Data.clicked.connect(self.show_registers_data) self.ui.AXL.clicked.connect(self.show_registers_data) self.ui.BXH.clicked.connect(self.show_registers_data) self.ui.BXL.clicked.connect(self.show_registers_data) self.ui.CXL.clicked.connect(self.show_registers_data) self.ui.CXH.clicked.connect(self.show_registers_data) self.ui.DXL.clicked.connect(self.show_registers_data) self.ui.DXH.clicked.connect(self.show_registers_data) self.ui.AXHo.clicked.connect(self.show_registers_data) self.ui.AXLo.clicked.connect(self.show_registers_data) self.ui.BXHo.clicked.connect(self.show_registers_data) self.ui.BXLo.clicked.connect(self.show_registers_data) self.ui.CXLo.clicked.connect(self.show_registers_data) self.ui.CXHo.clicked.connect(self.show_registers_data) self.ui.DXLo.clicked.connect(self.show_registers_data) self.ui.DXHo.clicked.connect(self.show_registers_data) self.ui.Data.clicked.connect(self.show_registers_data) self.ui.AX.clicked.connect(self.show_registers_data) self.ui.BX.clicked.connect(self.show_registers_data) self.ui.CX.clicked.connect(self.show_registers_data) self.ui.DX.clicked.connect(self.show_registers_data) self.ui.AXo.clicked.connect(self.show_registers_data) self.ui.BXo.clicked.connect(self.show_registers_data) self.ui.CXo.clicked.connect(self.show_registers_data) self.ui.DXo.clicked.connect(self.show_registers_data) self.ui.Operation.activated.connect(self.selected_operation) self.ui.AddStep.clicked.connect(self.add_step) self.ui.Execute.clicked.connect(self.execute_all) self.ui.LoadFile.clicked.connect(self.load_from_file) self.ui.Save.clicked.connect(self.save_to_file) self.ui.DeleteProgram.clicked.connect(self.delete_program) self.ui.DeleteLine.clicked.connect(self.delete_line) self.ui.StepByStep.clicked.connect(self.step_by_step_execution) self.show() def keyReleaseEvent(self, event): super(Microprocessor, self).keyReleaseEvent(event) self.keyboard.emit(event) def is_key_pressed(self): return self.key_pressed def on_key(self, event): if event.type() == QtCore.QEvent.KeyRelease: self.key = ord(chr(event.key()).lower()) self.wait_key = False self.key_pressed = event.isAutoRepeat() def get_key_value(self): return self.key def get_cursor_poisition(self): return self.cursor.pos().x(), self.cursor.pos().y() def set_cursor_poisition(self, x, y): return self.cursor.setPos(x, y) def set_output(self, char): self.ui.output.setText(char) def add_step(self): first, second = self.register_choosing() operation = self.ui.Operation.currentText() REG = ["AX", "BX", "CX", "DX"] if operation == "INT21": self.split_code.append([operation]) elif operation == "INT33": self.split_code.append([operation]) elif operation == "POP": if second in REG: self.split_code.append([operation, second]) elif operation == "PUSH": if first in REG: self.split_code.append([operation, first]) elif first not in REG and second not in REG: if self.ui.Data.isChecked() == True and first and operation: if self.ui.DataToRegister.text().isnumeric(): if int(self.ui.DataToRegister.text()) > 255: self.ui.DataToRegister.setText("255") elif int(self.ui.DataToRegister.text()) >= 0: self.split_code.append( [operation, first, self.ui.DataToRegister.text()]) else: self.ui.DataToRegister.setText("") if first and second and operation: self.split_code.append([operation, first, second]) elif first in REG and (second in REG or self.ui.Data.isChecked() == True): if self.ui.Data.isChecked() == True and first and operation: if self.ui.DataToRegister.text().isnumeric(): if int(self.ui.DataToRegister.text()) > 65535: self.ui.DataToRegister.setText("65535") elif int(self.ui.DataToRegister.text()) >= 0: self.split_code.append( [operation, first, self.ui.DataToRegister.text()]) else: self.ui.DataToRegister.setText("") if first and second and operation: self.split_code.append([operation, first, second]) self.show_program() def register_choosing(self): first = '' second = '' if self.ui.AXH.isChecked() == True: second = 'AXH' elif self.ui.AXL.isChecked() == True: second = 'AXL' elif self.ui.BXH.isChecked() == True: second = 'BXH' elif self.ui.BXL.isChecked() == True: second = 'BXL' elif self.ui.CXL.isChecked() == True: second = 'CXL' elif self.ui.CXH.isChecked() == True: second = 'CXH' elif self.ui.DXH.isChecked() == True: second = 'DXH' elif self.ui.DXL.isChecked() == True: second = 'DXL' elif self.ui.AX.isChecked() == True: second = 'AX' elif self.ui.BX.isChecked() == True: second = 'BX' elif self.ui.CX.isChecked() == True: second = 'CX' elif self.ui.DX.isChecked() == True: second = 'DX' if self.ui.AXHo.isChecked() == True: first = 'AXH' elif self.ui.AXLo.isChecked() == True: first = 'AXL' elif self.ui.BXHo.isChecked() == True: first = 'BXH' elif self.ui.BXLo.isChecked() == True: first = 'BXL' elif self.ui.CXLo.isChecked() == True: first = 'CXL' elif self.ui.CXHo.isChecked() == True: first = 'CXH' elif self.ui.DXHo.isChecked() == True: first = 'DXH' elif self.ui.DXLo.isChecked() == True: first = 'DXL' elif self.ui.AXo.isChecked() == True: first = 'AX' elif self.ui.BXo.isChecked() == True: first = 'BX' elif self.ui.CXo.isChecked() == True: first = 'CX' elif self.ui.DXo.isChecked() == True: first = 'DX' return first, second def show_program(self): commands = "" i = 0 for line in self.split_code: if len(line) == 3: commands = "{}. ".format(i).join((commands, " ".join( (line[0], ", ".join((line[1], line[2] + "\n")))))) elif len(line) == 2: commands = "{}. ".format(i).join((commands, " ".join( (line[0], line[1] + "\n")))) elif len(line) == 1: commands = "{}. ".format(i).join((commands, line[0] + "\n")) i += 1 self.ui.textBrowser.setText(commands) def selected_operation(self): if self.ui.Operation.currentText() == 'ADD': self.ui.textBrowser_2.setText( 'ADD R1, R2\n\n' 'Dodanie zawartości dwóch rejestrów i zapisanie wyniku do R1.\n\n' 'Możliwe jest działanie na całych rejestrach (16 bitów) lub ich połówkach. R2' ' może być liczbą w odpowiednim zakresie') elif self.ui.Operation.currentText() == 'SUB': self.ui.textBrowser_2.setText( 'SUB R1, R2\n\n' 'Odjęcie zawartości rejestru R2 od R1 i zapisanie wyniku do R1.\n\n' 'Możliwe jest działanie na całych rejestrach (16 bitów) lub ich połówkach. R2' ' może być liczbą w odpowiednim zakresie') elif self.ui.Operation.currentText() == 'MOV': self.ui.textBrowser_2.setText( 'MOVE R1, R2\n\n' 'Przesłanie zawartości rejestru R2 od R1.\n\n' 'Możliwe jest działanie na całych rejestrach (16 bitów) lub ich połówkach. R2' ' może być liczbą w odpowiednim zakresie') elif self.ui.Operation.currentText() == 'PUSH': self.ui.textBrowser_2.setText( 'PUSH R1 \n\n' 'Zapisanie zawartości rejestru R1 na stos. R1 musi być rejestrem 16-bitowym' ) elif self.ui.Operation.currentText() == 'POP': self.ui.textBrowser_2.setText( 'POP R1\n\n' 'Zdjęcie pierwszej wartości ze stosu i zapisanie jej do rejestru R1.' ' R1 musi być rejestrem 16-bitowym') elif self.ui.Operation.currentText() == 'INT21': self.ui.textBrowser_2.setText( "Przerwanie INT21H - funkcja przerwania wybierana jest w zależności od" " zawartości rejestru AXH. " "Numery przerwań są podane w systemie dziesiętnym\n\n" "Dostępne funkcje:" "\nAXH = 1\n Wczytanie znaku z klawiatury i zapisanie kodu ASCII\n" "Wyjście: \nAXL - kod ASCII\n" "" "\n\nAXH = 2\nWyświetlenie znaku, kod ASCII w DXL. Znak wyświetla się w " "przygotowanym miejscu.\n" "Wejście: \nDXL - kod ASCII\n" "\n\nAXH = 11\nSprawdzenie czy klawisz jest wciśniety\n" "\nWyjście: \n" "AXL = 00h, jeśli żaden klawisz nie jest wciśnięty\n" "AXL = FFh, jeśli jakiś klawisz jest wciśnięty\n" "\n\nAXH = 42\nSprawdzenie daty\n" "Wyjście:\n" "AXL - dzień tygodnia (0-6), 0 - niedziela\n" "CX - rok\n" "DXH - miesiąc (1-12)\n" "DXL - dzień\n" "\n\nAXH = 44\nSprawdzenie czasu\n" "Wyjście:\n" "CH - godzina (0-23)\n" "CL - minuta\n" "DH - sekunda\n" "DL - setna sekundy\n" "\n\nAXH = 76\nZakoncz program i zwróć konkretną wartość\n" "Wejście:\n" "AL - zwracana wartość\n") elif self.ui.Operation.currentText() == 'INT33': self.ui.textBrowser_2.setText( "INT33 - funkcja przerwania wybierana jest w zależności od" " zawartości rejestru AX. " "Numery przerwań są podane w systemie dziesiętnym\n\n" "Dostępne funkcje:\n" "\nAX = 1\nPokazanie kursora\n" "\n\nAX = 2\nUkrycie kursora" "\n\nAX = 3\nPobierz pozycję kursora\n" "\nWyjście: \n" "CX - pozycja pozioma - w X\n" "DX - pozycja pozioma - w Y\n" "BX - przycisk\n" "\n\nAX = 4\nUstaw pozycję kursora\n" "\nWejscie: \n" "CX - pozycja pozioma - w X\n" "DX - pozycja pozioma - w Y\n") def show_registers_data(self): first, second = self.register_choosing() if self.ui.Data.isChecked() == True and second: self.ui.OutputData.setText(self.ui.DataToRegister.text()) self.ui.InputData.setText( str(self.microprocessor.show_register_int(second))) if first and second: self.ui.InputData.setText( str(self.microprocessor.show_register_int(second))) self.ui.OutputData.setText( str(self.microprocessor.show_register_int(first))) def load_from_file(self): """ Zaladowanie kodu z pliku o nazwie file_name i zapisanie go do listy split_code (z instrukcjami rozdzielonymi od argumentów) """ file_browser = FileBrowser() file_browser.openFileNameDialog() filename = file_browser.file self.delete_program() file = open(filename, 'r') lines = file.readlines() for line in lines: split_line = re.split(' |, |;|\n', line) split_line = split_line[:3] if split_line[-1] == '': split_line.pop() if split_line[-1] == '': split_line.pop() self.split_code.append(split_line) file.close() self.show_program() def save_to_file(self): file_browser = FileBrowser() file_browser.saveFileDialog() filename = file_browser.file file = open(filename, 'w') for line in self.split_code: if len(line) == 3: file.write(line[0] + " " + line[1] + ", " + line[2] + "\n") elif len(line) == 2: file.write(line[0] + " " + line[1] + "\n") elif len(line) == 1: file.write(line[0] + "\n") file.close() def execute_all(self): """ Wykonanie całego kodu """ if self.wait_key is False: for line in self.split_code: self.microprocessor.ex_instruction(line) self.show_registers_data() self.show_program() def step_by_step_execution(self): if self.line_no >= len(self.split_code): self.line_no = 0 self.ui.StepLine.setText(str(self.line_no)) return if self.wait_key is False: line = self.split_code[self.line_no] self.microprocessor.ex_instruction(line) self.line_no += 1 self.ui.StepLine.setText(str(self.line_no)) if self.line_no < len(self.split_code): if self.split_code[self.line_no] == ['INT21'] and str( self.microprocessor.show_register_int("AXH")) == '1': self.wait_key = True self.show_registers_data() self.show_program() def delete_program(self): self.split_code = [] self.show_program() def delete_line(self): if self.ui.LineNo.text().isnumeric(): deleting_line = int(self.ui.LineNo.text()) if deleting_line >= 0 and deleting_line <= len(self.split_code): self.split_code.pop(deleting_line) self.ui.LineNo.setText("") self.show_program()
def setCursor(): cur = QCursor() cur.setPos(QDesktopWidget().availableGeometry().center())