Beispiel #1
0
class MainWindow(QMainWindow):
    startBut = Signal()

    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.manager = Manager(self)
        self.__threadRun = QThread()
        self.__threadRun.start()
        self.manager.moveToThread(self.__threadRun)

        self.ui.openFile_button.clicked.connect(self.openFileButtonClicked)
        self.ui.start_button.clicked.connect(self.startButtonClicked)
        self.startBut.connect(self.manager.startButtonClicked)

        self.manager.sendMessageConsole.connect(self.setMessage)

    def setMessage(self, message):
        self.ui.console_textBrowser.append(message)

    def openFileButtonClicked(self):
        path_to_file, _ = QFileDialog.getOpenFileName(
            self, self.tr("Load Image"), self.tr("~/Desktop/"),
            self.tr("Images (*.png *.jpg)"))
        self.manager.setImage(path_to_file)
        pix = QPixmap(path_to_file)
        pix = pix.scaled(640, 480, Qt.KeepAspectRatio)
        self.ui.inputImage_label.setPixmap(pix)

    def startButtonClicked(self):
        self.startBut.emit()
Beispiel #2
0
class Device:
    def __init__(self, device: hs100.HS100, deviceID: str, deviceName: str):
        # -Variables-
        self._device = device
        self.state = 0
        self.deviceID = deviceID
        self.deviceName = deviceName
        # Set threads
        self._turn_on = QThread()
        self._turn_off = QThread()
        self._turn_on.run = self._device.power_on
        self._turn_off.run = self._device.power_off
        self.refresh()

    def refresh(self):
        """
        Refresh the data of this station:
            - Update state
        """
        if self._device is None:
            return
        pass

    def turn_on(self):
        """Turn on the device"""
        self._turn_on.start()

    def turn_off(self):
        """Turn off the device"""
        self._turn_off.start()
Beispiel #3
0
class Torrents2Tab(QWidget):
    newtorrents = Signal(int)

    def __init__(self):
        QWidget.__init__(self)
        layout = QVBoxLayout(self)
        self.splitter = QSplitter(self)
        self.list = QTreeView(self)
        self.list.setSortingEnabled(True)
        self.model = NewTorrentModel()
        proxy = QSortFilterProxyModel()
        proxy.setSourceModel(self.model)
        self.list.setModel(proxy)
        self.splitter.addWidget(self.list)
        self.t = QTableWidget(0, 4, self)
        self.splitter.addWidget(self.t)
        layout.addWidget(self.splitter)
        self.setLayout(layout)
        self.ds = DataSource()
        self.worker = UpdateTorrentWorker()
        self.worker_thread = QThread()
        self.worker_thread.started.connect(self.worker.run)
        self.worker.finished.connect(self.worker_thread.quit)
        self.worker.moveToThread(self.worker_thread)
        self.worker_thread.start()
        self.worker.processed.connect(self.processed)

    def finish(self):
        self.worker.finish()
        self.worker_thread.quit()
        self.worker_thread.wait()

    def processed(self, topic):
        self.model.add_topic(topic['published'])
