Beispiel #1
0
    def __init__(self):
        super(PersistendIndexProve, self).__init__()
        self.uiw = loadUi("/u/isaito/data/Dropbox/ROS/groovy_quantal/catkin_ws/src/rqt_prove/resource/treeview.ui")

        self._std_model = QStandardItemModel()
        self._rootitem = self._std_model.invisibleRootItem()

        item_r_1 = QStandardItem("r1")
        item_r_2 = QStandardItem("r2")
        print 'index before {}'.format(item_r_1.index())

        qindex_persistent = QPersistentModelIndex(item_r_1.index())

        self._std_model.beginInsertRows(self._rootitem.index(), 0, 0)
        self._rootitem.appendRow(item_r_1)
        self._rootitem.appendRow(item_r_2)
        self._std_model.endInsertRows()
        print 'index after {}'.format(item_r_1.index())
        print 'index after 2 {}'.format(self._std_model.index(0, 0,
                                                              QModelIndex()))

        print '_rootitem index={} persistent list={}'.format(
                                         self._rootitem.index(),
                                         self._std_model.persistentIndexList())

        self.uiw._treeview.setModel(self._std_model)
        self.selectionModel = self.uiw._treeview.selectionModel()
        self.selectionModel.selectionChanged.connect(
                                                 self._selection_changed_slot)
        self.selectionModel.currentChanged.connect(
                                                 self._current_changed_slot)

        print('del/sel?\tde/sel index\tde/sel.row\tde/sel.dat\tparent\tinternal id')

        self.uiw.show()
	def findMatches(self):
		regexp, content = self.getRegExpAndText()
		if not regexp : return # Or if not content : return
		end = len(content)
		matches = bret.search(regexp, content, 0 if self.NoMatchesLimitCheckBox.isChecked() else self.MatchesLimitSpinBox.value(), 0, end)
		headers = [_translate("MatchesTreeView", 'Match', None), _translate("MatchesTreeView", 'From position', None), _translate("MatchesTreeView", 'to position', None)] if self.PositionsCheckBox.isChecked() else [_translate("MatchesTreeView", 'Match', None)]
		self.matchesModel.setHorizontalHeaderLabels(headers)
		for m in matches :
			item = QStandardItem(m.group())
			item.setToolTip(_translate("MatchesTreeView", "Double-click to copy", None))
			if self.PositionsCheckBox.isChecked() :
				startPositionItem = QStandardItem(str(m.start()))
				endPositionItem = QStandardItem(str(m.end()))
				self.matchesModel.appendRow([item, startPositionItem, endPositionItem])
			else :
				self.matchesModel.appendRow([item])
			if self.GroupsCheckBox.isChecked() :
				for i in range(len(m.groups())) :
					subgroupItem = QStandardItem(m.group(i+1))
					subgroupItem.setToolTip(_translate("MatchesTreeView", "Double-click to copy", None))
					if self.PositionsCheckBox.isChecked() :
						subgroupStartItem = QStandardItem(str(m.start(i+1)))
						subgroupEndItem = QStandardItem(str(m.end(i+1)))
						item.appendRow([subgroupItem, subgroupStartItem, subgroupEndItem])
					else :
						item.appendRow([subgroupItem])
		numberOfResults = len(matches)
		self.NumberOfResultsLabel.setText('<i>' + _translate("CentralWidget", 'Number of results returned :', None) + ' </i><b>' + str(numberOfResults) + '</b>')
		self.MatchesTreeView.expandAll()
		self.MatchesTreeView.resizeColumnToContents(0)
    def on_analyses_viewmodel_updated(self, view_model):
        qmodel = QStandardItemModel()
        qmodel.itemChanged.connect(self.on_qmodel_itemChanged)
        qmodel.setColumnCount(5)
        qmodel.setHorizontalHeaderItem(0, QStandardItem('Ion'))
        qmodel.setHorizontalHeaderItem(1, QStandardItem('Method'))
        qmodel.setHorizontalHeaderItem(2, QStandardItem('Start'))
        qmodel.setHorizontalHeaderItem(3, QStandardItem('End'))
        qmodel.setHorizontalHeaderItem(4, QStandardItem('Reason'))

        root = qmodel.invisibleRootItem()

        for ion, analysis in view_model.analyses.items():
            ion_name = QStandardItem(ion.name)
            ion_name.setData(ion, Qt.UserRole)
            method = QStandardItem(analysis.method)
            start = QStandardItem(str(round(analysis.range.start,2)))
            end = QStandardItem(str(round(analysis.range.end,2)))
            reason = QStandardItem(analysis.reason)

            root.appendRow([ion_name, method, start, end, reason])

        self.rangedTable.setModel(qmodel)
        self.rangedTable.setItemDelegateForColumn(1, MethodsComboDelegate(view_model.methods, self.rangedTable))
        for row in range(0, qmodel.rowCount()):
            self.rangedTable.openPersistentEditor(qmodel.index(row, 1))
        self.rangedTable.setColumnWidth(1, 95)
        self.rangedTable.setContextMenuPolicy(3)
        self.rangedTable.customContextMenuRequested.connect(self._context_menu_requested)
        shortcut = QShortcut(QKeySequence('Del'), self.rangedTable, self._delete_ion,self._delete_ion, context=0)
