class ConfigDialog(QDialog): """Spyder configuration ('Preferences') dialog box""" # Signals check_settings = Signal() size_change = Signal(QSize) 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) self.ok_btn = bbox.button(QDialogButtonBox.Ok) # 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 get_current_index(self): """Return current page index""" return self.contents_widget.currentRow() def set_current_index(self, index): """Set current page index""" self.contents_widget.setCurrentRow(index) def get_page(self, index=None): """Return page widget""" if index is None: widget = self.pages_widget.currentWidget() else: widget = self.pages_widget.widget(index) if widget: return widget.widget() def get_index_by_name(self, name): """Return page index by CONF_SECTION name.""" for idx in range(self.pages_widget.count()): widget = self.pages_widget.widget(idx) widget = widget.widget() if widget.CONF_SECTION == name: return idx else: return None @Slot() def accept(self): """Reimplement Qt method""" for index in range(self.pages_widget.count()): configpage = self.get_page(index) if not configpage.is_valid(): return configpage.apply_changes() QDialog.accept(self) def button_clicked(self, button): if button is self.apply_btn: # Apply button was clicked configpage = self.get_page() if not configpage.is_valid(): return configpage.apply_changes() def current_page_changed(self, index): widget = self.get_page(index) self.apply_btn.setVisible(widget.apply_callback is not None) self.apply_btn.setEnabled(widget.is_modified) def add_page(self, widget): self.check_settings.connect(widget.check_settings) widget.show_this_page.connect(lambda row=self.contents_widget.count(): self.contents_widget.setCurrentRow(row)) widget.apply_button_enabled.connect(self.apply_btn.setEnabled) scrollarea = QScrollArea(self) scrollarea.setWidgetResizable(True) scrollarea.setWidget(widget) self.pages_widget.addWidget(scrollarea) item = QListWidgetItem(self.contents_widget) try: item.setIcon(widget.get_icon()) except TypeError: pass item.setText(widget.get_name()) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) item.setSizeHint(QSize(0, 25)) def check_all_settings(self): """This method is called to check all configuration page settings after configuration dialog has been shown""" self.check_settings.emit() def resizeEvent(self, event): """ Reimplement Qt method to be able to save the widget's size from the main application """ QDialog.resizeEvent(self, event) self.size_change.emit(self.size())
class FileSwitcher(QDialog): """A Sublime-like file switcher.""" sig_goto_file = Signal(int, object) # Constants that define the mode in which the list widget is working # FILE_MODE is for a list of files, SYMBOL_MODE if for a list of symbols # in a given file when using the '@' symbol. FILE_MODE, SYMBOL_MODE = [1, 2] MAX_WIDTH = 600 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) # --- Properties @property def widgets(self): widgets = [] for plugin in self.plugins_instances: tabs = self.get_plugin_tabwidget(plugin) widgets += [(tabs.widget(index), plugin) for index in range(tabs.count())] return widgets @property def line_count(self): line_count = [] for widget in self.widgets: try: current_line_count = widget[0].get_line_count() except AttributeError: current_line_count = 0 line_count.append(current_line_count) return line_count @property def save_status(self): save_status = [] for da, icon in self.plugins_data: save_status += [getattr(td, 'newly_created', False) for td in da] return save_status @property def paths(self): paths = [] for plugin in self.plugins_instances: da = self.get_plugin_data(plugin) paths += [getattr(td, 'filename', None) for td in da] return paths @property def filenames(self): filenames = [] for plugin in self.plugins_instances: da = self.get_plugin_data(plugin) filenames += [ os.path.basename(getattr(td, 'filename', None)) for td in da ] return filenames @property def icons(self): icons = [] for da, icon in self.plugins_data: icons += [icon for td in da] return icons @property def current_path(self): return self.paths_by_widget[self.get_widget()] @property def paths_by_widget(self): widgets = [w[0] for w in self.widgets] return dict(zip(widgets, self.paths)) @property def widgets_by_path(self): widgets = [w[0] for w in self.widgets] return dict(zip(self.paths, widgets)) @property def filter_text(self): """Get the normalized (lowecase) content of the filter text.""" return to_text_string(self.edit.text()).lower() def set_search_text(self, _str): self.edit.setText(_str) def save_initial_state(self): """Save initial cursors and initial active widget.""" paths = self.paths self.initial_widget = self.get_widget() self.initial_cursors = {} for i, editor in enumerate(self.widgets): if editor is self.initial_widget: self.initial_path = paths[i] # This try is needed to make the fileswitcher work with # plugins that does not have a textCursor. try: self.initial_cursors[paths[i]] = editor.textCursor() except AttributeError: pass def accept(self): self.is_visible = False QDialog.accept(self) self.list.clear() def restore_initial_state(self): """Restores initial cursors and initial active editor.""" self.list.clear() self.is_visible = False widgets = self.widgets_by_path if not self.edit.clicked_outside: for path in self.initial_cursors: cursor = self.initial_cursors[path] if path in widgets: self.set_editor_cursor(widgets[path], cursor) if self.initial_widget in self.paths_by_widget: index = self.paths.index(self.initial_path) self.sig_goto_file.emit(index) def set_dialog_position(self): """Positions the file switcher dialog.""" parent = self.parent() geo = parent.geometry() width = self.list.width() # This has been set in setup left = parent.geometry().width() / 2 - width / 2 # Note: the +1 pixel on the top makes it look better if isinstance(parent, QMainWindow): top = (parent.toolbars_menu.geometry().height() + parent.menuBar().geometry().height() + 1) else: top = self.plugins_tabs[0][0].tabBar().geometry().height() + 1 while parent: geo = parent.geometry() top += geo.top() left += geo.left() parent = parent.parent() self.move(left, top) def get_item_size(self, content): """ Get the max size (width and height) for the elements of a list of strings as a QLabel. """ strings = [] if content: for rich_text in content: label = QLabel(rich_text) label.setTextFormat(Qt.PlainText) strings.append(label.text()) fm = label.fontMetrics() return (max([fm.width(s) * 1.3 for s in strings]), fm.height()) def fix_size(self, content): """ Adjusts the width and height of the file switcher based on the relative size of the parent and content. """ # Update size of dialog based on relative size of the parent if content: width, height = self.get_item_size(content) # Width parent = self.parent() relative_width = parent.geometry().width() * 0.65 if relative_width > self.MAX_WIDTH: relative_width = self.MAX_WIDTH self.list.setMinimumWidth(relative_width) # Height if len(content) < 8: max_entries = len(content) else: max_entries = 8 max_height = height * max_entries * 2.5 self.list.setMinimumHeight(max_height) # Resize self.list.resize(relative_width, self.list.height()) # --- Helper methods: List widget def count(self): """Gets the item count in the list widget.""" return self.list.count() def current_row(self): """Returns the current selected row in the list widget.""" return self.list.currentRow() def set_current_row(self, row): """Sets the current selected row in the list widget.""" return self.list.setCurrentRow(row) def select_row(self, steps): """Select row in list widget based on a number of steps with direction. Steps can be positive (next rows) or negative (previous rows). """ row = self.current_row() + steps if 0 <= row < self.count(): self.set_current_row(row) def previous_row(self): """Select previous row in list widget.""" if self.mode == self.SYMBOL_MODE: self.select_row(-1) return prev_row = self.current_row() - 1 if prev_row >= 0: title = self.list.item(prev_row).text() else: title = '' if prev_row == 0 and '</b></big><br>' in title: self.list.scrollToTop() elif '</b></big><br>' in title: # Select the next previous row, the one following is a title self.select_row(-2) else: self.select_row(-1) def next_row(self): """Select next row in list widget.""" if self.mode == self.SYMBOL_MODE: self.select_row(+1) return next_row = self.current_row() + 1 if next_row < self.count(): if '</b></big><br>' in self.list.item(next_row).text(): # Select the next next row, the one following is a title self.select_row(+2) else: self.select_row(+1) def get_stack_index(self, stack_index, plugin_index): """Get the real index of the selected item.""" other_plugins_count = sum([other_tabs[0].count() \ for other_tabs in \ self.plugins_tabs[:plugin_index]]) real_index = stack_index - other_plugins_count return real_index # --- Helper methods: Widget def get_plugin_data(self, plugin): """Get the data object of the plugin's current tab manager.""" # The data object is named "data" in the editor plugin while it is # named "clients" in the notebook plugin. try: data = plugin.get_current_tab_manager().data except AttributeError: data = plugin.get_current_tab_manager().clients return data def get_plugin_tabwidget(self, plugin): """Get the tabwidget of the plugin's current tab manager.""" # The tab widget is named "tabs" in the editor plugin while it is # named "tabwidget" in the notebook plugin. try: tabwidget = plugin.get_current_tab_manager().tabs except AttributeError: tabwidget = plugin.get_current_tab_manager().tabwidget return tabwidget def get_widget(self, index=None, path=None, tabs=None): """Get widget by index. If no tabs and index specified the current active widget is returned. """ if (index and tabs) or (path and tabs): return tabs.widget(index) elif self.plugin: return self.get_plugin_tabwidget(self.plugin).currentWidget() else: return self.plugins_tabs[0][0].currentWidget() def set_editor_cursor(self, editor, cursor): """Set the cursor of an editor.""" pos = cursor.position() anchor = cursor.anchor() new_cursor = QTextCursor() if pos == anchor: new_cursor.movePosition(pos) else: new_cursor.movePosition(anchor) new_cursor.movePosition(pos, QTextCursor.KeepAnchor) editor.setTextCursor(cursor) def goto_line(self, line_number): """Go to specified line number in current active editor.""" if line_number: line_number = int(line_number) try: self.plugin.go_to_line(line_number) except AttributeError: pass # --- Helper methods: Outline explorer def get_symbol_list(self): """Get the list of symbols present in the file.""" try: oedata = self.get_widget().get_outlineexplorer_data() except AttributeError: oedata = {} return oedata # --- Handlers def item_selection_changed(self): """List widget item selection change handler.""" row = self.current_row() if self.count() and row >= 0: if '</b></big><br>' in self.list.currentItem().text() and row == 0: self.next_row() if self.mode == self.FILE_MODE: try: stack_index = self.paths.index(self.filtered_path[row]) self.plugin = self.widgets[stack_index][1] plugin_index = self.plugins_instances.index(self.plugin) # Count the real index in the tabWidget of the # current plugin real_index = self.get_stack_index(stack_index, plugin_index) self.sig_goto_file.emit( real_index, self.plugin.get_current_tab_manager()) self.goto_line(self.line_number) try: self.plugin.switch_to_plugin() self.raise_() except AttributeError: # The widget using the fileswitcher is not a plugin pass self.edit.setFocus() except ValueError: pass else: line_number = self.filtered_symbol_lines[row] self.goto_line(line_number) def setup_file_list(self, filter_text, current_path): """Setup list widget content for file list display.""" short_paths = shorten_paths(self.paths, self.save_status) paths = self.paths icons = self.icons results = [] trying_for_line_number = ':' in filter_text # Get optional line number if trying_for_line_number: filter_text, line_number = filter_text.split(':') if line_number == '': line_number = None # Get all the available filenames scores = get_search_scores('', self.filenames, template="<b>{0}</b>") else: line_number = None # Get all available filenames and get the scores for # "fuzzy" matching scores = get_search_scores(filter_text, self.filenames, template="<b>{0}</b>") # Get max width to determine if shortpaths should be used max_width = self.get_item_size(paths)[0] self.fix_size(paths) # Build the text that will appear on the list widget for index, score in enumerate(scores): text, rich_text, score_value = score if score_value != -1: text_item = '<big>' + rich_text.replace('&', '') + '</big>' if trying_for_line_number: text_item += " [{0:} {1:}]".format(self.line_count[index], _("lines")) if max_width > self.list.width(): text_item += u"<br><i>{0:}</i>".format(short_paths[index]) else: text_item += u"<br><i>{0:}</i>".format(paths[index]) if (trying_for_line_number and self.line_count[index] != 0 or not trying_for_line_number): results.append((score_value, index, text_item)) # Sort the obtained scores and populate the list widget self.filtered_path = [] plugin = None for result in sorted(results): index = result[1] path = paths[index] icon = icons[index] text = '' try: title = self.widgets[index][1].get_plugin_title().split(' - ') if plugin != title[0]: plugin = title[0] text += '<br><big><b>' + plugin + '</b></big><br>' item = QListWidgetItem(text) item.setToolTip(path) item.setSizeHint(QSize(0, 25)) item.setFlags(Qt.ItemIsEditable) self.list.addItem(item) self.filtered_path.append(path) except: # The widget using the fileswitcher is not a plugin pass text = '' text += result[-1] item = QListWidgetItem(icon, text) item.setToolTip(path) item.setSizeHint(QSize(0, 25)) self.list.addItem(item) self.filtered_path.append(path) # To adjust the delegate layout for KDE themes self.list.files_list = True # Move selected item in list accordingly and update list size if current_path in self.filtered_path: self.set_current_row(self.filtered_path.index(current_path)) elif self.filtered_path: self.set_current_row(0) # If a line number is searched look for it self.line_number = line_number self.goto_line(line_number) def setup_symbol_list(self, filter_text, current_path): """Setup list widget content for symbol list display.""" # Get optional symbol name filter_text, symbol_text = filter_text.split('@') # Fetch the Outline explorer data, get the icons and values oedata = self.get_symbol_list() icons = get_python_symbol_icons(oedata) # The list of paths here is needed in order to have the same # point of measurement for the list widget size as in the file list # See issue 4648 paths = self.paths # Update list size self.fix_size(paths) symbol_list = process_python_symbol_data(oedata) line_fold_token = [(item[0], item[2], item[3]) for item in symbol_list] choices = [item[1] for item in symbol_list] scores = get_search_scores(symbol_text, choices, template="<b>{0}</b>") # Build the text that will appear on the list widget results = [] lines = [] self.filtered_symbol_lines = [] for index, score in enumerate(scores): text, rich_text, score_value = score line, fold_level, token = line_fold_token[index] lines.append(text) if score_value != -1: results.append((score_value, line, text, rich_text, fold_level, icons[index], token)) template = '{0}{1}' for (score, line, text, rich_text, fold_level, icon, token) in sorted(results): fold_space = ' ' * (fold_level) line_number = line + 1 self.filtered_symbol_lines.append(line_number) textline = template.format(fold_space, rich_text) item = QListWidgetItem(icon, textline) item.setSizeHint(QSize(0, 16)) self.list.addItem(item) # To adjust the delegate layout for KDE themes self.list.files_list = False # Select edit line when using symbol search initially. # See issue 5661 self.edit.setFocus() # Move selected item in list accordingly # NOTE: Doing this is causing two problems: # 1. It makes the cursor to auto-jump to the last selected # symbol after opening or closing a different file # 2. It moves the cursor to the first symbol by default, # which is very distracting. # That's why this line is commented! # self.set_current_row(0) def setup(self): """Setup list widget content.""" if len(self.plugins_tabs) == 0: self.close() return self.list.clear() current_path = self.current_path filter_text = self.filter_text # Get optional line or symbol to define mode and method handler trying_for_symbol = ('@' in self.filter_text) if trying_for_symbol: self.mode = self.SYMBOL_MODE self.setup_symbol_list(filter_text, current_path) else: self.mode = self.FILE_MODE self.setup_file_list(filter_text, current_path) # Set position according to size self.set_dialog_position() def show(self): """ Override Qt method to force an update of the fileswitcher before showing it. See Issue #5317 and PR #5389. """ self.setup() super(FileSwitcher, self).show() def add_plugin(self, plugin, tabs, data, icon): """Add a plugin to display its files.""" self.plugins_tabs.append((tabs, plugin)) self.plugins_data.append((data, icon)) self.plugins_instances.append(plugin)
class FileSwitcher(QDialog): """A Sublime-like file switcher.""" sig_goto_file = Signal(int) sig_close_file = Signal(int) # Constants that define the mode in which the list widget is working # FILE_MODE is for a list of files, SYMBOL_MODE if for a list of symbols # in a given file when using the '@' symbol. FILE_MODE, SYMBOL_MODE = [1, 2] def __init__(self, parent, tabs, data): QDialog.__init__(self, parent) # Variables self.tabs = tabs # Editor stack tabs self.data = data # Editor data 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_editor = 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-z]{0,100}:{0,1}[0-9]{0,100})") # Widgets self.edit = QLineEdit(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) # Setup self.save_initial_state() self.set_dialog_position() self.setup() # --- Properties @property def editors(self): return [self.tabs.widget(index) for index in range(self.tabs.count())] @property def line_count(self): return [editor.get_line_count() for editor in self.editors] @property def save_status(self): return [getattr(td, 'newly_created', False) for td in self.data] @property def paths(self): return [getattr(td, 'filename', None) for td in self.data] @property def filenames(self): return [self.tabs.tabText(index) for index in range(self.tabs.count())] @property def current_path(self): return self.paths_by_editor[self.get_editor()] @property def paths_by_editor(self): return dict(zip(self.editors, self.paths)) @property def editors_by_path(self): return dict(zip(self.paths, self.editors)) @property def filter_text(self): """Get the normalized (lowecase) content of the filter text.""" return to_text_string(self.edit.text()).lower() def save_initial_state(self): """Saves initial cursors and initial active editor.""" paths = self.paths self.initial_editor = self.get_editor() self.initial_cursors = {} for i, editor in enumerate(self.editors): if editor is self.initial_editor: self.initial_path = paths[i] self.initial_cursors[paths[i]] = editor.textCursor() def accept(self): self.is_visible = False QDialog.accept(self) self.list.clear() def restore_initial_state(self): """Restores initial cursors and initial active editor.""" self.list.clear() self.is_visible = False editors = self.editors_by_path for path in self.initial_cursors: cursor = self.initial_cursors[path] if path in editors: self.set_editor_cursor(editors[path], cursor) if self.initial_editor in self.paths_by_editor: index = self.paths.index(self.initial_path) self.sig_goto_file.emit(index) def set_dialog_position(self): """Positions the file switcher dialog in the center of the editor.""" parent = self.parent() geo = parent.geometry() width = self.list.width() # This has been set in setup left = parent.geometry().width()/2 - width/2 top = 0 while parent: geo = parent.geometry() top += geo.top() left += geo.left() parent = parent.parent() # Note: the +1 pixel on the top makes it look better self.move(left, top + self.tabs.tabBar().geometry().height() + 1) def fix_size(self, content, extra=50): """Adjusts the width of the file switcher, based on the content.""" # Update size of dialog based on longest shortened path strings = [] if content: for rich_text in content: label = QLabel(rich_text) label.setTextFormat(Qt.PlainText) strings.append(label.text()) fm = label.fontMetrics() max_width = max([fm.width(s)*1.3 for s in strings]) self.list.setMinimumWidth(max_width + extra) self.set_dialog_position() # --- Helper methods: List widget def count(self): """Gets the item count in the list widget.""" return self.list.count() def current_row(self): """Returns the current selected row in the list widget.""" return self.list.currentRow() def set_current_row(self, row): """Sets the current selected row in the list widget.""" return self.list.setCurrentRow(row) def select_row(self, steps): """Select row in list widget based on a number of steps with direction. Steps can be positive (next rows) or negative (previous rows). """ row = self.current_row() + steps if 0 <= row < self.count(): self.set_current_row(row) def previous_row(self): """Select previous row in list widget.""" self.select_row(-1) def next_row(self): """Select next row in list widget.""" self.select_row(+1) # --- Helper methods: Editor def get_editor(self, index=None, path=None): """Get editor by index or path. If no path or index specified the current active editor is returned """ if index: return self.tabs.widget(index) elif path: return self.tabs.widget(index) else: return self.parent().get_current_editor() def set_editor_cursor(self, editor, cursor): """Set the cursor of an editor.""" pos = cursor.position() anchor = cursor.anchor() new_cursor = QTextCursor() if pos == anchor: new_cursor.movePosition(pos) else: new_cursor.movePosition(anchor) new_cursor.movePosition(pos, QTextCursor.KeepAnchor) editor.setTextCursor(cursor) def goto_line(self, line_number): """Go to specified line number in current active editor.""" if line_number: line_number = int(line_number) editor = self.get_editor() editor.go_to_line(min(line_number, editor.get_line_count())) # --- Helper methods: Outline explorer def get_symbol_list(self): """Get the object explorer data.""" return self.get_editor().highlighter.get_outlineexplorer_data() # --- Handlers def item_selection_changed(self): """List widget item selection change handler.""" row = self.current_row() if self.count() and row >= 0: if self.mode == self.FILE_MODE: try: stack_index = self.paths.index(self.filtered_path[row]) self.sig_goto_file.emit(stack_index) self.goto_line(self.line_number) self.edit.setFocus() except ValueError: pass else: line_number = self.filtered_symbol_lines[row] self.goto_line(line_number) def setup_file_list(self, filter_text, current_path): """Setup list widget content for file list display.""" short_paths = shorten_paths(self.paths, self.save_status) paths = self.paths results = [] trying_for_line_number = ':' in filter_text # Get optional line number if trying_for_line_number: filter_text, line_number = filter_text.split(':') else: line_number = None # Get all available filenames and get the scores for "fuzzy" matching scores = get_search_scores(filter_text, self.filenames, template="<b>{0}</b>") # Build the text that will appear on the list widget for index, score in enumerate(scores): text, rich_text, score_value = score if score_value != -1: text_item = '<big>' + rich_text + '</big>' if trying_for_line_number: text_item += " [{0:} {1:}]".format(self.line_count[index], _("lines")) text_item += "<br><i>{0:}</i>".format( short_paths[index]) results.append((score_value, index, text_item)) # Sort the obtained scores and populate the list widget self.filtered_path = [] for result in sorted(results): index = result[1] text = result[-1] path = paths[index] item = QListWidgetItem(self.tabs.tabIcon(index), text) item.setToolTip(path) item.setSizeHint(QSize(0, 25)) self.list.addItem(item) self.filtered_path.append(path) # Move selected item in list accordingly and update list size if current_path in self.filtered_path: self.set_current_row(self.filtered_path.index(current_path)) elif self.filtered_path: self.set_current_row(0) self.fix_size(short_paths) # If a line number is searched look for it self.line_number = line_number self.goto_line(line_number) def setup_symbol_list(self, filter_text, current_path): """Setup list widget content for symbol list display.""" # Get optional symbol name filter_text, symbol_text = filter_text.split('@') # Fetch the Outline explorer data, get the icons and values oedata = self.get_symbol_list() icons = get_python_symbol_icons(oedata) symbol_list = process_python_symbol_data(oedata) line_fold_token = [(item[0], item[2], item[3]) for item in symbol_list] choices = [item[1] for item in symbol_list] scores = get_search_scores(symbol_text, choices, template="<b>{0}</b>") # Build the text that will appear on the list widget results = [] lines = [] self.filtered_symbol_lines = [] for index, score in enumerate(scores): text, rich_text, score_value = score line, fold_level, token = line_fold_token[index] lines.append(text) if score_value != -1: results.append((score_value, line, text, rich_text, fold_level, icons[index], token)) template_1 = '<code>{0}<big>{1} {2}</big></code>' template_2 = '<br><code>{0}</code><i>[Line {1}]</i>' for (score, line, text, rich_text, fold_level, icon, token) in sorted(results): fold_space = ' '*(fold_level) line_number = line + 1 self.filtered_symbol_lines.append(line_number) textline = template_1.format(fold_space, token, rich_text) textline += template_2.format(fold_space, line_number) item = QListWidgetItem(icon, textline) item.setSizeHint(QSize(0, 16)) self.list.addItem(item) # Move selected item in list accordingly # NOTE: Doing this is causing two problems: # 1. It makes the cursor to auto-jump to the last selected # symbol after opening or closing a different file # 2. It moves the cursor to the first symbol by default, # which is very distracting. # That's why this line is commented! # self.set_current_row(0) # Update list size self.fix_size(lines, extra=125) def setup(self): """Setup list widget content.""" if not self.tabs.count(): self.close() return self.list.clear() current_path = self.current_path filter_text = self.filter_text # Get optional line or symbol to define mode and method handler trying_for_symbol = ('@' in self.filter_text) if trying_for_symbol: self.mode = self.SYMBOL_MODE self.setup_symbol_list(filter_text, current_path) else: self.mode = self.FILE_MODE self.setup_file_list(filter_text, current_path)
class ApplicationsDialog(QDialog): """Dialog for selection of installed system/user applications.""" def __init__(self, parent=None): """Dialog for selection of installed system/user applications.""" super(ApplicationsDialog, self).__init__(parent=parent) # Widgets self.label = QLabel() self.label_browse = QLabel() self.edit_filter = QLineEdit() self.list = QListWidget() self.button_browse = QPushButton(_('Browse...')) self.button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.button_ok = self.button_box.button(QDialogButtonBox.Ok) self.button_cancel = self.button_box.button(QDialogButtonBox.Cancel) # Widget setup self.setWindowTitle(_('Applications')) self.edit_filter.setPlaceholderText(_('Type to filter by name')) self.list.setIconSize(QSize(16, 16)) # FIXME: Use metrics # Layout layout = QVBoxLayout() layout.addWidget(self.label) layout.addWidget(self.edit_filter) layout.addWidget(self.list) layout_browse = QHBoxLayout() layout_browse.addWidget(self.button_browse) layout_browse.addWidget(self.label_browse) layout.addLayout(layout_browse) layout.addSpacing(12) # FIXME: Use metrics layout.addWidget(self.button_box) self.setLayout(layout) # Signals self.edit_filter.textChanged.connect(self.filter) self.button_browse.clicked.connect(lambda x: self.browse()) self.button_ok.clicked.connect(self.accept) self.button_cancel.clicked.connect(self.reject) self.list.currentItemChanged.connect(self._refresh) self._refresh() self.setup() def setup(self, applications=None): """Load installed applications.""" QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.list.clear() if applications is None: apps = get_installed_applications() else: apps = applications for app in sorted(apps, key=lambda x: x.lower()): fpath = apps[app] icon = get_application_icon(fpath) item = QListWidgetItem(icon, app) item.setToolTip(fpath) item.fpath = fpath self.list.addItem(item) # FIXME: Use metrics self.list.setMinimumWidth(self.list.sizeHintForColumn(0) + 24) QApplication.restoreOverrideCursor() self._refresh() def _refresh(self): """Refresh the status of buttons on widget.""" self.button_ok.setEnabled(self.list.currentRow() != -1) def browse(self, fpath=None): """Prompt user to select an application not found on the list.""" app = None item = None if sys.platform == 'darwin': if fpath is None: basedir = '/Applications/' filters = _('Applications (*.app)') title = _('Select application') fpath, __ = getopenfilename(self, title, basedir, filters) if fpath and fpath.endswith('.app') and os.path.isdir(fpath): app = os.path.basename(fpath).split('.app')[0] for row in range(self.list.count()): item = self.list.item(row) if app == item.text() and fpath == item.fpath: break else: item = None elif os.name == 'nt': if fpath is None: basedir = 'C:\\' filters = _('Applications (*.exe *.bat *.com)') title = _('Select application') fpath, __ = getopenfilename(self, title, basedir, filters) if fpath: check_1 = fpath.endswith('.bat') and is_text_file(fpath) check_2 = (fpath.endswith(('.exe', '.com')) and not is_text_file(fpath)) if check_1 or check_2: app = os.path.basename(fpath).capitalize().rsplit('.')[0] for row in range(self.list.count()): item = self.list.item(row) if app == item.text() and fpath == item.fpath: break else: item = None else: if fpath is None: basedir = '/' filters = _('Applications (*.desktop)') title = _('Select application') fpath, __ = getopenfilename(self, title, basedir, filters) if fpath and fpath.endswith(('.desktop')) and is_text_file(fpath): entry_data = parse_linux_desktop_entry(fpath) app = entry_data['name'] for row in range(self.list.count()): item = self.list.item(row) if app == item.text() and fpath == item.fpath: break else: item = None if fpath: if item: self.list.setCurrentItem(item) elif app: icon = get_application_icon(fpath) item = QListWidgetItem(icon, app) item.fpath = fpath self.list.addItem(item) self.list.setCurrentItem(item) self.list.setFocus() self._refresh() def filter(self, text): """Filter the list of applications based on text.""" text = self.edit_filter.text().lower().strip() for row in range(self.list.count()): item = self.list.item(row) item.setHidden(text not in item.text().lower()) self._refresh() def set_extension(self, extension): """Set the extension on the label of the dialog.""" self.label.setText( _('Choose the application for files of type ') + extension) @property def application_path(self): """Return the selected application path to executable.""" item = self.list.currentItem() path = item.fpath if item else '' return path @property def application_name(self): """Return the selected application name.""" item = self.list.currentItem() text = item.text() if item else '' return text
class RateLawWidget(QWidget): """ Rate Law widget """ redirect_stdio = Signal(bool) def __init__(self, parent, max_entries=100): "Initialize Various list objects before assignment" displaylist = [] displaynamelist = [] infixmod = [] infixlist = [] desclist = [] parameternamelist = [] parameterdesclist = [] buttonlist = [] xmldoc = minidom.parse( os.path.dirname(os.path.abspath(__file__)) + '\\ratelaw2_0_3.xml') lawlistxml = xmldoc.getElementsByTagName('law') o = 0 for s in lawlistxml: o = o + 1 parameternamelistlist = [0 for x in range(o)] parameterdesclistlist = [0 for x in range(o)] """i is the number of laws currently in the xml file""" i = 0 """ Parsing xml: Acquiring rate law name, description, and list of parameter information """ for s in lawlistxml: """Gets Latec Expression""" displaylist.append(s.getAttribute('display')) """Gets Rate-Law Name""" displaynamelist.append(s.getAttribute('displayName')) """"Gets Raw Rate-Law expression""" infixlist.append(s.getAttribute('infixExpression')) """Gets description statement""" desclist.append(s.getAttribute('description')) """Gets listOfParameters Object""" parameterlist = s.getElementsByTagName('listOfParameters')[0] """Gets a list of parameters within ListOfParameters object""" parameters = parameterlist.getElementsByTagName('parameter') for param in parameters: parameternamelist.append(param.attributes['name'].value) parameterdesclist.append(param.attributes['description'].value) parameternamelistlist[i] = parameternamelist parameterdesclistlist[i] = parameterdesclist parameternamelist = [] parameterdesclist = [] i = i + 1 SLElistlist = [0 for x in range(i)] PLElistlist = [0 for x in range(i)] ILElistlist = [0 for x in range(i)] paramLElistlist = [0 for x in range(i)] numlistlist = [0 for x in range(i)] QWidget.__init__(self, parent) self.setWindowTitle("Rate Law Library") self.output = None self.error_output = None self._last_wdir = None self._last_args = None self._last_pythonpath = None self.lawlist = QListWidget() self.lawpage = QStackedWidget() for j in range(i): item = QListWidgetItem(displaynamelist[j]) self.lawlist.addItem(item) self.lawdetailpage = QWidget() setup_group = QGroupBox(displaynamelist[j]) infixmod.append(infixlist[j].replace("___", " ")) setup_label = QLabel(infixmod[j]) setup_label.setWordWrap(True) desc_group = QGroupBox("Description") desc_label = QLabel(desclist[j]) desc_label.setWordWrap(True) param_label = QGridLayout() nm = QLabel("Name:") des = QLabel("Description:") repl = QLabel("Replace with:") param_label.addWidget(nm, 0, 0) param_label.addWidget(des, 0, 1) param_label.addWidget(repl, 0, 2) """g is the total number of alterable values""" """t is the total number of alterable non-parameters""" t = 1 snum = 0 pnum = 0 inum = 0 """range of N is the max number of possible substrates OR products""" N = 5 for n in range(N): nl = n + 1 if (infixmod[j].find('S%s' % nl) > -1): z = QLabel('S%s is present' % nl) param_label.addWidget(z, t, 0) snum = snum + 1 t = t + 1 for n in range(N): nl = n + 1 if (infixmod[j].find('P%s' % nl) > -1): z = QLabel('P%s is present' % nl) param_label.addWidget(z, t, 0) pnum = pnum + 1 t = t + 1 for n in range(N): nl = n + 1 if (infixmod[j].find('I%s' % nl) > -1): z = QLabel('I%s is present' % nl) param_label.addWidget(z, t, 0) inum = inum + 1 t = t + 1 """Initialize lists of list of parameter lineedit""" length = len(parameternamelistlist[j]) for b in range(length): p = QLabel("%s :" % parameternamelistlist[j][b]) param_label.addWidget(p, b + t, 0) d = QLabel("'%s'" % parameterdesclistlist[j][b]) param_label.addWidget(d, b + t, 1) Slineeditlist = [0 for x in range(snum)] Plineeditlist = [0 for x in range(pnum)] Ilineeditlist = [0 for x in range(inum)] paramlineeditlist = [0 for x in range(length)] editcount = 1 """Place lineedit widgets for parameters""" for s in range(snum): Slineeditlist[s] = QLineEdit() param_label.addWidget(Slineeditlist[s], editcount, 2) editcount = editcount + 1 SLElistlist[j] = Slineeditlist for s in range(pnum): Plineeditlist[s] = QLineEdit() param_label.addWidget(Plineeditlist[s], editcount, 2) editcount = editcount + 1 PLElistlist[j] = Plineeditlist for s in range(inum): Ilineeditlist[s] = QLineEdit() param_label.addWidget(Ilineeditlist[s], editcount, 2) editcount = editcount + 1 ILElistlist[j] = Ilineeditlist for s in range(length): paramlineeditlist[s] = QLineEdit() param_label.addWidget(paramlineeditlist[s], editcount, 2) editcount = editcount + 1 paramLElistlist[j] = paramlineeditlist """Necessary lists for editable parameters. Housekeeping essentially.""" numlistlist[j] = [snum, pnum, inum, length] charlist = ["S", "P", "I"] buttonlist.append(QPushButton(self)) buttonlist[j].setText("Insert Rate Law: %s" % displaynamelist[j]) # 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 """Page formatting""" setup_layout = QVBoxLayout() setup_layout.addWidget(setup_label) setup_group.setLayout(setup_layout) desc_group.setLayout(param_label) vlayout2 = QVBoxLayout() vlayout2.addWidget(setup_group) vlayout2.addWidget(desc_group) vlayout2.addWidget(buttonlist[j]) vlayout2.addStretch(1) self.lawdetailpage.setLayout(vlayout2) self.lawpage.addWidget(self.lawdetailpage) """Set up button functionality""" for k in range(47): buttonlist[k].clicked.connect( self.pressbutton(infixmod[k], SLElistlist[k], PLElistlist[k], ILElistlist[k], paramLElistlist[k], parameternamelistlist[k], numlistlist[k], charlist, k)) self.lawlist.currentRowChanged.connect(self.lawpage.setCurrentIndex) self.lawlist.setCurrentRow(0) self.lawlist.setMinimumWidth(self.lawlist.sizeHintForColumn(0)) """Set up high-level widget formatting.""" hsplitter = QSplitter() hsplitter.addWidget(self.lawlist) hsplitter.addWidget(self.lawpage) layout = QVBoxLayout() layout.addWidget(hsplitter) self.setLayout(layout) """Testing LineEdit functionality""" def entertext(self, le, string, stringlist): def entertextreal(): stuff = self.le.text() string = "%s" % stuff stringlist[0].replace("vo", "%s" % string) return entertextreal """Analyze lineedits on page, replace appropriate text, then paste text in console""" def pressbutton(ratelaw, string, SLElist, PLElist, ILElist, paramLElist, paramlist, numlist, charlist, j): def pressbuttoninsert(): stringmod = string for k in range(4): for i in range(numlist[k]): l = i + 1 if (k == 0): stuff = SLElist[i].text() if (stuff.find(" ") != -1 or stuff.find('"') != -1): pass elif (stuff == ""): pass else: stringmod = stringmod.replace( charlist[k] + str(l), "%s" % stuff) if (k == 1): stuff = PLElist[i].text() if (stuff.find(" ") != -1 or stuff.find('"') != -1): pass elif (stuff == ""): pass else: stringmod = stringmod.replace( charlist[k] + str(l), "%s" % stuff) if (k == 2): stuff = ILElist[i].text() if (stuff.find(" ") != -1 or stuff.find('"') != -1): pass elif (stuff == ""): pass else: stringmod = stringmod.replace( charlist[k] + str(l), "%s" % stuff) if (k == 3): stuff = paramLElist[i].text() if (stuff.find(" ") != -1 or stuff.find('"') != -1): pass elif (stuff == ""): pass else: stringmod = stringmod.replace( paramlist[i], "%s" % stuff) ratelaw.insertText(stringmod) return pressbuttoninsert
class FileSwitcher(QDialog): """A Sublime-like file switcher.""" sig_goto_file = Signal(int, object) # Constants that define the mode in which the list widget is working # FILE_MODE is for a list of files, SYMBOL_MODE if for a list of symbols # in a given file when using the '@' symbol. FILE_MODE, SYMBOL_MODE = [1, 2] MAX_WIDTH = 600 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) # --- Properties @property def widgets(self): widgets = [] for tabs, plugin in self.plugins_tabs: widgets += [(tabs.widget(index), plugin) for index in range(tabs.count())] return widgets @property def line_count(self): line_count = [] for widget in self.widgets: try: current_line_count = widget[0].get_line_count() except AttributeError: current_line_count = 0 line_count.append(current_line_count) return line_count @property def save_status(self): save_status = [] for da, icon in self.plugins_data: save_status += [getattr(td, 'newly_created', False) for td in da] return save_status @property def paths(self): paths = [] for da, icon in self.plugins_data: paths += [getattr(td, 'filename', None) for td in da] return paths @property def filenames(self): filenames = [] for da, icon in self.plugins_data: filenames += [os.path.basename(getattr(td, 'filename', None)) for td in da] return filenames @property def icons(self): icons = [] for da, icon in self.plugins_data: icons += [icon for td in da] return icons @property def current_path(self): return self.paths_by_widget[self.get_widget()] @property def paths_by_widget(self): widgets = [w[0] for w in self.widgets] return dict(zip(widgets, self.paths)) @property def widgets_by_path(self): widgets = [w[0] for w in self.widgets] return dict(zip(self.paths, widgets)) @property def filter_text(self): """Get the normalized (lowecase) content of the filter text.""" return to_text_string(self.edit.text()).lower() def set_search_text(self, _str): self.edit.setText(_str) def save_initial_state(self): """Save initial cursors and initial active widget.""" paths = self.paths self.initial_widget = self.get_widget() self.initial_cursors = {} for i, editor in enumerate(self.widgets): if editor is self.initial_widget: self.initial_path = paths[i] # This try is needed to make the fileswitcher work with # plugins that does not have a textCursor. try: self.initial_cursors[paths[i]] = editor.textCursor() except AttributeError: pass def accept(self): self.is_visible = False QDialog.accept(self) self.list.clear() def restore_initial_state(self): """Restores initial cursors and initial active editor.""" self.list.clear() self.is_visible = False widgets = self.widgets_by_path if not self.edit.clicked_outside: for path in self.initial_cursors: cursor = self.initial_cursors[path] if path in widgets: self.set_editor_cursor(widgets[path], cursor) if self.initial_widget in self.paths_by_widget: index = self.paths.index(self.initial_path) self.sig_goto_file.emit(index) def set_dialog_position(self): """Positions the file switcher dialog.""" parent = self.parent() geo = parent.geometry() width = self.list.width() # This has been set in setup left = parent.geometry().width()/2 - width/2 # Note: the +1 pixel on the top makes it look better if isinstance(parent, QMainWindow): top = (parent.toolbars_menu.geometry().height() + parent.menuBar().geometry().height() + 1) else: top = self.plugins_tabs[0][0].tabBar().geometry().height() + 1 while parent: geo = parent.geometry() top += geo.top() left += geo.left() parent = parent.parent() self.move(left, top) def get_item_size(self, content): """ Get the max size (width and height) for the elements of a list of strings as a QLabel. """ strings = [] if content: for rich_text in content: label = QLabel(rich_text) label.setTextFormat(Qt.PlainText) strings.append(label.text()) fm = label.fontMetrics() return (max([fm.width(s) * 1.3 for s in strings]), fm.height()) def fix_size(self, content): """ Adjusts the width and height of the file switcher based on the relative size of the parent and content. """ # Update size of dialog based on relative size of the parent if content: width, height = self.get_item_size(content) # Width parent = self.parent() relative_width = parent.geometry().width() * 0.65 if relative_width > self.MAX_WIDTH: relative_width = self.MAX_WIDTH self.list.setMinimumWidth(relative_width) # Height if len(content) < 8: max_entries = len(content) else: max_entries = 8 max_height = height * max_entries * 2.5 self.list.setMinimumHeight(max_height) # Resize self.list.resize(relative_width, self.list.height()) # --- Helper methods: List widget def count(self): """Gets the item count in the list widget.""" return self.list.count() def current_row(self): """Returns the current selected row in the list widget.""" return self.list.currentRow() def set_current_row(self, row): """Sets the current selected row in the list widget.""" return self.list.setCurrentRow(row) def select_row(self, steps): """Select row in list widget based on a number of steps with direction. Steps can be positive (next rows) or negative (previous rows). """ row = self.current_row() + steps if 0 <= row < self.count(): self.set_current_row(row) def previous_row(self): """Select previous row in list widget.""" if self.mode == self.SYMBOL_MODE: self.select_row(-1) return prev_row = self.current_row() - 1 if prev_row >= 0: title = self.list.item(prev_row).text() else: title = '' if prev_row == 0 and '</b></big><br>' in title: self.list.scrollToTop() elif '</b></big><br>' in title: # Select the next previous row, the one following is a title self.select_row(-2) else: self.select_row(-1) def next_row(self): """Select next row in list widget.""" if self.mode == self.SYMBOL_MODE: self.select_row(+1) return next_row = self.current_row() + 1 if next_row < self.count(): if '</b></big><br>' in self.list.item(next_row).text(): # Select the next next row, the one following is a title self.select_row(+2) else: self.select_row(+1) def get_stack_index(self, stack_index, plugin_index): """Get the real index of the selected item.""" other_plugins_count = sum([other_tabs[0].count() \ for other_tabs in \ self.plugins_tabs[:plugin_index]]) real_index = stack_index - other_plugins_count return real_index # --- Helper methods: Widget def get_widget(self, index=None, path=None, tabs=None): """Get widget by index. If no tabs and index specified the current active widget is returned. """ if index and tabs: return tabs.widget(index) elif path and tabs: return tabs.widget(index) elif self.plugin: index = self.plugins_instances.index(self.plugin) return self.plugins_tabs[index][0].currentWidget() else: return self.plugins_tabs[0][0].currentWidget() def set_editor_cursor(self, editor, cursor): """Set the cursor of an editor.""" pos = cursor.position() anchor = cursor.anchor() new_cursor = QTextCursor() if pos == anchor: new_cursor.movePosition(pos) else: new_cursor.movePosition(anchor) new_cursor.movePosition(pos, QTextCursor.KeepAnchor) editor.setTextCursor(cursor) def goto_line(self, line_number): """Go to specified line number in current active editor.""" if line_number: line_number = int(line_number) editor = self.get_widget() try: editor.go_to_line(min(line_number, editor.get_line_count())) except AttributeError: pass # --- Helper methods: Outline explorer def get_symbol_list(self): """Get the list of symbols present in the file.""" try: oedata = self.get_widget().get_outlineexplorer_data() except AttributeError: oedata = {} return oedata # --- Handlers def item_selection_changed(self): """List widget item selection change handler.""" row = self.current_row() if self.count() and row >= 0: if '</b></big><br>' in self.list.currentItem().text() and row == 0: self.next_row() if self.mode == self.FILE_MODE: try: stack_index = self.paths.index(self.filtered_path[row]) self.plugin = self.widgets[stack_index][1] plugin_index = self.plugins_instances.index(self.plugin) # Count the real index in the tabWidget of the # current plugin real_index = self.get_stack_index(stack_index, plugin_index) self.sig_goto_file.emit(real_index, self.plugin.get_current_tab_manager()) self.goto_line(self.line_number) try: self.plugin.switch_to_plugin() self.raise_() except AttributeError: # The widget using the fileswitcher is not a plugin pass self.edit.setFocus() except ValueError: pass else: line_number = self.filtered_symbol_lines[row] self.goto_line(line_number) def setup_file_list(self, filter_text, current_path): """Setup list widget content for file list display.""" short_paths = shorten_paths(self.paths, self.save_status) paths = self.paths icons = self.icons results = [] trying_for_line_number = ':' in filter_text # Get optional line number if trying_for_line_number: filter_text, line_number = filter_text.split(':') # Get all the available filenames scores = get_search_scores('', self.filenames, template="<b>{0}</b>") else: line_number = None # Get all available filenames and get the scores for # "fuzzy" matching scores = get_search_scores(filter_text, self.filenames, template="<b>{0}</b>") # Get max width to determine if shortpaths should be used max_width = self.get_item_size(paths)[0] self.fix_size(paths) # Build the text that will appear on the list widget for index, score in enumerate(scores): text, rich_text, score_value = score if score_value != -1: text_item = '<big>' + rich_text.replace('&', '') + '</big>' if trying_for_line_number: text_item += " [{0:} {1:}]".format(self.line_count[index], _("lines")) if max_width > self.list.width(): text_item += u"<br><i>{0:}</i>".format(short_paths[index]) else: text_item += u"<br><i>{0:}</i>".format(paths[index]) if (trying_for_line_number and self.line_count[index] != 0 or not trying_for_line_number): results.append((score_value, index, text_item)) # Sort the obtained scores and populate the list widget self.filtered_path = [] plugin = None for result in sorted(results): index = result[1] path = paths[index] icon = icons[index] text = '' try: title = self.widgets[index][1].get_plugin_title().split(' - ') if plugin != title[0]: plugin = title[0] text += '<br><big><b>' + plugin + '</b></big><br>' item = QListWidgetItem(text) item.setToolTip(path) item.setSizeHint(QSize(0, 25)) item.setFlags(Qt.ItemIsEditable) self.list.addItem(item) self.filtered_path.append(path) except: # The widget using the fileswitcher is not a plugin pass text = '' text += result[-1] item = QListWidgetItem(icon, text) item.setToolTip(path) item.setSizeHint(QSize(0, 25)) self.list.addItem(item) self.filtered_path.append(path) # To adjust the delegate layout for KDE themes self.list.files_list = True # Move selected item in list accordingly and update list size if current_path in self.filtered_path: self.set_current_row(self.filtered_path.index(current_path)) elif self.filtered_path: self.set_current_row(0) # If a line number is searched look for it self.line_number = line_number self.goto_line(line_number) def setup_symbol_list(self, filter_text, current_path): """Setup list widget content for symbol list display.""" # Get optional symbol name filter_text, symbol_text = filter_text.split('@') # Fetch the Outline explorer data, get the icons and values oedata = self.get_symbol_list() icons = get_python_symbol_icons(oedata) # The list of paths here is needed in order to have the same # point of measurement for the list widget size as in the file list # See issue 4648 paths = self.paths # Update list size self.fix_size(paths) symbol_list = process_python_symbol_data(oedata) line_fold_token = [(item[0], item[2], item[3]) for item in symbol_list] choices = [item[1] for item in symbol_list] scores = get_search_scores(symbol_text, choices, template="<b>{0}</b>") # Build the text that will appear on the list widget results = [] lines = [] self.filtered_symbol_lines = [] for index, score in enumerate(scores): text, rich_text, score_value = score line, fold_level, token = line_fold_token[index] lines.append(text) if score_value != -1: results.append((score_value, line, text, rich_text, fold_level, icons[index], token)) template = '{0}{1}' for (score, line, text, rich_text, fold_level, icon, token) in sorted(results): fold_space = ' '*(fold_level) line_number = line + 1 self.filtered_symbol_lines.append(line_number) textline = template.format(fold_space, rich_text) item = QListWidgetItem(icon, textline) item.setSizeHint(QSize(0, 16)) self.list.addItem(item) # To adjust the delegate layout for KDE themes self.list.files_list = False # Move selected item in list accordingly # NOTE: Doing this is causing two problems: # 1. It makes the cursor to auto-jump to the last selected # symbol after opening or closing a different file # 2. It moves the cursor to the first symbol by default, # which is very distracting. # That's why this line is commented! # self.set_current_row(0) def setup(self): """Setup list widget content.""" if len(self.plugins_tabs) == 0: self.close() return self.list.clear() current_path = self.current_path filter_text = self.filter_text # Get optional line or symbol to define mode and method handler trying_for_symbol = ('@' in self.filter_text) if trying_for_symbol: self.mode = self.SYMBOL_MODE self.setup_symbol_list(filter_text, current_path) else: self.mode = self.FILE_MODE self.setup_file_list(filter_text, current_path) # Set position according to size self.set_dialog_position() def add_plugin(self, plugin, tabs, data, icon): """Add a plugin to display its files.""" self.plugins_tabs.append((tabs, plugin)) self.plugins_data.append((data, icon)) self.plugins_instances.append(plugin)
class MainWindow(QMainWindow): def __init__(self): self.logger = logging.getLogger(APPLICATION_NAME + '.MainWindow') self.logger.info("MainWindow.__init__") super(MainWindow, self).__init__() self.init_ui() self.read_settings() def init_ui(self): # Define standard icon. standard_icon = self.style().standardIcon # Central widget. self.main_widget = SpectrumWidget() self.main_widget.setFocus() self.setCentralWidget(self.main_widget) # Project action new_project_action = QAction(QIcon(':/oi/svg/document.svg'), 'New project', self) new_project_action.setShortcut('Ctrl+N') new_project_action.setStatusTip('New project') new_project_action.triggered.connect(self.new_project) open_project_action = QAction(QIcon(':/oi/svg/envelope-open.svg'), 'Open project', self) open_project_action.setShortcut('Ctrl+O') open_project_action.setStatusTip('Open project') open_project_action.triggered.connect(self.open_project) close_project_action = QAction(QIcon(':/oi/svg/envelope-closed.svg'), 'Close project', self) close_project_action.setShortcut('Ctrl+C') close_project_action.setStatusTip('Close project') close_project_action.triggered.connect(self.close_project) save_project_action = QAction(QIcon(':/oi/svg/hard-drive.svg'), 'Save project', self) save_project_action.setShortcut('Ctrl+S') save_project_action.setStatusTip('Save project') save_project_action.triggered.connect(self.save_project) saveas_project_action = QAction(QIcon(':/oi/svg/hard-drive.svg'), 'Save project as ...', self) # saveas_project_action.setShortcut('Ctrl+S') saveas_project_action.setStatusTip('Save project as ...') saveas_project_action.triggered.connect(self.saveas_project) # Spectrum action import_spectrum_action = QAction(QIcon(':/oi/svg/account-login.svg'), 'Import spectrum', self) import_spectrum_action.setShortcut('Ctrl+I') import_spectrum_action.setStatusTip('Import spectrum') import_spectrum_action.triggered.connect(self.import_spectrum) export_spectrum_action = QAction(QIcon(':/oi/svg/account-logout.svg'), 'Export spectrum', self) # export_spectrum_action.setShortcut('Ctrl+I') export_spectrum_action.setStatusTip('Export spectrum') export_spectrum_action.triggered.connect(self.export_spectrum) # Exit action exit_action = QAction(QIcon(':/oi/svg/x.svg'), 'Exit', self) exit_action.setShortcut('Ctrl+Q') exit_action.setStatusTip('Exit application') exit_action.triggered.connect(self.close) # Status bar. self.statusBar() # Menu bar. menubar = self.menuBar() file_menu = menubar.addMenu('&File') file_menu.addAction(new_project_action) file_menu.addAction(open_project_action) file_menu.addAction(save_project_action) file_menu.addAction(saveas_project_action) file_menu.addAction(close_project_action) file_menu.addSeparator() file_menu.addAction(exit_action) view_menu = menubar.addMenu('&View') spectrum_menu = menubar.addMenu('&Spectrum') spectrum_menu.addAction(import_spectrum_action) analysis_menu = menubar.addMenu('&Analysis') # Toolbar file_toolbar = self.addToolBar('File') file_toolbar.addAction(new_project_action) file_toolbar.addAction(open_project_action) file_toolbar.addAction(save_project_action) file_toolbar.addAction(saveas_project_action) file_toolbar.addAction(close_project_action) file_toolbar.addAction(exit_action) view_menu.addAction(file_toolbar.toggleViewAction()) spectrum_toolbar = self.addToolBar('Spectrum') spectrum_toolbar.addAction(import_spectrum_action) view_menu.addAction(spectrum_toolbar.toggleViewAction()) analysis_toolbar = self.addToolBar('Analysis') view_menu.addAction(analysis_toolbar.toggleViewAction()) view_menu.addSeparator() # Dock widget. self.graphic_settings_dock = QDockWidget("Graphic settings", self) self.graphic_settings_dock.setObjectName("graphic_settings_dock") self.graphic_settings_dock.setAllowedAreas(Qt.AllDockWidgetAreas) label_test = QLabel("Test label") self.graphic_settings_dock.setWidget(label_test) view_menu.addAction(self.graphic_settings_dock.toggleViewAction()) self.addDockWidget(Qt.AllDockWidgetAreas, self.graphic_settings_dock) print(self.graphic_settings_dock.objectName()) # Final options. self.setWindowTitle('X-ray spectrum analyzer') self.show() def closeEvent(self, event): self.save_settings() super(MainWindow, self).closeEvent(event) def save_settings(self): settings = QSettings("openMicroanalysis", "xrayspectrumanalyzergui") # print(settings.fileName()) settings.beginGroup("MainWindow") settings.setValue("geometry", self.saveGeometry()) settings.setValue("window_state", self.saveState()) settings.endGroup() settings.beginGroup("graphic_settings_dock") settings.setValue("visible", self.graphic_settings_dock.isVisible()) settings.endGroup() # settings.beginGroup("zero_loss_peak_dock") # settings.setValue("visible", self.zero_loss_peak_dock.isVisible()) # settings.endGroup() def read_settings(self): settings = QSettings("openMicroanalysis", "xrayspectrumanalyzergui") # print(settings.fileName()) # settings.clear() settings.beginGroup("MainWindow") geometry_value = settings.value("geometry") if geometry_value is None: self.setGeometry(300, 300, 600, 400) else: self.restoreGeometry(geometry_value) window_state_value = settings.value("window_state") if window_state_value is not None: self.restoreState(window_state_value) settings.endGroup() settings.beginGroup("graphic_settings_dock") visible_value = settings.value("visible") if visible_value is not None: if visible_value == "true": self.graphic_settings_dock.setVisible(True) elif visible_value == "false": self.graphic_settings_dock.setVisible(False) settings.endGroup() # settings.beginGroup("zero_loss_peak_dock") # visible_value = settings.value("visible") # if visible_value is not None: # if visible_value == "true": # self.zero_loss_peak_dock.setVisible(True) # elif visible_value == "false": # self.zero_loss_peak_dock.setVisible(False) # settings.endGroup() def import_spectrum(self): self.statusBar().showMessage("Import spectrum", 2000) path = os.path.dirname(__file__) formats = ["*.msa", "*.txt"] file_filters = "Spectrum file ({:s})".format(" ".join(formats)) file_names = QFileDialog.getOpenFileName(self, "Import an x-ray spectrum", path, file_filters) def export_spectrum(self): self.statusBar().showMessage("Export spectrum", 2000) def new_project(self): self.statusBar().showMessage("New project", 2000) def open_project(self): self.statusBar().showMessage("Open project", 2000) def close_project(self): self.statusBar().showMessage("Close project", 2000) def save_project(self): self.statusBar().showMessage("Save project", 2000) def saveas_project(self): self.statusBar().showMessage("Save project as ...", 2000) def create_gui(self): self.logger.info("MainWindow.create_gui") self._create_main_window() self._create_actions() self._create_menus() self._create_toolbars() self._create_tooltip() self._create_spectra_display() self._create_data_display() self._create_operations_display() self._create_layout() self._create_statusbar() self._read_settings() self.show() def _create_main_window(self): self.setGeometry(300, 300, 500, 500) self.setWindowTitle('Spectrum Analyzer') # self.setWindowIcon(QIcon('../../../images/cog.svg')) self.setWindowIcon(self.style().standardIcon(QStyle.SP_DesktopIcon)) self._center_main_window() def _center_main_window(self): self.logger.info("MainWindow._center_main_window") qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) def _create_menus(self): self.logger.info("MainWindow._create_menus") self.fileMenu = self.menuBar().addMenu("&File") self.fileMenu.addAction(self.newAct) self.fileMenu.addAction(self.openAct) self.fileMenu.addAction(self.saveAct) self.fileMenu.addAction(self.saveAsAct) self.fileMenu.addSeparator() self.fileMenu.addAction(self.exitAct) self.menuBar().addSeparator() self.helpMenu = self.menuBar().addMenu("&Help") self.helpMenu.addAction(self.aboutAct) self.helpMenu.addAction(self.aboutQtAct) def _create_layout(self): mainLayout = QHBoxLayout() mainLayout.addWidget(self.dataGroupBox) mainLayout.addWidget(self.plotGroupBox) mainLayout.addWidget(self.operationsGroupBox) self.mainGroupBox = QGroupBox("Main layout") self.mainGroupBox.setLayout(mainLayout) self.setCentralWidget(self.mainGroupBox) def _create_spectra_display(self): self.plotGroupBox = QGroupBox("Plot layout") self.figure1 = Figure(facecolor=(1, 1, 1), edgecolor=(0, 0, 0)) self.canvas1 = FigureCanvas(self.figure1) self.canvas1.setParent(self.plotGroupBox) self.canvas1.setFocusPolicy(Qt.StrongFocus) self.canvas1.setFocus() self.canvas1.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.canvas1.updateGeometry() self.mpl_toolbar1 = NavigationToolbar(self.canvas1, self.plotGroupBox) self.canvas1.mpl_connect('key_press_event', self.on_key_press) self.figure2 = Figure(facecolor=(1, 1, 1), edgecolor=(0, 0, 0)) self.canvas2 = FigureCanvas(self.figure2) self.canvas2.setParent(self.plotGroupBox) self.mpl_toolbar2 = NavigationToolbar(self.canvas1, self.plotGroupBox) layout = QVBoxLayout() layout.addWidget(self.canvas1) layout.addWidget(self.mpl_toolbar1) layout.addWidget(self.canvas2) layout.addWidget(self.mpl_toolbar2) self.plotGroupBox.setLayout(layout) def _create_data_display(self): self.dataGroupBox = QGroupBox("Data layout") data_layout = QVBoxLayout() group_box = QGroupBox("Spectra") self.spectra_list_view = QListWidget(self) self.spectra_list_view.setMinimumWidth(200) layout = QVBoxLayout() layout.addWidget(self.spectra_list_view) group_box.setLayout(layout) data_layout.addWidget(group_box) group_box = QGroupBox("ROI") roi_list_view = QListWidget(self) layout = QVBoxLayout() layout.addWidget(roi_list_view) group_box.setLayout(layout) data_layout.addWidget(group_box) group_box = QGroupBox("Elements") element_list_view = QListWidget(self) layout = QVBoxLayout() layout.addWidget(element_list_view) group_box.setLayout(layout) data_layout.addWidget(group_box) self.dataGroupBox.setLayout(data_layout) def _create_operations_display(self): self.operationsGroupBox = QGroupBox("Operations layout") results_layout = QVBoxLayout() group_box = QGroupBox("Operation") results_layout.addWidget(group_box) group_box = QGroupBox("Results") results_layout.addWidget(group_box) self.operationsGroupBox.setLayout(results_layout) def _create_tooltip(self): QToolTip.setFont(QFont('SansSerif', 10)) self.setToolTip('This is a <b>QWidget</b> widget') def _create_actions(self): self.logger.info("MainWindow._create_actions") self.newAct = QAction(self.style().standardIcon(QStyle.SP_FileIcon), "&New", self, shortcut=QKeySequence.New, statusTip="Create a new file", triggered=self.newFile) self.openAct = QAction(self.style().standardIcon( QStyle.SP_DirOpenIcon), "&Open...", self, shortcut=QKeySequence.Open, statusTip="Open an existing file", triggered=self.open) self.saveAct = QAction(self.style().standardIcon( QStyle.SP_DialogSaveButton), "&Save", self, shortcut=QKeySequence.Save, statusTip="Save the document to disk", triggered=self.save) self.saveAsAct = QAction( self.style().standardIcon(QStyle.SP_DialogSaveButton), "Save &As...", self, shortcut=QKeySequence.SaveAs, statusTip="Save the document under a new name", triggered=self.saveAs) self.exitAct = QAction(self.style().standardIcon( QStyle.SP_DialogCloseButton), "E&xit", self, shortcut="Ctrl+Q", statusTip="Exit the application", triggered=self.close) self.textEdit = QTextEdit() self.aboutAct = QAction(self.style().standardIcon( QStyle.SP_MessageBoxInformation), "&About", self, statusTip="Show the application's About box", triggered=self.about) self.aboutQtAct = QAction(self.style().standardIcon( QStyle.SP_TitleBarMenuButton), "About &Qt", self, statusTip="Show the Qt library's About box", triggered=QApplication().aboutQt) def _create_toolbars(self): self.logger.info("MainWindow._create_toolbars") self.fileToolBar = self.addToolBar("File") self.fileToolBar.addAction(self.newAct) self.fileToolBar.addAction(self.openAct) self.fileToolBar.addAction(self.saveAct) def _create_statusbar(self): self.logger.info("MainWindow._create_statusbar") self.statusBar().showMessage("Ready") def _read_settings(self): self.logger.info("MainWindow._read_settings") settings = QSettings(ORGANIZATION_NAME, APPLICATION_NAME) pos = settings.value("pos", QPoint(200, 200)) size = settings.value("size", QSize(400, 400)) self.resize(size) self.move(pos) def _write_settings(self): self.logger.info("MainWindow._write_settings") settings = QSettings(ORGANIZATION_NAME, APPLICATION_NAME) settings.setValue("pos", self.pos()) settings.setValue("size", self.size()) def maybeSave(self): self.logger.info("MainWindow.maybeSave") if self.textEdit.document().isModified(): ret = QMessageBox.warning( self, "Application", "The document has been modified.\nDo you want to save " "your changes?", QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel) if ret == QMessageBox.Save: return self.save() elif ret == QMessageBox.Cancel: return False return True def closeEvent(self, event): self.logger.info("MainWindow.closeEvent") if self.maybeSave(): self._write_settings() event.accept() else: event.ignore() def newFile(self): self.logger.info("MainWindow.newFile") if self.maybeSave(): self.textEdit.clear() self.setCurrentFile('') def open(self): self.logger.info("MainWindow.open") if self.maybeSave(): filepath, _filtr = QFileDialog.getOpenFileName(self) if filepath: self.spectrumAnalyzer.readSpectrum(filepath) filename = os.path.basename(filepath) self.spectra_list_view.addItem(filename) self.spectrumAnalyzer.plotSpectrum(self.figure1) self.canvas1.draw() def save(self): self.logger.info("MainWindow.save") if self.curFile: return self.saveFile(self.curFile) return self.saveAs() def saveAs(self): self.logger.info("MainWindow.saveAs") fileName, _filtr = QFileDialog.getSaveFileName(self) if fileName: return self.saveFile(fileName) return False def about(self): self.logger.info("MainWindow.about") QMessageBox.about( self, "About xrayspectrumanalyzer", "The <b>xrayspectrumanalyzer</b> extract peak intensity from EDS spectrum." ) def documentWasModified(self): self.logger.info("MainWindow.documentWasModified") self.setWindowModified(self.textEdit.document().isModified()) def on_key_press(self, event): print('you pressed', event.key) # implement the default mpl key press events described at # http://matplotlib.org/users/navigation_toolbar.html#navigation-keyboard-shortcuts key_press_handler(event, self.canvas1, self.mpl_toolbar1)
class ConfigDialog(QDialog): """Spyder configuration ('Preferences') dialog box""" # Signals check_settings = Signal() size_change = Signal(QSize) 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 get_current_index(self): """Return current page index""" return self.contents_widget.currentRow() def set_current_index(self, index): """Set current page index""" self.contents_widget.setCurrentRow(index) def get_page(self, index=None): """Return page widget""" if index is None: widget = self.pages_widget.currentWidget() else: widget = self.pages_widget.widget(index) return widget.widget() @Slot() def accept(self): """Reimplement Qt method""" for index in range(self.pages_widget.count()): configpage = self.get_page(index) if not configpage.is_valid(): return configpage.apply_changes() QDialog.accept(self) def button_clicked(self, button): if button is self.apply_btn: # Apply button was clicked configpage = self.get_page() if not configpage.is_valid(): return configpage.apply_changes() def current_page_changed(self, index): widget = self.get_page(index) self.apply_btn.setVisible(widget.apply_callback is not None) self.apply_btn.setEnabled(widget.is_modified) def add_page(self, widget): self.check_settings.connect(widget.check_settings) widget.show_this_page.connect(lambda row=self.contents_widget.count(): self.contents_widget.setCurrentRow(row)) widget.apply_button_enabled.connect(self.apply_btn.setEnabled) scrollarea = QScrollArea(self) scrollarea.setWidgetResizable(True) scrollarea.setWidget(widget) self.pages_widget.addWidget(scrollarea) item = QListWidgetItem(self.contents_widget) try: item.setIcon(widget.get_icon()) except TypeError: pass item.setText(widget.get_name()) item.setFlags(Qt.ItemIsSelectable|Qt.ItemIsEnabled) item.setSizeHint(QSize(0, 25)) def check_all_settings(self): """This method is called to check all configuration page settings after configuration dialog has been shown""" self.check_settings.emit() def resizeEvent(self, event): """ Reimplement Qt method to be able to save the widget's size from the main application """ QDialog.resizeEvent(self, event) self.size_change.emit(self.size())