Exemple #1
0
 def show_original_size(self):
     action = QAction(self.app.ui.show_original_size_icon, "Original Size")
     action.setToolTip("Original Size")
     action.setStatusTip("Show original image size, Shortcuts : Shift+Left")
     action.setShortcuts(["Shift+Left"])
     action.setCheckable(True)
     return action
Exemple #2
0
 def slideshow(self):
     action = QAction(self.app.ui.slideshow_icon, "Slide Show")
     action.setToolTip("Slide Show")
     action.setStatusTip("Play slideshow, Shortcuts : Alt+Return, F11")
     action.setShortcuts(["Alt+Return", "F11"])
     action.setCheckable(True)
     return action
Exemple #3
0
 def fit_to_height(self):
     action = QAction(self.app.ui.fit_to_height_icon, "Fit to height")
     action.setToolTip("Fit to height")
     action.setStatusTip("Fit image to window height, Shortcuts : Shift+Up")
     action.setShortcuts(["Shift+Up"])
     action.setCheckable(True)
     return action
Exemple #4
0
 def _init_toolbar(self):
     a = QAction(getIcon('color-wheel'), 'Color bar', self)
     a.setToolTip('Add color bar')
     a.setCheckable(True)
     a.triggered.connect(self.colorbar)
     self._actions['colorbar'] = a
     self.insertAction(self._actions['configure_subplots'], a)
Exemple #5
0
 def _init_toolbar(self):
     a = QAction(getIcon('snap'), 'Snap', self)
     a.setCheckable(True)
     a.setToolTip('Snap to data')
     a.triggered.connect(self.snap)
     self._actions['snap'] = a
     self.insertAction(self._actions['pan'], a)
Exemple #6
0
    def _cfg_action(
        self,
        menu,
        title,
        setting,
        icon=None,
        shortcut=None
    ):

        action = QAction(title, self)
        if icon:
            action.setIcon(self._ide.theme.qicon(icon))
        if shortcut:
            action.setShortcut(shortcut)
            action.setToolTip(
                u'{} ({})'.format(title.replace(u'&', u''), shortcut)
            )
        
        def change_setting(value):
            self._ide.extension_manager.fire(
                'setting_changed',
                setting=setting,
                value=value
            )
            
        action.triggered.connect(change_setting)
        action.setCheckable(True)
        action.setChecked(cfg[setting])
        action.setPriority(QAction.HighPriority)
        menu.addAction(action)
        self._cfg_actions[setting] = action
        return action
Exemple #7
0
class Tool(object):
    def __init__(
        self,
        name,
        help_link="",
        icon=None,
        enabled=True,
        checkable=False,
        popup_menu=False,
    ):
        super(Tool, self).__init__()
        self.__icon = icon
        self.__name = name
        self.__parent = None
        self.__enabled = enabled
        self.__checkable = checkable
        self.__help_link = help_link
        self.__is_popup_menu = popup_menu

        self.__action = QAction(self.getIcon(), self.getName(), None)
        self.__action.setIconText(self.getName())
        self.__action.setEnabled(self.isEnabled())
        self.__action.setCheckable(checkable)
        self.__action.triggered.connect(self.trigger)

        HelpCenter.addHelpToAction(self.__action, self.getHelpLink())

    def getIcon(self):
        return self.__icon

    def getName(self):
        return self.__name

    def trigger(self):
        raise NotImplementedError()

    def setParent(self, parent):
        self.__parent = parent
        self.__action.setParent(parent)

    def parent(self):
        return self.__parent

    def isEnabled(self):
        return self.__enabled

    def getHelpLink(self):
        return self.__help_link

    def getAction(self):
        return self.__action

    def setVisible(self, visible):
        self.__action.setVisible(visible)

    def setEnabled(self, enabled):
        self.__action.setEnabled(enabled)

    def isPopupMenu(self):
        return self.__is_popup_menu
Exemple #8
0
 def _init_toolbar(self):
     a = QAction(getIcon('ruler'), 'Scale bar', self)
     a.setToolTip('Add scale bar')
     a.setCheckable(True)
     a.triggered.connect(self.scalebar)
     self._actions['scalebar'] = a
     self.insertAction(self._actions['configure_subplots'], a)
def create_action(parent,
                  text,
                  shortcut=None,
                  icon=None,
                  tip=None,
                  toggled=None,
                  triggered=None,
                  data=None,
                  menurole=None,
                  context=Qt.WindowShortcut):
    """Create a QAction."""
    action = QAction(text, parent)
    if triggered is not None:
        action.triggered.connect(triggered)
    if toggled is not None:
        action.toggled.connect(toggled)
        action.setCheckable(True)
    if icon is not None:
        action.setIcon(icon)
    if shortcut is not None:
        action.setShortcut(shortcut)
    if tip is not None:
        action.setToolTip(tip)
        action.setStatusTip(tip)
    if data is not None:
        action.setData(to_qvariant(data))
    if menurole is not None:
        action.setMenuRole(menurole)
    # TODO: Hard-code all shortcuts and choose context=Qt.WidgetShortcut
    # (this will avoid calling shortcuts from another dockwidget
    #  since the context thing doesn't work quite well with these widgets)
    action.setShortcutContext(context)
    return action
