当前位置: 首页>>代码示例>>Python>>正文


Python QtCore.QThread类代码示例

本文整理汇总了Python中AnyQt.QtCore.QThread的典型用法代码示例。如果您正苦于以下问题:Python QThread类的具体用法?Python QThread怎么用?Python QThread使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了QThread类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_methodinvoke

    def test_methodinvoke(self):
        executor = ThreadExecutor()
        state = [None, None]

        class StateSetter(QObject):
            @Slot(object)
            def set_state(self, value):
                state[0] = value
                state[1] = QThread.currentThread()

        def func(callback):
            callback(QThread.currentThread())

        obj = StateSetter()
        f1 = executor.submit(func, methodinvoke(obj, "set_state", (object,)))
        f1.result()

        # So invoked method can be called
        QCoreApplication.processEvents()

        self.assertIs(state[1], QThread.currentThread(),
                      "set_state was called from the wrong thread")

        self.assertIsNot(state[0], QThread.currentThread(),
                         "set_state was invoked in the main thread")

        executor.shutdown(wait=True)
开发者ID:RachitKansal,项目名称:orange3,代码行数:27,代码来源:concurrent.py

示例2: test_task

    def test_task(self):
        results = []

        task = Task(function=QThread.currentThread)
        task.resultReady.connect(results.append)

        task.start()
        self.app.processEvents()

        self.assertSequenceEqual(results, [QThread.currentThread()])

        thread = QThread()
        thread.start()
        try:
            task = Task(function=QThread.currentThread)
            task.moveToThread(thread)

            self.assertIsNot(task.thread(), QThread.currentThread())
            self.assertIs(task.thread(), thread)
            results = Future()

            def record(value):
                # record the result value and the calling thread
                results.set_result((QThread.currentThread(), value))

            task.resultReady.connect(record, Qt.DirectConnection)
            task.start()
            f = task.future()
            emit_thread, thread_ = results.result(3)
            self.assertIs(f.result(3), thread)
            self.assertIs(emit_thread, thread)
            self.assertIs(thread_, thread)
        finally:
            thread.quit()
            thread.wait()
开发者ID:PrimozGodec,项目名称:orange3,代码行数:35,代码来源:test_concurrent.py

示例3: X11EventPoller

class X11EventPoller(QObject):
    keyPressed = pyqtSignal(object, object)

    def __init__(self):
        QObject.__init__(self)
        self._display = Display()
        self._thread = QThread()
        self.moveToThread(self._thread)
        self._thread.start()

    def start(self):
        QTimer.singleShot(0, self.run)

    def run(self):
        ctx = self._display.record_create_context(0,
                                                  [record.CurrentClients],
                                                  [{
                                                      'core_requests': (0, 0),
                                                      'core_replies': (0, 0),
                                                      'ext_requests': (0, 0, 0, 0),
                                                      'ext_replies': (0, 0, 0, 0),
                                                      'delivered_events': (0, 0),
                                                      'device_events': (X.KeyPress, X.KeyRelease),
                                                      'errors': (0, 0),
                                                      'client_started': False,
                                                      'client_died': False,
                                                  }])
        self._display.record_enable_context(ctx, self._record_callback)
        self._display.record_free_context(ctx)

    def _record_callback(self, reply):
        QApplication.processEvents()
        if reply.category != record.FromServer:
            return
        if reply.client_swapped:
            # received swapped protocol data, cowardly ignored
            return
        if not len(reply.data) or reply.data[0] < 2:
            # not an event
            return

        data = reply.data
        while len(data):
            event, data = rq.EventField(None).parse_binary_value(data, self._display.display, None, None)
            self.keyPressed.emit(event, data)

    def destroy(self):
        # self._thread.terminate()
        self._thread.wait()
开发者ID:rokups,项目名称:paste2box,代码行数:49,代码来源:global_hotkey_x11.py

示例4: __onRunFinished

    def __onRunFinished(self):
        assert QThread.currentThread() is self.thread()
        assert self.__state == State.Processing
        assert self.__pendingTask is not None
        assert self.sender() is self.__pendingTask.watcher
        assert self.__pendingTask.future.done()
        task = self.__pendingTask
        self.__pendingTask = None

        try:
            data, n_skipped = task.future.result()
        except Exception:
            sys.excepthook(*sys.exc_info())
            state = State.Error
            data = None
            n_skipped = 0
            self.error(traceback.format_exc())
        else:
            state = State.Done
            self.error()

        if data:
            self._n_image_data = len(data)
            self._n_image_categories = len(data.domain.class_var.values)\
                if data.domain.class_var else 0
        else:
            self._n_image_data, self._n_image_categories = 0, 0

        self.data = data
        self._n_skipped = n_skipped

        self.__setRuntimeState(state)
        self.commit()
