def _show_mashups(self, mashups):
        self.switch_btn_apis.hide()
        self.switch_btn_mashups.hide()
        self.recommendLabel.hide()

        row = 0
        model = QStandardItemModel(len(mashups), 4)
        model.setColumnCount(4)
        for mashup in mashups:
            model.setData(model.index(row, 0), QVariant(get_mashup_name(mashup)))
            model.setData(model.index(row, 1), QVariant(mashup['title']))
            model.setData(model.index(row, 2), QVariant(mashup['self']))
            model.setData(model.index(row, 3), QVariant(mashup['description']))
            
            row += 1
        
        model.setHeaderData(0, Qt.Horizontal, QVariant("Workflow"))
        model.setHeaderData(1, Qt.Horizontal, QVariant("Short Description"))
        model.setHeaderData(2, Qt.Horizontal, QVariant("Provider"))
        model.setHeaderData(3, Qt.Horizontal, QVariant("Detailed Info"))

#        model.setHeaderData(0, Qt.Horizontal, QVariant("Info"))
#        model.setHeaderData(1, Qt.Horizontal, QVariant("Title"))
#        model.setHeaderData(2, Qt.Horizontal, QVariant("self"))
#        model.setHeaderData(3, Qt.Horizontal, QVariant("Description"))

        self.table.setModel(model)
        self.table.resizeColumnsToContents()
        self.add_btn.show()
    def _show_related_mashups(self):
        self.switch_btn_apis.hide()
        self.switch_btn_mashups.hide()
        self.recommendLabel.hide()
        
        apis = []
        objs = []
        for mashup in self.related_mashups:
            apis.extend(mashup["related_mashups"])

        for api in apis:
            objs.append(api)
            mashups = self.data_source.mashups_by_api(api)
            objs.extend(mashups)

        row = 0
        model = QStandardItemModel(len(objs), 4)
        model.setColumnCount(4)
        for obj in objs:
            if obj.get('protocols'):
                model.setData(model.index(row, 0), QVariant(get_api_name(obj)))
                model.setData(model.index(row, 1), QVariant(obj['protocols']))
                model.setData(model.index(row, 2), QVariant(obj['provider']))
            else:
                model.setData(model.index(row, 3), QVariant(get_mashup_name(obj)))
            row += 1

        model.setHeaderData(0, Qt.Horizontal, QVariant("API"))
        model.setHeaderData(1, Qt.Horizontal, QVariant("Protocols"))
        model.setHeaderData(2, Qt.Horizontal, QVariant("Provider"))
        model.setHeaderData(3, Qt.Horizontal, QVariant("Mashup"))
        self.table.setModel(model)
        self.table.resizeColumnsToContents()
        self.switch_btn_apis.show()
    def init_view(self):
        self.table = QTableView(self)
        self.table.setMinimumSize(600, 600)

        manager = core.packagemanager.get_package_manager()
        package = manager.get_package("edu.cmu.sv.components", "1.0.0")
        modules = package.descriptors
        apis = []
        self.modules_to_upgrade = []
        for module in modules.values():
            api = self.data_source.api_by_id(module.name)
            if ("1.0" != module.version):
                apis.append(api)
                self.modules_to_upgrade.append(module)

        table_model = QStandardItemModel(len(apis), 4)
        row = 0
        for api in apis:
            table_model.setData(table_model.index(row, 0), QVariant(api['id']))
            table_model.setData(table_model.index(row, 1), QVariant(api['category']))
            table_model.setData(table_model.index(row, 2), QVariant(api['version']))
            table_model.setData(table_model.index(row, 3), QVariant(api['description']))
            row += 1

        table_model.setHeaderData(0, Qt.Horizontal, QVariant("Link"))
        table_model.setHeaderData(1, Qt.Horizontal, QVariant("Category"))
        table_model.setHeaderData(2, Qt.Horizontal, QVariant("Version"))
        table_model.setHeaderData(3, Qt.Horizontal, QVariant("Description"))
        self.table.setModel(table_model)


        btn = QPushButton(self)
        btn.clicked.connect(self.upgrade_api)
        btn.setText("Upgrade")
        btn.move(600, 500)
    def _show_apis(self, apis, recommend=False):
        self.switch_btn_apis.hide()
        self.switch_btn_mashups.hide()
        self.recommendLabel.hide()

        row = 0
        model = QStandardItemModel(len(apis), 4)
        model.setColumnCount(4)
        for api in apis:
            model.setData(model.index(row, 0), QVariant(get_api_name(api)))
            model.setData(model.index(row, 1), QVariant(api['protocols']))
            model.setData(model.index(row, 2), QVariant(api['provider']))
            model.setData(model.index(row, 3), QVariant(api['version']))
            row += 1

        model.setHeaderData(0, Qt.Horizontal, QVariant("Module"))
        model.setHeaderData(1, Qt.Horizontal, QVariant("Protocol"))
        model.setHeaderData(2, Qt.Horizontal, QVariant("Provider"))
        model.setHeaderData(3, Qt.Horizontal, QVariant("Version"))

#        model.setHeaderData(0, Qt.Horizontal, QVariant("API"))
#        model.setHeaderData(1, Qt.Horizontal, QVariant("Protocols"))
#        model.setHeaderData(2, Qt.Horizontal, QVariant("Provider"))
#        model.setHeaderData(3, Qt.Horizontal, QVariant("Version"))

        self.table.setModel(model)
        self.table.resizeColumnsToContents()
        
        if recommend:
            self.recommendLabel.show()
        
        self.add_btn.show()
    def _show_related_apis(self):
        self.switch_btn_apis.hide()
        self.switch_btn_mashups.hide()
        self.recommendLabel.hide()
        
        row = 0
        objs = []
        for mashup in self.related_mashups:
            objs.append(mashup)
            for api in mashup["related_mashups"]:
                objs.append(api)
        #Combining similarity and related.
        similar_apis = self.data_source.search_api_similarity(self.highlighted_api)
        #return str(mashup['id'])[(len("http://www.programmableweb.com/mashup/")):]
        objs.append({'id': "http://www.programmableweb.com/mashup/Using-Similarity-Metric"})
        objs.extend(similar_apis)
        #Combining similarity and related.

        model = QStandardItemModel(len(objs), 5)
        for obj in objs:
            if obj.get('protocols'):
                model.setData(model.index(row, 1), QVariant(get_api_name(obj)))
                model.setData(model.index(row, 2), QVariant(obj['protocols']))
                model.setData(model.index(row, 3), QVariant(obj['provider']))
                model.setData(model.index(row, 4), QVariant(obj['version']))
            else:
                model.setData(model.index(row, 0), QVariant(get_mashup_name(obj)))
            row += 1

        model.setHeaderData(0, Qt.Horizontal, QVariant("Mashup"))
        model.setHeaderData(1, Qt.Horizontal, QVariant("API"))
        model.setHeaderData(2, Qt.Horizontal, QVariant("Protocols"))
        model.setHeaderData(3, Qt.Horizontal, QVariant("Provider"))
        model.setHeaderData(4, Qt.Horizontal, QVariant("Version"))

        self.table.setModel(model)
        self.switch_btn_mashups.show()
예제 #6
0
파일: tree.py 프로젝트: vertrex/DFF
    def setData(self, index, value, role):
        """
    \reimp

    Set the data which value is `value` at index `index` with role `role`.

    \return `True` if no error occured, `False` otherwise.
    """
        if self.ch == True:
            if role == Qt.CheckStateRole:
                ret = QStandardItemModel.setData(self, index, value, role)
                if ret == False:
                    return False
                data = QStandardItemModel.data(self, index, Qt.UserRole + 1)
                if not data.isValid():
                    return False
                self.emit(SIGNAL("stateChanged"), index)
        return True
예제 #7
0
파일: vfsitemmodel.py 프로젝트: halbbob/dff
  def setData(self, index, value, role):
    """
    \reimp

    Set the data which value is `value` at index `index` with role `role`.

    \return `True` if no error occured, `False` otherwise.
    """
    if self.ch == True:
      if role == Qt.CheckStateRole:
        ret =  QStandardItemModel.setData(self, index, value, role)
        if ret == False:
          return False
        data = QStandardItemModel.data(self, index, Qt.UserRole + 1)
        if not data.isValid():
          return False
        self.emit(SIGNAL("stateChanged"), index)
    return True #return true if ok 	