Exemple #10
0
def create_action(parent, text, shortcut=None, icon=None, tip=None,
                  toggled=None, triggered=None, data=None, menurole=None,
                  context=Qt.WindowShortcut):
    """Create a QAction"""
    action = QAction(text, parent)
    if triggered is not None:
        action.triggered.connect(triggered)
    if toggled is not None:
        action.toggled.connect(toggled)
        action.setCheckable(True)
    if icon is not None:
        if is_text_string(icon):
            icon = get_icon(icon)
        action.setIcon(icon)
    if shortcut is not None:
        action.setShortcut(shortcut)
    if tip is not None:
        action.setToolTip(tip)
        action.setStatusTip(tip)
    if data is not None:
        action.setData(to_qvariant(data))
    if menurole is not None:
        action.setMenuRole(menurole)
    #TODO: Hard-code all shortcuts and choose context=Qt.WidgetShortcut
    # (this will avoid calling shortcuts from another dockwidget
    #  since the context thing doesn't work quite well with these widgets)
    action.setShortcutContext(context)
    return action
Exemple #11
0
 def fit_to_window(self):
     action = QAction(self.app.ui.fit_to_window_icon, "Fit to window")
     action.setToolTip("Fit to window")
     action.setStatusTip("Fit image to window size, Shortcuts : Shift+Down")
     action.setShortcuts(["Shift+Down"])
     action.setCheckable(True)
     return action
Exemple #12
0
 def show_statusbar(self):
     action = QAction(self.app.ui.statusbar_icon, "Show Statusbar")
     action.setToolTip("Show Statusbar")
     action.setToolTip("Show Statusbar, Shortcuts : Ctrl+.")
     action.setShortcuts(["Ctrl+."])
     action.setCheckable(True)
     return action
Exemple #13
0
 def fit_to_width(self):
     action = QAction(self.app.ui.fit_to_width_icon, "Fit to width")
     action.setToolTip("Fit to width")
     action.setStatusTip(
         "Fit image to window width, Shortcuts : Shift+Right")
     action.setShortcuts(["Shift+Right"])
     action.setCheckable(True)
     return action
Exemple #14
0
class MOSViewerToolbar(BasicToolbar):
    def __init__(self, *args, **kwargs):
        super(MOSViewerToolbar, self).__init__(*args, **kwargs)
        self.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)

        # Define the toolbar actions
        self.cycle_previous_action = QAction(
            QIcon(os.path.join(ICON_DIR, "Previous-96.png")), "Previous", self)
        self.cycle_next_action = QAction(
            QIcon(os.path.join(ICON_DIR, "Next-96.png")), "Next", self)

        # Include the dropdown widget
        self.source_select = QComboBox()

        # Add the items to the toolbar
        self.addAction(self.cycle_previous_action)
        self.addAction(self.cycle_next_action)
        self.addWidget(self.source_select)

        # Include a button to open spectrum in specviz
        self.open_specviz = QAction(
            QIcon(os.path.join(ICON_DIR, "External-96.png")),
            "Open in SpecViz", self)

        # Create a tool button to hold the lock axes menu object
        tool_button = QToolButton(self)
        tool_button.setText("Axes Settings")
        tool_button.setIcon(QIcon(os.path.join(ICON_DIR, "Settings-96.png")))
        tool_button.setPopupMode(QToolButton.MenuButtonPopup)
        tool_button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)

        # Create a menu for the axes settings drop down
        self.settings_menu = QMenu(self)

        # Add lock x axis action
        self.lock_x_action = QAction("Lock spectral axis", self.settings_menu)
        self.lock_x_action.setCheckable(True)

        # Add lock y axis action
        self.lock_y_action = QAction("Lock vertical displacement axis",
                                     self.settings_menu)
        self.lock_y_action.setCheckable(True)

        # Add the actions to the menu
        self.settings_menu.addAction(self.lock_x_action)
        self.settings_menu.addAction(self.lock_y_action)

        # Set the menu object on the tool button
        tool_button.setMenu(self.settings_menu)

        # Create a widget action object to hold the tool button, this way the
        # toolbar behaves the way it's expected to
        tool_button_action = QWidgetAction(self)
        tool_button_action.setDefaultWidget(tool_button)

        self.addAction(tool_button_action)
        self.addSeparator()
        self.addAction(self.open_specviz)