Beispiel #4
0
    def listCharts(self):

        self.chartModel.clear()
        for c in self.charts:
            item = QStandardItem(c[0] + ' (' + c[2] + ')')
            item.setData(c[1])
            self.chartModel.appendRow(item)
Beispiel #5
0
 def addSelection(self, selection, name=""):
     self._selections.append(selection)
     item = QStandardItem(selection.name)
     item.setFlags(item.flags() ^ Qt.ItemIsDropEnabled)
     self._listModel.appendRow(item)
     self.setSelectionModified(False)
     return item
Beispiel #6
0
 def _createListItem(self, values):
     result = []
     for val in values:
         item = QStandardItem(str(val))
         item.setEditable(False)
         result.append(item)
     return result
Beispiel #7
0
class UserItemModel(QStandardItemModel):

	foo, nama, userPicture, address, realname, locked = range(6)

	def __init__(self):
		QStandardItemModel.__init__(self)
		role_names = {
			self.foo: "",
			self.nama: "nama",
			self.userPicture: "userpicture",
			self.address: "address",
			self.realname: "realname",
			self.locked: "locked"
		}
		self.setRoleNames(role_names)

	def addRootElement(self):
		root = MyUser('root', 'root', '/root')
		self.addUserItem(root.getName(), 
				root.getAvatar(),
				root.getHome(),
				root.getRealName(),
				root.getLock())

	def addUserItem(self, username, userPicture, address, realname, locked, foo = ""):
		self.item = QStandardItem()
		self.item.setData(username, self.nama)
		self.item.setData(userPicture, self.userPicture)
		self.item.setData(address, self.address)
		self.item.setData(realname, self.realname)
		self.item.setData(locked, self.locked)
		self.appendRow(self.item)
Beispiel #8
0
 def addItemToQTableView(self, item, selectedItems):
     standardItem = QStandardItem(item.name)
     standardItem.setData(item.data)
     logger.debug(
         "--rightArrowClicked() self._model.appendRow(standardItem) selectedItems: {0}"
         .format(len(selectedItems)))
     self._model.appendRow(standardItem)
Beispiel #9
0
 def removePeakFromOneCluster(self):
     idx=self.view.treeView_3.selectedIndexes()[0]#supposed the selection exists 
     if not idx.isValid():
         return
     model=idx.model()
     #copy the item
     itemToDelete = model.itemFromIndex(idx)
     item = QStandardItem(itemToDelete)
     #no need to select already selected, then removing
     self.view.treeView_3.removeSelected()
     #putting the copied item in view
     parentIndex = idx.parent().parent().parent()
     sample = self.currentSample[3]#self.model.sample(parentIndex.data().toString(), 
                                #fullNameEntry=False)
     if sample is None:
         print "Unknown error"            
         return
     
     data = map(str, item.text().split('/'))[:2]
     dataParent = map(str, idx.parent().parent().data().toString().split('/'))
     sample.mappedPeaks.sample=sample; sample.rawPeaks.sample=sample#du to one bug don't know why        
     goodPeak = sample.mappedPeaks.peakAt(*map(float, dataParent))
     fragPeak = sample.rawPeaks.peakAt(*map(float, data))
     try:        
         goodPeak.fragCluster.remove(fragPeak)
         goodPeak.isoCluster.remove(fragPeak)
     except ValueError:
         pass            
     #adding item to the treeView
     parentItem = model.itemFromIndex(parentIndex)   
     index = bisect_left(sample.mappedPeaks.masses(), float(item.text().split('/')[0]))
     #model.insertRow(index, item)
     parentItem.insertRow(index, item)      
     self.view.treeView_3.update()
