Class: QgsCodeEditor

A text editor based on QScintilla2.

Note

may not be available in Python bindings, depending on platform support

QgsCodeEditor

QgsCodeEditor

Class Hierarchy

Inheritance diagram of qgis.gui.QgsCodeEditor

Base classes

QsciScintilla

QsciScintillaBase

QAbstractScrollArea

QFrame

QWidget

QObject

QPaintDevice

Subclasses

QgsCodeEditorCSS

A CSS editor based on QScintilla2.

QgsCodeEditorExpression

A QGIS expression editor based on QScintilla2.

QgsCodeEditorHTML

A HTML editor based on QScintilla2.

QgsCodeEditorJavascript

A Javascript editor based on QScintilla2.

QgsCodeEditorJson

A JSON editor based on QScintilla2.

QgsCodeEditorPython

A Python editor based on QScintilla2.

QgsCodeEditorR

A R stats code editor based on QScintilla2.

QgsCodeEditorSQL

A SQL editor based on QScintilla2.

QgsCodeEditorShell

A shell script code editor based on QScintilla2.

Enums

Flag

Flags controlling behavior of code editor

MarginRole

Margin roles.

Mode

Code editor modes.

Methods

addWarning

Adds a warning message and indicator to the specified a lineNumber.

adjustScrollWidth

Adjust the width of the scroll bar to fit the content.

clearPersistentHistory

Clears the entire persistent history of commands run in the editor.

clearSessionHistory

Clears the history of commands run in the current session.

clearWarnings

Clears all warning messages from the editor.

editingTimeoutInterval

Returns the timeout (in milliseconds) threshold for the editingTimeout() signal to be emitted after an edit.

foldingVisible

Returns True if the folding controls are visible in the editor.

history

Returns the list of commands previously executed in the editor.

insertText

Insert text at cursor position, or replace any selected text if user has made a selection.

interpreter

Returns the attached code interpreter, or None if not set.

isCursorOnLastLine

Returns True if the cursor is on the last line of the document.

lexerColor

Returns the color to use in the lexer for the specified role.

lexerFont

Returns the font to use in the lexer.

lineNumbersVisible

Returns whether line numbers are visible in the editor.

linearPosition

Convenience function to return the cursor position as a linear index

marginVisible

Returns whether margins are in a visible state

mode

Returns the code editor mode.

reformatCode

Applies code reformatting to the editor.

removeHistoryCommand

Removes the command at the specified index from the history of the code editor.

runCommand

Runs a command in the editor.

runPostLexerConfigurationTasks

Performs tasks which must be run after a lexer has been set for the widget.

selectionEnd

Convenience function to return the end of the selection as a linear index Contrary to the getSelection method, this method returns the cursor position if no selection is made.

selectionStart

Convenience function to return the start of the selection as a linear index Contrary to the getSelection method, this method returns the cursor position if no selection is made.

setEditingTimeoutInterval

Sets the timeout (in milliseconds) threshold for the editingTimeout() signal to be emitted after an edit.

setFoldingVisible

Set whether the folding controls are visible in the editor.

setHistoryFilePath

Sets the file path to use for recording and retrieving previously executed commands.

setInterpreter

Sets an attached code interpreter for executing commands when the editor is in the QgsCodeEditor.Mode.CommandInput mode.

setLineNumbersVisible

Sets whether line numbers should be visible in the editor.

setLinearPosition

Convenience function to set the cursor position as a linear index

setLinearSelection

Convenience function to set the selection using linear indexes

setMarginVisible

Set margin visible state

setTitle

Set the widget title

showHistory

Shows the command history dialog.

showNextCommand

Shows the next command from the session in the editor.

showPreviousCommand

Shows the previous command from the session in the editor.

toggleLineComments

Toggles comment for selected lines with the given comment prefix.

updatePrompt

Triggers an update of the interactive prompt part of the editor.

updateSoftHistory

Updates the soft history by storing the current editor text in the history.

wrapPosition

