def __view_addActions(self): """ Sets the View actions. """ self.__view.addAction(self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|addons.projectsExplorer|Add Project ...", slot=self.__view_addProjectAction__triggered)) self.__view.addAction(self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|addons.projectsExplorer|Remove Project", slot=self.__view_removeProjectAction__triggered)) separatorAction = QAction(self.__view) separatorAction.setSeparator(True) self.__view.addAction(separatorAction) self.__view.addAction(self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|addons.projectsExplorer|Add New File ...", slot=self.__view_addNewFileAction__triggered)) self.__view.addAction(self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|addons.projectsExplorer|Add New Directory ...", slot=self.__view_addNewDirectoryAction__triggered)) separatorAction = QAction(self.__view) separatorAction.setSeparator(True) self.__view.addAction(separatorAction) self.__view.addAction(self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|addons.projectsExplorer|Rename ...", slot=self.__view_renameAction__triggered)) # self.__view.addAction(self.__engine.actionsManager.registerAction( # "Actions|Umbra|Components|addons.projectsExplorer|Copy ...", # slot=self.__view_copyAction__triggered)) # self.__view.addAction(self.__engine.actionsManager.registerAction( # "Actions|Umbra|Components|addons.projectsExplorer|Move ...", # slot=self.__view_moveAction__triggered)) separatorAction = QAction(self.__view) separatorAction.setSeparator(True) self.__view.addAction(separatorAction) self.__view.addAction(self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|addons.projectsExplorer|Delete ...", slot=self.__view_deleteAction__triggered)) separatorAction = QAction(self.__view) separatorAction.setSeparator(True) self.__view.addAction(separatorAction) self.__view.addAction(self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|addons.projectsExplorer|Find In Files ...", slot=self.__view_findInFilesAction__triggered)) separatorAction = QAction(self.__view) separatorAction.setSeparator(True) self.__view.addAction(separatorAction) self.__view.addAction(self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|addons.projectsExplorer|Output Selected Path", slot=self.__view_outputSelectedPathAction__triggered))
def __addActions(self): """ This method sets Component actions. """ LOGGER.debug("> Adding '{0}' Component actions.".format(self.__class__.__name__)) if not self.__engine.parameters.databaseReadOnly: editIblSetsFilesAction = self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|core.iblSetsOutliner|Edit Ibl Set(s) File(s) ...", slot=self.__iblSetsOutliner_views_editIblSetsFilesAction__triggered) for view in self.__iblSetsOutliner.views: view.addAction(editIblSetsFilesAction) self.__inspector.Inspector_Overall_frame.addAction(self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|core.inspector|Edit Ibl Set File ...", slot=self.__inspector_editActiveIblSetFileAction__triggered)) self.__templatesOutliner.view.addAction(self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|core.templatesOutliner|Edit Template(s) File(s) ...", slot=self.__templatesOutliner_view_editTemplatesFilesAction__triggered)) else: LOGGER.info("{0} | Text editing capabilities deactivated by '{1}' command line parameter value!".format( self.__class__.__name__, "databaseReadOnly")) separatorAction = QAction(self.__componentsManagerUi.view) separatorAction.setSeparator(True) self.__componentsManagerUi.view.addAction(separatorAction) self.__componentsManagerUi.view.addAction(self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|factory.componentsManagerUi|Edit Component(s) ...", slot=self.__componentsManagerUi_view_editComponentsAction__triggered))
def configureToolBarActionsGroups(self): """ :return: """ sep = QAction(self) sep.setSeparator(True) # region Segmentation and Transformations actions segm_transf_actions = QActionGroup(self) segm_transf_actions_list = [ self.actionDetection, self.actionTwo_Dimensional_Graphs, self.actionDelete_Selected_Elements, self.actionDeselect_Elements, self.actionAddElement, self.actionParameter_Measurement, sep ] for act in segm_transf_actions_list: act.setActionGroup(segm_transf_actions) # endregion # add to the customizable sound lab toolbar first than the default actions # addActionGroup(actionGroup, name) self.toolBar.addActionGroup(segm_transf_actions, u"Segments and Parameters") # apply the common sound lab window toolbar actions SoundLabWindow.configureToolBarActionsGroups(self)
def registerDatabaseActions(self, mainWindow): Database.registerDatabaseActions(self, mainWindow) # add a separator separator = QAction(self) separator.setSeparator(True) mainWindow.registerAction(separator, self.tr("&Table")) action = QAction(self.tr("Run &Vacuum Analyze"), self) mainWindow.registerAction(action, self.tr("&Table"), self.runVacuumAnalyzeActionSlot)
def add_separator(self): "..." parent = self.iface.mainWindow() action = QAction(QIcon(), "separator", parent) action.setSeparator(True) self.iface.addPluginToDatabaseMenu(self.menu, action) self.separators.append(action) if self.toolbar is not None: self.toolbar.addAction(action) return action
def add_group_separator(self, add_to_menu=True, add_to_toolbar=True, parent=None): sep_action = QAction(parent) sep_action.setSeparator(True) if add_to_menu: self.iface.addPluginToMenu(self.menu, sep_action) if add_to_toolbar: self.toolbar.addAction(sep_action) self.actions.append(sep_action)
def addSeparator(self, context: Context, groupId: ItemId=ItemId()): """ Adds a separator to the end of the given group to the action container, which is enabled for a given context. The created separator action is returned as second item in the tuple. :param context: :param groupId: :return: tuple (created Command, separator reference) """ self.separatorIdCount += 1 separator = QAction(self) separator.setSeparator(True) sepId = self.itemID.withSuffix(".Separator.").withSuffix(self.separatorIdCount) command = ActionManager.registerAction(separator, sepId, context) self.addAction(command, groupId) return command, separator
def _create_action(self, action_name, icon_file, text, shortcuts): if action_name == "*separator*": action = QAction(self.window) action.setSeparator(True) else: if icon_file: action = QAction(QIcon(utils.resource_path(icon_file)), text, self.window) else: action = QAction(text, self.window) if shortcuts: sequences = [QKeySequence(s) for s in shortcuts] action.setShortcuts(sequences) if action_name.startswith("+"): action.setCheckable(True) if action_name.startswith("++"): action.setChecked(True) return action
def __addActions(self): """ This method sets Component actions. """ LOGGER.debug("> Adding '{0}' Component actions.".format(self.__class__.__name__)) viewIblSetsBackgroundImagesAction = self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|core.iblSetsOutliner|View Background Image ...", slot=self.__iblSetsOutliner_views_viewIblSetsBackgroundImagesAction__triggered) viewIblSetsLightingImagesAction = self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|core.iblSetsOutliner|View Lighting Image ...", slot=self.__iblSetsOutliner_views_viewIblSetsLightingImagesAction__triggered) viewIblSetsReflectionImagesAction = self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|core.iblSetsOutliner|View Reflection Image ...", slot=self.__iblSetsOutliner_views_viewIblSetsReflectionImagesAction__triggered) viewIblSetsPlatesAction = self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|core.iblSetsOutliner|View Plate(s) ...", slot=self.__iblSetsOutliner_views_viewIblSetsPlatesAction__triggered) for view in self.__iblSetsOutliner.views: separatorAction = QAction(view) separatorAction.setSeparator(True) for action in (separatorAction, viewIblSetsBackgroundImagesAction, viewIblSetsLightingImagesAction, viewIblSetsReflectionImagesAction, viewIblSetsPlatesAction): view.addAction(action) separatorAction = QAction(self.__inspector.Inspector_Overall_frame) separatorAction.setSeparator(True) self.__inspector.Inspector_Overall_frame.addAction(separatorAction) self.__inspector.Inspector_Overall_frame.addAction(self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|core.inspector|View Background Image ...", slot=self.__Inspector_Overall_frame_viewActiveIblSetBackgroundImageAction__triggered)) self.__inspector.Inspector_Overall_frame.addAction(self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|core.inspector|View Lighting Image ...", slot=self.__Inspector_Overall_frame_viewActiveIblSetLightingImageAction__triggered)) self.__inspector.Inspector_Overall_frame.addAction(self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|core.inspector|View Reflection Image ...", slot=self.__Inspector_Overall_frame_viewActiveIblSetReflectionImageAction__triggered)) self.__inspector.Inspector_Overall_frame.addAction(self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|core.inspector|View Plate(s) ...", slot=self.__Inspector_Overall_frame_viewActiveIblSetPlatesAction__triggered))
def _create_action(self, action_name, icon_file, text, shortcuts): if action_name == '*separator*': action = QAction(self.window) action.setSeparator(True) else: if icon_file: action = QAction(QIcon(utils.resource_path(icon_file)), text, self.window) else: action = QAction(text, self.window) if shortcuts: sequences = [QKeySequence(s) for s in shortcuts] action.setShortcuts(sequences) if action_name.startswith('+'): action.setCheckable(True) if action_name.startswith('++'): action.setChecked(True) return action
def __view_addActions(self): """ Sets the View actions. """ self.__view.addAction(self.__container.engine.actionsManager.registerAction( "Actions|Umbra|Components|factory.scriptEditor|Search In Files|Replace All", slot=self.__view_replaceAllAction__triggered)) self.__view.addAction(self.__container.engine.actionsManager.registerAction( "Actions|Umbra|Components|factory.scriptEditor|Search In Files|Replace Selected", slot=self.__view_replaceSelectedAction__triggered)) separatorAction = QAction(self.__view) separatorAction.setSeparator(True) self.__view.addAction(separatorAction) self.__view.addAction(self.__container.engine.actionsManager.registerAction( "Actions|Umbra|Components|factory.scriptEditor|Search In Files|Save All", slot=self.__view_saveAllAction__triggered)) self.__view.addAction(self.__container.engine.actionsManager.registerAction( "Actions|Umbra|Components|factory.scriptEditor|Search In Files|Save Selected", slot=self.__view_saveSelectedAction__triggered))
def __addActions(self): """ Sets Component actions. """ LOGGER.debug("> Adding '{0}' Component actions.".format( self.__class__.__name__)) if not self.__engine.parameters.databaseReadOnly: editIblSetsFilesAction = self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|core.iblSetsOutliner|Edit Ibl Set(s) File(s) ...", slot=self. __iblSetsOutliner_views_editIblSetsFilesAction__triggered) for view in self.__iblSetsOutliner.views: view.addAction(editIblSetsFilesAction) self.__inspector.Inspector_Overall_frame.addAction( self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|core.inspector|Edit Ibl Set File ...", slot=self.__inspector_editActiveIblSetFileAction__triggered )) self.__templatesOutliner.view.addAction( self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|core.templatesOutliner|Edit Template(s) File(s) ...", slot=self. __templatesOutliner_view_editTemplatesFilesAction__triggered )) else: LOGGER.info( "{0} | Text editing capabilities deactivated by '{1}' command line parameter value!" .format(self.__class__.__name__, "databaseReadOnly")) separatorAction = QAction(self.__componentsManagerUi.view) separatorAction.setSeparator(True) self.__componentsManagerUi.view.addAction(separatorAction) self.__componentsManagerUi.view.addAction( self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|factory.componentsManagerUi|Edit Component(s) ...", slot=self. __componentsManagerUi_view_editComponentsAction__triggered))
def _create_actions(self): tree = self.layerTree sep = QAction("Style", tree) sep.setSeparator(True) tree.addAction(sep) self._actions["label"] = ChangeLabelAction(self) self._actions["color"] = ChangeColorAction(self) self._actions["size"] = ChangeSizeAction(self) self._actions["marker"] = ChangeMarkerAction(self) sep = QAction("", tree) sep.setSeparator(True) tree.addAction(sep) self._actions["load"] = LoadAction(self) self._actions["save"] = SaveAction(self) self._actions["copy"] = CopyAction(self) self._actions["paste"] = PasteAction(self) self._actions["paste_special"] = PasteSpecialAction(self) self._actions["new"] = NewAction(self) self._actions["clear"] = ClearAction(self) self._actions["duplicate"] = DuplicateAction(self) self._actions["delete"] = DeleteAction(self) # combination actions separator = QAction("Subset Combination", tree) separator.setSeparator(True) tree.addAction(separator) self._actions["or"] = OrCombiner(self) self._actions["and"] = AndCombiner(self) self._actions["xor"] = XorCombiner(self) self._actions["invert"] = Inverter(self) # new component definer separator = QAction("sep", tree) separator.setSeparator(True) tree.addAction(separator) a = _act("Define new component", self, tip="Define a new component using python expressions") tree.addAction(a) a.triggered.connect(self._create_component) self._actions["new_component"] = a # right click pulls up menu tree.setContextMenuPolicy(Qt.ActionsContextMenu)
def _onCurrentDocumentChanged(self, old, new): """Change current directory, if current file changed """ if(new and new.filePath() is not None and os.path.exists(os.path.dirname(new.filePath()))): try: os.chdir(os.path.dirname(new.filePath())) except OSError as ex: # directory might be deleted print >> sys.stderr, 'Failed to change directory:', str(ex) if old is not None: for path, name in self._QUTEPART_ACTIONS: core.actionManager().removeAction(path) if new is not None: for path, name in self._QUTEPART_ACTIONS: if name is not None: core.actionManager().addAction(path, getattr(new.qutepart, name)) else: act = QAction(self) act.setSeparator(True) core.actionManager().addAction(path, act)
def __view_addActions(self): """ Sets the **Components_Manager_Ui_treeView** actions. """ self.Components_Manager_Ui_treeView.addAction(self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|factory.ComponentsManagerUi|Activate Component(s)", slot=self.__view_activateComponentsAction__triggered)) self.Components_Manager_Ui_treeView.addAction(self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|factory.ComponentsManagerUi|Deactivate Component(s)", slot=self.__view_deactivateComponentsAction__triggered)) separatorAction = QAction(self.Components_Manager_Ui_treeView) separatorAction.setSeparator(True) self.Components_Manager_Ui_treeView.addAction(separatorAction) self.Components_Manager_Ui_treeView.addAction(self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|factory.ComponentsManagerUi|Reload Component(s)", slot=self.__view_reloadComponentsAction__triggered)) separatorAction = QAction(self.Components_Manager_Ui_treeView) separatorAction.setSeparator(True) self.Components_Manager_Ui_treeView.addAction(separatorAction)
class QtAction(QtToolkitObject, ProxyAction): """ A Qt implementation of an Enaml ProxyAction. """ #: A reference to the widget created by the proxy. widget = Typed(QAction) #: Cyclic notification guard. This a bitfield of multiple guards. _guard = Int(0) # FIXME Currently, the checked state of the action is lost when # switching from checkable to non-checkable and back again. #-------------------------------------------------------------------------- # Initialization API #-------------------------------------------------------------------------- def create_widget(self): """ Create the underlying QAction object. """ self.widget = QAction(self.parent_widget()) def init_widget(self): """ Initialize the underlying control. """ super(QtAction, self).init_widget() d = self.declaration if d.text: self.set_text(d.text) if d.tool_tip: self.set_tool_tip(d.tool_tip) if d.status_tip: self.set_status_tip(d.status_tip) if d.icon: self.set_icon(d.icon) self.set_checkable(d.checkable) self.set_checked(d.checked) self.set_enabled(d.enabled) self.set_visible(d.visible) self.set_separator(d.separator) widget = self.widget widget.triggered.connect(self.on_triggered) widget.toggled.connect(self.on_toggled) #-------------------------------------------------------------------------- # Signal Handlers #-------------------------------------------------------------------------- def on_triggered(self, checked): """ The signal handler for the 'triggered' signal. """ if not self._guard & CHECKED_GUARD: self.declaration.checked = checked self.declaration.triggered(checked) def on_toggled(self, checked): """ The signal handler for the 'toggled' signal. """ if not self._guard & CHECKED_GUARD: self.declaration.checked = checked self.declaration.toggled(checked) #-------------------------------------------------------------------------- # ProxyAction API #-------------------------------------------------------------------------- def set_text(self, text): """ Set the text on the underlying control. """ widget = self.widget widget.setText(text) parts = text.split('\t') if len(parts) > 1: shortcut = QKeySequence(parts[-1]) widget.setShortcut(shortcut) def set_tool_tip(self, tool_tip): """ Set the tool tip on the underlying control. """ self.widget.setToolTip(tool_tip) def set_status_tip(self, status_tip): """ Set the status tip on the underyling control. """ self.widget.setStatusTip(status_tip) def set_icon(self, icon): """ Set the icon for the action. """ if icon: qicon = get_cached_qicon(icon) else: qicon = QIcon() self.widget.setIcon(qicon) def set_checkable(self, checkable): """ Set the checkable state on the underlying control. """ self.widget.setCheckable(checkable) def set_checked(self, checked): """ Set the checked state on the underlying control. """ self._guard |= CHECKED_GUARD try: self.widget.setChecked(checked) finally: self._guard &= ~CHECKED_GUARD def set_enabled(self, enabled): """ Set the enabled state on the underlying control. """ self.widget.setEnabled(enabled) def set_visible(self, visible): """ Set the visible state on the underlying control. """ self.widget.setVisible(visible) def set_separator(self, separator): """ Set the separator state on the underlying control. """ self.widget.setSeparator(separator)
def separator(parent=None): s = QAction(parent) s.setSeparator(True) return s
def separator(parent): separator = QAction(parent) separator.setSeparator(True) return separator
def action(self): separatorAct = QAction(self.composerView()) separatorAct.setSeparator(True) return separatorAct
def separator(): sep = QAction(None) sep.setSeparator(True) return sep
def __addActions(self): """ This method sets Component actions. """ LOGGER.debug("> Adding '{0}' Component actions.".format( self.__class__.__name__)) viewIblSetsBackgroundImagesAction = self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|core.iblSetsOutliner|View Background Image ...", slot=self. __iblSetsOutliner_views_viewIblSetsBackgroundImagesAction__triggered ) viewIblSetsLightingImagesAction = self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|core.iblSetsOutliner|View Lighting Image ...", slot=self. __iblSetsOutliner_views_viewIblSetsLightingImagesAction__triggered) viewIblSetsReflectionImagesAction = self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|core.iblSetsOutliner|View Reflection Image ...", slot=self. __iblSetsOutliner_views_viewIblSetsReflectionImagesAction__triggered ) viewIblSetsPlatesAction = self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|core.iblSetsOutliner|View Plate(s) ...", slot=self. __iblSetsOutliner_views_viewIblSetsPlatesAction__triggered) for view in self.__iblSetsOutliner.views: separatorAction = QAction(view) separatorAction.setSeparator(True) for action in (separatorAction, viewIblSetsBackgroundImagesAction, viewIblSetsLightingImagesAction, viewIblSetsReflectionImagesAction, viewIblSetsPlatesAction): view.addAction(action) separatorAction = QAction(self.__inspector.Inspector_Overall_frame) separatorAction.setSeparator(True) self.__inspector.Inspector_Overall_frame.addAction(separatorAction) self.__inspector.Inspector_Overall_frame.addAction( self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|core.inspector|View Background Image ...", slot=self. __Inspector_Overall_frame_viewActiveIblSetBackgroundImageAction__triggered )) self.__inspector.Inspector_Overall_frame.addAction( self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|core.inspector|View Lighting Image ...", slot=self. __Inspector_Overall_frame_viewActiveIblSetLightingImageAction__triggered )) self.__inspector.Inspector_Overall_frame.addAction( self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|core.inspector|View Reflection Image ...", slot=self. __Inspector_Overall_frame_viewActiveIblSetReflectionImageAction__triggered )) self.__inspector.Inspector_Overall_frame.addAction( self.__engine.actionsManager.registerAction( "Actions|Umbra|Components|core.inspector|View Plate(s) ...", slot=self. __Inspector_Overall_frame_viewActiveIblSetPlatesAction__triggered ))
class SpreadSheet(QMainWindow): dateFormats = ["dd/M/yyyy", "yyyy/M/dd", "dd.MM.yyyy"] currentDateFormat = dateFormats[0] def __init__(self, rows, cols, parent = None): super(SpreadSheet, self).__init__(parent) self.toolBar = QToolBar() self.addToolBar(self.toolBar) self.formulaInput = QLineEdit() self.cellLabel = QLabel(self.toolBar) self.cellLabel.setMinimumSize(80, 0) self.toolBar.addWidget(self.cellLabel) self.toolBar.addWidget(self.formulaInput) self.table = QTableWidget(rows, cols, self) for c in range(cols): character = chr(ord('A') + c) self.table.setHorizontalHeaderItem(c, QTableWidgetItem(character)) self.table.setItemPrototype(self.table.item(rows - 1, cols - 1)) self.table.setItemDelegate(SpreadSheetDelegate(self)) self.createActions() self.updateColor(0) self.setupMenuBar() self.setupContents() self.setupContextMenu() self.setCentralWidget(self.table) self.statusBar() self.table.currentItemChanged.connect(self.updateStatus) self.table.currentItemChanged.connect(self.updateColor) self.table.currentItemChanged.connect(self.updateLineEdit) self.table.itemChanged.connect(self.updateStatus) self.formulaInput.returnPressed.connect(self.returnPressed) self.table.itemChanged.connect(self.updateLineEdit) self.setWindowTitle("Spreadsheet") def createActions(self): self.cell_sumAction = QAction("Sum", self) self.cell_sumAction.triggered.connect(self.actionSum) self.cell_addAction = QAction("&Add", self) self.cell_addAction.setShortcut(Qt.CTRL | Qt.Key_Plus) self.cell_addAction.triggered.connect(self.actionAdd) self.cell_subAction = QAction("&Subtract", self) self.cell_subAction.setShortcut(Qt.CTRL | Qt.Key_Minus) self.cell_subAction.triggered.connect(self.actionSubtract) self.cell_mulAction = QAction("&Multiply", self) self.cell_mulAction.setShortcut(Qt.CTRL | Qt.Key_multiply) self.cell_mulAction.triggered.connect(self.actionMultiply) self.cell_divAction = QAction("&Divide", self) self.cell_divAction.setShortcut(Qt.CTRL | Qt.Key_division) self.cell_divAction.triggered.connect(self.actionDivide) self.fontAction = QAction("Font...", self) self.fontAction.setShortcut(Qt.CTRL | Qt.Key_F) self.fontAction.triggered.connect(self.selectFont) self.colorAction = QAction(QIcon(QPixmap(16, 16)), "Background &Color...", self) self.colorAction.triggered.connect(self.selectColor) self.clearAction = QAction("Clear", self) self.clearAction.setShortcut(Qt.Key_Delete) self.clearAction.triggered.connect(self.clear) self.aboutSpreadSheet = QAction("About Spreadsheet", self) self.aboutSpreadSheet.triggered.connect(self.showAbout) self.exitAction = QAction("E&xit", self) self.exitAction.setShortcut(QKeySequence.Quit) self.exitAction.triggered.connect(QApplication.instance().quit) self.printAction = QAction("&Print", self) self.printAction.setShortcut(QKeySequence.Print) self.printAction.triggered.connect(self.print_) self.firstSeparator = QAction(self) self.firstSeparator.setSeparator(True) self.secondSeparator = QAction(self) self.secondSeparator.setSeparator(True) def setupMenuBar(self): self.fileMenu = self.menuBar().addMenu("&File") self.dateFormatMenu = self.fileMenu.addMenu("&Date format") self.dateFormatGroup = QActionGroup(self) for f in self.dateFormats: action = QAction(f, self, checkable=True, triggered=self.changeDateFormat) self.dateFormatGroup.addAction(action) self.dateFormatMenu.addAction(action) if f == self.currentDateFormat: action.setChecked(True) self.fileMenu.addAction(self.printAction) self.fileMenu.addAction(self.exitAction) self.cellMenu = self.menuBar().addMenu("&Cell") self.cellMenu.addAction(self.cell_addAction) self.cellMenu.addAction(self.cell_subAction) self.cellMenu.addAction(self.cell_mulAction) self.cellMenu.addAction(self.cell_divAction) self.cellMenu.addAction(self.cell_sumAction) self.cellMenu.addSeparator() self.cellMenu.addAction(self.colorAction) self.cellMenu.addAction(self.fontAction) self.menuBar().addSeparator() self.aboutMenu = self.menuBar().addMenu("&Help") self.aboutMenu.addAction(self.aboutSpreadSheet) def changeDateFormat(self): action = self.sender() oldFormat = self.currentDateFormat newFormat = self.currentDateFormat = action.text() for row in range(self.table.rowCount()): item = self.table.item(row, 1) date = QDate.fromString(item.text(), oldFormat) item.setText(date.toString(newFormat)) def updateStatus(self, item): if item and item == self.table.currentItem(): self.statusBar().showMessage(item.data(Qt.StatusTipRole).toString(), 1000) self.cellLabel.setText("Cell: (%s)" % encode_pos(self.table.row(item), self.table.column(item))) def updateColor(self, item): pixmap = QPixmap(16, 16) color = QColor() if item: color = item.backgroundColor() if not color.isValid(): color = self.palette().base().color() painter = QPainter(pixmap) painter.fillRect(0, 0, 16, 16, color) lighter = color.lighter() painter.setPen(lighter) # light frame painter.drawPolyline(QPoint(0, 15), QPoint(0, 0), QPoint(15, 0)) painter.setPen(color.darker()) # dark frame painter.drawPolyline(QPoint(1, 15), QPoint(15, 15), QPoint(15, 1)) painter.end() self.colorAction.setIcon(QIcon(pixmap)) def updateLineEdit(self, item): if item != self.table.currentItem(): return if item: self.formulaInput.setText(item.data(Qt.EditRole).toString()) else: self.formulaInput.clear() def returnPressed(self): text = self.formulaInput.text() row = self.table.currentRow() col = self.table.currentColumn() item = self.table.item(row, col) if not item: self.table.setItem(row, col, SpreadSheetItem(text)) else: item.setData(Qt.EditRole, text) self.table.viewport().update() def selectColor(self): item = self.table.currentItem() color = item and QColor(item.background()) or self.table.palette().base().color() color = QColorDialog.getColor(color, self) if not color.isValid(): return selected = self.table.selectedItems() if not selected: return for i in selected: i and i.setBackground(color) self.updateColor(self.table.currentItem()) def selectFont(self): selected = self.table.selectedItems() if not selected: return font, ok = QFontDialog.getFont(self.font(), self) if not ok: return for i in selected: i and i.setFont(font) def runInputDialog(self, title, c1Text, c2Text, opText, outText, cell1, cell2, outCell): rows = [] cols = [] for r in range(self.table.rowCount()): rows.append(str(r + 1)) for c in range(self.table.columnCount()): cols.append(chr(ord('A') + c)) addDialog = QDialog(self) addDialog.setWindowTitle(title) group = QGroupBox(title, addDialog) group.setMinimumSize(250, 100) cell1Label = QLabel(c1Text, group) cell1RowInput = QComboBox(group) c1Row, c1Col = decode_pos(cell1) cell1RowInput.addItems(rows) cell1RowInput.setCurrentIndex(c1Row) cell1ColInput = QComboBox(group) cell1ColInput.addItems(cols) cell1ColInput.setCurrentIndex(c1Col) operatorLabel = QLabel(opText, group) operatorLabel.setAlignment(Qt.AlignHCenter) cell2Label = QLabel(c2Text, group) cell2RowInput = QComboBox(group) c2Row, c2Col = decode_pos(cell2) cell2RowInput.addItems(rows) cell2RowInput.setCurrentIndex(c2Row) cell2ColInput = QComboBox(group) cell2ColInput.addItems(cols) cell2ColInput.setCurrentIndex(c2Col) equalsLabel = QLabel("=", group) equalsLabel.setAlignment(Qt.AlignHCenter) outLabel = QLabel(outText, group) outRowInput = QComboBox(group) outRow, outCol = decode_pos(outCell) outRowInput.addItems(rows) outRowInput.setCurrentIndex(outRow) outColInput = QComboBox(group) outColInput.addItems(cols) outColInput.setCurrentIndex(outCol) cancelButton = QPushButton("Cancel", addDialog) cancelButton.clicked.connect(addDialog.reject) okButton = QPushButton("OK", addDialog) okButton.setDefault(True) okButton.clicked.connect(addDialog.accept) buttonsLayout = QHBoxLayout() buttonsLayout.addStretch(1) buttonsLayout.addWidget(okButton) buttonsLayout.addSpacing(10) buttonsLayout.addWidget(cancelButton) dialogLayout = QVBoxLayout(addDialog) dialogLayout.addWidget(group) dialogLayout.addStretch(1) dialogLayout.addItem(buttonsLayout) cell1Layout = QHBoxLayout() cell1Layout.addWidget(cell1Label) cell1Layout.addSpacing(10) cell1Layout.addWidget(cell1ColInput) cell1Layout.addSpacing(10) cell1Layout.addWidget(cell1RowInput) cell2Layout = QHBoxLayout() cell2Layout.addWidget(cell2Label) cell2Layout.addSpacing(10) cell2Layout.addWidget(cell2ColInput) cell2Layout.addSpacing(10) cell2Layout.addWidget(cell2RowInput) outLayout = QHBoxLayout() outLayout.addWidget(outLabel) outLayout.addSpacing(10) outLayout.addWidget(outColInput) outLayout.addSpacing(10) outLayout.addWidget(outRowInput) vLayout = QVBoxLayout(group) vLayout.addItem(cell1Layout) vLayout.addWidget(operatorLabel) vLayout.addItem(cell2Layout) vLayout.addWidget(equalsLabel) vLayout.addStretch(1) vLayout.addItem(outLayout) if addDialog.exec_(): cell1 = cell1ColInput.currentText() + cell1RowInput.currentText() cell2 = cell2ColInput.currentText() + cell2RowInput.currentText() outCell = outColInput.currentText() + outRowInput.currentText() return True, cell1, cell2, outCell return False, None, None, None def actionSum(self): row_first = 0 row_last = 0 row_cur = 0 col_first = 0 col_last = 0 col_cur = 0 selected = self.table.selectedItems() if selected: first = selected[0] last = selected[-1] row_first = self.table.row(first) row_last = self.table.row(last) col_first = self.table.column(first) col_last = self.table.column(last) current = self.table.currentItem() if current: row_cur = self.table.row(current) col_cur = self.table.column(current) cell1 = encode_pos(row_first, col_first) cell2 = encode_pos(row_last, col_last) out = encode_pos(row_cur, col_cur) ok, cell1, cell2, out = self.runInputDialog("Sum cells", "First cell:", "Last cell:", u"\N{GREEK CAPITAL LETTER SIGMA}", "Output to:", cell1, cell2, out) if ok: row, col = decode_pos(out) self.table.item(row, col).setText("sum %s %s" % (cell1, cell2)) def actionMath_helper(self, title, op): cell1 = "C1" cell2 = "C2" out = "C3" current = self.table.currentItem() if current: out = encode_pos(self.table.currentRow(), self.table.currentColumn()) ok, cell1, cell2, out = self.runInputDialog(title, "Cell 1", "Cell 2", op, "Output to:", cell1, cell2, out) if ok: row, col = decode_pos(out) self.table.item(row, col).setText("%s %s %s" % (op, cell1, cell2)) def actionAdd(self): self.actionMath_helper("Addition", "+") def actionSubtract(self): self.actionMath_helper("Subtraction", "-") def actionMultiply(self): self.actionMath_helper("Multiplication", "*") def actionDivide(self): self.actionMath_helper("Division", "/") def clear(self): for i in self.table.selectedItems(): i.setText("") def setupContextMenu(self): self.addAction(self.cell_addAction) self.addAction(self.cell_subAction) self.addAction(self.cell_mulAction) self.addAction(self.cell_divAction) self.addAction(self.cell_sumAction) self.addAction(self.firstSeparator) self.addAction(self.colorAction) self.addAction(self.fontAction) self.addAction(self.secondSeparator) self.addAction(self.clearAction) self.setContextMenuPolicy(Qt.ActionsContextMenu) def setupContents(self): titleBackground = QColor(Qt.lightGray) titleFont = self.table.font() titleFont.setBold(True) # column 0 self.table.setItem(0, 0, SpreadSheetItem("Item")) self.table.item(0, 0).setBackground(titleBackground) self.table.item(0, 0).setToolTip("This column shows the purchased item/service") self.table.item(0, 0).setFont(titleFont) self.table.setItem(1, 0, SpreadSheetItem("AirportBus")) self.table.setItem(2, 0, SpreadSheetItem("Flight (Munich)")) self.table.setItem(3, 0, SpreadSheetItem("Lunch")) self.table.setItem(4, 0, SpreadSheetItem("Flight (LA)")) self.table.setItem(5, 0, SpreadSheetItem("Taxi")) self.table.setItem(6, 0, SpreadSheetItem("Dinner")) self.table.setItem(7, 0, SpreadSheetItem("Hotel")) self.table.setItem(8, 0, SpreadSheetItem("Flight (Oslo)")) self.table.setItem(9, 0, SpreadSheetItem("Total:")) self.table.item(9, 0).setFont(titleFont) self.table.item(9, 0).setBackground(Qt.lightGray) # column 1 self.table.setItem(0, 1, SpreadSheetItem("Date")) self.table.item(0, 1).setBackground(titleBackground) self.table.item(0, 1).setToolTip("This column shows the purchase date, double click to change") self.table.item(0, 1).setFont(titleFont) self.table.setItem(1, 1, SpreadSheetItem("15/6/2006")) self.table.setItem(2, 1, SpreadSheetItem("15/6/2006")) self.table.setItem(3, 1, SpreadSheetItem("15/6/2006")) self.table.setItem(4, 1, SpreadSheetItem("21/5/2006")) self.table.setItem(5, 1, SpreadSheetItem("16/6/2006")) self.table.setItem(6, 1, SpreadSheetItem("16/6/2006")) self.table.setItem(7, 1, SpreadSheetItem("16/6/2006")) self.table.setItem(8, 1, SpreadSheetItem("18/6/2006")) self.table.setItem(9, 1, SpreadSheetItem()) self.table.item(9, 1).setBackground(Qt.lightGray) # column 2 self.table.setItem(0, 2, SpreadSheetItem("Price")) self.table.item(0, 2).setBackground(titleBackground) self.table.item(0, 2).setToolTip("This column shows the price of the purchase") self.table.item(0, 2).setFont(titleFont) self.table.setItem(1, 2, SpreadSheetItem("150")) self.table.setItem(2, 2, SpreadSheetItem("2350")) self.table.setItem(3, 2, SpreadSheetItem("-14")) self.table.setItem(4, 2, SpreadSheetItem("980")) self.table.setItem(5, 2, SpreadSheetItem("5")) self.table.setItem(6, 2, SpreadSheetItem("120")) self.table.setItem(7, 2, SpreadSheetItem("300")) self.table.setItem(8, 2, SpreadSheetItem("1240")) self.table.setItem(9, 2, SpreadSheetItem()) self.table.item(9, 2).setBackground(Qt.lightGray) # column 3 self.table.setItem(0, 3, SpreadSheetItem("Currency")) self.table.item(0, 3).setBackgroundColor(titleBackground) self.table.item(0, 3).setToolTip("This column shows the currency") self.table.item(0, 3).setFont(titleFont) self.table.setItem(1, 3, SpreadSheetItem("NOK")) self.table.setItem(2, 3, SpreadSheetItem("NOK")) self.table.setItem(3, 3, SpreadSheetItem("EUR")) self.table.setItem(4, 3, SpreadSheetItem("EUR")) self.table.setItem(5, 3, SpreadSheetItem("USD")) self.table.setItem(6, 3, SpreadSheetItem("USD")) self.table.setItem(7, 3, SpreadSheetItem("USD")) self.table.setItem(8, 3, SpreadSheetItem("USD")) self.table.setItem(9, 3, SpreadSheetItem()) self.table.item(9,3).setBackground(Qt.lightGray) # column 4 self.table.setItem(0, 4, SpreadSheetItem("Ex. Rate")) self.table.item(0, 4).setBackground(titleBackground) self.table.item(0, 4).setToolTip("This column shows the exchange rate to NOK") self.table.item(0, 4).setFont(titleFont) self.table.setItem(1, 4, SpreadSheetItem("1")) self.table.setItem(2, 4, SpreadSheetItem("1")) self.table.setItem(3, 4, SpreadSheetItem("8")) self.table.setItem(4, 4, SpreadSheetItem("8")) self.table.setItem(5, 4, SpreadSheetItem("7")) self.table.setItem(6, 4, SpreadSheetItem("7")) self.table.setItem(7, 4, SpreadSheetItem("7")) self.table.setItem(8, 4, SpreadSheetItem("7")) self.table.setItem(9, 4, SpreadSheetItem()) self.table.item(9,4).setBackground(Qt.lightGray) # column 5 self.table.setItem(0, 5, SpreadSheetItem("NOK")) self.table.item(0, 5).setBackground(titleBackground) self.table.item(0, 5).setToolTip("This column shows the expenses in NOK") self.table.item(0, 5).setFont(titleFont) self.table.setItem(1, 5, SpreadSheetItem("* C2 E2")) self.table.setItem(2, 5, SpreadSheetItem("* C3 E3")) self.table.setItem(3, 5, SpreadSheetItem("* C4 E4")) self.table.setItem(4, 5, SpreadSheetItem("* C5 E5")) self.table.setItem(5, 5, SpreadSheetItem("* C6 E6")) self.table.setItem(6, 5, SpreadSheetItem("* C7 E7")) self.table.setItem(7, 5, SpreadSheetItem("* C8 E8")) self.table.setItem(8, 5, SpreadSheetItem("* C9 E9")) self.table.setItem(9, 5, SpreadSheetItem("sum F2 F9")) self.table.item(9,5).setBackground(Qt.lightGray) def showAbout(self): QMessageBox.about(self, "About Spreadsheet", """ <HTML> <p><b>This demo shows use of <c>QTableWidget</c> with custom handling for individual cells.</b></p> <p>Using a customized table item we make it possible to have dynamic output in different cells. The content that is implemented for this particular demo is: <ul> <li>Adding two cells.</li> <li>Subtracting one cell from another.</li> <li>Multiplying two cells.</li> <li>Dividing one cell with another.</li> <li>Summing the contents of an arbitrary number of cells.</li> </HTML> """) def print_(self): pass
def _create_actions(self): tree = self.layerTree act = QAction("Save subset", tree) act.setEnabled(False) act.setToolTip("Save the mask for this subset to a file") act.setShortcut(QKeySequence.Save) act.setShortcutContext(Qt.WidgetShortcut) act.triggered.connect(self._save_subset) tree.addAction(act) self._save_action = act act = QAction("Load subset", tree) act.setEnabled(False) act.setToolTip("Load a subset from a file") act.setShortcut(QKeySequence.Open) act.setShortcutContext(Qt.WidgetShortcut) act.triggered.connect(self._load_subset) tree.addAction(act) self._load_action = act act = QAction("Copy subset", tree) act.setEnabled(False) act.setToolTip("Copy the definition for the selected subset") act.setShortcut(QKeySequence.Copy) act.setShortcutContext(Qt.WidgetShortcut) act.triggered.connect(self._copy_subset) tree.addAction(act) self._copy_action = act act = QAction("Paste subset", tree) act.setEnabled(False) act.setToolTip("Overwite selected subset with contents from clipboard") act.setShortcut(QKeySequence.Paste) act.setShortcutContext(Qt.WidgetShortcut) act.triggered.connect(self._paste_subset) tree.addAction(act) self._paste_action = act act = QAction("New subset", tree) act.setEnabled(False) act.setToolTip("Create a new subset for the selected data") act.setShortcut('Ctrl+B') act.setShortcutContext(Qt.WidgetShortcut) act.triggered.connect(self._new_subset) tree.addAction(act) self._new_action = act act = QAction("Clear subset", tree) act.setEnabled(False) act.setToolTip("Clear current selection") act.setShortcut('Ctrl+0') act.setShortcutContext(Qt.WidgetShortcut) act.triggered.connect(self._clear_subset) tree.addAction(act) self._clear_action = act act = QAction("Duplicate subset", tree) act.setEnabled(False) act.setToolTip("Duplicate the current subset") act.setShortcut('Ctrl+D') act.setShortcutContext(Qt.WidgetShortcut) act.triggered.connect(self._duplicate_subset) tree.addAction(act) self._duplicate_action = act act = QAction("Delete layer", tree) act.setEnabled(False) act.setToolTip("Remove the highlighted layer") act.setShortcut(QKeySequence.Delete) act.setShortcutContext(Qt.WidgetShortcut) act.triggered.connect(self.remove_and_delete_selected) self._delete_action = act tree.addAction(act) separator = QAction("Subset Combination", tree) separator.setSeparator(True) tree.addAction(separator) self._combination_actions() tree.setContextMenuPolicy(Qt.ActionsContextMenu)
class DocumentViewManager(QMainWindow): """ MDI area for displaying supporting documents within a given context e.g. supporting documents for a specific household based on the lifetime of the 'SourceDocumentManager' instance. """ def __init__(self, parent = None): QMainWindow.__init__(self, parent) self.setWindowFlags(Qt.Window) self._mdi_area = QMdiArea() self.setCentralWidget(self._mdi_area) self._mdi_area.subWindowActivated.connect(self.update_actions) self._viewer_mapper = QSignalMapper(self) self._viewer_mapper.mapped[QWidget].connect(self.set_active_sub_window) win_title = QApplication.translate("DocumentViewManager","Document Viewer") self.setWindowTitle(win_title) self.setUnifiedTitleAndToolBarOnMac(True) self.statusBar().showMessage(QApplication.translate("DocumentViewManager","Ready")) self._doc_viewers = {} self._create_menu_actions() self.update_actions() def _create_menu_actions(self): self._window_menu = self.menuBar().addMenu(QApplication.translate("DocumentViewManager","&Windows")) self._close_act = QAction(QApplication.translate("DocumentViewManager", "Cl&ose"), self) self._close_act.setStatusTip(QApplication.translate("DocumentViewManager", "Close the active document viewer")) self._close_act.triggered.connect(self._mdi_area.closeActiveSubWindow) self._close_all_act = QAction(QApplication.translate("DocumentViewManager", "Close &All"), self) self._close_all_act.setStatusTip(QApplication.translate("DocumentViewManager", "Close all the document viewers")) self._close_all_act.triggered.connect(self._mdi_area.closeAllSubWindows) self._tile_act = QAction(QApplication.translate("DocumentViewManager", "&Tile"), self) self._tile_act.setStatusTip(QApplication.translate("DocumentViewManager", "Tile the document viewers")) self._tile_act.triggered.connect(self._mdi_area.tileSubWindows) self._cascade_act = QAction(QApplication.translate("DocumentViewManager", "&Cascade"), self) self._cascade_act.setStatusTip(QApplication.translate("DocumentViewManager", "Cascade the document viewers")) self._cascade_act.triggered.connect(self._mdi_area.cascadeSubWindows) self._next_act = QAction(QApplication.translate("DocumentViewManager", "Ne&xt"), self) self._next_act.setStatusTip(QApplication.translate("DocumentViewManager", "Move the focus to the next document viewer")) self._next_act.triggered.connect(self._mdi_area.activateNextSubWindow) self._previous_act = QAction(QApplication.translate("DocumentViewManager", "Pre&vious"), self) self._previous_act.setStatusTip(QApplication.translate("DocumentViewManager", "Move the focus to the previous document viewer")) self._previous_act.triggered.connect(self._mdi_area.activatePreviousSubWindow) self._separator_act = QAction(self) self._separator_act.setSeparator(True) self.update_window_menu() self._window_menu.aboutToShow.connect(self.update_window_menu) def update_actions(self): if self._mdi_area.activeSubWindow(): has_mdi_child = True else: has_mdi_child = False self._close_act.setEnabled(has_mdi_child) self._close_all_act.setEnabled(has_mdi_child) self._tile_act.setEnabled(has_mdi_child) self._cascade_act.setEnabled(has_mdi_child) self._previous_act.setEnabled(has_mdi_child) self._next_act.setEnabled(has_mdi_child) self._separator_act.setVisible(has_mdi_child) def update_window_menu(self): self._window_menu.clear() self._window_menu.addAction(self._close_act) self._window_menu.addAction(self._close_all_act) self._window_menu.addSeparator() self._window_menu.addAction(self._tile_act) self._window_menu.addAction(self._cascade_act) self._window_menu.addSeparator() self._window_menu.addAction(self._next_act) self._window_menu.addAction(self._previous_act) self._window_menu.addAction(self._separator_act) windows = self._mdi_area.subWindowList() self._separator_act.setVisible(len(windows) != 0) for i, window in enumerate(windows): text = "%d. %s" % (i + 1, window.windowTitle()) win_action = self._window_menu.addAction(text) win_action.setCheckable(True) win_action.setChecked(window is self._mdi_area.activeSubWindow()) win_action.triggered.connect(self._viewer_mapper.map) self._viewer_mapper.setMapping(win_action, window) def load_viewer(self, document_widget): """ Open a new instance of the viewer or activate an existing one if the document had been previously loaded. :param document_widget: Contains all the necessary information required to load the specific document. """ doc_identifier = document_widget.file_identifier() if doc_identifier in self._doc_viewers: doc_sw = self._doc_viewers[doc_identifier] self._mdi_area.setActiveSubWindow(doc_sw) doc_sw.showNormal() else: doc_viewer = self._create_viewer(document_widget) abs_doc_path = self.absolute_document_path(document_widget) if not QFile.exists(abs_doc_path): msg = QApplication.translate("DocumentViewManager", "The selected document does not exist." "\nPlease check the supporting documents' " "repository setting.") QMessageBox.critical(self, QApplication.translate("DocumentViewManager","Invalid Document"), msg) return doc_viewer.load_document(abs_doc_path) self._doc_viewers[doc_identifier] = doc_viewer self._mdi_area.addSubWindow(doc_viewer) doc_viewer.show() if not self.isVisible(): self.setVisible(True) if self.isMinimized(): self.showNormal() def set_active_sub_window(self, viewer): if viewer: self._mdi_area.setActiveSubWindow(viewer) def absolute_document_path(self,document_widget): """ Build the absolute document path using info from the document widget. :param document_widget: Instance of document widget. :return: Absolute path of the supporting document. :rtype: str """ abs_path = "" file_manager = document_widget.fileManager if not file_manager is None: network_repository = file_manager.networkPath file_id = document_widget.file_identifier() doc_type = "%d"%(document_widget.documentType()) file_name, file_extension = guess_extension(document_widget.displayName()) abs_path = network_repository + "/" + doc_type + "/" +\ file_id + file_extension return abs_path def reset(self): """ Removes all document viewers in the view area. The QCloseEvent sent to each sub-window will decrement the register. """ self._mdi_area.closeAllSubWindows() def _create_viewer(self, document_widget): """ Creates a new instance of a document viewer. :param document_widget: Contains all the necessary information required to load the specific document. :return: Document viewer object :rtype: DocumentViewer """ doc_viewer = DocumentViewer(self._mdi_area, document_widget.file_identifier()) doc_viewer.setAttribute(Qt.WA_DeleteOnClose) doc_viewer.setWindowTitle(document_widget.displayName()) #TODO: Incorporate logic for determining viewer based on document type ph_viewer = PhotoViewer() doc_viewer.set_view_widget(ph_viewer) doc_viewer.closed.connect(self._on_viewer_closed) return doc_viewer def remove_viewer(self, viewer_id): """ Close and remove the viewer with the specified viewer ID. """ if viewer_id in self._doc_viewers: viewer = self._doc_viewers[viewer_id] self._mdi_area.setActiveSubWindow(viewer) self._mdi_area.closeActiveSubWindow() self._on_viewer_closed(viewer_id) def _on_viewer_closed(self,file_id): """ Slot raised when a document viewer is closed. """ if file_id in self._doc_viewers: del self._doc_viewers[file_id]
def __init__(self, fragment, args, client, animation_manager=None, parent=None, has_menu_pos=True): """ @fragment [Fragment] user_settings.Fragment object to describe fragment @client [RpcdClient] client @parent [QWidget] parent widget """ #assert isinstance(client, RpcdClient) assert frag_types.has_key(fragment.type) QFrame.__init__(self, parent) self.animation_manager = animation_manager self.has_menu_pos = has_menu_pos self.fragment = fragment self.fetcher = frag_types[fragment.type].fetcher(fragment, args, client) self.connect(self.fetcher, SIGNAL(self.fetcher.ERROR_SIGNAL), self.errorHandler) self.window = parent self.cumulative_mode = False self.interval = Interval('daily') self.setFragmentColor() self.setFrameShadow(QFrame.Sunken) self.setFrameShape(QFrame.StyledPanel) self.setContextMenuPolicy(Qt.ActionsContextMenu) self.toolspace = None self.vbox = QVBoxLayout() # self.vbox.setContentsMargins(9,0,9,9) self.vbox.setContentsMargins(9,0,9,0) self.setLayout(self.vbox) self.stacked = QStackedWidget(self) updating_label = QLabel("<img src=\":/icons/refresh.png\" /><br />%s" % self.tr("Updating...")) updating_label.setAlignment(Qt.AlignHCenter|Qt.AlignVCenter) self.stacked.addWidget(updating_label) # Create all actions for the rightclick context menu self.action_list = [] self.switch_actions = {} self.viewlayout = QHBoxLayout() self.viewlayout.setContentsMargins(0,0,0,0) self.viewlayout.setSpacing(2) self.viewlayout.addStretch() widget = QWidget() widget.setLayout(self.viewlayout) self.vbox.addWidget(widget) self.line = QFrame(self) self.line.setFrameShape(QFrame.HLine) self.line.setFrameShadow(QFrame.Sunken) self.line.setObjectName("line") # Menu to choose position of fragment if self.has_menu_pos: self.pos_menu = QMenu(tr('Position'), self) # self.pos_action = QAction(tr('Position'), self.pos_menu) def make_lambda(l): """ usefull to create the lambda function with a copied parameter. or it'll bug """ return lambda: QTimer.singleShot(0, lambda: self.setView(l)) self.buttons = [] button = QToolButton() button.visible = True button.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Ignored) button.setMinimumSize(0,16) button.setIcon(QIcon(":/icons/refresh.png")) button.setFixedHeight(16) button.setToolTip(tr("Refresh")) self.connect(button, SIGNAL("clicked()"), self.updateData) self.viewlayout.addWidget(button) self.buttons.append(button) # All of the views available for this kind of fragment. if len(frag_types[fragment.type].views) > 1: for label in frag_types[fragment.type].views: try: item_name = views_list_label[label] except KeyError: continue # item_name returns a unicode string, but PyQT (Qt 4.2.1) won't convert it to a char* # unless we convert it to a non-unicode string .... action = QAction(QIcon(':/icons/%s' % label), tr("Switch to %s") % self.tr(unicode(item_name)), self) self.connect(action, SIGNAL("triggered()"), make_lambda(label)) self.action_list += [action] self.switch_actions[label] = action button = QToolButton() button.visible = True button.setBackgroundRole(QPalette.Button) button.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Minimum) button.setMinimumSize(0,16) button.setFixedHeight(16) button.setIcon(QIcon(":/icons/%s" % label)) button.setToolTip(tr("Switch to %s") % self.tr(unicode(item_name))) self.connect(button, SIGNAL("clicked()"), make_lambda(label)) self.viewlayout.addWidget(button) self.buttons.append(button) # Separator action = QAction(self) action.setSeparator(True) self.action_list += [action] # Refresh action = QAction(QIcon(':/icons/refresh.png'), tr('Refresh'), self) self.connect(action, SIGNAL('triggered()'), self.updateData) self.action_list += [action] if self.FRAGMENT_EDITION: # Edit action = QAction(QIcon(':/icons/edit.png'), tr('Edit this fragment...'), self) self.connect(action, SIGNAL('triggered()'), self.editFragment) self.action_list += [action] # Delete action = QAction(QIcon(':/icons/moins.png'), tr('Delete this fragment'), self) self.connect(action, SIGNAL('triggered()'), self.removeFragment) self.action_list += [action] self.setView(fragment.view, update=False) self.setAcceptDrops(True) self.pos = -1
class DocumentViewManager(QMainWindow): """ MDI area for displaying supporting documents within a given context e.g. supporting documents for a specific household based on the lifetime of the 'SourceDocumentManager' instance. """ def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.setWindowFlags(Qt.Window) self._mdi_area = QMdiArea() self._mdi_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) self._mdi_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.setCentralWidget(self._mdi_area) # set the size of mid_area and DocumentViewManager based on the # screen size. screen = QDesktopWidget().availableGeometry() self._mdi_area.resize(screen.width() - 30, screen.height() - 80) self.resize(self._mdi_area.size()) self._mdi_area.subWindowActivated.connect(self.update_actions) self._viewer_mapper = QSignalMapper(self) self._viewer_mapper.mapped[QWidget].connect(self.set_active_sub_window) win_title = QApplication.translate( "DocumentViewManager", "Document Viewer" ) self.setWindowTitle(win_title) self.setUnifiedTitleAndToolBarOnMac(True) self.statusBar().showMessage( QApplication.translate( "DocumentViewManager", "Ready" ) ) self._doc_viewers = {} self._create_menu_actions() self.update_actions() def center(self): """ Move the Document viewer to the center of the screen. """ # Get the current screens' dimensions... screen = QDesktopWidget().availableGeometry() # ... and get this windows' dimensions mdi_area_size = self.frameGeometry() # The horizontal position hpos = (screen.width() - mdi_area_size.width()) / 2 # vertical position vpos = (screen.height() - mdi_area_size.height()) / 2 # repositions the window self.move(hpos, vpos) def _create_menu_actions(self): self._window_menu = self.menuBar().addMenu( QApplication.translate( "DocumentViewManager","&Windows")) self._close_act = QAction( QApplication.translate("DocumentViewManager", "Cl&ose"), self) self._close_act.setStatusTip( QApplication.translate("DocumentViewManager", "Close the active document viewer")) self._close_act.triggered.connect(self._mdi_area.closeActiveSubWindow) self._close_all_act = QAction(QApplication.translate( "DocumentViewManager", "Close &All"), self ) self._close_all_act.setStatusTip( QApplication.translate("DocumentViewManager", "Close all the document viewers") ) self._close_all_act.triggered.connect( self._mdi_area.closeAllSubWindows ) self._tile_act = QAction(QApplication.translate( "DocumentViewManager", "&Tile"), self ) self._tile_act.setStatusTip( QApplication.translate("DocumentViewManager", "Tile the document viewers")) self._tile_act.triggered.connect(self.tile_windows) self._cascade_act = QAction(QApplication.translate( "DocumentViewManager", "&Cascade"), self) self._cascade_act.setStatusTip(QApplication.translate( "DocumentViewManager", "Cascade the document viewers")) self._cascade_act.triggered.connect(self.cascade_windows) self._next_act = QAction(QApplication.translate( "DocumentViewManager", "Ne&xt"), self) self._next_act.setStatusTip( QApplication.translate( "DocumentViewManager", "Move the focus to the next document viewer" ) ) self._next_act.triggered.connect(self._mdi_area.activateNextSubWindow) self._previous_act = QAction(QApplication.translate( "DocumentViewManager", "Pre&vious"), self) self._previous_act.setStatusTip( QApplication.translate( "DocumentViewManager", "Move the focus to the previous document viewer" ) ) self._previous_act.triggered.connect( self._mdi_area.activatePreviousSubWindow ) self._separator_act = QAction(self) self._separator_act.setSeparator(True) self.update_window_menu() self._window_menu.aboutToShow.connect(self.update_window_menu) def cascade_windows(self): #Cascade document windows self._mdi_area.cascadeSubWindows() def tile_windows(self): #Arrange document windows to occupy the available space in mdi area self._mdi_area.tileSubWindows() def update_actions(self): if self._mdi_area.activeSubWindow(): has_mdi_child = True else: has_mdi_child = False self._close_act.setEnabled(has_mdi_child) self._close_all_act.setEnabled(has_mdi_child) self._tile_act.setEnabled(has_mdi_child) self._cascade_act.setEnabled(has_mdi_child) self._previous_act.setEnabled(has_mdi_child) self._next_act.setEnabled(has_mdi_child) self._separator_act.setVisible(has_mdi_child) def update_window_menu(self): self._window_menu.clear() self._window_menu.addAction(self._close_act) self._window_menu.addAction(self._close_all_act) self._window_menu.addSeparator() self._window_menu.addAction(self._tile_act) self._window_menu.addAction(self._cascade_act) self._window_menu.addSeparator() self._window_menu.addAction(self._next_act) self._window_menu.addAction(self._previous_act) self._window_menu.addAction(self._separator_act) windows = self._mdi_area.subWindowList() self._separator_act.setVisible(len(windows) != 0) for i, window in enumerate(windows): text = "%d. %s" % (i + 1, window.windowTitle()) win_action = self._window_menu.addAction(text) win_action.setCheckable(True) win_action.setChecked(window is self._mdi_area.activeSubWindow()) win_action.triggered.connect(self._viewer_mapper.map) self._viewer_mapper.setMapping(win_action, window) def load_viewer(self, document_widget, visible=True): """ Open a new instance of the viewer or activate an existing one if the document had been previously loaded. :param document_widget: Contains all the necessary information required to load the specific document. :type document_widget: DocumentWidget :param visible: True to show the view manager after the viewer has been loaded, otherwise it will be the responsibility of the caller to enable visibility. :type visible: bool :returns: True if the document was successfully loaded, else False. :rtype: bool """ doc_identifier = document_widget.file_identifier() if doc_identifier in self._doc_viewers: doc_sw = self._doc_viewers[doc_identifier] self._mdi_area.setActiveSubWindow(doc_sw) doc_sw.showNormal() else: doc_viewer = self._create_viewer(document_widget) abs_doc_path = self.absolute_document_path(document_widget) if not QFile.exists(abs_doc_path): msg = QApplication.translate( "DocumentViewManager", "The selected document does not exist." "\nPlease check the supporting documents' " "repository setting." ) QMessageBox.critical( self, QApplication.translate( "DocumentViewManager","Invalid Document" ), msg ) return False doc_viewer.load_document(abs_doc_path) self._doc_viewers[doc_identifier] = doc_viewer self._mdi_area.addSubWindow(doc_viewer) doc_viewer.show() if not self.isVisible() and visible: self.setVisible(True) if self.isMinimized(): self.showNormal() self.center() return True def set_active_sub_window(self, viewer): if viewer: self._mdi_area.setActiveSubWindow(viewer) def absolute_document_path(self, document_widget): """ Build the absolute document path using info from the document widget. :param document_widget: Instance of document widget. :return: Absolute path of the supporting document. :rtype: str """ abs_path = '' file_manager = document_widget.fileManager if not file_manager is None: network_repository = file_manager.networkPath file_id = document_widget.file_identifier() source_entity = document_widget.doc_source_entity() profile_name = current_profile().name doc_type = document_widget.doc_type_value().lower().replace( ' ', '_' ) file_name, file_extension = guess_extension( document_widget.displayName() ) abs_path = network_repository + "/" +profile_name + '/' +\ unicode(source_entity) + "/" + unicode(doc_type) + "/" +\ unicode(file_id) + unicode(file_extension) return abs_path def reset(self): """ Removes all document viewers in the view area. The QCloseEvent sent to each sub-window will decrement the register. """ self._mdi_area.closeAllSubWindows() def _create_viewer(self, document_widget): """ Creates a new instance of a document viewer. :param document_widget: Contains all the necessary information required to load the specific document. :return: Document viewer object :rtype: DocumentViewer """ doc_viewer = DocumentViewer( self._mdi_area, document_widget.file_identifier() ) doc_viewer.setAttribute(Qt.WA_DeleteOnClose) doc_viewer.setWindowTitle( document_widget.displayName() ) # TODO: Incorporate logic for determining # TODO: viewer based on document type ph_viewer = PhotoViewer() # v_layout = QVBoxLayout() # v_layout.addWidget(ph_viewer) # doc_viewer.setLayout(v_layout) doc_viewer.set_view_widget(ph_viewer) doc_viewer.closed.connect(self._on_viewer_closed) return doc_viewer def remove_viewer(self, viewer_id): """ Close and remove the viewer with the specified viewer ID. """ if viewer_id in self._doc_viewers: viewer = self._doc_viewers[viewer_id] self._mdi_area.setActiveSubWindow(viewer) self._mdi_area.closeActiveSubWindow() self._on_viewer_closed(viewer_id) def _on_viewer_closed(self,file_id): """ Slot raised when a document viewer is closed. """ if file_id in self._doc_viewers: del self._doc_viewers[file_id]
def _add_spacer_to_menu(self): """Create a spacer to the menu to separate action groups.""" separator = QAction(self.iface.mainWindow()) separator.setSeparator(True) self.iface.addPluginToMenu(self.tr('InaSAFE'), separator)
def setView(self, label, update=True): # If there isn't any view for this fragment, use the first available view # of this kind of fragment. if not label: assert frag_types.has_key(self.fragment.type) assert len(frag_types[self.fragment.type].views) > 0 label = frag_types[self.fragment.type].views[0] for button in self.buttons: if label in button.toolTip(): button.visible = False else: if not button.isEnabled(): button.visible = True # assert views_list.has_key(label) self.freeView() # Create the view object. self.view = views_list[label](self.fetcher, self) if label == "histo" or label == 'pie': self.view.is_graphics_view = True if label == 'histo': self.view.chart_type = BARCHART else: self.view.chart_type = PIECHART else: self.view.is_graphics_view = False if label != "error": self.connect(self, SIGNAL("closed"), self.setClosed) if self.animation_manager: if self.view.is_graphics_view: self.connect(self.view, SIGNAL("animation_done(QString)"), self, SIGNAL("animation_done(QString)")) self.animation_manager.addView(self.view) self.connect(self.view, SIGNAL("showButtons"), self.showButtonsSlot) self.connect(self.view, SIGNAL("autoRefresh"), self.updateData) self.view.setCumulative(self.cumulative_mode) self.view.setInterval(self.interval) self.stacked.insertWidget(0, self.view) self._show_view() self.connect(self.view, SIGNAL('open_page'), self._open_page) self.connect(self.view, SIGNAL('add_filter'), self._add_filter) self.connect(self.view, SIGNAL('updating'), self._show_animation) self.connect(self.view, SIGNAL('updated'), self._show_view) self.connect(self.view, SIGNAL('EAS_Message'), self.EAS_SendMessage) # Set some features if there are available on each or each type of widget. if hasattr(self.view, 'setFrameShape'): self.view.setFrameShape(QFrame.NoFrame) self.view.setContextMenuPolicy(Qt.ActionsContextMenu) # All views can ask me to display a toolspace (a widget with all kind of # things in). self.view.title.setText(self.view.getTitle()) self.fragment.view = label self.toolspace = self.view.getToolspace() self.viewlayout.insertWidget(0, self.toolspace) self.vbox.addWidget(self.line) self.vbox.addWidget(self.stacked) # Set the new menu. for action in self.actions(): self.removeAction(action) for view_label, action in self.switch_actions.items(): action.setEnabled(view_label != self.fragment.view) for action in self.action_list: self.addAction(action) self.view.addAction(action) # Add view's eventual menu. view_actions = self.view.getActions() if view_actions: separator = QAction(self) separator.setSeparator(True) view_actions = [separator] + view_actions for action in view_actions: self.view.addAction(action) self.addAction(action) if self.has_menu_pos: self.view.addAction(self.pos_menu.menuAction()) self.addAction(self.pos_menu.menuAction()) if update: self.updateData()