Exemplo n.º 1
0
    def new_item(self, cat, name, desc='', misc=None, sort=None,
                 userdata=None):
        """Add a new item to a category.

        Args:
            cat: The parent category.
            name: The name of the item.
            desc: The description of the item.
            misc: Misc text to display.
            sort: Data for the sort role (int).
            userdata: User data to be added for the first column.

        Return:
            A (nameitem, descitem, miscitem) tuple.
        """
        assert not isinstance(name, int)
        assert not isinstance(desc, int)
        assert not isinstance(misc, int)

        nameitem = QStandardItem(name)
        descitem = QStandardItem(desc)
        if misc is None:
            miscitem = QStandardItem()
        else:
            miscitem = QStandardItem(misc)

        cat.appendRow([nameitem, descitem, miscitem])
        if sort is not None:
            nameitem.setData(sort, Role.sort)
        if userdata is not None:
            nameitem.setData(userdata, Role.userdata)
        return nameitem, descitem, miscitem
 def __init__(self, database, main_spectrum = None):
     super(ReferenceSpectraDialog, self).__init__()
     self.main_spectrum = main_spectrum
     self.ui = Ui_ReferenceSpectraDialog()
     self.ui.setupUi(self)
     self.reference_catalogues = ReferenceCatalogues(database)
     self.full_model = QStandardItemModel()
     self.catalogues_model = QStandardItemModel()
     self.ui.catalogue.setModel(self.catalogues_model)
     self.ui.catalogue.currentTextChanged.connect(lambda txt: self.populate())
     for catname, cat in self.reference_catalogues.catalogues.items():
         row = QStandardItem(catname)
         row.setData(cat)
         self.catalogues_model.appendRow(row)
     
     self.model = QSortFilterProxyModel()
     self.model.setSourceModel(self.full_model)
     self.model.setFilterCaseSensitivity(Qt.CaseInsensitive)
     self.model.setFilterKeyColumn(0)
     self.ui.entries.setModel(self.model)
     self.ui.type_filter.currentTextChanged.connect(lambda txt: self.model.setFilterWildcard("{}*".format(txt) ) )
     self.ui.buttonBox.button(QDialogButtonBox.Open).setEnabled(False)
     self.ui.entries.selectionModel().selectionChanged.connect(lambda selected, deselected: self.ui.buttonBox.button(QDialogButtonBox.Open).setEnabled(len(selected.indexes()) > 0)  )
     self.accepted.connect(self.load_fits)
     self.populate()
Exemplo n.º 3
0
def test_completion_item_next_prev(tree, count, expected, completionview):
    """Test that on_next_prev_item moves the selection properly.

    Args:
        tree: Each list represents a completion category, with each string
              being an item under that category.
        count: Number of times to go forward (or back if negative).
        expected: item data that should be selected after going back/forward.
    """
    model = base.BaseCompletionModel()
    for catdata in tree:
        cat = QStandardItem()
        model.appendRow(cat)
        for name in catdata:
            cat.appendRow(QStandardItem(name))
    filtermodel = sortfilter.CompletionFilterModel(model,
                                                   parent=completionview)
    completionview.set_model(filtermodel)
    if count < 0:
        for _ in range(-count):
            completionview.completion_item_prev()
    else:
        for _ in range(count):
            completionview.completion_item_next()
    idx = completionview.selectionModel().currentIndex()
    assert filtermodel.data(idx) == expected
Exemplo n.º 4
0
def test_completion_show(show, rows, quick_complete, completionview,
                         config_stub):
    """Test that the completion widget is shown at appropriate times.

    Args:
        show: The completion show config setting.
        rows: Each entry represents a completion category with only one item.
        quick_complete: The completion quick-complete config setting.
    """
    config_stub.data['completion']['show'] = show
    config_stub.data['completion']['quick-complete'] = quick_complete

    model = base.BaseCompletionModel()
    for name in rows:
        cat = QStandardItem()
        model.appendRow(cat)
        cat.appendRow(QStandardItem(name))
    filtermodel = sortfilter.CompletionFilterModel(model,
                                                   parent=completionview)

    assert not completionview.isVisible()
    completionview.set_model(filtermodel)
    assert completionview.isVisible() == (show == 'always' and len(rows) > 0)
    completionview.completion_item_focus('next')
    expected = (show != 'never' and len(rows) > 0 and
                not (quick_complete and len(rows) == 1))
    assert completionview.isVisible() == expected
    completionview.set_model(None)
    completionview.completion_item_focus('next')
    assert not completionview.isVisible()
Exemplo n.º 5
0
    def __init__(self, parent=None):
        super(UniverseTreeView, self).__init__(parent)

        model = QStandardItemModel()
        self.setModel(model)

        root_item = model.invisibleRootItem()

        self.areas_item = QStandardItem("Areas")
        self.areas_item.setData(Areas, Qt.UserRole)
        self.areas_item.setEditable(False)
        root_item.appendRow(self.areas_item)

        Areas.added.connect(self.init_areas)
        Areas.removed.connect(self.init_areas)
        Areas.reset.connect(self.init_areas)


        self.characters_item = QStandardItem("Characters")
        self.characters_item.setData(Characters, Qt.UserRole)
        self.characters_item.setEditable(False)
        root_item.appendRow(self.characters_item)

        Characters.added.connect(self.init_characters)
        Characters.removed.connect(self.init_characters)
        Characters.reset.connect(self.init_characters)


        self.races_item = QStandardItem("Races")
        self.races_item.setEditable(False)
        self.races_item.setData(Races, Qt.UserRole)
        root_item.appendRow(self.races_item)

        Races.added.connect(self.init_races)
        Races.removed.connect(self.init_races)
        Races.reset.connect(self.init_races)


        self.item_prototypes_item = QStandardItem("Item Prototypes")
        self.item_prototypes_item.setData(ItemPrototypes, Qt.UserRole)
        self.item_prototypes_item.setEditable(False)
        root_item.appendRow(self.item_prototypes_item)

        ItemPrototypes.added.connect(self.init_item_prototypes)
        ItemPrototypes.removed.connect(self.init_item_prototypes)
        ItemPrototypes.reset.connect(self.init_item_prototypes)


        self.groups_item = QStandardItem("Groups")
        self.groups_item.setData(Groups, Qt.UserRole)
        self.groups_item.setEditable(False)
        root_item.appendRow(self.groups_item)

        Groups.added.connect(self.init_groups)
        Groups.removed.connect(self.init_groups)
        Groups.reset.connect(self.init_groups)

        self.init_all()

        self.activated.connect(self.item_activated)
Exemplo n.º 6
0
    def initUi(self, options, enabledOptions, headerOptions, singleSelectionMode):
        boldFont = QFont()
        boldFont.setBold(True)

        # set the selection mode
        if not singleSelectionMode:
            self.listView_options.setSelectionMode(QAbstractItemView.ExtendedSelection)

        # create enableItems if none
        if enabledOptions is None:
            enabledOptions = [True for idx in range(len(options))]

        # Insert the choices
        self.standaredItemModel = QStandardItemModel(self.listView_options)
        self.standaredItemModel.itemChanged.connect(self.onItemChanged)
        for idx in range(len(options)):
            standaredItem = QStandardItem(options[idx])
            standaredItem.setSelectable(enabledOptions[idx])
            if idx in headerOptions:
                standaredItem.setFont(boldFont)
            self.standaredItemModel.appendRow(standaredItem)

        self.listView_options.setModel(self.standaredItemModel)

        # disable select all / de select all buttons if in single selection
        # mode
        if singleSelectionMode:
            self.pushButton_sellectAll.setDisabled(True)
            self.pushButton_deSellectAll.setDisabled(True)
def test_completion_item_focus(which, tree, expected, completionview, qtbot):
    """Test that on_next_prev_item moves the selection properly.

    Args:
        which: the direction in which to move the selection.
        tree: Each list represents a completion category, with each string
              being an item under that category.
        expected: expected argument from on_selection_changed for each
                  successive movement. None implies no signal should be
                  emitted.
    """
    model = base.BaseCompletionModel()
    for catdata in tree:
        cat = QStandardItem()
        model.appendRow(cat)
        for name in catdata:
            cat.appendRow(QStandardItem(name))
    filtermodel = sortfilter.CompletionFilterModel(model,
                                                   parent=completionview)
    completionview.set_model(filtermodel)
    for entry in expected:
        if entry is None:
            with qtbot.assertNotEmitted(completionview.selection_changed):
                completionview.completion_item_focus(which)
        else:
            with qtbot.waitSignal(completionview.selection_changed) as sig:
                completionview.completion_item_focus(which)
                assert sig.args == [entry]
Exemplo n.º 8
0
 def populate(self):
     self.model.clear()
     self.model.setHorizontalHeaderLabels(['Lambda', 'Element', 'Atomic number', 'Ionization', 'Stellar spectral types'])
     c = self.database.cursor()
     query = "SELECT lambda, Element, Z, Ion, SpTypes from spectral_lines WHERE {} ORDER BY lambda ASC;"
     conditions = ['(1 = 1)']
     
     element = self.elements_model.item(self.ui.elements.currentIndex()).data()
     if element['z']:
         conditions.append("(Z = {})".format(element['z']))
     
     if self.ui.lambda_from.value() > 0:
         conditions.append("(Lambda >= {})".format(self.ui.lambda_from.value()))
     if self.ui.lambda_to.value() > 0:
         conditions.append("(Lambda <= {})".format(self.ui.lambda_to.value()))
     if self.ui.name.text():
         conditions.append("(Element like '%{}%')".format(self.ui.name.text()))
     if self.ui.sp_types.isChecked():
         conditions.append("(SpTypes <> '')")
     
     for row in c.execute(query.format(" AND ".join(conditions))):
         first_item = QStandardItem("{}".format(row[0]))
         first_item.setData({'lambda': row[0], 'name': row[1], 'z': row[2]})
         self.model.appendRow( [
             first_item,
             QStandardItem(row[1]),
             QStandardItem("{}".format(row[2])),
             QStandardItem("{}".format(row[3])),
             QStandardItem(row[4])
             ])