Beispiel #10
0
    def initialize_buckets_table(self):
        self.storj_engine = StorjEngine()  # init StorjEngine
        logger.info("resolving buckets")
        model = QStandardItemModel(1, 1)  # initialize model for inserting to table

        model.setHorizontalHeaderLabels(['Name', 'Storage', 'Transfer', 'ID'])

        i = 0
        try:
            for bucket in self.storj_engine.storj_client.bucket_list():
                item = QStandardItem(bucket.name)
                model.setItem(i, 0, item)  # row, column, item (QStandardItem)

                item = QStandardItem(str(bucket.storage))
                model.setItem(i, 1, item)  # row, column, item (QStandardItem)

                item = QStandardItem(str(bucket.transfer))
                model.setItem(i, 2, item)  # row, column, item (QStandardItem)

                item = QStandardItem(bucket.id)
                model.setItem(i, 3, item)  # row, column, item (QStandardItem)

                i = i + 1

        except sjexc.StorjBridgeApiError as e:
            QtGui.QMessageBox.about(
                self,
                'Unhandled bucket resolving exception',
                'Exception: %s' % e)

        self.bucket_manager_ui.total_buckets_label.setText(str(i))  # set label of user buckets number
        self.bucket_manager_ui.bucket_list_tableview.setModel(model)
        self.bucket_manager_ui.bucket_list_tableview.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)
Beispiel #11
0
 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)])
Beispiel #12
0
	def populateForms(self):
		row = 0
		for form in getForms():
			formitem = QStandardItem(form)
			formitem.setCheckable(True)
			self.formmodel.insertRow(row, formitem)
			row += 1
Beispiel #13
0
 def restore(self):
     try:
         address = os.path.join(os.path.dirname(__file__), 'EXPDATA',
                                'All.txt')
         self.address = address
         file1 = open(address, 'r+')
     except:
         address = os.path.join(os.path.dirname(__file__),
                                'Mineral_Physics', 'EXPDATA', 'All.txt')
         self.address = address
         file1 = open(address, 'r')
         next(file1)
         for i, line in enumerate(file1):
             line = line.split()
             newItem = QStandardItem(self.Solidsolution[i].name)
             self.model.setItem(i, 0, newItem)
             for col in range(len(line)):
                 try:
                     string = "{:5.2f}".format(line[col])
                 except:
                     string = line[col]
                 item = QStandardItem(string)
                 self.model.setItem(i, col, item)
         file1.close()
     self.update_data()
