Python PyQt5.QtWidgets.QAction() Examples

The following are code examples for showing how to use PyQt5.QtWidgets.QAction(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: libView   Author: liyanqing1987   File: libView.py    GNU General Public License v2.0 6 votes vote down vote up
def genMenubar(self):
        """
        Generate menubar.
        """
        menubar = self.menuBar()

        # File
        loadAction = QAction('Load', self)
        loadAction.triggered.connect(self.loadLibFile)

        exitAction = QAction('Quit', self)
        exitAction.triggered.connect(qApp.quit)

        fileMenu = menubar.addMenu('File')
        fileMenu.addAction(loadAction)
        fileMenu.addAction(exitAction) 
Example 2
Project: dcc   Author: amimo   File: mainwindow.py    Apache License 2.0 6 votes vote down vote up
def __init__(self, bin_windows, parent=None):
        super(TabsWindow, self).__init__(parent)
        self.bin_windows = bin_windows
        self.setTabsClosable(True)
        self.tabCloseRequested.connect(self.tabCloseRequestedHandler)
        self.currentChanged.connect(self.currentTabChanged)

        self.closeAllTabs = QtWidgets.QAction(
            "Close all tabs",
            self,
            triggered=self.actioncloseAllTabs)
        self.closeOtherTabs = QtWidgets.QAction(
            "Close other tabs",
            self,
            triggered=self.actioncloseOtherTabs)
        self.closeLeftTabs = QtWidgets.QAction(
            "Close left tabs",
            self,
            triggered=self.actioncloseLeftTabs)
        self.closeRightTabs = QtWidgets.QAction(
            "Close right tabs",
            self,
            triggered=self.actioncloseRightTabs) 
Example 3
Project: kucher   Author: Zubax   File: __init__.py    GNU General Public License v3.0 6 votes vote down vote up
def _configure_help_menu(self):
        # Help menu
        website_action = QAction(get_icon('www'), 'Open Zubax Robotics &website', self)
        website_action.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://zubax.com')))

        knowledge_base_action = QAction(get_icon('knowledge'), 'Open Zubax &Knowledge Base website', self)
        knowledge_base_action.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://kb.zubax.com')))

        show_log_directory_action = QAction(get_icon('log'), 'Open &log directory', self)
        show_log_directory_action.triggered.connect(lambda: QDesktopServices.openUrl(QUrl.fromLocalFile(LOG_DIR)))

        help_menu = self.menuBar().addMenu('&Help')
        help_menu.addAction(website_action)
        help_menu.addAction(knowledge_base_action)
        help_menu.addAction(show_log_directory_action)
        # help_menu.addAction(about_action)                 # TODO: Implement this 
Example 4
Project: QuantStudio   Author: Scorpi000   File: ResultDlg.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, parent=None, data_range=[], data=None):
        super().__init__(parent)
        self.DataRange = data_range
        self.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
        self.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
        nData = len(data_range)
        self.setRowCount(nData)
        self.setColumnCount(1)
        self.setHorizontalHeaderLabels(['参数值'])
        self.setVerticalHeaderLabels([str(iData) for iData in data_range])
        if data is None:
            for i in range(nData):
                iWidget = QtWidgets.QCheckBox(None)
                iWidget.setChecked(True)
                self.setCellWidget(i,0,iWidget)
        else:
            for i,iData in enumerate(data_range):
                iWidget = QtWidgets.QCheckBox(None)
                iWidget.setChecked((iData in data))
                self.setCellWidget(i,0,iWidget)
        # 设置弹出菜单
        self.addAction(QtWidgets.QAction('全选', self, triggered=self.selectAll))
        self.addAction(QtWidgets.QAction('全不选', self, triggered=self.selectNone))
        self.addAction(QtWidgets.QAction('反选', self, triggered=self.selectOpposite))
        return 
Example 5
Project: QuantStudio   Author: Scorpi000   File: PreviewRiskDataDlg.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, risk_db, table_name, idt, parent=None):
        super(PreviewRiskDataDlg, self).__init__(parent)
        self.setupUi(self)
        self.RiskDB = risk_db
        self.RT = self.RiskDB.getTable(table_name)
        self.DT = idt
        self.RiskData = self.RT.readCov(dts=[self.DT], ids=None).iloc[0]
        self.IDs = self.RiskData.index.tolist()
        self.setWindowTitle("预览: "+self.DT.strftime("%Y-%m-%d %H:%M:%S.%f"))
        self.PreviewTable.addAction(QAction("去除缺失", self.PreviewTable, triggered=self.dropNA))
        self.populatePreviewTable()
        self.populateID()
        if isinstance(self.RT, FactorRT):
            self.populateFactor()
        else:
            self.PreviewFactorRiskButton.setEnabled(False)
            self.PreviewSpecificRiskButton.setEnabled(False) 
Example 6
Project: cct   Author: awacha   File: mainwindow.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def openWindow(self):
        action = self.sender()
        assert isinstance(action, QtWidgets.QAction)
        windowclass = self._action_to_windowclass[action]
        try:
            logger.debug('Trying to find window for action {}'.format(action.objectName()))
            self.windowdict[action].show()
            self.windowdict[action].raise_()
            self.windowdict[action].activateWindow()
            self.windowdict[action].showNormal()
        except (KeyError, RuntimeError):
            logger.debug(
                'Window not found for action {}; creating new one, an instance of {}'.format(action.objectName(),
                                                                                             str(windowclass)))
            self.windowdict[action] = windowclass(parent=None, credo=weakref.proxy(self.credo))
            # self.windowdict[action].setWindowIcon()
            return self.openWindow()
        return True 