Exemplo n.º 9
0
    def addPoint(self):
        rows = self._current.editor.selectedRows()
        newStart = self._videoWidget.position

        if len(rows) == 0 or newStart is None:
            self._err.showMessage(_("Select a subtitle and position in current video first."))
            return

        # row and sub reflect the same subtitle, but we need both for different things
        row = rows[0]
        sub = self._current.data.subtitles[row]

        # Don't add the same subtitle or the same sync time twice
        if any(row == point.subNo or newStart == point.start
               for point in _syncPoints(self._current.model)):
            self._err.showMessage(_("Can't repeat synchronization points"))
            return

        if sub.fps != newStart.fps:
            self._err.showMessage(_("Subtitle and video have different framerates (%(sub)s vs"
                                    "%(vid)s") % dict(sub=sub.fps, vid=newStart.fps))
            return

        delta = sub.end - sub.start
        newEnd = newStart + delta

        startItem, endItem, textItem = createRow(sub, newStart, newEnd)
        subNoItem = QStandardItem(str(row))
        subNoItem.setEditable(False)
        textItem.setEditable(False)
        rmItem = QStandardItem("")
        self._current.model.appendRow([subNoItem, startItem, endItem, textItem, rmItem])

        self._rmButton(self._table, rmItem)
Exemplo n.º 10
0
 def __connect_events(self):
     self.model = QStandardItemModel()
     self.mass_list = []
     for i in range(10):
         mass = 184 + i
         self.mass_list.append(str(mass))
     for i in range(10):
         mass = 209 + i
         self.mass_list.append(str(mass))
     for i in range(10):
         mass = 273.3 + i
         self.mass_list.append(str(mass))
     for i in range(10):
         mass = 294 + i
         self.mass_list.append(str(mass))
     for mass in self.mass_list:
         item = QStandardItem(mass)
         item.setCheckable(True)
         item.setEditable(True)
         self.model.appendRow(item)
     self.view = self.ui.listView_Mass
     self.view.setModel(self.model)
     # changes in one item, don't know which one
     self.model.itemChanged.connect(self.change_list)
     # changes in button
     self.ui.pushButton_ChangeList.clicked.connect(self.emit_list_signal)
     # get peaks found and update automatically the mass list
     self.ana.masstabSelectorRaisedSignal.connect(self.update_list_view)
Exemplo n.º 11
0
 def fillReferences(self):
     
     for value in self.referenceList:                   
         item = QStandardItem(value[0])
         check = Qt.Checked if value[1] else Qt.Unchecked
         item.setCheckState(check)
         item.setCheckable(True)
         self.referenceListModel.appendRow(item)
Exemplo n.º 12
0
 def current_to_recent(self):
     track = self.player.get_item()
     if track is not "":
         item = QStandardItem(track)
         track_meta = self.meta_info(track)
         item.setText(track_meta)
         item.setData(track, 1)
         self.recentTrackListModel.insertRow(0, item)
Exemplo n.º 13
0
 def setModelData(self, items, checkedItems):
     self.clear()
     for item in items:
         modelItem = QStandardItem(item)
         if item in checkedItems:
             modelItem.setCheckState(Qt.Checked)
         else:
             modelItem.setCheckState(Qt.Unchecked)
         self.appendRow(modelItem)
Exemplo n.º 14
0
 def set_server_mgr(self, server_mgr):
     self.server_mgr = server_mgr
     self.nodesets = []
     self.model.clear()
     self.model.setHorizontalHeaderLabels(['Node Sets'])
     item = QStandardItem("Opc.Ua.NodeSet2.xml")
     item.setFlags(Qt.NoItemFlags)
     self.model.appendRow([item])
     self.view.expandAll()
Exemplo n.º 15
0
 def addItems(self, parent, elements):
     for k in sorted(elements.keys()):
         item = QStandardItem(k)
         parent.appendRow(item)
         if type(elements[k]) == dict:
             self.addItems(item, elements[k])
         else:
             child = QStandardItem(str(elements[k]))
             item.appendRow(child)
Exemplo n.º 16
0
    def init(self):
        model = self.model()
        model.clear()

        root_item = model.invisibleRootItem()
        for t in weapon_types:
            item = QStandardItem(t.title())
            item.setData(t, Qt.UserRole)
            root_item.appendRow(item)
Exemplo n.º 17
0
	def __init__(self,xpos=0.0,ypos=0.0,zpos=0.0):
		QStandardItem.__init__(self,"X: "+str(xpos)+" Y: "+str(ypos)+" Z: "+str(zpos))
		try:
			self.x=float(xpos)
			self.y=float(ypos)
			self.z=float(zpos)
		except ValueError:
			#raise
			raise ValueError("could not set point values")
Exemplo n.º 18
0
	def fresh(self):
		confFile=open("conf","r")
		self.listModel=QStandardItemModel()
		self.itemList=cPickle.load(confFile)
		confFile.close()
		for  item in self.itemList:
			itemView=QStandardItem(QIcon(item.path),item.name)
			itemView.setEditable(False)
			self.listModel.appendRow(itemView)
			self.listview.setModel(self.listModel)
Exemplo n.º 19
0
    def _set_items(self, item, data):
        item.setRowCount(0)
        subitems = []
        for d in sorted(data, key=lambda r: r.name.lower()):
            subitem = QStandardItem(d.name)
            subitem.setEditable(False)
            subitem.setData(d, Qt.UserRole)
            subitems.append(subitem)

        item.appendRows(subitems)
Exemplo n.º 20
0
 def _show_list(self, parent, mylist, vtype):
     for idx, val in enumerate(mylist):
         name_item = QStandardItem(str(idx))
         vitem = QStandardItem()
         vitem.setText(val_to_string(val))
         vitem.setData(ListData(mylist, idx, val, vtype), Qt.UserRole)
         row = [name_item, vitem, QStandardItem(vtype.name)]
         parent.appendRow(row)
         if vtype == ua.VariantType.ExtensionObject:
             self._show_ext_obj(name_item, val)
Exemplo n.º 21
0
    def init(self):
        print("SelectRaceComboBox.init")
        model = self.model()
        model.clear()

        root_item = model.invisibleRootItem()
        for race in Races:
            item = QStandardItem(race.name)
            item.setData(race, Qt.UserRole)
            root_item.appendRow(item)
Exemplo n.º 22
0
 def build_row(result):
     preview = QStandardItem(str(result.data))
     preview.setEditable(False)
     preview.result = result
     return [
         QStandardItem(result.manifest.label),
         QStandardItem(result.manifest._size),
         QStandardItem(result.manifest.type()),
         preview,
     ]
