def update_pages(self, new_download=False): if self.current_download is None: return if "files" not in self.current_download: self.current_download["files"] = [] self.window().download_progress_bar.update_with_download( self.current_download) self.window().download_detail_name_label.setText( self.current_download['name']) if self.current_download["vod_mode"]: self.window().download_detail_status_label.setText('Streaming') else: status_string = DLSTATUS_STRINGS[dlstatus_strings.index( self.current_download["status"])] if dlstatus_strings.index(self.current_download["status"] ) == DLSTATUS_STOPPED_ON_ERROR: status_string += f" (error: {self.current_download['error']})" self.window().download_detail_status_label.setText(status_string) self.window().download_detail_filesize_label.setText( "%s in %d files" % (format_size(float(self.current_download["size"])), len(self.current_download["files"]))) self.window().download_detail_health_label.setText( "%d seeders, %d leechers" % (self.current_download["num_seeds"], self.current_download["num_peers"])) self.window().download_detail_infohash_label.setText( self.current_download['infohash']) self.window().download_detail_destination_label.setText( self.current_download["destination"]) self.window().download_detail_ratio_label.setText( "%.3f, up: %s, down: %s" % ( self.current_download["ratio"], format_size(self.current_download["total_up"]), format_size(self.current_download["total_down"]), )) self.window().download_detail_availability_label.setText( f"{self.current_download['availability']:.2f}") if new_download or len(self.current_download["files"]) != len( self.files_widgets.keys()): # (re)populate the files list self.window().download_files_list.clear() self.files_widgets = {} for dfile in self.current_download["files"]: item = DownloadFileWidgetItem( self.window().download_files_list, dfile) DownloadsDetailsTabWidget.update_file_row(item, dfile) self.files_widgets[dfile["name"]] = item else: # No new download, just update data in the lists for dfile in self.current_download["files"]: DownloadsDetailsTabWidget.update_file_row( self.files_widgets[dfile["name"]], dfile) # Populate the trackers list self.window().download_trackers_list.clear() for tracker in self.current_download["trackers"]: item = QTreeWidgetItem(self.window().download_trackers_list) DownloadsDetailsTabWidget.update_tracker_row(item, tracker) # Populate the peers list if the peer information is available self.window().download_peers_list.clear() if "peers" in self.current_download: for peer in self.current_download["peers"]: item = QTreeWidgetItem(self.window().download_peers_list) DownloadsDetailsTabWidget.update_peer_row(item, peer)
def updatetree(self, pack): if self.running_tree == True: self.tree.clear() root1 = QTreeWidgetItem(self.tree) root1.setText(0, "Frame: " + str(pack["Packet_len"]) + " bytes") child1 = QTreeWidgetItem(root1) child1.setText( 0, "Arrival Time: " + str(pack["Time"]) + '\n' + "Frame Length: " + str(pack["Packet_len"]) + "bytes") root2 = QTreeWidgetItem(self.tree) root2.setText(0, "Ethernet,Src: " + str(pack["Source MAC"]) + ", Dst: " + str(pack["Destination MAC"])) #str(pack[]) child2 = QTreeWidgetItem(root2) child2.setText( 0, "Source Mac: " + str(pack['Source MAC']) + '\n' + "Destination MAC: " + str(pack["Destination MAC"]) + "\n" + "Protocol: " + str(pack["Protocol"])) print(pack['Protocol']) if str(pack['Protocol']) == 'UDP': root3 = QTreeWidgetItem(self.tree) root3.setText( 0, "Internet Protocol Version " + str(pack["IP Version"]) + ", Src: " + str(pack['Source']) + ", Dst" + str(pack['Destination'])) child3 = QTreeWidgetItem(root3) child3.setText( 0, "IP Header Length: " + str(int(str(pack['IP Header Length'])) * 4) + "\n" + "Time to live: " + str(pack['TTL']) + "\n" + "Source IP Address: " + str(pack["Source"]) + "\n" + "Destination IP Address: " + str(pack['Destination']) + "\nProtocol: " + str(pack['Protocol']) + "\nHeader Checksum: " + str(pack['Checksum'])) root4 = QTreeWidgetItem(self.tree) root4.setText( 0, "User Datagram Protocol, Src Port: " + str(pack['Souce port']) + "Dst Port: " + str(pack['Destination port'])) child4 = QTreeWidgetItem(root4) child4.setText(0,"Source Port: " + str(pack['Souce port']) + "\n" + 'Destination Port: ' + str(pack['Destination port']) + \ "\n" + "Length: " + str(pack['User packet length']) + "\nChecksum: " + str(pack['Checksum UDP'])) elif str(pack['Protocol']) == 'TCP': root3 = QTreeWidgetItem(self.tree) root3.setText( 0, "Internet Protocol Version " + str(pack["IP Version"]) + ", Src: " + str(pack['Source']) + ", Dst" + str(pack['Destination'])) child3 = QTreeWidgetItem(root3) child3.setText( 0, "IP Header Length: " + str(int(str(pack['IP Header Length'])) * 4) + "\n" + "Time to live: " + str(pack['TTL']) + "\n" + "Source IP Address: " + str(pack["Source"]) + "\n" + "Destination IP Address: " + str(pack['Destination']) + "\nProtocol: " + str(pack['Protocol']) + "\nHeader Checksum: " + str(pack['Checksum'])) root4 = QTreeWidgetItem(self.tree) root4.setText( 0, "Transmission Protocol, Src Port: " + str(pack['Source Port']) + ",Dst Port: " + str(pack['Destination Port'])) child4 = QTreeWidgetItem(root4) child4.setText(0, "Source Port: " + str(pack['Source Port']) + "\n" + 'Destination Port: ' + str(pack['Destination Port']) + \ "\n" + "Sequence Number: " + str(pack['Sequence Number']) + "\nAcknowledge Number: " + str(pack['Acknowledge Number']) +\ "\nTCP Header Length: " + str(int(str(pack['TCP Header Length']))*4) + "\nWindow length: " + str(pack['Window length']) +\ "\nChecksum: " + str(pack['Checksum_tcp']) + "\nUrgent pointer: " + str(pack['Urgepkt'])) elif str(pack['Protocol']) == 'ICMP': root3 = QTreeWidgetItem(self.tree) root3.setText( 0, "Internet Protocol Version " + str(pack["IP Version"]) + ", Src: " + str(pack['Source']) + ", Dst" + str(pack['Destination'])) child3 = QTreeWidgetItem(root3) child3.setText( 0, "IP Header Length: " + str(int(str(pack['IP Header Length'])) * 4) + "\n" + "Time to live: " + str(pack['TTL']) + "\n" + "Source IP Address: " + str(pack["Source"]) + "\n" + "Destination IP Address: " + str(pack['Destination']) + "\nProtocol: " + str(pack['Protocol']) + "\nHeader Checksum: " + str(pack['Checksum'])) root4 = QTreeWidgetItem(self.tree) root4.setText(0, "Internet Control Message Protocol") child4 = QTreeWidgetItem(root4) child4.setText( 0, "Type: " + str(pack["ICMP Type"]) + "\nCode: " + str(pack["ICMP Code"]) + "\nChecksum: " + str(pack["ICMP Checksum"]) + "\nIdentifier: " + str(pack["Identifier"] + "\nSequenct Numver: " + str(pack["Sequence"]))) elif str(pack["Protocol"]) == "ARP": root3 = QTreeWidgetItem(self.tree) root3.setText(0, "Address Resolution Protocol ") child3 = QTreeWidgetItem(root3) child3.setText(0,"Hardware type: " + str(pack["Hardware type"]) + '\n' + "Protocol type: " + str(pack["Protocol type"]) + "\n" + \ "Hardware size: " + str(pack["Hardware size"]) + '\n' + "Protocol size: " + str(pack["Protocol Size"]) + "\n" +\ "Opcode: " + str(pack["Opcode"]) + '\n' + "Sender MAC Address: " + str(pack["Source"]) + "\n" +\ "Sender IP Address: " + str(pack["Source IP Address"]) + "\n" + "Target MAC Address: " + str(pack["Destination"]) + '\n' +\ "Target IP Address: " + str(pack["Target IP Address"])) self.running_tree = False
def update(self, *, network: Network, servers: dict, use_tor: bool): self.clear() # connected servers connected_servers_item = QTreeWidgetItem([_("Connected nodes"), '']) connected_servers_item.setData(0, self.ITEMTYPE_ROLE, self.ItemType.TOPLEVEL) chains = network.get_blockchains() n_chains = len(chains) for chain_id, interfaces in chains.items(): b = blockchain.blockchains.get(chain_id) if b is None: continue name = b.get_name() if n_chains > 1: x = QTreeWidgetItem( [name + '@%d' % b.get_max_forkpoint(), '%d' % b.height()]) x.setData(0, self.ITEMTYPE_ROLE, self.ItemType.CHAIN) x.setData(0, self.CHAIN_ID_ROLE, b.get_id()) else: x = connected_servers_item for i in interfaces: star = ' *' if i == network.interface else '' item = QTreeWidgetItem( [f"{i.server.net_addr_str()}" + star, '%d' % i.tip]) item.setData(0, self.ITEMTYPE_ROLE, self.ItemType.CONNECTED_SERVER) item.setData(0, self.SERVER_ADDR_ROLE, i.server) item.setToolTip(0, str(i.server)) x.addChild(item) if n_chains > 1: connected_servers_item.addChild(x) # disconnected servers disconnected_servers_item = QTreeWidgetItem( [_("Other known servers"), ""]) disconnected_servers_item.setData(0, self.ITEMTYPE_ROLE, self.ItemType.TOPLEVEL) connected_hosts = set( [iface.host for ifaces in chains.values() for iface in ifaces]) protocol = PREFERRED_NETWORK_PROTOCOL for _host, d in sorted(servers.items()): if _host in connected_hosts: continue if _host.endswith('.onion') and not use_tor: continue port = d.get(protocol) if port: server = ServerAddr(_host, port, protocol=protocol) item = QTreeWidgetItem([server.net_addr_str(), ""]) item.setData(0, self.ITEMTYPE_ROLE, self.ItemType.DISCONNECTED_SERVER) item.setData(0, self.SERVER_ADDR_ROLE, server) disconnected_servers_item.addChild(item) self.addTopLevelItem(connected_servers_item) self.addTopLevelItem(disconnected_servers_item) connected_servers_item.setExpanded(True) for i in range(connected_servers_item.childCount()): connected_servers_item.child(i).setExpanded(True) disconnected_servers_item.setExpanded(True) # headers h = self.header() h.setStretchLastSection(False) h.setSectionResizeMode(0, QHeaderView.Stretch) h.setSectionResizeMode(1, QHeaderView.ResizeToContents) super().update()
def handleRequest(self, request, mainWindow): requestId = request[:3] requestdata = request[3:] if requestId in self.easyRequestIds: self.guiHelper.printOutput(requestdata) elif requestId == "402": print("[Client/Info] You got kicked by the console.") self.kicked = True elif requestId == "403": print("[Client/Info]Server shut down.") self.serverOffline = True elif requestId == "022": count = 0 countAtt = 0 channelNames = list() channelDescriptions = list() channelPasswords = list() channelAccessLevels = list() channelAttributes = requestdata.split(":") self.guiHelper.printOutput("[Client/Info] Channels: ") for attributeList in channelAttributes: attributes = attributeList.split(",") for attribute in attributes: attribute = attribute.replace("'", " ").strip("[]").strip() if countAtt == 0: channelNames.append(attribute) elif countAtt == 1: channelDescriptions.append(attribute) elif countAtt == 2: channelPasswords.append(attribute) else: channelAccessLevels.append(attribute) countAtt = countAtt + 1 for name in channelNames: self.guiHelper.printOutput(name + " desc: " + channelDescriptions[count] + " pw: " + channelPasswords[count] + " accessLevel: " + channelAccessLevels[count]) count = count + 1 elif requestId == "611": print("deleted") elif requestId == "405": self.guiHelper.printOutput(requestdata) self.banned = True elif requestId == "811": self.clientObject.socketObject.sendall( DecodingEncodingHelper().stringToBytes("901")) elif requestId == "903": mainWindow.statusButton.setText("Online Connected as: " + self.clientObject.username) self.clientObject.socketObject.sendall( DecodingEncodingHelper().stringToBytes("901")) elif requestId == "901": count = 0 mainWindow.channelTree.clear() requestdata = requestdata.strip("[]") requestdata = requestdata.split(";") for channel in requestdata: if count == 0: channel = channel.strip('"') channel = channel.replace(" '", "") channel = channel.strip("'") else: channel = channel.strip('"') channel = channel.replace(" '", "") channel = channel.strip("'") channel = channel[1:] channel = channel.strip() channel = channel.strip('"') channel = channel.split(":") channelName = channel[0] member = channel[1] member = member.strip("[]") member = member.split(",") channelItem = QTreeWidgetItem([channelName]) for mem in member: mem = mem.strip("'") clientItem = QTreeWidgetItem(["-" + mem]) channelItem.addChild(clientItem) mainWindow.channelTree.addTopLevelItem(channelItem) mainWindow.channelTree.expandAll() count = count + 1 elif requestId == "904": var = None #rank = requestdata elif requestId == "902": print("couldt log in") raise SystemExit() elif len(requestId) == 0: raise SystemExit() else: self.guiHelper.printOutput( "[Client/Error] Server sent unknown requestId: " + requestId)
def __createResultItem(self, file, line, pos, message, fixed, autofixing, ignored): """ Private method to create an entry in the result list. @param file file name of the file (string) @param line line number of issue (integer or string) @param pos character position of issue (integer or string) @param message message text (string) @param fixed flag indicating a fixed issue (boolean) @param autofixing flag indicating, that we are fixing issues automatically (boolean) @param ignored flag indicating an ignored issue (boolean) @return reference to the created item (QTreeWidgetItem) """ from .CodeStyleFixer import FixableCodeStyleIssues if self.__lastFileItem is None: # It's a new file self.__lastFileItem = QTreeWidgetItem(self.resultList, [file]) self.__lastFileItem.setFirstColumnSpanned(True) self.__lastFileItem.setExpanded(True) self.__lastFileItem.setData(0, self.filenameRole, file) fixable = False code, message = message.split(None, 1) itm = QTreeWidgetItem(self.__lastFileItem, ["{0:6}".format(line), code, message]) if code.startswith(("W", "-")): itm.setIcon(1, UI.PixmapCache.getIcon("warning.png")) elif code.startswith("N"): itm.setIcon(1, UI.PixmapCache.getIcon("namingError.png")) elif code.startswith("D"): itm.setIcon(1, UI.PixmapCache.getIcon("docstringError.png")) else: itm.setIcon(1, UI.PixmapCache.getIcon("syntaxError.png")) if fixed: itm.setIcon(0, UI.PixmapCache.getIcon("issueFixed.png")) elif code in FixableCodeStyleIssues and not autofixing: itm.setIcon(0, UI.PixmapCache.getIcon("issueFixable.png")) fixable = True itm.setTextAlignment(0, Qt.AlignRight) itm.setTextAlignment(1, Qt.AlignHCenter) itm.setTextAlignment(0, Qt.AlignVCenter) itm.setTextAlignment(1, Qt.AlignVCenter) itm.setTextAlignment(2, Qt.AlignVCenter) itm.setData(0, self.filenameRole, file) itm.setData(0, self.lineRole, int(line)) itm.setData(0, self.positionRole, int(pos)) itm.setData(0, self.messageRole, message) itm.setData(0, self.fixableRole, fixable) itm.setData(0, self.codeRole, code) itm.setData(0, self.ignoredRole, ignored) if ignored: font = itm.font(0) font.setItalic(True) for col in range(itm.columnCount()): itm.setFont(col, font) return itm
def updatedata(): # Load the SEN file path_sen = Dialog.lineEditInputFilePath.text() file_sen = pyst.SenFile(path_sen) # abort if file is empty Dialog.label_senFileNotReadable.setVisible(False) if len(file_sen.groups) == 0: Dialog.label_senFileNotReadable.setVisible(True) return path_pst = Dialog.lineEditInputFilePath_2.text() file_pst = pyst.PestCtrlFile(path_pst) # change working directory filename = path_pst.split("/")[-1] workpath = path_pst.replace(filename, "") os.chdir(workpath) # set spinbox and LCD to last iteration iterations = file_sen.getnumberofiterations() Dialog.spinBox_IterationNumber.setMaximum(iterations) CurrentIteration = Dialog.spinBox_IterationNumber.value() Dialog.lcdNumberTotalRuns.display(iterations) # POPULATE PREFERRED VALUES TREE view = Dialog.treeWidgetSlaves view.clear() treeelements = {} for group in file_sen.groups: newgroup = QTreeWidgetItem(0) newgroup.setText(0, group) treeelements[group] = newgroup view.addTopLevelItem(newgroup) newgroup.setExpanded(True) h = { 'name': 0, 'val': 1, 'sens': 2, 'lower': 3, 'pref': 4, 'upper': 5 } # column numbers for p in file_sen.getparamaternames(): newpar = QTreeWidgetItem(0) newpar.setText(h['name'], p) newpar.setText(h['val'], str(file_sen.parhistory[CurrentIteration][p])) newpar.setText(h['sens'], str(file_sen.senhistory[CurrentIteration][p])) newpar.setText(h['lower'], str(file_pst.params[p].PARLBND)) newpar.setText(h['pref'], str(file_pst.params[p].PARVAL1)) newpar.setText(h['upper'], str(file_pst.params[p].PARUBND)) treeelements[file_sen.membership[p]].addChild(newpar) # POPULATE PARAMETER STATE VIEW view = Dialog.treeWidgetParameterState view.clear() # get Parametergroups as top level items: viewTopLevelItems = {} viewTreeItems = {} for gname in file_sen.groups: newGroupItem = QTreeWidgetItem(0) newGroupItem.setText(0, gname) newScaleView = QParameterValueViewScale(logTransform=True) viewTreeItems[gname.lower()] = newScaleView viewTopLevelItems[gname] = newGroupItem view.addTopLevelItem(newGroupItem) Dialog.treeWidgetParameterState.setItemWidget(newGroupItem, 4, newScaleView) newGroupItem.setExpanded(True) AxisMinGlobal = None AxisMaxGlobal = None AxisBaseGlobal = 0 AxisIntervalGlobal = 0 parvals = file_sen.parhistory[CurrentIteration] for pname in file_sen.getparamaternames(): parameter = file_pst.params[pname] newPar = QTreeWidgetItem(0) viewTopLevelItems[parameter.PARGP].addChild(newPar) newPar.setText(0, pname) # set Sensitivity sh = file_sen.senhistory newPar.setText(1, str(sh[CurrentIteration][pname])) # set Phi contrib ph = file_sen.parhistory parval = ph[CurrentIteration][pname] prefval = parameter.PARVAL1 phi = abs(log10(parval) - log10(prefval))**2 newPar.setText(2, "{:.7f}".format(phi)) # set Identifiability index expectedFilePath = pname + ".genlinpred.out" if os.path.isfile(expectedFilePath): genlinpredresult = pyst.GenlinpredOutFile(expectedFilePath) identifiabilityIndex = genlinpredresult.parameterUncertainty.identifiability[ pname] newPar.setText(3, "{:.7f}".format(identifiabilityIndex)) # set parameterview parvalView = QParameterValueView(logTransform=True) parvalView.setParlbnd(parameter.PARLBND) parvalView.setParubnd(parameter.PARUBND) parvalView.setParval(parvals[pname.lower()]) parvalView.setPrefval(parameter.PARVAL1) if os.path.isfile(expectedFilePath): genlinpredresult = pyst.GenlinpredOutFile(expectedFilePath) priorvariance = genlinpredresult.predunc1.preCalTotalUncertaintyVariance priorstddev = priorvariance**0.5 posteriorvar = genlinpredresult.predunc1.postCalTotalUncertaintyVariance posteriorstddev = posteriorvar**0.5 else: priorstddev = 1 posteriorstddev = 1 parvalView.setPriorstdev(priorstddev) parvalView.setPosteriorstdev(posteriorstddev) parvalView.setAxisMin(parameter.PARLBND) parvalView.setAxisMax(parameter.PARUBND) parvalView.showBoundBracket(Dialog.checkBox_BoundBrackets.isChecked()) parvalView.showDevBar(Dialog.checkBox_Deviation.isChecked()) parvalView.showPreCalRange( Dialog.checkBox_PreCalParamUncert.isChecked()) parvalView.showPostCalRange( Dialog.checkBox_PostCalParamUncert.isChecked()) if AxisMinGlobal is None or parameter.PARLBND < AxisMinGlobal: AxisMinGlobal = parameter.PARLBND if AxisMaxGlobal is None or parameter.PARUBND > AxisMaxGlobal: AxisMaxGlobal = parameter.PARUBND Dialog.treeWidgetParameterState.setItemWidget(newPar, 4, parvalView) viewTreeItems[pname.lower()] = parvalView # set consistent axis scale amongst all widgets # TODO: consistency to be implemented per group for item in viewTreeItems.keys(): viewTreeItems[item].setAxisMin(AxisMinGlobal) viewTreeItems[item].setAxisMax(AxisMaxGlobal) viewTreeItems[item].setAxisbase(AxisBaseGlobal) viewTreeItems[item].setAxisinterval(AxisIntervalGlobal) # POPULATE FILE WINDOWS Dialog.plainTextEdit.clear() # SEN File Window senfileraw = open(path_sen) lines = senfileraw.readlines() for l in lines: Dialog.plainTextEdit.appendPlainText(l.replace("\n", "")) senfileraw.close() Dialog.plainTextEdit_PstFile.clear() # PST File Window pstfileraw = open(path_pst) lines = pstfileraw.readlines() for l in lines: Dialog.plainTextEdit_PstFile.appendPlainText(l.replace("\n", "")) pstfileraw.close()
def addRootItem(self, name): root = QTreeWidgetItem(self.treeWidget) root.setText(name) root.setFlags(Qt.ItemIsEnabled | Qt.ItemIsEditable)
def load(self): for frequency in self.frequencies: new = QTreeWidgetItem([str(frequency)]) self.treeWidget.addTopLevelItem(new)
def addFileToSubpackage(self, parent, title, data): item = QTreeWidgetItem(parent, [title]) item.setData(self.column, QtCore.Qt.UserRole, data) return item
def _populate_repo_tree(self): """ Initialize the tree widget of repos and volumes. """ self._repo_treewidget.clear() if self._repos_info is None: return for repo_uuid, repo_info in sorted(self._repos_info.items()): if repo_info is None: continue repo_column_dict = collections.defaultdict(str) repo_column_dict["Alias"] = repo_info["Alias"] repo_column_dict["Details"] = "Created: " + repo_info["Created"] repo_column_dict["UUID"] = repo_uuid repo_column_values = [ repo_column_dict[k] for k in TREEVIEW_COLUMNS ] repo_item = QTreeWidgetItem(self._repo_treewidget, repo_column_values) repo_item.setData(0, Qt.UserRole, (repo_uuid, "", "")) for data_name, data_info in repo_info["DataInstances"].items(): data_instance_dict = collections.defaultdict(str) data_instance_dict["Alias"] = data_name typename = data_info["Base"]["TypeName"] data_instance_dict["TypeName"] = typename is_voxels = (typename in VOXEL_TYPENAMES) if is_voxels: start_coord = data_info["Extended"]["MinPoint"] if start_coord: start_coord = tuple(start_coord) stop_coord = data_info["Extended"]["MaxPoint"] if stop_coord: stop_coord = tuple(x + 1 for x in stop_coord) if start_coord and stop_coord: shape = tuple(b - a for a, b in zip(start_coord, stop_coord)) else: shape = None data_instance_dict[ "Details"] = "Size={} | Start={} | Stop={}".format( shape, start_coord, stop_coord) data_column_values = [ data_instance_dict[k] for k in TREEVIEW_COLUMNS ] data_item = QTreeWidgetItem(repo_item, data_column_values) data_item.setData(0, Qt.UserRole, (repo_uuid, data_name, typename)) # If we're in specify_new mode, only the # repo parent items are selectable. # Also, non-volume items aren't selectable. if self._mode == 'specify_new' or typename not in self._selectable_types: flags = data_item.flags() flags &= ~Qt.ItemIsSelectable flags &= ~Qt.ItemIsEnabled data_item.setFlags(flags) self._repo_treewidget.collapseAll() self._repo_treewidget.setSortingEnabled(True) if self._hostname in self._default_nodes: self._select_node_uuid(self._default_nodes[self._hostname]) self._repo_treewidget.resizeColumnToContents(0) self._repo_treewidget.setFocus()
def on_update(self): selected_item = self.currentItem() current_token_id = selected_item.data(0, Qt.UserRole) if selected_item else None self.clear() tokens = self.parent.wallet.token_types.copy() for token_id, i in tokens.items(): name = i["name"] decimals = i["decimals"] calculated_balance= self.get_balance_from_token_id(token_id) if decimals != "?": balancestr = format_satoshis_nofloat(calculated_balance, decimal_point=decimals, num_zeros=decimals) balancestr += ' '*(9-decimals) else: balancestr = "double-click to add" typestr = "?" if i['class'] == "SLP1": typestr = "Type 1" elif i['class'] == "SLP65": typestr = "NFT1 Child" elif i['class'] == "SLP129": typestr = "NFT1 Parent" try: self.parent.wallet.get_slp_token_baton(token_id) item = QTreeWidgetItem([str(token_id),str(name),str(decimals),balancestr,"★", typestr]) except SlpNoMintingBatonFound: item = QTreeWidgetItem([str(token_id),str(name),str(decimals),balancestr,"", typestr]) squishyfont = QFont(MONOSPACE_FONT) squishyfont.setStretch(85) item.setFont(0, squishyfont) #item.setTextAlignment(2, Qt.AlignRight) item.setTextAlignment(3, Qt.AlignRight) item.setFont(3, QFont(MONOSPACE_FONT)) item.setData(0, Qt.UserRole, token_id) if decimals == "?": item.setForeground(0, QBrush(QColor("#BC1E1E"))) item.setForeground(1, QBrush(QColor("#BC1E1E"))) item.setForeground(2, QBrush(QColor("#BC1E1E"))) item.setForeground(3, QBrush(QColor("#BC1E1E"))) item.setForeground(4, QBrush(QColor("#BC1E1E"))) item.setForeground(5, QBrush(QColor("#BC1E1E"))) if i["class"] == "SLP129": for _token_id, _i in self.parent.wallet.token_types.items(): if _i["class"] == "SLP65" and _i.get("group_id", None) == token_id: name = _i["name"] decimals = _i["decimals"] calculated_balance= self.get_balance_from_token_id(_token_id) if decimals != "?": balancestr = format_satoshis_nofloat(calculated_balance, decimal_point=decimals, num_zeros=decimals) balancestr += ' '*(9-decimals) else: balancestr = "double-click to add" _nft_item = QTreeWidgetItem([str(_token_id),str(name),str(decimals),balancestr,"", "NFT1 Child"]) squishyfont = QFont(MONOSPACE_FONT) squishyfont.setStretch(85) _nft_item.setFont(0, squishyfont) #item.setTextAlignment(2, Qt.AlignRight) _nft_item.setTextAlignment(3, Qt.AlignRight) _nft_item.setFont(3, QFont(MONOSPACE_FONT)) _nft_item.setData(0, Qt.UserRole, _token_id) if decimals == "?": _nft_item.setForeground(0, QBrush(QColor("#BC1E1E"))) _nft_item.setForeground(1, QBrush(QColor("#BC1E1E"))) _nft_item.setForeground(2, QBrush(QColor("#BC1E1E"))) _nft_item.setForeground(3, QBrush(QColor("#BC1E1E"))) item.addChild(_nft_item) self.addTopLevelItem(item) elif i["class"] == "SLP65" and i.get("group_id", "?") == "?": self.addTopLevelItem(item) elif i["class"] == "SLP1": self.addTopLevelItem(item) if current_token_id == token_id: self.setCurrentItem(item) self.expandAll()
def populate_available_terms(self): """ Runs when annotations tab is viewed and when volume is changed. Populates the avaible annotation terms. """ self.ui.treeWidgetAvailableTerms.clear() vol = self.controller.current_annotation_volume() if not vol or None in (vol.annotations.stage, vol.annotations.center): # info_dialog(self, 'Chose centre and stage', 'You must choose a centre and stage from the options tab') return self.ui.lineEditCentre.setText(vol.annotations.center) self.ui.lineEditStage.setText(vol.annotations.stage.name) self.ui.lineEditModality.setText(vol.annotations.modality.value) def setup_option_box_signal(box_: QComboBox, child_: QTreeWidgetItem): """ Connect the Qcombobox to a slot """ box_.activated.connect( partial(self.update_annotation, child_, box_)) # Setup signal so when combobox is only opened, it sets the selection to that column box_.highlighted.connect(partial(self.on_box_highlight, child)) header_labels = QTreeWidgetItem( ['', 'term', 'name', 'option', 'done?']) self.ui.treeWidgetAvailableTerms.setHeaderItem(header_labels) parent = QTreeWidgetItem(self.ui.treeWidgetAvailableTerms) parent.setText(0, '') parent.setFlags(parent.flags()) parent.setExpanded(True) header = self.ui.treeWidgetAvailableTerms.header() # Set root column to invisible self.ui.treeWidgetAvailableTerms.setColumnWidth(0, 0) header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents) header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents) header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents) # For each annotation set an info row in the annotations table for i, ann in enumerate( sorted(vol.annotations, key=lambda an_: an_.order)): child = QTreeWidgetItem(parent) child.setText(1, ann.term) child.setText(3, ann.name) option = ann.selected_option # color = OPTION_COLOR_MAP[option] parent.addChild(child) # Set up the parameter option combobox and highlight the currently selected one options_box = QComboBox() options_box.setSizeAdjustPolicy(QComboBox.AdjustToContents) for opt in ann.options: options_box.addItem(opt) options_box.setCurrentIndex(options_box.findText( option)) # 060818 Louise's bug option is a bool not a str # Setup combobox selection signal setup_option_box_signal(options_box, child) self.ui.treeWidgetAvailableTerms.setItemWidget( child, 2, options_box) done_checkbox = QtWidgets.QCheckBox() done_checkbox.setChecked(ann.looked_at) done_checkbox.stateChanged.connect( partial(self.parameter_done_signal, child, done_checkbox)) self.ui.treeWidgetAvailableTerms.setItemWidget( child, 4, done_checkbox) # Set the roi coords to None self.roi_highlight_off_signal.emit()
def create_and_add_widget_item(self, key, value, widget): item = QTreeWidgetItem(widget) item.setText(0, key) item.setText(1, "%s" % value) widget.addTopLevelItem(item)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Set up dragging. #tree.setAcceptDrops(True) self.setDragEnabled(True) # Clear the treeWidget_Plugins list and redraw it, according to # the type filter. # TODO: is this needed? forget why it was put here. self.clear() # Loop over the plugin subpackages. for subpackage in [Analyses, Transforms, Utilities]: plugin_type = subpackage.__name__.split('.')[-1] # Make a new leaf item. package_item = QTreeWidgetItem() # Set the name in column 0. package_item.setText(0, plugin_type) # Attach the widget item to the parent tree. self.addTopLevelItem(package_item) # Loop over defined plugins in it. category_plugin_dict = defaultdict(list) for item_name in dir(subpackage): item = getattr(subpackage, item_name) # Can check for the _plugin_type attribute, attached # by the decorator. if not getattr(item, '_plugin_type', None): continue # Skip if the file name starts with an underscore, indicating # an experimental function. if item.__name__[0] == '_': continue # Record this function for the category. category_plugin_dict[item._category].append(item) # TODO: nested categories. # For now, just a flat list. for category, plugin_list in category_plugin_dict.items(): for plugin in plugin_list: # Create a nested tree node. subitem = QTreeWidgetItem() # Assign the name as text to column 0. subitem.setText(0, plugin.__name__) # Attach the widget item to the parent tree. package_item.addChild(subitem) # Annotate the item with the plugin, for easy # referencing. # TODO: record better customized doc text which # includes the function call signature. subitem.plugin = plugin self.expandAll() self.currentItemChanged.connect(self.Handle_currentItemChanged) return
def on_update(self): def item_path(item): # Recursively builds the path for an item eg 'parent_name/item_name' return item.text(0) if not item.parent() else item_path(item.parent()) + "/" + item.text(0) def remember_expanded_items(root): # Save the set of expanded items... so that address list updates don't annoyingly collapse # our tree list widget due to the update. This function recurses. Pass self.invisibleRootItem(). expanded_item_names = set() for i in range(0, root.childCount()): it = root.child(i) if it and it.childCount(): if it.isExpanded(): expanded_item_names.add(item_path(it)) expanded_item_names |= remember_expanded_items(it) # recurse return expanded_item_names def restore_expanded_items(root, expanded_item_names): # Recursively restore the expanded state saved previously. Pass self.invisibleRootItem(). for i in range(0, root.childCount()): it = root.child(i) if it and it.childCount(): restore_expanded_items(it, expanded_item_names) # recurse, do leaves first old = bool(it.isExpanded()) new = bool(item_path(it) in expanded_item_names) if old != new: it.setExpanded(new) self.wallet = self.parent.wallet had_item_count = self.topLevelItemCount() item = self.currentItem() current_address = item.data(0, Qt.UserRole) if item else None expanded_item_names = remember_expanded_items(self.invisibleRootItem()) self.clear() receiving_addresses = self.wallet.get_receiving_addresses() change_addresses = self.wallet.get_change_addresses() if self.parent.fx and self.parent.fx.get_fiat_address_config(): fx = self.parent.fx else: fx = None account_item = self sequences = [0,1] if change_addresses else [0] items_to_re_select = [] for is_change in sequences: if len(sequences) > 1: name = _("Receiving") if not is_change else _("Change") seq_item = QTreeWidgetItem( [ name, '', '', '', '', ''] ) account_item.addChild(seq_item) if not is_change and not had_item_count: # first time we create this widget, auto-expand the default address list seq_item.setExpanded(True) expanded_item_names.add(item_path(seq_item)) else: seq_item = account_item used_item = QTreeWidgetItem( [ _("Used"), '', '', '', '', ''] ) used_flag = False addr_list = change_addresses if is_change else receiving_addresses for n, address in enumerate(addr_list): num = len(self.wallet.get_address_history(address)) is_used = self.wallet.is_used(address) balance = sum(self.wallet.get_addr_balance(address)) address_text = address.to_ui_string() label = self.wallet.labels.get(address.to_storage_string(), '') balance_text = self.parent.format_amount(balance, whitespaces=True) columns = [address_text, str(n), label, balance_text, str(num)] if fx: rate = fx.exchange_rate() fiat_balance = fx.value_str(balance, rate) columns.insert(4, fiat_balance) address_item = SortableTreeWidgetItem(columns) address_item.setTextAlignment(3, Qt.AlignRight) address_item.setFont(3, QFont(MONOSPACE_FONT)) if fx: address_item.setTextAlignment(4, Qt.AlignRight) address_item.setFont(4, QFont(MONOSPACE_FONT)) address_item.setFont(0, QFont(MONOSPACE_FONT)) address_item.setData(0, Qt.UserRole, address) address_item.setData(0, Qt.UserRole+1, True) # label can be edited if self.wallet.is_frozen(address): address_item.setBackground(0, QColor('lightblue')) if self.wallet.is_beyond_limit(address, is_change): address_item.setBackground(0, QColor('red')) if is_used: if not used_flag: seq_item.insertChild(0, used_item) used_flag = True used_item.addChild(address_item) else: seq_item.addChild(address_item) if address == current_address: items_to_re_select.append(address_item) if items_to_re_select: # NB: Need to select the item at the end becasue internally Qt does some index magic # to pick out the selected item and the above code mutates the TreeList, invalidating indices # and other craziness, which might produce UI glitches. See #1042 self.setCurrentItem(items_to_re_select[-1]) # Now, at the very end, enforce previous UI state with respect to what was expanded or not. See #1042 restore_expanded_items(self.invisibleRootItem(), expanded_item_names)
def __init__(self, toolBarManager, parent=None): """ Constructor @param toolBarManager reference to a toolbar manager object (E5ToolBarManager) @param parent reference to the parent widget (QWidget) """ super(E5ToolBarDialog, self).__init__(parent) self.setupUi(self) self.__manager = toolBarManager self.__toolbarItems = {} # maps toolbar item IDs to toolbar items self.__currentToolBarItem = None self.__removedToolBarIDs = [] # remember custom toolbars to be deleted self.__widgetActionToToolBarItemID = {} # maps widget action IDs to toolbar item IDs self.__toolBarItemToWidgetActionID = {} # maps toolbar item IDs to widget action IDs self.upButton.setIcon(UI.PixmapCache.getIcon("1uparrow.png")) self.downButton.setIcon(UI.PixmapCache.getIcon("1downarrow.png")) self.leftButton.setIcon(UI.PixmapCache.getIcon("1leftarrow.png")) self.rightButton.setIcon(UI.PixmapCache.getIcon("1rightarrow.png")) self.__restoreDefaultsButton = \ self.buttonBox.button(QDialogButtonBox.RestoreDefaults) self.__resetButton = self.buttonBox.button(QDialogButtonBox.Reset) self.actionsTree.header().hide() self.__separatorText = self.tr("--Separator--") itm = QTreeWidgetItem(self.actionsTree, [self.__separatorText]) self.actionsTree.setCurrentItem(itm) for category in sorted(self.__manager.categories()): categoryItem = QTreeWidgetItem(self.actionsTree, [category]) for action in self.__manager.categoryActions(category): item = QTreeWidgetItem(categoryItem) item.setText(0, action.text()) item.setIcon(0, action.icon()) item.setTextAlignment(0, Qt.AlignLeft | Qt.AlignVCenter) item.setData(0, E5ToolBarDialog.ActionIdRole, int(id(action))) item.setData(0, E5ToolBarDialog.WidgetActionRole, False) if self.__manager.isWidgetAction(action): item.setData(0, E5ToolBarDialog.WidgetActionRole, True) item.setData(0, Qt.TextColorRole, QColor(Qt.blue)) self.__widgetActionToToolBarItemID[id(action)] = None categoryItem.setExpanded(True) for tbID, actions in list(self.__manager.toolBarsActions().items()): tb = self.__manager.toolBarById(tbID) default = self.__manager.isDefaultToolBar(tb) tbItem = E5ToolBarItem(tbID, [], default) self.__toolbarItems[id(tbItem)] = tbItem self.__toolBarItemToWidgetActionID[id(tbItem)] = [] actionIDs = [] for action in actions: if action is None: actionIDs.append(None) else: aID = id(action) actionIDs.append(aID) if aID in self.__widgetActionToToolBarItemID: self.__widgetActionToToolBarItemID[aID] = id(tbItem) self.__toolBarItemToWidgetActionID[id(tbItem)]\ .append(aID) tbItem.actionIDs = actionIDs self.toolbarComboBox.addItem(tb.windowTitle(), int(id(tbItem))) if default: self.toolbarComboBox.setItemData( self.toolbarComboBox.count() - 1, QColor(Qt.darkGreen), Qt.ForegroundRole) self.toolbarComboBox.model().sort(0) self.toolbarComboBox.currentIndexChanged[int].connect( self.__toolbarComboBox_currentIndexChanged) self.toolbarComboBox.setCurrentIndex(0)
def on_update(self): def remember_expanded_items(): # save the set of expanded items... so that address list updates don't # annoyingly collapse our tree list widget due to the update. expanded_item_names = set() for i in range(0, self.topLevelItemCount()): it = self.topLevelItem(i) if it and it.childCount(): if it.isExpanded(): expanded_item_names.add(it.text(0)) for j in range(0, it.childCount()): it2 = it.child(j) if it2 and it2.childCount() and it2.isExpanded(): expanded_item_names.add( it.text(0) + "/" + it2.text(0)) return expanded_item_names def restore_expanded_items(seq_item, used_item, expanded_item_names): # restore expanded items. if (isinstance(seq_item, QTreeWidgetItem) and not seq_item.isExpanded() and seq_item.text(0) in expanded_item_names): seq_item.setExpanded(True) used_item_name = (used_item.text(0) if not used_item.parent() else used_item.parent().text(0) + "/" + used_item.text(0)) if not used_item.isExpanded( ) and used_item_name in expanded_item_names: used_item.setExpanded(True) self.wallet = self.parent.wallet had_item_count = self.topLevelItemCount() item = self.currentItem() current_address = item.data(0, Qt.UserRole) if item else None expanded_item_names = remember_expanded_items() self.clear() receiving_addresses = self.wallet.get_receiving_addresses() change_addresses = self.wallet.get_change_addresses() account_item = self sequences = [0, 1] if change_addresses else [0] if app_state.fx and app_state.fx.get_fiat_address_config(): fx = app_state.fx else: fx = None for is_change in sequences: if len(sequences) > 1: name = _("Receiving") if not is_change else _("Change") seq_item = QTreeWidgetItem([name, '', '', '', '', '']) account_item.addChild(seq_item) # first time we create this widget, auto-expand the default address list if not is_change and not had_item_count: seq_item.setExpanded(True) else: seq_item = account_item used_item = QTreeWidgetItem([_("Used"), '', '', '', '', '']) used_flag = False addr_list = change_addresses if is_change else receiving_addresses for n, address in enumerate(addr_list): num = len(self.wallet.get_address_history(address)) is_used = self.wallet.is_used(address) balance = sum(self.wallet.get_addr_balance(address)) address_text = address.to_string() label = self.wallet.labels.get(address.to_string(), '') balance_text = self.parent.format_amount(balance, whitespaces=True) columns = [address_text, str(n), label, balance_text, str(num)] if fx: rate = fx.exchange_rate() fiat_balance = fx.value_str(balance, rate) columns.insert(4, fiat_balance) address_item = SortableTreeWidgetItem(columns) address_item.setTextAlignment(3, Qt.AlignRight) address_item.setFont(3, self.monospace_font) if fx: address_item.setTextAlignment(4, Qt.AlignRight) address_item.setFont(4, self.monospace_font) address_item.setFont(0, self.monospace_font) address_item.setData(0, Qt.UserRole, address) address_item.setData(0, Qt.UserRole + 1, True) # label can be edited if self.wallet.is_frozen(address): address_item.setBackground(0, QColor('lightblue')) if self.wallet.is_beyond_limit(address, is_change): address_item.setBackground(0, QColor('red')) if is_used: if not used_flag: seq_item.insertChild(0, used_item) used_flag = True used_item.addChild(address_item) else: seq_item.addChild(address_item) if address == current_address: self.setCurrentItem(address_item) restore_expanded_items(seq_item, used_item, expanded_item_names)
def _handle_chunk(self, msg): lines = msg.split('\r\n' if os.name == 'nt' else '\n') for i, line in enumerate(lines): if line == '': continue match = re.match(self.__re_active, line) if match is not None: filename = match.group(1) lineno = int(match.group(2)) # <frozen importlib._bootstrap> if filename[0] == '<': continue self.editor.markerDeleteAll(self.__active_line_marker_num) if filename != self.__filename: self._load_script(filename) self.editor.setReadOnly(True) self.editor.markerAdd(lineno - 1, self.__active_line_marker_num) self.editor.ensureLineVisible(lineno - 1) continue # breakpoints if line[:21] == 'Clear all breaks? ...': continue # Breakpoint 1 at d:\projects\python_debug\dbg_test.py:17 match = re.match(self.__re_bp_add, line) if match is not None: #num = match.group(1) filename = match.group(2) lineno = int(match.group(3)) continue # Deleted breakpoint 2 at d:\projects\python_debug\dbg_test.py:22 match = re.match(self.__re_bp_del, line) if match is not None: #num = match.group(1) filename = match.group(2) continue # check for vars update if line.startswith('__ENV__:'): try: env = json.loads(line[8:]) except json.JSONDecodeError as err: print(err) env = None if isinstance(env, dict): self.treeWidgetLocals.clear() for var_name, data in env['locals'][1].items(): self._add_var_item( self.treeWidgetLocals.invisibleRootItem(), var_name, data[0], data[1]) self.treeWidgetGlobals.clear() for var_name, data in env['globals'][1].items(): self._add_var_item( self.treeWidgetGlobals.invisibleRootItem(), var_name, data[0], data[1]) continue # check for stack update if line[:2] == ' ': self.treeWidgetStack.clear() for j in range(i + 1, len(lines)): line = lines[j] if line[:3] == '-> ': continue match = re.match(self.__re_stack, line) if match is not None: filename = match.group(1) if filename.startswith('<'): continue # only files # ignore pdb related files if os.path.basename(filename) in [ 'pdb.py', 'bdb.py', 'jsonpdb.py' ]: continue tree_item = QTreeWidgetItem() tree_item.setText(0, os.path.basename(filename)) tree_item.setText(1, match.group(2)) # lineno tree_item.setText(2, match.group(3)) # func tree_item.setToolTip(0, filename) self.treeWidgetStack.invisibleRootItem().addChild( tree_item) cnt = self.treeWidgetStack.topLevelItemCount() if cnt > 0: self.treeWidgetStack.setCurrentItem( self.treeWidgetStack.topLevelItem(cnt - 1)) self.treeWidgetStack.index = cnt - 1 break self._print_console(line + '\n')
def __init__(self, iface, layer, tree, dlg): QTreeWidgetItem.__init__(self) self.iface = iface self.layer = layer self.setText(0, layer.name()) self.setIcon(0, self.layerIcon) project = QgsProject.instance() if project.layerTreeRoot().findLayer(layer.id()).isVisible(): self.setCheckState(0, Qt.Checked) else: self.setCheckState(0, Qt.Unchecked) self.visibleItem = QTreeWidgetItem(self) self.visibleCheck = QCheckBox() vis = layer.customProperty("qgis2web/Visible", True) if (vis == 0 or unicode(vis).lower() == "false"): self.visibleCheck.setChecked(False) else: self.visibleCheck.setChecked(True) self.visibleItem.setText(0, "Visible") self.addChild(self.visibleItem) tree.setItemWidget(self.visibleItem, 1, self.visibleCheck) if layer.type() == layer.VectorLayer: if layer.providerType() == 'WFS': self.jsonItem = QTreeWidgetItem(self) self.jsonCheck = QCheckBox() if layer.customProperty("qgis2web/Encode to JSON") == 2: self.jsonCheck.setChecked(True) self.jsonItem.setText(0, "Encode to JSON") self.jsonCheck.stateChanged.connect(self.changeJSON) self.addChild(self.jsonItem) tree.setItemWidget(self.jsonItem, 1, self.jsonCheck) if layer.geometryType() == QgsWkbTypes.PointGeometry: self.clusterItem = QTreeWidgetItem(self) self.clusterCheck = QCheckBox() if layer.customProperty("qgis2web/Cluster") == 2: self.clusterCheck.setChecked(True) self.clusterItem.setText(0, "Cluster") self.clusterCheck.stateChanged.connect(self.changeCluster) self.addChild(self.clusterItem) tree.setItemWidget(self.clusterItem, 1, self.clusterCheck) self.popupItem = QTreeWidgetItem(self) self.popupItem.setText(0, "Popup fields") options = [] fields = self.layer.fields() for f in fields: fieldIndex = fields.indexFromName(unicode(f.name())) editorWidget = layer.editorWidgetSetup(fieldIndex).type() if editorWidget == 'Hidden': continue options.append(f.name()) for option in options: self.attr = QTreeWidgetItem(self) self.attrWidget = QComboBox() self.attrWidget.addItem("no label") self.attrWidget.addItem("inline label") self.attrWidget.addItem("header label") custProp = layer.customProperty("qgis2web/popup/" + option) if (custProp != "" and custProp is not None): self.attrWidget.setCurrentIndex( self.attrWidget.findText( layer.customProperty("qgis2web/popup/" + option))) self.attr.setText(1, option) self.popupItem.addChild(self.attr) tree.setItemWidget(self.attr, 2, self.attrWidget) self.addChild(self.popupItem) else: if layer.providerType() == 'wms': self.getFeatureInfoItem = QTreeWidgetItem(self) self.getFeatureInfoCheck = QCheckBox() if layer.customProperty("qgis2web/GetFeatureInfo") == 2: self.getFeatureInfoCheck.setChecked(True) self.getFeatureInfoItem.setText(0, "Enable GetFeatureInfo?") self.getFeatureInfoCheck.stateChanged.connect( self.changeGetFeatureInfo) self.addChild(self.getFeatureInfoItem) tree.setItemWidget(self.getFeatureInfoItem, 1, self.getFeatureInfoCheck)
def add_tree_item(self, parent, column, title, data): item = QTreeWidgetItem(parent, [title]) item.setData(column, QtCore.Qt.UserRole, data) return item
def send_settings(self): ''' Emit both general plot settings, and color labeling settings. These are the settings to be used when the plot is created. ''' print(self.get_updated_color_coding() self.general_settings = [ self.plot_title.text(), self.x_label.text(), self.y_label.text(), [self.twenty_percent_line.isChecked(), self.thirty_percent_line.isChecked(), self.zero_percent_line.isChecked()], [self.display_responses_as_text.isChecked(), self.display_responses_as_color.isChecked(), self.display_no_responses.isChecked()], self.include_table.isChecked(), self.show_cancer_type.isChecked() ] self.plot_settings_signal.emit(self.general_settings) def create_patient_tree(self): ''' Create QTreeWidget populated with a patient's data for the DataEntry dialog. Assumes that self.temp_patient is the patient of interest and that the variable belongs to the dialog. ''' self.tree = QTreeWidget() self.root = self.tree.invisibleRootItem() self.headers = [ 'Patient #', 'Best response %', 'Response', 'Cancer', 'Color key', ] self.headers_item = QTreeWidgetItem(self.headers) self.tree.setColumnCount(len(self.headers)) self.tree.setHeaderItem(self.headers_item) self.root.setExpanded(True) self.tree.header().setSectionResizeMode(QHeaderView.ResizeToContents) self.tree.header().setStretchLastSection(False) return self.tree def add_items(self): ''' Populate viewing tree ''' self.tree.clear() #clear prior to entering items, prevent aggregation i=0 for rect in self.rectangles_received: #populate editable tree with rect data self.rect_item = QTreeWidgetItem(self.root) self.rect_params = [ self.waterfall_data['Patient number'][i], rect.get_height(), self.waterfall_data['Overall response'][i], self.waterfall_data['Cancer'][i] ] for col in range(0,4): self.rect_item.setText(col,str(self.rect_params[col])) self.rect_item.setTextAlignment(col,4) self.tree.setItemWidget(self.rect_item, 4, CustomCombo(self,self.keys_and_colors,self.waterfall_data['Overall response'][i])) self.rect_item.setFlags(self.rect_item.flags() | QtCore.Qt.ItemIsEditable) i+=1 def get_updated_color_coding(self): tmp_updated_color_coding = [] self.root = self.tree.invisibleRootItem() child_count = self.root.childCount() # for i in range(child_count): # child_item = self.root.child(i) # self.tree.itemWidget(self.root.child(i),4).currentText() return [self.tree.itemWidget(self.root.child(i),4).currentText() for i in range(child_count)] def on_updated_tree_item(self): #update the rectangle which was edited pass class WaterfallPlotter(QWidget): generated_rectangles_signal = QtCore.pyqtSignal(list) #send list of rects for data display in tree def __init__(self,parent): super(WaterfallPlotter,self).__init__(parent) self.get_settings() self.settings_update = False self.figure = plt.figure() self.canvas = FigureCanvas(self.figure) self.toolbar = NavigationToolbar(self.canvas,self) self.btn_plot = QPushButton('Default Plot') self.btn_plot.clicked.connect(self.default_plot) self.layout = QVBoxLayout() self.layout.addWidget(self.toolbar) self.layout.addWidget(self.canvas) self.layout.addWidget(self.btn_plot) self.setLayout(self.layout) def on_waterfall_data_signal(self,signal): self.waterfall_data = signal['waterfall_data'] #pandas dataframe self.btn_plot.setEnabled(True) def get_settings(self): try: with shelve.open('WaterfallSettings') as shelfFile: self.keys_and_colors = shelfFile['keys_and_colors'] shelfFile.close() except: #set and use default settings self.keys_and_colors = { 'CR':'#03945D', 'PR':'#B1EE97', 'PD':'#FF6F69', 'SD':'#707070'} with shelve.open('WaterfallSettings') as shelfFile: shelfFile['keys_and_colors'] = self.keys_and_colors shelfFile.close() def on_general_settings_signal(self,signal): self.gen_settings = signal self.settings_update = True self.default_plot() def get_bar_colors(self,responses): return [self.keys_and_colors[x] for x in responses] def default_plot(self): ''' Plot waterfall data ''' self.figure.clear() self.rect_locations = np.arange(len(self.waterfall_data['Best response percent change'])) self.ax = self.figure.add_subplot(111) self.bar_colors = self.get_bar_colors(self.waterfall_data['Overall response']) if self.settings_update == False: self.ax.tick_params( axis='x', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom='on', # ticks along the bottom edge are off top='on', # ticks along the top edge are off labelbottom='on' ) # labels along the bottom edge are off self.ax.axhline(y=20, linestyle='--', c='k', alpha=0.5, lw=2.0, label='twenty_percent') self.ax.axhline(y=-30, linestyle='--', c='k', alpha=0.5, lw=2.0, label='thirty_percent') self.ax.axhline(y=0, c='k', alpha=1, lw=2.0, label='zero_percent') self.ax.grid(color = 'k', axis = 'y', alpha=0.25) self.rects = self.ax.bar(self.rect_locations, self.waterfall_data['Best response percent change'], color=self.bar_colors) else: #settings were updated, we received them and stored in variable self.gen_settings self.ax.set_title(self.gen_settings[0]) self.ax.set_xlabel(self.gen_settings[1]) self.ax.set_ylabel(self.gen_settings[2]) if self.gen_settings[3][0]: self.ax.axhline(y=20, linestyle='--', c='k', alpha=0.5, lw=2.0, label='twenty_percent') if self.gen_settings[3][1]: self.ax.axhline(y=-30, linestyle='--', c='k', alpha=0.5, lw=2.0, label='thirty_percent') if self.gen_settings[3][2]: self.ax.axhline(y=0, c='k', alpha=1, lw=2.0, label='zero_percent') if self.gen_settings[4][0] and ~self.gen_settings[6]: #show responses as labels, default color bars #legend depends on user specified keys self.rects = self.ax.bar(self.rect_locations, self.waterfall_data['Best response percent change']) self.add_labels(self.ax, self.rects, self.waterfall_data, 1) elif self.gen_settings[4][1]: #color bars with response type self.rects = self.ax.bar(self.rect_locations, self.waterfall_data['Best response percent change'], color=self.bar_colors) self.patches = [] for key in self.keys_and_colors.keys(): self.patches.append(mpatches.Patch(color = self.keys_and_colors[key],label=key)) self.ax.legend(handles=self.patches) else: self.rects = self.ax.bar(self.rect_locations, self.waterfall_data['Best response percent change']) if self.gen_settings[5]: self.plot_table() if self.gen_settings[6] and ~self.gen_settings[4][0]: self.add_labels(self.ax, self.rects, self.waterfall_data, 0) if ~self.gen_settings[4][1]: #response not shown as color coding, custom color code the bars pass self.ax.grid(color = 'k', axis = 'y', alpha=0.25) self.canvas.draw() self.generated_rectangles_signal.emit([self.rects]) def plot_table(self): rows = ['%s' % x for x in self.waterfall_data.keys()] rows = rows[4:] #skip first three, they are the 4 standard headers, rest are table rows columns = self.waterfall_data['Patient number'] #patient numbers cell_text = [] for row in rows: cell_text_temp = [] for col in range(len(columns)): cell_text_temp.append(self.waterfall_data[row][col]) cell_text.append(cell_text_temp) the_table = self.ax.table(cellText=cell_text, rowLabels=rows, colLabels=columns, loc='bottom', cellLoc='center', colLoc='center') plt.subplots_adjust(bottom=0.15,left=0.5) self.ax.set_xlim(-0.5,len(columns)-0.5) self.ax.tick_params( axis='x', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom='off', # ticks along the bottom edge are off top='off', # ticks along the top edge are off labelbottom='off' ) # labels along the bottom edge are off def update_plot(self): ''' TODO ''' pass def add_labels(self, ax, rects, waterfall_data, label_type): ''' Add labels above/below bars. label_type == 1 --> display responses; == 0 --> display cancer type ''' i = 0 if label_type: for rect in rects: height = rect.get_height() if height >= 0: valign = 'bottom' else: valign = 'top' ax.text(rect.get_x() + rect.get_width()/2., height, '%s' % waterfall_data['Overall response'][i], ha='center', va=valign) i+=1 else: for rect in rects: height = rect.get_height() if height >= 0: valign = 'top' hgt = -1 else: valign = 'bottom' hgt = 1 ax.text(rect.get_x() + rect.get_width()/2., hgt, '%s' % waterfall_data['Cancer'][i], ha='center', va=valign, rotation='vertical') i+=1
def load_streams(self): while self.__download_manager.thread_count > 1: self.sig_step.emit(self.id, 'Waiting for threads to clear...') thread_name = QThread.currentThread().objectName() thread_id = int(QThread.currentThreadId()) self.sig_step.emit(self.id, f'{thread_id}: {thread_name} thread starting...') self.__download_manager.videos = [] self.__download_manager.streams = [] proxies = self.__download_manager.get_proxies() top_level_item_count = self.__download_manager.stream_tree.topLevelItemCount( ) for i in range(top_level_item_count): self.__download_manager.stream_tree.takeTopLevelItem(i) self.__download_manager.stream_tree.clear() self.__download_manager.streams_to_download = {} try: print('get video id') print(extract.video_id(self.__download_manager.url.text())) self.sig_step.emit(self.id, f'Loading video') loaded_url = YouTube(self.__download_manager.url.text(), proxies=proxies) self.sig_step.emit(self.id, f'Loaded video: {loaded_url.title}') self.sig_msg.emit(f'Found {loaded_url.title}') if self.__abort: self.sig_progress_status.emit(f'Aborted!') self.sig_done.emit(self.id) return self.__download_manager.videos.append(loaded_url) except RegexMatchError: print('playlist') if 'playlist' in self.__download_manager.url.text(): regex_search(r'(?:list=|\/)([0-9A-Za-z_-]{11}).*', self.__download_manager.url.text(), group=1) loaded_url = Playlist(self.__download_manager.url.text()) self.sig_msg.emit(f'Loaded playlist. Discovering videos...') loaded_url.populate_video_urls() i = 0 self.sig_progress_status.emit(0) for video_url in loaded_url.video_urls: self.sig_step.emit(self.id, f'Loading video {i}') if self.__abort: self.sig_progress_status.emit(f'Aborted!') self.sig_done.emit(self.id) return self.sig_progress_total.emit( int((i / (len(loaded_url.video_urls) * 2)) * 100)) vid = YouTube(video_url, proxies=proxies) self.sig_step.emit(self.id, f'Loaded video: {vid.title}') if self.__abort: self.sig_progress_status.emit(f'Aborted!') self.sig_done.emit(self.id) return self.sig_msg.emit(f'Found {vid.title}') self.__download_manager.videos.append(vid) self.sig_progress_status.emit( int((i / len(loaded_url.video_urls)) * 100)) i += 1 self.sig_progress_total.emit(50) else: self.sig_error.emit('Could not determine Video ' 'or Playlist ID from provided URL!\n' 'Please check input!') self.sig_done.emit(self.id) return except Exception as e: self.sig_error.emit(str(e)) self.sig_done.emit(self.id) return self.sig_msg.emit(f'Loading Streams..') print('loading streams') i = 0 for video in self.__download_manager.videos: self.sig_progress_status.emit(0) self.sig_step.emit(self.id, f'Loading streams for video {i}') if self.__abort: self.sig_progress_status.emit(f'Aborted!') self.sig_done.emit(self.id) return audio_streams = QTreeWidgetItem(['Audio Only']) tree_item = StreamTreeWidgetItem([video.title], f'video_{i}', self.__download_manager, video, None) self.__download_manager.streams = video.streams x = 0 for stream in self.__download_manager.streams: self.sig_step.emit(self.id, f'Loading stream {x}') if self.__abort: self.sig_progress_status.emit(f'Aborted!') self.sig_done.emit(self.id) return self.sig_msg.emit( f'Video {i + 1}/{len(self.__download_manager.videos)}: ' f'Loading Stream ITAG ID: {stream.itag}') if stream.video_codec is None: stream_item = StreamTreeWidgetItem([ f'Codec: {stream.audio_codec}, ' f'ABR: {stream.abr}, ' f'File Type: {stream.mime_type.split("/")[1]}, ' f'Size: {stream.filesize // 1024} KB' ], f'video_{i}_stream{x}', self.__download_manager, video, stream) self.sig_step.emit(self.id, f'Loaded stream {x}') if self.__abort: self.sig_progress_status.emit(f'Aborted!') self.sig_done.emit(self.id) return audio_streams.addChild(stream_item) else: stream_item = StreamTreeWidgetItem([ f'Res: {stream.resolution}, FPS: {stream.fps}, ' f' Video Codec: {stream.video_codec}, Audio Codec: {stream.audio_codec}, ' f'File Type: {stream.mime_type.split("/")[1]}, ' f'Size: {stream.filesize // 1024} KB' ], f'video_{i}_stream{x}', self.__download_manager, video, stream) self.sig_step.emit(self.id, f'Loaded stream {x}') if self.__abort: self.sig_progress_status.emit(f'Aborted!') self.sig_done.emit(self.id) return tree_item.addChild(stream_item) stream_item.setCheckState(0, Qt.Unchecked) x += 1 self.sig_progress_status.emit( int((x / len(self.__download_manager.streams)) * 100)) tree_item.addChild(audio_streams) self.sig_step.emit(self.id, f'Adding video {i} to tree') if self.__abort: self.sig_progress_status.emit(f'Aborted!') self.sig_done.emit(self.id) return self.__download_manager.stream_tree.addTopLevelItem(tree_item) i += 1 self.sig_progress_status.emit(100) self.sig_progress_total.emit( int((i / (len(self.__download_manager.videos) * 2)) * 100) + 50) self.sig_msg.emit(f'Streams Loaded!') self.sig_done.emit(self.id)
def _createEditItem(self, treeItem): newItem = QTreeWidgetItem(treeItem) newItem.setIcon(0, self.style().standardIcon(QStyle.SP_FileIcon)) return newItem
def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(800, 600) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.treeWidget = QtWidgets.QTreeWidget(self.centralwidget) self.treeWidget.setGeometry(QtCore.QRect(10, 10, 771, 511)) # 设置树结构中的列数 self.treeWidget.setColumnCount(2) # 设置列标题名 self.treeWidget.setHeaderLabels(['姓名', '职务']) # 创建节点 root = QTreeWidgetItem(self.treeWidget) # 设置顶级节点文本 root.setText(0, '组织结构') # 定义字典,存储树结构中显示的数据 dict = { '任正非': '华为董事长', '马云': '阿里巴巴创始人', '马化腾': '腾讯CEO', '李彦宏': '百度CEO', '董明珠': '格力董事长', } for key, value in dict.items(): child = QTreeWidgetItem(root) # 创建子节点 # 为节点设置图标 if key == '任正非': child.setIcon(0, QtGui.QIcon('images/华为.jpg')) elif key == '马云': child.setIcon(0, QtGui.QIcon('images/阿里巴巴.jpg')) elif key == '马化腾': child.setIcon(0, QtGui.QIcon('images/腾讯.png')) elif key == '李彦宏': child.setIcon(0, QtGui.QIcon('images/百度.jpg')) elif key == '董明珠': child.setIcon(0, QtGui.QIcon('images/格力.jpeg')) child.setCheckState(0, QtCore.Qt.Checked) # 为节点设置复选框 child.setText(0, key) # 设置第一列的值 child.setText(1, value) # 设置第二列的值 # 设置隔行变色显示树节点 self.treeWidget.setAlternatingRowColors(True) # 将创建的树节点添加到树控件中 self.treeWidget.addTopLevelItem(root) # 展开所有树节点 self.treeWidget.expandAll() self.treeWidget.setObjectName("treeWidget") # self.treeWidget.headerItem().setText(0, "1") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 26)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) self.treeWidget.clicked.connect(self.gettreetext) QtCore.QMetaObject.connectSlotsByName(MainWindow)
def add_item_to_info_widget(key, value): item = QTreeWidgetItem(self.env_variables_list) item.setText(0, key) item.setText(1, value)
def _updateListBox(self, dummyVar=None): """Load/reload the content of the list box. The dummyVar variable captures the variable sent from the widgets connecting to it and discards it. """ self.listBox.clear() self.timeFilter = 0.0 incNovel = self.incNovel.isChecked() incNotes = self.incNotes.isChecked() hideZeros = self.hideZeros.isChecked() hideNegative = self.hideNegative.isChecked() groupByDay = self.groupByDay.isChecked() histMax = self.histMax.value() # Group the data if groupByDay: tempData = [] sessDate = None sessTime = 0 lstNovel = 0 lstNotes = 0 for n, (dStart, sDiff, wcNovel, wcNotes) in enumerate(self.logData): if n == 0: sessDate = dStart.date() if sessDate != dStart.date(): tempData.append((sessDate, sessTime, lstNovel, lstNotes)) sessDate = dStart.date() sessTime = sDiff lstNovel = wcNovel lstNotes = wcNotes else: sessTime += sDiff lstNovel = wcNovel lstNotes = wcNotes if sessDate is not None: tempData.append((sessDate, sessTime, lstNovel, lstNotes)) else: tempData = self.logData # Calculate Word Diff self.filterData = [] pcTotal = 0 listMax = 0 isFirst = True for dStart, sDiff, wcNovel, wcNotes in tempData: wcTotal = 0 if incNovel: wcTotal += wcNovel if incNotes: wcTotal += wcNotes dwTotal = wcTotal - pcTotal if hideZeros and dwTotal == 0: continue if hideNegative and dwTotal < 0: continue if isFirst: # Subtract the offset from the first list entry dwTotal -= self.wordOffset dwTotal = max(dwTotal, 1) # Don't go zero or negative isFirst = False if groupByDay: sStart = dStart.strftime(nwConst.dStampFmt) else: sStart = dStart.strftime(nwConst.tStampFmt) self.filterData.append((dStart, sStart, sDiff, dwTotal, wcNovel, wcNotes)) listMax = min(max(listMax, dwTotal), histMax) pcTotal = wcTotal # Populate the list for _, sStart, sDiff, nWords, _, _ in self.filterData: newItem = QTreeWidgetItem() newItem.setText(self.C_TIME, sStart) newItem.setText(self.C_LENGTH, formatTime(round(sDiff))) newItem.setText(self.C_COUNT, f"{nWords:n}") if nWords > 0 and listMax > 0: theBar = self.barImage.scaled( int(200*min(nWords, histMax)/listMax), self.barHeight, Qt.IgnoreAspectRatio, Qt.FastTransformation ) newItem.setData(self.C_BAR, Qt.DecorationRole, theBar) newItem.setTextAlignment(self.C_LENGTH, Qt.AlignRight) newItem.setTextAlignment(self.C_COUNT, Qt.AlignRight) newItem.setTextAlignment(self.C_BAR, Qt.AlignLeft | Qt.AlignVCenter) newItem.setFont(self.C_TIME, self.theTheme.guiFontFixed) newItem.setFont(self.C_LENGTH, self.theTheme.guiFontFixed) newItem.setFont(self.C_COUNT, self.theTheme.guiFontFixed) self.listBox.addTopLevelItem(newItem) self.timeFilter += sDiff self.labelFilter.setText(formatTime(round(self.timeFilter))) return True
def _update_io(self, i_table: MyTreeWidget, o_table: MyTreeWidget) -> None: def get_xtxoutput_account( output: XTxOutput) -> Optional[AbstractAccount]: if not output.x_pubkeys: return None for x_pubkey in output.x_pubkeys: result = self._main_window._wallet.resolve_xpubkey(x_pubkey) if result is not None: account, keyinstance_id = result if account.get_script_for_id( keyinstance_id) == output.script_pubkey: return account return None return None known_txos: Set[Tuple[bytes, int]] = set() if self._account is not None: known_txos = set(self._account._utxos) | set(self._account._stxos) def compare_key_path(account: AbstractAccount, txo_key: TxoKeyType, leading_path: Sequence[int]) -> bool: utxo = account._utxos.get(txo_key) if utxo is not None: key_path = account.get_derivation_path(utxo.keyinstance_id) if key_path is not None and key_path[:len(leading_path )] == leading_path: return True stxo_keyinstance_id = account._stxos.get(txo_key) if stxo_keyinstance_id is not None: key_path = account.get_derivation_path(stxo_keyinstance_id) if key_path is not None and key_path[:len(leading_path )] == leading_path: return True return False def name_for_account(account: AbstractAccount) -> str: name = account.display_name() return f"{account.get_id()}: {name}" for tx_index, txin in enumerate(self.tx.inputs): account_name = "" source_text = "" amount_text = "" is_receiving = is_change = False if txin.is_coinbase(): source_text = "<coinbase>" else: prev_hash_hex = hash_to_hex_str(txin.prev_hash) source_text = f"{prev_hash_hex}:{txin.prev_idx}" if self._account is not None: txo_key = TxoKeyType(txin.prev_hash, txin.prev_idx) is_receiving = compare_key_path(self._account, txo_key, RECEIVING_SUBPATH) is_change = compare_key_path(self._account, txo_key, CHANGE_SUBPATH) account_name = name_for_account(self._account) # TODO(rt12): When does a txin have a value? Loaded incomplete transactions only? if txin.value is not None: amount_text = app_state.format_amount(txin.value, whitespaces=True) item = QTreeWidgetItem( [str(tx_index), account_name, source_text, amount_text]) # item.setData(0, Qt.UserRole, row.paymentrequest_id) if is_receiving: item.setBackground(2, self._receiving_brush) if is_change: item.setBackground(2, self._change_brush) item.setTextAlignment(3, Qt.AlignRight | Qt.AlignVCenter) item.setFont(3, self._monospace_font) i_table.addTopLevelItem(item) for tx_index, tx_output in enumerate(self.tx.outputs): text, _kind = tx_output_to_display_text(tx_output) if isinstance(_kind, Unknown_Output): text = script_bytes_to_asm(tx_output.script_pubkey) account = get_xtxoutput_account(tx_output) accounts: List[AbstractAccount] = [] if account is not None: accounts.append(account) if self._account is not None and account is not self._account: accounts.append(self._account) account_name = "" is_receiving = is_change = False txo_key = TxoKeyType(self._tx_hash, tx_index) for account in accounts: if txo_key in account._stxos or txo_key in account._utxos: is_receiving = compare_key_path(account, txo_key, RECEIVING_SUBPATH) is_change = compare_key_path(account, txo_key, CHANGE_SUBPATH) account_name = name_for_account(account) break amount_text = app_state.format_amount(tx_output.value, whitespaces=True) item = QTreeWidgetItem( [str(tx_index), account_name, text, amount_text]) # item.setData(0, Qt.UserRole, row.paymentrequest_id) if is_receiving: item.setBackground(2, self._receiving_brush) if is_change: item.setBackground(2, self._change_brush) item.setTextAlignment(3, Qt.AlignRight | Qt.AlignVCenter) item.setFont(3, self._monospace_font) o_table.addTopLevelItem(item)
def __init__(self, errorsDict, parent=None): """ Constructor @param errorsDict error exceptions @type dict of list of int @param parent reference to the parent widget @type QWidget """ super(SslErrorExceptionsDialog, self).__init__(parent) self.setupUi(self) self.__errorDescriptions = { QWebEngineCertificateError.SslPinnedKeyNotInCertificateChain: self.tr("The certificate did not match the built-in public" " keys pinned for the host name."), QWebEngineCertificateError.CertificateCommonNameInvalid: self.tr("The certificate's common name did not match the" " host name."), QWebEngineCertificateError.CertificateDateInvalid: self.tr("The certificate is not valid at the current date" " and time."), QWebEngineCertificateError.CertificateAuthorityInvalid: self.tr("The certificate is not signed by a trusted" " authority."), QWebEngineCertificateError.CertificateContainsErrors: self.tr("The certificate contains errors."), QWebEngineCertificateError.CertificateNoRevocationMechanism: self.tr("The certificate has no mechanism for determining if" " it has been revoked."), QWebEngineCertificateError.CertificateUnableToCheckRevocation: self.tr("Revocation information for the certificate is" " not available."), QWebEngineCertificateError.CertificateRevoked: self.tr("The certificate has been revoked."), QWebEngineCertificateError.CertificateInvalid: self.tr("The certificate is invalid."), QWebEngineCertificateError.CertificateWeakSignatureAlgorithm: self.tr("The certificate is signed using a weak signature" " algorithm."), QWebEngineCertificateError.CertificateNonUniqueName: self.tr("The host name specified in the certificate is" " not unique."), QWebEngineCertificateError.CertificateWeakKey: self.tr("The certificate contains a weak key."), QWebEngineCertificateError.CertificateNameConstraintViolation: self.tr("The certificate claimed DNS names that are in" " violation of name constraints."), } try: self.__errorDescriptions[ QWebEngineCertificateError.CertificateValidityTooLong ] = self.tr( "The certificate has a validity period that is too long." ) except AttributeError: # the value was added in Qt 5.7 pass try: self.__errorDescriptions[ QWebEngineCertificateError.CertificateTransparencyRequired ] = self.tr( "Certificate Transparency was required for this" " connection, but the server did not provide" " information that complied with the policy." ) except AttributeError: # the value was added in Qt 5.8 pass for host, errors in errorsDict.items(): itm = QTreeWidgetItem(self.errorsTree, [host]) self.errorsTree.setFirstItemColumnSpanned(itm, True) for error in errors: try: errorDesc = self.__errorDescriptions[error] except KeyError: errorDesc = self.tr("No error description available.") QTreeWidgetItem(itm, [str(error), errorDesc]) self.errorsTree.expandAll() for i in range(self.errorsTree.columnCount()): self.errorsTree.resizeColumnToContents(i) self.errorsTree.sortItems(0, Qt.AscendingOrder) self.__setRemoveButtons()
def FillIndividual(self, Species): self.setWindowTitle(Species) self.lblCommonName.setText(Species) red = code_Stylesheet.speciesColor.red() green = code_Stylesheet.speciesColor.green() blue = code_Stylesheet.speciesColor.blue() self.lblCommonName.setStyleSheet( 'QLabel {font-weight: bold; color: rgb(' + str(red) + ',' + str(green) + ',' + str(blue) + ');}') self.lblScientificName.setText( self.mdiParent.db.GetScientificName(Species)) orderAndFamilyText = self.mdiParent.db.GetOrderName(Species) # check if taxonomy data has been loaded. If so, add a semi-colon and the family name if orderAndFamilyText != "": orderAndFamilyText = orderAndFamilyText + "; " + self.mdiParent.db.GetFamilyName( Species) self.lblOrderName.setText(orderAndFamilyText) # if available, add BBL banding code bblCode = self.mdiParent.db.GetBBLCode(Species) if bblCode != "": self.lblSpeciesCode.setText("IBP Banding Code: " + bblCode) else: # add species Quick Entry Code code used by eBird self.lblSpeciesCode.setText( "eBird Entry Code: " + self.mdiParent.db.GetQuickEntryCode(Species).upper()) # find list of dates for species, to find oldest and newest filter = code_Filter.Filter() filter.setSpeciesName(Species) dbDates = self.mdiParent.db.GetDates(filter) firstDate = dbDates[0] lastDate = dbDates[len(dbDates) - 1] # create filter to find the first location seen filter = code_Filter.Filter() filter.setStartDate(firstDate) filter.setEndDate(firstDate) filter.setSpeciesName(Species) firstDateLocations = self.mdiParent.db.GetLocations( filter, "Checklist") firstDateLocations = sorted(firstDateLocations, key=lambda x: (x[3])) firstLocation = firstDateLocations[0][0] # create filter to find the last location seen filter = code_Filter.Filter() filter.setStartDate(lastDate) filter.setEndDate(lastDate) filter.setSpeciesName(Species) lastDateLocations = self.mdiParent.db.GetLocations(filter, "Checklist") lastDateLocations = sorted(lastDateLocations, key=lambda x: (x[3])) lastLocation = lastDateLocations[len(lastDateLocations) - 1][0] self.lblFirstSeen.setText("First seen: " + dbDates[0] + " at " + firstLocation) self.lblMostRecentlySeen.setText("Most recently seen: " + dbDates[len(dbDates) - 1] + " at " + lastLocation) # display all locations for the species filter = code_Filter.Filter() filter.setSpeciesName(Species) locationList = self.mdiParent.db.GetLocations(filter, "LocationHierarchy") dateList = self.mdiParent.db.GetDates(filter) # fill treeview Locations widget self.trLocations.setColumnCount(1) theseCountries = set() sortedLocationList = sorted(locationList, key=lambda x: (x[0], x[1], x[2])) # add the top-level country tree items for l in sortedLocationList: theseCountries.add(l[0][0:2]) locationCount = 0 theseCountries = list(theseCountries) theseCountries.sort() for c in theseCountries: thisCountryItem = QTreeWidgetItem() thisCountry = self.mdiParent.db.GetCountryName(c) thisCountryItem.setText(0, thisCountry) self.trLocations.addTopLevelItem(thisCountryItem) thisCountryItem.setSizeHint(0, QSize(20, 20)) theseStates = set() for l in sortedLocationList: if l[0][0:2] == c: theseStates.add(l[0]) theseStates = list(theseStates) theseStates.sort() for s in theseStates: thisState = self.mdiParent.db.GetStateName(s) stateTreeItem = QTreeWidgetItem() stateTreeItem.setText(0, thisState) thisCountryItem.addChild(stateTreeItem) stateTreeItem.setSizeHint(0, QSize(20, 20)) theseCounties = set() for l in sortedLocationList: if l[0] == s: theseCounties.add(l[1]) theseCounties = list(theseCounties) theseCounties.sort() for co in theseCounties: countyTreeItem = QTreeWidgetItem() if co == "": countyTreeItem.setText(0, "No County Name") else: countyTreeItem.setText(0, co) stateTreeItem.addChild(countyTreeItem) countyTreeItem.setSizeHint(0, QSize(20, 20)) theseLocations = [] for l in sortedLocationList: if l[0] == s and l[1] == co: theseLocations.append(l[2]) theseLocations.sort() for lo in theseLocations: locationTreeItem = QTreeWidgetItem() locationTreeItem.setText(0, lo) countyTreeItem.addChild(locationTreeItem) locationTreeItem.setSizeHint(0, QSize(20, 20)) locationCount = locationCount + len(theseLocations) # Fill Year Tree widget theseYears = set() for d in dateList: theseYears.add(d[0:4]) theseYears = list(theseYears) theseYears.sort() dateCount = 0 for y in theseYears: thisYearItem = QTreeWidgetItem() thisYearItem.setText(0, str(y)) self.trDates.addTopLevelItem(thisYearItem) thisYearItem.setSizeHint(0, QSize(20, 20)) theseMonths = set() for d in dateList: if y == d[0:4]: theseMonths.add(d[5:7]) theseMonths = list(theseMonths) theseMonths.sort() for m in theseMonths: monthName = self.mdiParent.db.GetMonthName(m) monthTreeItem = QTreeWidgetItem() monthTreeItem.setText(0, str(monthName)) thisYearItem.addChild(monthTreeItem) monthTreeItem.setSizeHint(0, QSize(20, 20)) theseDates = set() for da in dateList: if da[0:4] == y: if da[5:7] == m: theseDates.add(da) theseDates = list(theseDates) theseDates.sort() for td in theseDates: dateTreeItem = QTreeWidgetItem() dateTreeItem.setText(0, str(td)) monthTreeItem.addChild(dateTreeItem) dateTreeItem.setSizeHint(0, QSize(20, 20)) dateCount = dateCount + len(theseDates) # Fill Month Tree widget theseMonths = [] theseMonths = set() for d in dateList: theseMonths.add(d[5:7]) theseMonths = list(theseMonths) theseMonths.sort() dateCount = 0 for m in theseMonths: monthName = self.mdiParent.db.GetMonthName(m) thisMonthItem = QTreeWidgetItem() thisMonthItem.setText(0, monthName) self.trMonthDates.addTopLevelItem(thisMonthItem) thisMonthItem.setSizeHint(0, QSize(20, 20)) theseYears = set() for d in dateList: if m == d[5:7]: theseYears.add(d[0:4]) theseYears = list(theseYears) theseYears.sort() for y in theseYears: yearTreeItem = QTreeWidgetItem() yearTreeItem.setText(0, y) thisMonthItem.addChild(yearTreeItem) yearTreeItem.setSizeHint(0, QSize(20, 20)) theseDates = set() for da in dateList: if da[0:4] == y: if da[5:7] == m: theseDates.add(da) theseDates = list(theseDates) theseDates.sort() for td in theseDates: dateTreeItem = QTreeWidgetItem() dateTreeItem.setText(0, str(td)) yearTreeItem.addChild(dateTreeItem) dateTreeItem.setSizeHint(0, QSize(20, 20)) dateCount = dateCount + len(theseDates) if locationCount == 1: self.lblLocations.setText("Location (1)") else: self.lblLocations.setText("Locations (" + str(locationCount) + ")") # add a photo button if the db holds photos of this species filter = code_Filter.Filter() filter.setSpeciesName(Species) photoSightings = self.mdiParent.db.GetSightingsWithPhotos(filter) if len(photoSightings) > 0: btnPhotos = QPushButton() btnPhotos.setText("Photos") btnPhotos.clicked.connect(self.createPhotos) self.verticalLayout_10.addWidget(btnPhotos) self.scaleMe() self.resizeMe()
def gotEvent(self, event): found = False for i in range(self.ui.typeBox.count()): s = self.ui.typeBox.itemData(i) if s == event.type: found = True if not found: print(event.type) self.ui.typeBox.addItem(event.type.capitalize(), event.type) if event.type == self.event_filter: self.ui.typeBox.setCurrentIndex(self.ui.typeBox.count() - 1) if self.event_filter and self.event_filter != event.type: return if not event.contact: return contact = event.contact contact.backend = event.backend status = '' if contact.status == contact.STATUS_ONLINE: status = u'Online' status_color = 0x00aa00 elif contact.status == contact.STATUS_OFFLINE: status = u'Offline' status_color = 0xff0000 elif contact.status == contact.STATUS_AWAY: status = u'Away' status_color = 0xffad16 else: status = u'Unknown' status_color = 0xaaaaaa if contact.status_msg: status += u' — %s' % contact.status_msg name = '<h2>%s</h2><font color="#%06X">%s</font><br /><i>%s</i>' % ( contact.name, status_color, status, event.backend) date = event.date.strftime('%Y-%m-%d %H:%M') type = event.type message = event.message item = QTreeWidgetItem(None, [name, date, type, message]) item.setData(0, Qt.UserRole, event) if contact.photos is NotLoaded: process = QtDo(self.weboob, lambda c: self.setPhoto(c, item)) process.do('fillobj', contact, ['photos'], backends=contact.backend) self.photo_processes[contact.id] = process elif len(contact.photos) > 0: if not self.setPhoto(contact, item): photo = list(contact.photos.values())[0] process = QtDo(self.weboob, lambda p: self.setPhoto(contact, item)) process.do('fillobj', photo, ['thumbnail_data'], backends=contact.backend) self.photo_processes[contact.id] = process self.ui.eventsList.addTopLevelItem(item) self.ui.eventsList.resizeColumnToContents(0) self.ui.eventsList.resizeColumnToContents(1)