Пример #1
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()
Пример #2
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)
Пример #3
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)
Пример #4
0
 def get_cursor_at_y(self, y):
     """
     Get an override cursor for an y coordinate given that the x == self.x
     :param y: A y coordinate.
     :return: QCursor or None.
     """
     is_at_top = self.is_at_top if self.is_moving else self._is_at_top(y)
     return QCursor(
         Qt.SizeAllCursor) if is_at_top else VerticalMarker.get_cursor_at_y(
             self, y)
Пример #5
0
 def func(button):
     button_id = widget.standardButton(button)
     for button_name in _QtDialog.supported_button_names:
         if button_id == getattr(QMessageBox, button_name):
             widget.setCursor(QCursor(Qt.WaitCursor))
             try:
                 callback(button_name)
             finally:
                 widget.unsetCursor()
                 break
Пример #6
0
    def _display_roi_context_menu(self, roi_index):
        def delete_roi(event):
            self._dc.remove_subset_group(self._dc.subset_groups[roi_index])

        context_menu = QMenu()
        action = QAction("Delete ROI", context_menu)
        action.triggered.connect(delete_roi)
        context_menu.addAction(action)
        pos = self._viewer.mapToParent(QCursor().pos())
        context_menu.exec_(pos)
Пример #7
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)
Пример #8
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)
Пример #9
0
    def enterEvent(self, event):
        """ Reimplemented to cancel the hide timer.
        """
        super(CallTipWidget, self).enterEvent(event)
        if self.as_tooltip:
            self.hide()

        if (self._hide_timer.isActive() and
          self.app.topLevelAt(QCursor.pos()) == self):
            self._hide_timer.stop()
Пример #10
0
def wait_cursor(msg=None):
    '''
    Allows long running functions to show a busy cursor.
    :param msg: a message to put in the status bar.
    '''
    try:
        QApplication.setOverrideCursor(QCursor(QtCore.Qt.WaitCursor))
        yield
    finally:
        QApplication.restoreOverrideCursor()
Пример #11
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
Пример #12
0
 def set_cursor(self, cursor, size=10):
     if cursor == 'square':
         if size < 10 or size > 300:
             q_cursor = self._cursors['cross']
         else:
             q_cursor = QCursor(
                 QPixmap(':/icons/cursor/cursor_square.png').scaledToHeight(
                     size))
     else:
         q_cursor = self._cursors[cursor]
     self.canvas.native.setCursor(q_cursor)
Пример #13
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())
Пример #14
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)
Пример #15
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)
Пример #16
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()
Пример #17
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
Пример #18
0
    def __init__(self, parent=None, command=None):
        QPushButton.__init__(self, parent)
        PyDMPrimitiveWidget.__init__(self)
        self.iconFont = IconFont()
        self._icon = self.iconFont.icon("cog")
        self.setIconSize(QSize(16, 16))
        self.setIcon(self._icon)
        self.setCursor(QCursor(self._icon.pixmap(16, 16)))

        self._command = command
        self._allow_multiple = False
        self.process = None
        self._show_icon = True
    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()
Пример #20
0
 def mouseMoveEvent(self, event):
     """Show Pointing Hand Cursor on error messages"""
     text = self.get_line_at(event.pos())
     if get_error_match(text):
         if not self.__cursor_changed:
             QApplication.setOverrideCursor(QCursor(Qt.PointingHandCursor))
             self.__cursor_changed = True
         event.accept()
         return
     if self.__cursor_changed:
         QApplication.restoreOverrideCursor()
         self.__cursor_changed = False
     self.QT_CLASS.mouseMoveEvent(self, event)
Пример #21
0
 def set_override_cursor(
         override: bool,
         override_cursor: Qt.CursorShape = Qt.SizeAllCursor) -> None:
     """
     Sets the override cursor if an override cursor doesn't exist. Otherwise, restores the override cursor
     :param override: A boolean for whether to set the override cursor or not
     :param override_cursor: The override cursor to use if the override parameter is true
     """
     cursor = QApplication.overrideCursor()
     if override and cursor is None:
         QApplication.setOverrideCursor(QCursor(override_cursor))
     elif not override and cursor is not None:
         QApplication.restoreOverrideCursor()
