示例#1
0
    def moveEvent(self, event: QMoveEvent):
        '''
        Moveevent

        Parameters
        ----------
        event : QMoveEvent
        '''
        super().moveEvent(event)
        state = self.d.dragging_state
        if state == DragState.mouse_pressed:
            self.d.set_state(DragState.floating_widget)
            self.d.update_drop_overlays(QCursor.pos())
        elif state == DragState.floating_widget:
            self.d.update_drop_overlays(QCursor.pos())
示例#2
0
 def _get_mouse_position(self):
     # Creates a text with empty space to get the height of the rendered text - this is used
     # to provide the same offset for the tooltip, scaled relative to the current resolution and zoom.
     font_metrics = QFontMetrics(QFont(" "))
     # The height itself is divided by 2 just to reduce the offset so that the tooltip is
     # reasonably positioned, relative to the cursor
     return QCursor.pos() + QPoint(font_metrics.height() / 2, 0)
示例#3
0
 def enterEvent(self, event):
     """ Reimplemented to cancel the hide timer.
     """
     super(CallTipWidget, self).enterEvent(event)
     if (self._hide_timer.isActive() and
       self.app.topLevelAt(QCursor.pos()) == self):
         self._hide_timer.stop()
示例#4
0
    def _show_context_menu(self, event):
        """Display a relevant context menu on the canvas
        :param event: The MouseEvent that generated this call
        """
        if not event.inaxes:
            # the current context menus are ony relevant for axes
            return

        fig_type = figure_type(self.canvas.figure)
        if fig_type == FigureType.Empty:
            # Fitting or changing scale types does not make sense in this case
            return

        menu = QMenu()

        if fig_type == FigureType.Image or fig_type == FigureType.Contour:
            if isinstance(event.inaxes, MantidAxes):
                self._add_axes_scale_menu(menu, event.inaxes)
                self._add_normalization_option_menu(menu, event.inaxes)
                self._add_colorbar_axes_scale_menu(menu, event.inaxes)
        elif fig_type == FigureType.Surface:
            self._add_colorbar_axes_scale_menu(menu, event.inaxes)
        elif fig_type != FigureType.Wireframe:
            if self.fit_browser.tool is not None:
                self.fit_browser.add_to_menu(menu)
                menu.addSeparator()
            self._add_axes_scale_menu(menu, event.inaxes)
            if isinstance(event.inaxes, MantidAxes):
                self._add_normalization_option_menu(menu, event.inaxes)
            self.add_error_bars_menu(menu, event.inaxes)
            self._add_marker_option_menu(menu, event)
            self._add_plot_type_option_menu(menu, event.inaxes)

        menu.exec_(QCursor.pos())
示例#5
0
    def eventFilter(self, obj, event):
        """ Reimplemented to hide on certain key presses and on text edit focus
            changes.
        """
        if obj == self._text_edit:
            etype = event.type()

            if etype == QEvent.KeyPress:
                key = event.key()
                if key in (Qt.Key_Enter, Qt.Key_Return,
                           Qt.Key_Down):
                    self.hide()
                elif key == Qt.Key_Escape:
                    self.hide()
                    return True

            elif etype == QEvent.FocusOut:
                self.hide()

            elif etype == QEvent.Enter:
                if (self._hide_timer.isActive() and
                  self.app.topLevelAt(QCursor.pos()) == self):
                    self._hide_timer.stop()

            elif etype == QEvent.Leave:
                self._leave_event_hide()

        return super(CallTipWidget, self).eventFilter(obj, event)
示例#6
0
    def eventFilter(self, obj, event):
        """ Reimplemented to hide on certain key presses and on text edit focus
            changes.
        """
        if obj == self._text_edit:
            etype = event.type()

            if etype == QEvent.KeyPress:
                key = event.key()
                cursor = self._text_edit.textCursor()
                prev_char = self._text_edit.get_character(cursor.position(),
                                                          offset=-1)
                if key in (Qt.Key_Enter, Qt.Key_Return, Qt.Key_Down,
                           Qt.Key_Up):
                    self.hide()
                elif key == Qt.Key_Escape:
                    self.hide()
                    return True
                elif prev_char == ')':
                    self.hide()

            elif etype == QEvent.FocusOut:
                self.hide()

            elif etype == QEvent.Enter:
                if (self._hide_timer.isActive()
                        and self.app.topLevelAt(QCursor.pos()) == self):
                    self._hide_timer.stop()

            elif etype == QEvent.Leave:
                self._leave_event_hide()

        return super(CallTipWidget, self).eventFilter(obj, event)