Beispiel #14
0
    def update_tree_view(self):
        sis = self.tree_view.header().sortIndicatorSection()
        sio = self.tree_view.header().sortIndicatorOrder()

        self.tree_view_model.clear()

        for info in infos.get_brick_infos():
            if info.connected_uid != '0':
                position_prefix = info.connected_uid
            else:
                position_prefix = info.uid

            position_item = QStandardItem(info.position.upper())
            position_item.setData(position_prefix + ':' + info.position.upper(), USER_ROLE_POSITION)

            parent = [QStandardItem(info.name),
                      QStandardItem(info.uid),
                      position_item,
                      QStandardItem('.'.join(map(str, info.firmware_version_installed)))]

            for item in parent:
                item.setFlags(item.flags() & ~Qt.ItemIsEditable)

            self.tree_view_model.appendRow(parent)

            for port in sorted(info.bricklets):
                if info.bricklets[port] and info.bricklets[port].protocol_version == 2:
                    child = [QStandardItem(info.bricklets[port].name),
                             QStandardItem(info.bricklets[port].uid),
                             QStandardItem(info.bricklets[port].position.upper()),
                             QStandardItem('.'.join(map(str, info.bricklets[port].firmware_version_installed)))]
                    for item in child:
                        item.setFlags(item.flags() & ~Qt.ItemIsEditable)
                    parent[0].appendRow(child)

            if info.can_have_extension:
                extensions = []
                if info.extensions['ext0'] != None:
                    extensions.append((info.extensions['ext0'], 'Ext0'))
                if info.extensions['ext1'] != None:
                    extensions.append((info.extensions['ext1'], 'Ext1'))

                for extension in extensions:
                    if extension[0].firmware_version_installed != (0, 0, 0):
                        fw_version = '.'.join(map(str, extension[0].firmware_version_installed))
                    else:
                        fw_version = ''

                    child = [QStandardItem(extension[0].name),
                             QStandardItem(''),
                             QStandardItem(extension[1]),
                             QStandardItem(fw_version)]
                    for item in child:
                        item.setFlags(item.flags() & ~Qt.ItemIsEditable)
                    parent[0].appendRow(child)

        self.set_tree_view_defaults()
        self.tree_view.header().setSortIndicator(sis, sio)
        self.update_advanced_window()
        self.delayed_refresh_updates_timer.start()
	def addItemToStore(self, name, category=None, icon=None):
		newItem = QStandardItem(name)
		if icon:
			newItem.setIcon(icon)
		if category:
			newItem.setData(category)
		self.__modelStore.appendRow(newItem)
    def __display_table_rslt(self, table_rows):
        '''
        controls table_comp_rslt widget
        fill the widget with table_rows list
        @param table_rows: []
        '''

        rows_count = len(table_rows)
        model = QStandardItemModel(rows_count, 3)

        model.setHorizontalHeaderLabels(TAB_LABELS)

        # fill model with data
        for row in range(rows_count):
            for col in range(3):
                item = QStandardItem()
                item.setData(str(table_rows[row][col]), Qt.DisplayRole)
                model.setItem(row, col, item)

        # self.table_comp_rslt.clearContents()
        if self.table_comp_rslt.isSortingEnabled():
            self.table_comp_rslt.setSortingEnabled(False)

        proxy = numsort.NumberSortModel()
        proxy.setSourceModel(model)
        self.table_comp_rslt.setModel(proxy)
        self.table_comp_rslt.resizeColumnsToContents()
        self.table_comp_rslt.setSortingEnabled(True)
Beispiel #17
0
  def __init__(self, __parent = None, event=False, fm = False):
    """
    Model constructor. Create the default QStandardItem's for the default nodes.
    """
    QStandardItemModel.__init__(self, __parent)
    EventHandler.__init__(self)
    self.__parent = __parent
    self.VFS = VFS.Get()
    self.ch = False

    # init translation
    self.translation()

    # creating qstandarditem for the default nodes (the four displayed nodes when dff is launched)
    self.root_item = self.invisibleRootItem()
    tmp = self.VFS.GetNode("/").children()
    item_list = []
    for i in tmp:
      node_item = QStandardItem(i.name())
      node_item.setData(QVariant(long(i.this)), Qt.UserRole + 1)
      node_item.setData(QVariant(False), Qt.UserRole + 2)
      item_list.append(node_item)
    if len(item_list):
      self.root_item.appendRows(item_list)

    if event:
      self.VFS.connection(self)
Beispiel #18
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.')
Beispiel #19
0
	def populateProjects(self):
		row = 0
		for project in getProjects():
			projectitem = QStandardItem(project.name)
			projectitem.setCheckable(True)
			self.projectsmodel.insertRow(row, projectitem)
			row += 1
Beispiel #20
0
    def __init__(self,
                 name=None,
                 description=None,
                 thumbnail=None,
                 icon=None,
                 path=None):
        QStandardItem.__init__(self)

        self.__name = ""

        if name is None:
            name = "Untitled"

        self.setName(name)

        if description is None:
            description = "No description."
        self.setDescription(description)

        if thumbnail is None:
            thumbnail = UNKNOWN_SVG
        self.setThumbnail(thumbnail)

        if icon is not None:
            self.setIcon(icon)

        if path is not None:
            self.setPath(path)
Beispiel #21
0
 def make_row(self, state, title):
     item = QStandardItem(title) if title else QStandardItem()
     item.setFlags(
         Qt.ItemIsUserCheckable | Qt.ItemIsTristate | Qt.ItemIsEnabled |
         Qt.ItemIsEditable)
     item.setData(self.state_to_check_state(state), Qt.CheckStateRole)
     return [item]
