def _addChildrenToParent(self, replaceParentNode, standardItemParent):
     if len(replaceParentNode.expressions) > 0:
         for e in replaceParentNode.expressions:
             if isinstance(e, list):
                 listItem = QStandardItem('+')
                 listItem.setEditable(False)
                 for e2 in e:
                     item = QStandardItem(self._buildTreeStringLabel(e2))
                     item.setEditable(False)
                     self._addChildrenToParent(e2, item)
                     listItem.appendRow(item)
                 standardItemParent.appendRow(listItem)
                 
             else:
                 item = QStandardItem(self._buildTreeStringLabel(e))
                 item.setEditable(False)
                 self._addChildrenToParent(e, item)
                 standardItemParent.appendRow(item)
             
     if len(replaceParentNode.children) > 0:
         for c in replaceParentNode.children:
             item = QStandardItem(self._buildTreeStringLabel(c))
             item.setEditable(False)
             self._addChildrenToParent(c, item)
             standardItemParent.appendRow(item)
Example #2
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_()
Example #3
0
    def on_ions_updated(self, new_ions):
        qmodel = QStandardItemModel()
        qmodel.setColumnCount(2)
        qmodel.setHorizontalHeaderItem(0, QStandardItem('Ion'))
        qmodel.setHorizontalHeaderItem(1, QStandardItem('Abundance (%)'))

        root = qmodel.invisibleRootItem()

        element_keyfunc = lambda x: x.isotope.element
        sorted_ions = sorted(new_ions, key=element_keyfunc)

        for element, ions in itertools.groupby(sorted_ions, key=element_keyfunc):
            element_item = QStandardItem(element)
            element_item.setCheckable(True)
            element_item.setCheckState(2)
            root.appendRow(element_item)

            for ion in ions:
                ion_name = QStandardItem(ion.name)
                ion_name.setData(ion,32)
                ion_name.emitDataChanged()
                ion_abundance = QStandardItem(str(ion.isotope.abundance))
                element_item.appendRow([ion_name, ion_abundance])

        self.ionlistTree.setModel(qmodel)
        self.ionlistTree.expandAll()
        self.addionsButton.setEnabled(True)
        self._qmodel=qmodel
Example #4
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_()
	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)
Example #6
0
    def show_frame_info(self, process):
        """ show the frame info """
        if not self.isVisible:
            return
        #TODO: no update if top frame is the same
        self.clear()
        root = self.frame_data.invisibleRootItem()
        self.source_files.clear()
        self.frames.clear()

        if process is None or not process.is_alive:
            return

        #if process.num_of_threads == 1:
        for thread in process:
            thread_name = thread.GetName()
            if not thread_name:
                thread_name = '[No Thread]'
            thread_row = QStandardItem(thread_name)
            thread_row.setEditable(False)
            thread_row.setSelectable(False)
            dummy = QStandardItem('')
            dummy.setEditable(False)
            dummy.setSelectable(False)
            root.appendRow([thread_row, dummy])
            if len(thread.frames):
                self.top_frame = thread.frames[0]
                self.frame_changed.emit(self.top_frame)
            for frame in thread.frames:
                # first show the frame on the top of call stack.
                frame_idx = '#%d: ' % frame.idx
                frame_info = ''
                selectable = False
                if frame.name:
                    frame_idx += frame.name
                    if self._show_args.isChecked():
                        args = ','.join([str(x) for x in frame.args])
                        frame_info += ' (%s)' % args
                line = frame.line_entry
                if line:
                    file_info = ' at %s:%d' % (str(line.GetFileSpec()), line.GetLine())
                    frame_info += file_info
                    selectable = True
                else:
                    frame_info += str(frame.module.GetFileSpec())
                if frame.is_inlined:
                    frame_info += ' (inlined)'
                col_idx = QStandardItem(frame_idx)
                self.source_files[col_idx] = line
                self.frames[col_idx] = frame
                col_idx.setEditable(False)
                col_idx.setSelectable(selectable)

                col_info = QStandardItem(frame_info)
                col_info.setEditable(False)
                col_info.setSelectable(selectable)

                thread_row.appendRow([col_idx, col_info])

        self.expandToDepth(1)
    def __init__(self, template, character, parent=None):
        super(SubPowerWidget, self).__init__(parent)

        self.__storage = template
        self.__character = character

        self.__model = QStandardItemModel()
        # Das ungenutzte Model dient dazu, alle Unterkräfte aufzunehmen, die ich nicht darstellen möchte. Ist einfacher, als diese im View zu verstecken.
        self.__modelUnused = QStandardItemModel()

        self._layout = QVBoxLayout()
        self.setLayout(self._layout)

        self.__view = QTreeView()
        self.__view.setHeaderHidden(True)
        self.__view.setModel(self.__model)

        self._layout.addWidget(self.__view)

        self._typ = "Subpower"
        categories = self.__storage.categories(self._typ)

        self.__items = {}

        self.__rootItem = QStandardItem()
        self.__rootItem = self.__model.invisibleRootItem()

        self.__rootItemUnused = QStandardItem()
        self.__rootItemUnused = self.__modelUnused.invisibleRootItem()

        for item in categories:
            categoryItem = QStandardItem(item)
            self.__rootItem.appendRow(categoryItem)

            ## Ich benötige diese Items auch im ungenutzten Model.
            categoryItemUnused = QStandardItem(item)
            self.__rootItemUnused.appendRow(categoryItemUnused)

            traitList = list(self.__character.traits[self._typ][item].items())
            traitList.sort()
            for trait in traitList:
                traitItem = QStandardItem(trait[1].name)
                traitItem.setCheckable(True)
                ## Unhashable Type
                self.__items[trait[1]] = traitItem
                categoryItem.appendRow(traitItem)

                ## Funktioniert mit PySide nicht:
                #trait[1].availableChanged.connect(traitItem.setEnabled)
                ## Funktioniert auch mit PySide:
                trait[1].availableChanged.connect(
                    lambda enable, item=traitItem: item.setEnabled(enable))
                trait[1].valueChanged.connect(lambda val, trait=trait[
                    1], item=traitItem: self.__setItemValue(trait, item))

        self.__model.itemChanged.connect(self.__getItemValue)
        self.__character.speciesChanged.connect(self.hideOrShowToolPage)
        self.__character.breedChanged.connect(self.hideOrShowToolPage)
        self.__character.factionChanged.connect(self.hideOrShowToolPage)
Example #8
0
    def importFromTsv(self, filename):
        # append file item
        rootItem = self.model.invisibleRootItem()
        basename = os.path.basename(filename)
        parent = QStandardItem(os.path.splitext(basename)[0])
        rootItem.appendRow([parent])

        # load service info from tsv file
        try:
            with codecs.open(filename, "r", "utf-8") as f:
                lines = f.readlines()
        except Exception as e:
            QgsMessageLog.logMessage(self.tr("Fail to read {0}: {1}").format(basename, unicode(e)),
                                     self.tr("TileLayerPlugin"))
            return False

        for i, line in enumerate(lines):
            if line.startswith("#"):
                continue
            vals = line.rstrip().split("\t")
            nvals = len(vals)
            try:
                if nvals < 3:
                    raise
                title, attribution, url = vals[0:3]
                if not url:
                    raise
                if nvals < 4:
                    serviceInfo = TileLayerDefinition(title, attribution, url)
                else:
                    yOriginTop = int(vals[3])
                    if nvals < 6:
                        serviceInfo = TileLayerDefinition(title, attribution, url, yOriginTop)
                    else:
                        zmin, zmax = map(int, vals[4:6])
                        if nvals < 10:
                            serviceInfo = TileLayerDefinition(title, attribution, url, yOriginTop, zmin, zmax)
                        else:
                            bbox = BoundingBox.fromString(",".join(vals[6:10]))
                            epsg = None
                            try:
                                epsg = int(vals[10])
                            except Exception as e:
                                i = 0
                            serviceInfo = TileLayerDefinition(title, attribution, url, yOriginTop, zmin, zmax, bbox, epsg)
            except:
                QgsMessageLog.logMessage(self.tr("Invalid line format: {} line {}").format(basename, i + 1),
                                         self.tr("TileLayerPlugin"))
                continue

            # append the service info into the tree
            vals = serviceInfo.toArrayForTreeView() + [len(self.serviceInfoList)]
            rowItems = map(QStandardItem, map(unicode, vals))
            parent.appendRow(rowItems)
            self.serviceInfoList.append(serviceInfo)
        return True
Example #9
0
 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()
Example #10
0
 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()
