def incProgress(self, val): """ Increase progressbar value by ``val`` If splash has no progressbar, it will be added dynamically. Remove progressbar with ``val`` as None. :param val: value to increase by :return: """ if val is not None: self._progressBar.show() self._progressBar.setTextVisible(True) self.progress = self.progress + val try: self._progressBar.setValue(self.progress) qApp.processEvents() except: pass else: self._progressBar.setTextVisible(False) self._progressBar.hide() self._progressBar.reset() if self.isHidden is True: self.isHidden = False self.show_()
def add_signal(self, signal, group_id=0, index=-1): self.setCursor(Qt.WaitCursor) pa = ProtocolAnalyzer(signal) sig_frame = self.signal_tab_controller.add_signal_frame(pa, index=index) pa = self.compare_frame_controller.add_protocol(pa, group_id) signal.blockSignals(True) has_entry = self.project_manager.read_project_file_for_signal(signal) if self.ui.actionAuto_detect_new_signals.isChecked() and not has_entry and not signal.changed: sig_frame.ui.stackedWidget.setCurrentWidget(sig_frame.ui.pageLoading) qApp.processEvents() signal.auto_detect(detect_modulation=True, detect_noise=False) sig_frame.ui.stackedWidget.setCurrentWidget(sig_frame.ui.pageSignal) signal.blockSignals(False) self.signal_protocol_dict[sig_frame] = pa sig_frame.refresh(draw_full_signal=True) # protocol is derived here if self.project_manager.read_participants_for_signal(signal, pa.messages): sig_frame.ui.gvSignal.redraw_view() sig_frame.ui.gvSignal.auto_fit_view() self.set_frame_numbers() self.compare_frame_controller.filter_search_results() self.refresh_main_menu() self.unsetCursor()
def setLabelText(self, l, id_="default"): """ Cambia el texto de la etiqueta del diálogo @param l Etiqueta """ pd_widget = self.__class__.progress_dialog_stack[-1] pd_widget.setLabelText(str(l)) qApp.processEvents()
def setProgress(self, step_number, id_="default"): """ Establece el grado de progreso del diálogo @param p Grado de progreso """ pd_widget = self.__class__.progress_dialog_stack[-1] pd_widget.setValue(step_number) qApp.processEvents()
def setTotalSteps(self, tS, id_="default"): """ Establece el número total de pasos del diálogo @param ts Número total de pasos """ pd_widget = self.__class__.progress_dialog_stack[-1] pd_widget.setRange(0, tS) qApp.processEvents()
def createProgressDialog(self, title, steps, id_="default"): """ Crea un diálogo de progreso @param l Label del diálogo @param tS Número total de pasos a realizar """ pd_widget = QtWidgets.QProgressDialog(str(title), str( self.translate("scripts", "Cancelar")), 0, steps) self.__class__.progress_dialog_stack.append(pd_widget) qApp.processEvents() return pd_widget
def write(self, s): if self.echo: sys.__stdout__.write(s) doc = self.document() cursor = QTextCursor(doc) cursor.clearSelection() cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor) cursor.insertText(s) cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor) cursor.clearSelection() self.ensureCursorVisible() qApp.processEvents()
def slot_batch_resize(self): dialog = QDialog() dialog.setWindowTitle(i18n("Resize all Pages")) buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttons.accepted.connect(dialog.accept) buttons.rejected.connect(dialog.reject) sizesBox = comics_export_dialog.comic_export_resize_widget("Scale", batch=True, fileType=False) exporterSizes = comics_exporter.sizesCalculator() dialog.setLayout(QVBoxLayout()) dialog.layout().addWidget(sizesBox) dialog.layout().addWidget(buttons) if dialog.exec_() == QDialog.Accepted: progress = QProgressDialog(i18n("Resizing pages..."), str(), 0, len(self.setupDictionary["pages"])) progress.setWindowTitle(i18n("Resizing Pages")) progress.setCancelButton(None) timer = QElapsedTimer() timer.start() config = {} config = sizesBox.get_config(config) for p in range(len(self.setupDictionary["pages"])): absoluteUrl = os.path.join(self.projecturl, self.setupDictionary["pages"][p]) progress.setValue(p) timePassed = timer.elapsed() if (p > 0): timeEstimated = (len(self.setupDictionary["pages"]) - p) * (timePassed / p) passedString = str(int(timePassed / 60000)) + ":" + format(int(timePassed / 1000), "02d") + ":" + format(timePassed % 1000, "03d") estimatedString = str(int(timeEstimated / 60000)) + ":" + format(int(timeEstimated / 1000), "02d") + ":" + format(int(timeEstimated % 1000), "03d") progress.setLabelText(str(i18n("{pages} of {pagesTotal} done. \nTime passed: {passedString}:\n Estimated:{estimated}")).format(pages=p, pagesTotal=len(self.setupDictionary["pages"]), passedString=passedString, estimated=estimatedString)) qApp.processEvents() if os.path.exists(absoluteUrl): doc = Application.openDocument(absoluteUrl) listScales = exporterSizes.get_scale_from_resize_config(config["Scale"], [doc.width(), doc.height(), doc.resolution(), doc.resolution()]) doc.scaleImage(listScales[0], listScales[1], listScales[2], listScales[3], "bicubic") doc.waitForDone() doc.save() doc.waitForDone() doc.close()
def doImport(self, filename): self.parent.settings['iconTheme'] = self.themeCombo.currentText() directory = os.path.join(os.path.dirname(filename), 'applications-merged') applicationsMerged = [] if os.path.isdir(directory): applicationsMerged = os.listdir(directory) applicationsMerged[:] = [i for i in applicationsMerged if i.endswith('.menu')] applicationsMerged[:] = [os.path.join(directory, i) for i in applicationsMerged] files = [filename] + applicationsMerged workingItems = [] for f in files: self.importStatus.setText('Importing ' + f) qApp.processEvents() reader = MenuReader(f) newItems = reader.menuItems self.removeEmptyFolders(newItems) self.mergeMenus(workingItems, newItems) if self.replaceCheck.isChecked(): self.parent.menuItems = workingItems else: self.mergeMenus(self.parent.menuItems, workingItems) # Looking for icons is slow - just do it once self.importStatus.setText('Loading icons') self.importProgress.setRange(0, len(self.parent.menuItems)) count = 0 for i in self.parent.menuItems: self.importProgress.setValue(count) i.findIcon() count += 1 self.importStatus.setText('Done') self.importProgress.setValue(len(self.parent.menuItems)) self.parent.refresh()
def show_(self, msg = ""): if msg != "": self._splash.showMessage(msg, QtCore.Qt.AlignCenter, QtCore.Qt.white) else: self.logger.debug("Show splash, parent: " + str(self._parent)) self._splash.showMessage(self.msg, QtCore.Qt.AlignCenter, QtCore.Qt.white) try: #if platform.system() == "Linux": parentUi = self._parent.centralwidget.geometry() # need to use centralwidget for linux preferably, don't know why except: #else: parentUi = self._parent.childrenRect() mysize = self._splash.geometry() hpos = parentUi.x() + ((parentUi.width() - mysize.width()) / 2) vpos = parentUi.y() + ((parentUi.height() - mysize.height()) / 2) self._splash.move(hpos, vpos) self._splash.show() qApp.processEvents()
def loadModules(self): global query_index if query_index is None: self.appendSearchOutput("Loading query-index...") qApp.processEvents() loadStart = time.perf_counter() query_index = __import__('query-index') # TODO: Adjust file name. loadTime = time.perf_counter() - loadStart self.appendSearchOutput(f"Loaded query-index: {loadTime:.4f}s") qApp.processEvents() if self.search is None: self.appendSearchOutput("Instantiating search...") qApp.processEvents() instantiateStart = time.perf_counter() self.search = query_index.Search() instantiateTime = time.perf_counter() - instantiateStart self.appendSearchOutput( f"Instantiated search: {instantiateTime:.4f}s") qApp.processEvents() self.appendSearchOutput("\n" + self.search.init_msg) self.searchHint.setText("Short help: " + self.search.prompt_prefix)
def put_info_into_log(self, info, progressValue): self.logTextEdit.append("[ {} ] : {}".format(get_current_screen_time(), info)) self.executeProgressBar.setValue(progressValue) qApp.processEvents() # 强制刷新界面
def load_Message(): time.sleep(1) qApp.processEvents()
def exec_(self): if not self.dbStat: return dsn = cx_Oracle.makedsn(self.dbHost, self.dbPort, service_name=self.dbService) self.ngwin.logEdit.append('<font color=blue>Connecting to Oracle DB</font>') self.ngwin.logEdit.append('-->DSN = %s' % dsn) qApp.processEvents() try: db = cx_Oracle.connect(self.dbUserName, self.dbUserPwd, dsn) except cx_Oracle.DatabaseError as e: # cx_Oracle 5.0.4 raises a cx_Oracle.DatabaseError exception # with the following attributes and values: # code = 2091 # message = 'ORA-02091: transaction rolled back # 'ORA-02291: integrity constraint (TEST_DJANGOTEST.SYS # _C00102056) violated - parent key not found' self.ngwin.logEdit.append('<font color=red>cx_Oracle.DatabaseError: %s!</font>' % e.args[0].message) return cursor = db.cursor() sqlDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'sql') for sqlFn in self.args['sqlQuery']: with open(os.path.join(sqlDir, sqlFn), 'r') as f: self.ngwin.logEdit.append('<font color=blue>Executing query: %s</font>' % f.name) qApp.processEvents() self.names = [] self.answers = [] reSql = re.compile(r"^[a-zA-Z0-9\_\s\>\<\=\(]+\&([a-zA-Z\_]+)[\,\s\'a-zA-Z0-9\)]+$") while True: line = f.readline() if not line: break #substitute names if necessary m = reSql.match(line) if m is not None: self.names.extend(m.groups()) f.seek(0) query = f.read() if len(self.names) > 0: #skip show NgSqlSubUi if self.names already exist in self.subsMap if self.checkSubMap(): for name in self.names: self.answers.append(self.subsMap[name]) else: dlg = NgSqlSubUi(self.ngwin, self.names) if dlg.exec_() == QDialog.Accepted: self.answers = dlg.answers valid = True for an in self.answers: if len(an) == 0: valid = False break if not valid: self.ngwin.logEdit.append('<font color=red>-->Query skipped!</font>') qApp.processEvents() continue #save for later use if possible if dlg.applyToAllChkBox.isChecked(): for name,answer in zip(self.names, self.answers): self.subsMap[name] = answer else: self.ngwin.logEdit.append('<font color=red>-->Query skipped!</font>') qApp.processEvents() continue for name, answer in zip(self.names, self.answers): self.ngwin.logEdit.append('-->Subsitution: [%s=%s]' % (name, answer)) qApp.processEvents() for index,name in enumerate(self.names): query = query.replace('&'+name, "'"+self.answers[index]+"'") try: cursor.execute(query) except cx_Oracle.DatabaseError as e: self.ngwin.logEdit.append('<font color=red>cx_Oracle.DatabaseError: %s!</font>' % e.args[0].message) return fields = ','.join([a[0] for a in cursor.description]) #self.ngwin.logEdit.append('Fields: %s' % fields) #record = cursor.fetchone() #self.ngwin.logEdit.append(','.join([str(i) for i in record])) records = cursor.fetchall() outDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'output') if not os.path.exists(outDir): os.mkdir(outDir) outFn = sqlFn.replace('.sql', '.csv') with open(os.path.join(outDir, outFn), 'w') as of: self.ngwin.logEdit.append('-->Exporting query results to: %s' % of.name) qApp.processEvents() of.write(fields) of.write('\n') for r in records: of.write(','.join([str(token) for token in r])) of.write('\n') self.queryStat = True self.ngwin.logEdit.append('<font color=blue>Done!</font>')
def sectionThroughLayers(self, layers): #Create new layers for the section based on the requested plan layers sectionLayers = [] # Total number of features for progress bar totalFeatures = 0 for layer in layers: if layer != None: totalFeatures = totalFeatures + layer.featureCount() pdInc = totalFeatures / 100 pdVal = 0 pdCount = 0 # Set up a progress bar pd = QProgressDialog() pd.setWindowTitle("Building Section") pd.setAutoReset(False) pd.setMinimumWidth(500) pd.setMinimum(0) pd.setMaximum(100) pd.setValue(0) for layer in layers: #Try and match the layer to be created with one already under the section.group, else create a new layer newName = self.createSectionLayerName(layer, self.name) sectionLayer = self.matchLayer(newName) usingNewLayer = False if sectionLayer == None: sectionLayer = self.createSectionLayer(layer, newName) usingNewLayer = True else: clearLayer(sectionLayer) #Loop through plan layer for lf in layer.getFeatures(): pdCount = pdCount + 1 if pdCount >= pdInc: pdVal = pdVal + 1 pdCount = 0 pd.setValue(pdVal) qApp.processEvents() # Variable to hold a feature feature = QgsFeature() # The normal asPolyline() function only returns QgsPointXY, yet we need the Z coordinate as well # We therefore get a vertex iterator for the abstractGeometry and build our own list tracePolyline = [] vi = lf.geometry().vertices() while vi.hasNext(): p = vi.next() tracePolyline.append(qgsToNp(p)) # Build array of points transalted to the +X axis (Section3D coordinates) pr = [] for p in tracePolyline: pt = p - self.origin pr.append(self.quat.rotate(pt)) # List of points to represent the portion of the line within the section # Note that the pointList array is in Section2D coordinates pointList = [] # Build new feature pointlist only for line segments that are inside or cross the section prlen = len(pr) # Equation of a plane in Section3D coordinates plane = np.array([0.0, 1.0, 0.0, 0.0]) # We only want to go half the section width each side of the section plane halfWidth = self.width / 2.0 # Loop through the array of Section3D points for index, p in enumerate(pr): # We are in Section3D coordinates, so we can reject anything with X less than 0 or greater # than the section length if p[0] < 0 or p[0] > self.sectionLength: continue # The distance from the section plane is equivalent to the Y coordinate if p[1] > halfWidth: # The point is in front of the section so check if the line segment passes through into the section # Check that we're not on the last point if index < prlen - 1: if pr[index + 1][1] < halfWidth: # Find intersection of line segment with plane pi = lineIntersectOffsetPlane( plane, halfWidth, p, pr[index + 1]) if pi is not None: # iface.messageBar().pushMessage("Debug", "Cross front plane: %f, %f, %f"%(pi[0], pi[1], pi[2]), level=Qgis.Info) pointList.append( QgsPoint(pi[0], pi[2], 0.0)) # If the line pases through the entire section and out the other side, then we need to # add a point for the far side as well, otherwise it will get missed if pr[index + 1][1] <= -halfWidth: # Find intersection of line segment with plane pi = lineIntersectOffsetPlane( plane, -halfWidth, p, pr[index + 1]) if pi is not None: pointList.append( QgsPoint(pi[0], pi[2], 0.0)) elif p[1] >= -halfWidth: # The point is within the section, so add it to the list pointList.append(QgsPoint(p[0], p[2], 0.0)) # We still need to check if the following line segment passes out of the section if index < prlen - 1: if pr[index + 1][1] > halfWidth: # Find intersection of line segment with plane pi = lineIntersectOffsetPlane( plane, halfWidth, p, pr[index + 1]) if pi is not None: pointList.append( QgsPoint(pi[0], pi[2], 0.0)) elif pr[index + 1][1] < -halfWidth: # Find intersection of line segment with plane pi = lineIntersectOffsetPlane( plane, -halfWidth, p, pr[index + 1]) if pi is not None: pointList.append( QgsPoint(pi[0], pi[2], 0.0)) else: # The point is behind the section so check if line segment passes through # Check that we're not on the last point if index < prlen - 1: # If if pr[index + 1][1] > -halfWidth: # Find intersection of line segment with plane pi = lineIntersectOffsetPlane( plane, -halfWidth, p, pr[index + 1]) if pi is not None: # iface.messageBar().pushMessage("Debug", "Cross back plane: %f, %f, %f"%(pi[0], pi[1], pi[2]), level=Qgis.Info) pointList.append( QgsPoint(pi[0], pi[2], 0.0)) # If the line pases through the entire section and out the other side, then we need to # add a point for the far side as well, otherwise it will get missed if pr[index + 1][1] >= halfWidth: # Find intersection of line segment with plane pi = lineIntersectOffsetPlane( plane, halfWidth, p, pr[index + 1]) if pi is not None: # iface.messageBar().pushMessage("Debug", "Cross back plane: %f, %f, %f"%(pi[0], pi[1], pi[2]), level=Qgis.Info) pointList.append( QgsPoint(pi[0], pi[2], 0.0)) # Set the geometry for the new downhole feature fvalid = False if QgsWkbTypes.flatType( sectionLayer.wkbType()) == QgsWkbTypes.Point: if len(pointList) > 0: fvalid = True feature.setGeometry(QgsGeometry(pointList[0])) else: if len(pointList) > 1: fvalid = True feature.setGeometry( QgsGeometry.fromPolyline(pointList)) if fvalid: # Set the attributes for the new feature feature.setAttributes(lf.attributes()) # Add the new feature to the new Trace_ layer sectionLayer.startEditing() sectionLayer.addFeature(feature) sectionLayer.commitChanges() styleNames = layer.styleManager().styles() currentStyleName = layer.styleManager().currentStyle() for styleName in styleNames: style = layer.styleManager().style(styleName) renamed = sectionLayer.styleManager().renameStyle( styleName, "temp") sectionLayer.styleManager().addStyle(styleName, style) if renamed: sectionLayer.styleManager().removeStyle("temp") sectionLayer.styleManager().setCurrentStyle(currentStyleName) sectionLayer.updateExtents(True) sectionLayers.append(sectionLayer) if usingNewLayer: QgsProject.instance().addMapLayer(sectionLayer, False) self.group.addLayer(sectionLayer) return sectionLayers
def export(self): export_success = False path = Path(self.projectURL) if path.exists(): # Make a meta-data folder so we keep the export folder nice and clean. exportPath = path / self.configDictionary["exportLocation"] if Path(exportPath / "metadata").exists() is False: Path(exportPath / "metadata").mkdir() # Get to which formats to export, and set the sizeslist. lengthProcess = len(self.configDictionary["pages"]) sizesList = {} if "CBZ" in self.configDictionary.keys(): if self.configDictionary["CBZactive"]: lengthProcess += 5 sizesList["CBZ"] = self.configDictionary["CBZ"] if "EPUB" in self.configDictionary.keys(): if self.configDictionary["EPUBactive"]: lengthProcess += 1 sizesList["EPUB"] = self.configDictionary["EPUB"] if "TIFF" in self.configDictionary.keys(): if self.configDictionary["TIFFactive"]: sizesList["TIFF"] = self.configDictionary["TIFF"] # Export the pngs according to the sizeslist. # Create a progress dialog. self.progress = QProgressDialog(i18n("Preparing export."), str(), 0, lengthProcess) self.progress.setWindowTitle(i18n("Exporting Comic...")) self.progress.setCancelButton(None) self.timer = QElapsedTimer() self.timer.start() self.progress.show() qApp.processEvents() export_success = self.save_out_pngs(sizesList) # Export acbf metadata. if export_success: if "CBZ" in sizesList.keys(): title = self.configDictionary["projectName"] if "title" in self.configDictionary.keys(): title = str(self.configDictionary["title"]).replace( " ", "_") self.acbfLocation = str(exportPath / "metadata" / str(title + ".acbf")) locationStandAlone = str(exportPath / str(title + ".acbf")) self.progress.setLabelText( i18n("Saving out ACBF and\nACBF standalone")) self.progress.setValue(self.progress.value() + 2) export_success = exporters.ACBF.write_xml( self.configDictionary, self.acbfPageData, self.pagesLocationList["CBZ"], self.acbfLocation, locationStandAlone, self.projectURL) print("CPMT: Exported to ACBF", export_success) # Export and package CBZ and Epub. if export_success: if "CBZ" in sizesList.keys(): export_success = self.export_to_cbz(exportPath) print("CPMT: Exported to CBZ", export_success) if "EPUB" in sizesList.keys(): self.progress.setLabelText(i18n("Saving out EPUB")) self.progress.setValue(self.progress.value() + 1) export_success = exporters.EPUB.export( self.configDictionary, self.projectURL, self.pagesLocationList["EPUB"], self.acbfPageData) print("CPMT: Exported to EPUB", export_success) else: QMessageBox.warning(None, i18n("Export not Possible"), i18n("Nothing to export, URL not set."), QMessageBox.Ok) print("CPMT: Nothing to export, url not set.") return export_success
def parseRawPmXml(self, fn, rat): self.ngwin.logEdit.append( '<font color=blue>Parsing raw PM:%s (rat=%s)</font>' % (fn, rat)) qApp.processEvents() if rat == '5g': try: root = ET.parse(fn).getroot() #root='OMes' ''' self.ngwin.logEdit.append('tag=%s,attrib=%s' % (root.tag, root.attrib)) for child in root: self.ngwin.logEdit.append('|--tag=%s,attrib=%s' % (child.tag, child.attrib)) ''' for pms in root.findall('PMSetup'): startTime = datetime.fromisoformat( pms.get('startTime')).strftime('%Y-%m-%d_%H:%M:%S') interval = pms.get('interval') for pmmoresult in pms.findall('PMMOResult'): ''' <MO dimension="network_element"> <DN>PLMN-PLMN/MRBTS-53775/NRBTS-1</DN> </MO> ''' mo = pmmoresult.find('MO') dn = mo.find('DN') pmtarget = pmmoresult.find( 'PMTarget') if pmmoresult.find( 'PMTarget') is not None else pmmoresult.find( 'NE-WBTS_1.0') measType = pmtarget.get('measurementType') for child in pmtarget: key = '%s;%s;%s' % (startTime, interval, dn.text[len('PLMN-PLMN/'):]) if measType not in self.data: self.data[measType] = dict() if key not in self.data[measType]: self.data[measType][key] = dict() self.data[measType][key][child.tag] = child.text if measType not in self.tagsMap: #note the difference between: a=set('hello') and a=set(['hello']) self.tagsMap[measType] = set([child.tag]) else: self.tagsMap[measType].add(child.tag) except Exception as e: #self.ngwin.logEdit.append(str(e)) self.ngwin.logEdit.append(traceback.format_exc()) return else: try: root = ET.parse(fn).getroot() #root='OMes' ''' self.ngwin.logEdit.append('tag=%s,attrib=%s' % (root.tag, root.attrib)) for child in root: self.ngwin.logEdit.append('|--tag=%s,attrib=%s' % (child.tag, child.attrib)) ''' for pms in root.findall('PMSetup'): startTime = datetime.fromisoformat( pms.get('startTime')).strftime('%Y-%m-%d_%H:%M:%S') interval = pms.get('interval') for pmmoresult in pms.findall('PMMOResult'): ''' <MO> <baseId>NE-MRBTS-833150</baseId> <localMoid>DN:NE-LNBTS-833150/FTM-1/IPNO-1/IEIF-1</localMoid> </MO> ''' mo = pmmoresult.find('MO') dn = mo.find('localMoid').text.split(':')[1] pmtarget = pmmoresult.find('NE-WBTS_1.0') measType = pmtarget.get('measurementType') for child in pmtarget: key = '%s;%s;%s' % (startTime, interval, dn.text[len('NE-'):]) if measType not in self.data: self.data[measType] = dict() if key not in self.data[measType]: self.data[measType][key] = dict() self.data[measType][key][child.tag] = child.text if measType not in self.tagsMap: #note the difference between: a=set('hello') and a=set(['hello']) self.tagsMap[measType] = set([child.tag]) else: self.tagsMap[measType].add(child.tag) except Exception as e: #self.ngwin.logEdit.append(str(e)) self.ngwin.logEdit.append(traceback.format_exc()) return
painter.restore() # 画圆 painter.save() painter.setPen(Qt.NoPen) painter.setBrush(p.circleColor) painter.drawRoundedRect( QRectF(p.x - p.radius, p.y - p.radius, 2 * p.radius, 2 * p.radius), p.radius, p.radius) painter.restore() # 开启动画 p.init_animation() # 测试 if __name__ == '__main__': import sys import cgitb sys.excepthook = cgitb.enable(1, None, 5, '') from PyQt5.QtWidgets import QApplication app = QApplication(sys.argv) splash = SplashScreen() splash.show() qApp.processEvents() # splash.close() # 隐藏启动界面 sys.exit(app.exec_())
def monitor(self, status, current, max): self.progress_bar.setFormat("{} %p %".format(status)) self.progress_bar.setMaximum(max) self.progress_bar.setValue(current) qApp.processEvents()
def setStatus(self, theMessage, timeOut=20.0): """Set the status bar message to display for 'timeOut' seconds. """ self.showMessage(theMessage, int(timeOut * 1000)) qApp.processEvents() return
def clearProgress(self) -> None: for progress in self._progressbars: progress.hide() progress.deleteLater() qApp.processEvents() self._progressbars.clear()
def loadData(self, model): print('load...') self.model = model self.table_view.setModel(self.model) qApp.processEvents()
def FillPhotos(self, filter): self.scaleMe() self.resizeMe() # clear the grdPhotos layout, in case there was anything in there to start # there could be photos in there if we're doing a refresh here for i in reversed(range(self.gridPhotos.count())): self.gridPhotos.itemAt(i).widget().setParent(None) # save the filter settings passed to this routine to the form for future use self.filter = filter photoSightings = self.mdiParent.db.GetSightingsWithPhotos(filter) if len(photoSightings) == 0: return False # for each sighting, iterate through attached photos and add them as a # label with photo to the gridPhotos species = set() row = 0 # count photos for message display photoCount = 0 for s in photoSightings: for p in s["photos"]: if self.mdiParent.db.TestIndividualPhoto(p, filter): photoCount += 1 species.add(s["commonName"]) photoCount = str(photoCount) speciesCount = len(species) self.lblSpecies.setText("Species: " + str(speciesCount) + ". Photos: " + str(photoCount)) self.mdiParent.SetChildDetailsLabels(self, filter) for s in photoSightings: for p in s["photos"]: if self.mdiParent.db.TestIndividualPhoto(p, filter): self.mdiParent.lblStatusBarMessage.setVisible(True) self.mdiParent.lblStatusBarMessage.setText( "Processing photo " + str(row + 1) + " of " + photoCount) # p is a filename. Use it to add the image to the label as a pixmap # save both the photo file name and the sighting data to the photoList # enlargements will use this data in the details display self.photoList.append([p, s]) buttonPhoto = QPushButton() buttonPhoto.setMinimumHeight(281) buttonPhoto.setMinimumWidth(500) pixMap = self.GetPixmapForThumbnail(p["fileName"]) buttonPhoto.setIcon(QIcon(pixMap)) buttonPhoto.setIconSize(QSize(500, 281)) buttonPhoto.setStyleSheet( "QPushButton:pressed{ background-color: #343333; }") buttonPhoto.setStyleSheet( "QPushButton:hover{ background-color: #343333; }") buttonPhoto.setStyleSheet( "QPushButton:flat{ background-color: #343333; }") buttonPhoto.setStyleSheet( "QPushButton{ background-color: #343333; border:none }" ) # set up behavior when button is clicked, passing the photo file name as p buttonPhoto.clicked.connect( partial(self.showEnlargement, row)) photoWeekday = datetime.datetime(int(s["date"][0:4]), int(s["date"][5:7]), int(s["date"][8:10])) photoWeekday = photoWeekday.strftime("%A") labelCaption = QLabel() labelCaption.setText(s["commonName"] + "\n" + s["scientificName"] + "\n\n" + s["location"] + "\n" + photoWeekday + ", " + s["date"] + " " + s["time"] + "\n\n" + "Rating: " + p["rating"]) labelCaption.setStyleSheet( "QLabel { background-color: #343333; color: silver; padding: 3px; }" ) self.gridPhotos.addWidget(buttonPhoto, row, 0) self.gridPhotos.addWidget(labelCaption, row, 1) # add species to species set so we can count them species.add(s["commonName"]) row = row + 1 maxValue = self.scrollArea.verticalScrollBar().maximum() self.scrollArea.verticalScrollBar().setValue(maxValue) qApp.processEvents() self.mdiParent.lblStatusBarMessage.setText("") self.mdiParent.lblStatusBarMessage.setVisible(False) QApplication.processEvents() icon = QIcon() icon.addPixmap(QPixmap(":/icon_camera.png"), QIcon.Normal, QIcon.Off) self.setWindowIcon(icon) self.scrollArea.verticalScrollBar().setValue(0) # don't show if we don't have any photos to show if len(self.photoList) == 0: # close our window self.close() # resie to a smaller window if we only have one photo to show if len(self.photoList) == 1: self.scaleMe() # tell MainWindow that we succeeded filling the list return (True)
def setLabel(self, text): self.label.setText(text) qApp.processEvents() self.parent().repaint()
def start_processing(self): ret = self.init_task_queue() if ret == -1: messageDialog = MessageDialog() messageDialog.warning(self, "消息提示对话框", "请先加载文件!", messageDialog.Yes, messageDialog.Yes) return self.isStop = False self.stopProcessingButton.setEnabled(True) import yaml with open("ip_config.yaml", 'r') as fd: yaml_file = yaml.load(fd) local_machine = yaml_file["LaserQtSystem"]["ip"] + ':' + str(yaml_file["LaserQtSystem"]["port"]) self.HOST, self.PORT = yaml_file["LaserProcessMachine"]["ip"], yaml_file["LaserProcessMachine"]["port"] process_machine = self.HOST + ':' + str(self.PORT) messageDialog = MessageDialog() reply = messageDialog.information(self, "消息提示对话框", "工艺规划计算机IP:[{}]\n主工控机IP:[{}]".format(local_machine, process_machine), messageDialog.Yes | messageDialog.No, messageDialog.Yes) if reply == messageDialog.Yes: # --- 加工开始 --- self.time = "00:00:00" self.count = 0 self.timer.start(1000) ## TODO self.canvas.axes.plot() self.canvas.axes.hold(True) self.canvas.axes.set_title("加工路径动态图", fontproperties=FONT, fontsize=14) self.canvas.axes.set_xlabel("X - 板长方向(m)", fontproperties=FONT, fontsize=9) self.canvas.axes.set_ylabel("Y - 板宽方向(m)", fontproperties=FONT, fontsize=9) self.canvas.axes.grid(True, which="both") self.udpSocketClient = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # IPv4 + UDP while (not self.isStop) and (not self.myTaskQueue.empty()): dataCell = self.myTaskQueue.get() self.dataShow02Edit.setText(str(dataCell[1])) self.dataShow03Edit.setText('( ' + str(dataCell[2]) + ', ' + str(dataCell[3]) + ' )') self.dataShow04Edit.setText('( ' + str(dataCell[4]) + ', ' + str(dataCell[5]) + ' )') self.dataShow05Edit.setText(str(dataCell[6])) self.dataShow06Edit.setText(str(dataCell[7])) self.udpSocketClient.sendto(bytes(json.dumps(dataCell), "utf-8"), (self.HOST, self.PORT)) # 发送的是json格式的列表数据 recv_all_flag = 1 while (not self.isStop) and recv_all_flag != 2): # 设置停止标志 self.dataShow07Edit.setText(self.time) # 时间显示好像有点不靠谱!!! dataRecv = json.loads(str(self.udpSocketClient.recv(1024), "utf-8")) _x = double(dataRecv[1]) _y = double(dataRecv[2]) recv_all_flag = int(dataRecv[4]) ## TODO self.plot_the_dynamic_data(_x, _y) qApp.processEvents() # 强制刷新界面 self.timer.stop() self.udpSocketClient.close() # --- 加工结束 --- if self.myTaskQueue.empty() == True: self.canvas.axes.hold(False) messageDialog = MessageDialog() messageDialog.information(self, "消息提示对话框", "所有路径加工完毕!", messageDialog.Yes, messageDialog.Yes) else: messageDialog = MessageDialog() messageDialog.information(self, "消息提示对话框", "您已停止加工!", messageDialog.Yes, messageDialog.Yes)
def showWaitWindow(self): self.paintEvent(QPaintEvent) self.update() qApp.processEvents()
self.template_build_result_edit.append("模板答案句如下:") for i_answer in range(len(ts_answers)): self.template_build_result_edit.append( str(i_answer) + "--" + ts_answers[i_answer]) self.template_build_result_edit.append("模板问题句如下:") for sentence in ts_questions: self.template_build_result_edit.append(sentence) if __name__ == "__main__": # 当前能够回答的问题 question_can_answer = ["录取分数", "招生计划"] app = QApplication(sys.argv) # 预加载数据界面 splash = QSplashScreen(QPixmap("images/cat.jpg")) splash.show() # 显示启动界面 font = QFont() font.setPointSize(16) font.setBold(True) font.setWeight(75) splash.setFont(font) splash.showMessage("加载... 0%", Qt.AlignCenter, Qt.black) qApp.processEvents() # 处理主进程事件 # 界面开始执行 QAPage = QASystemMainWindow() QAPage.pre_load_data(splash) QAPage.show() splash.finish(QAPage) sys.exit(app.exec_())
def __init__(self, ngwin, rat): self.ngwin = ngwin self.rat = rat self.inDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data/raw_pm') self.outDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'output') if not os.path.exists(self.outDir): os.mkdir(self.outDir) #extract tar.gz for root, dirs, files in os.walk(self.inDir): self.tgzs = sorted([ os.path.join(root, fn) for fn in files if fn.lower().endswith('tar.gz') ], key=str.lower) for tgz in self.tgzs: tar = tarfile.open(tgz, 'r:gz') fns = tar.getnames() for fn in fns: tar.extract(fn, self.inDir) #parse raw pm xml self.data = dict() self.tagsMap = dict() for root, dirs, files in os.walk(self.inDir): self.xmls = sorted([ os.path.join(root, fn) for fn in files if fn.lower().endswith('xml') ], key=str.lower) for fn in self.xmls: self.parseRawPmXml(fn, self.rat) #post-processing of raw pm self.aggMap = dict() self.gnbKpiReport = dict() for key1, val1 in self.data.items(): for key2, val2 in val1.items(): stime, interval, dn = key2.split(';') agg = dn.split('/')[-1].split('-')[0] #init gnbKpiReport: {agg, {'stime_interval_dn', {kpi_name, kpi_value}}} if agg not in self.gnbKpiReport: self.gnbKpiReport[agg] = dict() if key2 not in self.gnbKpiReport[agg]: self.gnbKpiReport[agg][key2] = dict() for key3, val3 in val2.items(): if key3 not in self.aggMap: self.aggMap[key3] = agg #sort self.gnbKpiReport[agg].keys() for agg in self.gnbKpiReport.keys(): keys = list(self.gnbKpiReport[agg].keys()) keys.sort() val = {key: self.gnbKpiReport[agg][key] for key in keys} self.gnbKpiReport[agg].clear() self.gnbKpiReport[agg] = val #print self.data ''' for key1,val1 in self.data.items(): self.ngwin.logEdit.append('|-measType=%s' % key1) for key2,val2 in val1.items(): self.ngwin.logEdit.append('|--tag=%s' % key2) for key3,val3 in val2.items(): self.ngwin.logEdit.append('|----key=%s,val=%s' % (key3, val3)) qApp.processEvents() for key,val in self.tagsMap.items(): self.ngwin.logEdit.append('key=%s,val=%s'%(key,val)) for key,val in self.aggMap.items(): self.ngwin.logEdit.append('tag=%s,agg=%s'%(key,val)) ''' #parse kpi definitions self.gnbKpis = [] self.confDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config') for root, dirs, files in os.walk(self.confDir): self.kpiDefs = sorted([ os.path.join(root, fn) for fn in files if (os.path.basename(fn).lower().startswith('kpi_def') or os.path.basename(fn).lower().startswith('menb_kpi_def')) and not fn.endswith('~') ], key=str.lower) for fn in self.kpiDefs: self.parseKpiDef(fn) #post-processing of gnbKpis for kpi in self.gnbKpis: try: if len(kpi) != 6: continue x = kpi[2] y = kpi[3] invalidx = False invalidy = False aggx = None aggy = None if not invalidx and x is not None: tokens = x.split(';') tokens = list(map(lambda z: z.strip(), tokens)) if len(tokens) == 1 and not (tokens[0].startswith('(') and tokens[0].endswith(')')): kpi[2] = int(tokens[0]) else: kpi[2] = [] for item in tokens: if item.startswith('(') and item.endswith(')'): a, b = item[1:-1].split(',') kpi[2].append([a, int(b)]) #all counters involved must have the same aggregation level if aggx is None: aggx = self.aggMap[a] else: if self.aggMap[a] != aggx: invalidx = True break else: invalidx = True break if not invalidy and y is not None: tokens = y.split(';') tokens = list(map(lambda z: z.strip(), tokens)) if len(tokens) == 1 and not (tokens[0].startswith('(') and tokens[0].endswith(')')): kpi[3] = int(tokens[0]) else: kpi[3] = [] for item in tokens: if item.startswith('(') and item.endswith(')'): a, b = item[1:-1].split(',') kpi[3].append([a, int(b)]) #all counters involved must have the same aggregation level if aggy is None: aggy = self.aggMap[a] else: if self.aggMap[a] != aggy: invalidy = True break else: invalidy = True break if invalidx or invalidy or aggx is None or ( aggx is not None and aggy is not None and aggx != aggy): self.ngwin.logEdit.append( '<font color=purple>Invalid KPI definition(name=%s,aggx=%s,aggy=%s), which will be ignored!</font>' % (kpi[0], aggx if aggx is not None else 'None', aggy if aggy is not None else 'None')) qApp.processEvents() kpi[0] = None else: kpi[5] = aggx except Exception as e: #self.ngwin.logEdit.append(str(e)) #self.ngwin.logEdit.append(repr(e)) #self.ngwin.logEdit.append(e.message) self.ngwin.logEdit.append( '<font color=purple>Invalid KPI definition(name=%s,aggx=%s,aggy=%s), which will be ignored!</font>' % (kpi[0], aggx if aggx is not None else 'None', aggy if aggy is not None else 'None')) self.ngwin.logEdit.append(traceback.format_exc()) qApp.processEvents() kpi[0] = None continue ''' for kpi in self.gnbKpis: if kpi[0] is None: continue self.ngwin.logEdit.append('name=%s,f=%s,x=%s,y=%s,p=%s,agg=%s' % (kpi[0], kpi[1] if kpi[1] is not None else 'None', kpi[2], kpi[3] if kpi[3] is not None else 'None', kpi[4] if kpi[4] is not None else 'None', kpi[5] if kpi[5] is not None else 'None')) qApp.processEvents() ''' #calculate kpi self.ngwin.logEdit.append( '<font color=blue>Calculating KPIs, please wait...</font>') qApp.processEvents() #reconstruct self.data to {'stime_interval_dn', {pm_tag, pm_value}} data2 = dict() for key1, val1 in self.data.items(): for key2, val2 in val1.items(): if key2 not in data2: data2[key2] = dict() for key3, val3 in val2.items(): if key3 not in data2[key2]: data2[key2][key3] = val3 ''' for key1,val1 in data2.items(): self.ngwin.logEdit.append('|key=%s'%key1) for key2,val2 in val1.items(): self.ngwin.logEdit.append('|--pm_tag=%s,pm_val=%s'%(key2,val2)) ''' for key1, val1 in self.gnbKpiReport.items(): agg = key1 for key2, val2 in val1.items(): #calculate valid kpi for key2('stime_interval_dn') for kpi in self.gnbKpis: try: if kpi[0] is None or kpi[5] != agg: continue f = kpi[1] x = kpi[2] y = kpi[3] p = kpi[4] #calculate x and y if x is not None: if not isinstance(x, int): xval = 0 for item in x: xval = xval + int( data2[key2][item[0]]) * item[1] else: xval = x if y is not None: if not isinstance(y, int): yval = 0 for item in y: yval = yval + int( data2[key2][item[0]]) * item[1] else: yval = y #calculate kpi if f is not None and x is not None and y is not None and p is not None: if yval != 0: kpival = '{:0.{precision}f}'.format( f * xval / yval, precision=p) else: kpival = 0 if f is None and x is not None and y is None and p is None: kpival = xval self.gnbKpiReport[agg][key2][kpi[0]] = kpival except Exception as e: self.gnbKpiReport[agg][key2][kpi[0]] = 'NA' self.ngwin.logEdit.append( '<font color=purple>Error when calculating KPI(=%s) for DN=%s:</font>' % (kpi[0], key2)) self.ngwin.logEdit.append(traceback.format_exc()) qApp.processEvents() continue if self.ngwin.enableDebug: for key1, val1 in self.gnbKpiReport.items(): self.ngwin.logEdit.append('|agg=%s' % key1) for key2, val2 in val1.items(): self.ngwin.logEdit.append('|--key=%s' % key2) for key3, val3 in val2.items(): self.ngwin.logEdit.append( '|----kpi_name=%s,kpi_val=%s' % (key3, val3)) qApp.processEvents() #export to excel self.ngwin.logEdit.append( '<font color=blue>Exporting to excel(engine=xlsxwriter), please wait...</font>' ) qApp.processEvents() workbook = xlsxwriter.Workbook( os.path.join( self.outDir, '%s_kpi_report_%s.xlsx' % (rat, time.strftime('%Y%m%d%H%M%S', time.localtime())))) fmtHHeader = workbook.add_format({ 'font_name': 'Arial', 'font_size': 9, 'align': 'center', 'valign': 'vcenter', 'text_wrap': True, 'bg_color': 'yellow' }) fmtCell = workbook.add_format({ 'font_name': 'Arial', 'font_size': 9, 'align': 'left', 'valign': 'vcenter' }) for key1, val1 in self.gnbKpiReport.items(): horizontalHeader = ['STIME', 'INTERVAL', 'DN'] for key2, val2 in val1.items(): if len(val2) == 0: continue horizontalHeader.extend(val2.keys()) break #skip unused agg if key1 in ('NRCUUP', 'SFP', 'MNLENT', 'ETHLK', 'ETHIF', 'IPIF', 'IPADDRESSV4', 'IPNO', 'LNMME', 'VLANIF', 'IPVOL', 'SMOD', 'LTAC', 'LNADJ', 'FSTSCH'): continue sheet1 = workbook.add_worksheet('KPI_%s' % key1) sheet1.set_zoom(90) sheet1.freeze_panes(1, 3) #write header sheet1.write_row(0, 0, horizontalHeader, fmtHHeader) count = 0 for key2, val2 in val1.items(): if len(val2) == 0: continue #key = 'time;interval;dn' stime, interval, dn = key2.split(';') row = [stime, interval, dn] row.extend(val2.values()) sheet1.write_row(count + 1, 0, row, fmtCell) count = count + 1 for measType in self.data.keys(): horizontalHeader = ['STIME', 'INTERVAL', 'DN'] tags = list(self.tagsMap[measType]) tags.sort() horizontalHeader.extend(tags) sheet1 = workbook.add_worksheet( measType[:31] if len(measType) > 31 else measType) sheet1.set_zoom(90) sheet1.freeze_panes(1, 3) #write header sheet1.write_row(0, 0, horizontalHeader, fmtHHeader) count = 0 for key, val in self.data[measType].items(): #key = 'time;interval;dn' #val = {tag:text} stime, interval, dn = key.split(';') row = [stime, interval, dn] for tag in tags: if tag in val: row.append(val[tag]) else: row.append('NA') sheet1.write_row(count + 1, 0, row, fmtCell) count = count + 1 workbook.close()
def createDownholeData(self): self.logFile.write("\nCreating Downhole Data Layer.\n") self.logFile.flush() # Check that desurvey layer is available if not self.desurveyLayer.isValid() or not self.dataLayer.isValid(): return # Set up a progress display pd = QProgressDialog() pd.setAutoReset(False) pd.setWindowTitle("Build Downhole Data Layer") pd.setMinimumWidth(500) pd.setMinimum(0) pd.setMaximum(self.dataLayer.featureCount()) pd.setValue(0) # Create memory layer layer = self.createDownholeLayer() # Get the fields from the data layer dp = self.dataLayer.dataProvider() idxId = dp.fieldNameIndex(self.dataId) idxFrom = dp.fieldNameIndex(self.dataFrom) idxTo = dp.fieldNameIndex(self.dataTo) # Create a list of attribute indices from the desired attribute field names idxAttList = [] for name in self.dataFields: idx = dp.fieldNameIndex(name) idxAttList.append(idx) # Get the fields from the desurveyed trace layer tdp = self.desurveyLayer.dataProvider() idxTraceId = tdp.fieldNameIndex("CollarID") idxTraceSegLength = tdp.fieldNameIndex("SegLength") # Store the relevant desurveyed drill trace so that it's persistent between loops # This way we should be able to re-use it instead of re-fetching it. traceFeature = QgsFeature() currentTraceCollar = "" currentTraceSegLength = 1.0 currentTracePolyline = None #Loop through downhole layer features # Calculate an optimum update interval for the progress bar (updating gui items is expensive) updateInt = max(100, long(self.dataLayer.featureCount()/100)) floatConvError = False nullDataError = False for index, df in enumerate(self.dataLayer.getFeatures()): # Update the Progress bar if index%updateInt == 0: pd.setValue(index) qApp.processEvents() # Variable to hold a feature feature = QgsFeature() # get the feature's attributes attrs = df.attributes() # Check all the data is valid dataId = str(attrs[idxId]) try: dataFrom = float(attrs[idxFrom]) dataTo = float(attrs[idxTo]) except: floatConvError = True if (dataId==NULL) or (dataFrom==NULL) or (dataTo==NULL): nullDataError = True continue dataId = dataId.strip() # Get the desurvey drill trace relevant to this collar, checking first that we don't already have it if not currentTraceCollar == dataId: # Get the correct trace feature via a query query = '''"CollarID" = '%s' ''' % (dataId) selection = self.desurveyLayer.getFeatures(QgsFeatureRequest().setFilterExpression(query)) # We have a selection of features if selection.isValid(): # There should be just 1, so get the first feature selection.nextFeature(traceFeature) # Is the feature valid? if traceFeature.isValid(): # Update information for the current feature currentTraceCollar = dataId currentTraceSegLength = traceFeature.attributes()[idxTraceSegLength] # The normal asPolyline() function only returns QgsPointXY, yet we need the Z coordinate as well # We therefore get a vertex iterator for the abstractGeometry and build our own list currentTracePolyline = [] vi = traceFeature.geometry().vertices() while vi.hasNext(): currentTracePolyline.append(vi.next()) else: continue else: continue if (floatConvError): iface.messageBar().pushMessage("Warning", "Some 'From' or 'To' values are not numbers", level=Qgis.Warning) if (nullDataError): iface.messageBar().pushMessage("Warning", "Some 'HoleId', 'From' or 'To' values are NULL. These have been skipped", level=Qgis.Warning) # Create line representing the downhole value using From and To pointList = [] # Calculate indices spanning the from and to depths, then linearly interpolate a position try: pFrom, iFrom = interpPolyline(dataFrom, currentTraceSegLength, currentTracePolyline) except: self.logFile.write("Error interpolating from polyline for hole: %s From: %f in row: %d.\n" % (dataId, dataFrom, index)) continue try: pTo, iTo = interpPolyline(dataTo, currentTraceSegLength, currentTracePolyline) except: self.logFile.write("Error interpolating from polyline for hole: %s To: %f in row: %d.\n" % (dataId, dataTo, index)) continue # Add the first (From) point to the list pointList.append(pFrom) # Add all the intermediate points (so a long interval accurately reflects the bend of the hole) if math.floor(iTo) - math.ceil(iFrom) > 1: for i in range(math.ceil(iFrom), math.floor(iTo)): pointList.append(currentTracePolyline[i]) # Add the last (To) point pointList.append(pTo) # Set the geometry for the new downhole feature feature.setGeometry(QgsGeometry.fromPolyline(pointList)) # Create a list of the attributes to be included in new file # These are just copied from the original down hole layer # according to whether the user selected the check boxes attList = [] for idx in idxAttList: attList.append(attrs[idx]) # Also append the 3D desurveyed From, To and Mid points attList.append(pointList[0].x()) attList.append(pointList[0].y()) attList.append(pointList[0].z()) attList.append(pointList[1].x()) attList.append(pointList[1].y()) attList.append(pointList[1].z()) attList.append((pointList[0].x()+pointList[1].x())*0.5) attList.append((pointList[0].y()+pointList[1].y())*0.5) attList.append((pointList[0].z()+pointList[1].z())*0.5) # Set the attributes for the new feature feature.setAttributes(attList) # Add the new feature to the new Trace_ layer layer.startEditing() layer.addFeature(feature) layer.commitChanges() # Flush the log file in case anything was written self.logFile.flush() # Build the new filename for saving to disk. We are using GeoPackages path=self.desurveyLayer.dataProvider().dataSourceUri() fileName=os.path.join(os.path.split(path)[0], self.desurveyLayer.name()) fileName = fileName.replace("_Desurvey","_Downhole") fileName = uriToFile(fileName + "_%s" % (self.dataSuffix)) # Generate a layer label label = os.path.splitext(os.path.basename(fileName))[0] # Remove trace layer from project if it already exists oldLayer = getLayerByName(label) QgsProject.instance().removeMapLayer(oldLayer) #Save memory layer to Geopackage file error = QgsVectorFileWriter.writeAsVectorFormat(layer, fileName, "CP1250", self.desurveyLayer.crs(), layerOptions=['OVERWRITE=YES']) # Load the one we just saved and add it to the map layer = QgsVectorLayer(fileName+".gpkg", label) QgsProject.instance().addMapLayer(layer)
def set_current_html(self, html): page = QWebEnginePage(self.parent) page.setHtml(html) self.setPage(page) self.update() qApp.processEvents()
def desurveyHole(self): # Write to the log file self.logFile.write("\nDesurveying data.\n") self.logFile.flush() # Set up a progress bar pd = QProgressDialog() pd.setAutoReset(False) pd.setMinimumWidth(500) pd.setMinimum(0) # Get the relevant attribute indices dp = self.collarLayer.dataProvider() idxCollarId = dp.fieldNameIndex(self.collarId) idxCollarEast = dp.fieldNameIndex(self.collarEast) idxCollarNorth = dp.fieldNameIndex(self.collarNorth) idxCollarElev = dp.fieldNameIndex(self.collarElev) idxCollarDepth = dp.fieldNameIndex(self.collarDepth) idxCollarAz = dp.fieldNameIndex(self.collarAz) idxCollarDip = dp.fieldNameIndex(self.collarDip) # Are we using azimuths and dips from the collar file? useCollarAzDip = (idxCollarAz > -1) and (idxCollarDip > -1) # Build Collar array (Id, east, north, elev, eoh, az, dip) numCollars = self.collarLayer.featureCount() arrCollar = [] # Update the progress bar pd.setWindowTitle("Build Collar Array") pd.setMaximum(numCollars) pd.setValue(0) floatConvError = False nullDataError = False # Create a new Collar 3D layer to hold 3D points. This will be used for section creation. collar3D = self.createCollarLayer() # Loop through the collar layer and build list of collars for index, feature in enumerate(self.collarLayer.getFeatures()): # Update progress bar pd.setValue(index) # get the feature's attributes attrs = feature.attributes() c = Collar() # Check all the data is valid c.id = str(attrs[idxCollarId]) try: c.east = float(attrs[idxCollarEast]) c.north = float(attrs[idxCollarNorth]) c.elev = float(attrs[idxCollarElev]) c.depth = float(attrs[idxCollarDepth]) except: floatConvError = True if (c.id==NULL) or (c.east==NULL) or (c.north==NULL) or (c.elev==NULL) or (c.depth==NULL): nullDataError = True continue c.id = c.id.strip() if useCollarAzDip: c.az = attrs[idxCollarAz] if c.az==NULL: c.az = 0.0 c.dip = attrs[idxCollarDip] if c.dip==NULL: c.dip = -90 if self.downDipNegative else 90 arrCollar.append(c) #Create a new 3D point feature and copy the attributes f = QgsFeature() # p = QPointF(c.east, c.north, c.elev) f.setGeometry(QgsGeometry(QgsPoint(c.east, c.north, c.elev, wkbType = QgsWkbTypes.PointZ))) # Add in the field attributes f.setAttributes(attrs) # Add the feature to the layer collar3D.startEditing() collar3D.addFeature(f) collar3D.commitChanges() if (floatConvError): iface.messageBar().pushMessage("Warning", "Some 'East', 'North', 'Collar' or 'Depth' values are not numbers", level=Qgis.Warning) if (nullDataError): iface.messageBar().pushMessage("Warning", "Some 'HoleId', 'East', 'North', 'Collar' or 'Depth' values are NULL. These have been skipped", level=Qgis.Warning) # Build Survey array (Id, depth, az, dip) arrSurvey = [] if self.surveyLayer is not None and self.surveyLayer.isValid(): numSurveys = self.surveyLayer.featureCount() # Get the attribute indices dp = self.surveyLayer.dataProvider() idxSurveyId = dp.fieldNameIndex(self.surveyId) idxSurveyDepth = dp.fieldNameIndex(self.surveyDepth) idxSurveyAz = dp.fieldNameIndex(self.surveyAz) idxSurveyDip = dp.fieldNameIndex(self.surveyDip) # Update progress bar pd.setWindowTitle("Build Survey Array") pd.setMaximum(numSurveys) pd.setValue(0) floatConvError = False nullDataError = False #Loop through Survey layer and buils list of surveys for index, feature in enumerate(self.surveyLayer.getFeatures()): pd.setValue(index) # get the feature's attributes attrs = feature.attributes() s = Survey() s.id = str(attrs[idxSurveyId]) try: s.depth = float(attrs[idxSurveyDepth]) s.az = float(attrs[idxSurveyAz]) s.dip = float(attrs[idxSurveyDip]) except: floatConvError = True if (s.id==NULL) or (s.depth==NULL) or (s.az==NULL) or (s.dip==NULL): nullDataError = True continue s.id = s.id.strip() arrSurvey.append(s) if (floatConvError): iface.messageBar().pushMessage("Warning", "Some survey 'Depth', 'Azimuth' or 'Dip' values are not numbers", level=Qgis.Warning) if (nullDataError): iface.messageBar().pushMessage("Warning", "Some 'HoleId', 'Depth', 'Azimuth' or 'Dip' values are NULL. These have been skipped", level=Qgis.Warning) # Create new layer for the desurveyed 3D coordinates. PolyLine, 1 row per collar, 2 attribute (Id, Segment Length) self.createDesurveyLayer() #Loop through collar list and desurvey each one # Update Progress bar pd.setWindowTitle("Desurvey Progress") pd.setMaximum(len(arrCollar)) pd.setValue(0) #Calculate optimum update interval updateInt = max(100, int(len(arrCollar)/100)) # Enter collar loop for index, collar in enumerate(arrCollar): pd.setValue(index) # Force update the progress bar visualisation every 1% as it normally only happens in idle time if index%updateInt == 0: qApp.processEvents() # Check the id exists if not collar.id: continue #Build array of surveys for this collar, including the top az and dip in collar layer. Repeat last survey at EOH. surveys = [] if len(arrSurvey) > 0: # Harvest surveys for this collar from Survey layer list for survey in arrSurvey: if survey.id == collar.id: s = Surveys() s.depth = survey.depth s.az = survey.az s.dip = survey.dip surveys.append(s) # If the az and dip from the collar are to be used, then insert them at depth 0.0 # We only do this if there are no surveys from the Survey layer if len(surveys) == 0 and useCollarAzDip: s = Surveys() s.depth = 0.0 s.az = collar.az s.dip = collar.dip surveys.append(s) # If there are no surveys, then the assume hole is vertical if len(surveys) == 0: s = Surveys() s.depth = 0.0 s.az = 0.0 s.dip = -90 if self.downDipNegative else 90 surveys.append(s) # Is the hole straight? If so, we can take short cuts holeStraight = False if len(surveys) == 1: holeStraight = True # We only replicate survey to the beginning and end if the hole is not straight if not holeStraight: # Sort the surveys array by depth surveys.sort(key = lambda x: x.depth) # If surveys exist, but there isn't one at 0.0, then replicate first survey at 0.0 if not surveys[0].depth == 0.0: s = Surveys() surveys.insert(0, s) s.depth = 0.0 surveys[0].az = surveys[1].az surveys[0].dip = surveys[1].dip # If the last survey isn't at the end of hole, then repeat the last one at eoh if len(surveys) > 0 and surveys[-1].depth < collar.depth: s = Surveys() s.depth = collar.depth s.az = surveys[-1].az s.dip = surveys[-1].dip surveys.append(s) # Create a quaternion for each survey quat = [] for j, s in enumerate(surveys): # Rotate about positive X axis by dip degrees (depends on downDipNegative flag) qdip = Quaternion(axis=[1, 0, 0], degrees=(s.dip if self.downDipNegative else -s.dip)) # Rotate about positive Z axis by -Az degrees qaz = Quaternion(axis=[0, 0, 1], degrees=-s.az) # Combine the dip and azimuth (order is important!) q = qaz * qdip #Ensure the quaternion rotates the shortest way around. This can go wrong when we cross 0/360 deg. # If the dot product of the quats is negative then it's the wrong way, # so we negate the quat. # But, don't do it on the first one if j > 0: if np.dot(quat[j-1].elements, q.elements) < 0.0: q = -q quat.append(q) #Build drill trace every desurveyLength to EOH xs = [] if not holeStraight: sz = int(collar.depth / self.desurveyLength) + 1 depth = 0.0 for d in range(0, sz): xs.append(depth) depth += self.desurveyLength if xs[-1] > collar.depth: xs[-1] = collar.depth if xs[-1] < collar.depth: xs.append(collar.depth) else: xs.append(0.0) # Create linestring to record the desurveyed points every Segment Length # This can then be used to interpolate intervening points feature = QgsFeature() # We'll create a pointlist to hold all the 3D points pointList = [] # We start by adding the collar coordinates pointList.append(QgsPoint(collar.east, collar.north, collar.elev)) # It's easier with a straight hole if not holeStraight: # We're going to keep iterating through the survey list looking for the bracketing surveys. # We therefore record the start point of the iteration as it will only go up. Saves time. idx0 = 0 # We already added the location at point0 (the collar) so start from 1 for i in range(1, len(xs)): q = Quaternion() # Find the lowest survey equal or less than xs for j in range(idx0, len(surveys)): # Is there a survey exactly at this point? if surveys[j].depth == xs[i]: # Update the iteration start point idx0 = j q = quat[j] break # Are there surveys bracketing this depth? If so, interpolate point if surveys[j].depth < xs[i] and surveys[j+1].depth >= xs[i]: # Update the iteration start point idx0 = j # How far are we between bracketing surveys? ratio = (xs[i] - surveys[j].depth) / (surveys[j+1].depth - surveys[j].depth) # Interpolate between bracketing survey rotations q = Quaternion.slerp(quat[j], quat[j+1], ratio) break # Calculate the deviation of this segment of the hole offset = q.rotate(np.array([0.0, 1.0, 0.0])) * self.desurveyLength # Calculate the new point by adding the offset to the old point p0 = pointList[i-1] pointList.append(QgsPoint(p0.x() + offset[0], p0.y() + offset[1], p0.z() + offset[2])) else: # Calculate the offset of the bottom of hole from the top of hole in a single segment offset = quat[0].rotate(np.array([0.0, 1.0, 0.0])) * collar.depth # Add the offset to the collar p0 = pointList[0] pointList.append(QgsPoint(p0.x() + offset[0], p0.y() + offset[1], p0.z() + offset[2])) # Create new geometry (Polyline) for the feature feature.setGeometry(QgsGeometry.fromPolyline(pointList)) # Add in the field attributes feature.setAttributes([collar.id, collar.depth if holeStraight else self.desurveyLength]) # Add the feature to the layer self.desurveyLayer.startEditing() self.desurveyLayer.addFeature(feature) self.desurveyLayer.commitChanges() self.desurveyLayer = self.writeVectorLayerFromMemory(self.desurveyLayer, self.createDesurveyFilename(), self.collarLayer.crs()) self.writeVectorLayerFromMemory(collar3D, self.createCollarFilename(), self.collarLayer.crs())
def show(self): super().show() qApp.processEvents()
def __execute_and_update(self, cmd, out_dir=None, out_file=sys.stdout): """Execute the given command and update the progress bar""" # TODO: kill this when done... fds_pid = util.execute(cmd=cmd, cwd=out_dir, out_file=out_file) t_end = float(self._fds.sim_time()) # self._progress_bar.setFormat("%p% ({0}s / {1}s)".format(0, t_end)) # Initialize the progress bar format # Make progress bar visible self._progress_bar.show() # We need to give WFDS some time to create the proper .out so that we may # read from it and update the progress bar. # Since everyone has different hardware, this seems to be the most sensible solution. # Could get caught in an infinite while loop if .out is never made, but we expect this file to be present # as part of WFDS' 'interface' wait = True while wait: try: out_file = osp.join(out_dir, self._fds.job() + '.out') for line in follow(open(out_file, 'r')): line = line.replace(' ', '').replace('\n', '') # Break if we hit STOP because simulation is over if line.startswith('STOP'): break if line.startswith('Timestep'): timestep_kv, sim_time_kv = line.split(',') # Not currently used, could be later? timestep_int = timestep_kv.split(':')[1] sim_time_float = float( sim_time_kv.split(':')[1].replace('s', '')) # Figure out percentage and update progress bar loading = (sim_time_float / t_end) * 100 self._progress_bar.setValue(loading) # self._progress_bar.setFormat("%p% ({0}s / {1}s)".format(sim_time_float, t_end)) wait = False except FileNotFoundError: logger.log(logger.INFO, 'Sleep') qApp.processEvents() # Helps keep gui responsive time.sleep(0.1) # TODO: could get pid from popen and check it or something here. # May also be useful to get pid for things such as killing if FireScape Rx is # terminated prematurely # If we reach here, simulation should be done. logger.log(logger.INFO, "Simulation complete") self._progress_bar.setValue(100) qApp.restoreOverrideCursor() QMessageBox.information(self, 'Simulation Complete', 'Simulation completed.') self.__hide_and_reset_progress()
def save_out_pngs(self, sizesList): # A small fix to ensure crop to guides is set. if "cropToGuides" not in self.configDictionary.keys(): self.configDictionary["cropToGuides"] = False # Check if we have pages at all... if "pages" in self.configDictionary.keys(): # Check if there's export methods, and if so make sure the appropriate dictionaries are initialised. if len(sizesList.keys()) < 1: print( "CPMT: Export failed because there's no export methods set." ) return False else: for key in sizesList.keys(): self.pagesLocationList[key] = [] # Get the appropriate paths. path = Path(self.projectURL) exportPath = path / self.configDictionary["exportLocation"] pagesList = self.configDictionary["pages"] fileName = str(exportPath) # Create a progress dialog. progress = QProgressDialog("Preparing export.", str(), 0, len(pagesList)) progress.setWindowTitle("Exporting comic...") progress.setCancelButton(None) timer = QElapsedTimer() timer.start() progress.show() qApp.processEvents() for p in range(0, len(pagesList)): # Update the label in the progress dialog. progress.setValue(p) timePassed = timer.elapsed() if (p > 0): timeEstimated = (len(pagesList) - p) * (timePassed / p) passedString = str(int(timePassed / 60000)) + ":" + format( int(timePassed / 1000), "02d") + ":" + format( timePassed % 1000, "03d") estimatedString = str(int( timeEstimated / 60000)) + ":" + format( int(timeEstimated / 1000), "02d") + ":" + format( int(timeEstimated % 1000), "03d") progress.setLabelText( str( i18n( "{pages} of {pagesTotal} done. \nTime passed: {passedString}:\n Estimated:{estimated}" )).format(pages=p, pagesTotal=len(pagesList), passedString=passedString, estimated=estimatedString)) qApp.processEvents() # Get the appropriate url and open the page. url = str(Path(self.projectURL) / pagesList[p]) page = Application.openDocument(url) page.waitForDone() # remove layers and flatten. labelList = self.configDictionary["labelsToRemove"] panelsAndText = [] # These three lines are what is causing the page not to close. root = page.rootNode() self.getPanelsAndText(root, panelsAndText) self.removeLayers(labelList, root) page.refreshProjection() # We'll need the offset and scale for aligning the panels and text correctly. We're getting this from the CBZ pageData = {} pageData["vector"] = panelsAndText tree = ET.fromstring(page.documentInfo()) pageData["title"] = page.name() calligra = "{http://www.calligra.org/DTD/document-info}" about = tree.find(calligra + "about") keywords = about.find(calligra + "keyword") keys = str(keywords.text).split(",") pKeys = [] for key in keys: if key in self.pageKeys: pKeys.append(key) pageData["keys"] = pKeys page.flatten() page.waitForDone() batchsave = Application.batchmode() Application.setBatchmode(True) # Start making the format specific copy. for key in sizesList.keys(): w = sizesList[key] # copy over data projection = page.clone() projection.setBatchmode(True) # Crop. Cropping per guide only happens if said guides have been found. if w["Crop"] is True: listHGuides = [] listHGuides = page.horizontalGuides() listHGuides.sort() for i in range(len(listHGuides) - 1, 0, -1): if listHGuides[i] < 0 or listHGuides[ i] > page.height(): listHGuides.pop(i) listVGuides = page.verticalGuides() listVGuides.sort() for i in range(len(listVGuides) - 1, 0, -1): if listVGuides[i] < 0 or listVGuides[ i] > page.width(): listVGuides.pop(i) if self.configDictionary["cropToGuides"] and len( listVGuides) > 1: cropx = listVGuides[0] cropw = listVGuides[-1] - cropx else: cropx = self.configDictionary["cropLeft"] cropw = page.width( ) - self.configDictionary["cropRight"] - cropx if self.configDictionary["cropToGuides"] and len( listHGuides) > 1: cropy = listHGuides[0] croph = listHGuides[-1] - cropy else: cropy = self.configDictionary["cropTop"] croph = page.height( ) - self.configDictionary["cropBottom"] - cropy projection.crop(cropx, cropy, cropw, croph) projection.waitForDone() qApp.processEvents() # resize appropriately else: cropx = 0 cropy = 0 res = page.resolution() listScales = [ projection.width(), projection.height(), res, res ] projectionOldSize = [ projection.width(), projection.height() ] sizesCalc = sizesCalculator() listScales = sizesCalc.get_scale_from_resize_config( config=w, listSizes=listScales) projection.unlock() projection.scaleImage(listScales[0], listScales[1], listScales[2], listScales[3], "bicubic") projection.waitForDone() qApp.processEvents() # png, gif and other webformats should probably be in 8bit srgb at maximum. if key != "TIFF": if (projection.colorModel() != "RGBA" and projection.colorModel() != "GRAYA" ) or projection.colorDepth() != "U8": projection.setColorSpace("RGBA", "U8", "sRGB built-in") else: # Tiff on the other hand can handle all the colormodels, but can only handle integer bit depths. # Tiff is intended for print output, and 16 bit integer will be sufficient. if projection.colorDepth( ) != "U8" or projection.colorDepth() != "U16": projection.setColorSpace(page.colorModel(), "U16", page.colorProfile()) # save # Make sure the folder name for this export exists. It'll allow us to keep the # export folders nice and clean. folderName = str(key + "-" + w["FileType"]) if Path(exportPath / folderName).exists() is False: Path.mkdir(exportPath / folderName) # Get a nice and descriptive fle name. fn = str( Path(exportPath / folderName) / str("page_" + format(p, "03d") + "_" + str(listScales[0]) + "x" + str(listScales[1]) + "." + w["FileType"])) # Finally save and add the page to a list of pages. This will make it easy for the packaging function to # find the pages and store them. projection.exportImage(fn, InfoObject()) projection.waitForDone() qApp.processEvents() if key == "CBZ": transform = {} transform["offsetX"] = cropx transform["offsetY"] = cropy transform["resDiff"] = page.resolution() / 72 transform["scaleWidth"] = projection.width( ) / projectionOldSize[0] transform["scaleHeight"] = projection.height( ) / projectionOldSize[1] pageData["transform"] = transform self.pagesLocationList[key].append(fn) projection.close() self.acbfPageData.append(pageData) page.close() progress.setValue(len(pagesList)) Application.setBatchmode(batchsave) # TODO: Check what or whether memory leaks are still caused and otherwise remove the entry below. print( "CPMT: Export has finished. If there are memory leaks, they are caused by file layers." ) return True print("CPMT: Export not happening because there aren't any pages.") return False
def write(self, info): self.log_browser.insertPlainText(info) qApp.processEvents(QEventLoop.ExcludeUserInputEvents | QEventLoop.ExcludeSocketNotifiers)
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() newPage.close() # add item to page. self.pagesModel.appendRow(newPageItem)
def closeAllFiles(self): for tab in list(range(self.tabwidget.count())): qApp.processEvents() self.tabwidget.removeTab(0)
def updateProgress(self, text: str) -> None: self.setValue(self._progress.value() + 1) self.setText(text) qApp.processEvents()
def setText(self, text): self.text = text self.paintEvent(None) self.update() qApp.processEvents()