3

I am new to PyQGIS and PyQT programming.

I have built a small QGIS plugin, which uses the NetworkX library to do some processing of shapefiles. The form executes it's business logic correctly, but if I close the form, then reopen it, all of the input fields are populated with the same values as when I last ran it.

The form also has a "Reset" button, which will clear the input fields (a couple of QLineEdit widgets and a QPlainText widget) while the form is open. When I close the plugin form and reopen it after clicking the "Reset" button, the form reopens with empty fields.

I've spent a significant amount of time researching this, but I can't seem to find the answer. I have added (what I think are) the relevent code snippets here.

From the main dialog script (this is also where the primary business logic is executed, with methods such as calc_subnetwork_id)

import os
import time
from PyQt4 import QtGui, uic
from PyQt4.QtCore import *
import network as network
import lib.symbolizer as symbol
from qgis.core import *
from qgis.gui import *
import qgis.utils


# constants
HELP_URL = "#"
FORM_CLASS, _ = uic.loadUiType(os.path.join(
    os.path.dirname(__file__), 'build_network_dialog_base.ui'))


class GNATDialog(QtGui.QDialog, FORM_CLASS):
    def __init__(self, parent=None):
        """Constructor."""
        super(GNATDialog, self).__init__(parent)
        # Set up the user interface from Designer.
        # After setupUI you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect
        self.setupUi(self)

        # Map functions to click events
        self.btnBrowseInput.clicked.connect(self.file_browser)
        self.btnBrowseOutput.clicked.connect(self.folder_browser)
        self.btnRun.clicked.connect(self.calc_subnetwork_id)

        self.formFields = [self.txtInputNetwork, self.txtOutputFolder, self.txtResults]
        self.btnReset.clicked.connect(self.reset_form)

        self.btnExportToTxt.clicked.connect(self.export_to_txt)
        self.btnDisplayResults.clicked.connect(self.display_results_lyr)
        self.btnClose.clicked.connect(self.close)

    def reset_form(self):
        for field in self.formFields:
            field.clear()
        del self.input_shp
        del self.output_folder

# additional business logic modules excluded

From the main plugin script

from PyQt4.QtCore import QSettings, QTranslator, qVersion, QCoreApplication
from PyQt4.QtGui import QAction, QIcon
# Initialize Qt resources from file resources.py
import resources
# Import the code for the dialog
from build_network_dialog import GNATDialog
import os.path

class GNAT:
    """QGIS Plugin Implementation."""

    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'GNAT_{}.qm'.format(locale))

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

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)


        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&GNAT')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'GNAT')
        self.toolbar.setObjectName(u'GNAT')

    def add_action(
        self,
        icon_path,
        text,
        callback,
        enabled_flag=True,
        add_to_menu=True,
        add_to_toolbar=True,
        status_tip=None,
        whats_this=None,
        parent=None):

        # Create the dialog (after translation) and keep reference
        self.dlg = GNATDialog()

        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_toolbar:
            self.toolbar.addAction(action)

        if add_to_menu:
            self.iface.addPluginToMenu(
                self.menu,
                action)

        self.actions.append(action)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/GNAT/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u'Build Network'),
            callback=self.run,
            parent=self.iface.mainWindow())


    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&GNaT'),
                action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar


    def run(self):
        """Run method that performs all the real work"""
        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            pass
2

You can call the function reset_form on closeEvent of the form.

Add this code to GNATDialog class:

def closeEvent(self, event):
    self.reset_form()
  • Thanks for the response. So I assumed I needed to change the 'Close' button to connect to this new closeEvent method. Like this: – tinyplanet00 Jun 9 '17 at 15:15
  • This an Event methode that will run when you close the form... so if you want to reset anything when you close the form you should add it inside this methode :) – Chiller Jun 9 '17 at 15:19
  • My comment was cutoff. Sorry for the confusion. That worked! Thanks! – tinyplanet00 Jun 9 '17 at 15:42
  • You are welcome! glad it helped :) – Chiller Jun 9 '17 at 16:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.