Example #11
0
 def addNcFile(self, ncFileName):
     f = NetCDFFile(ncFileName) 
     self.files[ncFileName] = f
     fItem = QStandardItem(ncFileName)
     fItem.setIcon(self.icons['file'])
     fItem.setData(QVariant(ncFileName))
     fItem.ncItem = ('F', f)
     self.rootItem.appendRow(fItem)
     for an,av in ncFAttributes(f).items():
         aItem = QStandardItem(an)
         aItem.setIcon(self.icons['attribute'])
         aItem.setData(QVariant(an))
         aItem.ncItem = ('A', av)
         fItem.appendRow(aItem)
     for dn,dv in f.dimensions.items():
         dItem = QStandardItem(dn)
         dItem.setIcon(self.icons['dimension'])
         dItem.setData(QVariant(dn))
         dItem.ncItem = ('D', dv)
         fItem.appendRow(dItem)
     for vn, vv in f.variables.items():
         vItem = QStandardItem(vn)
         vItem.setIcon(self.icons['variable'])
         vItem.setData(QVariant(vn))
         vItem.ncItem = ('V', vv)
         fItem.appendRow(vItem)
         for an,av in ncVAttributes(vv).items():
             aItem = QStandardItem(an)
             aItem.setIcon(self.icons['attribute'])
             aItem.setData(QVariant(an))
             aItem.ncItem = ('A', av)
             vItem.appendRow(aItem)
Example #12
0
 def update_bp_info(self, target):
     """ update breakpoint info """
     self.clear()
     root = self.bp_data.invisibleRootItem()
     for breakpoint in target.breakpoint_iter():
         if not breakpoint.IsValid() or breakpoint.IsInternal():
             continue
         bp_item = QStandardItem(str(breakpoint.id))
         bp_row =[bp_item, QStandardItem(str(breakpoint.GetHitCount())), 
                    QStandardItem(str(breakpoint.GetIgnoreCount())), QStandardItem(str(breakpoint.GetCondition()))]
         for loc in breakpoint:
             loc_row = [QStandardItem(str(loc.GetID())), QStandardItem(str(loc.GetAddress().GetLineEntry()))]
             bp_item.appendRow(loc_row)
         root.appendRow(bp_row)
     self.expandToDepth(1)
Example #13
0
    def add_widget(self, n):
        std_item = QStandardItem('{}th item'.format(n))
        self._datamodel.setItem(n, 0, std_item)

        node_widget = QPushButton('{}th button'.format(n))
        qindex_widget = self._datamodel.index(n, 1, QModelIndex())
        self.setIndexWidget(qindex_widget, node_widget)

        if n == 2:
            std_item_child = QStandardItem('child')
            std_item.appendRow(std_item_child)

            node_widget_child = QPushButton('petit button')
            qindex_widget_child = self._datamodel.index(n, 1, QModelIndex())
            self.setIndexWidget(qindex_widget_child, node_widget_child)
Example #14
0
    def add_widget(self, n):
        std_item = QStandardItem('{}th item'.format(n))
        self._datamodel.setItem(n, 0, std_item)

        node_widget = QPushButton('{}th button'.format(n))
        qindex_widget = self._datamodel.index(n, 1, QModelIndex())
        self.setIndexWidget(qindex_widget, node_widget)

        if n == 2:
            std_item_child = QStandardItem('child')
            std_item.appendRow(std_item_child)

            node_widget_child = QPushButton('petit button')
            qindex_widget_child = self._datamodel.index(n, 1, QModelIndex())
            self.setIndexWidget(qindex_widget_child, node_widget_child)
Example #15
0
    def model_init(self):
        categories = {}
        if not categories:
            with open('categories.json') as f:
                categories = load(f)

        for element in categories:
            catItem = QStandardItem(element.keys()[0])
            catItem.setCheckable(True)
            catItem.setCheckState(element[element.keys()[0]])
            for type_name, check_state in element["Types"].items():
                typeItem = QStandardItem(type_name)
                typeItem.setCheckable(True)
                typeItem.setCheckState(check_state)
                catItem.appendRow(typeItem)
            self.model.appendRow(catItem)
        self.treeView.setModel(self.model)
        self.submit_file_types()
Example #16
0
    def addPeakToOneCluster(self, action):
        #if action.text() == 'Identification':
        #print "launch Identification"
        #    return
        idx = self.view.treeView_3.selectedIndexes()[0]
        model = idx.model()

        s = self.currentSample[
            2]  #self.model.sample(idx.parent().data().toString(), fullNameEntry=False)
        peak = s.peakAt(str(idx.data().toString()))
        peakToAdd = s.peakAt(str(action.text()))
        peak.fragCluster += [peakToAdd]  #first add the parent
        peak.fragCluster += peakToAdd.fragCluster + peakToAdd.isoCluster  #then add its child

        #add item
        item = QStandardItem(action.text())
        gotFragItem = False
        for i in xrange(model.itemFromIndex(idx).rowCount()):
            if model.itemFromIndex(idx).child(
                    i).text() == "fragments/adducts:":
                gotFragItem = True
                fragItem = model.itemFromIndex(idx).child(i)
                fragItem.appendRow(item)
                break
        if not gotFragItem:
            fragItem = QStandardItem("fragments/adducts:")
            fragItem.appendRow(item)
            model.itemFromIndex(idx).appendRow(fragItem)
        #remove the entry peakToAdd
        for i in xrange(model.rowCount()):
            item_ = model.item(i, 0)
            if item_.text() == s.shortName():
                for j in xrange(item_.rowCount()):
                    if item_.child(j).text() == action.text():
                        selector = self.view.treeView_3.selectionModel()
                        for idx in self.view.treeView_3.selectedIndexes():
                            selector.select(idx, QItemSelectionModel.Deselect)
                        item.setIcon(item_.child(j).icon())
                        selector.select(model.indexFromItem(item_.child(j)),
                                        QItemSelectionModel.Select)
                        self.view.treeView_3.removeSelected()
                        break
            break
    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 updateStagesModel(self):
     '''
     Used to update the tree model for the Stages tree
     '''
     self.stagesModel.clear()
     parent = self.stagesModel.invisibleRootItem();
     
     i = 0
     for stage in self.stageTrees:
         i += 1
         stageItem = QStandardItem(stage.replaceVariable)
         stageItem.setEditable(False)
         
         item = QStandardItem(self._buildTreeStringLabel(stage))
         item.setEditable(False)
         self._addChildrenToParent(stage, item)
         
         stageItem.appendRow(item)
         parent.appendRow(stageItem)
         
     self.ui.stagesTreeView.setModel(self.stagesModel)
 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)
Example #20
0
 def addPeakToOneCluster(self, action):
     #if action.text() == 'Identification':
         #print "launch Identification"
     #    return
     idx=self.view.treeView_3.selectedIndexes()[0]
     model=idx.model()
     
     s=self.currentSample[2]#self.model.sample(idx.parent().data().toString(), fullNameEntry=False)
     peak= s.peakAt(str(idx.data().toString()))
     peakToAdd=s.peakAt(str(action.text()))
     peak.fragCluster += [peakToAdd]#first add the parent        
     peak.fragCluster += peakToAdd.fragCluster+peakToAdd.isoCluster#then add its child
             
     #add item
     item=QStandardItem(action.text())
     gotFragItem=False        
     for i in xrange (model.itemFromIndex(idx).rowCount()):
         if model.itemFromIndex(idx).child(i).text() == "fragments/adducts:":
             gotFragItem = True
             fragItem = model.itemFromIndex(idx).child(i)
             fragItem.appendRow(item)
             break
     if not gotFragItem:
         fragItem = QStandardItem("fragments/adducts:")
         fragItem.appendRow(item)
         model.itemFromIndex(idx).appendRow(fragItem)
     #remove the entry peakToAdd
     for i in xrange(model.rowCount()):
         item_=model.item(i, 0)
         if item_.text()==s.shortName():
             for j in xrange(item_.rowCount()):
                 if item_.child(j).text()==action.text():
                     selector=self.view.treeView_3.selectionModel()
                     for idx in self.view.treeView_3.selectedIndexes():
                         selector.select(idx ,QItemSelectionModel.Deselect)
                     item.setIcon(item_.child(j).icon())
                     selector.select(model.indexFromItem(item_.child(j)), QItemSelectionModel.Select)                        
                     self.view.treeView_3.removeSelected()
                     break
         break
Example #21
0
    def populateTree(self, disco):
        if len(disco) > 0:
            attribs = [
                x + "modified" for x in disco[0].getOptionalValues(self.comm)
            ]
            nodes = [QStandardItem("unmatchableStringForNonEmptyInit")]
            # Create root node
            root = QStandardItem('All music')
            self.model().appendRow(root)
        else:
            # Create empty root node
            root = [QStandardItem('Nothing')]
            self.model().appendRow(root)

        # For every song
        for s in disco:
            attr = s.getOptionalValues(self.comm)
            length = len(attr)

            # First attribut separated because attached to node
            if attr[0] != attribs[0]:
                node = QStandardItem(attr[0])
                nodes = [node]
                attribs = [x + "modified" for x in attr]
                root.appendRow(nodes[0])
                attribs[0] = attr[0]

            for i in range(1, length - 1):
                if (attr[i] != attribs[i]):
                    node = QStandardItem(attr[i])
                    nodes[i - 1].appendRow(node)
                    if i < len(nodes):
                        nodes[i] = node
                    else:
                        nodes.append(node)
                    attribs[i] = attr[i]
            # Last attribut
            node = QStandardItem(attr[length - 1])
            nodes[-1].appendRow(node)
            node.setData(s)
