Exemplo n.º 1
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())
Exemplo n.º 2
0
 def more_options_device_view(self, button):
     if 'Disconnect' in button.text():
         menu = QMenu("Menu", self)
         menu.addAction("Pair / Ping", self.ping_paired_device)
         menu.addAction("Attempt TCPIP on device", self.tcpip_paired_device)
         menu.addAction("Forget device", self.forget_paired_device)
     else:
         menu = QMenu("Menu", self)
         menu.addAction("Attempt TCPIP on device", self.tcpip_paired_device)
         menu.addAction("Attempt reconnection", self.ping_paired_device)
         menu.addAction("Refresh", self.refresh_devices)
     _, identifier = self.current_device_identifier()
     if platform.System.system() == "Linux" and identifier.count('.') >= 3:
         menu.addAction(
             "Add Desktop Shortcut to this device",
             self.create_desktop_shortcut_linux_os
         )
     menu.exec_(
         self.devices_view.mapToGlobal(
             QPoint(
                 self.devices_view.visualItemRect(button).x() + 22,
                 self.devices_view.visualItemRect(button).y() + 22
             )
         )
     )
Exemplo n.º 3
0
class DataResourceView(QObject):
    def __init__(self, model: QAbstractItemModel):
        super(DataResourceView, self).__init__()
        self._model = model  # type: QAbstractItemModel
        self.setModel(self._model)
        self.doubleClicked.connect(self.open)
        self.setSelectionMode(self.ExtendedSelection)
        self.setSelectionBehavior(self.SelectRows)
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.menuRequested)

        self.menu = QMenu()
        standardActions = [
            QAction("Open", self),
            QAction("Open Externally", self),
            QAction("Enable/Disable Streaming", self),
            QAction("Delete", self),
        ]
        self.menu.addActions(standardActions)
        standardActions[0].triggered.connect(self.open)
        standardActions[1].triggered.connect(self.openExternally)

    def menuRequested(self, position):
        self.menu.exec_(self.viewport().mapToGlobal(position))

    def open(self, index):
        pass

    def currentChanged(self, current, previous):
        pass

    def openExternally(self, uri: str):
        pass
Exemplo n.º 4
0
 def PopupMenu( self, window: QW.QWidget, menu: QW.QMenu ):
     
     if HC.PLATFORM_MACOS and window.window().isModal():
         
         # Ok, seems like Big Sur can't do menus at the moment lmao. it shows the menu but the mouse can't interact with it
         
         from hydrus.core import HydrusGlobals as HG
         
         if HG.client_controller.new_options.GetBoolean( 'do_macos_debug_dialog_menus' ):
             
             from hydrus.client.gui import ClientGUICoreMenuDebug
             
             ClientGUICoreMenuDebug.ShowMenuDialog( window, menu )
             
             ClientGUIMenus.DestroyMenu( menu )
             
             return
             
         
     
     if not menu.isEmpty():
         
         self._menu_open = True
         
         menu.exec_( QG.QCursor.pos() ) # This could also be window.mapToGlobal( QC.QPoint( 0, 0 ) ), but in practice, popping up at the current cursor position feels better.
         
         self._menu_open = False
         
     
     ClientGUIMenus.DestroyMenu( menu )
 def openMenu(self, position):
     indexes = self.ui.treeWidget.selectedIndexes()
     item = self.ui.treeWidget.itemAt(position)
     db_origin = ""
     #if item.parent():
     #   db_origin = item.parent().text(0)
     collec = str(item.text(0).encode("utf-8"))
     if len(indexes) > 0:
         level = 0
         index = indexes[0]
         while index.parent().isValid():
             index = index.parent()
             level = level + 1
         menu = QMenu()
         #print((collec, db_origin))
         if level == 0:
             pass
         else:
             #keyarray = GetKeys(collec, db_origin)
             #if "Open" in keyarray:
             if self.ui.combobox.currentText() == u"回测分析系统":
                 menu.addAction(QAction("ATP model", menu, checkable=True))
             if self.ui.combobox.currentText() == u"获取历史K线":
                 menu.addAction(QAction("Kline", menu, checkable=True))
                 menu.addAction(QAction("Open", menu, checkable=True))
                 menu.addAction(
                     QAction("Close", menu, checkable=True)
                 )  #open up different menu with different kind of graphs
                 menu.addAction(QAction("High", menu, checkable=True))
                 menu.addAction(QAction("Low", menu, checkable=True))
                 menu.addAction(QAction("Volume", menu, checkable=True))
                 #menu.addAction(QAction("P_change", menu, checkable=True))
                 #menu.addAction(QAction("Turnover",menu,checkable=True))
             if self.ui.combobox.currentText() == u"获取复权数据":
                 menu.addAction(QAction("Kline", menu, checkable=True))
                 menu.addAction(QAction("Open", menu, checkable=True))
                 menu.addAction(QAction("Close", menu, checkable=True))
                 menu.addAction(QAction("High", menu, checkable=True))
                 menu.addAction(QAction("Low", menu, checkable=True))
                 menu.addAction(QAction("Volume", menu, checkable=True))
                 menu.addAction(QAction("Amount", menu, checkable=True))
             if self.ui.combobox.currentText() == u"获取分笔数据":
                 menu.addAction(QAction("分笔", menu, checkable=True))
             if self.ui.combobox.currentText() == u"获取历史分钟数据":
                 menu.addAction(QAction("Kline", menu, checkable=True))
                 menu.addAction(QAction("Open", menu, checkable=True))
                 menu.addAction(QAction("Close", menu, checkable=True))
                 menu.addAction(QAction("High", menu, checkable=True))
                 menu.addAction(QAction("Low", menu, checkable=True))
                 menu.addAction(QAction("Volume", menu, checkable=True))
                 menu.addAction(QAction("Amount", menu, checkable=True))
             if self.ui.combobox.currentText() == u"分析十大股东":
                 menu.addAction(QAction("季度饼图", menu, checkable=True))
                 #menu.addAction(QAction("持股比例", menu, checkable=True))
             #for g in keyarray:
             #menu.addAction(QAction(g, menu, checkable=True))
     menu.triggered.connect(
         lambda action: self.methodSelected(action, collec))
     menu.exec_(self.ui.treeWidget.viewport().mapToGlobal(position))
Exemplo n.º 6
0
 def tableMenu(self, event):
     """Right click menu for table, can plot or print selected logs"""
     menu = QMenu(self)
     plotAction = menu.addAction("Plot selected")
     plotAction.triggered.connect(self.presenter.new_plot_logs)
     plotAction = menu.addAction("Print selected")
     plotAction.triggered.connect(self.presenter.print_selected_logs)
     menu.exec_(event.globalPos())
Exemplo n.º 7
0
 def tableMenu(self, event):
     """Right click menu for table, can plot or print selected logs"""
     menu = QMenu(self)
     plotAction = menu.addAction("Plot selected")
     plotAction.triggered.connect(self.presenter.new_plot_logs)
     plotAction = menu.addAction("Print selected")
     plotAction.triggered.connect(self.presenter.print_selected_logs)
     menu.exec_(event.globalPos())