def main(distress_queue, message_queue, audio_queue_out, audio_queue_in):

    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)

    print('Begin server gui')

    device_db, message_db, audio_sent_db, audio_recv_db = helper.init_db()

    app = QApplication(sys.argv)

    window = MainWindow(device_db, message_db, audio_sent_db, audio_recv_db,
                        audio_queue_out, audio_queue_in, message_queue)

    distress_reciever = window.ui.insert_distress_message
    distress_worker = Distress_Object(distress_queue)
    distress_worker.aSignal.connect(distress_reciever)
    distress_thread = QThread()
    distress_worker.moveToThread(distress_thread)
    distress_thread.started.connect(distress_worker.run)
    distress_thread.start()

    audio_reciever = window.ui.insert_audio_recieved
    audio_worker = Audio_Object(audio_queue_in)
    audio_worker.bSignal.connect(audio_reciever)
    audio_thread = QThread()
    audio_worker.moveToThread(audio_thread)
    audio_thread.started.connect(audio_worker.run)
    audio_thread.start()

    window.show()

    sys.exit(app.exec_())

    print('End server gui')
    def start_threads(self):
        self.log.append('starting {} threads'.format(self.NUM_THREADS))
        self.button_start_threads.setDisabled(True)
        self.button_stop_threads.setEnabled(True)

        self.__workers_done = 0
        self.__threads = []
        for idx in range(self.NUM_THREADS):
            worker = Worker(idx)
            thread = QThread()
            thread.setObjectName('thread_' + str(idx))
            self.__threads.append((thread, worker))  # need to store worker too otherwise will be gc'd
            worker.moveToThread(thread)

            # get progress messages from worker:
            worker.sig_step.connect(self.on_worker_step)
            worker.sig_done.connect(self.on_worker_done)
            worker.sig_msg.connect(self.log.append)

            # control worker:
            self.sig_abort_workers.connect(worker.abort)

            # get read to start worker:
            # self.sig_start.connect(worker.work)  # needed due to PyCharm debugger bug (!); comment out next line
            thread.started.connect(worker.work)
            thread.start()  # this will emit 'started' and start thread's event loop
Beispiel #6
0
class _PluginWorker(QObject):

    finished = Signal()

    def __init__(self):
        super().__init__()
        self._thread = QThread()
        self.moveToThread(self._thread)
        self._function = None
        self._args = None
        self._kwargs = None

    def start(self, function, *args, **kwargs):
        self._thread.started.connect(self._do_work)
        self._function = function
        self._args = args
        self._kwargs = kwargs
        self._thread.start()

    @Slot()
    def _do_work(self):
        self._function(*self._args, **self._kwargs)
        self.finished.emit()

    def clean_up(self):
        self._thread.quit()
        self._thread.wait()
        self.deleteLater()
class Backend(QObject):
    setval = Signal(QtCharts.QXYSeries)  
    
    def __init__(self, parent=None):
        QObject.__init__(self, parent)
        self._serie = None
    
    @Slot(QtCharts.QXYSeries) # expose QML serie to Python
    def exposeserie(self, serie):
        self._serie = serie
        # print(serie)
        # print("QML serie exposed to Python")
        
    @Slot(str)
    def startthread(self, text):
        self.WorkerThread = QThread()
        self.worker = Worker1(self._serie)
        self.WorkerThread.started.connect(self.worker.run)
        self.worker.finished.connect(self.end)
        self.worker.set_val.connect(self.setval)
        self.worker.moveToThread(self.WorkerThread)  # Move the Worker object to the Thread object
        self.WorkerThread.start()
        
    @Slot(str)     
    def stopthread(self, text):
        self.worker.stop()
        print("CLOSING THREAD")
               
    def end(self):
        self.WorkerThread.quit()
        self.WorkerThread.wait()
        msgBox = QMessageBox() 
        msgBox.setText("THREAD CLOSED")
        msgBox.exec()
class Form(QMainWindow):
    def __init__(self, splash):
        super(Form, self).__init__()
        self.resize(800, 600)

        self.splash = splash

        self.load_thread = QThread()
        self.load_worker = LoadData()
        self.load_worker.moveToThread(self.load_thread)
        self.load_thread.started.connect(self.load_worker.run)
        self.load_worker.message_signal.connect(self.set_message)
        self.load_worker.finished.connect(self.load_worker_finished)
        self.load_thread.start()

        while self.load_thread.isRunning():
            QtWidgets.QApplication.processEvents()  # 不断刷新,保证动画流畅

        self.load_thread.deleteLater()

    def load_worker_finished(self):
        self.load_thread.quit()
        self.load_thread.wait()

    def set_message(self, message):
        self.splash.showMessage(message, Qt.AlignLeft | Qt.AlignBottom,
                                Qt.white)
