How to integrate QT User Interface with QGIS Python Plugin?

المشرف العام

Administrator
طاقم الإدارة
I created a very simple python program using GDAL to calculate the summary and reduction between two raster value like this :

import os from osgeo import ogr, gdal from gdalconst import * import numpy as np # input First Raster using GDAL filename1 = raw_input("Input Raster 1 : ") raster1 = gdal.Open( filename1, GA_ReadOnly ) Raster1_Value = np.array(raster1.GetRasterBand(1).ReadAsArray(), dtype ="float") # input Second Raster using GDAL filename2 = raw_input("Input Raster 2 : ") raster2 = gdal.Open( filename2, GA_ReadOnly ) Raster2_Value = np.array(raster2.GetRasterBand(1).ReadAsArray(), dtype ="float") # Raster Parameter geotransform_ = raster1.GetGeoTransform() Col = raster1.RasterXSize print Col Row = raster1.RasterYSize Origin_X = geotransform_[0] Origin_Y = geotransform_[3] Cell_Size = geotransform_[1] # Choose Operator Operation = { "+" : "plus" , "-" : "minus" } Op = raw_input("Input Operator :") Condition = Operation[Op] # Calculate if Condition == "plus" : Result = Raster1_Value + Raster2_Value elif Condition == "minus" : Result = Raster1_Value - Raster2_Value print Result # Output Result in .asc filename_ras = raw_input("Output Raster PATH :")+'.asc' out = open(filename_ras, 'wb+') out.write('ncols %i\n' % Col) out.write('nrows %i\n' % Row) out.write('xllcorner %f\n' % Origin_X) out.write('yllcorner %f\n' % (Origin_Y - (Cell_Size * Row)) ) out.write('cellsize %i\n' % Cell_Size) out.write('NODATA_value %i\n' % 0) np.savetxt(out, Result, fmt="%4i") The input will be refer to GDAL Raster data format and the output is ESRI ASCII data format.I've been make a QGIS plugin by using plugin builder and an user interface by using QT Designer, This is my UI i've been made so far :



so the UI python script will be like this :