Exemplo n.º 8
0
 def contextMenuEvent(self, event):
     """."""
     pos = self.mapToGlobal(event.pos())
     if self._is_graph(pos):
         return
     context_menu = QMenu(self)
     action = context_menu.addAction('Show Connections...')
     action.triggered.connect(self.show_connections)
     context_menu.exec_(pos)
Exemplo n.º 9
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)
Exemplo n.º 10
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)
Exemplo n.º 11
0
    def _dim_order_menu(self, point: QPoint):
        menu = QMenu()
        for key in ORDER_DICT:
            action = menu.addAction(key)
            action.triggered.connect(partial(self._set_new_order, key))
            if key == self._current_order:
                font = action.font()
                font.setBold(True)
                action.setFont(font)

        menu.exec_(self.roll_dim_button.mapToGlobal(point))
Exemplo n.º 12
0
 def openMenu(self,position):
     indexes = self.ui.treeWidget.selectedIndexes()
     item = self.ui.treeWidget.itemAt(position)
     db_origin = ""
     #if item.parent():
      #   db_origin = item.parent().text(0)
     collec = str(item.text(0).encode("utf-8"))
     if len(indexes) > 0:
         level = 0
         index = indexes[0]
         while index.parent().isValid():
             index = index.parent()
             level = level + 1
         menu = QMenu()
         #print((collec, db_origin))
         if level ==0:
             pass
         else:
             #keyarray = GetKeys(collec, db_origin)
             #if "Open" in keyarray:
             if self.ui.combobox.currentText()==u"K线":
                 menu.addAction(QAction("Kline", menu, checkable=True))
                 menu.addAction(QAction("Open", menu, checkable=True))
                 menu.addAction(QAction("Close", menu, checkable=True))#open up different menu with different kind of graphs
                 menu.addAction(QAction("High", menu, checkable=True))
                 menu.addAction(QAction("Low", menu, checkable=True))
                 menu.addAction(QAction("Volume", menu, checkable=True))
                 #menu.addAction(QAction("P_change", menu, checkable=True))
                 #menu.addAction(QAction("Turnover",menu,checkable=True))
             if self.ui.combobox.currentText()==u"复权":
                 menu.addAction(QAction("Kline", menu, checkable=True))
                 menu.addAction(QAction("Open", menu, checkable=True))
                 menu.addAction(QAction("Close", menu, checkable=True))
                 menu.addAction(QAction("High", menu, checkable=True))
                 menu.addAction(QAction("Low", menu, checkable=True))
                 menu.addAction(QAction("Volume", menu, checkable=True))
                 menu.addAction(QAction("Amount", menu, checkable=True))
             if self.ui.combobox.currentText()==u"分笔数据":
                 menu.addAction(QAction("分笔", menu, checkable=True))
             if self.ui.combobox.currentText()==u"历史分钟":
                 menu.addAction(QAction("Kline", menu, checkable=True))
                 menu.addAction(QAction("Open", menu, checkable=True))
                 menu.addAction(QAction("Close", menu, checkable=True))
                 menu.addAction(QAction("High", menu, checkable=True))
                 menu.addAction(QAction("Low", menu, checkable=True))
                 menu.addAction(QAction("Volume", menu, checkable=True))
                 menu.addAction(QAction("Amount", menu, checkable=True))
             if self.ui.combobox.currentText()==u"十大股东":
                 menu.addAction(QAction("季度饼图", menu, checkable=True))
                 #menu.addAction(QAction("持股比例", menu, checkable=True))
             #for g in keyarray:
             #menu.addAction(QAction(g, menu, checkable=True))
     menu.triggered.connect(lambda action: self.methodSelected(action, collec))
     menu.exec_(self.ui.treeWidget.viewport().mapToGlobal(position))
Exemplo n.º 13
0
 def files_context_menu(self, point: QPoint):
     element = self.selected_files.itemAt(point)
     if element is None:
         return
     menu = QMenu()
     menu.addAction("Load image").triggered.connect(self._load_file)
     for mask_def in self.mask_list:
         menu.addAction(
             f"Load with mask '{mask_def.name}'").triggered.connect(
                 partial(self._load_file_with_mask, mask_def))
     menu.addAction("Delete").triggered.connect(self.delete_element)
     menu.exec_(self.selected_files.mapToGlobal(point))
Exemplo n.º 14
0
 def openWidgetMenu(self,position):
     indexes = self.ui.treeWidget_2.selectedIndexes()
     item = self.ui.treeWidget_2.itemAt(position)
     #item = self.ui.listWidget.itemAt(position)
     if len(indexes) > 0:
         menu = QMenu()
         menu.addAction(QAction("Delete", menu,checkable = True))#This function is perhaps useless
         #menu.triggered.connect(self.eraseItem)
         item = self.ui.treeWidget_2.itemAt(position)
         #collec = str(item.text())
         menu.triggered.connect(lambda action: self.ListMethodSelected(action, item))
     menu.exec_(self.ui.treeWidget_2.viewport().mapToGlobal(position))
Exemplo n.º 15
0
 def openWidgetMenu(self,position):
     indexes = self.ui.treeWidget_2.selectedIndexes()
     item = self.ui.treeWidget_2.itemAt(position)
     if item == None:
         return
     #item = self.ui.listWidget.itemAt(position)
     if len(indexes) > 0:
         menu = QMenu()
         menu.addAction(QAction("Delete", menu,checkable = True))#This function is perhaps useless
         #menu.triggered.connect(self.eraseItem)
         item = self.ui.treeWidget_2.itemAt(position)
         #collec = str(item.text())
         menu.triggered.connect(lambda action: self.ListMethodSelected(action, item))
     menu.exec_(self.ui.treeWidget_2.viewport().mapToGlobal(position))