Beispiel #9
0
class Collector(QObject):

    valuesChanged = Signal(object, object)

    def __init__(self, portName):
        super().__init__()
        self.portName = portName
        self.thread = QThread()
        self.moveToThread(self.thread)
        self.thread.started.connect(self.create)
        self.thread.start()

    def sendModeCmd(self, cmd):
        self.serialPort.write(cmd)
        #print("Sent CMD: ", cmd)

    def create(self):
        try:
            self.values = Values()
            self.serialPort = serial.Serial(self.portName,
                                            baudrate=460800,
                                            timeout=1)  #115200, timeout=1)
            self.serialPort.write(b'O')
            self.n = 0
            self.tstart = time.perf_counter_ns()
            self.timer = QTimer()
            self.timer.timeout.connect(self.readFromSerial,
                                       Qt.QueuedConnection)
            self.timer.setInterval(0)
            self.timer.start()
        except Exception as e:
            traceback.print_exc()

    def readFromSerial(self):
        try:
            buf = self.serialPort.read(1)
            numBytes, = struct.unpack("B", buf)
            while len(buf) < numBytes - 1:
                buf += self.serialPort.read(numBytes - 1)
            dbg = DebugStruct.from_buffer_copy(buf)
            self.n += len(buf) + 2
            if 0:
                print("read %d bytes in %.2f seconds: bits/second=%.1f" %
                      (self.n, (time.perf_counter_ns() - self.tstart) * 1e-9,
                       self.n * 8 /
                       ((time.perf_counter_ns() - self.tstart) * 1e-9)))
            if 0:
                print(
                    "Profiling 01: %.1f ms   12: %.1f ms   23: %.1f ms      03: %.1f ms"
                    % (
                        (items[-3] - items[-4]) * 1e-3,
                        (items[-2] - items[-3]) * 1e-3,
                        (items[-1] - items[-2]) * 1e-3,
                        (items[-1] - items[-4]) * 1e-3,
                    ))
            self.values.update(dbg)
            self.valuesChanged.emit(self.values, dbg)
        except Exception as e:
            traceback.print_exc()
Beispiel #10
0
def using_move_to_thread():
    app = QCoreApplication([])
    objThread = QThread()
    obj = SomeObject()
    obj.moveToThread(objThread)
    obj.finished.connect(objThread.quit)
    objThread.started.connect(obj.long_running)
    objThread.finished.connect(app.exit)
    objThread.start()
    sys.exit(app.exec_())
Beispiel #11
0
    def start_threads_and_send_mails(self):
        mails_to_send = []
        for i in range(self.listWidget_emails.count()):
            item = self.listWidget_emails.item(i)
            if item.checkState():
                item.setSelected(True)
                xlsx_row = item.xlsx_row
                # Сохраняем номер строки, чтобы потом легко пометить её зелёным
                xlsx_row['QListWidgetIndex_WcCRve89'] = i
                mails_to_send.append(item.xlsx_row)
        if not mails_to_send:
            msg = 'Ни одно письмо для отправки не выбрано'
            QMessageBox.information(self.parent, 'OK', msg)
            raise Exception(msg)
        # Создаём по отправляльщику на каждый worker
        # Равномерно распределяем на них на всех почту
        self.USE_THREADS = min(self.NUM_THREADS, len(mails_to_send))
        envelopes = [self.envelope.copy() for __ in range(self.USE_THREADS)]
        for i, xlsx_row in enumerate(mails_to_send):
            envelopes[i % self.USE_THREADS].add_mail_to_queue(
                recipients=xlsx_row['email'],
                subject=xlsx_row['subject'],
                html=self.template.format(**xlsx_row),
                files=xlsx_row['attach_list'],
                xls_id=xlsx_row[ORIGINAL_ROW_NUM],
                qt_id=xlsx_row['QListWidgetIndex_WcCRve89'])
        # Лочим кнопки
        self.pushButton_ask_and_send.setDisabled(True)
        self.pushButton_open_list_and_template.setDisabled(True)
        self.pushButton_cancel_send.setEnabled(True)
        # Готовим worker'ов
        self.__workers_done = 0
        self.__threads = []
        for idx in range(self.USE_THREADS):
            worker = Worker(idx, envelopes[idx])
            thread = QThread()
            thread.setObjectName('thread_' + str(idx))
            self.__threads.append(
                (thread,
                 worker))  # need to store worker too otherwise will be gc'd
            worker.moveToThread(thread)

            # get progress messages from worker:
            worker.sig_step.connect(self.on_worker_step)
            worker.sig_done.connect(self.on_worker_done)
            worker.sig_mail_sent.connect(self.on_mail_sent)
            worker.sig_mail_error.connect(self.on_mail_error)

            # control worker:
            self.sig_abort_workers.connect(worker.abort)

            # get read to start worker:
            thread.started.connect(worker.work)
            thread.start(
            )  # this will emit 'started' and start thread's event loop