Example 7
Project: cct   Author: awacha   File: maskeditor.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def initializeSelector(self, action: QtWidgets.QAction, selectorclass, callbackfunction, helptext, **kwargs):
        if action.isChecked():
            while self.plotimage.figtoolbar.mode != '':
                # turn off zoom, pan, etc. modes in the matplotlib figure toolbar
                self.plotimage.figtoolbar.zoom()
            if selectorclass in [RectangleSelector, EllipseSelector]:
                kwargs['rectprops'] = {'facecolor': 'white', 'edgecolor': 'none',
                                       'alpha': 0.7, 'fill': True, 'zorder': 10}
                kwargs['interactive'] = False
            if selectorclass!=PolygonSelector:
                kwargs['button'] = [1,]
            self.selector = selectorclass(self.plotimage.axes,
                                          callbackfunction,
                                          lineprops={'zorder': 10, 'color': 'white'},
                                          **kwargs)
            for act in self.toolBar.actions():
                act.setEnabled(False)
            action.setEnabled(True)
            self.helpLabel.setText(helptext)
            self.helpLabel.setVisible(True)
        else:
            self.finalizeSelector() 
Example 8
Project: cct   Author: awacha   File: maskeditor.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def initializeSelector(self, action: QtWidgets.QAction, selectorclass, callbackfunction, **kwargs):
        if action.isChecked():
            while self.plotimage.figtoolbar.mode != '':
                # turn off zoom, pan, etc. modes in the matplotlib figure toolbar
                self.plotimage.figtoolbar.zoom()
            if selectorclass in [RectangleSelector, EllipseSelector]:
                kwargs['rectprops'] = {'facecolor': 'white', 'edgecolor': 'none',
                                       'alpha': 0.7, 'fill': True, 'zorder': 10}
                kwargs['interactive'] = False
            self.selector = selectorclass(self.plotimage.axes,
                                          callbackfunction,
                                          button=[1, ],
                                          lineprops={'zorder': 10, 'color': 'white'},
                                          **kwargs)
            for act in self.actions():
                act.setEnabled(False)
            action.setEnabled(True)
        else:
            self.finalizeSelector() 
Example 9
Project: SCGV   Author: KrasnitzLab   File: profiles_window.py    MIT License 6 votes vote down vote up
def on_context_menu(self, pos, *args, **kwargs):
        open_browser = QAction("Open in UCSC Genome Browser", self)
        open_browser.triggered.connect(self.on_open_genome_browser)

        if self.browse_position_region:
            open_browser_region = QAction(
                "Open Region in UCSC Genome Browser End", self)
            open_browser_region.triggered.connect(
                self.on_open_genome_browser_region_end)
        else:
            open_browser_region = QAction(
                "Open Region in UCSC Genome Browser Start", self)
            open_browser_region.triggered.connect(
                self.on_open_genome_browser_region_start)

        context = QMenu(self)
        context.addAction(open_browser_region)
        context.addAction(open_browser)
        context.exec_(self.mapToGlobal(pos)) 
Example 10
Project: MeiTingTrunk   Author: Xunius   File: _MainWindow.py    GNU General Public License v3.0 6 votes vote down vote up
def viewChangeTriggered(self, action):
        """Change widget visibility in response to View menu actions

        Args:
            action (QAction): QAction in View menu
        """

        action_text=action.text()

        self.logger.info('View change action = %s' %action_text)

        if action_text=='Toggle Filter List':
            self.main_frame.foldFilterButtonClicked()
        elif action_text=='Toggle Tab Pane':
            self.main_frame.foldTabButtonClicked()
        elif action_text=='Toggle Status bar':
            self.main_frame.statusbarViewChange()
        else:
            self.main_frame.metaTabViewChange(action_text)

        return 
Example 11
Project: eddy   Author: obdasystems   File: mdi.py    GNU General Public License v3.0 6 votes vote down vote up
def addSubWindow(self, subwindow, flags=0, **kwargs):
        """
        Add a subwindow to the MDI area.
        :type subwindow: MdiSubWindow
        :type flags: int
        """
        menu = subwindow.systemMenu()
        action = QtWidgets.QAction('Close All', subwindow)
        action.setIcon(menu.actions()[7].icon())
        connect(action.triggered, self.closeAllSubWindows)
        menu.addAction(action)
        action = QtWidgets.QAction('Close Others', subwindow)
        action.setIcon(menu.actions()[7].icon())
        connect(action.triggered, self.doCloseOtherSubWindows)
        menu.addAction(action)
        return super().addSubWindow(subwindow) 
Example 12
Project: plexdesktop   Author: coryo   File: extra_widgets.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, parent=None):
        super().__init__(parent)
        """style is relying on object names so make sure they are set
           before registering widgets"""
        self.setObjectName('HubSearch')

        search_action = QtWidgets.QAction(self)
        search_action.setObjectName('search_action')
        close_action = QtWidgets.QAction(self)
        close_action.setObjectName('close_action')
        close_action.triggered.connect(self.cancel.emit)
        close_action.triggered.connect(self.clear)

        self.addAction(search_action, QtWidgets.QLineEdit.LeadingPosition)
        self.addAction(close_action, QtWidgets.QLineEdit.TrailingPosition)

        plexdesktop.style.Style.Instance().widget.register(search_action, 'glyphicons-search')
        plexdesktop.style.Style.Instance().widget.register(close_action, 'cancel') 