Exemplo n.º 16
0
 def openMenu(self, position):
     indexes = self.ui.stocks_tree.selectedIndexes()
     item = self.ui.stocks_tree.itemAt(position)
     collec = str(item.text(0).encode("utf-8"))
     menu = QMenu()
     if len(indexes) > 0:
         level = 0
         index = indexes[0]
         while index.parent().isValid():
             index = index.parent()
             level = level + 1
         if level == 0:
             pass
         else:
             if self.ui.stock_option_combobox.currentText() == u"K线":
                 menu.addAction(QAction("Kline", menu, checkable=True))
                 menu.addAction(QAction("Open", menu, checkable=True))
                 menu.addAction(
                     QAction("Close", menu, checkable=True)
                 )  #open up different menu with different kind of graphs
                 menu.addAction(QAction("High", menu, checkable=True))
                 menu.addAction(QAction("Low", menu, checkable=True))
                 menu.addAction(QAction("Volume", menu, checkable=True))
                 #menu.addAction(QAction("P_change", menu, checkable=True))
                 #menu.addAction(QAction("Turnover",menu,checkable=True))
             if self.ui.stock_option_combobox.currentText() == u"复权":
                 menu.addAction(QAction("Kline", menu, checkable=True))
                 menu.addAction(QAction("Open", menu, checkable=True))
                 menu.addAction(QAction("Close", menu, checkable=True))
                 menu.addAction(QAction("High", menu, checkable=True))
                 menu.addAction(QAction("Low", menu, checkable=True))
                 menu.addAction(QAction("Volume", menu, checkable=True))
                 menu.addAction(QAction("Amount", menu, checkable=True))
             if self.ui.stock_option_combobox.currentText() == u"分笔数据":
                 menu.addAction(QAction("分笔", menu, checkable=True))
             if self.ui.stock_option_combobox.currentText() == u"历史分钟":
                 menu.addAction(QAction("Kline", menu, checkable=True))
                 menu.addAction(QAction("Open", menu, checkable=True))
                 menu.addAction(QAction("Close", menu, checkable=True))
                 menu.addAction(QAction("High", menu, checkable=True))
                 menu.addAction(QAction("Low", menu, checkable=True))
                 menu.addAction(QAction("Volume", menu, checkable=True))
                 menu.addAction(QAction("Amount", menu, checkable=True))
             if self.ui.stock_option_combobox.currentText() == u"十大股东":
                 menu.addAction(QAction("季度饼图", menu, checkable=True))
                 #menu.addAction(QAction("持股比例", menu, checkable=True))
     menu.triggered.connect(
         lambda action: self.addActionSelected(action, collec))
     menu.exec_(self.ui.stocks_tree.viewport().mapToGlobal(position))
 def openWidgetMenu(self, position):
     indexes = self.ui.stocks_tree.selectedIndexes()
     item = self.ui.stocks_tree.itemAt(position)
     if item == None:
         return
     if len(indexes) > 0:
         menu = QMenu()
         menu.addAction(QAction("Delete", menu, checkable=True))
         #menu.triggered.connect(self.eraseItem)
         item = self.ui.stocks_tree.itemAt(position)
         # collec = str(item.text())
         # print(collec)
         menu.triggered.connect(
             lambda action: self.ListMethodSelected(action, item))
         menu.exec_(self.ui.stocks_tree.viewport().mapToGlobal(position))
         self.ui.stocks_tree.itemClicked.connect(self.onItemClick(item))
Exemplo n.º 18
0
    def show_context_menu(self, pos: QPoint):
        '''
        Show context menu

        Parameters
        ----------
        pos : QPoint
        '''
        menu = QMenu(self)
        menu.addAction("Detach Area", self.on_undock_button_clicked)
        menu.addSeparator()
        action = menu.addAction("Close Area", self.on_close_button_clicked)
        action.setEnabled(self.d.dock_area.closable)

        menu.addAction("Close Other Areas", self.d.dock_area.close_other_areas)
        menu.exec_(self.mapToGlobal(pos))
Exemplo n.º 19
0
 def showContextMenu(self, point):
     item = self.itemAt(point)
     if item is None:
         return
     menu = QMenu()
     if item.parent() is not None:
         action1 = QAction("Load")
         action1.triggered.connect(partial(self.context_load.emit, item))
         menu.addAction(action1)
         if self.compare and item.text(0) not in ["raw image", "image with mask"]:
             action2 = QAction("Compare")
             action2.triggered.connect(partial(self.context_compare.emit, item))
             menu.addAction(action2)
     action = QAction("Forget")
     action.triggered.connect(partial(self.context_forget.emit, item))
     menu.addAction(action)
     menu.exec_(self.mapToGlobal(point))
Exemplo n.º 20
0
    def onCustomTrackMenuRequested(self):
        menu = QMenu("Animator Track Context")
        itemTitle = menu.addAction('Create Custom Animator Track')
        itemTitle.setEnabled(False)
        menu.addSeparator()
        #check if there is animator track
        trackTypes = _MOCK.getCustomAnimatorTrackTypesForObject(
            self.getTarget())
        if not trackTypes: return
        for id, clas in list(trackTypes.items()):
            action = menu.addAction(id)

            def _makeTrackCreator(trackId):
                return lambda x: self.addCustomAnimatorTrack(trackId)

            action.triggered.connect(_makeTrackCreator(id))
            action.setIcon(getIcon('object_track'))
        menu.exec_(QtGui.QCursor.pos())
Exemplo n.º 21
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())
Exemplo n.º 22
0
    def contextMenuEvent(self, event):
        """也叫弹出式菜单, 就是右键单击弹出"""
        cmenu = QMenu(self)

        newAct = cmenu.addAction('New')
        openAct = cmenu.addAction('Open')
        quitAct = cmenu.addAction('Quit')

        # 从event获取位置信息, 通过mapToGlobal
        action = cmenu.exec_(self.mapToGlobal(event.pos()))
        if action == quitAct:
            qApp.quit()
Exemplo n.º 23
0
    def _show_markers_menu(self, markers, event):
        """
        This is opened when right-clicking on top of a marker.
        The menu will have an entry for each marker near the cursor at the time of clicking.
        The menu will allow deletion and single marker editing
        :param markers: list of markers close to the cursor at the time of clicking
        :param event: The MouseEvent that generated this call
        """
        if not event.inaxes:
            return

        QApplication.restoreOverrideCursor()
        fig_type = figure_type(self.canvas.figure)
        if fig_type == FigureType.Empty or fig_type == FigureType.Image:
            return

        menu = QMenu()

        for marker in markers:
            self._single_marker_menu(menu, marker)

        menu.exec_(QCursor.pos())
Exemplo n.º 24
0
    def _open_menu(self, point):
        menu = QMenu()
        index = self.indexAt(point)
        item = self.model().getItem(index)
        self.value_action = QAction(item.status, self)
        self.value_action.setEnabled(False)

        menu.addAction(self.value_action)

        self.acknowledge_action = QAction("Acknowledge", self)
        self.acknowledge_action.triggered.connect(
            partial(self._acknowledge_at_index, index))
        menu.addAction(self.acknowledge_action)

        self.remove_acknowledge_action = QAction("Remove Acknowledge", self)
        self.remove_acknowledge_action.triggered.connect(
            partial(self._remove_acknowledge_at_index, index))
        self.remove_acknowledge_action.setEnabled(False)

        menu.addAction(self.remove_acknowledge_action)

        menu.exec_(self.viewport().mapToGlobal(point))
Exemplo n.º 25
0
    def header_menu(self, position):
        '''
        Creates a menu allowing users to show and hide columns
        '''
        header = self.sender()  # type: QHeaderView
        index = header.logicalIndexAt(position)
        menu = QMenu("Options")
        action = menu.addAction("Hide Column")  # type: QAction
        column_name = str(header.model().headerData(index, Qt.Horizontal))
        action.triggered.connect(lambda: self.hide_column(header, index))
        show_columns_menu = menu.addMenu("Show Columns")

        for i in range(header.count()):
            if header.isSectionHidden(i):
                column_name = str(header.model().headerData(i, Qt.Horizontal))
                action = show_columns_menu.addAction(column_name)
                action.triggered.connect(
                    functools.partial(self.unhide_column, header, i))
                # why does below work, but not: lambda: self.unhide_column(header, i)
                # action.triggered.connect(lambda triggered, logicalIndex=i: self.unhide_column(header, logicalIndex))

        menu.exec_(header.mapToGlobal(position))