Beispiel #22
0
 def add_category(self):
     text, ok = QInputDialog.getText(self, 'Create new category',
                                     'Category name:')
     if ok:
         catItem = QStandardItem(text)
         catItem.setCheckable(True)
         self.model.appendRow(catItem)
Beispiel #23
0
 def fillScalars(self):
     scalars = [ 'absorbance (%)', 
                 'reflectance (%)', 
                 'transmittance (%)',
                 'absorbance (mA/cm²)',
                 'reflectance (mA/cm²)', 
                 'transmittance (mA/cm²)',
                 'generation',
                 'Jmax (mA/cm²)',
                 'absorption layerwise (%)',
                 'absorption layerwise (mA/cm²)', 
                 'collection layerwise (%)',
                 'collection layerwise (mA/cm²)', 
                 'calc. time (s)'
                 ]
                 
     self.scalarListModel = QStandardItemModel()
     scalarsToShow = self.defaults['defaultScalars']
     for value in scalars:                   
         item = QStandardItem(value)
         check = Qt.Checked if value in scalarsToShow else Qt.Unchecked
         item.setCheckState(check)
         item.setCheckable(True)
         self.scalarListModel.appendRow(item)
 
     self.scalarListView.setModel(self.scalarListModel)
Beispiel #24
0
    def create_last_modified_item(last_modified):
        item = QStandardItem(
            QDateTime.fromTime_t(last_modified).toString(
                'yyyy-MM-dd HH:mm:ss'))
        item.setData(last_modified, USER_ROLE_LAST_MODIFIED)

        return item
Beispiel #25
0
    def calcALT(self):
        thrAlt = Unit.ConvertFeetToMeter(self.data["ThrAltitude"])
        rdhAlt = Unit.ConvertFeetToMeter(self.data["RDHAltitude"])
        gradient = self.data["DescentGradient"]
        dx = self.data["dX"]

        for i in range(7):
            item = self.stdModel.item(1,
                                      self.data["CatOfAcftCount"][0] + 5 + i)
            val = 0.0
            try:
                val = float(item.text())
            except:
                continue
            dist = val * 1852
            valueHgt = Unit.ConvertFeetToMeter(
                (dist - dx) * math.tan(Unit.ConvertDegToRad(gradient)))
            valueAlt = valueHgt + thrAlt + rdhAlt
            if valueAlt > int(valueAlt):
                valueAlt = int(valueAlt) + 1
            if valueHgt > int(valueHgt):
                valueHgt = int(valueHgt) + 1

            itemTemp = QStandardItem(
                str(valueAlt) + "\n(" + str(valueHgt) + ")")
            itemTemp.setTextAlignment(Qt.AlignCenter)
            self.stdModel.setItem(2, self.data["CatOfAcftCount"][0] + 5 + i,
                                  itemTemp)
Beispiel #26
0
 def populateProjects(self):
     row = 0
     for project in getProjects():
         projectitem = QStandardItem(project.name)
         projectitem.setCheckable(True)
         self.projectsmodel.insertRow(row, projectitem)
         row += 1
Beispiel #27
0
 def sum_item(value):
     item = QStandardItem()
     item.setData(value, Qt.DisplayRole)
     item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
     item.setFlags(Qt.ItemIsEnabled)
     item.setFont(bold_font)
     return item
    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 _append_to_standard_item(self, item, checklist):
     if checklist is not None:
         for child_checklist in checklist:
             childitem = QStandardItem(child_checklist.name)
             childitem.setFlags( Qt.ItemIsEnabled )
             item.appendRow([childitem])
             self._append_to_standard_item(childitem, child_checklist.children)
