Skip to content

Main

QGIS CPLUS Plugin Implementation.

Source code in src/cplus_plugin/main.py
def __init__(self, iface):
    self.iface = iface
    self.plugin_dir = os.path.dirname(__file__)
    locale = QgsSettings().value("locale/userLocale")[0:2]
    locale_path = os.path.join(self.plugin_dir, "i18n", "CPLUS{}.qm".format(locale))

    if os.path.exists(locale_path):
        self.translator = QTranslator()
        self.translator.load(locale_path)
        QCoreApplication.installTranslator(self.translator)

    # Declare instance attributes
    self.actions = []
    self.pluginIsActive = False

    self.cplus_action = None

    self.menu = QMenu("&CPLUS")
    self.menu.setIcon(QIcon(ICON_PATH))

    self.raster_menu = self.iface.rasterMenu()
    self.raster_menu.addMenu(self.menu)

    self.toolbar = self.iface.addToolBar("Open CPLUS")
    self.toolbar.setObjectName("CPLUS")
    self.toolButton = QToolButton()
    self.toolButton.setMenu(QMenu())
    self.toolButton.setCheckable(True)
    self.toolButton.setPopupMode(QToolButton.MenuButtonPopup)
    self.toolBtnAction = self.toolbar.addWidget(self.toolButton)
    self.actions.append(self.toolBtnAction)

    create_priority_layers()

    initialize_model_settings()

    # Initialize default report settings
    initialize_report_settings()

    initialize_api_url()

    self.main_widget = QgisCplusMain(
        iface=self.iface, parent=self.iface.mainWindow()
    )
    self.main_widget.visibilityChanged.connect(
        self.on_dock_widget_visibility_changed
    )

    # Create options factories
    self.cplus_options_factory = CplusOptionsFactory(main_widget=self.main_widget)
    self.reports_options_factory = ReportOptionsFactory()
    self.log_options_factory = LogOptionsFactory()

    self.options_factory = None

add_action

add_action(icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_web_menu=True, add_to_toolbar=True, set_as_default_action=False, status_tip=None, whats_this=None, parent=None)

Add a toolbar icon to the toolbar.

Parameters:

Name Type Description Default
icon_path str

Path to the icon for this action

required
text str

Text that should be shown in menu items for this action

required
callback function

Function to be called when the action is triggered

required
enabled_flag bool

A flag indicating if the action should be enabled

True
add_to_menu bool

Flag indicating whether the action should also be added to the menu

True
add_to_web_menu bool

Flag indicating whether the action should also be added to the web menu

True
add_to_toolbar bool

Flag indicating whether the action should also be added to the toolbar

True
set_as_default_action bool

Flag indicating whether the action is the default action

False
status_tip str

Optional text to show in a popup when mouse pointer hovers over the action

None
parent QWidget

Parent widget for the new action

None
whats_this str

Optional text to show in the status bar when the mouse pointer hovers over the action

None

Returns:

Type Description
QAction

The action that was created

Source code in src/cplus_plugin/main.py
def add_action(
    self,
    icon_path,
    text,
    callback,
    enabled_flag=True,
    add_to_menu=True,
    add_to_web_menu=True,
    add_to_toolbar=True,
    set_as_default_action=False,
    status_tip=None,
    whats_this=None,
    parent=None,
):
    """Add a toolbar icon to the toolbar.

    :param icon_path: Path to the icon for this action
    :type icon_path: str

    :param text: Text that should be shown in menu items for this action
    :type text: str

    :param callback: Function to be called when the action is triggered
    :type callback: function

    :param enabled_flag: A flag indicating if the action should be enabled
    :type enabled_flag: bool

    :param add_to_menu: Flag indicating whether the action should also be added to the menu
    :type add_to_menu: bool

    :param add_to_web_menu: Flag indicating whether the action should also be added to the web menu
    :type add_to_web_menu: bool

    :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar
    :type add_to_toolbar: bool

    :param set_as_default_action: Flag indicating whether the action is the default action
    :type set_as_default_action: bool

    :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action
    :type status_tip: str

    :param parent: Parent widget for the new action
    :type parent: QWidget

    :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action
    :type whats_this: str

    :returns: The action that was created
    :rtype: QAction
    """

    icon = QIcon(icon_path)
    action = QAction(icon, text, parent)
    action.triggered.connect(callback)
    action.setEnabled(enabled_flag)

    if status_tip is not None:
        action.setStatusTip(status_tip)

    if whats_this is not None:
        action.setWhatsThis(whats_this)

    if add_to_menu:
        self.menu.addAction(action)

    # If we want to read this
    # if add_to_web_menu:
    #     self.iface.addPluginToWebMenu(self.menu, action)

    if add_to_toolbar:
        self.toolButton.menu().addAction(action)

        if set_as_default_action:
            self.toolButton.setDefaultAction(action)

    self.actions.append(action)

    return action