예제 #8
0
파일: SearchResult.py 프로젝트: einaru/luma
class ResultView(QWidget):
    """This class represent a search result view.
    """

    def __init__(self, filter='', attributes=[], resultlist=[], parent=None):
        """Initialize a result view for the `SearchPlugin`.

        :param filter: the filter applied on the search
        :type filter: string
        :param attributes: a list containing the attributes used in the
         search operation. Usually extracted from the `filter`.
        :type attributes: list
        :param resultlist: a list of `SmartDataObject` from the search
         operation.
        :type resultlist: list
        :param parent: the parent for this widget.
        :type parent: QWidget
        """
        super(ResultView, self).__init__(parent)
        self.setObjectName('ResultView')
        self.layout = QtGui.QVBoxLayout(self)

        # Only display the no-result message if resultlist is empty
        if len(resultlist) == 0:
            self.retranslate(all=False)
            self.onNoResult()
            return

        # The proxy model is used for sort and filter support
        self.proxymodel = QSortFilterProxyModel(self)
        self.proxymodel.setDynamicSortFilter(True)

        self.headerdata = ['dn']
        self.headerdata.extend(attributes)
        self.resultdata = resultlist

        # FIXME: should we create a custom item model ?
        self.model = QStandardItemModel(0, len(self.headerdata), parent=self)
        #self.model = ResultItemModel(self)
        #self.model = ResultItemModel(self.headerdata, self.resultdata, self)
        self.proxymodel.setSourceModel(self.model)

        self.resultview = QTreeView(self)
        self.resultview.setUniformRowHeights(True)
        self.resultview.setRootIsDecorated(False)
        self.resultview.setAlternatingRowColors(True)
        self.resultview.setSortingEnabled(True)

        self.resultview.setModel(self.proxymodel)

        # For right-click context menu
        self.resultview.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.resultview.setSelectionMode(QAbstractItemView.ExtendedSelection)

        self.layout.addWidget(self.resultview)
        # The filter box enables the user to filter the returned search
        # results. It becomes accessible with Ctrl-F (QKeySequence.Find)
        self.filterBox = ResultFilterWidget(self.headerdata, parent=self)
        self.filterBox.setVisible(False)

        self.layout.addWidget(self.filterBox)

        # We need to call the retranslate method before populating
        # the result data
        self.retranslate()
        #self.model.populateHeader(self.headerdata)
        #self.model.populateModel(self.resultdata)
        self.setHeaderData(self.headerdata)
        self.setResultData(self.resultdata)
        self.resultview.resizeColumnToContents(0)
        self.__createContextMenu()
        self.__connectSlots()

    def __connectSlots(self):
        """Connect signal and slots.
        """
        self.resultview.customContextMenuRequested.connect(
            self.onContextMenuRequested)
        self.filterBox.inputEdit.textChanged['QString'].connect(
            self.onFilterInputChanged)
        self.filterBox.columnBox.currentIndexChanged[int].connect(
            self.onFilterColumnChanged)

    def __getVSpacer(self):
        return QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding,
                                 QtGui.QSizePolicy.Minimum)

    def __createContextMenu(self):
        """Display the context menu.
        """
        self.contextMenu = QtGui.QMenu()
        self.contextMenuView = QtGui.QAction(self)
        self.contextMenuDelete = QtGui.QAction(self)
        self.contextMenuExport = QtGui.QAction(self)
        self.contextMenu.addAction(self.contextMenuView)
        self.contextMenu.addAction(self.contextMenuDelete)
        self.contextMenu.addAction(self.contextMenuExport)

        # Connect the context menu actions to the correct slots
        self.contextMenuView.triggered.connect(self.onViewItemsSelected)
        self.contextMenuDelete.triggered.connect(self.onDeleteItemsSelected)
        self.contextMenuExport.triggered.connect(self.onExportItemsSelected)

    def onNoResult(self):
        """Adds a styled *no result* message to the main layout.
        """
        font = QtGui.QFont()
        font.setBold(True)
        sadface = QtGui.QLabel(self)
        sadface.setPixmap(pixmapFromTheme('face-sad', ':/icons/48/face-sad'))
        noresult = QtGui.QLabel(self)
        noresult.setText(self.str_NO_RESULT)
        noresult.setFont(font)
        hlayout = QtGui.QHBoxLayout()
        hlayout.addItem(self.__getVSpacer())
        hlayout.addWidget(sadface)
        hlayout.addWidget(noresult)
        hlayout.addItem(self.__getVSpacer())

        self.layout.addLayout(hlayout)

    def setHeaderData(self, data=[]):
        """Populates the ``resultview`` model with header data.

        Parameters:

        - `data`: a list with header items. Usually this is the
          attributelist from the LDAP search.
        """
        i = 0
        for header in data:
            self.model.setHeaderData(i, QtCore.Qt.Horizontal, header)
            i += 1

    def setResultData(self, data=[]):
        """Populates the ``resultview`` model with result data.

        Parameters:

        - `data`: a list containing the SmartDataObjects representing
          items in the LDAP search result.
        """
        row = 0
        for obj in data:
            self.model.insertRow(row)
            col = 0
            for attr in self.headerdata:
                if self.isDistinguishedName(attr):
                    modelData = obj.getPrettyDN()
                elif self.isObjectClass(attr):
                    modelData = ','.join(obj.getObjectClasses())
                elif obj.hasAttribute(attr):
                    if obj.isAttributeBinary(attr):
                        modelData = self.str_BINARY_DATA
                    else:
                        modelData = ','.join(obj.getAttributeValueList(attr))

                self.model.setData(self.model.index(row, col), modelData)
                col += 1

            row += 1

    def isDistinguishedName(self, attr):
        """Returns ``True`` if `attr` is a distinguished name,
        ``False`` otherwise.

        Parameters:

        - `attr`: the LDAP string attribute value to check.
        """
        return attr.lower() == 'dn'

    def isObjectClass(self, attr):
        """Returns ``True`` if `attr` is an object class, ``False``
        otherwise.

        Parameters:

        - `attr`: the LDAP string attribute value to check.
        """
        return attr.lower() == 'objectclass'

    def onContextMenuRequested(self, point):
        """Display the context menu
        """

        # FIXME: In order to be able to export, delete and view search
        # result entries. We should make use of the various dialogs in
        # the Browser plugin. Unitl we have refactored the design in a
        # way that allow us to use these without accessing the browser
        # modules, we simple don't provide these options yet.
        return

        self.selection = self.resultview.selectedIndexes()

        deleteSupport = True
        exportSupport = True

        rowsselected = len(self.selection) / len(self.headerdata)

        if not rowsselected > 0:
            self.contextMenu.setEnabled(False)
            self.contextMenu.exec_(self.resultview.mapToGlobal(point))
            return

        self.contextMenu.setEnabled(True)
        # Look over at Browser plugin for implementation of
        # multiselect and operation support validation
        print rowsselected

        self.contextMenuView.setEnabled(True)
        if rowsselected == 1:
            self.contextMenuView.setText(self.str_VIEW_ITEM)
        else:
            self.contextMenuView.setText(self.str_VIEW_ITEMS)

        if deleteSupport:
            self.contextMenuDelete.setEnabled(True)
            if rowsselected == 1:
                self.contextMenuDelete.setText(self.str_DELETE_ITEM)
            else:
                self.contextMenuDelete.setText(self.str_DELETE_ITEMS)

        if exportSupport:
            self.contextMenuExport.setEnabled(True)
            if rowsselected == 1:
                self.contextMenuExport.setText(self.str_EXPORT_ITEM)
            else:
                self.contextMenuExport.setText(self.str_EXPORT_ITEMS)

        # Finally we execute the context menu
        self.contextMenu.exec_(self.resultview.mapToGlobal(point))

    def onViewItemsSelected(self):
        """Slot for the *view* context menu action.
        """
        raise NotImplementedError(
            'Need to implement a proper model for this to be supported')

    def onDeleteItemsSelected(self):
        """Slot for the *delete* context menu action.
        """
        msg = 'Delete from the Search Plugin is not implemented jet.'
        dialog = DeleteDialog(self, msg)
        dialog.setDeleteItems([])
        dialog.exec_()

    def onExportItemsSelected(self):
        """Slot for the 'export' context menu action.
        """
        msg = 'Export from the Search Plugin is not implemented jet.'
        dialog = ExportDialog(self, msg)
        # Only for proof of concept
        dialog.setExportData([])
        dialog.exec_()

    def onFilterBoxVisibilityChanged(self, visible):
        """Slot for the QKeySequence.Find.

        - `visible`: a boolean value indicating wether or not to toggle
          the filter box widget visibility on or off.
        """
        if visible:
            self.filterBox.setVisible(True)
            self.filterBox.inputEdit.setFocus()
        else:
            # I belive it's common practise to clear the filter when
            # the filter box is closed. This is at least the way the
            # filter boxes works for most webbrowsers.
            self.filterBox.inputEdit.clear()
            self.filterBox.setVisible(False)
            self.resultview.setFocus()

    def onFilterInputChanged(self, filter=''):
        """Slot for the filter input in the result filter widget.

        We get the selected syntax from the syntax combobox
        """
        # The PyQt4 QVariant is causing some problems here, when we try
        # to use the <combobox>.itemData directly, even though the data
        # holds valid QRexExp.PatternSyntax values.
        # We therefore need to explicitly make the QVariant and integer.
        i = self.filterBox.syntaxBox.currentIndex()
        syntaxIndex = self.filterBox.syntaxBox.itemData(i).toInt()[0]
        syntax = QtCore.QRegExp.PatternSyntax(syntaxIndex)
        # As of now we do filtering in a case insensitive way, until we
        # come up with a way to introduce case sensitivity selection in a
        # UI inexpensive way. We want to keep the filter widget as clean
        # and simple as possible.
        regex = QtCore.QRegExp(filter, QtCore.Qt.CaseInsensitive, syntax)
        self.proxymodel.setFilterRegExp(regex)

    def onFilterColumnChanged(self, index):
        """Slot for the column combobox in the filter box widget.
        """
        self.proxymodel.setFilterKeyColumn(index)

    def retranslate(self, all=True):
        """For dynamic translation support.
        """
        self.str_VIEW_ITEM = QtGui.QApplication.translate(
            'ResultView', 'View Item')
        self.str_VIEW_ITEMS = QtGui.QApplication.translate(
            'ResultView', 'View Items')
        self.str_DELETE_ITEM = QtGui.QApplication.translate(
            'ResultView', 'Delete Item')
        self.str_DELETE_ITEMS = QtGui.QApplication.translate(
            'ResultView', 'Delete Items')
        self.str_EXPORT_ITEM = QtGui.QApplication.translate(
            'ResultView', 'Export Item')
        self.str_EXPORT_ITEMS = QtGui.QApplication.translate(
            'ResultView', 'Export Items')
        self.str_NO_RESULT = QtGui.QApplication.translate(
            'ResultView', 'Sorry, no result to display!')
        self.str_BINARY_DATA = QtGui.QApplication.translate(
            'ResultView', 'Binary Data')
        if all:
            self.filterBox.retranslate()