开发者ID:biolab,项目名称:orange3-imageanalytics,代码行数:33,代码来源:owimageimport.py

示例5: __onRunFinished

    def __onRunFinished(self):
        assert QThread.currentThread() is self.thread()
        assert self.__state == State.Processing
        assert self.__pendingTask is not None
        assert self.sender() is self.__pendingTask.watcher
        assert self.__pendingTask.future.done()
        task = self.__pendingTask
        self.__pendingTask = None

        try:
            corpus, errors = task.future.result()
        except Exception:
            sys.excepthook(*sys.exc_info())
            state = State.Error
            corpus = None
            errors = []
            self.error(traceback.format_exc())
        else:
            state = State.Done
            self.error()

        if corpus:
            self.n_text_data = len(corpus)
            self.n_text_categories = len(corpus.domain.class_var.values)\
                if corpus.domain.class_var else 0

        self.corpus = corpus
        self.n_skipped = len(errors)

        if len(errors):
            self.Warning.read_error("Some files" if len(errors) > 1 else "One file")

        self.__setRuntimeState(state)
        self.commit()
开发者ID:s-alexey,项目名称:orange3-text,代码行数:34,代码来源:owimportdocuments.py

示例6: _task_finished

    def _task_finished(self, f):
        """
        Parameters
        ----------
        f : Future
            The future instance holding the built model
        """
        assert self.thread() is QThread.currentThread()
        assert self._task is not None
        assert self._task.future is f
        assert f.done()
        self._task.deleteLater()
        self._task = None
        self.setBlocking(False)
        self.progressBarFinished()

        try:
            self.model = f.result()
        except Exception as ex:  # pylint: disable=broad-except
            # Log the exception with a traceback
            log = logging.getLogger()
            log.exception(__name__, exc_info=True)
            self.model = None
            self.show_fitting_failed(ex)
        else:
            self.model.name = self.learner_name
            self.model.instances = self.data
            self.model.skl_model.orange_callback = None  # remove unpicklable callback
            self.Outputs.model.send(self.model)
开发者ID:PrimozGodec,项目名称:orange3,代码行数:29,代码来源:owneuralnetwork.py

示例7: _task_finished

    def _task_finished(self, f):
        """
        Parameters:
        ----------
        f: conncurent.futures.Future
            future instance holding the result of learner evaluation
        """
        assert self.thread() is QThread.currentThread()
        assert self._task is not None
        assert self._task.future is f
        assert f.done()

        self._task = None

        if not self.was_canceled:
            self.cancel_button.setDisabled(True)

        try:
            results = f.result()
        except Exception as ex:
            log = logging.getLogger()
            log.exception(__name__, exc_info=True)
            self.error("Exception occured during evaluation: {!r}".format(ex))

            for key in self.results.keys():
                self.results[key] = None
        else:
            self.update_view(results[1])

        self.progressBarFinished(processEvents=False)
开发者ID:pavlin-policar,项目名称:orange3-prototypes,代码行数:30,代码来源:owexplpredictions.py

示例8: run

    def run(self):
        """
        Reimplemented from `QRunnable.run`
        """
        self.eventLoop = QEventLoop()
        self.eventLoop.processEvents()

        # Move the task to the current thread so it's events, signals, slots
        # are triggered from this thread.
        assert self.task.thread() is _TaskDepotThread.instance()

        QMetaObject.invokeMethod(
            self.task.thread(), "transfer", Qt.BlockingQueuedConnection,
            Q_ARG(object, self.task),
            Q_ARG(object, QThread.currentThread())
        )

        self.eventLoop.processEvents()

        # Schedule task.run from the event loop.
        self.task.start()

        # Quit the loop and exit when task finishes or is cancelled.
        self.task.finished.connect(self.eventLoop.quit)
        self.task.cancelled.connect(self.eventLoop.quit)
        self.eventLoop.exec_()
开发者ID:astaric,项目名称:orange3,代码行数:26,代码来源:concurrent.py

示例9: setBioMartDatasets

 def setBioMartDatasets(self, datasets):
     assert(QThread.currentThread() is self.thread())
     self.setEnabled(True)
     self.datasets = [data for data in datasets if
                      getattr(data, "visible", "0") != "0"]
     self.datasetsCombo.clear()
     self.datasetsCombo.addItems([data.displayName for data in self.datasets])
开发者ID:JakaKokosar,项目名称:orange-bio,代码行数:7,代码来源:OWBioMart.py

