[GIS] How to open the “File Browse” dialog from PyQGIS plugin code

pyqgispythonqgisqgis-plugins

I am in the process of developing a plugin for QGIS using Python. Note that this is my first plugin, so the query could be quite basic…

I have used this Digital Geography link to create the basic plugin, and (quite surprisingly found it easy) created the plugin files.

I am stuck at a very basic concept. Previously, while using Python IDLE, using

QtCore.QObject.connect(self.Input, QtCore.SIGNAL("clicked()"), self.OpenBrowse)

to signal a click and writing a function OpenBrowse

    def OpenBrowse(self):
        self.Input_TB.setText(filename1)

I was able to open the Windows File Browse window on click and set the File location to an adjoining text box.

How do I do this while developing the plugin in the Python file that is created by Plugin Builder.? I am very confused about where should the code be written? Because if I place the 'clicked()' actions, etc. in the Python file generated from the UI file, it is not recognizing the variables as they are not global (obviously).

I am using QGIS 2.4, on a Windows 32-bit system.

Best Answer

Let us imagine your UI file name is MyDialogFile.py. Then,

from PyQt4.QtGui import QFileDialog
from MyDialogFile import MyDialog 

def InitGui(self):
    #other stuff....
    self.dialog = MyDialog()    

def OpenBrowse(self):        
    filename1 = QFileDialog.getOpenFileName()
    self.dialog.Input_TB.setText(filename1)
Related Question