Beispiel #30
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()
Beispiel #31
0
 def rowFromData(self, data):
         row = []
         for c in data:
                 item = QStandardItem(unicode(c))
                 item.setFlags( (item.flags() | Qt.ItemIsEditable) if self.editable else (item.flags() & ~Qt.ItemIsEditable) )
                 row.append( item )
         return row
    def populate_neo_unit_list(self):
        """ Fill the unit list with appropriate entries.
        Qt.UserRole: The :class:`neo.Unit` object
        """
        self.unit_model.clear()

        units = []
        for rcg in self.recording_channel_groups():
            units.extend(rcg.units)

        filters = self.parent.get_active_filters('Unit')
        units = self.filter_ordered(units, filters)

        for i, u in enumerate(units):
            if self.parent.is_filtered(u, filters):
                continue
            if u.name:
                name = u.name + ' (%s-%d)' % \
                       (self.parent.channel_group_names[rcg], i)
            else:
                name = '%s-%d' % (self.parent.channel_group_names[rcg], i)
            new_item = QStandardItem(name)
            new_item.setData(u, Qt.UserRole)
            self.unit_model.appendRow(new_item)

        if api.config.autoselect_units:
            self.neoUnitList.selectAll()
        self.selected_units_changed()
Beispiel #33
0
    def append_row(self):
        """
        Add a blank row after the last item in the view.
        """
        items = [QStandardItem(), QStandardItem()]

        self._pair_model.appendRow(items)
    def populate_neo_segment_list(self):
        """ Fill the segment list with appropriate entries.
        Qt.UserRole: The :class:`neo.Segment` object
        """
        self.segment_model.clear()

        segments = []
        for b in self.blocks():
            segments.extend(b.segments)

        filters = self.parent.get_active_filters('Segment')
        segments = self.filter_ordered(segments, filters)
        for i, s in enumerate(segments):
            if s.name:
                name = s.name + ' (%s-%i)' % \
                    (self.parent.block_ids[s.block], i)
            else:
                name = '%s-%i' % (self.parent.block_ids[s.block], i)

            new_item = QStandardItem(name)
            new_item.setData(s, Qt.UserRole)
            self.segment_model.appendRow(new_item)

        self.neoSegmentList.setCurrentIndex(self.segment_model.index(0, 0))
        if api.config.autoselect_segments:
            self.neoSegmentList.selectAll()
        self.selected_segments_changed()
    def populate_neo_channel_group_list(self):
        """ Fill the channel group list with appropriate entries.
        Qt.UserRole: The :class:`neo.RecordingChannelGroup` object
        """
        self.neoChannelGroupList.clearSelection()
        self.channelgroup_model.clear()
        self.parent.channel_group_names.clear()

        rcgs = []
        for b in self.blocks():
            rcgs.extend(b.recordingchannelgroups)

        filters = self.parent.get_active_filters(
            'Recording Channel Group')
        rcgs = self.filter_ordered(rcgs, filters)

        for i, rcg in enumerate(rcgs):
            self.parent.channel_group_names[rcg] = '%s-%s' % (
                self.parent.block_ids[rcg.block],
                self.get_letter_id(i, True))
            if rcg.name:
                name = rcg.name + ' (%s)' % \
                                  self.parent.channel_group_names[rcg]
            else:
                name = self.parent.channel_group_names[rcg]
            new_item = QStandardItem(name)
            new_item.setData(rcg, Qt.UserRole)
            self.channelgroup_model.appendRow(new_item)

        self.neoChannelGroupList.setCurrentIndex(
            self.channelgroup_model.index(0, 0))
        if api.config.autoselect_channel_groups:
            self.neoChannelGroupList.selectAll()
        elif not rcgs:
            self.selected_channel_groups_changed()
Beispiel #36
0
 def addSelection(self, selection, name=""):
     self._selections.append(selection)
     item = QStandardItem(selection.name)
     item.setFlags(item.flags() ^ Qt.ItemIsDropEnabled)
     self._listModel.appendRow(item)
     self.setSelectionModified(False)
     return item
    def insert_row(self):
        """ Inser single row into QStandardItemModel """
        standard_model = self.tbl_relation.model()
        feature_id = utils_giswater.getWidgetText(self.dlg_lot,
                                                  self.dlg_lot.feature_id)
        lot_id = utils_giswater.getWidgetText(self.dlg_lot, self.lot_id)

        layer_name = 'v_edit_' + utils_giswater.get_item_data(
            self.dlg_lot, self.dlg_lot.feature_type, 0).lower()
        field_id = utils_giswater.get_item_data(
            self.dlg_lot, self.dlg_lot.feature_type, 0).lower() + str('_id')
        layer = self.controller.get_layer_by_tablename(layer_name)
        feature = self.get_feature_by_id(layer, feature_id, field_id)
        if feature is False:
            return

        if feature_id not in self.ids:
            item = [lot_id, feature_id, feature.attribute('code'), 0]
            row = []
            for value in item:
                if value not in ('', None) and type(value) != QPyNullVariant:
                    row.append(QStandardItem(str(value)))
                else:
                    row.append(QStandardItem(None))
            if len(row) > 0:
                standard_model.appendRow(row)
                self.ids.append(feature_id)
                self.insert_single_checkbox(self.tbl_relation)