Exemplo n.º 26
0
    def _popup_menu(self, event):
        axes = self._find_calling_axes(event)  # find axes calling right click
        if axes is None: return

        pos = self.parent.mapFromGlobal(QtGui.QCursor().pos())

        popup_menu = QMenu(self.parent)
        xScaleMenu = popup_menu.addMenu('x-scale')
        yScaleMenu = popup_menu.addMenu('y-scale')

        for coord in ['x', 'y']:
            menu = eval(coord + 'ScaleMenu')
            for type in axes.scale[coord].keys():
                action = QAction(type, menu, checkable=True)
                if axes.scale[coord][type]:  # if it's checked
                    action.setEnabled(False)
                else:
                    action.setEnabled(True)
                menu.addAction(action)
                action.setChecked(axes.scale[coord][type])
                fcn = lambda event, coord=coord, type=type: self._set_scale(
                    coord, type, axes, True)
                action.triggered.connect(fcn)

        # Create menu for AutoScale options X Y All
        popup_menu.addSeparator()
        autoscale_options = ['AutoScale X', 'AutoScale Y', 'AutoScale All']
        for n, text in enumerate(autoscale_options):
            action = QAction(text, menu, checkable=True)
            if n < len(self.autoScale):
                action.setChecked(self.autoScale[n])
            else:
                action.setChecked(all(self.autoScale))
            popup_menu.addAction(action)
            action.toggled.connect(
                lambda event, n=n: self._setAutoScale(n, event, axes))

        popup_menu.exec_(self.parent.mapToGlobal(pos))
Exemplo n.º 27
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:
            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)
        else:
            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)

        # Able to change the plot type to waterfall if there is only one axes, it is a MantidAxes, and there is more
        # than one line on the axes.
        if len(event.inaxes.get_figure().get_axes()) == 1 and isinstance(event.inaxes, MantidAxes)\
                and len(event.inaxes.get_lines()) > 1:
            self._add_plot_type_option_menu(menu, event.inaxes)

        menu.exec_(QCursor.pos())
Exemplo n.º 28
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()
Exemplo n.º 29
0
    def onFieldContextMenuRequested(self, target, fieldId):
        menu = QMenu("Field Context")
        itemTitle = menu.addAction('[ %s ]' % fieldId)
        itemTitle.setEnabled(False)
        menu.addSeparator()

        animator = app.getModule('animator')
        if animator:
            itemAddKey = menu.addAction('Add key')
            itemAddKey.setIcon(getIcon('key'))
            itemAddKey.triggered.connect(self.onFieldAddKey)
            menu.addSeparator()

        itemDefault = menu.addAction('Set Default')
        itemDefault.triggered.connect(self.onFieldResetDefault)

        if _MOCK.isProtoInstanceOverrided(target, fieldId):
            menu.addSeparator()
            itemProtoReset = menu.addAction('Reset To Proto Value')
            itemProtoReset.triggered.connect(self.onFieldResetProto)
            itemProtoReset.setIcon(getIcon('reset'))

        self.currentFieldContext = (target, fieldId)
        menu.exec_(QtGui.QCursor.pos())
Exemplo n.º 30
0
    def showContextMenu(self, point):
        p = self._list.mapToGlobal(point)
        menu = QMenu()
        check_selected = menu.addAction("Check selected")
        uncheck_selected = menu.addAction("Uncheck selected")
        menu.addSeparator()
        clear_selection = menu.addAction("Clear selection")

        selected_item = menu.exec_(p)

        if selected_item == check_selected:
            self.checkSelected()
        elif selected_item == uncheck_selected:
            self.uncheckSelected()
        elif selected_item == clear_selection:
            self._list.clearSelection()