예제 #9
0
class Dialog_report(QDialog, Ui_Dialog_report):
    """
    Class documentation goes here.
    """
    def __init__(self, parent = None):
        """
        Constructor
        """
        QDialog.__init__(self, parent)
        self.setupUi(self)
        
                
        #construct Customer list class
        self.clist = Customer_list()        
                
        #construct accounting class
        self.caccount = Dfile()
        
        #construct customer price class
        self.cprice = Customer_price()
        
        #construct standard table
        self.tablemodel = QStandardItemModel(31,  len(PRODUCT_NAME) )
        self.setTableheader()

        #save customer list int
        self.list_customer = self.clist.readCompany()
        self.setCombo( 1,  self.list_customer )  
  
    def setMode(self, str_mode):
        
        if str_mode == 'init':
            self.clearAllshow()
            
    def setCombo(self, comboselect, m_str):
        """
        set combo box
        """
        if comboselect == 1:
            for i in m_str:
                self.comboBox_name.addItem(i)
        elif comboselect == 2:
            self.comboBox_date.clear()
            for i in m_str:                
                self.comboBox_date.addItem(i)
                
    
    def clearAllshow(self):
        
        #clear all spin box 
        self.setAllspin(0)
        
        #clear table
        self.clearTableview()
        
    def setAllspin(self,  int_value):
         self.spinBox_1.setValue(int_value)
         self.spinBox_2.setValue(int_value)
         self.spinBox_3.setValue(int_value)
         self.spinBox_4.setValue(int_value)
         self.spinBox_5.setValue(int_value)
         self.spinBox_6.setValue(int_value)
         self.spinBox_7.setValue(int_value)
         self.spinBox_8.setValue(int_value)
         self.spinBox_9.setValue(int_value)
         self.spinBox_10.setValue(int_value)
         self.spinBox_11.setValue(int_value)
         self.spinBox_12.setValue(int_value)
         self.spinBox_13.setValue(int_value)
         self.spinBox_14.setValue(int_value)
         self.spinBox_15.setValue(int_value)
         self.spinBox_16.setValue(int_value)
         self.spinBox_17.setValue(int_value)
         self.spinBox_18.setValue(int_value)
         self.spinBox_19.setValue(int_value)
         self.spinBox_19.setValue(0)
         
    def setTableheader(self):
                
        #set header data
        self.tablemodel.setHeaderData(0, Qt.Horizontal, PRODUCT_NAME[0] )
        self.tablemodel.setHeaderData(1, Qt.Horizontal, PRODUCT_NAME[1] )
        self.tablemodel.setHeaderData(2, Qt.Horizontal, PRODUCT_NAME[2] )
        self.tablemodel.setHeaderData(3, Qt.Horizontal, PRODUCT_NAME[3] )
        self.tablemodel.setHeaderData(4, Qt.Horizontal, PRODUCT_NAME[4] )
        self.tablemodel.setHeaderData(5, Qt.Horizontal, PRODUCT_NAME[5] )
        
    def setTableview(self,  dlist_data ):
        """
        set data into tableview model
        """
        #show data
        row = 0
        for i in dlist_data:
            self.tablemodel.setData(self.tablemodel.index(row, 0), QVariant(i[0]))
            self.tablemodel.setData(self.tablemodel.index(row, 1), QVariant(i[1]))
            self.tablemodel.setData(self.tablemodel.index(row, 2), QVariant(i[2]))
            self.tablemodel.setData(self.tablemodel.index(row, 3), QVariant(i[3]))
            self.tablemodel.setData(self.tablemodel.index(row, 4), QVariant(i[4]))
            self.tablemodel.setData(self.tablemodel.index(row, 5), QVariant(i[5]))
            row += 1
        
        #set table into tableview
        self.tableView.setModel(self.tablemodel)
        
    def clearTableview(self):
        """
        clear table
        """
        #show data
        row = 0
        i = [0, 0, 0, 0, 0, 0]
        for row in range(31):
            self.tablemodel.setData(self.tablemodel.index(row, 0), QVariant(i[0]))
            self.tablemodel.setData(self.tablemodel.index(row, 1), QVariant(i[1]))
            self.tablemodel.setData(self.tablemodel.index(row, 2), QVariant(i[2]))
            self.tablemodel.setData(self.tablemodel.index(row, 3), QVariant(i[3]))
            self.tablemodel.setData(self.tablemodel.index(row, 4), QVariant(i[4]))
            self.tablemodel.setData(self.tablemodel.index(row, 5), QVariant(i[5]))
        
        #set table into tableview
        self.tableView.setModel(self.tablemodel)
    
    @pyqtSignature("QString")
    def on_comboBox_name_currentIndexChanged(self, p0):
        """
        when name index change, set combo date
        """
        #set to initial status
        self.setMode('init')
        
        #read combo text and dict value
        self.str_customercombo = str( self.comboBox_name.currentText().toUtf8() )
        self.i_customercombo = self.clist.readCvalue( self.str_customercombo )
        
        #read all guest accounting data
        self.list_date = self.caccount.listDatafile( self.i_customercombo )
        
        self.setCombo(2, self.list_date)
    
    @pyqtSignature("QString")
    def on_comboBox_date_currentIndexChanged(self, p0):
        """
        search price data and load accounting into table
        """
        
        self.str_filename = str( self.comboBox_date.currentText() )
        
        if self.str_filename != '':
            self.str_datecombo = self.str_filename[3:9]
        
            #get price version
            self.i_priceversion = self.cprice.selectPrice( self.i_customercombo, self.str_datecombo )
            
            #get price dict
            dict_price = self.cprice.readPrice( self.i_customercombo, self.i_priceversion )
            self.list_price = self.cprice.getClist( dict_price )
            
            #show price 
            self.setPricespin( self.list_price )
            
            #show table
            self.caccount.open_dfile( self.str_filename )
            self.table_data = self.caccount.read_alldfile()
            self.setTableview( self.table_data )
            
            #calculate and show single amount
            self.eachamount = self.sumEachamount( self.table_data )
            self.setEachamount( self.eachamount )
            
            #calculate single price amount
            self.eachpriceamount = [ self.eachamount[i]*self.list_price[i] for i in range(len(PRODUCT_NAME))]
            self.setEachpriceamount( self.eachpriceamount )
            
            #show in total income
            self.spinBox_19.setValue( sum(self.eachpriceamount ) )
            
            
    def setPricespin( self,  list ):
        
         self.spinBox_1.setValue( list[0] )
         self.spinBox_2.setValue( list[1] )
         self.spinBox_3.setValue( list[2] )
         self.spinBox_4.setValue( list[3] )
         self.spinBox_5.setValue( list[4] )
         self.spinBox_6.setValue( list[5] )
    
    def setEachamount( self,  list ):
        
         self.spinBox_7.setValue( list[0] )
         self.spinBox_8.setValue( list[1] )
         self.spinBox_9.setValue( list[2] )
         self.spinBox_10.setValue( list[3] )
         self.spinBox_11.setValue( list[4] )
         self.spinBox_12.setValue( list[5] )
         
    def setEachpriceamount(self,  list ):
        
         self.spinBox_13.setValue( list[0] )
         self.spinBox_14.setValue( list[1] )
         self.spinBox_15.setValue( list[2] )
         self.spinBox_16.setValue( list[3] )
         self.spinBox_17.setValue( list[4] )
         self.spinBox_18.setValue( list[5] )
    
    #sum each item total amount
    def sumEachamount(self,  duallist ):
        
        eachamount = [0, 0, 0, 0, 0, 0]
        count = 0
        for i in duallist:
            for j in i:
                eachamount[count] += j
                count += 1
            count = 0
            
        return eachamount
예제 #10
0
     QTreeView
  
if __name__ == "__main__":
  
    app = QApplication(sys.argv)
  
    phonebook = {"Arthur": "Camelot",
                 "Monty": "The Circus",
                 "David": "Oslo"}
  
    model = QStandardItemModel(6, 4)
    row = 0
  
    for name, address in phonebook.items():
  
        model.setData(model.index(row, 0), QVariant(name))
        model.setData(model.index(row, 1), QVariant(address))
        font = QFont()
        font.setPointSize(16)
        font.setBold(True)
        model.setData(model.index(row, 0), QVariant(font), Qt.FontRole)
        model.setData(model.index(row, 1), QVariant(font), Qt.FontRole)
        row += 1
  
    model.setHeaderData(0, Qt.Horizontal, QVariant("Name"))
    model.setHeaderData(1, Qt.Horizontal, QVariant("Address"))
  
    tree = QTreeView()
    tree.setModel(model)
    tree.show()
  
예제 #11
0
    def _show_related_apis(self):
        self.switch_btn_apis.hide()
        self.switch_btn_mashups.hide()
        self.recommendLabel.hide()
        
        row = 0
        objs = []
        for mashup in self.related_mashups:
            objs.append(mashup)
            for api in mashup["related_mashups"]:
                objs.append(api)
        #Combining similarity and related.
        similar_apis = self.data_source.search_api_similarity(self.highlighted_api)
        #return str(mashup['id'])[(len("http://www.programmableweb.com/mashup/")):]
        objs.append({'id': "http://www.programmableweb.com/mashup/Using-Similarity-Metric"})
        objs.extend(similar_apis)
        #Combining similarity and related.

        #http://localhost:9000/getReputation/John%20Lions
        model = QStandardItemModel(len(objs), 6)
        for obj in objs:
            if obj.get('protocols'):
                model.setData(model.index(row, 1), QVariant(get_api_name(obj)))
                model.setData(model.index(row, 2), QVariant(obj['protocols']))
                model.setData(model.index(row, 3), QVariant(obj['provider']))
                model.setData(model.index(row, 4), QVariant(obj['version']))
                trust  = requests.get('http://localhost:9000/getReputation/Luis Ramos').content
                #model.setData(model.index(row, 5), QVariant(str(random.random())))
                model.setData(model.index(row, 5), QVariant(trust))
            else:
                model.setData(model.index(row, 0), QVariant(get_mashup_name(obj)))
            row += 1

        model.setHeaderData(0, Qt.Horizontal, QVariant("Mashup"))
        model.setHeaderData(1, Qt.Horizontal, QVariant("API"))
        model.setHeaderData(2, Qt.Horizontal, QVariant("Protocols"))
        model.setHeaderData(3, Qt.Horizontal, QVariant("Provider"))
        model.setHeaderData(4, Qt.Horizontal, QVariant("Version"))
        model.setHeaderData(5, Qt.Horizontal, QVariant("Trust"))

        self.table.setModel(model)
        self.table.resizeColumnsToContents()
        self.switch_btn_mashups.show()