Example 13
Project: screenrulerzoom   Author: ElMoribond   File: screenrulerzoom.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, parent):
            super().__init__(parent)
            self.parent, unitMeasure, rulerSize, colors, zoom= parent, QMenu(gettext("Unit Measure"), self), QMenu(gettext("Ruler Size"), self), QMenu(gettext("Colors"), self), QMenu(gettext("Zoom"), self)
            self.addAction(QAction(parent.orientation[1 if not parent.oH else 0], self, triggered= partial(parent.changeOrientation, 1 if not parent.oH else 0)))
            for menu in [ [ zoom, parent.zooms, parent.changeMode, parent.zoom ], [ unitMeasure, parent.unitMeasure, parent.changeUnitMeasure, parent.cUM ], [ rulerSize, parent.rulerSize, parent.changeRulerSize, parent.sXY ], [ colors, parent.colors, parent.changeRulerColor, parent.defaultColors ] ]:
                for i, item in enumerate(menu[1]):
                    item= QAction(item[0][0], self, triggered= partial(menu[2], i))
                    if type(menu[3]) == type(list()) and i == len(menu[1]) - 1:
                        menu[0].addSeparator()
                        item.setEnabled(False if menu[1] == menu[3] else True)
                    else:
                        item.setCheckable(True)
                        item.setChecked(True if i == menu[3] else False)
                        item.setEnabled(not item.isChecked())
                    menu[0].addAction(item)
                if menu[0] in [ unitMeasure, colors ]:
                    menu[0].setEnabled(not bool(parent.zoom))
                self.addMenu(menu[0])
            self.addSeparator()
            self.addAction(QAction(parent.about, self, triggered= self.AboutDialog(parent).exec_))
            self.addSeparator()
            self.addAction(QAction(gettext("Exit"), self, triggered= parent.close)) 
Example 14
Project: XulDebugTool   Author: starcor-company   File: FavoriteTreeView.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def menuBatchOperation(self,list):
        itemList = []
        #标记本次批量操作所有记录的类别是否一致,如果不一致就不进行右键批量操作
        itemTpye = None;
        for modelIndex in list:
            item = self.treeModel.itemFromIndex(modelIndex)
            if itemTpye != None:
                if itemTpye != item.type:
                    return
            itemTpye = item.type
            itemList.append(item)

        menu = QMenu()
        if itemTpye == ITEM_TYPE_HISTORY:
            deleteAction = QAction(IconTool.buildQIcon('clear.png'), '&Delete', self,triggered=lambda: self.deleteHistoryBatch(itemList))
            deleteAction.setShortcut('Ctrl+D')
            menu.addAction(deleteAction)

        if itemTpye == ITEM_TYPE_FAVORITES:
            deleteAction = QAction(IconTool.buildQIcon('clear.png'), '&Delete', self,triggered=lambda: self.deleteFavoritesBatch(itemList))
            deleteAction.setShortcut('Ctrl+D')
            menu.addAction(deleteAction)

        menu.exec_(QCursor.pos()) 
Example 15
Project: FIRST-plugin-ida   Author: vrtadmin   File: first.py    GNU General Public License v2.0 6 votes vote down vote up
def applied_custom_menu(self, point):
        index = self.applied_tree_view.indexAt(point)
        address = index.data(FIRSTUI.ROLE_ADDRESS)
        if not address:
            return

        menu = QtWidgets.QMenu(self.applied_tree_view)
        goto_action = QtWidgets.QAction('&Go to Function', self.applied_tree_view)
        goto_action.triggered.connect(lambda:IDAW.Jump(address))
        menu.addAction(goto_action)

        metadata_id = index.data(FIRSTUI.ROLE_ID)
        if metadata_id:
            history_action = QtWidgets.QAction('View &History', self.applied_tree_view)
            history_action.triggered.connect(lambda:self._metadata_history(metadata_id))
            menu.addAction(history_action)

        menu.exec_(QtGui.QCursor.pos()) 
Example 16
Project: FIRST-plugin-ida   Author: vrtadmin   File: first.py    GNU General Public License v2.0 6 votes vote down vote up
def custom_menu(self, point):
            index = self.tree_view.indexAt(point)
            address = index.data(FIRSTUI.ROLE_ADDRESS)
            if not address:
                return

            menu = QtWidgets.QMenu(self.tree_view)
            goto_action = QtWidgets.QAction('&Go to Function', self.tree_view)
            goto_action.triggered.connect(lambda:IDAW.Jump(address))
            menu.addAction(goto_action)

            metadata_id = index.data(FIRSTUI.ROLE_ID)
            if metadata_id:
                history_action = QtWidgets.QAction('View &History', self.tree_view)
                history_action.triggered.connect(lambda:self.metadata_history(metadata_id))
                menu.addAction(history_action)

            menu.exec_(QtGui.QCursor.pos()) 
Example 17
Project: ocelot   Author: ocelot-collab   File: ocl_table.py    GNU General Public License v3.0 6 votes vote down vote up
def contextMenuEvent(self, event):
        if self.selectionModel().selection().indexes():
            rows = []
            cols = []
            for i in self.selectionModel().selection().indexes():
                row, column = i.row(), i.column()
                rows.append(row)
                cols.append(column)
            self.menu = QMenu(self)

            #deleteAction = QAction('Delete', self)
            checkAction = QAction('Check', self)
            uncheckAction = QAction('Uncheck', self)
            #deleteAction.triggered.connect(lambda: self.deleteSlot(rows))
            checkAction.triggered.connect(lambda: self.checkSlot())
            uncheckAction.triggered.connect(lambda: self.uncheckSlot())
            self.menu.addAction(checkAction)
            self.menu.addAction(uncheckAction)
            #editAction = QtGui.QAction('Edit', self)
            #self.menu.addAction(editAction)
            # add other required actions
            self.menu.popup(QtGui.QCursor.pos()) 