示例#7
0
 def enterEvent(self, event):
     """ Reimplemented to cancel the hide timer.
     """
     super(CallTipWidget, self).enterEvent(event)
     if (self._hide_timer.isActive()
             and self.app.topLevelAt(QCursor.pos()) == self):
         self._hide_timer.stop()
示例#8
0
 def show_context_menu(self, module_name) -> None:
     self.menu = QMenu(self)
     unload_action = QAction("Unload", self)
     unload_action.triggered.connect(
         lambda: self.on_unload_action_triggered(module_name))
     self.menu.addAction(unload_action)
     self.menu.popup(QCursor.pos())
示例#9
0
def show_mouse_toast(message):
    # Creates a text with empty space to get the height of the rendered text - this is used
    # to provide the same offset for the tooltip, scaled relative to the current resolution and zoom.
    font_metrics = QFontMetrics(QFont(" "))
    # The height itself is divided by 2 just to reduce the offset so that the tooltip is
    # reasonably position relative to the cursor
    QToolTip.showText(QCursor.pos() + QPoint(font_metrics.height() / 2, 0), message)
示例#10
0
 def hide(self, force=False):
     if force:
         return super(ToolTip, self).hide()
     if self.rect().contains(self.mapFromGlobal(QCursor.pos())):
         self._hideTimer.start(self._timeout)
     else:
         super(ToolTip, self).hide()
示例#11
0
    def keyPressEvent(self, event):
        """
        """
        # preflight
        if not self.isSoloViewEnabled(): QSplitter.keyPressEvent(self, event)

        # solo view
        if event.key() == self.soloViewHotkey():
            # preflight
            pos = QCursor.pos()
            widget_pressed = qApp.widgetAt(pos)
            if isinstance(widget_pressed, QSplitterHandle): return

            # toggle solo view
            widget_soloable = self.getFirstSoloableWidget(widget_pressed)
            self.toggleIsSoloView(True, widget=widget_soloable)
            return

        # unsolo view
        elif event.key() == Qt.Key_Escape:
            self.toggleIsSoloView(False)
            return

        # something else
        return QSplitter.keyPressEvent(self, event)
示例#12
0
 def show_context_menu(self):
     """
     显示上下文右键菜单
     :return:
     """
     self.contextMenu.popup(QCursor.pos())
     self.contextMenu.show()
示例#13
0
    def findSuggestions(self, wrapper):
        self.suggestions = []
        self.dropCurrentSuggestionIndex = -1
        globalPos = QCursor.pos()
        candidates = []
        for splitter in wrapper.findChildren(QSplitter):
            candidates.append(splitter)

        for area in self.areas:
            if area.window() == wrapper.window():
                candidates.append(area)

        for widget in candidates:
            splitter = cast(widget, QSplitter)
            area = cast(widget, ToolWindowManagerArea)
            if not (splitter or area):
                qWarning('unexpected widget type')
                continue

            parentSplitter = cast(widget.parentWidget(), QSplitter)
            lastInSplitter = parentSplitter and \
              parentSplitter.indexOf(widget) == parentSplitter.count() - 1

            allowedSides = []
            if not splitter or splitter.orientation() == Qt.Vertical:
                allowedSides.append(ToolWindowManager.LeftOf)

            if not splitter or splitter.orientation() == Qt.Horizontal:
                allowedSides.append(ToolWindowManager.TopOf)

            if not parentSplitter or parentSplitter.orientation(
            ) == Qt.Vertical or lastInSplitter:
                if not splitter or splitter.orientation() == Qt.Vertical:
                    allowedSides.append(ToolWindowManager.RightOf)

            if not parentSplitter or parentSplitter.orientation(
            ) == Qt.Horizontal or lastInSplitter:
                if not splitter or splitter.orientation() == Qt.Horizontal:
                    allowedSides.append(ToolWindowManager.BottomOf)
            for side in allowedSides:
                rect = self.sideSensitiveArea(widget, side)
                pos = widget.mapFromGlobal(globalPos)
                if rect.contains(pos):
                    self.suggestions.append(AreaReference(side, widget))
            if area:
                rect = area.rect()
                pos = area.mapFromGlobal(globalPos)
                if rect.contains(pos):
                    self.suggestions.append(
                        AreaReference(ToolWindowManager.AddTo, area))

        #end of for
        if not candidates:
            self.suggestions.append(AreaReference(
                ToolWindowManager.EmptySpace))

        if len(self.suggestions) == 0:
            self.handleNoSuggestions()
        else:
            self.showNextDropSuggestion()
