Exemplo n.º 1
0
    def populateList(self):
        model = QStandardItemModel()
        for option in self.selectedoptions:
            item = QStandardItem(option)
            model.appendRow(item)

        self.lstLayers.setModel(model)
Exemplo n.º 2
0
    def __init__(self, terms, parent):
        items = {}
        model = QStandardItemModel(parent)

        for term in terms:
            parts = str(term).split('.')
            for i in range(len(parts)):
                parent_key = '.'.join(parts[:i])
                item_key = '.'.join(parts[:i + 1])

                if (item_key in items):
                    continue

                parent_item = items.get(parent_key)

                item = QStandardItem(parts[i])
                if (parent_item):
                    parent_item.appendRow(item)
                else:
                    model.appendRow(item)

                items[item_key] = item

        self._model = model
        super(XQueryCompleter, self).__init__(model, parent)
    def __addFirstRowToModel(self, oldModel, newRow):
        """

        :type oldModel: QAbstractItemModel
        :type newRow: list
        :return: QStandardItemModel
        """
        model = QStandardItemModel(self)
        items = []

        for str in newRow:
            items.append(QStandardItem(str))

        model.appendRow(items)

        for i in xrange(oldModel.rowCount()):
            items = []

            for j in xrange(oldModel.columnCount()):
                index = QModelIndex(oldModel.index(i, j))
                data = oldModel.data(index)
                item = QStandardItem(data)
                items.append(item)

            model.appendRow(items)

        return model
    def _select_tags(self):
        tag_dialog = SelectTagsDialog()
        # if the user has their own taglist, use it
        user_tag_list = os.path.join(os.path.expanduser("~"), '.plugin_tags.txt')
        if os.path.exists(user_tag_list):
            tag_file = user_tag_list
        else:
            tag_file = os.path.join(str(self.plugin_builder_path),
                                          'taglist.txt')

        with open(tag_file) as tf:
            tags = tf.readlines()

        model = QStandardItemModel()

        for tag in tags:
            item = QStandardItem(tag[:-1])
            model.appendRow(item)

        tag_dialog.listView.setModel(model)
        tag_dialog.show()
        ok = tag_dialog.exec_()
        if ok:
            selected = tag_dialog.listView.selectedIndexes()
            seltags = []
            for tag in selected:
                seltags.append(tag.data())
            taglist = ", ".join(seltags)
            self.dialog.tags.setText(taglist)
Exemplo n.º 5
0
    def _guiUpdate_table(self,uuid):
        ""
        self.dbconn=DbConn()
        # self.uuid=self.dbconn.get_uuid()
        uuid=''
        self.meta=self.dbconn.get_meta_kv()[uuid]


        keys=self.meta.keys()

        model=QStandardItemModel()
        model.setHorizontalHeaderItem(0,QStandardItem("Attribute"))
        model.setHorizontalHeaderItem(1,QStandardItem("Value"))

        for k in keys:
            name=self.meta[k]['Attribute']
            item1 = QStandardItem(k)
            item2 = QStandardItem(name)
            item1.setCheckable(True)

            model.appendRow([item1,item2])

        # model.itemChanged.connect(lambda: on_item_changed())

        self.model=model

        self.ui.metaeditor.setModel(model)
        self.ui.metaeditor.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.ui.metaeditor.sortByColumn(1)
        self.ui.metaeditor.resizeColumnsToContents()
Exemplo n.º 6
0
 def __init__( self, terms, parent ):
     items = {}
     model = QStandardItemModel(parent)
     
     for term in terms:
         parts = str(term).split('.')
         for i in range(len(parts)):
             parent_key  = '.'.join(parts[:i])
             item_key    = '.'.join(parts[:i+1])
             
             if ( item_key in items ):
                 continue
             
             parent_item = items.get(parent_key)
             
             item = QStandardItem(parts[i])
             if ( parent_item ):
                 parent_item.appendRow(item)
             else:
                 model.appendRow(item)
             
             items[item_key] = item
     
     self._model = model
     super(XQueryCompleter, self).__init__(model, parent)
    def __addFirstRowToModel(self, oldModel, newRow):
        """

        :type oldModel: QAbstractItemModel
        :type newRow: list
        :return: QStandardItemModel
        """
        model = QStandardItemModel(self)
        items = []

        for str in newRow:
            items.append(QStandardItem(str))

        model.appendRow(items)

        for i in xrange(oldModel.rowCount()):
            items = []

            for j in xrange(oldModel.columnCount()):
                index = QModelIndex(oldModel.index(i, j))
                data = oldModel.data(index)
                item = QStandardItem(data)
                items.append(item)

            model.appendRow(items)

        return model
Exemplo n.º 8
0
def setupChecklist(widget, names, checks = None):
    tp = type(widget)
    # Prepare checks
    if checks is None:
        checks = []
        for name in names:
            checks.append(Qt.Unchecked)
    else:
        newChecks = []
        for check in checks:
            if check: newChecks.append(Qt.Checked)
            else: newChecks.append(Qt.Unchecked)
        checks = newChecks

    ## QListView
    if tp is QListView:
        model = QStandardItemModel()
        for i in xrange(len(names)):
            item = QStandardItem(names[i])
            item.setCheckable(True)
            item.setCheckState(checks[i])
            model.appendRow(item)
        widget.setModel(model)

    ## QListWidget
    elif tp is QListWidget:
        for i in xrange(len(names)):
            item = QListWidgetItem(names[i])
            item.setFlags(Qt.ItemFlags(48)) # 48 = checkable(16), enabled(32)
            item.setCheckState(checks[i])
            widget.addItem(item)

    ## NOT SUPPORTED
    else: raise TypeError('Class ' + str(tp) + ' is not supported.')
Exemplo n.º 9
0
    def test_tooltree(self):
        tree = ToolTree()
        role = tree.actionRole()
        model = QStandardItemModel()
        tree.setModel(model)
        item = QStandardItem("One")
        item.setData(QAction("One", tree), role)
        model.appendRow([item])

        cat = QStandardItem("A Category")
        item = QStandardItem("Two")
        item.setData(QAction("Two", tree), role)
        cat.appendRow([item])
        item = QStandardItem("Three")
        item.setData(QAction("Three", tree), role)
        cat.appendRow([item])

        model.appendRow([cat])

        def p(action):
            print "triggered", action.text()

        tree.triggered.connect(p)

        tree.show()

        self.app.exec_()
Exemplo n.º 10
0
 def __loadRules(self, the_rules, tree_view):
     model = QStandardItemModel(self)
     for r in the_rules:
         item = QStandardItem(r)
         model.appendRow(item)
     model.setHeaderData(0, Qt.Horizontal, "Regular Expression")
     tree_view.setModel(model)
Exemplo n.º 11
0
Arquivo: sak.py Projeto: gyagp/perf
    def init_cmd_table(self):
        model = QStandardItemModel()
        model.setColumnCount(3)
        model.setHeaderData(0, Qt.Horizontal, "Command")
        model.setHeaderData(1, Qt.Horizontal, "Tag")
        model.setHeaderData(2, Qt.Horizontal, "Description")

        import json
        print sys.path[0]
        os.chdir(sys.path[0])
        f = file('command.txt')
        cmds = json.load(f)
        f.close()

        for cmd in cmds:
            l = []
            for field in cmd:
                if type(field) is types.ListType:
                    f = '\n'.join(field)
                else:
                    f = field
                l.append(QStandardItem(f))
            model.appendRow(l)
        self.tableView.setModel(model)
        self.tableView.resizeRowsToContents()

        self.model = model
Exemplo n.º 12
0
class CurvePanel(QListView):
    def __init__(self, curve_source):
        QListView.__init__(self)
        self.curve_source = curve_source
        self.setViewMode(QListView.IconMode)
        self.setIconSize(QSize(64,64))
        self.model = QStandardItemModel()
        for curve in curve_source._curves:
            self.add_curve(curve)
        self.setModel(self.model)
        self.setWrapping(True)
        self.show()

    def edit(self, index, trigger, event):
        if trigger == QAbstractItemView.DoubleClicked:
            item = self.model.item(index.row())
            curve = item.curve
            print curve.name()
            return True
        else:
            return False

    def add_new_curve(self):
        pass
    
    def add_curve(self, curve):
        name = curve.name()
        plot = self._create_plot(name)
        item = PlotItem(plot)
        item.curve = curve
        self.model.appendRow(item)

    def _create_plot(self, xcurve_name):
        index = self.curve_source.index()
        return Plot.of(xcurve_name, index.name()).from_(self.curve_source)
Exemplo n.º 13
0
 def generateLeftListLogTypeModel(self):
     '''Returns all LogType list model '''
     existingLogTypes = []
     logType = LogType.GAMMA
     #get type for each log
     if self._logs is not None and len(self._logs)>0:
         for log in self._logs:
             existingLogTypes.append(log.log_type_name)
     generalSettings = GeneralSettings()
     if generalSettings.workflowType == WorkflowType.petrophysics:
         logTypeList = logType.getAllLogTypesPetrophysicsStringList()
     elif generalSettings.workflowType == WorkflowType.rockphysics:
         logTypeList = logType.getAllLogTypesRockPhysicsStringList()
     else:
         logTypeList = logType.getAllLogTypesStringList()
         
     model = QStandardItemModel(self._dataListToListWidget.leftDataTypeListView)
     for logType in logTypeList:
         item = QStandardItem(logType)
         # checkboxes are confusing
         item.setCheckable(False)
         if logType not in existingLogTypes:
             item.setForeground(Qt.gray)
         model.appendRow(item)
     return model
Exemplo n.º 14
0
    def test_tooltree(self):
        tree = ToolTree()
        role = tree.actionRole()
        model = QStandardItemModel()
        tree.setModel(model)
        item = QStandardItem("One")
        item.setData(QAction("One", tree), role)
        model.appendRow([item])

        cat = QStandardItem("A Category")
        item = QStandardItem("Two")
        item.setData(QAction("Two", tree), role)
        cat.appendRow([item])
        item = QStandardItem("Three")
        item.setData(QAction("Three", tree), role)
        cat.appendRow([item])

        model.appendRow([cat])

        def p(action):
            print "triggered", action.text()

        tree.triggered.connect(p)

        tree.show()

        self.app.exec_()
Exemplo n.º 15
0
	def __loadRules(self, the_rules, tree_view):
		model = QStandardItemModel(self)
		for r in the_rules:
			item = QStandardItem(r)
			model.appendRow(item)
		model.setHeaderData(0, Qt.Horizontal, "Regular Expression")
		tree_view.setModel(model)
Exemplo n.º 16
0
class dockUrlMonitor(QTreeView):
    ''' dock widget for get all credentials logger netcreds'''
    def __init__(self, parent=None,info={}):
        super(dockUrlMonitor, self).__init__(parent)
        self.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.model = QStandardItemModel()
        self.model.setHorizontalHeaderLabels(['URL','HTTP-Headers'])
        self.setModel(self.model)
        self.setUniformRowHeights(True)
        self.setColumnWidth(0,130)

    def writeModeData(self,data):
        ''' get data output and add on QtableWidgets '''
        ParentMaster = QStandardItem('[ {0[src]} > {0[dst]} ] {1[Method]} {1[Host]}{1[Path]}'.format(
        data['urlsCap']['IP'], data['urlsCap']['Headers']))
        ParentMaster.setIcon(QIcon('icons/accept.png'))
        ParentMaster.setSizeHint(QSize(30,30))
        for item in data['urlsCap']['Headers']:
            ParentMaster.appendRow([QStandardItem('{}'.format(item)),
            QStandardItem(data['urlsCap']['Headers'][item])])
        self.model.appendRow(ParentMaster)
        self.setFirstColumnSpanned(ParentMaster.row(),
        self.rootIndex(), True)
        self.scrollToBottom()

    def clear(self):
        self.model.clear()

    def stopProcess(self):
        self.clearSelection()
Exemplo n.º 17
0
    def list_view(self):
        list = QListView()
        # Create an empty model for the list's data
        # model = QStandardItemModel(list)
        repo = LocusRepository()
        locusList = repo.get_all_locus()

        # Create an empty model for the list's data
        model = QStandardItemModel(list)

        for locus in locusList:
            # Create an item with a caption
            item = QStandardItem(locus.locus_id)

            # Add the item to the model
            model.appendRow(item)

        model.itemChanged.connect(self.on_item_changed)

        #    current_index = 0
        #    list.currentChanged(current_index)
        # list.selectionModel().currentChanged.connect(on_current_changed)

        # self.listWidget.itemClicked.connect(self.printItemText)
        # app.connect(list, SIGNAL("currentChanged()"),
        #              printItemText)

        # Apply the model to the list view
        list.setModel(model)
        list.selectionModel().currentChanged.connect(self.on_current_changed)

        self.horizontalLayout_1.addWidget(list)
Exemplo n.º 18
0
 def onConnectClick(self):
     # On remplit le champ Serveur s'il était vide
     if self.dlg.url.text() == "":
         self.dlg.url.setText("localhost")
     # On prépare la liste
     listView = self.dlg.layerList
     model = QStandardItemModel(listView)
     try:
         # On ouvre une connexion à la base
         self.connector = EsConnector(self.dlg.url.text(),
                                      self.dlg.port.text())
         # On parcourt les index
         aliases = self.connector.makeGetCallToES("_aliases")
         for index in aliases:
             # On parcourt les types
             metadata = self.connector.makeGetCallToES(index)
             mappings = metadata[index]["mappings"]
             for type in mappings:
                 # On parcourt les champs
                 mapping = mappings[type]["properties"]
                 for field in mapping:
                     # Si le champ est de type geo_shape ou geo_point
                     if mapping[field]["type"] == "geo_point" or mapping[
                             field]["type"] == "geo_shape":
                         # On mémorise ce champ
                         self.connector.addGeoField({
                             "index":
                             index,
                             "type":
                             type,
                             "field":
                             field,
                             "geotype":
                             mapping[field]["type"]
                         })
                         # On affiche ce champ dans la liste
                         item = QStandardItem('- Index "' + index +
                                              '" / Type "' + type +
                                              '" / Champ "' + field +
                                              '" (' +
                                              mapping[field]["type"] + ')')
                         model.appendRow(item)
         # Si au moins un champ a été trouvé
         if model.rowCount() > 0:
             # On met à jour le contenu de la liste
             listView.setModel(model)
             # On active le bouton "Ajouter"
             self.dlg.addLayers.setEnabled(True)
         else:
             self.iface.messageBar().pushMessage(
                 "ElasticSearch Connector",
                 'Aucun champ "geo_shape" ou "geo_point" disponible',
                 level=QgsMessageBar.WARNING,
                 duration=5)
         # On se déconnecte de la base
     except ESConnectorException, e:
         self.iface.messageBar().pushMessage("ElasticSearch Connector",
                                             str(e),
                                             level=QgsMessageBar.CRITICAL,
                                             duration=5)
Exemplo n.º 19
0
    def _select_tags(self):
        tag_dialog = SelectTagsDialog()
        # if the user has their own taglist, use it
        user_tag_list = os.path.join(os.path.expanduser("~"),
                                     '.plugin_tags.txt')
        if os.path.exists(user_tag_list):
            tag_file = user_tag_list
        else:
            tag_file = os.path.join(str(self.plugin_builder_path),
                                    'taglist.txt')

        with open(tag_file) as tf:
            tags = tf.readlines()

        model = QStandardItemModel()

        for tag in tags:
            item = QStandardItem(tag[:-1])
            model.appendRow(item)

        tag_dialog.listView.setModel(model)
        tag_dialog.show()
        ok = tag_dialog.exec_()
        if ok:
            selected = tag_dialog.listView.selectedIndexes()
            seltags = []
            for tag in selected:
                seltags.append(tag.data())
            taglist = ", ".join(seltags)
            self.dialog.tags.setText(taglist)
Exemplo n.º 20
0
class dockUrlMonitor(QTreeView):
    ''' dock widget for get all credentials logger netcreds'''
    def __init__(self, parent=None, info={}):
        super(dockUrlMonitor, self).__init__(parent)
        self.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.model = QStandardItemModel()
        self.model.setHorizontalHeaderLabels(['URL', 'HTTP-Headers'])
        self.setModel(self.model)
        self.setUniformRowHeights(True)
        self.setColumnWidth(0, 130)

    def writeModeData(self, data):
        ''' get data output and add on QtableWidgets '''
        ParentMaster = QStandardItem(
            '[ {0[src]} > {0[dst]} ] {1[Method]} {1[Host]}{1[Path]}'.format(
                data['urlsCap']['IP'], data['urlsCap']['Headers']))
        ParentMaster.setIcon(QIcon('icons/accept.png'))
        ParentMaster.setSizeHint(QSize(30, 30))
        for item in data['urlsCap']['Headers']:
            ParentMaster.appendRow([
                QStandardItem('{}'.format(item)),
                QStandardItem(data['urlsCap']['Headers'][item])
            ])
        self.model.appendRow(ParentMaster)
        self.setFirstColumnSpanned(ParentMaster.row(), self.rootIndex(), True)
        self.scrollToBottom()

    def clear(self):
        self.model.clear()

    def stopProcess(self):
        self.clearSelection()