예제 #12
0
class TreeLegend(QObject):

    toggledLegend = pyqtSignal(list)
    descriptionLegend = pyqtSignal(str)

    def __init__(self, treeView):
        def init():
            self.setHeader()
            self.tree.setModel(self.model)
            self.headerView.setMovable(False)
            self.headerView.setClickable(True)
            self.tree.setSelectionMode(0)  # no selection

        super(TreeLegend, self).__init__()
        self.tree = treeView
        #
        self.hasConnect = self.layer = self.legendItems = None
        self.visibleItems = []
        self.model = QStandardItemModel(0, 1)
        self.headerView = self.tree.header()
        #
        init()
        self._connect()

    def __del__(self):
        if self.hasConnect:
            self._connect(False)
        self.model.clear()
        self.layer.legendChanged.disconnect(self.updateLegendItems)

    def _connect(self, isConnect=True):
        ss = [{
            'signal': self.tree.clicked,
            'slot': self.toggleItem
        }, {
            'signal': self.headerView.sectionClicked,
            'slot': self.toggleHeader
        }, {
            'signal': self.headerView.sectionDoubleClicked,
            'slot': self.emitDescription
        }]
        if isConnect:
            self.hasConnect = True
            for item in ss:
                item['signal'].connect(item['slot'])
        else:
            self.hasConnect = False
            for item in ss:
                item['signal'].disconnect(item['slot'])

    def setHeader(self, data=None):
        if data is None:
            self.model.clear()
            nameHeader = 'Select Raster Layer(Palette)'
            font = QFont()
            font.setStrikeOut(False)
            headerModel = QStandardItem(nameHeader)
            headerModel.setData(font, Qt.FontRole)
            tip = "Raster with Palette(Single Band)"
            headerModel.setData(tip, Qt.ToolTipRole)
            self.model.setHorizontalHeaderItem(0, headerModel)
        else:
            headerModel = self.model.horizontalHeaderItem(0)
            label = "%s" % data['name']
            formatMgs = "Layer: %s\nSource: %s\nNumber Class: %d\nWidth: %d\nHeight: %d\nRes.X: %f\nRes.Y: %f\n\n* Double click copy to Clipboard"
            dataMsg = (data['name'], data['source'], data['num_class'],
                       data['width'], data['height'], data['resX'],
                       data['resY'])
            tip = formatMgs % dataMsg
            headerModel.setData(data, Qt.UserRole)
            headerModel.setData(label, Qt.DisplayRole)
            headerModel.setData(tip, Qt.ToolTipRole)

    def setLayer(self, layer):
        self.legendItems = layer.legendSymbologyItems()
        total = len(self.legendItems)
        self.visibleItems = [True for x in range(total)]
        data = {
            'name': layer.name(),
            'source': layer.source(),
            'num_class': total,
            'width': layer.width(),
            'height': layer.height(),
            'resX': layer.rasterUnitsPerPixelX(),
            'resY': layer.rasterUnitsPerPixelY()
        }
        self.setHeader(data)
        #
        if not self.layer is None:
            self.layer.legendChanged.disconnect(self.updateLegendItems)
        layer.legendChanged.connect(self.updateLegendItems)
        self.layer = layer

    def setLegend(self, values):
        def setHeader():
            headerModel = self.model.horizontalHeaderItem(0)
            data = headerModel.data(Qt.UserRole)
            data['num_class'] = len(values)
            self.setHeader(data)

        def createItem(item):
            (pixel, total) = item
            (legend, color) = self.legendItems[pixel]
            name = "[%d] %s" % (pixel, legend)
            tip = "Value pixel: %d\nTotal pixels: %d\nClass name: %s" % (
                pixel, total, legend)
            pix = QPixmap(16, 16)
            pix.fill(color)
            font.setStrikeOut(not self.visibleItems[pixel])
            #
            itemModel = QStandardItem(QIcon(pix), name)
            itemModel.setEditable(False)
            itemModel.setData(font, Qt.FontRole)
            itemModel.setData(tip, Qt.ToolTipRole)
            itemModel.setData(item, Qt.UserRole)
            #
            return itemModel

        setHeader()
        self.model.removeRows(0, self.model.rowCount())
        #
        font = QFont()
        for item in values:
            self.model.appendRow(createItem(item))

    def setEnabled(self, isEnable=True):
        self._connect(isEnable)
        self.tree.setEnabled(isEnable)

    def getLayerName(self):
        headerModel = self.model.horizontalHeaderItem(0)
        return headerModel.data(Qt.UserRole)['name']

    @pyqtSlot()
    def updateLegendItems(self):
        self.legendItems = self.layer.legendSymbologyItems()
        # Refresh legend
        rows = self.model.rowCount()
        row = 0
        while row < rows:
            index = self.model.index(row, 0)
            (pixel, total) = self.model.data(index, Qt.UserRole)
            (legend, color) = self.legendItems[pixel]
            pix = QPixmap(16, 16)
            pix.fill(color)
            self.model.setData(index, QIcon(pix), Qt.DecorationRole)
            row += 1

    @pyqtSlot('QModelIndex')
    def toggleItem(self, index):
        font = index.data(Qt.FontRole)
        strike = not font.strikeOut()
        font.setStrikeOut(strike)
        self.model.setData(index, font, Qt.FontRole)
        #
        (pixel, total) = index.data(Qt.UserRole)
        visible = not strike
        self.visibleItems[pixel] = visible
        #
        self.toggledLegend.emit(self.visibleItems)

    @pyqtSlot(int)
    def toggleHeader(self, logical):
        rowCount = self.model.rowCount()
        if rowCount == 0:
            return

        header = self.model.horizontalHeaderItem(0)
        font = header.data(Qt.FontRole)
        strike = not font.strikeOut()
        font.setStrikeOut(strike)
        header.setData(font, Qt.FontRole)
        #
        items = []
        row = 0
        while row < self.model.rowCount():
            index = self.model.index(row, 0)
            self.model.setData(index, font, Qt.FontRole)
            items.append(index.data(Qt.UserRole))
            row += 1

        visible = not strike
        for item in items:
            (pixel, total) = item
            self.visibleItems[pixel] = visible
        #
        self.toggledLegend.emit(self.visibleItems)

    @pyqtSlot(int)
    def emitDescription(self):
        def getDescription():
            data = self.model.horizontalHeaderItem(0).data(Qt.UserRole)
            formatMgs = "Layer: %s\nSource: %s\nNumber Class: %d\nWidth: %d\nHeight: %d\nRes.X: %f\nRes.Y: %f"
            dataMsg = (data['name'], data['source'], data['num_class'],
                       data['width'], data['height'], data['resX'],
                       data['resY'])
            descHeader = formatMgs % dataMsg
            #
            descItems = ["Value pixel;Total pixels;Class name"]
            rows = self.model.rowCount()
            row = 0
            while row < rows:
                index = self.model.index(row, 0)
                (pixel, total) = self.model.data(index, Qt.UserRole)
                (legend, color) = self.legendItems[pixel]
                descItems.append("%d;%d;%s" % (pixel, total, legend))
                row += 1

            return "%s\n\n%s" % (descHeader, '\n'.join(descItems))

        if self.model.rowCount() > 0:
            self.descriptionLegend.emit(getDescription())