Beispiel #38
0
    def setModel(self):
        from gui.MetBaseGui import MSStandardItem
        #we assume that the different peaks have the same identifiers
        #TODO: may have to merge several stuffs later
        if self.choosenOne.formulas:
            self.identificationModel.setHorizontalHeaderLabels(
                ["score", "formula", "diff mass", "names"])
            for i, f in enumerate(self.choosenOne.formulas.iterkeys()):

                self.identificationModel.setItem(
                    i, 0,
                    MSStandardItem(str(self.choosenOne.formulas[f]["score"])))
                self.identificationModel.setItem(i, 1, QStandardItem(str(f)))
                self.identificationModel.setItem(
                    i, 2,
                    MSStandardItem(str(
                        self.choosenOne.formulas[f]["diffmass"])))
                self.identificationModel.setItem(
                    i, 3, QStandardItem(self.choosenOne.formulas[f]["names"]))
                if self.choosenOne.formulas[f]["names"] != 'Not Found':
                    for j in xrange(4):
                        self.identificationModel.item(i, j).setBackground(
                            QBrush(Qt.green))
                else:
                    for j in xrange(4):
                        self.identificationModel.item(i, j).setBackground(
                            QBrush(Qt.red))
            self.tableView.setModel(self.identificationModel)
Beispiel #39
0
    def initTable(self):
        self.model.clear()
        #         header = QHeaderView(Qt.Horizontal)
        #         headerModel = QStandardItemModel()

        layer = self.baseLayer
        fields = layer.pendingFields()
        headersList = ["fid"]
        for field in fields:
            headersList.append(field.name())
        self.model.setHorizontalHeaderLabels(headersList)

        #         headerModel.setHorizontalHeaderLabels(headersList)
        #         header.setModel(headerModel)
        #         self.attributeTable.setHorizontalHeader(header)

        if len(layer.selectedFeatures()) > 0:
            features = layer.selectedFeatures()
        else:
            features = layer.getFeatures()
        for feature in features:
            record = [QStandardItem(str(feature.id()))]

            for field in feature.fields():
                name = field.name()
                attribute = feature.attribute(name).toString()

                stdItemValue = QStandardItem(attribute)
                stdItemValue.setEditable(False)
                record.append(stdItemValue)
            self.model.appendRow(record)
Beispiel #40
0
 def __init__(self, name, proc=None, path=None):
     QStandardItem.__init__(self, name)
     self.proc = proc
     self.path = path
     self.hive = None
     self.children = 0
     self.expanded = False
     self.root = False
 def _processDB(self, db, parent, dbf):
     """process the database and add its child nodes"""
     for k, v in db.items():
         item = QStandardItem(k)
         item.setIcon(self.icons["project"])
         item.setData(QVariant("P|%s|%s" % (dbf, v.path)))
         parent.appendRow(item)
         self._processProject(v, item, dbf)
Beispiel #42
0
    def mkitem(self, d):
        """ dict with field->value """
        si = QStandardItem()
        for k, v in d.items():
            rid = self.roleids[k]
            si.setData(v, rid)

        return si
 def _processProject(self, pr, parent, dbf):
     """process the project and add its child nodes"""
     for k, v in pr.items():
         item = QStandardItem(k)
         item.setIcon(self.icons['sensorgroup'])
         item.setData(QVariant("G|%s|%s" % (dbf, v.path)))
         parent.appendRow(item)
         self._processSensorGroup(v, item, dbf)