Exemplo n.º 21
0
 def createComboBoxWithStrings(self, array):
     dbList = QComboBox()
     dbsListModel = QStandardItemModel(dbList)
     for f in array:
         item = QStandardItem(f)
         dbsListModel.appendRow(item)
     dbList.setModel(dbsListModel)
     return dbList
Exemplo n.º 22
0
 def generateLeftListLogModel(self):
     '''Returns log model using all logs in self._logs '''
     model = QStandardItemModel(self._dataListToListWidget.leftDataTypeListView)
     for log in self._logs:
         item = QStandardItem(log.name)
         # checkboxes are confusing
         item.setCheckable(False)
         model.appendRow(item)
     return model
Exemplo n.º 23
0
    def populateList(self):
        model = QStandardItemModel()
        for i, option in enumerate(self.options):
            item = QStandardItem(option)
            item.setCheckState(Qt.Checked if i in self.selectedoptions else Qt.Unchecked)
            item.setCheckable(True)
            model.appendRow(item)

        self.lstLayers.setModel(model)
Exemplo n.º 24
0
    def populateList(self):
        model = QStandardItemModel()
        for i, option in enumerate(self.options):
            item = QStandardItem(option)
            item.setCheckState(Qt.Checked if i in
                               self.selectedoptions else Qt.Unchecked)
            item.setCheckable(True)
            model.appendRow(item)

        self.lstLayers.setModel(model)
Exemplo n.º 25
0
 def on_show_history_wifi_name(self):
     self.history_wifi_list = get_history_connected_wifi()
     model = QStandardItemModel(self.showWIFIListView)
     # Get each history wifi name
     for wifi_name in  self.history_wifi_list:
         item = QStandardItem(wifi_name)
         # Add the item to the model
         model.appendRow(item)
     self.showWIFIListView.setModel(model)
     self.showWIFIListView.show()
Exemplo n.º 26
0
class FlowItemTreeWidget(QTreeView):
    def __init__(self, parent=None):
        QTreeView.__init__(self, parent)

        self.setAnimated(True)
        self.setDragEnabled(True)
        self.setRootIsDecorated(False)
        self.setFrameShape(QFrame.NoFrame)
        self.setIconSize(QSize(22, 22))
        self.header().setStretchLastSection(True)

        # background color
        palette = self.viewport().palette()
        palette.setColor(self.viewport().backgroundRole(), Qt.transparent)
        palette.setColor(self.viewport().foregroundRole(),
                         palette.color(QPalette.WindowText))
        self.viewport().setPalette(palette)

        # Model
        self._model = QStandardItemModel()
        self.proxy = FlowItemSortFilterProxyModel(self)
        self.proxy.setSourceModel(self._model)
        self.setModel(self.proxy)

        self.header().hide()

    def addCategory(self, category, items):
        # Items
        root = QStandardItem(category)
        root.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
        self._model.appendRow(root)

        # Styling
        root.setFlags(Qt.ItemIsEnabled)
        f = root.font()
        f.setPointSize(10)
        f.setBold(True)
        root.setFont(f)

        for item in items:
            ins = item()
            child = QStandardItem(QIcon.fromTheme(ins.iconname),
                                  ins.description)
            child.setData(QVariant(item), Qt.UserRole)
            child.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable
                           | Qt.ItemIsDragEnabled)
            if ins.__doc__ is not None and len(ins.__doc__) > 0:
                child.setWhatsThis(ins.__doc__)
            root.appendRow(child)

    def setFilter(self, pattern):
        self.proxy.setFilterRegExp(
            QRegExp(pattern, Qt.CaseInsensitive, QRegExp.FixedString))
        self.expandAll()
Exemplo n.º 27
0
 def populateRightListView(self, rightDataList):
     assert all(isinstance(item, str) for item in rightDataList)
     model = self.rightListView.model()
     if model is None:
         model = QStandardItemModel(self.rightListView)
     for data in rightDataList:
         item = QStandardItem(data)
         # disable checkbox as is confusing
         item.setCheckable(False)
         model.appendRow(item)
     self.rightListView.setModel(model)
Exemplo n.º 28
0
	def loadData(self):
		model = QStandardItemModel()

		self.games = Game.loadFromFile()
		
		items = []
		for g in self.games:
			items.append(str(g))
			
		for i in items:
			model.appendRow( QStandardItem(i) ) 
		
		self.ui.listView.setModel(model)
Exemplo n.º 29
0
 def show_result(self, search_time):
     self.set_results_heading_text("{} Ergebnisse in {:.2f} Sekunden".format(len(self.result), search_time))
     result = self.result
     model = QStandardItemModel(self.list_results)
     for index in range(min(len(result), self.max_results)):
         node = result.get_node(index)
         context = result.get_context(index)
         item_text = [str(index + 1) + ". " + node.get_title(),
                      node.get_urls()[0],
                      "\t" + context]
         item = QStandardItem("\n".join(item_text))
         model.appendRow(item)
     self.list_results.setModel(model)
     self.list_results.show()
Exemplo n.º 30
0
class FlowItemTreeWidget( QTreeView ):
    def __init__( self, parent = None ):
        QTreeView.__init__( self, parent )

        self.setAnimated( True )
        self.setDragEnabled( True )
        self.setRootIsDecorated( False )
        self.setFrameShape( QFrame.NoFrame )
        self.setIconSize( QSize( 22, 22 ) )
        self.header().setStretchLastSection( True )

        # background color
        palette = self.viewport().palette()
        palette.setColor( self.viewport().backgroundRole(), Qt.transparent )
        palette.setColor( self.viewport().foregroundRole(), palette.color( QPalette.WindowText ) )
        self.viewport().setPalette( palette )

        # Model
        self._model = QStandardItemModel()
        self.proxy = FlowItemSortFilterProxyModel( self )
        self.proxy.setSourceModel( self._model )
        self.setModel( self.proxy )

        self.header().hide()

    def addCategory( self, category, items ):
        # Items
        root = QStandardItem( category )
        root.setFlags( Qt.ItemIsEnabled | Qt.ItemIsSelectable )
        self._model.appendRow( root )

        # Styling
        root.setFlags( Qt.ItemIsEnabled )
        f = root.font()
        f.setPointSize( 10 )
        f.setBold( True )
        root.setFont( f )

        for item in items:
            ins = item()
            child = QStandardItem( QIcon.fromTheme( ins.iconname ), ins.description )
            child.setData( QVariant( item ), Qt.UserRole )
            child.setFlags( Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled )
            if ins.__doc__ is not None and len( ins.__doc__ ) > 0: child.setWhatsThis( ins.__doc__ )
            root.appendRow( child )

    def setFilter( self, pattern ):
        self.proxy.setFilterRegExp( QRegExp( pattern, Qt.CaseInsensitive, QRegExp.FixedString ) )
        self.expandAll()
Exemplo n.º 31
0
class HistoryDialog(QDialog, Ui_HistoryDialogPythonConsole):
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.setupUi(self)
        self.parent = parent
        self.setWindowTitle(
            QCoreApplication.translate("PythonConsole",
                                       "Python Console - Command History"))
        self.listView.setToolTip(
            QCoreApplication.translate("PythonConsole",
                                       "Double click on item to execute"))
        self.model = QStandardItemModel(self.listView)

        self._reloadHistory()

        self.deleteScut = QShortcut(QKeySequence(Qt.Key_Delete), self)
        self.deleteScut.activated.connect(self._deleteItem)
        self.listView.doubleClicked.connect(self._runHistory)
        self.reloadHistory.clicked.connect(self._reloadHistory)
        self.saveHistory.clicked.connect(self._saveHistory)

    def _runHistory(self, item):
        cmd = item.data(Qt.DisplayRole)
        self.parent.runCommand(unicode(cmd))

    def _saveHistory(self):
        self.parent.writeHistoryFile(True)

    def _reloadHistory(self):
        self.model.clear()
        for i in self.parent.history:
            item = QStandardItem(i)
            if sys.platform.startswith('win'):
                item.setSizeHint(QSize(18, 18))
            self.model.appendRow(item)

        self.listView.setModel(self.model)
        self.listView.scrollToBottom()

    def _deleteItem(self):
        itemsSelected = self.listView.selectionModel().selectedIndexes()
        if itemsSelected:
            item = itemsSelected[0].row()
            ## Remove item from the command history (just for the current session)
            self.parent.history.pop(item)
            self.parent.historyIndex -= 1
            ## Remove row from the command history dialog
            self.model.removeRow(item)
Exemplo n.º 32
0
class NameList(QDockWidget):
    def __init__(self, window):
        super(NameList, self).__init__('Current Plots')
        self.namelist_model = QStandardItemModel()
        self.namelist_view = QListView()
        self.namelist_view.setModel(self.namelist_model)
        self.setWidget(self.namelist_view)
        self.window = window
        self.plot_dict = {}

        self.namelist_view.doubleClicked.connect(self.activate_item)
        self.namelist_view.setContextMenuPolicy(QtConst.ActionsContextMenu)
        delete_action = QAction("Delete Selected", self.namelist_view)
        delete_action.triggered.connect(self.delete_item)
        self.namelist_view.addAction(delete_action)

    def activate_item(self, index):
        item = self.namelist_model.itemFromIndex(index)
        plot = self.plot_dict[str(item.text())]
        if plot.closed:
            plot.closed = False
            self.window.add_plot(plot)

    def delete_item(self):
        index = self.namelist_view.currentIndex()
        item = self.namelist_model.itemFromIndex(index)
        del self[str(item.text())]

    def __getitem__(self, item):
        return self.plot_dict[item]

    def __setitem__(self, name, plot):
        model = QStandardItem(name)
        model.setEditable(False)
        self.namelist_model.appendRow(model)
        self.plot_dict[name] = plot

    def __contains__(self, value):
        return value in self.plot_dict

    def __delitem__(self, name):
        self.namelist_model.removeRow(
            self.namelist_model.findItems(name)[0].index().row())
        self.plot_dict[name].close()
        del self.plot_dict[name]

    def keys(self):
        return self.plot_dict.keys()
Exemplo n.º 33
0
class HistoryDialog(QDialog, Ui_HistoryDialogPythonConsole):

    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.setupUi(self)
        self.parent = parent
        self.setWindowTitle(QCoreApplication.translate("PythonConsole",
                                                       "Python Console - Command History"))
        self.listView.setToolTip(QCoreApplication.translate("PythonConsole",
                                                            "Double click on item to execute"))
        self.model = QStandardItemModel(self.listView)

        self._reloadHistory()

        self.deleteScut = QShortcut(QKeySequence(Qt.Key_Delete), self)
        self.deleteScut.activated.connect(self._deleteItem)
        self.listView.doubleClicked.connect(self._runHistory)
        self.reloadHistory.clicked.connect(self._reloadHistory)
        self.saveHistory.clicked.connect(self._saveHistory)

    def _runHistory(self, item):
        cmd = item.data(Qt.DisplayRole)
        self.parent.runCommand(unicode(cmd))

    def _saveHistory(self):
        self.parent.writeHistoryFile(True)

    def _reloadHistory(self):
        self.model.clear()
        for i in self.parent.history:
            item = QStandardItem(i)
            if sys.platform.startswith('win'):
                item.setSizeHint(QSize(18, 18))
            self.model.appendRow(item)

        self.listView.setModel(self.model)
        self.listView.scrollToBottom()

    def _deleteItem(self):
        itemsSelected = self.listView.selectionModel().selectedIndexes()
        if itemsSelected:
            item = itemsSelected[0].row()
            ## Remove item from the command history (just for the current session)
            self.parent.history.pop(item)
            self.parent.historyIndex -= 1
            ## Remove row from the command history dialog
            self.model.removeRow(item)
Exemplo n.º 34
0
    def _guiUpdate_status(self,data):
        ""

        model=QStandardItemModel()
        model.setHorizontalHeaderItem(0,QStandardItem("attribute"))
        model.setHorizontalHeaderItem(1,QStandardItem("status"))

        for key in data.keys():
            value=data[key]
            item1 = QStandardItem(key)
            item2 = QStandardItem(value)
            # item1.setCheckable(True)

            model.appendRow([item1,item2])

        self.ui.outStatus.setModel(model)
        self.ui.outStatus.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.ui.outStatus.resizeColumnsToContents()
Exemplo n.º 35
0
def setupList(widget, items):
    # QListWidget
    if type(widget) is QListWidget:
        widget.clear()
        for item in items:
            widget.addItem(item)
    # QListView
    elif type(widget) is QListView:
        model = QStandardItemModel()
        for item in items:
            row = QStandardItem(item)
            model.appendRow(row)
        widget.setModel(model)
    elif type(widget) is QPlainTextEdit:
        widget.clear()
        widget.insertPlainText(str.join('\n', items))
    # Not supported
    else: raise TypeError('Class ' + str(type(widget)) + ' is not supported.')
Exemplo n.º 36
0
class DataModel(object):
    def __init__(self):
        super(DataModel,self).__init__()
        self.servers     = QStandardItemModel(0,3)
        self.selected    = ''
        self.autoconnect = False
        
    def loadSettings(self):
        settings = QSettings()
        servers = settings.value("servers", None)
        self.servers.clear()
        if servers:
            for s in servers:
                self.servers.appendRow([QStandardItem(str(i)) for i in s])
        self.selected    =  str(settings.value("selected",    self.selected))
        self.autoconnect = int(settings.value("autoconnect", self.autoconnect))
        
    def saveSettings(self):
        settings = QSettings()
        servers = []
        if self.servers:
            for row in xrange(self.servers.rowCount()):
                entry = []
                for col in xrange(self.servers.columnCount()):
                    entry += [self.servers.item(row,col).text()]
                servers += [entry]
        if len(servers):
            settings.setValue("servers", servers)
        else:
            settings.setValue("servers", None)
        settings.setValue("selected",     str(self.selected))
        settings.setValue("autoconnect", int(self.autoconnect))

    def selectedServer(self):
        selectedServer = []
        if self.selected:
            result = self.servers.findItems( self.selected)
            if len(result):
                mi = result[0]
                row = mi.row()
                for col in xrange(self.servers.columnCount()):
                    selectedServer += [self.servers.item(row,col).text()]
        return selectedServer
Exemplo n.º 37
0
    def initListView(self):
        """Init status table"""
        # List Box model
        model = QStandardItemModel()

        # Init list objects
        for i, frame in enumerate(self.task.videoLabelHandler.files):
            item = QStandardItem(frame + "\t{0} Objects".format(len(self.task.videoLabelHandler.objects)))
            item.setCheckState(Qt.Checked)
            item.setCheckable(True)
            model.appendRow(item)

        if self.segmentation_mode:
            model.item(0).setEnabled(False)
        else:
            model.item(i).setCheckState(Qt.Unchecked)
            model.item(i).setEnabled(False)

        # Set model
        self.view.setModel(model)
Exemplo n.º 38
0
    def _guiUpdate_UUID(self):
        ""
        self.dbconn=DbConn()
        self.uuid=self.dbconn.get_uuid()
        keys=self.uuid.keys()

        model=QStandardItemModel()
        model.setHorizontalHeaderItem(0,QStandardItem("UUID"))
        model.setHorizontalHeaderItem(1,QStandardItem("Path"))

        def on_item_changed():
            i = 0
            list=[]
            while model.item(i):
                if not model.item(i,0).checkState():
                    ""
                    # return
                else:
                    # print model.item(i,0).text()
                    list.append(model.item(i,0).text())
                i += 1

            self.UUIDList=list


        for key in keys:
            name=self.uuid[key]['Path']
            item1 = QStandardItem(key)
            item2 = QStandardItem(name)
            # item1.setCheckable(True)

            model.appendRow([item1,item2])

        model.itemChanged.connect(lambda: on_item_changed())

        self.ui.model=model

        self.ui.inUUIDList.setModel(model)
        self.ui.inUUIDList.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.ui.inUUIDList.sortByColumn(1)
        self.ui.inUUIDList.resizeColumnsToContents()
 def __init__(self, data, parent=None):
     """Constructor."""
     super(GDALLocationInfoForm, self).__init__(parent)
     self.setupUi(self)
     
     self.treeView.setSelectionBehavior(QAbstractItemView.SelectRows)
     
     model = QStandardItemModel()
     model.setHorizontalHeaderLabels([self.tr('object/attribute'), self.tr('value')])
     
     self.treeView.setModel(model)
     self.treeView.setUniformRowHeights(True)
     
     
     for object_name, object_attrs in data.items():
         parent = QStandardItem(object_name)
         for attr_name, attr_value in object_attrs.items():
             attr_name_item = QStandardItem(attr_name)
             attr_value_item = QStandardItem(attr_value)
             parent.appendRow([attr_name_item, attr_value_item])
         model.appendRow(parent)