Exemple #15
0
    def __init__(self, parent=None, standalone=False):
        super(Camera, self).__init__(parent)

        # This prevents doing unneeded initialization
        # when QtDesginer loads the plugin.
        if parent is None and not standalone:
            return

        if not multimedia_available:
            return

        self.ui = uic.loadUi(os.path.join(WIDGET_PATH, "camera.ui"), self)

        self.camera = None
        self.imageCapture = None
        self.mediaRecorder = None
        self.isCapturingImage = False
        self.applicationExiting = False

        self.imageSettings = QImageEncoderSettings()
        self.audioSettings = QAudioEncoderSettings()
        self.videoSettings = QVideoEncoderSettings()
        self.videoContainerFormat = ''

        camera_device = QByteArray()

        videoDevicesGroup = QActionGroup(self)

        videoDevicesGroup.setExclusive(True)

        if not QCamera.availableDevices():
            self.ui.devicesCombo.addItem("No Device")
        else:
            for deviceName in QCamera.availableDevices():
                description = QCamera.deviceDescription(deviceName)
                self.ui.devicesCombo.addItem(description)

                videoDeviceAction = QAction(description, videoDevicesGroup)
                videoDeviceAction.setCheckable(True)
                videoDeviceAction.setData(deviceName)

                if camera_device.isEmpty():
                    cameraDevice = deviceName
                    videoDeviceAction.setChecked(True)

                self.ui.devicesCombo.addAction(videoDeviceAction)

        videoDevicesGroup.triggered.connect(self.updateCameraDevice)

        self.ui.captureWidget.currentChanged.connect(self.updateCaptureMode)

        self.ui.devicesCombo.currentIndexChanged.connect(self.get_device_action)

        self.ui.lockButton.hide()
        
        if not IN_DESIGNER:
            # Start camera 2s after the UI has loaded
            QTimer.singleShot(2000, lambda: self.setCamera(camera_device))
Exemple #16
0
    def customMenuRequested(self, position):
        """Builds a custom menu for items items"""
        index = self.indexAt(position)  # type: QModelIndex
        menu = QMenu(self)

        if index.isValid():

            if index.data(EnsembleModel.data_type_role
                          ) == WorkspaceDataType.Ensemble:

                # Allow renaming the ensemble via the context menu
                rename_action = QAction("Rename Collection", menu)
                rename_action.triggered.connect(self._rename_action)
                menu.addAction(rename_action)

                # Allow toggling the active ensemble via the context menu
                # * there can only be at most 1 active ensemble
                # * there are only 0 active ensembles when data has not yet been loaded ???
                # * opening data updates the active ensemble to that data
                is_active = index.data(EnsembleModel.active_role)
                active_text = "Active"
                toggle_active_action = QAction(active_text, menu)
                toggle_active_action.setCheckable(True)
                if is_active is True:
                    toggle_active_action.setChecked(True)
                else:
                    toggle_active_action.setChecked(False)
                    toggle_active_action.setText(f"Not {active_text}")

                # Make sure to update the model with the active / deactivated ensemble
                toggle_active_action.toggled.connect(self._set_active_action)
                # Don't allow deactivating the active ensemble if there is only one loaded
                if self.model().rowCount() == 1:
                    toggle_active_action.setEnabled(False)
                menu.addAction(toggle_active_action)

                menu.addSeparator()

            remove_text = "Remove "
            data_type_role = index.data(EnsembleModel.data_type_role)
            if data_type_role == WorkspaceDataType.Ensemble:
                remove_text += "Ensemble"
            elif data_type_role == WorkspaceDataType.Catalog:
                remove_text += "Catalog"
            elif data_type_role == WorkspaceDataType.Intent:
                remove_text += "Item"
            remove_action = QAction(remove_text, menu)
            remove_action.triggered.connect(self._remove_action)
            menu.addAction(remove_action)

        else:
            create_ensemble_action = QAction("Create New Collection", menu)
            create_ensemble_action.triggered.connect(
                self._create_ensemble_action)
            menu.addAction(create_ensemble_action)

        # Display menu wherever the user right-clicked
        menu.popup(self.viewport().mapToGlobal(position))
Exemple #17
0
    def _init_menu_buttons(self):
        """
        Add the two menu buttons to the tool bar. Currently two are defined:
            View - for changing the view of the active window
            Data Processing - for applying a data processing step to the data.

        :return:
        """
        self._option_buttons = [
            self.ui.view_option_button, self.ui.cube_option_button
        ]

        # Create the View Menu
        view_menu = self._dict_to_menu(
            OrderedDict([
                ('Hide Axes', ['checkable', self._toggle_viewer_axes]),
                ('Hide Toolbars', ['checkable', self._toggle_toolbars]),
                ('Hide Spaxel Value Tooltip',
                 ['checkable', self._toggle_hover_value]),
                ('Hide Stats', ['checkable', self._toggle_stats_display]),
                ('Convert Flux Units',
                 lambda: self._open_dialog('Convert Flux Units', None)),
                ('Wavelength Units/Redshift',
                 lambda: self._open_dialog('Wavelength Units/Redshift', None))
            ]))

        # Add toggle RA-DEC format:
        format_menu = view_menu.addMenu("RA-DEC Format")
        format_action_group = QActionGroup(format_menu)
        self.ra_dec_format_menu = format_menu

        # Make sure to change all instances of the the names
        # of the formats if modifications are made to them.
        for format_name in ["Sexagesimal", "Decimal Degrees"]:
            act = QAction(format_name, format_menu)
            act.triggered.connect(self._toggle_all_coords_in_degrees)
            act.setActionGroup(format_action_group)
            act.setCheckable(True)
            act.setChecked(
                True) if format == "Sexagesimal" else act.setChecked(False)
            format_menu.addAction(act)

        self.ui.view_option_button.setMenu(view_menu)

        # Create the Data Processing Menu
        cube_menu = self._dict_to_menu(
            OrderedDict([
                ('Collapse Cube',
                 lambda: self._open_dialog('Collapse Cube', None)),
                ('Spatial Smoothing',
                 lambda: self._open_dialog('Spatial Smoothing', None)),
                ('Moment Maps',
                 lambda: self._open_dialog('Moment Maps', None)),
                ('Arithmetic Operations',
                 lambda: self._open_dialog('Arithmetic Operations', None))
            ]))
        self.ui.cube_option_button.setMenu(cube_menu)