Example #22
0
  def __init__(self, parent = None):
    QDialog.__init__(self)
    self.setupUi(self)
    self.selectedDevice = None
    self.listdevices = {}
    self.devices = Devices()
    self.logical = Logical()
    self.combodevice = TreeComboBox()
    self.gridLayout.addWidget(self.combodevice, 0, 1, 1, 1)
    self.__model = QStandardItemModel()
    
    lidx = 0
    if len(self.logical):
        logicalitems = QStandardItem(self.tr("Logical drives"))
        self.__model.appendRow(logicalitems)
        for lidx in range(0, len(self.logical)):
            logicalitem = QStandardItem(self.logical[lidx].model())
            logicalitems.appendRow(logicalitem)
            self.listdevices[lidx] = self.logical[lidx]
        lidx += 1

    if len(self.devices):
        physicalitems = QStandardItem(self.tr("Physical drives"))
        self.__model.appendRow(physicalitems)
        for pidx in range(0, len(self.devices)):
            model = self.devices[pidx].model()
            if model != "Unknown":
              physicalitem = QStandardItem(self.devices[pidx].blockDevice() + " (" + model + ")")
            else:
              physicalitem = QStandardItem(self.devices[pidx].blockDevice())
            physicalitems.appendRow(physicalitem)
            self.listdevices[lidx+pidx] = self.devices[pidx]
    self.combodevice.setModel(self.__model)
    self.combodevice.view().expandAll()

    if len(self.devices):
      self.setDeviceInformations(self.devices[0], True)
      self.selectedDevice = self.devices[0]
    self.connect(self.combodevice, SIGNAL("currentIndexChanged(int)"), self.deviceChanged) 
Example #23
0
	def populateTree(self,disco):
		if len(disco) >0:
			attribs = [x+"modified" for x in  disco[0].getOptionalValues(self.comm)]
			nodes = [QStandardItem("unmatchableStringForNonEmptyInit")]
			# Create root node
			root = QStandardItem('All music')
			self.model().appendRow(root)
		else:
			# Create empty root node
			root = [QStandardItem('Nothing')]
			self.model().appendRow(root)

		# For every song
		for s in disco:
			attr = s.getOptionalValues(self.comm)
			length=len(attr)

			# First attribut separated because attached to node
			if attr[0] != attribs[0]:
				node=QStandardItem(attr[0])
				nodes = [node]
				attribs = [x+"modified" for x in  attr]
				root.appendRow(nodes[0])
				attribs[0]=attr[0]

			for i in range(1, length-1):
				if (attr[i] != attribs[i]):
					node=QStandardItem(attr[i])
					nodes[i-1].appendRow(node)
					if i<len(nodes):
						nodes[i]=node
					else:
						nodes.append(node)
					attribs[i]=attr[i]
			# Last attribut
			node = QStandardItem(attr[length-1])
			nodes[-1].appendRow(node)
			node.setData(s)
Example #24
0
    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)
Example #25
0
    def append_order_details(self, order_item, order):
        order_id = QStandardItem(self.tr('订单编号: ' + str(order.order_id)))
        strategy_id = QStandardItem(self.tr('策略编号: ') + str(order.strategy_id))
        symbol = QStandardItem(self.tr('品种: ') + str(order.symbol))
        direction = self.tr('买入') if order.type == ORDER_BUY else self.tr('卖出')
        direction = QStandardItem(self.tr('方向: ') + direction)
        price = QStandardItem(self.tr('开仓价: ') + str(order.price))
        open_time = QStandardItem(self.tr('开仓时间: ') + str(order.order_time))
        order_profit = QStandardItem(self.tr('总盈利: ') + str(order.profit))
        close_profit = QStandardItem(self.tr('每次平仓盈利'))
        for item in zip(order.get_close_profit_list(),
                        order.get_close_time_list()):
            cp = QStandardItem(str(item[1]) + self.tr(': ') + str(item[0]))
            close_profit.appendRow(cp)

        order_item.appendRow(order_id)
        order_item.appendRow(strategy_id)
        order_item.appendRow(symbol)
        order_item.appendRow(direction)
        order_item.appendRow(price)
        order_item.appendRow(open_time)
        order_item.appendRow(order_profit)
        order_item.appendRow(close_profit)
    def updateComboQueries(self):
        self.queriesModel.clear()
        self.queriesModel.setHorizontalHeaderLabels(['Files'])

        item = QStandardItem(self.tr(u"Query File"))
        item.setSelectable(False)
        self.queriesModel.appendRow(item)

        # read directories with sql files
        for path, dirs, files in os.walk(self.queriesFolder):
            for rep in dirs:
                item = QStandardItem(rep)
                item.setData(rep, Qt.UserRole)
                item.setSelectable(False)
                self.queriesModel.appendRow(item)
                # in each directory, look for sql files
                for nomfich in glob.glob(self.queriesFolder + "/" + rep + "/*.sql"):
                    fileName, fileExtension = os.path.splitext(os.path.basename(nomfich))

                    # one item found
                    subitem = QStandardItem(fileName)
                    subitem.setData(nomfich, Qt.UserRole)

                    item.appendRow(subitem)
Example #27
0
    def actualizeClusterModel(sample):
        model = QApplication.instance().view.clusterModel
        if model.rowCount():
            model.clear()

        idItems = []
        for peak in sample.imappedPeaks():
            std_item = QStandardItem(str(peak))
            std_item.setEditable(False)
            if peak.isFoundInDatabase:
                std_item.setBackground(QBrush(Qt.green))
                #put the formula with the best score
                o = QStandardItem(peak.formulas.keys()[0])
                o.setBackground(QBrush(Qt.green))
                idItems.append(o)
            else:
                idItems.append(QStandardItem("not found"))
            MSDialogController.setRightIcon(peak, std_item)
            if peak.isoCluster:
                iso_item = QStandardItem("isotopic cluster:")
                iso_item.setEditable(False)
                for iso in peak.isoCluster:
                    item = QStandardItem(str(iso))
                    item.setEditable(False)
                    MSDialogController.setRightIcon(iso, item)
                    iso_item.appendRow(item)
                std_item.appendRow(iso_item)
            if peak.fragCluster:
                frag_item = QStandardItem("fragments/adducts:")
                frag_item.setEditable(False)
                for frag in peak.fragCluster:
                    item = QStandardItem("/".join([
                        str(frag.mass()),
                        str(frag.rt),
                        str(frag.annotation.values())[2:-2]
                    ]))
                    item.setEditable(False)
                    MSDialogController.setRightIcon(frag, item)
                    frag_item.appendRow(item)
                std_item.appendRow(frag_item)
            model.appendRow(std_item)
        model.appendColumn(idItems)
Example #28
0
    def actualizeClusterModel(sample):
        model=QApplication.instance().view.clusterModel
        if model.rowCount():
            model.clear()

        idItems = []
        for peak in sample.imappedPeaks():
            std_item = QStandardItem(str(peak))
            std_item.setEditable(False)
            if peak.isFoundInDatabase:
                std_item.setBackground(QBrush(Qt.green))
                #put the formula with the best score
                o = QStandardItem(peak.formulas.keys()[0])
                o.setBackground(QBrush(Qt.green))
                idItems.append(o)
            else:
                idItems.append(QStandardItem("not found"))
            MSDialogController.setRightIcon(peak, std_item)
            if peak.isoCluster:
                iso_item = QStandardItem("isotopic cluster:")
                iso_item.setEditable(False)
                for iso in peak.isoCluster:
                    item = QStandardItem(str(iso))
                    item.setEditable(False)
                    MSDialogController.setRightIcon(iso, item)
                    iso_item.appendRow(item)
                std_item.appendRow(iso_item)
            if peak.fragCluster:
                frag_item = QStandardItem("fragments/adducts:")
                frag_item.setEditable(False)
                for frag in peak.fragCluster:
                    item =QStandardItem("/".join([str(frag.mass()), str(frag.rt), str(frag.annotation.values())[2:-2]]))
                    item.setEditable(False)
                    MSDialogController.setRightIcon(frag, item)
                    frag_item.appendRow(item)
                std_item.appendRow(frag_item)
            model.appendRow(std_item)
        model.appendColumn(idItems)
	def __init__(self, template, character, parent=None):
		super(SubPowerWidget, self).__init__(parent)

		self.__storage = template
		self.__character = character

		self.__model = QStandardItemModel()
		# Das ungenutzte Model dient dazu, alle Unterkräfte aufzunehmen, die ich nicht darstellen möchte. Ist einfacher, als diese im View zu verstecken.
		self.__modelUnused = QStandardItemModel()

		self._layout = QVBoxLayout()
		self.setLayout( self._layout )

		self.__view = QTreeView()
		self.__view.setHeaderHidden(True)
		self.__view.setModel( self.__model)

		self._layout.addWidget(self.__view)

		self._typ = "Subpower"
		categories = self.__storage.categories(self._typ)

		self.__items = {}

		self.__rootItem = QStandardItem()
		self.__rootItem = self.__model.invisibleRootItem()

		self.__rootItemUnused = QStandardItem()
		self.__rootItemUnused = self.__modelUnused.invisibleRootItem()

		for item in categories:
			categoryItem = QStandardItem(item)
			self.__rootItem.appendRow(categoryItem)

			## Ich benötige diese Items auch im ungenutzten Model.
			categoryItemUnused = QStandardItem(item)
			self.__rootItemUnused.appendRow(categoryItemUnused)
			
			traitList = list( self.__character.traits[self._typ][item].items() )
			traitList.sort()
			for trait in traitList:
				traitItem = QStandardItem(trait[1].name)
				traitItem.setCheckable(True)
				## Unhashable Type
				self.__items[trait[1]] = traitItem
				categoryItem.appendRow(traitItem)

				## Funktioniert mit PySide nicht:
				#trait[1].availableChanged.connect(traitItem.setEnabled)
				## Funktioniert auch mit PySide:
				trait[1].availableChanged.connect(
					lambda enable, item=traitItem: item.setEnabled(enable)
				)
				trait[1].valueChanged.connect(
					lambda val, trait=trait[1], item=traitItem: self.__setItemValue(trait, item)
				)

		self.__model.itemChanged.connect(self.__getItemValue)
		self.__character.speciesChanged.connect(self.hideOrShowToolPage)
		self.__character.breedChanged.connect(self.hideOrShowToolPage)
		self.__character.factionChanged.connect(self.hideOrShowToolPage)