Exemplo n.º 40
0
    def _guiInit(self):
        ""
        keys=self.uuid.keys()
        # self.selUUIDList=[]

        model=QStandardItemModel()
        model.setHorizontalHeaderItem(0,QStandardItem("UUID"))
        model.setHorizontalHeaderItem(1,QStandardItem("Path"))

        def on_item_changed():
            i = 0
            list=[]
            while model.item(i):
                if not model.item(i,0).checkState():
                    ""
                    # return
                else:
                    list.append(model.item(i,0).text())
                i += 1

            self.UUIDList=list


        for key in keys:
            name=self.uuid[key]['Path']
            item1 = QStandardItem(key)
            item2 = QStandardItem(name)
            item1.setCheckable(True)

            model.appendRow([item1,item2])



        model.itemChanged.connect(lambda: on_item_changed())

        self.ui.inUUIDList.setModel(model)
        self.ui.inUUIDList.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.ui.inUUIDList.sortByColumn(1)
Exemplo n.º 41
0
    def fillCheckboxes(self, layers, name):
        """
        Function for filling listView with checkboxes
        :param layers: layers from Qgis legend
        :param name: name of current layer from comboBox
        :return:
        """
        layer = None

        model = QStandardItemModel()
        self.dlg.listView.reset()

        for layer in layers:
            if layer.name() == name:
                fields = layer.pendingFields()
                fieldNames = [field.name() for field in fields]
                for fieldName in fieldNames:
                    item = QStandardItem(fieldName)
                    item.setCheckable(True)
                    item.setText(fieldName)
                    model.appendRow(item)

        self.dlg.listView.setModel(model)
Exemplo n.º 42
0
class GameListWidget(QListView):
    def __init__(self, parent=None):
        QListView.__init__(self, parent)
        self.game_list = []
        self.model = QStandardItemModel()
        self.setModel(self.model)
        self.setWordWrap(True)
        self.setUniformItemSizes(True)
        self.setGridSize(QSize(self.rect().width(), 30))
        self.setFont(QFont("Microsoft YaHei", 10))
        self.setEditTriggers(QAbstractItemView.NoEditTriggers)
        # self.setFocusPolicy(Qt.NoFocus)
        self.setSelectionMode(QAbstractItemView.SingleSelection)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        #self.setAcceptDrops(True)
        self.game_controller = GameController()
        self.game_controller.connector.connect(SIGNAL('game_list'),
                                               self.add_game_item)
        self.game_controller.connector.connect(SIGNAL('game_list_clear'),
                                               self.clear)

        self.clicked.connect(self.double_click_on_item)  ## ??????

    def double_click_on_item(self, idx):
        print('%d was clicked' % (idx))
        self.emit(SIGNAL("enter_room(QString, QString)"),
                  self.game_list[idx][0], self.game_list[idx][1])

    def add_game_item(self, txt, id):
        self.game_list.append((id, txt))
        item = QStandardItem(txt)
        item.setTextAlignment(Qt.AlignCenter)
        self.model.appendRow(item)

    def clear(self):
        self.model.clear()
Exemplo n.º 43
0
 def comboProjectChanged(self):
     if len(self.ui.comboProject.currentText()) > 0:
         self.project_id = self.projects_id[self.ui.comboProject.currentText()]
         #get project tasks
         qsubtasks = QStandardItemModel()
         for proj_tasks in self.asana_api.tasks.find_by_project(self.project_id, { 'completed_since': 'now'}):
             item = QStandardItem(proj_tasks['name'])
             item.setEditable(True)
             item.setToolTip('Double click to edit')
             if not proj_tasks['name'].endswith(':'):
                 check = Qt.Unchecked
                 item.setCheckState(check)
                 item.setCheckable(True)
                 self.projects_id[proj_tasks['name']] = proj_tasks['id']
                 item.setStatusTip(str(proj_tasks['id']))
             else:
                 font = QFont()
                 font.setWeight(QFont.Bold)
                 item.setFont(font)
             #populate the listview
             qsubtasks.appendRow(item)
         self.ui.listTasks.setModel(qsubtasks)
         QApplication.setOverrideCursor(QCursor(Qt.ArrowCursor))
         qsubtasks.itemChanged.connect(self.checkTasks)
Exemplo n.º 44
0
    def __init__(self):
        QWidget.__init__(self)

        layout = QVBoxLayout()

        self.model = DataTypeKeysListModel()
        self.filter_model = DataTypeProxyModel(self.model)

        self.search_box = SearchBox()
        self.search_box.filterChanged.connect(self.setSearchString)

        layout.addWidget(self.search_box)

        data_type_model = QStandardItemModel(0, 1)
        item = QStandardItem("Select data types...")

        data_type_model.appendRow(item)

        self.__summary_item = QStandardItem("Summary")
        self.__summary_item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
        self.__summary_item.setData(Qt.Checked, Qt.CheckStateRole)

        data_type_model.appendRow(self.__summary_item)

        self.__block_item = QStandardItem("Block")
        self.__block_item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
        self.__block_item.setData(Qt.Checked, Qt.CheckStateRole)
        data_type_model.appendRow(self.__block_item)

        data_type_model.itemChanged.connect(self.onItemChanged)

        combo = QComboBox()
        combo.setModel(data_type_model)
        layout.addWidget(combo)

        self.data_type_keys_widget = QListView()
        self.data_type_keys_widget.setModel(self.filter_model)
        self.data_type_keys_widget.selectionModel().selectionChanged.connect(self.itemSelected)

        layout.addSpacing(15)
        layout.addWidget(self.data_type_keys_widget, 2)

        layout.addWidget(Legend("Default types", DataTypeKeysListModel.DEFAULT_DATA_TYPE))
        layout.addWidget(Legend("Observations available", DataTypeKeysListModel.HAS_OBSERVATIONS))

        self.setLayout(layout)
Exemplo n.º 45
0
class TemplateDocumentSelector(QDialog, Ui_frmDocumentSelector):
    """
    Dialog for selecting a document template from the saved list.
    """
    def __init__(self, parent=None, selectMode=True):
        QDialog.__init__(self, parent)
        self.setupUi(self)

        self.notifBar = NotificationBar(self.vlNotification)

        if selectMode:
            self.buttonBox.setVisible(True)
            self.manageButtonBox.setVisible(False)
            currHeight = self.size().height()
            self.resize(200, currHeight)

        else:
            self.buttonBox.setVisible(False)
            self.manageButtonBox.setVisible(True)
            self.setWindowTitle(
                QApplication.translate("TemplateDocumentSelector",
                                       "Template Manager"))

        #Configure manage buttons
        btnEdit = self.manageButtonBox.button(QDialogButtonBox.Ok)
        btnEdit.setText(
            QApplication.translate("TemplateDocumentSelector", "Edit..."))
        btnEdit.setIcon(QIcon(":/plugins/stdm/images/icons/edit.png"))

        btnDelete = self.manageButtonBox.button(QDialogButtonBox.Save)
        btnDelete.setText(
            QApplication.translate("TemplateDocumentSelector", "Delete"))
        btnDelete.setIcon(QIcon(":/plugins/stdm/images/icons/delete.png"))

        #Connect signals
        self.buttonBox.accepted.connect(self.onAccept)
        btnEdit.clicked.connect(self.onEditTemplate)
        btnDelete.clicked.connect(self.onDeleteTemplate)

        #Get saved document templates then add to the model
        templates = documentTemplates()

        self._docItemModel = QStandardItemModel(parent)
        self._docItemModel.setColumnCount(2)

        for name, path in templates.iteritems():
            docNameItem = self._createDocNameItem(name)
            filePathItem = QStandardItem(path)
            self._docItemModel.appendRow([docNameItem, filePathItem])

        self.lstDocs.setModel(self._docItemModel)

    def _createDocNameItem(self, docName):
        """
        Create a template document standard item.
        """
        #Set icon
        icon = QIcon()
        icon.addPixmap(QPixmap(":/plugins/stdm/images/icons/document.png"),
                       QIcon.Normal, QIcon.Off)

        dnItem = QStandardItem(icon, docName)

        return dnItem

    def onEditTemplate(self):
        """
        Slot raised to edit document template.
        """
        self.notifBar.clear()

        if self.documentMapping() == None:
            self.notifBar.insertErrorNotification(QApplication.translate("TemplateDocumentSelector", \
                                                                         "Please select a document template to edit"))
            return

        templateName, filePath = self.documentMapping()

        docName,ok = QInputDialog.getText(self, \
                                              QApplication.translate("TemplateDocumentSelector","Edit Template"), \
                                              QApplication.translate("TemplateDocumentSelector","Please enter the new template name below"), \
                                              text = templateName)
        if ok and docName == "":
            self.notifBar.insertErrorNotification(QApplication.translate("TemplateDocumentSelector", \
                                                                         "Template name cannot be empty"))
            return

        elif docName == templateName:
            return

        elif ok and docName != "":
            result, newTemplatePath = self._editTemplate(filePath, docName)

            if result:
                #Update view
                mIndices = self._selectedMappings()

                docNameItem = self._docItemModel.itemFromIndex(mIndices[0])
                filePathItem = self._docItemModel.itemFromIndex(mIndices[1])

                docNameItem.setText(docName)
                filePathItem.setText(newTemplatePath)

                self.notifBar.insertInfoNotification(QApplication.translate("TemplateDocumentSelector", \
                                                                         "'{0}' template has been successfully updated".format(docName)))

            else:
                self.notifBar.insertErrorNotification(QApplication.translate("TemplateDocumentSelector", \
                                                                         "Error: '{0}' template could not be updated".format(templateName)))

    def onDeleteTemplate(self):
        """
        Slot raised to delete document template.
        """
        self.notifBar.clear()

        if self.documentMapping() == None:
            self.notifBar.insertErrorNotification(QApplication.translate("TemplateDocumentSelector", \
                                                                         "Please select a document template to delete"))
            return

        templateName, filePath = self.documentMapping()

        result = QMessageBox.warning(self, QApplication.translate("TemplateDocumentSelector", \
                                                                         "Confirm delete"),
                                     QApplication.translate("TemplateDocumentSelector", \
                                                                         "Are you sure you want to delete '{0}' template?" \
                                                                         "This action cannot be undone.\nClick Yes to proceed " \
                                                                         "or No to cancel.".format(templateName)),
                                     QMessageBox.Yes|QMessageBox.No)

        if result == QMessageBox.No:
            return

        status = self._deleteDocument(filePath)

        if status:
            #Remove item from list using model index row number
            selectedDocNameIndices = self.lstDocs.selectionModel(
            ).selectedRows(0)
            row = selectedDocNameIndices[0].row()
            self._docItemModel.removeRow(row)
            self.notifBar.insertInfoNotification(QApplication.translate("TemplateDocumentSelector", \
                                                                         "'{0}' template has been successfully removed".format(templateName)))

        else:
            self.notifBar.insertErrorNotification(QApplication.translate("TemplateDocumentSelector", \
                                                                         "Error: '{0}' template could not be removed".format(templateName)))

    def onAccept(self):
        """
        Slot raised to close the dialog only when a selection has been made by the user.
        """
        self.notifBar.clear()

        if self.documentMapping() == None:
            self.notifBar.insertErrorNotification(QApplication.translate("TemplateDocumentSelector", \
                                                                         "Please select a document"))
            return

        self.accept()

    def _selectedMappings(self):
        """
        Returns the model indices for the selected row.
        """
        selectedDocNameIndices = self.lstDocs.selectionModel().selectedRows(0)
        selectedFilePathIndices = self.lstDocs.selectionModel().selectedRows(1)

        if len(selectedDocNameIndices) == 0:
            return None

        docNameIndex = selectedDocNameIndices[0]
        filePathIndex = selectedFilePathIndices[0]

        return (docNameIndex, filePathIndex)

    def documentMapping(self):
        """
        Returns a tuple containing the selected document name and the corresponding file name.
        """
        mIndices = self._selectedMappings()

        if mIndices == None:
            return None

        docNameItem = self._docItemModel.itemFromIndex(mIndices[0])
        filePathItem = self._docItemModel.itemFromIndex(mIndices[1])

        return (docNameItem.text(), filePathItem.text())

    def _editTemplate(self, templatePath, newName):
        """
        Updates the template document to use the new name.
        """
        templateFile = QFile(templatePath)

        if not templateFile.open(QIODevice.ReadOnly):
            QMessageBox.critical(self, QApplication.translate("TemplateDocumentSelector","Open Operation Error"), \
                                            "{0}\n{1}".format(QApplication.translate("TemplateDocumentSelector","Cannot read template file."), \
                                                      templateFile.errorString()
                                                      ))
            return (False, "")

        templateDoc = QDomDocument()

        if templateDoc.setContent(templateFile):
            composerElement = templateDoc.documentElement()
            titleAttr = composerElement.attributeNode("title")
            if not titleAttr.isNull():
                titleAttr.setValue(newName)

            #Try remove file
            status = templateFile.remove()

            if not status:
                return (False, "")

            #Create new file
            newTemplatePath = self._composerTemplatesPath(
            ) + "/" + newName + ".sdt"
            newTemplateFile = QFile(newTemplatePath)

            if not newTemplateFile.open(QIODevice.WriteOnly):
                QMessageBox.critical(self, QApplication.translate("TemplateDocumentSelector","Save Operation Error"), \
                                                "{0}\n{1}".format(QApplication.translate("TemplateDocumentSelector","Could not save template file."), \
                                                          newTemplateFile.errorString()
                                                          ))
                return (False, "")

            if newTemplateFile.write(templateDoc.toByteArray()) == -1:
                QMessageBox.critical(self, QApplication.translate("TemplateDocumentSelector","Save Error"), \
                                                QApplication.translate("TemplateDocumentSelector","Could not save template file."))
                return (False, "")

            newTemplateFile.close()

            return (True, newTemplatePath)

    def _deleteDocument(self, templatePath):
        """
        Delete the document template from the file system.
        """
        docFile = QFile(templatePath)

        return docFile.remove()

    def _composerTemplatesPath(self):
        """
        Reads the path of composer templates in the registry.
        """
        regConfig = RegistryConfig()
        keyName = "ComposerTemplates"

        valueCollection = regConfig.read([keyName])

        if len(valueCollection) == 0:
            return None

        else:
            return valueCollection[keyName]