示例#14
0
 def pop_up(self, text='', move=True):
     self.edit.setText(text)
     self.edit.setSelection(0, len(text))
     self.edit.setFocus(Qt.PopupFocusReason)
     if move:
         self.move(QCursor.pos())
     return self.edit.text() if self.exec_() else None
示例#15
0
def show_mouse_toast(message):
    # Creates a text with empty space to get the height of the rendered text - this is used
    # to provide the same offset for the tooltip, scaled relative to the current resolution and zoom.
    font_metrics = QFontMetrics(QFont(" "))
    # The height itself is divided by 2 just to reduce the offset so that the tooltip is
    # reasonably position relative to the cursor
    QToolTip.showText(QCursor.pos() + QPoint(font_metrics.height() / 2, 0),
                      message)
示例#16
0
 def showContextMenu(self, pos):
     '''''
     右键点击时调用的函数
     '''
     # 菜单显示前,将它移动到鼠标点击的位置
     # self.contextMenu.move(self.pos() + pos)
     self.contextMenu.show()
     self.contextMenu.exec_(QCursor.pos())
示例#17
0
 def move_floating(self):
     '''
     Moves the widget to a new position relative to the position given when
     startFloating() was called
     '''
     border_size = (self.frameSize().width()-self.size().width())/2
     move_to_pos = QCursor.pos()-self.d.drag_start_mouse_position-QPoint(border_size, 0)
     self.move(move_to_pos)
 def getIndexUnderCursor(self):
     """
     Returns the QModelIndex underneath the cursor
     https://bugreports.qt.io/browse/QTBUG-72234
     """
     pos = self.viewport().mapFromParent(self.mapFromGlobal(QCursor.pos()))
     index = self.indexAt(pos)
     return index
示例#19
0
 def _leave_event_hide(self):
     """ Hides the tooltip after some time has passed (assuming the cursor is
         not over the tooltip).
     """
     if (self.hide_timer_on and not self._hide_timer.isActive() and
             # If Enter events always came after Leave events, we wouldn't need
             # this check. But on Mac OS, it sometimes happens the other way
             # around when the tooltip is created.
             self.app.topLevelAt(QCursor.pos()) != self):
         self._hide_timer.start(800, self)
示例#20
0
 def _leave_event_hide(self):
     """ Hides the tooltip after some time has passed (assuming the cursor is
         not over the tooltip).
     """
     if (not self._hide_timer.isActive() and
         # If Enter events always came after Leave events, we wouldn't need
         # this check. But on Mac OS, it sometimes happens the other way
         # around when the tooltip is created.
         self.app.topLevelAt(QCursor.pos()) != self):
         self._hide_timer.start(800, self)
示例#21
0
    def on_mouse_press_event(self, event):
        """
        Event handling for mouse press action
        Args:
            event:

        Returns:

        """
        # get the button and position information.
        curr_x = event.xdata
        curr_y = event.ydata
        if curr_x is None or curr_y is None:
            # outside of canvas
            return

        button = event.button
        if button == 1:
            # left button: no operation
            pass

        elif button == 3:
            # right button:
            # Pop-out menu
            self.menu = QMenu(self)

            if self.get_canvas().is_legend_on:
                # figure has legend: remove legend
                action1 = QAction('Hide legend', self)
                action1.triggered.connect(self._myCanvas.hide_legend)

                action2 = QAction('Legend font larger', self)
                action2.triggered.connect(
                    self._myCanvas.increase_legend_font_size)

                action3 = QAction('Legend font smaller', self)
                action3.triggered.connect(
                    self._myCanvas.decrease_legend_font_size)

                self.menu.addAction(action2)
                self.menu.addAction(action3)

            else:
                # figure does not have legend: add legend
                action1 = QAction('Show legend', self)
                action1.triggered.connect(self._myCanvas.show_legend)

            self.menu.addAction(action1)

            # pop up menu
            self.menu.popup(QCursor.pos())
        # END-IF-ELSE

        return