Exemplo n.º 31
0
class CustomMenu(QtWidgets.QPushButton):
    """合约管理组件"""
    signal = QtCore.Signal(type(Event()))

    # ----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        super(CustomMenu, self).__init__()
        self.parent = parent

        # self.initUi()
        self.initMenu()

    #-----------------------------------------------------------------------
    def initMenu(self):
        self.setStyleSheet(
            "QMenu{background:purple;}"
            "QMenu{border:1px solid lightgray;}"
            "QMenu{border-color:green;}"
            "QMenu::item{padding:0px 20px 0px 15px;}"
            "QMenu::item{height:30px;}"
            "QMenu::item{color:blue;}"
            "QMenu::item{background:white;}"
            "QMenu::item{margin:1px 0px 0px 0px;}"
            "QMenu::item:selected:enabled{background:lightgray;}"
            "QMenu::item:selected:enabled{color:blue;}"
            "QMenu::item:selected:!enabled{background:transparent;}"
            "QMenu::separator{height:50px;}"
            "QMenu::separator{width:1px;}"
            "QMenu::separator{background:white;}"
            "QMenu::separator{margin:1px 1px 1px 1px;}"
            "QMenu#menu{background:white;}"
            "QMenu#menu{border:1px solid lightgray;}"
            "QMenu#menu::item{padding:0px 20px 0px 15px;}"
            "QMenu#menu::item{height:15px;}"
            "QMenu#menu::item:selected:enabled{background:lightgray;}"
            "QMenu#menu::item:selected:enabled{color:white;}"
            "QMenu#menu::item:selected:!enabled{background:transparent;}"
            "QMenu#menu::separator{height:1px;}"
            "QMenu#menu::separator{background:lightgray;}"
            "QMenu#menu::separator{margin:2px 0px 2px 0px;}"
            "QMenu#menu::indicator {padding:5px;}")
        self.color = QColor(Qt.gray)
        self.opacity = 1.0
        '''''' ' 创建右键菜单 ' ''
        # 必须将ContextMenuPolicy设置为Qt.CustomContextMenu
        # 否则无法使用customContextMenuRequested信号
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.showContextMenu)

        # 创建QMenu
        self.contextMenu = QMenu(self)
        self.trendMenu = self.contextMenu.addMenu(u"k线形态")
        self.swingMenu = self.contextMenu.addMenu(u"技术指标")
        self.amountMenu = self.contextMenu.addMenu(u"策略研究")
        self.pzxzMenu = self.contextMenu.addMenu(u"品种选择")
        # 添加二级菜单

        #趋势分析指标
        self.actionSAR = self.trendMenu.addAction(u'k线')
        self.actionSAR.triggered.connect(
            lambda: self.parent.initIndicator(u"KLINE"))

        self.actionMA = self.trendMenu.addAction(u'信号隐藏')
        self.actionMA.triggered.connect(
            lambda: self.parent.initIndicator(u"信号隐藏"))

        self.actionMA = self.trendMenu.addAction(u'信号显示')
        self.actionMA.triggered.connect(
            lambda: self.parent.initIndicator(u"信号显示"))

        #摆动分析
        self.actionCCI = self.swingMenu.addAction(u'MA SHORT')
        self.actionCCI.triggered.connect(
            lambda: self.parent.initIndicator(u"MA SHORT"))
        self.actionROC = self.swingMenu.addAction(u'MA LONG')
        self.actionROC.triggered.connect(
            lambda: self.parent.initIndicator(u"MA LONG"))
        self.actionSHORTTERM = self.swingMenu.addAction(u'SHORT TERM(Limit)')
        self.actionSHORTTERM.triggered.connect(
            lambda: self.parent.initIndicator(u"SHORT TERM(Limit)"))
        self.actionSHORTTERMF = self.swingMenu.addAction(u'SHORT TERM(First)')
        self.actionSHORTTERMF.triggered.connect(
            lambda: self.parent.initIndicator(u"SHORT TERM(First)"))
        self.actionSHORTTERMALL = self.swingMenu.addAction(u'SHORT TERM(All)')
        self.actionSHORTTERMALL.triggered.connect(
            lambda: self.parent.initIndicator(u"SHORT TERM(All)"))
        self.actionWAIBAORI = self.swingMenu.addAction(u'外包日')
        self.actionWAIBAORI.triggered.connect(
            lambda: self.parent.initIndicator(u"外包日"))
        self.actionGJR_BUY = self.swingMenu.addAction(u'攻击日(买入)')
        self.actionGJR_BUY.triggered.connect(
            lambda: self.parent.initIndicator(u"攻击日(买入)"))
        self.actionGJR_SELL = self.swingMenu.addAction(u'攻击日(卖出)')
        self.actionGJR_SELL.triggered.connect(
            lambda: self.parent.initIndicator(u"攻击日(卖出)"))

        ##设为起始日期
        self.actionOPI = self.amountMenu.addAction(u'设为起始日期')
        self.actionOPI.triggered.connect(
            lambda: self.parent.initIndicator(u"设为起始日期"))

        self.actionOPI1 = self.amountMenu.addAction(u'设为结束日期')
        self.actionOPI1.triggered.connect(
            lambda: self.parent.initIndicator(u"设为结束日期"))

        ##量仓分析
        self.actionOPI2 = self.amountMenu.addAction(u'MA_螺纹空_PLUS')
        self.actionOPI2.triggered.connect(
            lambda: self.parent.initIndicator(u"MA_螺纹空_PLUS"))

        ##成交量分析
        self.actionVOL = self.amountMenu.addAction(u'SHORTTERM_螺纹_多')
        self.actionVOL.triggered.connect(
            lambda: self.parent.initIndicator(u"SHORTTERM_螺纹_多"))

        self.action1 = self.amountMenu.addAction(u'SHORTTERM_螺纹_空')
        self.action1.triggered.connect(
            lambda: self.parent.initIndicator(u"SHORTTERM_螺纹_空"))

        self.action2 = self.amountMenu.addAction(u'SHORTTERM_螺纹_多_加仓')
        self.action2.triggered.connect(
            lambda: self.parent.initIndicator(u"SHORTTERM_螺纹_多_加仓"))

        self.action5 = self.amountMenu.addAction(u'VOLATILITY_螺纹_多')
        self.action5.triggered.connect(
            lambda: self.parent.initIndicator(u"VOLATILITY_螺纹_多"))

        self.action6 = self.amountMenu.addAction(u'VOLATILITY_螺纹_空')
        self.action6.triggered.connect(
            lambda: self.parent.initIndicator(u"VOLATILITY_螺纹_空"))

        self.action9 = self.amountMenu.addAction(u'VOLATILITY_螺纹_V1')
        self.action9.triggered.connect(
            lambda: self.parent.initIndicator(u"VOLATILITY_螺纹_V1"))

        self.action7 = self.amountMenu.addAction(u'外包日_螺纹_多')
        self.action7.triggered.connect(
            lambda: self.parent.initIndicator(u"外包日_螺纹_多"))

        self.action3 = self.pzxzMenu.addAction(u'RB9999')
        self.action3.triggered.connect(
            lambda: self.parent.initIndicator(u"RB9999"))

        self.action4 = self.pzxzMenu.addAction(u'BU9999')
        self.action4.triggered.connect(
            lambda: self.parent.initIndicator(u"BU9999"))

        #self.contextMenu.exec_(QCursor.pos())  # 在鼠标位置显示
        #添加二级菜单

    def showContextMenu(self, pos):
        '''''
        右键点击时调用的函数
        '''
        # 菜单显示前,将它移动到鼠标点击的位置
        # self.contextMenu.move(self.pos() + pos)
        self.contextMenu.show()
        self.contextMenu.exec_(QCursor.pos())
Exemplo n.º 32
0
    def custom_context_menu(self, position):
        menu_main = QMenu()
        plot = QMenu("Plot...", menu_main)
        plot_line = QAction("Line", plot)
        plot_line.triggered.connect(
            partial(self.presenter.action_plot, PlotType.LINEAR))

        plot_line_with_yerr = QAction("Line with Y Errors", plot)
        plot_line_with_yerr.triggered.connect(
            partial(self.presenter.action_plot, PlotType.LINEAR_WITH_ERR))

        plot_scatter = QAction("Scatter", plot)
        plot_scatter.triggered.connect(
            partial(self.presenter.action_plot, PlotType.SCATTER))

        plot_scatter_with_yerr = QAction("Scatter with Y Errors", plot)
        plot_scatter_with_yerr.triggered.connect(
            partial(self.presenter.action_plot, PlotType.SCATTER_WITH_ERR))

        plot_line_and_points = QAction("Line + Symbol", plot)
        plot_line_and_points.triggered.connect(
            partial(self.presenter.action_plot, PlotType.LINE_AND_SYMBOL))

        plot.addAction(plot_line)
        plot.addAction(plot_line_with_yerr)
        plot.addAction(plot_scatter)
        plot.addAction(plot_scatter_with_yerr)
        plot.addAction(plot_line_and_points)
        menu_main.addMenu(plot)

        copy_bin_values = QAction(self.COPY_ICON, "Copy", menu_main)
        copy_bin_values.triggered.connect(
            self.presenter.action_copy_bin_values)

        set_as_x = QAction("Set as X", menu_main)
        set_as_x.triggered.connect(self.presenter.action_set_as_x)

        set_as_y = QAction("Set as Y", menu_main)
        set_as_y.triggered.connect(self.presenter.action_set_as_y)

        set_as_none = QAction("Set as None", menu_main)
        set_as_none.triggered.connect(self.presenter.action_set_as_none)

        statistics_on_columns = QAction("Statistics on Columns", menu_main)
        statistics_on_columns.triggered.connect(
            self.presenter.action_statistics_on_columns)

        hide_selected = QAction("Hide Selected", menu_main)
        hide_selected.triggered.connect(self.presenter.action_hide_selected)

        show_all_columns = QAction("Show All Columns", menu_main)
        show_all_columns.triggered.connect(
            self.presenter.action_show_all_columns)

        sort_ascending = QAction("Sort Ascending", menu_main)
        sort_ascending.triggered.connect(
            partial(self.presenter.action_sort, True))

        sort_descending = QAction("Sort Descending", menu_main)
        sort_descending.triggered.connect(
            partial(self.presenter.action_sort, False))

        menu_main.addAction(copy_bin_values)
        menu_main.addAction(self.make_separator(menu_main))
        menu_main.addAction(set_as_x)
        menu_main.addAction(set_as_y)

        marked_y_cols = self.presenter.get_columns_marked_as_y()
        num_y_cols = len(marked_y_cols)

        # If any columns are marked as Y then generate the set error menu
        if num_y_cols > 0:
            menu_set_as_y_err = QMenu("Set error for Y...")
            for label_index in range(num_y_cols):
                set_as_y_err = QAction("Y{}".format(label_index), menu_main)

                # This is the column index of the Y column for which a YERR column is being added.
                # The column index is relative to the whole table, this is necessary
                # so that later the data of the column marked as error can be retrieved
                related_y_column = marked_y_cols[label_index]

                # label_index here holds the index in the LABEL (multiple Y columns have labels Y0, Y1, YN...)
                # this is NOT the same as the column relative to the WHOLE table
                set_as_y_err.triggered.connect(
                    partial(self.presenter.action_set_as_y_err,
                            related_y_column))
                menu_set_as_y_err.addAction(set_as_y_err)
            menu_main.addMenu(menu_set_as_y_err)

        menu_main.addAction(set_as_none)
        menu_main.addAction(self.make_separator(menu_main))
        menu_main.addAction(statistics_on_columns)
        menu_main.addAction(self.make_separator(menu_main))
        menu_main.addAction(hide_selected)
        menu_main.addAction(show_all_columns)
        menu_main.addAction(self.make_separator(menu_main))
        menu_main.addAction(sort_ascending)
        menu_main.addAction(sort_descending)

        menu_main.exec_(self.mapToGlobal(position))