Exemple #18
0
    def _init_menu_buttons(self):
        """
        Add the two menu buttons to the tool bar. Currently two are defined:
            View - for changing the view of the active window
            Data Processing - for applying a data processing step to the data.

        :return:
        """
        self._option_buttons = [
            self.ui.view_option_button,
            self.ui.cube_option_button
        ]

        # Create the View Menu
        view_menu = self._dict_to_menu(OrderedDict([
            ('Hide Axes', ['checkable', self._toggle_viewer_axes]),
            ('Hide Toolbars', ['checkable', self._toggle_toolbars]),
            ('Hide Spaxel Value Tooltip', ['checkable', self._toggle_hover_value]),
            ('Hide Stats', ['checkable', self._toggle_stats_display]),
            ('Flux Units', OrderedDict([
                ('Convert Displayed Units', lambda: self._open_dialog('Convert Displayed Units', None)),
                ('Convert Data Values', lambda: self._open_dialog('Convert Data Values', None)),
                ])
             ),
            ('Wavelength Units/Redshift', lambda: self._open_dialog('Wavelength Units/Redshift', None))
        ]))

        # Add toggle RA-DEC format:
        format_menu = view_menu.addMenu("RA-DEC Format")
        format_action_group = QActionGroup(format_menu)
        self.ra_dec_format_menu = format_menu

        # Make sure to change all instances of the the names
        # of the formats if modifications are made to them.
        for format_name in ["Sexagesimal", "Decimal Degrees"]:
            act = QAction(format_name, format_menu)
            act.triggered.connect(self._toggle_all_coords_in_degrees)
            act.setActionGroup(format_action_group)
            act.setCheckable(True)
            act.setChecked(True) if format == "Sexagesimal" else act.setChecked(False)
            format_menu.addAction(act)

        self.ui.view_option_button.setMenu(view_menu)

        # Create the Data Processing Menu
        cube_menu = self._dict_to_menu(OrderedDict([
            ('Collapse Cube', lambda: self._open_dialog('Collapse Cube', None)),
            ('Spatial Smoothing', lambda: self._open_dialog('Spatial Smoothing', None)),
            ('Moment Maps', lambda: self._open_dialog('Moment Maps', None)),
            ('Arithmetic Operations', lambda: self._open_dialog('Arithmetic Operations', None))
        ]))
        self.ui.cube_option_button.setMenu(cube_menu)
Exemple #19
0
def create_action(parent,
                  text,
                  shortcut=None,
                  icon=None,
                  tip=None,
                  toggled=None,
                  triggered=None,
                  data=None,
                  menurole=None,
                  context=Qt.WindowShortcut):
    """Create a QAction"""
    action = QAction(text, parent)
    if triggered is not None:
        action.triggered.connect(triggered)
    if toggled is not None:
        action.toggled.connect(toggled)
        action.setCheckable(True)
    if icon is not None:
        if is_text_string(icon):
            icon = get_icon(icon)
        action.setIcon(icon)
    if tip is not None:
        action.setToolTip(tip)
        action.setStatusTip(tip)
    if data is not None:
        action.setData(to_qvariant(data))
    if menurole is not None:
        action.setMenuRole(menurole)

    # Workround for Mac because setting context=Qt.WidgetShortcut
    # there doesn't have any effect
    if sys.platform == 'darwin':
        action._shown_shortcut = None
        if context == Qt.WidgetShortcut:
            if shortcut is not None:
                action._shown_shortcut = shortcut
            else:
                # This is going to be filled by
                # main.register_shortcut
                action._shown_shortcut = 'missing'
        else:
            if shortcut is not None:
                action.setShortcut(shortcut)
            action.setShortcutContext(context)
    else:
        if shortcut is not None:
            action.setShortcut(shortcut)
        action.setShortcutContext(context)

    return action
Exemple #20
0
class Viewer(ViewerModel):
    """
    This extends the model by attaching a Qt Window as its view.

    This object is meant to be exposed to the user in an interactive console.
    """
    def __init__(self, *, show=True, title="Demo App"):
        # TODO Where does title thread through?
        super().__init__()

        self._widget = QtViewer(self)
        self._window = Window(self._widget, show=show)

        menu_bar = self._window._qt_window.menuBar()
        menu_item_control = menu_bar.addMenu("Control Actions")
        self.action_activate_env_destroy = QAction(
            "Activate 'Destroy Environment'", self._window._qt_window)
        self.action_activate_env_destroy.setCheckable(True)
        self._update_action_env_destroy_state()
        self.action_activate_env_destroy.triggered.connect(
            self._activate_env_destroy_triggered)
        menu_item_control.addAction(self.action_activate_env_destroy)

        self._widget.model.run_engine.events.status_changed.connect(
            self.on_update_widgets)

    def _update_action_env_destroy_state(self):
        env_destroy_activated = self._widget.model.run_engine.env_destroy_activated
        self.action_activate_env_destroy.setChecked(env_destroy_activated)

    def _activate_env_destroy_triggered(self):
        env_destroy_activated = self._widget.model.run_engine.env_destroy_activated
        self._widget.model.run_engine.activate_env_destroy(
            not env_destroy_activated)

    def on_update_widgets(self, event):
        self._update_action_env_destroy_state()

    @property
    def window(self):
        return self._window

    def show(self):
        """Resize, show, and raise the window."""
        self._window.show()

    def close(self):
        """Close the window."""
        self._window.close()