示例#22
0
    def show_context_menu(self, task_id) -> None:
        self.menu = QMenu(self)
        force_start_action = QAction('Force start', self)
        force_start_action.triggered.connect(
            lambda: self.on_force_start_action_triggered(task_id))

        stop_action = QAction('Stop', self)
        stop_action.triggered.connect(
            lambda: self.on_stop_action_triggered(task_id))
        self.menu.addAction(force_start_action)
        self.menu.addAction(stop_action)
        self.menu.popup(QCursor.pos())
示例#23
0
 def set_zoom(self, zoom: int) -> None:
     """Update zoom factor."""
     zoom_old = self.zoom
     self.zoom = zoom / 50.
     zoom_old -= self.zoom
     if self.zoomby == ZoomBy.CANVAS:
         pos = self.mapFromGlobal(QCursor.pos())
     else:
         pos = QPointF(self.width() / 2, self.height() / 2)
     self.ox += (pos.x() - self.ox) / self.zoom * zoom_old
     self.oy += (pos.y() - self.oy) / self.zoom * zoom_old
     self.update()
示例#24
0
    def on_mouse_press_event(self, event):
        """
        Event handling for mouse press action
        Args:
            event:

        Returns:

        """
        # get the button and position information.
        curr_x = event.xdata
        curr_y = event.ydata
        if curr_x is None or curr_y is None:
            # outside of canvas
            return

        button = event.button
        if button == 1:
            # left button: no operation
            pass

        elif button == 3:
            # right button:
            # Pop-out menu
            self.menu = QMenu(self)

            if self.get_canvas().is_legend_on:
                # figure has legend: remove legend
                action1 = QAction('Hide legend', self)
                action1.triggered.connect(self._myCanvas.hide_legend)

                action2 = QAction('Legend font larger', self)
                action2.triggered.connect(self._myCanvas.increase_legend_font_size)

                action3 = QAction('Legend font smaller', self)
                action3.triggered.connect(self._myCanvas.decrease_legend_font_size)

                self.menu.addAction(action2)
                self.menu.addAction(action3)

            else:
                # figure does not have legend: add legend
                action1 = QAction('Show legend', self)
                action1.triggered.connect(self._myCanvas.show_legend)

            self.menu.addAction(action1)

            # pop up menu
            self.menu.popup(QCursor.pos())
        # END-IF-ELSE

        return
    def __setValue(self):
        """
        This function is run to update the value on the parent widget.
        This will update the value on the widget, and then run
        the valueUpdateEvent
        """
        current_pos = QCursor.pos()
        magnitude = getMagnitude(self._calc_pos, current_pos)
        self._slider_pos, self._num_ticks = math.modf(magnitude / self.pixelsPerTick())

        # update values
        self.valueUpdateEvent()
        self.__updateValue()
示例#26
0
 def move_marker(self, canvas, marker, pos, dx, try_other_way_if_failed):
     tr = self.fit_browser.tool.ax.get_xaxis_transform()
     x0 = tr.transform((0, 0))[0]
     dx_pxl = tr.transform((dx, 0))[0] - x0
     pos.setX(marker.get_x_in_pixels())
     new_pos = pos + QPoint(dx_pxl, 0)
     yield drag_mouse(canvas, pos, new_pos)
     pos1 = canvas.mapFromGlobal(QCursor.pos())
     if try_other_way_if_failed and pos1 != new_pos:
         new_x = marker.x + dx
         marker.on_click(pos.x())
         marker.mouse_move(new_x)
         yield 0.1
         marker.stop()
 def move_marker(self, canvas, marker, pos, dx, try_other_way_if_failed):
     tr = self.fit_browser.tool.ax.get_xaxis_transform()
     x0 = tr.transform((0, 0))[0]
     dx_pxl = tr.transform((dx, 0))[0] - x0
     pos.setX(marker.get_x_in_pixels())
     new_pos = pos + QPoint(dx_pxl, 0)
     yield drag_mouse(canvas, pos, new_pos)
     pos1 = canvas.mapFromGlobal(QCursor.pos())
     if try_other_way_if_failed and pos1 != new_pos:
         new_x = marker.x + dx
         marker.on_click(pos.x())
         marker.mouse_move(new_x)
         yield 0.1
         marker.stop()
    def __activateStickyDrag(self, obj):
        """
        This should be run every time the user clicks.

        Args:
            obj (QWidget / QItem --> DragWidget): Object to install all of the extra attrs on
        """
        obj._cursor_pos = QCursor.pos()
        top_left = getTopLeftPos(obj)
        QCursor.setPos(top_left + QPoint(10, 10))
        obj.setFocus()

        # set up drag time attrs
        obj.updateOrigValue()
        obj._calc_pos = QCursor.pos()
        obj._drag_STICKY = not obj._drag_STICKY
        obj._num_ticks = 0
        obj._pixels_per_tick = self.pixelsPerTick()
        obj._value_per_tick = self.valuePerTick()

        # toggle cursor display
        if obj._drag_STICKY:
            obj.setCursor(Qt.BlankCursor)