Пример #22
0
 def motion_notify_callback(self, event):
     x = event.x
     if x is not None and (self.fit_start_x.should_override_cursor(x)
                           or self.fit_end_x.should_override_cursor(x)):
         if not self.is_cursor_overridden:
             QApplication.setOverrideCursor(QCursor(Qt.SizeHorCursor))
         self.is_cursor_overridden = True
     else:
         QApplication.restoreOverrideCursor()
         self.is_cursor_overridden = False
     self.fit_start_x.mouse_move(event.xdata)
     self.fit_end_x.mouse_move(event.xdata)
     self.canvas.draw()
Пример #23
0
 def _on_cursor(self, event):
     cursor = self.viewer.cursor
     size = self.viewer.cursor_size
     if cursor == 'square':
         if size < 10 or size > 300:
             q_cursor = self._cursors['cross']
         else:
             q_cursor = QCursor(
                 QPixmap(':/icons/cursor/cursor_square.png').scaledToHeight(
                     size))
     else:
         q_cursor = self._cursors[cursor]
     self.canvas.native.setCursor(q_cursor)
 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()
Пример #25
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()
Пример #26
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)
Пример #27
0
 def override_cursor(self, x, y):
     """
     Get the override cursor for mouse position (x, y)
     :param x: An x mouse coordinate.
     :param y: An y mouse coordinate.
     :return: QCursor or None.
     """
     if self.x0 is not None and x < self.x0:
         return None
     if self.x1 is not None and x > self.x1:
         return None
     if self.is_moving or self.is_above(x, y):
         return QCursor(Qt.SizeVerCursor)
     return None
    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 _on_cursor(self, event):
        """Set the appearance of the mouse cursor.

        Parameters
        ----------
        event : napari.utils.event.Event
            The napari event that triggered this method.
        """
        cursor = self.viewer.cursor
        if cursor == 'square':
            size = self.viewer.cursor_size
            # make sure the square fits within the current canvas
            if size < 8 or size > (
                    min(*self.viewer.window.qt_viewer.canvas.size) - 4):
                q_cursor = self._cursors['cross']
            else:
                q_cursor = QCursor(square_pixmap(size))
        elif cursor == 'circle':
            size = self.viewer.cursor_size
            q_cursor = QCursor(circle_pixmap(size))
        else:
            q_cursor = self._cursors[cursor]
        self.canvas.native.setCursor(q_cursor)
Пример #30
0
    def before_long_process(self, message):
        """
        Show a message in main window's status bar and change the mouse
        pointer to Qt.WaitCursor when starting a long process.

        Parameters
        ----------
        message: str
            Message to show in the status bar when the long process starts.
        """
        if message:
            self.show_status_message(message)

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        QApplication.processEvents()
Пример #31
0
    def move_from(self, cur_pos_data: Tuple[float, float]) -> None:
        """
        Calculate a new position based on the given starting position
        and self.newpixel transform and move the mouse cursor there.
        :param cur_pos_data: Current cursor position in data coordinates
        """
        new_pos_data = self.clip(self.new_pixel(*cur_pos_data))
        xdisp, ydisp = self.data_to_display.transform_point(new_pos_data)
        canvas = self.canvas
        dpi_ratio = canvas._dpi_ratio
        to_int = self.to_int
        xp = to_int(xdisp / dpi_ratio)
        yp = to_int((canvas.figure.bbox.height - ydisp) / dpi_ratio)
        # in the special case of just vertical/horizontal moves
        # use the original cursor position for the orthogonal coordinate
        # to avoid rounding errors and mouse jitter
        new_global_pos = canvas.mapToGlobal(QPoint(xp, yp))
        cur_global_pos = QCursor.pos()
        if new_pos_data[0] == cur_pos_data[0]:
            new_global_pos.setX(cur_global_pos.x())
        if new_pos_data[1] == cur_pos_data[1]:
            new_global_pos.setY(cur_global_pos.y())

        QCursor.setPos(new_global_pos)