Returns the linear position of the start of the last wrapped part for the specified line, or for the current line if line = -1 If wrapping is disabled, returns -1 instead

writeHistoryFile

Stores the commands executed in the editor to the persistent history file.

Virtual Methods

In PyQGIS, only methods marked as virtual can be safely overridden in a Python subclass of QgsCodeEditor. See the FAQ for more details.

checkSyntax

Applies syntax checking to the editor.

initializeLexer

Called when the dialect specific code lexer needs to be initialized (or reinitialized).

language

Returns the associated scripting language.

languageCapabilities

Returns the associated scripting language capabilities.

moveCursorToEnd

Moves the cursor to the end of the document and scrolls to ensure it is visible.

moveCursorToStart

Moves the cursor to the start of the document and scrolls to ensure it is visible.

populateContextMenu

Called when the context menu for the widget is about to be shown, after it has been fully populated with the standard actions created by the base class.

reformatCodeString

Applies code reformatting to a string and returns the result.

showMessage

Shows a user facing message (eg a warning message).

toggleComment

Toggle comment for the selected text.

Static Methods

color

Returns the color to use in the editor for the specified role.

defaultColor

Returns the default color for the specified role.

getMonospaceFont

Returns the monospaced font to use for code editors.

isFixedPitch

Returns True if a font is a fixed pitch font.

languageToString

Returns a user-friendly, translated name of the specified script language.

setColor

Sets the color to use in the editor for the specified role.

Signals

editingTimeout

Emitted when either:

helpRequested

Emitted when documentation was requested for the specified word.

persistentHistoryCleared

Emitted when the persistent history of commands run in the editor is cleared.

sessionHistoryCleared

Emitted when the history of commands run in the current session is cleared.

Attributes

SEARCH_RESULT_INDICATOR

Indicator index for search results

class qgis.gui.QgsCodeEditor[source]

Bases: QsciScintilla

__init__(parent: QWidget | None = None, title: str | None = '', folding: bool = False, margin: bool = False, flags: QgsCodeEditor.Flags | QgsCodeEditor.Flag = QgsCodeEditor.Flags(), mode: QgsCodeEditor.Mode = QgsCodeEditor.Mode.ScriptEditor)

Construct a new code editor.

Parameters:
  • parent (Optional[QWidget] = None) – The parent QWidget

  • title (Optional[str] = '') – The title to show in the code editor dialog

  • folding (bool = False) – False: Enable folding for code editor (deprecated, use flags instead)

  • margin (bool = False) – False: Enable margin for code editor (deprecated)

  • flags (Union[QgsCodeEditor.Flags, QgsCodeEditor.Flag] = QgsCodeEditor.Flags()) – flags controlling behavior of code editor (since QGIS 3.28)

  • mode (QgsCodeEditor.Mode = QgsCodeEditor.Mode.ScriptEditor) – code editor mode (since QGIS 3.30)

class Flag(*values)

Bases: IntEnum

Flags controlling behavior of code editor

Added in version 3.28.

  • CodeFolding: Indicates that code folding should be enabled for the editor

  • ImmediatelyUpdateHistory: Indicates that the history file should be immediately updated whenever a command is executed, instead of the default behavior of only writing the history on widget close

    Added in version 3.32.

CodeFolding = 1
ImmediatelyUpdateHistory = 2
class Flags
class Flags(f: QgsCodeEditor.Flags | QgsCodeEditor.Flag)
class Flags(a0: QgsCodeEditor.Flags)

Bases: object

class MarginRole(*values)

Bases: IntEnum

Margin roles.

This enum contains the roles which the different numbered margins are used for.

Added in version 3.16.

  • LineNumbers: Line numbers

  • ErrorIndicators: Error indicators

  • FoldingControls: Folding controls

class Mode(*values)

Bases: IntEnum

Code editor modes.

Added in version 3.30.

  • ScriptEditor: Standard mode, allows for display and edit of entire scripts

  • OutputDisplay: Read only mode for display of command outputs

  • CommandInput: Command input mode