示例#29
0
 def check_mouse_move(self, event):
     self.manager.updateDragPosition()
     if event.buttons() == Qt.LeftButton \
     and not self.rect().contains( self.mapFromGlobal( QCursor.pos() ) ) \
     and self.dragCanStart:
         self.dragCanStart = False
         toolWindows = []
         for i in range(self.count()):
             toolWindow = self.widget(i)
             if self.manager.hasToolWindow(toolWindow):
                 toolWindows.append(toolWindow)
             else:
                 qWarning("tab widget contains unmanaged widget")
         self.manager.startDrag(toolWindows)
示例#30
0
    def peak_range_table_right_click(self, position=-1):

        nbr_row = self.parent.ui.peak_range_table.rowCount()
        if nbr_row == 0:
            return

        menu = QMenu(self.parent)
        _remove_row = menu.addAction("Remove")
        action = menu.exec_(QCursor.pos())

        if action == _remove_row:
            self.remove_peak_range_table_row()

        o_gui = GuiUtilities(parent=self.parent)
        o_gui.check_if_fitting_widgets_can_be_enabled()
示例#31
0
        def __init__(self, parent=None, value=0):
            super(TestWidget, self).__init__(parent)
            pos = QCursor().pos()
            self.setGeometry(pos.x(), pos.y(), 200, 100)
            value_list = [0.001, 0.01, 0.1, 1, 10, 100, 1000]
            pos = QCursor.pos()
            ladder = installLadderDelegate(
                self,
                user_input=QEvent.MouseButtonRelease,
                value_list=value_list)

            ladder.setDiscreteDrag(True, alignment=Qt.AlignLeft, depth=10)
            ladder.setDiscreteDrag(True,
                                   alignment=Qt.AlignLeft,
                                   depth=10,
                                   display_widget=self.parent().parent())
    def leaveEvent(self, event, *args, **kwargs):
        """
        When the cursor leaves the invisible display area,
        this will return it back to the original point that it
        was set at.  It will then update the positions to accomdate this
        so that one drag seems seemless.
        """
        if not self._drag_STICKY: return
        current_pos = QCursor.pos()
        offset = (current_pos - self._cursor_pos)
        self._calc_pos = self._calc_pos - offset

        # reset cursor
        QCursor.setPos(self._cursor_pos)

        # update value
        self.__setValue()
        return QFrame.leaveEvent(self, event, *args, **kwargs)
示例#33
0
    def cursor_location(self) -> DockWidgetArea:
        '''
        Returns the dock widget area depending on the current cursor location.
        The function checks, if the mouse cursor is inside of any drop
        indicator widget and returns the corresponding DockWidgetArea.

        Returns
        -------
        value : DockWidgetArea
        '''
        pos = self.mapFromGlobal(QCursor.pos())
        allowed_areas = self.d.dock_overlay.allowed_areas()
        for area, widget in self.d.drop_indicator_widgets.items():
            if (area in allowed_areas and widget and widget.isVisible()
                    and widget.geometry().contains(pos)):
                return area

        return DockWidgetArea.invalid
