def doTKSweep(self): for angle in self.settings["thzSweepPoints"]: if not self.ui.bStartSweep.isChecked(): break print "at angle", angle self.sigDoGui.emit(self.motorWid.ui.sbAngle.setValue, angle) self.motorWid.ui.bGo.clicked.emit(False) time.sleep(0.1) self.motorWid.thMoveMotor.wait() angleData = [] for i in range(self.settings["numAve"]): print "\t num", i waiter = QtCore.QEventLoop() self.scopeWid.ch1View.sigUpdateData.connect(waiter.exit) waiter.exec_() waveformData = self.scopeWid.ch1View.data.copy() try: angleData = np.column_stack((angleData, waveformData[:, 1])) except: angleData = waveformData[:, 1] tkVal = self.processTKWaveform(angleData.mean(axis=1)) print "\n\tmeasured {}\n\n".format(tkVal) self.settings["saveData"].append([angle, tkVal]) self.sigDoGui.emit(self.ui.bStartSweep.setChecked, False) self.saveData()
def viewFinal(Envir): app = QtCore.QEventLoop() window = Window() window.DoStuff(app, Envir) window.show() app.exec_() return window.ReturnVal
def showText(self): """ Creates a dialog to show the generated text output. """ try: generatedText = self.genText() except ValueError: return self.txtwin = QtGui.QDialog() self.txtedt = QtGui.QTextEdit() self.txtbtn = QtGui.QPushButton('OK') self.txtwin.layout = QtGui.QVBoxLayout(self.txtwin) self.txtwin.layout.addWidget(self.txtedt) self.txtwin.layout.addWidget(self.txtbtn) self.txtbtn.clicked.connect(self.txtwin.deleteLater) self.txtedt.setText(generatedText) self.txtedt.setReadOnly(True) self.txtwin.setWindowTitle('Resolution information') self.txtwin.setWindowModality(QtCore.Qt.ApplicationModal) self.txtwin.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.txtwin.setMinimumSize(400, 600) self.txtwin.resize(400, 600) self.txtwin.show() self.txtloop = QtCore.QEventLoop() self.txtloop.exec_()
def browseList(Text, List): MyEventLoop = QtCore.QEventLoop() window = Window() window.DoStuff(MyEventLoop, Text, List) window.show() MyEventLoop.exec_ () return window.ui.FINALANSWER
def closeEvent(self, ev): self.saveMailInfo() loop = QtCore.QEventLoop() self.thread.finished.connect(loop.quit) self.thread.quit() loop.exec_() QMainWindow.closeEvent(self, ev)
def run(self, installSignalHandlers=True): if self._ownApp: self._blockApp = self.qApp else: self._blockApp = QtCore.QEventLoop() self.runReturn() self._blockApp.exec_()
def onHelp(self): """ Shows the help page """ try: from pymantidplot.proxies import showCustomInterfaceHelp showCustomInterfaceHelp("PyChop") except ImportError: helpTxt = "PyChop is a tool to allow direct inelastic neutron\nscattering users to estimate the inelastic resolution\n" helpTxt += "and incident flux for a given spectrometer setting.\n\nFirst select the instrument, chopper settings and\n" helpTxt += "Ei, and then click 'Calculate and Plot'. Data for all\nthe graphs will be generated (may take 1-2s) and\n" helpTxt += "all graphs will be updated. If the 'Hold current plot'\ncheck box is ticked, additional settings will be\n" helpTxt += "overplotted on the existing graphs if they are\ndifferent from previous settings.\n\nMore in-depth help " helpTxt += "can be obtained from the\nMantid help pages." self.hlpwin = QtGui.QDialog() self.hlpedt = QtGui.QLabel(helpTxt) self.hlpbtn = QtGui.QPushButton('OK') self.hlpwin.layout = QtGui.QVBoxLayout(self.hlpwin) self.hlpwin.layout.addWidget(self.hlpedt) self.hlpwin.layout.addWidget(self.hlpbtn) self.hlpbtn.clicked.connect(self.hlpwin.deleteLater) self.hlpwin.setWindowTitle('Help') self.hlpwin.setWindowModality(QtCore.Qt.ApplicationModal) self.hlpwin.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.hlpwin.setMinimumSize(370, 300) self.hlpwin.resize(370, 300) self.hlpwin.show() self.hlploop = QtCore.QEventLoop() self.hlploop.exec_()
def viewCard(card): import sys MyEventLoop = QtCore.QEventLoop() window = Window() window.DoStuff(MyEventLoop, card) window.show() MyEventLoop.exec_()
def start(self): try: worker = RequestWorker(self.url, self.method, self.payload, self.headers) pause = QtCore.QEventLoop() worker.finished.connect(pause.quit) worker.successfully_finished.connect(self.save_resp) worker.error.connect(self.save_exception) start_worker( worker, iface, QtGui.QApplication.translate("LDMP", 'Contacting LDMP server...')) pause.exec_() if self.get_exception(): raise self.get_exception() except requests.exceptions.ConnectionError: log('API unable to access server - check internet connection') QtGui.QMessageBox.critical( None, QtGui.QApplication.translate("LDMP", "Error"), QtGui.QApplication.translate( "LDMP", "Unable to login to LDMP server. Check your internet connection." )) resp = None except requests.exceptions.Timeout: log('API unable to login - general error') QtGui.QMessageBox.critical( None, QtGui.QApplication.translate("LDMP", "Error"), QtGui.QApplication.translate( "LDMP", "Unable to connect to LDMP server.")) resp = None
def ViewRoller(): MyEventLoop = QtCore.QEventLoop() window2 = Window2() window2.DoStuff2(MyEventLoop) window2.show() MyEventLoop.exec_() return window2.ReturnVal
def __init__(self, application, dialogs): # We need the application to send posted events. We hold a reference # to any dialogs to ensure that they don't get garbage collected # (and thus close in the process). The reference count for this object # will go to zero when it removes itself from Houdini's event loop. self.application = application self.dialogs = dialogs self.event_loop = QtCore.QEventLoop()
def loadPage(url): page = QtWebKit.QWebPage() loop = QtCore.QEventLoop() # Create event loop page.mainFrame().loadFinished.connect( loop.quit) # Connect loadFinished to loop quit page.mainFrame().load(QtCore.QUrl(url)) loop.exec_() # Run event loop, it will end on loadFinished return page.mainFrame().toHtml()
def Combat(Player, MonsterList, DefeatedList, EvadedList, Env): MyEventLoop = QtCore.QEventLoop() window = Window() window.DoStuff(MyEventLoop, Player, MonsterList, DefeatedList, EvadedList, Env) window.show() MyEventLoop.exec_()
def qt4(): """PyOS_InputHook python hook for Qt4. Process pending Qt events and if there's no pending keyboard input, spend a short slice of time (50ms) running the Qt event loop. As a Python ctypes callback can't raise an exception, we catch the KeyboardInterrupt and temporarily deactivate the hook, which will let a *second* CTRL+C be processed normally and go back to a clean prompt line. """ try: allow_CTRL_C() app = QtCore.QCoreApplication.instance() if not app: app = QtGui.QApplication([" "]) app.processEvents(QtCore.QEventLoop.AllEvents, 300) if not stdin_ready(): # Generally a program would run QCoreApplication::exec() # from main() to enter and process the Qt event loop until # quit() or exit() is called and the program terminates. # # For our input hook integration, we need to repeatedly # enter and process the Qt event loop for only a short # amount of time (say 50ms) to ensure that Python stays # responsive to other user inputs. # # A naive approach would be to repeatedly call # QCoreApplication::exec(), using a timer to quit after a # short amount of time. Unfortunately, QCoreApplication # emits an aboutToQuit signal before stopping, which has # the undesirable effect of closing all modal windows. # # To work around this problem, we instead create a # QEventLoop and call QEventLoop::exec(). Other than # setting some state variables which do not seem to be # used anywhere, the only thing QCoreApplication adds is # the aboutToQuit signal which is precisely what we are # trying to avoid. timer = QtCore.QTimer() event_loop = QtCore.QEventLoop() timer.timeout.connect(event_loop.quit) while not stdin_ready(): timer.start(50) event_loop.exec_() timer.stop() except KeyboardInterrupt: print("\nKeyboardInterrupt - Press Enter for new prompt") except: # NO exceptions are allowed to escape from a ctypes callback ignore_CTRL_C() from traceback import print_exc print_exc() print("Got exception from inputhook, unregistering.") clear_inputhook() finally: allow_CTRL_C() return 0
def xmlConfigDl(self, device, file): """ Download configure .xml file to selected device Refresh details in local "Device Details" window """ # Obtain type of selected device and open correct window if device == None: # Display message window QApplication.restoreOverrideCursor() self.showdialog("None device selected") return # Local Device is type 1 elif device.type() == 1: if "DEV" in self.__selectedLocalDevice[0]: try: self.__ntd.do_lcfg(self.__selectedLocalDevice[0], file) except ValueError as e: QApplication.restoreOverrideCursor() self.showdialog(e.args[0]) return # time.sleep(5) # if self.scanLocal(): # print("reset", self.__selectedLocalDevice[2]) # self.reset(device) # Wait 2s until IP is changed loop = QtCore.QEventLoop() QtCore.QTimer.singleShot(1000, loop.quit) loop.exec_() self.scanLocal() return if device.type() == 2: parent = device.parent() # Obtain parent (local) device name "DEV-?" parentSplited = unicode(parent.text(0)).split(' ', 3) if "DEV" in parentSplited[0]: try: self.__ntd.do_rcfg( parentSplited[0], unicode(self.lineEditRemoteFifo0MacAddress.text()), file) except ValueError as e: QApplication.restoreOverrideCursor() self.showdialog(e.args[0]) return self.treeWidget.setCurrentItem(parent, True) print("current item", unicode(self.treeWidget.currentItem().text(0))) self.scanRemote() # self.treeWidget.setCurrentItem(parent, False) # print("device after xmlDl", device.text(0)) # self.treeWidget.setCurrentItem(parent.child(0), True) # self.treeWidget.setItemSelected(device, True) self.printInfo(parent)
def execute(func, message=None): ''' Executes a lengthy tasks in a separate thread and displays a waiting dialog if needed. Sets the cursor to wait cursor while the task is running. This function does not provide any support for progress indication :param func: The function to execute. :param message: The message to display in the wait dialog. If not passed, the dialog won't be shown ''' global _dialog cursor = QtGui.QApplication.overrideCursor() waitCursor = (cursor is not None and cursor.shape() == QtCore.Qt.WaitCursor) dialogCreated = False try: QtCore.QCoreApplication.processEvents() if not waitCursor: QtGui.QApplication.setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor)) if message is not None: t = ExecutorThread(func) loop = QtCore.QEventLoop() t.finished.connect(loop.exit, QtCore.Qt.QueuedConnection) if _dialog is None: dialogCreated = True _dialog = QtGui.QProgressDialog(message, "Running", 0, 0, iface.mainWindow()) _dialog.setWindowTitle("Running") _dialog.setWindowModality(QtCore.Qt.WindowModal) _dialog.setMinimumDuration(1000) _dialog.setMaximum(100) _dialog.setValue(0) _dialog.setMaximum(0) _dialog.setCancelButton(None) else: oldText = _dialog.labelText() _dialog.setLabelText(message) QtGui.QApplication.processEvents() t.start() loop.exec_(flags=QtCore.QEventLoop.ExcludeUserInputEvents) if t.exception is not None: raise t.exception return t.returnValue else: return func() finally: if message is not None: if dialogCreated: _dialog.reset() _dialog = None else: _dialog.setLabelText(oldText) if not waitCursor: QtGui.QApplication.restoreOverrideCursor() QtCore.QCoreApplication.processEvents()
def checkUrl(url): def setFinished(response): self.response = response loop.quit() loop = QtCore.QEventLoop() self.currentUrl = QtCore.QUrl(url) API_Catalog.isHostLive(self, setFinished) loop.exec_()
def ViewRoller(Type, Player, NumDice, Required, Diff): app = QtCore.QEventLoop() window = Window() window.DoStuff(app, Type, Player, NumDice, Required, Diff) window.show() app.exec_() if (window.AutoWin == 1): return 100 return window.ReturnVal
def pause(pauseTime): #pause time is in milliseconds loop = QtCore.QEventLoop() timer = QtCore.QTimer() #timer.setSingleShot(True) #timer.timeout.connect(loop.quit) #timer.start(pauseTime) timer.singleShot(pauseTime, loop.quit) loop.exec_()
def exec_(self, valor): if not self.cursor_: return None if not self.cursor_.isLocked(): self.cursor_.setModeAccess(FLSqlCursor.Edit) if self.loop or self.inExec_: print( "FLFormSearchDB::exec(): Se ha detectado una llamada recursiva" ) super(FLFormDB, self).show() if self.initFocusWidget_: self.initFocusWidget_.setFocus() return None self.load() #Extra self.inExec_ = True self.acceptingRejecting_ = False super(FLFormDB, self).show() if self.initFocusWidget_: self.initFocusWidget_.setFocus() if self.iface: try: timer1 = QtCore.QTimer(self) timer1.singleShot(300, self.iface.init) except Exception: pass if not self.isClosing_: timer2 = QtCore.QTimer(self) timer2.singleShot(0, self.emitFormReady) self.accepted_ = False self.loop = True self.eventloop = QtCore.QEventLoop() self.eventloop.exec_() #if not self.isClosing_ and not self.acceptingRejecting_: #QtCore.QEventLoop().enterLoop() FIXME self.loop = False #self.clearWFlags(WShowModal) FIXME v = None if self.accepted_ and valor: v = self.cursor_.valueBuffer(valor) else: v = None self.inExec_ = False return v
def run(self): loop = QtCore.QEventLoop() nm = QNetworkAccessManager() reply = nm.get(QNetworkRequest(self.url)) reply.finished.connect(loop.quit) loop.exec_() data = reply.readAll() self.resourceLoaded.emit(self.res_type, self.url, data) reply.deleteLater() nm.deleteLater()
def __init__(self, title, parent=None): QtGui.QProgressDialog.__init__(self, parent) self.nstep = 0 self.text = None self.oldprogress = 0 self.progress = 0 self.calls = 0 self.loop=QtCore.QEventLoop(self) self.setWindowTitle(title)
def javaScriptAlert(self, frame, msg): if self.toolBarLimit < 5: pause = QtCore.QEventLoop() tb = self.createAlertToolBar(frame, msg) self.alertToolBar.emit(tb) tb.button.clicked.connect(self.lowerToolBarLimit) tb.button.clicked.connect(pause.quit) pause.exec_() return else: return QtWebKit.QWebPage.javaScriptAlert(self, frame, msg)
def runAndWait(self, function, *args): """Funcao que executa outra funcao, passada como parametro, em uma thread separada""" eventLoop = QtCore.QEventLoop() eventThread = SimpleThread(function, *args) self.connect(eventThread, QtCore.SIGNAL("finished()"), eventLoop.quit) eventThread.start() eventLoop.exec_() return eventThread.result
def do_gevent(): """ Descript. can't call gevent.run inside inner event loops (message boxes...) """ if QtCore.QEventLoop(): try: gevent.wait(timeout=0.01) except AssertionError: pass else: # all that I tried with gevent here fails! => seg fault pass
def start(self): try: worker = DownloadWorker(self.url, self.outfile) pause = QtCore.QEventLoop() worker.finished.connect(pause.quit) worker.successfully_finished.connect(self.save_resp) worker.error.connect(self.save_exception) start_worker( worker, iface, QtGui.QApplication.translate("LDMP", 'Downloading {}').format( self.url.rsplit('/', 1)[-1])) pause.exec_() if self.get_exception(): raise self.get_exception() except requests.exceptions.ChunkedEncodingError: log("Download failed due to ChunkedEncodingError - likely a connection loss" ) QtGui.QMessageBox.critical( None, QtGui.QApplication.translate("LDMP", "Error"), QtGui.QApplication.translate( "LDMP", "Download failed. Check your internet connection.")) return False except requests.exceptions.ConnectionError: log("Download failed due to connection error") QtGui.QMessageBox.critical( None, QtGui.QApplication.translate("LDMP", "Error"), QtGui.QApplication.translate( "LDMP", "Unable to access internet. Check your internet connection." )) return False except requests.exceptions.Timeout: log('Download timed out') QtGui.QMessageBox.critical( None, QtGui.QApplication.translate("LDMP", "Error"), QtGui.QApplication.translate( "LDMP", "Download timed out. Check your internet connection.")) return False except DownloadError: log("Download failed - file size doesn't match expected") QtGui.QMessageBox.critical( None, QtGui.QApplication.translate("LDMP", "Error"), QtGui.QApplication.translate( "LDMP", "Download failed. Check your internet connection.")) return False return True
def accept(self): if not self.ship: return False if self.running: return self.save() draft = self.form.minDraft.value() drafts = [draft] dDraft = (self.form.maxDraft.value() - self.form.minDraft.value()) / (self.form.nDraft.value() - 1) for i in range(1, self.form.nDraft.value()): draft = draft + dDraft drafts.append(draft) # Compute data # Get external faces self.loop = QtCore.QEventLoop() self.timer = QtCore.QTimer() self.timer.setSingleShot(True) QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"), self.loop, QtCore.SLOT("quit()")) self.running = True faces = self.externalFaces(self.ship.Shape) if not self.running: return False if len(faces) == 0: msg = QtGui.QApplication.translate( "ship_console", "Can't detect external faces from ship object", None, QtGui.QApplication.UnicodeUTF8) App.Console.PrintError(msg + '\n') return False faces = Part.makeShell(faces) # Get hydrostatics msg = QtGui.QApplication.translate("ship_console", "Computing hydrostatics", None, QtGui.QApplication.UnicodeUTF8) App.Console.PrintMessage(msg + '...\n') points = [] for i in range(0, len(drafts)): App.Console.PrintMessage("\t%d / %d\n" % (i + 1, len(drafts))) draft = drafts[i] point = Tools.Point(self.ship, faces, draft, self.form.trim.value()) points.append(point) self.timer.start(0.0) self.loop.exec_() if (not self.running): break PlotAux.Plot(self.ship, self.form.trim.value(), points) return True
def __init__(self, flags=None, default=True): assert (not QtCore.QCoreApplication.startingUp()) self._loop = QtCore.QEventLoop() self._loop.default = default self.__callback_timers = {} self._signal_watchers = {} self._raised_signal = None self._child_watchers = {} self._loop.excepthook = functools.partial(self.handle_error, None) self._signal_notifier = QtCore.QSocketNotifier( _signal_rfd.fileno(), QtCore.QSocketNotifier.Read, self._loop) self._signal_notifier.activated.connect(self._handle_signal_in_loop) self._signal_notifier.setEnabled(True) self._watchers = set() self._sigchld_handle = None
def execute(command): global _dialog try: QtCore.QCoreApplication.processEvents() t = ExecutorThread(command) loop = QtCore.QEventLoop() t.finished.connect(loop.exit, QtCore.Qt.QueuedConnection) QtGui.QApplication.processEvents() t.start() loop.exec_(flags=QtCore.QEventLoop.ExcludeUserInputEvents) if t.exception is not None: raise t.exception return t.returnValue finally: QtCore.QCoreApplication.processEvents()
def execute(func, message=None): global _dialog cursor = QtGui.QApplication.overrideCursor() waitCursor = (cursor is not None and cursor.shape() == QtCore.Qt.WaitCursor) dialogCreated = False try: QtCore.QCoreApplication.processEvents() if not waitCursor: QtGui.QApplication.setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor)) useThread = config.getConfigValue(config.GENERAL, config.USE_THREAD) if message is not None and useThread: t = GeoGigThread(func) loop = QtCore.QEventLoop() t.finished.connect(loop.exit, QtCore.Qt.QueuedConnection) if _dialog is None: dialogCreated = True _dialog = QtGui.QProgressDialog(message, "GeoGig", 0, 0, config.iface.mainWindow()) _dialog.setWindowTitle("GeoGig") _dialog.setWindowModality(QtCore.Qt.WindowModal) _dialog.setMinimumDuration(1000) _dialog.setMaximum(100) _dialog.setValue(0) _dialog.setMaximum(0) _dialog.setCancelButton(None) else: oldText = _dialog.labelText() _dialog.setLabelText(message) QtGui.QApplication.processEvents() t.start() loop.exec_(flags=QtCore.QEventLoop.ExcludeUserInputEvents) if t.exception is not None: raise t.exception return t.returnValue else: return func() finally: if message is not None and useThread: if dialogCreated: _dialog.reset() _dialog = None else: _dialog.setLabelText(oldText) if not waitCursor: QtGui.QApplication.restoreOverrideCursor() QtCore.QCoreApplication.processEvents()