def append_data(self, x_data: float, y_data: float) -> None: self.x_data.append(x_data) self.y_data.append(y_data) self.plot_data_item.setData(self.x_data, self.y_data) if len(self.x_data) == self.x_range: self.plot_widget.setXRange(self.x_data[0], self.x_data[-1]) QApplication.processEvents()
def run(): # Be able to close with Ctrl+C in the terminal once Qt is started https://stackoverflow.com/a/5160720 signal.signal(signal.SIGINT, signal.SIG_DFL) arguments = sys.argv # Remove warning about invalid style override arguments.extend(['-style', 'Fusion']) app = QApplication(arguments) apply_dark_theme(app) # Show splash screen pixmap = QPixmap(':/icons/splash.png') splash = QSplashScreen(pixmap) splash.setWindowTitle('The Little Hat') splash.showMessage('loading...', alignment=Qt.AlignBottom | Qt.AlignCenter, color=Qt.white) splash.show() app.processEvents() window = MainWindow(app) window.show() splash.finish(window) return app.exec_()
def _progressCallback(self, task: str, iteration: int, maximum: int) -> bool: if iteration == -1: self._progress_dialog.close() self._progress_dialog.reset() return False else: self._progress_dialog.setLabelText(task) self._progress_dialog.setMaximum(maximum) self._progress_dialog.setValue(iteration) if not iteration: QApplication.processEvents() return self._progress_dialog.wasCanceled()
def main(): app = QApplication(sys.argv) pixmap = QPixmap("icon.ico") splash = QSplashScreen(pixmap) splash.show() if __debug__: start = timer() ex = TableClothGenerator() app.processEvents() ex.show() splash.finish(ex) if __debug__: end = timer() print("This took %d seconds." % (end - start)) sys.exit(app.exec())
async def run(application: Application) -> None: app = QApplication([]) qml_filepath = str(Path(__file__).parent / "window.qml") engine = QQmlApplicationEngine() # bind model context = engine.rootContext() application_proxy = ApplicationProxy(application) context.setContextProperty("application", application_proxy) # import_paths = engine.importPathList() # import_paths.append('/usr/lib/qt/qml') # engine.setImportPathList(import_paths) QQuickStyle.setStyle('Imagine') engine.load(qml_filepath) while application.is_running: app.processEvents() await asyncio.sleep(0.01)
def start_plot(self): self.action_run.setEnabled(False) self.action_stop.setEnabled(True) try: port1_info = self.ui.port_combobox1.get_current_port_info() port1 = port1_info.device if port1_info is not None else port1_info port2_info = self.ui.port_combobox2.get_current_port_info() port2 = port2_info.device if port2_info is not None else port2_info baudrate = self.ui.baudrate_combobox.currentText() with Serial(port1, baudrate) as ser1, Serial(port2, baudrate) as ser2: while self.action_stop.isEnabled(): if port1 is not None: data = ser1.readline().decode().rstrip() self.ui.monitor1.appendPlainText(data) if port2 is not None: data = ser2.readline().decode().rstrip() self.ui.monitor2.appendPlainText(data) QApplication.processEvents() except Exception as e: QMessageBox.critical(self, "ERROR", str(e)) self.action_run.setEnabled(False) self.action_stop.setEnabled(False)
def read_subreddit(subreddit, after_id: Optional[str] = None, statusbar=None, mainWindow=None) -> List[ImageWithExtraInfo]: try: if mainWindow: mainWindow.loading_line.show() if not after_id: img_url = url_template.format(subreddit=subreddit) else: img_url = url_template_with_after_id.format(subreddit=subreddit, after_id=after_id) r = requests.get(img_url, headers=cfg.headers, timeout=cfg.REQUESTS_TIMEOUT) d = r.json() result = [] total = len(d["data"]["children"]) for idx, child in enumerate(d["data"]["children"], start=1): percent = round(idx * 100 / total) log.info(f"{percent}%") if statusbar: statusbar.progressbar.show() statusbar.progressbar.setValue(percent) # statusbar.flash_message(blue(f"{percent} %")) # without this nothing appeared until 100%: QApplication.processEvents() # reason: https://stackoverflow.com/a/29917237/232485 entry = child["data"] domain = entry["domain"] link = entry["url"] after_id = entry["name"] # use this for a new page that comes after this entry extra = { 'subreddit': subreddit, 'after_id': after_id, 'next_page_url': f'https://www.reddit.com/r/{subreddit}/.json?after={after_id}' } if Path(link).suffix.lower() in cfg.SUPPORTED_FORMATS: result.append(ImageWithExtraInfo(link, extra)) continue # if domain.endswith(".tumblr.com"): # print("# tumblr found:", link) try: images = tumblr.extract_images_from_a_specific_post(link) except: log.warning(f"cannot extract images from {link}") images = [] # print("# extracted images:", len(images)) for img_url in images: if Path(img_url).suffix.lower() in cfg.SUPPORTED_FORMATS: result.append(ImageWithExtraInfo(img_url, extra)) # # continue # end tumblr section if domain.endswith("imgur.com"): if imgur.is_album(link): try: images = imgur.extract_images_from_an_album(link) except: log.warning(f"cannot extract images from {link}") images = [] for img_url in images: if Path(img_url).suffix.lower() in cfg.SUPPORTED_FORMATS: result.append(ImageWithExtraInfo(img_url, extra)) # # else: # it's on imgur.com but it's not an album # it may be a single image embedded in an HTML page try: img_url = link + ".jpg" # it works sometimes r = requests.head(img_url, headers=cfg.headers, timeout=cfg.REQUESTS_TIMEOUT) if r.ok: result.append(ImageWithExtraInfo(img_url, extra)) except: log.warning(f"problem with {link} -> {img_url}") # end imgur section # return result except KeyError: log.warning(f"cannot extract data from {img_url}") return [] except Exception as e: log.warning(f"exception: {str(e)}") log.warning(f"problem with {img_url}") return [] finally: if statusbar: statusbar.progressbar.hide() if mainWindow: mainWindow.loading_line.hide()
def update(self, x_list: list[float], y_dict: dict[str, list[np.ndarray]]): for i, yData in enumerate(y_dict.values()): self.plotItem.getViewBox().addedItems[i].setData(x_list, yData) x_end = self.x_range if x_list[-1] < self.x_range else x_list[-1] self.setXRange(x_list[0], x_end) QApplication.processEvents()
painter.drawPixmap(0, 0, pixmap) if __name__ == '__main__': app = QApplication() progressbar_value = 30 path_to_gif = 'loading_gifs/1.gif' splash = MovieSplashScreen(path_to_gif) progressbar = QProgressBar(splash) progressbar.setMaximum(progressbar_value) progressbar.setTextVisible(False) progressbar.setGeometry(0, splash.my_size.height() - 50, splash.my_size.width(), 20) splash.show() for i in range(progressbar_value): progressbar.setValue(i) t = time.time() while time.time() < t + 0.1: app.processEvents() time.sleep(1) window = MainWindow() window.show() splash.finish(window) sys.exit(app.exec_())
def CenterItem(self, item: ChipItem): QApplication.processEvents() sceneCenter = self.mapToScene(self.rect().center()) currentCenter = item.GraphicsObject().sceneBoundingRect().center() delta = sceneCenter - currentCenter item.Move(delta)
def pyside6_splash_main(main_module_name: str, main_func_name: str, min_py_ver: Iterable, requirements: Iterable, splash_text: str, pre_main_name: Optional[str] = None): """ Splash screen & intall packages. 1. Show PySide6 splash 2. Check & install packages 3. Hide splash 4. Then run the main function. Text of splash screen is read from launch.json at root directory. Args: main_module_name (str): The module that main function exists. main_func_name (str): The name of main function. It will be called by this function if installer successfully executed. min_py_ver (Iterable): The minimum requirement of python version. requirements (Iterable): PIP names of required package. splash_text (str): The text displayed to splash screen. pre_main_name (str, optional): Function that must be called before main function run. Return value of function will be used as second argument of main function. """ if _check_py_ver(min_py_ver): return 1 # pylint: disable = not-callable if _check_imports(): # When PySide6 is not installed # Check missing packages and install (with PySide6) if IS_ZIPFILE: return_code = _zipapp_package_installer(requirements) else: return_code = _normal_package_checker(requirements) if return_code != 0: return return_code # Create Qt application & Show splash app = QApplication() icon = get_icon() if icon is not None: app.setWindowIcon(icon) splash = _Splash(app, splash_text) splash.show() QApplication.processEvents() else: # When PySide6 is installed # Create Qt application & Show splash app = QApplication() icon = get_icon() if icon is not None: app.setWindowIcon(icon) splash = _Splash(app, splash_text) splash.show() QApplication.processEvents() # Check another missing packages if IS_ZIPFILE: return_code = _zipapp_package_installer(requirements) else: return_code = _normal_package_checker(requirements) if return_code != 0: splash.hide() return return_code QApplication.processEvents() main_module = import_module(main_module_name) QApplication.processEvents() if pre_main_name is not None: res = getattr(main_module, pre_main_name)() QApplication.processEvents() splash.hide() return getattr(main_module, main_func_name)(app, res) splash.hide() return getattr(main_module, main_func_name)(app)
def download_data(self): validation_errors: List[str] = self.validate() if len(validation_errors) > 0: self.info("Errors encountered") for error in validation_errors: self.info(error) return username: str = self.authentication_widget.username.text() password: str = self.authentication_widget.password.text() protocol: str if self.server_selection_widget.https.isChecked(): protocol = "https" else: protocol = "http" host: str = self.server_selection_widget.host.text() port: int = int(self.server_selection_widget.port.text()) out_dir: str = self.output_directory_widget.output_dir.text() redvox_config: RedVoxConfig = RedVoxConfig(username, password, protocol, host, port) req_start: int = int(self.window_selection_widget.start_dt. dateTime().toSecsSinceEpoch()) req_end: int = int(self.window_selection_widget.end_dt.dateTime(). toSecsSinceEpoch()) station_ids: List[str] = list( map(str.strip, self.station_ids_widget.toPlainText().splitlines(False))) api_type: DataRangeReqType if self.api_selection_widget.api_900_1000.isChecked(): # noinspection PyTypeChecker api_type = DataRangeReqType.API_900_1000 elif self.api_selection_widget.api_1000.isChecked(): # noinspection PyTypeChecker api_type = DataRangeReqType.API_1000 else: # noinspection PyTypeChecker api_type = DataRangeReqType.API_900 retries: int = int(self.server_selection_widget.retries.text()) timeout: int = int(self.server_selection_widget.timeout.text()) correct_query_timing: bool = ( not self.server_selection_widget.disable_timing_correction. isChecked()) manager = Manager() out_queue = manager.Queue(1024) self.info("Starting data query") process = Process( target=download_process, args=( redvox_config, timeout, req_start, req_end, station_ids, api_type, correct_query_timing, out_dir, retries, out_queue, ), ) process.start() result: str = "" while result != "done": # noinspection PyBroadException try: result = out_queue.get(block=True, timeout=0.1) self.info(result) QApplication.processEvents() except: pass