예제 #13
0
class ResultView(QWidget):
    """This class represent a search result view.
    """
    def __init__(self, filter='', attributes=[], resultlist=[], parent=None):
        """Initialize a result view for the `SearchPlugin`.

        :param filter: the filter applied on the search
        :type filter: string
        :param attributes: a list containing the attributes used in the
         search operation. Usually extracted from the `filter`.
        :type attributes: list
        :param resultlist: a list of `SmartDataObject` from the search
         operation.
        :type resultlist: list
        :param parent: the parent for this widget.
        :type parent: QWidget
        """
        super(ResultView, self).__init__(parent)
        self.setObjectName('ResultView')
        self.layout = QtGui.QVBoxLayout(self)

        # Only display the no-result message if resultlist is empty
        if len(resultlist) == 0:
            self.retranslate(all=False)
            self.onNoResult()
            return

        # The proxy model is used for sort and filter support
        self.proxymodel = QSortFilterProxyModel(self)
        self.proxymodel.setDynamicSortFilter(True)

        self.headerdata = ['dn']
        self.headerdata.extend(attributes)
        self.resultdata = resultlist

        # FIXME: should we create a custom item model ?
        self.model = QStandardItemModel(0, len(self.headerdata), parent=self)
        #self.model = ResultItemModel(self)
        #self.model = ResultItemModel(self.headerdata, self.resultdata, self)
        self.proxymodel.setSourceModel(self.model)

        self.resultview = QTreeView(self)
        self.resultview.setUniformRowHeights(True)
        self.resultview.setRootIsDecorated(False)
        self.resultview.setAlternatingRowColors(True)
        self.resultview.setSortingEnabled(True)

        self.resultview.setModel(self.proxymodel)

        # For right-click context menu
        self.resultview.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.resultview.setSelectionMode(QAbstractItemView.ExtendedSelection)

        self.layout.addWidget(self.resultview)
        # The filter box enables the user to filter the returned search
        # results. It becomes accessible with Ctrl-F (QKeySequence.Find)
        self.filterBox = ResultFilterWidget(self.headerdata, parent=self)
        self.filterBox.setVisible(False)

        self.layout.addWidget(self.filterBox)

        # We need to call the retranslate method before populating
        # the result data
        self.retranslate()
        #self.model.populateHeader(self.headerdata)
        #self.model.populateModel(self.resultdata)
        self.setHeaderData(self.headerdata)
        self.setResultData(self.resultdata)
        self.resultview.resizeColumnToContents(0)
        self.__createContextMenu()
        self.__connectSlots()

    def __connectSlots(self):
        """Connect signal and slots.
        """
        self.resultview.customContextMenuRequested.connect(
            self.onContextMenuRequested)
        self.filterBox.inputEdit.textChanged['QString'].connect(
            self.onFilterInputChanged)
        self.filterBox.columnBox.currentIndexChanged[int].connect(
            self.onFilterColumnChanged)

    def __getVSpacer(self):
        return QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding,
                                 QtGui.QSizePolicy.Minimum)

    def __createContextMenu(self):
        """Display the context menu.
        """
        self.contextMenu = QtGui.QMenu()
        self.contextMenuView = QtGui.QAction(self)
        self.contextMenuDelete = QtGui.QAction(self)
        self.contextMenuExport = QtGui.QAction(self)
        self.contextMenu.addAction(self.contextMenuView)
        self.contextMenu.addAction(self.contextMenuDelete)
        self.contextMenu.addAction(self.contextMenuExport)

        # Connect the context menu actions to the correct slots
        self.contextMenuView.triggered.connect(self.onViewItemsSelected)
        self.contextMenuDelete.triggered.connect(self.onDeleteItemsSelected)
        self.contextMenuExport.triggered.connect(self.onExportItemsSelected)

    def onNoResult(self):
        """Adds a styled *no result* message to the main layout.
        """
        font = QtGui.QFont()
        font.setBold(True)
        sadface = QtGui.QLabel(self)
        sadface.setPixmap(pixmapFromTheme('face-sad', ':/icons/48/face-sad'))
        noresult = QtGui.QLabel(self)
        noresult.setText(self.str_NO_RESULT)
        noresult.setFont(font)
        hlayout = QtGui.QHBoxLayout()
        hlayout.addItem(self.__getVSpacer())
        hlayout.addWidget(sadface)
        hlayout.addWidget(noresult)
        hlayout.addItem(self.__getVSpacer())

        self.layout.addLayout(hlayout)

    def setHeaderData(self, data=[]):
        """Populates the ``resultview`` model with header data.

        Parameters:

        - `data`: a list with header items. Usually this is the
          attributelist from the LDAP search.
        """
        i = 0
        for header in data:
            self.model.setHeaderData(i, QtCore.Qt.Horizontal, header)
            i += 1

    def setResultData(self, data=[]):
        """Populates the ``resultview`` model with result data.

        Parameters:

        - `data`: a list containing the SmartDataObjects representing
          items in the LDAP search result.
        """
        row = 0
        for obj in data:
            self.model.insertRow(row)
            col = 0
            for attr in self.headerdata:
                if self.isDistinguishedName(attr):
                    modelData = obj.getPrettyDN()
                elif self.isObjectClass(attr):
                    modelData = ','.join(obj.getObjectClasses())
                elif obj.hasAttribute(attr):
                    if obj.isAttributeBinary(attr):
                        modelData = self.str_BINARY_DATA
                    else:
                        modelData = ','.join(obj.getAttributeValueList(attr))

                self.model.setData(self.model.index(row, col), modelData)
                col += 1

            row += 1

    def isDistinguishedName(self, attr):
        """Returns ``True`` if `attr` is a distinguished name,
        ``False`` otherwise.

        Parameters:

        - `attr`: the LDAP string attribute value to check.
        """
        return attr.lower() == 'dn'

    def isObjectClass(self, attr):
        """Returns ``True`` if `attr` is an object class, ``False``
        otherwise.

        Parameters:

        - `attr`: the LDAP string attribute value to check.
        """
        return attr.lower() == 'objectclass'

    def onContextMenuRequested(self, point):
        """Display the context menu
        """

        # FIXME: In order to be able to export, delete and view search
        # result entries. We should make use of the various dialogs in
        # the Browser plugin. Unitl we have refactored the design in a
        # way that allow us to use these without accessing the browser
        # modules, we simple don't provide these options yet.
        return

        self.selection = self.resultview.selectedIndexes()

        deleteSupport = True
        exportSupport = True

        rowsselected = len(self.selection) / len(self.headerdata)

        if not rowsselected > 0:
            self.contextMenu.setEnabled(False)
            self.contextMenu.exec_(self.resultview.mapToGlobal(point))
            return

        self.contextMenu.setEnabled(True)
        # Look over at Browser plugin for implementation of
        # multiselect and operation support validation
        print rowsselected

        self.contextMenuView.setEnabled(True)
        if rowsselected == 1:
            self.contextMenuView.setText(self.str_VIEW_ITEM)
        else:
            self.contextMenuView.setText(self.str_VIEW_ITEMS)

        if deleteSupport:
            self.contextMenuDelete.setEnabled(True)
            if rowsselected == 1:
                self.contextMenuDelete.setText(self.str_DELETE_ITEM)
            else:
                self.contextMenuDelete.setText(self.str_DELETE_ITEMS)

        if exportSupport:
            self.contextMenuExport.setEnabled(True)
            if rowsselected == 1:
                self.contextMenuExport.setText(self.str_EXPORT_ITEM)
            else:
                self.contextMenuExport.setText(self.str_EXPORT_ITEMS)

        # Finally we execute the context menu
        self.contextMenu.exec_(self.resultview.mapToGlobal(point))

    def onViewItemsSelected(self):
        """Slot for the *view* context menu action.
        """
        raise NotImplementedError(
            'Need to implement a proper model for this to be supported')

    def onDeleteItemsSelected(self):
        """Slot for the *delete* context menu action.
        """
        msg = 'Delete from the Search Plugin is not implemented jet.'
        dialog = DeleteDialog(self, msg)
        dialog.setDeleteItems([])
        dialog.exec_()

    def onExportItemsSelected(self):
        """Slot for the 'export' context menu action.
        """
        msg = 'Export from the Search Plugin is not implemented jet.'
        dialog = ExportDialog(self, msg)
        # Only for proof of concept
        dialog.setExportData([])
        dialog.exec_()

    def onFilterBoxVisibilityChanged(self, visible):
        """Slot for the QKeySequence.Find.

        - `visible`: a boolean value indicating wether or not to toggle
          the filter box widget visibility on or off.
        """
        if visible:
            self.filterBox.setVisible(True)
            self.filterBox.inputEdit.setFocus()
        else:
            # I belive it's common practise to clear the filter when
            # the filter box is closed. This is at least the way the
            # filter boxes works for most webbrowsers.
            self.filterBox.inputEdit.clear()
            self.filterBox.setVisible(False)
            self.resultview.setFocus()

    def onFilterInputChanged(self, filter=''):
        """Slot for the filter input in the result filter widget.

        We get the selected syntax from the syntax combobox
        """
        # The PyQt4 QVariant is causing some problems here, when we try
        # to use the <combobox>.itemData directly, even though the data
        # holds valid QRexExp.PatternSyntax values.
        # We therefore need to explicitly make the QVariant and integer.
        i = self.filterBox.syntaxBox.currentIndex()
        syntaxIndex = self.filterBox.syntaxBox.itemData(i).toInt()[0]
        syntax = QtCore.QRegExp.PatternSyntax(syntaxIndex)
        # As of now we do filtering in a case insensitive way, until we
        # come up with a way to introduce case sensitivity selection in a
        # UI inexpensive way. We want to keep the filter widget as clean
        # and simple as possible.
        regex = QtCore.QRegExp(filter, QtCore.Qt.CaseInsensitive, syntax)
        self.proxymodel.setFilterRegExp(regex)

    def onFilterColumnChanged(self, index):
        """Slot for the column combobox in the filter box widget.
        """
        self.proxymodel.setFilterKeyColumn(index)

    def retranslate(self, all=True):
        """For dynamic translation support.
        """
        self.str_VIEW_ITEM = QtGui.QApplication.translate(
            'ResultView', 'View Item')
        self.str_VIEW_ITEMS = QtGui.QApplication.translate(
            'ResultView', 'View Items')
        self.str_DELETE_ITEM = QtGui.QApplication.translate(
            'ResultView', 'Delete Item')
        self.str_DELETE_ITEMS = QtGui.QApplication.translate(
            'ResultView', 'Delete Items')
        self.str_EXPORT_ITEM = QtGui.QApplication.translate(
            'ResultView', 'Export Item')
        self.str_EXPORT_ITEMS = QtGui.QApplication.translate(
            'ResultView', 'Export Items')
        self.str_NO_RESULT = QtGui.QApplication.translate(
            'ResultView', 'Sorry, no result to display!')
        self.str_BINARY_DATA = QtGui.QApplication.translate(
            'ResultView', 'Binary Data')
        if all:
            self.filterBox.retranslate()