示例#34
0
    def drop_area_under_cursor(self) -> DockWidgetArea:
        '''
        Returns the drop area under the current cursor location

        Returns
        -------
        value : DockWidgetArea
        '''
        result = self.d.cross.cursor_location()
        if result != DockWidgetArea.invalid:
            return result

        dock_area = self.d.target_widget
        if isinstance(dock_area, DockAreaWidget):
            pos = dock_area.mapFromGlobal(QCursor.pos())
            if dock_area.title_bar_geometry().contains(pos):
                return DockWidgetArea.center

        return DockWidgetArea.invalid
示例#35
0
    def on_mouse_press_event(self, event):
        """
        determine whether the mode is on
        right button:
            pop out menu if it is relevant
        left button:
            get start to
        :param event:
        :return:
        """
        # only respond when in manual picking mode
        if not self._inManualPickingMode:
            return

        button = event.button
        self._currMousePosX = event.xdata

        if button == 1:
            # left button: if a picker is selected then enter on hold mode
            if self._currentSelectedPicker is not None:
                self._mouseLeftButtonHold = True

        elif button == 3:
            # right button: pop-out menu
            self.menu = QMenu(self)

            if self._currentSelectedPicker is None:
                # no picker is selected
                action1 = QAction('Add Picker', self)
                action1.triggered.connect(self.menu_add_picker)
                self.menu.addAction(action1)

            else:
                # some picker is selected
                action2 = QAction('Delete Picker', self)
                action2.triggered.connect(self.menu_delete_picker)
                self.menu.addAction(action2)

            # add other required actions
            self.menu.popup(QCursor.pos())
        # END-IF-ELSE

        return
    def title_mouse_release_event(self):
        self.set_state(DragState.inactive)
        if not self.drop_container:
            logger.debug('title_mouse_release_event: no drop container?')
            return

        dock_manager = self.dock_manager
        dock_area_overlay = dock_manager.dock_area_overlay()
        container_overlay = dock_manager.container_overlay()
        if any(widget.drop_area_under_cursor() != DockWidgetArea.invalid
               for widget in (dock_area_overlay, container_overlay)):
            # Resize the floating widget to the size of the highlighted drop area
            # rectangle
            overlay = container_overlay
            if not overlay.drop_overlay_rect().isValid():
                overlay = dock_area_overlay

            rect = overlay.drop_overlay_rect()
            if not rect.isValid():
                logger.debug('title_mouse_release_event: invalid rect '
                             'x %s y %s w %s h %s',
                             rect.x(), rect.y(),
                             rect.width(), rect.height())
            else:
                public = self.public
                frame_width = (public.frameSize().width() -
                               public.rect().width()) // 2
                title_bar_height = int(public.frameSize().height() -
                                       public.rect().height() - frame_width)

                top_left = overlay.mapToGlobal(rect.topLeft())
                top_left.setY(top_left.y() + title_bar_height)
                geom = QRect(top_left, QSize(rect.width(), rect.height() -
                                             title_bar_height))
                self.public.setGeometry(geom)
                qapp = QApplication.instance()
                qapp.processEvents()

            self.drop_container.drop_floating_widget(self.public, QCursor.pos())

        container_overlay.hide_overlay()
        dock_area_overlay.hide_overlay()
示例#37
0
    def _show_context_menu(self, event):
        """Display a relevant context menu on the canvas
        :param event: The MouseEvent that generated this call
        """
        if not event.inaxes:
            # the current context menus are ony relevant for axes
            return

        fig_type = figure_type(self.canvas.figure)
        if fig_type == FigureType.Empty or fig_type == FigureType.Image:
            # Fitting or changing scale types does not make sense in
            # these cases
            return

        menu = QMenu()
        if self.fit_browser.tool is not None:
            self.fit_browser.add_to_menu(menu)
            menu.addSeparator()
        self._add_axes_scale_menu(menu)
        menu.exec_(QCursor.pos())
示例#38
0
    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)