class ProjectXML():
    def __init__(self, xmlPath, treeControl, parent=None):
        """ Constructor """
        if xmlPath is None or not os.path.isfile(xmlPath):
            msg = "..."
            q = QMessageBox(QMessageBox.Warning, "Could not find that file",
                            msg)
            q.setStandardButtons(QMessageBox.Ok)
            i = QIcon()
            i.addPixmap(QPixmap("..."), QIcon.Normal)
            q.setWindowIcon(i)
            q.exec_()
        else:
            self.tree = treeControl
            self.model = QStandardItemModel()
            # Set up an invisible root item for the tree.
            #self.treeRoot = self.model.invisibleRootItem()
            self.treeRoot = QStandardItem("Root Item")
            self.model.appendRow(self.treeRoot)
            self.tree.setModel(self.model)
            self.tree.doubleClicked.connect(self.item_doubleClicked)
            self.tree.customContextMenuRequested.connect(self.openMenu)
            self.tree.setDragEnabled(True)

            self.xmlTreeDir = os.path.join(os.path.dirname(__file__),
                                           "Resources/XML/")
            self.xmlProjfile = xmlPath
            self.xmlProjDir = os.path.dirname(xmlPath)
            self.namespace = "{http://tempuri.org/ProjectDS.xsd}"
            self.xmlTreePath = None

            # Load the GCD Project (the raw data that will be used to populate the tree)
            # instead of ET.fromstring(xml)
            self.xmlProjectDoc = self.LoadXMLFile(self.xmlProjfile)

            if self.FindTreeParser():
                print "got ya"
                # Load the tree file (the rules we use to build the tree)

            else:
                print "This is an error"

            # Set up the first domino for the recursion
            projectName = self.xmlProjectDoc.find("Project/name")
            if projectName is not None:
                self.treeRoot.setText(projectName.text)

            self.LoadNode(None, self.xmlTemplateDoc.find("node"),
                          self.xmlProjectDoc)
            self.tree.expandToDepth(5)

    def FindTreeParser(self):
        # Now we need to figure out which kind of project it is.
        for subdir, dirs, files in os.walk(self.xmlTreeDir):
            for filename in files:
                if filename.endswith(".xml"):
                    filePath = os.path.join(subdir, filename)
                    candidate = self.LoadXMLFile(filePath)
                    testNode = candidate.find('test')
                    if len(testNode.text) > 10 and not testNode is None:
                        if self.xmlProjectDoc.find("./" +
                                                   testNode.text) is not None:
                            found = True
                            self.xmlTreePath = filePath
                            self.xmlTemplateDoc = ET.parse(self.xmlTreePath)
                            return True
        return False

    def LoadXMLFile(self, file):
        with open(file, 'r') as myfile:
            data = myfile.read().replace('\n', '')
            it = ET.iterparse(StringIO(data))
            # strip all namespaces
            for _, el in it:
                if '}' in el.tag:
                    el.tag = el.tag.split('}', 1)[1]
            return it.root

    def LoadNode(self, tnParent, templateNode, projNode):
        """ Load a single node """
        data = {}
        label = self.getLabel(templateNode, projNode)

        # Detect if this is an XML node element and reset the root Project node to this.
        entityType = templateNode.find('entity/type')
        entityXPath = templateNode.find('entity/xpath')
        newProjNode = projNode

        if entityXPath is not None:
            newProjNode = projNode.find(entityXPath.text)

        # This node might be a leaf. If so we need to get some meta dat
        if entityType is not None and entityXPath is not None:
            filepathNode = projNode.find(entityXPath.text)
            if filepathNode is not None:
                # normalize the slashes
                # filepath = re.sub('[\\\/]+', os.path.sep, filepathNode.text)
                # make it an absolute path
                filepath = os.path.join(self.xmlProjDir, filepathNode.text)
                data['filepath'] = filepath
            if entityXPath is not None:
                data['xpath'] = entityXPath.text
            symbologyNode = templateNode.find('entity/symbology')
            if symbologyNode is not None:
                data['symbology'] = symbologyNode.text

        # Add the leaf to the tree
        newTreeItem = QStandardItem(label)

        if tnParent is None:
            self.treeRoot.appendRow(newTreeItem)
        else:
            tnParent = tnParent.appendRow(newTreeItem)

        # Just a regular node with children
        for xChild in templateNode.findall("children/node"):
            self.LoadNode(newTreeItem, xChild, newProjNode)
        for xRepeater in templateNode.findall("children/repeater"):
            self.LoadRepeater(newTreeItem, xRepeater, newProjNode)

        data['group_layers'] = self.getTreeAncestry(newTreeItem)
        newTreeItem.setData(data)

    def LoadRepeater(self, tnParent, templateNode, projNode):
        """ Repeater is for using an XPAth in the project file for repeating elements """

        label = self.getLabel(templateNode, projNode)

        newTreeItem = QStandardItem(label)
        if tnParent is None:
            self.treeRoot.appendRow(newTreeItem)
        else:
            tnParent = tnParent.appendRow(newTreeItem)

        # REmember, repeaters can only contain one "pattern" node
        xPatternNode = templateNode.find("node")

        # If there is an Xpath then reset the base project node to that.
        xpath = templateNode.find("xpath")
        xNewProjList = []
        if xPatternNode is not None and xpath is not None:
            absoluteXPath = xpath.text[:1] == "/"
            # Should we search from the root or not.
            if absoluteXPath:
                xNewProjList = self.xmlProjectDoc.findall("." + xpath.text)
            else:
                xNewProjList = projNode.findall(xpath.text)

        for xProjChild in xNewProjList:
            self.LoadNode(newTreeItem, xPatternNode, xProjChild)

    def getTreeAncestry(self, item):
        ancestry = []
        parent = item.parent()
        while parent is not None:
            ancestry.append(parent.text())
            parent = parent.parent()
        ancestry.reverse()
        return ancestry

    def item_doubleClicked(self, index):
        item = self.tree.selectedIndexes()[0]
        self.addToMap(item.model().itemFromIndex(index))

    def openMenu(self, position):
        """ Handle the contextual menu """
        index = self.tree.selectedIndexes()[0]
        item = index.model().itemFromIndex(index)
        menu = QMenu()

        receiver = lambda item=item: self.addToMap(item)
        menu.addAction("Add to Map", receiver)

        menu.exec_(self.tree.viewport().mapToGlobal(position))

    def getLabel(self, templateNode, projNode):
        """ Either use the liral text inside <label> or look it
            up in the project node if there's a <label xpath="/x/path">
        """
        labelNode = templateNode.find("label")
        label = "TITLE_NOT_FOUND"
        if labelNode is not None:
            if "xpath" in labelNode.attrib:
                xpath = labelNode.attrib['xpath']
                label = projNode.find(xpath).text
            else:
                label = labelNode.text

        return label

    def addToMap(self, item):
        print "ADDING TO MAP::", item.data()
        itemExt = path.splitext(item.data()['filepath'])[1]
        if itemExt == '.shp':
            AddVectorLayer(item)
        else:
            AddRasterLayer(item)
