def _setup_loop(self): # if self.value is not None: self.timer = QTimer(self.control) self.timer.timeout.connect(self._update) print('fps', self.factory.fps) if self.factory.fps: self.timer.setInterval(1000 / self.factory.fps) self.timer.start()
def update(self, pt): if self.control and self._alive: self.value.request_redraw() # self.value.invalidate_and_redraw() st = time.time() et = time.time() - pt pt = st # print et # = time.time() # self.value.invalidate_and_redraw() QTimer.singleShot(max(1, self._get_interval() - et), lambda: self.update(pt))
def update(self, pt): if self.control and self._alive: self.value.request_redraw() # self.value.invalidate_and_redraw() st = time.time() et = time.time() - pt pt = st # print et # = time.time() # self.value.invalidate_and_redraw() QTimer.singleShot(max(1, self._get_interval()-et), lambda: self.update(pt))
class _CameraEditor(Editor): timer = Instance(QTimer) swap = False def init(self, parent): self.control = self._create_control(parent) self._setup_loop() def update_editor(self): self._setup_loop() def dispose(self): if self.timer: self.timer.stop() def _setup_loop(self): # if self.value is not None: self.timer = QTimer(self.control) self.timer.timeout.connect(self._update) print('fps', self.factory.fps) if self.factory.fps: self.timer.setInterval(1000 / self.factory.fps) self.timer.start() def _update(self): if self.value: # w, h = self.control.width(), self.control.height() # img = self.value.get_image_data(size=(w, h)) img = self.value.get_image_data() if img is not None: s = img.shape if s: im = QImage(img, s[1], s[0], QImage.Format_RGB32) # im = QImage(img, s[1], s[0], QImage.Format_RGB16) if self.swap: im = QImage.rgbSwapped(im) pix = QPixmap.fromImage(im) self.control.setPixmap(pix) def _create_control(self, parent): label = QLabel() width, height = self.item.width, self.item.height if self.item.width != -1.0: label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) label.setFixedWidth(abs(width)) label.setFixedHeight(abs(height)) return label
def init(self, parent): """ Finishes initializing the editor by creating the underlying toolkit widget. """ super(_VideoComponentEditor, self).init(parent) # self.playTimer = QTimer(self.control) # self.playTimer.timeout.connect(self.update) # self.control.connect(self.playTimer, SIGNAL('timeout()'), self.update) # if self.value.fps: # self.playTimer.setInterval(1000 / float(self.value.fps)) # self.playTimer.start() self.value.on_trait_change(self.stop, 'closed_event') # self.value.on_trait_change(self._update_fps, 'fps') self.sync_value('stop_timer', 'stop_timer', mode='from') # self._prev_time = time.time() self._alive = True QTimer.singleShot(self._get_interval(), lambda: self.update(-1))
def delete_widget(widget, timeout=1.0): """ Context manager that executes the event loop so that we can safely delete a Qt widget. """ app = get_app_qt4() timer = QTimer() timer.setSingleShot(True) timer.setInterval(round(timeout * 1000)) timer.timeout.connect(app.quit) widget.destroyed.connect(app.quit) yield timer.start() app.exec_() if not timer.isActive(): # We exited the event loop on timeout. msg = "Could not destroy widget before timeout: {!r}" raise AssertionError(msg.format(widget))
def delete_widget(widget, timeout=1.0): """ Context manager that executes the event loop so that we can safely delete a Qt widget. """ app = get_app_qt4() timer = QTimer() timer.setSingleShot(True) timer.setInterval(timeout*1000) timer.timeout.connect(app.quit) widget.destroyed.connect(app.quit) yield timer.start() app.exec_() if not timer.isActive(): # We exited the event loop on timeout. msg = 'Could not destroy widget before timeout: {!r}' raise AssertionError(msg.format(widget))
def __init__(self): self._reads = {} self._writes = {} self._notifiers = {} self._timer = QTimer() self._timer.setSingleShot(True) QObject.connect(self._timer, SIGNAL("timeout()"), self.iterate) if QCoreApplication.instance() is None: # Application Object has not been started yet self.qApp=QCoreApplication([]) self._ownApp=True else: self.qApp = QCoreApplication.instance() self._ownApp=False self._blockApp = None posixbase.PosixReactorBase.__init__(self) # Workaround for some bugs in the Twisted POSIXReactorBase class (see # docs for _cleanup_reactor). self.addSystemEventTrigger('after', 'shutdown', self._cleanup_reactor)
def run_until(self, object, trait, condition, timeout): """ Run event loop until the given condition holds true, or until timeout. The condition is re-evaluated, with the object as argument, every time the trait changes. Parameters ---------- object : traits.has_traits.HasTraits Object whose trait we monitor. trait : str Name of the trait to monitor for changes. condition Single-argument callable, returning a boolean. This will be called with *object* as the only input. timeout : float Number of seconds to allow before timing out with an exception. Raises ------ RuntimeError If timeout is reached, regardless of whether the condition is true or not at that point. """ qt_app = self.qt_app timeout_in_ms = round(1000.0 * timeout) timeout_timer = QTimer() timeout_timer.setSingleShot(True) timeout_timer.setInterval(timeout_in_ms) def stop_on_timeout(): qt_app.exit(1) def stop_if_condition(event): if condition(object): qt_app.exit(0) object.observe(stop_if_condition, trait) try: # The condition may have become True before we # started listening to changes. So start with a check. if condition(object): timed_out = 0 else: timeout_timer.timeout.connect(stop_on_timeout) timeout_timer.start() try: # Qt wrapper support is a bit of a mess here. PyQt6 has # only "exec". PyQt5 and PySide6 support both "exec" and # "exec_", with "exec" the preferred spelling. PyQt4 and # PySide2 support only "exec_". try: exec_method = qt_app.exec except AttributeError: exec_method = qt_app.exec_ timed_out = exec_method() finally: timeout_timer.stop() timeout_timer.timeout.disconnect(stop_on_timeout) finally: object.observe(stop_if_condition, trait, remove=True) if timed_out: raise RuntimeError("run_until timed out after {} seconds. " "At timeout, condition was {}.".format( timeout, condition(object)))
def __init__(self, **traits): traits.setdefault("_timer", QTimer()) super(PyfaceTimer, self).__init__(**traits) self._timer.timeout.connect(self.perform)
class QtReactor(posixbase.PosixReactorBase): implements(IReactorFDSet) def __init__(self): self._reads = {} self._writes = {} self._notifiers = {} self._timer = QTimer() self._timer.setSingleShot(True) QObject.connect(self._timer, SIGNAL("timeout()"), self.iterate) if QCoreApplication.instance() is None: # Application Object has not been started yet self.qApp=QCoreApplication([]) self._ownApp=True else: self.qApp = QCoreApplication.instance() self._ownApp=False self._blockApp = None posixbase.PosixReactorBase.__init__(self) # Workaround for some bugs in the Twisted POSIXReactorBase class (see # docs for _cleanup_reactor). self.addSystemEventTrigger('after', 'shutdown', self._cleanup_reactor) def _cleanup_reactor(self): """ Workaround some bugs in the Twisted POSIXReactorBase class that causes an application to be kept alive even after reactor.stop() has been called. """ for r in list(self._internalReaders): self.removeReader(r) def _add(self, xer, primary, type): """ Private method for adding a descriptor from the event loop. It takes care of adding it if new or modifying it if already added for another state (read -> read/write for example). """ if xer not in primary: primary[xer] = TwistedSocketNotifier(None, self, xer, type) def addReader(self, reader): """ Add a FileDescriptor for notification of data available to read. """ self._add(reader, self._reads, QSocketNotifier.Read) def addWriter(self, writer): """ Add a FileDescriptor for notification of data available to write. """ self._add(writer, self._writes, QSocketNotifier.Write) def _remove(self, xer, primary): """ Private method for removing a descriptor from the event loop. It does the inverse job of _add, and also add a check in case of the fd has gone away. """ if xer in primary: notifier = primary.pop(xer) notifier.shutdown() def removeReader(self, reader): """ Remove a Selectable for notification of data available to read. """ self._remove(reader, self._reads) def removeWriter(self, writer): """ Remove a Selectable for notification of data available to write. """ self._remove(writer, self._writes) def removeAll(self): """ Remove all selectables, and return a list of them. """ rv = self._removeAll(self._reads, self._writes) return rv def getReaders(self): return self._reads.keys() def getWriters(self): return self._writes.keys() def callLater(self,howlong, *args, **kargs): rval = super(QtReactor,self).callLater(howlong, *args, **kargs) self.reactorInvocation() return rval def reactorInvocation(self): self._timer.stop() self._timer.setInterval(0) self._timer.start() def _iterate(self, delay=None, fromqt=False): """See twisted.internet.interfaces.IReactorCore.iterate. """ self.runUntilCurrent() self.doIteration(delay, fromqt) iterate = _iterate def doIteration(self, delay=None, fromqt=False): 'This method is called by a Qt timer or by network activity on a file descriptor' if not self.running and self._blockApp: self._blockApp.quit() self._timer.stop() delay = max(delay, 1) if not fromqt: self.qApp.processEvents(QEventLoop.AllEvents, delay * 1000) if self.timeout() is None: timeout = 0.1 elif self.timeout() == 0: timeout = 0 else: timeout = self.timeout() self._timer.setInterval(timeout * 1000) self._timer.start() def runReturn(self, installSignalHandlers=True): self.startRunning(installSignalHandlers=installSignalHandlers) self.reactorInvocation() def run(self, installSignalHandlers=True): if self._ownApp: self._blockApp = self.qApp else: self._blockApp = QEventLoop() self.runReturn() self._blockApp.exec_()