示例#39
0
    def mouse_move(self, event):
        """
        Event handler for matplotlib motion_notify_event.
        Updates coord display and vars.
        :param event: matplotlib event.
        """
        # Check if mouse is in widget but not on plot
        if not event.inaxes:
            self.is_mouse_over = False
            self.clear_coords()
            return
        mouse_pos = QCursor.pos()
        self.is_mouse_over = True

        # If hold_coords is active, return
        if self.hold_coords:
            return

        # Get x and y of the pixel under the mouse
        x, y = [int(event.xdata + 0.5), int(event.ydata + 0.5)]
        self.x_mouse, self.y_mouse = [x, y]

        # Create coord display string
        if self._slice_index is not None:
            string = "({:1.0f}, {:1.0f}, {:1.0f})".format(x, y, self._slice_index)
        else:
            string = "({:1.0f}, {:1.0f})".format(x, y)

        self.mouse_value = ""

        # If viewer has a layer.
        if len(self.visible_layers()) > 0:

            arr = self.first_visible_layer().state.get_sliced_data()

            if 0 <= y < arr.shape[0] and 0 <= x < arr.shape[1]:
                # if x and y are in bounds. Note: x and y are swapped in array.
                # get value and check if wcs is obtainable
                # WCS:
                if len(self.figure.axes) > 0:
                    wcs = self.figure.axes[0].wcs.celestial
                    if wcs is not None:
                        # Check the number of axes in the WCS and add to string
                        ra = dec = None
                        if wcs.naxis == 3 and self.slice_index is not None:
                            ra, dec, wave = wcs.wcs_pix2world([[x, y, self._slice_index]], 0)[0]
                        elif wcs.naxis == 2:
                            ra, dec = wcs.wcs_pix2world([[x, y]], 0)[0]

                        if ra is not None and dec is not None:
                            string = string + " " + self._coords_format_function(ra, dec)
                # Pixel Value:
                v = arr[y][x]
                if self.cubeviz_unit is not None:
                    wave = self.cubeviz_layout.get_wavelength(self.slice_index)
                    v = self.cubeviz_unit.convert_value(v, wave=wave)

                unit_string = ""
                if self.component_unit_label:
                    unit_string = "[{0}]".format(self.component_unit_label)

                if 0.001 <= abs(v) <= 1000 or abs(v) == 0.0:
                    value_string = "{0:.3f} ".format(v)
                else:
                    value_string = "{0:.3e} ".format(v)

                self.mouse_value = value_string + unit_string
                string = value_string + string
        # Add a gap to string and add to viewer.
        string += " "
        self._dont_update_status = True
        self.statusBar().clearMessage()
        self._dont_update_status = False
        self.coord_label.setText(string)

        if self._is_tooltip_on:
            if self.mouse_value:
                QToolTip.showText(mouse_pos, "...", self)
                QToolTip.showText(mouse_pos, self.mouse_value, self)
            else:
                QToolTip.showText(mouse_pos, "...", self)
                QToolTip.showText(mouse_pos, " ", self)

        return
示例#40
0
 def move_and_show(editor):
     editor.move(QCursor.pos())
     editor.exec_()
