pyqode.core.widgets package

Module contents

This package contains a set of widgets that might be useful when writing pyqode applications:

  • TextCodeEdit: code edit specialised for plain text
  • GenericCodeEdit: generic code edit, using PygmentsSH. Not really fast, not really smart.
  • InteractiveConsole: QTextEdit made for running background process interactively. Can be used in an IDE for running programs or to display the compiler output,...
  • CodeEditTabWidget: tab widget made to handle CodeEdit instances (or any other object that have the same interface).
  • ErrorsTable: a QTableWidget specialised to show CheckerMessage.

Classes

EncodingsContextMenu

class pyqode.core.widgets.EncodingsContextMenu(title='Encodings', parent=None, selected_encoding='ANSI_X3.4-1968')

Bases: pyqode.core.widgets.encodings.EncodingsMenu

Extends the encoding menu to be tightly coupled with a CodeEdit instance for an easier integration (automatically reload the editor file content when the encoding changed).

The parent widget of the menu must be set to a CodeEdit instance.

EncodingsComboBox

class pyqode.core.widgets.EncodingsComboBox(parent, default_encoding='ANSI_X3.4-1968')

Bases: PyQt5.QtWidgets.QComboBox

This combo box display the list of user preferred encoding. The last item let you choose an additional encoding from the list of encodings define in pyqode.core.api.encodings using the EncodingsEditorDialog.

You can also set the current encoding, it will be automatically appended if not in the user list or set as the current index.

current_encoding

Gets/Sets the current encoding

EncodingsMenu

class pyqode.core.widgets.EncodingsMenu(title='Encodings', parent=None, selected_encoding='ANSI_X3.4-1968')

Bases: PyQt5.QtWidgets.QMenu

Implements a menu that show the user preferred encoding and emit reload_requested when the user changed the selected encoding.

This menu is a general purpose menu that you can put anywhere in your application but you will have to manage the reload operation yourself. For an integrated context menu, prefer using pyqode.core.widgets.EncodingsContextMenu.

current_encoding

Gets/Sets the current encoding

reload_requested

Signal emitted when the user triggered an action.

ErrorsTable

class pyqode.core.widgets.ErrorsTable(parent=None)

Bases: PyQt5.QtWidgets.QTableWidget

Extends a QtWidgets.QTableWidget to easily show pyqode.core.modes.CheckerMessage.

You add messages to the table using pyqode.core.widgets.ErrorsTable.add_message().

You clear the table using pyqode.core.widgets.ErrorsTable().

add_message(msg)

Adds a checker message to the table.

Parameters:msg (pyqode.core.modes.CheckerMessage) – The message to append
clear()

Clears the tables and the message list

showDetails()

Shows the error details.

ICONS = {0: ':/ide-icons/rc/accept.png', 1: ':pyqode-icons/rc/dialog-warning.png', 2: ':pyqode-icons/rc/dialog-error.png'}
msg_activated

Signal emitted when a message is activated, the clicked signal is passed as a parameter

FileSystemContextMenu

class pyqode.core.widgets.FileSystemContextMenu

Bases: PyQt5.QtWidgets.QMenu

Default context menu for the file system treeview.

This context menu contains the following actions:
  • Copy
  • Cut
  • Paste
  • Delete
  • Copy path

Note

copy/cut/paste action works only from inside the application (e.g. you cannot paste what you copied in the app to the explorer)

get_linux_file_explorer()
get_new_user_actions()

Returns user actions for “new” sub-menu.

Example:

def get_new_user_actions(self):
    actions = []
    action_python_package = QtWidgets.QAction(
        '&Python package', self)
    action_python_package.triggered.connect(
        self._on_create_python_package_triggered)
    actions.append(action_python_package)
    return actions
tree_view = None

Reference to the tree view

FileSystemTreeView

class pyqode.core.widgets.FileSystemTreeView(parent=None)

Bases: PyQt5.QtWidgets.QTreeView