Exemplo n.º 46
0
class dbmanagerUI(QMainWindow, ui_dbmanager.Ui_dbmanagerUI):
    """Main UI for MASAR database manager."""
    def __init__(self):
        """"""
        super(dbmanagerUI, self).__init__()
        self.setupUi(self)
        self.statusbar.showMessage("Ready")

        exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit Masar Configuration Manager.')
        exitAction.triggered.connect(QtGui.qApp.quit)

        self.groupdatabasemenubar()

        #default database source, could be 0: SQLite, 1: MongoDB, and 2: MySQL
        self.dbsource = None

        self.defaultdbinfo = self._loadmasarconfig()
        self.usedefaultdb = True

        self.comboxboxSignalMapper = QtCore.QSignalMapper(self)
        self.comboxboxSignalMapper.mapped[QtGui.QWidget].connect(
            self.comboboxSignalMapperMapped)

        self.pushbuttonSignalMapper = QtCore.QSignalMapper(self)
        self.pushbuttonSignalMapper.mapped[QtGui.QWidget].connect(
            self.pushbuttonSignalMapperMapped)

        self.showpvbuttonSignalMapper = QtCore.QSignalMapper(self)
        self.showpvbuttonSignalMapper.mapped[QtGui.QWidget].connect(
            self.showpvbuttonSignalMapperMapped)

        self.choosepvbuttonSignalMapper = QtCore.QSignalMapper(self)
        self.choosepvbuttonSignalMapper.mapped[QtGui.QWidget].connect(
            self.choosepvbuttonSignalMapperMapped)

        self.currentselectedrow4config = -1

        self.selectedsystem = "Others"

        # self.pvgrouptreeview = QTreeView()
        self.pvGroupTreeView.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.pvgroupmodel = QStandardItemModel()
        # self.pvgroupmodel.setHorizontalHeaderLabels(['id', 'date', 'version', "description"])
        self.pvgroupmodel.setHorizontalHeaderLabels(["PV Groups"])
        self.pvGroupTreeView.setModel(self.pvgroupmodel)
        self.pvGroupTreeView.setUniformRowHeights(True)

    @QtCore.pyqtSlot(QtGui.QWidget)
    def comboboxSignalMapperMapped(self, comboBox):
        if self.masarConfigTableWidget.cellWidget(
                comboBox.row, comboBox.column + 1).isEnabled():
            self.masarConfigTableWidget.cellWidget(
                comboBox.row, comboBox.column + 1).setEnabled(False)
            button = self.masarConfigTableWidget.cellWidget(
                comboBox.row, comboBox.column + 1)
            palette = QtGui.QPalette(
                button.palette())  # make a copy of the palette
            palette.setColor(QtGui.QPalette.ButtonText, QtGui.QColor('grey'))
            button.setPalette(palette)
        else:
            self.masarConfigTableWidget.cellWidget(
                comboBox.row, comboBox.column + 1).setEnabled(True)
            button = self.masarConfigTableWidget.cellWidget(
                comboBox.row, comboBox.column + 1)
            palette = QtGui.QPalette(
                button.palette())  # make a copy of the palette
            palette.setColor(QtGui.QPalette.ButtonText, QtGui.QColor('red'))
            button.setPalette(palette)

    @QtCore.pyqtSlot(QtGui.QWidget)
    def pushbuttonSignalMapperMapped(self, pushbutton):
        configstatus = str(
            self.masarConfigTableWidget.cellWidget(
                pushbutton.row, pushbutton.column - 1).currentText())
        cid = str(self.masarConfigTableWidget.item(pushbutton.row, 0).text())
        cname = str(self.masarConfigTableWidget.item(pushbutton.row, 1).text())

        if self.updatemasarconfigstatus(configstatus, cid, configname=cname):
            palette = QtGui.QPalette(
                pushbutton.palette())  # make a copy of the palette
            palette.setColor(QtGui.QPalette.ButtonText, QtGui.QColor('grey'))
            pushbutton.setPalette(palette)
            pushbutton.setEnabled(False)

    @QtCore.pyqtSlot(QtGui.QWidget)
    def showpvbuttonSignalMapperMapped(self, showpvbutton):
        if self.newConfigTableWidget.item(showpvbutton.row,
                                          showpvbutton.column + 2) is None:
            raise RuntimeError("Unknown pv file")
        pvfilename = self.newConfigTableWidget.item(
            showpvbutton.row, showpvbutton.column + 2).text()
        if not os.path.isfile(pvfilename):
            raise RuntimeError(
                "Invalid pv file name for (row, col): (%s, %s)" %
                (showpvbutton.row, showpvbutton.column + 2))

        text = ", ".join(np.loadtxt(str(pvfilename), dtype=str, comments="#"))
        if self.newConfigTableWidget.item(showpvbutton.row, 0) is not None:
            head = self.newConfigTableWidget.item(showpvbutton.row, 0).text()
        else:
            head = ""
        msg = QMessageBox(self,
                          windowTitle='PVs for group %s' % head,
                          text="The following PVs to be added:")
        msg.setDetailedText(text)
        msg.exec_()

    @QtCore.pyqtSlot(QtGui.QWidget)
    def choosepvbuttonSignalMapperMapped(self, chhosepvbutton):
        self.newConfigTableWidget.setItem(
            chhosepvbutton.row, chhosepvbutton.column + 1,
            QTableWidgetItem(QFileDialog.getOpenFileName(self, "Open File")))

    def _loadmasarconfig(self):
        cf = ConfigParser.SafeConfigParser()
        cf.read([
            os.path.expanduser('~/.masarservice.conf'),
            '/etc/masarservice.conf', 'masarservice.conf',
            "%s/masarservice.conf" % os.path.abspath(os.path.dirname(__file__))
        ])
        return cf

    def groupdatabasemenubar(self):
        """Group 3 Databases menu together to make selection exclusive."""
        group = QtGui.QActionGroup(self)
        self.actionSQLite.setActionGroup(group)
        self.actionMongoDB.setActionGroup(group)
        self.actionMySQL.setActionGroup(group)

    def actionsqlitemenu(self):
        """Answer action when SQLite is selected."""
        if self.actionSQLite.isChecked():
            self.dbsource = 0
            self.defaultsqlitedb()
            self.listPvGroupPushButton.setEnabled(True)

    def actionmongodbmenu(self):
        """Answer action when MongoDB is selected."""
        if self.actionMongoDB.isChecked():
            self.dbsource = 1
            self.defaultmongodb()
            self.listPvGroupPushButton.setEnabled(False)

    def actionmysqlmenu(self):
        """Answer action when MySQL is selected."""
        if self.actionMySQL.isChecked():
            QMessageBox.warning(self, 'Warning',
                                "MySQL support not implemented yet.")
            self.actionMySQL.setChecked(False)
            if self.dbsource == 0:
                self.actionSQLite.setChecked(True)
            elif self.dbsource == 1:
                self.actionMongoDB.setChecked(True)

    def showdefaultdbinfo(self):
        """"""
        if self.dbsource == 0:
            self.defaultsqlitedb()
        elif self.dbsource == 1:
            self.defaultmongodb()
        elif self.dbsource == 2:
            QMessageBox.warning(self, 'Warning',
                                "MySQL support not implemented yet.")

    def defaultsqlitedb(self):
        """"""
        if self.defaultdbinfo.has_section("sqlite"):
            self.databaseDefault.setText(
                self.defaultdbinfo.get("sqlite", "database"))
            self.hostDefault.clear()
            self.portDefault.clear()
            self.userDefault.clear()

    def defaultmongodb(self):
        """"""
        if self.defaultdbinfo.has_section("mongodb"):
            self.databaseDefault.setText(
                self.defaultdbinfo.get("mongodb", "database"))
            self.hostDefault.setText(self.defaultdbinfo.get("mongodb", "host"))
            self.portDefault.setText(self.defaultdbinfo.get("mongodb", "port"))
            self.userDefault.setText(
                self.defaultdbinfo.get("mongodb", "username"))

    def getdatabasename(self):
        """"""
        self.database = self.databaseLineEdit.text()

    def getdatabaseport(self):
        """"""
        self.databaseport = self.databaseportLineEdit.text()

    def getdatabasehost(self):
        """"""
        self.databasehost = self.databaseHostLineEdit.text()

    def getdatabasepw(self):
        """"""
        self.databasepw = self.databasePwLineEdit.text()

    def showmasarconfigs(self):
        """"""
        result = None
        if self.dbsource == 0:
            # get data from sqlite
            if self.usedefaultdb:
                # masardb = str(self.databaseDefault.text())
                masardb = str(self.databaseDefault.toPlainText())
            else:
                masardb = str(self.databaseLineEdit.text())

            if masardb != "":
                os.environ["MASAR_SQLITE_DB"] = masardb
            else:
                raise RuntimeError("Cannot find MASAR SQLite Database")

            import pymasarsqlite
            conn = pymasarsqlite.utils.connect()
            result = pymasarsqlite.service.retrieveServiceConfigs(
                conn, servicename="masar")
            pymasarsqlite.utils.close(conn)

        elif self.dbsource == 1:
            # get data from mongodb
            if self.usedefaultdb:
                database = str(self.databaseDefault.toPlainText())
                host = str(self.hostDefault.toPlainText())
                port = str(self.portDefault.toPlainText())
            else:
                database = str(self.databaseLineEdit.text())
                host = str(self.databaseHostLineEdit.text())
                port = str(self.databasePortLineEdit.text())

            import pymasarmongo
            mongoconn, collection = pymasarmongo.db.utils.conn(host=host,
                                                               port=port,
                                                               db=database)
            resultdict = pymasarmongo.pymasarmongo.pymasar.retrieveconfig(
                mongoconn, collection)
            pymasarmongo.db.utils.close(mongoconn)

            result = [['id', 'name', 'desc', 'date', 'version', 'status']]
            for res in resultdict:
                result.append([
                    res['configidx'], res['name'], res['desc'],
                    res['created_on'], res['version'], res['status']
                ])
                # res['system']

        if result is not None:
            self._setconfigtable(result)

    def choosedbsrc(self, bool):
        """Choose DB source"""
        if bool:
            self.usedefaultdb = True
        else:
            self.usedefaultdb = False

    def _setconfigtable(self, content):
        """"""
        # head = self.masarConfigTableWidget.horizontalHeader()
        self.masarConfigTableWidget.clearContents()
        # self.masarConfigTableWidget.setHorizontalHeaderLabels(head)

        if len(content) > 1:
            self.masarConfigTableWidget.setRowCount(len(content) - 1)

            n = 0
            data = sorted(content[1:], key=itemgetter(0), reverse=True)
            for res in data:
                m = 0
                for item in res:
                    if not isinstance(item, basestring):
                        item = str(item)
                    if item:
                        if m == 5:
                            newitem = QtGui.QComboBox()
                            newitem.addItem("active")
                            newitem.addItem("inactive")
                            if item == "active":
                                newitem.setCurrentIndex(0)
                            else:
                                newitem.setCurrentIndex(1)

                            newitem.row = n
                            newitem.column = m
                            self.masarConfigTableWidget.setCellWidget(
                                n, m, newitem)
                            self.comboxboxSignalMapper.setMapping(
                                newitem, newitem)
                            newitem.currentIndexChanged.connect(
                                self.comboxboxSignalMapper.map)

                            updatebutton = QtGui.QPushButton()
                            updatebutton.setText("Update")
                            updatebutton.setEnabled(False)
                            updatebutton.row = n
                            updatebutton.column = m + 1
                            self.pushbuttonSignalMapper.setMapping(
                                updatebutton, updatebutton)
                            self.masarConfigTableWidget.setCellWidget(
                                n, m + 1, updatebutton)
                            updatebutton.clicked.connect(
                                self.pushbuttonSignalMapper.map)
                        else:
                            newitem = QTableWidgetItem(item)
                            newitem.setFlags(Qt.ItemIsEnabled
                                             | Qt.ItemIsSelectable)
                            self.masarConfigTableWidget.setItem(n, m, newitem)
                    m += 1
                n += 1

            self.masarConfigTableWidget.resizeColumnsToContents()

    def updatemasarconfigstatus(self, configstatus, cid, configname=None):
        if self.dbsource == 0:
            # get data from sqlite
            if self.usedefaultdb:
                masardb = str(self.databaseDefault.toPlainText())
            else:
                masardb = str(self.databaseLineEdit.text())

            if masardb != "":
                os.environ["MASAR_SQLITE_DB"] = masardb
            else:
                raise RuntimeError("Cannot find MASAR SQLite Database")

            import pymasarsqlite

            conn = pymasarsqlite.utils.connect()
            pymasarsqlite.service.updateServiceConfigStatus(
                conn, cid, status=configstatus)
            pymasarsqlite.utils.save(conn)
            pymasarsqlite.utils.close(conn)

        elif self.dbsource == 1:
            # get data from mongodb
            if self.usedefaultdb:
                database = str(self.databaseDefault.toPlainText())
                host = str(self.hostDefault.toPlainText())
                port = str(self.portDefault.toPlainText())
            else:
                database = str(self.databaseLineEdit.text())
                host = str(self.databaseHostLineEdit.text())
                port = str(self.databasePortLineEdit.text())

            import pymasarmongo

            mongoconn, collection = pymasarmongo.db.utils.conn(host=host,
                                                               port=port,
                                                               db=database)
            pymasarmongo.pymasarmongo.pymasar.updateconfig(mongoconn,
                                                           collection,
                                                           configname,
                                                           configidx=int(cid),
                                                           status=configstatus)
            pymasarmongo.db.utils.close(mongoconn)

        return True

    def addnewpvgrouprow(self):
        """Add a new row to add pv group to MASAR configuration"""
        print("""Add a new row to add pv group to MASAR configuration""")
        currowcount = self.newConfigTableWidget.rowCount()
        self.newConfigTableWidget.setRowCount(currowcount + 1)

        showpvbutton = QtGui.QPushButton()
        showpvbutton.setText("Show PVs")
        showpvbutton.setEnabled(True)
        showpvbutton.row = currowcount
        showpvbutton.column = 2
        self.showpvbuttonSignalMapper.setMapping(showpvbutton, showpvbutton)
        self.newConfigTableWidget.setCellWidget(currowcount,
                                                showpvbutton.column,
                                                showpvbutton)
        showpvbutton.clicked.connect(self.showpvbuttonSignalMapper.map)

        choosepvbutton = QtGui.QPushButton()
        choosepvbutton.setText("PV File")
        choosepvbutton.setEnabled(True)
        choosepvbutton.row = currowcount
        choosepvbutton.column = 3
        self.choosepvbuttonSignalMapper.setMapping(choosepvbutton,
                                                   choosepvbutton)
        self.newConfigTableWidget.setCellWidget(currowcount,
                                                choosepvbutton.column,
                                                choosepvbutton)
        choosepvbutton.clicked.connect(self.choosepvbuttonSignalMapper.map)

    def removepvgrouprow(self):
        """Remove selected pv group from the configuration to be added into MASAR database"""
        if self.currentselectedrow4config == -1:
            raise RuntimeError("No pv group selected.")
        rownametobedelete = self.newConfigTableWidget.item(
            self.currentselectedrow4config, 0)
        if rownametobedelete is not None:
            rownametobedelete = rownametobedelete.text()
        self.newConfigTableWidget.removeRow(self.currentselectedrow4config)
        if rownametobedelete is not None:
            print("Successfully delete pv group: ", rownametobedelete)
        else:
            print("Successfully delete row: ", self.currentselectedrow4config)
        self.currentselectedrow4config = -1

    def savemasarsqlite(self):
        """"""
        # get data from sqlite
        if self.usedefaultdb:
            masardb = str(self.databaseDefault.toPlainText())
        else:
            masardb = str(self.databaseLineEdit.text())

        if masardb != "":
            os.environ["MASAR_SQLITE_DB"] = masardb
        else:
            QMessageBox.warning(self, "Warning",
                                "Cannot find MASAR SQLite Database")
            return

        import pymasarsqlite
        conn = pymasarsqlite.utils.connect()
        existedresult = pymasarsqlite.service.retrieveServiceConfigs(
            conn, servicename="masar")

        newcfgdata = self._getnewconfigurationdata(existedresult)
        if newcfgdata is None:
            QMessageBox.warning(
                self, "Warning",
                "Not enough information for a new configuration.")
            return
        newcfgname = newcfgdata[0]
        desc = newcfgdata[1]
        msystem = newcfgdata[2]
        # config data format: [[name], [desc], [pv files]]
        cfgdata = newcfgdata[3]

        if newcfgname is None or msystem is None or newcfgdata is None:
            # Nothing to be added.
            QMessageBox.warning(
                self, "Warning",
                "No name or system is given, or empty configuration data.")
            return

        for i in range(len(cfgdata[0])):
            if cfgdata[0][i] is None:
                QMessageBox.warning(self, "Warning", "Wrong PV group name")
                return

            if cfgdata[2][i] is not None and os.path.isfile(cfgdata[2][i]):
                pvs = list(np.loadtxt(cfgdata[2][i], dtype=str, comments="#"))
                if len(pvs) > 0:
                    for j, pv in enumerate(pvs):
                        pvs[j] = pv.strip()
                    pymasarsqlite.pvgroup.savePvGroup(conn,
                                                      cfgdata[0][i],
                                                      func=cfgdata[1][i])
                    pymasarsqlite.pvgroup.saveGroupPvs(conn, cfgdata[0][i],
                                                       pvs)

        try:
            pymasarsqlite.service.saveServiceConfig(conn,
                                                    "masar",
                                                    newcfgname,
                                                    configdesc=desc,
                                                    system=msystem)
            pymasarsqlite.service.saveServicePvGroup(conn, newcfgname,
                                                     cfgdata[0])
        except Exception as e:
            QMessageBox.warning(self, "Error", e.message)
            return

        pymasarsqlite.utils.save(conn)
        QMessageBox.information(
            self, "Congratulation",
            "A new configuration has been added successfully.")
        pymasarsqlite.utils.close(conn)

    def savemasarmongodb(self):
        """"""
        # get data from mongodb
        if self.usedefaultdb:
            database = str(self.databaseDefault.toPlainText())
            host = str(self.hostDefault.toPlainText())
            port = str(self.portDefault.toPlainText())
        else:
            database = str(self.databaseLineEdit.text())
            host = str(self.databaseHostLineEdit.text())
            port = str(self.databasePortLineEdit.text())

        import pymasarmongo

        mongoconn, collection = pymasarmongo.db.utils.conn(host=host,
                                                           port=port,
                                                           db=database)
        existedresult = pymasarmongo.pymasarmongo.pymasar.retrieveconfig(
            mongoconn, collection)
        existedcfg = []
        for res in existedresult:
            existedcfg.append([
                res['configidx'], res['name'], res['desc'], res['created_on'],
                res['version'], res['status']
            ])
        newcfgdata = self._getnewconfigurationdata(existedcfg)
        if newcfgdata is None:
            # Nothing to be added.
            raise ValueError("Empty configuration.")

        newcfgname = newcfgdata[0]
        desc = newcfgdata[1]
        msystem = newcfgdata[2]
        # config data format: [[name], [desc], [pv files]]
        cfgdata = newcfgdata[3]
        pvs = []
        for pvf in cfgdata[2]:
            if pvf is not None and os.path.isfile(pvf):
                pvs += list(np.loadtxt(pvf, dtype=str, comments="#"))
        if pvs:
            for i, pv in enumerate(pvs):
                pvs[i] = pv.strip()
            pymasarmongo.pymasarmongo.pymasar.saveconfig(mongoconn,
                                                         collection,
                                                         newcfgname,
                                                         desc=desc,
                                                         system=msystem,
                                                         pvlist={"names": pvs})
            QMessageBox.information(
                self, "Congratulation",
                "A new configuration has been added successfully.")
        else:
            QMessageBox.warning(self, "Warning",
                                "No PVs available for the new configuration.")

        pymasarmongo.db.utils.close(mongoconn)

    def submitmasarconfig(self):
        """submit a new configuration to MASAR database"""
        if self.dbsource is None:
            QMessageBox.warning(
                self, "Warning",
                "Unknown database source.\nPlease select which database should be use."
            )
            return
        if self.dbsource == 0:
            self.savemasarsqlite()
        elif self.dbsource == 1:
            self.savemasarmongodb()

    def _getnewconfigurationdata(self, existedresult):
        """"""
        newcfgname = self.newConfigurationLineEdit.text()
        if newcfgname is None or str(newcfgname) == "":
            QMessageBox.warning(self, "Warning",
                                "Name of configuration is empty.")
            return None
        elif str(newcfgname) in np.array(existedresult)[:, 1]:
            QMessageBox.warning(
                self, "Warning",
                "Configuration (%s) exists already." % str(newcfgname))
            return None
        else:
            newcfgname = str(newcfgname)
        desc = self.newConfigurationDescription.text()
        if str(desc) == "":
            desc = None
        else:
            desc = str(desc)

        msystem = str(self.systemComboBox.currentText())
        if msystem == "Others":
            msystem = self.systemLineEdit.text()
            if msystem is None or str(msystem) == "":
                QMessageBox.warning(
                    self, "Warning",
                    "System for configuration (%s) not specified yet." %
                    str(newcfgname))
                return None
            else:
                msystem = str(msystem)

        pvgroups = self.newConfigTableWidget.rowCount()
        if pvgroups == 0:
            QMessageBox.warning(
                self, "Warning",
                "No PV founded for new configuration (%s)." % str(newcfgname))
            return None

        pvgroupnames = []
        pvgroupdescs = []
        pvgroupfiles = []
        for count in range(pvgroups):
            # Collect PV group name information
            if self.newConfigTableWidget.item(count, 0) is not None and str(
                    self.newConfigTableWidget.item(count, 0).text()) != "":
                pvgname = str(self.newConfigTableWidget.item(count, 0).text())
                if pvgname in pvgroupnames:
                    QMessageBox.warning(
                        self, "Warning",
                        "Duplicated pv group name: %s." % str(pvgname))
                    return None
                pvgroupnames.append(pvgname)
            elif self.newConfigTableWidget.item(count, 4) is None or str(
                    self.newConfigTableWidget.item(count, 4)) == "":
                continue
            elif self.dbsource == 1:
                pvgroupnames.append(None)
            else:
                QMessageBox.warning(self, "Warning", "Empty pv group name.")
                return None
                # reply = QMessageBox.question(self, "Message",
                #                              "pv group name not specified for row {}.\nContinue?".format(count),
                #                              QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                # if reply == QMessageBox.Yes:
                #     pvgroupnames.append(None)
                # else:
                #     return None

            # Collection PV group descriptions
            if self.newConfigTableWidget.item(count, 1) is not None:
                pvgroupdescs.append(
                    str(self.newConfigTableWidget.item(count, 1).text()))
            else:
                pvgroupdescs.append(None)

            # PV files for the pv group.
            if self.newConfigTableWidget.item(count, 4) is not None:
                pvgroupfiles.append(
                    str(self.newConfigTableWidget.item(count, 4).text()))
            else:
                pvgroupfiles.append(None)

        if pvgroupfiles:
            return newcfgname, desc, msystem, [
                pvgroupnames, pvgroupdescs, pvgroupfiles
            ]
        else:
            return None

    def currentselectedrow(self, row, col):
        """Cache current selected row in MASAR configuration Table Widget."""
        self.currentselectedrow4config = row

    def updateselectedsystem(self, system):
        """Update selected system if value changed"""
        self.selectedsystem = str(system)

    def updatesystemcombobox(self):
        """Update selected system if value changed"""
        self.systemComboBox.clear()
        if self.dbsource == 0:
            # get data from sqlite
            if self.usedefaultdb:
                # masardb = str(self.databaseDefault.text())
                masardb = str(self.databaseDefault.toPlainText())
            else:
                masardb = str(self.databaseLineEdit.text())

            if masardb != "":
                os.environ["MASAR_SQLITE_DB"] = masardb
            else:
                raise RuntimeError("Cannot find MASAR SQLite Database")

            import pymasarsqlite

            conn = pymasarsqlite.utils.connect()
            result = pymasarsqlite.service.retrieveServiceConfigProps(
                conn, propname="system", servicename="masar")
            index = 0
            if len(result) > 1:
                res = sorted(set(list(np.array(result[1:])[:, 3])))
                #for res in result[1:]:
                self.systemComboBox.addItems(res)
                index = len(res)
            self.systemComboBox.addItem("Others")
            self.systemComboBox.setCurrentIndex(index)
            pymasarsqlite.utils.close(conn)

        elif self.dbsource == 1:
            # get data from mongodb
            if self.usedefaultdb:
                database = str(self.databaseDefault.toPlainText())
                host = str(self.hostDefault.toPlainText())
                port = str(self.portDefault.toPlainText())
            else:
                database = str(self.databaseLineEdit.text())
                host = str(self.databaseHostLineEdit.text())
                port = str(self.databasePortLineEdit.text())

            import pymasarmongo

            mongoconn, collection = pymasarmongo.db.utils.conn(host=host,
                                                               port=port,
                                                               db=database)

            result = pymasarmongo.pymasarmongo.pymasar.retrieveconfig(
                mongoconn, collection)
            pymasarmongo.db.utils.close(mongoconn)

            results = []
            for res in result:
                if res["system"] not in results:
                    results.append(res["system"])
            res = sorted(set(results))
            self.systemComboBox.addItems(res)
            index = len(res)
            self.systemComboBox.addItem("Others")
            self.systemComboBox.setCurrentIndex(index)

    def listpvgroups(self):
        """"""
        self.pvgroupmodel.clear()
        self.pvgroupmodel.setHorizontalHeaderLabels(["PV Groups"])
        if self.dbsource == 0:
            # get data from sqlite
            if self.usedefaultdb:
                # masardb = str(self.databaseDefault.text())
                masardb = str(self.databaseDefault.toPlainText())
            else:
                masardb = str(self.databaseLineEdit.text())

            if masardb != "":
                os.environ["MASAR_SQLITE_DB"] = masardb
            else:
                raise RuntimeError("Cannot find MASAR SQLite Database")

            import pymasarsqlite

            conn = pymasarsqlite.utils.connect()
            result = pymasarsqlite.pvgroup.retrievePvGroups(conn)
            if len(result) > 0:
                result = sorted(result, key=itemgetter(0), reverse=True)
            for res in result:
                parent1 = QStandardItem(res[1])
                child1 = QStandardItem('id: {}'.format(res[0]))
                child2 = QStandardItem('description: {}'.format(res[2]))
                child3 = QStandardItem('date: {}'.format(res[3]))
                child4 = QStandardItem('version: {}'.format(res[4]))
                parent1.appendColumn([child1, child2, child3, child4])
                self.pvgroupmodel.appendRow(parent1)
            selmod = self.pvGroupTreeView.selectionModel()
            index2 = self.pvgroupmodel.indexFromItem(child3)
            selmod.select(
                index2, QItemSelectionModel.Select | QItemSelectionModel.Rows)
            pymasarsqlite.utils.close(conn)

            self.pvGroupTreeView.setContextMenuPolicy(Qt.CustomContextMenu)
            self.pvGroupTreeView.clicked.connect(self.showpvsinpvgroup)
            # self.connect(self.pvGroupTreeView,
            #              QtCore.SIGNAL("clicked(QModelIndex)"),
            #              #QtCore.SIGNAL("customContextMenuRequested(const QPoint &)"),
            #              self.doMenu)

        elif self.dbsource == 1:
            # get data from mongodb
            if self.usedefaultdb:
                database = str(self.databaseDefault.toPlainText())
                host = str(self.hostDefault.toPlainText())
                port = str(self.portDefault.toPlainText())
            else:
                database = str(self.databaseLineEdit.text())
                host = str(self.databaseHostLineEdit.text())
                port = str(self.databasePortLineEdit.text())

            import pymasarmongo

    def showpvsinpvgroup(self, point):
        if point.model().itemFromIndex(point).child(0) is None:
            return
        reply = QMessageBox.question(
            self, 'Message', "show all pvs belong to group {} ?".format(
                point.model().itemFromIndex(point).text()),
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            pvgroupidx = int(
                str(point.model().itemFromIndex(point).child(0).text().split(
                    ":")[1]).strip())

            # msg = QMessageBox(self)
            msg = ShowPvMessageBox()
            msg.setWindowTitle('PVs for group {}'.format(
                point.model().itemFromIndex(point).text()))
            msg.setText("Click show details to see all pvs.")
            # windowTitle = 'PVs for group {}'.format(point.model().itemFromIndex(point).text())

            if self.dbsource == 0:
                # get data from sqlite
                if self.usedefaultdb:
                    # masardb = str(self.databaseDefault.text())
                    masardb = str(self.databaseDefault.toPlainText())
                else:
                    masardb = str(self.databaseLineEdit.text())

                if masardb != "":
                    os.environ["MASAR_SQLITE_DB"] = masardb
                else:
                    raise RuntimeError("Cannot find MASAR SQLite Database")

                import pymasarsqlite

                conn = pymasarsqlite.utils.connect()
                result = pymasarsqlite.pvgroup.retrieveGroupPvs(
                    conn, pvgroupidx)
                text = "\n".join(list(np.array(result)[:, 0]))
                msg.setDetailedText(text)
                msg.exec_()

            elif self.dbsource == 1:
                # get data from mongodb
                if self.usedefaultdb:
                    database = str(self.databaseDefault.toPlainText())
                    host = str(self.hostDefault.toPlainText())
                    port = str(self.portDefault.toPlainText())
                else:
                    database = str(self.databaseLineEdit.text())
                    host = str(self.databaseHostLineEdit.text())
                    port = str(self.databasePortLineEdit.text())

                import pymasarmongo
Exemplo n.º 47
0
def get_gds_model(progress=lambda val: None):
    """
    Initialize and return a GDS datasets model.

    :param progress: A progress callback.
    :rval tuple:
        A tuple of (QStandardItemModel, geo.GDSInfo, [geo.GDS])

    .. note::
        The returned QStandardItemModel's thread affinity is set to
        the GUI thread.

    """
    progress(1)
    info = geo.GDSInfo()
    search_keys = ["dataset_id", "title", "platform_organism", "description"]
    cache_dir = serverfiles.localpath(geo.DOMAIN)
    gds_link = "http://www.ncbi.nlm.nih.gov/sites/GDSbrowser?acc={0}"
    pm_link = "http://www.ncbi.nlm.nih.gov/pubmed/{0}"
    gds_list = []

    def is_cached(gds):
        return os.path.exists(
            os.path.join(cache_dir, gds["dataset_id"]) + ".soft.gz")

    def item(displayvalue, item_values={}):
        item = QStandardItem()
        item.setData(displayvalue, Qt.DisplayRole)
        for role, value in item_values.items():
            item.setData(value, role)
        return item

    def gds_to_row(gds):
        #: Text for easier full search.
        search_text = " | ".join(
            [gds.get(key, "").lower() for key in search_keys])
        row = [
            item(" " if is_cached(gds) else "", {TextFilterRole: search_text}),
            item(gds["dataset_id"],
                 {LinkRole: gds_link.format(gds["dataset_id"])}),
            item(gds["title"]),
            item(gds["platform_organism"]),
            item(len(gds["samples"])),
            item(gds["feature_count"]),
            item(gds["gene_count"]),
            item(len(gds["subsets"])),
            item(
                gds.get("pubmed_id", ""), {
                    LinkRole:
                    pm_link.format(gds["pubmed_id"])
                    if gds.get("pubmed_id") else None
                })
        ]
        return row

    model = QStandardItemModel()
    model.setHorizontalHeaderLabels([
        "", "ID", "Title", "Organism", "Samples", "Features", "Genes",
        "Subsets", "PubMedID"
    ])
    progress(20)
    for gds in info.values():
        model.appendRow(gds_to_row(gds))

        gds_list.append(gds)

    progress(50)

    if QThread.currentThread() is not QCoreApplication.instance().thread():
        model.moveToThread(QCoreApplication.instance().thread())
    return model, info, gds_list
Exemplo n.º 48
0
class ListWidget(EditorWidget):
    widgettype = 'List'

    def __init__(self, *args, **kwargs):
        super(ListWidget, self).__init__(*args)
        self.listmodel = QStandardItemModel()
        self._bindvalue = None

    def createWidget(self, parent):
        return QComboBox(parent)

    def _buildfromlist(self, widget, listconfig):
        items = listconfig['items']
        for item in items:
            parts = item.split(';')
            data = parts[0]
            try:
                desc = parts[1]
            except IndexError:
                desc = data

            try:
                path = parts[2]
                path = path.strip()
                icon = QIcon(path)
            except:
                icon = QIcon()

            item = QStandardItem(desc)
            item.setData(data, Qt.UserRole)
            item.setIcon(icon)
            self.listmodel.appendRow(item)

    def _buildfromlayer(self, widget, layerconfig):
        layername = layerconfig['layer']
        keyfield = layerconfig['key']
        valuefield = layerconfig['value']
        filterexp = layerconfig.get('filter', None)

        try:
            layer = QgsMapLayerRegistry.instance().mapLayersByName(
                layername)[0]
        except IndexError:
            roam.utils.warning(
                "Can't find layer {} in project".format(layername))
            return

        keyfieldindex = layer.fieldNameIndex(keyfield)
        valuefieldindex = layer.fieldNameIndex(valuefield)
        if keyfieldindex == -1 or valuefieldindex == -1:
            roam.utils.warning("Can't find key or value column")
            return

        if self.allownulls:
            item = QStandardItem('(no selection)')
            item.setData(None, Qt.UserRole)
            self.listmodel.appendRow(item)

        attributes = {keyfieldindex, valuefieldindex}
        iconfieldindex = layer.fieldNameIndex('icon')
        if iconfieldindex > -1:
            attributes.add(iconfieldindex)

        if not filterexp and valuefieldindex == keyfieldindex and iconfieldindex == -1:
            values = layer.uniqueValues(keyfieldindex)
            for value in values:
                value = nullconvert(value)
                item = QStandardItem(value)
                item.setData(value, Qt.UserRole)
                self.listmodel.appendRow(item)
            return

        flags = QgsFeatureRequest.NoGeometry

        expression = None
        if filterexp:
            expression = QgsExpression(filterexp)
            expression.prepare(layer.pendingFields())
            if expression.hasParserError():
                roam.utils.warning("Expression has parser error: {}".format(
                    expression.parserErrorString()))
                return

            if expression.needsGeometry():
                flags = QgsFeatureRequest.NoFlags

            for field in expression.referencedColumns():
                index = layer.fieldNameIndex(field)
                attributes.add(index)

        request = QgsFeatureRequest().setFlags(flags).setSubsetOfAttributes(
            list(attributes))
        for feature in layer.getFeatures(request):
            if expression and not expression.evaluate(feature):
                continue

            keyvalue = nullconvert(feature[keyfieldindex])
            valuvalue = nullconvert(feature[valuefield])
            try:
                path = feature[iconfieldindex]
                icon = QIcon(path)
            except KeyError:
                icon = QIcon()

            item = QStandardItem(unicode(keyvalue))
            item.setData(unicode(valuvalue), Qt.UserRole)
            item.setIcon(icon)
            self.listmodel.appendRow(item)

    def initWidget(self, widget, config):
        if widget.isEditable():
            widget.editTextChanged.connect(self.emitvaluechanged)

        widget.currentIndexChanged.connect(self.emitvaluechanged)
        widget.setModel(self.listmodel)
        widget.showPopup = self.showpopup
        widget.setIconSize(QSize(24, 24))
        widget.setStyleSheet(
            "QComboBox::drop-down {border-width: 0px;} QComboBox::down-arrow {image: url(noimg); border-width: 0px;}"
        )
        widget.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLength)

    def showpopup(self):
        if self.listmodel.rowCount() == 0:
            return

        self.largewidgetrequest.emit(
            BigListWidget, self.widget.currentIndex(), self._biglistitem,
            dict(model=self.listmodel, label=self.labeltext))

    def updatefromconfig(self):
        super(ListWidget, self).updatefromconfig()

        self.listmodel.clear()
        if 'list' in self.config:
            listconfig = self.config['list']
            self._buildfromlist(self.widget, listconfig)
        elif 'layer' in self.config:
            layerconfig = self.config['layer']
            self._buildfromlayer(self.widget, layerconfig)

        super(ListWidget, self).endupdatefromconfig()

    @property
    def allownulls(self):
        return self.config.get('allownull', False)

    def validate(self, *args):
        if (not self.widget.currentText() == ''
                and not self.widget.currentText() == "(no selection)"):
            return True
        else:
            return False

    def _biglistitem(self, index):
        self.widget.setCurrentIndex(index.row())

    def setvalue(self, value):
        self._bindvalue = value
        index = self.widget.findData(value)
        self.widget.setCurrentIndex(index)
        if index == -1 and self.widget.isEditable():
            if value is None and not self.config['allownull']:
                return

            self.widget.addItem(str(value))
            index = self.widget.count() - 1
            self.widget.setCurrentIndex(index)

    def value(self):
        index = self.widget.currentIndex()
        value = self.widget.itemData(index)
        text = self.widget.currentText()
        if value is None and self.widget.isEditable(
        ) and not text == '(no selection)':
            return self.widget.currentText()

        return value