Exemple #21
0
    def __init__(self, entity, env):
        d = Diagram_Item(entity)
        d.modified_callback = self.set_modified
        super().__init__(d)
        self.modified_callback = env.set_modified
        self.entity = entity

        show_ports_action = QAction("Connection Ports", self)
        self._show_ports_action = show_ports_action
        show_ports_action.setStatusTip("Show connection ports when hovering")
        show_ports_action.setCheckable(True)
        show_ports_action.setChecked(False)
        show_ports_action.setIcon(QIcon.fromTheme("edit-find"))
        show_ports_action.triggered.connect(
            lambda x: d.set_show_connection_ports_on_hover(x))
        self.view_menu.addAction(show_ports_action)
        self.tools.append(show_ports_action)
Exemple #22
0
    def _add_plugin_actions(self, hook_type: str, plugin_name: str,
                            widgets: Sequence[str]):
        from ...plugins import menu_item_template

        multiprovider = len(widgets) > 1
        if multiprovider:
            menu = NapariMenu(plugin_name, self)
            self.addMenu(menu)
        else:
            menu = self

        for wdg_name in widgets:
            key = (plugin_name, wdg_name)
            if multiprovider:
                action = QAction(wdg_name.replace("&", "&&"), parent=self)
            else:
                full_name = menu_item_template.format(*key)
                action = QAction(full_name.replace("&", "&&"), parent=self)

            def _add_toggle_widget(*, key=key, hook_type=hook_type):
                full_name = menu_item_template.format(*key)
                if full_name in self._win._dock_widgets.keys():
                    dock_widget = self._win._dock_widgets[full_name]
                    if dock_widget.isVisible():
                        dock_widget.hide()
                    else:
                        dock_widget.show()
                    return

                if hook_type == 'dock':
                    dock_widget, _w = self._win.add_plugin_dock_widget(*key)
                else:
                    dock_widget = self._win._add_plugin_function_widget(*key)

                # Fixes https://github.com/napari/napari/issues/3624
                dock_widget.setFloating(True)
                dock_widget.setFloating(False)

            action.setCheckable(True)
            # check that this wasn't added to the menu already
            actions = [a.text() for a in menu.actions()]
            if action.text() not in actions:
                menu.addAction(action)
            action.triggered.connect(_add_toggle_widget)
Exemple #23
0
    def _dict_to_menu(self, menu_dict):
        '''Stolen shamelessly from specviz. Thanks!'''
        menu_widget = QMenu()
        for k, v in menu_dict.items():
            if isinstance(v, dict):
                new_menu = menu_widget.addMenu(k)
                self._dict_to_menu(v, menu_widget=new_menu)
            else:
                act = QAction(k, menu_widget)

                if isinstance(v, list):
                    if v[0] == 'checkable':
                        v = v[1]
                        act.setCheckable(True)
                        act.setChecked(True)

                act.triggered.connect(v)
                menu_widget.addAction(act)
        return menu_widget
Exemple #24
0
def dict_to_menu(parent, menu_dict, menu_widget=None):
    if not menu_widget:
        menu_widget = QMenu(parent)
    for k, v in menu_dict.items():
        if isinstance(v, dict):
            new_menu = menu_widget.addMenu(k)
            dict_to_menu(v, menu_widget=new_menu)
        else:
            act = QAction(k, menu_widget)

            if isinstance(v, list):
                if v[0] == 'checkable':
                    v = v[1]
                    act.setCheckable(True)
                    act.setChecked(False)

            act.triggered.connect(v)
            menu_widget.addAction(act)
    return menu_widget
Exemple #25
0
def create_action(parent, text, shortcut=None, icon=None, tip=None,
                  toggled=None, triggered=None, data=None, menurole=None,
                  context=Qt.WindowShortcut):
    """Create a QAction"""
    action = QAction(text, parent)
    if triggered is not None:
        action.triggered.connect(triggered)
    if toggled is not None:
        action.toggled.connect(toggled)
        action.setCheckable(True)
    if icon is not None:
        if is_text_string(icon):
            icon = get_icon(icon)
        action.setIcon(icon)
    if tip is not None:
        action.setToolTip(tip)
        action.setStatusTip(tip)
    if data is not None:
        action.setData(to_qvariant(data))
    if menurole is not None:
        action.setMenuRole(menurole)

    # Workround for Mac because setting context=Qt.WidgetShortcut
    # there doesn't have any effect
    if sys.platform == 'darwin':
        action._shown_shortcut = None
        if context == Qt.WidgetShortcut:
            if shortcut is not None:
                action._shown_shortcut = shortcut
            else:
                # This is going to be filled by
                # main.register_shortcut
                action._shown_shortcut = 'missing'
        else:
            if shortcut is not None:
                action.setShortcut(shortcut)
            action.setShortcutContext(context)
    else:
        if shortcut is not None:
            action.setShortcut(shortcut)
        action.setShortcutContext(context)

    return action
