class LabelableSegmentationEdgesLayer( SegmentationEdgesLayer ): """ Shows a set of user-labeled edges. """ labelsChanged = pyqtSignal( dict ) # { id_pair, label_class } def __init__(self, datasource, label_class_pens, initial_labels={}, delay_ms=1000): # Class 0 (no label) is the default pen super(LabelableSegmentationEdgesLayer, self).__init__( datasource, default_pen=label_class_pens[0] ) self._delay_ms = delay_ms self._label_class_pens = label_class_pens # Initialize the labels and pens self.overwrite_edge_labels(initial_labels) self._buffered_updates = {} # To avoid sending lots of single updates if the user is clicking quickly, # we buffer the updates into a dict that is only sent after a brief delay. self._timer = QTimer(self) self._timer.setInterval(self._delay_ms) self._timer.setSingleShot(True) self._timer.timeout.connect( self._signal_buffered_updates ) def overwrite_edge_labels(self, new_edge_labels): self._edge_labels = defaultdict(lambda: 0, new_edge_labels) # Change the pens accordingly pen_table = {} for id_pair, label_class in self._edge_labels.items(): pen_table[id_pair] = self._label_class_pens[label_class] self.pen_table.overwrite(pen_table) def handle_edge_clicked(self, id_pair): """ Overridden from SegmentationEdgesLayer """ num_classes = len(self._label_class_pens) old_class = self._edge_labels[id_pair] new_class = (old_class+1) % num_classes # Update the display self.pen_table[id_pair] = self._label_class_pens[new_class] # For now, edge_labels dictionary will still contain 0-labeled edges. # We could delete them, but why bother? self._edge_labels[id_pair] = new_class # Buffer the update for listeners self._buffered_updates[id_pair] = new_class # Reset the timer self._timer.start() def _signal_buffered_updates(self): updates = self._buffered_updates self._buffered_updates = {} self.labelsChanged.emit( updates )
class DelayWidget(WebWidget): def __init__(self, name, cfg, parent = None): WebWidget.__init__(self, name, parent) self.config = cfg self.url.setUrl(self.config.loadLinks()[str(self.objectName())]['data']) self.timer = QTimer(self) self.timer.setInterval(1000) self.timer.setSingleShot(1) self.timeoutTimer = QTimer(self) self.timeoutTimer.setInterval(10000) self.timeoutTimer.setSingleShot(1) self.connect(self.timeoutTimer , SIGNAL('timeout()') , self.clear) self.connect(self.timer , SIGNAL('timeout()') , self.reload_) self.connect(self , SIGNAL('done()') , self.clear) def clear(self): self.config.saveDelayWidgetBusy(False) def reload_(self): if not self.isVisible(): return if not self.timeoutTimer.isActive(): self.timeoutTimer.start() if self.config.loadDelayWidgetBusy(): self.timer.start() else: self.timeoutTimer.stop() self.config.saveDelayWidgetBusy(True) WebWidget.reload_(self)
def _processPendingEvents(): """Process pending application events.""" # Create an event loop to run in. Otherwise, we need to use the # QApplication main loop, which may already be running and therefore # unusable. qe = QEventLoop() # Create a single-shot timer. Could use QTimer.singleShot(), # but can't cancel this / disconnect it. timer = QTimer() timer.setSingleShot(True) timer.timeout.connect(qe.quit) timer.start(1) # Wait for an emitted signal. qe.exec_() # Clean up: don't allow the timer to call qe.quit after this # function exits, which would produce "interesting" behavior. timer.stop() # Stopping the timer may not cancel timeout signals in the # event queue. Disconnect the signal to be sure that loop # will never receive a timeout after the function exits. timer.timeout.disconnect(qe.quit)
def register_timer(self, time_delta, callback): """Registers a callback function to be run after time_delta ms.""" timer = QTimer(self.window) timer.setSingleShot(True) timer.timeout.connect(callback) timer.setInterval(time_delta) timer.start()
class ByteView(QTableView): """Byte table view.""" def __init__(self, parent=None): QTableView.__init__(self, parent) self.autoscroll_toggle = QAction("Autoscroll", self) self.autoscroll_toggle.setCheckable(True) self.autoscroll_toggle.setChecked(False) self.autoscroll_timer = QTimer(self) self.autoscroll_timer.setSingleShot(True) self.autoscroll_timer.timeout.connect(self.scrollToBottom) def contextMenuEvent(self, event): menu = QMenu() menu.addAction(self.autoscroll_toggle) menu.exec_(event.globalPos()) def col_added(self): self.resizeColumnsToContents() def row_added(self): if self.autoscroll_toggle.isChecked() and not self.autoscroll_timer.isActive(): self.autoscroll_timer.start(50)
class _StatusBar(QStatusBar): """Extended status bar. Supports HTML messages """ def __init__(self, *args): QStatusBar.__init__(self, *args) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.setSizeGripEnabled(False) self.setStyleSheet("QStatusBar {border: 0} QStatusBar::item {border: 0}") self._label = QLabel(self) self._label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self._label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) self._label.setStyleSheet("color: red") self.addWidget(self._label) self._timer = QTimer() self._timer.setSingleShot(True) self._timer.timeout.connect(self.clearMessage) def showMessage(self, text, timeout=0): """QStatusBar.showMessage() """ self._label.setText(text) self._timer.stop() if timeout > 0: self._timer.start(timeout) def clearMessage(self): """QStatusBar.clearMessage() """ self._label.clear()
def __init__(self, thread, parent): QDialog.__init__(self, parent) self.ui = Ui_PlotPreview() self.ui.setupUi(self) self.parent = parent icon = QIcon() icon.addPixmap(QPixmap(":/icons/reload.png"), QIcon.Normal, QIcon.Off) self.update_btn = QPushButton(icon, "Update") self.ui.buttonBox.addButton(self.update_btn, QDialogButtonBox.ApplyRole) self.update_btn.clicked.connect(self.render_image) self._pix = None self._image_list = None self._thread = thread self.scene = QGraphicsScene() self.scene.setSceneRect(0,0,1,1) self.ui.imageView.setScene(self.scene) self.pix_item = None self.ui.imageView.setEnabled(False) self.ui.imageView.setInteractive(False) self.ui.imageView.setDragMode(QGraphicsView.ScrollHandDrag) self.pic_w = None self.pic_c = None self.show_pic_w = None self.show_pic_c = None timer = QTimer(self) timer.setSingleShot(True) timer.setInterval(500) self.timer = timer timer.timeout.connect(self.render_image) if parameters.instance.use_OpenGL: self.ui.imageView.setViewport(QGLWidget(QGLFormat(QGL.SampleBuffers)))
class ErrorMessageFilter(QObject): """ In a parallel program, the same error may occur in several threads in close succession. For example, all slice views will notice a "filter too large" error simultaneously. This class collects error messages for a certain time (currently: 1000ms) and then displays each unique message only once. """ def __init__(self, parent): super(QObject, self).__init__(parent) self.messages = {} self.timer = QTimer(self) self.timer.setSingleShot(True) self.timer.setInterval(1000) self.connect(self.timer, QtCore.SIGNAL("timeout()"), self.timeout) def showErrorMessage(self, caption, text): if not self.timer.isActive(): self.timer.start() self.messages[caption] = text def timeout(self): # Must copy now because the eventloop is allowed to run during QMessageBox.critical, below. # That is, self.messages might change while the loop is executing (not allowed). messages = copy.copy(self.messages) for caption, text in messages.iteritems(): QMessageBox.critical(self.parent(), caption, text) self.messages = {}
def wait(self, time_ms, callback, onredirect=None, onerror=None): """ Wait for time_ms, then run callback. If onredirect is True then the timer is cancelled if redirect happens. If onredirect is callable then in case of redirect the timer is cancelled and this callable is called. If onerror is True then the timer is cancelled if a render error happens. If onerror is callable then in case of a render error the timer is cancelled and this callable is called. """ timer = QTimer() timer.setSingleShot(True) timer_callback = functools.partial(self._on_wait_timeout, timer=timer, callback=callback, ) timer.timeout.connect(timer_callback) self.logger.log("waiting %sms; timer %s" % (time_ms, id(timer)), min_level=2) timer.start(time_ms) self._active_timers.add(timer) if onredirect: self._timers_to_cancel_on_redirect[timer] = onredirect if onerror: self._timers_to_cancel_on_error[timer] = onerror
class AsyncCaller(object): """Call a Python function after a delay.""" def __init__(self, delay=10): self._delay = delay self._timer = None def _create_timer(self, f): self._timer = QTimer() self._timer.timeout.connect(f) self._timer.setSingleShot(True) def set(self, f): """Call a function after a delay, unless another function is set in the meantime.""" self.stop() self._create_timer(f) self.start() def start(self): """Start the timer and call the function after a delay.""" if self._timer: self._timer.start(self._delay) def stop(self): """Stop the current timer if there is one and cancel the async call.""" if self._timer: self._timer.stop() self._timer.deleteLater()
def main(): global trading_account global trading_account_name global qtimer # start connection to etrade etradepy.login() accounts = etradepy.listAccounts() trading_account = accounts['json.accountListResponse']['response'][0][ 'accountId'] trading_account_name = accounts['json.accountListResponse']['response'][0][ 'accountDesc'] app = QtGui.QApplication(sys.argv) form = EtradeApp() form.show() form.statusBar.showMessage( accounts['json.accountListResponse']['response'][0]['accountDesc']) form.restoreState() # # This is a kludge to automatically place a stop loss order after placing a buy or a sell_short # Ideally we'd get a response from the server after the initial order executes, but instead # we set a short delay on qtimer in the placeEquityOrder function # qtimer = QTimer() qtimer.setSingleShot(True) qtimer.timeout.connect(form.recordStopLossOrder) app.aboutToQuit.connect(form.saveState) app.exec_()
def wait(self, time_ms, callback, onredirect=None, onerror=None): """ Wait for time_ms, then run callback. If onredirect is True then the timer is cancelled if redirect happens. If onredirect is callable then in case of redirect the timer is cancelled and this callable is called. If onerror is True then the timer is cancelled if a render error happens. If onerror is callable then in case of a render error the timer is cancelled and this callable is called. """ timer = QTimer() timer.setSingleShot(True) timer_callback = functools.partial( self._on_wait_timeout, timer=timer, callback=callback, ) timer.timeout.connect(timer_callback) self.logger.log("waiting %sms; timer %s" % (time_ms, id(timer)), min_level=2) timer.start(time_ms) self._active_timers.add(timer) if onredirect: self._timers_to_cancel_on_redirect[timer] = onredirect if onerror: self._timers_to_cancel_on_error[timer] = onerror
class MessageDialog(QDialog): def __init__(self, parent = None): QDialog.__init__(self, parent) self.setWindowFlags(Qt.Dialog | Qt.FramelessWindowHint) self.layout = QVBoxLayout(self) self.label = ScaledLabel() self.label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) self.layout.addWidget(self.label) self.timer = QTimer() self.timer.timeout.connect(self.hide) self.timer.setSingleShot(True) def showMessage(self, message): self.label.setText(message) self.show() self.raise_() def showMessageTimed(self, message, timeout = 3000): self.showMessage(message) self.timer.start(timeout)
def highlightReferencingFeature(self): self.deleteHighlight() if not self.relation.isValid() or not self.referencingFeature.isValid( ): return self.featureHighlight = QgsHighlight( self.iface.mapCanvas(), self.referencingFeature.geometry(), self.relation.referencingLayer()) settings = QSettings() color = QColor( settings.value("/Map/highlight/color", QGis.DEFAULT_HIGHLIGHT_COLOR.name())) alpha = int( settings.value("/Map/highlight/colorAlpha", QGis.DEFAULT_HIGHLIGHT_COLOR.alpha())) bbuffer = float( settings.value("/Map/highlight/buffer", QGis.DEFAULT_HIGHLIGHT_BUFFER_MM)) minWidth = float( settings.value("/Map/highlight/minWidth", QGis.DEFAULT_HIGHLIGHT_MIN_WIDTH_MM)) self.featureHighlight.setColor(color) color.setAlpha(alpha) self.featureHighlight.setFillColor(color) self.featureHighlight.setBuffer(bbuffer) self.featureHighlight.setMinWidth(minWidth) self.featureHighlight.show() timer = QTimer(self) timer.setSingleShot(True) timer.timeout.connect(self.deleteHighlight) timer.start(3000)
def _check_path_exists(self, path, text_box): #Validates if the specified folder exists dir = QDir() if not dir.exists(path): msg = self.tr(u"'{0}' directory does not exist.".format(path)) self.notif_bar.insertErrorNotification(msg) #Highlight textbox control text_box.setStyleSheet(INVALIDATESTYLESHEET) timer = QTimer(self) #Sync interval with that of the notification bar timer.setInterval(self.notif_bar.interval) timer.setSingleShot(True) #Remove previous connected slots (if any) receivers = timer.receivers(SIGNAL('timeout()')) if receivers > 0: self._timer.timeout.disconnect() timer.start() timer.timeout.connect(lambda:self._restore_stylesheet( text_box) ) return False return True
class _GlobalUpdateWordSetTimer: """Timer updates word set, when editor is idle. (5 sec. after last change) Timer is global, for avoid situation, when all instances update set simultaneously """ _IDLE_TIMEOUT_MS = 1000 def __init__(self): self._timer = QTimer() self._timer.setSingleShot(True) self._timer.timeout.connect(self._onTimer) self._scheduledMethods = [] def schedule(self, method): if not method in self._scheduledMethods: self._scheduledMethods.append(method) self._timer.start(self._IDLE_TIMEOUT_MS) def cancel(self, method): """Cancel scheduled method Safe method, may be called with not-scheduled method""" if method in self._scheduledMethods: self._scheduledMethods.remove(method) if not self._scheduledMethods: self._timer.stop() def _onTimer(self): method = self._scheduledMethods.pop() method() if self._scheduledMethods: self._timer.start(self._IDLE_TIMEOUT_MS)
def private_call_later(self, callback, delay=None): if delay is None: delay = 0 if not isinstance(delay, (float, int)): raise ScriptError({ "argument": "delay", "message": "splash:call_later delay must be a number", "splash_method": "call_later", }) delay = int(float(delay)*1000) if delay < 0: raise ScriptError({ "argument": "delay", "message": "splash:call_later delay must be >= 0", "splash_method": "call_later", }) if lupa.lua_type(callback) != 'function': raise ScriptError({ "argument": "callback", "message": "splash:call_later callback is not a function", "splash_method": "call_later", }) qtimer = QTimer(self.tab) qtimer.setSingleShot(True) timer = _ExposedTimer(self, qtimer) run_coro = self.get_coroutine_run_func( "splash:call_later", callback, return_error=timer.store_error ) qtimer.timeout.connect(run_coro) qtimer.start(delay) return timer
def _check_path_exists(self, path, text_box): #Validates if the specified folder exists dir = QDir() if not dir.exists(path): msg = self.tr(u"'{0}' directory does not exist.".format(path)) self.notif_bar.insertErrorNotification(msg) #Highlight textbox control text_box.setStyleSheet(INVALIDATESTYLESHEET) timer = QTimer(self) #Sync interval with that of the notification bar timer.setInterval(self.notif_bar.interval) timer.setSingleShot(True) #Remove previous connected slots (if any) receivers = timer.receivers(SIGNAL('timeout()')) if receivers > 0: self._timer.timeout.disconnect() timer.start() timer.timeout.connect(lambda: self._restore_stylesheet(text_box)) return False return True
class Plugin: def __init__(self): self.timer = QTimer(None) self.timer.setInterval(10000) self.timer.timeout.connect(self.Timeout) self.timer.setSingleShot(True) self.action = QAction("Preview mode", None) self.action.setCheckable(True) self.action.triggered.connect(self.Enabled) clementine.ui.AddAction("playlist_menu", self.action) clementine.player.Playing.connect(self.Playing) clementine.player.Paused.connect(self.Stopped) clementine.player.Stopped.connect(self.Stopped) self.enabled = False def Enabled(self, enabled): self.enabled = enabled if enabled: if clementine.player.GetState() == 2: # Playing self.timer.start() else: self.timer.stop() def Playing(self): if self.enabled: self.timer.start() def Stopped(self): self.timer.stop() def Timeout(self): if clementine.player.GetState() == 2: clementine.player.Next()
def __init__ (self, parent = None): QTimer.__init__ (self, parent) self.startTime = 0 self.ispaused = False self.interval = 0 QTimer.setSingleShot(self,True) self.timeout.connect(self._timeend)
class PreviewEnabledRenderingFunction(object): def __init__(self, scene, timeout=250): self.scene = scene self._fine_rendering_allocated_time = None self._timer = QTimer() self._timer.setSingleShot(True) self._timer.setInterval(timeout) QObject.connect(self._timer, SIGNAL('timeout()'), self.render) def abort_rendering(self): self._timer.stop() if self._fine_rendering_allocated_time is not None: self.scene.renderer.allocated_render_time = \ self._fine_rendering_allocated_time self._fine_rendering_allocated_time = None def render(self): self.scene.renderer.allocated_render_time = \ self._fine_rendering_allocated_time self.scene.render() def render_preview(self): self._fine_rendering_allocated_time = \ self.scene.renderer.allocated_render_time self.scene.renderer.allocated_render_time = 0 self.scene.render() self._timer.start() def __call__(self): self.render_preview()
class ErrorMessageFilter(QObject): """ In a parallel program, the same error may occur in several threads in close succession. For example, all slice views will notice a "filter too large" error simultaneously. This class collects error messages for a certain time (currently: 200ms) and then displays each unique message only once. """ def __init__(self, parent): super(QObject, self).__init__(parent) self.messages = {} self.timer = QTimer(self) self.timer.setSingleShot(True) self.timer.setInterval(200) self.connect(self.timer, QtCore.SIGNAL("timeout()"), self.timeout) def showErrorMessage(self, caption, text): if not self.timer.isActive(): self.timer.start() self.messages[text] = caption def timeout(self): for text, caption in self.messages.iteritems(): QMessageBox.critical(self.parent(), caption, text) self.messages = {}
class SequenceInstrumentController(NonBlockingInstrumentController): def __init__(self, instrument_config): NonBlockingInstrumentController.__init__(self, instrument_config) # circular list of command sequence self.commands = deque(instrument_config.operation_commands) self.tx_timer = QTimer() self.tx_timer.setSingleShot(True) def run(self): # define the timer used to wait for the next command self.tx_timer.timeout.connect(self.send_command) # send the first command self.send_command() NonBlockingInstrumentController.run(self) def quit(self): self.tx_timer.stop() NonBlockingInstrumentController.quit(self) def send_command(self): # send next command cmd = self.commands[0] self.new_command.emit(cmd) # wait for next command self.tx_timer.start(cmd.param) # advance command list self.commands.rotate(-1)
def get(self, url=None, script=None, key=None): """Load given url in webkit and return html when loaded """ self.base_url = self.base_url or url # set base URL if not set html = self.cache.get(key) if html: if self.debug: print 'load cache', key self.setHtml(html, QUrl(self.base_url)) elif url: self.load(QUrl(url)) elif script: self.js(script) loop = QEventLoop() timer = QTimer() timer.setSingleShot(True) timer.timeout.connect(loop.quit) self.loadFinished.connect(loop.quit) timer.start(self.timeout * 1000) loop.exec_() # delay here until download finished or timeout if timer.isActive(): # downloaded successfully timer.stop() html = self.current_html() if key: self.cache[key] = html self.inject_jquery() else: # didn't download in time print 'Download timeout' html = '' return html
class Overlay(QDialog): shown = pyqtSignal() def __init__(self, keyPressHandler, parent=None): QDialog.__init__(self, parent) self.keyPressHandler = keyPressHandler self.setWindowFlags(Qt.Dialog | Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) self.setFocusPolicy(Qt.NoFocus) # Causes issues in some non-compositing WM's (notably Fluxbox) if QX11Info.isCompositingManagerRunning(): self.setAttribute(Qt.WA_TranslucentBackground) self.timer = QTimer() self.timer.setSingleShot(True) self.timer.timeout.connect(self.hide) def showTimed(self, interval=2000): self.show() self.timer.start(interval) def keyPressEvent(self, event): if not self.keyPressHandler(event): QDialog.keyPressEvent(self, event)
class _StatusBar(QStatusBar): """Extended status bar. Supports HTML messages """ def __init__(self, *args): QStatusBar.__init__(self, *args) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.setSizeGripEnabled(False) self.setStyleSheet( "QStatusBar {border: 0} QStatusBar::item {border: 0}") self._label = QLabel(self) self._label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self._label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) self._label.setStyleSheet("color: red") self.addWidget(self._label) self._timer = QTimer() self._timer.setSingleShot(True) self._timer.timeout.connect(self.clearMessage) def showMessage(self, text, timeout=0): """QStatusBar.showMessage() """ self._label.setText(text) self._timer.stop() if timeout > 0: self._timer.start(timeout) def clearMessage(self): """QStatusBar.clearMessage() """ self._label.clear() def currentMessage(self): return self._label.text()
def OeQ_wait_for_file(filepath,timeout=10000): """Block loop until signal emitted, or timeout (ms) elapses.""" from PyQt4.QtCore import QEventLoop,QTimer from os.path import isfile import platform import os if platform.system() == 'Darwin': return True if isfile(filepath): return True loop = QEventLoop() timer=QTimer() file_result = [True] # def check_file(testpath): if isfile(testpath): timer.stop() loop.quit() # timer.timeout.connect(lambda: check_file(filepath)) timer.setSingleShot(False) timer.start(500) # def timed_out(file_result_flag): file_result_flag[0]=False loop.quit() # if timeout >500: timer.singleShot(timeout,lambda: timed_out(file_result)) loop.exec_() return file_result[0]
def download_file(self, url, path_file): """ download function :param url: url path of file :param path_file: path to save file :return: """ self.file_install = path_file self.url = url loop = QEventLoop() timer = QTimer() timer.setSingleShot(True) timer.timeout.connect(lambda: loop.exit(1)) timer.start(100000) # 10 second time-out # req = QNetworkRequest(QUrl('https://www.python.org/')) req = QNetworkRequest(QUrl(url)) result = self.manager.get(req) result.finished.connect(lambda: self.fin_req(loop, result)) self.print_('fetching request...', self.dbg) if loop.exec_() == 0: timer.stop() self.print_( '{} is received: {}'.format(os.path.basename(path_file), result.readAll().count()), self.dbg) else: self.print_('request timed-out')
class QnoteroQuery(QLineEdit): """The search input box""" def __init__(self, qnotero): """ Constructor Arguments: qnotero -- a Qnotero instance """ QLineEdit.__init__(self, qnotero) self.qnotero = qnotero self.timer = QTimer(self) self.needUpdate = True self.textChanged.connect(self._textChanged) def keyPressEvent(self, e): """ Handle key presses Arguments: e -- a QKeyEvent """ if e.key() == Qt.Key_Return: self.qnotero.search(setFocus=False) return if e.key() == Qt.Key_Down: if self.needUpdate: self.qnotero.search(setFocus=True) elif self.qnotero.ui.listWidgetResults.count() > 0: self.qnotero.ui.listWidgetResults.setFocus() self.qnotero.ui.listWidgetResults.setCurrentItem( \ self.qnotero.ui.listWidgetResults.item(0)) return QLineEdit.keyPressEvent(self, e) self.timer.stop() self.timer = QTimer(self) self.timer.setSingleShot(True) self.timer.setInterval(getConfig("autoFire")) self.timer.timeout.connect(self.search) self.timer.start() def search(self): """Perform a search without losing focus""" self.qnotero.search(setFocus=False) def _textChanged(self): """Set the needUpdate flag""" self.needUpdate = True
def __init__(self, text, parent=None): super(PopupButton, self).__init__(text, parent) timer = QTimer() timer.setSingleShot(True) timer.setInterval(500) timer.timeout.connect(self.showPopup) self.timer = timer self.popup = None
def repeat(self, interval, function, *args): timer = QTimer() timer.setSingleShot(False) self.params[timer] = (interval, function, args) timer.start(0) timer.timeout.connect(self.timeout)
def _default__band_timer(self): """ Create the default timer for the band state changes. """ timer = QTimer() timer.setSingleShot(True) timer.timeout.connect(self._on_band_timer) return timer
def _poll(self): self.ad_status.fetch_data(self.mainwindow.client) timer = QTimer() timer.setSingleShot(True) timer.setInterval(20000) # ms timer.start() self.connect(timer, SIGNAL('timeout()'), self._poll) self.connect(self, SIGNAL('destroyed()'), timer.stop)
def schedule(self, interval, function, *args): timer = QTimer() timer.setInterval(interval * 1000) timer.setSingleShot(True) self.params[timer] = (None, function, args) timer.start() timer.timeout.connect(self.timeout)
class Tracker(QObject): sig_error = pyqtSignal(str) sig_started = pyqtSignal() sig_inview = pyqtSignal(bool) # True if in view, else False def __init__(self, parent): super(Tracker, self).__init__(parent) self.name = self.__class__.__name__ # Ros Stuff self.sub_tf = parent.sub_tf self.pub_tf = parent.pub_tf # Timer that checks if we have failed to start self.timer = QTimer() self.timer.setSingleShot(True) self.timer.timeout.connect(self.failed) self.timeout = 2000 #ms self.timer.setInterval(self.timeout) def started(self): """ Called when starting was possible """ if self.timer.isActive(): self.timer.stop() self.sig_started.emit() rospy.loginfo("Started [%s]", self.name) def onStart(self): pass def getStartMsg(self): return "Default start msg.." def getFailMsg(self): return "Default fail msg" def onStop(self): pass def start(self): rospy.loginfo("Starting [%s]", self.name) self.timer.start() return self.onStart() def failed(self, msg=None): """ Called when starting not possible """ if msg is None: msg = self.getFailMsg() self.sig_error.emit(msg) rospy.logerr("Failed to start [%s]: %s", self.name, msg) self.stop() def stop(self): self.timer.stop() rospy.loginfo("Stopping [%s]", self.name) self.onStop()
class Tracker(QObject): sig_error = pyqtSignal(str) sig_started = pyqtSignal() sig_inview = pyqtSignal(bool) # True if in view, else False def __init__(self, parent): super(Tracker, self).__init__(parent) self.name = self.__class__.__name__ # Ros Stuff self.sub_tf = parent.sub_tf self.pub_tf = parent.pub_tf # Timer that checks if we have failed to start self.timer = QTimer() self.timer.setSingleShot(True) self.timer.timeout.connect(self.failed) self.timeout = 2000 #ms self.timer.setInterval(self.timeout) def started(self): """ Called when starting was possible """ if self.timer.isActive(): self.timer.stop() self.sig_started.emit() rospy.loginfo("Started [%s]" , self.name) def onStart(self): pass def getStartMsg(self): return "Default start msg.." def getFailMsg(self): return "Default fail msg" def onStop(self): pass def start(self): rospy.loginfo("Starting [%s]", self.name) self.timer.start() return self.onStart() def failed(self, msg=None): """ Called when starting not possible """ if msg is None: msg = self.getFailMsg() self.sig_error.emit(msg) rospy.logerr("Failed to start [%s]: %s" , self.name, msg) self.stop() def stop(self): self.timer.stop() rospy.loginfo("Stopping [%s]", self.name) self.onStop()
def repeat(self, interval, function, *args): timer = QTimer() timer.setSingleShot(False) count = self.count self.count += 1 timer.start(0) self.app.connect(timer, SIGNAL("timeout()"), lambda: self.timeout(count, interval, function, *args)) self.timers[count] = timer
def schedule(self, interval, function, *args): timer = QTimer() timer.setInterval(interval * 1000) timer.setSingleShot(True) count = self.count self.count += 1 timer.start() self.app.connect(timer, SIGNAL("timeout()"), lambda: self.timeout(count, None, function, *args)) self.timers[count] = timer
class QEventLoop(QObject): def __init__(self): super(QObject, self).__init__() self.hooks = [] self.waiting_for_shot = False self.started = False self.run_count = 0 self.timer = QTimer(self) self.timer.setSingleShot(True) self.timer.timeout.connect(self._run) def start(self): logger.debug("Starting event loop") self.started = True self._activate() def stop(self): logger.debug("Stopping event loop") self.timer.stop() self.started = False def register_hook(self, hook): logger.debug(msg("Registering hook", hook)) self.hooks.append(hook) self._activate() def unregister_hook(self, hook): try: self.hooks.remove(hook) except: pass self._activate() def _activate(self): if len(self.hooks) > 0 and not self.waiting_for_shot and self.started: self.waiting_for_shot = True self.timer.start(10) if self.run_count % 1000 == 0: logger.debug(msg( "Activating eventloop, timerID:", self.timer.timerId())) @pyqtSlot() def _run(self): if self.run_count % 1000 == 0: logger.debug("Running hooks") self.run_count += 1 for h in self.hooks: h() self.waiting_for_shot = False self._activate() def __del__(self): logger.debug("Deleting event event loop") self.stop()
def get(self, url, html=None, headers=None, data=None): """Load given url in webkit and return html when loaded url: the URL to load html: optional HTML to set instead of downloading headers: the headers to attach to the request data: the data to POST """ if isinstance(url, basestring): # convert string to Qt's URL object url = QUrl(url) if html: # load pre downloaded HTML self.setContent(html, baseUrl=url) return html t1 = time() loop = QEventLoop() self.loadFinished.connect(loop.quit) # need to make network request request = QNetworkRequest(url) if headers: # add headers to request when defined for header, value in headers: request.setRawHeader(header, value) self.page().networkAccessManager().main_url = url request.setOriginatingObject(self) if data: # POST request super(Browser, self).load(request, QNetworkAccessManager.PostOperation, data) else: # GET request super(Browser, self).load(request) # set a timeout on the download loop timer = QTimer() timer.setSingleShot(True) timer.timeout.connect(loop.quit) timer.start(self.timeout * 1000) loop.exec_() # delay here until download finished or timeout if timer.isActive(): # downloaded successfully timer.stop() parsed_html = self.current_html() self.wait(self.delay - (time() - t1)) else: # did not download in time common.logger.debug('Timed out: {}'.format(url.toString())) parsed_html = '' return parsed_html
def repeat(self, interval, function, *args): timer = QTimer() timer.setSingleShot(False) count = self.count self.count += 1 timer.start(0) self.app.connect( timer, SIGNAL("timeout()"), lambda: self.timeout(count, interval, function, *args)) self.timers[count] = timer
def __init__(self, args): super(QApplication, self).__init__(args) self.error_msg = QErrorMessage() self.ipcon = IPConnection() signal.signal(signal.SIGINT, self.exit_demo) signal.signal(signal.SIGTERM, self.exit_demo) timer = QTimer(self) timer.setSingleShot(True) timer.timeout.connect(self.connect) timer.start(1)
def _setReplyTimeout(self, reply, timeout_ms): request_id = self._getRequestId(reply.request()) # reply is used as a parent for the timer in order to destroy # the timer when reply is destroyed. It segfaults otherwise. timer = QTimer(reply) timer.setSingleShot(True) timer_callback = functools.partial(self._onReplyTimeout, reply=reply, timer=timer, request_id=request_id) timer.timeout.connect(timer_callback) self._reply_timeout_timers[request_id] = timer timer.start(timeout_ms)
class ColumnResizerPrivate: widgets = [] wrWidgetItemList = [] gridColumnInfoList = [] def __init__( self, q ): self.q = q self.updateTimer = QTimer( q ) self.updateTimer.setSingleShot( True ) self.updateTimer.setInterval( 0 ) QObject.connect( self.updateTimer, SIGNAL( 'timeout()' ), q.updateWidth ) def scheduleWithUpdate( self ): self.updateTimer.start()
class BlockingInstrumentController(InstrumentController): RX_TIMEOUT = 2000 def __init__(self, instrument_config): InstrumentController.__init__(self, instrument_config) # circular list of operation commands self.commands = deque([ command for command in instrument_config.operation_commands for i in xrange(command.param) ]) self.rx_timeout = QTimer() self.rx_timeout.setSingleShot(True) def run(self): # define a timeout, if response not received send the command again self.rx_timeout.timeout.connect(self.send_command_timeout) self.rx_timeout.start(self.RX_TIMEOUT) # send the first command self.send_next_command() InstrumentController.run(self) def quit(self): self.rx_timeout.stop() InstrumentController.quit(self) def on_new_packet_parsed(self, packet): InstrumentController.on_new_packet_parsed(self, packet) self.send_next_command() def send_next_command(self): self.new_command.emit(self.commands[0]) # advance command list self.commands.rotate(-1) # restart reception timeout self.rx_timeout.start(self.RX_TIMEOUT) def send_command_timeout(self): self.log.warn("Timeout! response packet not received") # send next command self.send_next_command()
def callLater(self, timeout, callback=None): def onTimer(): del self.timers[op] op.notify() def doCancel(): del self.timers[op] timer.stop() timer = QTimer() QObject.connect(timer, SIGNAL('timeout()'), onTimer) timer.setSingleShot(True) timer.start(int(timeout * 1000)) op = AsyncOp(callback, doCancel) self.timers[op] = (timer, op, onTimer, doCancel) return op
def get(self, url=None, script=None, num_retries=1, jquery=False): """Load given url in webkit and return html when loaded script is some javasript to exexute that will change the loaded page (eg form submission) num_retries is how many times to try downloading this URL or executing this script jquery is whether to inject JQuery into the document """ t1 = time() self.base_url = self.base_url or url # set base URL if not set #html = self.cache.get(key, {}).get('value') #if html: # self.debug('Load cache ' + key) # self.setHtml(html, QUrl(self.base_url)) #else: if 1: loop = QEventLoop() timer = QTimer() timer.setSingleShot(True) timer.timeout.connect(loop.quit) self.loadFinished.connect(loop.quit) if url: self.load(QUrl(url)) elif script: self.js(script) timer.start(self.timeout * 1000) loop.exec_() # delay here until download finished or timeout if timer.isActive(): # downloaded successfully timer.stop() parsed_html = self.current_html() #if key: # self.cache[key] = html self.wait(self.delay - (time() - t1)) else: # didn't download in time if num_retries > 0: common.logger.debug('Timeout - retrying') parsed_html = self.get(url, script=script, num_retries=num_retries - 1, jquery=jquery) else: common.logger.debug('Timed out') parsed_html = '' return parsed_html
def open(self, url, timeout=60): """Wait for download to complete and return result""" loop = QEventLoop() timer = QTimer() timer.setSingleShot(True) timer.timeout.connect(loop.quit) self.loadFinished.connect(loop.quit) self.load(QUrl(url)) timer.start(timeout * 1000) loop.exec_() # delay here until download finised if timer.isActive(): #downloaded successfully timer.stop() return self.html() else: #time out print('Request timed out:', url)
def wrapper(*args): self = args[0] # create a single-shot timer. Could use QTimer.singleShot(), # but can't cancel this / disconnect it. timer = QTimer() timer.setSingleShot(True) timer.timeout.connect(self.app.quit) def execWithArgs(): core.mainWindow().show() QTest.qWaitForWindowShown(core.mainWindow()) app = QApplication.instance() app.setActiveWindow(core.mainWindow()) assert app.focusWidget() is not None func(*args) # When done processing these events, exit the event loop. To do so, timer.start(0) QTimer.singleShot(0, execWithArgs) # Catch any exceptions which the EventLoop would otherwise catch # and not re-raise. exceptions = [] def excepthook(type_, value, tracebackObj): exceptions.append((value, tracebackObj)) self.app.exit() oldExcHook = sys.excepthook sys.excepthook = excepthook try: # Run the requested function in the application's main loop. self.app.exec_() # If an exception occurred in the event loop, re-raise it. if exceptions: value, tracebackObj = exceptions[0] raise value, None, tracebackObj finally: # Restore the old exception hook sys.excepthook = oldExcHook # Stop the timer, in case an exception or an unexpected call to # self.app.exit() brought us here. timer.stop() timer.timeout.disconnect(self.app.quit)