Example 18
Project: lyric-grabber   Author: aaronhktan   File: main_window.py    MIT License 6 votes vote down vote up
def removeCurrentFile(self):
    """Remove file currently selected by user"""
    i = self.selectedWidgetIndex
    if self._mainScrollAreaWidgetLayout.itemAt(i).widget().getState() == states.COMPLETE \
    or self._mainScrollAreaWidgetLayout.itemAt(i).widget().getState() == states.ERROR:
      self._all_filepaths.remove(self._mainScrollAreaWidgetLayout.itemAt(i).widget().getFilepath())
      songWidget = self._mainScrollAreaWidgetLayout.itemAt(i).widget()
      songWidget.removeFromList()
      if utils.IS_MAC and i < 10:
        # Replace entry in the "View lyrics for..." submenu with the 10th song
        try:
          self._songsSubMenu.removeAction(songWidget.openItemAction)
        except Exception as e:
          print(e)
        if self._mainScrollAreaWidgetLayout.itemAt(8) is not None:
          nextWidget = self._mainScrollAreaWidgetLayout.itemAt(8).widget()
          nextWidget.openItemAction = QtWidgets.QAction(nextWidget.getTitleText() + ' - ' + nextWidget.getArtistText(), self)
          nextWidget.openItemAction.setData(nextWidget.getFilepath())
          nextWidget.openItemAction.triggered.connect(nextWidget.openDetailDialog)
          nextWidget.openItemAction.triggered.connect(lambda: self.setSelectedWidget(nextWidget.getFilepath()))
          print(nextWidget.openItemAction)
          self._songsSubMenu.addAction(nextWidget.openItemAction)
        if self._songsSubMenu.isEmpty():
          self._noLyricsAction.setVisible(True)
    self.selectedWidgetIndex = None 
Example 19
Project: PointlessMaker   Author: aboood40091   File: main.py    GNU General Public License v3.0 6 votes vote down vote up
def CreateAction(self, shortname, function, icon, text, statustext, shortcut, toggle=False):
        """
        Helper function to create an action
        From Miyamoto
        """
        if icon is not None:
            act = QtWidgets.QAction(icon, text, self)

        else:
            act = QtWidgets.QAction(text, self)

        if shortcut is not None:
            act.setShortcut(shortcut)

        if statustext is not None:
            act.setStatusTip(statustext)

        if toggle:
            act.setCheckable(True)

        if function is not None:
            act.triggered.connect(function)

        self.actions[shortname] = act 
Example 20
Project: pyqt5-face-recognition   Author: Aimledge   File: face_recognition_app.py    MIT License 6 votes vote down vote up
def setup_camera(self):
    camera_device = QByteArray()

    video_devices_group = QActionGroup(self)
    video_devices_group.setExclusive(True)

    for device in QCamera.availableDevices():
      description = QCamera.deviceDescription(device)
      video_device_action = QAction(description, video_devices_group)
      video_device_action.setCheckable(True)
      video_device_action.setData(device)

      if camera_device.isEmpty():
        camera_device = device
        video_device_action.setChecked(True)

      self.ui.menuDevices.addAction(video_device_action)
    if camera_device.isEmpty():
      self.camera = QCamera()
    else:
      self.camera = QCamera(camera_device)
    self.camera.setViewfinder(self.ui.cameraViewFinder) 
Example 21
Project: DevilYuan   Author: moyuanz   File: DyMainWindow.py    MIT License 6 votes vote down vote up
def _initMenu(self):
        # 创建菜单
        menuBar = self.menuBar()
        
        # 添加菜单
        menu = menuBar.addMenu('配置')

        action = QAction('股票历史日线数据源...', self)
        action.triggered.connect(self._configStockHistDaysDataSource)
        menu.addAction(action)

        action = QAction('MongoDB...', self)
        action.triggered.connect(self._configMongoDb)
        menu.addAction(action)

        subMenu = menu.addMenu('实盘交易')
        action = QAction('微信...', self)
        action.triggered.connect(self._configWx)
        subMenu.addAction(action)

        action = QAction('账号...', self)
        action.triggered.connect(self._configAccount)
        subMenu.addAction(action) 
Example 22
Project: opcua-modeler   Author: FreeOpcUa   File: refnodesets_widget.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, view):
        QObject.__init__(self, view)
        self.view = view
        self.model = QStandardItemModel()
        self.view.setModel(self.model)
        self.nodesets = []
        self.server_mgr = None
        self.view.header().setSectionResizeMode(1)
        
        addNodeSetAction = QAction("Add Reference Node Set", self.model)
        addNodeSetAction.triggered.connect(self.add_nodeset)
        self.removeNodeSetAction = QAction("Remove Reference Node Set", self.model)
        self.removeNodeSetAction.triggered.connect(self.remove_nodeset)

        self.view.setContextMenuPolicy(Qt.CustomContextMenu)
        self.view.customContextMenuRequested.connect(self.showContextMenu)
        self._contextMenu = QMenu()
        self._contextMenu.addAction(addNodeSetAction)
        self._contextMenu.addAction(self.removeNodeSetAction) 
Example 23
Project: opcua-modeler   Author: FreeOpcUa   File: namespace_widget.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, view):
        QObject.__init__(self, view)
        self.view = view
        self.model = QStandardItemModel()
        self.view.setModel(self.model)
        delegate = MyDelegate(self.view, self)
        delegate.error.connect(self.error.emit)
        self.view.setItemDelegate(delegate)
        self.node = None
        self.view.header().setSectionResizeMode(1)
        
        self.addNamespaceAction = QAction("Add Namespace", self.model)
        self.addNamespaceAction.triggered.connect(self.add_namespace)
        self.removeNamespaceAction = QAction("Remove Namespace", self.model)
        self.removeNamespaceAction.triggered.connect(self.remove_namespace)

        self.view.setContextMenuPolicy(Qt.CustomContextMenu)
        self.view.customContextMenuRequested.connect(self.showContextMenu)
        self._contextMenu = QMenu()
        self._contextMenu.addAction(self.addNamespaceAction)
        self._contextMenu.addAction(self.removeNamespaceAction) 
Example 24
Project: QMusic   Author: dragondjf   File: dmenu.py    GNU Lesser General Public License v2.1 6 votes vote down vote up
def creatAction(self, submenu, menuaction):
        if 'checkable' in menuaction:
            setattr(self,
                    '%sAction' % menuaction['trigger'],
                    QAction(
                        QIcon(QPixmap(menuaction['icon'])),
                        u'%s' % menuaction['name'],
                        self,
                        checkable=menuaction['checkable']))
        else:
            setattr(self, '%sAction' % menuaction['trigger'], QAction(
                QIcon(QPixmap(menuaction['icon'])),
                u'%s' % menuaction['name'],
                self, ))

        action = getattr(self, '%sAction' % menuaction['trigger'])
        action.setShortcut(QKeySequence(menuaction['shortcut']))
        submenu.addAction(action)
        self.qactions.update({menuaction['trigger']: action}) 