Beispiel #12
0
class Bridge(QObject):
    def __init__(self, widget, index, login, password, proxy, key):
        QObject.__init__(self)

        self.thread = QThread()
        self.user = User(index, login, password, proxy, key)
        self.user.moveToThread(self.thread)
        self.init_signal_connections(widget)
        self.thread.started.connect(self.user.run)
        self.thread.start()

    def init_signal_connections(self, widget):
        self.user.signal_update_column_color.connect(widget.change_column_color)
        self.user.signal_update_column_text.connect(widget.change_column_text)
        self.user.signal_update_chart.connect(widget.update_chart)
def snapshot_in_bkgroud():
    # Step 2: Create a QThread object
    thread = QThread()
    # Step 3: Create a worker object
    worker = Worker()
    # Step 4: Move worker to the thread
    worker.moveToThread(thread)
    # Step 5: Connect signals and slots
    thread.started.connect(worker.run)
    worker.finished.connect(thread.quit)
    worker.finished.connect(worker.deleteLater)
    thread.finished.connect(thread.deleteLater)
    # worker.progress.connect(reportProgress)
    # Step 6: Start the thread
    thread.start()
Beispiel #14
0
 def start(self):
     if not self.arduino_process_started or not self._arduino_process_is_alive(
     ):
         for proc in psutil.process_iter():
             # check whether the process name matches
             if 'arduino_monitor.py' in proc.cmdline():
                 proc.kill()
         if os.path.exists('arduino_monitor.py'):
             self.arduino_process = subprocess.Popen(
                 ['python', 'arduino_monitor.py'])
         else:
             self.arduino_process = subprocess.Popen(
                 ['Juice_Ardiuno_Monitor'])
         self.arduino_process_started = True
     QThread.start(self)
Beispiel #15
0
 def create_thread(self, socketDescriptor):
     worker = Worker(socketDescriptor)
     thread = QThread()
     self.onWrite.connect(worker.write_message)
     worker.signal.callFunc.connect(self.call_func_parent)
     worker.messageReceived.connect(self.message_received)
     worker.signal.getStatus.connect(self.getStatus)
     worker.signal.setStatus.connect(self.setStatus)
     self.signal.getStatus.connect(worker.getStatus)
     thread.started.connect(worker.start)
     worker.signal.updateNr.connect(self.update_nr_clients)
     worker.finished.connect(self.test)
     worker.moveToThread(thread)
     thread.worker = worker
     thread.start()
     return thread