CommandInput = 2
OutputDisplay = 1
ScriptEditor = 0
SEARCH_RESULT_INDICATOR: int = 34

Indicator index for search results

addWarning(self, lineNumber: int, warning: str | None)[source]

Adds a warning message and indicator to the specified a lineNumber.

See also

clearWarnings()

Added in version 3.16.

Parameters:
  • lineNumber (int)

  • warning (Optional[str])

adjustScrollWidth(self)[source]

Adjust the width of the scroll bar to fit the content.

Added in version 3.42.

virtual checkSyntax(self) bool[source]

Applies syntax checking to the editor.

This is only supported for editors which return the Qgis.ScriptLanguageCapability.CheckSyntax capability from languageCapabilities().

Added in version 3.32.

Return type:

bool

clearPersistentHistory(self)[source]

Clears the entire persistent history of commands run in the editor.

Note

Applies to code editors in the QgsCodeEditor.Mode.CommandInput mode only.

Added in version 3.30.

clearSessionHistory(self)[source]

Clears the history of commands run in the current session.

Note

Applies to code editors in the QgsCodeEditor.Mode.CommandInput mode only.

Added in version 3.30.

clearWarnings(self)[source]

Clears all warning messages from the editor.

See also

addWarning()

Added in version 3.16.

static color(role: QgsCodeEditorColorScheme.ColorRole) QColor[source]

Returns the color to use in the editor for the specified role.

This color will be the default theme color for the role, unless the user has manually selected a custom color scheme for the editor.

See also

setColor()

Added in version 3.16.

Parameters:

role (QgsCodeEditorColorScheme.ColorRole)

Return type:

QColor

static defaultColor(role: QgsCodeEditorColorScheme.ColorRole, theme: str | None = '') QColor[source]

Returns the default color for the specified role.

The optional theme argument can be used to specify a color theme. A blank theme indicates the default color scheme.

Available themes are stored in QgsCodeEditorColorSchemeRegistry, and can be retrieved via QgsGui.codeEditorColorSchemeRegistry().

Added in version 3.16.

Parameters:
Return type:

QColor

signal editingTimeout[source]

Emitted when either:

  1. 1 second has elapsed since the last text change in the widget

  2. or, immediately after the widget has lost focus after its text was changed.

Added in version 3.42.

editingTimeoutInterval(self) int[source]

Returns the timeout (in milliseconds) threshold for the editingTimeout() signal to be emitted after an edit.

Added in version 3.42.

Return type:

int

foldingVisible(self) bool[source]

Returns True if the folding controls are visible in the editor.

Return type:

bool

static getMonospaceFont() QFont[source]

Returns the monospaced font to use for code editors.

Added in version 3.16.

Return type:

QFont

signal helpRequested(word: str)[source]

Emitted when documentation was requested for the specified word.

Added in version 3.42.

Parameters:

word (str)

history(self) List[str][source]

Returns the list of commands previously executed in the editor.

Note

Applies to code editors in the QgsCodeEditor.Mode.CommandInput mode only.

Added in version 3.30.

Return type:

List[str]

virtual initializeLexer(self)[source]

Called when the dialect specific code lexer needs to be initialized (or reinitialized).

The default implementation does nothing.

Added in version 3.16.

insertText(self, text: str | None)[source]

Insert text at cursor position, or replace any selected text if user has made a selection.

Parameters:

text (Optional[str]) – The text to be inserted

interpreter(self) QgsCodeInterpreter | None[source]

Returns the attached code interpreter, or None if not set.

See also

setInterpreter()

Added in version 3.30.

Return type:

Optional[QgsCodeInterpreter]

isCursorOnLastLine(self) bool[source]

Returns True if the cursor is on the last line of the document.

Added in version 3.28.

Return type:

bool

static isFixedPitch(font: QFont) bool[source]

Returns True if a font is a fixed pitch font.

Parameters:

font (QFont)

Return type:

bool

virtual language(self) Qgis.ScriptLanguage[source]

Returns the associated scripting language.

