INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Show warning using Tkinter if available | def show_warning(message):
"""Show warning using Tkinter if available"""
try:
# If Tkinter is installed (highly probable), showing an error pop-up
import Tkinter, tkMessageBox
root = Tkinter.Tk()
root.withdraw()
tkMessageBox.showerror("Spyder", message)
except... |
Check sys.path: is Spyder properly installed? | def check_path():
"""Check sys.path: is Spyder properly installed?"""
dirname = osp.abspath(osp.join(osp.dirname(__file__), osp.pardir))
if dirname not in sys.path:
show_warning("Spyder must be installed properly "
"(e.g. from source: 'python setup.py install'),\n"
... |
Check Qt binding requirements | def check_qt():
"""Check Qt binding requirements"""
qt_infos = dict(pyqt5=("PyQt5", "5.6"))
try:
import qtpy
package_name, required_ver = qt_infos[qtpy.API]
actual_ver = qtpy.PYQT_VERSION
if LooseVersion(actual_ver) < LooseVersion(required_ver):
show_warni... |
Check spyder-kernel requirement. | def check_spyder_kernels():
"""Check spyder-kernel requirement."""
try:
import spyder_kernels
required_ver = '1.0.0'
actual_ver = spyder_kernels.__version__
if LooseVersion(actual_ver) < LooseVersion(required_ver):
show_warning("Please check Spyder installation... |
Register plugin in Spyder's main window | def register_plugin(self):
"""Register plugin in Spyder's main window"""
self.breakpoints.edit_goto.connect(self.main.editor.load)
#self.redirect_stdio.connect(self.main.redirect_internalshell_stdio)
self.breakpoints.clear_all_breakpoints.connect(
... |
Determine if the lock of the given name is held or not.
@type name: C{str}
@param name: The filesystem path to the lock to test
@rtype: C{bool}
@return: True if the lock is held, False otherwise. | def isLocked(name):
"""Determine if the lock of the given name is held or not.
@type name: C{str}
@param name: The filesystem path to the lock to test
@rtype: C{bool}
@return: True if the lock is held, False otherwise.
"""
l = FilesystemLock(name)
result = None
try:
... |
Acquire this lock.
@rtype: C{bool}
@return: True if the lock is acquired, false otherwise.
@raise: Any exception os.symlink() may raise, other than
EEXIST. | def lock(self):
"""
Acquire this lock.
@rtype: C{bool}
@return: True if the lock is acquired, false otherwise.
@raise: Any exception os.symlink() may raise, other than
EEXIST.
"""
clean = True
while True:
try:
... |
Release this lock.
This deletes the directory with the given name.
@raise: Any exception os.readlink() may raise, or
ValueError if the lock is not owned by this process. | def unlock(self):
"""
Release this lock.
This deletes the directory with the given name.
@raise: Any exception os.readlink() may raise, or
ValueError if the lock is not owned by this process.
"""
pid = readlink(self.name)
if int(pid) != os.getp... |
Start thread to render a given documentation | def render(self, doc, context=None, math_option=False, img_path='',
css_path=CSS_PATH):
"""Start thread to render a given documentation"""
# If the thread is already running wait for it to finish before
# starting it again.
if self.wait():
self.doc = doc
... |
Qt Override. | def sortByName(self):
"""Qt Override."""
self.servers = sorted(self.servers, key=lambda x: x.language)
self.reset() |
Qt Override. | def data(self, index, role=Qt.DisplayRole):
"""Qt Override."""
row = index.row()
if not index.isValid() or not (0 <= row < len(self.servers)):
return to_qvariant()
server = self.servers[row]
column = index.column()
if role == Qt.DisplayRole:
if c... |
Qt Override. | def headerData(self, section, orientation, role=Qt.DisplayRole):
"""Qt Override."""
if role == Qt.TextAlignmentRole:
if orientation == Qt.Horizontal:
return to_qvariant(int(Qt.AlignHCenter | Qt.AlignVCenter))
return to_qvariant(int(Qt.AlignRight | Qt.AlignVCenter)... |
Qt Override. | def focusInEvent(self, e):
"""Qt Override."""
super(LSPServerTable, self).focusInEvent(e)
self.selectRow(self.currentIndex().row()) |
Update selected row. | def selection(self, index):
"""Update selected row."""
self.update()
self.isActiveWindow()
self._parent.delete_btn.setEnabled(True) |
Adjust column size based on contents. | def adjust_cells(self):
"""Adjust column size based on contents."""
self.resizeColumnsToContents()
fm = self.horizontalHeader().fontMetrics()
names = [fm.width(s.cmd) for s in self.source_model.servers]
if names:
self.setColumnWidth(CMD, max(names))
self.horiz... |
Move to next row from currently selected row. | def next_row(self):
"""Move to next row from currently selected row."""
row = self.currentIndex().row()
rows = self.source_model.rowCount()
if row + 1 == rows:
row = -1
self.selectRow(row + 1) |
Move to previous row from currently selected row. | def previous_row(self):
"""Move to previous row from currently selected row."""
row = self.currentIndex().row()
rows = self.source_model.rowCount()
if row == 0:
row = rows
self.selectRow(row - 1) |
Qt Override. | def keyPressEvent(self, event):
"""Qt Override."""
key = event.key()
if key in [Qt.Key_Enter, Qt.Key_Return]:
self.show_editor()
elif key in [Qt.Key_Backtab]:
self.parent().reset_btn.setFocus()
elif key in [Qt.Key_Up, Qt.Key_Down, Qt.Key_Left, Qt.Key_Right... |
Handle convention changes. | def setup_docstring_style_convention(self, text):
"""Handle convention changes."""
if text == 'Custom':
self.docstring_style_select.label.setText(
_("Show the following errors:"))
self.docstring_style_ignore.label.setText(
_("Ignore the following e... |
Adds an external path to the combobox if it exists on the file system.
If the path is already listed in the combobox, it is removed from its
current position and added back at the end. If the maximum number of
paths is reached, the oldest external path is removed from the list. | def add_external_path(self, path):
"""
Adds an external path to the combobox if it exists on the file system.
If the path is already listed in the combobox, it is removed from its
current position and added back at the end. If the maximum number of
paths is reached, the olde... |
Returns a list of the external paths listed in the combobox. | def get_external_paths(self):
"""Returns a list of the external paths listed in the combobox."""
return [to_text_string(self.itemText(i))
for i in range(EXTERNAL_PATHS, self.count())] |
Returns the path corresponding to the currently selected item
in the combobox. | def get_current_searchpath(self):
"""
Returns the path corresponding to the currently selected item
in the combobox.
"""
idx = self.currentIndex()
if idx == CWD:
return self.path
elif idx == PROJECT:
return self.project_path
... |
Handles when the current index of the combobox changes. | def path_selection_changed(self):
"""Handles when the current index of the combobox changes."""
idx = self.currentIndex()
if idx == SELECT_OTHER:
external_path = self.select_directory()
if len(external_path) > 0:
self.add_external_path(external_path)... |
Select directory | def select_directory(self):
"""Select directory"""
self.__redirect_stdio_emit(False)
directory = getexistingdirectory(
self, _("Select directory"), self.path)
if directory:
directory = to_unicode_from_fs(osp.abspath(directory))
self.__redirect_s... |
Sets the project path and disables the project search in the combobox
if the value of path is None. | def set_project_path(self, path):
"""
Sets the project path and disables the project search in the combobox
if the value of path is None.
"""
if path is None:
self.project_path = None
self.model().item(PROJECT, 0).setEnabled(False)
if s... |
Used to handle key events on the QListView of the combobox. | def eventFilter(self, widget, event):
"""Used to handle key events on the QListView of the combobox."""
if event.type() == QEvent.KeyPress and event.key() == Qt.Key_Delete:
index = self.view().currentIndex().row()
if index >= EXTERNAL_PATHS:
# Remove item and... |
Searches through the parent tree to see if it is possible to emit the
redirect_stdio signal.
This logic allows to test the SearchInComboBox select_directory method
outside of the FindInFiles plugin. | def __redirect_stdio_emit(self, value):
"""
Searches through the parent tree to see if it is possible to emit the
redirect_stdio signal.
This logic allows to test the SearchInComboBox select_directory method
outside of the FindInFiles plugin.
"""
parent = s... |
Reimplemented to handle key events | def keyPressEvent(self, event):
"""Reimplemented to handle key events"""
ctrl = event.modifiers() & Qt.ControlModifier
shift = event.modifiers() & Qt.ShiftModifier
if event.key() in (Qt.Key_Enter, Qt.Key_Return):
self.find.emit()
elif event.key() == Qt.Key_F and... |
Get options | def get_options(self, to_save=False):
"""Get options"""
text_re = self.edit_regexp.isChecked()
exclude_re = self.exclude_regexp.isChecked()
case_sensitive = self.case_button.isChecked()
# Return current options for them to be saved when closing
# Spyder.
... |
Double-click event | def activated(self, item):
"""Double-click event"""
itemdata = self.data.get(id(self.currentItem()))
if itemdata is not None:
filename, lineno, colno = itemdata
self.sig_edit_goto.emit(filename, lineno, self.search_text) |
Enable result sorting after search is complete. | def set_sorting(self, flag):
"""Enable result sorting after search is complete."""
self.sorting['status'] = flag
self.header().setSectionsClickable(flag == ON) |
Real-time update of search results | def append_result(self, results, num_matches):
"""Real-time update of search results"""
filename, lineno, colno, match_end, line = results
if filename not in self.files:
file_item = FileMatchItem(self, filename, self.sorting,
self.text_col... |
Override show event to start waiting spinner. | def showEvent(self, event):
"""Override show event to start waiting spinner."""
QWidget.showEvent(self, event)
self.spinner.start() |
Override hide event to stop waiting spinner. | def hideEvent(self, event):
"""Override hide event to stop waiting spinner."""
QWidget.hideEvent(self, event)
self.spinner.stop() |
Call the find function | def find(self):
"""Call the find function"""
options = self.find_options.get_options()
if options is None:
return
self.stop_and_reset_thread(ignore_results=True)
self.search_thread = SearchThread(self)
self.search_thread.sig_finished.connect(self.search... |
Stop current search thread and clean-up | def stop_and_reset_thread(self, ignore_results=False):
"""Stop current search thread and clean-up"""
if self.search_thread is not None:
if self.search_thread.isRunning():
if ignore_results:
self.search_thread.sig_finished.disconnect(
... |
Current search thread has finished | def search_complete(self, completed):
"""Current search thread has finished"""
self.result_browser.set_sorting(ON)
self.find_options.ok_button.setEnabled(True)
self.find_options.stop_button.setEnabled(False)
self.status_bar.hide()
self.result_browser.expandAll()
... |
Get the stored credentials if any. | def _get_credentials_from_settings(self):
"""Get the stored credentials if any."""
remember_me = CONF.get('main', 'report_error/remember_me')
remember_token = CONF.get('main', 'report_error/remember_token')
username = CONF.get('main', 'report_error/username', '')
if not remember_... |
Store credentials for future use. | def _store_credentials(self, username, password, remember=False):
"""Store credentials for future use."""
if username and password and remember:
CONF.set('main', 'report_error/username', username)
try:
keyring.set_password('github', username, password)
... |
Store token for future use. | def _store_token(self, token, remember=False):
"""Store token for future use."""
if token and remember:
try:
keyring.set_password('github', 'token', token)
except Exception:
if self._show_msgbox:
QMessageBox.warning(self.parent_... |
Get user credentials with the login dialog. | def get_user_credentials(self):
"""Get user credentials with the login dialog."""
password = None
token = None
(username, remember_me,
remember_token) = self._get_credentials_from_settings()
valid_py_os = not (PY2 and sys.platform.startswith('linux'))
if username... |
Attempts to show the specified tip at the current cursor location. | def show_tip(self, point, tip):
"""
Attempts to show the specified tip at the current cursor location.
"""
# Don't attempt to show it if it's already visible and the text
# to be displayed is the same as the one displayed before.
if self.isVisible():
if self.t... |
Override Qt method to hide the tooltip on leave. | def leaveEvent(self, event):
"""Override Qt method to hide the tooltip on leave."""
super(ToolTipWidget, self).leaveEvent(event)
self.hide() |
Reimplemented to hide on certain key presses and on text edit focus
changes. | def eventFilter(self, obj, event):
""" Reimplemented to hide on certain key presses and on text edit focus
changes.
"""
if obj == self._text_edit:
etype = event.type()
if etype == QEvent.KeyPress:
key = event.key()
cursor = sel... |
Reimplemented to hide the widget when the hide timer fires. | def timerEvent(self, event):
""" Reimplemented to hide the widget when the hide timer fires.
"""
if event.timerId() == self._hide_timer.timerId():
self._hide_timer.stop()
self.hide() |
Reimplemented to cancel the hide timer. | def enterEvent(self, event):
""" Reimplemented to cancel the hide timer.
"""
super(CallTipWidget, self).enterEvent(event)
if self.as_tooltip:
self.hide()
if (self._hide_timer.isActive() and
self.app.topLevelAt(QCursor.pos()) == self):
self._hide... |
Reimplemented to disconnect signal handlers and event filter. | def hideEvent(self, event):
""" Reimplemented to disconnect signal handlers and event filter.
"""
super(CallTipWidget, self).hideEvent(event)
self._text_edit.cursorPositionChanged.disconnect(
self._cursor_position_changed)
self._text_edit.removeEventFilter(self) |
Reimplemented to start the hide timer. | def leaveEvent(self, event):
""" Reimplemented to start the hide timer.
"""
super(CallTipWidget, self).leaveEvent(event)
self._leave_event_hide() |
Reimplemented to connect signal handlers and event filter. | def showEvent(self, event):
""" Reimplemented to connect signal handlers and event filter.
"""
super(CallTipWidget, self).showEvent(event)
self._text_edit.cursorPositionChanged.connect(
self._cursor_position_changed)
self._text_edit.installEventFilter(self) |
Attempts to show the specified tip at the current cursor location. | def show_tip(self, point, tip, wrapped_tiplines):
""" Attempts to show the specified tip at the current cursor location.
"""
# Don't attempt to show it if it's already visible and the text
# to be displayed is the same as the one displayed before.
if self.isVisible():
... |
Hides the tooltip after some time has passed (assuming the cursor is
not over the tooltip). | def _leave_event_hide(self):
""" Hides the tooltip after some time has passed (assuming the cursor is
not over the tooltip).
"""
if (self.hide_timer_on and not self._hide_timer.isActive() and
# If Enter events always came after Leave events, we wouldn't need
#... |
Updates the tip based on user cursor movement. | def _cursor_position_changed(self):
""" Updates the tip based on user cursor movement.
"""
cursor = self._text_edit.textCursor()
position = cursor.position()
document = self._text_edit.document()
char = to_text_string(document.characterAt(position - 1))
if positio... |
Detect if text has mixed EOL characters | def has_mixed_eol_chars(text):
"""Detect if text has mixed EOL characters"""
eol_chars = get_eol_chars(text)
if eol_chars is None:
return False
correct_text = eol_chars.join((text+eol_chars).splitlines())
return repr(correct_text) != repr(text) |
Use the same eol's in text | def normalize_eols(text, eol='\n'):
"""Use the same eol's in text"""
for eol_char, _ in EOL_CHARS:
if eol_char != eol:
text = text.replace(eol_char, eol)
return text |
Test if passed string is the name of a Python builtin object | def is_builtin(text):
"""Test if passed string is the name of a Python builtin object"""
from spyder.py3compat import builtins
return text in [str(name) for name in dir(builtins)
if not name.startswith('_')] |
Return Python object in *source_code* at *offset*
Periods to the left of the cursor are carried forward
e.g. 'functools.par^tial' would yield 'functools.partial'
Retry prevents infinite recursion: retry only once | def get_primary_at(source_code, offset, retry=True):
"""Return Python object in *source_code* at *offset*
Periods to the left of the cursor are carried forward
e.g. 'functools.par^tial' would yield 'functools.partial'
Retry prevents infinite recursion: retry only once
"""
obj = ''
... |
Split source code into lines | def split_source(source_code):
'''Split source code into lines
'''
eol_chars = get_eol_chars(source_code)
if eol_chars:
return source_code.split(eol_chars)
else:
return [source_code] |
Split source code into python identifier-like tokens | def get_identifiers(source_code):
'''Split source code into python identifier-like tokens'''
tokens = set(re.split(r"[^0-9a-zA-Z_.]", source_code))
valid = re.compile(r'[a-zA-Z_]')
return [token for token in tokens if re.match(valid, token)] |
Return the individual components of a given file path
string (for the local operating system).
Taken from https://stackoverflow.com/q/21498939/438386 | def path_components(path):
"""
Return the individual components of a given file path
string (for the local operating system).
Taken from https://stackoverflow.com/q/21498939/438386
"""
components = []
# The loop guarantees that the returned components can be
# os.path.joined wi... |
Return the differentiated prefix of the given two iterables.
Taken from https://stackoverflow.com/q/21498939/438386 | def differentiate_prefix(path_components0, path_components1):
"""
Return the differentiated prefix of the given two iterables.
Taken from https://stackoverflow.com/q/21498939/438386
"""
longest_prefix = []
root_comparison = False
common_elmt = None
for index, (elmt0, elmt... |
Get tab title without ambiguation. | def disambiguate_fname(files_path_list, filename):
"""Get tab title without ambiguation."""
fname = os.path.basename(filename)
same_name_files = get_same_name_files(files_path_list, fname)
if len(same_name_files) > 1:
compare_path = shortest_path(same_name_files)
if compare_path ==... |
Get a list of the path components of the files with the same name. | def get_same_name_files(files_path_list, filename):
"""Get a list of the path components of the files with the same name."""
same_name_files = []
for fname in files_path_list:
if filename == os.path.basename(fname):
same_name_files.append(path_components(fname))
return same_nam... |
Add text decorations on a CodeEditor instance.
Don't add duplicated decorations, and order decorations according
draw_order and the size of the selection.
Args:
decorations (sourcecode.api.TextDecoration) (could be a list)
Returns:
int: Amount of decorations add... | def add(self, decorations):
"""
Add text decorations on a CodeEditor instance.
Don't add duplicated decorations, and order decorations according
draw_order and the size of the selection.
Args:
decorations (sourcecode.api.TextDecoration) (could be a list)
Ret... |
Update editor extra selections with added decorations.
NOTE: Update TextDecorations to use editor font, using a different
font family and point size could cause unwanted behaviors. | def update(self):
"""Update editor extra selections with added decorations.
NOTE: Update TextDecorations to use editor font, using a different
font family and point size could cause unwanted behaviors.
"""
font = self.editor.font()
for decoration in self._decorations:
... |
Removes a text decoration from the editor.
:param decoration: Text decoration to remove
:type decoration: spyder.api.TextDecoration | def remove(self, decoration):
"""
Removes a text decoration from the editor.
:param decoration: Text decoration to remove
:type decoration: spyder.api.TextDecoration
"""
try:
self._decorations.remove(decoration)
self.update()
return Tr... |
Order decorations according draw_order and size of selection.
Highest draw_order will appear on top of the lowest values.
If draw_order is equal,smaller selections are draw in top of
bigger selections. | def _order_decorations(self):
"""Order decorations according draw_order and size of selection.
Highest draw_order will appear on top of the lowest values.
If draw_order is equal,smaller selections are draw in top of
bigger selections.
"""
def order_function(sel):
... |
Get signature from inspect reply content | def get_signature(self, content):
"""Get signature from inspect reply content"""
data = content.get('data', {})
text = data.get('text/plain', '')
if text:
text = ANSI_OR_SPECIAL_PATTERN.sub('', text)
self._control.current_prompt_pos = self._prompt_pos
... |
Get object documentation dictionary | def get_doc(self, objtxt):
"""Get object documentation dictionary"""
if self._reading:
return
wait_loop = QEventLoop()
self.sig_got_reply.connect(wait_loop.quit)
self.silent_exec_method("get_ipython().kernel.get_doc('%s')" % objtxt)
wait_loop.exec_()
... |
Reimplement call tips to only show signatures, using the same
style from our Editor and External Console too | def _handle_inspect_reply(self, rep):
"""
Reimplement call tips to only show signatures, using the same
style from our Editor and External Console too
"""
cursor = self._get_cursor()
info = self._request_info.get('call_tip')
if info and info.id == rep['parent_head... |
Encode parameters. | def _encode_params(kw):
'''
Encode parameters.
'''
args = []
for k, v in kw.items():
try:
# Python 2
qv = v.encode('utf-8') if isinstance(v, unicode) else str(v)
except:
qv = v
args.append('%s=%s' % (k, urlquote(qv)))
return '&'.join(ar... |
Encode object as json str. | def _encode_json(obj):
'''
Encode object as json str.
'''
def _dump_obj(obj):
if isinstance(obj, dict):
return obj
d = dict()
for k in dir(obj):
if not k.startswith('_'):
d[k] = getattr(obj, k)
return d
return json.dumps(obj, de... |
Generate authorize_url.
>>> GitHub(client_id='3ebf94c5776d565bcf75').authorize_url()
'https://github.com/login/oauth/authorize?client_id=3ebf94c5776d565bcf75' | def authorize_url(self, state=None):
'''
Generate authorize_url.
>>> GitHub(client_id='3ebf94c5776d565bcf75').authorize_url()
'https://github.com/login/oauth/authorize?client_id=3ebf94c5776d565bcf75'
'''
if not self._client_id:
raise ApiAuthError('No client i... |
In callback url: http://host/callback?code=123&state=xyz
use code and state to get an access token. | def get_access_token(self, code, state=None):
'''
In callback url: http://host/callback?code=123&state=xyz
use code and state to get an access token.
'''
kw = dict(client_id=self._client_id, client_secret=self._client_secret, code=code)
if self._redirect_uri:
... |
Call function req and then send its results via ZMQ. | def send_request(req=None, method=None, requires_response=True):
"""Call function req and then send its results via ZMQ."""
if req is None:
return functools.partial(send_request, method=method,
requires_response=requires_response)
@functools.wraps(req)
def wrapp... |
Class decorator that allows to map LSP method names to class methods. | def class_register(cls):
"""Class decorator that allows to map LSP method names to class methods."""
cls.handler_registry = {}
cls.sender_registry = {}
for method_name in dir(cls):
method = getattr(cls, method_name)
if hasattr(method, '_handle'):
cls.handler_registry.update({... |
Set model data | def set_data(self, data, coll_filter=None):
"""Set model data"""
self._data = data
data_type = get_type_string(data)
if coll_filter is not None and not self.remote and \
isinstance(data, (tuple, list, dict, set)):
data = coll_filter(data)
self.shown... |
Overriding sort method | def sort(self, column, order=Qt.AscendingOrder):
"""Overriding sort method"""
reverse = (order==Qt.DescendingOrder)
if column == 0:
self.sizes = sort_against(self.sizes, self.keys, reverse)
self.types = sort_against(self.types, self.keys, reverse)
try:
... |
Array row number | def rowCount(self, index=QModelIndex()):
"""Array row number"""
if self.total_rows <= self.rows_loaded:
return self.total_rows
else:
return self.rows_loaded |
Return current value | def get_value(self, index):
"""Return current value"""
if index.column() == 0:
return self.keys[ index.row() ]
elif index.column() == 1:
return self.types[ index.row() ]
elif index.column() == 2:
return self.sizes[ index.row() ]
else:
... |
Background color depending on value | def get_bgcolor(self, index):
"""Background color depending on value"""
if index.column() == 0:
color = QColor(Qt.lightGray)
color.setAlphaF(.05)
elif index.column() < 3:
color = QColor(Qt.lightGray)
color.setAlphaF(.2)
else:
... |
Overriding method headerData | def headerData(self, section, orientation, role=Qt.DisplayRole):
"""Overriding method headerData"""
if role != Qt.DisplayRole:
return to_qvariant()
i_column = int(section)
if orientation == Qt.Horizontal:
headers = (self.header0, _("Type"), _("Size"), _("Val... |
Cell content | def data(self, index, role=Qt.DisplayRole):
"""Cell content"""
if not index.isValid():
return to_qvariant()
value = self.get_value(index)
if index.column() == 3 and self.remote:
value = value['view']
if index.column() == 3:
display = va... |
Overriding method flags | def flags(self, index):
"""Overriding method flags"""
# This method was implemented in CollectionsModel only, but to enable
# tuple exploration (even without editing), this method was moved here
if not index.isValid():
return Qt.ItemIsEnabled
return Qt.ItemFlags... |
Set value | def set_value(self, index, value):
"""Set value"""
self._data[ self.keys[index.row()] ] = value
self.showndata[ self.keys[index.row()] ] = value
self.sizes[index.row()] = get_size(value)
self.types[index.row()] = get_human_readable_type(value)
self.sig_setting_data.... |
Background color depending on value | def get_bgcolor(self, index):
"""Background color depending on value"""
value = self.get_value(index)
if index.column() < 3:
color = ReadOnlyCollectionsModel.get_bgcolor(self, index)
else:
if self.remote:
color_name = value['color']
... |
Cell content change | def setData(self, index, value, role=Qt.EditRole):
"""Cell content change"""
if not index.isValid():
return False
if index.column() < 3:
return False
value = display_to_value(value, self.get_value(index),
ignore_errors=True)... |
Decide if showing a warning when the user is trying to view
a big variable associated to a Tablemodel index
This avoids getting the variables' value to know its
size and type, using instead those already computed by
the TableModel.
The problem is when a variable ... | def show_warning(self, index):
"""
Decide if showing a warning when the user is trying to view
a big variable associated to a Tablemodel index
This avoids getting the variables' value to know its
size and type, using instead those already computed by
the TableMode... |
Overriding method createEditor | def createEditor(self, parent, option, index):
"""Overriding method createEditor"""
if index.column() < 3:
return None
if self.show_warning(index):
answer = QMessageBox.warning(self.parent(), _("Warning"),
_("Opening this variab... |
Overriding method setEditorData
Model --> Editor | def setEditorData(self, editor, index):
"""
Overriding method setEditorData
Model --> Editor
"""
value = self.get_value(index)
if isinstance(editor, QLineEdit):
if is_binary_string(value):
try:
value = to_text_strin... |
Overriding method setModelData
Editor --> Model | def setModelData(self, editor, model, index):
"""
Overriding method setModelData
Editor --> Model
"""
if not hasattr(model, "set_value"):
# Read-only mode
return
if isinstance(editor, QLineEdit):
value = editor.text()... |
Setup table | def setup_table(self):
"""Setup table"""
self.horizontalHeader().setStretchLastSection(True)
self.adjust_columns()
# Sorting columns
self.setSortingEnabled(True)
self.sortByColumn(0, Qt.AscendingOrder) |
Setup context menu | def setup_menu(self, minmax):
"""Setup context menu"""
if self.minmax_action is not None:
self.minmax_action.setChecked(minmax)
return
resize_action = create_action(self, _("Resize rows to contents"),
triggered=self.re... |
Refresh context menu | def refresh_menu(self):
"""Refresh context menu"""
index = self.currentIndex()
condition = index.isValid()
self.edit_action.setEnabled( condition )
self.remove_action.setEnabled( condition )
self.refresh_plot_entries(index) |
Set table data | def set_data(self, data):
"""Set table data"""
if data is not None:
self.model.set_data(data, self.dictfilter)
self.sortByColumn(0, Qt.AscendingOrder) |
Reimplement Qt method | def mousePressEvent(self, event):
"""Reimplement Qt method"""
if event.button() != Qt.LeftButton:
QTableView.mousePressEvent(self, event)
return
index_clicked = self.indexAt(event.pos())
if index_clicked.isValid():
if index_clicked == self.curre... |
Reimplement Qt method | def mouseDoubleClickEvent(self, event):
"""Reimplement Qt method"""
index_clicked = self.indexAt(event.pos())
if index_clicked.isValid():
row = index_clicked.row()
# TODO: Remove hard coded "Value" column number (3 here)
index_clicked = index_clicked.chi... |
Reimplement Qt methods | def keyPressEvent(self, event):
"""Reimplement Qt methods"""
if event.key() == Qt.Key_Delete:
self.remove_item()
elif event.key() == Qt.Key_F2:
self.rename_item()
elif event == QKeySequence.Copy:
self.copy()
elif event == QKeySequence.P... |
Reimplement Qt method | def contextMenuEvent(self, event):
"""Reimplement Qt method"""
if self.model.showndata:
self.refresh_menu()
self.menu.popup(event.globalPos())
event.accept()
else:
self.empty_ws_menu.popup(event.globalPos())
event.accept() |
Allow user to drag files | def dragEnterEvent(self, event):
"""Allow user to drag files"""
if mimedata2url(event.mimeData()):
event.accept()
else:
event.ignore() |
Allow user to move files | def dragMoveEvent(self, event):
"""Allow user to move files"""
if mimedata2url(event.mimeData()):
event.setDropAction(Qt.CopyAction)
event.accept()
else:
event.ignore() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.