Beispiel #16
0
class LoggingWorker(QObject):
    """
    QObject living in a separate QThread, logging everything it receiving. Intended to be an attached Stm32pio project
    class property. Stringifies log records using DispatchingFormatter and passes them via Signal interface so they can
    be conveniently received by any Qt entity. Also, the level of the message is attaching so the reader can interpret
    them differently.

    Can be controlled by two threading.Event's:
      stopped - on activation, leads to thread termination
      can_flush_log - use this to temporarily save the logs in an internal buffer while waiting for some event to occurs
        (for example GUI widgets to load), and then flush them when time has come
    """

    sendLog = Signal(str, int)

    def __init__(self, logger: logging.Logger, parent: QObject = None):
        super().__init__(parent=parent)

        self.buffer = collections.deque()
        self.stopped = threading.Event()
        self.can_flush_log = threading.Event()
        self.logging_handler = BufferedLoggingHandler(self.buffer)

        logger.addHandler(self.logging_handler)
        self.logging_handler.setFormatter(
            stm32pio.util.DispatchingFormatter(
                f"%(levelname)-8s %(funcName)-{stm32pio.settings.log_fieldwidth_function}s %(message)s",
                special=stm32pio.util.special_formatters))

        self.thread = QThread()
        self.moveToThread(self.thread)

        self.thread.started.connect(self.routine)
        self.thread.start()

    def routine(self) -> None:
        """
        The worker constantly querying the buffer on the new log messages availability.
        """
        while not self.stopped.wait(timeout=0.050):
            if self.can_flush_log.is_set():
                if len(self.buffer):
                    record = self.buffer.popleft()
                    self.sendLog.emit(self.logging_handler.format(record),
                                      record.levelno)
        module_logger.debug('exit logging worker')
        self.thread.quit()
Beispiel #17
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.inputFileButton.clicked.connect(self.handle_input)
        self.ui.openButton.clicked.connect(self.handle_open)
        self.ui.startButton.clicked.connect(self.handle_start)

    def handle_input(self):
        current_path = QDir.currentPath()
        filter = QDir(current_path, "text files (*.txt)").filter()
        dlg = QFileDialog()
        dlg.setFileMode(QFileDialog.AnyFile)
        dlg.setFilter(filter)
        filename = dlg.getOpenFileName()
        f = open(filename[0], 'r', encoding='utf-8-sig')
        self.ui.inputFileLabel.setText(filename[0].split('/')[-1])
        with f:
            self.query_list = f.read().splitlines()
        return

    def handle_open(self):
        path = os.getcwd()+"/result"
        webbrowser.open("file:///"+path)

    def handle_start(self):
        self.thread = QThread()
        self.worker = Worker(self.query_list, self.ui.delaySpinBox.text())
        self.worker.moveToThread(self.thread)
        self.thread.started.connect(self.worker.run)
        self.worker.finished.connect(self.thread.quit)
        self.worker.finished.connect(self.worker.deleteLater)
        self.thread.finished.connect(self.thread.deleteLater)
        self.worker.progress.connect(self.ui.progressBar.setValue)
        self.thread.start()
        self.ui.buttonFrame.setEnabled(False)
        self.ui.inputFrame.setEnabled(False)
        self.thread.finished.connect(self.handle_finished)

    def handle_finished(self):
        self.ui.buttonFrame.setEnabled(True)
        self.ui.inputFrame.setEnabled(True)
        msgBox = QMessageBox()
        msgBox.setIcon(QMessageBox.Information)
        msgBox.setText("수집이 완료되었습니다.")
        msgBox.exec_()
Beispiel #18
0
class LoggingWorker(QObject):
    """
    QObject living in a separate QThread, logging everything it receiving. Intended to be an attached
    ProjectListItem property. Stringifies log records using global BuffersDispatchingHandler instance (its
    stm32pio.util.DispatchingFormatter, to be precise) and passes them via Qt Signal interface so they can be
    conveniently received by any Qt entity. Also, the level of the message is attaching so the reader can
    interpret them differently.

    Can be controlled by two threading.Event's:
        stopped - on activation, leads to thread termination
        can_flush_log - use this to temporarily save the logs in an internal buffer while waiting for some event to
            occurs (for example GUI widgets to load), and then flush them when the time has come
    """

    sendLog = Signal(str, int)

    def __init__(self, project_id: ProjectID, parent: QObject = None):
        super().__init__(parent=parent)

        self.project_id = project_id
        self.buffer = collections.deque()
        projects_logger_handler.buffers[
            project_id] = self.buffer  # register our buffer

        self.stopped = threading.Event()
        self.can_flush_log = threading.Event()

        self.thread = QThread()
        self.moveToThread(self.thread)
        self.thread.started.connect(self.routine)
        self.thread.start()

    def routine(self) -> None:
        """
        The worker constantly querying the buffer on the new log messages availability
        """
        while not self.stopped.wait(timeout=0.050):
            if self.can_flush_log.is_set() and len(self.buffer):
                record = self.buffer.popleft()
                self.sendLog.emit(projects_logger_handler.format(record),
                                  record.levelno)
        # TODO: maybe we should flush all remaining logs before termination
        projects_logger_handler.buffers.pop(
            self.project_id)  # unregister our buffer
        module_logger.debug(
            f"exit LoggingWorker of project id {self.project_id}")
        self.thread.quit()