from PyQt4 import QtCore, QtGuitry: _fromUtf8 = QtCore.QString.fromUtf8except AttributeError: def _fromUtf8(s): return stry: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding)except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig)class Ui_praticeDialogBase(object): def setupUi(self, praticeDialogBase): praticeDialogBase.setObjectName(_fromUtf8("praticeDialogBase")) praticeDialogBase.resize(384, 300) self.button_box = QtGui.QDialogButtonBox(praticeDialogBase) self.button_box.setGeometry(QtCore.QRect(30, 240, 341, 32)) self.button_box.setOrientation(QtCore.Qt.Horizontal) self.button_box.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok) self.button_box.setObjectName(_fromUtf8("button_box")) self.browse_raster1 = QtGui.QPushButton(praticeDialogBase) self.browse_raster1.setGeometry(QtCore.QRect(310, 40, 41, 23)) self.browse_raster1.setObjectName(_fromUtf8("browse_raster1")) self.PATH_RASTER1 = QtGui.QLineEdit(praticeDialogBase) self.PATH_RASTER1.setGeometry(QtCore.QRect(110, 40, 191, 20)) self.PATH_RASTER1.setObjectName(_fromUtf8("PATH_RASTER1")) self.PATH_RASTER2 = QtGui.QLineEdit(praticeDialogBase) self.PATH_RASTER2.setGeometry(QtCore.QRect(110, 70, 191, 20)) self.PATH_RASTER2.setObjectName(_fromUtf8("PATH_RASTER2")) self.browse_raster2 = QtGui.QPushButton(praticeDialogBase) self.browse_raster2.setGeometry(QtCore.QRect(310, 70, 41, 23)) self.browse_raster2.setObjectName(_fromUtf8("browse_raster2")) self.comboBox = QtGui.QComboBox(praticeDialogBase) self.comboBox.setGeometry(QtCore.QRect(110, 100, 131, 22)) self.comboBox.setObjectName(_fromUtf8("comboBox")) self.comboBox.addItem(_fromUtf8("")) self.comboBox.addItem(_fromUtf8("")) self.PATH_RESULT = QtGui.QLineEdit(praticeDialogBase) self.PATH_RESULT.setGeometry(QtCore.QRect(110, 140, 191, 20)) self.PATH_RESULT.setObjectName(_fromUtf8("PATH_RESULT")) self.browse_result = QtGui.QPushButton(praticeDialogBase) self.browse_result.setGeometry(QtCore.QRect(310, 140, 41, 23)) self.browse_result.setObjectName(_fromUtf8("browse_result")) self.label = QtGui.QLabel(praticeDialogBase) self.label.setGeometry(QtCore.QRect(30, 40, 46, 13)) self.label.setObjectName(_fromUtf8("label")) self.label_2 = QtGui.QLabel(praticeDialogBase) self.label_2.setGeometry(QtCore.QRect(30, 70, 46, 13)) self.label_2.setObjectName(_fromUtf8("label_2")) self.label_3 = QtGui.QLabel(praticeDialogBase) self.label_3.setGeometry(QtCore.QRect(30, 100, 61, 20)) self.label_3.setObjectName(_fromUtf8("label_3")) self.label_4 = QtGui.QLabel(praticeDialogBase) self.label_4.setGeometry(QtCore.QRect(30, 140, 46, 13)) self.label_4.setObjectName(_fromUtf8("label_4")) self.retranslateUi(praticeDialogBase) QtCore.QObject.connect(self.button_box, QtCore.SIGNAL(_fromUtf8("accepted()")), praticeDialogBase.accept) QtCore.QObject.connect(self.button_box, QtCore.SIGNAL(_fromUtf8("rejected()")), praticeDialogBase.reject) QtCore.QMetaObject.connectSlotsByName(praticeDialogBase) def retranslateUi(self, praticeDialogBase): praticeDialogBase.setWindowTitle(_translate("praticeDialogBase", "pratice", None)) self.browse_raster1.setText(_translate("praticeDialogBase", "...", None)) self.browse_raster2.setText(_translate("praticeDialogBase", "...", None)) self.comboBox.setItemText(0, _translate("praticeDialogBase", "Plus", None)) self.comboBox.setItemText(1, _translate("praticeDialogBase", "Minus", None)) self.browse_result.setText(_translate("praticeDialogBase", "...", None)) self.label.setText(_translate("praticeDialogBase", "Raster 1", None)) self.label_2.setText(_translate("praticeDialogBase", "Raster 2", None)) self.label_3.setText(_translate("praticeDialogBase", "Operation", None)) self.label_4.setText(_translate("praticeDialogBase", "Result", None))And this is my default script from plugin builder :

from PyQt4.QtCore import QSettings, QTranslator, qVersion, QCoreApplicationfrom PyQt4.QtGui import QAction, QIcon# Initialize Qt resources from file resources.pyimport resources_rc# Import the code for the dialogfrom pratice_dialog import praticeDialogimport os.pathclass pratice: """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', 'pratice_{}.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) # Create the dialog (after translation) and keep reference self.dlg = praticeDialog() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&pratice') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'pratice') self.toolbar.setObjectName(u'pratice') # noinspection PyMethodMayBeStatic def tr(self, message): """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, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('pratice', message) 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): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :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 by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: 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. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :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_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/pratice/icon.png' self.add_action( icon_path, text=self.tr(u'pratice'), 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'&pratice'), 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. passMy Question is, what should i write to integrate that User Interface script with my main program?

for example filename1 will be base on PATH_RASTER1 and browse_raster1 button to find the path location of my raster file. All that i've learned from many online literatures is that the main program must be write on run() function.

I know that my program is to simple and useless to be build as plugin but my purpose is to understand how PyQT works on QGIS plugin environment. All kind of helps, suggestion, and answer will be very appreciate...



أكثر...
 
أعلى