Extends QtWidgets.QTreeView with a filterable file system model.

To exclude directories or extension, just set FilterProxyModel.ignored_directories and FilterProxyModel.ignored_extensions.

Provides methods to retrieve file info from model index.

By default there is no context menu and no file operations are possible. We provide a standard context menu with basic file system operation ( FileSystemContextMenu) that you can extend and set on the tree view using FileSystemTreeView.set_context_menu()

class FilterProxyModel

Bases: PyQt5.QtCore.QSortFilterProxyModel

Excludes ignored_directories and ignored_extensions from the file system model.

filterAcceptsRow(row, parent)
set_root_path(path)

Sets the root path to watch. :param path: root path (str).

ignored_directories = None

The list of directories to ignore

ignored_extensions = None

The list of file extension to exclude

FileSystemTreeView.fileInfo(index)

Gets the file info of the item at the specified index.

Parameters:index – item index - QModelIndex
Returns:QFileInfo
FileSystemTreeView.filePath(index)

Gets the file path of the item at the specified index.

Parameters:index – item index - QModelIndex
Returns:str
FileSystemTreeView.ignore_directories(*directories)

Adds the specified directories to the list of ignored directories.

This must be done before calling set_root_path!

Parameters:directories – the directories to ignore
FileSystemTreeView.ignore_extensions(*extensions)

Adds the specified extensions to the list of ignored directories.

This must be done before calling set_root_path!

Parameters:extensions – the extensions to ignore

Note

extension must have the dot: ‘.py’ and not ‘py’

FileSystemTreeView.set_context_menu(context_menu)

Sets the context menu of the tree view.

Parameters:context_menu – QMenu
FileSystemTreeView.set_root_path(path, hide_extra_columns=True)

Sets the root path to watch :param path: root path - str :param hide_extra_columns: Hide extra column (size, paths,...)

FileSystemTreeView.file_created

signal emitted when the user created a file Parameters: - path (str): path of the file that got created

FileSystemTreeView.file_deleted

signal emitted when the user deleted a file Parameters: - path (str): path of the file that got deleted

FileSystemTreeView.file_renamed

signal emitted when the user renamed a file Parameters: - old (str): old path - new (str): new path

GenericCodeEdit

class pyqode.core.widgets.GenericCodeEdit(parent=None, server_script='/home/colin/pyqode/core/pyqode/core/backend/server.py', interpreter='/usr/bin/python3', args=None, create_default_actions=True, color_scheme='qt', reuse_backend=False)

Bases: pyqode.core.api.code_edit.CodeEdit

This generic code edit uses the PygmentSH for syntax highlighting and commpletion engine based on the document words. It is not very smart and is probably 2 times slower than a native specialised code edit. It is meant to be used as a fallback editor in case you’re missing a specialised editor.

clone()
setPlainText(txt, mime_type='', encoding='')
mimetypes = []

InteractiveConsole

class pyqode.core.widgets.InteractiveConsole(parent=None)

Bases: PyQt5.QtWidgets.QTextEdit

An interactive console is a QTextEdit specialised to run a process interactively

The user will see the process outputs and will be able to interact with the process by typing some text, this text will be forwarded to the process stdin.

You can customize the colors using the following attributes:

  • stdout_color: color of the process stdout
  • stdin_color: color of the user inputs. Green by default
  • app_msg_color: color for custom application message ( process started, process finished)
  • stderr_color: color of the process stderr
apply_color_scheme(color_scheme)

Apply a pygments color scheme to the console.

As there is not a 1 to 1 mapping between color scheme formats and console formats, we decided to make the following mapping (it usually looks good for most of the available pygments styles):

  • stdout_color = normal color
  • stderr_color = red (lighter if background is dark)
  • stdin_color = numbers color
  • app_msg_color = string color
  • bacgorund_color = background
Parameters:color_scheme – pyqode.core.api.ColorScheme to apply
closeEvent(*args, **kwargs)
keyPressEvent(event)
set_writer(writer)