Exemple #26
0
    def _dict_to_menu(self, menu_dict,  menu_widget=None):
        '''Stolen shamelessly from specviz. Thanks!'''
        if not menu_widget:
            menu_widget = QMenu()
        for k, v in menu_dict.items():
            if isinstance(v, dict):
                new_menu = menu_widget.addMenu(k)
                self._dict_to_menu(v, menu_widget=new_menu)
            else:
                act = QAction(k, menu_widget)

                if isinstance(v, list):
                    if v[0] == 'checkable':
                        v = v[1]
                        act.setCheckable(True)
                        act.setChecked(False)

                act.triggered.connect(v)
                menu_widget.addAction(act)
        return menu_widget
Exemple #27
0
def makeAction(parent,
               descr,
               menutext,
               slot,
               icon=None,
               key=None,
               checkable=False):
    a = QAction(parent)
    a.setText(menutext)
    a.setStatusTip(descr)
    a.setToolTip(textwrap.fill(descr, 25))
    if slot:
        a.triggered.connect(slot)
    if icon:
        a.setIcon(getIcon(icon))
    if key:
        a.setShortcut(QKeySequence(key))
    if checkable:
        a.setCheckable(True)
    return a
Exemple #28
0
class MainWindowMenu(QMenu):
    def __init__(self, parent):
        super(MainWindowMenu, self).__init__(parent)
        self.setTitle("QtPyBotnet")

        self.console_action = QAction('Show console', self)
        self.console_action.setObjectName("show_console")
        self.addAction(self.console_action)

        self.stay_top_action = QAction("Stay on top", self)
        self.stay_top_action.setObjectName("stay_top_action")
        self.stay_top_action.setCheckable(True)
        self.stay_top_action.setChecked(
            bool(self.window().windowFlags() & Qt.WindowStaysOnTopHint))
        self.addAction(self.stay_top_action)

        self.style_picker_action = QWidgetAction(self)
        self.style_picker = StylePickerHorizontal(self)
        self.style_picker_action.setDefaultWidget(self.style_picker)
        self.addAction(self.style_picker_action)
Exemple #29
0
    def _action(self,
                title,
                icon,
                shortcut,
                target,
                checkable=False,
                checked=False):

        action = QAction(title, self)
        if icon:
            action.setIcon(self._ide.theme.qicon(icon))
        if shortcut:
            action.setShortcut(shortcut)
            action.setToolTip(u'{} ({})'.format(title.replace(u'&', u''),
                                                shortcut))
        action.triggered.connect(target)
        if checkable:
            action.setCheckable(True)
            action.setChecked(checked)
        action.setPriority(QAction.HighPriority)
        return action
Exemple #30
0
def addaction(name='',
              icon_name='',
              tip='',
              checkable=False,
              slot=None,
              toolbar=None,
              menu=None):
    """Create a new action and add it eventually to a toolbar and a menu
    Parameters
    ----------
    name: (str) Displayed name if should be displayed (for instance in menus)
    icon_name: (str) png file name to produce the icon
    tip: (str) a tooltip to be displayed when hovering above the action
    checkable: (bool) set the checkable state of the action
    slot: (callable) Method or function that will be called when the action is triggered
    toolbar: (QToolBar) a toolbar where action should be added.
    menu: (QMenu) a menu where action should be added.
    """
    if icon_name != '':
        icon = QtGui.QIcon()
        if Path(icon_name).is_file():
            icon.addPixmap(QtGui.QPixmap(icon_name), QtGui.QIcon.Normal,
                           QtGui.QIcon.Off)
        else:
            icon.addPixmap(
                QtGui.QPixmap(f":/icons/Icon_Library/{icon_name}.png"),
                QtGui.QIcon.Normal, QtGui.QIcon.Off)
        action = QAction(icon, name, None)
    else:
        action = QAction(name)

    if slot is not None:
        action.connect_to(slot)
    action.setCheckable(checkable)
    action.setToolTip(tip)
    if toolbar is not None:
        toolbar.addAction(action)
    if menu is not None:
        menu.addAction(action)
    return action