Exemplo n.º 33
0
class StructureSynthesis(QWidget, Ui_Form):
    """Number and type synthesis widget.

    Calculate the combinations of mechanism family and show the atlas.
    """
    assortment: Dict[Assortment, List[Assortment]]
    answer: List[Graph]

    def __init__(self, parent: MainWindowBase):
        """Reference names:

        + IO functions from main window.
        + Table data from PMKS expression.
        + Graph data function from main window.
        """
        super(StructureSynthesis, self).__init__(parent)
        self.setupUi(self)
        header = self.link_assortment_list.header()
        header.setSectionResizeMode(QHeaderView.ResizeToContents)

        # Function references
        self.output_to = parent.output_to
        self.save_reply_box = parent.save_reply_box
        self.input_from_multiple = parent.input_from_multiple
        self.vpoints = parent.vpoint_list
        self.vlinks = parent.vlink_list
        self.get_graph = parent.get_graph
        self.prefer = parent.prefer
        self.add_collection = parent.collections.structure_widget.add_collection
        # Answer list
        self.assortment = {}
        self.answer = []
        # Signals
        self.nl_input.valueChanged.connect(self.__adjust_structure_data)
        self.nj_input.valueChanged.connect(self.__adjust_structure_data)
        self.graph_engine.addItems(engines)
        self.structure_list.customContextMenuRequested.connect(
            self.__structure_list_context_menu
        )

        # Context menu
        self.pop_menu_topo = QMenu(self)
        self.to_collection = QAction(
            QIcon(QPixmap(":/icons/collections.png")),
            "Add to collections",
            self
        )
        self.copy_edges = QAction("Copy edges", self)
        self.copy_image = QAction("Copy image", self)
        self.pop_menu_topo.addActions([
            self.to_collection,
            self.copy_edges,
            self.copy_image,
        ])

        self.nl_input_old_value = 0
        self.nj_input_old_value = 0
        self.clear()

    def clear(self) -> None:
        """Clear all sub-widgets."""
        self.edges_text.clear()
        self.__clear_assortment()
        self.__clear_structure_list()
        self.nl_input.setValue(0)
        self.nj_input.setValue(0)
        self.nl_input_old_value = 0
        self.nj_input_old_value = 0
        self.dof.setValue(1)

    @Slot(name='on_assortment_clear_button_clicked')
    def __clear_assortment(self) -> None:
        """Clear the number synthesis list."""
        self.link_assortment_list.clear()
        self.assortment.clear()

    @Slot(name='on_structure_list_clear_button_clicked')
    def __clear_structure_list(self) -> None:
        """Clear the structure list."""
        self.answer.clear()
        self.structure_list.clear()
        self.time_label.setText("")

    @Slot(name='on_from_mechanism_button_clicked')
    def __from_mechanism(self) -> None:
        """From a generalized mechanism of main canvas."""
        if self.vpoints and self.vlinks:
            graph, _, _, _, _, _ = self.get_graph()
        else:
            graph = Graph([])
        if graph.edges:
            self.edges_text.setText(str(list(graph.edges)))
        else:
            self.edges_text.setText("")
        keep_dof_checked = self.keep_dof.isChecked()
        self.keep_dof.setChecked(False)
        self.nl_input.setValue(len(graph.vertices))
        self.nj_input.setValue(len(graph.edges))
        self.keep_dof.setChecked(keep_dof_checked)

        # Show attributes
        QMessageBox.information(
            self,
            "Generalization",
            f"Link assortment:\n{link_assortment(graph)}\n"
            f"Contracted link assortment:\n{contracted_link_assortment(graph)}"
            if graph.edges else
            "Is a empty graph."
        )

    def __adjust_structure_data(self) -> None:
        """Update NJ and NL values.

        If user don't want to keep the DOF:
        Change the DOF then exit.
        """
        if not self.keep_dof.isChecked():
            self.dof.setValue(
                3 * (self.nl_input.value() - 1)
                - 2 * self.nj_input.value()
            )
            return

        # N2: Get the user's adjusted value.
        # NL_func: Get the another value of parameters (N1) by degrees of freedom formula.
        # is_above: Is value increase or decrease?
        if self.sender() is self.nj_input:
            n2 = self.nj_input.value()

            def nl_func() -> float:
                return (self.dof.value() + 2 * n2) / 3 + 1

            is_above = n2 > self.nj_input_old_value
        else:
            n2 = self.nl_input.value()

            def nl_func() -> float:
                return (3 * (n2 - 1) - self.dof.value()) / 2

            is_above = n2 > self.nl_input_old_value
        n1 = nl_func()
        while not n1.is_integer():
            n2 += 1 if is_above else -1
            n1 = nl_func()
            if n1 == 0 or n2 == 0:
                break

        n1 = int(n1)
        n2 = int(n2)
        # Return the result values
        # + Value of widgets.
        # + Setting old value record.
        if self.sender() is self.nl_input:
            self.nj_input.setValue(n1)
            self.nl_input.setValue(n2)
            self.nj_input_old_value = n1
            self.nl_input_old_value = n2
        else:
            self.nj_input.setValue(n2)
            self.nl_input.setValue(n1)
            self.nj_input_old_value = n2
            self.nl_input_old_value = n1

    @Slot(name='on_number_synthesis_button_clicked')
    def __number_synthesis(self) -> None:
        """Synthesis of link assortment."""
        self.__clear_assortment()
        nl = self.nl_input.value()
        nj = self.nj_input.value()
        dlg = SynthesisProgressDialog(
            "Link assortment",
            f"Number of links: {nl}\n"
            f"Number of joints: {nj}",
            1,
            self
        )

        @Slot(dict)
        def update_result(assortment: Dict[Assortment, List[Assortment]]) -> None:
            """Update results."""
            self.assortment.update(assortment)
            for la, cla_list in assortment.items():
                la_item = QTreeWidgetItem([", ".join(
                    f"NL{i + 2} = {a}" for i, a in enumerate(la)
                ), "N/A"])
                for cla in cla_list:
                    la_item.addChild(QTreeWidgetItem([", ".join(
                        f"NC{i + 1} = {a}" for i, a in enumerate(cla)
                    ), "N/A"]))
                self.link_assortment_list.addTopLevelItem(la_item)
            first_item = self.link_assortment_list.topLevelItem(0)
            self.link_assortment_list.setCurrentItem(first_item)
            dlg.deleteLater()

        work = LinkThread(nl, nj, dlg)
        work.progress_update.connect(dlg.setValue)
        work.size_update.connect(dlg.setMaximum)
        work.result.connect(update_result)
        dlg.show()
        work.start()

    def __set_time_count(self, t: float, count: int) -> None:
        """Set time and count digit to label."""
        self.time_label.setText(f"{t:.04f} s ({count})")

    def __set_paint_time(self, t: float) -> None:
        """Set painting time of atlas."""
        self.paint_time_label.setText(f"{t:.04f}s")

    @Slot(name='on_structure_synthesis_button_clicked')
    def __structure_synthesis(self) -> None:
        """Structural synthesis - find by contracted links."""
        self.__clear_structure_list()
        item = self.link_assortment_list.currentItem()
        if item is None:
            self.__number_synthesis()
            item = self.link_assortment_list.currentItem()
        root = item.parent()
        if root is None:
            # Find by link assortment
            try:
                # Test
                assortment_eval(item.text(0))
            except ValueError:
                return
            jobs = [item.child(i) for i in range(item.childCount())]
        else:
            # Find by contracted link assortment
            jobs = [item]
        self.__structural_combine(jobs)

    @Slot(name='on_structure_synthesis_all_button_clicked')
    def __structure_synthesis_all(self) -> None:
        """Structural synthesis - find all."""
        self.__clear_structure_list()
        jobs = []
        for i in range(self.link_assortment_list.topLevelItemCount()):
            root = self.link_assortment_list.topLevelItem(i)
            for j in range(root.childCount()):
                jobs.append(root.child(j))
        self.__structural_combine(jobs)

    def __structural_combine(self, jobs: Sequence[QTreeWidgetItem]) -> None:
        """Structural combine by iterator."""
        t0 = process_time()
        dlg = SynthesisProgressDialog(
            "Structural Synthesis",
            f"Number of cases: {len(jobs)}",
            len(jobs),
            self
        )

        @Slot(QTreeWidgetItem, int)
        def update_count(item: QTreeWidgetItem, count: int) -> None:
            """Update the number of graphs."""
            item.setText(1, f"{count}")

        @Slot(list)
        def update_result(answer: List[Graph]) -> None:
            """Update the result of atlas."""
            self.answer = answer
            dlg.deleteLater()
            for i in range(self.link_assortment_list.topLevelItemCount()):
                root = self.link_assortment_list.topLevelItem(i)
                count = 0
                for j in range(root.childCount()):
                    item = root.child(j)
                    try:
                        count += int(item.text(1))
                    except ValueError:
                        pass
                root.setText(1, f"{count}")
            self.__set_time_count(process_time() - t0, len(self.answer))
            self.__reload_atlas()

        work = GraphThread(jobs, self.graph_degenerate.currentIndex(), dlg)
        work.count_update.connect(update_count)
        work.progress_update.connect(dlg.setValue)
        work.result.connect(update_result)
        dlg.show()
        work.start()

    @Slot(name='on_reload_atlas_clicked')
    @Slot(bool, name='on_graph_link_as_node_toggled')
    @Slot(bool, name='on_graph_show_label_toggled')
    @Slot(int, name='on_graph_engine_currentIndexChanged')
    def __reload_atlas(self, *_) -> None:
        """Reload the atlas."""
        scroll_bar: QScrollBar = self.structure_list.verticalScrollBar()
        scroll_pos = scroll_bar.sliderPosition()
        index = self.structure_list.currentRow()
        self.structure_list.clear()

        if not self.answer:
            return

        dlg = SynthesisProgressDialog(
            "Structural Synthesis",
            f"Drawing atlas ({len(self.answer)}) ...",
            len(self.answer),
            self
        )
        dlg.show()
        t0 = process_time()
        for i, G in enumerate(self.answer):
            QCoreApplication.processEvents()
            if dlg.wasCanceled():
                return
            if self.__draw_atlas(i, G):
                dlg.setValue(i + 1)
            else:
                break
        self.__set_paint_time(process_time() - t0)
        dlg.setValue(dlg.maximum())
        dlg.deleteLater()
        scroll_bar.setSliderPosition(scroll_pos)
        self.structure_list.setCurrentRow(index)

    def __draw_atlas(self, i: int, g: Graph) -> bool:
        """Draw atlas and return True if done."""
        item = QListWidgetItem(f"No. {i + 1}")
        item.setIcon(graph2icon(
            g,
            self.structure_list.iconSize().width(),
            self.graph_link_as_node.isChecked(),
            self.graph_show_label.isChecked(),
            self.prefer.monochrome_option,
            engine=self.graph_engine.currentText()
        ))
        item.setToolTip(
            f"Edge Set: {list(g.edges)}\n"
            f"Link assortment: {link_assortment(g)}\n"
            f"Contracted Link assortment: {contracted_link_assortment(g)}\n"
            f"Degree code: {g.degree_code()}"
        )
        self.structure_list.addItem(item)
        return True

    def __atlas_image(self, row: Optional[int] = None) -> QImage:
        """Capture a result item icon to image."""
        if row is None:
            item = self.structure_list.currentItem()
        else:
            item = self.structure_list.item(row)
        return item.icon().pixmap(self.structure_list.iconSize()).toImage()

    @Slot(QPoint)
    def __structure_list_context_menu(self, point) -> None:
        """Context menu for the type synthesis results."""
        index = self.structure_list.currentIndex().row()
        self.to_collection.setEnabled(index > -1)
        self.copy_edges.setEnabled(index > -1)
        self.copy_image.setEnabled(index > -1)
        action = self.pop_menu_topo.exec_(self.structure_list.mapToGlobal(point))
        if not action:
            return
        clipboard = QApplication.clipboard()
        if action == self.to_collection:
            self.add_collection(self.answer[index].edges)
        elif action == self.copy_edges:
            clipboard.setText(str(self.answer[index].edges))
        elif action == self.copy_image:
            # Turn the transparent background to white
            image1 = self.__atlas_image()
            image2 = QImage(image1.size(), image1.format())
            image2.fill(Qt.white)
            painter = QPainter(image2)
            painter.drawImage(QPointF(0, 0), image1)
            painter.end()
            clipboard.setPixmap(QPixmap.fromImage(image2))

    @Slot(name='on_expr_copy_clicked')
    def __copy_expr(self) -> None:
        """Copy expression button."""
        string = self.edges_text.text()
        if string:
            QApplication.clipboard().setText(string)
            self.edges_text.selectAll()

    @Slot(name='on_expr_add_collection_clicked')
    def __add_collection(self) -> None:
        """Add this expression to collections widget."""
        string = self.edges_text.text()
        if string:
            self.add_collection(eval(string))

    @Slot(name='on_save_atlas_clicked')
    def __save_atlas(self) -> None:
        """Saving all the atlas to image file.

        We should turn transparent background to white first.
        Then using QImage class to merge into one image.
        """
        count = self.structure_list.count()
        if count < 1:
            return

        lateral = self.__save_atlas_ask()
        if not lateral:
            return

        file_name = self.output_to("atlas image", qt_image_format)
        if not file_name:
            return

        width = self.structure_list.iconSize().width()
        image_main = QImage(QSize(
            lateral * width if count > lateral else count * width,
            ((count // lateral) + bool(count % lateral)) * width
        ), self.__atlas_image(0).format())
        image_main.fill(Qt.transparent)
        painter = QPainter(image_main)
        for row in range(count):
            image = self.__atlas_image(row)
            painter.drawImage(QPointF(row % lateral, row // lateral) * width, image)
        painter.end()
        pixmap = QPixmap.fromImage(image_main)
        pixmap.save(file_name)
        self.save_reply_box("Atlas", file_name)

    def __save_atlas_ask(self) -> int:
        """Ask when saving the atlas."""
        lateral, ok = QInputDialog.getInt(
            self,
            "Atlas",
            "The number of lateral:",
            5, 1
        )
        if not ok:
            return 0
        return lateral

    @Slot(name='on_save_edges_clicked')
    def __save_edges(self) -> None:
        """Saving all the atlas to text file."""
        file_name = ""
        count = self.structure_list.count()
        if count < 1:
            return
        if not file_name:
            file_name = self.output_to("atlas edges expression", ["Text file (*.txt)"])
        if not file_name:
            return
        with open(file_name, 'w+', encoding='utf-8') as f:
            f.write('\n'.join(str(G.edges) for G in self.answer))
        self.save_reply_box("edges expression", file_name)

    @Slot(name='on_edges2atlas_button_clicked')
    def __edges2atlas(self) -> None:
        """Turn the text files into a atlas image.

        This operation will load all edges to list widget first.
        """
        file_names = self.input_from_multiple(
            "edges data",
            ["Text file (*.txt)"]
        )
        if not file_names:
            return

        read_data = []
        for file_name in file_names:
            with open(file_name, 'r', encoding='utf-8') as f:
                for line in f:
                    read_data.append(line)

        answer = []
        for edges in read_data:
            try:
                g = Graph(eval(edges))
            except (SyntaxError, TypeError):
                QMessageBox.warning(
                    self,
                    "Wrong format",
                    "Please check text format."
                )
            else:
                answer.append(g)

        if not answer:
            QMessageBox.information(
                self,
                "No data",
                "The graph data is empty."
            )
            return

        self.answer = answer
        self.__set_time_count(0, len(answer))
        self.__reload_atlas()
        self.__save_atlas()
Exemplo n.º 34
0
    def custom_context_menu(self, position):
        menu_main = QMenu()
        plot = QMenu("Plot...", menu_main)
        plot_line = QAction("Line", plot)
        plot_line.triggered.connect(partial(self.presenter.action_plot, PlotType.LINEAR))

        plot_line_with_yerr = QAction("Line with Y Errors", plot)
        plot_line_with_yerr.triggered.connect(partial(self.presenter.action_plot, PlotType.LINEAR_WITH_ERR))

        plot_scatter = QAction("Scatter", plot)
        plot_scatter.triggered.connect(partial(self.presenter.action_plot, PlotType.SCATTER))

        plot_line_and_points = QAction("Line + Symbol", plot)
        plot_line_and_points.triggered.connect(partial(self.presenter.action_plot, PlotType.LINE_AND_SYMBOL))

        plot.addAction(plot_line)
        plot.addAction(plot_line_with_yerr)
        plot.addAction(plot_scatter)
        plot.addAction(plot_line_and_points)
        menu_main.addMenu(plot)

        copy_bin_values = QAction(self.COPY_ICON, "Copy", menu_main)
        copy_bin_values.triggered.connect(self.presenter.action_copy_bin_values)

        set_as_x = QAction("Set as X", menu_main)
        set_as_x.triggered.connect(self.presenter.action_set_as_x)

        set_as_y = QAction("Set as Y", menu_main)
        set_as_y.triggered.connect(self.presenter.action_set_as_y)

        set_as_none = QAction("Set as None", menu_main)
        set_as_none.triggered.connect(self.presenter.action_set_as_none)

        statistics_on_columns = QAction("Statistics on Columns", menu_main)
        statistics_on_columns.triggered.connect(self.presenter.action_statistics_on_columns)

        hide_selected = QAction("Hide Selected", menu_main)
        hide_selected.triggered.connect(self.presenter.action_hide_selected)

        show_all_columns = QAction("Show All Columns", menu_main)
        show_all_columns.triggered.connect(self.presenter.action_show_all_columns)

        sort_ascending = QAction("Sort Ascending", menu_main)
        sort_ascending.triggered.connect(partial(self.presenter.action_sort_ascending, Qt.AscendingOrder))

        sort_descending = QAction("Sort Descending", menu_main)
        sort_descending.triggered.connect(partial(self.presenter.action_sort_ascending, Qt.DescendingOrder))

        menu_main.addAction(copy_bin_values)
        menu_main.addAction(self.make_separator(menu_main))
        menu_main.addAction(set_as_x)
        menu_main.addAction(set_as_y)

        marked_y_cols = self.presenter.get_columns_marked_as_y()
        num_y_cols = len(marked_y_cols)

        # If any columns are marked as Y then generate the set error menu
        if num_y_cols > 0:
            menu_set_as_y_err = QMenu("Set error for Y...")
            for col in range(num_y_cols):
                set_as_y_err = QAction("Y{}".format(col), menu_main)
                # the column index of the column relative to the whole table, this is necessary
                # so that later the data of the column marked as error can be retrieved
                real_column_index = marked_y_cols[col]
                # col here holds the index in the LABEL (multiple Y columns have labels Y0, Y1, YN...)
                # this is NOT the same as the column relative to the WHOLE table
                set_as_y_err.triggered.connect(partial(self.presenter.action_set_as_y_err, real_column_index, col))
                menu_set_as_y_err.addAction(set_as_y_err)
            menu_main.addMenu(menu_set_as_y_err)

        menu_main.addAction(set_as_none)
        menu_main.addAction(self.make_separator(menu_main))
        menu_main.addAction(statistics_on_columns)
        menu_main.addAction(self.make_separator(menu_main))
        menu_main.addAction(hide_selected)
        menu_main.addAction(show_all_columns)
        menu_main.addAction(self.make_separator(menu_main))
        menu_main.addAction(sort_ascending)
        menu_main.addAction(sort_descending)

        menu_main.exec_(self.mapToGlobal(position))
Exemplo n.º 35
0
 def mouse_click(self, event):
     if event.button == event.canvas.buttond.get(Qt.RightButton):
         menu = QMenu()
         self.fit_browser.add_to_menu(menu)
         menu.exec_(QCursor.pos())
Exemplo n.º 36
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()