Changes the writer function to handle writing to the text edit.

A writer function must have the following prototype:

def write(text_edit, text, color)
Parameters:writer – write function as described above.
start_process(process, args=None, cwd=None, env=None)

Starts a process interactively.

Parameters:
  • process (str) – Process to run
  • args (list) – List of arguments (list of str)
  • cwd (str) – Working directory
  • env – environment variables (dict).
stop_process()

Stop the process (by killing it).

static write(text_edit, text, color)

Default write function. Move the cursor to the end and insert text with the specified color.

Parameters:
  • text_edit (pyqode.widgets.QInteractiveConsole) – QInteractiveConsole instance
  • text (str) – Text to write
  • color (QColor) – Desired text color
app_msg_color

Color of the application messages (e.g.: ‘Process started’, ‘Process finished with status %d’)

background_color

The console background color. Default is white.

clear_on_start

True to clear window when starting a new process. False to accumulate outputs.

is_running

Checks if the process is running. :return:

merge_outputs

Merge stderr with stdout. Default is False.

If set to true, stderr and stdin will use the same color: stdin_color.

process_finished

Signal emitted when the process has finished.

stderr_color

Color for stderr output if pyqode.core.widgets.InteractiveConsole.merge_outputs is False.

Default is Red.

stdin_color

STDIN color. Default is green.

stdout_color

STDOUT color. Default is black.

PromptLineEdit

class pyqode.core.widgets.PromptLineEdit(parent=None, prompt_text=' Search', button_icon=None)

Bases: PyQt5.QtWidgets.QLineEdit

Extends QLineEdit to show a prompt text and a clear icon

paintEvent(event)
resizeEvent(event)
set_button_visible(visible)

Sets the clear button as visible

Parameters:visible – Visible state (True = visible, False = hidden).
clear_clicked

Signal emitted when the embedded button is clicked

prompt_text

Gets/Sets the prompt text.

RecentFilesManager

class pyqode.core.widgets.RecentFilesManager(organisation, application)

Bases: PyQt5.QtCore.QObject

Manages a list of recent files. The list of files is stored in your application QSettings.

clear()

Clears recent files in QSettings

get_recent_files()

Gets the list of recent files. (files that do not exists anymore are automatically filtered)

get_value(key, default=None)

Reads value from QSettings :param key: value key :param default: default value. :return: value

last_file()

Returns the path to the last opened file.

open_file(file)

Adds a file to the list (and move it to the top of the list if the file already exists)

Parameters:file – file path to add the list of recent files.
remove(filename)

Remove a file path from the list of recent files. :param filename: Path of the file to remove

set_value(key, value)

Set the recent files value in QSettings. :param key: value key :param value: new value

max_recent_files = 15

Maximum number of files kept in the list.

updated

SplittableTabWidget

class pyqode.core.widgets.SplittableTabWidget(parent=None, root=True)

Bases: PyQt5.QtWidgets.QSplitter

A splittable tab widget. The widget is implemented as a splitter which contains a main tab widget and a collection of child SplittableTabWidget.

Widgets added to the the tab widget must have a split method which returns a clone of the widget instance.

You can add new tabs to the main tab widget by using the add_tab method. Tabs are always closable.

To change the underlying tab widget class, just set the tab_widget_klass class attribute.

The splittable tab widget works with any kind of widget. There is a specialisation made specifically for managing a collection code editor widgets: SplittableCodeEditTabWidget.