Beispiel #19
0
class RssFeedReader(QObject):
    """
    Loads the RSS feed from the network async, every complete
    download is announced as the emit of the signal
    """

    rssFeedLoadedFromSource = Signal()
    rssFeedComplete = Signal()

    def __init__(self, parent=None):
        super().__init__(parent)
        self._rss = []

    @Slot()
    def refreshRssFeed(self):
        """
        Refresh the RSS data from the servers
        """
        logging.info("Worker thread starting")
        self._thread = QThread()
        self.worker = Worker()

        # connect the signals with slots or re-emit the signals
        self._thread.started.connect(self.worker.do_work)
        self._thread.finished.connect(self._thread.deleteLater)
        self.worker.rssSourceLoaded.connect(self.rssFeedLoadedFromSource.emit)
        self.worker.rssDownloadComplete.connect(self.downloadComplete)

        # move the worker to its own thread
        self.worker.moveToThread(self._thread)
        self._thread.start()
        logging.info("Worker thread started via QThread")

    @Slot()
    def downloadComplete(self):
        logging.info("Download complete, stopping thread")

        self._rss = self.worker.get_list()

        self._thread.quit()
        self.rssFeedComplete.emit()

    def get_list(self):
        return self._rss

    rssList = Property('QVariantList', get_list)
Beispiel #20
0
class JoystickSink(QObject):
    def __init__(self, jsdev):
        super().__init__()
        self.jsdev = jsdev
        self.thread = QThread()
        self.moveToThread(self.thread)
        self.thread.started.connect(self.create)
        self.thread.start()

    def create(self):
        self.timer = QTimer()
        self.timer.timeout.connect(self.readFromDevice, Qt.QueuedConnection)
        self.timer.setInterval(0)
        self.timer.start()

    def readFromDevice(self):
        try:
            events = self.jsdev.read()
        except:
            pass
class Form(QWidget):
    def __init__(self):
        super().__init__()
        self.label = QLabel("0")

        # 1 - create Worker and Thread inside the Form
        self.obj = worker.Worker()  # no parent!
        self.thread = QThread()  # no parent!

        # 2 - Connect Worker`s Signals to Form method slots to post data.
        self.obj.intReady.connect(self.onIntReady)

        # 3 - Move the Worker object to the Thread object
        self.obj.moveToThread(self.thread)

        # 4 - Connect Worker Signals to the Thread slots
        self.obj.finished.connect(self.thread.quit)

        # 5 - Connect Thread started signal to Worker operational slot method
        self.thread.started.connect(self.obj.procCounter)

        # * - Thread finished signal will close the app if you want!
        #self.thread.finished.connect(app.exit)

        # 6 - Start the thread
        self.thread.start()

        # 7 - Start the form
        self.initUI()

    def initUI(self):
        grid = QGridLayout()
        self.setLayout(grid)
        grid.addWidget(self.label, 0, 0)

        self.move(300, 150)
        self.setWindowTitle('thread test')
        self.show()

    def onIntReady(self, i):
        self.label.setText("{}".format(i))