Exemplo n.º 49
0
class MultipleSelectTreeView(QListView):
    """
    Custom QListView implementation that displays checkable items from a
    multiple select column type.
    """
    def __init__(self, column, parent=None):
        """
        Class constructor.
        :param column: Multiple select column object.
        :type column: MultipleSelectColumn
        :param parent: Parent widget for the control.
        :type parent: QWidget
        """
        QListView.__init__(self, parent)

        #Disable editing of lookup values
        self.setEditTriggers(QAbstractItemView.NoEditTriggers)

        self.column = column

        self._item_model = QStandardItemModel(self)

        self._value_list = self.column.value_list

        #Stores lookup objects based on primary keys
        self._lookup_cache = {}

        self._initialize()

        self._association = self.column.association

        self._first_parent_col = self._association.first_reference_column.name
        self._second_parent_col = self._association.second_reference_column.name

        #Association model
        self._assoc_cls = entity_model(self._association)

    def reset_model(self):
        """
        Resets the item model.
        """
        self._item_model.clear()
        self._item_model.setColumnCount(2)

    def clear(self):
        """
        Clears all items in the model.
        """
        self._item_model.clear()

    @property
    def association(self):
        """
        :return: Returns the association object corresponding to the column.
        :rtype: AssociationEntity
        """
        return self._association

    @property
    def value_list(self):
        """
        :return: Returns the ValueList object corresponding to the configured
        column object.
        :rtype: ValueList
        """
        return self._value_list

    @property
    def item_model(self):
        """
        :return: Returns the model corresponding to the checkable items.
        :rtype: QStandardItemModel
        """
        return self._item_model

    def _add_item(self, id, value):
        """
        Adds a row corresponding to id and corresponding value from a lookup
        table.
        :param id: Primary key of a lookup record.
        :type id: int
        :param value: Lookup value
        :type value: str
        """
        value_item = QStandardItem(value)
        value_item.setCheckable(True)
        id_item = QStandardItem(str(id))

        self._item_model.appendRow([value_item, id_item])

    def _initialize(self):
        #Populate list with lookup items
        self.reset_model()

        #Add all lookup values in the value list table
        vl_cls = entity_model(self._value_list)
        if not vl_cls is None:
            vl_obj = vl_cls()
            res = vl_obj.queryObject().all()
            for r in res:
                self._lookup_cache[r.id] = r
                self._add_item(r.id, r.value)

        self.setModel(self._item_model)

    def clear_selection(self):
        """
        Unchecks all items in the view.
        """
        for i in range(self._item_model.rowCount()):
            value_item = self._item_model.item(i, 0)

            if value_item.checkState() == Qt.Checked:
                value_item.setCheckState(Qt.Unchecked)

                if value_item.rowCount() > 0:
                    value_item.removeRow(0)

    def selection(self):
        """
        :return: Returns a list of selected items.
        :rtype: list
        """
        selection = []

        for i in range(self._item_model.rowCount()):
            value_item = self._item_model.item(i, 0)

            if value_item.checkState() == Qt.Checked:
                id_item = self._item_model.item(i, 1)
                id = int(id_item.text())

                #Get item from the lookup cache and append to selection
                if id in self._lookup_cache:
                    lookup_rec = self._lookup_cache[id]
                    selection.append(lookup_rec)

        return selection

    def set_selection(self, models):
        """
        Checks items corresponding to the specified models.
        :param models: List containing model values in the view for selection.
        :type models: list
        """
        for m in models:
            search_value = m.value
            v_items = self._item_model.findItems(search_value)

            #Loop through result and check items
            for vi in v_items:
                if vi.checkState() == Qt.Unchecked:
                    vi.setCheckState(Qt.Checked)
