def __init__(self, id_: str, network, graph=ig.Graph(), interactions=pd.DataFrame()): super().__init__() uic.loadUi(os.path.join(os.path.dirname(__file__), 'network.ui'), self) self.id = id_ self._name = None self._layout = None self._hide_isolated_nodes = False self._isolated_nodes = [] self._network = network self._graph = graph if isinstance(graph, ig.Graph) else ig.Graph() self._interactions = interactions if isinstance( interactions, pd.DataFrame) else pd.DataFrame() # Send Scale sliders to a toolbutton menu menu = QMenu() action = QWidgetAction(self) action.setDefaultWidget(self.sliderScale) menu.addAction(action) self.btRuler.setMenu(menu) self.view().setScene(AnnotationsNetworkScene()) if self.unlockable: self.btLock.toggled.connect(lambda x: self.scene().lock(x)) else: self.btLock.hide() self.btOptions.clicked.connect( lambda: self.editOptionsTriggered.emit(self)) self.sliderScale.valueChanged.connect(self.on_scale_changed)
def setup_menu(self): self.menu = QMenu() clock_item = QWidgetAction(self.menu) self.clock = QPushButton(' ') self.clock.setProperty('objectName', 'menu') font = self.clock.font() font.setPixelSize(CLOCK_FONT_SIZE) self.clock.setFont(font) clock_item.setDefaultWidget(self.clock) self.clock.clicked.connect(self.activate_window) exit_item = QWidgetAction(self.menu) label = QPushButton(EXIT_LABEL) label.setProperty('objectName', 'menu') exit_item.setDefaultWidget(label) label.clicked.connect(self.activate_exit) self.menu.addAction(clock_item) self.menu.addAction(exit_item) if sys.platform == 'darwin': clock_item.button = self.clock exit_item.button = label self.menu.actions = [clock_item, exit_item] self.set_up_menu_macos(self.menu)
def init_tray(self): """ Initializes the systray menu """ traymenu = QMenu("Menu") self.tray.setContextMenu(traymenu) self.tray.show() self.tray.activated.connect(self.tray_click) self.tray.setToolTip("Pomodori: "+str(self.pom.pomodori)) set_timer_tray = QLineEdit() set_timer_tray.setPlaceholderText("Set timer") set_timer_tray.textChanged.connect(lambda: self.update_timer_text(set_timer_tray.text())) traywidget = QWidgetAction(set_timer_tray) traywidget.setDefaultWidget(set_timer_tray) traymenu.addAction(traywidget) start_timer_action = QAction("&Start Timer", self) start_timer_action.triggered.connect(self.start_timer_click) traymenu.addAction(start_timer_action) exit_action = QAction("&Exit", self) exit_action.triggered.connect(QCoreApplication.instance().quit) traymenu.addAction(exit_action)
def add_smiles_toolbar(chatik): def smile_slot(img_path): chatik.textEdit.insertHtml('<img src="%s" />' % img_path) button = QToolButton(chatik) button.setText(':-)') button.setPopupMode(QToolButton.InstantPopup) menu = QMenu(button) chunks = [SMILES[x:x + 4] for x in range(0, len(SMILES), 4)] for chunk in chunks: menu_toolbar = QToolBar(menu) widget_action = QWidgetAction(menu) widget_action.setDefaultWidget(menu_toolbar) menu.addAction(widget_action) for file, title in chunk: path = SMILES_DIR + file icon = QIcon(path) action = QAction(icon, '', chatik) slot = partial(smile_slot, path) action.triggered.connect(slot) menu_toolbar.addAction(action) button.setMenu(menu) chatik.addToolBar('Smiles').addWidget(button)
def gui_setup(self): main_menu = QMenu() self.disable_suppression_menu.setEnabled(False) self.disable_suppression_menu.triggered.connect( self.disable_noise_suppression) for src in pulse.source_list(): mic_menu_item = AudioMenuItem( src.description, self.enable_suppression_menu, src.name, ) self.enable_suppression_menu.addAction(mic_menu_item) mic_menu_item.triggered.connect(self.enable_noise_suppression) self.exit_menu.triggered.connect(self.quit) main_menu.addMenu(self.enable_suppression_menu) main_menu.addAction(self.disable_suppression_menu) main_menu.addAction(self.exit_menu) # Add slider widget self.level_section = self.enable_suppression_menu.addSection( self.get_section_message()) wa = QWidgetAction(self.enable_suppression_menu) wa.setDefaultWidget(self.slider) self.enable_suppression_menu.addAction(wa) self.setIcon(self.disabled_icon) self.setContextMenu(main_menu)
def add_element(self, port_id: int, portgrp_id: int, port_name: str, is_alternate=False): if self._port_type == PORT_TYPE_AUDIO_JACK and is_alternate: port_name = "CV| %s" % port_name check_box = PortCheckBox(port_id, portgrp_id, port_name, self._port_type, self) action = QWidgetAction(self._parent) action.setDefaultWidget(check_box) if not self._portgrp_id and portgrp_id != self._last_portgrp_id: self.addSeparator() self._last_portgrp_id = portgrp_id self.addAction(action) self.elements.append({ 'port_id': port_id, 'portgrp_id': portgrp_id, 'action': action, 'check_box': check_box })
def init_items(self): self.toolbar.setObjectName("maintoolbar") self.parent.addToolBar(Qt.TopToolBarArea, self.toolbar) self.toolbar.setMovable(False) self.toolbar.addSeparator() toolbar_ctx_list = QComboBox(self.parent) toolbar_ctx_list.setDuplicatesEnabled(False) toolbar_ctx_list.setEditable(True) toolbar_ctx_list.currentIndexChanged[str].connect( lambda new_tool: self.on_toolbar_tool_changed(new_tool)) toolbar_ctx_list_action = QWidgetAction(self.parent) toolbar_ctx_list_action.setText(DEVTOOLS_COMBO_NAME) toolbar_ctx_list_action.setDefaultWidget(toolbar_ctx_list) self.toolbar.addAction(toolbar_ctx_list_action) spacer = QWidget(self.parent) spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.toolbar.addWidget(spacer) toolbar_configure_action = QAction(QIcon(":/images/configure-48.png"), "Settings", self.parent) toolbar_configure_action.triggered.connect( self.parent.config_controller.show_dialog) self.toolbar.addAction(toolbar_configure_action)
def __init__(self, parentToolBar): super().__init__() self.parentToolBar = parentToolBar self.setToolTip("Toggle item visibility") self.setMenu(QMenu(self)) self.setPopupMode(QToolButton.InstantPopup) # self.setIcon(Icon("TODO")) self.setFixedWidth(16) m = 0 mainWidget = QWidget() mainlay = QVBoxLayout() mainlay.setContentsMargins(m, m, m, m) mainWidget.setLayout(mainlay) lbl = QLabel("Set preferences for visibility") lbl.setStyleSheet("background-color: #FFFDC3; padding: 4px;") mainlay.addWidget(lbl) m = 5 self.grid = QGridLayout() self.grid.setContentsMargins(m, m, m, m) mainlay.addLayout(self.grid) self.create_widgets() widget_action = QWidgetAction(self) widget_action.setDefaultWidget(mainWidget) self.menu().addAction(widget_action)
def __init__(self, action: QAction = None, color_group=None, default_color=Qt.blue, *args, **kwargs): super().__init__(*args, **kwargs) self.last_color_action = action if action is not None else QAction( self) self._color_group = color_group dialog_action = QWidgetAction(self) self._dialog = QColorDialog(self) self.btReset = None button_box = self._dialog.findChild(QDialogButtonBox, "") if button_box is not None: self.btReset = button_box.addButton(QDialogButtonBox.Reset) self._dialog.setWindowFlags(Qt.Widget) self._dialog.setOptions(self._dialog.options() | QColorDialog.DontUseNativeDialog) dialog_action.setDefaultWidget(self._dialog) # Hide pick screen color button button = self._dialog.findChild(QAbstractButton) if button: button.hide() # Load custom colors settings = QSettings() settings.beginGroup("Colors") custom_colors = settings.value("Custom", []) for i, color in enumerate(custom_colors): self._dialog.setCustomColor(i, color) current_color = QColor(default_color) if color_group is None\ else settings.value(f"{color_group}/Current", QColor(default_color), type=QColor) if current_color.isValid(): self._dialog.setCurrentColor(current_color) self.on_color_selected(current_color) settings.endGroup() menu = QMenu() menu.addAction(dialog_action) self.setMenu(menu) self.setPopupMode(QToolButton.MenuButtonPopup) self.setDefaultAction(self.last_color_action) # Connect events self.colorSelected = self._dialog.colorSelected if self.btReset is not None: self.btReset.clicked.connect(self.colorReset.emit) self.currentColorChanged = self._dialog.currentColorChanged menu.aboutToShow.connect(self._dialog.show) self._dialog.rejected.connect(menu.hide) self._dialog.colorSelected.connect(menu.hide) self._dialog.colorSelected.connect(self.on_color_selected) self.last_color_action.triggered.connect(self.on_use_last_color)
def setup_menu_items(self): """ Setup the items listed in the menu, including a (select all) item to check or uncheck all items at once. """ self.clear() if '__select_all__' not in self._actions: checkbox = QCheckBox('(Select All)', self.parent()) checkbox.setChecked(True) checkbox.stateChanged.connect(self.handle_select_was_clicked) action = QWidgetAction(self.parent()) action.setDefaultWidget(checkbox) self._actions['__select_all__'] = action self.addAction(self._actions['__select_all__']) if self.client is not None: self.addSeparator() for item in self.items(): if item in self._actions: self.addAction(self._actions[item]) else: checkbox = QCheckBox(item, self.parent()) checkbox.setChecked(True) checkbox.stateChanged.connect(self.handle_item_was_clicked) action = QWidgetAction(self.parent()) action.setDefaultWidget(checkbox) self.addAction(action) self._actions[item] = action self.setup_select_all_item()
def __init__(self, name, linkedGraph, parent): super(InputSettingsBar, self).__init__(parent) root = QFileInfo(__file__).absolutePath() self.cmapButton = MiniGradientButton( gradient_name=linkedGraph.data[name].cmap_name) self.cmapMenuDisplay = ColormapMenu(name=name, linkedGraph=linkedGraph, parent_settings_bar=self) self.cmapButton.setMenu(QMenu(self.cmapButton)) showColormapMenu = QWidgetAction(self.cmapButton) showColormapMenu.setDefaultWidget(self.cmapMenuDisplay) self.cmapButton.menu().addAction(showColormapMenu) self.settingsButton = MiniButton(root + '/../../styles/assets/icons/cog.png', parent=self) self.deleteButton = MiniButton(root + '/../../styles/assets/icons/close.png', parent=self) self.hideButton = MiniButton(root + '/../../styles/assets/icons/eye.png', parent=self) self.plotButton = MiniButton(root + '/../../styles/assets/icons/refresh.png', parent=self) self.addWidget(self.cmapButton) self.addWidget(self.settingsButton) self.addWidget(self.deleteButton) self.addWidget(self.hideButton) self.addWidget(self.plotButton) self.setMinimumWidth(33 * 5)
def create_menu(self): _menu = QMenu() self.statsLabel = QLabel("") self.imageLabel = QLabel() self.updateImageStats() self.updateImage() label_action = QWidgetAction(self.imageLabel) label_action.setDefaultWidget(self.imageLabel) _menu.addAction(label_action) # add stats label label_action = QWidgetAction(self.statsLabel) label_action.setDefaultWidget(self.statsLabel) _menu.addAction(label_action) _menu.addSeparator() _submenu = QMenu(_menu) _submenu.setTitle("Preferences") _switch_submenu = QMenu(_submenu) _switch_submenu.setTitle("Image change action") self.onOpenAction = QAction("On Open", _switch_submenu) self.onOpenAction.setCheckable(True) self.onOpenAction.setChecked(self.configBool("config/switch_on_open")) self.onOpenAction.triggered.connect(self.onOpen) _switch_submenu.addAction(self.onOpenAction) self.onTimerAction = QAction("Every 3sec", _switch_submenu) self.onTimerAction.setCheckable(True) self.onTimerAction.setChecked( self.configBool("config/switch_every_interval")) self.onTimerAction.triggered.connect(self.onTimer) _switch_submenu.addAction(self.onTimerAction) _submenu.addMenu(_switch_submenu) self.manageDirectoryAction = QAction(self.getSourceLabel()) self.manageDirectoryAction.triggered.connect(self.manageDirectory) _submenu.addAction(self.manageDirectoryAction) self.showStockAction = QAction("Show stock images (ignore source)") self.showStockAction.setCheckable(True) self.showStockAction.setChecked(self.configBool("config/show_stock")) self.showStockAction.triggered.connect(self.showStock) _submenu.addAction(self.showStockAction) _menu.addMenu(_submenu) quiteA = QAction("Exit", _menu) quiteA.triggered.connect(self.exit_slot) _menu.addAction(quiteA) self._menu = _menu self.setContextMenu(self._menu)
def _init_rename_menu(self): rename = self.addMenu('Rename') rename_action = QWidgetAction(self) line_edit = QLineEdit(self.roi.name) line_edit.editingFinished.connect( lambda: self.roi_dict.change_name(self.key, line_edit.text())) rename_action.setDefaultWidget(line_edit) rename.addAction(rename_action)
def _createActions(self): test = QWidgetAction(self.menu) l = QLabel(self) l.setText('test') test.setDefaultWidget(ItemAction('Group')) self.menu.addAction(test) settingsAction = QAction('settings', self.menu) self.menu.addAction(settingsAction)
def addItem(self, text, checked=False): checkBox = QCheckBox(self.toolMenu) checkBox.setText(text) checkBox.setChecked(checked) checkableAction = QWidgetAction(self.toolMenu) checkableAction.setDefaultWidget(checkBox) self.toolMenu.addAction(checkableAction)
def __init_rename_menu__(self): rename = self.addMenu('Rename') rename_action = QWidgetAction(self) line_edit = QLineEdit(self.value.name) line_edit.editingFinished.connect( lambda: self.roi.send_name(line_edit.text())) rename_action.setDefaultWidget(line_edit) rename.addAction(rename_action)
def _template(): """ Peripheral action separator - generator """ _label = QLabel(getattr(self._lang, f'Action{heading}Heading')) _label.setStyleSheet('QLabel {color: gray;}') _label.setAlignment(Qt.AlignCenter) _action = QWidgetAction(None) _action.setDefaultWidget(_label) _action.setObjectName(f'{self._lang.__name__}{heading}') yield _action
def __init__(self): QWidget.__init__(self) layout = QHBoxLayout(self) self.button = QToolButton(self) self.button.setPopupMode(QToolButton.MenuButtonPopup) self.button.setMenu(QMenu(self.button)) self.textBox = QTextBrowser(self) action = QWidgetAction(self.button) action.setDefaultWidget(self.textBox) self.button.menu().addAction(action) layout.addWidget(self.button)
def __init__(self, core): super(TabButtonWidget, self).__init__() self.setText("Icon") self.setPopupMode(QToolButton.InstantPopup) self.setIcon(icon("mdi.account-circle", color="white", scale_factor=1.25)) self.setToolTip("Account") self.setIconSize(QSize(25, 25)) self.setMenu(QMenu()) action = QWidgetAction(self) action.setDefaultWidget(MiniWidget(core)) self.menu().addAction(action)
def showHeaderMenu(self, event): self.save_columns() menu = QMenu(self) header_view = HeaderEditWidget(self, self.config, menu_mode=True, parent=menu) # header_view.setFixedHeight((header_view.geometry().height()-2) * len(header_view.columns)) # box.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) action = QWidgetAction(menu) action.setDefaultWidget(header_view) menu.addAction(action) menu.exec_(QCursor.pos()) header_view.save_preset()
def toQAction(act : IAction, parent : QObject) : qact = QAction(QIcon(act.icon), act.title, parent=parent) if act.shortcut is not None: qact.setShortcut(act.shortcut) children = get().queryChildren(act.id) # action widget if act.widget : menu = QMenu() wact = QWidgetAction(menu) wact.setDefaultWidget(act.widget(menu)) menu.addAction(wact) qact.setMenu(menu) # wact.setText(act.title) # wact.setIcon(QIcon(act.icon)) return qact # single action if act.callable is not None: def cb(checked) : print(act) print(qact.text()) act.callable() qact.triggered.connect(cb) return qact # sub menu elif act.fetch is not None: menu = QMenu() qact.setMenu(menu) def fresh(): acts = act.fetch(menu) for a in acts: menu.addAction(a) menu.aboutToShow.connect(fresh) menu.aboutToHide.connect(menu.clear) return qact else : menu = QMenu() qact.setMenu(menu) for a in children: qa = toQAction(a, qact) menu.addAction(qa) return qact
def initUI(self): self.setPopupMode(QToolButton.MenuButtonPopup) self.menu = QMenu(self) self.setMenu(self.menu) self.setFixedSize(*self.BUTTON_SIZE) self.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) self.listWidget = self.createListWidget() self.listWidget.installEventFilter(self) action = QWidgetAction(self) action.setDefaultWidget(self.listWidget) self.menu.addAction(action) self.updateIcon()
def __init__(self, parent=None): super(BaseSourceView, self).__init__(parent=parent) self._shows_amazon = False self._source_table_widget = None self._product_details_widget = None self._product_links_widget = None self._selected_source = None self._last_add_list = None # Set up the source selector self.sourceBox = QComboBox(self) source_box_action = QWidgetAction(self) source_box_action.setDefaultWidget(self.sourceBox) self.sourceBox.activated.connect(self.on_source_selection_changed) self.add_toolbar_action(source_box_action) # Create the other toolbar actions self.action_reload_source = QAction(QIcon('icons/reload.png'), 'Reload', self) self.action_delete_source = QAction(QIcon('icons/delete.png'), 'Delete', self) self.action_reload_source.triggered.connect(self.reload) self.action_delete_source.triggered.connect(self.delete_source) self.add_toolbar_actions( [self.action_reload_source, self.action_delete_source]) # Create some common context menu actions self.action_add_to_list = QAction(QIcon('icons/list.png'), 'Add to list...', self) self.action_remove_from_list = QAction(QIcon('icons/delete.png'), 'Remove from list...', self) self.action_open_in_browser = QAction(QIcon('icons/internet.png'), 'Open in browser...', self) self.action_open_in_google = QAction(QIcon('icons/search_google.png'), 'Open in Google...', self) self.action_lookup_upc = QAction(QIcon('icons/barcode.png'), 'Look up UPC...', self) self.action_unlink_products = QAction(QIcon('icons/unlink.png'), 'Unlink', self) # Context menu connections self.action_add_to_list.triggered.connect(self.on_add_to_list) self.action_remove_from_list.triggered.connect( self.on_remove_from_list) self.action_unlink_products.triggered.connect(self.on_unlink_products) self.action_open_in_browser.triggered.connect(self.on_open_in_browser) self.action_open_in_google.triggered.connect(self.on_open_in_google) self.action_lookup_upc.triggered.connect(self.on_lookup_upc)
def create_perspective_ui(self): save_perspective_action = QAction("Create Perspective", self) save_perspective_action.triggered.connect(self.save_perspective) perspective_list_action = QWidgetAction(self) self.perspective_combobox = QComboBox(self) self.perspective_combobox.setSizeAdjustPolicy(QComboBox.AdjustToContents) self.perspective_combobox.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) self.perspective_combobox.activated[str].connect(self.dock_manager.openPerspective) perspective_list_action.setDefaultWidget(self.perspective_combobox) self.toolBar.addSeparator() self.toolBar.addAction(perspective_list_action) self.toolBar.addAction(save_perspective_action)
def get_header_action(parent, map_name): label = QLabel(map_name) font = label.font() font.setBold(True) label.setFont(font) label.setStyleSheet('color: black; margin:5px; margin-left: 15px;') action = QWidgetAction(parent) action.setDisabled(True) action.setDefaultWidget(label) return action
def createCheckBoxes(self): #Create checkbox data_unique = [] self.table=QTableWidget() self.table.setColumnCount(1) self.table.verticalHeader().hide() self.table.horizontalHeader().hide() self.table.horizontalHeader().setStretchLastSection(True) self.table.setRowCount(self.rowCount()) #Assign the action a create the list of checkbox self.checkBoxs = [] checkBox = QCheckBox("Seleccionar todo", self.menu) checkableAction = QWidgetAction(self.menu) checkableAction.setDefaultWidget(checkBox) self.menu.addAction(checkableAction) checkBox.setChecked(Qt.Checked) checkBox.stateChanged.connect(self.slotSelect) j=0 for i in range(self.rowCount()): if not self.isRowHidden(i): item = self.item(i, self.col ) if item.text() not in data_unique: data_unique.append(item.text()) it = QTableWidgetItem(item.text()) it.setFlags(Qt.ItemIsUserCheckable |Qt.ItemIsEnabled) it.setCheckState(Qt.Checked) self.checkBoxs.append(it) j=j+1 #Sort the element of the list self.checkBoxs=sorted(self.checkBoxs, key=lambda it: it.text()) # self.sort(self.checkBoxs[i]) j=0 for i in range(len(self.checkBoxs)): #print(self.checkBoxs[i].text()) self.table.setItem(j,0, self.checkBoxs[i]) j=j+1 self.table.update() self.table.setRowCount(len(self.checkBoxs)) checkableAction = QWidgetAction(self.menu) checkableAction.setDefaultWidget(self.table) self.menu.addAction(checkableAction)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setPopupMode(QToolButton.MenuButtonPopup) self.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) self.tree = QTreeView(self) self.tree.setMinimumWidth(640) self.tree.setSelectionMode(QTreeView.SingleSelection) self.tree.setSelectionBehavior(QTreeView.SelectRows) act = QWidgetAction(self) act.setDefaultWidget(self.tree) self.menu = QMenu(self) self.menu.addAction(act) self.setMenu(self.menu) self.clicked.connect(self.showMenu)
def __init__(self, view, sigma: float = 3): super().__init__(view) self._use_clahe = True self.slider = LabeledSlider('Clip sigma factor', bounds=(0.001, 4), value=sigma, parent=self) self.slider.valueChanged.connect(self.sigSigmaChanged.emit) self.addAction('Set range as default', lambda *x: self.sigRangeAsDefault.emit()) self.clahe_action = self.addAction('Disable CLAHE', self._use_clahe_changed) self.sigma_factor_menu = self.addMenu('Set sigma factor') action = QWidgetAction(self) action.setDefaultWidget(self.slider) self.sigma_factor_menu.addAction(action)
def create_menu(self): _menu = QMenu() self.label = QLabel(self.formatStatus()) self.label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.label.setAlignment(Qt.AlignmentFlag.AlignCenter) self.label.setObjectName("status_text") if self.last_theme == "dark": self.label.setStyleSheet("QLabel {color: white;}") label_action = QWidgetAction(self.label) label_action.setDefaultWidget(self.label) _menu.addAction(label_action) _menu.addSeparator() _submenu = QMenu(_menu) _submenu.setTitle("Preferences") invert = QAction("⇆ Invert", _submenu) invert.triggered.connect(self.invert) invert.setShortcut("Ctrl+I") _submenu.addAction(invert) self.launchAtLogin = QAction("Launch At Login", _submenu) self.launchAtLogin.setCheckable(True) config_value = self.config.value("config/start_at_login") if config_value: config_value = True else: config_value = False self.launchAtLogin.setChecked(config_value) self.launchAtLogin.triggered.connect(self.launchAtLoginAction) _submenu.addAction(self.launchAtLogin) _menu.addMenu(_submenu) quiteA = QAction("Exit", _menu) quiteA.triggered.connect(self.exit_slot) _menu.addAction(quiteA) self._menu = _menu self.setContextMenu(self._menu)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._undo_stack = QUndoStack(self) self._undo_view = QUndoView(self._undo_stack) self._undo_view.setCleanIcon(QIcon(":/icons/images/document-save.svg")) self._undo_menu = QMenu(self) action = QWidgetAction(self._undo_menu) action.setDefaultWidget(self._undo_view) self._undo_menu.addAction(action) self._orig_point = None self._item_to_draw = None self._item_old_pos = None self._item_old_line_or_rect = None self._mode = None self._dialog = None self.setDragMode(QGraphicsView.RubberBandDrag)
def rightMenuShow(self): try: self.contextMenu = QMenu() self.contextMenu.setFont(fontawesome("far")) index_action = QWidgetAction() index_button = QPushButton(unichr(0xf015), # clicked=self.zoom_out_func, font=fontawesome("far"), ) index_button.setToolTip("主页") index_button.setCursor(Qt.ArrowCursor) index_action.setDefaultWidget(index_button) self.actionA = self.contextMenu.addAction(index_action) self.contextMenu.popup(QCursor.pos()) # 2菜单显示的位置 # self.actionA.triggered.connect(self.actionHandler) self.contextMenu.show() except Exception as e: print(e)
def menu_linestyle_entry_generator(pen_style=Qt.SolidLine, width=2, parent=None, color=QColor(246, 116, 0)): """return QWidgetAction with QLabel widget as main widget where it is displaying sample line painted with provided pen_style and width""" menu_entry = QWidgetAction(parent) label = QLabel(parent) pix = QPixmap(74, 24) pix.fill(Qt.transparent) painter = QPainter(pix) pen = QPen(color, width, pen_style) painter.setPen(pen) painter.drawLine(5, 12, 75, 12) # ForegroundNeutral painter.end() label.setPixmap(pix) menu_entry.setDefaultWidget(label) menu_entry.pen = pen # this attribute will hold the style return menu_entry
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setPopupMode(QToolButton.MenuButtonPopup) self.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) self.widget = FrameSelectWidget(self) self.widget.okayBtn.clicked.connect(self._handleOKClicked) self.widget.cancelBtn.clicked.connect(self._handleCancelClicked) act = QWidgetAction(self) act.setDefaultWidget(self.widget) self.menu = QMenu(self) self.menu.addAction(act) self.setMenu(self.menu) self.clicked.connect(self.showMenu) self.setFrameSource(None, None) self.setFrameSelection((0, 0))
def TitledMenu(titles, padding=5, with_separator=True): """ :param title: the title for menu :param padding: the padding defaults to 5 px :param with_separator: if true adds a separator :return: the QMenu with a title """ menu = QMenu() for title in titles: label = QLabel(title) label.setStyleSheet("padding: {}px; background-color: rgba(0, 0, 0, 0);".format(padding)) title_widget = QWidgetAction(menu) title_widget.setDefaultWidget(label) menu.addAction(title_widget) if with_separator: menu.addSeparator() return menu
def on_view_horizontalHeader_sectionClicked(self, index): self.menu = QMenu(self) self.col = index self.createCheckBoxes() #Accept and cancel button btn = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self.menu) btn.accepted.connect(self.menuClose) btn.rejected.connect(self.menu.close) checkableAction = QWidgetAction(self.menu) checkableAction.setDefaultWidget(btn) self.menu.addAction(checkableAction) ##Clear Button btnClr = QPushButton(QIcon(),"Limpiar Filtro", self.menu) btnClr.clicked.connect(self.clearFilter) checkableAction = QWidgetAction(self.menu) checkableAction.setDefaultWidget(btnClr) self.menu.addAction(checkableAction) headerPos = self.mapToGlobal(self.horizontalHeader().pos()) posY = headerPos.y() + self.horizontalHeader().height() posX = headerPos.x() + self.horizontalHeader().sectionPosition(index) self.menu.exec_(QPoint(posX, posY))
class StaticPlot(vip_base): """ style_codes: 0 : QtCore.Qt.SolidLine, 1 : QtCore.Qt.DashDotDotLine, 2 : QtCore.Qt.DashDotLine, 3 : QtCore.Qt.DashLine, 4 : QtCore.Qt.DotLine color_codes: 0 : (255, 255, 255), 1 : (255, 0 , 0 ), 2 : (0 , 255, 0 ), 3 : (0 , 0 , 255), 4 : (100, 100, 100) """ def __init__(self): super(StaticPlot, self).__init__() """ Function init :param config: :return: """ self.__colors_selected__ = [] self.__styles_selected__ = [] self.__show_grid_x__ = None self.__show_grid_y__ = None self.__parameters__ = {} self.__plotWidget__ = None self.__legend__ = None self.styles = { 0: QtCore.Qt.SolidLine, 1: QtCore.Qt.DashDotDotLine, 2: QtCore.Qt.DashDotLine, 3: QtCore.Qt.DashLine, 4: QtCore.Qt.DotLine } self.colors = { 0: (255, 255, 255), 1: (255, 0, 0 ), 2: (0, 255, 0 ), 3: (0, 0, 255), 4: (100, 100, 100) } def cb_initialize_plugin(self): """ Function initiate layer 0 :param config: :return: """ self.config = self.pl_get_current_config_ref() # --------------------------- # Read configuration # --------------------------- int_re = re.compile(r'(\d+)') self.__show_grid_x__ = self.config['x-grid']['value'] == '1' self.__show_grid_y__ = self.config['y-grid']['value'] == '1' self.__colors_selected__ = int_re.findall(self.config['color']['value']) self.__styles_selected__ = int_re.findall(self.config['style']['value']) # ---------------------------- # Set internal variables used for single timestamp plotting (stp) # ---------------------------- self.__plotWidget__ = pg.PlotWidget() self.__plotWidget__.setWindowTitle('StaticPlot') self.__plotWidget__.showGrid(x=self.__show_grid_x__, y=self.__show_grid_y__) self.__plotWidget__.getPlotItem().getViewBox().disableAutoRange() self.__plotWidget__.getPlotItem().getViewBox().setYRange(0,6) self.pl_set_widget_for_internal_usage(self.__plotWidget__) # --------------------------- # Create Parameters # --------------------------- self.__parameters__['x-grid'] = \ DParameter('x-grid', '[0 1]', Regex='^(1|0){1}$') self.__parameters__['y-grid'] = \ DParameter('y-grid', '[0 1]', Regex='^(1|0){1}$') self.__parameters__['color'] = \ DParameter('color', self.config['color']['value'], Regex='^\[(\s*\d\s*)+\]') self.__parameters__['style'] = \ DParameter('style', self.config['style']['value'], Regex='^\[(\s*\d\s*)+\]') self.__parameters__['yRange'] = \ DParameter('yRange', '[0,1]', Regex='^\[(\d+\.\d+)\s+(\d+\.\d+)\]$') self.pl_send_new_parameter_list(list(self.__parameters__.values())) # --------------------------- # Create Legend # --------------------------- if self.config['show_legend']['value']=='1': self.__legend__ = pg.LegendItem((100, 40), offset=(40, 1)) # args are (size, offset) self.__legend__.setParentItem(self.__plotWidget__.graphicsItem()) self.setup_context_menu() self.__plotWidget__.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.__plotWidget__.customContextMenuRequested.connect(self.showContextMenu) self.read_json_data() return True def cb_pause(self): """ Function pause :return: """ pass def cb_resume(self): """ Function resume :return: """ pass def cb_execute(self, Data=None, block_name = None, plugin_uname = None): """ Function cb_execute :param **kwargs: :param Data: :param block_name: :return: """ pass def cb_set_parameter(self, name, value): """ Function set parameters :param name: :param value: :return: """ if name == 'x-grid': self.config['x-grid']['value'] = value self.__plotWidget__.showGrid(x=value == '1') self.xGrid_Checkbox.setChecked(value=='1') if name == 'y-grid': self.config['y-grid']['value'] = value self.__plotWidget__.showGrid(y=value == '1') self.yGrid_Checkbox.setChecked(value=='1') if name == 'color': self.clear() self.config['color']['value'] = value int_re = re.compile(r'(\d+)') self.__colors_selected__ = int_re.findall(self.config['color']['value']) if name == 'style': self.clear() self.config['style']['value'] = value int_re = re.compile(r'(\d+)') self.__styles_selected__ = int_re.findall(self.config['style']['value']) if name == 'yRange': self.use_range_for_y(value) if name == 'xRange': self.use_range_for_x(value) def read_json_data(self): json_str = self.config['json_data']['value'] axis_id = self.config['axis_identifier']['value'] data = json.loads(json_str) self.plot_data(data, axis_id) def plot_data(self, data, axis_id): """ Function update_plot_single_timestamp :return: """ self.clear() tdata = data[axis_id] x_min = min(tdata) x_max = max(tdata) y_min = None y_max = None counter = 0 for signal_name in data: if signal_name != axis_id: signal_data = data[signal_name] if y_max is not None: y_max = max(max(signal_data), y_max) else: y_max = max(signal_data) if y_min is not None: y_min = min(min(signal_data), y_min) else: y_min = min(signal_data) pen = self.get_pen(counter) graphic = GraphicItem(np.array(tdata), np.array(signal_data), 0, pen=pen) self.__plotWidget__.addItem(graphic) if self.__legend__ is not None: data_item = pg.PlotDataItem() data_item.setPen(pen) self.__legend__.addItem(data_item, signal_name) counter += 1 self.use_range_for_x("[{:2.2f} {:2.2f}]".format(x_min, x_max)) self.use_range_for_y("[{:2.2f} {:2.2f}]".format(y_min, y_max)) # self.__plotWidget__.getPlotItem().getViewBox().setXRange(x_min, x_max) def cb_plugin_meta_updated(self): """ This function is called whenever meta information are changed. This enables the plot to handle more than one input for plotting. :return: """ pass def get_pen(self, index): """ Function get pen :param index: :return: """ index = int(index) style_index = index % len(self.__styles_selected__) style_code = int(self.__styles_selected__[style_index]) color_index = index % len(self.__colors_selected__) color_code = int(self.__colors_selected__[color_index]) if style_code in self.styles: style = self.styles[style_code] else: style = self.styles[0] if color_code in self.colors: color = self.colors[color_code] else: color = self.colors[0] return pg.mkPen(color=color, style=style) def use_range_for_x(self, value): """ :param value: :return: """ reg = re.compile(r'(\d+\.\d+)') range = reg.findall(value) if len(range) == 2: self.__plotWidget__.getPlotItem().getViewBox().setXRange(float(range[0]),float(range[1])) def use_range_for_y(self, value): """ :param value: :return: """ reg = re.compile(r'([-]{0,1}\d+\.\d+)') range = reg.findall(value) if len(range) == 2: self.__plotWidget__.getPlotItem().getViewBox().setYRange(float(range[0]), float(range[1])) def setup_context_menu(self): """ :return: """ self.custMenu = QMenu("Options") self.gridMenu = QMenu('Grid') # Grid Menu: # ----------------------------------------------------------- # Y-Grid checkbox self.xGrid_Checkbox = QCheckBox() self.xGrid_Checkbox.stateChanged.connect(self.contextMenu_xGrid_toogle) self.xGrid_Checkbox.setText('X-Grid') self.xGrid_Action = QWidgetAction(self.__plotWidget__) self.xGrid_Action.setDefaultWidget(self.xGrid_Checkbox) self.gridMenu.addAction(self.xGrid_Action) # Check config for startup state if self.__show_grid_x__: self.xGrid_Checkbox.setChecked(True) # X-Grid checkbox self.yGrid_Checkbox = QCheckBox() self.yGrid_Checkbox.stateChanged.connect(self.contextMenu_yGrid_toogle) self.yGrid_Checkbox.setText('Y-Grid') self.yGrid_Action = QWidgetAction(self.__plotWidget__) self.yGrid_Action.setDefaultWidget(self.yGrid_Checkbox) self.gridMenu.addAction(self.yGrid_Action) # Check config for startup state if self.__show_grid_y__: self.yGrid_Checkbox.setChecked(True) # add Menus self.custMenu.addMenu(self.gridMenu) self.__plotWidget__.getPlotItem().getViewBox().menu.clear() self.__plotWidget__.getPlotItem().ctrlMenu = [self.pl_create_control_context_menu(), self.custMenu] def showContextMenu(self): self.setup_context_menu() def contextMenu_xGrid_toogle(self): if self.xGrid_Checkbox.isChecked(): self.control_api.do_set_parameter(self.__id__, 'x-grid', '1') else: self.control_api.do_set_parameter(self.__id__, 'x-grid', '0') def contextMenu_yGrid_toogle(self): if self.yGrid_Checkbox.isChecked(): self.control_api.do_set_parameter(self.__id__, 'y-grid', '1') else: self.control_api.do_set_parameter(self.__id__, 'y-grid', '0') def contextMenu_yRange_toogle(self): mi = self.yRange_minEdit.text() ma = self.yRange_maxEdit.text() if float(mi) < float(ma): self.control_api.do_set_parameter(self.__id__, 'yRange', '[' + float(mi) + ' ' + float(ma) + ']') def cb_quit(self): """ Function quit plugin :return: """ print('StaticPlot: will quit') def cb_get_plugin_configuration(self): """ Function get plugin configuration :return {}: """ config = { 'json_data' : { 'value' : '{"v1": [5, 6, 7, 8, 9 ], "v2": [ 0, 1, 2, 3, 4 ], ' '"v3": [ -5, -6, -7, -8, -9 ], "v4": [ 0, -1, -2, -3, -4 ], ' '"t": [ 0, 1, 2, 3, 4 ]}', 'tooltip' : 'Used as data source. Format: { "time" : [...], "y1" : [...], "y2" : [...]}' }, 'axis_identifier' : { 'value' : 't', 'tooltip' : 'Used to specify the identifier for the X-Axis e.g. time in json_data' }, 'show_legend' : { 'value' : pc.REGEX_BOOL_BIN, 'type' : pc.CFG_TYPE_BOOL }, 'x-grid': { 'value': "0", 'regex': pc.REGEX_BOOL_BIN, 'type': pc.CFG_TYPE_BOOL, 'display_text': 'Grid-X' }, 'y-grid': { 'value': "0", 'regex': pc.REGEX_BOOL_BIN, 'type': pc.CFG_TYPE_BOOL, 'display_text': 'Grid-Y' }, 'color': { 'value': "[0 1 2 3 4]", 'regex': '^\[(\s*\d\s*)+\]', 'advanced': '1', 'display_text': 'Color' }, 'style': { 'value': "[0 0 0 0 0]", 'regex': '^\[(\s*\d\s*)+\]', 'advanced': '1', 'display_text': 'Style' } } # http://www.regexr.com/ return config def clear(self): """ :return: """ self.__plotWidget__.clear()
def makePopupMenu(self): index = self.currentIndex() sel = self.getSelection() clipboard = qApp.clipboard() menu = QMenu(self) # Get index under cursor pos = self.viewport().mapFromGlobal(QCursor.pos()) mouseIndex = self.indexAt(pos) # Get index's title if mouseIndex.isValid(): title = mouseIndex.internalPointer().title() elif self.rootIndex().parent().isValid(): # mouseIndex is the background of an item, so we check the parent mouseIndex = self.rootIndex().parent() title = mouseIndex.internalPointer().title() else: title = qApp.translate("outlineBasics", "Root") if len(title) > 25: title = title[:25] + "…" # Open Item action self.actOpen = QAction(QIcon.fromTheme("go-right"), qApp.translate("outlineBasics", "Open {}".format(title)), menu) self.actOpen.triggered.connect(self.openItem) menu.addAction(self.actOpen) # Open item(s) in new tab if mouseIndex in sel and len(sel) > 1: actionTitle = qApp.translate("outlineBasics", "Open {} items in new tabs").format(len(sel)) self._indexesToOpen = sel else: actionTitle = qApp.translate("outlineBasics", "Open {} in a new tab").format(title) self._indexesToOpen = [mouseIndex] self.actNewTab = QAction(QIcon.fromTheme("go-right"), actionTitle, menu) self.actNewTab.triggered.connect(self.openItemsInNewTabs) menu.addAction(self.actNewTab) menu.addSeparator() # Add text / folder self.actAddFolder = QAction(QIcon.fromTheme("folder-new"), qApp.translate("outlineBasics", "New &Folder"), menu) self.actAddFolder.triggered.connect(self.addFolder) menu.addAction(self.actAddFolder) self.actAddText = QAction(QIcon.fromTheme("document-new"), qApp.translate("outlineBasics", "New &Text"), menu) self.actAddText.triggered.connect(self.addText) menu.addAction(self.actAddText) menu.addSeparator() # Copy, cut, paste, duplicate self.actCut = QAction(QIcon.fromTheme("edit-cut"), qApp.translate("outlineBasics", "C&ut"), menu) self.actCut.triggered.connect(self.cut) menu.addAction(self.actCut) self.actCopy = QAction(QIcon.fromTheme("edit-copy"), qApp.translate("outlineBasics", "&Copy"), menu) self.actCopy.triggered.connect(self.copy) menu.addAction(self.actCopy) self.actPaste = QAction(QIcon.fromTheme("edit-paste"), qApp.translate("outlineBasics", "&Paste"), menu) self.actPaste.triggered.connect(self.paste) menu.addAction(self.actPaste) # Rename / duplicate / remove items self.actDelete = QAction(QIcon.fromTheme("edit-delete"), qApp.translate("outlineBasics", "&Delete"), menu) self.actDelete.triggered.connect(self.delete) menu.addAction(self.actDelete) self.actRename = QAction(QIcon.fromTheme("edit-rename"), qApp.translate("outlineBasics", "&Rename"), menu) self.actRename.triggered.connect(self.rename) menu.addAction(self.actRename) menu.addSeparator() # POV self.menuPOV = QMenu(qApp.translate("outlineBasics", "Set POV"), menu) mw = mainWindow() a = QAction(QIcon.fromTheme("dialog-no"), qApp.translate("outlineBasics", "None"), self.menuPOV) a.triggered.connect(lambda: self.setPOV("")) self.menuPOV.addAction(a) self.menuPOV.addSeparator() menus = [] for i in [qApp.translate("outlineBasics", "Main"), qApp.translate("outlineBasics", "Secondary"), qApp.translate("outlineBasics", "Minor")]: m = QMenu(i, self.menuPOV) menus.append(m) self.menuPOV.addMenu(m) mpr = QSignalMapper(self.menuPOV) for i in range(mw.mdlCharacter.rowCount()): a = QAction(mw.mdlCharacter.icon(i), mw.mdlCharacter.name(i), self.menuPOV) a.triggered.connect(mpr.map) mpr.setMapping(a, int(mw.mdlCharacter.ID(i))) imp = toInt(mw.mdlCharacter.importance(i)) menus[2 - imp].addAction(a) mpr.mapped.connect(self.setPOV) menu.addMenu(self.menuPOV) # Status self.menuStatus = QMenu(qApp.translate("outlineBasics", "Set Status"), menu) # a = QAction(QIcon.fromTheme("dialog-no"), qApp.translate("outlineBasics", "None"), self.menuStatus) # a.triggered.connect(lambda: self.setStatus("")) # self.menuStatus.addAction(a) # self.menuStatus.addSeparator() mpr = QSignalMapper(self.menuStatus) for i in range(mw.mdlStatus.rowCount()): a = QAction(mw.mdlStatus.item(i, 0).text(), self.menuStatus) a.triggered.connect(mpr.map) mpr.setMapping(a, i) self.menuStatus.addAction(a) mpr.mapped.connect(self.setStatus) menu.addMenu(self.menuStatus) # Labels self.menuLabel = QMenu(qApp.translate("outlineBasics", "Set Label"), menu) mpr = QSignalMapper(self.menuLabel) for i in range(mw.mdlLabels.rowCount()): a = QAction(mw.mdlLabels.item(i, 0).icon(), mw.mdlLabels.item(i, 0).text(), self.menuLabel) a.triggered.connect(mpr.map) mpr.setMapping(a, i) self.menuLabel.addAction(a) mpr.mapped.connect(self.setLabel) menu.addMenu(self.menuLabel) menu.addSeparator() # Custom icons if self.menuCustomIcons: menu.addMenu(self.menuCustomIcons) else: self.menuCustomIcons = QMenu(qApp.translate("outlineBasics", "Set Custom Icon"), menu) a = QAction(qApp.translate("outlineBasics", "Restore to default"), self.menuCustomIcons) a.triggered.connect(lambda: self.setCustomIcon("")) self.menuCustomIcons.addAction(a) self.menuCustomIcons.addSeparator() txt = QLineEdit() txt.textChanged.connect(self.filterLstIcons) txt.setPlaceholderText("Filter icons") txt.setStyleSheet("QLineEdit { background: transparent; border: none; }") act = QWidgetAction(self.menuCustomIcons) act.setDefaultWidget(txt) self.menuCustomIcons.addAction(act) self.lstIcons = QListWidget() for i in customIcons(): item = QListWidgetItem() item.setIcon(QIcon.fromTheme(i)) item.setData(Qt.UserRole, i) item.setToolTip(i) self.lstIcons.addItem(item) self.lstIcons.itemClicked.connect(self.setCustomIconFromItem) self.lstIcons.setViewMode(self.lstIcons.IconMode) self.lstIcons.setUniformItemSizes(True) self.lstIcons.setResizeMode(self.lstIcons.Adjust) self.lstIcons.setMovement(self.lstIcons.Static) self.lstIcons.setStyleSheet("background: transparent; background: none;") self.filterLstIcons("") act = QWidgetAction(self.menuCustomIcons) act.setDefaultWidget(self.lstIcons) self.menuCustomIcons.addAction(act) menu.addMenu(self.menuCustomIcons) # Disabling stuff if not clipboard.mimeData().hasFormat("application/xml"): self.actPaste.setEnabled(False) if len(sel) == 0: self.actCopy.setEnabled(False) self.actCut.setEnabled(False) self.actRename.setEnabled(False) self.actDelete.setEnabled(False) self.menuPOV.setEnabled(False) self.menuStatus.setEnabled(False) self.menuLabel.setEnabled(False) self.menuCustomIcons.setEnabled(False) if len(sel) > 1: self.actRename.setEnabled(False) return menu
def __evt_yeahdoc_contextMenu(self, p): """ context menu """ item = self.yeahdoclisttree.currentItem() if item == None or item.isDisabled(): pass else: menu = QMenu() # menu top action = QWidgetAction(self) title = item.text(0) if len(title) < 25: for i in range(len(title), 25): title = title + " " action.setDefaultWidget( QLabel(" <img src='%s'/> %s" % (getPath("iconDir", "yeahdoc/item.png"), title))) menu.addAction(action) menu.addSeparator() menu.addAction(self.__actions["__yeahdoc_open__"]) menu.addAction(self.__actions["__yeahdoc_edit__"]) # change class change_class_menu = QMenu() entry = YeahdocDatasSupply().bb_read1_simple(item.getMark()) current_categoryid = entry['categoryid'] for class_item in YeahdocDatasSupply().bc_list(): action = QAction(class_item["title"], self, \ triggered=lambda re, item=item, categoryid=str(class_item["id"]): \ self.__evt_change_category(categoryid, item)) action.setIcon(QIcon(getPath("iconDir", "yeahdoc/flag/%s" % str(class_item["img"])))) action.setIconVisibleInMenu(True) # mark current class id menu checked if class_item['id'] == current_categoryid: action.setCheckable(True) action.setChecked(True) action.setDisabled(True) change_class_menu.addAction(action) action = QAction(QIcon(getPath("iconDir", "yeahdoc/change.png")), QApplication.translate("YeahdocList", "Change Category"), self) action.setIconVisibleInMenu(True) action.setMenu(change_class_menu) menu.addAction(action) menu.addAction(self.__actions["__yeahdoc_star__"]) menu.addAction(self.__actions["__yeahdoc_rename__"]) menu.addAction(self.__actions["__yeahdoc_delete__"]) menu.addSeparator() setmode = True if entry['lock'] == 0 else False action = QWidgetAction(self) widget = QWidget() layout = QHBoxLayout() layout.setSpacing(0) layout.setMargin(0) widget.setLayout(layout) widgetMore = QWidget() widgetMore.setVisible(False) layoutMore = QHBoxLayout() layoutMore.setSpacing(0) layoutMore.setMargin(0) widgetMore.setLayout(layoutMore) layout.addWidget(QLabel("<img src='%s'/>" % getPath("iconDir", "yeahdoc/password.png"))) passwordMore = QPushButton( QApplication.translate("YeahdocEditor", "Encrypt") if setmode else QApplication.translate( "YeahdocEditor", "Decrypt")) passwordMore.setFlat(True) layout.addWidget(passwordMore) passwordInput = QLineEdit() passwordInput.setEchoMode(QLineEdit.Password) passwordInput.setMaximumWidth(70) layoutMore.addWidget(passwordInput) if setmode: passwordInputAgain = QLineEdit() passwordInputAgain.setEchoMode(QLineEdit.Password) passwordInputAgain.setMaximumWidth(70) layoutMore.addWidget(QLabel(QApplication.translate("YeahdocEditor", "Re"))) layoutMore.addWidget(passwordInputAgain) passwordSubmit = QPushButton("OK") passwordSubmit.setFlat(True) layoutMore.addWidget(passwordSubmit) layout.addWidget(widgetMore) layout.addItem(QSpacerItem(0, 20, QSizePolicy.Expanding, QSizePolicy.Expanding)) action.setDefaultWidget(widget) QObject.connect(passwordSubmit, SIGNAL("clicked ()"), lambda: self.__evt_password(setmode, passwordInput.text(), passwordInputAgain.text() if setmode else "")) QObject.connect(passwordMore, SIGNAL("clicked ()"), lambda: widgetMore.setVisible(not widgetMore.isVisible())) menu.addAction(action) # show it. menu.exec_(self.mapToGlobal(self.yeahdoclisttree.mapTo(self, p)))
class Plot(vip_base): """ style_codes: 0 : QtCore.Qt.SolidLine, 1 : QtCore.Qt.DashDotDotLine, 2 : QtCore.Qt.DashDotLine, 3 : QtCore.Qt.DashLine, 4 : QtCore.Qt.DotLine color_codes: 0 : (255, 255, 255), 1 : (255, 0 , 0 ), 2 : (0 , 255, 0 ), 3 : (0 , 0 , 255), 4 : (100, 100, 100) """ def __init__(self, debug=False): super(Plot, self).__init__() """ Function init :param config: :return: """ self.signals = {} self.__papi_debug__ = debug self.__buffer_size__ = None self.__downsampling_rate__ = 1 self.__tbuffer__ = [] self.__signals_have_same_length = True self.__append_at__ = 1 self.__new_added_data__ = 0 self.__input_size__ = 0 self.__rolling_plot__ = False self.__colors_selected__ = [] self.__styles_selected__ = [] self.__show_grid_x__ = None self.__show_grid_y__ = None self.__parameters__ = {} self.__update_intervall__ = None self.__last_time__ = None self.__last_plot_time__ = None self.__plotWidget__ = None self.__legend__ = None self.__stp_min_x = None self.__stp_max_x = None self.__stp_min_y = None self.__stp_max_y = None self.__stp_active__ = None self.__downsampling_rate_start__ = None; self.__downsampling_rate__ = None self.styles = { 0: QtCore.Qt.SolidLine, 1: QtCore.Qt.DashDotDotLine, 2: QtCore.Qt.DashDotLine, 3: QtCore.Qt.DashLine, 4: QtCore.Qt.DotLine } self.colors = { 0: (255, 255, 255), 1: (255, 0, 0 ), 2: (0, 255, 0 ), 3: (0, 0, 255), 4: (100, 100, 100) } def cb_initialize_plugin(self): """ Function initiate layer 0 :param config: :return: """ self.config = self.pl_get_current_config_ref() # --------------------------- # Read configuration # --------------------------- int_re = re.compile(r'(\d+)') self.__show_legend__ = self.config['show_legend']['value'] == '1' self.__show_grid_x__ = self.config['x-grid']['value'] == '1' self.__show_grid_y__ = self.config['y-grid']['value'] == '1' self.__rolling_plot__ = self.config['rolling_plot']['value'] == '1' self.__colors_selected__ = int_re.findall(self.config['color']['value']) self.__styles_selected__ = int_re.findall(self.config['style']['value']) self.__buffer_size__ = int(int_re.findall(self.config['buffersize']['value'])[0]) self.__downsampling_rate__ = int(int_re.findall(self.config['downsampling_rate']['value'])[0]) self.__downsampling_rate_start__ = 0 # ---------------------------- # Set internal variables # ---------------------------- self.__tbuffer__ = collections.deque([0.0] * 0, self.__buffer_size__) # ---------------------------- # Set internal variables used for single timestamp plotting (stp) # ---------------------------- self.__stp_min_x = 0 self.__stp_max_x = 0 self.__stp_min_y = 0 self.__stp_max_y = 1 self.__stp_active__ = False # -------------------------------- # Create Layout and labels # -------------------------------- self.central_widget = QWidget() self.central_widget.setContentsMargins(0,0,0,0) self.label_widget = QWidget() self.label_widget.setContentsMargins(0,0,0,0) self.verticalLayout = QVBoxLayout() self.verticalLayout.setContentsMargins(0,0,0,0) self.verticalLayout.setSpacing(0) self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setContentsMargins(0,0,0,0) self.horizontalLayout.setSpacing(0) self.space_label = QLabel() self.space_label.setMargin(0) self.space_label.setAlignment(QtCore.Qt.AlignJustify) self.space_label.setStyleSheet("QLabel { background-color : black; color : grey;" "border : 0px solid black ; border-bottom-width : 5px }") self.time_label = QLabel() self.time_label.setMargin(0) self.time_label.setAlignment(QtCore.Qt.AlignJustify) self.time_label.setStyleSheet("QLabel { background-color : black; color : grey;" "border : 0px solid black ; border-bottom-width : 5px }") self.time_label.setMaximumWidth(55) self.unit_label = QLabel() self.unit_label.setMargin(0) self.unit_label.setAlignment(QtCore.Qt.AlignLeft) self.unit_label.setStyleSheet("QLabel { background-color : black; color : grey;" "border : 0px solid black ; border-bottom-width : 5px }") self.unit_label.setText('[s]') self.central_widget.setLayout(self.verticalLayout) self.label_widget.setLayout(self.horizontalLayout) # -------------------------------- # Create PlotWidget # -------------------------------- self.__plotWidget__ = PlotWidget() self.__plotWidget__.yRangeChanged.connect(self.plot_yrange_changed) self.__plotWidget__.setWindowTitle('PlotPerformanceTitle') self.__plotWidget__.showGrid(x=self.__show_grid_x__, y=self.__show_grid_y__) self.__plotWidget__.getPlotItem().getViewBox().disableAutoRange() self.__plotWidget__.getPlotItem().getViewBox().setYRange(0,6) self.__plotWidget__.getPlotItem().setDownsampling(auto=True) # ------------------------------ # Add Widget to Layout # ------------------------------ self.horizontalLayout.addWidget(self.space_label) self.horizontalLayout.addWidget(self.time_label) self.horizontalLayout.addWidget(self.unit_label) self.verticalLayout.addWidget(self.__plotWidget__) self.verticalLayout.addWidget(self.label_widget) if not self.__papi_debug__: # self.pl_set_widget_for_internal_usage(self.__plotWidget__) self.pl_set_widget_for_internal_usage(self.central_widget) self.__plotWidget__.getPlotItem().getViewBox().enableAutoRange(axis=pg.ViewBox.YAxis, enable=False) self.__plotWidget__.getPlotItem().getViewBox().enableAutoRange(axis=pg.ViewBox.XAxis, enable=False) self.__plotWidget__.getPlotItem().getViewBox().setMouseEnabled(x=False, y=True) # --------------------------- # Create Parameters # --------------------------- self.__parameters__['x-grid'] = \ DParameter('x-grid', self.config['x-grid']['value'], Regex='^(1|0){1}$') self.__parameters__['y-grid'] = \ DParameter('y-grid', self.config['y-grid']['value'], Regex='^(1|0){1}$') self.__parameters__['color'] = \ DParameter('color', self.config['color']['value'], Regex='^\[(\s*\d\s*)+\]') self.__parameters__['style'] = \ DParameter('style', self.config['style']['value'], Regex='^\[(\s*\d\s*)+\]') self.__parameters__['rolling'] = \ DParameter('rolling', self.config['rolling_plot']['value'], Regex='^(1|0){1}') self.__parameters__['downsampling_rate'] = \ DParameter('downsampling_rate', self.__downsampling_rate__, Regex='^\d+$') self.__parameters__['buffersize'] = \ DParameter('buffersize', self.__buffer_size__, Regex='^\d+$') self.__parameters__['yRange'] = \ DParameter('yRange', self.config['yRange']['value'], Regex='^\[(\d+\.\d+)\s+(\d+\.\d+)\]$') self.__parameters__['show_legend'] = \ DParameter('show_legend', self.config['show_legend']['value'], Regex=pc.REGEX_BOOL_BIN) if not self.__papi_debug__: self.pl_send_new_parameter_list(list(self.__parameters__.values())) # --------------------------- # Create Legend # --------------------------- if self.__show_legend__: self.__legend__ = self.__plotWidget__.getPlotItem().addLegend() else: self.__legend__ = None self.__last_time__ = current_milli_time() self.__update_intervall__ = 20 # in milliseconds self.__last_plot_time__ = 0 self.setup_context_menu() self.__plotWidget__.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.__plotWidget__.customContextMenuRequested.connect(self.showContextMenu) self.use_range_for_y(self.config['yRange']['value']) # ---------------------------- # Initiate for default plotting # ---------------------------- self.initiate_update_plot() return True def cb_pause(self): """ Function pause :return: """ self.__plotWidget__.getPlotItem().getViewBox().setMouseEnabled(x=True, y=True) def cb_resume(self): """ Function resume :return: """ self.__plotWidget__.getPlotItem().getViewBox().setMouseEnabled(x=False, y=True) def cb_execute(self, Data=None, block_name = None, plugin_uname = None): """ Function cb_execute :param Data: :param block_name: :return: """ t = Data[CORE_TIME_SIGNAL] self.__input_size__ = len(t) self.__signals_have_same_length = True now = pg.ptime.time() for key in Data: if key != CORE_TIME_SIGNAL: y = Data[key] if key in self.signals: if self.__downsampling_rate_start__ < len(y): ds_y = y[self.__downsampling_rate_start__::self.__downsampling_rate__] self.signals[key].add_data(ds_y) self.__signals_have_same_length &= (len(y) == len(t)) if self.__downsampling_rate_start__ >= len(t): self.__downsampling_rate_start__ -= len(t) else: ds_t = t[self.__downsampling_rate_start__::self.__downsampling_rate__] self.__downsampling_rate_start__ += self.__downsampling_rate__ - len(ds_t) self.__tbuffer__.extend(ds_t) self.__new_added_data__ += len(t) self.rolling_Checkbox.setDisabled(self.__stp_active__) if self.__input_size__ > 1 or self.__signals_have_same_length: if self.__stp_active__: self.initiate_update_plot() if current_milli_time() - self.__last_time__ > self.__update_intervall__ - self.__last_plot_time__: self.__last_time__ = current_milli_time() self.update_plot() self.__last_time__ = current_milli_time() self.__new_added_data__ = 0 else: if not self.__stp_active__ : self.initiate_update_plot_single_timestamp() if current_milli_time() - self.__last_time__ > self.__update_intervall__ - self.__last_plot_time__: self.__last_time__ = current_milli_time() self.update_plot_single_timestamp(Data) self.__last_time__ = current_milli_time() self.__new_added_data__ = 0 # print("Plot time: %0.5f sec" % (self.__last_plot_time__) ) def cb_set_parameter(self, name, value): """ Function set parameters :param name: :param value: :return: """ if name == 'x-grid': self.config['x-grid']['value'] = value self.__plotWidget__.showGrid(x=value == '1') self.xGrid_Checkbox.stateChanged.disconnect() self.xGrid_Checkbox.setChecked(value=='1') self.xGrid_Checkbox.stateChanged.connect(self.contextMenu_xGrid_toogle) if name == 'y-grid': self.config['y-grid']['value'] = value self.__plotWidget__.showGrid(y=value == '1') self.yGrid_Checkbox.stateChanged.disconnect() self.yGrid_Checkbox.setChecked(value=='1') self.yGrid_Checkbox.stateChanged.connect(self.contextMenu_yGrid_toogle) if name == 'downsampling_rate': self.config['downsampling_rate']['value'] = value self.__downsampling_rate__ = int(value) self.__new_added_data__ = 0 self.update_downsampling_rate() if name == 'rolling': self.clear() self.config['rolling_plot']['value'] = value self.update_rolling_plot() if name == 'color': self.clear() self.config['color']['value'] = value int_re = re.compile(r'(\d+)') self.__colors_selected__ = int_re.findall(self.config['color']['value']) self.update_pens() self.update_legend() if name == 'style': self.clear() self.config['style']['value'] = value int_re = re.compile(r'(\d+)') self.__styles_selected__ = int_re.findall(self.config['style']['value']) self.update_pens() self.update_legend() if name == 'show_legend': self.config['show_legend']['value'] = value if value == '0': if self.__legend__ is not None: self.__legend__.scene().removeItem(self.__legend__) del self.__legend__ self.__legend__ = None if value == '1': self.update_legend() if name == 'buffersize': self.config['buffersize']['value'] = value self.update_buffer_size(value) if name == 'yRange': self.config['yRange']['value'] = value self.use_range_for_y(value) def update_pens(self): """ Function update pens :return: """ for signal_name in self.signals.keys(): signal_id = self.signals[signal_name].id new_pen = self.get_pen(signal_id) other_pen = self.get_pen(signal_id) o_color = other_pen.color() o_color.setAlpha(100) other_pen.setColor(o_color) self.signals[signal_name].pen = new_pen self.signals[signal_name].other_pen = other_pen def update_plot(self): """ Function update_plot :return: """ if len(self.__tbuffer__) == 0: return if not self.__rolling_plot__: tdata = list(self.__tbuffer__) if self.__rolling_plot__: tdata = list(range(0, len(self.__tbuffer__))) self.__append_at__ += self.signals[list(self.signals.keys())[0]].get_new_added_since_last_drawing() self.__append_at__ %= len(tdata) tdata = np.roll(tdata, -int(self.__append_at__)) now = pg.ptime.time() for signal_name in self.signals: # get all no more needed graphic items graphics = self.signals[signal_name].get_old_graphics() for graphic in graphics: self.__plotWidget__.removeItem(graphic) # Create new new graphic items self.signals[signal_name].create_graphics(tdata) # Get new created graphic item and paint them graphics = self.signals[signal_name].get_graphics() for graphic in graphics: self.__plotWidget__.addItem(graphic) self.__last_plot_time__ = pg.ptime.time()-now if self.__rolling_plot__: self.__plotWidget__.getPlotItem().getViewBox().setXRange(0, len(tdata)-1) self.time_label.setNum(self.__tbuffer__[-1]) else: self.__plotWidget__.getPlotItem().getViewBox().setXRange(tdata[0], tdata[-1]) # if self.__papi_debug__: # print("Plot time: %0.5f sec" % (self.__last_plot_time__) ) def initiate_update_plot(self): """ To all needed changes to use default plotting :return: """ self.__stp_active__ = False if self.__rolling_plot__: self.time_label.setHidden(False) else: self.time_label.setHidden(True) pass def initiate_update_plot_single_timestamp(self): """ To all needed changes to use single timestamp plotting :return: """ self.__stp_active__ = True self.time_label.setHidden(False) def update_plot_single_timestamp(self, data): """ Function update_plot_single_timestamp :return: """ self.__plotWidget__.clear() cur_max_y = 0 cur_min_y = 1000 for signal_name in data: if signal_name != CORE_TIME_SIGNAL: signal_data = data[signal_name] if signal_name in self.signals: tdata = np.linspace(1, len(signal_data), len(signal_data)) plot_item = self.signals[signal_name] if len(tdata) == 1: graphic = GraphicItem(np.array([self.__stp_min_x, self.__stp_max_x]), np.array([signal_data[0], signal_data[0]]), 0, pen=plot_item.pen) else: graphic = GraphicItem(np.array(tdata), np.array(signal_data), 0, pen=plot_item.pen) self.__plotWidget__.addItem(graphic) self.__stp_max_x = max(self.__stp_max_x, max(tdata)) self.__stp_min_x = min(self.__stp_min_x, min(tdata)) cur_max_y = max(cur_max_y, max(signal_data)) cur_min_y = min(cur_min_y, min(signal_data)) self.__stp_max_y = cur_max_y self.__stp_min_y = cur_min_y self.__plotWidget__.getPlotItem().getViewBox().setXRange(self.__stp_min_x, self.__stp_max_x) self.time_label.setNum(data[CORE_TIME_SIGNAL][0]) def update_buffer_size(self, new_size): """ Function set buffer size :param new_size: :return: """ self.__buffer_size__ = int(new_size) start_size = len(self.__tbuffer__) for signal_name in self.signals: self.__tbuffer__ = collections.deque([0.0] * start_size, self.__buffer_size__) # COLLECTION plot_item = self.signals[signal_name] plot_item.max_elements = self.__buffer_size__ plot_item.clear() self.__plotWidget__.clear() self.update_rolling_plot() self.__new_added_data__ = 0 def cb_plugin_meta_updated(self): """ This function is called whenever meta information are changed. This enables the plot to handle more than one input for plotting. :return: """ dp_info = self.pl_get_dplugin_info() subscriptions = dp_info.get_subscribtions() changes = False current_signals = {} index = 0 for dpluginsub_id in subscriptions: for dblock_name in subscriptions[dpluginsub_id]: # get subscription for dblock subscription = subscriptions[dpluginsub_id][dblock_name] for signal_name in subscription.get_signals(): if signal_name != pc.CORE_TIME_SIGNAL: signal = subscription.get_dblock().get_signal_by_uname(signal_name) current_signals[signal_name] = {} current_signals[signal_name]['signal'] = signal current_signals[signal_name]['index'] = index index += 1 # ---------------------------- # Add new subscribed signals # ---------------------------- for signal_name in sorted(current_signals.keys()): if signal_name != CORE_TIME_SIGNAL: if signal_name not in self.signals: signal = current_signals[signal_name]['signal'] self.add_plot_item(signal, current_signals[signal_name]['index']) changes = True # ------------------------------- # Remove unsubscribed signals # ------------------------------- for signal_name in self.signals.copy(): if signal_name not in current_signals: if self.__legend__ is not None: self.remove_plot_item(signal_name) changes = True if changes: self.update_pens() self.update_signals() self.update_legend() self.update_rolling_plot() self.update_downsampling_rate() else: self.update_signals() #self.update_legend() def add_plot_item(self, signal, signal_id): """ Create a new plot item object for a given signal and internal id :param signal: DSignal object :param signal_id: plot internal signal id :return: """ signal_name = signal.uname if signal_name not in self.signals: self.signals[signal_name] = {} plot_item = PlotItem(signal, signal_id, self.__buffer_size__) plot_item.set_downsampling_rate(self.__downsampling_rate__) self.signals[signal_name] = plot_item def remove_plot_item(self, signal_name): """ Remove the plot item object for a given signal_name. :param signal_name: :return: """ if signal_name in self.signals: plot_item = self.signals[signal_name] # Remove all graphic objects for graphic in plot_item.graphics: self.__plotWidget__.removeItem(graphic) # Remove from Legend self.__legend__.removeItem(plot_item.signal_name) del self.signals[signal_name] def get_pen(self, index): """ Function get pen :param index: :return: """ index = int(index) style_index = index % len(self.__styles_selected__) style_code = int(self.__styles_selected__[style_index]) color_index = index % len(self.__colors_selected__) color_code = int(self.__colors_selected__[color_index]) if style_code in self.styles: style = self.styles[style_code] else: style = self.styles[0] if color_code in self.colors: color = self.colors[color_code] else: color = self.colors[0] return pg.mkPen(color=color, style=style) def update_rolling_plot(self): """ Used to update the rolling plot by resolving all dependencies. The configuration for the rolling plot depends on the current value in self.config['rolling_plot']['value'] :return: """ value = self.config['rolling_plot']['value'] self.__rolling_plot__ = int(float(self.config['rolling_plot']['value'])) == int('1') self.rolling_Checkbox.stateChanged.disconnect() self.rolling_Checkbox.setChecked(value == '1') self.rolling_Checkbox.stateChanged.connect(self.contextMenu_rolling_toogled) self.clear() for signal_name in self.signals: self.signals[signal_name].rolling_plot = self.__rolling_plot__ self.initiate_update_plot() def use_range_for_x(self, value): """ :param value: :return: """ reg = re.compile(r'(\d+\.\d+)') range = reg.findall(value) if len(range) == 2: #self.xRange_minEdit.setText(range[0]) #self.xRange_maxEdit.setText(range[1]) self.__plotWidget__.getPlotItem().getViewBox().setXRange(float(range[0]),float(range[1])) def use_range_for_y(self, value): """ :param value: :return: """ reg = re.compile(r'([-]{0,1}\d+\.\d+)') range = reg.findall(value) if len(range) == 2: self.yRange_minEdit.setText(range[0]) self.yRange_maxEdit.setText(range[1]) self.__plotWidget__.getPlotItem().getViewBox().setYRange(float(range[0]), float(range[1])) def setup_context_menu(self): """ :return: """ self.custMenu = QMenu("Options") self.axesMenu = QMenu('Y-Axis') self.gridMenu = QMenu('Grid') ##### Y-Range Actions self.yRange_Widget = QWidget() self.yRange_Layout = QVBoxLayout(self.yRange_Widget) self.yRange_Layout.setContentsMargins(2, 2, 2, 2) self.yRange_Layout.setSpacing(1) self.yAutoRangeButton = QPushButton() self.yAutoRangeButton.clicked.connect(self.contextMenu_yAutoRangeButton_clicked) self.yAutoRangeButton.setText('Use autorange') self.yRange_Layout.addWidget(self.yAutoRangeButton) ##### Y Line Edits # Layout self.yRange_EditWidget = QWidget() self.yRange_EditLayout = QHBoxLayout(self.yRange_EditWidget) self.yRange_EditLayout.setContentsMargins(2, 2, 2, 2) self.yRange_EditLayout.setSpacing(1) # get old values; reg = re.compile(r'(\d+\.\d+)') range = reg.findall(self.config['yRange']['value']) if len(range) == 2: y_min = range[0] y_max = range[1] else: y_min = '0.0' y_max = '1.0' rx = QRegExp(r'([-]{0,1}\d+\.\d+)') validator = QRegExpValidator(rx, self.__plotWidget__) # Min self.yRange_minEdit = QLineEdit() self.yRange_minEdit.setFixedWidth(80) self.yRange_minEdit.setText(y_min) self.yRange_minEdit.editingFinished.connect(self.contextMenu_yRange_toogle) self.yRange_minEdit.setValidator(validator) # Max self.yRange_maxEdit = QLineEdit() self.yRange_maxEdit.setFixedWidth(80) self.yRange_maxEdit.setText(y_max) self.yRange_maxEdit.editingFinished.connect(self.contextMenu_yRange_toogle) self.yRange_maxEdit.setValidator(validator) # addTo Layout self.yRange_EditLayout.addWidget(self.yRange_minEdit) self.yRange_EditLayout.addWidget(QLabel('<')) self.yRange_EditLayout.addWidget(self.yRange_maxEdit) self.yRange_Layout.addWidget(self.yRange_EditWidget) # build Action self.yRange_Action = QWidgetAction(self.__plotWidget__) self.yRange_Action.setDefaultWidget(self.yRange_Widget) ##### Rolling Plot self.rolling_Checkbox = QCheckBox() self.rolling_Checkbox.setText('Rolling plot') self.rolling_Checkbox.setChecked(self.config['rolling_plot']['value'] == '1') self.rolling_Checkbox.stateChanged.connect(self.contextMenu_rolling_toogled) self.rolling_Checkbox_Action = QWidgetAction(self.__plotWidget__) self.rolling_Checkbox_Action.setDefaultWidget(self.rolling_Checkbox) if self.__stp_active__: self.rolling_Checkbox.setDisabled(True) # show legend self.legend_Checkbox = QCheckBox() self.legend_Checkbox.setText('Show legend') self.legend_Checkbox.setChecked(self.config['show_legend']['value'] == '1') self.legend_Checkbox.stateChanged.connect(self.contextMenu_legend_toogled) self.legend_Checkbox_Action = QWidgetAction(self.__plotWidget__) self.legend_Checkbox_Action.setDefaultWidget(self.legend_Checkbox) ##### Build axes menu #self.axesMenu.addAction(self.xRange_Action) self.axesMenu.addSeparator().setText("Y-Range") self.axesMenu.addAction(self.yRange_Action) # Grid Menu: # ----------------------------------------------------------- # Y-Grid checkbox self.xGrid_Checkbox = QCheckBox() self.xGrid_Checkbox.stateChanged.connect(self.contextMenu_xGrid_toogle) self.xGrid_Checkbox.setText('X-Grid') self.xGrid_Action = QWidgetAction(self.__plotWidget__) self.xGrid_Action.setDefaultWidget(self.xGrid_Checkbox) self.gridMenu.addAction(self.xGrid_Action) # Check config for startup state if self.__show_grid_x__: self.xGrid_Checkbox.setChecked(True) # X-Grid checkbox self.yGrid_Checkbox = QCheckBox() self.yGrid_Checkbox.stateChanged.connect(self.contextMenu_yGrid_toogle) self.yGrid_Checkbox.setText('Y-Grid') self.yGrid_Action = QWidgetAction(self.__plotWidget__) self.yGrid_Action.setDefaultWidget(self.yGrid_Checkbox) self.gridMenu.addAction(self.yGrid_Action) # Check config for startup state if self.__show_grid_y__: self.yGrid_Checkbox.setChecked(True) # add Menus self.custMenu.addMenu(self.axesMenu) self.custMenu.addMenu(self.gridMenu) self.custMenu.addSeparator().setText("Rolling Plot") self.custMenu.addAction(self.rolling_Checkbox_Action) self.custMenu.addAction(self.legend_Checkbox_Action) self.__plotWidget__.getPlotItem().getViewBox().menu.clear() if not self.__papi_debug__: self.__plotWidget__.getPlotItem().ctrlMenu = [self.pl_create_control_context_menu(), self.custMenu] def showContextMenu(self): self.setup_context_menu() def contextMenu_yAutoRangeButton_clicked(self): mi = None ma = None if self.__stp_active__: mi = self.__stp_min_y ma = self.__stp_max_y else: for sig in self.signals: graphics = self.signals[sig].graphics buf = [] for graphic in graphics: buf.extend(graphic.y) ma_buf = max(buf) mi_buf = min(buf) if ma is not None: if ma_buf > ma: ma = ma_buf else: ma = ma_buf if mi is not None: if mi_buf < mi: mi = mi_buf else: mi = mi_buf ma = str(float(ma)) mi = str(float(mi)) self.yRange_maxEdit.setText(ma) self.yRange_minEdit.setText(mi) self.control_api.do_set_parameter(self.__id__, 'yRange', '[' +mi + ' ' + ma + ']') def contextMenu_rolling_toogled(self): if self.rolling_Checkbox.isChecked(): self.control_api.do_set_parameter(self.__id__, 'rolling', '1') else: self.control_api.do_set_parameter(self.__id__, 'rolling', '0') def contextMenu_legend_toogled(self): if self.legend_Checkbox.isChecked(): self.control_api.do_set_parameter(self.__id__, 'show_legend', '1') else: self.control_api.do_set_parameter(self.__id__, 'show_legend', '0') def contextMenu_xGrid_toogle(self): if self.xGrid_Checkbox.isChecked(): self.control_api.do_set_parameter(self.__id__, 'x-grid', '1') else: self.control_api.do_set_parameter(self.__id__, 'x-grid', '0') def contextMenu_yGrid_toogle(self): if self.yGrid_Checkbox.isChecked(): self.control_api.do_set_parameter(self.__id__, 'y-grid', '1') else: self.control_api.do_set_parameter(self.__id__, 'y-grid', '0') def contextMenu_yRange_toogle(self): mi = self.yRange_minEdit.text() ma = self.yRange_maxEdit.text() if float(mi) < float(ma): self.control_api.do_set_parameter(self.__id__, 'yRange', '[' + mi + ' ' + ma + ']') def update_signals(self): """ Used to update the signals as they are described in self.dplugin_info :return: """ dp_info = self.pl_get_dplugin_info() subscriptions = dp_info.get_subscribtions() for dpluginsub_id in subscriptions: for dblock_name in subscriptions[dpluginsub_id]: # get subscription for dblock subscription = subscriptions[dpluginsub_id][dblock_name] for signal_name in subscription.get_signals(): if signal_name != CORE_TIME_SIGNAL: signal = subscription.get_dblock().get_signal_by_uname(signal_name) self.signals[signal_name].update_signal(signal) def update_legend(self): """ Used to update the legend. :return: """ if not self.__show_legend__: return if self.__legend__ is not None: self.__legend__.scene().removeItem(self.__legend__) del self.__legend__ self.__legend__ = None self.__legend__ = self.__plotWidget__.getPlotItem().addLegend() if not self.__papi_debug__: self.update_signals() for signal_name in sorted(self.signals.keys()): graphic = self.signals[signal_name].get_legend_item() if graphic is not None: signal = self.signals[signal_name].signal legend_name = signal.dname self.__legend__.addItem(graphic, legend_name) def update_downsampling_rate(self): """ Used to update the downsampling rate by resolving all dependencies. The new downsampling rate is taken by using the private attribute __downsampling_rate__. :return: """ rate = self.__downsampling_rate__ self.__downsampling_rate_start__ = 0 self.__downsampling_rate__ = rate for signal_name in self.signals: self.signals[signal_name].set_downsampling_rate(rate) def plot_yrange_changed(self): viewbox = self.__plotWidget__.getPlotItem().getViewBox() [xRange, yRange] = viewbox.viewRange() self.control_api.do_update_parameter(self.__id__, 'yRange', '[' + str(yRange[0]) + ' ' + str(yRange[1]) + ']') self.config['yRange']['value'] = '[' + str(yRange[0]) + ' ' + str(yRange[1]) + ']' def cb_quit(self): """ Function quit plugin :return: """ print('PlotPerformance: will quit') def debug_papi(self): config = self.get_cb_plugin_configuration() config['yRange'] = { 'value': '[0.0 50.0]', 'regex': '(\d+\.\d+)', 'advanced': '1', 'display_text': 'y: range' } config['buffersize'] = { 'value': '1000', 'regex': '(\d+\.\d+)', 'advanced': '1', 'display_text': 'y: range' } config['downsampling_rate'] = { 'value': '10', 'regex': '(\d+\.\d+)', 'advanced': '1', 'display_text': 'y: range' } self.config = config self.__id__ = 0 self.cb_initialize_plugin(config) signal_1 = DSignal('signal_1') signal_2 = DSignal('signal_2') signal_3 = DSignal('signal_3') signal_4 = DSignal('signal_4') signal_5 = DSignal('signal_5') self.add_plot_item(signal_1, 1) self.add_plot_item(signal_2, 2) self.add_plot_item(signal_3, 3) self.add_plot_item(signal_4, 4) self.add_plot_item(signal_5, 5) self.update_pens() self.update_legend() pass def cb_get_plugin_configuration(self): """ Function get plugin configuration :return {}: """ config = { 'x-grid': { 'value': "0", 'regex': '^(1|0)$', 'type': 'bool', 'display_text': 'Grid-X' }, 'y-grid': { 'value': "0", 'regex': '^(1|0)$', 'type': 'bool', 'display_text': 'Grid-Y' }, 'color': { 'value': "[0 1 2 3 4]", 'regex': '^\[(\s*\d\s*)+\]', 'advanced': '1', 'display_text': 'Color' }, 'style': { 'value': "[0 0 0 0 0]", 'regex': '^\[(\s*\d\s*)+\]', 'advanced': '1', 'display_text': 'Style' }, 'buffersize': { 'value': "100", 'regex': '^(\d+)$', 'advanced': '1', 'display_text': 'Buffersize' }, 'downsampling_rate': { 'value': "1", 'regex': '(\d+)' }, 'rolling_plot': { 'value': '0', 'regex': '^(1|0)$', 'type': 'bool', 'display_text': 'Rolling Plot' }, 'yRange': { 'value': '[0.0 1.0]', 'regex': '^\[(\d+\.\d+)\s+(\d+\.\d+)\]$', 'advanced': '1', 'display_text': 'y: range' }, 'show_legend' : { 'value' : '1', 'regex' : pc.REGEX_BOOL_BIN, 'display_text' : 'Enable/Disable legend', 'type' : pc.CFG_TYPE_BOOL } } # http://www.regexr.com/ return config def clear(self): """ :return: """ self.__plotWidget__.clear() self.__tbuffer__.clear() for signal_name in self.signals: self.signals[signal_name].clear()
def __init__(self, font, parent=None): super().__init__(parent) auxiliaryWidth = self.fontMetrics().width('0') * 8 self.leftTextField = MetricsSequenceEdit(font, self) self.leftTextField.setMaximumWidth(auxiliaryWidth) self.textField = MetricsSequenceComboBox(font, self) # XXX: had to use Maximum because Preferred did extend the widget(?) self.textField.setSizePolicy( QSizePolicy.Expanding, QSizePolicy.Maximum) self.rightTextField = MetricsSequenceEdit(font, self) self.rightTextField.setMaximumWidth(auxiliaryWidth) self.leftTextField.textEdited.connect(self.textField.editTextChanged) self.rightTextField.textEdited.connect(self.textField.editTextChanged) self.textField.editTextChanged.connect(self._textChanged) self.comboBox = QComboBox(self) self.comboBox.setEditable(True) self.comboBox.setCompleter(None) self.comboBox.setValidator(QIntValidator(self)) for p in pointSizes: self.comboBox.addItem(str(p)) self.pointSizeChanged = self.comboBox.currentIndexChanged[str] self.configBar = QPushButton(self) self.configBar.setFlat(True) self.configBar.setIcon(QIcon(":settings.svg")) self.configBar.setStyleSheet("padding: 2px 0px; padding-right: 10px") self.toolsMenu = QMenu(self) self._showKerning = self.toolsMenu.addAction( self.tr("Show Kerning"), self._kerningVisibilityChanged) self._showKerning.setCheckable(True) self._showMetrics = self.toolsMenu.addAction( self.tr("Show Metrics"), self._controlsTriggered) self._showMetrics.setCheckable(True) self.toolsMenu.addSeparator() self._verticalFlip = self.toolsMenu.addAction( self.tr("Vertical Flip"), self._controlsTriggered) self._verticalFlip.setCheckable(True) self._wrapLines = self.toolsMenu.addAction( self.tr("Wrap Lines"), self._controlsTriggered) self._wrapLines.setCheckable(True) self.toolsMenu.addSeparator() action = self.toolsMenu.addAction(self.tr("Line Height:")) action.setEnabled(False) lineHeight = QWidgetAction(self.toolsMenu) self._lineHeightSlider = slider = QSlider(Qt.Horizontal, self) # QSlider works with integers so we'll just divide what comes out of it # by 100 slider.setMinimum(80) slider.setMaximum(160) slider.setValue(110) slider.valueChanged.connect(self._controlsTriggered) slider.valueChanged.connect(self._sliderLineHeightChanged) lineHeight.setDefaultWidget(slider) self.toolsMenu.addAction(lineHeight) self.configBar.setMenu(self.toolsMenu) self.addWidget(self.leftTextField) self.addWidget(self.textField) self.addWidget(self.rightTextField) self.addWidget(self.comboBox) self.addWidget(self.configBar) app = QApplication.instance() app.dispatcher.addObserver( self, "_currentGlyphChanged", "currentGlyphChanged") self.readSettings()