Exemplo n.º 23
0
    def colorize(self, excelModel, prologModel):

        for row in range(prologModel.rowCount()):

            if str(excelModel.data(excelModel.index(row, 0))).lower() == "none":
                if "_lab" in str(prologModel.data(prologModel.index(row, 1))).lower() or "lab_" in str(prologModel.data(prologModel.index(row, 2))).lower():
                    pass
                else:
                    for column in range(prologModel.columnCount()):
                        if str(prologModel.data(prologModel.index(row, column))).lower() != str(excelModel.data(excelModel.index(row, column))).lower():
                            toAdd = QStandardItem(str(prologModel.data(prologModel.index(row, column))))
                            toAdd.setBackground(QBrush(QColor(255, 155, 55, 200)))
                            prologModel.setItem(row, column, toAdd)


            elif str(prologModel.data(prologModel.index(row, 2))).lower() not in str(excelModel.data(excelModel.index(row, 1))).lower(): #confronto docente
                toAdd = QStandardItem(str(prologModel.data(prologModel.index(row, 2))))
                toAdd.setBackground(QBrush(QColor(255, 0, 0, 100)))
                prologModel.setItem(row, 2, toAdd)

            elif str(excelModel.data(excelModel.index(row, 4))).lower() != str(prologModel.data(prologModel.index(row, 5))).lower(): #confronto ore
                toAdd = QStandardItem(str(prologModel.data(prologModel.index(row, 5))))
                toAdd.setBackground(QBrush(QColor(255, 0, 0, 100)))
                prologModel.setItem(row, 5, toAdd)

            """"
Exemplo n.º 24
0
    def load_projects(self):
        self.clear()

        self.setHorizontalHeaderLabels(['Name'])

        for project in get_projects():
            item = QStandardItem(project)
            item.setEditable(False)
            self.appendRow(item)

        self.sort(0)
Exemplo n.º 25
0
 def AddTag( self, name ):
     newTag = QStandardItem( name )
     newTagQuantity = QItemToSortByNum( "0" )
     newTag.setFlags( Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsSelectable )
     newTag.setData( QVariant( Qt.Unchecked ), Qt.CheckStateRole )
     self.tagDict[ name ] = newTag
     currentRow = [ newTag, newTagQuantity ]
     self.tagNameToTagItemsDict[ name ] = currentRow
     self.tagModel.appendRow( currentRow )
     self.tagModel.sort( Qt.AscendingOrder )
     self.wereAnyChanges = True
Exemplo n.º 26
0
    def _createRow(self, sub):
        timeStart = QStandardItem(sub.start.toStr())
        timeEnd = QStandardItem(sub.end.toStr())
        text = QStandardItem(sub.text)

        timeStart.setData(sub.start, CustomDataRoles.FrameTimeRole)
        timeEnd.setData(sub.end, CustomDataRoles.FrameTimeRole)

        timeStart.setData(False, CustomDataRoles.ErrorFlagRole)
        timeEnd.setData(False, CustomDataRoles.ErrorFlagRole)

        return [timeStart, timeEnd, text]
Exemplo n.º 27
0
Arquivo: main.py Projeto: damekr/chat
def fillUserList(newUser=None):
    model = QStandardItemModel()
    mylist = ['asd', 'wqe', 'wqra', 'tewt4']
    if newUser:
        mylist += newUser
        print(mylist)
    for item in mylist:
        myitem = QStandardItem(item)
        myitem.setEditable(0)
        model.appendRow(myitem)
    myapp.listView.setModel(model)
    myapp.listView.doubleClicked.connect(openConversationWindow)
Exemplo n.º 28
0
 def addTreeEntry(self, parent, name, parameter, func, level = 1):
     child = QStandardItem(name)
     child.setCheckable(True)
     value = QStandardItem(str(parameter))
     parent.appendRow([child, value])
     
     if level == 3:
         osciNum = parent.parent().rowCount() - 2
         itemNum = parent.rowCount() - 1
         self.parameterList.append([parameter, func, osciNum, itemNum])
     else:
         self.parameterList.append([parameter, func])
Exemplo n.º 29
0
 def populate(self):
     self.full_model.clear()
     catalogue = self.catalogues_model.item(self.ui.catalogue.currentIndex()).data()
     self.full_model.setHorizontalHeaderLabels(['Spectral Type'])
     entries = self.reference_catalogues.spectra(catalogue['name'])
     self.ui.type_filter.clear()
     self.ui.type_filter.addItem('')
     self.ui.type_filter.addItems( sorted(set([i['sptype'] for i in entries])) )
     
     for entry in entries:
         item = QStandardItem(entry['sptype'])
         item.setData(entry)
         self.full_model.appendRow(item)
Exemplo n.º 30
0
    def create_table(self, rela):
        table = custom_table.Table()
        model = QStandardItemModel()
        table.setModel(model)
        model.setHorizontalHeaderLabels(rela.header)

        for row_count, row in enumerate(rela.content):
            for col_count, data in enumerate(row):
                item = QStandardItem(data)
                item.setFlags(item.flags() & ~Qt.ItemIsEditable)
                model.setItem(row_count, col_count, item)

        return table
Exemplo n.º 31
0
   def __iniModelFromStringList(self,allLines):  ##从字符串列表构建模型
      rowCnt=len(allLines) #文本行数,第1行是标题
      self.itemModel.setRowCount(rowCnt-1) #实际数据行数

      headerText=allLines[0].strip() #第1行是表头,去掉末尾的换行符 "\n"
      headerList=headerText.split("\t")
      self.itemModel.setHorizontalHeaderLabels(headerList)

      self.__lastColumnTitle=headerList[len(headerList)-1] # 最后一列表头的标题,即“测井取样”

      lastColNo=self.COL_COUNT-1  #最后一列的列号
      for i in range(rowCnt-1):  
         lineText=allLines[i+1].strip()  #一行的文字,\t分隔
         strList=lineText.split("\t")
         for j in range(self.COL_COUNT-1):  #不含最后一列
             item=QStandardItem(strList[j])
             self.itemModel.setItem(i,j,item)
             
         item=QStandardItem(self.__lastColumnTitle)  #最后一列
         item.setFlags(self.__lastColumnFlags)
         item.setCheckable(True)
         if (strList[lastColNo]=="0"):
             item.setCheckState(Qt.Unchecked)
         else:
             item.setCheckState(Qt.Checked)
         
         self.itemModel.setItem(i,lastColNo,item) #设置最后一列的item
Exemplo n.º 32
0
    def add_new_page(self, templateUrl):

        # check for page list and or location.
        pagesList = []
        if "pages" in self.setupDictionary.keys():
            pagesList = self.setupDictionary["pages"]
        if not "pageNumber" in self.setupDictionary.keys():
            self.setupDictionary['pageNumber'] = 0

        if (str(self.setupDictionary["pagesLocation"]).isspace()):
            self.setupDictionary["pagesLocation"] = os.path.relpath(
                QFileDialog.getExistingDirectory(
                    caption=i18n("Where should the pages go?"),
                    options=QFileDialog.ShowDirsOnly), self.projecturl)

        # Search for the possible name.
        extraUnderscore = str()
        if str(self.setupDictionary["projectName"])[-1].isdigit():
            extraUnderscore = "_"
        self.setupDictionary['pageNumber'] += 1
        pageName = str(self.setupDictionary["projectName"]).replace(
            " ", "_") + extraUnderscore + str(
                format(self.setupDictionary['pageNumber'], "03d"))
        url = os.path.join(str(self.setupDictionary["pagesLocation"]),
                           pageName + ".kra")

        # open the page by opening the template and resaving it, or just opening it.
        absoluteUrl = os.path.join(self.projecturl, url)
        if (os.path.exists(absoluteUrl)):
            newPage = Application.openDocument(absoluteUrl)
        else:
            booltemplateExists = os.path.exists(
                os.path.join(self.projecturl, templateUrl))
            if booltemplateExists is False:
                templateUrl = os.path.relpath(
                    QFileDialog.getOpenFileName(
                        caption=i18n(
                            "Which image should be the basis the new page?"),
                        directory=self.projecturl,
                        filter=str(i18n("Krita files") + "(*.kra)"))[0],
                    self.projecturl)
            newPage = Application.openDocument(
                os.path.join(self.projecturl, templateUrl))
            newPage.waitForDone()
            newPage.setFileName(absoluteUrl)
            newPage.setName(pageName.replace("_", " "))
            newPage.save()
            newPage.waitForDone()

        # Get out the extra data for the standard item.
        newPageItem = QStandardItem()
        newPageItem.setIcon(
            QIcon(QPixmap.fromImage(newPage.thumbnail(256, 256))))
        newPageItem.setDragEnabled(True)
        newPageItem.setDropEnabled(False)
        newPageItem.setEditable(False)
        newPageItem.setText(pageName.replace("_", " "))
        newPageItem.setData("", role=CPE.DESCRIPTION)
        newPageItem.setData(url, role=CPE.URL)
        newPageItem.setData("", role=CPE.KEYWORDS)
        newPageItem.setData("", role=CPE.LASTEDIT)
        newPageItem.setData("", role=CPE.EDITOR)
        newPageItem.setToolTip(url)

        # close page document.
        while os.path.exists(absoluteUrl) is False:
            qApp.processEvents()

        self.pagesWatcher.addPath(absoluteUrl)
        newPage.close()

        # add item to page.
        self.pagesModel.appendRow(newPageItem)
Exemplo n.º 33
0
 def add_module(self, module):
     _module_name = QStandardItem()
     _module_name.setText(module)
     self._ObjCmodule_model.appendRow(_module_name)
Exemplo n.º 34
0
 def __init__(self, data):
     QStandardItem.__init__(self)
     self._logger = logging.getLogger(self.__class__.__name__)
     self._data = data
     self._text = self._getText(data)
Exemplo n.º 35
0
    def addBackends(self, cap=None, entry_all=True, entry_title=False):
        """
        Populate the model by adding backends.

        Appends backends to the model, without clearing previous entries.
        For each entry in the model, the cap name is stored under role
        RoleBackendName and the capability object under role
        RoleCapability.

        :param cap: capabilities to add (None to add all loaded caps)
        :param entry_all: if True, add a "All backends" entry
        :param entry_title: if True, add a disabled entry with the cap name
        """

        if entry_title:
            if cap:
                capname = cap.__name__
            else:
                capname = '(All capabilities)'

            item = QStandardItem(capname)
            item.setEnabled(False)
            self.appendRow(item)

        first = True
        for backend in self.weboob.iter_backends(caps=cap):
            if first and entry_all:
                item = QStandardItem('(All backends)')
                item.setData('', self.RoleBackendName)
                item.setData(cap, self.RoleCapability)
                self.appendRow(item)
            first = False

            item = QStandardItem(backend.name)
            item.setData(backend.name, self.RoleBackendName)
            item.setData(cap, self.RoleCapability)
            minfo = self.weboob.repositories.get_module_info(backend.NAME)
            icon_path = self.weboob.repositories.get_module_icon_path(minfo)
            if icon_path:
                pixmap = QPixmapCache.find(icon_path)
                if not pixmap:
                    pixmap = QPixmap(QImage(icon_path))
                item.setIcon(QIcon(pixmap))
            self.appendRow(item)
Exemplo n.º 36
0
 def _on_class_enumeration_match(self, java_class):
     _class_name = QStandardItem()
     _class_name.setText(java_class)
     self._javaclass_model.appendRow(_class_name)
Exemplo n.º 37
0
                return True

        return super().helpEvent(event, view, option, index)


class AutoToolTipItemDelegate(AutoToolTipItemDelegateMixin, QItemDelegate):
    pass


if __name__ == "__main__":
    import sys
    from PyQt5.QtWidgets import QApplication, QListView
    from PyQt5.QtGui import QStandardItemModel, QStandardItem

    app = QApplication(sys.argv)

    view = QListView()
    model = QStandardItemModel()
    view.setModel(model)
    view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
    view.setItemDelegate(AutoToolTipItemDelegate())
    view.setMinimumWidth(200)

    for i in range(0, 20):
        item = QStandardItem(str(i) * (50 - i))
        model.appendRow(item)

    view.show()

    sys.exit(app.exec_())
Exemplo n.º 38
0
    def add_context(self, data):
        if self.dwarf.arch == 'ia32':
            self.threads_model.setHeaderData(1, Qt.Horizontal, 'EIP')
        elif self.dwarf.arch == 'x64':
            self.threads_model.setHeaderData(1, Qt.Horizontal, 'RIP')
        else:
            self.threads_model.setHeaderData(1, Qt.Horizontal, 'PC')
        is_java = data['is_java']
        tid = QStandardItem()
        tid.setText(str(data['tid']))
        tid.setData(data, Qt.UserRole + 1)
        tid.setTextAlignment(Qt.AlignCenter)

        pc_col = QStandardItem()
        if not is_java:
            if data['reason'] == 2:
                pc_col.setText(data['ptr'])
            else:
                pc = int(data['ptr'], 16)
                if 'arm' in self.dwarf.arch:
                    # dethumbify
                    if pc & 1 == 1:
                        pc -= 1

                if self._uppercase_hex:
                    str_fmt = '0x{0:X}'
                else:
                    str_fmt = '0x{0:x}'

                pc_col.setText(str_fmt.format(pc))
        else:
            parts = data['ptr'].split('.')
            pc_col.setText(parts[len(parts) - 1])

        symb_col = QStandardItem()
        if True:
            if not is_java:
                if 'symbol' in data['context']['pc']:
                    str_fmt = ('{0} - {1}'.format(
                        data['context']['pc']['symbol']['moduleName'],
                        data['context']['pc']['symbol']['name']))
                    symb_col.setText(str_fmt)
            else:
                symb_col.setText('.'.join(parts[:len(parts) - 1]))
        else:
            str_fmt = ('loading {0}'.format(''))
            # str_fmt = ('loading {0}'.format(library_onload))
            symb_col.setText(str_fmt)

        self.threads_model.appendRow([tid, pc_col, symb_col])
        self.resizeColumnToContents(0)
        self.resizeColumnToContents(1)
        self.setCurrentIndex(
            self.threads_model.index(self.threads_model.rowCount() - 1, 0))
Exemplo n.º 39
0
 def update(self):
     if self.maybe_defer_update():
         return
     current_address = self.get_role_data_for_current_item(
         col=self.Columns.LABEL, role=self.ROLE_ADDRESS_STR)
     if self.show_change == AddressTypeFilter.RECEIVING:
         addr_list = self.wallet.get_receiving_addresses()
     elif self.show_change == AddressTypeFilter.CHANGE:
         addr_list = self.wallet.get_change_addresses()
     else:
         addr_list = self.wallet.get_addresses()
     self.proxy.setDynamicSortFilter(
         False)  # temp. disable re-sorting after every change
     self.std_model.clear()
     self.refresh_headers()
     fx = self.parent.fx
     set_address = None
     addresses_beyond_gap_limit = self.wallet.get_all_known_addresses_beyond_gap_limit(
     )
     for address in addr_list:
         num = self.wallet.get_address_history_len(address)
         label = self.wallet.get_label(address)
         c, u, x = self.wallet.get_addr_balance(address)
         balance = c + u + x
         is_used_and_empty = self.wallet.is_used(address) and balance == 0
         if self.show_used == AddressUsageStateFilter.UNUSED and (
                 balance or is_used_and_empty):
             continue
         if self.show_used == AddressUsageStateFilter.FUNDED and balance == 0:
             continue
         if self.show_used == AddressUsageStateFilter.USED_AND_EMPTY and not is_used_and_empty:
             continue
         if self.show_used == AddressUsageStateFilter.FUNDED_OR_UNUSED and is_used_and_empty:
             continue
         balance_text = self.parent.format_amount(balance, whitespaces=True)
         # create item
         if fx and fx.get_fiat_address_config():
             rate = fx.exchange_rate()
             fiat_balance = fx.value_str(balance, rate)
         else:
             fiat_balance = ''
         labels = [
             '', address, label, balance_text, fiat_balance,
             "%d" % num
         ]
         address_item = [QStandardItem(e) for e in labels]
         # align text and set fonts
         for i, item in enumerate(address_item):
             item.setTextAlignment(Qt.AlignVCenter)
             if i not in (self.Columns.TYPE, self.Columns.LABEL):
                 item.setFont(QFont(MONOSPACE_FONT))
         self.set_editability(address_item)
         address_item[self.Columns.FIAT_BALANCE].setTextAlignment(
             Qt.AlignRight | Qt.AlignVCenter)
         # setup column 0
         if self.wallet.is_change(address):
             address_item[self.Columns.TYPE].setText(_('change'))
             address_item[self.Columns.TYPE].setBackground(
                 ColorScheme.YELLOW.as_color(True))
         else:
             address_item[self.Columns.TYPE].setText(_('receiving'))
             address_item[self.Columns.TYPE].setBackground(
                 ColorScheme.GREEN.as_color(True))
         address_item[self.Columns.LABEL].setData(address,
                                                  self.ROLE_ADDRESS_STR)
         address_path = self.wallet.get_address_index(address)
         address_item[self.Columns.TYPE].setData(address_path,
                                                 self.ROLE_SORT_ORDER)
         address_path_str = self.wallet.get_address_path_str(address)
         if address_path_str is not None:
             address_item[self.Columns.TYPE].setToolTip(address_path_str)
         address_item[self.Columns.FIAT_BALANCE].setData(
             balance, self.ROLE_SORT_ORDER)
         # setup column 1
         if self.wallet.is_frozen_address(address):
             address_item[self.Columns.ADDRESS].setBackground(
                 ColorScheme.BLUE.as_color(True))
         if address in addresses_beyond_gap_limit:
             address_item[self.Columns.ADDRESS].setBackground(
                 ColorScheme.RED.as_color(True))
         # add item
         count = self.std_model.rowCount()
         self.std_model.insertRow(count, address_item)
         address_idx = self.std_model.index(count, self.Columns.LABEL)
         if address == current_address:
             set_address = QPersistentModelIndex(address_idx)
     self.set_current_idx(set_address)
     # show/hide columns
     if fx and fx.get_fiat_address_config():
         self.showColumn(self.Columns.FIAT_BALANCE)
     else:
         self.hideColumn(self.Columns.FIAT_BALANCE)
     self.filter()
     self.proxy.setDynamicSortFilter(True)
Exemplo n.º 40
0
def create_stat_model(database):
    # Список записей из базы
    hist_list = database.message_history()

    # Объект модели данных:
    list_qmodel = QStandardItemModel()
    list_qmodel.setHorizontalHeaderLabels(
        ['Имя Клиента', 'Последний раз входил',
         'Сообщений отправлено', 'Сообщений получено'])
    for row in hist_list:
        user, last_seen, sent, recvd = row
        user = QStandardItem(user)
        user.setEditable(False)
        last_seen = QStandardItem(str(last_seen.replace(microsecond=0)))
        last_seen.setEditable(False)
        sent = QStandardItem(str(sent))
        sent.setEditable(False)
        recvd = QStandardItem(str(recvd))
        recvd.setEditable(False)
        list_qmodel.appendRow([user, last_seen, sent, recvd])
    return list_qmodel
Exemplo n.º 41
0
def gui_create_model(database):
    list_users = database.active_users_list()
    list_qmodel = QStandardItemModel()
    list_qmodel.setHorizontalHeaderLabels(['Имя Клиента', 'IP Адрес', 'Порт',
                                           'Время подключения'])
    for row in list_users:
        user, ip, port, time = row
        user = QStandardItem(user)
        user.setEditable(False)
        ip = QStandardItem(ip)
        ip.setEditable(False)
        port = QStandardItem(str(port))
        port.setEditable(False)
        # Уберём милисекунды из строки времени,
        # т.к. такая точность не требуется.
        time = QStandardItem(str(time.replace(microsecond=0)))
        time.setEditable(False)
        list_qmodel.appendRow([user, ip, port, time])
    return list_qmodel
Exemplo n.º 42
0
 def update(self):
     self.wallet = self.parent.wallet
     current_address = self.current_item_user_role(col=self.Columns.LABEL)
     if self.show_change == 1:
         addr_list = self.wallet.get_receiving_addresses()
     elif self.show_change == 2:
         addr_list = self.wallet.get_change_addresses()
     else:
         addr_list = self.wallet.get_addresses()
     self.model().clear()
     self.refresh_headers()
     fx = self.parent.fx
     set_address = None
     for address in addr_list:
         num = self.wallet.get_address_history_len(address)
         label = self.wallet.labels.get(address, '')
         c, u, x = self.wallet.get_addr_balance(address)
         balance = c + u + x
         is_used_and_empty = self.wallet.is_used(address) and balance == 0
         if self.show_used == 1 and (balance or is_used_and_empty):
             continue
         if self.show_used == 2 and balance == 0:
             continue
         if self.show_used == 3 and not is_used_and_empty:
             continue
         balance_text = self.parent.format_amount(balance, whitespaces=True)
         # create item
         if fx and fx.get_fiat_address_config():
             rate = fx.exchange_rate()
             fiat_balance = fx.value_str(balance, rate)
         else:
             fiat_balance = ''
         labels = [
             '', address, label, balance_text, fiat_balance,
             "%d" % num
         ]
         address_item = [QStandardItem(e) for e in labels]
         # align text and set fonts
         for i, item in enumerate(address_item):
             item.setTextAlignment(Qt.AlignVCenter)
             if i not in (self.Columns.TYPE, self.Columns.LABEL):
                 item.setFont(QFont(MONOSPACE_FONT))
             item.setEditable(i in self.editable_columns)
         address_item[self.Columns.FIAT_BALANCE].setTextAlignment(
             Qt.AlignRight | Qt.AlignVCenter)
         # setup column 0
         if self.wallet.is_change(address):
             address_item[self.Columns.TYPE].setText(_('change'))
             address_item[self.Columns.TYPE].setBackground(
                 ColorScheme.YELLOW.as_color(True))
         else:
             address_item[self.Columns.TYPE].setText(_('receiving'))
             address_item[self.Columns.TYPE].setBackground(
                 ColorScheme.GREEN.as_color(True))
         address_item[self.Columns.LABEL].setData(address, Qt.UserRole)
         # setup column 1
         if self.wallet.is_frozen_address(address):
             address_item[self.Columns.ADDRESS].setBackground(
                 ColorScheme.BLUE.as_color(True))
         if self.wallet.is_beyond_limit(address):
             address_item[self.Columns.ADDRESS].setBackground(
                 ColorScheme.RED.as_color(True))
         # add item
         count = self.model().rowCount()
         self.model().insertRow(count, address_item)
         address_idx = self.model().index(count, self.Columns.LABEL)
         if address == current_address:
             set_address = QPersistentModelIndex(address_idx)
     self.set_current_idx(set_address)
     # show/hide columns
     if fx and fx.get_fiat_address_config():
         self.showColumn(self.Columns.FIAT_BALANCE)
     else:
         self.hideColumn(self.Columns.FIAT_BALANCE)
     self.filter()
Exemplo n.º 43
0
    def slot_add_page_from_url(self):
        # get the pages.
        urlList = QFileDialog.getOpenFileNames(
            caption=i18n("Which existing pages to add?"),
            directory=self.projecturl,
            filter=str(i18n("Krita files") + "(*.kra)"))[0]

        # get the existing pages list.
        pagesList = []
        if "pages" in self.setupDictionary.keys():
            pagesList = self.setupDictionary["pages"]

        # And add each url in the url list to the pages list and the model.
        for url in urlList:
            if self.projecturl not in urlList:
                newUrl = os.path.join(self.projecturl,
                                      self.setupDictionary["pagesLocation"],
                                      os.path.basename(url))
                shutil.move(url, newUrl)
                url = newUrl
            relative = os.path.relpath(url, self.projecturl)
            if url not in pagesList:
                page = zipfile.ZipFile(url, "r")
                thumbnail = QImage.fromData(page.read("preview.png"))
                dataList = self.get_description_and_title(
                    page.read("documentinfo.xml"))
                if (dataList[0].isspace() or len(dataList[0]) < 1):
                    dataList[0] = os.path.basename(url)
                newPageItem = QStandardItem()
                newPageItem.setIcon(QIcon(QPixmap.fromImage(thumbnail)))
                newPageItem.setDragEnabled(True)
                newPageItem.setDropEnabled(False)
                newPageItem.setEditable(False)
                newPageItem.setText(dataList[0].replace("_", " "))
                newPageItem.setData(dataList[1], role=CPE.DESCRIPTION)
                newPageItem.setData(relative, role=CPE.URL)
                self.pagesWatcher.addPath(url)
                newPageItem.setData(dataList[2], role=CPE.KEYWORDS)
                newPageItem.setData(dataList[3], role=CPE.LASTEDIT)
                newPageItem.setData(dataList[4], role=CPE.EDITOR)
                newPageItem.setToolTip(relative)
                page.close()
                self.pagesModel.appendRow(newPageItem)
Exemplo n.º 44
0
 def _update_event_model(self, event):
     self.model.appendRow([QStandardItem(str(event))])
Exemplo n.º 45
0
    def populate(self, data):
        """Populate the data model using the data passed
        from the extensions object.

        The data model has up to three root-level items:
        - Invalid metadata
        - Failed to load
        - Failed dependencies
        """

        # font for use in various Items
        bold = QFont()
        bold.setWeight(QFont.Bold)

        root = self.invisibleRootItem()
        infos = data['infos']
        if infos:
            # Handle extensions with metadata errors
            infos_item = QStandardItem()
            infos_item.setFont(bold)
            infos_item.setText(_("Invalid metadata:"))
            infos_tooltip = (
                _("Extensions whose extension.cnf file has errors.\n"
                  "They will be loaded nevertheless."))
            infos_item.setToolTip(infos_tooltip)

            root.appendRow(infos_item)
            for info in infos:
                name_item = QStandardItem(info)
                name_item.setToolTip(infos_tooltip)
                icon = self.extensions.icon(info)
                if icon:
                    name_item.setIcon(icon)
                details_item = QStandardItem(infos[info])
                details_item.setToolTip(infos_tooltip)
                infos_item.appendRow([name_item, details_item])

        exceptions = data['exceptions']
        if exceptions:
            # Handle extensions that failed to load properly
            import traceback
            exceptions_item = self.exceptions_item = QStandardItem()
            exceptions_item.setFont(bold)
            exceptions_item.setText(_("Failed to load:"))
            extensions_tooltip = (
                _("Extensions that failed to load properly.\n"
                  "Double click on name to show the stacktrace.\n"
                  "Please contact the extension maintainer."))
            exceptions_item.setToolTip(extensions_tooltip)

            root.appendRow(exceptions_item)
            for ext in exceptions:
                extension_info = self.extensions.infos(ext)
                name = (extension_info.get('extension-name', ext)
                    if extension_info
                    else ext)
                name_item = QStandardItem(name)
                name_item.setToolTip(extensions_tooltip)
                icon = self.extensions.icon(ext)
                if icon:
                    name_item.setIcon(icon)
                exc_info = exceptions[ext]
                # store exception information in the first item
                name_item.exception_info = exc_info
                message = '{}: {}'.format(exc_info[0].__name__, exc_info[1])
                details_item = QStandardItem(message)
                details_item.setToolTip(extensions_tooltip)
                exceptions_item.appendRow([name_item, details_item])

        dependencies = data['dependencies']
        if dependencies:
            # Handle extensions with dependency issues
            dep_item = QStandardItem(_("Failed dependencies:"))
            dep_item.setFont(bold)
            dep_tooltip = (
                _("Extensions with failed or circular dependencies.\n"
                  "They are not loaded."))
            dep_item.setToolTip(dep_tooltip)

            root.appendRow(dep_item)
            missing = dependencies.get('missing', None)
            if missing:
                missing_item = QStandardItem(_("Missing:"))
                missing_item.setFont(bold)
                missing_item.setToolTip(dep_tooltip)
                dep_item.appendRow(missing_item)
                for m in missing:
                    item = QStandardItem(m)
                    item.setToolTip(dep_item)
                    missing_item.appendRow(item)
            inactive = dependencies.get('inactive', None)
            if inactive:
                inactive_item = QStandardItem(_("Inactive:"))
                inactive_item.setFont(bold)
                inactive_item.setToolTip(dep_tooltip)
                dep_item.appendRow(inactive_item)
                for i in inactive:
                    item = QStandardItem(i)
                    item.setToolTip(dep_tooltip)
                    inactive_item.appendRow(item)
            circular = dependencies.get('circular', None)
            if circular:
                circular_item = QStandardItem(_("Circular:"))
                circular_item.setFont(bold)
                circular_item.setToolTip(dep_tooltip)
                dep_item.appendRow(circular_item)
                item = QStandardItem(' | '.join(circular))
                item.setToolTip(dep_tooltip)
                circular_item.appendRow(item)
Exemplo n.º 46
0
def append(model, text):
    item = QStandardItem()
    text = str(text) if text is not None else ""
    item.setText(text)
    item.setDropEnabled(False)
    item.setEditable(False)
    font: QFont = item.font()
    font.setFamily("Courier New")
    font.setPointSize(font.pointSize() - FONT_DIFF)
    item.setFont(font)
    if text.startswith("+"):
        item.setBackground(QColor(0, 255, 0, 127))
    if text.startswith("-"):
        item.setBackground(QColor(255, 0, 0, 127))
    if text == "":
        item.setBackground(QColor(0, 0, 0, 47))

    model.appendRow(item)
Exemplo n.º 47
0
 def add_channel(self):
     self.ItemView.appendRow(QStandardItem(self.addText.text()))
     channel_ls.append(self.addText.text())
     self.ListView.setModel(self.ItemView)
     self.addText.setText("")
Exemplo n.º 48
0
    def window_loaded(self):
        try:
            if self.timer is not None:
                self.timer.stop()
                self.timer = None
            self.list_model.clear()
            instances_url = 'https://raw.githubusercontent.com/ckan/ckan-instances/gh-pages/config/instances.json'
            self.util.msg_log_debug('before getting instances: ' +
                                    instances_url)
            http_call = HttpCall(self.settings, self.util)
            response = http_call.execute_request(
                instances_url
                # , headers=self.ua_chrome
                ,
                verify=False,
                stream=True
                # not needed anymore, as we use QgsNetworkAccessManager.instance() now
                #, proxies=self.settings.get_proxies()[1]
                ,
                timeout=self.settings.request_timeout)

            if not response.ok:
                QApplication.restoreOverrideCursor()
                self.util.dlg_warning(u'{}: {} {}'.format(
                    response.status_code, response.status_message,
                    response.reason))
                return
            else:
                try:
                    json_txt = response.text.data().decode()
                    self.util.msg_log_debug(
                        u'resp_msg (decoded):\n{} .......'.format(
                            json_txt[:255]))
                    result = json.loads(json_txt)
                except TypeError as te:
                    self.util.msg_log_error(
                        u'unexpected TypeError: {0}'.format(te))
                    return False, self.util.tr(u'cc_api_not_accessible')
                except AttributeError as ae:
                    self.util.msg_log_error(
                        u'unexpected AttributeError: {0}'.format(ae))
                    return False, self.util.tr(u'cc_api_not_accessible')
                except:
                    self.util.msg_log_error(
                        u'unexpected error during request or parsing of response:'
                    )
                    self.util.msg_log_last_exception()
                    return False, self.util.tr(u'cc_invalid_json')

                self.settings.load()
                selected_servers = self.settings.selected_ckan_servers.split(
                    '|')
                self.servers = []
                self.util.msg_log_debug(u'{} custom servers'.format(
                    len(self.settings.custom_servers)))
                for cs_name in self.settings.custom_servers:
                    url = self.settings.custom_servers[cs_name]
                    si = ServerInstance(cs_name,
                                        cs_name,
                                        url,
                                        url,
                                        custom_entry=True)
                    si.selected = True if si.settings_key in selected_servers else False
                    self.servers.append(si)
                for entry in result:
                    url_api = None
                    if 'url-api' in entry:
                        url_api = entry['url-api']
                        if 'geothermaldata' not in url_api:
                            url_api = url_api.replace('http://', 'https://')
                        url_api += '/api/3/'
                    si = ServerInstance(entry['title'], entry['description'],
                                        entry['url'], url_api)
                    si.selected = True if si.settings_key in selected_servers else False
                    self.servers.append(si)

                for idx, server in enumerate(self.servers):
                    i = QStandardItem(server.title)
                    i.setData(server)
                    if server.api_url is not None:
                        if server.is_custom:
                            i.setBackground(QColor(0, 0, 255, 50))
                        i.setCheckable(True)
                        i.setCheckState(
                            Qt.Checked if server.selected else Qt.Unchecked)
                        self.list_model.appendRow(i)
        finally:
            self.__update_server_count()
            QApplication.restoreOverrideCursor()
Exemplo n.º 49
0
    def tabInformation(self):
        info = QWidget()
        vl = VLayout()

        self.program_model = QStandardItemModel()
        for d in [
                "Program version", "Build date & time", "Core/SDK version",
                "Flash write count", "Boot count", "Restart reason",
                "Friendly Name 1", "Friendly Name 2", "Friendly Name 3",
                "Friendly Name 4"
        ]:
            k = QStandardItem(d)
            k.setEditable(False)
            v = QStandardItem()
            v.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
            v.setEditable(False)
            self.program_model.appendRow([k, v])

        gbPrgm = GroupBoxH("Program")
        gbPrgm.setFlat(True)
        tvPrgm = QTreeView()
        tvPrgm.setHeaderHidden(True)
        tvPrgm.setRootIsDecorated(False)
        tvPrgm.setModel(self.program_model)
        tvPrgm.resizeColumnToContents(0)
        gbPrgm.addWidget(tvPrgm)

        self.esp_model = QStandardItemModel()
        for d in [
                "ESP Chip Id", "Flash Chip Id", "Flash Size",
                "Program Flash Size", "Program Size", "Free Program Space",
                "Free Memory"
        ]:
            k = QStandardItem(d)
            k.setEditable(False)
            v = QStandardItem()
            v.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
            v.setEditable(False)
            self.esp_model.appendRow([k, v])

        gbESP = GroupBoxH("ESP")
        gbESP.setFlat(True)
        tvESP = QTreeView()
        tvESP.setHeaderHidden(True)
        tvESP.setRootIsDecorated(False)
        tvESP.setModel(self.esp_model)
        tvESP.resizeColumnToContents(0)
        gbESP.addWidget(tvESP)

        # self.emul_model = QStandardItemModel()
        # for d in ["Emulation", "mDNS Discovery"]:
        #     k = QStandardItem(d)
        #     k.setEditable(False)
        #     v = QStandardItem()
        #     v.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
        #     v.setEditable(False)
        #     self.emul_model.appendRow([k, v])
        #
        # gbEmul = GroupBoxH("Emulation")
        # gbEmul.setFlat(True)
        # tvEmul = QTreeView()
        # tvEmul.setHeaderHidden(True)
        # tvEmul.setRootIsDecorated(False)
        # tvEmul.setModel(self.emul_model)
        # tvEmul.resizeColumnToContents(0)
        # gbEmul.addWidget(tvEmul)

        self.wifi_model = QStandardItemModel()
        for d in [
                "AP1 SSId (RSSI)", "Hostname", "IP Address", "Gateway",
                "Subnet Mask", "DNS Server", "MAC Address"
        ]:
            k = QStandardItem(d)
            k.setEditable(False)
            v = QStandardItem()
            v.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
            v.setEditable(False)
            self.wifi_model.appendRow([k, v])

        gbWifi = GroupBoxH("Wifi")
        gbWifi.setFlat(True)
        tvWifi = QTreeView()
        tvWifi.setHeaderHidden(True)
        tvWifi.setRootIsDecorated(False)
        tvWifi.setModel(self.wifi_model)
        tvWifi.resizeColumnToContents(0)
        gbWifi.addWidget(tvWifi)

        self.mqtt_model = QStandardItemModel()
        for d in [
                "MQTT Host", "MQTT Port", "MQTT User", "MQTT Client",
                "MQTT Topic", "MQTT Group Topic", "MQTT Full Topic",
                "MQTT Fallback Topic"
        ]:
            k = QStandardItem(d)
            k.setEditable(False)
            v = QStandardItem()
            v.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
            v.setEditable(False)
            self.mqtt_model.appendRow([k, v])

        gbMQTT = GroupBoxH("MQTT")
        gbMQTT.setFlat(True)
        tvMQTT = QTreeView()
        tvMQTT.setHeaderHidden(True)
        tvMQTT.setRootIsDecorated(False)
        tvMQTT.setModel(self.mqtt_model)
        tvMQTT.resizeColumnToContents(0)
        gbMQTT.addWidget(tvMQTT)

        hl = HLayout(0)
        vl_lc = VLayout(0, 3)
        vl_rc = VLayout(0, 3)

        vl_lc.addWidgets([gbPrgm, gbESP])
        vl_rc.addWidgets([gbWifi, gbMQTT])

        vl_rc.setStretch(0, 2)
        vl_rc.setStretch(1, 2)
        vl_rc.setStretch(2, 1)

        hl.addLayout(vl_lc)
        hl.addLayout(vl_rc)
        vl.addLayout(hl)
        info.setLayout(vl)
        return info
Exemplo n.º 50
0
    def rebuild(self):
        self.listModel.clear()
        if not self.ui.groupBox.isChecked() and self.ui.groupBox.isCheckable():
            self.parts=None
            self.listModel.clear()
            self.update()
            return
        field=self.ui.comboBox.itemData(self.ui.comboBox.currentIndex())

        minimum=None
        if self.ui.minCheckBox.isChecked():
            minimum=self.ui.minSpinBox.value()
        maximum=None
        if self.ui.maxCheckBox.isChecked():
            maximum=self.ui.maxSpinBox.value()
        bins=None
        if self.ui.binCheckBox.isChecked():
            bins=self.ui.binSpinBox.value()

        self.parts=self.model.partition(field,minimum,maximum,bins)

        lst=list(sorted(self.parts.keys()))
        keep=np.zeros(self.model.data.shape,dtype=bool)
        for i,s in enumerate(lst):
            c=self.model.cfg.color(field,s,i)
            item=QStandardItem(s)
            if self.colors:
                item.setData(QColor(c),Qt.DecorationRole)
            if self.checkable:
                item.setCheckable(True)
                item.setCheckState(Qt.Checked)
            item.setData(s)
            self.listModel.appendRow(item)
            keep |= self.parts[s]
        keep = np.logical_not(keep)
        if np.count_nonzero(keep):
            self.parts[MyPartitionWidget.unassignedStr] = keep
            item=QStandardItem(MyPartitionWidget.unassignedStr)
            if self.colors:
                item.setData(QColor("white"),Qt.DecorationRole)
            if self.checkable:
                item.setCheckable(True)
                item.setCheckState(Qt.Unchecked)
            item.setData("NaN / Outside Range")
            self.listModel.appendRow(item)
        self.update()
Exemplo n.º 51
0
    def setup_ui(self):
        """ Setup Ui
        """
        main_wrap = QVBoxLayout()
        main_wrap.setContentsMargins(0, 0, 0, 0)

        # updatebar on top
        self.update_bar = UpdateBar(self)
        self.update_bar.onUpdateNowClicked.connect(self._update_dwarf)
        self.update_bar.setVisible(False)
        main_wrap.addWidget(self.update_bar)

        # main content
        h_box = QHBoxLayout()
        h_box.setContentsMargins(15, 15, 15, 15)
        wrapper = QVBoxLayout()
        # wrapper.setGeometry(QRect(0, 0, 400, 200))
        head = QHBoxLayout()
        head.setContentsMargins(0, 10, 0, 10)
        # dwarf icon
        icon = QLabel()
        icon.setContentsMargins(40, 0, 0, 0)
        dwarf_logo = QPixmap(utils.resource_path('assets/dwarf.svg'))
        icon.setPixmap(dwarf_logo)
        head.addWidget(icon)

        # main title
        v_box = QVBoxLayout()
        title = QLabel('Dwarf')
        title.setContentsMargins(0, 0, 50, 0)
        title.setFont(QFont('Anton', 90, QFont.Bold))
        title.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        title.setFixedHeight(self.height() * .35)
        title.setAlignment(Qt.AlignCenter)
        v_box.addWidget(title)

        sub_title_text = (self._pick_random_word(0) + ' ' + self._pick_random_word(1) + ' ' +
                          self._pick_random_word(2) + ' ' + self._pick_random_word(3) + ' ' +
                          self._pick_random_word(4))
        sub_title_text = sub_title_text[:1].upper() + sub_title_text[1:]
        sub_title = QLabel(sub_title_text)
        sub_title.setFont(QFont('OpenSans', 14, QFont.Bold))
        sub_title.setFixedHeight(title.height() * .25)
        sub_title.setAlignment(Qt.AlignCenter)
        sub_title.setContentsMargins(0, 0, 50, 0)
        sub_title.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        v_box.addWidget(sub_title)
        head.addLayout(v_box)

        wrapper.addLayout(head)

        recent = QLabel('Last saved Sessions')
        font = recent.font()
        font.setBold(True)
        #font.setPointSize(10)
        recent.setFont(font)
        wrapper.addWidget(recent)
        wrapper.addWidget(self._recent_list)
        h_box.addLayout(wrapper, stretch=False)
        buttonSpacer = QSpacerItem(15, 100, QSizePolicy.Fixed, QSizePolicy.Minimum)
        h_box.addItem(buttonSpacer)
        wrapper = QVBoxLayout()

        btn = QPushButton()
        ico = QIcon(QPixmap(utils.resource_path('assets/android.svg')))
        btn.setIconSize(QSize(75, 75))
        btn.setIcon(ico)
        btn.setToolTip('New Android Session')
        btn.clicked.connect(self._on_android_button)

        wrapper.addWidget(btn)
        btn = QPushButton()
        ico = QIcon(QPixmap(utils.resource_path('assets/apple.svg')))
        btn.setIconSize(QSize(75, 75))
        btn.setIcon(ico)
        btn.setToolTip('New iOS Session')
        btn.clicked.connect(self._on_ios_button)
        wrapper.addWidget(btn)

        btn = QPushButton()
        ico = QIcon(QPixmap(utils.resource_path('assets/local.svg')))
        btn.setIconSize(QSize(75, 75))
        btn.setIcon(ico)
        btn.setToolTip('New Local Session')
        btn.clicked.connect(self._on_local_button)
        wrapper.addWidget(btn)

        btn = QPushButton()
        ico = QIcon(QPixmap(utils.resource_path('assets/remote.svg')))
        btn.setIconSize(QSize(75, 75))
        btn.setIcon(ico)
        btn.setToolTip('New Remote Session')
        btn.clicked.connect(self._on_remote_button)
        wrapper.addWidget(btn)

        session_history = self._prefs.get(prefs.RECENT_SESSIONS, default=[])
        invalid_session_files = []
        for recent_session_file in session_history:
            if os.path.exists(recent_session_file):
                with open(recent_session_file, 'r') as f:
                    exported_session = json.load(f)
                hooks = '0'
                watchers = '0'
                on_loads = 0
                bookmarks = '0'
                #have_user_script = False
                if 'hooks' in exported_session and exported_session['hooks'] is not None:
                    hooks = str(len(exported_session['hooks']))
                if 'watchers' in exported_session and exported_session['watchers'] is not None:
                    watchers = str(len(exported_session['watchers']))
                if 'nativeOnLoads' in exported_session and exported_session['nativeOnLoads'] is not None:
                    on_loads += len(exported_session['nativeOnLoads'])
                if 'javaOnLoads' in exported_session and exported_session['javaOnLoads'] is not None:
                    on_loads += len(exported_session['javaOnLoads'])
                if 'bookmarks' in exported_session and exported_session['bookmarks'] is not None:
                    bookmarks = str(len(exported_session['bookmarks']))
                if 'user_script' in exported_session and exported_session['user_script']:
                    have_user_script = exported_session['user_script'] != ''

                #user_script_item = QStandardItem()
                #if have_user_script:
                #user_script_item.setIcon(self._dot_icon)

                on_loads = str(on_loads)

                recent_session_file_item = QStandardItem(recent_session_file)
                recent_session_file_item.setData(exported_session, Qt.UserRole + 2)

                item_1 = QStandardItem(exported_session['session'])
                item_1.setTextAlignment(Qt.AlignCenter)
                item_2 = QStandardItem(hooks)
                item_2.setTextAlignment(Qt.AlignCenter)
                item_3 = QStandardItem(watchers)
                item_3.setTextAlignment(Qt.AlignCenter)
                item_4 = QStandardItem(on_loads)
                item_4.setTextAlignment(Qt.AlignCenter)
                item_5 = QStandardItem(bookmarks)
                item_5.setTextAlignment(Qt.AlignCenter)
                #item_6 = QStandardItem(user_script_item)
                #item_6.setTextAlignment(Qt.AlignCenter)

                self._recent_list_model.insertRow(self._recent_list_model.rowCount(), [
                    recent_session_file_item,
                    item_1, item_2, item_3, item_4, item_5
                ])
            else:
                invalid_session_files.append(recent_session_file)
        for invalid in invalid_session_files:
            session_history.pop(session_history.index(invalid))
        self._prefs.put(prefs.RECENT_SESSIONS, session_history)

        h_box.addLayout(wrapper, stretch=False)
        main_wrap.addLayout(h_box)
        self.setLayout(main_wrap)
Exemplo n.º 52
0
    def initLandmarkList(self):

        # initialize the landmarkTableModel (QTableView)
        landmarkModel = QStandardItemModel(0, 0)
        landmarkModel.setHorizontalHeaderItem(0, QStandardItem(''))
        landmarkModel.setHorizontalHeaderItem(1, QStandardItem('Source x'))
        landmarkModel.setHorizontalHeaderItem(2, QStandardItem('Source y'))
        landmarkModel.setHorizontalHeaderItem(3, QStandardItem('Target x'))
        landmarkModel.setHorizontalHeaderItem(4, QStandardItem('Target y'))
        landmarkModel.setHorizontalHeaderItem(5, QStandardItem('Set'))
        landmarkModel.setHorizontalHeaderItem(6, QStandardItem('Move'))
        landmarkModel.setHorizontalHeaderItem(7, QStandardItem('Clear'))
        self.lTable.setModel(landmarkModel)

        header = self.lTable.horizontalHeader()
        for i in range(8):
            if i not in [3, 4]:  # fixed width for target columns
                header.setSectionResizeMode(i, QHeaderView.ResizeToContents)

        self.lTable.setColumnWidth(3, 70)
        self.lTable.setColumnWidth(4, 70)
        self.lTable.verticalHeader().setSectionResizeMode(
            QHeaderView.ResizeToContents)

        landmarkModel = self.lTable.model()
        landmarks = json.loads(self.cfg['magc']['landmarks'])
        for id, (key, sourceTarget) in enumerate(landmarks.items()):
            item0 = QStandardItem(str(key))

            item1 = QStandardItem(str(sourceTarget['source'][0]))

            item2 = QStandardItem(str(sourceTarget['source'][1]))

            item5 = QPushButton('Set')
            item5.setFixedSize(QSize(50, 40))
            item5.clicked.connect(self.set_landmark(id))

            item6 = QPushButton('Go to')
            item6.setFixedSize(QSize(60, 40))
            item6.clicked.connect(self.goto_landmark(id))

            if self.cfg['sys']['simulation_mode'] == 'True':
                item5.setEnabled(False)
                item6.setEnabled(False)

            item7 = QPushButton('Clear')
            item7.setFixedSize(QSize(60, 40))
            item7.clicked.connect(self.clear_landmark(id))

            if 'target' in sourceTarget:
                item0.setBackground(QColor(Qt.green))

                item3 = QStandardItem(str(sourceTarget['target'][0]))
                item3.setBackground(QColor(Qt.green))

                item4 = QStandardItem(str(sourceTarget['target'][1]))
                item4.setBackground(QColor(Qt.green))
            else:
                item0.setBackground(QColor(Qt.lightGray))

                item3 = QStandardItem('')
                item3.setBackground(QColor(Qt.lightGray))

                item4 = QStandardItem('')
                item4.setBackground(QColor(Qt.lightGray))

                item6.setEnabled(False)
                item7.setEnabled(False)

            item3.setCheckable(False)
            item4.setCheckable(False)

            landmarkModel.appendRow([item0, item1, item2, item3, item4])
            self.lTable.setIndexWidget(landmarkModel.index(id, 5), item5)
            self.lTable.setIndexWidget(landmarkModel.index(id, 6), item6)
            self.lTable.setIndexWidget(landmarkModel.index(id, 7), item7)
Exemplo n.º 53
0
    def import_metadata(self):
        color_not_acquired = QColor(Qt.lightGray)
        color_acquired = QColor(Qt.green)
        color_acquiring = QColor(Qt.yellow)
        #-----------------------------
        # read sections from MagC yaml
        file_path = os.path.normpath(self.lineEdit_fileName.text())
        if not os.path.isfile(file_path):
            self.add_to_main_log('MagC file not found')
        else:
            self.cfg['magc']['sections_path'] = file_path
            with open(file_path, 'r') as f:
                sectionsYAML = yaml.full_load(f)
            sections, landmarks = utils.sectionsYAML_to_sections_landmarks(
                sectionsYAML)

            if 'sourceROIsUpdatedFromSBEMimage' in sectionsYAML:
                result = QMessageBox.question(
                    self, 'Section import',
                    'Using section locations that have been previously updated in SBEMImage ?',
                    QMessageBox.Yes | QMessageBox.No)
                if result == QMessageBox.Yes:
                    for sectionId, sectionXYA in \
                        sectionsYAML['sourceROIsUpdatedFromSBEMimage'].items():
                        sections[int(sectionId)] = {
                            'center': [float(a) for a in sectionXYA[:2]],
                            'angle': float((-sectionXYA[2] + 90) % 360)
                        }
                    self.cfg['magc']['roi_mode'] = 'False'

            n_sections = len([k for k in sections.keys() if str(k).isdigit()])
            self.add_to_main_log(
                str(n_sections) + ' MagC sections have been loaded.')
            #-----------------------------
            #--------------------------------------
            # import wafer overview if file present
            dir_sections = os.path.dirname(os.path.normpath(file_path))
            im_names = [
                im_name for im_name in os.listdir(dir_sections)
                if ('wafer' in im_name) and (
                    os.path.splitext(im_name)[1] in ['.tif', '.png'])
            ]
            if im_names == []:
                self.add_to_main_log('No wafer picture was found.')
            elif len(im_names) == 1:
                im_path = os.path.normpath(
                    os.path.join(dir_sections, im_names[0]))

                selection_success = True
                selected_filename = os.path.basename(im_path)
                timestamp = str(datetime.datetime.now())
                # Remove some characters from timestamp to get valid file name:
                timestamp = timestamp[:19].translate(
                    {ord(c): None
                     for c in ' :-.'})
                target_path = os.path.join(
                    self.target_dir,
                    os.path.splitext(selected_filename)[0] + '_' + timestamp +
                    '.png')
                if os.path.isfile(im_path):
                    # Copy file to data folder as png:
                    try:
                        imported_img = Image.open(im_path)
                        imported_img.save(target_path)
                    except Exception as e:
                        QMessageBox.warning(
                            self, 'Error',
                            'Could not load image file.' + str(e),
                            QMessageBox.Ok)
                        selection_success = False

                    if selection_success:
                        new_img_number = self.ovm.get_number_imported()
                        self.ovm.add_imported_img()
                        width, height = imported_img.size
                        self.ovm.set_imported_img_file(new_img_number,
                                                       target_path)
                        self.ovm.set_imported_img_name(new_img_number,
                                                       selected_filename)
                        self.ovm.set_imported_img_size_px_py(
                            new_img_number, width, height)
                        self.ovm.set_imported_img_pixel_size(
                            new_img_number, 1000)
                        self.cs.set_imported_img_centre_s(
                            new_img_number, [width // 2, height // 2])

                        self.viewport.mv_load_last_imported_image()
                        self.viewport.mv_draw()

                else:
                    QMessageBox.warning(self, 'Error',
                                        'Specified file not found.',
                                        QMessageBox.Ok)
                    selection_success = False
            else:
                self.add_to_main_log(
                    'There are more than 1 picture available in the folder containing the .magc section description file. Please place only one wafer picture (.tif) in the folder.'
                )
            #--------------------------------------

            #---------------------------------------
            # populate the grids and the sectionList
            tile_size_selector = self.comboBox_tileSize.currentIndex()
            pixel_size = self.doubleSpinBox_pixelSize.value()
            tile_overlap = self.doubleSpinBox_tileOverlap.value()

            sectionListView = self.gui_items['sectionList']
            sectionListModel = sectionListView.model()

            sectionListModel.clear()
            sectionListModel.setHorizontalHeaderItem(0,
                                                     QStandardItem('Section'))
            sectionListModel.setHorizontalHeaderItem(1, QStandardItem('State'))
            header = sectionListView.horizontalHeader()
            for i in range(2):
                header.setSectionResizeMode(i, QHeaderView.ResizeToContents)
            header.setStretchLastSection(True)

            self.gm.delete_all_grids()
            for section in range(n_sections):
                self.gm.add_new_grid()
            for idx, section in sections.items():
                if str(idx).isdigit():  # to exclude tissueROI and landmarks
                    self.gm.set_grid_size(
                        idx,
                        (self.spinBox_rows.value(), self.spinBox_cols.value()))
                    self.gm.set_tile_size_selector(idx, tile_size_selector)
                    self.gm.set_pixel_size(idx, pixel_size)
                    self.gm.set_overlap(idx, tile_overlap)
                    self.gm.select_all_tiles(idx)
                    self.gm.set_rotation(idx,
                                         (180 - float(section['angle'])) % 360)
                    self.gm.set_grid_center_s(
                        idx, list(map(float, section['center'])))
                    self.gm.calculate_grid_map(grid_number=idx)

                    # populate the sectionList
                    item1 = QStandardItem(str(idx))
                    item1.setCheckable(True)
                    item2 = QStandardItem('')
                    item2.setBackground(color_not_acquired)
                    item2.setCheckable(False)
                    item2.setSelectable(False)
                    sectionListModel.appendRow([item1, item2])
                    sectionListView.setRowHeight(idx, 40)
            #---------------------------------------

            #---------------------------------------
            # Update config with MagC items
            self.cfg['sys']['magc_mode'] = 'True'
            self.cfg['magc']['sections'] = json.dumps(sections)
            self.cfg['magc']['selected_sections'] = '[]'
            self.cfg['magc']['checked_sections'] = '[]'
            self.cfg['magc']['landmarks'] = json.dumps(landmarks)
            # xxx does importing a new magc file always require a wafer_calibration ?
            self.queue.put('SAVE INI')
            self.trigger.s.emit()
            # ---------------------------------------

            # enable wafer configuration button
            self.queue.put('MAGC ENABLE CALIBRATION')
            self.trigger.s.emit()
            self.queue.put('MAGC WAFER NOT CALIBRATED')
            self.trigger.s.emit()

        self.accept()
Exemplo n.º 54
0
 def addGCodeFileLine(self, num: int):
     item = QStandardItem("")
     self.__gcodeFileUiModel.insertRow(num + 1, item)
Exemplo n.º 55
0
    def __init__(self, parent, info, title="Channel Properties"):
        super().__init__(parent)
        self.setWindowTitle(title)

        self.model = QStandardItemModel(info["nchan"], 4)
        self.model.setHorizontalHeaderLabels(["#", "Label", "Type", "Bad"])
        for index, ch in enumerate(info["chs"]):
            item = QStandardItem()
            item.setData(index, Qt.DisplayRole)
            item.setFlags(item.flags() & ~Qt.ItemIsEditable)
            self.model.setItem(index, 0, item)
            self.model.setItem(index, 1, QStandardItem(ch["ch_name"]))
            kind = channel_type(info, index).upper()
            self.model.setItem(index, 2, QStandardItem(str(kind)))
            bad = QStandardItem()
            bad.setData(ch["ch_name"] in info["bads"], Qt.UserRole)
            bad.setCheckable(True)
            bad.setEditable(False)
            checked = ch["ch_name"] in info["bads"]
            bad.setCheckState(Qt.Checked if checked else Qt.Unchecked)
            self.model.setItem(index, 3, bad)

        self.model.itemChanged.connect(bad_changed)
        self.proxymodel = MySortFilterProxyModel()
        self.proxymodel.setDynamicSortFilter(False)
        self.proxymodel.setSourceModel(self.model)

        self.view = QTableView()
        self.view.setModel(self.proxymodel)
        self.view.setItemDelegateForColumn(2, ComboBoxDelegate(self.view))
        self.view.setEditTriggers(QAbstractItemView.AllEditTriggers)
        self.view.verticalHeader().setVisible(False)
        self.view.horizontalHeader().setStretchLastSection(True)
        self.view.setShowGrid(False)
        self.view.setSelectionMode(QAbstractItemView.NoSelection)
        self.view.setSortingEnabled(True)
        self.view.sortByColumn(0, Qt.AscendingOrder)

        vbox = QVBoxLayout(self)
        vbox.addWidget(self.view)
        self.buttonbox = QDialogButtonBox(QDialogButtonBox.Ok |
                                          QDialogButtonBox.Cancel)
        vbox.addWidget(self.buttonbox)
        self.buttonbox.accepted.connect(self.accept)
        self.buttonbox.rejected.connect(self.reject)

        self.resize(475, 650)
        self.view.setColumnWidth(0, 70)
        self.view.setColumnWidth(1, 155)
        self.view.setColumnWidth(2, 90)
Exemplo n.º 56
0
    def _on_add_breakpoint(self, breakpoint):
        type_ = QStandardItem()
        type_.setFont(self._bold_font)
        type_.setTextAlignment(Qt.AlignCenter)
        if breakpoint.breakpoint_type == BREAKPOINT_NATIVE:
            type_.setText('N')
            type_.setToolTip('Native breakpoint')
        elif breakpoint.breakpoint_type == BREAKPOINT_JAVA:
            type_.setText('J')
            type_.setToolTip('Java breakpoint')
        elif breakpoint.breakpoint_type == BREAKPOINT_INITIALIZATION:
            type_.setText('C')
            type_.setToolTip('Initialization breakpoint')
        elif breakpoint.breakpoint_type == BREAKPOINT_OBJC:
            type_.setText('O')
            type_.setToolTip('ObjC breakpoint')
        else:
            type_.setText('U')
            type_.setToolTip('Unknown Type')

        addr = QStandardItem()

        if breakpoint.breakpoint_type == BREAKPOINT_JAVA:
            addr.setText(breakpoint.get_target())
        elif breakpoint.breakpoint_type == BREAKPOINT_OBJC:
            addr.setText(breakpoint.get_target())
        elif breakpoint.breakpoint_type == BREAKPOINT_INITIALIZATION:
            addr.setText(breakpoint.get_target())
            addr.setData(breakpoint.debug_symbol, Qt.UserRole + 2)
        else:
            str_fmt = '0x{0:x}'
            if self._breakpoints_list.uppercase_hex:
                str_fmt = '0x{0:X}'
            # addr.setTextAlignment(Qt.AlignCenter)
            addr.setText(str_fmt.format(breakpoint.get_target()))

        condition = QStandardItem()
        condition.setTextAlignment(Qt.AlignCenter)
        condition.setFont(self._bold_font)
        if breakpoint.condition and breakpoint.condition != 'null' and breakpoint.condition != 'undefined':
            condition.setText('ƒ')
            condition.setToolTip(breakpoint.condition)
            condition.setData(breakpoint.condition, Qt.UserRole + 2)

        self._breakpoints_model.appendRow([addr, type_, condition])
        self._breakpoints_list.resizeColumnToContents(0)
Exemplo n.º 57
0
 def fill_pages(self):
     self.loadingPages = True
     self.pagesModel.clear()
     if len(self.pagesWatcher.files()) > 0:
         self.pagesWatcher.removePaths(self.pagesWatcher.files())
     pagesList = []
     if "pages" in self.setupDictionary.keys():
         pagesList = self.setupDictionary["pages"]
     progress = QProgressDialog()
     progress.setMinimum(0)
     progress.setMaximum(len(pagesList))
     progress.setWindowTitle(i18n("Loading Pages..."))
     for url in pagesList:
         absurl = os.path.join(self.projecturl, url)
         relative = os.path.relpath(absurl, self.projecturl)
         if (os.path.exists(absurl)):
             #page = Application.openDocument(absurl)
             page = zipfile.ZipFile(absurl, "r")
             thumbnail = QImage.fromData(page.read("preview.png"))
             pageItem = QStandardItem()
             dataList = self.get_description_and_title(
                 page.read("documentinfo.xml"))
             if (dataList[0].isspace() or len(dataList[0]) < 1):
                 dataList[0] = os.path.basename(url)
             pageItem.setText(dataList[0].replace("_", " "))
             pageItem.setDragEnabled(True)
             pageItem.setDropEnabled(False)
             pageItem.setEditable(False)
             pageItem.setIcon(QIcon(QPixmap.fromImage(thumbnail)))
             pageItem.setData(dataList[1], role=CPE.DESCRIPTION)
             pageItem.setData(relative, role=CPE.URL)
             self.pagesWatcher.addPath(absurl)
             pageItem.setData(dataList[2], role=CPE.KEYWORDS)
             pageItem.setData(dataList[3], role=CPE.LASTEDIT)
             pageItem.setData(dataList[4], role=CPE.EDITOR)
             pageItem.setToolTip(relative)
             page.close()
             self.pagesModel.appendRow(pageItem)
             progress.setValue(progress.value() + 1)
     progress.setValue(len(pagesList))
     self.loadingPages = False
Exemplo n.º 58
0
def makeItem(text, data=None):
    item = QStandardItem(text)
    item.setFlags(Qt.ItemIsEnabled)
    item.setData(data)
    return item
Exemplo n.º 59
0
            elif checked:
                header.updateCheckState(i, 1)
            else:
                header.updateCheckState(i, 0)

    app = QApplication(sys.argv)

    tableView = QTableView()
    model = QStandardItemModel()
    model.itemChanged.connect(modelChanged)
    model.setHorizontalHeaderLabels(['Title 1\nA Second Line', 'Title 2'])
    header = CheckBoxHeader([0, 1], parent=tableView)
    header.clicked.connect(updateModel)

    # populate the models with some items
    for i in range(3):
        item1 = QStandardItem('Item %d' % i)
        item1.setCheckable(True)

        item2 = QStandardItem('Another Checkbox %d' % i)
        item2.setCheckable(True)

        model.appendRow([item1, item2])

    tableView.setModel(model)
    tableView.setHorizontalHeader(header)
    tableView.setSortingEnabled(True)
    tableView.show()

    sys.exit(app.exec_())
Exemplo n.º 60
0
 def get_list_item(self):
     name = self.get_name()
     icon = self.get_icon()
     return QStandardItem(icon,
                          self.__class__.__name__), QStandardItem(name)