def _launchImport(self): ''' Launch the import ''' if not self._validateMapping(): return qgis_layer = self.qgislayers[self.cbbLayers.currentIndex()] self.close() # Progress bar + message progressMessageBar = PagLuxembourg.main.qgis_interface.messageBar().createMessage(QCoreApplication.translate('ImportShpDialog','Importing {}').format(self.shplayer.source())) progress = QProgressBar() progress.setMaximum(self.shplayer.featureCount()) progress.setAlignment(Qt.AlignLeft|Qt.AlignVCenter) progressMessageBar.layout().addWidget(progress) PagLuxembourg.main.qgis_interface.messageBar().pushWidget(progressMessageBar, QgsMessageBar.INFO) # Start import session self._startImportSession() # Import the layer, and get the imported extent self._importLayer( self.shplayer, qgis_layer, self.mapping.asIndexFieldMappings(qgis_layer.dataProvider().fields(), self.shpfields), progress ) # Commit import session self._commitImport()
class Popup(QDialog): def __init__(self, widget, parent = None): QDialog.__init__(self, parent) self.setModal(True) self.setWindowTitle("Plot save progress") layout = QVBoxLayout() layout.addWidget(widget) self.progress_bar = QProgressBar() self.progress_bar.setMinimum(0) self.progress_bar.setMaximum(1) self.progress_bar.setValue(0) layout.addWidget(self.progress_bar) buttons = QDialogButtonBox(QDialogButtonBox.Ok, Qt.Horizontal, self) layout.addWidget(buttons) self.setLayout(layout) self.connect(buttons, SIGNAL('accepted()'), self.accept) self.ok_button = buttons.button(QDialogButtonBox.Ok) self.ok_button.setEnabled(False) def closeEvent(self, event): """Ignore clicking of the x in the top right corner""" event.ignore() def keyPressEvent(self, event): """Ignore ESC keystrokes""" if not event.key() == Qt.Key_Escape: QDialog.keyPressEvent(self, event)
def startWorker(self, Folder, Stats, OutImage, NoData): # create a new worker instance worker = Worker(Folder, Stats, OutImage, NoData) #Create Progressbar qgis.utils.iface.messageBar().clearWidgets() progressMessageBar = qgis.utils.iface.messageBar().createMessage( 'Calculating Statistics Image...') progressBar = QProgressBar() progressBar.setMaximum(100) progressMessageBar.layout().addWidget(progressBar) qgis.utils.iface.messageBar().pushWidget(progressMessageBar) self.progressMessageBar = progressMessageBar # start the worker in a new thread thread = QThread() worker.moveToThread(thread) worker.finished.connect(self.workerFinished) worker.error.connect(self.workerError) worker.progress.connect(progressBar.setValue) thread.started.connect(worker.StatsImage) thread.start() self.thread = thread self.worker = worker self.outImage = OutImage
def startWorker(self): # create a new worker instance if self.worker is None: worker = UpdateRegistryWorker() # configure the QgsMessageBar messageBar = self.iface.messageBar().createMessage(u"Update Image Registry", u"Dieser Vorgang kann einige Minute dauern, bitte haben Sie geduld!") progressBar = QProgressBar() progressBar.setMinimum(0) progressBar.setMaximum(0) progressBar.setAlignment(Qt.AlignLeft|Qt.AlignVCenter) cancelButton = QPushButton() cancelButton.setText('Cancel') cancelButton.clicked.connect(self.killWorker) messageBar.layout().addWidget(progressBar) self.progressBar = progressBar messageBar.layout().addWidget(cancelButton) self.iface.messageBar().pushWidget(messageBar, self.iface.messageBar().INFO) #self.iface.messageBar().widgetRemoved # messageBar self.messageBar = messageBar # start the worker in a new thread thread = QThread() worker.moveToThread(thread) worker.finished.connect(self.workerFinished) worker.error.connect(self.workerError) #worker.progress.connect(progressBar.setValue) thread.started.connect(worker.run) thread.start() self.thread = thread self.worker = worker
def synccomplete(self): try: self.iface.messageBar().popWidget(self.syncwidget) except RuntimeError: pass stylesheet = ("QgsMessageBar { background-color: rgba(239, 255, 233); border: 0px solid #b9cfe4; } " "QLabel,QTextEdit { color: #057f35; } ") closebutton = self.iface.messageBar().findChildren(QToolButton)[0] closebutton.setVisible(True) closebutton.clicked.connect(functools.partial(self.report.setVisible, False)) self.syncwidget = self.iface.messageBar().createMessage("Syncing", "Sync Complete", QIcon(":/icons/syncdone")) button = QPushButton(self.syncwidget) button.setCheckable(True) button.setChecked(self.report.isVisible()) button.setText("Sync Report") button.setIcon(QIcon(":/icons/syncinfo")) button.toggled.connect(functools.partial(self.report.setVisible)) pro = QProgressBar() pro.setMaximum(100) pro.setValue(100) self.syncwidget.layout().addWidget(pro) self.syncwidget.layout().addWidget(button) self.iface.messageBar().pushWidget(self.syncwidget) self.iface.messageBar().setStyleSheet(stylesheet) self.iface.mapCanvas().refresh()
class ReportExportProgress(QObject): def __init__(self, name, eventCount, eventStart, eventFinish, child=None): QObject.__init__(self) self.name = name self.eventCount = eventCount self.eventStart = eventStart self.eventFinish = eventFinish self.child = child self.label = QLabel() self.label.setWordWrap(True) self.bar = QProgressBar() self.bar.setFormat(" %v/%m (%p%)") self.reset() def reset(self): self.title = "" self.current = 0 self.count = 0 def event(self, event): if event.type == self.eventStart: self.title = event.value.value() if self.child: self.child.reset() if event.type == self.eventFinish: self.current += 1 self.bar.setValue(self.current) if event.type == self.eventCount: self.count = event.value.value() self.bar.setValue(0) self.bar.setMaximum(self.count) self.label.setText( self.tr("Extraction ") + self.name + " : " + str(self.title))
def startWorker(self, inFolder, OutFolder, Window, Polynomial): # create a new worker instance worker = Worker(inFolder, OutFolder, Window, Polynomial) #Create Progressbar qgis.utils.iface.messageBar().clearWidgets() progressMessageBar = qgis.utils.iface.messageBar().createMessage( 'Executing Savitzky Golay Filter...') progressBar = QProgressBar() progressBar.setMaximum(100) progressMessageBar.layout().addWidget(progressBar) qgis.utils.iface.messageBar().pushWidget(progressMessageBar) self.progressMessageBar = progressMessageBar # start the worker in a new thread thread = QThread() worker.moveToThread(thread) worker.finished.connect(self.workerFinished) worker.error.connect(self.workerError) worker.progress.connect(progressBar.setValue) thread.started.connect(worker.SavitzkyGolayFilter) thread.start() self.thread = thread self.worker = worker
def startWorker(self, ExtrairShape, CalcShape, OutShape, Ref, TypeUnits): # create a new worker instance worker = Worker(ExtrairShape, CalcShape, OutShape, Ref, TypeUnits) # configure the QgsMessageBar qgis.utils.iface.messageBar().clearWidgets() progressMessageBar = qgis.utils.iface.messageBar().createMessage('Calculating area...') progressBar = QProgressBar() progressBar.setMaximum(100) progressMessageBar.layout().addWidget(progressBar) qgis.utils.iface.messageBar().pushWidget(progressMessageBar) self.progressMessageBar = progressMessageBar # start the worker in a new thread thread = QThread() worker.moveToThread(thread) worker.finished.connect(self.workerFinished) worker.error.connect(self.workerError) worker.progress.connect(progressBar.setValue) thread.started.connect(worker.runCalc) thread.start() self.thread = thread self.worker = worker self.output = OutShape
def on_downloaded(self): widget = self.iface.messageBar().createMessage(u"Géofoncier", u"Téléchargement du RFU.") progress_bar = QProgressBar() progress_bar.setMinimum(0) progress_bar.setMaximum(2) widget.layout().addWidget(progress_bar) self.iface.messageBar().pushWidget(widget, QgsMessageBar.WARNING) progress_bar.setValue(1) # https://pro.geofoncier.fr/index.php?¢re=-196406,5983255&context=metropole url = self.permalinkLineEdit.text() if not url: return self.abort_action(msg=u"Veuillez renseigner le permalien.") self.url = url try: self.download(self.url) except Exception as e: return self.abort_action(msg=e.message) progress_bar.setValue(2) self.iface.messageBar().clearWidgets() return
def setupCommandGUI(self, commands): for name, node in sorted(commands.items(), key=natural_keys): row = self.ui.gridLayout.rowCount() + 1 label = QLabel(self.ui.groupBox) if not node.category: label.setText((' ' * node.level) + node.name.replace('___', ' ')) else: label.setText((' ' * node.level) + '<b>' + node.name.replace('___', ' ') + '</b>') label.setObjectName('lableCommand_' + node.name) if not node.category: buttonStart = QPushButton(self.ui.groupBox) buttonStart.setText('Start') buttonStart.setObjectName('pushButtonCommand_' + node.name + '_start') buttonStart.clicked.connect(partial(self.onStart, name)) buttonStop = QPushButton(self.ui.groupBox) buttonStop.setText('Stop') buttonStop.setObjectName('pushButtonCommand_' + node.name + '_stop') buttonStop.clicked.connect(partial(self.onStop, name)) buttonRestart = QPushButton(self.ui.groupBox) buttonRestart.setText('Restart') buttonRestart.setObjectName('pushButtonCommand_' + node.name + '_restart') buttonRestart.clicked.connect(partial(self.onRestart, name)) progressBar = None if node.name in self.progressTopics: progressBar = QProgressBar(self.ui.groupBox) progressBar.setObjectName('progressBarCommand_' + node.name) progressBar.setValue(0) progressBar.setMaximum(100) progressBar.setMaximumWidth(300) # if node.level == 0 or (node.level == 1 and node.parent.category): # buttonStart.setEnabled(True) # buttonStop.setEnabled(True) # buttonRestart.setEnabled(True) # else: # buttonStart.setEnabled(False) # buttonStop.setEnabled(False) # buttonRestart.setEnabled(False) self.ui.gridLayout.addWidget(buttonStart, row, 1) self.ui.gridLayout.addWidget(buttonStop, row, 2) self.ui.gridLayout.addWidget(buttonRestart, row, 3) if not progressBar is None: self.ui.gridLayout.addWidget(progressBar, row, 4) self.ui.gridLayout.addWidget(label, row, 0) self.setupCommandGUI(node.childs)
def on_downloaded(self): widget = self.iface.messageBar().createMessage( u"Géofoncier", u"Téléchargement du RFU.") progress_bar = QProgressBar() progress_bar.setMinimum(0) progress_bar.setMaximum(2) widget.layout().addWidget(progress_bar) self.iface.messageBar().pushWidget(widget, QgsMessageBar.WARNING) progress_bar.setValue(1) # https://pro.geofoncier.fr/index.php?¢re=-196406,5983255&context=metropole url = self.permalinkLineEdit.text() if not url: return self.abort_action(msg=u"Veuillez renseigner le permalien.") self.url = url try: self.download(self.url) except Exception as e: return self.abort_action(msg=e.message) progress_bar.setValue(2) self.iface.messageBar().clearWidgets() return
class ExerciseUI(QGroupBox): def __init__(self, exercise): super(ExerciseUI, self).__init__() self.exercise = exercise self.initUI() def initUI(self): self.setTitle(self.exercise.label) self.level = QLabel(QString('Lvl. %d' % self.exercise.level)) self.progressbar = QProgressBar() self.progressbar.setMinimum(0) self.progressbar.setMaximum(100) self.progressbar.setValue(self.exercise.progress) grid = QGridLayout() grid.addWidget(self.level, 0, 0) grid.addWidget(self.progressbar, 0, 1, 1, 9) for (index, step) in enumerate(self.exercise.steps): btn = QPushButton(QString('+') + QString.number(step)) grid.addWidget(btn, 1, index) btn.clicked.connect(self.buttonClicked) self.setLayout(grid) def buttonClicked(self): sender = self.sender() step = int(str(sender.text()).lstrip('+')) self.exercise.add(step) self.level.setText(QString('Lvl. %d' % self.exercise.level)) self.progressbar.setValue(self.exercise.progress)
class SeekOverlay(Overlay): def __init__(self, keyPressHandler, parent = None): Overlay.__init__(self, keyPressHandler, parent) self.setupUI() def setupUI(self): self.layout = QHBoxLayout(self) self.timeBar = QProgressBar() self.layout.addWidget(self.timeBar) def resizeEvent(self, event): textHeight = event.size().height() * .4 self.timeBar.setStyleSheet('QProgressBar {font-size: %dpt;}' % textHeight) def setTime(self, current, total): current = int(current) total = int(total) self.timeBar.setMaximum(total) self.timeBar.setValue(current) self.timeBar.setFormat(MPlayer.formatTime(current) + '/' + MPlayer.formatTime(total))
class ReportExportProgressItems(QObject): def __init__(self): QObject.__init__(self) self.eventCount = ReportManager.EventExportItems self.eventFinish = [ ReportManager.EventExportCategoryFinish, ReportPage.EventExportFinish, ReportPageFragment.EventWriteFinish, ReportPageFragment.EventWriteElementFinish ] self.label = QLabel(self.tr("Extracting report")) self.bar = QProgressBar() self.bar.setFormat(" %v/%m (%p%)") self.reset() def reset(self): self.count = 0 self.current = 0 def event(self, event): if event.type == self.eventCount: self.count = event.value.value() self.bar.setValue(0) self.bar.setMaximum(self.count) if event.type in self.eventFinish: self.current += 1 self.bar.setValue(self.current)
class RenameGui(BaseWindow, QtGui.QMainWindow): renameCompleted = QtCore.pyqtSignal() def __init__(self, session, parent=None): super(RenameGui, self).__init__(parent) self.session = session self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.renameUser.clicked.connect(self.renameUser) self.progressIndicator = QProgressBar(self.ui.statusBar) self.progressIndicator.setMinimumHeight(5) self.progressIndicator.setVisible(False) self.progressIndicator.setMaximum(0) self.progressIndicator.setMinimum(0) self.ui.statusBar.addWidget(self.progressIndicator) self.renameCompleted.connect(self.renameCompletedSlot) self.uiTranslate() def uiTranslate(self): self.setWindowTitle(strings["renameWindowTitle"]) self.ui.newUsername.setPlaceholderText(strings["newUsernameBoxHint"]) self.ui.renameUser.setText(strings["renameUserButtonText"]) def renameCompletedSlot(self): self.progressIndicator.setVisible(False) self.showMessageBox.emit(strings["renameSuccessText"]) def renameUser(self): self.progressIndicator.setVisible(True) def renameThread(): newUsername = self.ui.newUsername.text() if newUsername == "": self.showMessageBox.emit(strings["missingFieldsErrorText"]) return try: oldUsername = self.session.username self.session.renameUser(newUsername) for message in sharedData.messages: if message.sender == oldUsername: message.sender = newUsername elif message.receiver == oldUsername: message.receiver = newUsername storeMessages(self.session.username, sharedData.messages) storeToken(self.session.username, self.session.token) storeKey(self.session.username, self.session.public, self.session.private) storeMessages(oldUsername, None) storeToken(oldUsername, None) storeKey(oldUsername, None, None) self.renameCompleted.emit() except SecureMessagingException as error: self.showMessageBox.emit(strings["errorText"] + responseTranslations[str(error)]) return Thread(target=renameThread).start()
class ProgressWidget(QgsMessageBar): def __init__(self, min, max, message, parent=None, timeout = 1.5): """ Constructs a progress widget """ super(self.__class__, self).__init__(parent) self.min = min self.max = max sizePolicy = QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) if parent: self.setMinimumSize(parent.width(),40) else: self.setMinimumSize(766,40) self.setSizePolicy(sizePolicy) self.progressBar = QProgressBar() self.progressBar.setMinimum(min) self.progressBar.setMaximum(max) self.msgBarItem = QgsMessageBarItem(self.tr("INFO: "), message, self.progressBar, level=QgsMessageBar.INFO, duration=timeout) self.pushWidget(self.msgBarItem) def initBar(self): """ Initializes the progress bar """ self.progressBar.setValue(0) def step(self): """ Increments the progress bar """ value = self.progressBar.value() + 1 self.progressBar.setValue(value) if value == self.max: time.sleep(1) self.close()
def startWorker(self, Folder, Stats, OutImage,NoData): # create a new worker instance worker = Worker(Folder,Stats, OutImage,NoData) #Create Progressbar qgis.utils.iface.messageBar().clearWidgets() progressMessageBar = qgis.utils.iface.messageBar().createMessage('Calculating Statistics Image...') progressBar = QProgressBar() progressBar.setMaximum(100) progressMessageBar.layout().addWidget(progressBar) qgis.utils.iface.messageBar().pushWidget(progressMessageBar) self.progressMessageBar = progressMessageBar # start the worker in a new thread thread = QThread() worker.moveToThread(thread) worker.finished.connect(self.workerFinished) worker.error.connect(self.workerError) worker.progress.connect(progressBar.setValue) thread.started.connect(worker.StatsImage) thread.start() self.thread = thread self.worker = worker self.outImage = OutImage
def start_worker(worker, iface, message, with_progress=True): # configure the QgsMessageBar message_bar_item = iface.messageBar().createMessage(message) progress_bar = QProgressBar() progress_bar.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) if not with_progress: progress_bar.setMinimum(0) progress_bar.setMaximum(0) cancel_button = QPushButton() cancel_button.setText('Cancel') cancel_button.clicked.connect(worker.kill) message_bar_item.layout().addWidget(progress_bar) message_bar_item.layout().addWidget(cancel_button) iface.messageBar().pushWidget(message_bar_item, iface.messageBar().INFO) # start the worker in a new thread # let Qt take ownership of the QThread thread = QThread(iface.mainWindow()) worker.moveToThread(thread) worker.set_message.connect( lambda message: set_worker_message(message, message_bar_item)) worker.toggle_show_progress.connect( lambda show: toggle_worker_progress(show, progress_bar)) worker.toggle_show_cancel.connect( lambda show: toggle_worker_cancel(show, cancel_button)) worker.finished.connect(lambda result: worker_finished( result, thread, worker, iface, message_bar_item)) worker.error.connect(lambda e: worker_error(e)) worker.progress.connect(progress_bar.setValue) thread.started.connect(worker.run) thread.start() return thread, message_bar_item
class ProgressDialog(QDialog): def __init__(self, parent): QDialog.__init__(self, parent) self.resize(300, 75) self.setWindowTitle("Updating") self.vw = QWidget(self) self.vl = QVBoxLayout(self.vw) self.vl.setMargin(10) self.label = QLabel(self.vw) self.label.setText("<b>Downloading:</b> library.zip") self.vl.addWidget(self.label) self.horizontalLayoutWidget = QWidget() self.horizontalLayout = QHBoxLayout(self.horizontalLayoutWidget) self.horizontalLayout.setMargin(0) self.progressbar = QProgressBar(self.horizontalLayoutWidget) self.progressbar.setFixedWidth(260) self.progressbar.setMinimum(0) self.progressbar.setMaximum(100) self.stopButton = QPushButton(self.horizontalLayoutWidget) self.stopButton.setFlat(True) self.stopButton.setIcon(Icons.stop) self.stopButton.setFixedSize(16,16) self.horizontalLayout.addWidget(self.progressbar) self.horizontalLayout.addWidget(self.stopButton) self.vl.addWidget(self.horizontalLayoutWidget) self.stopButton.clicked.connect(self.forceStop) def setValue(self,val): self.progressbar.setValue(val) def forceStop(self): self.emit(SIGNAL("forceStop"))
def addLoadingMsg(self, countLayers, barText='Downloading datasets'): barText = self.tr(barText) progressMessageBar = self.iface.messageBar().createMessage(barText, '0/' + str(countLayers)) progress = QProgressBar() progress.setMaximum(countLayers) progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) progressMessageBar.layout().addWidget(progress) return progressMessageBar, progress
def addLoadingMsg(self, countLayers, barText='Downloading datasets'): barText = self.tr(barText) progressMessageBar = self.iface.messageBar().createMessage( barText, '0/' + str(countLayers)) progress = QProgressBar() progress.setMaximum(countLayers) progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) progressMessageBar.layout().addWidget(progress) return progressMessageBar, progress
class ForgotPasswordUi(BaseWindow, QtGui.QMainWindow): requestSendingCompleted = QtCore.pyqtSignal() def __init__(self, parent=None): super(ForgotPasswordUi, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.forgot.clicked.connect(self.forgot) self.ui.forgot.setDefault(True) self.shortcut = QtGui.QShortcut(QtGui.QKeySequence("Return"), self) self.shortcut.activated.connect(self.forgot) self.shortcut2 = QtGui.QShortcut(QtGui.QKeySequence("Up"), self) self.shortcut2.activated.connect(self.focusUp) self.shortcut2 = QtGui.QShortcut(QtGui.QKeySequence("Down"), self) self.shortcut2.activated.connect(self.focusDown) self.progressIndicator = QProgressBar(self.ui.statusBar) self.progressIndicator.setMinimumHeight(5) self.progressIndicator.setVisible(False) self.progressIndicator.setMaximum(0) self.progressIndicator.setMinimum(0) self.ui.statusBar.addWidget(self.progressIndicator) self.requestSendingCompleted.connect(self.requestSendingCompleteSlot) self.uiTranslate() def uiTranslate(self): self.setWindowTitle(strings["forgotPasswordWindowTitle"]) self.ui.username.setPlaceholderText(strings["usernameBoxHint"]) self.ui.email.setPlaceholderText(strings["emailBoxHint"]) self.ui.forgot.setText(strings["forgotPasswordButtonText"]) def requestSendingCompleteSlot(self): self.progressIndicator.setVisible(False) self.showMessageBox.emit(strings["forgotSuccessText"]) def focusUp(self): self.ui.username.setFocus() def focusDown(self): self.ui.email.setFocus() def forgot(self): self.progressIndicator.setVisible(True) def requestSenderThread(): if self.ui.username.text() and self.ui.email.text(): try: requestRecovery(self.ui.username.text(), self.ui.email.text()) self.requestSendingCompleted.emit() except SecureMessagingException as error: self.showMessageBox.emit(strings["errorText"] + responseTranslations[str(error)]) else: self.showMessageBox.emit(strings["missingFieldsErrorText"]) Thread(target=requestSenderThread).start()
def executar(self): progressMessageBar = self.iface.messageBar().createMessage( u'ECO Downloader', u' Baixando Dados... Isso poderá levar alguns minutos.') progress = QProgressBar() progress.setMaximum(len(self.estacoes)) progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) progressMessageBar.layout().addWidget(progress) self.iface.messageBar().pushWidget(progressMessageBar, self.iface.messageBar().INFO) opcao = self.opcao if opcao == 1: post_data = {'cboTipoReg': '10'} # para chuvas elif opcao == 2: post_data = {'cboTipoReg': '8'} # para cotas elif opcao == 3: post_data = {'cboTipoReg': '9'} # para vazões elif opcao == 4: post_data = {'cboTipoReg': '12'} # qualidade da água elif opcao == 5: post_data = {'cboTipoReg': '13'} # resumo de descarga elif opcao == 6: post_data = {'cboTipoReg': '16'} # perfil transversal contagem = 0 for idx, est in enumerate(self.estacoes): time.sleep(1) progress.setValue(idx + 1) try: print '** %s ** - Procurando dados...' % (est, ) r = requests.post(self.montar_url_estacao(est), data=post_data) link = self.obter_link_arquivo(r) self.salvar_arquivo_texto(est, link) print u'** %s ** (Concluído)' % (est, ) contagem += 1 except: print u'** %s ** - ERRO: Estacão não possui dados ou verifique sua conexão e tente novamente.\n' % ( est, ) contagem = str(contagem) nEstacoes = str(len(self.estacoes)) self.iface.messageBar().clearWidgets() self.iface.messageBar().pushInfo( u'ECO Downloader', contagem + u' das ' + nEstacoes + u' estações selecionadas foram baixadas com sucesso.')
def launch(self): progressMessageBar = self.iface.messageBar().createMessage("Obteniendo informacion del catastro... ") progress = QProgressBar() progress.setMaximum(0) progress.setMinimum(0) progress.setAlignment(Qt.AlignLeft|Qt.AlignVCenter) progressMessageBar.layout().addWidget(progress) self.iface.messageBar().pushWidget(progressMessageBar, self.iface.messageBar().INFO) self.parcelaService.procDone.connect(self.callback) self.parcelaService.start()
def export_features(self): """ Exportiert die Datenbanklayer als ESRI-Shapefile :return: """ directory = QFileDialog.getExistingDirectory() if not directory: return # Abfrage, ob Daten überschrieben werden sollen, wenn Verzeichnis nicht leer override = True if os.listdir(directory): reply = self.raise_message("dir_not_empty") if reply == QMessageBox.Yes: pass else: override = False # Verzeichnis leer oder override = True if override: # progress bar QgsMessageLog.logMessage("Exportiere nach " + directory, "KKG Plugin", QgsMessageLog.INFO) layers = QgsMapLayerRegistry.instance().mapLayers().values() progress_message_bar = self.iface.messageBar().createMessage("Exportiere...") progress = QProgressBar() progress.setMaximum(len(layers)) progress.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) progress_message_bar.layout().addWidget(progress) self.iface.messageBar().pushWidget(progress_message_bar, self.iface.messageBar().INFO) # current extent extent = self.iface.mapCanvas().extent() for i in range(0, len(layers)): layer = layers[i] file_path = directory + "\\" + layer.name() errors = QgsVectorFileWriter.writeAsVectorFormat(layer, file_path, "UTF-8", None, "ESRI Shapefile", filterExtent=extent, symbologyExport=QgsVectorFileWriter.NoSymbology) if errors: QgsMessageLog.logMessage(layer.name() + " konnte nicht geschrieben werden.", "KKG Plugin", QgsMessageLog.WARNING) else: QgsMessageLog.logMessage(layer.name() + " erfolgreich geschrieben", "KKG Plugin", QgsMessageLog.INFO) progress.setValue(i + 1) self.iface.messageBar().clearWidgets() QgsMessageLog.logMessage("Export abgeschlossen", "KKG Plugin", QgsMessageLog.INFO) self._create_project_from_export(directory)
class AddUserGui(BaseWindow): addUserCompleted = QtCore.pyqtSignal() def __init__(self, parent=None): super(AddUserGui, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.adduser.clicked.connect(self.adduser) self.progressIndicator = QProgressBar(self.ui.statusBar) self.progressIndicator.setMinimumHeight(5) self.progressIndicator.setVisible(False) self.progressIndicator.setMaximum(0) self.progressIndicator.setMinimum(0) self.ui.statusBar.addWidget(self.progressIndicator) self.addUserCompleted.connect(self.addUserCompletedSlot) self.uiTranslate() def uiTranslate(self): self.setWindowTitle(strings["registerUserWindowTitle"]) self.ui.username.setPlaceholderText(strings["usernameBoxHint"]) self.ui.password.setPlaceholderText(strings["passwordBoxHint"]) self.ui.email.setPlaceholderText(strings["emailBoxHint"]) self.ui.confirm.setPlaceholderText(strings["confirmPasswordBoxHint"]) self.ui.adduser.setText(strings["registerUserButtonText"]) def addUserCompletedSlot(self): self.progressIndicator.setVisible(False) self.showMessageBox.emit(strings["registrationSuccessText"]) def adduser(self): self.progressIndicator.setVisible(True) def addUserThread(): name = self.ui.username.text() password = self.ui.password.text() confirm = self.ui.confirm.text() email = self.ui.email.text() if name == "" or password == "" or email == "": self.showMessageBox.emit(strings["missingFieldsErrorText"]) return if password != confirm: self.showMessageBox.emit(strings["passwordsDontMatchErrorText"]) return try: addUser(name, email, password) self.addUserCompleted.emit() except SecureMessagingException as error: self.showMessageBox.emit(strings["errorText"] + responseTranslations[str(error)]) return Thread(target=addUserThread).start()
class AsyncProgressDialog(QDialog): """ dialog with progress bar to be shown during the asynchronous process """ def __init__(self, parent=None): super(AsyncProgressDialog, self).__init__(parent) self.setFixedSize(300, 40) self.setLayout(QBoxLayout(QBoxLayout.TopToBottom, self)) self.progress_bar = QProgressBar(self) self.progress_bar.setFixedSize(280, 20) self.progress_bar.setMinimum(0) self.progress_bar.setMaximum(10) self.progress_bar.setTextVisible(False) self.layout().addWidget(self.progress_bar)
class QtProgressBar(QtControl, ProxyProgressBar): """ A Qt implementation of an Enaml ProxyProgressBar. """ #: A reference to the widget created by the proxy. widget = Typed(QProgressBar) #-------------------------------------------------------------------------- # Initialization API #-------------------------------------------------------------------------- def create_widget(self): """ Create the underlying progress bar widget. """ self.widget = QProgressBar(self.parent_widget()) def init_widget(self): """ Create and initialize the underlying widget. """ super(QtProgressBar, self).init_widget() d = self.declaration self.set_minimum(d.minimum) self.set_maximum(d.maximum) self.set_value(d.value) self.set_text_visible(d.text_visible) #-------------------------------------------------------------------------- # ProxyProgressBar API #-------------------------------------------------------------------------- def set_minimum(self, value): """ Set the minimum value of the widget. """ self.widget.setMinimum(value) def set_maximum(self, value): """ Set the maximum value of the widget. """ self.widget.setMaximum(value) def set_value(self, value): """ Set the value of the widget. """ self.widget.setValue(value) def set_text_visible(self, visible): """ Set the text visibility on the widget. """ self.widget.setTextVisible(visible)
def ProgresBar(self): progressMessageBar = iface.messageBar().createMessage( "Doing something boring...") progress = QProgressBar() progress.setMaximum(10) progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) progressMessageBar.layout().addWidget(progress) iface.messageBar().pushWidget(progressMessageBar, iface.messageBar().INFO) for i in range(10): time.sleep(0.2) progress.setValue(i + 1) iface.messageBar().clearWidgets()
def _launchImport(self): ''' Launch the import ''' if not self._validateMapping(): return self.close() # Progress bar + message progressMessageBar = PagLuxembourg.main.qgis_interface.messageBar().createMessage(QCoreApplication.translate('ImportDxfDialog','Importing DXF')) progress = QProgressBar() progress.setMaximum(self._getEnabledLayerMappingCount()) progress.setAlignment(Qt.AlignLeft|Qt.AlignVCenter) progressMessageBar.layout().addWidget(progress) progress2 = QProgressBar() progress2.setMaximum(self.dxflayer_points.featureCount() + self.dxflayer_linestrings.featureCount() + self.dxflayer_polygons.featureCount()) progress2.setAlignment(Qt.AlignLeft|Qt.AlignVCenter) progressMessageBar.layout().addWidget(progress2) PagLuxembourg.main.qgis_interface.messageBar().pushWidget(progressMessageBar, QgsMessageBar.INFO) # Start import session self._startImportSession() for layer_mapping in self.mapping.layerMappings(): # Skip if not enabled if not layer_mapping.isEnabled(): continue # Progression message progressMessageBar.setText(QCoreApplication.translate('ImportDxfDialog','Importing {}').format(layer_mapping.sourceLayerName())) # QGIS layer qgis_layer = self._getQgisLayerFromTableName(layer_mapping.destinationLayerName()) layer_indexmapping = layer_mapping.asIndexFieldMappings(qgis_layer.dataProvider().fields()) progress2.setValue(0) # Import features according to geometry type if qgis_layer.geometryType() == QGis.Point: self._importLayer(self.dxflayer_points, qgis_layer, layer_indexmapping, progress2) elif qgis_layer.geometryType() == QGis.Line: self._importLayer(self.dxflayer_linestrings, qgis_layer, layer_indexmapping, progress2) elif qgis_layer.geometryType() == QGis.Polygon: self._importLayer(self.dxflayer_linestrings, qgis_layer, layer_indexmapping, progress2) self._importLayer(self.dxflayer_polygons, qgis_layer, layer_indexmapping, progress2) # Commit import session self._commitImport()
def createProgressbar(self, loopnumber): """ Create a progress bar when iterating over features """ progressMessageBar = self.messageBar.createMessage( unicode("Chargement des données...", "utf-8")) progress = QProgressBar() progress.setMinimum(0) progress.setMaximum(loopnumber) progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) progressMessageBar.layout().addWidget(progress) self.messageBar.pushWidget(progressMessageBar, self.messageBar.INFO) return progress
def _set_progressbar(self): """Set QGIS progress bar and display progress """ progressMessageBar = self.iface.messageBar().createMessage(self.tr("Zpracovávám objekty".decode("utf-8"))) progress = QProgressBar() progress.setMaximum(100) progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) progressMessageBar.layout().addWidget(progress) self.iface.messageBar().pushWidget( progressMessageBar, self.iface.messageBar().INFO) progress.setValue(2) return progress
def __init__(self, iface, provincia,municipio,x,y,callback): #super(Ui_ProgressDialog, self).__init__(parent) self.thread = ParcelaService(provincia,municipio) self.thread.initCoords(x,y) self.iface = iface progressMessageBar = iface.messageBar().createMessage("Obteniendo informacion del catastro... ") progress = QProgressBar() progress.setMaximum(0) progress.setMinimum(0) progress.setAlignment(Qt.AlignLeft|Qt.AlignVCenter) progressMessageBar.layout().addWidget(progress) iface.messageBar().pushWidget(progressMessageBar, iface.messageBar().INFO) self.thread.procDone.connect(self.fin) self.thread.start()
def OeQ_push_progressbar(title='Be patient!', message='Background calculations are going on...', timeout=0, maxcount=100): widget = iface.messageBar().createMessage(title, message) # set a new message bar progressbarwidget = QProgressBar() progressbarwidget.setAlignment(Qt.AlignLeft) progressbarwidget.setMaximum(maxcount) progressbarwidget.setValue(0) widget.layout().addWidget(progressbarwidget) # pass the progress bar to the message Bar baritem=iface.messageBar().pushWidget(widget, iface.messageBar().INFO) OeQ_unlockQgis() #print "THIS PRINTLN IS NECESSARY TO TRIGGER THE MESSAGEBAR" return {'widget':progressbarwidget,'baritem':baritem}
def processToa(self): """Converts DN to TOA reflectance""" startTime = time.time() if self.dlg.cbOutput.isChecked() and os.path.exists(self.dlg.leOutput.text()): outputPath = self.dlg.leOutput.text() else: outputPath = os.path.dirname(self.dlg.leInput.text().split(',')[0]) if self.dlg.rbRefNorm.isChecked(): bitcode = '32' outname = '_refToa32.tif' elif self.dlg.rbRefMilli.isChecked(): bitcode = '16' outname = '_refToa16.tif' progressMessageBar = self.iface.messageBar().createMessage("DN to TOA conversion...") progress = QProgressBar() progress.setMaximum(100) progress.setAlignment(Qt.AlignLeft|Qt.AlignVCenter) progress.setTextVisible(False) label = QLabel() label.setText(' {0}%'.format(0)) progressMessageBar.layout().addWidget(label) progressMessageBar.layout().addWidget(progress) self.iface.messageBar().pushWidget(progressMessageBar, self.iface.messageBar().INFO) if self.dlg.comboBox.currentIndex() == 0: bandList = self.dlg.leInput.text().split(',') idBand = {int(os.path.splitext(os.path.basename(i))[0][-1])-1:i for i in bandList} for band in idBand.keys(): self.imgfile = idBand[band] nbBand = band self.history(outputPath, outname) for i in self.meta.dnToToa(self.imgfile, outname=outname, bitcode=bitcode, outpath=outputPath, nbBand=nbBand): progress.setValue(i) label.setText('{0}%'.format(i)) else: self.imgfile = self.dlg.leInput.text().split(',')[0] self.history(outputPath, outname) for i in self.meta.dnToToa(self.imgfile, outname=outname, bitcode=bitcode, outpath=outputPath): progress.setValue(i) label.setText('{0}%'.format(i)) self.iface.messageBar().clearWidgets() self.bar.pushMessage("Image processed !", level=QgsMessageBar.INFO, duration=3) endTime = time.time() self.dlg.teHistory.append('<b>reflectance processing duration:</b><br>{0} seconds<br>'.format(str(endTime - startTime)))
class ProgressDialog(QDialog): """ Progress dialog """ def __init__(self, dialogName, parent=None): """ Constructor @param dialogName: @type dialogName: @param parent: @type parent: """ QDialog.__init__(self, parent) self.setWindowIcon(QIcon(":/main.png")) self.name = dialogName self.createDialog() def createDialog(self): """ Create qt dialog """ self.setWindowTitle("%s" % self.name) layout = QVBoxLayout() self.loadingLabel = QLabel("Loading...") self.imageLabel = QLabel() layout2 = QHBoxLayout() layout2.addWidget(self.imageLabel) layout2.addWidget(self.loadingLabel) self.progressBar = QProgressBar(self) self.progressBar.setMaximum(0) self.progressBar.setProperty("value", 0) self.progressBar.setAlignment(Qt.AlignCenter) self.progressBar.setObjectName("progressBar") layout.addLayout(layout2) layout.addWidget(self.progressBar) self.setLayout(layout) flags = Qt.WindowFlags() flags |= Qt.MSWindowsFixedSizeDialogHint self.setWindowFlags(flags)
class MessageBarProgress: def __init__(self, algname=None): self.msg = [] self.progressMessageBar = \ iface.messageBar().createMessage(self.tr('Executing algorithm <i>{0}</i>'.format(algname if algname else ''))) self.progress = QProgressBar() self.progress.setMaximum(100) self.progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self.progressMessageBar.layout().addWidget(self.progress) iface.messageBar().pushWidget(self.progressMessageBar, iface.messageBar().INFO) def error(self, msg): self.msg.append(msg) def setText(self, text): pass def setPercentage(self, i): self.progress.setValue(i) def setInfo(self, _): pass def setCommand(self, _): pass def setDebugInfo(self, _): pass def setConsoleInfo(self, _): pass def close(self): if self.msg: dlg = MessageDialog() dlg.setTitle( QCoreApplication.translate('MessageBarProgress', 'Problem executing algorithm')) dlg.setMessage("<br>".join(self.msg)) dlg.exec_() iface.messageBar().clearWidgets() def tr(self, string, context=''): if context == '': context = 'MessageBarProgress' return QCoreApplication.translate(context, string)
class MessageBarProgress: def __init__(self, algname=None): self.msg = [] self.progressMessageBar = \ iface.messageBar().createMessage(self.tr('Executing algorithm <i>{0}</i>'.format(algname if algname else ''))) self.progress = QProgressBar() self.progress.setMaximum(100) self.progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self.progressMessageBar.layout().addWidget(self.progress) iface.messageBar().pushWidget(self.progressMessageBar, iface.messageBar().INFO) def error(self, msg): self.msg.append(msg) def setText(self, text): pass def setPercentage(self, i): self.progress.setValue(i) def setInfo(self, _): pass def setCommand(self, _): pass def setDebugInfo(self, _): pass def setConsoleInfo(self, _): pass def close(self): if self.msg: dlg = MessageDialog() dlg.setTitle(QCoreApplication.translate('MessageBarProgress', 'Problem executing algorithm')) dlg.setMessage("<br>".join(self.msg)) dlg.exec_() iface.messageBar().clearWidgets() def tr(self, string, context=''): if context == '': context = 'MessageBarProgress' return QCoreApplication.translate(context, string)
def _progress_bar_factory_function(self, window_parent, editor, *args, **kwargs): """ Returns a QProgressBar widget for a TraitsUI window. Used by CustomEditor(factory=_progress_bar_factory_function, args=('tuple',) Can't just return self.progress_bar one should be should be created here and then set. window_parent = <PyQt4.QtGui.QBoxLayout object at ...> editor = <traitsui.qt4.custom_editor.CustomEditor object at ...> """ progress_bar = QProgressBar() progress_bar.setMinimum(self.min) progress_bar.setMaximum(self.max) self.progress_bar = progress_bar return progress_bar
def run(self): """Create the output shapefile.""" gpsStatus = self.checkGpsStatus() if gpsStatus: pass #QMessageBox.warning(None, "Test", "Create GPS SHP") elif gpsStatus == None: QMessageBox.warning(None, "Verzeichnis", u"Es wurde kein Bildverzeichnis für diesen Film gefunden.") return else: QMessageBox.warning(None, "Bilder", u"Die vorhandenen Bilder enthalten keine GPS Information.") return check = QFile(self.shpFile) if check.exists(): if not QgsVectorFileWriter.deleteShapeFile(self.shpFile): msg = 'Unable to delete existing shapefile "{}"' self.iface.messageBar().pushMessage(u"Error", u"Die Datei existiert bereits und kann nicht überschrieben werden (Eventuell in QGIS geladen!).", level=QgsMessageBar.CRITICAL, duration=10) return False #fields fields = QgsFields() fields.append(QgsField("bildnr", QVariant.Int)) fields.append(QgsField("lat", QVariant.Double)) fields.append(QgsField("lon", QVariant.Double)) fields.append(QgsField("alt", QVariant.Double)) writer = QgsVectorFileWriter(str(self.shpFile), "UTF-8", fields, QGis.WKBPoint, QgsCoordinateReferenceSystem(4326, QgsCoordinateReferenceSystem.EpsgCrsId)) mb = self.iface.messageBar().createMessage(u"EXIF", u"Die EXIF Daten (Geo Koordinaten und Höhe) werden aus den Bildern ausgelesen") progress = QProgressBar() progress.setMinimum(0) progress.setMaximum(0) progress.setAlignment(Qt.AlignLeft|Qt.AlignVCenter) mb.layout().addWidget(progress) self.iface.messageBar().pushWidget(mb, QgsMessageBar.INFO) for feature in self.iter_points(): writer.addFeature(feature) del writer self.iface.messageBar().clearWidgets() self.iface.messageBar().pushMessage(u"EXIF", u"Die Shape Datei wurde erfolgreich erstellt und in QGIS geladen!", level=QgsMessageBar.SUCCESS, duration=10) return self.shpFile
def processRouteOptimization(self): """This function manages the progressBar """ iface.messageBar().clearWidgets() progressMessageBar = iface.messageBar() progress = QProgressBar() progress.setMaximum(100) progressMessageBar.pushWidget(progress) waypointsLayer = QgsMapLayerRegistry.instance().mapLayersByName( self.waypointsLayerComboBox.currentText())[0] try: ok, message = inputs_checker.check_layers( self.finder.dtm["layer"], waypointsLayer, self.finder.exclusion_areas["layer"]) if not ok: raise ValueError(message) waypoints = af.waypoints_list(waypointsLayer) for idx, point_coords in enumerate(waypoints): def updateProgress(value): progress.setValue(max(0, float(value)/(len(waypoints)-1) + (idx-1)*100.0/(len(waypoints)-1))) progress.repaint() self.finder.optimizer.progress_callback = updateProgress self.finder.add_segment_to(point_coords) for _ in range(10): QgsApplication.instance().processEvents() self.finder.raw_layer.triggerRepaint() self.iface.mapCanvas().refresh() for _ in range(10): QgsApplication.instance().processEvents() except ValueError as e: self.showMessageBox(unicode(e), u"Error del optimizador") self.showMessageBar( u"Forest Road Designer: ha fallado la optimización", u"Error", QgsMessageBar.WARNING) return False return True
def OeQ_push_progressbar(title='Be patient!', message='Background calculations are going on...', timeout=0, maxcount=100): widget = iface.messageBar().createMessage(title, message) # set a new message bar progressbarwidget = QProgressBar() progressbarwidget.setAlignment(Qt.AlignLeft) progressbarwidget.setMaximum(maxcount) progressbarwidget.setValue(0) widget.layout().addWidget(progressbarwidget) # pass the progress bar to the message Bar baritem = iface.messageBar().pushWidget(widget, iface.messageBar().INFO) OeQ_unlockQgis() #print "THIS PRINTLN IS NECESSARY TO TRIGGER THE MESSAGEBAR" return {'widget': progressbarwidget, 'baritem': baritem}
def progress_dialog(progress=0, title='CQFS Progress', label='Running...'): dialog = QProgressDialog() dialog.setWindowTitle(title) dialog.setLabelText(label) dialog.setAutoClose(True) bar = QProgressBar(dialog) bar.setTextVisible(True) bar.setValue(progress) bar.setMaximum(100) dialog.setBar(bar) dialog.setMinimumWidth(300) dialog.show() if int(progress) == 0: bar.setValue(0) return dialog, bar
def processAlgorithm(self, progress): """Here is where the processing itself takes place.""" INPUT_RASTER = self.getParameterValue(self.INPUT_RASTER) OUTPUT_RASTER = self.getOutputValue(self.OUTPUT_RASTER) MEDIAN_ITER = self.getParameterValue(self.MEDIAN_ITER) MEDIAN_SIZE = self.getParameterValue(self.MEDIAN_SIZE) # First we create the output layer. The output value entered by # the user is a string containing a filename, so we can use it # directly from scipy import ndimage data, im = dataraster.open_data_band(INPUT_RASTER) # get proj,geo and dimension (d) from data proj = data.GetProjection() geo = data.GetGeoTransform() d = data.RasterCount # add progress bar # And now we can process from PyQt4.QtGui import QProgressBar pb = QProgressBar() pb.setMaximum(d * MEDIAN_ITER) pbNow = 0 outFile = dataraster.create_empty_tiff(OUTPUT_RASTER, im, d, geo, proj) for i in range(d): # Read data from the right band pbNow += 1 pb.setValue(pbNow) tempBand = data.GetRasterBand(i + 1).ReadAsArray() tempBand = ndimage.filters.median_filter(tempBand, size=(MEDIAN_SIZE, MEDIAN_SIZE)) # Save bandand outFile out = outFile.GetRasterBand(i + 1) out.WriteArray(tempBand) out.FlushCache() tempBand = None
def load(self, reader): """Load LOG file using specified reader. SafecastReaderError is raised on failure. :param reader: reader class used for reading input data """ if self._loaded: return # data already loaded # store metadata self._metadata = { 'format': reader.format_version, 'deadtime': reader.deadtime } # create progress bar widget progressMessageBar = iface.messageBar().createMessage(self.tr("Loading data...")) progress = QProgressBar() progress.setMaximum(100) progressMessageBar.layout().addWidget(progress) iface.messageBar().pushWidget(progressMessageBar, iface.messageBar().INFO) # load items as new point features (inform user about progress) i = 0 count = reader.count() start = time.clock() for f in reader: self._process_row(f) # add features to the map layer i += 1 if i % 100 == 0: percent = i / float(count) * 100 progress.setValue(percent) endtime = time.clock() - start progress.setValue(100) iface.messageBar().clearWidgets() # inform user about successfull import iface.messageBar().pushMessage(self.tr("Info"), self.tr("{} features loaded (in {:.2f} sec).").format(count, endtime), level=QgsMessageBar.INFO, duration=3) # data loaded (avoid multiple imports) self._loaded = True
def __init__(self, parent): QProgressBar.__init__(self, parent) self.fLeftClickDown = False self.fMinimum = 0.0 self.fMaximum = 1.0 self.fRealValue = 0.0 self.fLabel = "" self.fPreLabel = " " self.fTextCall = None self.setFormat("(none)") # Fake internal value, 10'000 precision QProgressBar.setMinimum(self, 0) QProgressBar.setMaximum(self, 10000) QProgressBar.setValue(self, 0)
def _draw_transfer_item(self, container, filename, id, part_number, peer_ip, percent): items_found = container.findItems(id, Qt.MatchExactly, 1) item = None if len(items_found) > 0: for i in items_found: if i.text(4) == peer_ip and i.text(2) == str(part_number): item = i break if item: container.itemWidget(item, 3).setValue(percent) else: item = QTreeWidgetItem(container, QStringList([str(filename), str(id), str(part_number), "0", str(peer_ip)])) progress_bar = QProgressBar() progress_bar.setMinimum(0) progress_bar.setMaximum(100) progress_bar.setValue(percent) container.setItemWidget(item, 3, progress_bar)
class MessageBarProgress: def __init__(self): self.progressMessageBar = \ iface.messageBar().createMessage(self.tr('Executing algorithm')) self.progress = QProgressBar() self.progress.setMaximum(100) self.progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self.progressMessageBar.layout().addWidget(self.progress) iface.messageBar().pushWidget(self.progressMessageBar, iface.messageBar().INFO) def error(self, msg): iface.messageBar().clearWidgets() iface.messageBar().pushMessage(self.tr('Error'), msg, level=QgsMessageBar.CRITICAL, duration=3) def setText(self, text): pass def setPercentage(self, i): self.progress.setValue(i) def setInfo(self, _): pass def setCommand(self, _): pass def setDebugInfo(self, _): pass def setConsoleInfo(self, _): pass def close(self): iface.messageBar().clearWidgets() def tr(self, string, context=''): if context == '': context = 'MessageBarProgress' return QCoreApplication.translate(context, string)
def __init__(self,inMsg=' Loading...',inMaxStep=1): # initialize progressBar """ """# Save reference to the QGIS interface QApplication.processEvents() # Help to keep UI alive widget = iface.messageBar().createMessage('Please wait ',inMsg) prgBar = QProgressBar() self.prgBar=prgBar self.iface=iface widget.layout().addWidget(self.prgBar) iface.messageBar().pushWidget(widget, iface.messageBar().WARNING) QApplication.setOverrideCursor(QtCore.Qt.WaitCursor) # if Max 0 and value 0, no progressBar, only cursor loading # default is set to 0 prgBar.setValue(1) # set Maximum for progressBar prgBar.setMaximum(inMaxStep)
def CRC_Calculation(byteArray): numArray = [0, 2577006594, 2553349383, 27985157, 2607222541, 50138895, 55970314, 2597063176, 2647333657, 72424219, 100277790, 2623544860, 111940628, 2671121430, 2661093651, 117903633, 2425566001, 151597875, 144848438, 2436380212, 200555580, 2456697918, 2479175995, 174012729, 223881256, 2495752234, 2506698031, 217263405, 2520721189, 262481703, 235807266, 2543067680, 2317575009, 330916707, 303195750, 2340972132, 289696876, 2296278126, 2306173291, 284125545, 401111160, 2389866618, 2413395327, 373521789, 2358212469, 353728375, 348025458, 2367976048, 447762512, 2200588370, 2189514071, 454776149, 2178375517, 407723871, 434526810, 2155633240, 2273004361, 518081355, 524963406, 2261798476, 471614532, 2240169030, 2217558339, 498549057, 3208889281, 651805635, 661833414, 3202926276, 606391500, 3183398094, 3155544523, 630180297, 579393752, 3138574554, 3132743135, 589553117, 3119503317, 544593879, 568251090, 3091518160, 802222320, 3058364658, 3085039095, 779875829, 3031957501, 757989375, 747043578, 3038575352, 2988174313, 729934827, 707456750, 3014717164, 696050916, 2967921894, 2974671331, 685236705, 895525024, 2902106274, 2907809191, 885761445, 2919739309, 933081007, 909552298, 2947328680, 2829827001, 825342907, 815447742, 2835398332, 869053620, 2857809078, 2885530035, 845656497, 2784203665, 1013552019, 1036162710, 2757269140, 1049926812, 2802752670, 2795870619, 1061132697, 943229064, 2711783562, 2684980623, 965971341, 2740946821, 986023815, 997098114, 2733933184, 3582100097, 1276674691, 1303611270, 3559491460, 1323666828, 3615460750, 3604252811, 1330546825, 1212783000, 3520305562, 3497565343, 1239587997, 3543045781, 1253349015, 1260360594, 3531969424, 1158787504, 3700142514, 3709908151, 1153086645, 3732324029, 1206697663, 1179106234, 3755850680, 3638209193, 1094757035, 1089187758, 3648106412, 1136502180, 3660031398, 3683426467, 1108779169, 1604444640, 3325813218, 3348161767, 1577772261, 3301371629, 1566371567, 1559751658, 3312315368, 3261790969, 1542519547, 1515978750, 3284271100, 1494087156, 3231184374, 3241996531, 1487335665, 3476214481, 1453904595, 1459869654, 3466188756, 1414913500, 3452952030, 3429161179, 1442765017, 1392101832, 3412314570, 3402157263, 1397935309, 3382625989, 1342490311, 1370473410, 3358966720, 1791050048, 4082843970, 4075832391, 1802126405, 4054208077, 1748782671, 1771522890, 4027403080, 4144650841, 1854954075, 1866162014, 4137770844, 1819104596, 4126627158, 4099690579, 1841713233, 4199707249, 1674080883, 1650685814, 4227430260, 1630895484, 4172250494, 4177819771, 1620998265, 1738107240, 4261636458, 4289227887, 1714580589, 4244530789, 1701078631, 1691312994, 4250231648, 3772916257, 2037916195, 2027104038, 3779667748, 2072325420, 3793693998, 3820234795, 2049845289, 2099853624, 3836950842, 3843570751, 2088909885, 3863885365, 2144613943, 2122265394, 3890557744, 1886458128, 3924496658, 3896513559, 1910117397, 3944095261, 1921785375, 1931942682, 3938261784, 3988392457, 1948256779, 1972047630, 3960540940, 1994196228, 4014408966, 4008443907, 2004221953] num = 0 j = 0 progressMessageBar = define._messagBar.createMessage("Reading the file ...") progress = QProgressBar() progress.setAlignment(Qt.AlignLeft|Qt.AlignVCenter) progressMessageBar.layout().addWidget(progress) define._messagBar.pushWidget(progressMessageBar, define._messagBar.INFO) maxium = len(byteArray) progress.setMaximum(maxium) progress.setValue(0) for i in range(len(byteArray)): byte0 = None if isinstance(byteArray, bytearray): byte0 = Type.ByteFunc.d2b(num ^ ord(chr(byteArray[i]))) else: byte0 = Type.ByteFunc.d2b(num ^ ord(byteArray[i])) num = num >> 8 num = num ^ numArray[ord(byte0) % 36] progress.setValue(i) QApplication.processEvents() progress.setValue(maxium) define._messagBar.hide() resultByteArray = bytearray(4) for i in range(4): resultByteArray[i] = '0' resultByteArray[0] = Type.ByteFunc.d2b(num) resultByteArray[1] = Type.ByteFunc.d2b(num >> 8) resultByteArray[2] = Type.ByteFunc.d2b(num >> 16) resultByteArray[3] = Type.ByteFunc.d2b(num >> 24) stringBuilder = StringBuilder() for i in range(4): stringBuilder.Append(hex(ord(chr(resultByteArray[i]))).replace("0x", "").upper()) return stringBuilder.ToString()
def syncstarted(self): # Remove the old widget if it's still there. # I don't really like this. Seems hacky. try: self.iface.messageBar().popWidget(self.syncwidget) except RuntimeError: pass except AttributeError: pass self.iface.messageBar().findChildren(QToolButton)[0].setVisible(False) self.syncwidget = self.iface.messageBar().createMessage("Syncing", "Sync in progress", QIcon(":/icons/syncing")) button = QPushButton(self.syncwidget) button.setCheckable(True) button.setText("Status") button.setIcon(QIcon(":/icons/syncinfo")) button.toggled.connect(functools.partial(self.report.setVisible)) pro = QProgressBar() pro.setMaximum(0) pro.setMinimum(0) self.syncwidget.layout().addWidget(pro) self.syncwidget.layout().addWidget(button) self.iface.messageBar().pushWidget(self.syncwidget, QgsMessageBar.INFO)
def _launchImport(self): ''' Launch the import ''' if not self._validateMapping(): return qgis_layer = self.qgislayers[self.cbbLayers.currentIndex()] self.close() # Progress bar + message progressMessageBar = PagLuxembourg.main.qgis_interface.messageBar( ).createMessage( QCoreApplication.translate('ImportShpDialog', 'Importing {}').format( self.shplayer.source())) progress = QProgressBar() progress.setMaximum(self.shplayer.featureCount()) progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) progressMessageBar.layout().addWidget(progress) PagLuxembourg.main.qgis_interface.messageBar().pushWidget( progressMessageBar, QgsMessageBar.INFO) # Start import session self._startImportSession() # Import the layer, and get the imported extent self._importLayer( self.shplayer, qgis_layer, self.mapping.asIndexFieldMappings( qgis_layer.dataProvider().fields(), self.shpfields), progress) # Commit import session self._commitImport()