create_dock_widget_action

create_dock_widget_action()

Create the action corresponding to the main dock widget.

Source code in src/cplus_plugin/main.py
def create_dock_widget_action(self):
    """Create the action corresponding to the main dock widget."""
    self.cplus_action = self.main_widget.toggleViewAction()
    self.cplus_action.setIcon(QIcon(ICON_PATH))
    self.cplus_action.setText(self.tr("CPLUS"))
    self.menu.addAction(self.cplus_action)
    self.toolButton.menu().addAction(self.cplus_action)
    self.toolButton.setDefaultAction(self.cplus_action)

    self.actions.append(self.cplus_action)

initGui

initGui()

Create the menu entries and toolbar icons inside the QGIS GUI.

Source code in src/cplus_plugin/main.py
def initGui(self):
    """Create the menu entries and toolbar icons inside the QGIS GUI."""
    # Create main dock widget action
    self.create_dock_widget_action()

    self.add_action(
        os.path.join(os.path.dirname(__file__), "icons", "settings.svg"),
        text=self.tr("Settings"),
        callback=self.run_settings,
        parent=self.iface.mainWindow(),
        status_tip=self.tr("CPLUS Settings"),
    )

    self.add_action(
        os.path.join(
            os.path.dirname(__file__), "icons", "mActionHelpContents_green.svg"
        ),
        text=self.tr("Help"),
        callback=self.open_help,
        parent=self.iface.mainWindow(),
        status_tip=self.tr("CPLUS Help"),
    )

    self.add_action(
        os.path.join(os.path.dirname(__file__), "icons", "info_green.svg"),
        text=self.tr("About"),
        callback=self.open_about,
        parent=self.iface.mainWindow(),
        status_tip=self.tr("CPLUS About"),
    )

    # Register plugin options factories
    self.iface.registerOptionsWidgetFactory(self.cplus_options_factory)
    self.iface.registerOptionsWidgetFactory(self.reports_options_factory)

    # Register custom layout items
    self.register_layout_items()

    # Register custom report variables when a layout is opened
    self.iface.layoutDesignerOpened.connect(self.on_layout_designer_opened)

    # Install report font
    self.install_report_font()

install_report_font

install_report_font()

Checks if the report font exists and install it.

Source code in src/cplus_plugin/main.py
def install_report_font(self):
    """Checks if the report font exists and install it."""
    font_exists = contains_font_family(REPORT_FONT_NAME)
    if not font_exists:
        log(message=self.tr("Installing report font..."))
        status = install_font(REPORT_FONT_NAME.lower())
        if status:
            log(message=self.tr("Report font successfully installed."))
        else:
            log(message=self.tr("Report font could not be installed."), info=False)
    else:
        log(message="Report font exists.")

onClosePlugin

onClosePlugin()

Cleanup necessary items here when plugin widget is closed.

Source code in src/cplus_plugin/main.py
def onClosePlugin(self):
    """Cleanup necessary items here when plugin widget is closed."""
    self.pluginIsActive = False

on_dock_widget_visibility_changed

on_dock_widget_visibility_changed(visible)

Slot raised when the visibility of the main docket widget changes.

Parameters:

Name Type Description Default
visible bool

True if the dock widget is visible, else False.