Example 25
Project: python-code   Author: ouening   File: youdao_translation.py    MIT License 6 votes vote down vote up
def initMenuBar(self):
        '''
        初始化菜单栏
        '''
        menubar = self.menuBar()
        #self.actionExit.triggered.connect(qApp.quit)    # 按下菜单栏的Exit按钮会退出程序
        #self.actionExit.setStatusTip("退出程序")         # 左下角状态提示
        #self.actionExit.setShortcut('Ctrl+Q')           # 添加快捷键
        exitAct = QAction(QIcon('exit.png'), 'Exit', self)
        exitAct.setShortcut('Ctrl+Q')
        exitAct.triggered.connect(qApp.quit)
        
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAct)
        
        fileMenu = menubar.addMenu('&Help') 
Example 26
Project: python-code   Author: ouening   File: baidu_translation.py    MIT License 6 votes vote down vote up
def initMenuBar(self):
        '''
        初始化菜单栏
        '''
        menubar = self.menuBar()
        #self.actionExit.triggered.connect(qApp.quit)    # 按下菜单栏的Exit按钮会退出程序
        #self.actionExit.setStatusTip("退出程序")         # 左下角状态提示
        #self.actionExit.setShortcut('Ctrl+Q')           # 添加快捷键
        exitAct = QAction(QIcon('exit.png'), 'Exit', self)
        exitAct.setShortcut('Ctrl+Q')
        exitAct.triggered.connect(qApp.quit)
        
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAct)
        
        fileMenu = menubar.addMenu('&Help') 
Example 27
Project: openlavaMonitor   Author: liyanqing1987   File: bmonitorGUI.py    GNU General Public License v2.0 6 votes vote down vote up
def genMenubar(self):
        """
        Generate menubar.
        """
        menubar = self.menuBar()

        # File
        exitAction = QAction('Quit', self)
        exitAction.triggered.connect(qApp.quit)

        fileMenu = menubar.addMenu('File')
        fileMenu.addAction(exitAction)

        # Setup
        freshAction = QAction('Fresh', self)
        freshAction.triggered.connect(self.fresh)

        setupMenu = menubar.addMenu('Setup')
        setupMenu.addAction(freshAction) 
Example 28
Project: Physics_Project   Author: QuandisS   File: test2.py    Apache License 2.0 5 votes vote down vote up
def initUI(self):

        exitAction = QAction(QIcon('exit24.png'), 'Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.triggered.connect(qApp.quit)

        self.toolbar = self.addToolBar('Exit')
        self.toolbar.addAction(exitAction)

        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('Toolbar')
        self.show() 
Example 29
Project: dcc   Author: amimo   File: sourcewindow.py    Apache License 2.0 5 votes vote down vote up
def CustomContextMenuHandler(self, pos):
        menu = QtWidgets.QMenu(self)
        menu.addAction(QtWidgets.QAction(
            "Xref ...",
            self,
            statusTip="List the references where this element is used",
            triggered=self.actionXref))
        menu.addAction(QtWidgets.QAction("&Goto",
                                         self,
                                         statusTip="Go to element definition",
                                         triggered=self.actionGoto))
        menu.addAction(
            QtWidgets.QAction("Rename...",
                              self,
                              statusTip="Rename an element (class, method, ...)",
                              triggered=self.actionRename))
        menu.addAction(QtWidgets.QAction(
            "&Info",
            self,
            statusTip=
            "Display info of an element (anything useful in the document)",
            triggered=self.actionInfo))
        menu.addAction(QtWidgets.QAction(
            "&Reload sources",
            self,
            statusTip=
            "Reload sources (needed when renaming changed other tabs)",
            triggered=self.reload_java_sources))
        menu.addAction(QtWidgets.QAction("&Copy",
                                         self,
                                         shortcut=QtGui.QKeySequence.Copy,
                                         statusTip="Copy the current selection's contents to the clipboard",
                                         triggered=self.actionCopy))
        menu.exec_(QtGui.QCursor.pos()) 
Example 30
Project: dcc   Author: amimo   File: treewindow.py    Apache License 2.0 5 votes vote down vote up
def createActions(self):
        self.xrefAct = QtWidgets.QAction(
            "Xref from/to",
            self,
            statusTip="List the references where this element is used",
            triggered=self.actionXref)
        self.expandAct = QtWidgets.QAction("Expand",
                                           self,
                                           statusTip="Expand all the subtrees",
                                           triggered=self.actionExpand)
        self.collapseAct = QtWidgets.QAction("Collapse",
                                             self,
                                             statusTip="Collapse all the subtrees",
                                             triggered=self.actionCollapse) 
Example 31
Project: kucher   Author: Zubax   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def _configure_file_menu(self):
        # File menu
        quit_action = QAction(get_icon('exit'), '&Quit', self)
        quit_action.triggered.connect(self._on_close)

        file_menu = self.menuBar().addMenu('&File')
        file_menu.addAction(quit_action)

    # noinspection PyCallByClass,PyUnresolvedReferences,PyArgumentList 
Example 32
Project: MovieHeavens   Author: lt94   File: movies.py    GNU General Public License v2.0 5 votes vote down vote up
def init_event(self):
        self.search_push_button.clicked.connect(self.search)
        self.search_content_text_list.itemClicked.connect(self.copy_text)

        reward_action = QAction('赞赏', self)
        reward_action.setIcon(QIcon('resources/reward.png'),)
        reward_action.triggered.connect(self.reward)

        watch_action = QAction('关注', self)
        watch_action.setIcon(QIcon('resources/watch.png'),)
        watch_action.triggered.connect(self.watch_wechat)

        reward_menu = self.menu_bar.addMenu('支持作者')
        reward_menu.addAction(reward_action)
        reward_menu.addAction(watch_action) 
Example 33
Project: cct   Author: awacha   File: mainwindow.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def showHideDockWidget(self, state: bool):
        action = self.sender()
        assert isinstance(action, QtWidgets.QAction)
        if not state:
            # we need to close the dockwidget
            try:
                self._dockwidgets[action].destroyed.disconnect(action.setChecked)
                self._dockwidgets[action].close()
                del self._dockwidgets[action]
            except (RuntimeError, TypeError):
                del self._dockwidgets[action]
            except KeyError:
                pass
        else:
            assert action not in self._dockwidgets
            cls = [self._dockwidgetinfo[a] for a in self._dockwidgetinfo if a is action][0]
            if not cls.testRequirements(self.credo, not_ready_is_ok=True):
                return False
            self._dockwidgets[action] = cls(self, credo=self.credo)
            self._dockwidgets[action].setSizePolicy(
                QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum,
                                      QtWidgets.QSizePolicy.Minimum))
            self._dockwidgets[action].setAttribute(QtCore.Qt.WA_DeleteOnClose)
            self._dockwidgets[action].destroyed.connect(lambda x=False: action.setChecked(False))
            self.addDockWidget(QtCore.Qt.TopDockWidgetArea, self._dockwidgets[action])
            action.setChecked(True) 