示例#41
0
    def right_click(self, position=None):
        _duplicate_row = -1
        _plot_sofq = -1
        _remove_row = -1
        _new_row = -1
        _copy = -1
        _paste = -1
        _cut = -1
        _refresh_table = -1
        _clear_table = -1
        # _import = -1
        # _export = -1        _check_all = -1
        _uncheck_all = -1
        _undo = -1
        _redo = -1
        _plot_sofq_diff_first_run_row = -1
        _plot_sofq_diff_average_row = -1
        _plot_cryostat = -1
        _plot_furnace = -1
        _invert_selection = -1

        menu = QMenu(self.main_window)

        if self.main_window.table_selection_buffer == {}:
            paste_status = False
        else:
            paste_status = True

        if (self.main_window.postprocessing_ui.table.rowCount() > 0):
            _undo = menu.addAction("Undo")
            _undo.setEnabled(self.main_window.undo_button_enabled)
            _redo = menu.addAction("Redo")
            _redo.setEnabled(self.main_window.redo_button_enabled)
            menu.addSeparator()
            _copy = menu.addAction("Copy")
            _paste = menu.addAction("Paste")
            self._paste_menu = _paste
            _paste.setEnabled(paste_status)
            _cut = menu.addAction("Clear")
            menu.addSeparator()
            _check_all = menu.addAction("Check All")
            _uncheck_all = menu.addAction("Unchecked All")
            menu.addSeparator()
            _invert_selection = menu.addAction("Inverse Selection")
            menu.addSeparator()

        _new_row = menu.addAction("Insert Blank Row")

        if (self.main_window.postprocessing_ui.table.rowCount() > 0):
            _duplicate_row = menu.addAction("Duplicate Row")
            _remove_row = menu.addAction("Remove Row(s)")

            menu.addSeparator()
            _plot_menu = menu.addMenu('Plot')
            _plot_sofq = _plot_menu.addAction("S(Q) ...")
            _plot_sofq_diff_first_run_row = _plot_menu.addAction("S(Q) Diff (1st run)...")
            _plot_sofq_diff_average_row = _plot_menu.addAction("S(Q) Diff (Avg.)...")

            _temp_menu = _plot_menu.addMenu("Temperature")
            _plot_cryostat = _temp_menu.addAction("Cyrostat...")
            _plot_furnace = _temp_menu.addAction("Furnace...")

            menu.addSeparator()
            _refresh_table = menu.addAction("Refresh/Reset Table")
            _clear_table = menu.addAction("Clear Table")

        action = menu.exec_(QCursor.pos())
        self.current_row = self.current_row()

        if action == _undo:
            self.main_window.action_undo_clicked()
        elif action == _redo:
            self.main_window.action_redo_clicked()
        elif action == _copy:
            self._copy()
        elif action == _paste:
            self._paste()
        elif action == _cut:
            self._cut()
        elif action == _duplicate_row:
            self._duplicate_row()
        elif action == _plot_sofq:
            self._plot_sofq()
        elif action == _plot_sofq_diff_first_run_row:
            self._plot_sofq_diff_first_run_row()
        elif action == _plot_sofq_diff_average_row:
            self._plot_sofq_diff_average_row()
        elif action == _plot_cryostat:
            self._plot_temperature(samp_env_choice='cryostat')
        elif action == _plot_furnace:
            self._plot_temperature(samp_env_choice='furnace')
        elif action == _invert_selection:
            self._inverse_selection()
        elif action == _new_row:
            self._new_row()
        elif action == _remove_row:
            self._remove_selected_rows()
        elif action == _refresh_table:
            self._refresh_table()
        elif action == _clear_table:
            self._clear_table()
        elif action == _check_all:
            self.check_all()
        elif action == _uncheck_all:
            self.uncheck_all()
示例#42
0
    def on_mouse_press_event(self, event):
        """
        Handle mouse pressing event
        (1) left mouse: in show-boundary mode, check the action to select a boundary indicator
        (2) right mouse: pop up the menu
        Returns
        -------

        """
        # get the button
        button = event.button

        if button == 3:
            # right button:
            # Pop-out menu
            self.menu = QMenu(self)

            if self.get_canvas().is_legend_on:
                # figure has legend: remove legend
                action1 = QAction('Hide legend', self)
                action1.triggered.connect(self._myCanvas.hide_legend)

                action2 = QAction('Legend font larger', self)
                action2.triggered.connect(self._myCanvas.increase_legend_font_size)

                action3 = QAction('Legend font smaller', self)
                action3.triggered.connect(self._myCanvas.decrease_legend_font_size)

                self.menu.addAction(action2)
                self.menu.addAction(action3)

            else:
                # figure does not have legend: add legend
                action1 = QAction('Show legend', self)
                action1.triggered.connect(self._myCanvas.show_legend)

            self.menu.addAction(action1)
            # pop up menu
            self.menu.popup(QCursor.pos())

            return
        # END-IF

        # ignore if boundary is not shown and the pressed mouse button is left or middle
        if not self._showBoundary:
            return

        # get mouse cursor x position
        mouse_x_pos = event.xdata
        if mouse_x_pos is None:
            return
        else:
            self._prevCursorPos = mouse_x_pos

        # get absolute resolution
        x_range = self.getXLimit()
        resolution = (x_range[1] - x_range[0]) * self.IndicatorResolution

        # see whether it is close enough to any boundary
        left_bound_pos = self.get_indicator_position(self._leftID)[0]
        right_bound_pos = self.get_indicator_position(self._rightID)[0]
        if abs(mouse_x_pos - left_bound_pos) < resolution:
            self._selectedBoundary = 1
        elif abs(mouse_x_pos - right_bound_pos) < resolution:
            self._selectedBoundary = 2
        else:
            self._selectedBoundary = 0
        # END-IF-ELSE

        return