예제 #14
0
class Dialog_report(QDialog, Ui_Dialog_report):
    """
    Class documentation goes here.
    """
    def __init__(self, parent=None):
        """
        Constructor
        """
        QDialog.__init__(self, parent)
        self.setupUi(self)

        #construct Customer list class
        self.clist = Customer_list()

        #construct accounting class
        self.caccount = Dfile()

        #construct customer price class
        self.cprice = Customer_price()

        #construct standard table
        self.tablemodel = QStandardItemModel(31, len(PRODUCT_NAME))
        self.setTableheader()

        #save customer list int
        self.list_customer = self.clist.readCompany()
        self.setCombo(1, self.list_customer)

    def setMode(self, str_mode):

        if str_mode == 'init':
            self.clearAllshow()

    def setCombo(self, comboselect, m_str):
        """
        set combo box
        """
        if comboselect == 1:
            for i in m_str:
                self.comboBox_name.addItem(i)
        elif comboselect == 2:
            self.comboBox_date.clear()
            for i in m_str:
                self.comboBox_date.addItem(i)

    def clearAllshow(self):

        #clear all spin box
        self.setAllspin(0)

        #clear table
        self.clearTableview()

    def setAllspin(self, int_value):
        self.spinBox_1.setValue(int_value)
        self.spinBox_2.setValue(int_value)
        self.spinBox_3.setValue(int_value)
        self.spinBox_4.setValue(int_value)
        self.spinBox_5.setValue(int_value)
        self.spinBox_6.setValue(int_value)
        self.spinBox_7.setValue(int_value)
        self.spinBox_8.setValue(int_value)
        self.spinBox_9.setValue(int_value)
        self.spinBox_10.setValue(int_value)
        self.spinBox_11.setValue(int_value)
        self.spinBox_12.setValue(int_value)
        self.spinBox_13.setValue(int_value)
        self.spinBox_14.setValue(int_value)
        self.spinBox_15.setValue(int_value)
        self.spinBox_16.setValue(int_value)
        self.spinBox_17.setValue(int_value)
        self.spinBox_18.setValue(int_value)
        self.spinBox_19.setValue(int_value)
        self.spinBox_19.setValue(0)

    def setTableheader(self):

        #set header data
        self.tablemodel.setHeaderData(0, Qt.Horizontal, PRODUCT_NAME[0])
        self.tablemodel.setHeaderData(1, Qt.Horizontal, PRODUCT_NAME[1])
        self.tablemodel.setHeaderData(2, Qt.Horizontal, PRODUCT_NAME[2])
        self.tablemodel.setHeaderData(3, Qt.Horizontal, PRODUCT_NAME[3])
        self.tablemodel.setHeaderData(4, Qt.Horizontal, PRODUCT_NAME[4])
        self.tablemodel.setHeaderData(5, Qt.Horizontal, PRODUCT_NAME[5])

    def setTableview(self, dlist_data):
        """
        set data into tableview model
        """
        #show data
        row = 0
        for i in dlist_data:
            self.tablemodel.setData(self.tablemodel.index(row, 0),
                                    QVariant(i[0]))
            self.tablemodel.setData(self.tablemodel.index(row, 1),
                                    QVariant(i[1]))
            self.tablemodel.setData(self.tablemodel.index(row, 2),
                                    QVariant(i[2]))
            self.tablemodel.setData(self.tablemodel.index(row, 3),
                                    QVariant(i[3]))
            self.tablemodel.setData(self.tablemodel.index(row, 4),
                                    QVariant(i[4]))
            self.tablemodel.setData(self.tablemodel.index(row, 5),
                                    QVariant(i[5]))
            row += 1

        #set table into tableview
        self.tableView.setModel(self.tablemodel)

    def clearTableview(self):
        """
        clear table
        """
        #show data
        row = 0
        i = [0, 0, 0, 0, 0, 0]
        for row in range(31):
            self.tablemodel.setData(self.tablemodel.index(row, 0),
                                    QVariant(i[0]))
            self.tablemodel.setData(self.tablemodel.index(row, 1),
                                    QVariant(i[1]))
            self.tablemodel.setData(self.tablemodel.index(row, 2),
                                    QVariant(i[2]))
            self.tablemodel.setData(self.tablemodel.index(row, 3),
                                    QVariant(i[3]))
            self.tablemodel.setData(self.tablemodel.index(row, 4),
                                    QVariant(i[4]))
            self.tablemodel.setData(self.tablemodel.index(row, 5),
                                    QVariant(i[5]))

        #set table into tableview
        self.tableView.setModel(self.tablemodel)

    @pyqtSignature("QString")
    def on_comboBox_name_currentIndexChanged(self, p0):
        """
        when name index change, set combo date
        """
        #set to initial status
        self.setMode('init')

        #read combo text and dict value
        self.str_customercombo = str(self.comboBox_name.currentText().toUtf8())
        self.i_customercombo = self.clist.readCvalue(self.str_customercombo)

        #read all guest accounting data
        self.list_date = self.caccount.listDatafile(self.i_customercombo)

        self.setCombo(2, self.list_date)

    @pyqtSignature("QString")
    def on_comboBox_date_currentIndexChanged(self, p0):
        """
        search price data and load accounting into table
        """

        self.str_filename = str(self.comboBox_date.currentText())

        if self.str_filename != '':
            self.str_datecombo = self.str_filename[3:9]

            #get price version
            self.i_priceversion = self.cprice.selectPrice(
                self.i_customercombo, self.str_datecombo)

            #get price dict
            dict_price = self.cprice.readPrice(self.i_customercombo,
                                               self.i_priceversion)
            self.list_price = self.cprice.getClist(dict_price)

            #show price
            self.setPricespin(self.list_price)

            #show table
            self.caccount.open_dfile(self.str_filename)
            self.table_data = self.caccount.read_alldfile()
            self.setTableview(self.table_data)

            #calculate and show single amount
            self.eachamount = self.sumEachamount(self.table_data)
            self.setEachamount(self.eachamount)

            #calculate single price amount
            self.eachpriceamount = [
                self.eachamount[i] * self.list_price[i]
                for i in range(len(PRODUCT_NAME))
            ]
            self.setEachpriceamount(self.eachpriceamount)

            #show in total income
            self.spinBox_19.setValue(sum(self.eachpriceamount))

    def setPricespin(self, list):

        self.spinBox_1.setValue(list[0])
        self.spinBox_2.setValue(list[1])
        self.spinBox_3.setValue(list[2])
        self.spinBox_4.setValue(list[3])
        self.spinBox_5.setValue(list[4])
        self.spinBox_6.setValue(list[5])

    def setEachamount(self, list):

        self.spinBox_7.setValue(list[0])
        self.spinBox_8.setValue(list[1])
        self.spinBox_9.setValue(list[2])
        self.spinBox_10.setValue(list[3])
        self.spinBox_11.setValue(list[4])
        self.spinBox_12.setValue(list[5])

    def setEachpriceamount(self, list):

        self.spinBox_13.setValue(list[0])
        self.spinBox_14.setValue(list[1])
        self.spinBox_15.setValue(list[2])
        self.spinBox_16.setValue(list[3])
        self.spinBox_17.setValue(list[4])
        self.spinBox_18.setValue(list[5])

    #sum each item total amount
    def sumEachamount(self, duallist):

        eachamount = [0, 0, 0, 0, 0, 0]
        count = 0
        for i in duallist:
            for j in i:
                eachamount[count] += j
                count += 1
            count = 0

        return eachamount