The implementation uses duck typing and will automatically show a dialog when closing an editor which has a dirty property. To actually save the widget, you must reimplement SplittableTabWidget.save_widget`().

tab_widget_klass

underlying tab widget class

alias of BaseTabWidget

add_tab(tab, title='', icon=None)

Adds a tab to main tab widget.

Parameters:
  • tab – Widget to add as a new tab of the main tab widget.
  • title – Tab title
  • icon – Tab icon
count()

Returns the number of widgets currently displayed (takes child splits into account).

current_widget()

Returns a reference to the current widget, i.e. the last widget that got the focus. :return: QWidget

has_children()

Checks if there are children tab widgets. :return: True if there is at least one tab in the children tab widget.

split(widget, orientation)

Split the the current widget in new SplittableTabWidget.

Parameters:
  • widget – widget to split
  • orientation – orientation of the splitter
Returns:

the new splitter

widgets(include_clones=False)

Recursively gets the list of widgets.

Parameters:include_clones – True to retrieve all tabs, including clones, otherwise only original widgets are returned.
current_changed

Signal emitted when the active tab changed (takes child tab widgets into account). Parameter is the new tab widget.

last_tab_closed

Signal emitted when the last tab has been closed.

SplittableCodeEditTabWidget

class pyqode.core.widgets.SplittableCodeEditTabWidget(parent=None, root=True)

Bases: pyqode.core.widgets.splittable_tab_widget.SplittableTabWidget

SplittableTabWidget specialised for CodeEdit and subclasses.

Offers some convenience function for opening/saving files.

The widget supports multiple type of code editors. Each editor type must be explicitly registered using register_editor. If there is no registered editor for the given mime-type, fallback_editor is used.

fallback_editor

Fallback editor is used in case not editors matching the requested mime-type could not be found in the editors map. By default the fallback_editor is a pyqode.core.widgets.GenericCodeEdit

alias of GenericCodeEdit

icon_provider_klass

the icon provider class to use when creating new document. Must be a subclass of QtWidgets.QFileIconProvider. By default, QFileIconProvider is used.

alias of QFileIconProvider

tab_widget_klass

uses a CodeEditTabWidget which is able to save code editor widgets.

alias of CodeEditTabWidget

closeEvent(event)

Saves dirty editors on close and cancel the event if the user choosed to continue to work.

Parameters:event – close event
close_all()
close_document(path)

Closes a text document. :param path: Path of the document to close.

create_new_document(base_name='New Document', extension='.txt', *args, **kwargs)

Creates a new document.

The document name will be base_name + count + extension

Parameters:
  • base_name – Base name of the document. An int will be appended.
  • extension – Document extension (dotted)
  • args – Positional arguments that must be forwarded to the editor widget constructor.
  • kwargs – Keyworded arguments that must be forwarded to the editor widget constructor.
Returns:

Code editor widget instance.

guess_mimetype(path)
open_document(path, *args, **kwargs)

Opens a document.

Parameters:
  • args – additional args to pass to the widget constructor.
  • kwargs – addtional keyword args to pass to the widget constructor.
Returns:

The created code editor

classmethod register_code_edit(code_edit_class)

Register an additional code edit class :param code_edit_class: code edit class to regiter.

rename_document(old_path, new_path)

Renames an already opened document (this will not rename the file, just update the file path and tab title).

Use that function to update a file that has been renamed externally.

Parameters:
  • old_path – old path (path of the widget to rename with new_path
  • new_path – new path that will be used to rename the tab.
save_all()

Save all editors.

save_current()

Save current editor. If the editor.file.path is None, a save as dialog will be shown.

save_current_as()

Save current widget as.

dirty_changed

signal emitted when the dirty_changed signal of the current editor has been emitted.

editors = {'text/x-plain': <class 'pyqode.core.widgets.code_edits.TextCodeEdit'>, 'text/x-log': <class 'pyqode.core.widgets.code_edits.TextCodeEdit'>, 'text/plain': <class 'pyqode.core.widgets.code_edits.TextCodeEdit'>}

Maps a mime-type with an editor type. This map is used to instantiate the proper editor type when opening/creating a document.

TabBar

class pyqode.core.widgets.TabBar(parent)

Bases: PyQt5.QtWidgets.QTabBar

Tab bar specialized to allow the user to close a tab using mouse middle click. Also exposes a double clicked signal.

mouseDoubleClickEvent(event)
mousePressEvent(event)
double_clicked

TabWidget

class pyqode.core.widgets.TabWidget(parent)

Bases: PyQt5.QtWidgets.QTabWidget

QTabWidget specialised to hold CodeEdit instances (or any other object that has the same interace).

It ensures that there is only one open editor tab for a specific file path, it adds a few utility methods to quickly manipulate the current editor widget. It will automatically rename tabs that share the same base filename to include their distinctive parent directory.

It handles tab close requests automatically and show a dialog box when a dirty tab widget is being closed. It also adds a convenience QTabBar with a “close”, “close others” and “close all” menu. (You can add custom actions by using the addAction and addSeparator methods).

It exposes a variety of signal and slots for a better integration with your applications( dirty_changed, save_current, save_all, close_all, close_current, close_others).

addAction(action)

Adds an action to the TabBar context menu

Parameters:action – QAction to append
addTab(elem, icon, name)

Extends QTabWidget.addTab to keep an internal list of added tabs.

Parameters:
  • elem – tab widget
  • icon – tab icon
  • name – tab name
add_code_edit(code_edit, name=None)

Adds a code edit tab, sets its text as the editor.file.name and sets it as the active tab.

The widget is only added if there is no other editor tab open with the same filename, else the already open tab is set as current.

If the widget file path is empty, i.e. this is a new document that has not been saved to disk, you may provided a formatted string such as ‘New document %d.txt’ for the document name. The int format will be automatically replaced by the number of new documents (e.g. ‘New document 1.txt’ then ‘New document 2.txt’ and so on). If you prefer to use your own code to manage the file names, just ensure that the names are unique.

Parameters:
  • code_edit (pyqode.core.api.CodeEdit) – The code editor widget tab to append
  • name – Name of the tab. Will use code_edit.file.name if None is supplied. Default is None. If this is a new document, you should either pass a unique name or a formatted string (with a ‘%d’ format)
Returns:

Tab index

add_separator()

Adds a separator to the TabBar context menu.

:returns The separator action.

close()

Closes the active editor

closeEvent(event)
close_all()

Closes all editors

close_others()

Closes every editors tabs except the current one.

index_from_filename(path)

Checks if the path is already open in an editor tab.

Parameters:path – path to check
Returns:The tab index if found or -1
removeTab(index)

Removes tab at index index.

This method will emits tab_closed for the removed tab.

Parameters:index – index of the tab to remove.
save_all()

Save all editors.

save_current(path=None)

Save current editor content. Leave file to None to erase the previous file content. If the current editor’s file_path is None and path is None, the function will call QtWidgets.QFileDialog.getSaveFileName to get a valid save filename.

Parameters:path – path of the file to save, leave it None to overwrite existing file.
active_editor

Returns the current editor widget or None if the current tab widget is not a subclass of CodeEdit or if there is no open tab.

dirty_changed

Signal emitted when a tab dirty flag changed

last_tab_closed

Signal emitted when the last tab has been closed

tab_closed

Signal emitted when a tab has been closed

TextCodeEdit

class pyqode.core.widgets.TextCodeEdit(parent=None, server_script='/home/colin/pyqode/core/pyqode/core/backend/server.py', interpreter='/usr/bin/python3', args=None, create_default_actions=True, color_scheme='qt', reuse_backend=False)

Bases: pyqode.core.api.code_edit.CodeEdit

CodeEdit specialised for plain text.

Especially useful for long text file such as log files because it’s syntax highlighter does not do anything.

class TextSH(parent, color_scheme=None)

Bases: pyqode.core.api.syntax_highlighter.SyntaxHighlighter

Empty highlighter, does not do anything (very fast at loading very big files).

highlight_block(text, user_data)

Does nothing

TextCodeEdit.clone()
TextCodeEdit.mimetypes = ['text/x-plain', 'text/x-log', 'text/plain']