def loadpages(self, pages): def safe_connect(method, to): try: method.connect(to) except AttributeError: pass for PageClass in pages: action = QAction(self.menutoolbar) text = PageClass.title.ljust(13) action.setIconText(text) action.setIcon(QIcon(PageClass.icon)) action.setCheckable(True) if PageClass.projectpage: action.setVisible(False) self.projectbuttons.append(action) self.menutoolbar.insertAction(self.spaceraction, action) else: self.menutoolbar.insertAction(self.actionProject, action) iface = RoamInterface(RoamEvents, GPS, self) pagewidget = PageClass(iface, self) safe_connect(RoamEvents.selectionchanged, pagewidget.selection_changed) safe_connect(RoamEvents.projectloaded, pagewidget.project_loaded) pageindex = self.stackedWidget.insertWidget(-1, pagewidget) action.setProperty('page', pageindex) self.pluginactions.append(action) self.menuGroup.addAction(action)
def loadpages(self, pages): def safe_connect(method, to): try: method.connect(to) except AttributeError: pass for PageClass in pages: action = QAction(self.menutoolbar) text = PageClass.title.ljust(13) action.setIconText(text) action.setIcon(QIcon(PageClass.icon)) action.setCheckable(True) if PageClass.projectpage: action.setVisible(False) self.projectbuttons.append(action) self.menutoolbar.insertAction(self.spaceraction, action) else: self.menutoolbar.insertAction(self.actionProject, action) iface = RoamInterface(RoamEvents, GPS, self) pagewidget = PageClass(iface, self) safe_connect(RoamEvents.selectionchanged, pagewidget.selection_changed) safe_connect(RoamEvents.projectloaded, pagewidget.project_loaded) pageindex = self.stackedWidget.insertWidget(-1, pagewidget) action.setProperty('page', pageindex) self.pluginactions.append(action) self.menuGroup.addAction(action)
class Tool(object): def __init__(self, name, help_link="", icon=None, enabled=True, checkable=False, popup_menu=False): super(Tool, self).__init__() self.__icon = icon self.__name = name self.__parent = None self.__enabled = enabled self.__checkable = checkable self.__help_link = help_link self.__is_popup_menu = popup_menu self.__action = QAction(self.getIcon(), self.getName(), None) self.__action.setIconText(self.getName()) self.__action.setEnabled(self.isEnabled()) self.__action.setCheckable(checkable) self.__action.triggered.connect(self.trigger) HelpCenter.addHelpToAction(self.__action, self.getHelpLink()) def getIcon(self): return self.__icon def getName(self): return self.__name def trigger(self): raise NotImplementedError() def setParent(self, parent): self.__parent = parent self.__action.setParent(parent) def parent(self): return self.__parent def isEnabled(self): return self.__enabled def getHelpLink(self): return self.__help_link def getAction(self): return self.__action def setVisible(self, visible): self.__action.setVisible(visible) def setEnabled(self, enabled): self.__action.setEnabled(enabled) def isPopupMenu(self): return self.__is_popup_menu
class Actions(actioncollection.ActionCollection): name = "musicview" def createActions(self, panel): self.music_document_select = DocumentChooserAction(panel) self.music_print = QAction(panel) self.music_zoom_in = QAction(panel) self.music_zoom_out = QAction(panel) self.music_zoom_original = QAction(panel) self.music_zoom_combo = ZoomerAction(panel) self.music_fit_width = QAction(panel, checkable=True) self.music_fit_height = QAction(panel, checkable=True) self.music_fit_both = QAction(panel, checkable=True) self.music_maximize = QAction(panel) self.music_jump_to_cursor = QAction(panel) self.music_sync_cursor = QAction(panel, checkable=True) self.music_copy_image = QAction(panel) self.music_pager = PagerAction(panel) self.music_next_page = QAction(panel) self.music_prev_page = QAction(panel) self.music_print.setIcon(icons.get('document-print')) self.music_zoom_in.setIcon(icons.get('zoom-in')) self.music_zoom_out.setIcon(icons.get('zoom-out')) self.music_zoom_original.setIcon(icons.get('zoom-original')) self.music_fit_width.setIcon(icons.get('zoom-fit-width')) self.music_fit_height.setIcon(icons.get('zoom-fit-height')) self.music_fit_both.setIcon(icons.get('zoom-fit-best')) self.music_maximize.setIcon(icons.get('view-fullscreen')) self.music_jump_to_cursor.setIcon(icons.get('go-jump')) self.music_copy_image.setIcon(icons.get('edit-copy')) self.music_next_page.setIcon(icons.get('go-next')) self.music_prev_page.setIcon(icons.get('go-previous')) self.music_document_select.setShortcut(QKeySequence(Qt.SHIFT | Qt.CTRL | Qt.Key_O)) self.music_print.setShortcuts(QKeySequence.Print) self.music_zoom_in.setShortcuts(QKeySequence.ZoomIn) self.music_zoom_out.setShortcuts(QKeySequence.ZoomOut) self.music_jump_to_cursor.setShortcut(QKeySequence(Qt.CTRL | Qt.Key_J)) self.music_copy_image.setShortcut(QKeySequence(Qt.SHIFT | Qt.CTRL | Qt.Key_C)) def translateUI(self): self.music_document_select.setText(_("Select Music View Document")) self.music_print.setText(_("&Print Music...")) self.music_zoom_in.setText(_("Zoom &In")) self.music_zoom_out.setText(_("Zoom &Out")) self.music_zoom_original.setText(_("Original &Size")) self.music_zoom_combo.setText(_("Zoom Music")) self.music_fit_width.setText(_("Fit &Width")) self.music_fit_height.setText(_("Fit &Height")) self.music_fit_both.setText(_("Fit &Page")) self.music_maximize.setText(_("&Maximize")) self.music_jump_to_cursor.setText(_("&Jump to Cursor Position")) self.music_sync_cursor.setText(_("S&ynchronize with Cursor Position")) self.music_copy_image.setText(_("Copy to &Image...")) self.music_next_page.setText(_("Next Page")) self.music_next_page.setIconText(_("Next")) self.music_prev_page.setText(_("Previous Page")) self.music_prev_page.setIconText(_("Previous"))
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
class ToolBar(QToolBar): def __init__(self, window, qsci): QToolBar.__init__(self) self.qsci = qsci self.actions_dict = {'action_new':("document-new", "New", self._new_file), 'action_open':("document-open", "Open", self._open_file), 'action_save':("document-save", "Save", self._save_file), 'action_save_as':("document-save-as", "Save As", self._saveas_file), 'action_cut':("edit-cut", "Cut", SLOT("cut ()")), 'action_copy':("edit-copy", "Copy", SLOT("copy ()")), 'action_paste':("edit-paste", "Paste", SLOT("paste ()")), 'action_undo':("edit-undo", "Undo", SLOT("undo ()")), 'action_redo':("edit-redo", "Redo", SLOT("redo ()")), 'action_execute':("edit-Execute", "Execute", self._execute)} self._action_names = {} for action in self.actions_dict: self.action = QAction(window) self.action.setIcon(QIcon.fromTheme(self.actions_dict[action][0])) self._action_names[action] = self.action self.action.setIconText(QApplication.translate("MainWindow", self.actions_dict[action][1], None, QApplication.UnicodeUTF8)) self.addAction(self.action) self.addSeparator() if action in ('action_new', 'action_open', 'action_save', 'action_save_as', 'action_execute'): QObject.connect(self.action, SIGNAL("triggered()"), self.actions_dict[action][2]) else: QObject.connect(self.action, SIGNAL("triggered()"), qsci, self.actions_dict[action][2]) QObject.connect(self.qsci, SIGNAL("textChanged()"), self._enable_save_btn) def _enable_save_btn(self): self._action_names['action_save'].setEnabled(True) def _execute(self): pass ##when empty document has been created - Save button should be disabled def _new_file(self): self.qsci.setText(QString("")) self._action_names['action_save'].setDisabled(True) ##name of document to be saved is given explicitly for simple purpose #to be changed def _save_file(self): self.filename = 'syntax.txt' content = open(self.filename, 'w') content.write(self.qsci.text()) content.close() def _saveas_file(self): pass def _open_file(self): pass
class Tool(object): def __init__(self, name, help_link="", icon=None, enabled=True, checkable=False, popup_menu=False): super(Tool, self).__init__() self.__icon = icon self.__name = name self.__parent = None self.__enabled = enabled self.__checkable = checkable self.__help_link = help_link self.__is_popup_menu = popup_menu self.__action = QAction(self.getIcon(), self.getName(), None) self.__action.setIconText(self.getName()) self.__action.setEnabled(self.isEnabled()) self.__action.setCheckable(checkable) self.__action.triggered.connect(self.trigger) HelpCenter.addHelpToAction(self.__action, self.getHelpLink()) def getIcon(self): return self.__icon def getName(self): return self.__name def trigger(self): raise NotImplementedError() def setParent(self, parent): self.__parent = parent self.__action.setParent(parent) def parent(self): return self.__parent def isEnabled(self): return self.__enabled def getHelpLink(self): return self.__help_link def getAction(self): return self.__action def setVisible(self, visible): self.__action.setVisible(visible) def setEnabled(self, enabled): self.__action.setEnabled(enabled) def isPopupMenu(self): return self.__is_popup_menu
def addActions(): actn = QAction(winLegend) actn.setIcon(qgis.utils.iface.actionShowSelectedLayers().icon()) actn.setIconText('Show selected layers') actn.setObjectName('showLayer') actn.triggered.connect(self.onAction) toolBar.addAction(actn) actn = QAction(winLegend) actn.setIcon(qgis.utils.iface.actionHideSelectedLayers().icon()) actn.setIconText('Hide selected layers') actn.setObjectName('hideLayer') actn.triggered.connect(self.onAction) toolBar.addAction(actn) actn = QAction(winLegend) actn.setIcon(qgis.utils.iface.actionRemoveLayer().icon()) actn.setIconText('Remove selected layers') actn.setObjectName('removeLayer') actn.triggered.connect(self.onAction) toolBar.addAction(actn) toolBar.addSeparator() actn = QAction(winLegend) actn.setIcon(qgis.utils.iface.actionDuplicateLayer().icon()) actn.setIconText('Add selected layers from main map') actn.setObjectName('addLayer') actn.triggered.connect(self.onAction) toolBar.addAction(actn) actn = QAction(winLegend) actn.setIcon( QIcon( os.path.join(os.path.dirname(__file__), 'mActionCurrentLayer.png'))) actn.setIconText('Current layer for main map') actn.setObjectName('currentLayer') actn.triggered.connect(self.onAction) toolBar.addAction(actn) actn = QAction(winLegend) actn.setIcon( QIcon( os.path.join(os.path.dirname(__file__), 'mActionAddGroup.png'))) actn.setObjectName('syncGroup') actn.triggered.connect(self.onAction) toolBar.addAction(actn)
class Actions(actioncollection.ActionCollection): name = "browseriface" def createActions(self, parent): self.go_back = QAction(parent) self.go_forward = QAction(parent) self.go_back.setIcon(icons.get('go-previous')) self.go_forward.setIcon(icons.get('go-next')) self.go_back.setShortcut(QKeySequence(Qt.ALT + Qt.Key_Backspace)) self.go_forward.setShortcut(QKeySequence(Qt.ALT + Qt.Key_End)) def translateUI(self): self.go_back.setText(_("Go to previous position")) self.go_back.setIconText(_("Back")) self.go_forward.setText(_("Go to next position")) self.go_forward.setIconText(_("Forward"))
class Actions(actioncollection.ActionCollection): name = "browseriface" def createActions(self, parent): self.go_back = QAction(parent) self.go_forward = QAction(parent) self.go_back.setIcon(icons.get('go-previous')) self.go_forward.setIcon(icons.get('go-next')) self.go_back.setShortcut(QKeySequence(Qt.ALT + Qt.Key_Backspace)) self.go_forward.setShortcut(QKeySequence(Qt.ALT + Qt.Key_End)) def translateUI(self): self.go_back.setText(_("Go to previous position")) self.go_back.setIconText(_("Back")) self.go_forward.setText(_("Go to next position")) self.go_forward.setIconText(_("Forward"))
def addActions(): actn = QAction( winLegend ) actn.setIcon( qgis.utils.iface.actionShowSelectedLayers().icon() ) actn.setIconText( 'Show selected layers') actn.setObjectName( 'showLayer') actn.triggered.connect( self.onAction ) toolBar.addAction( actn ) actn = QAction( winLegend ) actn.setIcon( qgis.utils.iface.actionHideSelectedLayers().icon() ) actn.setIconText( 'Hide selected layers') actn.setObjectName( 'hideLayer') actn.triggered.connect( self.onAction ) toolBar.addAction( actn ) actn = QAction( winLegend ) actn.setIcon( qgis.utils.iface.actionRemoveLayer().icon() ) actn.setIconText( 'Remove selected layers') actn.setObjectName( 'removeLayer') actn.triggered.connect( self.onAction ) toolBar.addAction( actn ) toolBar.addSeparator() actn = QAction( winLegend ) actn.setIcon( qgis.utils.iface.actionDuplicateLayer().icon() ) actn.setIconText( 'Add selected layers from main map') actn.setObjectName( 'addLayer') actn.triggered.connect( self.onAction ) toolBar.addAction( actn ) actn = QAction( winLegend ) actn.setIcon( QIcon( os.path.join( os.path.dirname(__file__), 'mActionCurrentLayer.png' ) ) ) actn.setIconText( 'Current layer for main map') actn.setObjectName( 'currentLayer') actn.triggered.connect( self.onAction ) toolBar.addAction( actn ) actn = QAction( winLegend ) actn.setIcon( QIcon( os.path.join( os.path.dirname(__file__), 'mActionAddGroup.png' ) ) ) actn.setObjectName( 'syncGroup' ) actn.triggered.connect( self.onAction ) toolBar.addAction( actn )
def registerAction(self, name, **kwargs): """ Registers given action name, optional arguments like a parent, icon, slot etc ... can be given. :param name: Action to register. :type name: unicode :param \*\*kwargs: Keywords arguments. :type \*\*kwargs: \*\* :return: Action. :rtype: QAction """ settings = foundations.dataStructures.Structure(**{"parent": None, "text": None, "icon": None, "iconText": None, "checkable": None, "checked": None, "statusTip": None, "whatsThis": None, "toolTip": None, "shortcut": None, "shortcutContext": None, "slot": None}) settings.update(kwargs) name = self.__normalizeName(name) category = foundations.namespace.getNamespace(name) name = foundations.namespace.removeNamespace(name) action = QAction(name, settings.parent or self) self.addToCategory(category, name, action) settings.text and action.setText(settings.text) settings.icon and action.setIcon(settings.icon) settings.iconText and action.setIconText(settings.iconText) settings.checkable and action.setCheckable(settings.checkable) settings.checked and action.setChecked(settings.checked) settings.statusTip and action.setStatusTip(settings.statusTip) settings.whatsThis and action.setWhatsThis(settings.whatsThis) settings.toolTip and action.setToolTip(settings.toolTip) settings.shortcut and action.setShortcut(QKeySequence(settings.shortcut)) settings.shortcutContext and action.setShortcutContext(settings.shortcutContext) if settings.slot: self.__actionsSignalsSlots[action] = settings.slot action.triggered.connect(settings.slot) return action
class Actions(actioncollection.ActionCollection): name = "musicview" def createActions(self, panel): self.music_document_select = DocumentChooserAction(panel) self.music_print = QAction(panel) self.music_zoom_in = QAction(panel) self.music_zoom_out = QAction(panel) self.music_zoom_original = QAction(panel) self.music_zoom_combo = ZoomerAction(panel) self.music_fit_width = QAction(panel, checkable=True) self.music_fit_height = QAction(panel, checkable=True) self.music_fit_both = QAction(panel, checkable=True) self.music_maximize = QAction(panel) self.music_jump_to_cursor = QAction(panel) self.music_sync_cursor = QAction(panel, checkable=True) self.music_copy_image = QAction(panel) self.music_pager = PagerAction(panel) self.music_next_page = QAction(panel) self.music_prev_page = QAction(panel) self.music_reload = QAction(panel) self.music_print.setIcon(icons.get('document-print')) self.music_zoom_in.setIcon(icons.get('zoom-in')) self.music_zoom_out.setIcon(icons.get('zoom-out')) self.music_zoom_original.setIcon(icons.get('zoom-original')) self.music_fit_width.setIcon(icons.get('zoom-fit-width')) self.music_fit_height.setIcon(icons.get('zoom-fit-height')) self.music_fit_both.setIcon(icons.get('zoom-fit-best')) self.music_maximize.setIcon(icons.get('view-fullscreen')) self.music_jump_to_cursor.setIcon(icons.get('go-jump')) self.music_copy_image.setIcon(icons.get('edit-copy')) self.music_next_page.setIcon(icons.get('go-next')) self.music_prev_page.setIcon(icons.get('go-previous')) self.music_document_select.setShortcut( QKeySequence(Qt.SHIFT | Qt.CTRL | Qt.Key_O)) self.music_print.setShortcuts(QKeySequence.Print) self.music_zoom_in.setShortcuts(QKeySequence.ZoomIn) self.music_zoom_out.setShortcuts(QKeySequence.ZoomOut) self.music_jump_to_cursor.setShortcut(QKeySequence(Qt.CTRL | Qt.Key_J)) self.music_copy_image.setShortcut( QKeySequence(Qt.SHIFT | Qt.CTRL | Qt.Key_C)) self.music_reload.setShortcut(QKeySequence(Qt.Key_F5)) def translateUI(self): self.music_document_select.setText(_("Select Music View Document")) self.music_print.setText(_("&Print Music...")) self.music_zoom_in.setText(_("Zoom &In")) self.music_zoom_out.setText(_("Zoom &Out")) self.music_zoom_original.setText(_("Original &Size")) self.music_zoom_combo.setText(_("Zoom Music")) self.music_fit_width.setText(_("Fit &Width")) self.music_fit_height.setText(_("Fit &Height")) self.music_fit_both.setText(_("Fit &Page")) self.music_maximize.setText(_("&Maximize")) self.music_jump_to_cursor.setText(_("&Jump to Cursor Position")) self.music_sync_cursor.setText(_("S&ynchronize with Cursor Position")) self.music_copy_image.setText(_("Copy to &Image...")) self.music_next_page.setText(_("Next Page")) self.music_next_page.setIconText(_("Next")) self.music_prev_page.setText(_("Previous Page")) self.music_prev_page.setIconText(_("Previous")) self.music_reload.setText(_("&Reload"))
class QuickPanel(QWidget, WidgetManager): """ 一个快捷面板。类似于KDE的桌面。只不过功能会简单些。主要的方法有: addQuickAccessShortcut() 供插件添加一个系统快捷方式。 removeQuickAccessShortcut() 删除插件添加的系统快捷方式。 toggle() 如果快捷面板已经显示就隐藏它。如果处于隐藏状态则显示它。 showAndGetFocus() 显示快捷面板并且将焦点放置于常用的位置。 registerWidget() 注册部件 unregisterWidget() 反注册部件 """ def __init__(self, platform): QWidget.__init__(self, None, Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) self.setWindowModality(Qt.ApplicationModal) self.platform = platform self.db = QuickPanelDatabase(platform.databaseFile) self.createActions() self.createControls() self.loadSettings() self.makeConnections() #Besteam系统快捷方式作为QuickPanel提供的一个服务,必须定义在这里 #虽然部件可能没有运行。QuickPanel也应该记住其它插件添加的快捷方式,以便在 #用户添加QuickAccessWidget之后,可以显示所有的系统快捷方式 self.quickAccessModel = QuickAccessModel() def createActions(self): self.actionChangeBackground = QAction(self) self.actionChangeBackground.setIcon(QIcon(":/images/change_background.png")) self.actionChangeBackground.setText(self.trUtf8("Change &Background")) self.actionChangeBackground.setIconText(self.trUtf8("Background")) self.actionChangeBackground.setToolTip(self.trUtf8("Change Background")) self.actionClose = QAction(self) self.actionClose.setIcon(QIcon(":/images/close.png")) self.actionClose.setText(self.trUtf8("&Close")) self.actionClose.setIconText(self.trUtf8("Close")) self.actionClose.setToolTip(self.trUtf8("Close")) self.actionChangeLayout = QAction(self) self.actionChangeLayout.setIcon(QIcon(":/images/change_layout.png")) self.actionChangeLayout.setText(self.trUtf8("Change &Layout")) self.actionChangeLayout.setIconText(self.trUtf8("Layout")) self.actionChangeLayout.setToolTip(self.trUtf8("Change Layout")) self.actionChangeLayout.setCheckable(True) self.actionSelectWidgets = QAction(self) self.actionSelectWidgets.setIcon(QIcon(":/images/select_widgets.png")) self.actionSelectWidgets.setText(self.trUtf8("&Select Widgets")) self.actionSelectWidgets.setIconText(self.trUtf8("Widgets")) self.actionSelectWidgets.setToolTip(self.trUtf8("Select Widgets")) self.actionResetBackground = QAction(self) self.actionResetBackground.setIcon(QIcon(":/images/reset.png")) self.actionResetBackground.setText(self.trUtf8("&Reset Background")) self.actionResetBackground.setIconText(self.trUtf8("Reset")) self.actionResetBackground.setToolTip(self.trUtf8("Reset Background")) self.actionResetDefaultLayout = QAction(self) self.actionResetDefaultLayout.setIcon(QIcon(":/images/reset.png")) self.actionResetDefaultLayout.setText(self.trUtf8("Reset &Layout")) self.actionResetDefaultLayout.setIconText(self.trUtf8("Reset")) self.actionResetDefaultLayout.setToolTip(self.trUtf8("Reset Layout")) def createControls(self): self.toolBarMain = QToolBar(self) self.toolBarMain.addAction(self.actionChangeBackground) self.toolBarMain.addAction(self.actionResetBackground) self.toolBarMain.addAction(self.actionChangeLayout) self.toolBarMain.addAction(self.actionClose) self.toolBarMain.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) self.toolBarMain.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) self.toolBarLayout = QToolBar(self) self.toolBarLayout.addAction(self.actionSelectWidgets) self.toolBarLayout.addAction(self.actionResetDefaultLayout) self.toolBarLayout.addAction(self.actionChangeLayout) self.toolBarLayout.addAction(self.actionClose) self.toolBarLayout.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) self.toolBarLayout.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) self.canvas = Canvas(self) self.layoutEditor = LayoutEditor(self) self.lblTitle = QLabel(self) self.lblTitle.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) self.setLayout(QVBoxLayout()) self.layoutTop = QHBoxLayout() self.layoutTop.addWidget(self.lblTitle) self.layoutTop.addWidget(self.toolBarMain) self.layoutTop.addWidget(self.toolBarLayout) self.toolBarLayout.hide() self.layout().addLayout(self.layoutTop) self.layout().addWidget(self.canvas) self.layout().addWidget(self.layoutEditor) self.layoutEditor.hide() def loadSettings(self): settings = self.platform.getSettings() filepath = settings.value("background", "background.png") if not os.path.exists(filepath): filepath = os.path.join(os.path.dirname(__file__), filepath) if not os.path.exists(filepath): return image = QImage(filepath) self._makeBackground(image) def makeConnections(self): self.actionClose.triggered.connect(self.close) self.actionChangeLayout.triggered.connect(self.toggleLayoutEditor) self.actionChangeBackground.triggered.connect(self.changeBackground) self.actionResetBackground.triggered.connect(self.useDefaultBackground) self.actionSelectWidgets.triggered.connect(self.selectWidgets) self.actionResetDefaultLayout.triggered.connect(self.resetDefaultLayout) qApp.focusChanged.connect(self.onWindowFocusChanged) def paintEvent(self, event): painter = QPainter(self) painter.drawImage(event.rect(), self._background_image, event.rect()) def keyPressEvent(self, event): QWidget.keyPressEvent(self, event) if not event.isAccepted() and event.key() == Qt.Key_Escape: if self.layoutEditor.isVisible(): self.leaveLayoutEditor() self.actionChangeLayout.setChecked(False) else: self.close() def onWindowFocusChanged(self, old, new): "实现类似于Qt.Popup那样点击其它窗口就立即关闭本窗口的效果。" if self.isVisible() and not self.isActiveWindow(): self.close() def showEvent(self, event): settings = self.platform.getSettings() key = settings.value("globalkey", "Alt+`") if key is not None: if os.name == "nt": #在Windows系统下,Meta键习惯叫Win键 key = key.replace("Meta", "Win") title = self.trUtf8("提示:在任何位置按<b>{0}</b>打开快捷面板。").format(key) self.lblTitle.setText('<span style=" font-size:14pt;font-style:italic;">{0}</span>'.format(title)) else: title = self.trUtf8("快捷面板") self.lblTitle.setText('<span style=" font-size:14pt;font-style:italic;">{0}</span>'.format(title)) #如果有时候运行全屏程序,快捷面板的位置就会发生改变 self._makeBackground(self._background_image) moveToCenter(self) self.canvas.positWidgets() QWidget.showEvent(self, event) def showAndGetFocus(self): if not self.isVisible(): self.show() if self.windowState() & Qt.WindowMinimized: self.setWindowState(self.windowState() ^ Qt.WindowMinimized) self.raise_() if os.name == "nt": ctypes.windll.user32.BringWindowToTop(int(self.winId())) ctypes.windll.user32.SwitchToThisWindow(int(self.winId()), 1) self.activateWindow() def toggle(self): if self.isVisible(): self.hide() else: self.showAndGetFocus() def addQuickAccessShortcut(self, name, icon, callback): """ 添加一个快捷方式。有一个widget专门用于显示Besteam内部各种工具的快捷方式。 name 快捷方式的名字 icon 快捷方式的图标 callback 当用户点击快捷方式的时候调用的回调函数。不会传入任何参数。 """ self.quickAccessModel.addShortcut(name, icon, callback) def removeQuickAccessShortcut(self, name): """删除一个系统快捷方式。参数name是快捷方式的名字。""" self.quickAccessModel.removeShortcut(name) def enterLayoutEditor(self): self.layoutEditor.show() self.canvas.hide() self.toolBarLayout.show() self.toolBarMain.hide() self.layoutEditor.beginEdit(self.widgets) def leaveLayoutEditor(self): self.layoutEditor.hide() self.canvas.show() self.toolBarLayout.hide() self.toolBarMain.show() changedWidgets = self.layoutEditor.saveLayout(self.widgets) for widget in changedWidgets: conf = {} conf["left"] = widget.rect.left() conf["top"] = widget.rect.top() conf["width"] = widget.rect.width() conf["height"] = widget.rect.height() conf["enabled"] = widget.enabled conf["id"] = widget.id self.db.saveWidgetConfig(conf) if widget.enabled: self._enableWidget(widget, False) else: self._disableWidget(widget, False) self.canvas.positWidgets(True) self.layoutEditor.endEdit() def toggleLayoutEditor(self, checked): if checked: self.enterLayoutEditor() else: self.leaveLayoutEditor() def changeBackground(self): filename = QFileDialog.getOpenFileName(self, self.trUtf8("Change Background"), \ QDesktopServices.storageLocation(QDesktopServices.PicturesLocation), \ self.trUtf8("Image Files (*.png *.gif *.jpg *.jpeg *.bmp *.mng *ico)")) if filename == "": return image = QImage(filename) if image.isNull(): QMessageBox.information(self, self.trUtf8("Change Background"), \ self.trUtf8("不能读取图像文件,请检查文件格式是否正确,或者图片是否已经损坏。")) return if image.width() < 800 or image.height() < 600: answer = QMessageBox.information(self, self.trUtf8("Change Background"), \ self.trUtf8("不建议设置小于800x600的图片作为背景图案。如果继续,可能会使快捷面板显示错乱。是否继续?"), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if answer == QMessageBox.No: return self._makeBackground(image) moveToCenter(self) self.canvas.positWidgets() self.update() with self.platform.getSettings() as settings: settings.setValue("background", filename) def useDefaultBackground(self): filename = "background.png" if not os.path.exists(filename): filename = os.path.join(os.path.dirname(__file__), filename) if os.path.exists(filename): image = QImage(filename) if not image.isNull(): self._makeBackground(image) moveToCenter(self) self.canvas.positWidgets() self.update() settings = self.platform.getSettings() settings.remove("background") def _makeBackground(self, image): desktopSize = QApplication.desktop().screenGeometry(self).size() if desktopSize.width() < image.width() or desktopSize.height() < image.height(): self._background_image = image.scaled(desktopSize, Qt.KeepAspectRatio, Qt.SmoothTransformation) else: self._background_image = image self.resize(self._background_image.size()) def runDialog(self, *args, **kwargs): """ 在QuickPanel中显示一个对话框。主要是为了避免对话框显示的时候,快捷面板会隐藏。 接受两种形式的参数,其中d是对话框: runDialog(d, d.exec_) runDialog(d.exec_, *args, **kwargs) 建议使用第二种 """ if isinstance(args[0], QDialog): return self._runDialog2(args[0], args[1]) else: callback, args = args[0], args[1:] return self._runDialog3(callback, args, kwargs) def _runDialog2(self, d, callback): return self._runDialog(d, self.canvas, callback) def _runDialog3(self, callback, args, kwargs): d = callback.__self__ f = functools.partial(callback, *args, **kwargs) return self._runDialog(d, self.canvas, f) def _runDialog(self, d, container, callback): shutter = ShutterWidget(container) newPaintEvent = functools.partial(self._dialog_paintEvent, d) oldPaintEvent = d.paintEvent d.paintEvent = newPaintEvent r = d.geometry() r.moveCenter(container.rect().center()) d.setGeometry(r) d.setWindowFlags(Qt.Widget) d.setParent(container) d.setFocus(Qt.OtherFocusReason) try: shutter.show() d.raise_() return callback() finally: d.paintEvent = oldPaintEvent shutter.close() shutter.setParent(None) def _dialog_paintEvent(self, d, event): QDialog.paintEvent(d, event) pen = QPen() pen.setWidth(2) pen.setColor(QColor(200, 200, 200)) rect = d.rect() rect = rect.adjusted(0, 0, -1, -1) painter = QPainter(d) painter.setRenderHint(QPainter.Antialiasing, True) painter.setPen(pen) painter.setOpacity(0.8) painter.setBrush(QBrush(QColor(Qt.white))) painter.drawRoundedRect(rect, 15, 15)