Exemple #31
0
    def getContextMenus(self, event):
        if self._menu: return None

        menu = QMenu(parent=self.getViewWidget())
        menu.setTitle("Slicing")

        if self.slice_direction != 'vertical':
            horizontal_action = QAction('Horizontal slice', menu)
            horizontal_action.toggled.connect(self.sigToggleHorizontalSlice)
            horizontal_action.setCheckable(True)
            menu.addAction(horizontal_action)

        if self.slice_direction != 'horizontal':
            vertical_action = QAction('Vertical slice', menu)
            vertical_action.toggled.connect(self.sigToggleVerticalSlice)
            vertical_action.setCheckable(True)
            menu.addAction(vertical_action)

        if self.slice_direction == 'depth':
            depth_action = QAction('Depth slice', menu)
            depth_action.toggled.connect(self.sigToggleDepthSlice)
            depth_action.setCheckable(True)
            menu.addAction(depth_action)

        make_primary_action = QAction('Set as Primary View', menu)
        make_primary_action.triggered.connect(self.makePrimary)
        menu.addAction(make_primary_action)

        self._menu = menu

        return menu
    def generateContextMenu(self):
        """
        Generate the window's context menu. This first calls the base class's
        context menu generator and then extends it with the filtering options.
        """
        qmenu = super(MessageDisplay, self).generateContextMenu()
        filter_menu = qmenu.addMenu("&View")

        framework_action = QAction('Mantid Log Output', filter_menu)
        framework_action.triggered.connect(self.toggle_filter_framework_output)
        framework_action.setCheckable(True)
        framework_action.setChecked(self.showFrameworkOutput())
        filter_menu.addAction(framework_action)

        filter_menu.addSeparator()

        actions_to_group = []
        active_script_action = QAction("Active Tab Output", filter_menu)
        active_script_action.triggered.connect(self.show_active_script)
        actions_to_group.append(active_script_action)
        all_script_action = QAction('All Script Output', filter_menu)
        all_script_action.triggered.connect(self.show_all_scripts)
        actions_to_group.append(all_script_action)
        hide_all_script_action = QAction("Hide All Script Output", filter_menu)
        hide_all_script_action.triggered.connect(self.hide_all_scripts)
        actions_to_group.append(hide_all_script_action)

        action_group = QActionGroup(filter_menu)
        for action in actions_to_group:
            action_group.addAction(action)
            filter_menu.addAction(action)
            action.setCheckable(True)

        if self.showAllScriptOutput():
            all_script_action.setChecked(True)
        elif self.showActiveScriptOutput():
            active_script_action.setChecked(True)
        else:
            hide_all_script_action.setChecked(True)
        return qmenu
Exemple #33
0
def create_action(
    parent,
    title,
    triggered=None,
    toggled=None,
    shortcut=None,
    icon=None,
    tip=None,
    checkable=None,
    context=Qt.WindowShortcut,
    enabled=None,
):
    """
    Create a new QAction
    """
    action = QAction(title, parent)
    if triggered:
        if checkable:
            action.triggered.connect(triggered)
        else:
            action.triggered.connect(lambda checked=False: triggered())
    if checkable is not None:
        # Action may be checkable even if the toggled signal is not connected
        action.setCheckable(checkable)
    if toggled:
        action.toggled.connect(toggled)
        action.setCheckable(True)
    if icon is not None:
        assert isinstance(icon, QIcon)
        action.setIcon(icon)
    if shortcut is not None:
        action.setShortcut(shortcut)
    if tip is not None:
        action.setToolTip(tip)
        action.setStatusTip(tip)
    if enabled is not None:
        action.setEnabled(enabled)
    action.setShortcutContext(context)
    return action
Exemple #34
0
    def initUI(self):

        exitAct = QAction('&Exit', self)
        exitAct.setShortcut('Ctrl+Q')  # 设置快捷键
        exitAct.setStatusTip('Exit app')  # 设置状态栏提醒
        exitAct.triggered.connect(qApp.quit)

        # 子目录
        impMenu = QMenu('import', self)
        subAct = QAction('test', self)
        impMenu.addAction(subAct)

        # check菜单
        viewStatAct = QAction('View Statusbar', self)
        viewStatAct.setStatusTip('View statusbar')
        viewStatAct.setCheckable(True)  # 开启打钩模式
        viewStatAct.triggered.connect(self.toggleMenu)  # toggleMenu会传入参数

        # 状态栏
        self.statusBar().showMessage('Ready')

        # 菜单栏
        menuBar = self.menuBar()
        fileMenu = menuBar.addMenu('&File')
        fileMenu.addAction(exitAct)
        fileMenu.addMenu(impMenu)
        fileMenu.addAction(viewStatAct)

        self.resize(250, 150)
        self.center()
        self.setWindowTitle('Message box')
        self.show()

        # 工具栏(菜单栏某几个工具的快速使用)
        self.toolbar = self.addToolBar('Exti')
        self.toolbar.addAction(exitAct)
Exemple #35
0
    def initactions(self):
        self.clear()

        self.actions = []

        for category in self.categories:
            if not category in self.panels.keys(): continue
            panels = self.panels[category]
            keys = sorted(panels.keys())
            for panid in keys:
                if category == self.parent().category and panid == self.parent(
                ).panid:
                    continue
                panel = panels[panid]
                action = QAction(panel.windowTitle())
                action.setCheckable(True)
                action.setChecked((category,
                                   panel.panid) in self.panel.bindings)
                action.triggered.connect(
                    FuncToPanel(self.func, category, panel.panid))
                self.addAction(action)
                self.actions.append(action)

            self.addSeparator()