required
Source code in src/cplus_plugin/main.py
def on_dock_widget_visibility_changed(self, visible: bool):
    """Slot raised when the visibility of the main docket widget changes.

    :param visible: True if the dock widget is visible, else False.
    :type visible: bool
    """
    # Set default dock position on first time load.
    if visible:
        app_window = self.iface.mainWindow()
        dock_area = app_window.dockWidgetArea(self.main_widget)

        if dock_area == Qt.NoDockWidgetArea and not self.main_widget.isFloating():
            self.iface.addDockWidget(Qt.RightDockWidgetArea, self.main_widget)
            self.main_widget.show()

on_layout_designer_opened

on_layout_designer_opened(designer)

Register custom report variables in a print layout only.

Source code in src/cplus_plugin/main.py
def on_layout_designer_opened(self, designer: QgsLayoutDesignerInterface):
    """Register custom report variables in a print layout only."""
    layout_type = designer.masterLayout().layoutType()
    if layout_type == QgsMasterLayoutInterface.PrintLayout:
        layout = designer.layout()
        report_manager.register_variables(layout)

open_about

open_about()

Opens the about documentation for the plugin in a browser

Source code in src/cplus_plugin/main.py
def open_about(self):
    """Opens the about documentation for the plugin in a browser"""
    open_documentation(ABOUT_DOCUMENTATION_SITE)

open_help

open_help()

Opens documentation home page for the plugin in a browser

Source code in src/cplus_plugin/main.py
def open_help(self):
    """Opens documentation home page for the plugin in a browser"""
    open_documentation(DOCUMENTATION_SITE)

register_layout_items

register_layout_items()

Register custom layout items.

Source code in src/cplus_plugin/main.py
def register_layout_items(self):
    """Register custom layout items."""
    # Register map layout item
    QgsApplication.layoutItemRegistry().addLayoutItemType(
        CplusMapRepeatItemLayoutItemMetadata()
    )

    # Register map GUI metadata
    item_gui_registry = QgsGui.layoutItemGuiRegistry()
    map_item_gui_metadata = CplusMapLayoutItemGuiMetadata()
    item_gui_registry.addLayoutItemGuiMetadata(map_item_gui_metadata)

run

run()

Creates the main widget for the plugin.

Source code in src/cplus_plugin/main.py
def run(self):
    """Creates the main widget for the plugin."""
    if self.main_widget is None:
        self.main_widget = QgisCplusMain(
            iface=self.iface, parent=self.iface.mainWindow()
        )
        self.create_dock_widget_action()

    self.iface.addDockWidget(Qt.RightDockWidgetArea, self.main_widget)
    self.main_widget.show()

    if not self.pluginIsActive:
        self.pluginIsActive = True

run_settings

run_settings()

Options the CPLUS settings in the QGIS options dialog.

Source code in src/cplus_plugin/main.py
def run_settings(self):
    """Options the CPLUS settings in the QGIS options dialog."""
    self.iface.showOptionsDialog(currentPage=OPTIONS_TITLE)

tr

tr(message)

Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject.

Parameters:

Name Type Description Default
message str

String for translation

required

Returns:

Type Description
QString

Translated version of the message

Source code in src/cplus_plugin/main.py
def tr(self, message) -> str:
    """Get the translation for a string using Qt translation API.
    We implement this ourselves since we do not inherit QObject.

    :param message: String for translation
    :type message: str

    :returns: Translated version of the message
    :rtype: QString
    """
    # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
    return QCoreApplication.translate("CPLUS", message)

unload

unload()

Removes the plugin menu item and icon from QGIS GUI.

Source code in src/cplus_plugin/main.py
def unload(self):
    """Removes the plugin menu item and icon from QGIS GUI."""
    try:
        for action in self.actions:
            self.iface.removePluginMenu(self.tr("&CPLUS"), action)
            self.iface.removePluginWebMenu(self.tr("&CPLUS"), action)
            self.iface.removeToolBarIcon(action)

        # Unregister plugin options factories
        self.iface.unregisterOptionsWidgetFactory(self.cplus_options_factory)
        self.iface.unregisterOptionsWidgetFactory(self.reports_options_factory)
        self.iface.unregisterOptionsWidgetFactory(self.log_options_factory)

    except Exception as e:
        log(str(e), info=False)

Last update: October 2, 2024
Back to top