示例10: initialize

    def initialize(self):
        """
        Clear and initialize the dialog.

        This method must be called by the widget when the data is reset,
        e.g. from `set_data` handler.
        """
        if self._thread is not None and self._thread.isRunning():
            self.keep_running = False
            self._thread.quit()
            self._thread.wait()
        self.keep_running = False
        self.scheduled_call = None
        self.saved_state = None
        self.saved_progress = 0
        self.update_timer.stop()
        self.progressBarFinished()
        self.scores = []
        self._update_model()  # empty queue
        self.rank_model.clear()
        self.button.setText("Start")
        self.button.setEnabled(self.check_preconditions())
        self._thread = QThread(self)
        self._worker = Worker(self)
        self._worker.moveToThread(self._thread)
        self._worker.stopped.connect(self._thread.quit)
        self._worker.stopped.connect(self._select_first_if_none)
        self._worker.stopped.connect(self._stopped)
        self._worker.done.connect(self._done)
        self._thread.started.connect(self._worker.do_work)
开发者ID:lanzagar,项目名称:orange3,代码行数:30,代码来源:__init__.py

示例11: __emitpending

    def __emitpending(self, index, future):
        # type: (int, Future) -> None
        assert QThread.currentThread() is self.thread()
        assert self.__futures[index] is future
        assert future.done()
        assert self.__countdone < len(self.__futures)
        self.__futures[index] = None
        self.__countdone += 1

        if future.cancelled():
            self.cancelledAt.emit(index, future)
            self.doneAt.emit(index, future)
        elif future.done():
            self.finishedAt.emit(index, future)
            self.doneAt.emit(index, future)
            if future.exception():
                self.exceptionReadyAt.emit(index, future.exception())
            else:
                self.resultReadyAt.emit(index, future.result())
        else:
            assert False

        self.progressChanged.emit(self.__countdone, len(self.__futures))

        if self.__countdone == len(self.__futures):
            self.doneAll.emit()
开发者ID:astaric,项目名称:orange3,代码行数:26,代码来源:concurrent.py

示例12: __commit_complete

    def __commit_complete(self, f):
        # complete the commit operation after the required file has been
        # downloaded
        assert QThread.currentThread() is self.thread()
        assert self.__awaiting_state is not None
        assert self.__awaiting_state.future is f

        if self.isBlocking():
            self.progressBarFinished(processEvents=None)
            self.setBlocking(False)
            self.setStatusMessage("")

        self.__awaiting_state = None

        try:
            path = f.result()
        except Exception as ex:
            log.exception("Error:")
            self.error(format_exception(ex))
            path = None

        self.__update_cached_state()

        if path is not None:
            data = Orange.data.Table(path)
        else:
            data = None
        self.Outputs.data.send(data)
开发者ID:nikicc,项目名称:orange3,代码行数:28,代码来源:owdatasets.py

示例13: __accepted

    def __accepted(self):
        steps = self.addonwidget.itemState()

        if steps:
            # Move all uninstall steps to the front
            steps = sorted(
                steps, key=lambda step: 0 if step[0] == Uninstall else 1
            )
            self.__installer = Installer(steps=steps)
            self.__thread = QThread(self)
            self.__thread.start()

            self.__installer.moveToThread(self.__thread)
            self.__installer.finished.connect(self.__on_installer_finished)
            self.__installer.error.connect(self.__on_installer_error)

            progress = self.progressDialog()

            self.__installer.installStatusChanged.connect(progress.setLabelText)
            progress.show()
            progress.setLabelText("Installing")
            self.__installer.start()

        else:
            self.accept()
开发者ID:ales-erjavec,项目名称:orange-canvas,代码行数:25,代码来源:addons.py

示例14: __onReportProgress

 def __onReportProgress(self, arg):
     # report on scan progress from a worker thread
     # arg must be a namespace(count: int, lastpath: str)
     assert QThread.currentThread() is self.thread()
     if self.__state == State.Processing:
         self.pathlabel.setText(prettifypath(arg.lastpath))
         self.progress_widget.setValue(arg.progress)
         self.progress_widget.setValue(100 * arg.progress)
开发者ID:s-alexey,项目名称:orange3-text,代码行数:8,代码来源:owimportdocuments.py

示例15: _handleException

 def _handleException(self, exception):
     assert(QThread.currentThread() is self.thread())
     print("Task failed with:", exception, file=sys.stderr)
     import logging
     log = logging.getLogger(__name__)
     log.exception("Error:", exc_info=exception)
     self.error(0, str(exception))
     self.setEnabled(True)
开发者ID:JakaKokosar,项目名称:orange-bio,代码行数:8,代码来源:OWBioMart.py


注:本文中的AnyQt.QtCore.QThread类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。