Exemple #36
0
 def _create_action(self,
                    text,
                    slot=None,
                    shortcut=None,
                    icon=None,
                    tip=None,
                    checkable=False,
                    checked=False):
     """Convenience function to create actions"""
     action = QAction(text, self)
     if icon is not None:
         action.setIcon(QIcon(icon))
     if shortcut is not None:
         action.setShortcut(shortcut)
     if tip is not None:
         action.setToolTip(tip)
         action.setStatusTip(tip)
     if slot is not None:
         action.triggered.connect(slot)
     if checkable:
         action.setCheckable(True)
         if checked:
             action.setChecked(True)
     return action
Exemple #37
0
    def getMenuAction(self, menu, title='notitle', action_name='noaction',
                      args=[], kwargs={}):
        # ToDo: Clean this up, it is very hacky
        env = {'app': QApplication.instance(),
               'win': self,
               'action': actions,
               }

        if action_name is not None:

            if action_name.startswith('settings.'):
                setting_id = action_name[len('settings.'):]
                setting = getSetting(setting_id)

                if setting:
                    if setting.enum_options is not None:
                        submenu = QMenu(parent=self, title=title)

                        group = QActionGroup(self)
                        group.setExclusive(True)
                        group.triggered.connect(lambda a: setting.setValue(a.data()))

                        def update(group, val):
                            for act in group.actions():
                                if act.data() == val:
                                    act.setChecked(True)
                                    break

                        for num, opt in enumerate(setting.enum_options):

                            act = QAction(parent=self, text=opt)
                            act.setCheckable(True)
                            if setting.value == num:
                                act.setChecked(True)

                            act.setData(num)
                            setting.notify(lambda v: update(group, v))

                            act.setActionGroup(group)
                            submenu.addAction(act)
                        menu.addMenu(submenu)

                    elif setting.value_type == bool:
                        # works for bool settings
                        menu_action = QAction(parent=self, text=title)
                        menu_action.setCheckable(True)
                        menu_action.triggered.connect(setting.setValue)
                        setting.notify(menu_action.setChecked)
                        menu.addAction(menu_action)

                    return

            try:
                menu_action = QAction(parent=self, text=title)

                mod, action = action_name.split('.', 1)
                method = getattr(env.get(mod, self), action)
                if menu_action.isCheckable():
                    menu_action.triggered.connect(method)
                else:
                    menu_action.triggered.connect(lambda checked: method(*args, **kwargs))

                menu.addAction(menu_action)
                return
            except:
                pass

            try:
                menu_action = QAction(parent=self, text=title)
                actions.bindWidget(menu_action, action_name)
                menu.addAction(menu_action)
                return
            except actions.InvalidAction:
                LOG.exception('Error binding menu action %s', action_name)

        menu_action = QAction(parent=self, text=title)
        msg = "The <b>{}</b> action specified for the " \
              "<b>{}</b> menu item could not be triggered. " \
              "Check the YAML config file for errors." \
              .format(action_name or '', title.replace('&', ''))
        menu_action.triggered.connect(lambda: QMessageBox.critical(self, "Menu Action Error!", msg))
        menu.addAction(menu_action)
Exemple #38
0
class MOSViewerToolbar(BasicToolbar):
    def __init__(self, *args, **kwargs):
        super(MOSViewerToolbar, self).__init__(*args, **kwargs)
        # self.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)

        # Define icon path
        icon_path = os.path.join(os.path.dirname(__file__),
                                 'ui', 'icons')

        # Define the toolbar actions
        self.cycle_previous_action = QAction(
            QIcon(os.path.join(icon_path, "Previous-96.png")),
            "Previous", self)
        self.cycle_next_action = QAction(
            QIcon(os.path.join(icon_path, "Next-96.png")),
            "Next", self)

        # Include the dropdown widget
        self.source_select = QComboBox()

        # Add the items to the toolbar
        self.addAction(self.cycle_previous_action)
        self.addAction(self.cycle_next_action)
        self.addWidget(self.source_select)

        # Include a button to open spectrum in specviz
        self.open_specviz = QAction(
            QIcon(os.path.join(icon_path, "External-96.png")),
            "Open in SpecViz", self)

        # Create a tool button to hold the lock axes menu object
        tool_button = QToolButton(self)
        tool_button.setText("Axes Settings")
        tool_button.setIcon(QIcon(os.path.join(icon_path, "Settings-96.png")))
        tool_button.setPopupMode(QToolButton.MenuButtonPopup)

        # Create a menu for the axes settings drop down
        self.settings_menu = QMenu(self)

        # Add lock x axis action
        self.lock_x_action = QAction("Lock X Axis",
                                     self.settings_menu)
        self.lock_x_action.setCheckable(True)

        # Add lock y axis action
        self.lock_y_action = QAction("Lock Y Axis",
                                     self.settings_menu)
        self.lock_y_action.setCheckable(True)

        # Add the actions to the menu
        self.settings_menu.addAction(self.lock_x_action)
        self.settings_menu.addAction(self.lock_y_action)

        # Set the menu object on the tool button
        tool_button.setMenu(self.settings_menu)

        # Create a widget action object to hold the tool button, this way the
        # toolbar behaves the way it's expected to
        tool_button_action = QWidgetAction(self)
        tool_button_action.setDefaultWidget(tool_button)

        self.addAction(tool_button_action)
        self.addSeparator()
        self.addAction(self.open_specviz)