Example #31
0
    def fillTree(self):
        self.items = {}
        self.model.clear()
        self.model.setHorizontalHeaderLabels([self.tr('Setting'),
                                              self.tr('Value')])

        text = unicode(self.searchBox.text())
        settings = ProcessingConfig.getSettings()

        rootItem = self.model.invisibleRootItem()
        priorityKeys = [self.tr('General'), self.tr('Models'), self.tr('Scripts')]
        for group in priorityKeys:
            groupItem = QStandardItem(group)
            icon = ProcessingConfig.getGroupIcon(group)
            groupItem.setIcon(icon)
            groupItem.setEditable(False)
            emptyItem = QStandardItem()
            emptyItem.setEditable(False)
            rootItem.insertRow(0, [groupItem, emptyItem])
            for setting in settings[group]:
                if setting.hidden or setting.name.startswith("MENU_"):
                    continue

                if text == '' or text.lower() in setting.description.lower():
                    labelItem = QStandardItem(setting.description)
                    labelItem.setIcon(icon)
                    labelItem.setEditable(False)
                    self.items[setting] = SettingItem(setting)
                    groupItem.insertRow(0, [labelItem, self.items[setting]])

            if text != '':
                self.tree.expand(groupItem.index())

        providersItem = QStandardItem(self.tr('Providers'))
        icon = QIcon(os.path.join(pluginPath, 'images', 'alg.png'))
        providersItem.setIcon(icon)
        providersItem.setEditable(False)
        emptyItem = QStandardItem()
        emptyItem.setEditable(False)
        rootItem.insertRow(0, [providersItem, emptyItem])
        for group in settings.keys():
            if group in priorityKeys or group == menusSettingsGroup:
                continue

            groupItem = QStandardItem(group)
            icon = ProcessingConfig.getGroupIcon(group)
            groupItem.setIcon(icon)
            groupItem.setEditable(False)
            for setting in settings[group]:
                if setting.hidden:
                    continue

                if text == '' or text.lower() in setting.description.lower():
                    labelItem = QStandardItem(setting.description)
                    labelItem.setIcon(icon)
                    labelItem.setEditable(False)
                    self.items[setting] = SettingItem(setting)
                    groupItem.insertRow(0, [labelItem, self.items[setting]])

            emptyItem = QStandardItem()
            emptyItem.setEditable(False)
            providersItem.appendRow([groupItem, emptyItem])

        menusItem = QStandardItem(self.tr('Menus (requires restart)'))
        icon = QIcon(os.path.join(pluginPath, 'images', 'menu.png'))
        menusItem.setIcon(icon)
        menusItem.setEditable(False)
        emptyItem = QStandardItem()
        emptyItem.setEditable(False)
        rootItem.insertRow(0, [menusItem, emptyItem])
        providers = Processing.providers
        for provider in providers:
            groupItem = QStandardItem(provider.getDescription())
            icon = provider.getIcon()
            groupItem.setIcon(icon)
            groupItem.setEditable(False)
            for alg in provider.algs:
                labelItem = QStandardItem(alg.name)
                labelItem.setIcon(icon)
                labelItem.setEditable(False)
                try:
                    setting = ProcessingConfig.settings["MENU_" + alg.commandLineName()]
                except:
                    continue
                self.items[setting] = SettingItem(setting)
                groupItem.insertRow(0, [labelItem, self.items[setting]])
            emptyItem = QStandardItem()
            emptyItem.setEditable(False)
            menusItem.appendRow([groupItem, emptyItem])

        self.tree.sortByColumn(0, Qt.AscendingOrder)
        self.adjustColumns()
Example #32
0
    def add_device_to_tree(self, device):
        # check if device is already added
        if len(device['uid']) > 0:
            for row in range(self.model_devices.rowCount()):
                existing_name = self.model_devices.item(row, 0).text()
                exisitng_uid = self.tree_devices.indexWidget(self.model_devices.item(row, 1).index()).text()

                if device['name'] == existing_name and device['uid'] == exisitng_uid:
                    EventLogger.info('Ignoring duplicate device "{0}" with UID "{1}"'
                                     .format(device['name'], device['uid']))
                    return

        # add device
        name_item = QStandardItem(device['name'])
        uid_item = QStandardItem('')

        self.model_devices.appendRow([name_item, uid_item])

        edit_uid = QLineEdit()
        edit_uid.setPlaceholderText('Enter UID')
        edit_uid.setValidator(QRegExpValidator(QRegExp('^[{0}]{{1,6}}$'.format(BASE58)))) # FIXME: use stricter logic
        edit_uid.setText(device['uid'])

        self.tree_devices.setIndexWidget(uid_item.index(), edit_uid)

        value_specs = device_specs[device['name']]['values']
        parent_item = QStandardItem('Values')

        name_item.appendRow([parent_item, QStandardItem('')])
        self.tree_devices.expand(parent_item.index())

        # add values
        for value_spec in value_specs:
            value_name_item = QStandardItem(value_spec['name'])
            value_interval_item = QStandardItem('')

            parent_item.appendRow([value_name_item, value_interval_item])

            spinbox_interval = QSpinBox()
            spinbox_interval.setRange(0, (1 << 31) - 1)
            spinbox_interval.setSingleStep(1)
            spinbox_interval.setValue(device['values'][value_spec['name']]['interval'])
            spinbox_interval.setSuffix(' seconds')

            self.tree_devices.setIndexWidget(value_interval_item.index(), spinbox_interval)

            if value_spec['subvalues'] != None:
                for subvalue_name in value_spec['subvalues']:
                    subvalue_name_item = QStandardItem(subvalue_name)
                    subvalue_check_item = QStandardItem('')

                    value_name_item.appendRow([subvalue_name_item, subvalue_check_item])

                    check_subvalue = QCheckBox()
                    check_subvalue.setChecked(device['values'][value_spec['name']]['subvalues'][subvalue_name])

                    self.tree_devices.setIndexWidget(subvalue_check_item.index(), check_subvalue)

        self.tree_devices.expand(name_item.index())

        # add options
        option_specs = device_specs[device['name']]['options']

        if option_specs != None:
            parent_item = QStandardItem('Options')

            name_item.appendRow([parent_item, QStandardItem('')])

            for option_spec in option_specs:
                option_name_item = QStandardItem(option_spec['name'])
                option_widget_item = QStandardItem('')

                parent_item.appendRow([option_name_item, option_widget_item])

                if option_spec['type'] == 'choice':
                    widget_option_value = QComboBox()

                    for option_value_spec in option_spec['values']:
                        widget_option_value.addItem(option_value_spec[0].decode('utf-8'), option_value_spec[1])

                    widget_option_value.setCurrentIndex(widget_option_value.findText(device['options'][option_spec['name']]['value'].decode('utf-8')))
                elif option_spec['type'] == 'int':
                    widget_option_value = QSpinBox()
                    widget_option_value.setRange(option_spec['minimum'], option_spec['maximum'])
                    widget_option_value.setSuffix(option_spec['suffix'])
                    widget_option_value.setValue(device['options'][option_spec['name']]['value'])
                elif option_spec['type'] == 'bool':
                    widget_option_value = QCheckBox()
                    widget_option_value.setChecked(device['options'][option_spec['name']]['value'])

                self.tree_devices.setIndexWidget(option_widget_item.index(), widget_option_value)
Example #33
0
    def add_device_to_tree(self, device):
        # check if device is already added
        if len(device['uid']) > 0:
            for row in range(self.model_devices.rowCount()):
                existing_name = self.model_devices.item(row, 0).text()
                exisitng_uid = self.tree_devices.indexWidget(
                    self.model_devices.item(row, 1).index()).text()

                if device['name'] == existing_name and device[
                        'uid'] == exisitng_uid:
                    EventLogger.info(
                        'Ignoring duplicate device "{0}" with UID "{1}"'.
                        format(device['name'], device['uid']))
                    return

        # add device
        name_item = QStandardItem(device['name'])
        uid_item = QStandardItem('')

        self.model_devices.appendRow([name_item, uid_item])

        edit_uid = QLineEdit()
        edit_uid.setPlaceholderText('Enter UID')
        edit_uid.setValidator(
            QRegExpValidator(QRegExp(
                '^[{0}]{{1,6}}$'.format(BASE58))))  # FIXME: use stricter logic
        edit_uid.setText(device['uid'])

        self.tree_devices.setIndexWidget(uid_item.index(), edit_uid)

        value_specs = device_specs[device['name']]['values']
        parent_item = QStandardItem('Values')

        name_item.appendRow([parent_item, QStandardItem('')])
        self.tree_devices.expand(parent_item.index())

        # add values
        for value_spec in value_specs:
            value_name_item = QStandardItem(value_spec['name'])
            value_interval_item = QStandardItem('')

            parent_item.appendRow([value_name_item, value_interval_item])

            spinbox_interval = QSpinBox()
            spinbox_interval.setRange(0, (1 << 31) - 1)
            spinbox_interval.setSingleStep(1)
            spinbox_interval.setValue(
                device['values'][value_spec['name']]['interval'])
            spinbox_interval.setSuffix(' seconds')

            self.tree_devices.setIndexWidget(value_interval_item.index(),
                                             spinbox_interval)

            if value_spec['subvalues'] != None:
                for subvalue_name in value_spec['subvalues']:
                    subvalue_name_item = QStandardItem(subvalue_name)
                    subvalue_check_item = QStandardItem('')

                    value_name_item.appendRow(
                        [subvalue_name_item, subvalue_check_item])

                    check_subvalue = QCheckBox()
                    check_subvalue.setChecked(device['values'][
                        value_spec['name']]['subvalues'][subvalue_name])

                    self.tree_devices.setIndexWidget(
                        subvalue_check_item.index(), check_subvalue)

        self.tree_devices.expand(name_item.index())

        # add options
        option_specs = device_specs[device['name']]['options']

        if option_specs != None:
            parent_item = QStandardItem('Options')

            name_item.appendRow([parent_item, QStandardItem('')])

            for option_spec in option_specs:
                option_name_item = QStandardItem(option_spec['name'])
                option_widget_item = QStandardItem('')

                parent_item.appendRow([option_name_item, option_widget_item])

                if option_spec['type'] == 'choice':
                    widget_option_value = QComboBox()

                    for option_value_spec in option_spec['values']:
                        widget_option_value.addItem(
                            option_value_spec[0].decode('utf-8'),
                            option_value_spec[1])

                    widget_option_value.setCurrentIndex(
                        widget_option_value.findText(device['options'][
                            option_spec['name']]['value'].decode('utf-8')))
                elif option_spec['type'] == 'int':
                    widget_option_value = QSpinBox()
                    widget_option_value.setRange(option_spec['minimum'],
                                                 option_spec['maximum'])
                    widget_option_value.setSuffix(option_spec['suffix'])
                    widget_option_value.setValue(
                        device['options'][option_spec['name']]['value'])
                elif option_spec['type'] == 'bool':
                    widget_option_value = QCheckBox()
                    widget_option_value.setChecked(
                        device['options'][option_spec['name']]['value'])

                self.tree_devices.setIndexWidget(option_widget_item.index(),
                                                 widget_option_value)