Exemplo n.º 50
0
class GroupPhotoWindow(QMainWindow, Ui_main_win):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setupUi(self)

        self.image_model = QStandardItemModel()
        self.image_list.setModel(self.image_model)

        QObject.connect(self.add_btn, QtCore.SIGNAL('clicked()'),
                        self.on_add_image)
        QObject.connect(self.delete_btn, QtCore.SIGNAL('clicked()'),
                        self.on_remove_image)
        QObject.connect(
            self.image_list.selectionModel(),
            QtCore.SIGNAL(
                'currentChanged (const QModelIndex &, const QModelIndex &)'),
            self.on_row_changed)
        QObject.connect(self.harris_btn, QtCore.SIGNAL('clicked()'),
                        self.on_harris_detect)
        QObject.connect(self.stitch_btn, QtCore.SIGNAL('clicked()'),
                        self.on_stitch)

    def on_add_image(self):
        image_path = QFileDialog.getOpenFileName(
            self, 'Select image', filter='Images (*.png *.jpg *.bmp)')
        ignored, name = os.path.split(unicode(image_path))
        self.image_model.appendRow(
            [QStandardItem(name),
             QStandardItem(image_path)])

    def on_remove_image(self):
        row = self.image_list.selectionModel().currentIndex().row()
        if row == -1:
            return
        self.image_model.removeRows(row, 1)

    def on_row_changed(self, current, previous):
        row = current.row()
        if row == -1:
            file_path = PLACE_HOLDER
        else:
            file_path = self.image_model.item(row, 1).text()
        self.set_pixmap(QPixmap(file_path))

    def on_harris_detect(self):
        row = self.image_list.selectionModel().currentIndex().row()
        if row == -1:
            return
        file_path = self.image_model.item(row, 1).text()

        image_pfm = convert_to_pfm(imread(unicode(file_path)))
        image = image_to_gray(image_pfm)
        kernel = self.ksize_slider.value()
        cornerness = harris_corner(image, ksize=kernel)
        is_corner = cornerness > 0.000001
        suppress = non_max_suppression(cornerness, ksize=kernel)
        result = np.array(is_corner * suppress)
        zero = np.zeros_like(result)
        gray_img = np.dstack((zero, zero, draw_cross(result)))

        self.set_pixmap(
            QPixmap.fromImage(
                image_from_ndarray(np.array(gray_img + image_pfm))))

    def on_stitch(self):
        i = 0
        images = []
        while self.image_model.item(i):
            file_path = self.image_model.item(i, 1).text()
            image = image_to_gray(convert_to_pfm(imread(unicode(file_path))))
            images.append(image)
            i += 1
        stitch(self.ksize_slider.value(), images)

    def set_pixmap(self, pixmap):
        self.image_label.setPixmap(
            pixmap.scaled(self.image_label.size(), QtCore.Qt.KeepAspectRatio))
Exemplo n.º 51
0
class TreeView(QTreeView):
    def __init__(self, parent):
        QTreeView.__init__(self, parent)
        while not isinstance(parent, QDialog) and not isinstance(parent, QMainWindow):
            parent = parent.parent()
        self.setObjectName("TreeView" + str(len(parent.findChildren(TreeView))))

        # self.setObjectName("TreeViewWidget")
        # self.hLayout = QHBoxLayout(self)
        # self.hLayout.setObjectName("hLayout")
        # 
        # sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        # sizePolicy.setHorizontalStretch(0)
        # sizePolicy.setVerticalStretch(0)
        # sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        # self.setSizePolicy(sizePolicy)
        # 
        # # self.frame = Frame()
        # self = QTreeView(self)
        # self.hLayout.addWidget(self)

        self.stdModel = QStandardItemModel()
        self.setModel(self.stdModel)

        self.hasObject = False
        self.treeNodeList = []

        self.checkBoxList = []
        self.setHeaderHidden(True)
        # self.stdModel.appendRow(TreeNode("P"))
        # rootIndex = self.rootIndex()

        # rootItem = self.stdModel.itemFromIndex(rootIndex)
        # rootItem.setText("Root")

    def mouseMoveEvent(self, mouseEvent):
        pt = mouseEvent.pos()
        pass
    def Clear(self):
        self.stdModel.clear()
        self.hasObject = False
        self.treeNodeList = []
    def Add(self, caption):
        item = TreeNode(caption)
        if len(self.treeNodeList) > 0:
            item.PrevNode = self.treeNodeList[len(self.treeNodeList) - 1]
            item.PrevNode.NextNode = item
            item.Index = len(self.treeNodeList)
        # item.nodeIndex = len(self.treeNodeList)
        self.treeNodeList.append(item)
        self.stdModel.appendRow(item)
        return item
    def RemoveNode(self, i):
        self.stdModel.removeRow(i)
        self.treeNodeList.pop(i)
        for j in range(i, len(self.treeNodeList)):
            self.treeNodeList[j].nodeIndex -= 1
    def Remove(self, item):
        removedIndex = self.treeNodeList.index(item)
        if removedIndex == 0:
            self.treeNodeList[1].PrevNode = None
        elif removedIndex == len(self.treeNodeList) - 1:
            self.treeNodeList[len(self.treeNodeList) - 2].NextNode = None
        else:
            self.treeNodeList[removedIndex + 1].PrevNode = self.treeNodeList[removedIndex - 1]
            self.treeNodeList[removedIndex - 1].NextNode = self.treeNodeList[removedIndex + 1]
        self.treeNodeList.pop(removedIndex)
        self.stdModel.removeRow(removedIndex)
        i = 0
        for node in self.treeNodeList:
            node.Index = i
            node.LastNode = self.treeNodeList[len(self.treeNodeList) - 1]
            i += 1
    def Insert(self, index, text):
        if index == 0 and len(self.treeNodeList) == 0:
            self.Add(text)
            return
        node = TreeNode(text)
        node.Parent = self
        self.treeNodeList.insert(index, node)
        i = 0
        for node0 in self.treeNodeList:
            node0.Index = i
            i += 1
        if index == 0:
            self.treeNodeList[index].PrevNode = None
            if len(self.treeNodeList) == 1:
                self.treeNodeList[index].NextNode = None
                self.treeNodeList[index].LastNode = self.treeNodeList[index]
            else:
                self.treeNodeList[index].NextNode = self.treeNodeList[index + 1]
                self.treeNodeList[index].LastNode = self.treeNodeList[len(self.treeNodeList) - 1]
            
            self.treeNodeList[index + 1].PrevNode = self.treeNodeList[index]
            
        else:
            self.treeNodeList[index].PrevNode = self.treeNodeList[index - 1]
            self.treeNodeList[index].NextNode = self.treeNodeList[index + 1]
            self.treeNodeList[index].LastNode = self.treeNodeList[len(self.treeNodeList) - 1]
            
            self.treeNodeList[index + 1].PrevNode = self.treeNodeList[index]
            self.treeNodeList[index - 1].NextNode = self.treeNodeList[index]
            

        self.stdModel.insertRow(index, node)
        return node

    def get_Items(self):
        return self.treeNodeList
    Nodes = property(get_Items, None, None, None)

    def Node(self, index):
        if not self.stdModel.rowCount() > 0:
            return None
        return self.treeNodeList[index]

    def getSelectedNode(self):
        if not self.stdModel.rowCount() > 0:
            return None
        index = self.currentIndex()
        return self.stdModel.itemFromIndex(index)
    def setSelectedNode(self, node):
        if not self.stdModel.rowCount() > 0:
            return
        # self.s
        index = self.stdModel.indexFromItem(node)
        self.setCurrentIndex(index)
        # self.treeNodeList.pop(index)
        # self.treeNodeList.insert(index, node)
        # self.stdModel.setItem(index, node)

    SelectedNode = property(getSelectedNode, setSelectedNode, None, None)




    def get_Enabled(self):
        return self.isEnabled()
    def set_Enabled(self, bool):
        self.setEnabled(bool)
    Enabled = property(get_Enabled, set_Enabled, None, None)

    def get_Visible(self):
        return self.isVisible()
    def set_Visible(self, bool):
        self.setVisible(bool)
    Visible = property(get_Visible, set_Visible, None, None)