Added in version 3.30.

Return type:

Qgis.ScriptLanguage

virtual languageCapabilities(self) Qgis.ScriptLanguageCapabilities[source]

Returns the associated scripting language capabilities.

Added in version 3.32.

Return type:

Qgis.ScriptLanguageCapabilities

static languageToString(language: Qgis.ScriptLanguage) str[source]

Returns a user-friendly, translated name of the specified script language.

Added in version 3.30.

Parameters:

language (Qgis.ScriptLanguage)

Return type:

str

lexerColor(self, role: QgsCodeEditorColorScheme.ColorRole) QColor[source]

Returns the color to use in the lexer for the specified role.

Added in version 3.16.

Parameters:

role (QgsCodeEditorColorScheme.ColorRole)

Return type:

QColor

lexerFont(self) QFont[source]

Returns the font to use in the lexer.

Added in version 3.16.

Return type:

QFont

lineNumbersVisible(self) bool[source]

Returns whether line numbers are visible in the editor.

Added in version 3.16.

Return type:

bool

linearPosition(self) int[source]

Convenience function to return the cursor position as a linear index

Added in version 3.36.

Return type:

int

marginVisible(self) bool[source]

Returns whether margins are in a visible state

Deprecated since version 3.40: Use base class methods for individual margins instead, or lineNumbersVisible().

Return type:

bool

mode(self) QgsCodeEditor.Mode[source]

Returns the code editor mode.

Added in version 3.30.

Return type:

QgsCodeEditor.Mode

virtual moveCursorToEnd(self)[source]

Moves the cursor to the end of the document and scrolls to ensure it is visible.

Added in version 3.28.

virtual moveCursorToStart(self)[source]

Moves the cursor to the start of the document and scrolls to ensure it is visible.

Added in version 3.28.

signal persistentHistoryCleared[source]

Emitted when the persistent history of commands run in the editor is cleared.

Added in version 3.30.

virtual populateContextMenu(self, menu: QMenu | None)[source]

Called when the context menu for the widget is about to be shown, after it has been fully populated with the standard actions created by the base class.

This method provides an opportunity for subclasses to add additional non-standard actions to the context menu.

Added in version 3.30.

Parameters:

menu (Optional[QMenu])

reformatCode(self)[source]

Applies code reformatting to the editor.

This is only supported for editors which return the Qgis.ScriptLanguageCapability.Reformat capability from languageCapabilities().

Added in version 3.32.

virtual reformatCodeString(self, string: str | None) str[source]

Applies code reformatting to a string and returns the result.

This is only supported for editors which return the Qgis.ScriptLanguageCapability.Reformat capability from languageCapabilities().

Added in version 3.32.

Parameters:

string (Optional[str])

Return type:

str

removeHistoryCommand(self, index: int)[source]

Removes the command at the specified index from the history of the code editor.

Added in version 3.30.

Parameters:

index (int)

runCommand(self, command: str | None, skipHistory: bool = False)[source]

Runs a command in the editor.

An interpreter() must be set.

Since QGIS 3.32, if skipHistory is True then the command will not be automatically added to the widget’s history.

Added in version 3.30.

Parameters:
  • command (Optional[str])

  • skipHistory (bool = False)

runPostLexerConfigurationTasks(self)[source]

Performs tasks which must be run after a lexer has been set for the widget.

Added in version 3.16.

selectionEnd(self) int[source]

Convenience function to return the end of the selection as a linear index Contrary to the getSelection method, this method returns the cursor position if no selection is made.

Added in version 3.36.

Return type:

int

selectionStart(self) int[source]

Convenience function to return the start of the selection as a linear index Contrary to the getSelection method, this method returns the cursor position if no selection is made.

Added in version 3.36.

Return type:

int

signal sessionHistoryCleared[source]

Emitted when the history of commands run in the current session is cleared.

Added in version 3.30.

static setColor(role: QgsCodeEditorColorScheme.ColorRole, color: QColor | Qt.GlobalColor)[source]