Пример #32
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()
Пример #33
0
    def _on_cursor(self):
        """Set the appearance of the mouse cursor."""
        cursor = self.viewer.cursor.style
        # Scale size by zoom if needed
        if self.viewer.cursor.scaled:
            size = self.viewer.cursor.size * self.viewer.camera.zoom
        else:
            size = self.viewer.cursor.size

        if cursor == 'square':
            # make sure the square fits within the current canvas
            if size < 8 or size > (
                    min(*self.viewer.window._qt_viewer.canvas.size) - 4):
                q_cursor = self._cursors['cross']
            else:
                q_cursor = QCursor(square_pixmap(size))
        elif cursor == 'circle':
            q_cursor = QCursor(circle_pixmap(size))
        elif cursor == 'crosshair':
            q_cursor = QCursor(crosshair_pixmap())
        else:
            q_cursor = self._cursors[cursor]

        self.canvas.native.setCursor(q_cursor)
Пример #34
0
    def mouseMoveEvent(self, event):
        """
        Detect mouser over indicator and highlight the current scope in the
        editor (up and down decoration arround the foldable text when the mouse
        is over an indicator).

        :param event: event
        """
        super(FoldingPanel, self).mouseMoveEvent(event)
        th = TextHelper(self.editor)
        line = th.line_nbr_from_position(event.pos().y())
        if line >= 0:
            block = self.editor.document().findBlockByNumber(line)
            block = self.find_parent_scope(block)
            line_number = block.blockNumber()
            if line_number in self.folding_regions:
                if self._mouse_over_line is None:
                    # mouse enter fold scope
                    QApplication.setOverrideCursor(
                        QCursor(Qt.PointingHandCursor))
                if (self._mouse_over_line != block.blockNumber()
                        and self._mouse_over_line is not None):
                    # fold scope changed, a previous block was highlighter so
                    # we quickly update our highlighting
                    self._mouse_over_line = block.blockNumber()
                    try:
                        self._highlight_block(block)
                    except KeyError:
                        # Catching the KeyError above is necessary to avoid
                        # issue spyder-ide/spyder#13230.
                        pass
                else:
                    # same fold scope, request highlight
                    self._mouse_over_line = block.blockNumber()
                    try:
                        self._highlight_runner.request_job(
                            self._highlight_block, block)
                    except KeyError:
                        # Catching the KeyError above is necessary to avoid
                        # issue spyder-ide/spyder#11291.
                        pass
                self._highight_block = block
            else:
                # no fold scope to highlight, cancel any pending requests
                self._highlight_runner.cancel_requests()
                self._mouse_over_line = None
                QApplication.restoreOverrideCursor()
            self.repaint()
Пример #35
0
    def initialize(self, checked=True):
        """
        Start pydoc server.

        Parameters
        ----------
        checked: bool, optional
            This method is connected to the `sig_toggle_view_changed` signal,
            so that the first time the widget is made visible it will start
            the server. Default is True.
        """
        if checked and self.server is None:
            self.sig_toggle_view_changed.disconnect(self.initialize)
            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
            QApplication.processEvents()
            self.start_server()
Пример #36
0
    def _update_hover_html_link_style(self, url):
        """Update style of labels that include rich text and html links."""
        link = 'text-decoration:none;'
        link_hovered = 'text-decoration:underline;'
        self._url = url

        if url:
            QApplication.setOverrideCursor(QCursor(Qt.PointingHandCursor))
            new_text, old_text = link_hovered, link
        else:
            new_text, old_text = link, link_hovered
            QApplication.restoreOverrideCursor()

        text = self.text()
        new_text = text.replace(old_text, new_text)

        self.setText(new_text)
Пример #37
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
Пример #38
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())
Пример #39
0
 def move_and_show(editor):
     editor.move(QCursor.pos())
     editor.exec_()
Пример #40
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()
Пример #41
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
Пример #42
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