Exemplo n.º 52
0
class ObstacleTable(QSortFilterProxyModel):

    MocMultiplier = 1
    SelectionMode = SelectionModeType.Automatic

    def __init__(self, surfacesList, fileWriter=None):
        QSortFilterProxyModel.__init__(self)
        ObstacleTable.SelectionMode = SelectionModeType.Automatic
        self.manualPolygon = None
        self.surfacesList = surfacesList
        self.surfaceType = None
        self.source = QStandardItemModel()
        self.setSourceModel(self.source)
        #         tableView.hideColumn(self.IndexObjectId)
        #         tableView.hideColumn(self.IndexLayerId)
        #         tableView.hideColumn(self.IndexX)
        #         tableView.hideColumn(self.IndexY)
        #         tableView.hideColumn(self.IndexLat)
        #         tableView.hideColumn(self.IndexLon)
        #         tableView.hideColumn(self.IndexSurface)
        self.hideColumnLabels = [
            ObstacleTableColumnType.ObjectId, ObstacleTableColumnType.LayerId,
            ObstacleTableColumnType.X, ObstacleTableColumnType.Y,
            ObstacleTableColumnType.Lat, ObstacleTableColumnType.Lon,
            ObstacleTableColumnType.Surface
        ]

        self.fixedColumnLabels = [
            ObstacleTableColumnType.ObjectId, ObstacleTableColumnType.LayerId,
            ObstacleTableColumnType.Name, ObstacleTableColumnType.X,
            ObstacleTableColumnType.Y, ObstacleTableColumnType.Lat,
            ObstacleTableColumnType.Lon, ObstacleTableColumnType.AltM,
            ObstacleTableColumnType.AltFt, ObstacleTableColumnType.TreesM,
            ObstacleTableColumnType.TreesFt
        ]

        self.IndexObjectId = 0
        self.IndexLayerId = 1
        self.IndexName = 2
        self.IndexX = 3
        self.IndexY = 4
        self.IndexLat = 5
        self.IndexLon = 6
        self.IndexAltM = 7
        self.IndexAltFt = 8
        self.IndexTreesM = 9
        self.IndexTreesFt = 10
        self.IndexOcaM = -1
        self.IndexOcaFt = -1
        self.IndexOchM = -1
        self.IndexOchFt = -1
        self.IndexObstArea = -1
        self.IndexDistInSecM = -1
        self.IndexMocAppliedM = -1
        self.IndexMocAppliedFt = -1
        self.IndexMocMultiplier = -1
        self.IndexMocReqM = -1
        self.IndexMocReqFt = -1
        self.IndexDoM = -1
        self.IndexDrM = -1
        self.IndexDzM = -1
        self.IndexDxM = -1
        self.IndexDsocM = -1
        self.IndexHeightLossM = -1
        self.IndexHeightLossFt = -1
        self.IndexAcAltM = -1
        self.IndexAcAltFt = -1
        self.IndexAltReqM = -1
        self.IndexAltReqFt = -1
        self.IndexCritical = -1
        self.IndexMACG = -1
        self.IndexPDG = -1
        self.IndexSurfAltM = -1
        self.IndexSurfAltFt = -1
        self.IndexDifferenceM = -1
        self.IndexDifferenceFt = -1
        self.IndexIlsX = -1
        self.IndexIlsY = -1
        self.IndexEqAltM = -1
        self.IndexEqAltFt = -1
        self.IndexSurfaceName = -1
        self.IndexDisregardable = -1
        self.IndexCloseIn = -1
        self.IndexTag = -1
        self.IndexSurface = -1
        self.IndexArea = -1
        self.IndexHLAppliedM = -1
        self.setHeaderLabels()
        self.setFilterKeyColumn(self.IndexSurface)
        self.setSortRole(Qt.UserRole + 1)
        self.layoutChanged.connect(self.setVerticalHeader)
        self.btnLocate = None
        self.tblObstacles = None

    def FilterDisregardableObstacles(self, state):
        if state:
            self.setFilterKeyColumn(self.IndexDisregardable)
            self.setFilterFixedString("Yes")
            self.setFilterKeyColumn(self.IndexSurface)

    def setSurfaceType(self, surfaceType):
        self.surfaceType = surfaceType

    def setFilterFixedString(self, filterString):
        QSortFilterProxyModel.setFilterFixedString(self, filterString)
        self.setVerticalHeader()
        if self.btnLocate != None and self.tblObstacles != None:
            selectedIndexes = self.tblObstacles.selectedIndexes()
            if len(selectedIndexes) == 0:
                self.btnLocate.setEnabled(False)
            else:
                self.btnLocate.setEnabled(True)

    def setLocateBtn(self, btnLocate):
        self.btnLocate = btnLocate
        self.btnLocate.setEnabled(False)
        self.btnLocate.clicked.connect(self.btnLocateClicked)

    def btnLocateClicked(self):
        if self.tblObstacles == None:
            return
        selectedIndexes = self.tblObstacles.selectedIndexes()
        self.locate(selectedIndexes)

    def tblObstaclesClicked(self, idx):
        if len(self.tblObstacles.selectedIndexes()) > 0:
            self.btnLocate.setEnabled(True)

    def setTableView(self, tblObstacles):
        self.tblObstacles = tblObstacles
        self.tblObstacles.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.tblObstacles.setSortingEnabled(True)
        self.tblObstacles.clicked.connect(self.tblObstaclesClicked)
        self.tblObstacles.verticalHeader().sectionClicked.connect(
            self.tblObstaclesClicked)
        pass

    def setHeaderLabels(self):
        #         print self.setHeaderData(1, Qt.Vertical, 1, Qt.DisplayRole)
        pass

    def setVerticalHeader(self):
        for i in range(self.rowCount()):
            self.setHeaderData(i, Qt.Vertical, i + 1, Qt.DisplayRole)

    def setHiddenColumns(self, tableView):
        tableView.hideColumn(self.IndexObjectId)
        tableView.hideColumn(self.IndexLayerId)
        tableView.hideColumn(self.IndexX)
        tableView.hideColumn(self.IndexY)
        tableView.hideColumn(self.IndexLat)
        tableView.hideColumn(self.IndexLon)
        tableView.hideColumn(self.IndexSurface)

    def getExtentForLocate(self, sourceRow):
        extent = None
        surfaceType = None
        if self.IndexSurface < 0:
            surfaceType = self.surfaceType
        else:
            surfaceType = self.source.item(sourceRow, self.IndexSurface).text()
        surfaceLayers = QgisHelper.getSurfaceLayers(self.surfaceType)
        for sfLayer in surfaceLayers:
            lId = sfLayer.name()
            if lId.contains(surfaceType):
                extent = sfLayer.extent()
                break
        return extent

    def clear(self):
        self.source.clear()
        self.source.setHorizontalHeaderLabels(self.fixedColumnLabels)
#         self.setHeaderLabels()

    def locate(self, selectedRowIndexes):
        if selectedRowIndexes == None or len(selectedRowIndexes) <= 0:
            return
        sourceRow = self.mapToSource(selectedRowIndexes[0]).row()
        objectId = int(self.source.item(sourceRow, self.IndexObjectId).text())
        layerId = self.source.item(sourceRow, self.IndexLayerId).text()
        QgisHelper.selectFeature(layerId, objectId)
        layer = QgsMapLayerRegistry.instance().mapLayer(layerId)
        crs = define._canvas.mapSettings().destinationCrs()
        if crs.mapUnits() == QGis.Meters:
            x = float(self.source.item(sourceRow, self.IndexX).text())
            y = float(self.source.item(sourceRow, self.IndexY).text())
            extent = QgsRectangle(x - 350, y - 350, x + 350, y + 350)
        else:
            x, result1 = self.source.item(sourceRow,
                                          self.IndexLon).data().toDouble()
            y, result2 = self.source.item(sourceRow,
                                          self.IndexLat).data().toDouble()
            extent = QgsRectangle(x - 0.005, y - 0.005, x + 0.005, y + 0.005)
        point = QgsPoint(x, y)
        # extent = self.getExtentForLocate(sourceRow)

        if extent is None:
            return

        QgisHelper.zoomExtent(point, extent, 2)
        pass

    def loadObstacles(self, surfaceLayers):
        if self.source.rowCount() > 0:
            self.source.clear()
            self.source.setHorizontalHeaderLabels(self.fixedColumnLabels)
        demEvaluateAg = None
        existingDemFlag = False
        obstacleLayersDEM = QgisHelper.getSurfaceLayers(SurfaceTypes.DEM)
        obstacleLayers = QgisHelper.getSurfaceLayers(SurfaceTypes.Obstacles)
        if obstacleLayersDEM != None and len(obstacleLayersDEM) > 0:
            if QMessageBox.question(
                    None, "Question",
                    "Do you want to use DEM for evaluating Obstacle?",
                    QMessageBox.Yes | QMessageBox.No) == QMessageBox.Yes:
                self.loadObstaclesDEM(obstacleLayersDEM, surfaceLayers)
        if obstacleLayers != None and len(obstacleLayers) > 0:
            #             if QMessageBox.question(None, "Question", "Do you want to use DEM for evaluating Obstacle?", QMessageBox.Yes | QMessageBox.No) == QMessageBox.No:
            self.loadObstaclesVector(obstacleLayers, surfaceLayers)
        return True

    def loadObstaclesDEM(self, obstacleLayersDEM, surfaceLayers):
        progressMessageBar = define._messagBar.createMessage(
            "Loading DEM Obstacles...")
        self.progress = QProgressBar()
        self.progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        progressMessageBar.layout().addWidget(self.progress)
        define._messagBar.pushWidget(progressMessageBar,
                                     define._messagBar.INFO)
        maxium = 0
        offset = 0.0
        self.progress.setValue(0)
        wCount = 0
        hCount = 0
        for ly in obstacleLayersDEM:
            demDataProvider = ly.dataProvider()
            boundDem = demDataProvider.extent()
            xMin = boundDem.xMinimum()
            xMax = boundDem.xMaximum()
            yMin = boundDem.yMinimum()
            yMax = boundDem.yMaximum()
            bound = QgisHelper.getIntersectExtent(
                ly, QgsGeometry.fromRect(boundDem), surfaceLayers)
            #             boundGeom = QgsGeometry.fromRect(bound)
            if bound == None:
                continue
            block = ly.dataProvider().block(0, ly.extent(), ly.width(),
                                            ly.height())
            xMinimum = ly.dataProvider().extent().xMinimum()
            yMaximum = ly.dataProvider().extent().yMaximum()
            yMinimum = ly.dataProvider().extent().yMinimum()
            xMaximum = ly.dataProvider().extent().xMaximum()

            xOffSet = ly.extent().width() / ly.width()
            yOffSet = ly.extent().height() / ly.height()
            offset = xOffSet
            if bound.xMinimum() < xMinimum:
                wStartNumber = 0
                xStartValue = xMinimum
            else:
                wStartNumber = int((bound.xMinimum() - xMinimum) / xOffSet)
                xStartValue = bound.xMinimum()
            if yMaximum < bound.yMaximum():
                hStartNumber = 0
                yStartValue = yMaximum
            else:
                hStartNumber = int((yMaximum - bound.yMaximum()) / yOffSet)
                yStartValue = bound.yMaximum()

            if bound.xMaximum() > xMaximum:
                xEndValue = xMaximum
            else:
                xEndValue = bound.xMaximum()
            if yMinimum > bound.yMinimum():
                yEndValue = yMinimum
            else:
                yEndValue = bound.yMinimum()
            wCount = int(math.fabs(xEndValue - xStartValue) / xOffSet)
            hCount = int(math.fabs(yEndValue - yStartValue) / yOffSet)

            pixelCount = hCount
            maxium += pixelCount

        cellSizeWnd = cellsizeWnd(offset, wCount * hCount, maxium * 0.04)
        cellSizeWnd.setWindowTitle("Input Cell Size")
        result = cellSizeWnd.exec_()
        cellRate = 1
        if result == 1:
            offset = cellSizeWnd.cellsize
            maxium = cellSizeWnd.cellCount + 2
            cellRate = cellSizeWnd.cellRate


#             print cellSizeWnd.textedit1.text()

        if maxium == 0:
            return False
        self.progress.setMaximum(maxium)

        trees = define._treesDEM
        tolerance = define._toleranceDEM

        for obstacleLayer in obstacleLayersDEM:
            obstacleUnits = obstacleLayer.crs().mapUnits()
            demDataProvider = obstacleLayer.dataProvider()
            boundDem = demDataProvider.extent()
            bound = QgisHelper.getIntersectExtent(
                obstacleLayer, QgsGeometry.fromRect(boundDem), surfaceLayers)
            if bound == None:
                continue
            boundGeom = QgsGeometry.fromRect(bound)
            if not boundGeom.intersects(QgsGeometry.fromRect(boundDem)):
                continue
            block = obstacleLayer.dataProvider().block(1,
                                                       obstacleLayer.extent(),
                                                       obstacleLayer.width(),
                                                       obstacleLayer.height())
            xMinimum = obstacleLayer.extent().xMinimum()
            yMaximum = obstacleLayer.extent().yMaximum()
            yMinimum = obstacleLayer.extent().yMinimum()
            xMaximum = obstacleLayer.extent().xMaximum()

            xOffSet = obstacleLayer.extent().width() / obstacleLayer.width()
            yOffSet = obstacleLayer.extent().height() / obstacleLayer.height()

            if bound.xMinimum() < xMinimum:
                hStartNumber = 0
                xStartValue = xMinimum
            else:
                hStartNumber = int((bound.xMinimum() - xMinimum) / xOffSet)
                xStartValue = bound.xMinimum()
            if yMaximum < bound.yMaximum():
                wStartNumber = 0
                yStartValue = yMaximum
            else:
                wStartNumber = int((yMaximum - bound.yMaximum()) / yOffSet)
                yStartValue = bound.yMaximum()

            if bound.xMaximum() > xMaximum:
                xEndValue = xMaximum
            else:
                xEndValue = bound.xMaximum()
            if yMinimum > bound.yMinimum():
                yEndValue = yMinimum
            else:
                yEndValue = bound.yMinimum()
            wCount = int(math.fabs(xEndValue - xStartValue) / offset)
            hCount = int(math.fabs(yEndValue - yStartValue) / offset)

            xPixelWidth = 0.0
            yPixelWidth = 0.0
            featureID = 0
            # i = 0
            # k = 0
            # altitudeList = []
            # self.progress.setValue(0)
            # while i  <=  hCount - 1:
            #     j = 0
            #     while j <= wCount - 1:
            #         if block.isNoData(j * int(cellRate) + wStartNumber, i* int(cellRate) + hStartNumber):
            #             self.progress.setValue(k)
            #             QApplication.processEvents()
            #             j += 1
            #             k += 1
            #             altitudeList.append(None)
            #             continue
            #         altitude = block.value(j * int(cellRate) + wStartNumber, i * int(cellRate) + hStartNumber)
            #         altitudeList.append(altitude)
            #         self.progress.setValue(k)
            #         QApplication.processEvents()
            #         j += 1
            #         k += 1
            #     i += 1

            i = 0
            k = 0
            name = "DEM"
            semiXoffset = xOffSet / 2
            semiYoffset = yOffSet / 2
            while i <= hCount - 1:
                j = 0
                while j <= wCount - 1:
                    if block.isNoData(j * cellRate + wStartNumber,
                                      i * cellRate + hStartNumber):
                        self.progress.setValue(k)
                        QApplication.processEvents()
                        j += 1
                        k += 1
                        continue
                    altitude = block.value(j * cellRate + wStartNumber,
                                           i * cellRate + hStartNumber)
                    # # if block.isNoData(j * int(cellRate) + wStartNumber, i* int(cellRate) + hStartNumber):
                    # #     j += 1
                    # #     self.progress.setValue(self.progress.value() + 1)
                    # #     QApplication.processEvents()
                    # #     continue
                    # # altitude = block.value(j* int(cellRate) + wStartNumber, i* int(cellRate)+ hStartNumber)
                    # altitude = altitudeList[k]
                    # if altitude == None:
                    #     self.progress.setValue(k)
                    #     QApplication.processEvents()
                    #     j += 1
                    #     k += 1
                    #     continue

                    point = QgsPoint(
                        xStartValue + (i * cellRate) * xOffSet + semiXoffset,
                        yStartValue - (j * cellRate - 1) * yOffSet -
                        semiYoffset)
                    position = Point3D()
                    positionDegree = Point3D()

                    if define._canvas.mapUnits() == QGis.Meters:
                        if define._canvas.mapSettings().destinationCrs(
                        ) != obstacleLayer.crs():
                            position = QgisHelper.CrsTransformPoint(
                                point.x(), point.y(), obstacleLayer.crs(),
                                define._canvas.mapSettings().destinationCrs(),
                                altitude)
                        else:
                            position = Point3D(point.x(), point.y(), altitude)
                    else:
                        if define._canvas.mapSettings().destinationCrs(
                        ) != obstacleLayer.crs():
                            positionDegree = QgisHelper.CrsTransformPoint(
                                point.x(), point.y(), obstacleLayer.crs(),
                                define._canvas.mapSettings().destinationCrs(),
                                altitude)
                        else:
                            positionDegree = Point3D(point.x(), point.y(),
                                                     altitude)
                    obstacle = Obstacle(name, position, obstacleLayer.id(),
                                        featureID, None, trees,
                                        ObstacleTable.MocMultiplier, tolerance)
                    obstacle.positionDegree = positionDegree
                    if self.manualPolygon != None:
                        if not self.manualPolygon.contains(obstacle.Position):
                            continue
                    self.checkObstacle(obstacle)
                    self.progress.setValue(k)
                    QApplication.processEvents()
                    j += 1
                    featureID += 1
                    k += 1
                i += 1
        self.progress.setValue(maxium)
        define._messagBar.hide()
        self.manualPolygon = None

    def loadObstaclesVector(self, obstacleLayers, surfaceLayers):
        progressMessageBar = define._messagBar.createMessage(
            "Loading Vector Obstacles...")
        self.progress = QProgressBar()
        self.progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        progressMessageBar.layout().addWidget(self.progress)
        define._messagBar.pushWidget(progressMessageBar,
                                     define._messagBar.INFO)
        maxium = 0
        self.progress.setValue(0)
        for ly in obstacleLayers:
            maxium += ly.featureCount()

        if maxium == 0:
            return False
        self.progress.setMaximum(maxium)

        for obstacleLayer in obstacleLayers:
            obstacleUnits = obstacleLayer.crs().mapUnits()
            features = QgisHelper.getFeaturesInLayerExtent(
                define._canvas, obstacleLayer, surfaceLayers,
                SelectionModeType.Automatic)
            #             print len(features)
            for feature in features:
                name = feature.attribute("Name").toString()
                altitude = feature.attribute("Altitude").toFloat()[0]
                trees = define._trees
                tolerance = define._tolerance
                point = feature.geometry().asPoint()
                position = Point3D()
                positionDegree = Point3D()
                if define._canvas.mapUnits() == QGis.Meters:
                    if define._canvas.mapSettings().destinationCrs(
                    ) != obstacleLayer.crs():
                        position = QgisHelper.CrsTransformPoint(
                            point.x(), point.y(), obstacleLayer.crs(),
                            define._canvas.mapSettings().destinationCrs(),
                            altitude)
                    else:
                        position = Point3D(point.x(), point.y(), altitude)
                else:
                    if define._canvas.mapSettings().destinationCrs(
                    ) != obstacleLayer.crs():
                        positionDegree = QgisHelper.CrsTransformPoint(
                            point.x(), point.y(), obstacleLayer.crs(),
                            define._canvas.mapSettings().destinationCrs(),
                            altitude)
                    else:
                        positionDegree = Point3D(point.x(), point.y(),
                                                 altitude)
                featureId = feature.id()
                layerId = obstacleLayer.id()
                obstacle = Obstacle(name, position, layerId, featureId, None,
                                    trees, ObstacleTable.MocMultiplier,
                                    tolerance)
                obstacle.positionDegree = positionDegree
                #                 obstacle.positionDegree = positionDegree
                self.checkObstacle(obstacle)
                self.progress.setValue(self.progress.value() + 1)
                QApplication.processEvents()
            QApplication.processEvents()
        self.progress.setValue(maxium)
        define._messagBar.hide()
        self.manualPolygon = None

    def addObstacleToModel(self, obstacle, checkResult=None):
        standardItemList = []
        # obstacle.positionDegree = QgisHelper.Meter2Degree(obstacle.Position.x(), obstacle.Position.y())
        standardItem = QStandardItem(str(obstacle.featureId))
        standardItem.setData(obstacle.featureId)
        standardItemList.append(standardItem)

        standardItem = QStandardItem(str(obstacle.layerId))
        standardItem.setData(obstacle.layerId)
        standardItemList.append(standardItem)

        standardItem = QStandardItem(str(obstacle.name))
        standardItem.setData(obstacle.name)
        standardItemList.append(standardItem)

        standardItem = QStandardItem(str(obstacle.Position.x()))
        standardItem.setData(obstacle.Position.x())
        standardItemList.append(standardItem)

        standardItem = QStandardItem(str(obstacle.Position.y()))
        standardItem.setData(obstacle.Position.y())
        standardItemList.append(standardItem)

        value = QVariant(QgisHelper.strDegree(obstacle.positionDegree.y()))
        standardItem = QStandardItem(value.toString())
        standardItem.setData(obstacle.positionDegree.y())
        standardItemList.append(standardItem)
        strV = QgisHelper.strDegree(obstacle.positionDegree.y())

        value = QVariant(QgisHelper.strDegree(obstacle.positionDegree.x()))
        standardItem = QStandardItem(value.toString())
        standardItem.setData(obstacle.positionDegree.x())
        standardItemList.append(standardItem)

        standardItem = QStandardItem(str(obstacle.Position.z()))
        standardItem.setData(obstacle.Position.z())
        standardItemList.append(standardItem)

        standardItem = QStandardItem(
            str(Unit.ConvertMeterToFeet(obstacle.Position.z())))
        standardItem.setData(Unit.ConvertMeterToFeet(obstacle.Position.z()))
        standardItemList.append(standardItem)

        standardItem = QStandardItem(str(obstacle.trees))
        standardItem.setData(obstacle.trees)
        standardItemList.append(standardItem)

        standardItem = QStandardItem(
            str(Unit.ConvertMeterToFeet(obstacle.trees)))
        standardItem.setData(Unit.ConvertMeterToFeet(obstacle.trees))
        standardItemList.append(standardItem)

        #         for i in range(len(standardItemList), self.source.columnCount()):
        #             standardItemList.append(QStandardItem("None"))

        self.source.appendRow(standardItemList)

        standardItem = QStandardItem(str(obstacle.mocMultiplier))
        standardItem.setData(obstacle.mocMultiplier)
        self.source.setItem(self.source.rowCount() - 1,
                            self.IndexMocMultiplier, standardItem)

    def checkObstacle(self, obstacle):
        pass

    def CompareObstacleRows(self, newRow, row, ignore):
        pass

    def method_0(self, obstacle_0):
        colCount = self.columnCount()
        objectId = range(colCount)

        objectId[0] = (obstacle_0.featureId)
        objectId[1] = (obstacle_0.name)
        objectId[2] = (obstacle_0.position.x())
        objectId[3] = (obstacle_0.position.y())
        objectId[4] = (obstacle_0.Position.z())
        position = obstacle_0.position
        objectId[6] = (Unit.ConvertMeterToFeet(position.z()))
        objectId[7] = (obstacle_0.trees)
        objectId[8] = (Unit.ConvertMeterToFeet(obstacle_0.Trees))
        if (self.IndexMocMultiplier > -1):
            objectId[self.IndexMocMultiplier] = obstacle_0.MocMultiplier

        return objectId

    def method_1(self, object_0):
        pass