Beispiel #44
0
	def addRow(self, song):
		attribs = song.getFormatedValues(self.playlistOrder)
		nodes = [QStandardItem('')]
		nodes[-1].setData(song)
		for i in attribs:
			nodes.append(QStandardItem(i))
			nodes[-1].setData(song)
		self.model().appendRow(nodes)
Beispiel #45
0
 def mkitem(self, d):
     """ dict with field->value """        
     si = QStandardItem()
     for k,v in d.items():
         rid = self.roleids[k]
         si.setData(v, rid)
         
     return si
Beispiel #46
0
 def populateClients(self):
     row = 0
     for client, settings in self.config['clients'].iteritems():
         name = QStandardItem(client)
         name.setData(settings)
         path = QStandardItem(settings['path'])
         self.model.insertRow(row, [name, path])
         row += 1
 def addSensorgroup(self, project_mi, sg):
     """show a newly created or updated sensorgroup"""
     dbf = self.dsFolder(project_mi)
     item = QStandardItem(sg.name)
     item.setIcon(self.icons["sensorgroup"])
     item.setData(QVariant("G|%s|%s" % (dbf, sg.path)))
     self.itemFromIndex(project_mi).appendRow(item)
     self._processSensorGroup(sg, item, dbf)
Beispiel #48
0
 def row_for_state(self, score, state):
     items = []
     attrs = sorted((self.attrs[x] for x in state), key=attrgetter("name"))
     for attr in attrs:
         item = QStandardItem(attr.name)
         item.setData(attr, self._AttrRole)
         items.append(item)
     return items
Beispiel #49
0
	def populateClients(self):
		row = 0
		for client, settings in self.config['clients'].iteritems():
			name = QStandardItem(client)
			name.setData(settings)
			path = QStandardItem(settings['path'])
			self.model.insertRow(row, [name, path])
			row += 1
Beispiel #50
0
 def __init__(self, path, display, contents=None):
     QStandardItem.__init__(self, display)
     self.setEditable(False)
     self.setData(QVariant(path))
     self.path = path
     self.isClass = isinstance(contents, Class)
     self.isFunction = isinstance(contents, Function)
     self.setIcon(self.selectIcon())
Beispiel #51
0
 def populate_sync_path_model(self, folder_paths):
     self.sync_path_model.clear() 
     for folder_path in folder_paths:
         item = QStandardItem(folder_path)
         item.setEditable(False)
         if folder_path == "Connect to DropBox first":
             item.setTextAlignment(Qt.AlignCenter)
         self.sync_path_model.appendRow(item)
Beispiel #52
0
 def addParentItem(self, category):
     item = QStandardItem(category)
     item.setFlags(item.flags() & ~(Qt.ItemIsEnabled | Qt.ItemIsSelectable))
     item.setData("parent", Qt.AccessibleDescriptionRole)
     font = item.font()
     font.setBold(True)
     item.setFont(font)
     self.model().appendRow(item)
Beispiel #53
0
 def __init__(self, path, display, contents=None):
     QStandardItem.__init__(self, display)
     self.setEditable(False)
     self.setData(QVariant(path))
     self.path = path
     self.isClass = isinstance(contents, Class)
     self.isFunction = isinstance(contents, Function)
     self.setIcon(self.selectIcon())
Beispiel #54
0
 def loadFile(self):
     file = str(QtGui.QFileDialog.getOpenFileName(self, "Open csv file"))
     reader=csv.reader(open(file, 'rb'), delimiter=',')
     model=QtGui.QStandardItemModel()
     for i, r in enumerate(reader[1:]):
         model.setItem(i, 0, QStandardItem(r[0]))
         model.setItem(i, 1, QStandardItem(r[1]))
     self.tableView.setModel(model)
Beispiel #55
0
 def row_for_state(self, score, state):
     items = []
     attrs = sorted((self.attrs[x] for x in state), key=attrgetter("name"))
     for attr in attrs:
         item = QStandardItem(attr.name)
         item.setData(attr, self._AttrRole)
         items.append(item)
     return items
Beispiel #56
0
 def add_parent_tree(self, icon, title):
     roots = OrderedDict()
     for feature_id in self.selected_features():
         root = QStandardItem(icon, title)
         root.setData(feature_id)
         self.set_bold(root)
         self.model.appendRow(root)
         roots[feature_id] = root
     return roots
Beispiel #57
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