Example 34
Project: cct   Author: awacha   File: plotcurve.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setupUi(self, Form):
        Ui_Form.setupUi(self, Form)
        self.figure = Figure()
        self.canvas = FigureCanvasQTAgg(self.figure)
        self.axes = self.figure.add_subplot(1, 1, 1)
        self.figureContainer.setLayout(QtWidgets.QVBoxLayout())
        self.figureContainer.layout().addWidget(self.canvas)
        self.figureToolbar = NavigationToolbar2QT(self.canvas, self.figureContainer)
        self.figureContainer.layout().addWidget(self.figureToolbar)
        assert isinstance(self.figureToolbar, QtWidgets.QToolBar)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(":/icons/legend.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.legendAction = QtWidgets.QAction(icon, 'Show legend', None)
        self.legendAction.setCheckable(True)
        self.legendAction.setChecked(True)
        self.legendAction.triggered.connect(self.onLegendTriggered)
        icon = QtGui.QIcon.fromTheme("edit-clear-all")
        self.clearAxesAction = QtWidgets.QAction(icon, 'Clear all curves', None)
        self.clearAxesAction.triggered.connect(self.onClearAxes)
        toolbutton = QtWidgets.QToolButton()
        toolbutton.setDefaultAction(self.legendAction)
        self.figureToolbar.insertWidget(self.figureToolbar.actions()[0], toolbutton)
        toolbutton = QtWidgets.QToolButton()
        toolbutton.setDefaultAction(self.clearAxesAction)
        self.figureToolbar.insertWidget(self.figureToolbar.actions()[0], toolbutton)
        self.legendAction.setVisible(True)
        self.clearAxesAction.setVisible(True)
        self.figureToolbar.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Maximum)
        self.canvas.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        self.canvas.mpl_connect('resize_event', self.onCanvasResize) 
Example 35
Project: cct   Author: awacha   File: main.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def openRecentProject(self):
        action = self.sender()
        assert isinstance(action, QtWidgets.QAction)
        filename = action.toolTip()
        if self.createNewProject():
            self.project.open(filename) 
Example 36
Project: pyaudiorestoration   Author: HENDRIX-ZT2   File: widgets.py    GNU General Public License v2.0 5 votes vote down vote up
def add_to_menu(self, button_data):
		for submenu, name, func, shortcut in button_data:
			button = QtWidgets.QAction(name, self)
			button.triggered.connect(func)
			if shortcut: button.setShortcut(shortcut)
			submenu.addAction(button) 
Example 37
Project: Lector   Author: BasioMeusPuga   File: __main__.py    GNU General Public License v3.0 5 votes vote down vote up
def generate_library_filter_menu(self, directory_list=None):
        self.libraryFilterMenu.clear()

        def generate_name(path_data):
            this_filter = path_data[1]
            if not this_filter:
                this_filter = os.path.basename(
                    path_data[0]).title()
            return this_filter

        filter_actions = []
        filter_list = []
        if directory_list:
            checked = [i for i in directory_list if i[3] == QtCore.Qt.Checked]
            filter_list = list(map(generate_name, checked))
            filter_list.sort()

        filter_list.append(self._translate('Main_UI', 'Manually Added'))
        filter_actions = [QtWidgets.QAction(i, self.libraryFilterMenu) for i in filter_list]

        filter_all = QtWidgets.QAction('All', self.libraryFilterMenu)
        filter_actions.append(filter_all)

        for i in filter_actions:
            i.setCheckable(True)
            i.setChecked(True)
            i.triggered.connect(self.set_library_filter)

        self.libraryFilterMenu.addActions(filter_actions)
        self.libraryFilterMenu.insertSeparator(filter_all)
        self.libraryToolBar.libraryFilterButton.setMenu(self.libraryFilterMenu) 
Example 38
Project: eddy   Author: obdasystems   File: session.py    GNU General Public License v3.0 5 votes vote down vote up
def doLookupOccurrence(self):
        """
        Focus the item which is being held by the supplying QAction.
        """
        self.sgnFocusItem.emit(self.sender().data()) 
