def setup_ui(self): main = QHBoxLayout() sub = QVBoxLayout() for i in range(10): sub.addWidget(QLabel(str(i))) main.addLayout(sub) self.setLayout(main)
def create_controls(self): table = QTableView(self) self.model = PluginsModel(self.plugin_manager) table.setModel(self.model) h = table.horizontalHeader() h.setSectionResizeMode(QHeaderView.ResizeToContents) table.setHorizontalHeader(h) h = table.verticalHeader() h.setSectionResizeMode(QHeaderView.ResizeToContents) table.setVerticalHeader(h) self.table = table width = 80 for i in range(3): width += table.columnWidth(i) btns = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal) self.edit_btn = QPushButton("Edit") btns.addButton(self.edit_btn, QDialogButtonBox.ActionRole) self.edit_btn.clicked.connect(self.edit_plugin) btns.accepted.connect(self.accept) btns.rejected.connect(self.reject) vbox = QVBoxLayout() vbox.addWidget(table) vbox.addWidget(btns) self.setLayout(vbox) s = self.size() s.setHeight(table.rowHeight(0) * 10) s.setWidth(width) self.resize(s)
def create_controls(self): """ Create UI controls. """ self.tabs = QTabWidget(self) # Fill in tabs by setting groups s = QSettings(self.ui) self._add_groups(s) # Add button bar at end btns = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Apply | QDialogButtonBox.Cancel | QDialogButtonBox.Reset, QtCore.Qt.Horizontal, self) btns.accepted.connect(self._on_accept) btns.rejected.connect(self.reject) btns.clicked[QAbstractButton].connect(self._on_click) self._btns = btns self.apply_btn.setEnabled(False) vbox = QVBoxLayout() vbox.addWidget(self.tabs) vbox.addWidget(btns) self.setLayout(vbox)
def __init__(self, rootnode: JsonNode, settings, parent=None): super().__init__(parent) self.settings = settings self.rootnode = rootnode self.plotitems = [] self.starttime = datetime.datetime.now() self.dirty = False # matplotlib figure self.fig = pylab.figure() self.canvas = MyCanvas(self.fig, self) self.canvas.setParent(self) self.ax1 = self.fig.add_subplot(111) self.ax1.grid() self.ax1.callbacks.connect('xlim_changed', self.plotlim_changed) self.ax1.callbacks.connect('ylim_changed', self.plotlim_changed) # navigation toolbar self.toolbar = NavigationToolbar(self.canvas, self) # layout layout = QVBoxLayout() layout.addWidget(self.toolbar) layout.addWidget(self.canvas) self.setLayout(layout) self.setAcceptDrops(True)
def __init__(self, parent=None, logname=None, level=logging.NOTSET): QWidget.__init__(self, parent=parent) # Create Widgets self.label = QLabel('Minimum displayed log level: ', parent=self) self.combo = QComboBox(parent=self) self.text = QPlainTextEdit(parent=self) self.text.setReadOnly(True) self.clear_btn = QPushButton("Clear", parent=self) # Create layout layout = QVBoxLayout() level_control = QHBoxLayout() level_control.addWidget(self.label) level_control.addWidget(self.combo) layout.addLayout(level_control) layout.addWidget(self.text) layout.addWidget(self.clear_btn) self.setLayout(layout) # Allow QCombobox to control log level for log_level, value in LogLevels.as_dict().items(): self.combo.addItem(log_level, value) self.combo.currentIndexChanged[str].connect(self.setLevel) # Allow QPushButton to clear log text self.clear_btn.clicked.connect(self.clear) # Create a handler with the default format self.handler = GuiHandler(level=level, parent=self) self.logFormat = self.default_format self.handler.message.connect(self.write) # Create logger. Either as a root or given logname self.log = None self.level = None self.logName = logname or '' self.logLevel = level self.destroyed.connect(functools.partial(logger_destroyed, self.log))
def create_controls(self): self.setWindowTitle(tr(self.plugin.name)) vbox = QVBoxLayout() form = QFormLayout() for Name, (enabled, url) in self.packages.items(): name = Name.lower() cbo = QComboBox() if enabled: branches = get_branches(name, url) for n, b in branches.items(): cbo.addItem(n, b) if not check_git_repo(name): cbo.insertItem(0, "<Select to change>", None) cbo.setCurrentIndex(0) self._prev_indices[cbo] = 0 cbo.currentIndexChanged.connect( partial(self._cbo_changed, cbo)) else: cbo.setEditText("<git repository>") cbo.setToolTip(tr( "This is installed in a git repository but we're set to " "not use git.")) cbo.setEnabled(enabled) form.addRow(Name + ':', cbo) vbox.addLayout(form) vbox.addWidget(QLabel(tr( "You should restart the application if you make any changes!"))) btns = QDialogButtonBox(QDialogButtonBox.Ok, Qt.Horizontal, self) btns.accepted.connect(self.accept) vbox.addWidget(btns) self.setLayout(vbox)
def create_window(): # Create app and widgets app = QApplication(sys.argv) win = QMainWindow() main_area = QWidget() button_area = QWidget() scroll_area = QScrollArea() button = QPushButton("Start Video") btn_grab = QPushButton("Grab Frame") # Create layouts vbox = QVBoxLayout() hbox = QHBoxLayout() # Fill Layouts vbox.addWidget(scroll_area) vbox.addWidget(button_area) hbox.addStretch() hbox.addWidget(button) hbox.addWidget(btn_grab) # Assign layouts to widgets main_area.setLayout(vbox) button_area.setLayout(hbox) scroll_area.setLayout(QVBoxLayout()) # Attach some child widgets directly win.setCentralWidget(main_area) return app, win, button, btn_grab, scroll_area
def __init__(self, parent=None, show_fullpath=True, fullpath_sorting=True, show_all_files=True, show_comments=True): QWidget.__init__(self, parent) self.treewidget = OutlineExplorerTreeWidget(self, show_fullpath=show_fullpath, fullpath_sorting=fullpath_sorting, show_all_files=show_all_files, show_comments=show_comments) self.visibility_action = create_action(self, _("Show/hide outline explorer"), icon='outline_explorer_vis.png', toggled=self.toggle_visibility) self.visibility_action.setChecked(True) btn_layout = QHBoxLayout() btn_layout.setAlignment(Qt.AlignLeft) for btn in self.setup_buttons(): btn_layout.addWidget(btn) layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) layout.addLayout(btn_layout) layout.addWidget(self.treewidget) self.setLayout(layout)
def __init__(self, parent=None): """Initialization.""" SpyderPluginWidget.__init__(self, parent) self.explorer = ProjectExplorerWidget( self, name_filters=self.get_option('name_filters'), show_all=self.get_option('show_all'), show_hscrollbar=self.get_option('show_hscrollbar'), options_button=self.options_button) layout = QVBoxLayout() layout.addWidget(self.explorer) self.setLayout(layout) self.recent_projects = self.get_option('recent_projects', default=[]) self.current_active_project = None self.latest_project = None self.editor = None self.workingdirectory = None # Initialize plugin self.initialize_plugin() self.explorer.setup_project(self.get_active_project_path())
class OutputPreviewWidget(QWidget): """ A .py preview widget that appears as a drawer on the side of the main import widget. """ def __init__(self, parent=None): super(OutputPreviewWidget, self).__init__(parent=parent) self.setWindowFlags(Qt.Sheet) self.text_editor = QPlainTextEdit() self.close_button = QPushButton('Close') self.layout = QVBoxLayout() self.layout.addWidget(self.text_editor) self.layout.addWidget(self.close_button) self.setLayout(self.layout) self.close_button.clicked.connect(self.hide) self.resize(400, 500) font = QFont('Courier') self.text_editor.setFont(font) self.text_editor.setReadOnly(True) def set_text(self, text): """ Set the text in the loader preview widget. This will display the text that will be saved to the output loader python file. Parameters ---------- text: str Text that will be saved to the final loader file """ self.text_editor.setPlainText(text)
def __init__(self, parent): QWidget.__init__(self, parent) vert_layout = QVBoxLayout() # Type frame type_layout = QHBoxLayout() type_label = QLabel(_("Import as")) type_layout.addWidget(type_label) self.array_btn = array_btn = QRadioButton(_("array")) array_btn.setEnabled(ndarray is not FakeObject) array_btn.setChecked(ndarray is not FakeObject) type_layout.addWidget(array_btn) list_btn = QRadioButton(_("list")) list_btn.setChecked(not array_btn.isChecked()) type_layout.addWidget(list_btn) if pd: self.df_btn = df_btn = QRadioButton(_("DataFrame")) df_btn.setChecked(False) type_layout.addWidget(df_btn) h_spacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) type_layout.addItem(h_spacer) type_frame = QFrame() type_frame.setLayout(type_layout) self._table_view = PreviewTable(self) vert_layout.addWidget(type_frame) vert_layout.addWidget(self._table_view) self.setLayout(vert_layout)
def __init__(self, plugin, id_, history_filename, config_options, additional_options, interpreter_versions, connection_file=None, hostname=None, menu_actions=None, slave=False, external_kernel=False, given_name=None): super(ClientWidget, self).__init__(plugin) SaveHistoryMixin.__init__(self, history_filename) # --- Init attrs self.id_ = id_ self.connection_file = connection_file self.hostname = hostname self.menu_actions = menu_actions self.slave = slave self.given_name = given_name # --- Other attrs self.options_button = None self.stop_button = None self.stop_icon = ima.icon('stop') self.history = [] self.allow_rename = True self.stderr_dir = None # --- Widgets self.shellwidget = ShellWidget(config=config_options, ipyclient=self, additional_options=additional_options, interpreter_versions=interpreter_versions, external_kernel=external_kernel, local_kernel=True) self.infowidget = WebView(self) self.set_infowidget_font() self.loading_page = self._create_loading_page() self._show_loading_page() # --- Layout vlayout = QVBoxLayout() toolbar_buttons = self.get_toolbar_buttons() hlayout = QHBoxLayout() for button in toolbar_buttons: hlayout.addWidget(button) vlayout.addLayout(hlayout) vlayout.setContentsMargins(0, 0, 0, 0) vlayout.addWidget(self.shellwidget) vlayout.addWidget(self.infowidget) self.setLayout(vlayout) # --- Exit function self.exit_callback = lambda: plugin.close_client(client=self) # --- Signals # As soon as some content is printed in the console, stop # our loading animation document = self.get_control().document() document.contentsChange.connect(self._hide_loading_page) # --- Dialog manager self.dialog_manager = DialogManager()
def __init__(self, font=None, default_content=None, parent=None): """ :param font: An optional font to override the default editor font :param default_content: str, if provided this will populate any new editor that is created :param parent: An optional parent widget """ super(MultiPythonFileInterpreter, self).__init__(parent) # attributes self.default_content = default_content self.default_font = font self.prev_session_tabs = None self.whitespace_visible = False self.setAttribute(Qt.WA_DeleteOnClose, True) # widget setup layout = QVBoxLayout(self) self._tabs = CodeEditorTabWidget(self) layout.addWidget(self._tabs) self.setLayout(layout) layout.setContentsMargins(0, 0, 0, 0) # add a single editor by default self.append_new_editor() # setting defaults self.confirm_on_save = True
def __init__(self, parent, plugin, tabs, data, icon): QDialog.__init__(self, parent) # Variables self.plugins_tabs = [] self.plugins_data = [] self.plugins_instances = [] self.add_plugin(plugin, tabs, data, icon) self.plugin = None # Last plugin with focus self.mode = self.FILE_MODE # By default start in this mode self.initial_cursors = None # {fullpath: QCursor} self.initial_path = None # Fullpath of initial active editor self.initial_widget = None # Initial active editor self.line_number = None # Selected line number in filer self.is_visible = False # Is the switcher visible? help_text = _("Press <b>Enter</b> to switch files or <b>Esc</b> to " "cancel.<br><br>Type to filter filenames.<br><br>" "Use <b>:number</b> to go to a line, e.g. " "<b><code>main:42</code></b><br>" "Use <b>@symbol_text</b> to go to a symbol, e.g. " "<b><code>@init</code></b>" "<br><br> Press <b>Ctrl+W</b> to close current tab.<br>") # Either allow searching for a line number or a symbol but not both regex = QRegExp("([A-Za-z0-9_]{0,100}@[A-Za-z0-9_]{0,100})|" + "([A-Za-z0-9_]{0,100}:{0,1}[0-9]{0,100})") # Widgets self.edit = FilesFilterLine(self) self.help = HelperToolButton() self.list = QListWidget(self) self.filter = KeyPressFilter() regex_validator = QRegExpValidator(regex, self.edit) # Widgets setup self.setWindowFlags(Qt.Popup | Qt.FramelessWindowHint) self.setWindowOpacity(0.95) self.edit.installEventFilter(self.filter) self.edit.setValidator(regex_validator) self.help.setToolTip(help_text) self.list.setItemDelegate(HTMLDelegate(self)) # Layout edit_layout = QHBoxLayout() edit_layout.addWidget(self.edit) edit_layout.addWidget(self.help) layout = QVBoxLayout() layout.addLayout(edit_layout) layout.addWidget(self.list) self.setLayout(layout) # Signals self.rejected.connect(self.restore_initial_state) self.filter.sig_up_key_pressed.connect(self.previous_row) self.filter.sig_down_key_pressed.connect(self.next_row) self.edit.returnPressed.connect(self.accept) self.edit.textChanged.connect(self.setup) self.list.itemSelectionChanged.connect(self.item_selection_changed) self.list.clicked.connect(self.edit.setFocus)
def __init__(self, parent, name_filters=[], show_all=True, show_hscrollbar=True, options_button=None): QWidget.__init__(self, parent) self.name_filters = name_filters self.show_all = show_all self.show_hscrollbar = show_hscrollbar self.treewidget = ExplorerTreeWidget(self, self.show_hscrollbar) self.treewidget.setup(name_filters=self.name_filters, show_all=self.show_all) self.treewidget.setup_view() self.treewidget.hide() self.emptywidget = ExplorerTreeWidget(self) if options_button: btn_layout = QHBoxLayout() btn_layout.setAlignment(Qt.AlignLeft) btn_layout.addStretch() btn_layout.addWidget(options_button, Qt.AlignRight) layout = create_plugin_layout(btn_layout) else: layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(self.emptywidget) layout.addWidget(self.treewidget) self.setLayout(layout)
def __init__(self): QWidget.__init__(self) vlayout = QVBoxLayout() self.setLayout(vlayout) self.explorer = ProjectExplorerWidget(None, show_all=True) self.explorer.setup_project(osp.dirname(osp.abspath(__file__))) vlayout.addWidget(self.explorer) hlayout1 = QHBoxLayout() vlayout.addLayout(hlayout1) label = QLabel("<b>Open file:</b>") label.setAlignment(Qt.AlignRight) hlayout1.addWidget(label) self.label1 = QLabel() hlayout1.addWidget(self.label1) self.explorer.sig_open_file.connect(self.label1.setText) hlayout3 = QHBoxLayout() vlayout.addLayout(hlayout3) label = QLabel("<b>Option changed:</b>") label.setAlignment(Qt.AlignRight) hlayout3.addWidget(label) self.label3 = QLabel() hlayout3.addWidget(self.label3) self.explorer.sig_option_changed.connect( lambda x, y: self.label3.setText('option_changed: %r, %r' % (x, y)))
def __init__(self, parent, model): super(AlgorithmMonitorDialog, self).__init__(parent) self.tree = QTreeWidget(self) self.tree.setColumnCount(3) self.tree.setSelectionMode(QTreeWidget.NoSelection) self.tree.setColumnWidth(0, 220) self.tree.setHeaderLabels(['Algorithm', 'Progress', '']) header = self.tree.header() header.setSectionResizeMode(1, QHeaderView.Stretch) header.setSectionResizeMode(2, QHeaderView.Fixed) header.setStretchLastSection(False) button_layout = QHBoxLayout() self.close_button = QPushButton('Close') button_layout.addStretch() button_layout.addWidget(self.close_button) layout = QVBoxLayout() layout.addWidget(self.tree) layout.addLayout(button_layout) self.setLayout(layout) self.setWindowTitle('Mantid - Algorithm progress') self.setWindowIcon(QIcon(":/MantidPlot_Icon_32offset.png")) self.resize(500, 300) self.presenter = AlgorithmProgressDialogPresenter(self, model) self.presenter.update_gui()
def __init__(self, parent=None, stack=None): super(SchemeEditor, self).__init__(parent) self.parent = parent self.stack = stack self.order = [] # Uses scheme names # Needed for self.get_edited_color_scheme() self.widgets = {} self.scheme_name_textbox = {} self.last_edited_color_scheme = None self.last_used_scheme = None # Widgets bbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) # Layout layout = QVBoxLayout() layout.addWidget(self.stack) layout.addWidget(bbox) self.setLayout(layout) # Signals bbox.accepted.connect(self.accept) bbox.accepted.connect(self.get_edited_color_scheme) bbox.rejected.connect(self.reject)
def __init__(self, parent): super(WorkspaceWidget, self).__init__(parent) self._ads = AnalysisDataService.Instance() # layout self.workspacewidget = WorkspaceTreeWidget() layout = QVBoxLayout() layout.addWidget(self.workspacewidget) self.setLayout(layout) # behaviour self.workspacewidget.plotSpectrumClicked.connect(partial(self._do_plot_spectrum, errors=False, overplot=False)) self.workspacewidget.overplotSpectrumClicked.connect(partial(self._do_plot_spectrum, errors=False, overplot=True)) self.workspacewidget.plotSpectrumWithErrorsClicked.connect(partial(self._do_plot_spectrum, errors=True, overplot=False)) self.workspacewidget.overplotSpectrumWithErrorsClicked.connect(partial(self._do_plot_spectrum, errors=True, overplot=True)) self.workspacewidget.plotColorfillClicked.connect(self._do_plot_colorfill) self.workspacewidget.sampleLogsClicked.connect(self._do_sample_logs) self.workspacewidget.sliceViewerClicked.connect(self._do_slice_viewer) self.workspacewidget.showDataClicked.connect(self._do_show_data) self.workspacewidget.showInstrumentClicked.connect(self._do_show_instrument) self.workspacewidget.showAlgorithmHistoryClicked.connect(self._do_show_algorithm_history) self.workspacewidget.workspaceDoubleClicked.connect(self._action_double_click_workspace)
def __init__(self, parent): """ Initialize plugin and corresponding widget. The part of the initialization that depends on `parent` is done in `self.register_plugin()`. """ SpyderPluginWidget.__init__(self, parent) self.main = parent # Spyder 3 compatibility # Create unit test widget. For compatibility with Spyder 3.x # here we check if the plugin has the attributes # 'options_button' and 'options_menu'. See issue 83 if hasattr(self, 'options_button') and hasattr(self, 'options_menu'): # Works with Spyder 4.x self.unittestwidget = UnitTestWidget( self.main, options_button=self.options_button, options_menu=self.options_menu) else: # Works with Spyder 3.x self.unittestwidget = UnitTestWidget(self.main) # Add unit test widget in dockwindow layout = QVBoxLayout() layout.addWidget(self.unittestwidget) self.setLayout(layout) # Initialize plugin self.initialize_plugin()
def setup_page(self): newcb = self.create_checkbox # --- Workspace interface_group = QGroupBox(_("Interface")) restore_data_box = newcb(_("Restore data on startup"), 'restore_data_on_startup') save_data_box = newcb(_("Save data on exit"), 'save_data_on_exit') save_history_box = newcb(_("Save history"), 'save_history') save_non_project_box = newcb(_("Save non project files opened"), 'save_non_project_files') interface_layout = QVBoxLayout() interface_layout.addWidget(restore_data_box) interface_layout.addWidget(save_data_box) interface_layout.addWidget(save_history_box) interface_layout.addWidget(save_non_project_box) interface_group.setLayout(interface_layout) vlayout = QVBoxLayout() vlayout.addWidget(interface_group) vlayout.addStretch(1) self.setLayout(vlayout)
def _promote_widgets(self): graphicsView_layout = QVBoxLayout() self.ui.frame_graphicsView.setLayout(graphicsView_layout) self.ui.graphicsView = MplPlot3dCanvas(self) graphicsView_layout.addWidget(self.ui.graphicsView) return
def __init__(self, *args, **kwargs): super(ClosePackageManagerDialog, self).__init__(*args, **kwargs) self.label_icon = QLabel() self.label_about = QLabel('Conda is still busy.\n\n' 'Do you want to cancel the process?') self.button_ok = QPushButton('Yes') self.button_cancel = QPushButton('No') self.buttonbox = QDialogButtonBox(Qt.Horizontal) # Widget setup self.buttonbox.addButton(self.button_ok, QDialogButtonBox.ActionRole) self.buttonbox.addButton(self.button_cancel, QDialogButtonBox.ActionRole) # self.label_icon.setPixmap(QPixmap(images.ANACONDA_ICON_64_PATH)) self.setWindowTitle("Cancel Process") # Layouts h_layout = QHBoxLayout() h_layout.addWidget(self.label_icon, 0, Qt.AlignTop) h_layout.addSpacing(10) h_layout.addWidget(self.label_about) main_layout = QVBoxLayout() main_layout.addLayout(h_layout) main_layout.addSpacing(20) main_layout.addWidget(self.buttonbox) self.setLayout(main_layout) # Signals self.button_ok.clicked.connect(self.accept) self.button_cancel.clicked.connect(self.reject)
def __init__(self, plotted_lines, *args, **kwargs): super().__init__(None, *args, **kwargs) self.plotted_lines = plotted_lines layout = QVBoxLayout() layout.setSizeConstraint(QLayout.SetMaximumSize) self.setLayout(layout) table_model = LineListTableModel(plotted_lines) if table_model.rowCount() > 0: table_view = QTableView() # disabling sorting will significantly speed up theWidget # plot. This is because the table view must be re-built # every time a new set of markers is drawn on the plot # surface. Alternate approaches are worth examining. It # remains to be seen what would be the approach users # will favor. table_view.setSortingEnabled(False) proxy = SortModel(table_model.get_name()) proxy.setSourceModel(table_model) table_view.setModel(proxy) table_view.setSortingEnabled(True) table_view.setSelectionMode(QAbstractItemView.NoSelection) table_view.horizontalHeader().setStretchLastSection(True) table_view.resizeColumnsToContents() layout.addWidget(table_view)
def setup_page(self): # Widgets self.table = ShortcutsTable(self) self.finder = ShortcutFinder(self.table, self.table.set_regex) self.table.finder = self.finder self.label_finder = QLabel(_('Search: ')) self.reset_btn = QPushButton(_("Reset to default values")) # Layout hlayout = QHBoxLayout() vlayout = QVBoxLayout() hlayout.addWidget(self.label_finder) hlayout.addWidget(self.finder) vlayout.addWidget(self.table) vlayout.addLayout(hlayout) vlayout.addWidget(self.reset_btn) self.setLayout(vlayout) self.setTabOrder(self.table, self.finder) self.setTabOrder(self.finder, self.reset_btn) # Signals and slots if PYQT5: # Qt5 'dataChanged' has 3 parameters self.table.proxy_model.dataChanged.connect( lambda i1, i2, roles, opt='': self.has_been_modified(opt)) else: self.table.proxy_model.dataChanged.connect( lambda i1, i2, opt='': self.has_been_modified(opt)) self.reset_btn.clicked.connect(self.reset_to_default)
def __init__(self, parent=None): QDialog.__init__(self, parent) self.main = parent # Widgets self.pages_widget = QStackedWidget() self.pages_widget.setMinimumWidth(600) self.contents_widget = QListWidget() self.button_reset = QPushButton(_('Reset to defaults')) bbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Apply | QDialogButtonBox.Cancel) self.apply_btn = bbox.button(QDialogButtonBox.Apply) # Widgets setup # Destroying the C++ object right after closing the dialog box, # otherwise it may be garbage-collected in another QThread # (e.g. the editor's analysis thread in Spyder), thus leading to # a segmentation fault on UNIX or an application crash on Windows self.setAttribute(Qt.WA_DeleteOnClose) self.setWindowTitle(_('Preferences')) self.setWindowIcon(ima.icon('configure')) self.contents_widget.setMovement(QListView.Static) self.contents_widget.setSpacing(1) self.contents_widget.setCurrentRow(0) self.contents_widget.setMinimumWidth(220) self.contents_widget.setMinimumHeight(400) # Layout hsplitter = QSplitter() hsplitter.addWidget(self.contents_widget) hsplitter.addWidget(self.pages_widget) hsplitter.setStretchFactor(0, 1) hsplitter.setStretchFactor(1, 2) btnlayout = QHBoxLayout() btnlayout.addWidget(self.button_reset) btnlayout.addStretch(1) btnlayout.addWidget(bbox) vlayout = QVBoxLayout() vlayout.addWidget(hsplitter) vlayout.addLayout(btnlayout) self.setLayout(vlayout) # Signals and slots if self.main: self.button_reset.clicked.connect(self.main.reset_spyder) self.pages_widget.currentChanged.connect(self.current_page_changed) self.contents_widget.currentRowChanged.connect( self.pages_widget.setCurrentIndex) bbox.accepted.connect(self.accept) bbox.rejected.connect(self.reject) bbox.clicked.connect(self.button_clicked) # Ensures that the config is present on spyder first run CONF.set('main', 'interface_language', load_lang_conf())
def __init__(self, parent): super(AlgorithmSelector, self).__init__(parent) # layout self.algorithm_selector = AlgorithmSelectorWidget() layout = QVBoxLayout() layout.addWidget(self.algorithm_selector) self.setLayout(layout)
def __init__(self, editor_stack): """Main Window Mock constructor.""" QWidget.__init__(self, None) self.plugin_focus_changed = Mock() self.editor = EditorMock(editor_stack) layout = QVBoxLayout() layout.addWidget(self.editor) self.setLayout(layout)
def create_controls(self, path): editor = api.CodeEdit() editor.backend.start(server.__file__) # editor.panels.append(panels.FoldingPanel()) editor.panels.append(panels.LineNumberPanel()) editor.panels.append(panels.CheckerPanel()) editor.modes.append(modes.CaretLineHighlighterMode()) editor.modes.append(modes.CodeCompletionMode()) editor.modes.append(modes.ExtendedSelectionMode()) editor.modes.append(modes.FileWatcherMode()) editor.modes.append(modes.RightMarginMode()) editor.modes.append(modes.SmartBackSpaceMode()) editor.modes.append(modes.OccurrencesHighlighterMode()) editor.modes.append(modes.SymbolMatcherMode()) # editor.modes.append(modes.WordClickMode()) editor.modes.append(modes.ZoomMode()) editor.modes.append(pymodes.PythonSH(editor.document())) editor.modes.append(pymodes.CommentsMode()) editor.modes.append(ConsoleCodeCalltipsMode(self)) editor.modes.append(ConsoleCodeCheckerMode(self)) editor.modes.append(pymodes.PEP8CheckerMode()) editor.modes.append(pymodes.PyAutoCompleteMode()) editor.modes.append(pymodes.PyAutoIndentMode()) editor.modes.append(pymodes.PyIndenterMode()) if path is not None: editor.file._path = path self.editor = editor self.tab = TabWidget(self) if path is not None and os.path.isfile(path): self.tab.add_code_edit(editor) else: self.tab.add_code_edit(editor, tr("untitled") + "%d.py") self.btn_save = QPushButton(tr("Save")) self.btn_run = QPushButton(tr("Run")) self.btn_make_plugin = QPushButton(tr("Make Plugin")) self.btn_reg_plugin = QPushButton(tr("Register Plugin")) self.btn_reg_plugin.setVisible(False) self.btn_save.clicked.connect(self.save) self.btn_run.clicked.connect(self.run) self.btn_make_plugin.clicked.connect(self.make_plugin) self.btn_reg_plugin.clicked.connect(self.register_plugin) self.hbox = QHBoxLayout() for w in [self.btn_save, self.btn_run, self.btn_make_plugin, self.btn_reg_plugin]: self.hbox.addWidget(w) vbox = QVBoxLayout(self) vbox.addWidget(self.tab) vbox.addLayout(self.hbox) self.setLayout(vbox)
def __init__(self, parent): super(JupyterConsole, self).__init__(parent) # layout self.console = InProcessJupyterConsole(self, banner=BANNER, startup_code=STARTUP_CODE) layout = QVBoxLayout() layout.addWidget(self.console) self.setLayout(layout)
def __init__(self, napari_viewer): super().__init__() self.viewer = napari_viewer napari_viewer.events.layers_change.connect(self._on_layer_change) # viewers self.properties_viewer = SPropertiesViewer(napari_viewer) self.properties_viewer.setVisible(False) self.properties_viewer.setWindowFlag( qtpy.QtCore.Qt.WindowStaysOnTopHint, True) # create the dict of the filters global_layout = QVBoxLayout() global_layout.setContentsMargins(5, 5, 5, 5) self.setLayout(global_layout) filter_frame = QWidget() global_layout.addWidget(filter_frame) filter_frame.setStyleSheet(".QWidget{border: none;}") layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) # layer select tracks_selector = QWidget() tracks_selector.setStyleSheet(".QWidget{border: none;}") tracks_select_layout = QGridLayout() tracks_selector.setLayout(tracks_select_layout) self.points_layer_box = QComboBox() self.image_layer_box = QComboBox() self.points_layer_box.currentTextChanged.connect( self._on_point_layer_change) tracks_select_layout.addWidget(QLabel('Image layer'), 0, 0) tracks_select_layout.addWidget(self.image_layer_box, 0, 1) tracks_select_layout.addWidget(QLabel('Points layer'), 1, 0) tracks_select_layout.addWidget(self.points_layer_box, 1, 1) self._advanced_check = QCheckBox('Advanced') self._advanced_check.stateChanged.connect(self.toggle_advanced) tracks_select_layout.addWidget(self._advanced_check, 2, 0, 1, 2) tracks_select_layout.setContentsMargins(0, 0, 0, 0) # header widget (add filter from list) header_widget = QWidget() header_widget.setStyleSheet(".QWidget{border: 1px solid #3d4851;}") header_layout = QHBoxLayout() header_layout.addWidget(QLabel("Add feature:")) self.filters_names = QComboBox() self.filters_names.addItems(['Intensity']) header_layout.addWidget(self.filters_names) add_filter_button = QPushButton("Add") add_filter_button.released.connect(self._on_add) header_layout.addWidget(add_filter_button) header_widget.setLayout(header_layout) # FilterListWidget list_widget = QWidget() list_layout = QVBoxLayout() list_layout.setContentsMargins(0, 0, 0, 0) list_widget.setLayout(list_layout) list_widget.setStyleSheet(".QWidget{border: 1px solid #3d4851;}") self.pipeline_list_widget = SPipelineListWidget() self.pipeline_list_widget.setMinimumHeight(350) list_layout.addWidget(self.pipeline_list_widget) # viewer buttons viewer_bar = QWidget() viewer_layout = QHBoxLayout() self.properties_btn = QPushButton('particles features') self.properties_btn.released.connect(self._on_show_properties) viewer_layout.addWidget(self.properties_btn) viewer_bar.setLayout(viewer_layout) viewer_layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(tracks_selector, 0) layout.addWidget(header_widget, 0) layout.addWidget(list_widget, 1) layout.addWidget(viewer_bar, 0) layout.insertSpacing(2, -9) filter_frame.setLayout(layout) self.toggle_advanced(False)
def get_orbit_widget(self, parent): """.""" orb_wid = QWidget(parent) orb_wid.setObjectName('grp') orb_wid.setStyleSheet('#grp{min-height: 11em; max-height: 15em;}') orb_wid.setLayout(QGridLayout()) conf = PyDMPushButton( orb_wid, pressValue=1, init_channel=self.devpref.substitute(propty='TrigAcqConfig-Cmd')) conf.setToolTip('Refresh Configurations') conf.setIcon(qta.icon('fa5s.sync')) conf.setObjectName('conf') conf.setStyleSheet( '#conf{min-width:25px; max-width:25px; icon-size:20px;}') sts = QPushButton('', orb_wid) sts.setIcon(qta.icon('fa5s.list-ul')) sts.setToolTip('Open Detailed Status View') sts.setObjectName('sts') sts.setStyleSheet( '#sts{min-width:25px; max-width:25px; icon-size:20px;}') icon = qta.icon( 'fa5s.hammer', color=_util.get_appropriate_color(self.acc)) window = create_window_from_widget( StatusWidget, title='Orbit Status', icon=icon) _util.connect_window( sts, window, orb_wid, device=self.device, prefix=self.prefix, acc=self.acc, is_orb=True) pdm_led = SiriusLedAlert( orb_wid, self.devpref.substitute(propty='OrbStatus-Mon')) lbl = QLabel('Status:', orb_wid) hbl = QHBoxLayout() hbl.setSpacing(9) hbl.addStretch() hbl.addWidget(lbl) hbl.addWidget(pdm_led) hbl.addWidget(sts) hbl.addWidget(conf) orb_wid.layout().addItem(hbl, 0, 0, 1, 2) lbl = QLabel('SOFB Mode', orb_wid) wid = self.create_pair_sel(orb_wid, 'SOFBMode') orb_wid.layout().addWidget(lbl, 1, 0, alignment=Qt.AlignVCenter) orb_wid.layout().addWidget(wid, 1, 1) lbl = QLabel('RefOrb:', orb_wid) combo = RefControl( self, self.device, self.ctrls, prefix=self.prefix, acc=self.acc) lbl2 = QLabel('', orb_wid) combo.configname.connect(lbl2.setText) vbl_ref = QVBoxLayout() vbl_ref.addWidget(combo) vbl_ref.addWidget(lbl2) orb_wid.layout().addWidget(lbl, 3, 0, alignment=Qt.AlignVCenter) orb_wid.layout().addLayout(vbl_ref, 3, 1) lbl = QLabel('Num. Pts.', orb_wid) stp = SiriusSpinbox( orb_wid, self.devpref.substitute(propty='SmoothNrPts-SP')) stp.showStepExponent = False rdb = PyDMLabel( orb_wid, self.devpref.substitute(propty='SmoothNrPts-RB')) rdb.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) slsh = QLabel('/', orb_wid, alignment=Qt.AlignCenter) slsh.setStyleSheet('min-width:0.7em; max-width:0.7em;') cnt = PyDMLabel( orb_wid, self.devpref.substitute(propty='BufferCount-Mon')) cnt.setAlignment(Qt.AlignRight | Qt.AlignVCenter) cnt.setToolTip('Current Buffer Size') rst = PyDMPushButton( orb_wid, pressValue=1, init_channel=self.devpref.substitute(propty='SmoothReset-Cmd')) rst.setToolTip('Reset Buffer') rst.setIcon(qta.icon('mdi.delete-empty')) rst.setObjectName('rst') rst.setStyleSheet( '#rst{min-width:25px; max-width:25px; icon-size:20px;}') hbl = QHBoxLayout() hbl.addWidget(stp) hbl.addWidget(cnt) hbl.addWidget(slsh) hbl.addWidget(rdb) hbl.addWidget(rst) orb_wid.layout().addWidget(lbl, 4, 0, alignment=Qt.AlignVCenter) orb_wid.layout().addItem(hbl, 4, 1) orb_wid.layout().setColumnStretch(1, 2) return orb_wid
def __init__(self, parent, project_types): """Project creation dialog.""" super(ProjectDialog, self).__init__(parent=parent) self.plugin = parent self._project_types = project_types self.project_data = {} self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint) self.project_name = None self.location = get_home_dir() # Widgets projects_url = "http://docs.spyder-ide.org/current/panes/projects.html" self.description_label = QLabel( _("Select a new or existing directory to create a new Spyder " "project in it. To learn more about projects, take a look at " "our <a href=\"{0}\">documentation</a>.").format(projects_url)) self.description_label.setOpenExternalLinks(True) self.description_label.setWordWrap(True) self.groupbox = QGroupBox() self.radio_new_dir = QRadioButton(_("New directory")) self.radio_from_dir = QRadioButton(_("Existing directory")) self.label_project_name = QLabel(_('Project name')) self.label_location = QLabel(_('Location')) self.label_project_type = QLabel(_('Project type')) self.text_project_name = QLineEdit() self.text_location = QLineEdit(get_home_dir()) self.combo_project_type = QComboBox() self.label_information = QLabel("") self.label_information.hide() self.button_select_location = create_toolbutton( self, triggered=self.select_location, icon=ima.icon('DirOpenIcon'), tip=_("Select directory")) self.button_cancel = QPushButton(_('Cancel')) self.button_create = QPushButton(_('Create')) self.bbox = QDialogButtonBox(Qt.Horizontal) self.bbox.addButton(self.button_cancel, QDialogButtonBox.ActionRole) self.bbox.addButton(self.button_create, QDialogButtonBox.ActionRole) # Widget setup self.radio_new_dir.setChecked(True) self.text_location.setEnabled(True) self.text_location.setReadOnly(True) self.button_cancel.setDefault(True) self.button_cancel.setAutoDefault(True) self.button_create.setEnabled(False) for (id_, name) in [(pt_id, pt.get_name()) for pt_id, pt in project_types.items()]: self.combo_project_type.addItem(name, id_) self.setWindowTitle(_('Create new project')) # Layouts layout_top = QHBoxLayout() layout_top.addWidget(self.radio_new_dir) layout_top.addSpacing(15) layout_top.addWidget(self.radio_from_dir) layout_top.addSpacing(200) self.groupbox.setLayout(layout_top) layout_grid = QGridLayout() layout_grid.addWidget(self.label_project_name, 0, 0) layout_grid.addWidget(self.text_project_name, 0, 1, 1, 2) layout_grid.addWidget(self.label_location, 1, 0) layout_grid.addWidget(self.text_location, 1, 1) layout_grid.addWidget(self.button_select_location, 1, 2) layout_grid.addWidget(self.label_project_type, 2, 0) layout_grid.addWidget(self.combo_project_type, 2, 1, 1, 2) layout_grid.addWidget(self.label_information, 3, 0, 1, 3) layout = QVBoxLayout() layout.addWidget(self.description_label) layout.addSpacing(3) layout.addWidget(self.groupbox) layout.addSpacing(8) layout.addLayout(layout_grid) layout.addSpacing(8) layout.addWidget(self.bbox) layout.setSizeConstraint(layout.SetFixedSize) self.setLayout(layout) # Signals and slots self.button_create.clicked.connect(self.create_project) self.button_cancel.clicked.connect(self.close) self.radio_from_dir.clicked.connect(self.update_location) self.radio_new_dir.clicked.connect(self.update_location) self.text_project_name.textChanged.connect(self.update_location)
class EvolutionaryAlgorithmWindow(QMainWindow): def __init__(self, parent=None): super(EvolutionaryAlgorithmWindow, self).__init__(parent) self.__setupUI() self.__algoThreaded = EAThreaded(1,1,1,1,1) self.__algoThreaded.signal.connect(self.status) self.__thread = EAStats('data\\ea.in') self.__thread.signal.connect(self.received) def __setupUI(self): self.setWindowTitle('EA') self.solutionButton = QPushButton('Solution', self) self.solutionButton.resize(self.solutionButton.sizeHint()) self.solutionButton.clicked.connect(self.__solutionButtonClicked) self.stopSolutionButton = QPushButton('Stop solution', self) self.stopSolutionButton.resize(self.stopSolutionButton.sizeHint()) self.stopSolutionButton.clicked.connect(self.__stopSolution) self.stopSolutionButton.setEnabled(False) self.statsButton = QPushButton('Statistics', self) self.statsButton.resize(self.statsButton.sizeHint()) self.statsButton.clicked.connect(self.__statsButtonClicked) self.stopStatsButton = QPushButton('Stop stats', self) self.stopStatsButton.resize(self.stopStatsButton.sizeHint()) self.stopStatsButton.clicked.connect(self.__stopStats) self.stopStatsButton.setEnabled(False) self.horizontalBox = QHBoxLayout() self.horizontalBox.addStretch(1) self.horizontalBox.addWidget(self.solutionButton) self.horizontalBox.addWidget(self.stopSolutionButton) self.horizontalBox.addWidget(self.statsButton) self.horizontalBox.addWidget(self.stopStatsButton) individualSizeBox = QHBoxLayout() label = QLabel("individual size:") self.problemSizeInput = QLineEdit() individualSizeBox.addWidget(label) individualSizeBox.addWidget(self.problemSizeInput) popSizeBox = QHBoxLayout() popSizeLabel = QLabel("Population size:") self.populationSizeInput = QLineEdit() popSizeBox.addWidget(popSizeLabel) popSizeBox.addWidget(self.populationSizeInput) mutationsBox = QHBoxLayout() mutationsLabel = QLabel("Mutations probability:") self.mutationProbabilityInput = QLineEdit() mutationsBox.addWidget(mutationsLabel) mutationsBox.addWidget(self.mutationProbabilityInput) crossoverBox = QHBoxLayout() crossoverLabel = QLabel("Crossover probability:") self.crossoverProbabilityInput = QLineEdit() crossoverBox.addWidget(crossoverLabel) crossoverBox.addWidget(self.crossoverProbabilityInput) gensBox = QHBoxLayout() gensLabel = QLabel("Number of generations:") self.numberOfGenerationsInput = QLineEdit() gensBox.addWidget(gensLabel) gensBox.addWidget(self.numberOfGenerationsInput) self.solutionLabel = QLabel() self.statsLabel = QLabel() self.verticalBox = QVBoxLayout() self.verticalBox.addStretch(1) self.verticalBox.addLayout(individualSizeBox) self.verticalBox.addLayout(popSizeBox) self.verticalBox.addLayout(mutationsBox) self.verticalBox.addLayout(crossoverBox) self.verticalBox.addLayout(gensBox) self.verticalBox.addWidget(self.solutionLabel) self.verticalBox.addWidget(self.statsLabel) self.verticalBox.addLayout(self.horizontalBox) self.setCentralWidget(QWidget()) self.centralWidget().setLayout(self.verticalBox) def __solutionButtonClicked(self): self.__algoThreaded = EAThreaded(int(self.numberOfGenerationsInput.text()), int(self.problemSizeInput.text()), int(self.populationSizeInput.text()), float(self.crossoverProbabilityInput.text()), float(self.mutationProbabilityInput.text())) self.__algoThreaded.signal.connect(self.status) self.__algoThreaded.start() self.stopSolutionButton.setEnabled(True) self.solutionButton.setEnabled(False) def status(self, data): if len(data)==3: self.solutionButton.setEnabled(True) self.solutionLabel.setText("Solution:\n" + str(data[0]) + "\nFitness:" + str(data[1])) else: print("[EA]Step: " + str(data[1]) + " Best fitness so far:" + str(data[0])) def __stopSolution(self): self.__algoThreaded.terminate() self.stopSolutionButton.setEnabled(False) self.solutionButton.setEnabled(True) def __statsButtonClicked(self): self.statsButton.setEnabled(False) self.stopStatsButton.setEnabled(True) self.__thread.start() def __stopStats(self): self.__thread.terminate() self.statsButton.setEnabled(True) self.stopStatsButton.setEnabled(False) def received(self, data): if len(data)==3: self.statsButton.setEnabled(True) self.stopStatsButton.setEnabled(False) self.statsLabel.setText("Std dev: " + str(data[0]) + "\nMean:" + str(data[1])) plt.plot(data[2]) plt.show() else: print("[EA]Step: " + str(data[1]) + " Best fitness so far:" + str(data[0]))
def __init__(self, viewer, welcome=False): # Avoid circular import. from .layer_controls import QtLayerControlsContainer super().__init__() self.setAttribute(Qt.WA_DeleteOnClose) QCoreApplication.setAttribute( Qt.AA_UseStyleSheetPropagationInWidgetStyles, True ) self.viewer = viewer self.dims = QtDims(self.viewer.dims) self.controls = QtLayerControlsContainer(self.viewer) self.layers = QtLayerList(self.viewer.layers) self.layerButtons = QtLayerButtons(self.viewer) self.viewerButtons = QtViewerButtons(self.viewer) self._console = None layerList = QWidget() layerList.setObjectName('layerList') layerListLayout = QVBoxLayout() layerListLayout.addWidget(self.layerButtons) layerListLayout.addWidget(self.layers) layerListLayout.addWidget(self.viewerButtons) layerListLayout.setContentsMargins(8, 4, 8, 6) layerList.setLayout(layerListLayout) self.dockLayerList = QtViewerDockWidget( self, layerList, name='layer list', area='left', allowed_areas=['left', 'right'], ) self.dockLayerControls = QtViewerDockWidget( self, self.controls, name='layer controls', area='left', allowed_areas=['left', 'right'], ) self.dockConsole = QtViewerDockWidget( self, QWidget(), name='console', area='bottom', allowed_areas=['top', 'bottom'], shortcut='Ctrl+Shift+C', ) self.dockConsole.setVisible(False) # because the console is loaded lazily in the @getter, this line just # gets (or creates) the console when the dock console is made visible. self.dockConsole.visibilityChanged.connect( lambda visible: self.console if visible else None ) self.dockLayerControls.visibilityChanged.connect(self._constrain_width) self.dockLayerList.setMaximumWidth(258) self.dockLayerList.setMinimumWidth(258) # Only created if using perfmon. self.dockPerformance = self._create_performance_dock_widget() # Only created if using async rendering. self.dockRender = self._create_render_dock_widget() # This dictionary holds the corresponding vispy visual for each layer self.layer_to_visual = {} self.viewerButtons.consoleButton.clicked.connect( self.toggle_console_visibility ) self._create_canvas() main_widget = QWidget() main_layout = QVBoxLayout() main_layout.setContentsMargins(10, 22, 10, 2) main_layout.addWidget(self.canvas.native) main_layout.addWidget(self.dims) main_layout.setSpacing(10) main_widget.setLayout(main_layout) self.setOrientation(Qt.Vertical) self.addWidget(main_widget) self._last_visited_dir = str(Path.home()) self._cursors = { 'cross': Qt.CrossCursor, 'forbidden': Qt.ForbiddenCursor, 'pointing': Qt.PointingHandCursor, 'standard': QCursor(), } self._update_palette() self.viewer.events.interactive.connect(self._on_interactive) self.viewer.cursor.events.style.connect(self._on_cursor) self.viewer.cursor.events.size.connect(self._on_cursor) self.viewer.events.palette.connect(self._update_palette) self.viewer.layers.events.reordered.connect(self._reorder_layers) self.viewer.layers.events.inserted.connect(self._on_add_layer_change) self.viewer.layers.events.removed.connect(self._remove_layer) # stop any animations whenever the layers change self.viewer.events.layers_change.connect(lambda x: self.dims.stop()) self.setAcceptDrops(True) for layer in self.viewer.layers: self._add_layer(layer) self.view = self.canvas.central_widget.add_view() self.camera = VispyCamera( self.view, self.viewer.camera, self.viewer.dims ) self.canvas.connect(self.camera.on_draw) # Add axes, scale bar and welcome visuals. self._add_visuals(welcome) # Optional experimental monitor service. self._qt_monitor = _create_qt_monitor(self, self.viewer.camera) # Experimental QtPool for Octree visuals. self._qt_poll = _create_qt_poll(self, self.viewer.camera)
def __init__(self, parent=None, window_flags=None): """ Initialization and set up """ # Base class QMainWindow.__init__(self, parent) if window_flags: self.setWindowFlags(window_flags) # Mantid configuration config = ConfigService.Instance() self._instrument = config["default.instrument"] # Central widget self.centralwidget = QWidget(self) # UI Window (from Qt Designer) self.ui = load_ui(__file__, 'MainWindow.ui', baseinstance=self) mpl_layout = QVBoxLayout() self.ui.graphicsView.setLayout(mpl_layout) self.fig = Figure() self.canvas = FigureCanvas(self.fig) self.ui.mainplot = self.fig.add_subplot(111, projection='mantid') mpl_layout.addWidget(self.canvas) # Do initialize plotting vecx, vecy, xlim, ylim = self.computeMock() self.mainline = self.ui.mainplot.plot(vecx, vecy, 'r-') leftx = [xlim[0], xlim[0]] lefty = [ylim[0], ylim[1]] self.leftslideline = self.ui.mainplot.plot(leftx, lefty, 'b--') rightx = [xlim[1], xlim[1]] righty = [ylim[0], ylim[1]] self.rightslideline = self.ui.mainplot.plot(rightx, righty, 'g--') upperx = [xlim[0], xlim[1]] uppery = [ylim[1], ylim[1]] self.upperslideline = self.ui.mainplot.plot(upperx, uppery, 'b--') lowerx = [xlim[0], xlim[1]] lowery = [ylim[0], ylim[0]] self.lowerslideline = self.ui.mainplot.plot(lowerx, lowery, 'g--') self.canvas.mpl_connect('button_press_event', self.on_mouseDownEvent) # Set up horizontal slide (integer) and string value self._leftSlideValue = 0 self._rightSlideValue = 99 self.ui.horizontalSlider.setRange(0, 100) self.ui.horizontalSlider.setValue(self._leftSlideValue) self.ui.horizontalSlider.setTracking(True) self.ui.horizontalSlider.setTickPosition(QSlider.NoTicks) self.ui.horizontalSlider.valueChanged.connect(self.move_leftSlider) self.ui.horizontalSlider_2.setRange(0, 100) self.ui.horizontalSlider_2.setValue(self._rightSlideValue) self.ui.horizontalSlider_2.setTracking(True) self.ui.horizontalSlider_2.setTickPosition(QSlider.NoTicks) self.ui.horizontalSlider_2.valueChanged.connect(self.move_rightSlider) self.ui.lineEdit_3.editingFinished.connect(self.set_startTime) self.ui.pushButton_setT0.clicked.connect(self.set_startTime) self.ui.lineEdit_4.editingFinished.connect(self.set_stopTime) self.ui.pushButton_setTf.clicked.connect(self.set_stopTime) # File loader self.scanEventWorkspaces() self.ui.pushButton_refreshWS.clicked.connect(self.scanEventWorkspaces) self.ui.pushButton_browse.clicked.connect(self.browse_File) self.ui.pushButton_load.clicked.connect(self.load_File) self.ui.pushButton_3.clicked.connect(self.use_existWS) # validates any number, but does not accept comma, contrary to QDoubleValidator # this way, it is possible to cast to float without checking for stray commas. regexp = QRegExp("[-+]?((\d+\.?\d*)|(\.\d+))(e[-+]?\d+)?") # noqa # noqa because flake is not happy about regex escape sequences regexp_val = QRegExpValidator(regexp, self) # Set up time self.ui.lineEdit_3.setValidator(regexp_val) self.ui.lineEdit_4.setValidator(regexp_val) # Filter by time self.ui.pushButton_filterTime.clicked.connect(self.filterByTime) self.ui.lineEdit_timeInterval.returnPressed.connect(self.filterByTime) # Filter by log value self.ui.lineEdit_5.setValidator(regexp_val) self.ui.lineEdit_6.setValidator(regexp_val) self.ui.lineEdit_7.setValidator(regexp_val) self.ui.lineEdit_8.setValidator(regexp_val) self.ui.lineEdit_9.setValidator(regexp_val) self.ui.lineEdit_5.textChanged.connect(self.set_minLogValue) self.ui.lineEdit_6.textChanged.connect(self.set_maxLogValue) dirchangeops = ["Both", "Increase", "Decrease"] self.ui.comboBox_4.addItems(dirchangeops) logboundops = ["Centre", "Left"] self.ui.comboBox_5.addItems(logboundops) self.ui.pushButton_4.clicked.connect(self.plotLogValue) self.ui.pushButton_filterLog.clicked.connect(self.filterByLogValue) # Set up help button self.ui.helpBtn.clicked.connect(self.helpClicked) # Set up vertical slide self._upperSlideValue = 99 self._lowerSlideValue = 0 self.ui.verticalSlider.setRange(0, 100) self.ui.verticalSlider.setValue(self._upperSlideValue) self.ui.verticalSlider.setTracking(True) self.ui.verticalSlider.valueChanged.connect(self.move_upperSlider) self.ui.verticalSlider_2.setRange(0, 100) self.ui.verticalSlider_2.setValue(self._lowerSlideValue) self.ui.verticalSlider_2.setTracking(True) self.ui.verticalSlider_2.valueChanged.connect(self.move_lowerSlider) # Set up for filtering (advanced setup) self._tofcorrection = False self.ui.checkBox_fastLog.setChecked(False) self.ui.checkBox_filterByPulse.setChecked(False) self.ui.checkBox_from1.setChecked(False) self.ui.checkBox_groupWS.setChecked(True) self.ui.comboBox_tofCorr.currentIndexChanged.connect(self.showHideEi) self.ui.pushButton_refreshCorrWSList.clicked.connect( self._searchTableWorkspaces) self.ui.lineEdit_Ei.setValidator(regexp_val) self.ui.label_Ei.hide() self.ui.lineEdit_Ei.hide() self.ui.label_Ei_2.hide() self.ui.comboBox_corrWS.hide() self.ui.pushButton_refreshCorrWSList.hide() # Set up for workspaces self._dataWS = None self._sampleLogNames = [] self._sampleLog = None # Side information self.ui.label_mean.hide() self.ui.label_meanvalue.hide() self.ui.label_avg.hide() self.ui.label_timeAvgValue.hide() self.ui.label_freq.hide() self.ui.label_freqValue.hide() self.ui.label_logname.hide() self.ui.label_lognamevalue.hide() self.ui.label_logsize.hide() self.ui.label_logsizevalue.hide() # Default self._defaultdir = os.getcwd() # register startup mantid.UsageService.registerFeatureUsage( mantid.kernel.FeatureType.Interface, "EventFilter", False)
def add_color_scheme_stack(self, scheme_name, custom=False): """Add a stack for a given scheme and connects the CONF values.""" color_scheme_groups = [(_('Text'), [ "normal", "comment", "string", "number", "keyword", "builtin", "definition", "instance", ]), (_('Highlight'), [ "currentcell", "currentline", "occurrence", "matched_p", "unmatched_p", "ctrlclick" ]), (_('Background'), ["background", "sideareas"])] parent = self.parent line_edit = parent.create_lineedit(_("Scheme name:"), '{0}/name'.format(scheme_name)) self.widgets[scheme_name] = {} # Widget setup line_edit.label.setAlignment(Qt.AlignRight | Qt.AlignVCenter) self.setWindowTitle(_('Color scheme editor')) # Layout name_layout = QHBoxLayout() name_layout.addWidget(line_edit.label) name_layout.addWidget(line_edit.textbox) self.scheme_name_textbox[scheme_name] = line_edit.textbox if not custom: line_edit.textbox.setDisabled(True) if not self.isVisible(): line_edit.setVisible(False) cs_layout = QVBoxLayout() cs_layout.addLayout(name_layout) h_layout = QHBoxLayout() v_layout = QVBoxLayout() for index, item in enumerate(color_scheme_groups): group_name, keys = item group_layout = QGridLayout() for row, key in enumerate(keys): option = "{0}/{1}".format(scheme_name, key) value = self.parent.get_option(option) name = syntaxhighlighters.COLOR_SCHEME_KEYS[key] if is_text_string(value): label, clayout = parent.create_coloredit( name, option, without_layout=True, ) label.setAlignment(Qt.AlignRight | Qt.AlignVCenter) group_layout.addWidget(label, row + 1, 0) group_layout.addLayout(clayout, row + 1, 1) # Needed to update temp scheme to obtain instant preview self.widgets[scheme_name][key] = [clayout] else: label, clayout, cb_bold, cb_italic = parent.create_scedit( name, option, without_layout=True, ) label.setAlignment(Qt.AlignRight | Qt.AlignVCenter) group_layout.addWidget(label, row + 1, 0) group_layout.addLayout(clayout, row + 1, 1) group_layout.addWidget(cb_bold, row + 1, 2) group_layout.addWidget(cb_italic, row + 1, 3) # Needed to update temp scheme to obtain instant preview self.widgets[scheme_name][key] = [ clayout, cb_bold, cb_italic ] group_box = QGroupBox(group_name) group_box.setLayout(group_layout) if index == 0: h_layout.addWidget(group_box) else: v_layout.addWidget(group_box) h_layout.addLayout(v_layout) cs_layout.addLayout(h_layout) stackitem = QWidget() stackitem.setLayout(cs_layout) self.stack.addWidget(stackitem) self.order.append(scheme_name)
def __init__(self, parent): super().__init__(parent) newcb = self.create_checkbox introspection_group = QGroupBox(_("Basic features")) goto_definition_box = newcb( _("Enable Go to definition"), 'jedi_definition', tip=_("If enabled, left-clicking on an object name while \n" "pressing the {} key will go to that object's definition\n" "(if resolved).").format(self.CTRL)) follow_imports_box = newcb(_("Follow imports when going to a " "definition"), 'jedi_definition/follow_imports') show_signature_box = newcb(_("Show calltips"), 'jedi_signature_help') enable_hover_hints_box = newcb( _("Enable hover hints"), 'enable_hover_hints', tip=_("If enabled, hovering the mouse pointer over an object\n" "name will display that object's signature and/or\n" "docstring (if present).")) introspection_layout = QVBoxLayout() introspection_layout.addWidget(goto_definition_box) introspection_layout.addWidget(follow_imports_box) introspection_layout.addWidget(show_signature_box) introspection_layout.addWidget(enable_hover_hints_box) introspection_group.setLayout(introspection_layout) goto_definition_box.toggled.connect(follow_imports_box.setEnabled) # Advanced group advanced_group = QGroupBox(_("Advanced")) modules_textedit = self.create_textedit( _("Preload the following modules to make completion faster " "and more accurate:"), 'preload_modules' ) if is_dark_interface(): modules_textedit.textbox.setStyleSheet( f"border: 1px solid {QStylePalette.COLOR_BACKGROUND_2};" ) advanced_layout = QVBoxLayout() advanced_layout.addWidget(modules_textedit) advanced_group.setLayout(advanced_layout) layout = QVBoxLayout() layout.addWidget(introspection_group) layout.addWidget(advanced_group) layout.addStretch(1) self.setLayout(layout)
def _setupUi(self): lay = QVBoxLayout() lay.addWidget( QLabel('<h3>Settings</h3>', self, alignment=Qt.AlignHCenter | Qt.AlignBottom)) lay.setStretch(0, 1) # Measure l_reliablemeas = QLabel('Reliability: ') self.led_ReliableMeas = SiriusLedAlert( self, self.dcct_prefix.substitute(propty='ReliableMeas-Mon')) l_curr = QLabel('Current [mA]: ', self, alignment=Qt.AlignRight) self.label_current = PyDMLabel( self, self.dcct_prefix.substitute(propty='Current-Mon')) self.led_StoredEBeam = SiriusLedState( self, self.dcct_prefix.substitute(propty='StoredEBeam-Mon')) hlay_current = QHBoxLayout() hlay_current.addWidget(self.label_current) hlay_current.addWidget(self.led_StoredEBeam) l_enbl = QLabel('Enable:', self) self.pydmstatebutton_Enbl = PyDMStateButton( self, self.dcct_prefix.substitute(propty='Enbl-Sel')) self.pydmstatebutton_Enbl.shape = 1 self.led_Enbl = SiriusLedState( self, self.dcct_prefix.substitute(propty='Enbl-Sts')) hlay_enbl = QHBoxLayout() hlay_enbl.addWidget(self.pydmstatebutton_Enbl) hlay_enbl.addWidget(self.led_Enbl) l_meastrig = QLabel('Trigger Source:', self) self.pydmenumcombobox_MeasTrg = PyDMEnumComboBox( self, self.dcct_prefix.substitute(propty='MeasTrg-Sel')) self.pydmlabel_MeasTrg = PyDMLabel( self, self.dcct_prefix.substitute(propty='MeasTrg-Sts')) hlay_meastrig = QHBoxLayout() hlay_meastrig.addWidget(self.pydmenumcombobox_MeasTrg) hlay_meastrig.addWidget(self.pydmlabel_MeasTrg) if 'SI' in self.device: l_range = QLabel('Range: ', self) self.pydmenumcombobox_Range = PyDMEnumComboBox( self, self.dcct_prefix.substitute(propty='Range-Sel')) self.pydmlabel_Range = PyDMLabel( self, self.dcct_prefix.substitute(propty='Range-Sts')) hlay_range = QHBoxLayout() hlay_range.addWidget(self.pydmenumcombobox_Range) hlay_range.addWidget(self.pydmlabel_Range) hlay_range.setContentsMargins(0, 0, 0, 0) l_measmode = QLabel('Mode: ', self) self.pydmenumcombobox_MeasMode = PyDMEnumComboBox( self, self.dcct_prefix.substitute(propty='MeasMode-Sel')) self.pydmlabel_MeasMode = PyDMLabel( self, self.dcct_prefix.substitute(propty='MeasMode-Sts')) hlay_measmode = QHBoxLayout() hlay_measmode.addWidget(self.pydmenumcombobox_MeasMode) hlay_measmode.addWidget(self.pydmlabel_MeasMode) hlay_measmode.setContentsMargins(0, 0, 0, 0) glay_mode = QGridLayout() self.normalmode_widget = self._setupMeasSettingsWidget('Normal') self.fastmode_widget = self._setupMeasSettingsWidget('Fast') glay_mode.addWidget(self.normalmode_widget, 0, 0) glay_mode.addWidget(self.fastmode_widget, 0, 0) glay_mode.setContentsMargins(0, 0, 0, 0) self.mode_channel = SiriusConnectionSignal( self.dcct_prefix.substitute(propty='MeasMode-Sel')) self.mode_channel.new_value_signal.connect(self._showMeasModeSettings) # Details self.pb_details = QPushButton(qta.icon('fa5s.ellipsis-h'), '', self) self.pb_details.setToolTip('Open details') self.pb_details.setObjectName('detail') self.pb_details.setStyleSheet( "#detail{min-width:25px; max-width:25px; icon-size:20px;}") detail_window = create_window_from_widget(DCCTSettingsDetails, title=self.device + ' Settings Details') _hlautil.connect_window(self.pb_details, detail_window, self, prefix=self.prefix, device=self.device) gbox_gen = QGroupBox('Measure') glay_gen = QGridLayout(gbox_gen) glay_gen.setAlignment(Qt.AlignVCenter) glay_gen.addWidget(l_curr, 0, 0) glay_gen.addLayout(hlay_current, 0, 1) glay_gen.addWidget(l_reliablemeas, 1, 0) glay_gen.addWidget(self.led_ReliableMeas, 1, 1, alignment=Qt.AlignLeft) glay_gen.addWidget(l_enbl, 2, 0) glay_gen.addLayout(hlay_enbl, 2, 1) glay_gen.addWidget(l_meastrig, 3, 0) glay_gen.addLayout(hlay_meastrig, 3, 1) if 'SI' in self.device: glay_gen.addWidget(l_range, 4, 0) glay_gen.addLayout(hlay_range, 4, 1) glay_gen.addWidget(l_measmode, 5, 0) glay_gen.addLayout(hlay_measmode, 5, 1) glay_gen.addLayout(glay_mode, 6, 0, 1, 2) glay_gen.addWidget(self.pb_details, 7, 0, 1, 2, alignment=Qt.AlignRight) gbox_gen.setStyleSheet(""" .QLabel{ qproperty-alignment: 'AlignVCenter | AlignRight'; min-width: 6em;} PyDMLed{ min-width: 6em;}""") lay.addWidget(gbox_gen) lay.setStretch(1, 7) # Trigger self.trigger_widget = QGroupBox('Trigger') hbl = QHBoxLayout(self.trigger_widget) hbl.addWidget( HLTriggerSimple(self.trigger_widget, device=self.device.substitute(dis='TI'), prefix=self.prefix)) lay.addWidget(self.trigger_widget) lay.setStretch(2, 3) self.setLayout(lay) self.setStyleSheet(""" QSpinBox, QComboBox, QPushButton, PyDMSpinbox, PyDMEnumComboBox, PyDMLabel{ min-width:6em; max-width:6em;} .QLabel{max-height:1.5em;}""")
def __init__( self, config_folder=CONFIG_FOLDER, title="PartSeg", settings=None, signal_fun=None, initial_image=None ): super().__init__(config_folder, title, settings, io_functions.load_dict, signal_fun) self.channel_info = "channelcontrol" self.channel_control = ChannelProperty(self.settings, start_name="channelcontrol") self.image_view = StackImageView(self.settings, self.channel_control, name="channelcontrol") self.image_view.setMinimumWidth(450) self.info_text = QLabel() self.info_text.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Preferred) self.image_view.text_info_change.connect(self.info_text.setText) self.options_panel = Options(self.settings, self.image_view) self.main_menu = MainMenu(self.settings, self) self.main_menu.image_loaded.connect(self.image_read) self.settings.image_changed.connect(self.image_read) self.color_bar = ColorBar(self.settings, self.image_view) self.multiple_files = MultipleFileWidget(self.settings, io_functions.load_dict) self.multiple_files.setVisible(self.options_panel.image_properties.multiple_files.isChecked()) self.options_panel.algorithm_options.batch_process.multiple_result.connect( partial(self.multiple_files.save_state_action, custom_name=False) ) icon = QIcon(os.path.join(PartSegData.icons_dir, "icon_stack.png")) self.setWindowIcon(icon) menu_bar = self.menuBar() file_menu = menu_bar.addMenu("File") file_menu.addAction("&Open").triggered.connect(self.main_menu.load_image) file_menu.addMenu(self.recent_file_menu) file_menu.addAction("&Save segmentation").triggered.connect(self.main_menu.save_segmentation) file_menu.addAction("&Save components").triggered.connect(self.main_menu.save_result) view_menu = menu_bar.addMenu("View") view_menu.addAction("Settings and Measurement").triggered.connect(self.main_menu.show_advanced_window) view_menu.addAction("Additional output").triggered.connect(self.additional_layers_show) view_menu.addAction("Additional output with data").triggered.connect(lambda: self.additional_layers_show(True)) view_menu.addAction("Napari viewer").triggered.connect(self.napari_viewer_show) view_menu.addAction("Toggle Multiple Files").triggered.connect(self.toggle_multiple_files) action = view_menu.addAction("Screenshot") action.triggered.connect(self.screenshot(self.image_view)) action.setShortcut(QKeySequence.Print) image_menu = menu_bar.addMenu("Image operations") image_menu.addAction("Image adjustment").triggered.connect(self.image_adjust_exec) help_menu = menu_bar.addMenu("Help") help_menu.addAction("State directory").triggered.connect(self.show_settings_directory) help_menu.addAction("About").triggered.connect(self.show_about_dialog) layout = QVBoxLayout() layout.addWidget(self.main_menu) sub_layout = QHBoxLayout() sub2_layout = QVBoxLayout() sub3_layout = QVBoxLayout() sub_layout.addWidget(self.multiple_files) sub_layout.addWidget(self.color_bar, 0) sub3_layout.addWidget(self.image_view, 1) sub3_layout.addWidget(self.info_text, 0) sub2_layout.addWidget(self.options_panel, 1) sub2_layout.addWidget(self.channel_control, 0) sub_layout.addLayout(sub3_layout, 1) sub_layout.addLayout(sub2_layout, 0) layout.addLayout(sub_layout) self.widget = QWidget() self.widget.setLayout(layout) self.setCentralWidget(self.widget) if initial_image is None: reader = TiffImageReader() im = reader.read(self.initial_image_path) im.file_path = "" self.settings.image = im elif initial_image is False: # FIXME This is for test opening pass else: self.settings.image = initial_image try: geometry = self.settings.get_from_profile("main_window_geometry") self.restoreGeometry(QByteArray.fromHex(bytes(geometry, "ascii"))) except KeyError: pass
def __init__(self, settings: StackSettings, image_view: StackImageView): control_view = image_view.get_control_view() super().__init__() self.settings = settings self.show_result = EnumComboBox(LabelEnum) # QCheckBox("Show result") self.show_result.set_value(control_view.show_label) self.opacity = QDoubleSpinBox() self.opacity.setRange(0, 1) self.opacity.setSingleStep(0.1) self.opacity.setValue(control_view.opacity) self.only_borders = QCheckBox("Only borders") self.only_borders.setChecked(control_view.only_borders) self.borders_thick = QSpinBox() self.borders_thick.setRange(1, 11) self.borders_thick.setSingleStep(2) self.borders_thick.setValue(control_view.borders_thick) # noinspection PyUnresolvedReferences self.borders_thick.valueChanged.connect(self.border_value_check) self.execute_in_background_btn = QPushButton("Execute in background") self.execute_in_background_btn.setToolTip("Run calculation in background. Put result in multiple files panel") self.execute_btn = QPushButton("Execute") self.execute_btn.setStyleSheet("QPushButton{font-weight: bold;}") self.execute_all_btn = QPushButton("Execute all") self.execute_all_btn.setToolTip( "Execute in batch mode segmentation with current parameter. " "File list need to be specified in image tab." ) self.execute_all_btn.setDisabled(True) self.save_parameters_btn = QPushButton("Save parameters") self.block_execute_all_btn = False self.algorithm_choose_widget = AlgorithmChoose(settings, mask_algorithm_dict) self.algorithm_choose_widget.result.connect(self.execution_result_set) self.algorithm_choose_widget.finished.connect(self.execution_finished) self.algorithm_choose_widget.progress_signal.connect(self.progress_info) # self.stack_layout = QStackedLayout() self.keep_chosen_components_chk = QCheckBox("Save selected components") self.keep_chosen_components_chk.setToolTip( "Save chosen components when loading segmentation form file\n" "or from multiple file widget." ) self.keep_chosen_components_chk.stateChanged.connect(self.set_keep_chosen_components) self.keep_chosen_components_chk.setChecked(settings.keep_chosen_components) self.show_parameters = QPushButton("Show parameters") self.show_parameters.setToolTip("Show parameters of segmentation for each components") self.show_parameters_widget = SegmentationInfoDialog( self.settings, self.algorithm_choose_widget.change_algorithm ) self.show_parameters.clicked.connect(self.show_parameters_widget.show) self.choose_components = ChosenComponents() self.choose_components.check_change_signal.connect(control_view.components_change) self.choose_components.mouse_leave.connect(image_view.component_unmark) self.choose_components.mouse_enter.connect(image_view.component_mark) # WARNING works only with one channels algorithms # SynchronizeValues.add_synchronization("channels_chose", widgets_list) self.chosen_list = [] self.progress_bar2 = QProgressBar() self.progress_bar2.setHidden(True) self.progress_bar = QProgressBar() self.progress_bar.setHidden(True) self.progress_info_lab = QLabel() self.progress_info_lab.setHidden(True) self.file_list = [] self.batch_process = BatchProceed() self.batch_process.progress_signal.connect(self.progress_info) self.batch_process.error_signal.connect(self.execution_all_error) self.batch_process.execution_done.connect(self.execution_all_done) self.batch_process.range_signal.connect(self.progress_bar.setRange) self.is_batch_process = False self.setContentsMargins(0, 0, 0, 0) main_layout = QVBoxLayout() # main_layout.setSpacing(0) opt_layout = QHBoxLayout() opt_layout.setContentsMargins(0, 0, 0, 0) opt_layout.addWidget(self.show_result) opt_layout.addWidget(right_label("Opacity:")) opt_layout.addWidget(self.opacity) main_layout.addLayout(opt_layout) opt_layout2 = QHBoxLayout() opt_layout2.setContentsMargins(0, 0, 0, 0) opt_layout2.addWidget(self.only_borders) opt_layout2.addWidget(right_label("Border thick:")) opt_layout2.addWidget(self.borders_thick) main_layout.addLayout(opt_layout2) btn_layout = QGridLayout() btn_layout.setContentsMargins(0, 0, 0, 0) btn_layout.addWidget(self.execute_btn, 0, 0) btn_layout.addWidget(self.execute_in_background_btn, 0, 1) btn_layout.addWidget(self.execute_all_btn, 1, 0) btn_layout.addWidget(self.save_parameters_btn, 1, 1) main_layout.addLayout(btn_layout) main_layout.addWidget(self.progress_bar2) main_layout.addWidget(self.progress_bar) main_layout.addWidget(self.progress_info_lab) main_layout.addWidget(self.algorithm_choose_widget, 1) # main_layout.addWidget(self.algorithm_choose) # main_layout.addLayout(self.stack_layout, 1) main_layout.addWidget(self.choose_components) down_layout = QHBoxLayout() down_layout.addWidget(self.keep_chosen_components_chk) down_layout.addWidget(self.show_parameters) main_layout.addLayout(down_layout) main_layout.addStretch() main_layout.setContentsMargins(0, 0, 0, 0) # main_layout.setSpacing(0) self.setLayout(main_layout) # noinspection PyUnresolvedReferences self.execute_in_background_btn.clicked.connect(self.execute_in_background) self.execute_btn.clicked.connect(self.execute_action) self.execute_all_btn.clicked.connect(self.execute_all_action) self.save_parameters_btn.clicked.connect(self.save_parameters) # noinspection PyUnresolvedReferences self.opacity.valueChanged.connect(control_view.set_opacity) # noinspection PyUnresolvedReferences self.show_result.current_choose.connect(control_view.set_show_label) self.only_borders.stateChanged.connect(control_view.set_borders) # noinspection PyUnresolvedReferences self.borders_thick.valueChanged.connect(control_view.set_borders_thick) image_view.component_clicked.connect(self.choose_components.other_component_choose) settings.chosen_components_widget = self.choose_components settings.components_change_list.connect(self.choose_components.new_choose) settings.image_changed.connect(self.choose_components.remove_components)
def __init__(self, viewer): super().__init__() QCoreApplication.setAttribute( Qt.AA_UseStyleSheetPropagationInWidgetStyles, True) self.viewer = viewer self.dims = QtDims(self.viewer.dims) self.controls = QtControls(self.viewer) self.layers = QtLayerList(self.viewer.layers) self.buttons = QtLayersButtons(self.viewer) self.console = QtConsole({'viewer': self.viewer}) # This dictionary holds the corresponding vispy visual for each layer self.layer_to_visual = {} if self.console.shell is not None: self.console.style().unpolish(self.console) self.console.style().polish(self.console) self.console.hide() self.buttons.consoleButton.clicked.connect( lambda: self._toggle_console()) else: self.buttons.consoleButton.setEnabled(False) self.canvas = SceneCanvas(keys=None, vsync=True) self.canvas.native.setMinimumSize(QSize(200, 200)) self.canvas.connect(self.on_mouse_move) self.canvas.connect(self.on_mouse_press) self.canvas.connect(self.on_mouse_release) self.canvas.connect(self.on_key_press) self.canvas.connect(self.on_key_release) self.canvas.connect(self.on_draw) self.view = self.canvas.central_widget.add_view() self._update_camera() center = QWidget() center_layout = QVBoxLayout() center_layout.setContentsMargins(15, 20, 15, 10) center_layout.addWidget(self.canvas.native) center_layout.addWidget(self.dims) center.setLayout(center_layout) right = QWidget() right_layout = QVBoxLayout() right_layout.addWidget(self.layers) right_layout.addWidget(self.buttons) right.setLayout(right_layout) right.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding) left = self.controls top = QWidget() top_layout = QHBoxLayout() top_layout.addWidget(left) top_layout.addWidget(center) top_layout.addWidget(right) top.setLayout(top_layout) self.setOrientation(Qt.Vertical) self.addWidget(top) if self.console.shell is not None: self.addWidget(self.console) self._last_visited_dir = str(Path.home()) self._cursors = { 'disabled': QCursor( QPixmap(':/icons/cursor/cursor_disabled.png').scaled(20, 20)), 'cross': Qt.CrossCursor, 'forbidden': Qt.ForbiddenCursor, 'pointing': Qt.PointingHandCursor, 'standard': QCursor(), } self._update_palette(viewer.palette) self._key_release_generators = {} self.viewer.events.interactive.connect(self._on_interactive) self.viewer.events.cursor.connect(self._on_cursor) self.viewer.events.reset_view.connect(self._on_reset_view) self.viewer.events.palette.connect( lambda event: self._update_palette(event.palette)) self.viewer.layers.events.reordered.connect(self._reorder_layers) self.viewer.layers.events.added.connect(self._add_layer) self.viewer.layers.events.removed.connect(self._remove_layer) self.viewer.dims.events.camera.connect( lambda event: self._update_camera()) self.setAcceptDrops(True)
class TextEditor(QDialog): """Array Editor Dialog""" def __init__(self, text, title='', font=None, parent=None, readonly=False, size=(400, 300)): QDialog.__init__(self, parent) # Destroying the C++ object right after closing the dialog box, # otherwise it may be garbage-collected in another QThread # (e.g. the editor's analysis thread in Spyder), thus leading to # a segmentation fault on UNIX or an application crash on Windows self.setAttribute(Qt.WA_DeleteOnClose) self.text = None # Display text as unicode if it comes as bytes, so users see # its right representation if is_binary_string(text): self.is_binary = True text = to_text_string(text, 'utf8') else: self.is_binary = False self.layout = QVBoxLayout() self.setLayout(self.layout) # Text edit self.edit = QTextEdit(parent) self.edit.textChanged.connect(self.text_changed) self.edit.setReadOnly(readonly) self.edit.setPlainText(text) if font is None: font = get_font() self.edit.setFont(font) self.layout.addWidget(self.edit) # Buttons configuration buttons = QDialogButtonBox.Ok if not readonly: buttons = buttons | QDialogButtonBox.Cancel bbox = QDialogButtonBox(buttons) bbox.accepted.connect(self.accept) bbox.rejected.connect(self.reject) self.layout.addWidget(bbox) # Make the dialog act as a window self.setWindowFlags(Qt.Window) self.setWindowIcon(ima.icon('edit')) self.setWindowTitle(_("Text editor") + \ "%s" % (" - "+str(title) if str(title) else "")) self.resize(size[0], size[1]) def text_changed(self): """Text has changed""" # Save text as bytes, if it was initially bytes if self.is_binary: self.text = to_binary_string(self.edit.toPlainText(), 'utf8') else: self.text = to_text_string(self.edit.toPlainText()) def get_value(self): """Return modified text""" # It is import to avoid accessing Qt C++ object as it has probably # already been destroyed, due to the Qt.WA_DeleteOnClose attribute return self.text
def initUi(self): try: self.setWindowTitle(u"期权选择器") self.setMinimumWidth(1200) self.setMinimumHeight(800) labelStockCode = QLabel(u"代码") labelStockPrice = QLabel(u"价格(非实时)") labelSTDTimes = QLabel(u"标准差倍数") labelSTDValue = QLabel(u"标准差") labelSTDDays = QLabel(u"计算天数") lableStartDate = QLabel(u"开始日期") labelEndDate = QLabel(u"结束日期") labelType = QLabel(u"类型") labelStrikePrice = QLabel(u"行权价范围") self.lineStockCode = QLineEdit() self.lineStockPrice = QLineEdit() self.lineStockPrice.setEnabled(False) self.lineSTDTimes = QLineEdit() self.lineSTDValue = QLineEdit() self.lineSTDValue.setEnabled(False) self.lineSTDDays = QLineEdit() self.lineStartDate = QLineEdit() self.lineEndDate = QLineEdit() self.comboxType = QComboBox() self.comboxType.addItems(self.optionType) self.lineLowStrikePrice = QLineEdit() self.lineHighStrikePrice = QLineEdit() btQry = QPushButton(u"查询") btSort = QPushButton(u"排序开关") glayout = QGridLayout() glayout.addWidget(labelStockCode, 0, 0) glayout.addWidget(labelStockPrice, 0, 1) glayout.addWidget(labelSTDTimes, 0, 2) glayout.addWidget(labelSTDValue, 0, 3) glayout.addWidget(labelSTDDays, 0, 4) glayout.addWidget(self.lineStockCode, 1, 0) glayout.addWidget(self.lineStockPrice, 1, 1) glayout.addWidget(self.lineSTDTimes, 1, 2) glayout.addWidget(self.lineSTDValue, 1, 3) glayout.addWidget(self.lineSTDDays, 1, 4) self.lineStockCode.setMaximumWidth(150) self.lineStockPrice.setMaximumWidth(150) self.lineSTDTimes.setMaximumWidth(80) self.lineSTDValue.setMaximumWidth(150) self.lineSTDDays.setMaximumWidth(80) glayout.addWidget(lableStartDate, 2, 0) glayout.addWidget(labelEndDate, 2, 1) glayout.addWidget(labelType, 2, 2) glayout.addWidget(labelStrikePrice, 2, 3) glayout.addWidget(self.lineStartDate, 3, 0) glayout.addWidget(self.lineEndDate, 3, 1) glayout.addWidget(self.comboxType, 3, 2) glayout.addWidget(self.lineLowStrikePrice, 3, 3) glayout.addWidget(self.lineHighStrikePrice, 3, 4) self.lineStartDate.setMaximumWidth(150) self.lineEndDate.setMaximumWidth(150) self.lineLowStrikePrice.setMaximumWidth(150) self.lineHighStrikePrice.setMaximumWidth(150) glayout.addWidget(btQry, 4, 0) glayout.addWidget(btSort, 4, 1) vbox = QVBoxLayout() # 策略状态组件 self.optionSelectorMonitorWidget = OptionSelectorMonitor(self.optionSelectorEngine, self.eventEngine, \ self.mainWindow) groupBoxStraMonitor = GroupBoxWithSinglWidget( self.optionSelectorMonitorWidget, u"期权信息") vbox.addLayout(glayout) vbox.addWidget(groupBoxStraMonitor) self.setLayout(vbox) btQry.clicked.connect(self.qryOptionList) btSort.clicked.connect(self.switchSort) self.lineStockCode.returnPressed.connect(self.pressPriceReturn) self.optionSelectorMonitorWidget.itemDoubleClicked.connect( self.passOptionSelectorDataToMainWindow) except: traceback.print_exc()
def __init__(self, device, preprocess_enabled=True, maxfps=2): super(AreaDetectorController, self).__init__(device) self.maxfps = maxfps self.preprocess_enabled = preprocess_enabled self._autolevel = True self.RE = get_run_engine() self.setLayout(QVBoxLayout()) self.coupled_devices = [] self.cached_frame = None self.imageview = self.viewclass() self.passive = QCheckBox('Passive Mode') self.passive.setChecked(True) self.error_text = pg.TextItem('Waiting for data...') self.imageview.view.addItem(self.error_text) self.layout().addWidget(self.imageview) self.layout().addWidget(self.passive) self.metadata = {} config_layout = QFormLayout() config_layout.addRow( 'Acquire Time', PyDMLineEdit( init_channel=f'ca://{device.cam.acquire_time.setpoint_pvname}') ) config_layout.addRow( 'Acquire Period', PyDMLineEdit( init_channel=f'ca://{device.cam.acquire_period.setpoint_pvname}' )) config_layout.addRow( 'Number of Images', PyDMLineEdit( init_channel=f'ca://{device.hdf5.num_capture.setpoint_pvname}') ) config_layout.addRow( 'Number of Exposures', PyDMLineEdit( init_channel=f'ca://{device.cam.num_exposures.setpoint_pvname}' )) # config_layout.addRow('Image Mode', PyDMEnumComboBox(init_channel=f'ca://{device.cam.image_mode.setpoint_pvname}')) # config_layout.addRow('Trigger Mode', PyDMEnumComboBox(init_channel=f'ca://{device.cam.trigger_mode.setpoint_pvname}')) config_panel = QGroupBox('Configuration') config_panel.setLayout(config_layout) acquire_layout = QVBoxLayout() acquire_button = QPushButton('Acquire') acquire_button.clicked.connect(self.acquire) acquire_layout.addWidget(acquire_button) acquire_panel = QGroupBox('Acquire') acquire_panel.setLayout(acquire_layout) self.hlayout = QHBoxLayout() self.hlayout.addWidget(config_panel) self.hlayout.addWidget(acquire_panel) self.layout().addLayout(self.hlayout) # WIP # self.lutCheck = QCheckBox() # self.LUT = GradientWidget() # self.downsampleCheck = QCheckBox() # self.scaleCheck = QCheckBox() # self.rgbLevelsCheck = QCheckBox() self.thread = None self._last_timestamp = time.time() # self.update_timer = QTimer() # self.update_timer.setInterval(1000 // maxfps) # self.update_timer.timeout.connect(self.updateFrame) # self.update_timer.start() # self.device.image1.shaped_image.subscribe(self.cacheFrame, 'value') self.setPassive(True) self.passive.toggled.connect(self.setPassive)
def setup_page(self): newcb = self.create_checkbox # Interface Group interface_group = QGroupBox(_("Interface")) banner_box = newcb(_("Display initial banner"), 'show_banner', tip=_("This option lets you hide the message " "shown at\nthe top of the console when " "it's opened.")) pager_box = newcb(_("Use a pager to display additional text inside " "the console"), 'use_pager', tip=_("Useful if you don't want to fill the " "console with long help or completion " "texts.\n" "Note: Use the Q key to get out of the " "pager.")) calltips_box = newcb(_("Display balloon tips"), 'show_calltips') ask_box = newcb(_("Ask for confirmation before closing"), 'ask_before_closing') reset_namespace_box = newcb( _("Ask for confirmation before removing all user-defined " "variables"), 'show_reset_namespace_warning', tip=_("This option lets you hide the warning message shown\n" "when resetting the namespace from Spyder.")) show_time_box = newcb(_("Show elapsed time"), 'show_elapsed_time') ask_restart_box = newcb( _("Ask for confirmation before restarting"), 'ask_before_restart', tip=_("This option lets you hide the warning message shown\n" "when restarting the kernel.")) interface_layout = QVBoxLayout() interface_layout.addWidget(banner_box) interface_layout.addWidget(pager_box) interface_layout.addWidget(calltips_box) interface_layout.addWidget(ask_box) interface_layout.addWidget(reset_namespace_box) interface_layout.addWidget(show_time_box) interface_layout.addWidget(ask_restart_box) interface_group.setLayout(interface_layout) comp_group = QGroupBox(_("Completion Type")) comp_label = QLabel(_("Decide what type of completion to use")) comp_label.setWordWrap(True) completers = [(_("Graphical"), 0), (_("Terminal"), 1), (_("Plain"), 2)] comp_box = self.create_combobox( _("Completion:") + " ", completers, 'completion_type') comp_layout = QVBoxLayout() comp_layout.addWidget(comp_label) comp_layout.addWidget(comp_box) comp_group.setLayout(comp_layout) # Source Code Group source_code_group = QGroupBox(_("Source code")) buffer_spin = self.create_spinbox( _("Buffer: "), _(" lines"), 'buffer_size', min_=-1, max_=1000000, step=100, tip=_("Set the maximum number of lines of text shown in the\n" "console before truncation. Specifying -1 disables it\n" "(not recommended!)")) source_code_layout = QVBoxLayout() source_code_layout.addWidget(buffer_spin) source_code_group.setLayout(source_code_layout) # --- Graphics --- # Pylab Group pylab_group = QGroupBox(_("Support for graphics (Matplotlib)")) pylab_box = newcb(_("Activate support"), 'pylab') autoload_pylab_box = newcb( _("Automatically load Pylab and NumPy modules"), 'pylab/autoload', tip=_("This lets you load graphics support without importing\n" "the commands to do plots. Useful to work with other\n" "plotting libraries different to Matplotlib or to develop\n" "GUIs with Spyder.")) autoload_pylab_box.setEnabled(self.get_option('pylab')) pylab_box.toggled.connect(autoload_pylab_box.setEnabled) pylab_layout = QVBoxLayout() pylab_layout.addWidget(pylab_box) pylab_layout.addWidget(autoload_pylab_box) pylab_group.setLayout(pylab_layout) # Pylab backend Group inline = _("Inline") automatic = _("Automatic") backend_group = QGroupBox(_("Graphics backend")) bend_label = QLabel( _("Decide how graphics are going to be displayed " "in the console. If unsure, please select " "<b>%s</b> to put graphics inside the " "console or <b>%s</b> to interact with " "them (through zooming and panning) in a " "separate window.") % (inline, automatic)) bend_label.setWordWrap(True) backends = [(inline, 0), (automatic, 1), ("Qt5", 2), ("Qt4", 3)] if sys.platform == 'darwin': backends.append(("OS X", 4)) if sys.platform.startswith('linux'): backends.append(("Gtk3", 5)) backends.append(("Gtk", 6)) if PY2: backends.append(("Wx", 7)) backends.append(("Tkinter", 8)) backends = tuple(backends) backend_box = self.create_combobox( _("Backend:") + " ", backends, 'pylab/backend', default=0, tip=_("This option will be applied the next time a console is " "opened.")) backend_layout = QVBoxLayout() backend_layout.addWidget(bend_label) backend_layout.addWidget(backend_box) backend_group.setLayout(backend_layout) backend_group.setEnabled(self.get_option('pylab')) pylab_box.toggled.connect(backend_group.setEnabled) # Inline backend Group inline_group = QGroupBox(_("Inline backend")) inline_label = QLabel( _("Decide how to render the figures created by " "this backend")) inline_label.setWordWrap(True) formats = (("PNG", 0), ("SVG", 1)) format_box = self.create_combobox(_("Format:") + " ", formats, 'pylab/inline/figure_format', default=0) resolution_spin = self.create_spinbox( _("Resolution:") + " ", " " + _("dpi"), 'pylab/inline/resolution', min_=50, max_=999, step=0.1, tip=_("Only used when the format is PNG. Default is " "72")) width_spin = self.create_spinbox(_("Width:") + " ", " " + _("inches"), 'pylab/inline/width', min_=2, max_=20, step=1, tip=_("Default is 6")) height_spin = self.create_spinbox(_("Height:") + " ", " " + _("inches"), 'pylab/inline/height', min_=1, max_=20, step=1, tip=_("Default is 4")) bbox_inches_box = newcb(_("Use a tight layout for inline plots"), 'pylab/inline/bbox_inches', tip=_( "Sets bbox_inches to \"tight\" when\n" "plotting inline with matplotlib.\n" "When enabled, can cause discrepancies\n" "between the image displayed inline and\n" "that created using savefig.")) inline_v_layout = QVBoxLayout() inline_v_layout.addWidget(inline_label) inline_layout = QGridLayout() inline_layout.addWidget(format_box.label, 1, 0) inline_layout.addWidget(format_box.combobox, 1, 1) inline_layout.addWidget(resolution_spin.plabel, 2, 0) inline_layout.addWidget(resolution_spin.spinbox, 2, 1) inline_layout.addWidget(resolution_spin.slabel, 2, 2) inline_layout.addWidget(width_spin.plabel, 3, 0) inline_layout.addWidget(width_spin.spinbox, 3, 1) inline_layout.addWidget(width_spin.slabel, 3, 2) inline_layout.addWidget(height_spin.plabel, 4, 0) inline_layout.addWidget(height_spin.spinbox, 4, 1) inline_layout.addWidget(height_spin.slabel, 4, 2) inline_layout.addWidget(bbox_inches_box, 5, 0, 1, 4) inline_h_layout = QHBoxLayout() inline_h_layout.addLayout(inline_layout) inline_h_layout.addStretch(1) inline_v_layout.addLayout(inline_h_layout) inline_group.setLayout(inline_v_layout) inline_group.setEnabled(self.get_option('pylab')) pylab_box.toggled.connect(inline_group.setEnabled) # --- Startup --- # Run lines Group run_lines_group = QGroupBox(_("Run code")) run_lines_label = QLabel( _("You can run several lines of code when " "a console is started. Please introduce " "each one separated by semicolons and a " "space, for example:<br>" "<i>import os; import sys</i>")) run_lines_label.setWordWrap(True) run_lines_edit = self.create_lineedit(_("Lines:"), 'startup/run_lines', '', alignment=Qt.Horizontal) run_lines_layout = QVBoxLayout() run_lines_layout.addWidget(run_lines_label) run_lines_layout.addWidget(run_lines_edit) run_lines_group.setLayout(run_lines_layout) # Run file Group run_file_group = QGroupBox(_("Run a file")) run_file_label = QLabel( _("You can also run a whole file at startup " "instead of just some lines (This is " "similar to have a PYTHONSTARTUP file).")) run_file_label.setWordWrap(True) file_radio = newcb(_("Use the following file:"), 'startup/use_run_file', False) run_file_browser = self.create_browsefile('', 'startup/run_file', '') run_file_browser.setEnabled(False) file_radio.toggled.connect(run_file_browser.setEnabled) run_file_layout = QVBoxLayout() run_file_layout.addWidget(run_file_label) run_file_layout.addWidget(file_radio) run_file_layout.addWidget(run_file_browser) run_file_group.setLayout(run_file_layout) # ---- Advanced settings ---- # Enable Jedi completion jedi_group = QGroupBox(_("Jedi completion")) jedi_label = QLabel( _("Enable Jedi-based <tt>Tab</tt> completion " "in the IPython console; similar to the " "greedy completer, but without evaluating " "the code.<br>" "<b>Warning:</b> Slows down your console " "when working with large dataframes!")) jedi_label.setWordWrap(True) jedi_box = newcb(_("Use Jedi completion in the IPython console"), "jedi_completer", tip=_("<b>Warning</b>: " "Slows down your console when working with " "large dataframes!<br>" "Allows completion of nested lists etc.")) jedi_layout = QVBoxLayout() jedi_layout.addWidget(jedi_label) jedi_layout.addWidget(jedi_box) jedi_group.setLayout(jedi_layout) # Greedy completer group greedy_group = QGroupBox(_("Greedy completion")) greedy_label = QLabel( _("Enable <tt>Tab</tt> completion on elements " "of lists, results of function calls, etc, " "<i>without</i> assigning them to a variable, " "like <tt>li[0].<Tab></tt> or " "<tt>ins.meth().<Tab></tt> <br>" "<b>Warning:</b> Due to a bug, IPython's " "greedy completer requires a leading " "<tt><Space></tt> for some completions; " "e.g. <tt>np.sin(<Space>np.<Tab>" "</tt> works while <tt>np.sin(np.<Tab> " "</tt> doesn't.")) greedy_label.setWordWrap(True) greedy_box = newcb(_("Use greedy completion in the IPython console"), "greedy_completer", tip="<b>Warning</b>: It can be unsafe because the " "code is actually evaluated when you press " "<tt>Tab</tt>.") greedy_layout = QVBoxLayout() greedy_layout.addWidget(greedy_label) greedy_layout.addWidget(greedy_box) greedy_group.setLayout(greedy_layout) # Autocall group autocall_group = QGroupBox(_("Autocall")) autocall_label = QLabel( _("Autocall makes IPython automatically call " "any callable object even if you didn't " "type explicit parentheses.<br>" "For example, if you type <i>str 43</i> it " "becomes <i>str(43)</i> automatically.")) autocall_label.setWordWrap(True) smart = _('Smart') full = _('Full') autocall_opts = ((_('Off'), 0), (smart, 1), (full, 2)) autocall_box = self.create_combobox( _("Autocall: "), autocall_opts, 'autocall', default=0, tip=_("On <b>%s</b> mode, Autocall is not applied if " "there are no arguments after the callable. On " "<b>%s</b> mode, all callable objects are " "automatically called (even if no arguments are " "present).") % (smart, full)) autocall_layout = QVBoxLayout() autocall_layout.addWidget(autocall_label) autocall_layout.addWidget(autocall_box) autocall_group.setLayout(autocall_layout) # Sympy group sympy_group = QGroupBox(_("Symbolic Mathematics")) sympy_label = QLabel( _("Perfom symbolic operations in the console " "(e.g. integrals, derivatives, vector " "calculus, etc) and get the outputs in a " "beautifully printed style (it requires the " "Sympy module).")) sympy_label.setWordWrap(True) sympy_box = newcb(_("Use symbolic math"), "symbolic_math", tip=_("This option loads the Sympy library to work " "with.<br>Please refer to its documentation " "to learn how to use it.")) sympy_layout = QVBoxLayout() sympy_layout.addWidget(sympy_label) sympy_layout.addWidget(sympy_box) sympy_group.setLayout(sympy_layout) # Prompts group prompts_group = QGroupBox(_("Prompts")) prompts_label = QLabel( _("Modify how Input and Output prompts are " "shown in the console.")) prompts_label.setWordWrap(True) in_prompt_edit = self.create_lineedit( _("Input prompt:"), 'in_prompt', '', _('Default is<br>' 'In [<span class="in-prompt-number">' '%i</span>]:'), alignment=Qt.Horizontal) out_prompt_edit = self.create_lineedit( _("Output prompt:"), 'out_prompt', '', _('Default is<br>' 'Out[<span class="out-prompt-number">' '%i</span>]:'), alignment=Qt.Horizontal) prompts_layout = QVBoxLayout() prompts_layout.addWidget(prompts_label) prompts_g_layout = QGridLayout() prompts_g_layout.addWidget(in_prompt_edit.label, 0, 0) prompts_g_layout.addWidget(in_prompt_edit.textbox, 0, 1) prompts_g_layout.addWidget(out_prompt_edit.label, 1, 0) prompts_g_layout.addWidget(out_prompt_edit.textbox, 1, 1) prompts_layout.addLayout(prompts_g_layout) prompts_group.setLayout(prompts_layout) # --- Tabs organization --- tabs = QTabWidget() tabs.addTab( self.create_tab(interface_group, comp_group, source_code_group), _("Display")) tabs.addTab(self.create_tab(pylab_group, backend_group, inline_group), _("Graphics")) tabs.addTab(self.create_tab(run_lines_group, run_file_group), _("Startup")) tabs.addTab( self.create_tab(jedi_group, greedy_group, autocall_group, sympy_group, prompts_group), _("Advanced Settings")) vlayout = QVBoxLayout() vlayout.addWidget(tabs) self.setLayout(vlayout)
def create_layout(self): """displays the menu objects""" grid = QGridLayout() grid.addWidget(self.icase, 0, 0) grid.addWidget(self.icase_edit, 0, 1) grid.addWidget(self.scale, 1, 0) grid.addWidget(self.scale_edit, 1, 1) grid.addWidget(self.scale_button, 1, 2) grid.addWidget(self.time, 2, 0) grid.addWidget(self.time_edit, 2, 1) grid.addWidget(self.time_button, 2, 2) # spacer spacer = QLabel('') grid.addWidget(self.fps, 3, 0) grid.addWidget(self.fps_edit, 3, 1) grid.addWidget(self.fps_button, 3, 2) grid.addWidget(self.resolution, 4, 0) grid.addWidget(self.resolution_edit, 4, 1) grid.addWidget(self.resolution_button, 4, 2) grid.addWidget(self.browse_folder, 5, 0) grid.addWidget(self.browse_folder_edit, 5, 1) grid.addWidget(self.browse_folder_button, 5, 2) grid.addWidget(self.gif, 6, 0) grid.addWidget(self.gif_edit, 6, 1) grid.addWidget(self.gif_button, 6, 2) grid.addWidget(self.animation_type, 7, 0) grid.addWidget(self.animation_type_edit, 7, 1) grid.addWidget(spacer, 8, 0) #---------- #Time grid_time = QGridLayout() grid_time.addWidget(self.icase_start, 0, 0) grid_time.addWidget(self.icase_start_edit, 0, 1) #grid_time.addWidget(self.icase_start_button, 0, 2) grid_time.addWidget(self.icase_end, 1, 0) grid_time.addWidget(self.icase_end_edit, 1, 1) #grid_time.addWidget(self.icase_end_button, 1, 2) grid_time.addWidget(self.icase_delta, 2, 0) grid_time.addWidget(self.icase_delta_edit, 2, 1) #grid_time.addWidget(self.icase_delta_button, 2, 2) #grid_time.addWidget(self.min_value, 3, 0) #grid_time.addWidget(self.min_value_edit, 3, 1) #grid_time.addWidget(self.min_value_button, 3, 2) #grid_time.addWidget(self.max_value, 4, 0) #grid_time.addWidget(self.max_value_edit, 4, 1) #grid_time.addWidget(self.max_value_button, 4, 2) grid_time.addWidget(spacer, 5, 0) #-------------- grid_scale = QGridLayout() grid_scale.addWidget(self.animation_profile, 0, 0) grid_scale.addWidget(self.animation_profile_edit, 0, 1) #grid_scale.addWidget(self.csv_profile, 1, 0) #grid_scale.addWidget(self.csv_profile_edit, 1, 1) #grid_scale.addWidget(self.csv_profile_browse_button, 1, 2) self.csv_profile = QLabel("CSV profile:") self.csv_profile_edit = QLineEdit() self.csv_profile_button = QPushButton('Browse') #box_time = QVBoxLayout() # TODO: It's super annoying that the animate time box doesn't # line up with the previous box box_scale = QGroupBox('Animate Scale') box_scale.setLayout(grid_scale) box_time = QGroupBox('Animate Time') box_time.setLayout(grid_time) #---------- grid2 = QGridLayout() #grid2.addWidget(self.animate_scale_radio, 8, 0) #grid2.addWidget(self.animate_phase_radio, 8, 1) #grid2.addWidget(self.animate_time_radio, 8, 2) #grid2.addWidget(self.animate_freq_sweeep_radio, 8, 3) grid2.addWidget(self.animate_in_gui_checkbox, 10, 0) grid2.addWidget(self.make_images_checkbox, 11, 0) #grid2.addWidget(self.overwrite_images_checkbox, 11, 0) grid2.addWidget(self.delete_images_checkbox, 11, 1) grid2.addWidget(self.make_gif_checkbox, 11, 2) grid2.addWidget(self.repeat_checkbox, 12, 0) grid2.addWidget(spacer, 13, 0) grid_hbox = QHBoxLayout() grid_hbox.addWidget(spacer) grid_hbox.addLayout(grid2) grid_hbox.addWidget(spacer) # bottom buttons step_run_box = QHBoxLayout() step_run_box.addWidget(self.step_button) step_run_box.addWidget(self.wipe_button) step_run_box.addWidget(self.stop_button) step_run_box.addWidget(self.run_button) ok_cancel_box = QHBoxLayout() ok_cancel_box.addWidget(self.cancel_button) vbox = QVBoxLayout() vbox.addLayout(grid) vbox.addWidget(box_scale) vbox.addWidget(box_time) #vbox.addLayout(checkboxes) vbox.addLayout(grid_hbox) vbox.addStretch() vbox.addLayout(step_run_box) vbox.addLayout(ok_cancel_box) self.setLayout(vbox)
def __init__(self, parent, text, title=None, icon=None, contents_title=None, varname=None): QDialog.__init__(self, parent) # Destroying the C++ object right after closing the dialog box, # otherwise it may be garbage-collected in another QThread # (e.g. the editor's analysis thread in Spyder), thus leading to # a segmentation fault on UNIX or an application crash on Windows self.setAttribute(Qt.WA_DeleteOnClose) if title is None: title = _("Import wizard") self.setWindowTitle(title) if icon is None: self.setWindowIcon(ima.icon('fileimport')) if contents_title is None: contents_title = _("Raw text") if varname is None: varname = _("variable_name") self.var_name, self.clip_data = None, None # Setting GUI self.tab_widget = QTabWidget(self) self.text_widget = ContentsWidget(self, text) self.table_widget = PreviewWidget(self) self.tab_widget.addTab(self.text_widget, _("text")) self.tab_widget.setTabText(0, contents_title) self.tab_widget.addTab(self.table_widget, _("table")) self.tab_widget.setTabText(1, _("Preview")) self.tab_widget.setTabEnabled(1, False) name_layout = QHBoxLayout() name_label = QLabel(_("Variable Name")) name_layout.addWidget(name_label) self.name_edt = QLineEdit() self.name_edt.setText(varname) name_layout.addWidget(self.name_edt) btns_layout = QHBoxLayout() cancel_btn = QPushButton(_("Cancel")) btns_layout.addWidget(cancel_btn) cancel_btn.clicked.connect(self.reject) h_spacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) btns_layout.addItem(h_spacer) self.back_btn = QPushButton(_("Previous")) self.back_btn.setEnabled(False) btns_layout.addWidget(self.back_btn) self.back_btn.clicked.connect(ft_partial(self._set_step, step=-1)) self.fwd_btn = QPushButton(_("Next")) btns_layout.addWidget(self.fwd_btn) self.fwd_btn.clicked.connect(ft_partial(self._set_step, step=1)) self.done_btn = QPushButton(_("Done")) self.done_btn.setEnabled(False) btns_layout.addWidget(self.done_btn) self.done_btn.clicked.connect(self.process) self.text_widget.asDataChanged.connect(self.fwd_btn.setEnabled) self.text_widget.asDataChanged.connect(self.done_btn.setDisabled) layout = QVBoxLayout() layout.addLayout(name_layout) layout.addWidget(self.tab_widget) layout.addLayout(btns_layout) self.setLayout(layout)
def setup_gui(self): """Setup the main layout of the widget.""" layout = QVBoxLayout(self) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(0) layout.addWidget(self.setup_scrollarea())
def __init__(self, parent, text): QWidget.__init__(self, parent) self.text_editor = QTextEdit(self) self.text_editor.setText(text) self.text_editor.setReadOnly(True) # Type frame type_layout = QHBoxLayout() type_label = QLabel(_("Import as")) type_layout.addWidget(type_label) data_btn = QRadioButton(_("data")) data_btn.setChecked(True) self._as_data = True type_layout.addWidget(data_btn) code_btn = QRadioButton(_("code")) self._as_code = False type_layout.addWidget(code_btn) txt_btn = QRadioButton(_("text")) type_layout.addWidget(txt_btn) h_spacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) type_layout.addItem(h_spacer) type_frame = QFrame() type_frame.setLayout(type_layout) # Opts frame grid_layout = QGridLayout() grid_layout.setSpacing(0) col_label = QLabel(_("Column separator:")) grid_layout.addWidget(col_label, 0, 0) col_w = QWidget() col_btn_layout = QHBoxLayout() self.tab_btn = QRadioButton(_("Tab")) self.tab_btn.setChecked(False) col_btn_layout.addWidget(self.tab_btn) other_btn_col = QRadioButton(_("other")) other_btn_col.setChecked(True) col_btn_layout.addWidget(other_btn_col) col_w.setLayout(col_btn_layout) grid_layout.addWidget(col_w, 0, 1) self.line_edt = QLineEdit(",") self.line_edt.setMaximumWidth(30) self.line_edt.setEnabled(True) other_btn_col.toggled.connect(self.line_edt.setEnabled) grid_layout.addWidget(self.line_edt, 0, 2) row_label = QLabel(_("Row separator:")) grid_layout.addWidget(row_label, 1, 0) row_w = QWidget() row_btn_layout = QHBoxLayout() self.eol_btn = QRadioButton(_("EOL")) self.eol_btn.setChecked(True) row_btn_layout.addWidget(self.eol_btn) other_btn_row = QRadioButton(_("other")) row_btn_layout.addWidget(other_btn_row) row_w.setLayout(row_btn_layout) grid_layout.addWidget(row_w, 1, 1) self.line_edt_row = QLineEdit(";") self.line_edt_row.setMaximumWidth(30) self.line_edt_row.setEnabled(False) other_btn_row.toggled.connect(self.line_edt_row.setEnabled) grid_layout.addWidget(self.line_edt_row, 1, 2) grid_layout.setRowMinimumHeight(2, 15) other_group = QGroupBox(_("Additional options")) other_layout = QGridLayout() other_group.setLayout(other_layout) skiprows_label = QLabel(_("Skip rows:")) other_layout.addWidget(skiprows_label, 0, 0) self.skiprows_edt = QLineEdit('0') self.skiprows_edt.setMaximumWidth(30) intvalid = QIntValidator(0, len(to_text_string(text).splitlines()), self.skiprows_edt) self.skiprows_edt.setValidator(intvalid) other_layout.addWidget(self.skiprows_edt, 0, 1) other_layout.setColumnMinimumWidth(2, 5) comments_label = QLabel(_("Comments:")) other_layout.addWidget(comments_label, 0, 3) self.comments_edt = QLineEdit('#') self.comments_edt.setMaximumWidth(30) other_layout.addWidget(self.comments_edt, 0, 4) self.trnsp_box = QCheckBox(_("Transpose")) #self.trnsp_box.setEnabled(False) other_layout.addWidget(self.trnsp_box, 1, 0, 2, 0) grid_layout.addWidget(other_group, 3, 0, 2, 0) opts_frame = QFrame() opts_frame.setLayout(grid_layout) data_btn.toggled.connect(opts_frame.setEnabled) data_btn.toggled.connect(self.set_as_data) code_btn.toggled.connect(self.set_as_code) # self.connect(txt_btn, SIGNAL("toggled(bool)"), # self, SLOT("is_text(bool)")) # Final layout layout = QVBoxLayout() layout.addWidget(type_frame) layout.addWidget(self.text_editor) layout.addWidget(opts_frame) self.setLayout(layout)
def setup_page(self): self.ICON = ima.icon('eyedropper') names = self.get_option("names") try: names.pop(names.index(u'Custom')) except ValueError: pass custom_names = self.get_option("custom_names", []) # Interface options theme_group = QGroupBox(_("Main interface")) # Interface Widgets ui_themes = ['Automatic', 'Light', 'Dark'] ui_theme_choices = list( zip(ui_themes, [ui_theme.lower() for ui_theme in ui_themes])) ui_theme_combo = self.create_combobox(_('Interface theme'), ui_theme_choices, 'ui_theme', restart=True) styles = [str(txt) for txt in list(QStyleFactory.keys())] # Don't offer users the possibility to change to a different # style in Gtk-based desktops # See spyder-ide/spyder#2036. if is_gtk_desktop() and ('GTK+' in styles): styles = ['GTK+'] choices = list(zip(styles, [style.lower() for style in styles])) style_combo = self.create_combobox(_('Qt windows style'), choices, 'windows_style', default=self.main.default_style) self.style_combobox = style_combo.combobox themes = ['Spyder 2', 'Spyder 3'] icon_choices = list(zip(themes, [theme.lower() for theme in themes])) icons_combo = self.create_combobox(_('Icon theme'), icon_choices, 'icon_theme', restart=True) theme_comboboxes_layout = QGridLayout() theme_comboboxes_layout.addWidget(ui_theme_combo.label, 0, 0) theme_comboboxes_layout.addWidget(ui_theme_combo.combobox, 0, 1) theme_comboboxes_layout.addWidget(style_combo.label, 1, 0) theme_comboboxes_layout.addWidget(self.style_combobox, 1, 1) theme_comboboxes_layout.addWidget(icons_combo.label, 2, 0) theme_comboboxes_layout.addWidget(icons_combo.combobox, 2, 1) theme_layout = QVBoxLayout() theme_layout.addLayout(theme_comboboxes_layout) theme_group.setLayout(theme_layout) # Syntax coloring options syntax_group = QGroupBox(_("Syntax highlighting theme")) # Syntax Widgets edit_button = QPushButton(_("Edit selected scheme")) create_button = QPushButton(_("Create new scheme")) self.delete_button = QPushButton(_("Delete scheme")) self.reset_button = QPushButton(_("Reset to defaults")) self.preview_editor = CodeEditor(self) self.stacked_widget = QStackedWidget(self) self.scheme_editor_dialog = SchemeEditor(parent=self, stack=self.stacked_widget) self.scheme_choices_dict = {} schemes_combobox_widget = self.create_combobox('', [('', '')], 'selected') self.schemes_combobox = schemes_combobox_widget.combobox # Syntax layout syntax_layout = QGridLayout(syntax_group) btns = [ self.schemes_combobox, edit_button, self.reset_button, create_button, self.delete_button ] for i, btn in enumerate(btns): syntax_layout.addWidget(btn, i, 1) syntax_layout.setColumnStretch(0, 1) syntax_layout.setColumnStretch(1, 2) syntax_layout.setColumnStretch(2, 1) syntax_layout.setContentsMargins(0, 12, 0, 12) # Fonts options fonts_group = QGroupBox(_("Fonts")) # Fonts widgets self.plain_text_font = self.create_fontgroup( option='font', title=_("Plain text"), fontfilters=QFontComboBox.MonospacedFonts, without_group=True) self.rich_text_font = self.create_fontgroup(option='rich_font', title=_("Rich text"), without_group=True) # Fonts layouts fonts_layout = QGridLayout(fonts_group) fonts_layout.addWidget(self.plain_text_font.fontlabel, 0, 0) fonts_layout.addWidget(self.plain_text_font.fontbox, 0, 1) fonts_layout.addWidget(self.plain_text_font.sizelabel, 0, 2) fonts_layout.addWidget(self.plain_text_font.sizebox, 0, 3) fonts_layout.addWidget(self.rich_text_font.fontlabel, 1, 0) fonts_layout.addWidget(self.rich_text_font.fontbox, 1, 1) fonts_layout.addWidget(self.rich_text_font.sizelabel, 1, 2) fonts_layout.addWidget(self.rich_text_font.sizebox, 1, 3) fonts_layout.setRowStretch(fonts_layout.rowCount(), 1) # Left options layout options_layout = QVBoxLayout() options_layout.addWidget(theme_group) options_layout.addWidget(syntax_group) options_layout.addWidget(fonts_group) # Right preview layout preview_group = QGroupBox(_("Preview")) preview_layout = QVBoxLayout() preview_layout.addWidget(self.preview_editor) preview_group.setLayout(preview_layout) # Combined layout combined_layout = QGridLayout() combined_layout.setRowStretch(0, 1) combined_layout.setColumnStretch(1, 100) combined_layout.addLayout(options_layout, 0, 0) combined_layout.addWidget(preview_group, 0, 1) self.setLayout(combined_layout) # Signals and slots create_button.clicked.connect(self.create_new_scheme) edit_button.clicked.connect(self.edit_scheme) self.reset_button.clicked.connect(self.reset_to_default) self.delete_button.clicked.connect(self.delete_scheme) self.schemes_combobox.currentIndexChanged.connect(self.update_preview) self.schemes_combobox.currentIndexChanged.connect(self.update_buttons) # Setup for name in names: self.scheme_editor_dialog.add_color_scheme_stack(name) for name in custom_names: self.scheme_editor_dialog.add_color_scheme_stack(name, custom=True) self.update_combobox() self.update_preview() self.update_qt_style_combobox()
def setup_ui(self): self.resize(1080, 640) vlay_1 = QVBoxLayout(self) self.h_splitter = QSplitter(self) vlay_1.addWidget(self.h_splitter) self.h_splitter.setOrientation(Qt.Horizontal) self.v_splitter = QSplitter(self.h_splitter) self.v_splitter.setOrientation(Qt.Vertical) self.v_splitter.setMinimumWidth(500) installed = QWidget(self.v_splitter) lay = QVBoxLayout(installed) lay.setContentsMargins(0, 2, 0, 2) self.installed_label = QLabel(trans._("Installed Plugins")) self.packages_filter = QLineEdit() self.packages_filter.setPlaceholderText(trans._("filter...")) self.packages_filter.setMaximumWidth(350) self.packages_filter.setClearButtonEnabled(True) mid_layout = QVBoxLayout() mid_layout.addWidget(self.packages_filter) mid_layout.addWidget(self.installed_label) lay.addLayout(mid_layout) self.installed_list = QPluginList(installed, self.installer) self.packages_filter.textChanged.connect(self.installed_list.filter) lay.addWidget(self.installed_list) uninstalled = QWidget(self.v_splitter) lay = QVBoxLayout(uninstalled) lay.setContentsMargins(0, 2, 0, 2) self.avail_label = QLabel(trans._("Available Plugins")) mid_layout = QHBoxLayout() mid_layout.addWidget(self.avail_label) mid_layout.addStretch() lay.addLayout(mid_layout) self.available_list = QPluginList(uninstalled, self.installer) self.packages_filter.textChanged.connect(self.available_list.filter) lay.addWidget(self.available_list) self.stdout_text = QTextEdit(self.v_splitter) self.stdout_text.setReadOnly(True) self.stdout_text.setObjectName("pip_install_status") self.stdout_text.hide() buttonBox = QHBoxLayout() self.working_indicator = QLabel(trans._("loading ..."), self) sp = self.working_indicator.sizePolicy() sp.setRetainSizeWhenHidden(True) self.working_indicator.setSizePolicy(sp) self.process_error_indicator = QLabel(self) self.process_error_indicator.setObjectName("error_label") self.process_error_indicator.hide() load_gif = str(Path(napari.resources.__file__).parent / "loading.gif") mov = QMovie(load_gif) mov.setScaledSize(QSize(18, 18)) self.working_indicator.setMovie(mov) mov.start() visibility_direct_entry = not running_as_constructor_app() self.direct_entry_edit = QLineEdit(self) self.direct_entry_edit.installEventFilter(self) self.direct_entry_edit.setPlaceholderText( trans._('install by name/url, or drop file...')) self.direct_entry_edit.setVisible(visibility_direct_entry) self.direct_entry_btn = QPushButton(trans._("Install"), self) self.direct_entry_btn.setVisible(visibility_direct_entry) self.direct_entry_btn.clicked.connect(self._install_packages) self.show_status_btn = QPushButton(trans._("Show Status"), self) self.show_status_btn.setFixedWidth(100) self.cancel_all_btn = QPushButton(trans._("cancel all actions"), self) self.cancel_all_btn.setObjectName("remove_button") self.cancel_all_btn.setVisible(False) self.cancel_all_btn.clicked.connect(lambda: self.installer.cancel()) self.close_btn = QPushButton(trans._("Close"), self) self.close_btn.clicked.connect(self.accept) self.close_btn.setObjectName("close_button") buttonBox.addWidget(self.show_status_btn) buttonBox.addWidget(self.working_indicator) buttonBox.addWidget(self.direct_entry_edit) buttonBox.addWidget(self.direct_entry_btn) if not visibility_direct_entry: buttonBox.addStretch() buttonBox.addWidget(self.process_error_indicator) buttonBox.addSpacing(20) buttonBox.addWidget(self.cancel_all_btn) buttonBox.addSpacing(20) buttonBox.addWidget(self.close_btn) buttonBox.setContentsMargins(0, 0, 4, 0) vlay_1.addLayout(buttonBox) self.show_status_btn.setCheckable(True) self.show_status_btn.setChecked(False) self.show_status_btn.toggled.connect(self._toggle_status) self.v_splitter.setStretchFactor(1, 2) self.h_splitter.setStretchFactor(0, 2) self.packages_filter.setFocus()
def setup_page(self): settings_group = QGroupBox(_("Settings")) save_box = self.create_checkbox(_("Save file before analyzing it"), 'save_before', default=True) hist_group = QGroupBox(_("History")) hist_label1 = QLabel( _("The following option will be applied at next " "startup.")) hist_label1.setWordWrap(True) hist_spin = self.create_spinbox(_("History: "), _(" results"), 'max_entries', default=50, min_=10, max_=1000000, step=10) results_group = QGroupBox(_("Results")) results_label1 = QLabel(_("Results are stored here:")) results_label1.setWordWrap(True) # Warning: do not try to regroup the following QLabel contents with # widgets above -- this string was isolated here in a single QLabel # on purpose: to fix Issue 863 results_label2 = QLabel(PylintWidget.DATAPATH) results_label2.setTextInteractionFlags(Qt.TextSelectableByMouse) results_label2.setWordWrap(True) settings_layout = QVBoxLayout() settings_layout.addWidget(save_box) settings_group.setLayout(settings_layout) hist_layout = QVBoxLayout() hist_layout.addWidget(hist_label1) hist_layout.addWidget(hist_spin) hist_group.setLayout(hist_layout) results_layout = QVBoxLayout() results_layout.addWidget(results_label1) results_layout.addWidget(results_label2) results_group.setLayout(results_layout) vlayout = QVBoxLayout() vlayout.addWidget(settings_group) vlayout.addWidget(hist_group) vlayout.addWidget(results_group) vlayout.addStretch(1) self.setLayout(vlayout)
def __init__(self, parent, max_entries=100, options_button=None): QWidget.__init__(self, parent) self.setWindowTitle("Profiler") self.output = None self.error_output = None self._last_wdir = None self._last_args = None self._last_pythonpath = None self.filecombo = PythonModulesComboBox(self) self.start_button = create_toolbutton(self, icon=ima.icon('run'), text=_("Profile"), tip=_("Run profiler"), triggered=lambda: self.start(), text_beside_icon=True) self.stop_button = create_toolbutton(self, icon=ima.icon('stop'), text=_("Stop"), tip=_("Stop current profiling"), text_beside_icon=True) self.filecombo.valid.connect(self.start_button.setEnabled) #self.connect(self.filecombo, SIGNAL('valid(bool)'), self.show_data) # FIXME: The combobox emits this signal on almost any event # triggering show_data() too early, too often. browse_button = create_toolbutton(self, icon=ima.icon('fileopen'), tip=_('Select Python script'), triggered=self.select_file) self.datelabel = QLabel() self.log_button = create_toolbutton(self, icon=ima.icon('log'), text=_("Output"), text_beside_icon=True, tip=_("Show program's output"), triggered=self.show_log) self.datatree = ProfilerDataTree(self) self.collapse_button = create_toolbutton( self, icon=ima.icon('collapse'), triggered=lambda dD: self.datatree.change_view(-1), tip=_('Collapse one level up')) self.expand_button = create_toolbutton( self, icon=ima.icon('expand'), triggered=lambda dD: self.datatree.change_view(1), tip=_('Expand one level down')) self.save_button = create_toolbutton(self, text_beside_icon=True, text=_("Save data"), icon=ima.icon('filesave'), triggered=self.save_data, tip=_('Save profiling data')) self.load_button = create_toolbutton( self, text_beside_icon=True, text=_("Load data"), icon=ima.icon('fileimport'), triggered=self.compare, tip=_('Load profiling data for comparison')) self.clear_button = create_toolbutton(self, text_beside_icon=True, text=_("Clear comparison"), icon=ima.icon('editdelete'), triggered=self.clear) hlayout1 = QHBoxLayout() hlayout1.addWidget(self.filecombo) hlayout1.addWidget(browse_button) hlayout1.addWidget(self.start_button) hlayout1.addWidget(self.stop_button) if options_button: hlayout1.addWidget(options_button) hlayout2 = QHBoxLayout() hlayout2.addWidget(self.collapse_button) hlayout2.addWidget(self.expand_button) hlayout2.addStretch() hlayout2.addWidget(self.datelabel) hlayout2.addStretch() hlayout2.addWidget(self.log_button) hlayout2.addWidget(self.save_button) hlayout2.addWidget(self.load_button) hlayout2.addWidget(self.clear_button) layout = QVBoxLayout() layout.addLayout(hlayout1) layout.addLayout(hlayout2) layout.addWidget(self.datatree) self.setLayout(layout) self.process = None self.set_running_state(False) self.start_button.setEnabled(False) self.clear_button.setEnabled(False) if not is_profiler_installed(): # This should happen only on certain GNU/Linux distributions # or when this a home-made Python build because the Python # profilers are included in the Python standard library for widget in (self.datatree, self.filecombo, self.start_button, self.stop_button): widget.setDisabled(True) url = 'http://docs.python.org/library/profile.html' text = '%s <a href=%s>%s</a>' % (_('Please install'), url, _("the Python profiler modules")) self.datelabel.setText(text) else: pass # self.show_data()
def get_auto_correction_widget(self, parent): """.""" auto_wid = QWidget(parent) vbl2 = QVBoxLayout(auto_wid) tabw = QTabWidget(auto_wid) vbl2.addWidget(tabw) # Add Main Tab gpbx = QWidget(tabw) gpbx_lay = QVBoxLayout(gpbx) tabw.addTab(gpbx, 'Main') fbl = QFormLayout() fbl.setHorizontalSpacing(9) gpbx_lay.addLayout(fbl) lbl = QLabel('Freq. [Hz]', gpbx) wid = self.create_pair(gpbx, 'LoopFreq') fbl.addRow(lbl, wid) lbl = QLabel('Max. Orb. Distortion [um]', gpbx) wid = self.create_pair(gpbx, 'LoopMaxOrbDistortion') fbl.addRow(lbl, wid) wid = QWidget(gpbx) wid.setLayout(QHBoxLayout()) pbtn = QPushButton('Loop Performance', wid) pbtn.setIcon(qta.icon('mdi.poll')) wid.layout().addStretch() wid.layout().addWidget(pbtn) icon = qta.icon( 'fa5s.hammer', color=_util.get_appropriate_color(self.acc)) wind = create_window_from_widget( PerformanceWidget, title='Loop Performance', icon=icon) _util.connect_window( pbtn, wind, self, device=self.device, prefix=self.prefix) fbl.addRow(wid) # Add PID Tab gpbx = QWidget(tabw) gpbx_lay = QGridLayout(gpbx) gpbx_lay.setSpacing(1) tabw.addTab(gpbx, 'PID') gpbx_lay.addWidget(QLabel('CH', gpbx), 1, 0) gpbx_lay.addWidget(QLabel('CV', gpbx), 2, 0) tmpl = 'LoopPID{:s}{:s}' pairs = [] for i, k in enumerate(('Kp', 'Ki', 'Kd'), 1): gpbx_lay.addWidget( QLabel(k, gpbx), 0, i, alignment=Qt.AlignCenter) pair = self.create_pair(wid, tmpl.format(k, 'CH'), is_vert=True) pairs.append(pair) gpbx_lay.addWidget(pair, 1, i) pair = self.create_pair(wid, tmpl.format(k, 'CV'), is_vert=True) pairs.append(pair) gpbx_lay.addWidget(pair, 2, i) if self.acc in {'SI', 'BO'}: pair = self.create_pair( wid, tmpl.format(k, 'RF'), is_vert=True) pairs.append(pair) gpbx_lay.addWidget(pair, 3, i) if self.acc in {'SI', 'BO'}: gpbx_lay.addWidget(QLabel('RF', gpbx), 3, 0) pbc = QPushButton('SP') pbc.setStyleSheet('max-width:2.2em;') gpbx_lay.addWidget(pbc, 0, 0) pbc.setCheckable(True) pbc.setChecked(False) pbc.toggled.connect( lambda x: pbc.setText('RB' if x else 'SP')) for pair in pairs: pair.rb_wid.setVisible(False) pbc.toggled.connect(pair.rb_wid.setVisible) pbc.toggled.connect(pair.sp_wid.setHidden) gpbx_lay.setRowStretch(4, 2) return auto_wid
def create_layout(self): cancel_box = QHBoxLayout() cancel_box.addWidget(self.close_button) grid1 = QGridLayout() grid2 = QGridLayout() #----------------------------------------- # setup self.radio_rectangular = QRadioButton('Rectangular') self.radio_cylindrical = QRadioButton('Cylindrical') self.radio_spherical = QRadioButton('Spherical') coord_type_layout = QHBoxLayout() coord_type_layout.addWidget(self.radio_rectangular) coord_type_layout.addWidget(self.radio_cylindrical) coord_type_layout.addWidget(self.radio_spherical) location_layout = QHBoxLayout() location_layout.addWidget(self.location_x_edit) location_layout.addWidget(self.location_y_edit) location_layout.addWidget(self.location_z_edit) checkboxs = QButtonGroup(self) checkboxs.addButton(self.checkbox_show) checkboxs.addButton(self.checkbox_hide) vbox1 = QVBoxLayout() vbox1.addWidget(self.checkbox_show) vbox1.addWidget(self.checkbox_hide) #vbox1.addLayout(checkboxs) #----------------------------------------- irow = 0 grid1.addWidget(self.all_nodes_header, irow, 0) irow += 1 grid1.addWidget(self.color, irow, 0) grid1.addWidget(self.color_edit, irow, 1) irow += 1 grid1.addWidget(self.opacity, irow, 0) grid1.addWidget(self.opacity_edit, irow, 1) irow += 1 grid1.addWidget(self.point_size, irow, 0) grid1.addWidget(self.point_size_edit, irow, 1) irow += 1 #----------------------------------------- irow = 0 grid2.addWidget(self.nodes_header, irow, 0) irow += 1 grid2.addWidget(self.name, irow, 0) grid2.addWidget(self.name_edit, irow, 1) irow += 1 grid2.addWidget(self.description, irow, 0) grid2.addWidget(self.description_edit, irow, 1) irow += 1 #| All Nodes: | #| Color red | #| PointSize 3 | #| Opacity 0.3 | #| Show/Hide | #| | #| Name LEwingTip | #| Location X Y Z | #| Coord 0 | #| CoordType R, C, S | #| | #| Previous Next | grid2.addWidget(self.coord, irow, 0) grid2.addWidget(self.coord_edit, irow, 1) irow += 1 grid2.addWidget(self.coord_type, irow, 0) grid2.addLayout(coord_type_layout, irow, 1) irow += 1 grid2.addWidget(self.location, irow, 0) grid2.addLayout(location_layout, irow, 1) irow += 1 #------------------------------------ vbox = QVBoxLayout() vbox.addLayout(grid1) vbox.addLayout(vbox1) vbox.addStretch() vbox.addWidget(self.table) vbox.addLayout(grid2) vbox.addStretch() #vbox.addWidget(self.check_apply) vbox.addLayout(cancel_box) self.setLayout(vbox)
class PythonFileInterpreter(QWidget): sig_editor_modified = Signal(bool) sig_filename_modified = Signal(str) def __init__(self, content=None, filename=None, parent=None): """ :param content: An optional string of content to pass to the editor :param filename: The file path where the content was read. :param parent: An optional parent QWidget """ super(PythonFileInterpreter, self).__init__(parent) # layout self.editor = CodeEditor("AlternateCSPythonLexer", self) # Clear QsciScintilla key bindings that may override PyQt's bindings self.clear_key_binding("Ctrl+/") self.status = QStatusBar(self) self.layout = QVBoxLayout() self.layout.addWidget(self.editor) self.layout.addWidget(self.status) self.setLayout(self.layout) self.layout.setContentsMargins(0, 0, 0, 0) self._setup_editor(content, filename) self.setAttribute(Qt.WA_DeleteOnClose, True) self._presenter = PythonFileInterpreterPresenter( self, PythonCodeExecution(content)) self.editor.modificationChanged.connect(self.sig_editor_modified) self.editor.fileNameChanged.connect(self.sig_filename_modified) self.find_replace_dialog = None self.find_replace_dialog_shown = False def closeEvent(self, event): self.deleteLater() if self.find_replace_dialog: self.find_replace_dialog.close() super(PythonFileInterpreter, self).closeEvent(event) def show_find_replace_dialog(self): if self.find_replace_dialog is None: self.find_replace_dialog = EmbeddedFindReplaceDialog( self, self.editor) self.layout.insertWidget(0, self.find_replace_dialog.view) self.find_replace_dialog.show() def hide_find_replace_dialog(self): if self.find_replace_dialog is not None: self.find_replace_dialog.hide() @property def filename(self): return self.editor.fileName() def confirm_close(self): """Confirm the widget can be closed. If the editor contents are modified then a user can interject and cancel closing. :return: True if closing was considered successful, false otherwise """ return self.save(confirm=True) def abort(self): self._presenter.req_abort() def execute_async(self): self._presenter.req_execute_async() def save(self, confirm=False): if self.editor.isModified(): io = EditorIO(self.editor) return io.save_if_required(confirm) else: return True def set_editor_readonly(self, ro): self.editor.setReadOnly(ro) def set_status_message(self, msg): self.status.showMessage(msg) def replace_tabs_with_spaces(self): self.replace_text(TAB_CHAR, SPACE_CHAR * TAB_WIDTH) def replace_text(self, match_text, replace_text): if self.editor.selectedText() == '': self.editor.selectAll() new_text = self.editor.selectedText().replace(match_text, replace_text) self.editor.replaceSelectedText(new_text) def replace_spaces_with_tabs(self): self.replace_text(SPACE_CHAR * TAB_WIDTH, TAB_CHAR) def set_whitespace_visible(self): self.editor.setWhitespaceVisibility(CodeEditor.WsVisible) def set_whitespace_invisible(self): self.editor.setWhitespaceVisibility(CodeEditor.WsInvisible) def clear_key_binding(self, key_str): """Clear a keyboard shortcut bound to a Scintilla command""" self.editor.clearKeyBinding(key_str) def toggle_comment(self): if self.editor.selectedText() == '': # If nothing selected, do nothing return # Note selection indices to restore highlighting later selection_idxs = list(self.editor.getSelection()) # Expand selection from first character on start line to end char on last line line_end_pos = len( self.editor.text().split('\n')[selection_idxs[2]].rstrip()) line_selection_idxs = [ selection_idxs[0], 0, selection_idxs[2], line_end_pos ] self.editor.setSelection(*line_selection_idxs) selected_lines = self.editor.selectedText().split('\n') if self._are_comments(selected_lines) is True: toggled_lines = self._uncomment_lines(selected_lines) # Track deleted characters to keep highlighting consistent selection_idxs[1] -= 2 selection_idxs[-1] -= 2 else: toggled_lines = self._comment_lines(selected_lines) selection_idxs[1] += 2 selection_idxs[-1] += 2 # Replace lines with commented/uncommented lines self.editor.replaceSelectedText('\n'.join(toggled_lines)) # Restore highlighting self.editor.setSelection(*selection_idxs) def _comment_lines(self, lines): for i in range(len(lines)): lines[i] = '# ' + lines[i] return lines def _uncomment_lines(self, lines): for i in range(len(lines)): uncommented_line = lines[i].replace('# ', '', 1) if uncommented_line == lines[i]: uncommented_line = lines[i].replace('#', '', 1) lines[i] = uncommented_line return lines def _are_comments(self, code_lines): for line in code_lines: if line.strip(): if not line.strip().startswith('#'): return False return True def _setup_editor(self, default_content, filename): editor = self.editor # use tabs not spaces for indentation editor.setIndentationsUseTabs(False) editor.setTabWidth(TAB_WIDTH) # show current editing line but in a softer color editor.setCaretLineBackgroundColor(CURRENTLINE_BKGD_COLOR) editor.setCaretLineVisible(True) # set a margin large enough for sensible file sizes < 1000 lines # and the progress marker font_metrics = QFontMetrics(self.font()) editor.setMarginWidth(1, font_metrics.averageCharWidth() * 3 + 20) # fill with content if supplied and set source filename if default_content is not None: editor.setText(default_content) if filename is not None: editor.setFileName(filename) # Default content does not count as a modification editor.setModified(False) editor.enableAutoCompletion(CodeEditor.AcsAll)
class TextEditor(BaseDialog): """Array Editor Dialog""" def __init__(self, text, title='', font=None, parent=None, readonly=False): super().__init__(parent) # Destroying the C++ object right after closing the dialog box, # otherwise it may be garbage-collected in another QThread # (e.g. the editor's analysis thread in Spyder), thus leading to # a segmentation fault on UNIX or an application crash on Windows self.setAttribute(Qt.WA_DeleteOnClose) self.text = None self.btn_save_and_close = None # Display text as unicode if it comes as bytes, so users see # its right representation if is_binary_string(text): self.is_binary = True text = to_text_string(text, 'utf8') else: self.is_binary = False self.layout = QVBoxLayout() self.setLayout(self.layout) # Text edit self.edit = QTextEdit(parent) self.edit.setReadOnly(readonly) self.edit.textChanged.connect(self.text_changed) self.edit.setPlainText(text) if font is None: font = get_font() self.edit.setFont(font) self.layout.addWidget(self.edit) # Buttons configuration btn_layout = QHBoxLayout() btn_layout.addStretch() if not readonly: self.btn_save_and_close = QPushButton(_('Save and Close')) self.btn_save_and_close.setDisabled(True) self.btn_save_and_close.clicked.connect(self.accept) btn_layout.addWidget(self.btn_save_and_close) self.btn_close = QPushButton(_('Close')) self.btn_close.setAutoDefault(True) self.btn_close.setDefault(True) self.btn_close.clicked.connect(self.reject) btn_layout.addWidget(self.btn_close) self.layout.addLayout(btn_layout) # Make the dialog act as a window if sys.platform == 'darwin': # See spyder-ide/spyder#12825 self.setWindowFlags(Qt.Tool) else: # Make the dialog act as a window self.setWindowFlags(Qt.Window) self.setWindowIcon(ima.icon('edit')) if title: try: unicode_title = to_text_string(title) except UnicodeEncodeError: unicode_title = u'' else: unicode_title = u'' self.setWindowTitle(_("Text editor") + \ u"%s" % (u" - " + unicode_title if unicode_title else u"")) @Slot() def text_changed(self): """Text has changed""" # Save text as bytes, if it was initially bytes if self.is_binary: self.text = to_binary_string(self.edit.toPlainText(), 'utf8') else: self.text = to_text_string(self.edit.toPlainText()) if self.btn_save_and_close: self.btn_save_and_close.setEnabled(True) self.btn_save_and_close.setAutoDefault(True) self.btn_save_and_close.setDefault(True) def get_value(self): """Return modified text""" # It is import to avoid accessing Qt C++ object as it has probably # already been destroyed, due to the Qt.WA_DeleteOnClose attribute return self.text def setup_and_check(self, value): """Verify if TextEditor is able to display strings passed to it.""" try: to_text_string(value, 'utf8') return True except: return False
def setup_ui(self): self.resize(1080, 640) vlay_1 = QVBoxLayout(self) self.h_splitter = QSplitter(self) vlay_1.addWidget(self.h_splitter) self.h_splitter.setOrientation(Qt.Horizontal) self.v_splitter = QSplitter(self.h_splitter) self.v_splitter.setOrientation(Qt.Vertical) self.v_splitter.setMinimumWidth(500) self.plugin_sorter = QtPluginSorter(parent=self.h_splitter) self.plugin_sorter.layout().setContentsMargins(2, 0, 0, 0) self.plugin_sorter.hide() installed = QWidget(self.v_splitter) lay = QVBoxLayout(installed) lay.setContentsMargins(0, 2, 0, 2) lay.addWidget(QLabel("Installed Plugins")) self.installed_list = QPluginList(installed, self.installer) lay.addWidget(self.installed_list) uninstalled = QWidget(self.v_splitter) lay = QVBoxLayout(uninstalled) lay.setContentsMargins(0, 2, 0, 2) lay.addWidget(QLabel("Available Plugin Packages")) self.available_list = QPluginList(uninstalled, self.installer) lay.addWidget(self.available_list) self.stdout_text = QTextEdit(self.v_splitter) self.stdout_text.setReadOnly(True) self.stdout_text.setObjectName("pip_install_status") self.stdout_text.hide() buttonBox = QHBoxLayout() self.working_indicator = QLabel("loading ...", self) self.process_error_indicator = QLabel(self) self.process_error_indicator.setObjectName("error_label") self.process_error_indicator.hide() load_gif = str(Path(napari.resources.__file__).parent / "loading.gif") mov = QMovie(load_gif) mov.setScaledSize(QSize(18, 18)) self.working_indicator.setMovie(mov) mov.start() self.show_status_btn = QPushButton("Show Status", self) self.show_status_btn.setFixedWidth(100) self.show_sorter_btn = QPushButton("<< Show Sorter", self) self.close_btn = QPushButton("Close", self) self.close_btn.clicked.connect(self.reject) buttonBox.addWidget(self.show_status_btn) buttonBox.addWidget(self.working_indicator) buttonBox.addWidget(self.process_error_indicator) buttonBox.addStretch() buttonBox.addWidget(self.show_sorter_btn) buttonBox.addWidget(self.close_btn) buttonBox.setContentsMargins(0, 0, 4, 0) vlay_1.addLayout(buttonBox) self.show_status_btn.setCheckable(True) self.show_status_btn.setChecked(False) self.show_status_btn.toggled.connect(self._toggle_status) self.show_sorter_btn.setCheckable(True) self.show_sorter_btn.setChecked(False) self.show_sorter_btn.toggled.connect(self._toggle_sorter) self.v_splitter.setStretchFactor(1, 2) self.h_splitter.setStretchFactor(0, 2)
def create_layout(self): grid = QGridLayout() irow = 0 grid.addWidget(self.font_size_label, irow, 0) grid.addWidget(self.font_size_edit, irow, 1) grid.addWidget(self.font_size_button, irow, 2) irow += 1 grid.addWidget(self.gradient_scale_label, irow, 0) grid.addWidget(self.gradient_scale_checkbox, irow, 1) irow += 1 grid.addWidget(self.background_color2_label, irow, 0) grid.addWidget(self.background_color2_edit, irow, 1) irow += 1 grid.addWidget(self.background_color_label, irow, 0) grid.addWidget(self.background_color_edit, irow, 1) irow += 1 grid.addWidget(self.highlight_color_label, irow, 0) grid.addWidget(self.highlight_color_edit, irow, 1) irow += 1 grid.addWidget(self.highlight_opacity_label, irow, 0) grid.addWidget(self.highlight_opacity_edit, irow, 1) irow += 1 grid.addWidget(self.text_color_label, irow, 0) grid.addWidget(self.text_color_edit, irow, 1) irow += 1 grid.addWidget(self.text_size_label, irow, 0) grid.addWidget(self.text_size_edit, irow, 1) grid.addWidget(self.text_size_button, irow, 2) irow += 1 grid.addWidget(self.annotation_color_label, irow, 0) grid.addWidget(self.annotation_color_edit, irow, 1) irow += 1 grid.addWidget(self.annotation_size_label, irow, 0) grid.addWidget(self.annotation_size_edit, irow, 1) grid.addWidget(self.annotation_size_button, irow, 2) irow += 1 #grid.addWidget(self.clipping_min_label, irow, 0) #grid.addWidget(self.clipping_min_edit, irow, 1) #grid.addWidget(self.clipping_min_button, irow, 2) #irow += 1 #grid.addWidget(self.clipping_max_label, irow, 0) #grid.addWidget(self.clipping_max_edit, irow, 1) #grid.addWidget(self.clipping_max_button, irow, 2) #irow += 1 grid.addWidget(self.corner_coord_label, irow, 0) grid.addWidget(self.corner_coord_checkbox, irow, 1) irow += 1 grid.addWidget(self.coord_scale_label, irow, 0) grid.addWidget(self.coord_scale_edit, irow, 1) grid.addWidget(self.coord_scale_button, irow, 2) irow += 1 grid.addWidget(self.coord_text_scale_label, irow, 0) grid.addWidget(self.coord_text_scale_edit, irow, 1) grid.addWidget(self.coord_text_scale_button, irow, 2) irow += 1 #----------------------------------------------- grid.addWidget(self.magnify_label, irow, 0) grid.addWidget(self.magnify_edit, irow, 1) irow += 1 grid.addWidget(self.picker_size_label, irow, 0) grid.addWidget(self.picker_size_edit, irow, 1) irow += 1 #-------------------------------------------------- grid_nastran = QGridLayout() irow = 0 grid_nastran.addWidget(self.nastran_create_coords_checkbox, irow, 0) irow += 1 grid_nastran.addWidget(self.nastran_is_element_quality_checkbox, irow, 0) grid_nastran.addWidget(self.nastran_is_properties_checkbox, irow, 1) irow += 1 grid_nastran.addWidget(self.nastran_is_bar_axes_checkbox, irow, 0) irow += 1 grid_nastran.addWidget(self.nastran_is_3d_bars_checkbox, irow, 0) grid_nastran.addWidget(self.nastran_is_3d_bars_update_checkbox, irow, 1) irow += 1 #bold_font = make_font(self._default_font_size, is_bold=True) vbox_nastran = QVBoxLayout() self.nastran_label = QLabel('Nastran:') vbox_nastran.addWidget(self.nastran_label) vbox_nastran.addLayout(grid_nastran) #self.create_legend_widgets() #grid2 = self.create_legend_layout() ok_cancel_box = QHBoxLayout() ok_cancel_box.addWidget(self.apply_button) ok_cancel_box.addWidget(self.ok_button) ok_cancel_box.addWidget(self.cancel_button) vbox = QVBoxLayout() vbox.addLayout(grid) vbox.addLayout(vbox_nastran) #vbox.addStretch() #vbox.addLayout(grid2) vbox.addStretch() vbox.addLayout(ok_cancel_box) self.setLayout(vbox)