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()
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 ask_password_dialog(parent, title, prompt, timeout=None): if parent is None: qt4tools.create_qapplication() import icon dialog = QInputDialog() timer = QTimer() if not timeout is None: dialog.connect(timer, SIGNAL("timeout()"), dialog.reject) timer.setInterval(timeout * 1000) timer.start() dialog.setWindowIcon(icon.BIT_LOGO) dialog.setWindowTitle(title) dialog.setLabelText(prompt) dialog.setTextEchoMode(QLineEdit.Password) QApplication.processEvents() ret = dialog.exec_() timer.stop() if ret: password = dialog.textValue() else: password = '' del (dialog) return (password)
class NPGPull(ZMQPull): def __init__(self, host, port, imgModel, table, opts, flags): ZMQPull.__init__(self, host, port, opts=[], flags=flags) self.socketTimer = QTimer() self.socketTimer.timeout.connect(self.receive) self.imgModel = imgModel self.table = table def start(self): self.connect() self.socketTimer.start(100) def stop(self): self.close() self.socketTimer.stop() def receive(self): try: data = self.puller.recv_json(flags=zmq.NOBLOCK) fn = str(data['fn'].strip()) path = str(data['path']) index = int(data['index']) total = int(data['total']) N = int(data['processed']) hit = int(data['hit']) self.imgModel.updateData(fn, path, int(index)) self.table.progress((total, N, hit)) return except zmq.error.Again: return
class GenericTerminalOutputBox(QtGui.QLineEdit): def __init__(self) -> None: super().__init__() self.animate = False self.timer = QTimer(self) self.timer.setInterval(5) self.timer.timeout.connect(self._add_character) self.buffer = "" def set_timer_interval(self, num: int) -> None: self.timer.setInterval(num) def _add_character(self) -> None: if not self.buffer: self.timer.stop() return super().setText(self.text() + self.buffer[0]) self.buffer = self.buffer[1:] def setText(self, text: str) -> None: if not self.animate or not text: super().setText(text) return super().setText(text[0]) if len(text) > 1: self.buffer = text[1:] self.timer.start()
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()
class Stopper(QObject): start_timer = pyqtSignal() stop_timer = pyqtSignal() def __init__(self): super(Stopper, self).__init__() print "current thread 2 %r" % QThread.currentThread() self.timer = QTimer() self.thread_of_timer = self.timer.thread() print "stopper.timer thread: %r" % self.thread_of_timer self.timer.setInterval(1000) self.timer.timeout.connect(self.prnt_msg) self.start_timer.connect(self.start) self.stop_timer.connect(self.stop) def start(self): print "starting" self.timer.start() def stop(self): print "stopping" print QThread.currentThread() print self.thread() print self.timer.thread() print "Timer thread has changed: %s" % (self.thread_of_timer is self.timer.thread()) self.timer.stop() def prnt_msg(self): print "timer running"
def ask_password_dialog(parent, title, prompt, timeout = None): if parent is None: app = qt4tools.create_qapplication() translator = qt4tools.get_translator() app.installTranslator(translator) import icon dialog = QInputDialog() timer = QTimer() if not timeout is None: dialog.connect(timer, SIGNAL("timeout()"), dialog.reject) timer.setInterval(timeout * 1000) timer.start() dialog.setWindowIcon(icon.BIT_LOGO) dialog.setWindowTitle(title) dialog.setLabelText(prompt) dialog.setTextEchoMode(QLineEdit.Password) QApplication.processEvents() ret = dialog.exec_() timer.stop() if ret: password = dialog.textValue() else: password = '' del(dialog) return(password)
class FileGPSService(GPSService): def __init__(self, filename): super(FileGPSService, self).__init__() self.file = None self.timer = QTimer() self.timer.setInterval(100) self.timer.timeout.connect(self._read_from_file) self.filename = filename def connectGPS(self, portname): # Normally the portname is passed but we will take a filename # because it's a fake GPS service if not self.isConnected: self.file = open(self.filename, "r") self.timer.start() self.isConnected = True def _read_from_file(self): line = self.file.readline() if not line: self.file.seek(0) line = self.file.readline() self.parse_data(line) def disconnectGPS(self): if self.file: self.file.close() self.timer.stop() self.file = None self.gpsdisconnected.emit()
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)
class Player(QThread, midifile.player.Player): """An implementation of midifile.player.Player using a QThread and QTimer. emit signals: stateChanged(playing): True or False if playing state changes time(msec): The playing time, emit by default every 1000ms beat(measnum, beat, num, den): the measure number, beat number, time signature numerator and denom., where 0 = whole note, 1 = half note, 2 = quarter note, etc. """ stateChanged = pyqtSignal(bool) time = pyqtSignal(int) beat = pyqtSignal(int, int, int, int) def __init__(self, parent=None): QThread.__init__(self, parent) midifile.player.Player.__init__(self) self._timer = None def run(self): self._timer = QTimer(singleShot=True) self._timer.timeout.connect(self.timer_timeout, Qt.DirectConnection) self.timer_start_playing() self.stateChanged.emit(True) if self.exec_(): self.timer_stop_playing() self._timer = None self.stateChanged.emit(False) def start(self): if self.has_events(): QThread.start(self) def stop(self): if self.isRunning(): self.exit(1) self.wait() def timer_start(self, msec): """Starts the timer to fire once, the specified msec from now.""" self._timer.start(int(msec)) def timer_stop(self): self._timer.stop() def finish_event(self): midifile.player.Player.finish_event(self) self.exit(0) def time_event(self, time): self.time.emit(time) def beat_event(self, measnum, beat, num, den): self.beat.emit(measnum, beat, num, den)
class Blinker: def __init__(self, parent, color=Qt.green): self.parent = parent self.timer = QTimer(parent) self.parent.connect(self.timer, SIGNAL("timeout()"), self.blink) self.defaultColor = self.color = color self.transfer = 0 def blink(self): if self.color == self.defaultColor: self.color = Qt.transparent else: self.color = self.defaultColor self.parent.update() def update(self, data): if not data == self.transfer: self.timer.start(100) else: self.stop() self.transfer = data def isActive(self): return self.timer.isActive() def stop(self): self.timer.stop() self.color = Qt.transparent self.parent.update()
class DeviceReader(QThread): """Used for polling data from the Input layer during configuration""" raw_axis_data_signal = pyqtSignal(object) raw_button_data_signal = pyqtSignal(object) mapped_values_signal = pyqtSignal(object) def __init__(self, input): QThread.__init__(self) self._input = input self._read_timer = QTimer() self._read_timer.setInterval(25) self.connect(self._read_timer, SIGNAL("timeout()"), self._read_input) def stop_reading(self): """Stop polling data""" self._read_timer.stop() def start_reading(self): """Start polling data""" self._read_timer.start() def _read_input(self): [rawaxis, rawbuttons, mapped_values] = self._input.read_raw_values() self.raw_axis_data_signal.emit(rawaxis) self.raw_button_data_signal.emit(rawbuttons) self.mapped_values_signal.emit(mapped_values)
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)
class AnimationSpinner(QLabel): def __init__(self, parent=None): QLabel.__init__(self, parent) brightness = parent.palette().color(QPalette.Window).valueF() self._bw = brightness < 0.5 and 1 or 0 self._steps = 12 self._setup() self._isRunning = False self.animationTimer = None def _setup(self): steps = self._steps anglestep = 360. / steps fillstep = 0.6 / (steps - 1) self._fillsteps = [0.71 - i * fillstep for i in range(steps)] self._coords = [coordinates(8, 8, 6, anglestep*i) for i in range(steps)] self._path = QPainterPath() self._path.addRoundedRect(0, 0, 4, 2, 1, 1) def start(self): self.animationTimer = QTimer(self) self.connect(self.animationTimer, SIGNAL("timeout()"), self.run) self.animationTimer.start(35) self._isRunning = True def stop(self): if self.animationTimer is not None: self.animationTimer.stop() self.animationTimer = None self._isRunning = False self.repaint() def run(self): self.repaint() self._fillsteps = self._fillsteps[1:] + [self._fillsteps[0]] def paintEvent(self, event): if self._isRunning: anglestep = 360. / self._steps fillsteps = self._fillsteps factor = min(self.width(), self.height()) / 16. bw = self._bw p = QPainter(self) p.setRenderHint(QPainter.Antialiasing, True) p.scale(factor, factor) p.setPen(Qt.NoPen) for i in range(self._steps): x1, y1 = self._coords[i] c = fillsteps[self._steps - 1 - i] a = anglestep * i p.setBrush(QBrush(QColor.fromRgbF(bw, bw, bw, c))) p.save() p.translate(x1 - 2, y1 - 1) p.translate(2, 1) p.rotate(a) p.translate(-2, -1) p.drawPath(self._path) p.restore()
class ProgressWindow(QProgressDialog): def __init__(self, parent, model): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint QProgressDialog.__init__(self, '', "Cancel", 0, 100, parent, flags) self.model = model model.view = self # We don't have access to QProgressDialog's labels directly, so we se the model label's view # to self and we'll refresh them together. self.model.jobdesc_textfield.view = self self.model.progressdesc_textfield.view = self self.setModal(True) self.setAutoReset(False) self.setAutoClose(False) self._timer = QTimer() self._timer.timeout.connect(self.model.pulse) # --- Callbacks def refresh(self): # Labels self.setWindowTitle(self.model.jobdesc_textfield.text) self.setLabelText(self.model.progressdesc_textfield.text) def set_progress(self, last_progress): self.setValue(last_progress) def show(self): QProgressDialog.show(self) self._timer.start(500) def close(self): self._timer.stop() QProgressDialog.close(self)
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()
class RelayTest(QObject): finished = pyqtSignal() progress = pyqtSignal(str) def __init__(self, socket): QObject.__init__(self) self._socket = socket self.start_time, self.end_time = None, None self.addr = None self.received = set() self._sent, self._total = 0, 250 self.host, self.port = None, None self._sendtimer = QTimer() self._sendtimer.timeout.connect(self.send) def start_relay_test(self, address): self.addr = address self._logger.info("Starting relay test") self._socket.data.connect(self.receive) self._socket.permit(self.addr) self.start_time, self.end_time = time.time(), None host, port = self.addr self.host, self.port = QHostAddress(host), port self._sent = 0 self.received = set() self._sendtimer.start(20) end_timer = QTimer() end_timer.singleShot(10000, self.end) @property def report(self): return "Relay address: {}\nReceived {} packets in {}s. {}% loss.". \ format("{}:{}".format(*self.addr), len(self.received), round((time.time()-self.start_time), 2), round(100-(len(self.received)/self._sent) * 100), 2) def send(self): self._socket.writeDatagram(('{}'.format(self._sent)).encode(), self.host, self.port) if self._sent >= self._total: self._sendtimer.stop() self._sent += 1 def end(self): if self.end_time: return self.end_time = time.time() self._sendtimer.stop() self._logger.info('Relay test finished') self.finished.emit() self.socket.data.disconnect(self.receive) def receive(self, sender, data): self.received.add(int(data.decode())) self.progress.emit(self.report) if len(self.received) == self._total: self.end()
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 StatusTabBar(QTabBar): def __init__(self): QTabBar.__init__(self) self.tabTimer = QTimer() self.connect(self.tabTimer, SIGNAL('timeout()'), self.__selectTab) self.setAcceptDrops(True) def dragEnterEvent(self, event): '''Starts timer on enter and sets first position.''' self.tabPos = event.pos() event.accept() self.tabTimer.start(500) def dragLeaveEvent(self, event): '''If the mouse leaves the tabWidget stop the timer.''' self.tabTimer.stop() def dragMoveEvent(self, event): '''Keep track of the mouse and change the position, restarts the timer when moved.''' tabPos = event.pos() moved = tabPos.manhattanLength() - self.tabPos.manhattanLength() if moved > 7 or moved < -7: self.tabTimer.start(500) self.tabPos = tabPos def __selectTab(self): '''Changes the view to the tab where the mouse was hovering above.''' index = self.tabAt(self.tabPos) self.setCurrentIndex(index) self.tabTimer.stop()
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)
class EzSphinxSplitter(QSplitter): """A splitter that backs up its presentation""" def __init__(self, parent, mainwin, name, orientation): QSplitter.__init__(self, parent) self.mainwin = mainwin self.setOrientation(orientation) self.setHandleWidth(7) self.setObjectName(name) self.splitterMoved.connect(self._update_position) self._timer = QTimer() self._timer.timeout.connect(self._timer_exhaust) def load_presentation(self, config): if 'main' in config: main = config['main'] for key, value in main: if key == self.objectName().toUtf8(): self.restoreState(unhexlify(value)) #------------------------------------------------------------------------- # Signal handlers (slots) #------------------------------------------------------------------------- def _update_position(self, pos, index): """^: a splitter has been moved""" self._timer.stop() self._timer.start(1000) def _timer_exhaust(self): """^: timer-filtered event handler for rapid changing UI mods""" data = hexlify(self.saveState()) config = {'main' : [(str(self.objectName().toUtf8()), data)]} self.mainwin.save_presentation(config)
class Channel: def __init__(self, client, channel, start=False, interval=120): self.on = start self.client = client self.channel = channel self.interval = interval self.timer = QTimer() self.timer.connect(self.timer, SIGNAL("timeout()"), self.doquestion) if self.on: self.timer.start(1000)#kind of a hack. problem is client.channels doesnt have the channel yet def nobodygotit(self): self.post("Nobody got it! The answer was \x0310" + self.answer + "\x03.") self.doquestion() def doquestion(self): self.category, self.topics = random.choice(trivia.items()) self.topic, (self.desc, self.questions) = random.choice(self.topics.items()) self.question, (self.answer, self.explanation) = random.choice(self.questions) self.hint = re.sub("[a-zA-Z0-9]", '*', self.answer) self.post("Category:\x039 " + self.category) self.post("Topic:\x0313 " + self.topic + (" - " + self.desc if self.desc else "")) self.post("\x0312" + self.question) if self.on: self.timer.stop() self.timer.start(self.interval*1000) self.timer.disconnect(self.timer, SIGNAL("timeout()"), self.nobodygotit) self.timer.disconnect(self.timer, SIGNAL("timeout()"), self.doquestion) self.timer.connect(self.timer, SIGNAL("timeout()"), self.nobodygotit) def post(self, message): self.client.channels[self.client.conn.irclower(self.channel)].post(message)
class BalanceScreen(object): def __init__(self, conf_path): self.core_app = QtGui.QApplication(sys.argv) self.db_api = db_api.DBApi( utils.get_conf_value(conf_path, 'db', 'db_path')) self.procedure_dialog = Procedure(conf_path) self.mesg_box_dialog = MesgBox(conf_path) self.pay_way_dialog = Pay_way(conf_path, self.procedure_dialog, self.mesg_box_dialog) self.shopping_cart_dialog = ShoppingCart(conf_path, self.procedure_dialog, self.pay_way_dialog) self.recognition_result_win = RecognitionResultWindow( conf_path, self.shopping_cart_dialog, self.procedure_dialog, self.mesg_box_dialog) self.recognition_result_win.button_home.clicked.connect( self.return_home) self.shopping_cart_dialog.button_home.clicked.connect(self.return_home) self.pay_way_dialog.button_home.clicked.connect(self.return_home) self.mesg_box_dialog.hide_button.clicked.connect( self.show_shopping_cart_hide_mesg) self.timeout_timer = QTimer() self.timeout_timer.timeout.connect(self.timeout_handler) def mainloop(self): sys.exit(self.core_app.exec_()) def timeout_handler(self): self.timeout_timer.stop() self.recognition_result_win.hide() self.shopping_cart_dialog.hide() self.pay_way_dialog.hide() def show_shopping_cart_hide_mesg(self): self.shopping_cart_dialog.show() self.mesg_box_dialog.hide() def return_home(self): # self.hide_all_dialog() task_id = self.db_api.get_device_task_id() self.db_api.update_task_status(task_id, 'canceled') new_req_id = utils.generate_uuid() self.db_api.update_device_req_id(new_req_id) logger.info("new req id generate %s" % new_req_id) self.db_api.update_device_status('idle') self.procedure_dialog.show_guide_ui() self.recognition_result_win.timeout_timer.stop() self.pay_way_dialog.lineEdit.clearFocus() self.timeout_timer.start(300) def hide_all_dialog(self): self.procedure_dialog.hide() self.recognition_result_win.hide() self.shopping_cart_dialog.hide() self.pay_way_dialog.hide()
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 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
class SeaAN24(QDialog, Ui_SeaAN24): """ Class documentation goes here. """ n=0 """ 此处用真实搜索到的name:address字典来替换AN24Dict的内容,变量名不要换。 """ #print '111111111111' AN24Dict=init_An24.scan_bluetooth() #!!!!!!!!!!!!!! #print '22222' NameList=[] Address='' Name='' for key in AN24Dict: NameList.append(key) def __init__(self, parent = None): """ Constructor """ QDialog.__init__(self, parent) self.setupUi(self) self.timerScan = QTimer() QtCore.QObject.connect(self.timerScan, SIGNAL("timeout()"),self.addItems) self.timerScan.start(1000) def addItems(self): print 'Scan', SeaAN24.n self.listWidget.addItems([SeaAN24.NameList[SeaAN24.n]]) if SeaAN24.n==len(SeaAN24.AN24Dict)-1: self.timerScan.stop() print 'stop' SeaAN24.n+=1 @pyqtSignature("QListWidgetItem*") def on_listWidget_itemClicked(self, item): """ Slot documentation goes here. """ # TODO: not implemented yet foot=self.listWidget.currentRow() SeaAN24.Name=SeaAN24.NameList[foot] SeaAN24.Address=SeaAN24.AN24Dict[SeaAN24.Name] print SeaAN24.Name, SeaAN24.Address self.pushButton.setEnabled(True) @pyqtSignature("bool") def on_pushButton_clicked(self, checked): """ Slot documentation goes here. """ # TODO: not implemented yet #print '333' DlgCntAN24.show() CntAN24.timerConnecting.start(100)
class TestWindow(QWidget): def __init__(self): super(TestWindow, self).__init__() self.setWindowTitle("LivePlot Example Runner") layout = QHBoxLayout(self) button_layout = QVBoxLayout() time_layout = QHBoxLayout() time_spin = QSpinBox() self.timer = QTimer() time_spin.valueChanged.connect(self.timer.setInterval) self.timer.timeout.connect(self.iterate) self.progress_bar = QProgressBar() time_spin.setValue(50) time_spin.setRange(0, 1000) time_layout.addWidget(QLabel("Sleep Time (ms)")) time_layout.addWidget(time_spin) button_layout.addLayout(time_layout) tests = { 'plot y': test_plot_y, 'plot xy': test_plot_xy, 'plot parametric': test_plot_xy_parametric, 'plot z': test_plot_z, 'plot huge': test_plot_huge, 'append y': test_append_y, 'append xy': test_append_xy, 'append z': test_append_z, 'label': test_label, } fn_text_widget = QPlainTextEdit() fn_text_widget.setMinimumWidth(500) def make_set_iterator(iter): def set_iterator(): fn_text_widget.setPlainText(inspect.getsource(iter)) QApplication.instance().processEvents() self.iterator = iter() self.timer.start() return set_iterator for name, iter in tests.items(): button = QPushButton(name) button.clicked.connect(make_set_iterator(iter)) button_layout.addWidget(button) layout.addLayout(button_layout) text_layout = QVBoxLayout() text_layout.addWidget(fn_text_widget) text_layout.addWidget(self.progress_bar) layout.addLayout(text_layout) def iterate(self): try: self.iterator.next() self.progress_bar.setValue(self.progress_bar.value() + 1) except StopIteration: self.timer.stop() self.progress_bar.setValue(0)
class MusicPosition(plugin.ViewSpacePlugin): def __init__(self, space): self._timer = QTimer(singleShot=True, timeout=self.slotTimeout) self._waittimer = QTimer(singleShot=True, timeout=self.slotTimeout) self._label = QLabel() space.status.layout().insertWidget(1, self._label) self._view = lambda: None space.viewChanged.connect(self.slotViewChanged) view = space.activeView() if view: self.slotViewChanged(view) def slotViewChanged(self, view): old = self._view() if old: self.disconnectView(old) self._view = weakref.ref(view) self.connectView(view) self.startTimer() def connectView(self, view): view.cursorPositionChanged.connect(self.startTimer) view.document().contentsChanged.connect(self.startWaitTimer) def disconnectView(self, view): view.cursorPositionChanged.disconnect(self.startTimer) view.document().contentsChanged.disconnect(self.startWaitTimer) def startWaitTimer(self): """Called when the document changes, waits longer to prevent stutter.""" self._waittimer.start(900) self._timer.stop() def startTimer(self): """Called when the cursor moves.""" if not self._waittimer.isActive(): self._timer.start(100) def slotTimeout(self): """Called when one of the timers fires.""" view = self._view() if view: d = view.document() c = view.textCursor() import documentinfo m = documentinfo.music(d) import ly.duration if c.hasSelection(): cursortools.strip_selection(c) length = m.time_length(c.selectionStart(), c.selectionEnd()) text = _("Length: {length}").format( length=ly.duration.format_fraction( length)) if length is not None else '' else: pos = m.time_position(c.position()) text = _("Pos: {pos}").format(pos=ly.duration.format_fraction( pos)) if pos is not None else '' self._label.setText(text)
class TestWindow(QWidget): def __init__(self): super(TestWindow, self).__init__() self.setWindowTitle("LivePlot Example Runner") layout = QHBoxLayout(self) button_layout = QVBoxLayout() time_layout = QHBoxLayout() time_spin = QSpinBox() self.timer = QTimer() time_spin.valueChanged.connect(self.timer.setInterval) self.timer.timeout.connect(self.iterate) self.progress_bar = QProgressBar() time_spin.setValue(50) time_spin.setRange(0, 1000) time_layout.addWidget(QLabel("Sleep Time (ms)")) time_layout.addWidget(time_spin) button_layout.addLayout(time_layout) tests = { 'plot y': test_plot_y, 'plot xy': test_plot_xy, 'plot parametric': test_plot_xy_parametric, 'plot z': test_plot_z, 'plot huge': test_plot_huge, 'append y': test_append_y, 'append xy': test_append_xy, 'append z': test_append_z, } fn_text_widget = QPlainTextEdit() fn_text_widget.setMinimumWidth(500) def make_set_iterator(iter): def set_iterator(): fn_text_widget.setPlainText(inspect.getsource(iter)) QApplication.instance().processEvents() self.iterator = iter() self.timer.start() return set_iterator for name, iter in tests.items(): button = QPushButton(name) button.clicked.connect(make_set_iterator(iter)) button_layout.addWidget(button) layout.addLayout(button_layout) text_layout = QVBoxLayout() text_layout.addWidget(fn_text_widget) text_layout.addWidget(self.progress_bar) layout.addLayout(text_layout) def iterate(self): try: self.iterator.next() self.progress_bar.setValue(self.progress_bar.value() + 1) except StopIteration: self.timer.stop() self.progress_bar.setValue(0)
class SpeedReader(QDialog): """ SpeedReader is a simple application that provides easy&speed reading for plain text files. """ def __init__(self, parent = None): """ Init Method :param parent: Parent Widget :type parent: QWidget """ QDialog.__init__(self, parent) self.setWindowTitle('Speed Reader') # Add a FunnyLabel self.label = FunnyLabel(self) self.layout = QGridLayout(self) self.layout.addWidget(self.label) # Setup a timer to show next word self.timer = QTimer(self) self.timer.timeout.connect(self._showNextWord) def loadContent(self, content): """ This function loads given content and starts the reading timer. :param path_to_file: Content of the file, content must be PLAINTEXT :type path_to_file: string """ if content: # Stop current timer if its running self.timer.stop() # Load and split the file self.content = unicode(content).split() # Set the current word as 0 self.current = 0 # Burn it! self.timer.start(300) else: self.loadContent('Please use a file which has contents') def _showNextWord(self): """ This function is an internal function to show next word in the content. """ # Get the current word self.label.setText(self.content[self.current]) # Next self.current += 1 # Stop if at EOF if self.current == len(self.content): self.timer.stop()
class SeaAN24(QDialog, Ui_SeaAN24): """ Class documentation goes here. """ n = 0 """ 此处用真实搜索到的name:address字典来替换AN24Dict的内容,变量名不要换。 """ #print '111111111111' AN24Dict = init_An24.scan_bluetooth() #!!!!!!!!!!!!!! #print '22222' NameList = [] Address = '' Name = '' for key in AN24Dict: NameList.append(key) def __init__(self, parent=None): """ Constructor """ QDialog.__init__(self, parent) self.setupUi(self) self.timerScan = QTimer() QtCore.QObject.connect(self.timerScan, SIGNAL("timeout()"), self.addItems) self.timerScan.start(1000) def addItems(self): print 'Scan', SeaAN24.n self.listWidget.addItems([SeaAN24.NameList[SeaAN24.n]]) if SeaAN24.n == len(SeaAN24.AN24Dict) - 1: self.timerScan.stop() print 'stop' SeaAN24.n += 1 @pyqtSignature("QListWidgetItem*") def on_listWidget_itemClicked(self, item): """ Slot documentation goes here. """ # TODO: not implemented yet foot = self.listWidget.currentRow() SeaAN24.Name = SeaAN24.NameList[foot] SeaAN24.Address = SeaAN24.AN24Dict[SeaAN24.Name] print SeaAN24.Name, SeaAN24.Address self.pushButton.setEnabled(True) @pyqtSignature("bool") def on_pushButton_clicked(self, checked): """ Slot documentation goes here. """ # TODO: not implemented yet #print '333' DlgCntAN24.show() CntAN24.timerConnecting.start(100)
class MusicPosition(plugin.ViewSpacePlugin): def __init__(self, space): self._timer = QTimer(singleShot=True, timeout=self.slotTimeout) self._waittimer = QTimer(singleShot=True, timeout=self.slotTimeout) self._label = QLabel() space.status.layout().insertWidget(1, self._label) self._view = lambda: None space.viewChanged.connect(self.slotViewChanged) view = space.activeView() if view: self.slotViewChanged(view) def slotViewChanged(self, view): old = self._view() if old: self.disconnectView(old) self._view = weakref.ref(view) self.connectView(view) self.startTimer() def connectView(self, view): view.cursorPositionChanged.connect(self.startTimer) view.document().contentsChanged.connect(self.startWaitTimer) def disconnectView(self, view): view.cursorPositionChanged.disconnect(self.startTimer) view.document().contentsChanged.disconnect(self.startWaitTimer) def startWaitTimer(self): """Called when the document changes, waits longer to prevent stutter.""" self._waittimer.start(900) self._timer.stop() def startTimer(self): """Called when the cursor moves.""" if not self._waittimer.isActive(): self._timer.start(100) def slotTimeout(self): """Called when one of the timers fires.""" view = self._view() if view: d = view.document() c = view.textCursor() import documentinfo m = documentinfo.music(d) import ly.duration if c.hasSelection(): cursortools.strip_selection(c) length = m.time_length(c.selectionStart(), c.selectionEnd()) text = _("Length: {length}").format( length=ly.duration.format_fraction(length)) if length is not None else '' else: pos = m.time_position(c.position()) text = _("Pos: {pos}").format( pos=ly.duration.format_fraction(pos)) if pos is not None else '' self._label.setText(text)
class MIndicator(QFrame): def __init__(self, parent=None): super(MIndicator, self).__init__(parent) self.__default_font = QFont('Microsoft Yahei', 8, QFont.Normal) self.__pic_bg = QPixmap(':resource') self.displayer = self.MDisplayer(self) self.timer = QTimer(self) QObject.connect(self.timer, SIGNAL('timeout()'), self, SLOT('__roll_text()')) self.timer.setInterval(1000) self.__text = None def setText(self, text): if QFontMetrics(self.__default_font).width(text) + 8 < self.width(): self.__text = QString(text) if self.timer.isActive(): self.timer.stop() elif not self.timer.isActive(): self.__text = QString(text + ' ') self.timer.start() self.displayer.repaint() def getText(self): return self.__text @pyqtSlot() def __roll_text(self): self.__text = self.__text.mid(1) + self.__text.left(1) self.displayer.repaint() def setRollingSpeed(self, int_speed): self.timer.setInterval(int_speed) def getDefaultFont(self): return self.__default_font def paintEvent(self, event): painter = QPainter(self) painter.drawPixmap(0, 0, 10, 23, self.__pic_bg, 25, 70, 10, 23) painter.drawPixmap(10, 0, self.width() - 20, 23, self.__pic_bg, 35, 70, 1, 23) painter.drawPixmap(self.width() - 10, 0, 10, 23, self.__pic_bg, 36, 70, 10, 23) def resizeEvent(self, event): self.displayer.setGeometry(4, 1, event.size().width() - 8, 20) class MDisplayer(QLabel): def __init__(self, parent=None): super(MIndicator.MDisplayer, self).__init__(parent) self.__parent = parent def paintEvent(self, event): painter = QPainter(self) painter.setRenderHint(QPainter.TextAntialiasing) painter.setFont(self.__parent.getDefaultFont()) painter.setPen(QColor(250, 250, 250, 250)) painter.drawText(0, 0, self.width(), self.height(), Qt.AlignVCenter | Qt.AlignHCenter, self.__parent.getText())
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 EventBasedClient(QObject): def __init__(self, clientObject, hostname, port, parentObject, fastForward=False): QObject.__init__(self, parentObject) self.transport = TSocket.TSocket(hostname, port) self.transport = TTransport.TBufferedTransport(self.transport) self.protocol = TBinaryProtocol.TBinaryProtocol(self.transport) self.client = clientObject(self.protocol) self.transport.open() self.lastEventIndex = -1 self.mappings = {} self.playerID = -1 self.playerIDIgnores = [] self.fastForward = fastForward def addMapping(self, eventName, function): # TODO: Add check if mapping really does exist try: self.mappings[eventName] print "Note: Mapping already exists for event %s, overwriting." except KeyError: pass self.mappings[eventName] = function def removeMapping(self, eventName): try: del self.mappings[eventName] except: pass def startEventLoop(self, eventFunction): '''Be sure to have playerID set. Called separately from the constructor to allow subclasses a chance to change, say, lastEventIndex''' self.timer = QTimer(self) self.connect(self.timer, SIGNAL('timeout()'), self.eventLoop) self.timer.start(500); self.eventFunction = eventFunction def endEventLoop(self): self.timer.stop() def eventLoop(self): events = self.eventFunction(self.lastEventIndex) self.lastEventIndex += len(events) for event in events: if event.sender == self.playerID and event.type not in self.playerIDIgnores and not self.fastForward: continue try: eventListener = self.mappings[event.type] except: # Mapping does not exist for event.type print "Unknown event: " + event.type eventListener(event) if self.fastForward: self.fastForward = False
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 Handler(QFrame, Ui_Form): def __init__(self, Exp): super(Handler, self).__init__() self.setupUi(self) self.I = interface.Interface() self.timegap = 0 self.looptimer = QTimer() self.plot = Exp.add2DPlot() self.plot3d = Exp.add3DPlot() self.trace = Exp.addCurve(self.plot, "IV", (255, 0, 255)) Exp.setRange(self.plot, 0, 0, 1.0, 1.5e-3) self.plot.setLabel("bottom", "Voltage -->>", units="V") self.plot.setLabel("left", "Current -->>", units="A") def start(self, x=None): self.Vval = 0.0 self.num = 0 Exp.clearLinesOnPlane(self.plot3d) self.X = [] self.Y = [] self.scaleX = 20 / 0.6 self.offX = -10 self.scaleY = 20 / 1.0e-3 self.offY = -10 if not self.looptimer.isActive(): self.looptimer = Exp.loopTask(self.timegap, self.acquire, 0) def acquire(self, chan): self.I.set_pvs3(self.Vval) V = self.I.get_average_voltage("CH3") I = self.I.get_average_voltage("I2V") self.VLabel.setText("V = %0.2fV" % (V)) self.ILabel.setText("I = %0.2fmA" % (I * 1e3)) self.X.append(V) self.Y.append(I) self.progress.setValue(round(self.Vval * 100 / 1.5)) self.Vval += 0.005 self.trace.setData(self.X, self.Y) if self.Vval > 1.5: Z = [20 - 20.0 * self.num / 50 - 10] * len(self.X) Exp.draw3dLine( self.plot3d, Z, np.array(self.X) * self.scaleX + self.offX, np.array(self.Y) * self.scaleY + self.offY, (0, 100, 255), ) self.X = [] self.Y = [] self.Vval = 0 self.I.set_pvs3(self.Vval) time.sleep(0.1) self.num += 1 if self.num == 50: self.looptimer.stop()
class SystemTrayIcon(QSystemTrayIcon): def __init__(self, icon, altIcon, exe, parent=None): self.icons = { 'main': QIcon(icon), 'alt': QIcon(altIcon), } # Init SystemTrayIcon QSystemTrayIcon.__init__(self, self.icons['main'], parent) self.onclick_exec = exe self.blinker = QTimer() self.blinker.timeout.connect(self.blink) # Add signal handler for button click self.activated.connect(self.onTrayIconActivated) # Create signal handlers for menu self.createActions() # Add menu and set signal handler for mouse clicks menu = QMenu(parent) exitAction = menu.addAction(self.quitAction) self.setContextMenu(menu) def __getitem__(self, key): return self.icons[key] def createActions(self): self.quitAction = QAction("&Quit", self, triggered=qApp.quit) def onTrayIconActivated(self, reason): # If any click other than a right click if reason != QSystemTrayIcon.Context: process = QProcess() process.startDetached(self.onclick_exec) self.stopBlink() def blink(self): QTimer().singleShot(500, lambda: self.setIcon(self.icons['alt'])) QTimer().singleShot(1000, lambda: self.setIcon(self.icons['main'])) def stopBlink(self): if self.blinker.isActive(): self.blinker.stop() def sigUSR1(self, signum, frame): if not self.blinker.isActive(): self.blinker.start(1000) def sigUSR2(self, signum, frame): if self.blinker.isActive(): self.blinker.stop()
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()
class ServerWindow (QMainWindow, Ui_ServerWindow): def __init__(self, pipe = None,xlabel=None,ylabel=None,title=None,parent = None): try: if LOGENABLED: write_log('Initializing server window') QMainWindow.__init__(self, parent) self.setupUi(self) self.setWindowTitle(title) self.pipe=pipe self.setup_plot(title, xlabel, ylabel) write_log ('Starting timer') self.ctimer = QTimer() #Setup autoupdating timer to call update_plots at 10Hz QtCore.QObject.connect(self.ctimer, QtCore.SIGNAL("timeout()"), self.process_command ) # self.connect() self.ctimer.start(10) if LOGENABLED: write_log('timer started') except: if LOGENABLED: log_error() else: pass def setup_plot(self, title, xlabel, ylabel): # self.curvewidget = CurveWidget() # self.setCentralWidget(self.curvewidget) self.curvewidget.add_toolbar(self.addToolBar("Curve")) self.curvewidget.register_all_image_tools() self.plot = self.curvewidget.plot x=np.linspace(-5,5,1000) #Create some sample curves y1=np.cos(x) self.plot_item = make.mcurve(x, y1,label='Magnitude') #Make Ch1 curve self.plot.add_item(self.plot_item) self.plot.set_titles(title=title, xlabel=xlabel, ylabel=ylabel) def process_command(self): self.ctimer.stop() #write_log('process command') try: if self.pipe!=None: while self.pipe.poll(): cmd=self.pipe.recv() #write_log('Received command: '+cmd[0]) ans=getattr(self,cmd[0])(*cmd[1],**cmd[2]) except: if LOGENABLED: log_error('process command') else: pass self.ctimer.start(10) def blah(self,cmd): return 'blahblah' def update_plot(self, data): x, y = data self.plot_item.set_data(x, y) self.plot.replot()
class GuiInitialExtraction(QDialog): def __init__(self, remote, defered): QDialog.__init__(self, remote.le2mclt.screen) self.remote = remote self.defered = defered layout = QVBoxLayout() self.setLayout(layout) explanation_area = WExplication(parent=self, text=texts_DYNCPR.INITIAL_EXTRACTION) layout.addWidget(explanation_area) self.slider_area = MySlider() layout.addWidget(self.slider_area) buttons = QDialogButtonBox(QDialogButtonBox.Ok) buttons.accepted.connect(self._accept) layout.addWidget(buttons) self.setWindowTitle("Decision") self.adjustSize() self.setFixedSize(self.size()) if self.remote.le2mclt.automatique: self.slider_area.slider.setValue( random.randint(pms.DECISION_MIN, pms.DECISION_MAX * int(1 / pms.DECISION_STEP))) self.timer_automatique = QTimer() self.timer_automatique.timeout.connect( buttons.button(QDialogButtonBox.Ok).click) self.timer_automatique.start(7000) def _accept(self): try: self.timer_automatique.stop() except AttributeError: pass val = self.slider_area.slider.value() / int(1 / pms.DECISION_STEP) if not self.remote.le2mclt.automatique: confirmation = QMessageBox.question( self, "Confirmation", trans_DYNCPR(u"Do you confirm your choice?"), QMessageBox.No | QMessageBox.Yes) if confirmation != QMessageBox.Yes: return self.accept() logger.info("send {}".format(val)) self.defered.callback(val) def reject(self): pass
class VariableManager(plugin.DocumentPlugin): """Caches variables in the document and monitors for changes. The changed() Signal is emitted some time after the list of variables has been changed. It is recommended to not change the document itself in response to this signal. """ changed = signals.Signal() # without argument def __init__(self, document): self._updateTimer = QTimer(singleShot=True, timeout=self.slotTimeout) self._variables = self.readVariables() document.contentsChange.connect(self.slotContentsChange) document.closed.connect(self._updateTimer.stop) # just to be sure def slotTimeout(self): variables = self.readVariables() if variables != self._variables: self._variables = variables self.changed() def slotContentsChange(self, position, removed, added): """Called if the document changes.""" if (self.document().findBlock(position).blockNumber() < _LINES or self.document().findBlock(position + added).blockNumber() > self.document().blockCount() - _LINES): self._updateTimer.start(500) def variables(self): """Returns the document variables (cached) as a dictionary. This method is recommended.""" if self._updateTimer.isActive(): # an update is pending, force it self._updateTimer.stop() self.slotTimeout() return self._variables def readVariables(self): """Reads the variables from the document and returns a dictionary. Internal.""" count = self.document().blockCount() blocks = [self.document().firstBlock()] if count > _LINES * 2: blocks.append(self.document().findBlockByNumber(count - _LINES)) count = _LINES def lines(block): for i in range(count): yield block.text() block = block.next() variables = {} for block in blocks: variables.update(m.group(1, 2) for n, m in positions(lines(block))) return variables
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
class StateSetting(Setting): """Stores the last state of application. The state after start-up is determined programmatically; the value set during configuration loading will be ignored. """ name = 'state_on' state = None require = { ModeSettings, EnableNightMode } @property def value(self): if self.mode_settings.mode == 'manual': return self.enable_night_mode.value else: return self.mode_settings.is_active @value.setter def value(self, value): pass def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # check the state every 60 seconds # (maybe a bit suboptimal, but the most reliable) from aqt import mw as main_window self.timer = QTimer(main_window) self.timer.setInterval(60 * 100) # 1000 milliseconds self.timer.timeout.connect(self.maybe_enable_maybe_disable) def on_load(self): if self.value: self.app.on() self.update_state() self.timer.start() def on_save(self): self.timer.stop() def maybe_enable_maybe_disable(self): if self.value != self.state: self.app.refresh() self.update_state() def update_state(self): self.state = self.value
class Handler(QFrame, Ui_Form): def __init__(self, Exp): super(Handler, self).__init__() self.setupUi(self) self.I = interface.Interface() self.timegap = 0 self.looptimer = QTimer() self.plot = Exp.add2DPlot() self.plot3d = Exp.add3DPlot() self.trace = Exp.addCurve(self.plot, 'IV', (255, 0, 255)) Exp.setRange(self.plot, 0, 0, 1.0, 1.5e-3) self.plot.setLabel('bottom', 'Voltage -->>', units='V') self.plot.setLabel('left', 'Current -->>', units='A') def start(self, x=None): self.Vval = 0. self.num = 0 Exp.clearLinesOnPlane(self.plot3d) self.X = [] self.Y = [] self.scaleX = 20 / 0.6 self.offX = -10 self.scaleY = 20 / 1.0e-3 self.offY = -10 if (not self.looptimer.isActive()): self.looptimer = Exp.loopTask(self.timegap, self.acquire, 0) def acquire(self, chan): self.I.set_pvs2(self.Vval) V = self.I.get_average_voltage('CH4') I = self.I.get_average_voltage('CH1') / 441 self.VLabel.setText('V = %0.2fV' % (V)) self.ILabel.setText('I = %0.2fmA' % (I * 1e3)) self.X.append(V) self.Y.append(I) self.progress.setValue(round(self.Vval * 100 / 1.5)) self.Vval += 0.005 self.trace.setData(self.X, self.Y) if (self.Vval > 1.5): Z = [20 - 20. * self.num / 50 - 10] * len(self.X) Exp.draw3dLine(self.plot3d, Z, np.array(self.X) * self.scaleX + self.offX, np.array(self.Y) * self.scaleY + self.offY, (0, 100, 255)) self.X = [] self.Y = [] self.Vval = 0 self.num += 1 if (self.num == 50): self.looptimer.stop()
class CntAN24(QDialog, Ui_CntAN24): """ Class documentation goes here. """ def __init__(self, DlgSelect, parent=None): """ Constructor """ QDialog.__init__(self, parent) self.setupUi(self) self.count = 0 self.timerConnecting = QTimer() QtCore.QObject.connect(self.timerConnecting, SIGNAL("timeout()"), self.connectAN24) self.DlgSeaAN24 = DlgSelect self.DlgChkAN24 = ChkAN24(self.DlgSeaAN24) def connectAN24(self): self.label.setText(self.DlgSeaAN24.Name + u"正在连接……") self.repaint() self.count += 1 print self.count, '----------CntAN24.count' """ 此处连接蓝牙的函数,参数为SeaAN24.Address,return connected,a bool. """ print time.ctime() time.sleep(2) connected = random.randint(0, 1) if connected: print 'successful connection!' self.label.setText(self.DlgSeaAN24.Name + u"连接成功!") self.repaint() self.timerConnecting.stop() time.sleep(1) self.close() self.DlgChkAN24.show() print 'close' else: if self.count == 2: self.label.setText(self.DlgSeaAN24.Name + u"连接失败,请重新选择") self.repaint() self.timerConnecting.stop() self.count = 0 time.sleep(1) self.close() self.DlgSeaAN24.show()
class TimedProgressBar(QProgressBar): """A QProgressBar showing a certain time elapse.""" hideOnTimeout = True def __init__(self, parent=None): super(TimedProgressBar, self).__init__(parent, minimum=0, maximum=100) self._timeline = QTimeLine(updateInterval=100, frameChanged=self.setValue) self._timeline.setFrameRange(0, 100) self._hideTimer = QTimer(timeout=self._done, singleShot=True, interval=3000) def start(self, total, elapsed=0.0): """Starts showing progress. total is the number of seconds (maybe float) the timeline will last, elapsed (defaulting to 0) is the value to start with. """ self._hideTimer.stop() self._timeline.stop() self._timeline.setDuration(total * 1000) self._timeline.setCurrentTime(elapsed * 1000) self.setValue(self._timeline.currentFrame()) self._timeline.resume() if self.hideOnTimeout: self.show() def stop(self, showFinished=True): """Ends the progress display. If showFinished is True (the default), 100% is shown for a few seconds and then the progress is reset. The progressbar is hidden if the hideOnTimeout attribute is True. """ self._hideTimer.stop() self._timeline.stop() if showFinished: self.setValue(100) self._hideTimer.start() else: self._done() def _done(self): if self.hideOnTimeout: self.hide() self.reset()
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()
class MitSchemeShell: """MIT scheme shell. Implements REPL. Graphical frontend for original terminal version. """ def __init__(self): self._term = _MitSchemeTermWidget(self) self._term.show() self._processOutputTimer = QTimer( ) # I use Qt timer, because we must append data to GUI in the GUI thread self._processOutputTimer.timeout.connect(self._processOutput) self._processOutputTimer.setInterval(100) self._bufferedPopen = BufferedPopen("scheme") self._schemeIsRunning = False self._term.appendOutput( "Execute any command to run scheme interpreter\n") def __del__(self): self.stop() def start(self): self._bufferedPopen.start() self._processOutputTimer.start() self._schemeIsRunning = True def stop(self): self._processOutputTimer.stop() self._bufferedPopen.stop() self._schemeIsRunning = False def execCommand(self, text): if not self._schemeIsRunning: self.start() self._processOutput( ) # write old output to the log, and only then write fresh input self._bufferedPopen.write(text) def _processOutput(self): output = self._bufferedPopen.readOutput() if output: self._term.appendOutput(output) if self._schemeIsRunning and not self._bufferedPopen.isAlive(): self._term.appendError( "Interpreter process exited. Execute any command to run it again\n" ) self.stop()
class _CompleterConstructorThread(threading.Thread): """Thread constructs Completer Sometimes it requires a lot of time, i.e. when expanding "/usr/lib/*" hlamer: I tried to use QThread + pyqtSignal, but got tired with crashes and deadlocks """ def __init__(self, locator): """Works in the GUI thread """ threading.Thread.__init__(self) self._locator = locator self._queue = Queue.Queue() self._checkQueueTimer = QTimer() self._checkQueueTimer.setInterval(50) self._checkQueueTimer.timeout.connect(self._checkQueue) def _checkQueue(self): """Check if thread constructed a completer and put it to the queue Works in the GUI thread """ if not self._queue.empty(): command, completer = self._queue.get() self._locator._applyCompleter(command, completer) def start(self, command, text, cursorPos): """Start constructing completer Works in the GUI thread """ self._terminated = False self._command = command self._text = text self._cursorPos = cursorPos self._checkQueueTimer.start() threading.Thread.start(self) def terminate(self): """Set termination flag Works in the GUI thread """ self._checkQueueTimer.stop() def run(self): """Thread function Works in NEW thread """ completer = self._command.completer(self._text, self._cursorPos) self._queue.put([self._command, completer])
def fetchFiles(self, urls): self.logT("TileLayer.fetchFiles() starts") # create a QEventLoop object that belongs to the current thread (if ver. > 2.1, it is render thread) eventLoop = QEventLoop() self.logT("Create event loop: " + str(eventLoop)) # DEBUG QObject.connect(self, SIGNAL("allRepliesFinished()"), eventLoop.quit) # create a timer to watch whether rendering is stopped watchTimer = QTimer() watchTimer.timeout.connect(eventLoop.quit) # send a fetch request to the main thread self.emit(SIGNAL("fetchRequest(QStringList)"), urls) # wait for the fetch to finish tick = 0 interval = 500 timeoutTick = self.plugin.downloadTimeout * 1000 / interval watchTimer.start(interval) while tick < timeoutTick: # run event loop for 0.5 seconds at maximum eventLoop.exec_() if debug_mode: qDebug("watchTimerTick: %d" % tick) qDebug("unfinished downloads: %d" % self.downloader.unfinishedCount()) if self.downloader.unfinishedCount( ) == 0 or self.renderContext.renderingStopped(): break tick += 1 watchTimer.stop() if tick == timeoutTick and self.downloader.unfinishedCount() > 0: self.log("fetchFiles timeout") # self.showBarMessage("fetchFiles timeout", duration=5) #DEBUG self.downloader.abort() self.downloader.errorStatus = Downloader.TIMEOUT_ERROR files = self.downloader.fetchedFiles watchTimer.timeout.disconnect(eventLoop.quit) # QObject.disconnect(self, SIGNAL("allRepliesFinished()"), eventLoop.quit) self.logT("TileLayer.fetchFiles() ends") return files
class HATZero(COMCUPluginBase, Ui_HATZero): def __init__(self, *args): COMCUPluginBase.__init__(self, BrickletHATZero, *args) self.setupUi(self) self.hat_zero = self.device self.ports = [self.port_a, self.port_b, self.port_c, self.port_d] self.update_timer = QTimer() self.update_timer.timeout.connect(self.update_bricklets) def port_label_clicked(self, event, uid): get_main_window().show_plugin(uid) def get_port_label_clicked_lambda(self, uid): return lambda x: self.port_label_clicked(x, uid) def update_bricklets(self): try: bricklets = infos.get_info(self.uid).connections for i in range(4): port = chr(ord('a') + i) try: bricklet = bricklets[port] text = '{0} ({1})'.format(bricklet.name, bricklet.uid) if text != self.ports[i].text(): self.ports[i].setText(text) self.ports[ i].mousePressEvent = self.get_port_label_clicked_lambda( bricklet.uid) except: self.ports[i].setText('Not Connected') except: pass def start(self): self.update_timer.start(500) def stop(self): self.update_timer.stop() def destroy(self): pass @staticmethod def has_device_identifier(device_identifier): return device_identifier == BrickletHATZero.DEVICE_IDENTIFIER
class MemUsageDialog(QDialog): def __init__(self, parent=None, update=True): QDialog.__init__(self, parent=parent) layout = QVBoxLayout() self.tree = QTreeWidget() layout.addWidget(self.tree) self.setLayout(layout) self._mgr = CacheMemoryManager() self._tracked_caches = {} # tree setup code self.tree.setHeaderLabels( ["cache", "memory", "roi", "dtype", "type", "info", "id"]) self._idIndex = self.tree.columnCount() - 1 self.tree.setColumnHidden(self._idIndex, True) self.tree.setSortingEnabled(True) self.tree.clear() self._root = TreeNode() # refresh every x seconds (see showEvent()) self.timer = QTimer(self) if update: self.timer.timeout.connect(self._updateReport) def _updateReport(self): # we keep track of dirty reports so we just have to update the tree # instead of reconstructing it reports = [] for c in self._mgr.getFirstClassCaches(): r = MemInfoNode() c.generateReport(r) reports.append(r) self._root.handleChildrenReports(reports, root=self.tree.invisibleRootItem()) def hideEvent(self, event): self.timer.stop() def showEvent(self, show): # update once so we don't have to wait for initial report self._updateReport() # update every 5 sec. self.timer.start(5 * 1000)