Beispiel #22
0
class EvoLisaWidget(QWidget):
    def __init__(self):
        super(EvoLisaWidget, self).__init__()
        self.__image = QImage('evolisa.png')
        self.__thread = QThread()
        self.__worker = EvoLisaWorker()
        self.__worker.moveToThread(self.__thread)
        self.__thread.started.connect(self.__worker.run)
        self.__thread.finished.connect(self.__thread.quit)
        self.__worker.progress.connect(self.__report_progress)

        self.__pixmap = None

        self.setWindowTitle('EvoLisa')

    def __report_progress(self, chromosone, generation):
        size = 250, 250
        total_triangles = self.__worker.total_triangles()
        self.__pixmap = _chromosone_to_pixmap(chromosone, total_triangles,
                                              size)
        self.setWindowTitle('EvoLisa g={}'.format(generation))

        self.update()

    def mousePressEvent(self, event):
        event.accept()

    def showEvent(self, event):
        self.__thread.start()

    def paintEvent(self, event):
        painter = QPainter()
        painter.begin(self)
        painter.drawPixmap(QPoint(), self.__pixmap)
        painter.drawImage(QPoint(250, 0), self.__image)

    def sizeHint(self):
        return QSize(500, 250)

    def closeEvent(self, event):
        self.__worker.stop()
Beispiel #23
0
class InitialWidget(QWidget, Ui_Form):
    def __init__(self, mainwindow):
        super(self.__class__, self).__init__()
        self.setupUi(self)
        self.setStyleSheet(qss)
        self.mainwindow = mainwindow
        self.progressBar.setFixedHeight(10)
        self.thread = QThread()
        self.job = InitJob()
        self.job.sig_progress.connect(self.show_progress)
        self.job.moveToThread(self.thread)
        self.thread.started.connect(self.job.box_init)
        self.thread.start()

    def show_progress(self, pro, msg):
        self.progressBar.setValue(pro)
        self.msg.setText(msg)
        if pro == -1:
            self.mainwindow.home_handler()
            self.thread.quit()
            self.close()
Beispiel #24
0
class QueueConsumer(QObject):
    on_result = Signal(object)

    def __init__(self, queue: Queue):
        super(QueueConsumer, self).__init__()
        self._queue = queue
        self._worker = None
        self._thread: QThread = None

    def start(self):
        self._worker = QueueConsumerWorker(self._queue)
        self._thread = QThread()
        self._worker.moveToThread(self._thread)
        self._worker.finished.connect(self._thread.quit)
        self._worker.error.connect(self._handle_exception)
        self._worker.on_result.connect(self._on_result)
        self._thread.started.connect(self._worker.run)
        self._thread.start()

    def stop(self):
        if not (self._worker and self._thread):
            raise RuntimeError("not started yet")
        self._worker.stop()
        if self._thread.isRunning():
            self._thread.quit()
            self._thread.wait()

    @Slot()
    def _handle_exception(self, e):
        if isinstance(e, RQAmsHelperException):
            e.exec_msg_box()
        else:
            logger.error("consumer failed: " + str(e))
        logger.info("restart consumer")
        self.stop()
        self.start()

    @Slot()
    def _on_result(self, result):
        self.on_result.emit(result)
Beispiel #25
0
class BPMQt():
    """Calculate BPM using a QThread."""
    def __init__(self, bpm_set_fun, algorithm="multifeature"):
        self.bpm_set_fun = bpm_set_fun
        self.essentia_rhythm_algorithm = algorithm
        self.worker = None
        self.worker_thread = None

    def start_bpm_calculation(self, audio):
        """Set up thread and start BPM calculation."""
        self.worker = BPMWorkerQt(audio, self.essentia_rhythm_algorithm)
        self.worker_thread = QThread()
        self.worker_thread.started.connect(self.worker.extract_bpm)
        self.worker.finished.connect(self.worker_thread.quit)
        self.worker.bpm.connect(self.update_bpm)
        self.worker.moveToThread(self.worker_thread)
        self.worker_thread.start()

    def update_bpm(self, bpm):
        """Update BPM for changing Gandalf gif's playback speed."""
        if 0 < bpm < 300:
            self.bpm_set_fun(bpm)