class SubPowerWidget(QWidget):
    """
	@brief Zeigt alle Unterkräfte in einer Baumstruktur an.
	"""
    def __init__(self, template, character, parent=None):
        super(SubPowerWidget, self).__init__(parent)

        self.__storage = template
        self.__character = character

        self.__model = QStandardItemModel()
        # Das ungenutzte Model dient dazu, alle Unterkräfte aufzunehmen, die ich nicht darstellen möchte. Ist einfacher, als diese im View zu verstecken.
        self.__modelUnused = QStandardItemModel()

        self._layout = QVBoxLayout()
        self.setLayout(self._layout)

        self.__view = QTreeView()
        self.__view.setHeaderHidden(True)
        self.__view.setModel(self.__model)

        self._layout.addWidget(self.__view)

        self._typ = "Subpower"
        categories = self.__storage.categories(self._typ)

        self.__items = {}

        self.__rootItem = QStandardItem()
        self.__rootItem = self.__model.invisibleRootItem()

        self.__rootItemUnused = QStandardItem()
        self.__rootItemUnused = self.__modelUnused.invisibleRootItem()

        for item in categories:
            categoryItem = QStandardItem(item)
            self.__rootItem.appendRow(categoryItem)

            ## Ich benötige diese Items auch im ungenutzten Model.
            categoryItemUnused = QStandardItem(item)
            self.__rootItemUnused.appendRow(categoryItemUnused)

            traitList = list(self.__character.traits[self._typ][item].items())
            traitList.sort()
            for trait in traitList:
                traitItem = QStandardItem(trait[1].name)
                traitItem.setCheckable(True)
                ## Unhashable Type
                self.__items[trait[1]] = traitItem
                categoryItem.appendRow(traitItem)

                ## Funktioniert mit PySide nicht:
                #trait[1].availableChanged.connect(traitItem.setEnabled)
                ## Funktioniert auch mit PySide:
                trait[1].availableChanged.connect(
                    lambda enable, item=traitItem: item.setEnabled(enable))
                trait[1].valueChanged.connect(lambda val, trait=trait[
                    1], item=traitItem: self.__setItemValue(trait, item))

        self.__model.itemChanged.connect(self.__getItemValue)
        self.__character.speciesChanged.connect(self.hideOrShowToolPage)
        self.__character.breedChanged.connect(self.hideOrShowToolPage)
        self.__character.factionChanged.connect(self.hideOrShowToolPage)

    def __setItemValue(self, trait, item):
        """
		Setzt den Wert der Angezeigten Items.
		"""

        if trait.value == 0:
            item.setCheckState(Qt.Unchecked)
        elif trait.value == 1:
            item.setCheckState(Qt.PartiallyChecked)
        else:
            item.setCheckState(Qt.Checked)

    def __getItemValue(self, item):
        """
		Setzt den Wert der Eigenschaft im Speicher.
		"""

        for trait in self.__items.items():
            if id(trait[1]) == id(item):
                trait[0].value = item.checkState()
                break

    def hideOrShowToolPage(self, res):
        """
		Alle Eigenschaften, die nicht zur Verfügung stehen, werden verborgen, indem sie in ein anderes Model verschoben werden.

		\bug Möglicher Fehler in PySide: Der Aufruf von QStandardItem.model() führt beim Beenden des Programms zu einem Segmentation Fault.
		"""

        # Versteckt alle Unterkräfte, die zu gewähltem Charakter nicht passen.
        for item in self.__items.items():
            if ((item[0].species
                 and item[0].species != self.__character.species) or
                (item[0].only and self.__character.breed not in item[0].only
                 and self.__character.faction not in item[0].only)):
                #self.__view.setRowHidden(item[1].index().row(), item[1].parent().index(), True)
                #Debug.debug(item[1].model())
                ## Hier wird beispielsweise besagter Aufruf getätigt, der zu einem segfault führt.
                if item[1].model() == self.__model:
                    parent = item[1].parent()
                    itemUnused = parent.takeRow(item[1].index().row())
                    parentUnused = self.__modelUnused.findItems(
                        parent.text())[0]
                    parentUnused.appendRow(itemUnused)
            else:
                #self.__view.setRowHidden(item[1].index().row(), item[1].parent().index(), False)
                if item[1].model() == self.__modelUnused:
                    parent = item[1].parent()
                    itemUsed = parent.takeRow(item[1].index().row())
                    parentUsed = self.__model.findItems(parent.text())[0]
                    parentUsed.appendRow(itemUsed)

        ## Versteckt alle Elternzeilen, wenn sie keine Kinder enthalten.
        for i in range(self.__model.rowCount()):
            categoryItem = self.__model.item(i)
            if categoryItem.hasChildren():
                self.__view.setRowHidden(categoryItem.index().row(),
                                         self.__rootItem.index(), False)
            else:
                self.__view.setRowHidden(categoryItem.index().row(),
                                         self.__rootItem.index(), True)
Example #35
0
    for j in range(4):
        item = QStandardItem("({0}, {1})".format(i, j))
        model.setItem(i, j, item)
        if i == 1:
            item.appendRow([QStandardItem("..({0}, {1})".format(i*3, k)) for k in range(4)])