Example 39
Project: eddy   Author: obdasystems   File: factory.py    GNU General Public License v3.0 5 votes vote down vote up
def buildValueDomainNodeMenu(self, diagram, node):
        """
        Build and return a QMenu instance for value domain nodes.
        :type diagram: Diagram
        :type node: ValueDomainNode
        :rtype: QMenu
        """
        menu = self.buildGenericNodeMenu(diagram, node)
        # CREATE A NEW MENU FOR DATATYPE SELECTION NOT TO OVERWRITE THE PRE-DEFINED ONE
        self.customMenu['datatype'] = QtWidgets.QMenu('Select type')
        self.customMenu['datatype'].setIcon(self.session.menu('datatype').icon())
        # CREATE NEW CUSTOM ACTION SET FOR THE DATATYPES SUPPORTED BY THE CURRENT PROFILE
        self.customAction['datatype'] = []
        for datatype in sorted(Datatype.forProfile(self.project.profile.type()), key=attrgetter('value')):
            action = QtWidgets.QAction(self.session)
            action.setCheckable(True)
            action.setData(datatype)
            action.setText(datatype.value)
            connect(action.triggered, self.session.doSetDatatype)
            self.customAction['datatype'].append(action)
            self.customMenu['datatype'].addAction(action)
        # INSERT THE CUSTOM MENU IN THE NODE CONTEXTUAL MENU
        menu.insertMenu(self.session.action('node_properties'), self.customMenu['datatype'])
        menu.insertSeparator(self.session.action('node_properties'))
        for action in self.customAction['datatype']:
            action.setChecked(node.datatype == action.data())
        return menu

    #############################################
    #   LABEL
    ################################# 
Example 40
Project: bitmask-dev   Author: leapcode   File: systray.py    GNU General Public License v3.0 5 votes vote down vote up
def _createActions(self):
        self.quitAction = QAction(
            "&Quit", self,
            triggered=self.closeFromSystray) 
Example 41
Project: visma   Author: aerospaceresearch   File: window.py    GNU General Public License v3.0 5 votes vote down vote up
def initUI(self):
        exitAction = QtWidgets.QAction('Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.close)

        wikiAction = QtWidgets.QAction('Wiki', self)
        wikiAction.setStatusTip('Open Github wiki')
        wikiAction.triggered.connect(self.popupBrowser)

        addEqList = QtWidgets.QAction('Add Equations', self)
        addEqList.setStatusTip('Add custom equations')
        addEqList.triggered.connect(self.loadEquations)

        self.statusBar()

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAction)
        fileMenu.addAction(addEqList)
        # configMenu = menubar.addMenu('&Config')

        helpMenu = menubar.addMenu('&Help')
        helpMenu.addAction(wikiAction)
        self.workSpace = WorkSpace()
        self.setCentralWidget(self.workSpace)
        self.GUIwidth = 1300
        self.GUIheight = 900
        self.setGeometry(300, 300, self.GUIwidth, self.GUIheight)
        self.setWindowTitle('VISual MAth')
        self.show() 
Example 42
Project: Anki-TouchScreen   Author: krassowski   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def ts_setup_menu():
    """
    Initialize menu. If there is an entity "View" in top level menu
    (shared with other plugins, like "Zoom" of R. Sieker) options of
    the addon will be placed there. In other case it creates that menu.
    """
    global ts_menu_switch

    try:
        mw.addon_view_menu
    except AttributeError:
        mw.addon_view_menu = QMenu(_(u"&View"), mw)
        mw.form.menubar.insertMenu(mw.form.menuTools.menuAction(),
                                    mw.addon_view_menu)

    mw.ts_menu = QMenu(_('&Touchscreen'), mw)

    mw.addon_view_menu.addMenu(mw.ts_menu)

    ts_menu_switch = QAction(_('&Enable touchscreen mode'), mw, checkable=True)
    ts_menu_color = QAction(_('Set &pen color'), mw)
    ts_menu_width = QAction(_('Set pen &width'), mw)
    ts_menu_opacity = QAction(_('Set pen &opacity'), mw)
    ts_menu_about = QAction(_('&About...'), mw)

    ts_toggle_seq = QKeySequence("Ctrl+r")
    ts_menu_switch.setShortcut(ts_toggle_seq)

    mw.ts_menu.addAction(ts_menu_switch)
    mw.ts_menu.addAction(ts_menu_color)
    mw.ts_menu.addAction(ts_menu_width)
    mw.ts_menu.addAction(ts_menu_opacity)
    mw.ts_menu.addSeparator()
    mw.ts_menu.addAction(ts_menu_about)

    ts_menu_switch.triggered.connect(ts_switch)
    ts_menu_color.triggered.connect(ts_change_color)
    ts_menu_width.triggered.connect(ts_change_width)
    ts_menu_opacity.triggered.connect(ts_change_opacity)
    ts_menu_about.triggered.connect(ts_about) 
Example 43
Project: plexdesktop   Author: coryo   File: browser.py    GNU General Public License v3.0 5 votes vote down vote up
def ui_load_shortcuts(self):
        self.ui.bookmarksToolBar.clear()
        for i, (name, loc) in enumerate(self.session_manager.shortcuts.items()):
            action = QtWidgets.QAction(name, self.ui.bookmarksToolBar)
            action.setData(loc)
            action.triggered.connect(self.goto_bookmark)
            action.setShortcut('ALT+{}'.format(i + 1))
            self.ui.bookmarksToolBar.addAction(action) 
Example 44
Project: plexdesktop   Author: coryo   File: browser.py    GNU General Public License v3.0 5 votes vote down vote up
def ui_update_servers(self):
        self.ui.servers.blockSignals(True)
        self.ui.servers.clear()
        self.ui.menuServers.clear()
        session = self.session_manager.session
        for i, server in enumerate(session.servers):
            self.ui.servers.addItem(server.name, server)
            action = QtWidgets.QAction(server.name, self.ui.menuServers)
            action.setData(server)
            action.triggered.connect(self.action_change_server2)
            action.setShortcut('CTRL+{}'.format(i + 1))
            self.ui.menuServers.addAction(action)
        self.ui.servers.blockSignals(False) 