예제 #15
0
class DoProfile(QWidget):

    def __init__(self, iface, dockwidget1 , tool1 , plugin, parent = None):
        QWidget.__init__(self, parent)
        self.profiles = None        #dictionary where is saved the plotting data {"l":[l],"z":[z], "layer":layer1, "curve":curve1}
        self.xAxisSteps = None
        self.xAxisStepType = "numeric"
        self.iface = iface
        self.tool = tool1
        self.dockwidget = dockwidget1
        self.pointstoDraw = None
        self.plugin = plugin
        #init scale widgets
        self.dockwidget.sbMaxVal.setValue(0)
        self.dockwidget.sbMinVal.setValue(0)
        self.dockwidget.sbMaxVal.setEnabled(False)
        self.dockwidget.sbMinVal.setEnabled(False)
        self.dockwidget.sbMinVal.valueChanged.connect(self.reScalePlot)
        self.dockwidget.sbMaxVal.valueChanged.connect(self.reScalePlot)


    #**************************** function part *************************************************

    # remove layers which were removed from QGIS
    def removeClosedLayers(self, model1):
        qgisLayerNames = []
        for i in range(0, self.iface.mapCanvas().layerCount()):
                qgisLayerNames.append(self.iface.mapCanvas().layer(i).name())

        for i in range(0 , model1.rowCount()):
            layerName = model1.item(i,2).data(Qt.EditRole)
            if not layerName in qgisLayerNames:
                self.plugin.removeLayer(i)
                self.removeClosedLayers(model1)
                break

    def calculatePointProfile(self, point, model, library):
        self.model = model
        self.library = library
        
        statName = self.getPointProfileStatNames()[0]

        self.removeClosedLayers(model)
        if point == None:
            return
        PlottingTool().clearData(self.dockwidget, model, library)
        self.profiles = []
        
        #creating the plots of profiles
        for i in range(0 , model.rowCount()):
            self.profiles.append( {"layer": model.item(i,3).data(Qt.EditRole) } )
            self.profiles[i][statName] = []
            self.profiles[i]["l"] = []
            layer = self.profiles[i]["layer"]

            if layer:
                try:
                    ident = layer.dataProvider().identify(point, QgsRaster.IdentifyFormatValue )
                except:
                    ident = None
            else:
                ident = None
            #if ident is not None and ident.has_key(choosenBand+1):
            if ident is not None:
                self.profiles[i][statName] = ident.results().values()
                self.profiles[i]["l"] = ident.results().keys()
        
        self.setXAxisSteps()
        PlottingTool().attachCurves(self.dockwidget, self.profiles, model, library)
        PlottingTool().reScalePlot(self.dockwidget, self.profiles, model, library)
        self.setupTableTab(model)

    def getPointProfileStatNames(self):
        return ["value"]

    # The code is based on the approach of ZonalStatistics from Processing toolbox 
    def calculatePolygonProfile(self, geometry, crs, model, library):
        self.model = model
        self.library = library
        
        self.removeClosedLayers(model)
        if geometry is None or geometry.isEmpty():
            return
        
        PlottingTool().clearData(self.dockwidget, model, library)
        self.profiles = []

        #creating the plots of profiles
        for i in range(0 , model.rowCount()):
            self.profiles.append( {"layer": model.item(i,3).data(Qt.EditRole) } )
            self.profiles[i]["l"] = []
            for statistic in self.getPolygonProfileStatNames():
                self.profiles[i][statistic] = []
            
            # Get intersection between polygon geometry and raster following ZonalStatistics code
            rasterDS = gdal.Open(self.profiles[i]["layer"].source(), gdal.GA_ReadOnly)
            geoTransform = rasterDS.GetGeoTransform()
            
    
            cellXSize = abs(geoTransform[1])
            cellYSize = abs(geoTransform[5])
            rasterXSize = rasterDS.RasterXSize
            rasterYSize = rasterDS.RasterYSize
    
            rasterBBox = QgsRectangle(geoTransform[0], geoTransform[3] - cellYSize
                                      * rasterYSize, geoTransform[0] + cellXSize
                                      * rasterXSize, geoTransform[3])
            rasterGeom = QgsGeometry.fromRect(rasterBBox)
            
            memVectorDriver = ogr.GetDriverByName('Memory')
            memRasterDriver = gdal.GetDriverByName('MEM')
            
            intersectedGeom = rasterGeom.intersection(geometry)
            ogrGeom = ogr.CreateGeometryFromWkt(intersectedGeom.exportToWkt())
            
            bbox = intersectedGeom.boundingBox()

            xMin = bbox.xMinimum()
            xMax = bbox.xMaximum()
            yMin = bbox.yMinimum()
            yMax = bbox.yMaximum()

            (startColumn, startRow) = self.mapToPixel(xMin, yMax, geoTransform)
            (endColumn, endRow) = self.mapToPixel(xMax, yMin, geoTransform)

            width = endColumn - startColumn
            height = endRow - startRow

            if width == 0 or height == 0:
                return

            srcOffset = (startColumn, startRow, width, height)

            newGeoTransform = (
                geoTransform[0] + srcOffset[0] * geoTransform[1],
                geoTransform[1],
                0.0,
                geoTransform[3] + srcOffset[1] * geoTransform[5],
                0.0,
                geoTransform[5],
            )
            
            # Create a temporary vector layer in memory
            memVDS = memVectorDriver.CreateDataSource('out')
            memLayer = memVDS.CreateLayer('poly', crs, ogr.wkbPolygon)

            ft = ogr.Feature(memLayer.GetLayerDefn())
            ft.SetGeometry(ogrGeom)
            memLayer.CreateFeature(ft)
            ft.Destroy()
            
            # Rasterize it
            rasterizedDS = memRasterDriver.Create('', srcOffset[2],
                    srcOffset[3], 1, gdal.GDT_Byte)
            rasterizedDS.SetGeoTransform(newGeoTransform)
            gdal.RasterizeLayer(rasterizedDS, [1], memLayer, burn_values=[1])
            rasterizedArray = rasterizedDS.ReadAsArray()
            
            for bandNumber in range(1, rasterDS.RasterCount+1): 
                rasterBand = rasterDS.GetRasterBand(bandNumber)
                noData = rasterBand.GetNoDataValue()
                if noData is None:
                    noData = np.nan
                scale = rasterBand.GetScale()
                if scale is None:
                    scale = 1.0
                offset = rasterBand.GetOffset()
                if offset is None:
                    offset = 0.0
                srcArray = rasterBand.ReadAsArray(*srcOffset)
                srcArray = srcArray*scale+offset 
                masked = np.ma.MaskedArray(srcArray,
                            mask=np.logical_or.reduce((
                             srcArray == noData,
                             np.logical_not(rasterizedArray),
                             np.isnan(srcArray))))

                self.profiles[i]["l"].append(bandNumber)
                self.profiles[i]["count"].append(float(masked.count()))
                self.profiles[i]["max"].append(float(masked.max()))
                self.profiles[i]["mean"].append(float(masked.mean()))
                self.profiles[i]["median"].append(float(np.ma.median(masked)))
                self.profiles[i]["min"].append(float(masked.min()))
                self.profiles[i]["range"].append(float(masked.max()) - float(masked.min()))
                self.profiles[i]["std"].append(float(masked.std()))
                self.profiles[i]["sum"].append(float(masked.sum()))
                self.profiles[i]["unique"].append(np.unique(masked.compressed()).size)
                self.profiles[i]["var"].append(float(masked.var()))
                
            memVDS = None
            rasterizedDS = None
        
        rasterDS = None
        
        self.setXAxisSteps()
        PlottingTool().attachCurves(self.dockwidget, self.profiles, model, library)
        PlottingTool().reScalePlot(self.dockwidget, self.profiles, model, library)
        self.setupTableTab(model)

    def getPolygonProfileStatNames(self):
        return ["count", "max", "mean", "median", "min", "range", "std", "sum", "unique", "var"]

    def setXAxisSteps(self):
        if self.xAxisSteps == None:
            self.changeXAxisStepType("numeric")
            return
        
        elif self.xAxisSteps[0] == "Timesteps":
            self.changeXAxisStepType("numeric")
            for profile in self.profiles:
                stepsNum = len(profile["l"])
                startTime = self.xAxisSteps[1]
                step = self.xAxisSteps[2]
                stepType = self.xAxisSteps[3]
                useNetcdfTime = self.xAxisSteps[4]
                if stepType == "years":
                    stepType = "days"
                    step = step * 365
                elif stepType == "months":
                    stepType = "days"
                    step = step * 365/12

                profile["l"] = []
                if useNetcdfTime and (profile["layer"].source().startswith("NETCDF:") or
                                      profile["layer"].source().endswith(".nc")):
                    try:
                        import netCDF4
                        if profile["layer"].source().startswith("NETCDF:"):
                            filename = re.match('NETCDF:\"(.*)\":.*$', profile["layer"].source()).group(1)
                        else:
                            filename = profile["layer"].source()
                        nc = netCDF4.Dataset(filename, mode='r')
                        profile["l"] = netCDF4.num2date(nc.variables["time"][:],
                                                        units = nc.variables["time"].units,
                                                        calendar = nc.variables["time"].calendar)
                        nc.close()
                    except ImportError:
                        text = "Temporal/Spectral Profile Tool: netCDF4 module is required to read NetCDF " + \
                               "time dimension. Please use pip install netCDF4"
                        self.iface.messageBar().pushWidget(self.iface.messageBar().createMessage(text), 
                                                           QgsMessageBar.WARNING, 5)
                        profile["l"] = []
                    except KeyError:
                        text = "Temporal/Spectral Profile Tool: NetCDF file does not have " + \
                               "time dimension."
                        self.iface.messageBar().pushWidget(self.iface.messageBar().createMessage(text), 
                                                           QgsMessageBar.WARNING, 5)
                        nc.close()
                        profile["l"] = []
                if profile["l"] == []:
                    for i in range(stepsNum):
                        timedeltaParams = {stepType: step*i}
                        profile["l"].append(startTime + timedelta(**timedeltaParams))
                self.changeXAxisStepType("timedate")        
        else:
            for profile in self.profiles:
                # Truncate the profiles to the minimum of the length of each profile
                # or length of provided x-axis steps
                stepsNum = min(len(self.xAxisSteps), len(profile["l"]))
                profile["l"] = self.xAxisSteps[:stepsNum]
                for stat in profile.keys():
                    if stat == "l" or stat == "layer":
                        continue
                    profile[stat] = profile[stat][:stepsNum]
                    
                # If any x-axis step is a NaN then remove the corresponding
                # value from profile
                nans = [i for i, x in enumerate(profile["l"]) if math.isnan(x)]
                for stat in profile.keys():
                    if stat == "layer":
                        continue
                    profile[stat] = [x for i, x in enumerate(profile[stat]) if i not in nans]
            
            self.changeXAxisStepType("numeric")
            
    def changeXAxisStepType(self, newType):
        if self.xAxisStepType == newType:
            return
        else:
            self.xAxisStepType = newType
            PlottingTool().resetAxis(self.dockwidget, self.library)
    
    def mapToPixel(self, mX, mY, geoTransform):
        (pX, pY) = gdal.ApplyGeoTransform(
            gdal.InvGeoTransform(geoTransform), mX, mY)
            
        return (int(pX), int(pY))            
    
    def setupTableTab(self, model1):
        #*********************** TAble tab *************************************************
        try:                                                                    #Reinitializing the table tab
            self.VLayout = self.dockwidget.scrollAreaWidgetContents.layout()
            while 1:
                child = self.VLayout.takeAt(0)
                if not child:
                    break
                child.widget().deleteLater()
        except:
            self.VLayout = QVBoxLayout(self.dockwidget.scrollAreaWidgetContents)
            self.VLayout.setContentsMargins(9, -1, -1, -1)
        #Setup the table tab
        self.groupBox = []
        self.profilePushButton = []
        self.tableView = []
        self.verticalLayout = []
        for i in range(0 , model1.rowCount()):
            self.groupBox.append( QGroupBox(self.dockwidget.scrollAreaWidgetContents) )
            sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            sizePolicy.setHeightForWidth(self.groupBox[i].sizePolicy().hasHeightForWidth())
            self.groupBox[i].setSizePolicy(sizePolicy)
            self.groupBox[i].setMinimumSize(QSize(0, 150))
            self.groupBox[i].setMaximumSize(QSize(16777215, 350))
            self.groupBox[i].setTitle(QApplication.translate("GroupBox" + str(i), self.profiles[i]["layer"].name(), None, QApplication.UnicodeUTF8))
            self.groupBox[i].setObjectName("groupBox" + str(i))

            self.verticalLayout.append( QVBoxLayout(self.groupBox[i]) )
            self.verticalLayout[i].setObjectName("verticalLayout")
            #The table
            self.tableView.append( QTableView(self.groupBox[i]) )
            self.tableView[i].setObjectName("tableView" + str(i))
            font = QFont("Arial", 8)
            columns = len(self.profiles[i]["l"])
            rowNames = self.profiles[i].keys()
            rowNames.remove("layer") # holds the QgsMapLayer instance
            rowNames.remove("l") # holds the band number
            rows = len(rowNames)
            self.mdl = QStandardItemModel(rows+1, columns)
            self.mdl.setVerticalHeaderLabels(["band"] + rowNames)
            for j in range(columns):
                self.mdl.setData(self.mdl.index(0, j, QModelIndex()), str(self.profiles[i]["l"][j]))
                self.mdl.setData(self.mdl.index(0, j, QModelIndex()), font ,Qt.FontRole)
                for k in range(rows):
                    self.mdl.setData(self.mdl.index(k+1, j, QModelIndex()), str(self.profiles[i][rowNames[k]][j]))
                    self.mdl.setData(self.mdl.index(k+1, j, QModelIndex()), font ,Qt.FontRole)
            #self.tableView[i].setVerticalHeaderLabels(rowNames)
            self.tableView[i].verticalHeader().setDefaultSectionSize(18)
            self.tableView[i].horizontalHeader().setDefaultSectionSize(60)
            self.tableView[i].setModel(self.mdl)
            self.verticalLayout[i].addWidget(self.tableView[i])

            self.horizontalLayout = QHBoxLayout()

            #the copy to clipboard button
            self.profilePushButton.append( QPushButton(self.groupBox[i]) )
            sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            sizePolicy.setHeightForWidth(self.profilePushButton[i].sizePolicy().hasHeightForWidth())
            self.profilePushButton[i].setSizePolicy(sizePolicy)
            self.profilePushButton[i].setText(QApplication.translate("GroupBox", "Copy to clipboard", None, QApplication.UnicodeUTF8))
            self.profilePushButton[i].setObjectName(str(i))
            self.horizontalLayout.addWidget(self.profilePushButton[i])

            self.horizontalLayout.addStretch(0)
            self.verticalLayout[i].addLayout(self.horizontalLayout)

            self.VLayout.addWidget(self.groupBox[i])
            QObject.connect(self.profilePushButton[i], SIGNAL("clicked()"), self.copyTable)

    def copyTable(self):                            #Writing the table to clipboard in excel form
        nr = int( self.sender().objectName() )
        self.clipboard = QApplication.clipboard()
        text = "band"
        rowNames = self.profiles[nr].keys()
        rowNames.remove("layer")
        rowNames.remove("l")
        for name in rowNames:
            text += "\t"+name
        text += "\n"
        for i in range( len(self.profiles[nr]["l"]) ):
            text += str(self.profiles[nr]["l"][i])
            for j in range(len(rowNames)):
                text += "\t" + str(self.profiles[nr][rowNames[j]][i])
            text += "\n"
        self.clipboard.setText(text)

    def reScalePlot(self, param):                         # called when a spinbox value changed
        if type(param) != float:    
            # don't execute it twice, for both valueChanged(int) and valueChanged(str) signals
            return
        if self.dockwidget.sbMinVal.value() == self.dockwidget.sbMaxVal.value() == 0:
            # don't execute it on init
            return
        PlottingTool().reScalePlot(self.dockwidget, self.profiles, self.model, self.library, autoMode = False)