"""

model = QStandardItemModel(2,1)
model.setHorizontalHeaderItem(0,QStandardItem("Menu"))
cadastro = QStandardItem("Cadastro")
model.setItem(0,0,cadastro)
pesquisa = QStandardItem("Pesquisa")
model.setItem(1,0,pesquisa)

for i in ["Usuarios", "Empresas"]:
    cadastro.appendRow(QStandardItem(i))
    pesquisa.appendRow(QStandardItem(i))

parent = QModelIndex()

"""model = QDirModel()
model.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot)
parent = model.index(QDir.currentPath())"""

"""model = QFileSystemModel()"""

    
p = PainelConsole()
l = TreeViewTela(6)
l.setModel(model)
l.setRootIndex(parent)
Example #36
0
class OrderTreeModel(QAbstractItemModel):
    """"""
    order_reg = re.compile(u'订单[0-9]+')

    def __init__(self, order):
        super(OrderTreeModel, self).__init__()
        self.__root = QStandardItem()
        self.append_orders(order)

    def data(self, index, role=Qt.DisplayRole):
        """获取index位置的数据"""
        if not index.isValid():
            return QVariant()
        if role == Qt.TextColorRole:
            node = self.node_from_index(index)
            string = node.text()
            if OrderTreeModel.order_reg.match(string):  # 订单结点
                profit_child = node.child(6)  # 第6个孩子结点是收益结点
                if '-' in profit_child.text():  # 收益为负,订单结点绿色,否则红色
                    return QBrush(QColor(0, 180, 0))
                else:
                    return QBrush(QColor(255, 0, 0))
        elif role == Qt.DisplayRole:
            node = self.node_from_index(index)
            return QVariant(node.text())
        else:
            return QVariant()

    def node_from_index(self, index):
        if index.isValid():
            return index.internalPointer()
        else:
            return self.__root

    def index(self, row, column, parent=None, *args, **kwargs):
        if not self.hasIndex(row, column, parent):
            return QModelIndex()
        if not parent.isValid():
            parent_item = self.__root
        else:
            parent_item = parent.internalPointer()
        child_item = parent_item.child(row)
        if child_item:
            return self.createIndex(row, column, child_item)
        else:
            return QModelIndex()

    def parent(self, index=None):
        if not index.isValid():
            return QModelIndex()
        child_item = index.internalPointer()
        parent_item = child_item.parent()
        if parent_item == self.__root:
            return QModelIndex()
        return self.createIndex(parent_item.row(), 0, parent_item)

    def columnCount(self, parent=None, *args, **kwargs):
        return 1

    def rowCount(self, parent=None, *args, **kwargs):
        if not parent.isValid():
            parent_item = self.__root
        else:
            parent_item = parent.internalPointer()
        return parent_item.rowCount()

    def append_orders(self, orders):
        for i, order in enumerate(orders):
            order_item = QStandardItem(self.tr('订单') + str(i))
            self.append_order_details(order_item, order)
            self.__root.appendRow(order_item)

    def append_order_details(self, order_item, order):
        order_id = QStandardItem(self.tr('订单编号: ' + str(order.order_id)))
        strategy_id = QStandardItem(self.tr('策略编号: ') + str(order.strategy_id))
        symbol = QStandardItem(self.tr('品种: ') + str(order.symbol))
        direction = self.tr('买入') if order.type == ORDER_BUY else self.tr('卖出')
        direction = QStandardItem(self.tr('方向: ') + direction)
        price = QStandardItem(self.tr('开仓价: ') + str(order.price))
        open_time = QStandardItem(self.tr('开仓时间: ') + str(order.order_time))
        order_profit = QStandardItem(self.tr('总盈利: ') + str(order.profit))
        close_profit = QStandardItem(self.tr('每次平仓盈利'))
        for item in zip(order.get_close_profit_list(),
                        order.get_close_time_list()):
            cp = QStandardItem(str(item[1]) + self.tr(': ') + str(item[0]))
            close_profit.appendRow(cp)

        order_item.appendRow(order_id)
        order_item.appendRow(strategy_id)
        order_item.appendRow(symbol)
        order_item.appendRow(direction)
        order_item.appendRow(price)
        order_item.appendRow(open_time)
        order_item.appendRow(order_profit)
        order_item.appendRow(close_profit)
class SubPowerWidget(QWidget):
	"""
	@brief Zeigt alle Unterkräfte in einer Baumstruktur an.
	"""


	def __init__(self, template, character, parent=None):
		super(SubPowerWidget, self).__init__(parent)

		self.__storage = template
		self.__character = character

		self.__model = QStandardItemModel()
		# Das ungenutzte Model dient dazu, alle Unterkräfte aufzunehmen, die ich nicht darstellen möchte. Ist einfacher, als diese im View zu verstecken.
		self.__modelUnused = QStandardItemModel()

		self._layout = QVBoxLayout()
		self.setLayout( self._layout )

		self.__view = QTreeView()
		self.__view.setHeaderHidden(True)
		self.__view.setModel( self.__model)

		self._layout.addWidget(self.__view)

		self._typ = "Subpower"
		categories = self.__storage.categories(self._typ)

		self.__items = {}

		self.__rootItem = QStandardItem()
		self.__rootItem = self.__model.invisibleRootItem()

		self.__rootItemUnused = QStandardItem()
		self.__rootItemUnused = self.__modelUnused.invisibleRootItem()

		for item in categories:
			categoryItem = QStandardItem(item)
			self.__rootItem.appendRow(categoryItem)

			## Ich benötige diese Items auch im ungenutzten Model.
			categoryItemUnused = QStandardItem(item)
			self.__rootItemUnused.appendRow(categoryItemUnused)
			
			traitList = list( self.__character.traits[self._typ][item].items() )
			traitList.sort()
			for trait in traitList:
				traitItem = QStandardItem(trait[1].name)
				traitItem.setCheckable(True)
				## Unhashable Type
				self.__items[trait[1]] = traitItem
				categoryItem.appendRow(traitItem)

				## Funktioniert mit PySide nicht:
				#trait[1].availableChanged.connect(traitItem.setEnabled)
				## Funktioniert auch mit PySide:
				trait[1].availableChanged.connect(
					lambda enable, item=traitItem: item.setEnabled(enable)
				)
				trait[1].valueChanged.connect(
					lambda val, trait=trait[1], item=traitItem: self.__setItemValue(trait, item)
				)

		self.__model.itemChanged.connect(self.__getItemValue)
		self.__character.speciesChanged.connect(self.hideOrShowToolPage)
		self.__character.breedChanged.connect(self.hideOrShowToolPage)
		self.__character.factionChanged.connect(self.hideOrShowToolPage)


	def __setItemValue(self, trait, item):
		"""
		Setzt den Wert der Angezeigten Items.
		"""

		if trait.value == 0:
			item.setCheckState(Qt.Unchecked)
		elif trait.value == 1:
			item.setCheckState(Qt.PartiallyChecked)
		else:
			item.setCheckState(Qt.Checked)


	def __getItemValue(self, item):
		"""
		Setzt den Wert der Eigenschaft im Speicher.
		"""

		for trait in self.__items.items():
			if id(trait[1]) == id(item):
				trait[0].value = item.checkState()
				break


	def hideOrShowToolPage(self, res):
		"""
		Alle Eigenschaften, die nicht zur Verfügung stehen, werden verborgen, indem sie in ein anderes Model verschoben werden.

		\bug Möglicher Fehler in PySide: Der Aufruf von QStandardItem.model() führt beim Beenden des Programms zu einem Segmentation Fault.
		"""

		# Versteckt alle Unterkräfte, die zu gewähltem Charakter nicht passen.
		for item in self.__items.items():
			if (
				(
					item[0].species and
					item[0].species != self.__character.species
				) or (
					item[0].only and
					self.__character.breed not in item[0].only and
					self.__character.faction not in item[0].only
				)
			):
				#self.__view.setRowHidden(item[1].index().row(), item[1].parent().index(), True)
				#Debug.debug(item[1].model())
				## Hier wird beispielsweise besagter Aufruf getätigt, der zu einem segfault führt.
				if item[1].model() == self.__model:
					parent = item[1].parent()
					itemUnused = parent.takeRow(item[1].index().row())
					parentUnused = self.__modelUnused.findItems(parent.text())[0]
					parentUnused.appendRow(itemUnused)
			else:
				#self.__view.setRowHidden(item[1].index().row(), item[1].parent().index(), False)
				if item[1].model() == self.__modelUnused:
					parent = item[1].parent()
					itemUsed = parent.takeRow(item[1].index().row())
					parentUsed = self.__model.findItems(parent.text())[0]
					parentUsed.appendRow(itemUsed)

		## Versteckt alle Elternzeilen, wenn sie keine Kinder enthalten.
		for i in range(self.__model.rowCount()):
			categoryItem = self.__model.item(i)
			if categoryItem.hasChildren():
				self.__view.setRowHidden(categoryItem.index().row(), self.__rootItem.index(), False)
			else:
				self.__view.setRowHidden(categoryItem.index().row(), self.__rootItem.index(), True)
Example #38
0
class GCDXML():
    
    def __init__(self, xmlPath, treeControl, parent = None):
        """ Constructor """
        if xmlPath is None or not os.path.isfile(xmlPath):
            msg = "..."
            q = QMessageBox(QMessageBox.Warning, "Could not find that file",  msg)
            q.setStandardButtons(QMessageBox.Ok);
            i = QIcon()
            i.addPixmap(QPixmap("..."), QIcon.Normal)
            q.setWindowIcon(i)
            q.exec_()
        else:
            self.tree = treeControl
            self.model = QStandardItemModel()
            # Set up an invisible root item for the tree.
            #self.treeRoot = self.model.invisibleRootItem()
            self.treeRoot = QStandardItem("Root Item")
            self.model.appendRow(self.treeRoot)
            self.tree.setModel(self.model)
            self.tree.doubleClicked.connect(self.item_doubleClicked)
            self.tree.customContextMenuRequested.connect(self.openMenu)
            self.tree.setDragEnabled(True)

            # This is the GCD projet viewer so no harm in hardcoding this for now.
            self.xmlTreePath = os.path.join(os.path.dirname(__file__), "Resources/XML/gcd_tree.xml")
            self.xmlProjfile = xmlPath
            self.xmlProjDir = os.path.dirname(xmlPath)
            self.namespace = "{http://tempuri.org/ProjectDS.xsd}"
            
            # Load the tree file (the rules we use to build the tree)
            self.xmlTemplateDoc = ET.parse(self.xmlTreePath)
            # Load the GCD Project (the raw data that will be used to populate the tree)
            # instead of ET.fromstring(xml)
            with open(self.xmlProjfile, 'r') as myfile:
                data=myfile.read().replace('\n', '')
                it = ET.iterparse(StringIO(data))
                for _, el in it:
                    if '}' in el.tag:
                        el.tag = el.tag.split('}', 1)[1]  # strip all namespaces
                self.xmlProjectDoc = it.root
                        
            # Set up the first domino for the recursion         
            projectName = self.xmlProjectDoc.find("Project/Name")
            if projectName is not None:
                self.treeRoot.setText(projectName.text)
   
            self.LoadNode(None, self.xmlTemplateDoc.find("node"), self.xmlProjectDoc)
            self.tree.expandToDepth(5)
                    
                        
    def LoadNode(self, tnParent, templateNode, projNode):
        """ Load a single node """
        data = {}
        label = self.getLabel(templateNode, projNode)

        # Detect if this is an XML node element and reset the root Project node to this.
        entityType = templateNode.find('entity/type')
        entityXPath = templateNode.find('entity/xpath')
        newProjNode = projNode

        if entityXPath is not None:
            newProjNode = projNode.find(entityXPath.text)        
        
        # This node might be a leaf. If so we need to get some meta dat
        if entityType is not None:
            filepathNode = projNode.find(entityXPath.text)
            if filepathNode is not None: 
                # normalize the slashes
                filepath = re.sub('[\\\/]+', os.path.sep, filepathNode.text) 
                # make it an absolute path
                filepath = os.path.join(self.xmlProjDir, filepath)
                data['filepath'] = filepath
            if entityXPath is not None:
                data['xpath'] = entityXPath.text
            symbologyNode = templateNode.find('entity/symbology')
            if symbologyNode is not None: 
                data['symbology'] = symbologyNode.text
            
        # Add the leaf to the tree
        newTreeItem = QStandardItem(label)

        if tnParent is None:
            self.treeRoot.appendRow(newTreeItem)
        else:
            tnParent = tnParent.appendRow(newTreeItem)        
        
        # Just a regular node with children
        for xChild in templateNode.findall("children/node"):
            self.LoadNode(newTreeItem, xChild, newProjNode)
        for xRepeater in templateNode.findall("children/repeater"):
            self.LoadRepeater(newTreeItem, xRepeater, newProjNode)

        data['group_layers'] = self.getTreeAncestry(newTreeItem)
        newTreeItem.setData(data)

    def LoadRepeater(self, tnParent, templateNode, projNode):
        """ Repeater is for using an XPAth in the project file for repeating elements """
        
        label = self.getLabel(templateNode, projNode)
        
        newTreeItem = QStandardItem(label)
        if tnParent is None:
            self.treeRoot.appendRow(newTreeItem)
        else:
            tnParent = tnParent.appendRow(newTreeItem)                
            
        # REmember, repeaters can only contain one "pattern" node
        xPatternNode = templateNode.find("node")

        # If there is an Xpath then reset the base project node to that.   
        xpath = templateNode.find("xpath")
        xNewProjList = []
        if xPatternNode is not None and xpath is not None:
            absoluteXPath = xpath.text[:1] == "/"
            # Should we search from the root or not.
            if absoluteXPath:
                xNewProjList = self.xmlProjectDoc.findall("." + xpath.text)
            else:
                xNewProjList = projNode.findall(xpath.text)

        for xProjChild in xNewProjList:
            self.LoadNode(newTreeItem, xPatternNode, xProjChild)    
    
    def getTreeAncestry(self, item):
        ancestry = []
        parent = item.parent()
        while parent is not None:
            ancestry.append(parent.text())
            parent = parent.parent()
        ancestry.reverse()
        return ancestry
    
    
    def item_doubleClicked(self, index):
        item = self.tree.selectedIndexes()[0]
        self.addToMap( item.model().itemFromIndex(index))
    
    

    def openMenu(self, position):
        """ Handle the contextual menu """
        index = self.tree.selectedIndexes()[0]
        item = index.model().itemFromIndex(index)
        menu = QMenu()
        
        receiver = lambda item=item: self.addToMap(item)
        menu.addAction("Add to Map", receiver)

        menu.exec_(self.tree.viewport().mapToGlobal(position))
    
    def getLabel(self, templateNode, projNode):
        """ Either use the liral text inside <label> or look it
            up in the project node if there's a <label xpath="/x/path">
        """
        labelNode = templateNode.find("label")
        label = "TITLE_NOT_FOUND"
        if labelNode is not None:
            if "xpath" in labelNode.attrib:
                xpath = labelNode.attrib['xpath']
                label = projNode.find(xpath).text
            else:
                label = labelNode.text      
                
        return label
    
    def addToMap(self, item):
        print "ADDING TO MAP::", item.data()
        
        AddRasterLayer(item)
        
Example #39
0
    def randomize_groups(self):
        #participant_list_form = Participant_list()
        #participant_list_form.show()
        #participant_list_form.ui3.label.setText("sdsdfdsf")
        #ex2.ui.label_6.setText("test")
        participant_list_form = ex3
        # participant_list_form = Participant_list()
        # participant_list_form.show()
        tv = participant_list_form.ui3.tableView

        # set the table model
        tablemdata = 0
        #tabledata.append([2, 2, 2, 2, 2])
        # tabledata.remove([0])
        # tabledata.append([1, 1, 1, 1, 1])
        # table.model().layoutChanged.emit()
        tablemodel = MyTableModel(tabledata, header, self)
        rowcount = int(tablemodel.rowCount(None))
        tvmodel = tv.model()
        nums = [x+1 for x in range(rowcount)]
        random.shuffle(nums)

        print nums

        #iterating list





        #print i+1 % groups_to_create

        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # init widgets
        view = ex8.ui8.treeView
        view.setSelectionBehavior(QAbstractItemView.SelectRows)
        model = QStandardItemModel()
        model.setHorizontalHeaderLabels(header)
        view.setModel(model)
        view.setUniformRowHeights(True)
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # populate data

        groups_to_create = int(self.ui.lineEdit.text())
        participants_in_group = int(self.ui.lineEdit_2.text())
        divider = 0
        group = 1
        parent1 = QStandardItem('Grupa {}'.format(group))
        for i, val in enumerate(nums):

            if divider == participants_in_group:
                divider = 0
                group = group + 1
                parent1 = QStandardItem('Grupa {}'.format(group))
            divider = divider + 1
            if val != 0:
                print "Grupa " + str(group) + " Osoby: " + str(val)
                self.tableindex_id = tablemodel.index (val-1,1)
                self.tableindex_surname = tablemodel.index (val-1,2)
                child1 = QStandardItem(str(val)+' '+" ")
                child2 = QStandardItem(str(tablemodel.data(self.tableindex_id,  Qt.DisplayRole)))
                child3 = QStandardItem(str(tablemodel.data(self.tableindex_surname,  Qt.DisplayRole)))
                parent1.appendRow([child1, child2, child3])


                model.appendRow(parent1)
                # span container columns
                view.setFirstColumnSpanned(i, view.rootIndex(), True)


        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # expand third container
        index = model.indexFromItem(parent1)
        view.expand(index)
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # select last row
        selmod = view.selectionModel()
        index2 = model.indexFromItem(child3)
        selmod.select(index2, QItemSelectionModel.Select | QItemSelectionModel.Rows)
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        print i+1
        if i+1 > 3:
            print i / groups_to_create
        else:
            print i / groups_to_create

        #index = tablemodel.index(row, 1)

        print nums
Example #40
0
    def fillTree(self):
        self.items = {}
        self.model.clear()
        self.model.setHorizontalHeaderLabels([self.tr('Setting'),
                                              self.tr('Value')])

        text = unicode(self.searchBox.text())
        settings = ProcessingConfig.getSettings()

        rootItem = self.model.invisibleRootItem()
        priorityKeys = [self.tr('General'), self.tr('Models'), self.tr('Scripts')]
        for group in priorityKeys:
            groupItem = QStandardItem(group)
            icon = ProcessingConfig.getGroupIcon(group)
            groupItem.setIcon(icon)
            groupItem.setEditable(False)
            emptyItem = QStandardItem()
            emptyItem.setEditable(False)
            rootItem.insertRow(0, [groupItem, emptyItem])
            for setting in settings[group]:
                if setting.hidden:
                    continue

                if text == '' or text.lower() in setting.description.lower():
                    labelItem = QStandardItem(setting.description)
                    labelItem.setIcon(icon)
                    labelItem.setEditable(False)
                    self.items[setting] = SettingItem(setting)
                    groupItem.insertRow(0, [labelItem, self.items[setting]])

            if text != '':
                self.tree.expand(groupItem.index())

        providersItem = QStandardItem(self.tr('Providers'))
        icon = QIcon(os.path.join(pluginPath, 'images', 'alg.png'))
        providersItem.setIcon(icon)
        providersItem.setEditable(False)
        emptyItem = QStandardItem()
        emptyItem.setEditable(False)
        rootItem.insertRow(0, [providersItem, emptyItem])
        for group in settings.keys():
            if group in priorityKeys:
                continue

            groupItem = QStandardItem(group)
            icon = ProcessingConfig.getGroupIcon(group)
            groupItem.setIcon(icon)
            groupItem.setEditable(False)
            for setting in settings[group]:
                if setting.hidden:
                    continue

                if text == '' or text.lower() in setting.description.lower():
                    labelItem = QStandardItem(setting.description)
                    labelItem.setIcon(icon)
                    labelItem.setEditable(False)
                    self.items[setting] = SettingItem(setting)
                    groupItem.insertRow(0, [labelItem, self.items[setting]])

            emptyItem = QStandardItem()
            emptyItem.setEditable(False)
            providersItem.appendRow([groupItem, emptyItem])

        self.tree.sortByColumn(0, Qt.AscendingOrder)
        self.adjustColumns()
Example #41
0
def func(*args):
    parent1 = QStandardItem('par')
    child3 = QStandardItem('child')
    child2 = QStandardItem('child2')
    parent1.appendRow([child2, child3])
    model.appendRow(parent1)