def _addDrawingTool(self, classCode, category, toolName, icon, featureType, query=None): data = {} data['class'] = classCode data['category'] = category action = QAction(icon, category, self) action.setData(data) action.setToolTip(toolName) action.setCheckable(True) mapTool = MapToolAddFeature(self._iface, featureType, toolName) mapTool.setAction(action) mapTool.setPanningEnabled(True) mapTool.setZoomingEnabled(True) mapTool.setSnappingEnabled(True) mapTool.activated.connect(self._mapToolActivated) if query is not None: field = Config.fields[query] mapTool.setAttributeQuery( field['attribute'], field['type'], field['default'], field['label'], field['query'], field['min'], field['max'], field['decimals'] ) self._addToolButton(action, featureType) self._actions[category] = action self._mapTools[category] = mapTool
def create_action(parent, text, shortcut=None, icon=None, tip=None, toggled=None, triggered=None, data=None, window_context=True): """Create a QAction""" action = QAction(text, parent) if triggered is not None: parent.connect(action, SIGNAL("triggered()"), triggered) if toggled is not None: parent.connect(action, SIGNAL("toggled(bool)"), toggled) action.setCheckable(True) if icon is not None: if isinstance(icon, (str, unicode)): icon = get_icon(icon) action.setIcon(icon) if shortcut is not None: action.setShortcut(shortcut) if tip is not None: action.setToolTip(tip) action.setStatusTip(tip) if data is not None: action.setData(QVariant(data)) if window_context: action.setShortcutContext(Qt.WindowShortcut) else: #TODO: Hard-code all shortcuts and choose window_context=False # (this will avoid calling shortcuts from another dockwidget # since the context thing doesn't work quite well with these) action.setShortcutContext(Qt.WidgetShortcut) return action
def captureLayer(self, layer): text = layer.icontext tool = layer.getMaptool(self.iface.mapCanvas()) # Hack until I fix it later if isinstance(tool, PointTool): add = functools.partial(self.addNewFeature, qgslayer) tool.geometryComplete.connect(add) else: tool.finished.connect(self.openForm) tool.error.connect(functools.partial(self.showToolError, text)) action = QAction(QIcon(layer.icon), text, self.mainwindow) action.setData(layer) action.setCheckable(True) action.toggled.connect(functools.partial(self.setMapTool, tool)) self.toolbar.insertAction(self.editingmodeaction, action) if not tool.isEditTool(): # Connect the GPS tools strip to the action pressed event. showgpstools = (functools.partial(self.extraaddtoolbar.showToolbar, action, None)) action.toggled.connect(showgpstools) self.actionGroup.addAction(action) self.actions.append(action)
def create_action(parent, text, shortcut=None, icon=None, tip=None, toggled=None, triggered=None, data=None, context=Qt.WindowShortcut): """Create a QAction""" action = QAction(text, parent) if triggered is not None: parent.connect(action, SIGNAL("triggered()"), triggered) if toggled is not None: parent.connect(action, SIGNAL("toggled(bool)"), toggled) action.setCheckable(True) if icon is not None: if isinstance(icon, (str, unicode)): icon = get_icon(icon) action.setIcon( icon ) if shortcut is not None: action.setShortcut(shortcut) if tip is not None: action.setToolTip(tip) action.setStatusTip(tip) if data is not None: action.setData(QVariant(data)) #TODO: Hard-code all shortcuts and choose context=Qt.WidgetShortcut # (this will avoid calling shortcuts from another dockwidget # since the context thing doesn't work quite well with these widgets) action.setShortcutContext(context) return action
def setupLanguageMenu(self): self.languages = QDir(":/languages").entryList() if self.current_language is None: self.current_language = QLocale.system().name( ) # Retrieve Current Locale from the operating system. log.debug("Detected user's locale as %s" % self.current_language) for language in self.languages: translator = QTranslator( ) # Create a translator to translate Language Display Text. translator.load(":/languages/%s" % language) language_display_text = translator.translate( "Translation", "Language Display Text") languageAction = QAction(self) languageAction.setCheckable(True) languageAction.setText(language_display_text) languageAction.setData(language) self.menuLanguage.addAction(languageAction) self.langActionGroup.addAction(languageAction) if self.current_language == str(language).strip("tr_").rstrip( ".qm"): languageAction.setChecked(True)
def create_exampleActs(self): """ Create Actions to open example files """ exdir = None self.menuExamples.menuAction().setVisible(False) bpath = sys.path[0] + os.sep for p in ['../share/openscadpy/examples', '../../share/openscadpy/examples', '../../examples','../examples','examples']: exdir = bpath + p if os.access(exdir, os.R_OK ): break else: exdir = None if not exdir: return for e in sorted(os.listdir(exdir)): if e[-3:] == '.py': fname = exdir + os.sep + e a = QAction(self) QtCore.QObject.connect(a, QtCore.SIGNAL(_fromUtf8("triggered()")), self.on_open_menu_file) a.setText(e) a.setData(fname) self.menuExamples.addAction(a) self.menuExamples.menuAction().setVisible(True)
def _addDrawingAction(self, drawingAction, text): action = QAction(text, self) action.setCheckable(True) action.setData(drawingAction) action.triggered.connect(self._drawingActionSelected) self._drawingActionGroup.addAction(action) return action
def create_action(parent, text, shortcut=None, icon=None, tip=None, toggled=None, triggered=None, data=None, menurole=None, context=Qt.WindowShortcut): """Create a QAction""" action = QAction(text, parent) if triggered is not None: parent.connect(action, SIGNAL("triggered()"), triggered) if toggled is not None: parent.connect(action, SIGNAL("toggled(bool)"), toggled) action.setCheckable(True) if icon is not None: if is_text_string(icon): icon = get_icon(icon) action.setIcon(icon) if shortcut is not None: action.setShortcut(shortcut) if tip is not None: action.setToolTip(tip) action.setStatusTip(tip) if data is not None: action.setData(data) if menurole is not None: action.setMenuRole(menurole) #TODO: Hard-code all shortcuts and choose context=Qt.WidgetShortcut # (this will avoid calling shortcuts from another dockwidget # since the context thing doesn't work quite well with these widgets) action.setShortcutContext(context) return action
def createActionForItem(self, item): """Create the QAction instance for item. """ action = QAction(item.icon(), item.text(), self, toolTip=item.toolTip()) action.setData(item) return action
def populateMenuFromSettings(self, menu): """ :type menu: QMenu """ actions = menu.actions() before = actions[0] if actions else None title = QWidgetAction(menu) label = QLabel("Hosts") font = label.font() px = font.pointSize() font.setBold(True) font.setPointSize(px * 1.5) label.setFont(font) label.setMargin(4) label.setIndent(10) # label.setStyleSheet("font-weight: bold; margin: 4px 2px; border-bottom: 2px solid black") title.setDefaultWidget(label) menu.insertAction(before, title) self.menuServers.append(title) servers = self.settings.beginReadArray("servers") for d in range(servers): self.settings.setArrayIndex(d) server = Server.fromSettings(self.settings) action = QAction(QIcon("res/server.png"), server.alias, menu) menu.insertAction(before, action) action.setData(server) action.triggered.connect(self.wakeFromMenu) self.menuServers.append(action) self.settings.endArray()
def __init__(self): QObject.__init__(self) self._createdActions = [] self._createdMenus = [] self._currentDocument = core.workspace().currentDocument() # probably None model = core.actionManager() for menu in _MENUS: if menu[2]: menuObj = model.addMenu(menu[0], menu[1], QIcon(':/enkiicons/' + menu[2])) else: menuObj = model.addMenu(menu[0], menu[1]) menuObj.setEnabled(False) self._createdMenus.append(menuObj) for command, path, text, shortcut, icon in _ACTIONS: actObject = QAction(text, self) if shortcut: actObject.setShortcut(shortcut) if icon: actObject.setIcon(QIcon(':/enkiicons/' + icon)) actObject.setData(command) actObject.setEnabled(False) actObject.triggered.connect(self.onAction) model.addAction(path, actObject) self._createdActions.append(actObject) core.workspace().currentDocumentChanged.connect(self.onCurrentDocumentChanged)
def __init__(self): QObject.__init__(self) self._createdActions = [] self._createdSeparators = [] self._createdMenus = [] self._currentDocument = core.workspace().currentDocument() # probably None for menu in _MENUS: if menu[2]: menuObj = core.actionManager().addMenu(menu[0], menu[1], QIcon(':/enkiicons/' + menu[2])) else: menuObj = core.actionManager().addMenu(menu[0], menu[1]) menuObj.setEnabled(False) self._createdMenus.append(menuObj) for item in _ACTIONS: if isinstance(item, tuple): # action command, path, text, shortcut, icon = item actObject = QAction(text, self) if shortcut: actObject.setShortcut(shortcut) if icon: actObject.setIcon(QIcon(':/enkiicons/' + icon)) actObject.setData(command) actObject.setEnabled(False) actObject.triggered.connect(self.onAction) core.actionManager().addAction(path, actObject) self._createdActions.append(actObject) else: # separator menuPath = item menu = core.actionManager().menu(menuPath) self._createdSeparators.append(menu.addSeparator()) core.workspace().currentDocumentChanged.connect(self.onCurrentDocumentChanged)
def _addFilterAction(self, filterAction, text): action = QAction(text, self) action.setCheckable(True) action.setData(filterAction) action.triggered.connect(self._filterActionSelected) self._filterActionGroup.addAction(action) return action
def updateFileMenu(self): """ Creates new file menu everytime the user invokes it. File menu can't be created only once, because of recent files section which has to be refreshed. """ self.fileMenu.clear() # add all fixed actions, but close self.fileMenu.addActions(self.fileMenuActions[:-1]) current = QString(self.model.fname) \ if self.model.fname is not None else None recentFiles = [] for fname in self.recentFiles: if fname != current and QFile.exists(fname): recentFiles.append(fname) if recentFiles: self.fileMenu.addSeparator() self.recentFilesMenu = self.fileMenu.addMenu("Recent Files") for i, fname in enumerate(recentFiles): action = QAction("&%d %s" % ( i + 1, QFileInfo(fname).fileName()), self) action.setData(QVariant(fname)) self.connect(action, SIGNAL("triggered()"), lambda file = fname: self.loadRecentFile(file)) self.recentFilesMenu.addAction(action) self.fileMenu.addSeparator() # add the last action - close self.fileMenu.addAction(self.fileMenuActions[-1])
def _addDrawingTool(self, classCode, category, toolName, icon, featureType, query=None): data = {} data['class'] = classCode data['category'] = category action = QAction(icon, category, self) action.setData(data) action.setToolTip(toolName) action.setCheckable(True) mapTool = MapToolAddFeature(self._iface, featureType, toolName) mapTool.setAction(action) mapTool.setPanningEnabled(True) mapTool.setZoomingEnabled(True) mapTool.setSnappingEnabled(True) mapTool.activated.connect(self._mapToolActivated) if query is not None: field = Config.fields[query] mapTool.setAttributeQuery(field['attribute'], field['type'], field['default'], field['label'], field['query'], field['min'], field['max'], field['decimals']) self._addToolButton(action, featureType) self._actions[category] = action self._mapTools[category] = mapTool
def initUI(self): closeAction = QAction('Close', self) closeAction.setShortcut('Ctrl+Q') closeAction.setStatusTip('Close Application') closeAction.triggered.connect(lambda: sys.exit(0)) loadAction = QAction('Load Protocol', self) loadAction.setStatusTip('Load the Default Protocol') loadAction.triggered.connect(self.find_pcl_file) menubar = self.menuBar() file_menu = menubar.addMenu('&File') file_menu.addAction(closeAction) load_menu = menubar.addMenu('&Load') load_menu.addAction(loadAction) self.toolbar = self.addToolBar('Exit') self.toolbar.addAction(closeAction) load_menu.addSeparator() for idx, recent_pcl in enumerate(self.recent_pcls): new_action = QAction("%d %s" % (idx + 1, recent_pcl['name']), self) new_action.triggered.connect(self.open_recent_pcl) new_action.setData(QVariant(recent_pcl['filename'])) load_menu.addAction(new_action) self.setWindowTitle('fealines') self.show_empty_screen() self.showMaximized()
def create_action_for_item(self, item): """ Create a QAction instance for the widget description item. """ name = item.text() tooltip = item.toolTip() whatsThis = item.whatsThis() icon = item.icon() if icon: action = QAction(icon, name, self, toolTip=tooltip, whatsThis=whatsThis, statusTip=name) else: action = QAction(name, self, toolTip=tooltip, whatsThis=whatsThis, statusTip=name) widget_desc = item.data(self.WIDGET_DESC_ROLE) action.setData(widget_desc) action.setProperty("item", item) return action
def _SH_ModelChanged(self, parent_index, start, end): menu = self.account_button.menu() menu.clear() for row in xrange(self.model.rowCount()): account_info = self.model.data(self.model.index(row, 0), Qt.UserRole).toPyObject() action = QAction(account_info.name, self) action.setData(QVariant(account_info.account)) menu.addAction(action)
def createAction( parent, label, callback=None, icon = None, tip = None, shortcut = None, data = None, toggled = False, tooltip=None, cb_arg=None, iconText=None, checkable=None): """ Create a QAction @param parent: @type parent: @param label: @type label: @param callback: @type callback: @param icon: @type icon: @param tip: @type tip: @param shortcut: @type shortcut: @param data: @type data: @param toggled: @type toggled: @return: @rtype: """ action = QAction(label, parent) if toggled: if callback is not None: action.toggled.connect(callback) action.setCheckable(True) else: if callback is not None: if cb_arg is None: action.triggered.connect(callback) else: action.triggered.connect(lambda: callback(cb_arg) ) if icon: action.setIcon(icon) if shortcut: action.setShortcut(shortcut) if tip: action.setStatusTip(tip) if tooltip: action.setToolTip(tooltip) if data is not None: action.setData( QVariant(data) ) if iconText is not None: action.setIconText(iconText) if checkable is not None: action.setCheckable(checkable) return action
def createActionForItem(self, index): """Create the QAction instance for item at `index` (`QModelIndex`). """ action = QAction( item_icon(index), item_text(index), self, toolTip=item_tooltip(index) ) action.setData(QPersistentModelIndex(index)) return action
def _SH_ModelChanged(self, parent_index, start, end): menu = self.account_button.menu() menu.clear() for row in xrange(self.model.rowCount()): account_info = self.model.data(self.model.index(row, 0), Qt.UserRole) action = QAction(account_info.name, self) action.setData(account_info.account) menu.addAction(action)
def createActionForItem(self, index): """Create the QAction instance for item at `index` (`QModelIndex`). """ action = QAction(item_icon(index), item_text(index), self, toolTip=item_tooltip(index)) action.setData(QPersistentModelIndex(index)) return action
def makeBookmarkAction(self, parent, id, book, chapter, verse, title, added=None): """ Creates and returns a QAction for a bookmark. """ action = QAction(title, parent) action.setData(QVariant(id)) def bookmarkActivated(checked=False): self.navigateToPassage(book, chapter, verse) self.connect(action, Signals.triggered, bookmarkActivated) return action
def _refreshMenu(self, menuEntry): menu, fixedItemCount = menuEntry for action in menu.actions()[fixedItemCount:]: menu.removeAction(action) for item in self._items: action = QAction(item, menu) action.setData(item) action.triggered.connect(self.menuItemWasClicked) menu.addAction(action) menu.addSeparator() action = QAction(tr("Clear List"), menu) action.triggered.connect(self.clear) menu.addAction(action)
def _on_header_menu(self, point): menu = QMenu() for index, title in enumerate(self.model().header): action = QAction(self) action.setData(index) action.setText(title) action.setCheckable(True) action.setChecked(False if self.isColumnHidden(index) else True) action.triggered.connect(self._on_header_menu_action) menu.addAction(action) menu.popup(self.mapToGlobal(point)) menu.exec_()
def setDefaultDatabases(self, connStrings): self.menuStandard.clear() self.defaultDatabases = {} names = connStrings.keys() names.sort() for name in names: conn = connStrings[name] action = QAction(self) action.setText(name) action.setData(QVariant(conn)) action.setStatusTip(conn) QObject.connect(action, SIGNAL("triggered()"), self.openStandardDatabase) self.menuStandard.addAction(action) self.defaultDatabases[name] = action self.menuStandard.setEnabled(not self.menuStandard.isEmpty())
def _NH_SIPAccountManagerDidAddAccount(self, notification): account = notification.data.account action = QAction(account.id if account is not BonjourAccount() else u'Bonjour', None) action.setEnabled(True if account is not BonjourAccount() else BonjourAccount.mdns_available) action.setCheckable(True) action.setChecked(account.enabled) action.setData(account) action.triggered.connect(partial(self._AH_AccountActionTriggered, action)) self.accounts_menu.addAction(action) action = QAction(self.mwi_icons[0], account.id, None) action.setVisible(False if account is BonjourAccount() else account.enabled and account.message_summary.enabled) action.setEnabled(False if account is BonjourAccount() else account.voicemail_uri is not None) action.setData(account) action.triggered.connect(partial(self._AH_VoicemailActionTriggered, action)) self.voicemail_menu.addAction(action)
def _addDatasetAction(self, dataset): """ Adds an action for the inputed dataset to the toolbar :param dataset | <XChartDataset> """ # create the toolbar action action = QAction(dataset.name(), self) action.setIcon(XColorIcon(dataset.color())) action.setCheckable(True) action.setChecked(True) action.setData(qt.wrapVariant(dataset)) action.toggled.connect(self.toggleDataset) self.uiDatasetTBAR.addAction(action)
def canvasReleaseEvent(self, e): self._reset() if e.button() != Qt.LeftButton: return mapPoint = self.toMapCoordinates(e.pos()) self._vertexMarker.setCenter(mapPoint) layers = [ self.collection().layer('points'), self.collection().layer('lines'), self.collection().layer('polygons') ] results = self.identify(e.x(), e.y(), layers, QgsMapToolIdentify.TopDownAll) if (len(results) < 1): return # Build the set of unique items identified items = set() for result in results: feature = result.mFeature siteCode = feature.attribute('site') classCode = feature.attribute('class') itemId = feature.attribute('id') items.add(Item(siteCode, classCode, itemId)) action = QAction('Plan Items', self._menu) action.setData('top') self._menu.addAction(action) site = '' for item in sorted(items): if item.siteCode() != site: site = item.siteCode() self._menu.addSeparator() action = QAction('Site ' + site + ':', self._menu) action.setData('top') self._menu.addAction(action) action = IdentifyItemAction(item, self._plugin, self._menu) action.setData('top') action.zoomToItemSelected.connect(self._zoom) action.panToItemSelected.connect(self._pan) action.filterItemSelected.connect(self._filterItem) action.excludeFilterItemSelected.connect(self._excludeFilterItem) action.highlightItemSelected.connect(self._highlightItem) action.addHighlightItemSelected.connect(self._addHighlightItem) action.editItemSelected.connect(self._editInBuffers) action.deleteItemSelected.connect(self._delete) action.openDrawingsSelected.connect(self._openDrawings) self._actions.append(action) self._menu.addAction(action) self._menu.addSeparator() action = ClipboardAction('Map: ', mapPoint.toString(3), self._menu) action.setData('top') self._menu.addAction(action) if self._plugin.grid().mapTransformer is not None: localPoint = self._plugin.grid().mapTransformer.map(mapPoint) self._menu.addAction( ClipboardAction('Local: ', localPoint.toString(3), self._menu)) menuPos = QPoint(e.globalX() + 100, e.globalY() - 50) selected = self._menu.exec_(menuPos) self._reset(resetVertex=False)
def __createLanguageOptions(self): """Creates the language selection in the menubar. """ self.langGroup = QActionGroup(self) self.langGroup.setExclusive(True) self.langGroup.triggered['QAction*'].connect(self.languageChanged) for key, name in self.languages.iteritems(): action = QAction(self) action.setCheckable(True) action.setData(key) action.setText(name[0]) action.setStatusTip(name[1]) action.setActionGroup(self.langGroup) self.menuLanguage.addAction(action) if key == self.currentLanguage: action.setChecked(True)
def update_file_menu(self): self.fileMenu.clear() self.addActions(self.fileMenu, self.fileMenuActions[:-1]) current = self.filename if self.filename is not None else None recentFiles = [] for fname in self.recentFiles: if fname != current and QFile.exists(fname): recentFiles.append(fname) if recentFiles: self.fileMenu.addSeparator() for i, fname in enumerate(recentFiles): action = QAction("&{num} {name}".format(num=i+1, name=QFileInfo(fname).fileName()), self) action.setData(fname) action.triggered.connect(lambda: self.loadFile(fname)) self.fileMenu.addAction(action) self.fileMenu.addSeparator() self.fileMenu.addAction(self.fileMenuActions[-1])
def create_action(self): """ Factory method that creates a QAction from the specified icon file and data source display name. :return: Returns a QAction object. :rtype: QAction """ name = u'{0} {1}'.format(self._search_prefix, self._display_name) if not self._icon_file: icon = QIcon() else: icon = QIcon(self._icon_file) action = QAction(icon, name, None) action.setCheckable(True) action.setData(self._data_source) return action
def setupLanguageMenu(self): self.languages = QDir(":/languages").entryList() if self.current_language is None: self.current_language = QLocale.system().name() # Retrieve Current Locale from the operating system. log.debug("Detected user's locale as %s" % self.current_language) for language in self.languages: translator = QTranslator() # Create a translator to translate Language Display Text. translator.load(":/languages/%s" % language) language_display_text = translator.translate("Translation", "Language Display Text") languageAction = QAction(self) languageAction.setCheckable(True) languageAction.setText(language_display_text) languageAction.setData(language) self.menuLanguage.addAction(languageAction) self.langActionGroup.addAction(languageAction)
def canvasReleaseEvent(self, e): self._reset() if e.button() != Qt.LeftButton: return mapPoint = self.toMapCoordinates(e.pos()) self._vertexMarker.setCenter(mapPoint) layers = [self.collection().layer('points'), self.collection().layer('lines'), self.collection().layer('polygons')] results = self.identify(e.x(), e.y(), layers, QgsMapToolIdentify.TopDownAll) if (len(results) < 1): return # Build the set of unique items identified items = set() for result in results: feature = result.mFeature siteCode = feature.attribute('site') classCode = feature.attribute('class') itemId = feature.attribute('id') items.add(Item(siteCode, classCode, itemId)) action = QAction('Plan Items', self._menu) action.setData('top') self._menu.addAction(action) site = '' for item in sorted(items): if item.siteCode() != site: site = item.siteCode() self._menu.addSeparator() action = QAction('Site ' + site + ':', self._menu) action.setData('top') self._menu.addAction(action) action = IdentifyItemAction(item, self._plugin, self._menu) action.setData('top') action.zoomToItemSelected.connect(self._zoom) action.panToItemSelected.connect(self._pan) action.filterItemSelected.connect(self._filterItem) action.excludeFilterItemSelected.connect(self._excludeFilterItem) action.highlightItemSelected.connect(self._highlightItem) action.addHighlightItemSelected.connect(self._addHighlightItem) action.editItemSelected.connect(self._editInBuffers) action.deleteItemSelected.connect(self._delete) action.openDrawingsSelected.connect(self._openDrawings) self._actions.append(action) self._menu.addAction(action) self._menu.addSeparator() action = ClipboardAction('Map: ', mapPoint.toString(3), self._menu) action.setData('top') self._menu.addAction(action) if self._plugin.grid().mapTransformer is not None: localPoint = self._plugin.grid().mapTransformer.map(mapPoint) self._menu.addAction(ClipboardAction('Local: ', localPoint.toString(3), self._menu)) menuPos = QPoint(e.globalX() + 100, e.globalY() - 50) selected = self._menu.exec_(menuPos) self._reset(resetVertex=False)
def updateFileMenu(self): self.fileMenu.clear() self.addActions(self.fileMenu, self.fileMenuActions[:-1]) current = (QString(self.filename) if self.filename is not None else None) recentFiles = [] for fname in self.recentFiles: if fname != current and QFile.exists(fname): recentFiles.append(fname) if recentFiles: self.fileMenu.addSeparator() for i, fname in enumerate(recentFiles): action = QAction(QIcon(":/icon.png"), "&{0} {1}".format(i + 1, QFileInfo( fname).fileName()), self) action.setData(QVariant(fname)) action.triggered.connect(self.loadFile) self.fileMenu.addAction(action) self.fileMenu.addSeparator() self.fileMenu.addAction(self.fileMenuActions[-1])
def createMenus(self): self.fileMenu = self.menuBar().addMenu("File") self.fileMenu.addAction(self.quitAct) self.fileMenu.addAction(self.saveAct) self.modeMenu = self.menuBar().addMenu("Mode") self.modeActionGroup = QActionGroup(self,triggered=self.modeActionTriggered) self.modeActionGroup.setExclusive(True) allModeList = [] allModeList.append(["Manual Mode", False, Mode.MANUAL_MODE]) allModeList.append(["Manual Player Mode",True,Mode.MANUAL_PLAYER_MODE]) allModeList.append(["Pegasus Mode", False,Mode.PEGASUS_MODE]) for modeData in allModeList: modeActionObject = QAction(modeData[0],self) modeActionObject.setCheckable(True) modeActionObject.setChecked(modeData[1]) modeActionObject.setData(modeData[2]) self.modeActionGroup.addAction(modeActionObject) self.modeMenu.addAction(modeActionObject)
def update_recently_used_files(self, path = None): """ Update the list of recently used files. We update both the menu as well as the stored value in settings. """ fileString = self.settings.recently_used_files # need this check to avoid interpreting an empty entry # as an empty filename if len(fileString) == 0: files = [] else: files = fileString.split("%") # whithout a path we simply update the menu without # adding any filename if path: fullPath = QFileInfo(path).absoluteFilePath() if fullPath in files: return else: files.append(fullPath) while len(files) > 10 and files: files.pop(len(files)-1) self.settings.recently_used_files = "%".join(files) self.clear_recently_used_files_menu() # the actual path is stored as data since the text # of the Action also provides numbering and accelerators for (index, path) in enumerate(files): fileName = QFileInfo(path).fileName() newPathAction = \ QAction("&%d. %s" % (index+1, fileName), self.menuRecent_Files) newPathAction.setData(path) self.menuRecent_Files.addAction(newPathAction)
def update_recently_used_files(self, path=None): """ Update the list of recently used files. We update both the menu as well as the stored value in settings. """ fileString = self.settings.recently_used_files # need this check to avoid interpreting an empty entry # as an empty filename if not fileString: files = [] else: files = fileString.split("%") # whithout a path we simply update the menu without # adding any filename if path: fullPath = QFileInfo(path).absoluteFilePath() if fullPath in files: return else: files.append(fullPath) while len(files) > 10 and files: files.pop(len(files) - 1) self.settings.recently_used_files = "%".join(files) self.clear_recently_used_files_menu() # the actual path is stored as data since the text # of the Action also provides numbering and accelerators for (index, path) in enumerate(files): fileName = QFileInfo(path).fileName() newPathAction = \ QAction("&%d. %s" % (index+1, fileName), self.menuRecent_Files) newPathAction.setData(path) self.menuRecent_Files.addAction(newPathAction)
def addTab(self, widget, text, toolTip=None, icon=None): if self.__macUnified: action = QAction(text, self) if toolTip: action.setToolTip(toolTip) if icon: action.setIcon(toolTip) action.setData(len(self.tab.actions())) self.tab.addAction(action) self.stack.addWidget(widget) else: i = self.tab.addTab(widget, text) if toolTip: self.tab.setTabToolTip(i, toolTip) if icon: self.tab.setTabIcon(i, icon)
def _on_row_menu(self, point): row = self.rowAt(point.y()) task = self.get_task_by_row(row) if row < 0 or task is None: return menu = QMenu() load_action = QAction(self) load_action.setData(task.id) load_action.setText("Load parameters") load_action.triggered.connect(self._on_load_params_action) menu.addAction(load_action) delete_action = QAction(self) delete_action.setData(task.id) delete_action.setText('Delete') delete_action.triggered.connect(self._on_row_delete_action) menu.addAction(delete_action) menu.popup(self.mapToGlobal(point)) menu.exec_()
def load_video_devices(self): settings = SIPSimpleSettings() action = QAction(u'System default', self.video_devices_group) action.setData(u'system_default') self.video_camera_menu.addAction(action) self.video_camera_menu.addSeparator() for device in SIPApplication.engine.video_devices: action = QAction(device, self.video_devices_group) action.setData(device) self.video_camera_menu.addAction(action) action = QAction(u'None', self.video_devices_group) action.setData(None) self.video_camera_menu.addAction(action) for action in self.video_devices_group.actions(): action.setCheckable(True) if settings.video.device == action.data(): action.setChecked(True)
def __init__(self, quarterwidget): QObject.__init__(self, quarterwidget) #QObject.__init__(quarterwidget) self._quarterwidget = quarterwidget self._rendermanager = self._quarterwidget.getSoRenderManager() self.contextmenu = QMenu() self.functionsmenu = QMenu("Functions") self.rendermenu = QMenu("Render Mode") self.stereomenu = QMenu("Stereo Mode") self.transparencymenu = QMenu("Transparency Type") self.functionsgroup = QActionGroup(self) self.stereomodegroup = QActionGroup(self) self.rendermodegroup = QActionGroup(self) self.transparencytypegroup = QActionGroup(self) self.rendermodes = [] self.rendermodes.append((SoRenderManager.AS_IS, "as is")) self.rendermodes.append((SoRenderManager.WIREFRAME, "wireframe")) self.rendermodes.append( (SoRenderManager.WIREFRAME_OVERLAY, "wireframe overlay")) self.rendermodes.append((SoRenderManager.POINTS, "points")) self.rendermodes.append((SoRenderManager.HIDDEN_LINE, "hidden line")) self.rendermodes.append((SoRenderManager.BOUNDING_BOX, "bounding box")) self.stereomodes = [] self.stereomodes.append((SoRenderManager.MONO, "mono")) self.stereomodes.append((SoRenderManager.ANAGLYPH, "anaglyph")) self.stereomodes.append((SoRenderManager.QUAD_BUFFER, "quad buffer")) self.stereomodes.append( (SoRenderManager.INTERLEAVED_ROWS, "interleaved rows")) self.stereomodes.append( (SoRenderManager.INTERLEAVED_COLUMNS, "interleaved columns")) self.transparencytypes = [] self.transparencytypes.append((SoGLRenderAction.NONE, "none")) self.transparencytypes.append( (SoGLRenderAction.SCREEN_DOOR, "screen door")) self.transparencytypes.append((SoGLRenderAction.ADD, "add")) self.transparencytypes.append( (SoGLRenderAction.DELAYED_ADD, "delayed add")) self.transparencytypes.append( (SoGLRenderAction.SORTED_OBJECT_ADD, "sorted object add")) self.transparencytypes.append((SoGLRenderAction.BLEND, "blend")) self.transparencytypes.append( (SoGLRenderAction.DELAYED_BLEND, "delayed blend")) self.transparencytypes.append( (SoGLRenderAction.SORTED_OBJECT_BLEND, "sorted object blend")) self.transparencytypes.append( (SoGLRenderAction.SORTED_OBJECT_SORTED_TRIANGLE_ADD, "sorted object sorted triangle add")) self.transparencytypes.append( (SoGLRenderAction.SORTED_OBJECT_SORTED_TRIANGLE_BLEND, "sorted object sorted triangle blend")) self.transparencytypes.append( (SoGLRenderAction.SORTED_LAYERS_BLEND, "sorted layers blend")) self.rendermodeactions = [] for first, second in self.rendermodes: action = QAction(second, self) action.setCheckable(True) action.setChecked(self._rendermanager.getRenderMode() == first) action.setData(QVariant(first)) self.rendermodeactions.append(action) self.rendermodegroup.addAction(action) self.rendermenu.addAction(action) self.stereomodeactions = [] for first, second in self.stereomodes: action = QAction(second, self) action.setCheckable(True) action.setChecked(self._rendermanager.getStereoMode() == first) action.setData(QVariant(first)) self.stereomodeactions.append(action) self.stereomodegroup.addAction(action) self.stereomenu.addAction(action) self.transparencytypeactions = [] for first, second in self.transparencytypes: action = QAction(second, self) action.setCheckable(True) action.setChecked(self._rendermanager.getGLRenderAction(). getTransparencyType() == first) action.setData(QVariant(first)) self.transparencytypeactions.append(action) self.transparencytypegroup.addAction(action) self.transparencymenu.addAction(action) viewall = QAction("View All", self) seek = QAction("Seek", self) self.functionsmenu.addAction(viewall) self.functionsmenu.addAction(seek) self.connect(seek, QtCore.SIGNAL("triggered(bool)"), self.seek) self.connect(viewall, QtCore.SIGNAL("triggered(bool)"), self.viewAll) self.connect(self.rendermodegroup, QtCore.SIGNAL("triggered(QAction *)"), self.changeRenderMode) self.connect(self.stereomodegroup, QtCore.SIGNAL("triggered(QAction *)"), self.changeStereoMode) self.connect(self.transparencytypegroup, QtCore.SIGNAL("triggered(QAction *)"), self.changeTransparencyType) self.contextmenu.addMenu(self.functionsmenu) self.contextmenu.addMenu(self.rendermenu) self.contextmenu.addMenu(self.stereomenu) self.contextmenu.addMenu(self.transparencymenu)
def load_menus(self, profile=None, schema=None): """ Load menus in the main windows qgis bar """ if not schema: schema = self.combo_schema.currentText() if not profile: profile = self.combo_profile.currentText() # remove previous menus for menu in self.uiparent.menus: self.uiparent.iface.mainWindow().menuBar().removeAction( menu.menuAction()) with self.transaction(): cur = self.connection.cursor() select = """ select name, profile, model_index, datasource_uri from {}.{} where profile = '{}' """.format(schema, self.table, profile) cur.execute(select) rows = cur.fetchall() # item accessor ex: '0-menu/0-submenu/1-item/' menudict = {} # reference to parent item parent = '' # reference to qgis main menu bar menubar = self.uiparent.iface.mainWindow().menuBar() for name, profile, model_index, datasource_uri in self.sortby_modelindex( rows): uri_struct = QgsMimeDataUtils.Uri(datasource_uri) indexes = json.loads(model_index) # root menu parent = '{}-{}/'.format(indexes[0][0], indexes[0][1]) if parent not in menudict: menu = QMenu(self.uiparent.iface.mainWindow()) self.uiparent.menus.append(menu) menu.setObjectName(indexes[0][1]) menu.setTitle(indexes[0][1]) menubar.insertMenu( self.uiparent.iface.firstRightStandardMenu().menuAction(), menu) menudict[parent] = menu else: # menu already there menu = menudict[parent] for idx, subname in indexes[1:-1]: # intermediate submenus parent += '{}-{}/'.format(idx, subname) if parent not in menudict: submenu = menu.addMenu(subname) submenu.setObjectName(subname) submenu.setTitle(subname) menu = submenu # store it for later use menudict[parent] = menu continue # already treated menu = menudict[parent] # last item = layer layer = QAction(name, self.uiparent.iface.mainWindow()) if uri_struct.providerKey in ICON_MAPPER: layer.setIcon(QIcon(ICON_MAPPER[uri_struct.providerKey])) if uri_struct.providerKey == 'postgres': # set tooltip to postgres comment comment = self.get_table_comment(uri_struct.uri) layer.setStatusTip(comment) layer.setToolTip(comment) layer.setData(uri_struct.uri) layer.setWhatsThis(uri_struct.providerKey) layer.triggered.connect(self.layer_handler[uri_struct.layerType]) menu.addAction(layer)
def createFormButtons(self, projectlayers): """ Create buttons for each form that is definded """ # Remove all the old buttons for action in self.actions: self.actionGroup.removeAction(action) self.toolbar.removeAction(action) self.edittool.layers = [] self.movetool.layers = [] for layer in projectlayers: try: qgslayer = QgsMapLayerRegistry.instance().mapLayersByName(layer.name)[0] if qgslayer.type() == QgsMapLayer.RasterLayer: utils.log("We can't support raster layers for data entry") continue layer.QGISLayer = qgslayer except KeyError: utils.log("Layer not found in project") continue if 'capture' in layer.capabilities: text = layer.icontext try: tool = layer.getMaptool(self.iface.mapCanvas()) except NoMapToolConfigured: utils.log("No map tool configured") continue except ErrorInMapTool as error: self.messageBar.pushMessage("Error configuring map tool", error.message, level=QgsMessageBar.WARNING) continue # Hack until I fix it later if isinstance(tool, PointTool): add = functools.partial(self.addNewFeature, qgslayer) tool.geometryComplete.connect(add) else: tool.finished.connect(self.openForm) action = QAction(QIcon(layer.icon), text, self.mainwindow) action.setData(layer) action.setCheckable(True) action.toggled.connect(functools.partial(self.setMapTool, tool)) self.toolbar.insertAction(self.editingmodeaction, action) if not tool.isEditTool(): # Connect the GPS tools strip to the action pressed event. showgpstools = (functools.partial(self.extraaddtoolbar.showToolbar, action, None)) action.toggled.connect(showgpstools) self.actionGroup.addAction(action) self.actions.append(action) if 'edit' in layer.capabilities: # TODO Use snapping options from project radius = (QgsTolerance.toleranceInMapUnits( 10, qgslayer, self.iface.mapCanvas().mapRenderer(), QgsTolerance.Pixels)) self.edittool.addLayer(qgslayer) self.edittool.searchRadius = radius if 'move' in layer.capabilities: self.movetool.addLayer(qgslayer)
def device_discovery(self, devs): """Called when new devices have been added""" for menu in self._all_role_menus: role_menu = menu["rolemenu"] mux_menu = menu["muxmenu"] dev_group = QActionGroup(role_menu, exclusive=True) for d in devs: dev_node = QAction(d.name, role_menu, checkable=True, enabled=True) role_menu.addAction(dev_node) dev_group.addAction(dev_node) dev_node.toggled.connect(self._inputdevice_selected) map_node = None if d.supports_mapping: map_node = QMenu(" Input map", role_menu, enabled=False) map_group = QActionGroup(role_menu, exclusive=True) # Connect device node to map node for easy # enabling/disabling when selection changes and device # to easily enable it dev_node.setData((map_node, d)) for c in ConfigManager().get_list_of_configs(): node = QAction(c, map_node, checkable=True, enabled=True) node.toggled.connect(self._inputconfig_selected) map_node.addAction(node) # Connect all the map nodes back to the device # action node where we can access the raw device node.setData(dev_node) map_group.addAction(node) # If this device hasn't been found before, then # select the default mapping for it. if d not in self._available_devices: last_map = Config().get("device_config_mapping") if d.name in last_map and last_map[d.name] == c: node.setChecked(True) role_menu.addMenu(map_node) dev_node.setData((map_node, d, mux_menu)) # Update the list of what devices we found # to avoid selecting default mapping for all devices when # a new one is inserted self._available_devices = () for d in devs: self._available_devices += (d,) # Only enable MUX nodes if we have enough devies to cover # the roles for mux_node in self._all_mux_nodes: (mux, sub_nodes) = mux_node.data() if len(mux.supported_roles()) <= len(self._available_devices): mux_node.setEnabled(True) # TODO: Currently only supports selecting default mux if self._all_mux_nodes[0].isEnabled(): self._all_mux_nodes[0].setChecked(True) # If the previous length of the available devies was 0, then select # the default on. If that's not available then select the first # on in the list. # TODO: This will only work for the "Normal" mux so this will be # selected by default if Config().get("input_device") in [d.name for d in devs]: for dev_menu in self._all_role_menus[0]["rolemenu"].actions(): if dev_menu.text() == Config().get("input_device"): dev_menu.setChecked(True) else: # Select the first device in the first mux (will always be "Normal" # mux) self._all_role_menus[0]["rolemenu"].actions()[0].setChecked(True) logger.info("Select first device") self._update_input_device_footer()
def __init__(self, *args): super(MainUI, self).__init__(*args) self.setupUi(self) ###################################################### ### By lxrocks ### 'Skinny Progress Bar' tweak for Yosemite ### Tweak progress bar - artistic I am not - so pick your own colors !!! ### Only apply to Yosemite ###################################################### import platform if platform.system() == 'Darwin': (Version, junk, machine) = platform.mac_ver() logger.info( "This is a MAC - checking if we can apply Progress Bar Stylesheet for Yosemite Skinny Bars " ) yosemite = (10, 10, 0) tVersion = tuple(map(int, (Version.split(".")))) if tVersion >= yosemite: logger.info("Found Yosemite:") tcss = """ QProgressBar { border: 2px solid grey; border-radius: 5px; text-align: center; } QProgressBar::chunk { background-color: #05B8CC; } """ self.setStyleSheet(tcss) else: logger.info("Pre-Yosemite") ###################################################### self.cf = Crazyflie(ro_cache=sys.path[0] + "/cflib/cache", rw_cache=sys.path[1] + "/cache") cflib.crtp.init_drivers( enable_debug_driver=Config().get("enable_debug_driver")) zmq_params = ZMQParamAccess(self.cf) zmq_params.start() zmq_leds = ZMQLEDDriver(self.cf) zmq_leds.start() # Create the connection dialogue self.connectDialogue = ConnectDialogue() # Create and start the Input Reader self._statusbar_label = QLabel("No input-device found, insert one to" " fly.") self.statusBar().addWidget(self._statusbar_label) self.joystickReader = JoystickReader() self._active_device = "" #self.configGroup = QActionGroup(self._menu_mappings, exclusive=True) self._mux_group = QActionGroup(self._menu_inputdevice, exclusive=True) # TODO: Need to reload configs #ConfigManager().conf_needs_reload.add_callback(self._reload_configs) # Connections for the Connect Dialogue self.connectDialogue.requestConnectionSignal.connect(self.cf.open_link) self.cf.connection_failed.add_callback( self.connectionFailedSignal.emit) self.connectionFailedSignal.connect(self._connection_failed) self._input_device_error_signal.connect( self._display_input_device_error) self.joystickReader.device_error.add_callback( self._input_device_error_signal.emit) self._input_discovery_signal.connect(self.device_discovery) self.joystickReader.device_discovery.add_callback( self._input_discovery_signal.emit) # Connect UI signals self.menuItemConnect.triggered.connect(self._connect) self.logConfigAction.triggered.connect(self._show_connect_dialog) self.connectButton.clicked.connect(self._connect) self.quickConnectButton.clicked.connect(self._quick_connect) self.menuItemQuickConnect.triggered.connect(self._quick_connect) self.menuItemConfInputDevice.triggered.connect( self._show_input_device_config_dialog) self.menuItemExit.triggered.connect(self.closeAppRequest) self.batteryUpdatedSignal.connect(self._update_vbatt) self._menuitem_rescandevices.triggered.connect(self._rescan_devices) self._menuItem_openconfigfolder.triggered.connect( self._open_config_folder) self._auto_reconnect_enabled = Config().get("auto_reconnect") self.autoReconnectCheckBox.toggled.connect( self._auto_reconnect_changed) self.autoReconnectCheckBox.setChecked(Config().get("auto_reconnect")) self.joystickReader.input_updated.add_callback( self.cf.commander.send_setpoint) # Connection callbacks and signal wrappers for UI protection self.cf.connected.add_callback(self.connectionDoneSignal.emit) self.connectionDoneSignal.connect(self._connected) self.cf.disconnected.add_callback(self.disconnectedSignal.emit) self.disconnectedSignal.connect(lambda linkURI: self._update_ui_state( UIState.DISCONNECTED, linkURI)) self.cf.connection_lost.add_callback(self.connectionLostSignal.emit) self.connectionLostSignal.connect(self._connection_lost) self.cf.connection_requested.add_callback( self.connectionInitiatedSignal.emit) self.connectionInitiatedSignal.connect( lambda linkURI: self._update_ui_state(UIState.CONNECTING, linkURI)) self._log_error_signal.connect(self._logging_error) # Connect link quality feedback self.cf.link_quality_updated.add_callback(self.linkQualitySignal.emit) self.linkQualitySignal.connect( lambda percentage: self.linkQualityBar.setValue(percentage)) # Set UI state in disconnected buy default self._update_ui_state(UIState.DISCONNECTED) # Parse the log configuration files self.logConfigReader = LogConfigReader(self.cf) self._current_input_config = None self._active_config = None self._active_config = None self.inputConfig = None # Add things to helper so tabs can access it cfclient.ui.pluginhelper.cf = self.cf cfclient.ui.pluginhelper.inputDeviceReader = self.joystickReader cfclient.ui.pluginhelper.logConfigReader = self.logConfigReader self.logConfigDialogue = LogConfigDialogue(cfclient.ui.pluginhelper) self._bootloader_dialog = BootloaderDialog(cfclient.ui.pluginhelper) self._cf2config_dialog = Cf2ConfigDialog(cfclient.ui.pluginhelper) self._cf1config_dialog = Cf1ConfigDialog(cfclient.ui.pluginhelper) self.menuItemBootloader.triggered.connect(self._bootloader_dialog.show) self._about_dialog = AboutDialog(cfclient.ui.pluginhelper) self.menuItemAbout.triggered.connect(self._about_dialog.show) self._menu_cf2_config.triggered.connect(self._cf2config_dialog.show) self._menu_cf1_config.triggered.connect(self._cf1config_dialog.show) # Loading toolboxes (A bit of magic for a lot of automatic) self.toolboxes = [] self.toolboxesMenuItem.setMenu(QtGui.QMenu()) for t_class in cfclient.ui.toolboxes.toolboxes: toolbox = t_class(cfclient.ui.pluginhelper) dockToolbox = MyDockWidget(toolbox.getName()) dockToolbox.setWidget(toolbox) self.toolboxes += [ dockToolbox, ] # Add menu item for the toolbox item = QtGui.QAction(toolbox.getName(), self) item.setCheckable(True) item.triggered.connect(self.toggleToolbox) self.toolboxesMenuItem.menu().addAction(item) dockToolbox.closed.connect(lambda: self.toggleToolbox(False)) # Setup some introspection item.dockToolbox = dockToolbox item.menuItem = item dockToolbox.dockToolbox = dockToolbox dockToolbox.menuItem = item # Load and connect tabs self.tabsMenuItem.setMenu(QtGui.QMenu()) tabItems = {} self.loadedTabs = [] for tabClass in cfclient.ui.tabs.available: tab = tabClass(self.tabs, cfclient.ui.pluginhelper) item = QtGui.QAction(tab.getMenuName(), self) item.setCheckable(True) item.toggled.connect(tab.toggleVisibility) self.tabsMenuItem.menu().addAction(item) tabItems[tab.getTabName()] = item self.loadedTabs.append(tab) if not tab.enabled: item.setEnabled(False) # First instantiate all tabs and then open them in the correct order try: for tName in Config().get("open_tabs").split(","): t = tabItems[tName] if (t != None and t.isEnabled()): # Toggle though menu so it's also marked as open there t.toggle() except Exception as e: logger.warning("Exception while opening tabs [{}]".format(e)) # References to all the device sub-menus in the "Input device" menu self._all_role_menus = () # Used to filter what new devices to add default mapping to self._available_devices = () # Keep track of mux nodes so we can enable according to how many # devices we have self._all_mux_nodes = () # Check which Input muxes are available self._mux_group = QActionGroup(self._menu_inputdevice, exclusive=True) for m in self.joystickReader.available_mux(): node = QAction(m.name, self._menu_inputdevice, checkable=True, enabled=False) node.toggled.connect(self._mux_selected) self._mux_group.addAction(node) self._menu_inputdevice.addAction(node) self._all_mux_nodes += (node, ) mux_subnodes = () for name in m.supported_roles(): sub_node = QMenu(" {}".format(name), self._menu_inputdevice, enabled=False) self._menu_inputdevice.addMenu(sub_node) mux_subnodes += (sub_node, ) self._all_role_menus += ({ "muxmenu": node, "rolemenu": sub_node }, ) node.setData((m, mux_subnodes)) self._mapping_support = True
def makeUrlAction(text, url, toolTip='', parent=None): action = QAction(text + '...', parent) action.setData(QVariant(url)) action.setToolTip(toolTip) return action
def device_discovery(self, devs): """Called when new devices have been added""" for menu in self._all_role_menus: role_menu = menu["rolemenu"] mux_menu = menu["muxmenu"] dev_group = QActionGroup(role_menu, exclusive=True) for d in devs: dev_node = QAction(d.name, role_menu, checkable=True, enabled=True) role_menu.addAction(dev_node) dev_group.addAction(dev_node) dev_node.toggled.connect(self._inputdevice_selected) map_node = None if d.supports_mapping: map_node = QMenu(" Input map", role_menu, enabled=False) map_group = QActionGroup(role_menu, exclusive=True) # Connect device node to map node for easy # enabling/disabling when selection changes and device # to easily enable it dev_node.setData((map_node, d)) for c in ConfigManager().get_list_of_configs(): node = QAction(c, map_node, checkable=True, enabled=True) node.toggled.connect(self._inputconfig_selected) map_node.addAction(node) # Connect all the map nodes back to the device # action node where we can access the raw device node.setData(dev_node) map_group.addAction(node) # If this device hasn't been found before, then # select the default mapping for it. if d not in self._available_devices: last_map = Config().get("device_config_mapping") if last_map.has_key( d.name) and last_map[d.name] == c: node.setChecked(True) role_menu.addMenu(map_node) dev_node.setData((map_node, d, mux_menu)) # Update the list of what devices we found # to avoid selecting default mapping for all devices when # a new one is inserted self._available_devices = () for d in devs: self._available_devices += (d, ) # Only enable MUX nodes if we have enough devies to cover # the roles for mux_node in self._all_mux_nodes: (mux, sub_nodes) = mux_node.data().toPyObject() if len(mux.supported_roles()) <= len(self._available_devices): mux_node.setEnabled(True) # TODO: Currently only supports selecting default mux if self._all_mux_nodes[0].isEnabled(): self._all_mux_nodes[0].setChecked(True) # If the previous length of the available devies was 0, then select # the default on. If that's not available then select the first # on in the list. # TODO: This will only work for the "Normal" mux so this will be # selected by default if Config().get("input_device") in [d.name for d in devs]: for dev_menu in self._all_role_menus[0]["rolemenu"].actions(): if dev_menu.text() == Config().get("input_device"): dev_menu.setChecked(True) else: # Select the first device in the first mux (will always be "Normal" # mux) self._all_role_menus[0]["rolemenu"].actions()[0].setChecked(True) logger.info("Select first device") self._update_input_device_footer()
def load_audio_devices(self): settings = SIPSimpleSettings() action = QAction(u'System default', self.output_devices_group) action.setData(u'system_default') self.output_device_menu.addAction(action) self.output_device_menu.addSeparator() for device in SIPApplication.engine.output_devices: action = QAction(device, self.output_devices_group) action.setData(device) self.output_device_menu.addAction(action) action = QAction(u'None', self.output_devices_group) action.setData(None) self.output_device_menu.addAction(action) for action in self.output_devices_group.actions(): action.setCheckable(True) if settings.audio.output_device == action.data(): action.setChecked(True) action = QAction(u'System default', self.input_devices_group) action.setData(u'system_default') self.input_device_menu.addAction(action) self.input_device_menu.addSeparator() for device in SIPApplication.engine.input_devices: action = QAction(device, self.input_devices_group) action.setData(device) self.input_device_menu.addAction(action) action = QAction(u'None', self.input_devices_group) action.setData(None) self.input_device_menu.addAction(action) for action in self.input_devices_group.actions(): action.setCheckable(True) if settings.audio.input_device == action.data(): action.setChecked(True) action = QAction(u'System default', self.alert_devices_group) action.setData(u'system_default') self.alert_device_menu.addAction(action) self.alert_device_menu.addSeparator() for device in SIPApplication.engine.output_devices: action = QAction(device, self.alert_devices_group) action.setData(device) self.alert_device_menu.addAction(action) action = QAction(u'None', self.alert_devices_group) action.setData(None) self.alert_device_menu.addAction(action) for action in self.alert_devices_group.actions(): action.setCheckable(True) if settings.audio.alert_device == action.data(): action.setChecked(True)