예제 #16
0
class Dialog(QDialog, Ui_nbEditor_dialog):         
    def __init__(self, iface, ml, mc):
        """Constructor for the dialog.
        
        Args:
          iface: QgsInterface instance.
        """
        
        QDialog.__init__(self, iface.mainWindow())                               
                        
        self.setupUi(self)
        
        self.ml = ml
        self.mCanvas = mc         
        self.mRubberBand = QgsRubberBand(self.mCanvas, True)
        self.mRubberBand.reset(QGis.Polygon)
        self.mRubberBand.setColor(Qt.red)
        self.mRubberBand.setWidth(2)
        self.ids = []
        
        self.ini(0)
        
        self.pushCancel.clicked.connect(self.close)
        self.pushOK.clicked.connect(self.convert)
        self.comboBox.addItems(['','Intersections','Touches','Within distance']) 
        
        self.comboBox.currentIndexChanged.connect(self.nbMethod)         
        self.ml.selectionChanged.connect(self.map2tab)
        
        
    def ini(self, n):
        self.model = QStandardItemModel(n, 1)
        self.tableView.setModel(self.model)
        self.model.setHeaderData(0, Qt.Horizontal, 'Neighbouring IDs')
        self.tableView.setSelectionMode(QAbstractItemView.SingleSelection)        
        self.selectionModel = QItemSelectionModel(self.model)
        self.tableView.setSelectionModel(self.selectionModel)
        self.tableView.horizontalHeader().setStretchLastSection(True)    
        self.tableView.selectionModel().selectionChanged.connect(self.tab2map)
        self.progressBar.setValue(0)


    def settings(self):
        self.mod = min(self.ids)
        self.p = 1
        if self.mod==1:
            self.p = 0


    def map2tab(self):
        s = ''
        idx = self.tableView.selectionModel().selectedIndexes()[0]
        ts = str(self.model.itemData(idx)[0])
        
        for fid in sorted(self.ml.selectedFeaturesIds()):
            s += '%s,' % str(int(fid)+self.p)                   
 
        s = s[:-1]
         
        if s!=ts:
            self.model.setData(idx, s)
         
        # in order to handle the symmetry
        if len(s)>len(ts):
             iLst = s.strip().replace(' ', '').split(',')
             jLst = ts.strip().replace(' ', '').split(',')
        else:
             iLst = ts.strip().replace(' ', '').split(',')
             jLst = s.strip().replace(' ', '').split(',')
              
        cent = str(idx.row()+self.p)
        dLst = list(set(iLst)-set(jLst))
          
        for d in dLst:              
            row = int(d)-self.p
            sor = str(self.model.itemData(self.model.index(row, 0))[0])
            eLst = sor.strip().replace(' ', '').split(',')            
            res = ''
            if cent in set(eLst):
                ii = eLst.index(cent)                
                del eLst[ii]
                eLst = sorted(map(int, eLst))                
                for e in eLst:
                    res += '%s,' % e
                res = res[:-1]
            else:
                u = sor + ',%s' % cent
                eLst = sorted(map(int, u.strip().replace(' ', '').split(',')))
                for e in eLst:
                    res += '%s,' % e
                res = res[:-1]                 
                               
            self.model.setData(self.model.index(row, 0, QModelIndex()), res)
                   
                
    def nbWithinDist(self):
        dlg = xdist.Dialog()
        dlg.setModal(True)
        dlg.setWindowTitle("Between two objects")
                
        if dlg.exec_() == QDialog.Accepted:
            lDist = float(dlg.lineEdit.text())
            if lDist==0:
                return

            feat = QgsFeature()
            provider = self.ml.dataProvider()
            e = provider.featureCount()

            self.settings()

            for ne in range(self.mod, e + self.mod):
                feat = QgsFeature()
                geom = QgsGeometry()
                fiter = self.ml.getFeatures(QgsFeatureRequest(ne))
                if fiter.nextFeature(feat):
                    geom = QgsGeometry(feat.geometry())

                neighbours = self.hdist(feat, lDist)
                row = feat.id()-self.mod
                self.model.setData(self.model.index(row, 0, QModelIndex()), neighbours)
                self.progressBar.setValue(100*ne/e)


    def hdist(self, feata, lDist):
        geoma = QgsGeometry(feata.geometry()) 
        feat = QgsFeature()
        provider = self.ml.dataProvider()
        feats = provider.getFeatures()
        self.emit(SIGNAL("runStatus(PyQt_PyObject)"), 0)
        self.emit(SIGNAL("runRange(PyQt_PyObject)"), (0, provider.featureCount())) 
        ne = 0              
        neighbours = ""
        while feats.nextFeature(feat):
            ne += 1
            self.emit(SIGNAL("runStatus(PyQt_PyObject)"), ne)                       
            geomb = QgsGeometry(feat.geometry())            
            if feata.id()!=feat.id():
                if geoma.distance(geomb)<=lDist:
                    neighbours = neighbours + '%s,' % (feat.id()+self.p)
        return neighbours[:-1]            
    
    
    def tab2map(self):        
        QApplication.setOverrideCursor(Qt.WaitCursor)
        
        self.ml.selectionChanged.disconnect(self.map2tab)
        
        idx = self.tableView.selectionModel().selectedIndexes()[0]
        featureId = idx.row() + self.p
        
        s = self.model.itemData(idx)
        lst = s[0].strip().replace(' ', '').split(',')
        
        self.ml.removeSelection()
        
        for sid in lst:
            self.ml.select(int(sid)-self.p)
              
        provider = self.ml.dataProvider()        
        
        feat = QgsFeature()
        layer = QgsVectorLayerCache(self.ml, provider.featureCount())
        layer.featureAtId(idx.row()+self.mod, feat)
        geom = QgsGeometry(feat.geometry())   
        
        self.mRubberBand.setToGeometry(geom, self.ml)
        self.mRubberBand.show()
        
        self.ml.selectionChanged.connect(self.map2tab)
        
        QApplication.restoreOverrideCursor()        
        
        
    def closeEvent(self,event):
        QApplication.setOverrideCursor(Qt.WaitCursor)

        self.ml.selectionChanged.disconnect(self.map2tab)
        self.ml.removeSelection()
        self.mRubberBand.hide()
        self.close()

        QApplication.restoreOverrideCursor()

        
    def convert(self):
        dlg = editor.Dialog()
        dlg.setModal(True)
        dlg.setWindowTitle("Neighbour list in BUGS format")
        num = ""
        adj = ""
        sumNumNeigh = 0
        for row in range(0, self.model.rowCount()):
            ts = self.model.itemData(self.model.index(row, 0))
            lst = ts[0].strip().replace(' ', '').split(',')
            num += '%s, ' % len(lst)
            sumNumNeigh += len(lst)
            lst.reverse()
            sor = ', '.join(lst) + ','
            adj = adj + str(sor) + '\n' 
        
        num = num[:-2]
        adj = adj[:-2]
        
        nblist = 'list(\nnum = c(%s),\nadj = c(%s),\nsumNumNeigh=%s)' % (num, adj, sumNumNeigh)
        dlg.plainTextEdit.appendPlainText(nblist)
        
        dlg.exec_()                


    def nbMethod(self):
        QApplication.setOverrideCursor(Qt.WaitCursor)

        self.ml.selectionChanged.disconnect(self.map2tab)
        self.model.removeRows(0, self.model.rowCount(QModelIndex()), QModelIndex())
        n = self.ml.dataProvider().featureCount()
        self.ini(n)

        self.ids = []

        provider = self.ml.dataProvider()
        feats = provider.getFeatures()
        self.emit(SIGNAL("runStatus(PyQt_PyObject)"), 0)
        self.emit(SIGNAL("runRange(PyQt_PyObject)"), (0, n))
        ne = 0
        feat = QgsFeature()
        while feats.nextFeature(feat):
            ne += 1
            self.emit(SIGNAL("runStatus(PyQt_PyObject)"), ne)
            self.ids.append(feat.id())

        if self.comboBox.currentText()=="Touches":            
            if self.ml.geometryType()==0:
                return
            else:
                self.nbTouches()
        if self.comboBox.currentText()=="Intersections":
            if self.ml.geometryType()==0:
                return
            else:
                self.nbIntersects()
        if self.comboBox.currentText()=="Within distance":
            self.nbWithinDist()

        self.ml.selectionChanged.connect(self.map2tab)

        QApplication.restoreOverrideCursor()
        
            
    def nbTouches(self):                                
        feat = QgsFeature()
        provider = self.ml.dataProvider()
        e = provider.featureCount()

        self.settings()

        for ne in range(self.mod, e + self.mod):
            feat = QgsFeature()
            geom = QgsGeometry()
            fiter = self.ml.getFeatures(QgsFeatureRequest(ne))
            if fiter.nextFeature(feat):
                geom = QgsGeometry(feat.geometry())

            neighbours = self.htouch(feat)
            row = feat.id()-self.mod    
            self.model.setData(self.model.index(row, 0, QModelIndex()), neighbours)
            self.progressBar.setValue(100*ne/e)

         
    def htouch(self, feata):
        geoma = QgsGeometry(feata.geometry()) 
        feat = QgsFeature()
        provider = self.ml.dataProvider()
        feats = provider.getFeatures()
        self.emit(SIGNAL("runStatus(PyQt_PyObject)"), 0)
        self.emit(SIGNAL("runRange(PyQt_PyObject)"), (0, provider.featureCount())) 
        ne = 0              
        neighbours = ""
        while feats.nextFeature(feat):
            ne += 1
            self.emit(SIGNAL("runStatus(PyQt_PyObject)"), ne)                       
            geomb = QgsGeometry(feat.geometry())
            if feata.id()!=feat.id():
                if geoma.touches(geomb)==True:
                    neighbours = neighbours + '%s,' % (feat.id()+self.p)                
        return neighbours[:-1]

    
    def nbIntersects(self):
        feat = QgsFeature()
        provider = self.ml.dataProvider()
        e = provider.featureCount()

        self.settings()

        for ne in range(self.mod, e + self.mod):
            feat = QgsFeature()
            geom = QgsGeometry()
            fiter = self.ml.getFeatures(QgsFeatureRequest(ne))
            if fiter.nextFeature(feat):
                geom = QgsGeometry(feat.geometry())

            neighbours = self.hintersect(feat)
            row = feat.id()-self.mod
            self.model.setData(self.model.index(row, 0, QModelIndex()), neighbours)
            self.progressBar.setValue(100*ne/e)


    def hintersect(self, feata):
        geoma = QgsGeometry(feata.geometry())  
        feat = QgsFeature()
        provider = self.ml.dataProvider()
        feats = provider.getFeatures()
        self.emit(SIGNAL("runStatus(PyQt_PyObject)"), 0)
        self.emit(SIGNAL("runRange(PyQt_PyObject)"), (0, provider.featureCount())) 
        ne = 0              
        neighbours = ""
        while feats.nextFeature(feat):
            ne += 1
            self.emit(SIGNAL("runStatus(PyQt_PyObject)"), ne)                       
            geomb = QgsGeometry(feat.geometry())
            if feata.id()!=feat.id():
                if geoma.intersects(geomb)==True:
                    neighbours = neighbours + '%s,' % (feat.id()+self.p)
        return neighbours[:-1]