Exemplo n.º 53
0
class Main(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setup_signals()
        self.initialize_project()

    def initialize_project(self):
        print 'initializing'
        prj_files = glob.glob('../data/*.conf')

        self.projects = {}

        for config in prj_files:
            path_fname = list(os.path.split(os.path.abspath(config)))
            config_name = os.path.splitext(path_fname[1])[0]
            self.projects[config_name] = path_fname

        self.prj_model = QStandardItemModel(self.ui.ProjectsListView)
        for prj_name in self.projects:
            item = QStandardItem(prj_name)
            print "Adding " + prj_name
            self.prj_model.appendRow(item)

        self.ui.ProjectsListView.setModel(self.prj_model)
        self.ui.ProjectsListView.selectionModel().select(
            self.prj_model.index(0, 0, QModelIndex()),
            QtGui.QItemSelectionModel.Select)

    def show_about(self):
        print "its all about me!"
        dlg = QtGui.QDialog()
        ui = Ui_aboutDialog()
        ui.setupUi(dlg)
        dlg.show()
        dlg.exec_()

    def show_help(self):
        print "show Help!"
        pass

    def new_prj(self):
        print "create new tag name"
        dlg = QtGui.QDialog()
        TagNames(dlg)
        dlg.show()
        dlg.exec_()

    def delete_prj(self):
        print "Delete"

    def do_save(self):
        print "save it"

    def do_save_as(self):
        print "save as this"

    def prj_menu(self, QPos):
        self.listMenu = QtGui.QMenu(self.ui.ProjectsListView)

        menu_item = self.listMenu.addAction("New")
        self.connect(menu_item, QtCore.SIGNAL("triggered()"), self.new_prj)

        menu_item = self.listMenu.addAction("Save")
        self.connect(menu_item, QtCore.SIGNAL("triggered()"), self.do_save)

        menu_item = self.listMenu.addAction("Save as")
        self.connect(menu_item, QtCore.SIGNAL("triggered()"), self.do_save_as)

        menu_item = self.listMenu.addAction("Delete")
        self.connect(menu_item, QtCore.SIGNAL("triggered()"), self.delete_prj)

        parentPosition = self.ui.ProjectsListView.mapToGlobal(
            QtCore.QPoint(0, 0))
        self.listMenu.move(parentPosition + QPos)

        self.listMenu.show()

    def setup_signals(self):
        # will be setting up slots and signals here
        print "setting up slots and signals"
        QtCore.QObject.connect(self.ui.actionAbout,
                               QtCore.SIGNAL(_fromUtf8("activated()")),
                               self.show_about)

        QtCore.QObject.connect(self.ui.actionNew,
                               QtCore.SIGNAL(_fromUtf8("activated()")),
                               self.new_prj)

        QtCore.QObject.connect(self.ui.actionSave,
                               QtCore.SIGNAL(_fromUtf8("activated()")),
                               self.do_save)

        QtCore.QObject.connect(self.ui.actionSave_as,
                               QtCore.SIGNAL(_fromUtf8("activated()")),
                               self.do_save_as)

        QtCore.QObject.connect(self.ui.actionHelp,
                               QtCore.SIGNAL(_fromUtf8("activated()")),
                               self.show_help)

        self.ui.ProjectsListView.setContextMenuPolicy(
            QtCore.Qt.CustomContextMenu)
        self.ui.ProjectsListView.connect(
            self.ui.ProjectsListView,
            QtCore.SIGNAL("customContextMenuRequested(QPoint)"), self.prj_menu)
Exemplo n.º 54
0
class LookupValueSelector(QDialog, Ui_LookupValueSelector):
    """
    A dialog that enables to select a value and code from a lookup.
    .. versionadded:: 1.5
    """

    def __init__(self, parent, lookup_entity_name, profile=None):
        """
        Initializes LookupValueSelector.
        :param parent: The parent of the dialog.
        :type parent: QWidget
        :param lookup_entity_name: The lookup entity name
        :type lookup_entity_name: String
        :param profile: The current profile object
        :type profile: Object
        """
        QDialog.__init__(self, parent, Qt.WindowTitleHint |
                         Qt.WindowCloseButtonHint)
        self.setupUi(self)
        self.value_and_code = None
        if profile is None:
            self._profile = current_profile()
        else:
            self._profile = profile

        self.lookup_entity = self._profile.entity_by_name(
            '{}_{}'.format(self._profile.prefix, lookup_entity_name)
        )

        self.notice = NotificationBar(self.notice_bar)
        self._view_model = QStandardItemModel()
        self.value_list_box.setModel(self._view_model)
        header_item = QStandardItem(lookup_entity_name)
        self._view_model.setHorizontalHeaderItem(0, header_item)
        self.populate_value_list_view()

        self.selected_code = None
        self.selected_value_code = None

        self.value_list_box.clicked.connect(self.validate_selected_code)

    def populate_value_list_view(self):
        """
        Populates the lookup values and codes.
        """
        self.value_and_code = self.lookup_entity.values

        for value, code in self.value_and_code.iteritems():
            u_value = unicode(value)
            code_value = self.lookup_entity.values[u_value]

            value_code = QStandardItem('{} ({})'.format(
                    code_value.value, code.code
                )
            )
            value_code.setData(code.code)
            self._view_model.appendRow(value_code)

    def validate_selected_code(self):
        """
        Validate the selected code for the presence of Code or not.
        """
        self.notice.clear()
        self.selected_code_value()
        if self.selected_code == '':
            notice = QApplication.tr(self, 'The selected value has no code.')
            self.notice.insertWarningNotification(notice)

    def selected_code_value(self):
        """
        Get the selected lookup value.
        """
        index = self.value_list_box.currentIndex()
        item = self._view_model.itemFromIndex(index)
        self.selected_code = item.data()
        self.selected_value_code = item.text()

    def accept(self):
        """
        Overridden QDialog accept method.
        """
        self.selected_code_value()
        self.done(1)

    def reject(self):
        """
        Overridden QDialog accept method.
        """
        self.selected_code = None
        self.selected_value_code = None
        self.done(0)
Exemplo n.º 55
0
class GroupPhotoWindow(QMainWindow, Ui_main_win):

    def __init__(self):
        QMainWindow.__init__(self)
        self.setupUi(self)

        self.image_model = QStandardItemModel()
        self.image_list.setModel(self.image_model)

        QObject.connect(self.add_btn, QtCore.SIGNAL('clicked()'), self.on_add_image)
        QObject.connect(self.delete_btn, QtCore.SIGNAL('clicked()'), self.on_remove_image)
        QObject.connect(self.image_list.selectionModel(), QtCore.SIGNAL(
            'currentChanged (const QModelIndex &, const QModelIndex &)'), self.on_row_changed)
        QObject.connect(self.harris_btn, QtCore.SIGNAL('clicked()'), self.on_harris_detect)
        QObject.connect(self.stitch_btn, QtCore.SIGNAL('clicked()'), self.on_stitch)

    def on_add_image(self):
        image_path = QFileDialog.getOpenFileName(self, 'Select image', filter='Images (*.png *.jpg *.bmp)')
        ignored, name = os.path.split(unicode(image_path))
        self.image_model.appendRow([QStandardItem(name), QStandardItem(image_path)])

    def on_remove_image(self):
        row = self.image_list.selectionModel().currentIndex().row()
        if row == -1:
            return
        self.image_model.removeRows(row, 1)

    def on_row_changed(self, current, previous):
        row = current.row()
        if row == -1:
            file_path = PLACE_HOLDER
        else:
            file_path = self.image_model.item(row, 1).text()
        self.set_pixmap(QPixmap(file_path))

    def on_harris_detect(self):
        row = self.image_list.selectionModel().currentIndex().row()
        if row == -1:
            return
        file_path = self.image_model.item(row, 1).text()

        image_pfm = convert_to_pfm(imread(unicode(file_path)))
        image = image_to_gray(image_pfm)
        kernel = self.ksize_slider.value()
        cornerness = harris_corner(image, ksize=kernel)
        is_corner = cornerness > 0.000001
        suppress = non_max_suppression(cornerness, ksize=kernel)
        result = np.array(is_corner * suppress)
        zero = np.zeros_like(result)
        gray_img = np.dstack((zero, zero, draw_cross(result)))

        self.set_pixmap(QPixmap.fromImage(image_from_ndarray(np.array(gray_img + image_pfm))))

    def on_stitch(self):
        i = 0
        images = []
        while self.image_model.item(i):
            file_path = self.image_model.item(i, 1).text()
            image = image_to_gray(convert_to_pfm(imread(unicode(file_path))))
            images.append(image)
            i += 1
        stitch(self.ksize_slider.value(), images)

    def set_pixmap(self, pixmap):
        self.image_label.setPixmap(pixmap.scaled(self.image_label.size(), QtCore.Qt.KeepAspectRatio))
Exemplo n.º 56
0
class LookupValueSelector(QDialog, Ui_LookupValueSelector):
    """
    A dialog that enables to select a value and code from a lookup.
    .. versionadded:: 1.5
    """

    def __init__(self, parent, lookup_entity_name, profile=None):
        """

        """
        QDialog.__init__(self, parent, Qt.WindowTitleHint|Qt.WindowCloseButtonHint)
        self.setupUi(self)
        self.value_and_code = None
        if profile is None:
            self._profile = current_profile()
        else:
            self._profile = profile

        self.lookup_entity = self._profile.entity_by_name(
            '{}_{}'.format(self._profile.prefix, lookup_entity_name)
        )

        self.notice = NotificationBar(self.notice_bar)
        self._view_model = QStandardItemModel()
        self.value_list_box.setModel(self._view_model)
        header_item = QStandardItem(lookup_entity_name)
        self._view_model.setHorizontalHeaderItem(0, header_item)
        self.populate_value_list_view()

        self.selected_code = None
        self.selected_value_code = None

        self.value_list_box.clicked.connect(self.validate_selected_code)


    def populate_value_list_view(self):
        self.value_and_code = self.lookup_entity.values
        for value, code in self.value_and_code.iteritems():
            value_code = QStandardItem('{} ({})'.format(value, code.code))
            value_code.setData(code.code)
            self._view_model.appendRow(value_code)

    def validate_selected_code(self):
        self.notice.clear()
        self.selected_code_value()
        if self.selected_code == '':
            notice = QApplication.tr(self, 'The selected value has no code.')
            self.notice.insertWarningNotification(notice)

    def selected_code_value(self):
        index = self.value_list_box.currentIndex()
        item = self._view_model.itemFromIndex(index)
        self.selected_code = item.data()
        self.selected_value_code = item.text()

    def accept(self):
        self.selected_code_value()
        self.done(1)

    def reject(self):
        self.selected_code = None
        self.selected_value_code = None
        self.done(0)
Exemplo n.º 57
-1
    def _guiUpdate_metaTable(self,uuid):
        dbconn=DbConn()
        meta=dbconn.get_meta_kv()

        stream=meta[str(uuid)]
        print stream

        model=QStandardItemModel()
        model.setHorizontalHeaderItem(0,QStandardItem("Attribute"))
        model.setHorizontalHeaderItem(1,QStandardItem("Value"))


        while model.rowCount() > 0:
            model.removeRow(0)

        for k in stream.keys():
            name=stream[k]
            # print name
            # print k
            item1 = QStandardItem(k)
            item2 = QStandardItem(name)
            # item=QTableWidgetItem()
            # item.setText(1,name)
            # item.setText(2,k)
            # self.ui.metaEditor
            # model.appendRow([item1,item2])
            # self.ui.metaEditor.appendI
            model.appendRow([item1,item2])
        self.ui.metaEditor.setModel(model)

        # self.ui.metaEditor.addTopLevelItem(item)
        # self.ui.metaEditor.

        # model.itemChanged.connect(lambda: on_item_changed())

        self.metamodel=model

        # self.ui.met
        self.ui.metaEditor.setModel(model)
        # self.ui.metaEditor.setEditTriggers(QAbstractItemView.NoEditTriggers)
        # self.ui.metaEditor.sortByColumn(1)
        self.ui.metaEditor.resizeColumnsToContents()