Beispiel #26
0
class TimeWidget(QWidget, Ui_TimeWidget):
    def __init__(self, parent=None):
        super(TimeWidget, self).__init__(parent)
        self.setupUi(self)
        self.btnStart.clicked.connect(self.start)
        self.btnStop.clicked.connect(self.stop)
        self.setupThread()
        self.show()

    def setupThread(self):
        self.worker = TimeDisplayer()
        self.thread = QThread()
        self.worker.moveToThread(self.thread)
        self.worker.timeUpdated.connect(self.lblTime.setText)
        self.thread.started.connect(self.worker.run)
        self.thread.finished.connect(self.worker.stop)

    def start(self):
        self.thread.start()

    def stop(self):
        self.thread.quit()
Beispiel #27
0
class ODummyControl(QtCore.QObject):
    def __init__(self, parent = None):
        QObject.__init__(self, parent)

        self.worldMap = OAbstractMap(self)
        self.mainWidget_ = OMainWidget(self.worldMap)

        self.objectList = []

        self.eventManager = EventManager()

        self.objectEventThread = QThread(self)
        self.eventManager.moveToThread(self.objectEventThread)


    def showTheWorld(self):
        self.mainWidget_.showTheWorld()

    def startTheWorld(self):
        self.objectEventThread.start()
        self.generateSingleObject()

        for objectIt in self.objectList:
            objectIt.activeObject()

    @Slot()
    def processObjEvent(self):
        objectCommand = OObjectAbsCommand(self.sender())
        self.eventManager.addObjectEvent(objectCommand)


    @Slot()
    def generateSingleObject(self):
        singleObject = OAbstractObject(self.worldMap, self)
        singleObject.setRange(self.worldMap.getRange()[0], self.worldMap.getRange()[1])
        singleObject.generatePosition(self.worldMap.getRange()[0], self.worldMap.getRange()[1])
        singleObject.signalRequestToDo.connect(self.processObjEvent)

        self.objectList.append(singleObject)
Beispiel #28
0
class AsyncWorker(QObject):
    task_started = Signal(SSUTask)

    def __init__(self):
        super().__init__()
        self.background_worker = BackgroundWorker()
        self.working_thread = QThread()
        self.background_worker.moveToThread(self.working_thread)
        self.task_started.connect(self.background_worker.on_task_started)
        self.background_worker.task_failed.connect(self.on_task_failed)
        self.background_worker.task_succeeded.connect(self.on_task_succeeded)
        self.working_thread.start()

    def on_task_succeeded(self, fitting_result: SSUResult):
        pass

    def on_task_failed(self, failed_info, task):
        pass

    @Slot()
    def execute_task(self, task: SSUTask):
        self.task_started.emit(task)
Beispiel #29
0
class UserTab(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        layout = QVBoxLayout(self)
        self.text = QPlainTextEdit()
        layout.addWidget(self.text)
        self.setLayout(layout)
        self.ds = DataSource()
        self.worker = UpdateUserWorker()
        self.worker_thread = QThread()
        self.worker_thread.started.connect(self.worker.run)
        self.worker.finished.connect(self.worker_thread.quit)
        self.worker.moveToThread(self.worker_thread)
        self.worker_thread.start()
        self.worker.processed.connect(self.processed)

    @Slot(dict)
    def processed(self, user):
        self.text.appendPlainText('USER: {}'.format(str(user)))

    def finish(self):
        self.worker.finish()
        self.worker_thread.quit()
        self.worker_thread.wait()
Beispiel #30
0
class ImageStreamServer(QObject):
    """
    Server class that will asynchronously listen for images coming from the vehicle and emit signals when images are
    received.
    """

    # Emitted when a new image is received
    image_received = Signal()

    def __init__(self) -> None:
        super().__init__()
        self._worker = ImageStreamWorker()
        self._thread = QThread(self)
        self._worker.image_received.connect(self.image_received_slot)
        self._worker.moveToThread(self._thread)
        self._thread.started.connect(self._worker.do_work)

    @Slot()
    def image_received_slot(self):
        # Just pass on the signal
        self.image_received.emit()

    def get_last_image(self):
        return self._worker.get_last_image()

    def streaming(self):
        return self._worker.streaming()

    def start(self):
        self._thread.start()

    def stop(self):
        logging.info("Stopping image server")
        self._worker._running = False
        self._thread.quit()
        self._thread.wait()