class MainWindow(QMainWindow): def __init__(self): super().__init__() # Some buttons layout = QVBoxLayout() self.text = QPlainTextEdit() layout.addWidget(self.text) btn_run = QPushButton("Execute") btn_run.clicked.connect(self.start) layout.addWidget(btn_run) w = QWidget() w.setLayout(layout) self.setCentralWidget(w) # Thread runner self.threadpool = QThreadPool() def start(self): # Create a runner self.runner = SubProcessWorker("python ~/dumy.py") self.runner.signals.result.connect(self.result) self.threadpool.start(self.runner) def result(self, s): self.text.appendPlainText(s)
class App(QWidget): def __init__(self): super().__init__() self.title = 'Hello, world!' self.left = 2100 self.top = 500 self.width = 640 self.height = 480 self.threadpool = QThreadPool() self.initUI() def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) checkbox = QCheckBox('Check Box', self) checkbox.stateChanged.connect(self.clickCheckbox) self.show() def clickCheckbox(self): thread = Thread() thread.signal.return_signal.connect(self.function_thread) self.threadpool.start(thread) def function_thread(self, signal): print(signal)
class Ui(QtWidgets.QDialog): def __init__(self): container = Container() super(Ui, self).__init__() # Call the inherited classes __init__ method uic.loadUi('./view/main.ui', self) # Load the .ui file self.show() # Show the GUI worker = Container.worker_logic() worker.frameSignal.result.connect(self.display_data) self.thread = QThreadPool() self.thread.start(worker) self.text = self.findChild(QtWidgets.QLabel, 'label') self.frame = self.findChild(QtWidgets.QFrame, 'frameLabel') self.data_input = self.findChild(QtWidgets.QLineEdit, 'inputFrame') self.button = self.findChild(QtWidgets.QPushButton, 'sendFrameButton') self.button.clicked.connect(self.sendFrame) def sendFrame(self): print('sent') data = self.data_input.text() self.thread.start(Container.send_frame_logic(data)) @pyqtSlot(object) def display_data(self, data): print(data) self.text.setText(data)
class Downloader(QObject): finished = pyqtSignal() def __init__(self, queue): """ Class that spawns the separate download threads. This is a separate class so it can be moved to its own thread and run simultaneously with post extraction. :param queue: The download queue in which extracted content is placed """ super().__init__() self.queue = queue self.run = True self.settings = QSettings("SomeGuySoftware", "RedditDownloader") self.download_pool = QThreadPool() self.download_pool.setMaxThreadCount( self.settings.value('thread_limit', 4, type=int)) def download(self): """Spawns the download pool threads""" while self.run: post = self.queue.get() if post is not None: self.download_pool.start(post) else: self.run = False self.download_pool.waitForDone() self.finished.emit() def stop(self): self.run = False self.download_pool.clear()
def main(): args = read_args() # application app = QApplication([]) app.setOverrideCursor(Qt.BlankCursor) # main window window = MainWindow( { 'green': ROOT / 'bg_green.png', 'red': ROOT / 'bg_red.png' }, fullscreen=True, debug=False, size=app.desktop().screenGeometry().size()) try: window.set_power(not args.poweroff) window.set_color(args.color) window.set_background(args.background) except BaseException: logging.exception('Failed to exec args') # signals piper = Piper() window.connect_signals(piper.signals) pool = QThreadPool() pool.start(piper) try: app.exec() except KeyboardInterrupt: print('Keyboard interrupt', flush=True) finally: print('quitting', flush=True)
class SpeedSlider(QSlider): def __init__(self, geo, object_name, value, max, parent): super().__init__(Qt.Vertical, parent) self.speed = 50 self.light = parent.light self.strobe_worker = StrobeWorker(self.light, 50, self) self.thread_pool = QThreadPool() self.setObjectName(object_name) self.setGeometry(geo[0], geo[1], geo[2], geo[3]) self.setValue(value) self.setMaximum(max) self.valueChanged[int].connect(self.strobe) def strobe(self, value): try: value = 50 - value if self.speed == 50 and value < 50: self.strobe_worker = StrobeWorker(self.light, value, self) self.thread_pool.start(self.strobe_worker) self.speed = value self.strobe_worker.change_speed(value) except (GenericHueError, UnauthorizedUserError) as e: self.connection_handler.update_status(str(e), True) except DeviceIsOffError: # Don't care if device is off, just don't take any action pass
class appWin(QMainWindow): def __init__(self): super(appWin, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.threadpool = QThreadPool() print('Multithreading with maximum {} thread'.format( self.threadpool.maxThreadCount())) self.timer = QTimer() self.timer.setInterval(0.1) self.timer.timeout.connect(self.on_timer_timeout) self.timer.start() self.count = 0 self.ui.pushButton.clicked.connect(self.on_btn) def on_timer_timeout(self): self.count += 1 self.ui.label.setText(str(self.count)) def on_btn(self): # for i in range(5): # # QApplication.processEvents() # self.ui.label_2.setText(str(i+1)) # time.sleep(1) worker1 = Worker([1, 2, 3, 4], 'Ali', ui=self.ui, test='pp') self.threadpool.start(worker1)
class AsyncPoolController(AsyncAbstractController): def __init__( self, # A number *n* to create a pool of *n* simple threads, where each thread # lacks an event loop, so that it can emit but not receive signals. # This means that ``g`` may **not** be run in a thread of this pool, # without manually adding a event loop. If *n* < 1, the global thread pool # is used. maxThreadCount, # |parent| parent=None): super(AsyncPoolController, self).__init__(parent) if maxThreadCount < 1: self.threadPool = QThreadPool.globalInstance() else: self.threadPool = QThreadPool() self.threadPool.setMaxThreadCount(maxThreadCount) # |_start| def _start(self, future): # Asynchronously invoke ``f``. apw = _AsyncPoolWorker(future) self.threadPool.start(apw) # |terminate| def _terminate(self): self.threadPool.waitForDone() del self.threadPool
class LiveFlight(): def __init__(self): pass def run(self): self.app = QApplication(sys.argv) self.mm = MemoryManager() self.mm.dm.data_processor.set_structure(self.mm.conf['new_structure']) # Logic threads self.threadpool = QThreadPool() self.log = LiveFlightLogic(self) self.gui = LiveFlightGui(self) self.af = AdditionalThread(self) self.af.port_dialog_signal.connect(self.open_port_dialog) self.af.start() # main window self.main_window = MainWindow() self.main_window.show() # running it self.threadpool.start(self.log) self.threadpool.start(self.gui) self.app.exec_() def open_port_dialog(self, args): def dialog_callback(self, args): ans = self.dialog.ans self.dialog.close() self.mm.dyn['port'] = ans args['callback']() self.dialog = PortSetWindow(self.main_window) self.dialog.set_port(args['ports']) ans = None self.dialog.value_changed_signal.connect( lambda: dialog_callback(self, args)) self.dialog.exec_()
class LockWindow(QtWidgets.QWidget): def __init__(self): super(LockWindow, self).__init__() self.create_UI() self.threadpool = QThreadPool() def unlock(self): self.start_button.setEnabled(False) rec_thread = FaceRecognitionThread() rec_thread.signals.finished.connect(self.update_UI) self.threadpool.start(rec_thread) def update_UI(self): self.descr_label.setText("Hi, nice to see you again! UNLOCKED") def create_UI(self): self.start_button = QPushButton("Start") self.start_button.clicked.connect(self.unlock) self.descr_label = QLabel("Place your face in front of your camera.") self.descr_label.setAlignment(Qt.AlignCenter) vbox = QVBoxLayout() vbox.addWidget(self.descr_label) vbox.addWidget(self.start_button) self.setLayout(vbox) self.showFullScreen()
class FatContentExporter(QDialog): progress_signal = pyqtSignal(tuple) def __init__(self, parent, dest_dir: str, selected_album: AlbumData, images: []): super().__init__(parent) self.setWindowFlag(Qt.WindowCloseButtonHint, False) self.setWindowFlag(Qt.WindowContextHelpButtonHint, False) self.setWindowTitle('Album Content Exporter') self.setWindowIcon(QIcon(QPixmap(QImageReader('assets/exportAlbumContent.png').read()))) # Layout setup layout = QVBoxLayout() layout.addWidget(QLabel('Exporting album files...')) self.progress = QProgressBar() self.progress.setValue(0) self.progress.setFormat('Waiting (%p%)') layout.addWidget(self.progress) self.current_file = QLabel('Waiting...') layout.addWidget(self.current_file) layout.addStretch() # Init thread self.progress_signal.connect(self.update_progress) self.thread_pool = QThreadPool() self.thread_worker = Worker(self.run) self.thread_worker.signals.progress.connect(self.progress_signal) self.thread_worker.signals.finished.connect(self.update_after_completion) self.images = images self.selected_album = selected_album self.dest_dir = dest_dir self.setLayout(layout) self.setFixedSize(300, 80) self.thread_pool.start(self.thread_worker) self.exec() def update_after_completion(self): self.hide() def update_progress(self, status: tuple): if status[0] is 'COLLECTING': self.progress.setFormat('Collecting (%p%)') else: self.progress.setFormat('Saving (%p%)') self.progress.setValue(status[1] + 1) self.current_file.setText(status[2]) def run(self, signal): self.progress.setMaximum(len(self.images) - 1) images = [] for cap_img in self.images: images.append(FatPhoto(cv2.imread(cap_img.get_image(), cv2.IMREAD_UNCHANGED), basename(cap_img.get_image()))) signal.emit(('COLLECTING', self.images.index(cap_img), cap_img.get_name())) fat_data = FatAlbumData(self.selected_album.get_title(), self.selected_album.get_description(), images) signal.emit(('SAVING', -1, fat_data.get_title() + '.jfatalbum')) self.progress.setMaximum(0) pickle.dump(fat_data, open(join(self.dest_dir, fat_data.get_title() + '.jfatalbum'), 'wb'), 4)
class SSRInstallDialog(QDialog, Ui_SSRInstallDialog): def __init__(self, *args, path, **kwargs): super(SSRInstallDialog, self).__init__(*args, **kwargs) self.setupUi(self) self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False) self.threadPool = QThreadPool(parent=self) self.path = path self.installThread = SSRInstallThread(self.path) self.installThread.signals.stderr.connect(self.display_stderr) self.installThread.signals.stdout.connect(self.display_stdout) self.installThread.signals.done.connect(self.finalize) self.threadPool.start(self.installThread) def display_stderr(self, text): self.textEdit.moveCursor(QTextCursor.End) cursor = self.textEdit.textCursor() fmt = cursor.charFormat() fmt.setForeground(QtCore.Qt.red) cursor.setCharFormat(fmt) cursor.insertText(text) def display_stdout(self, text): self.textEdit.moveCursor(QTextCursor.End) cursor = self.textEdit.textCursor() fmt = cursor.charFormat() fmt.setForeground(QtCore.Qt.black) cursor.setCharFormat(fmt) cursor.insertText(text) def finalize(self): self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True)
class AsyncPoolController(_AsyncAbstractController): def __init__(self, # A number *n* to create a pool of *n* simple threads, where each thread # lacks an event loop, so that it can emit but not receive signals. # This means that g_ may **not** be run in a thread of this pool, # without manually adding a event loop. If *n* < 1, the global thread # pool is used. maxThreadCount, # See parent_. parent=None): super().__init__(parent) if maxThreadCount < 1: self.threadPool = QThreadPool.globalInstance() else: self.threadPool = QThreadPool(self) self.threadPool.setMaxThreadCount(maxThreadCount) # See `_start`_. def _start(self, future): # Asynchronously invoke f_. apw = _AsyncPoolWorker(future) self.threadPool.start(apw) # See `_terminate`_. def _terminate(self): self.threadPool.waitForDone() del self.threadPool
class MainWindow(QMainWindow): def __init__(self): super().__init__() # Some buttons w = QWidget() l = QHBoxLayout() w.setLayout(l) btn_stop = QPushButton("Stop") l.addWidget(btn_stop) # Create a statusbar. self.status = self.statusBar() self.progress = QProgressBar() self.status.addPermanentWidget(self.progress) # Thread runner self.threadpool = QThreadPool() # Create a runner self.runner = JobRunner() self.runner.signals.progress.connect(self.update_progress) self.threadpool.start(self.runner) btn_stop.pressed.connect(self.runner.kill) self.setCentralWidget(w) def update_progress(self, n): self.progress.setValue(n)
class ThreadingApi: """API for scheduling background tasks.""" def __init__(self, log_api: LogApi) -> None: """Initialize self. :param log_api: logging API """ self._log_api = log_api self._thread_pool = QThreadPool() def schedule_task( self, function: Callable[..., Any], complete_callback: Callable[..., Any], ) -> None: """Schedule a task to run in the background thread pool. :param function: function to run :param complete_callback: callback to execute when the function finishes (executed in the qt thread) """ worker = OneShotWorker(self._log_api, function) worker.signals.finished.connect(complete_callback) self._thread_pool.start(worker) def schedule_runnable(self, runnable: QRunnable) -> None: """Schedule a QRunnable to run in the background thread pool. :param runnable: QRunnable to schedule """ self._thread_pool.start(runnable)
class MainWindow(QtWidgets.QMainWindow): def __init__(self): super().__init__(flags=Qt.CustomizeWindowHint | Qt.WindowMinimizeButtonHint | Qt.WindowCloseButtonHint) vlayout = QtWidgets.QVBoxLayout() widget = QtWidgets.QWidget() widget.setLayout(vlayout) self.setCentralWidget(widget) self.bar = QtWidgets.QProgressBar() self.bar.setMinimum(0) self.bar.setMaximum(MAX_ITER) self.bar.setValue(0) vlayout.addWidget(self.bar) self.button = QtWidgets.QPushButton("Start") self.button.pressed.connect(self.process) vlayout.addWidget(self.button) button = QtWidgets.QPushButton("About") button.pressed.connect(app.aboutQt) vlayout.addWidget(button) self.thread_pool = QThreadPool(self) self.destroyed.connect(lambda: self.cleanup()) def process(self): processor = Processor(self) processor.signals.iteration_passed.connect(self.bar.setValue, Qt.DirectConnection) processor.signals.status_changed.connect(self.button.setDisabled) processor.signals.finished.connect(lambda: self.bar.setValue(0)) self.thread_pool.start(processor) def cleanup(self): self.thread_pool.waitForDone()
class PROCESS(QObject): queue_finished = pyqtSignal(int) prog_finished = pyqtSignal(tuple) stoped = pyqtSignal(int, int) # 1: start, 0: finished, 2: error | queue state = pyqtSignal(int, str) def __init__(self, parent=None): QObject.__init__(self, parent) self.process = QProcess() self.process.setProcessChannelMode(QProcess.MergedChannels) self.process.finished.connect(self.emit_finished) self.process.stateChanged.connect(self.emit_state) self.process_type = 0 # 0 process, 1 runnable self.threadpool = QThreadPool() self.worker = Worker() self.worker.signals.state.connect(self.emit_state) self.queue = None def emit_state(self, state): self.state.emit(state, self.prog_name) def emit_finished(self, exitcode, exitstatus): self.prog_finished.emit((self.prog_name, exitcode, exitstatus)) def set_queue(self, queue): self.queue = queue def start_process(self): try: obj = self.queue.get(False) self.prog_name = list(obj.keys())[0] if callable(list(obj.values())[0][0]): self.process_type = 1 funct = list(obj.values())[0][0] args = list(obj.values())[0][1] self.worker.insert_function(funct, args, self.prog_name) self.threadpool.start(self.worker) else: self.process_type = 0 self.process.start( list(obj.values())[0][0], list(obj.values())[0][1]) except Empty: self.queue_finished.emit(self.queue.name) def force_finished(self): # for process (programs) self.stoped.emit(1, self.queue.name) if self.process_type == 0: self.process.terminate() if not self.process.waitForFinished(1000): self.process.kill() else: if self.threadpool.activeThreadCount(): self.threadpool.clear() self.threadpool.waitForDone() with self.queue.mutex: self.queue.queue.clear() self.stoped.emit(0, self.queue.name)
class MainWindow(QMainWindow, Ui_MainWindow): def __init__(self): super(MainWindow, self).__init__() self.setupUi(self) for country in LOCATION.keys(): self.comboBoxCountry.addItem(country) for city in LOCATION[self.comboBoxCountry.currentText()]: self.comboBoxCity.addItem(city) self.comboBoxCountry.currentTextChanged.connect(self.set_city) self.pushButton.pressed.connect(self.update_weather) self.threadpool = QThreadPool() self.show() def set_city(self, country): self.comboBoxCity.clear() for city in LOCATION[country]: self.comboBoxCity.addItem(city) def update_weather(self): location = self.comboBoxCity.currentText( ) + "," + self.comboBoxCountry.currentText() worker = WeatherWorker(location) worker.signals.result.connect(self.weather_result) worker.signals.error.connect(self.alert) self.threadpool.start(worker) def alert(self, message): QMessageBox.warning(self, "Warning", message) def weather_result(self, weather, forecasts): self.latitudeLabel.setText("%.2f °" % weather['coord']['lat']) self.longitudeLabel.setText("%.2f °" % weather['coord']['lon']) self.windLabel.setText("%.2f m/s" % weather['wind']['speed']) self.temperatureLabel.setText("%.1f °C" % weather['main']['temp']) self.pressureLabel.setText("%d" % weather['main']['pressure']) self.humidityLabel.setText("%d" % weather['main']['humidity']) self.weatherLabel.setText("%s (%s)" % (weather['weather'][0]['main'], weather['weather'][0]['description'])) self.set_weather_icon(self.weatherIcon, weather['weather']) for n, forecast in enumerate(forecasts['list'][:5], 1): getattr(self, 'forecastTime%d' % n).setText( from_ts_to_time_of_day(forecast['dt'])) self.set_weather_icon(getattr(self, 'forecastIcon%d' % n), forecast['weather']) getattr(self, 'forecastTemp%d' % n).setText( "%.1f °C" % forecast['main']['temp']) def set_weather_icon(self, label, weather): label.setPixmap( QPixmap(os.path.join('images', "%s.png" % weather[0]['icon'])))
def asyncrun(function: typing.Callable, *args, pool: QThreadPool = None, **kwargs) -> None: """Run function with args and kwargs in parallel on a QThreadPool.""" pool = pool if pool is not None else Pool.get() runnable = GenericRunnable(function, *args, **kwargs) pool.start(runnable)
class LibraryTaskManager(QWidget): class Runner(QRunnable): def __init__(self, function, args): super().__init__() self.function = function self.args = args def run(self): self.function(*self.args) def __init__(self): super().__init__() self.thread_pool = QThreadPool() self.task_combo = QComboBox() self.task_combo.currentIndexChanged.connect(self.get_item_status) self.progress = QProgressBar() self.progress.setMaximum(100) self.timer = QTimer() q_size = QSize(16, 16) self.icon_in_progress = QIcon.fromTheme("media-playback-start") self.icon_completed = QIcon.fromTheme("media-playback-stop") self.task_combo.setIconSize(q_size) self.timer.timeout.connect(self.timeout) self.task_lookup = {} self._init_ui() def _init_ui(self): layout = QHBoxLayout() layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(QLabel("Task Executor")) layout.addWidget(self.task_combo) layout.addWidget(self.progress) self.setLayout(layout) def execute(self, function, args): runner = self.Runner(function, args) runner.setAutoDelete(True) self.thread_pool.start(runner) def execute_with_progress(self, function, args, task_ref): self.execute(function, args) self.task_lookup[task_ref[0]] = task_ref[1] self.task_combo.addItem(self.icon_in_progress, task_ref[0]) self.task_combo.setCurrentIndex(self.task_combo.findText(task_ref[0])) def get_item_status(self): self.timer.start(500) def timeout(self): task_name = self.task_combo.currentText() task_ref = self.task_lookup[task_name] print(f"status for {task_ref}") status = LibraryManagement.get_task_status(task_ref) self.progress.setValue(status['percent_complete']) if status['status'] == "COMPLETE": self.task_combo.setItemIcon(self.task_combo.findText(task_ref), self.icon_completed) self.timer.stop()
class MainWindow(QWidget): log = logging.getLogger(__name__) EXIT_CODE_REBOOT: int = -123456789 def __init__(self, version: str): super().__init__() self.status = CheckVersionMessage.not_checked self.current_version = version self.wait_window = WaitWindow(f'You use the version {version}.') self.debug_window = QTextEditLogger() self.wait_window.sigUpdateClicked.connect(self._update_version) self.wait_window.sigRestartClicked.connect(self.restart) self.wait_window.sigCheckClicked.connect(self.check_version) self.q_thread_pool = QThreadPool() @pyqtSlot(object, name='setStatus') def _set_status(self, res: CheckVersionMessage): self.status = res @pyqtSlot(name='updateVersion') def _update_version(self): self.wait_window.on_update() try: version = self.status.version except AttributeError: version = None self.worker = Worker(update_version, version=version) self.worker.signals.result.connect(self._on_updated) self.q_thread_pool.start(self.worker) @pyqtSlot(name='checkVerison') def check_version(self): self.wait_window.on_checking() self.worker = Worker(check_outdated, self.current_version) self.worker.signals.result.connect(self.wait_window.get_result) self.worker.signals.result.connect(self._set_status) self.q_thread_pool.start(self.worker) @pyqtSlot(object, name='onUpdatedFinished') def _on_updated(self, updated: bool): if updated: self.wait_window.show_restart() else: self.wait_window.show_info('Auto update failed. Please, update the program manually.') @pyqtSlot(name='restartApp') def restart(self): qApp = QApplication.instance() qApp.closeAllWindows() qApp.exit(self.EXIT_CODE_REBOOT)
class MainWindow(QMainWindow): def __init__(self): super().__init__() self.threadpool = QThreadPool() self.x = {} self.y = {} self.lines = {} layout = QVBoxLayout() self.graphWidget = pg.PlotWidget() self.graphWidget.setBackground("w") layout.addWidget(self.graphWidget) button = QPushButton("Create New Worker") button.pressed.connect(self.execute) # layout.addWidget(self.progress) layout.addWidget(button) w = QWidget() w.setLayout(layout) self.setCentralWidget(w) def execute(self): worker = Worker() worker.signals.data.connect(self.receive_data) # Execute self.threadpool.start(worker) def receive_data(self, data): worker_id, x, y = data if worker_id not in self.lines: self.x[worker_id] = [x] self.y[worker_id] = [y] pen = pg.mkPen( width=2, color=( random.randint(100,255), random.randint(100,255), random.randint(100,255), ), ) self.lines[worker_id] = self.graphWidget.plot( self.x[worker_id], self.y[worker_id], pen=pen ) return self.x[worker_id].append(x) self.y[worker_id].append(y) self.lines[worker_id].setData(self.x[worker_id], self.y[worker_id])
class ProgressWindow(QDialog): signal_loaded = QtCore.pyqtSignal(tuple) signal_error = QtCore.pyqtSignal(int) def __init__(self, *args, **kwargs): super(ProgressWindow, self).__init__(*args, **kwargs) # Setting up progress bar self.progress_bar = QtWidgets.QProgressBar() self.progress_bar.setGeometry(10, 50, 230, 20) self.progress_bar.setMaximum(100) self.setWindowTitle("Loading") self.setFixedSize(248, 80) self.text_field = QLabel("Loading") self.layout = QVBoxLayout() self.layout.addWidget(self.text_field) self.layout.addWidget(self.progress_bar) self.setLayout(self.layout) self.threadpool = QThreadPool() self.interrupt_flag = threading.Event() def start_loading(self, selected_files): image_loader = ImageLoader(selected_files) worker = Worker(image_loader.load, self.interrupt_flag) worker.signals.result.connect(self.on_finish) worker.signals.error.connect(self.on_error) worker.signals.progress.connect(self.update_progress) self.threadpool.start(worker) def on_finish(self, results): self.update_progress(("Initalizing patient window...", 90)) self.signal_loaded.emit((results, self)) def update_progress(self, progress_update): """ Function responsible for updating the bar percentage and the label. :param progress_update: A tuple containing update text and update percentage """ self.text_field.setText(progress_update[0]) self.progress_bar.setValue(progress_update[1]) def on_error(self, err): if type(err[1]) is ImageLoading.NotRTSetError: self.signal_error.emit(0) elif type(err[1]) is ImageLoading.NotAllowedClassError: self.signal_error.emit(1) def closeEvent(self, event: QtGui.QCloseEvent) -> None: self.interrupt_flag.set()
class GenerateDocWidget(QWidget): def __init__(self, app): super().__init__() self.app = app self.threadpool = QThreadPool() self.images = None self.init_ui() def init_ui(self): self.setWindowTitle("Generowanie dokumentu w toku...") self.layout = QVBoxLayout() self.label = QLabel() self.movie = QMovie(os.path.join("resources", "waiting.gif")) self.movie.start() self.label.setMovie(self.movie) self.layout.addWidget(self.label) self.progressbar = QProgressBar() self.layout.addWidget(self.progressbar) self.textedit = QTextEdit() self.textedit.setEnabled(False) self.layout.addWidget(self.textedit) self.setLayout(self.layout) def start(self, settings): self.images = list(self.app.workspace_structures.keys()) worker = Worker(self.generate_doc, settings=settings) worker.signals.result.connect(self.on_document_ready) worker.signals.progress.connect(self.on_progress) self.threadpool.start(worker) def generate_doc(self, progress_callback, settings): print(settings) return generate_doc(self.app.workspace_path, self.app.workspace_structures, settings, progress_callback) def on_progress(self, imagename): self.textedit.append("Przygotowuję {}...".format(imagename)) self.progressbar.setValue(100.0 * float(self.images.index(imagename) + 1) / float(len(self.images))) print("on progress:", imagename) def on_document_ready(self, document): self.hide() document_path = QFileDialog.getSaveFileName( None, "Zapisz dokument", "oznaczone struktury.docx", "docx (*.docx)") if document_path[0] != "": document.save(document_path[0]) self.close()
class recordWindow(Ui_recordDialog): def __init__(self, Dialog): super(recordWindow, self).setupUi(Dialog) def setupUiRecord(self, Dialog): self.quitButton.clicked.connect(Dialog.reject) self.chooseButton.clicked.connect(self.getDirectory) self.recStopButton.clicked.connect(self.runRecStop) self.stringPath = '' def getDirectory(self): chosenPath = str( QFileDialog.getExistingDirectory(cpsMainWindow, caption="Select Directory")) if chosenPath != "": self.pathBrowser.setText(chosenPath) self.stringPath = chosenPath def thread_complete(self): self.recStopButton.setEnabled(True) self.recStopButton.setText('Record') self.quitButton.setEnabled(True) def thread_progress(self, i): self.recStopButton.setText(str(i) + 's') def runRecStop(self): if self.stringPath != '' and self.filenameInput.text() != '': self.threadpool = QThreadPool() input = self.filenameInput.text() input = input.split('.', 1)[0] self.recStopButton.setEnabled(False) self.quitButton.setEnabled(False) self.threadRecord = QThread() self.threadTime = QThread() self.workerRecord = workerRecord(self.lengthSpinBox.value(), input) self.workerTime = workerTime(self.lengthSpinBox.value()) self.workerRecord.signals.finished.connect(self.thread_complete) self.workerRecord.signals.finished.connect( self.threadRecord.deleteLater) self.workerRecord.signals.finished.connect( self.workerRecord.signals.deleteLater) self.workerTime.signals.finished.connect(self.thread_complete) self.workerTime.signals.finished.connect( self.threadTime.deleteLater) self.workerTime.signals.finished.connect( self.workerTime.signals.deleteLater) self.workerTime.signals.progress.connect(self.thread_progress) self.threadpool.start(self.workerRecord) self.threadpool.start(self.workerTime)
class LiveGraph(Canvas): def __init__(self): self.axes = [None] # correction only for one plot with subplots self.fig, self.axes[0] = plt.subplots(1) Canvas.__init__(self, self.fig) Canvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) Canvas.updateGeometry(self) self.x = [] self.y = [] self.running = None self.line = None self.graphWorker = Worker(self.liveGraphThread) self.threadPool = QThreadPool() self.initGraph() def initGraph(self): self.line, = self.axes[0].plot(self.x, self.y, color='b', linestyle='', marker='o', markersize='8') self.axes[0].set_ylim(0, 1) self.axes[0].set_xlim(0, 10) self.draw() def start(self): self.running = True self.threadPool.start(self.graphWorker) def liveGraphThread( self, statusSignal=None ): # statusSignal argument required for threaded functions """ Simple random graph (Use a Queue object from multiprocessing to handle external data flow inside this thread) """ self.line.set_xdata(np.arange(0, 11)) while True: if self.running: self.line.set_ydata(np.random.rand(11)) self.draw() time.sleep(0.1) def stop(self): self.running = False
def __init__(self): super().__init__() task = Task() QThreadPool.globalInstance().setMaxThreadCount(5) #QThreadPool.globalInstance().start(Task()) threadpool = QThreadPool(self) threadpool.start(Task())
class LivePlot(QtWidgets.QWidget): ''' A basic PyQt Widget for plotting live data received from Mantis Data handling is done by a new thread using the Worker Class, as otherwise the UI freezes and doesn't update the plot. ''' def __init__(self): super().__init__() self.w = QtGui.QWidget() # Plot Widgets self.plotWidget = pg.PlotWidget() self.plotWidget2 = pg.PlotWidget() # Plot objects self.trace = self.plotWidget.plot() self.avgTrace = self.plotWidget.plot(pen='c') self.stats = self.plotWidget2.plot(pen='r', symbol='o', symbolPen='r', symbolBrush='r') # Add data properties to plot objects to store data self.stats.data = [] # Button for initiating sockets with Mantis self.commsButton = QtWidgets.QPushButton('Start Mantis Comms', self) self.commsButton.clicked.connect(self.startPlot) # UI layout self.layout = QtGui.QGridLayout() self.w.setLayout(self.layout) self.layout.addWidget(self.plotWidget) self.layout.addWidget(self.plotWidget2) self.layout.addWidget(self.commsButton) self.w.show() # Ininiate the thread pool self.threadpool = QThreadPool() print("Multithreading with maximum %d threads" % self.threadpool.maxThreadCount()) @pyqtSlot() def startPlot(self): ''' Slot for sockets the initiation button ''' worker = Worker(mantisComms, plotLiveData, [self.trace, self.stats]) self.threadpool.start(worker) print('push') def testFunc(self): print("test")
class Thread: def __init__(self): self.threadpool = QThreadPool() def make_worker(self, fn, *args, **kwargs) -> Worker: return Worker(fn, *args, **kwargs) def connect_sig(self, worker: Worker, signal, fn): worker.sig[signal].connect(fn) def start(self, worker): self.threadpool.start(worker)
class MyMainWindow(QtWidgets.QMainWindow, Ui_AwAI): def __init__(self): super(MyMainWindow, self).__init__() self.setupUi(self) self.buttons = [ self.pushButton_1, self.pushButton_2, self.pushButton_3, self.pushButton_4, self.pushButton_5, self.pushButton_6, self.pushButton_7, self.pushButton_8, self.pushButton_9, self.pushButton_10, self.pushButton_11, self.pushButton_12 ] self.thread_pool = QThreadPool() def run(self): """Create the thread pool and set the refresh function every second """ w0 = Worker(self.game.run_game) self.thread_pool.start(w0) self.timer = QTimer() self.timer.setInterval(1000) self.timer.timeout.connect(self.refresh) self.timer.start() def play(self, pit): """Update the human player variable to the right value. It is the human player play function to check if the move is allowed.""" print(self.game.who_is_playing()) self.game.who_is_playing().human_player_move = pit def refresh(self): for button, pit in zip(self.buttons, self.b.board): self.setValue(button, pit) self.nbGraines1.display(self.game.player0.loft) self.nbGraines2.display(self.game.player1.loft) def setValue(self, button, value): button.setText(str(value)) def new(self): """Create the Settings window""" dialog = Settings() dialog.exec_() def closeEvent(self, event): """To close main function proper""" sys.exit(0) def close(self): """To close settings""" self.destroy() sys.exit(0)
class MainWindow(QMainWindow): def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.counter = 0 layout = QVBoxLayout() self.l = QLabel("Start") b = QPushButton("DANGER!") b.pressed.connect(self.oh_no) layout.addWidget(self.l) layout.addWidget(b) w = QWidget() w.setLayout(layout) self.setCentralWidget(w) self.show() self.threadpool = QThreadPool() print("Multithreading with maximum %d threads" % self.threadpool.maxThreadCount()) def progress_fn(self, progress): p, m = (progress) print("%d%% done %s" % (p, m)) def execute_this_fn(self, progress_callback): for n in range(0, 5): time.sleep(1) progress_callback.emit((n * 100 / 4, 'blabla')) return "Done." def print_output(self, s): print(s) def thread_complete(self): print("THREAD COMPLETE!") def oh_no(self): # Pass the function to execute worker = Worker( self.execute_this_fn ) # Any other args, kwargs are passed to the run function worker.signals.result.connect(self.print_output) worker.signals.finished.connect(self.thread_complete) worker.signals.progress.connect(self.progress_fn) # Execute self.threadpool.start(worker)