Example 45
Project: plexdesktop   Author: coryo   File: browser.py    GNU General Public License v3.0 5 votes vote down vote up
def ui_update_session(self):
        sm = self.session_manager

        self.ui.menuRemotes.clear()
        self.ui_update_servers()
        self.ui_update_users()

        current_tab = self.ui.tabs.currentWidget()

        if current_tab:
            last_server = [x for x in range(self.ui.servers.count()) if
                           self.ui.servers.itemData(x) == current_tab.current_server]
            self.ui_update_servers_no_signal(last_server[0] if last_server else -1)

        last_user = [x for x in range(self.ui.users.count()) if
                     self.ui.users.itemData(x) == sm.user]
        self.ui_update_users_no_signal(last_user[0] if last_user else -1)

        for player in sm.session.players:
            action = QtWidgets.QAction(str(player), self.ui.menuRemotes)
            action.setData(player)
            action.triggered.connect(self.action_launch_remote)
            self.ui.menuRemotes.addAction(action)

        # if not self.initialized:
        if not current_tab:
            self.initialize(sm.current_server) 
Example 46
Project: XulDebugTool   Author: starcor-company   File: FavoriteTreeView.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def menuOperation(self,point):
        index = self.indexAt(point)
        if not index.isValid():
            return
        item = self.treeModel.itemFromIndex(index)
        menu = QMenu()

        if item.type == ITEM_TYPE_HISTORY:
            queryAction = QAction(IconTool.buildQIcon('data.png'), '&Edit ...', self,triggered=lambda: self.showQueryDialog(item))
            queryAction.setShortcut('Alt+E')
            menu.addAction(queryAction)

            favoritesAction = QAction(IconTool.buildQIcon('star.png'), 'Add to &favorites', self,triggered=lambda: self.add2Favorites(item))
            favoritesAction.setShortcut('Alt+F')
            menu.addAction(favoritesAction)

            deleteAction = QAction(IconTool.buildQIcon('clear.png'), '&Delete', self,triggered=lambda: self.deleteHistory(item))
            deleteAction.setShortcut('Ctrl+D')
            menu.addAction(deleteAction)

        if item.type == ITEM_TYPE_FAVORITES:
            queryAction = QAction(IconTool.buildQIcon('data.png'), '&Edit ...', self,triggered=lambda: self.showQueryDialog(item))
            queryAction.setShortcut('Alt+E')
            menu.addAction(queryAction)

            disFavoritesAction = QAction(IconTool.buildQIcon('remove_favorites.png'), 'Remove from &favorites', self,triggered=lambda: self.remove2Favorites(item))
            disFavoritesAction.setShortcut('Alt+F')
            menu.addAction(disFavoritesAction)

            deleteAction = QAction(IconTool.buildQIcon('clear.png'), '&Delete', self,triggered=lambda: self.deleteFavorite(item))
            deleteAction.setShortcut('Ctrl+D')
            menu.addAction(deleteAction)

        if item.type == ITEM_TYPE_URL:
            copyAction = QAction(IconTool.buildQIcon('copy.png'), 'Copy', self,triggered=lambda: pyperclip.copy('%s' % index.data()))
            copyAction.setShortcut('Ctrl+C')
            menu.addAction(copyAction)

        menu.exec_(self.viewport().mapToGlobal(point)) 
Example 47
Project: uPyLoader   Author: BetaRavener   File: transfer_tree_view.py    MIT License 5 votes vote down vote up
def _add_menu_action(self, title, handler):
        action = QAction(title, self.context_menu)
        action.triggered.connect(handler)
        self.context_menu.addAction(action)
        return action 
Example 48
Project: PyRHEED   Author: yux1991   File: canvas.py    MIT License 5 votes vote down vote up
def contextMenuEvent(self,event):
        """This is an overload function"""
        self.menu = QtWidgets.QMenu()
        self.clear = QtWidgets.QAction('Clear')
        self.clear.triggered.connect(self.clear_canvas)
        self.save = QtWidgets.QAction('Save as...')
        self.save.triggered.connect(self.save_scene)
        self.menu.addAction(self.clear)
        self.menu.addAction(self.save)
        self.menu.popup(event.globalPos()) 
Example 49
Project: PyRHEED   Author: yux1991   File: plot_chart.py    MIT License 5 votes vote down vote up
def contextMenuEvent(self,event):
        """This is an overload function"""
        self.menu = QtWidgets.QMenu()
        self.saveAsText = QtWidgets.QAction('Save as text...')
        self.saveAsText.triggered.connect(self.save_polar_as_text)
        self.saveAsImage = QtWidgets.QAction('Save as an image...')
        self.saveAsImage.triggered.connect(self.save_polar_as_image)
        self.saveAsSVG = QtWidgets.QAction('Export as SVG...')
        self.saveAsSVG.triggered.connect(self.save_polar_as_SVG)
        self.menu.addAction(self.saveAsText)
        self.menu.addAction(self.saveAsImage)
        self.menu.addAction(self.saveAsSVG)
        self.menu.popup(event.globalPos()) 
Example 50
Project: PyRHEED   Author: yux1991   File: profile_chart.py    MIT License 5 votes vote down vote up
def contextMenuEvent(self,event):
        """This is an overload function"""
        self.menu = QtWidgets.QMenu()
        self.saveAsText = QtWidgets.QAction('Save as text...')
        self.saveAsText.triggered.connect(self.save_profile_as_text)
        self.saveAsImage = QtWidgets.QAction('Save as an image...')
        self.saveAsImage.triggered.connect(self.save_profile_as_image)
        self.saveAsSVG = QtWidgets.QAction('Export as SVG...')
        self.saveAsSVG.triggered.connect(self.save_profile_as_SVG)
        self.menu.addAction(self.saveAsText)
        self.menu.addAction(self.saveAsImage)
        self.menu.addAction(self.saveAsSVG)
        self.menu.popup(event.globalPos())