Sets the color to use in the editor for the specified role.

This color will be stored as the new default color for the role, to be used for all code editors.

Set color to an invalid QColor in order to clear the stored color value and reset it to the default color.

See also

color()

Added in version 3.16.

Parameters:
setEditingTimeoutInterval(self, timeout: int)[source]

Sets the timeout (in milliseconds) threshold for the editingTimeout() signal to be emitted after an edit.

See also

editingTimeout()

Added in version 3.42.

Parameters:

timeout (int)

setFoldingVisible(self, folding: bool)[source]

Set whether the folding controls are visible in the editor.

See also

foldingVisible()

Parameters:

folding (bool)

setHistoryFilePath(self, path: str | None)[source]

Sets the file path to use for recording and retrieving previously executed commands.

Note

Applies to code editors in the QgsCodeEditor.Mode.CommandInput mode only.

Added in version 3.30.

Parameters:

path (Optional[str])

setInterpreter(self, newInterpreter: QgsCodeInterpreter | None)[source]

Sets an attached code interpreter for executing commands when the editor is in the QgsCodeEditor.Mode.CommandInput mode.

See also

interpreter()

Added in version 3.30.

Parameters:

newInterpreter (Optional[QgsCodeInterpreter])

setLineNumbersVisible(self, visible: bool)[source]

Sets whether line numbers should be visible in the editor.

Defaults to False.

Added in version 3.16.

Parameters:

visible (bool)

setLinearPosition(self, position: int)[source]

Convenience function to set the cursor position as a linear index

Added in version 3.36.

Parameters:

position (int)

setLinearSelection(self, start: int, end: int)[source]

Convenience function to set the selection using linear indexes

Added in version 3.36.

Parameters:
  • start (int)

  • end (int)

setMarginVisible(self, margin: bool)[source]

Set margin visible state

Parameters:

margin (bool) – Set margin in the editor

Deprecated since version 3.40: Use base class methods for individual margins instead, or setLineNumbersVisible().

setTitle(self, title: str | None)[source]

Set the widget title

Parameters:

title (Optional[str]) – widget title

showHistory(self)[source]

Shows the command history dialog.

Note

Applies to code editors in the QgsCodeEditor.Mode.CommandInput mode only.

Added in version 3.30.

virtual showMessage(self, title: str | None, message: str | None, level: Qgis.MessageLevel)[source]

Shows a user facing message (eg a warning message).

The default implementation uses QMessageBox.

Added in version 3.32.

Parameters:
showNextCommand(self)[source]

Shows the next command from the session in the editor.

Note

Applies to code editors in the QgsCodeEditor.Mode.CommandInput mode only.

Added in version 3.30.

showPreviousCommand(self)[source]

Shows the previous command from the session in the editor.

Note

Applies to code editors in the QgsCodeEditor.Mode.CommandInput mode only.

Added in version 3.30.

virtual toggleComment(self)[source]

Toggle comment for the selected text.

This is only supported for editors which return the Qgis.ScriptLanguageCapability.ToggleComment capability from languageCapabilities().

Added in version 3.32.

toggleLineComments(self, commentPrefix: str | None)[source]

Toggles comment for selected lines with the given comment prefix.

Added in version 3.44.

Parameters:

commentPrefix (Optional[str])

updatePrompt(self)[source]

Triggers an update of the interactive prompt part of the editor.

Note

Applies to code editors in the QgsCodeEditor.Mode.CommandInput mode only.

Added in version 3.30.

updateSoftHistory(self)[source]

Updates the soft history by storing the current editor text in the history.

Added in version 3.30.

wrapPosition(self, line: int = -1) int[source]

Returns the linear position of the start of the last wrapped part for the specified line, or for the current line if line = -1 If wrapping is disabled, returns -1 instead

Added in version 3.40.

Parameters:

line (int = -1)

Return type:

int

writeHistoryFile(self) bool[source]

Stores the commands executed in the editor to the persistent history file.

Added in version 3.30.

Return type:

bool