def __reload_atlas(self, *_) -> None: """Reload the atlas.""" scroll_bar: QScrollBar = self.structure_list.verticalScrollBar() scroll_pos = scroll_bar.sliderPosition() index = self.structure_list.currentRow() self.structure_list.clear() if not self.answer: return dlg = SynthesisProgressDialog( "Structural Synthesis", f"Drawing atlas ({len(self.answer)}) ...", len(self.answer), self ) dlg.show() t0 = process_time() for i, G in enumerate(self.answer): QCoreApplication.processEvents() if dlg.wasCanceled(): return if self.__draw_atlas(i, G): dlg.setValue(i + 1) else: break self.__set_paint_time(process_time() - t0) dlg.setValue(dlg.maximum()) dlg.deleteLater() scroll_bar.setSliderPosition(scroll_pos) self.structure_list.setCurrentRow(index)
def GetInputOptions( self, message='', options='', default='', address='', addressType='' ): # Construct the list of options if options are given ok = False item = '' if options != '': input_dialog = QInputDialog() input_dialog.setComboBoxItems(options) input_dialog.setComboBoxEditable(False) if default: # of there is no default, the first item will be the default input_dialog.setTextValue(default) input_dialog.setWindowTitle("Input") input_dialog.setLabelText(message) input_dialog.setModal(False) input_dialog.show() while input_dialog.isVisible(): QCoreApplication.processEvents() ok = input_dialog.result() item = input_dialog.textValue() response = item if ok and item else 'stop' if response == 'stop': self.addlog(response) raise Exception('User requested stop') self.StoreMeasurement(address, addressType, response) self.addlog(response) return self.returnlog()
def stop_func(self) -> bool: """Return dialog status.""" try: QCoreApplication.processEvents() return self.wasCanceled() except ValueError: return False
def check_update(dlg: QProgressDialog) -> str: """Check for update.""" ver_list = [int(v) for v in __version__.split('.') if v.isdigit()] logger.info(f"Getting update for \"{__version__}\":") m = len(ver_list) for i in range(m): if i == 0: text = "major" elif i == 1: text = "minor" else: text = "micro" dlg.setLabelText(f"Checking for {text}...") QCoreApplication.processEvents() if dlg.wasCanceled(): return "" next_ver = ver_list[:m] next_ver[i] += 1 for j in range(i + 1, m): next_ver[j] = 0 if i == 0: next_ver[1] = 1 elif i == 1: if next_ver[1] > 12: dlg.setValue(i + 1) continue url = (f"https://github.com/KmolYuan/Pyslvs-UI/releases/tag/" f"v{next_ver[0]}.{next_ver[1]:02}.{next_ver[2]}") request = get_url(url) dlg.setValue(i + 1) if request.status_code == 200: dlg.setValue(m) return url return ""
def _on_tree_selection(self, selected: QItemSelection, deselected: QItemSelection): item = self.model.itemFromIndex(selected.indexes()[0]) self.thumb_grid.set_item(item) if item.isImage(): QCoreApplication.processEvents() self.load_image(item.wrapper)
def test_connected_receiver_receives_text(self): recv = Receiver() writer = WriteToSignal(sys.stdout) writer.sig_write_received.connect(recv.capture_text) txt = "I expect to see this" writer.write(txt) QCoreApplication.processEvents() self.assertEqual(txt, recv.captured_txt)
def test_connected_receiver_receives_text(self): recv = Receiver() writer = WriteToSignal() writer.sig_write_received.connect(recv.capture_text) txt = "I expect to see this" writer.write(txt) QCoreApplication.processEvents() self.assertEqual(txt, recv.captured_txt)
def test_connected_receiver_receives_text(self): with patch("sys.stdout.fileno", return_value=1) as mock_fileno: recv = Receiver() writer = WriteToSignal(sys.stdout) writer.sig_write_received.connect(recv.capture_text) txt = "I expect to see this" writer.write(txt) QCoreApplication.processEvents() self.assertEqual(txt, recv.captured_txt) mock_fileno.assert_called_once_with()
def _run_async_code(self, code, filename=None): executor = PythonCodeExecution() recv = Receiver() executor.sig_exec_success.connect(recv.on_success) executor.sig_exec_error.connect(recv.on_error) task = executor.execute_async(code, filename) task.join() QCoreApplication.processEvents() return executor, recv
def test_connected_receiver_receives_text(self): with patch("sys.stdout") as mock_stdout: mock_stdout.fileno.return_value = -1 recv = Receiver() writer = WriteToSignal(mock_stdout) writer.sig_write_received.connect(recv.capture_text) txt = "I expect to see this" writer.write(txt) QCoreApplication.processEvents() self.assertEqual(txt, recv.captured_txt) mock_stdout.fileno.assert_called_once_with()
def test_open_mask(self, qtbot, monkeypatch, tmp_path): monkeypatch.setattr(mask_main_window, "CONFIG_FOLDER", str(tmp_path)) if platform.system() == "Linux" and (GITHUB_ACTIONS or TRAVIS): monkeypatch.setattr(mask_main_window.MainWindow, "show", empty) main_window = LauncherMainWindow("Launcher") qtbot.addWidget(main_window) main_window._launch_mask() with qtbot.waitSignal(main_window.prepare.finished): main_window.prepare.start() # qtbot.addWidget(main_window.wind) QCoreApplication.processEvents() main_window.wind.hide()
def _run_async_code(self, code, with_progress=False, filename=None): executor = PythonCodeExecution() if with_progress: recv = ReceiverWithProgress() executor.sig_exec_progress.connect(recv.on_progess_update) else: recv = Receiver() executor.sig_exec_success.connect(recv.on_success) executor.sig_exec_error.connect(recv.on_error) task = executor.execute_async(code, filename) task.join() QCoreApplication.processEvents() return executor, recv
def __reload_atlas(self) -> None: """Reload atlas with the engine.""" current_pos = self.collection_list.currentRow() self.collections_layouts.clear() self.collection_list.clear() self.__clear_selection() if not self.collections: return dlg = QProgressDialog( "Drawing atlas...", "Cancel", 0, len(self.collections), self ) dlg.setWindowTitle("Type synthesis") dlg.resize(400, dlg.height()) dlg.setModal(True) dlg.show() engine_str = self.graph_engine.currentText() for i, g in enumerate(self.collections): QCoreApplication.processEvents() if dlg.wasCanceled(): dlg.deleteLater() return item = QListWidgetItem(f"No. {i + 1}") engine = engine_picker(g, engine_str, self.graph_link_as_node.isChecked()) item.setIcon(graph2icon( g, self.collection_list.iconSize().width(), engine, self.graph_link_as_node.isChecked(), self.graph_show_label.isChecked(), self.prefer.monochrome_option )) self.collections_layouts.append(engine) item.setToolTip(f"{g.edges}") self.collection_list.addItem(item) dlg.setValue(i + 1) dlg.deleteLater() if current_pos > -1: self.collection_list.setCurrentRow(current_pos) self.__set_selection(self.collection_list.currentItem())
def flush(self, error=False, prompt=False): """Flush buffer, write text to console""" # Fix for Issue 2452 try: text = "".join(self.__buffer) except TypeError: text = b"".join(self.__buffer) try: text = text.decode(locale.getdefaultlocale()[1]) except: pass self.__buffer = [] self.insert_text(text, at_end=True, error=error, prompt=prompt) QCoreApplication.processEvents() self.repaint() # Clear input buffer: self.new_input_line = True
class CreateFileInformationTest(unittest.TestCase): def setUp(self): self.success_callback = mock.MagicMock() self.success_callback_1 = mock.MagicMock() self.error_callback = mock.MagicMock() self.work_handler = WorkHandler() self.qApp = QCoreApplication(['test_app']) def test_retieves_file_information_and_passes_to_callback(self): create_file_information('LOQ74044', self.error_callback, self.success_callback, self.work_handler, 0) self.work_handler.wait_for_done() self.qApp.processEvents() self.assertEqual(self.success_callback.call_count, 1) self.assertEqual(self.error_callback.call_count, 0) def test_that_retrieved_file_information_is_correct(self): create_file_information('LOQ74044', self.error_callback, self.success_callback, self.work_handler, 0) self.work_handler.wait_for_done() self.qApp.processEvents() file_information = self.success_callback.call_args[0][0] self.assertEqual(file_information.is_event_mode(), False) self.assertEqual(file_information.get_run_number(), 74044) self.assertEqual(file_information.get_thickness(), 1.0) def test_that_multiple_threading_calls_at_once_are_handled_cleanly(self): create_file_information('LOQ74044', self.error_callback, self.success_callback, self.work_handler, 0) create_file_information('LOQ74044', self.error_callback, self.success_callback_1, self.work_handler, 0) create_file_information('LOQ74044', self.error_callback, self.success_callback_1, self.work_handler, 1) create_file_information('LOQ74044', self.error_callback, self.success_callback_1, self.work_handler, 0) create_file_information('LOQ74044', self.error_callback, self.success_callback_1, self.work_handler, 2) self.work_handler.wait_for_done() self.qApp.processEvents() self.assertEqual(self.success_callback.call_count, 0) self.assertEqual(self.success_callback_1.call_count, 3) self.assertEqual(self.error_callback.call_count, 0) @mock.patch('sans.gui_logic.presenter.create_file_information.SANSFileInformationFactory') def test_that_error_callback_is_called_on_error_with_correct_message(self, file_information_factory_mock): file_information_factory_instance = mock.MagicMock() file_information_factory_instance.create_sans_file_information.side_effect = RuntimeError('File Error') file_information_factory_mock.return_value = file_information_factory_instance create_file_information('LOQ74044', self.error_callback, self.success_callback, self.work_handler, 0) self.work_handler.wait_for_done() self.qApp.processEvents() self.success_callback.assert_called_once_with(None) self.assertEqual(self.error_callback.call_count, 1) self.assertEqual(str(self.error_callback.call_args[0][0][1]), 'File Error')
def test_set_roi(self, qtbot, part_settings, image): prop = ChannelProperty(part_settings, "test") viewer = ResultImageView(part_settings, prop, "test") qtbot.add_widget(prop) qtbot.add_widget(viewer) viewer.show() part_settings.image = image roi = ROIInfo((image.get_channel(0) > 0).astype(np.uint8)) roi = roi.fit_to_image(image) viewer.set_roi(roi, image) QCoreApplication.processEvents() assert not viewer.roi_alternative_select.isVisible() assert viewer.label1.isVisible() assert viewer.label2.isVisible() assert viewer.opacity.isVisible() assert viewer.only_border.isVisible() assert not viewer.roi_alternative_select.isVisible() assert viewer.any_roi() assert not viewer.available_alternatives() viewer.hide()
def flush(self, error=False, prompt=False): """Flush buffer, write text to console""" # Fix for Issue 2452 if PY3: try: text = "".join(self.__buffer) except TypeError: text = b"".join(self.__buffer) try: text = text.decode( locale.getdefaultlocale()[1] ) except: pass else: text = "".join(self.__buffer) self.__buffer = [] self.insert_text(text, at_end=True, error=error, prompt=prompt) QCoreApplication.processEvents() self.repaint() # Clear input buffer: self.new_input_line = True
def runTests(classname): """ Run the test suite in the class. Uses the XML runner if the MANTID_SOURCE environment variable was set. """ # Custom code to create and run this single test suite suite = QAppThreadCall(unittest.TestSuite)() QAppThreadCall(suite.addTest)(unittest.makeSuite(classname)) # Get the XML runner if the environment variable was set src = os.getenv('MANTID_SOURCE') if src is None: runner = QAppThreadCall(unittest.TextTestRunner)() else: sys.path.append(os.path.join(src, "Testing", "Tools", "unittest-xml-reporting", "src")) import xmlrunner runner = QAppThreadCall(xmlrunner.XMLTestRunner)(output='Testing') # Run using either runner res = QAppThreadCall(runner.run)(suite) # Process some events that ensure MantidPlot closes properly. QCoreApplication.processEvents() QCoreApplication.processEvents() QCoreApplication.processEvents() # Close Mantid and set exit code if not res.wasSuccessful(): sys.exit(1) else: sys.exit(0)
def runTests(classname): """ Run the test suite in the class. Uses the XML runner if the MANTID_SOURCE environment variable was set. """ # Custom code to create and run this single test suite suite = QAppThreadCall(unittest.TestSuite)() QAppThreadCall(suite.addTest)(unittest.makeSuite(classname)) # Get the XML runner if the environment variable was set src = os.getenv('MANTID_SOURCE') if src is None: runner = QAppThreadCall(unittest.TextTestRunner)() else: sys.path.append( os.path.join(src, "Testing", "Tools", "unittest-xml-reporting", "src")) import xmlrunner runner = QAppThreadCall(xmlrunner.XMLTestRunner)(output='Testing') # Run using either runner res = QAppThreadCall(runner.run)(suite) # Process some events that ensure MantidPlot closes properly. QCoreApplication.processEvents() QCoreApplication.processEvents() QCoreApplication.processEvents() # Close Mantid and set exit code if not res.wasSuccessful(): sys.exit(1) else: sys.exit(0)
def GetInput(self, message='', default='', address='', addressType=''): input_dialog = QInputDialog() input_dialog.setTextEchoMode(QLineEdit.Normal) input_dialog.setTextValue(default) input_dialog.setWindowTitle("Input") input_dialog.setLabelText(message) input_dialog.setModal(False) input_dialog.show() while input_dialog.isVisible(): QCoreApplication.processEvents() ok = input_dialog.result() item = input_dialog.textValue() response = item if ok else 'stop' if response == '': response = default elif response == 'stop': self.addlog(response) raise Exception('User requested stop') self.StoreMeasurement(address, addressType, response) self.addlog(response) return self.returnlog()
def listen(self, name=''): super(QZmqNode, self).listen(name) QCoreApplication.processEvents(QEventLoop.ExcludeUserInputEvents)
def create_screenshots(app, window, no_dark): """Save screenshots for different application views and quit.""" from qtpy.QtCore import QCoreApplication from qtpy.QtGui import QGuiApplication from qtpy.QtWidgets import QDockWidget, QTabWidget theme = 'no_dark' if no_dark else 'dark' print('\nCreating {} screenshots'.format(theme)) docks = window.findChildren(QDockWidget) tabs = window.findChildren(QTabWidget) widget_data = { 'containers_no_tabs_buttons.png': [ 'Containers - No Tabs', 'Buttons', ], 'containers_tabs_displays.png': [ 'Containers - Tabs', 'Displays', ], 'widgets_inputs_fields.png': [ 'Widgets', 'Inputs - Fields', ], 'views_inputs_no_fields.png': [ 'Views', 'Inputs - No Fields', ] } # Central widget tabs of with examples, reset positions tab = [tab for tab in tabs if tab.count() >= 12][0] tab.setCurrentIndex(0) QCoreApplication.processEvents() for fname_suffix, dw_titles in widget_data.items(): png_path = os.path.join(SCREENSHOTS_PATH, theme + '_' + fname_suffix) print('\t' + png_path) for dw in docks: if dw.windowTitle() in dw_titles: print('Evidencing : ', dw.windowTitle()) dw.raise_() dw.show() QCoreApplication.processEvents() # Attention: any change in update, processEvent and sleep calls # make those screenshots not working, specially the first one. # It seems that processEvents are not working properly window.update() window.showFullScreen() QCoreApplication.processEvents() time.sleep(0.5) QCoreApplication.processEvents() screen = QGuiApplication.primaryScreen() QCoreApplication.processEvents() pixmap = screen.grabWindow(window.winId()) # Yeah, this is duplicated to avoid screenshot problems screen = QGuiApplication.primaryScreen() QCoreApplication.processEvents() pixmap = screen.grabWindow(window.winId()) img = pixmap.toImage() img.save(png_path) QCoreApplication.processEvents() QCoreApplication.processEvents() window.close() print('\n') app.exit(sys.exit())
def refreshScreen(cls): QCoreApplication.processEvents()
def create_screenshots(app, window, is_darkstyle): """Save screenshots for different application views and quit.""" from qtpy.QtCore import QCoreApplication from qtpy.QtGui import QGuiApplication from qtpy.QtWidgets import QDockWidget, QTabWidget theme = 'dark' if is_darkstyle else 'normal' print('\nCreating {} screenshots'.format(theme)) docks = window.findChildren(QDockWidget) tabs = window.findChildren(QTabWidget) widget_data = { 'containers_buttons.png': [ 'Containers - No Tabs', 'Buttons', ], 'containers_tabs_displays.png': [ 'Containers - Tabs', 'Displays', ], 'views_inputs_no_fields.png': [ 'Views', 'Inputs - No Fields', ], 'widgets_inputs_fields.png': [ 'Widgets', 'Inputs - Fields', ], } prefix = 'qdarkstyle_' if is_darkstyle else 'no_dark_' screen = QGuiApplication.primaryScreen() QCoreApplication.processEvents() tab = [tab for tab in tabs if tab.count() >= 12][0] tab.setCurrentIndex(11) QCoreApplication.processEvents() for fname_suffix, widgets in widget_data.items(): QCoreApplication.processEvents() png_path = os.path.join(SCREENSHOTS_PATH, prefix + fname_suffix) print('\t' + png_path) for dockwidget_name in widgets: dockwidget = [dw for dw in docks if dw.windowTitle() == dockwidget_name] if dockwidget: dockwidget = dockwidget[0] dockwidget.show() dockwidget.raise_() QCoreApplication.processEvents() dockwidget = None QCoreApplication.processEvents() pixmap = screen.grabWindow(window.winId()) img = pixmap.toImage() img.save(png_path) QCoreApplication.processEvents() window.showNormal() QCoreApplication.processEvents() print('\n') app.exit()
class GuiCommonTest(unittest.TestCase): def setUp(self): self.qApp = QCoreApplication(['test_app']) self.table_model = TableModel() self.state_gui_model = StateGuiModel({}) table_index_model_0 = TableIndexModel('LOQ74044', '', '', '', '', '', '', '', '', '', '', '') table_index_model_1 = TableIndexModel('LOQ74044', '', '', '', '', '', '', '', '', '', '', '') self.table_model.add_table_entry(0, table_index_model_0) self.table_model.add_table_entry(1, table_index_model_1) self.table_model.wait_for_file_finding_done() self.qApp.processEvents() self.fake_state = mock.MagicMock(spec=State) self.gui_state_director_instance = mock.MagicMock() self.gui_state_director_instance.create_state.return_value = self.fake_state self.patcher = mock.patch('sans.gui_logic.models.create_state.GuiStateDirector') self.addCleanup(self.patcher.stop) self.gui_state_director = self.patcher.start() self.gui_state_director.return_value = self.gui_state_director_instance def test_create_states_returns_correct_number_of_states(self): states, errors = create_states(self.state_gui_model, self.table_model, SANSInstrument.LOQ, SANSFacility.ISIS, row_index=[0,1]) self.assertEqual(len(states), 2) def test_create_states_returns_correct_number_of_states_for_specified_row_index(self): states, errors = create_states(self.state_gui_model, self.table_model, SANSInstrument.LOQ, SANSFacility.ISIS, row_index=[1]) self.assertEqual(len(states), 1) def test_skips_empty_rows(self): table_index_model = TableIndexModel('', '', '', '', '', '', '', '', '', '', '', '') self.table_model.add_table_entry(1, table_index_model) self.table_model.wait_for_file_finding_done() self.qApp.processEvents() states, errors = create_states(self.state_gui_model, self.table_model, SANSInstrument.LOQ, SANSFacility.ISIS, row_index=[0,1, 2]) self.assertEqual(len(states), 2) @mock.patch('sans.gui_logic.models.create_state.create_gui_state_from_userfile') def test_create_state_from_user_file_if_specified(self, create_gui_state_mock): create_gui_state_mock.returns = StateGuiModel({}) table_index_model = TableIndexModel('LOQ74044', '', '', '', '', '', '', '', '', '', '', '', user_file='MaskLOQData.txt') table_model = TableModel() table_model.add_table_entry(0, table_index_model) table_model.wait_for_file_finding_done() self.qApp.processEvents() states, errors = create_states(self.state_gui_model, table_model, SANSInstrument.LOQ, SANSFacility.ISIS, row_index=[0,1, 2]) self.assertEqual(len(states), 1) create_gui_state_mock.assert_called_once_with('MaskLOQData.txt', self.state_gui_model) def test_create_gui_state_from_userfile_adds_save_format_from_gui(self): gui_state = StateGuiModel({}) gui_state.save_types = [SaveType.NXcanSAS] row_state = create_gui_state_from_userfile('MaskLOQData.txt', gui_state) self.assertEqual(gui_state.save_types, row_state.save_types)
class QtReactor(posixbase.PosixReactorBase): # implements(IReactorFDSet) def __init__(self): self._reads = {} self._writes = {} self._notifiers = {} self._timer = QTimer() self._timer.setSingleShot(True) self._timer.timeout.connect(self.iterate_qt) if QCoreApplication.instance() is None: # Application Object has not been started yet self.qApp = QCoreApplication([]) self._ownApp = True else: self.qApp = QCoreApplication.instance() self._ownApp = False self._blockApp = None posixbase.PosixReactorBase.__init__(self) def _add(self, xer, primary, type): """ Private method for adding a descriptor from the event loop. It takes care of adding it if new or modifying it if already added for another state (read -> read/write for example). """ if xer not in primary: primary[xer] = TwistedSocketNotifier(None, self, xer, type) def addReader(self, reader): """Add a FileDescriptor for notification of data available to read.""" self._add(reader, self._reads, QSocketNotifier.Read) def addWriter(self, writer): """Add a FileDescriptor for notification of data available to write.""" self._add(writer, self._writes, QSocketNotifier.Write) def _remove(self, xer, primary): """ Private method for removing a descriptor from the event loop. It does the inverse job of _add, and also add a check in case of the fd has gone away. """ if xer in primary: notifier = primary.pop(xer) notifier.shutdown() def removeReader(self, reader): """Remove a Selectable for notification of data available to read.""" self._remove(reader, self._reads) def removeWriter(self, writer): """Remove a Selectable for notification of data available to write.""" self._remove(writer, self._writes) def removeAll(self): """Remove all selectables, and return a list of them.""" return self._removeAll(self._reads, self._writes) def getReaders(self): return self._reads.keys() def getWriters(self): return self._writes.keys() def callLater(self, howlong, *args, **kargs): rval = super(QtReactor, self).callLater(howlong, *args, **kargs) self.reactorInvocation() return rval def reactorInvocation(self): self._timer.stop() self._timer.setInterval(0) self._timer.start() def _iterate(self, delay=None, fromqt=False): """See twisted.internet.interfaces.IReactorCore.iterate.""" self.runUntilCurrent() self.doIteration(delay, fromqt=fromqt) iterate = _iterate def iterate_qt(self, delay=None): self.iterate(delay=delay, fromqt=True) def doIteration(self, delay=None, fromqt=False): """This method is called by a Qt timer or by network activity on a file descriptor""" if not self.running and self._blockApp: self._blockApp.quit() self._timer.stop() if delay is None: delay = 0 delay = max(delay, 1) if not fromqt: self.qApp.processEvents(QEventLoop.AllEvents, delay * 1000) timeout = self.timeout() if timeout is not None: self._timer.setInterval(timeout * 1000) self._timer.start() def runReturn(self, installSignalHandlers=True): self.startRunning(installSignalHandlers=installSignalHandlers) self.reactorInvocation() def run(self, installSignalHandlers=True): if self._ownApp: self._blockApp = self.qApp else: self._blockApp = QEventLoop() self.runReturn() self._blockApp.exec_() if self.running: self.stop() self.runUntilCurrent()
def create_screenshots(app, window, is_darkstyle): """Save screenshots for different application views and quit.""" from qtpy.QtCore import QCoreApplication from qtpy.QtGui import QGuiApplication from qtpy.QtWidgets import QDockWidget, QTabWidget theme = 'dark' if is_darkstyle else 'normal' print('\nCreating {} screenshots'.format(theme)) docks = window.findChildren(QDockWidget) tabs = window.findChildren(QTabWidget) widget_data = { 'containers_buttons.png': [ 'Containers - No Tabs', 'Buttons', ], 'containers_tabs_displays.png': [ 'Containers - Tabs', 'Displays', ], 'views_inputs_no_fields.png': [ 'Views', 'Inputs - No Fields', ], 'widgets_inputs_fields.png': [ 'Widgets', 'Inputs - Fields', ], } prefix = 'qdarkstyle_' if is_darkstyle else 'no_dark_' screen = QGuiApplication.primaryScreen() QCoreApplication.processEvents() tab = [tab for tab in tabs if tab.count() >= 12][0] tab.setCurrentIndex(11) QCoreApplication.processEvents() for fname_suffix, widgets in widget_data.items(): QCoreApplication.processEvents() png_path = os.path.join(SCREENSHOTS_PATH, prefix + fname_suffix) print('\t' + png_path) for dockwidget_name in widgets: dockwidget = [ dw for dw in docks if dw.windowTitle() == dockwidget_name ] if dockwidget: dockwidget = dockwidget[0] dockwidget.show() dockwidget.raise_() QCoreApplication.processEvents() dockwidget = None QCoreApplication.processEvents() pixmap = screen.grabWindow(window.winId()) img = pixmap.toImage() img.save(png_path) QCoreApplication.processEvents() window.showNormal() QCoreApplication.processEvents() print('\n') app.exit()
def load_data(self, file_name: str, data: Dict[str, Any]) -> None: """Load file method.""" self.main_clear() ver = data.get('pyslvs_ver', "") if ver: logger.info(f"Load data from Pyslvs {ver}") del ver dlg = QProgressDialog("Loading project", "Cancel", 0, 8, self.parent()) dlg.setLabelText("Reading file ...") dlg.show() # Mechanism data dlg.setValue(1) dlg.setLabelText("Loading mechanism ...") if dlg.wasCanceled(): dlg.deleteLater() return self.main_clear() self.__set_group("Add mechanism") links_data: Dict[str, str] = data.get('links', {}) self.add_empty_links(links_data) mechanism_data: str = data.get('mechanism', "") self.parse_expression(mechanism_data) self.__end_group() # Input data dlg.setValue(2) dlg.setLabelText("Loading inputs data ...") if dlg.wasCanceled(): dlg.deleteLater() return self.main_clear() self.__set_group("Add inputs data") input_data: List[Dict[str, int]] = data.get('input', []) i_attr = [] for b, d in input_data: QCoreApplication.processEvents() i_attr.append((b, d)) self.load_inputs(i_attr) self.__end_group() # Storage data dlg.setValue(3) dlg.setLabelText("Loading storage ...") if dlg.wasCanceled(): dlg.deleteLater() return self.main_clear() self.__set_group("Add storage") storage_data: Dict[str, str] = data.get('storage', {}) self.load_storage(storage_data) self.__end_group() # Path data dlg.setValue(4) dlg.setLabelText("Loading paths ...") if dlg.wasCanceled(): dlg.deleteLater() return self.main_clear() self.__set_group("Add paths") path_data: Dict[str, Sequence[Tuple[float, float]]] = data.get('path', {}) self.load_paths(path_data) self.__end_group() # Collection data dlg.setValue(5) dlg.setLabelText("Loading graph collections ...") if dlg.wasCanceled(): dlg.deleteLater() return self.main_clear() self.__set_group("Add graph collections") collection_data: List[Tuple[Tuple[int, int], ...]] = data.get('collection', []) self.load_collections(collection_data) self.__end_group() # Configuration data dlg.setValue(6) dlg.setLabelText("Loading synthesis configurations ...") if dlg.wasCanceled(): dlg.deleteLater() return self.main_clear() self.__set_group("Add synthesis configurations") config_data: Dict[str, Dict[str, Any]] = data.get('triangle', {}) self.load_config(config_data) self.__end_group() # Algorithm data dlg.setValue(7) dlg.setLabelText("Loading synthesis results ...") if dlg.wasCanceled(): dlg.deleteLater() return self.main_clear() self.__set_group("Add synthesis results") algorithm_data: List[Dict[str, Any]] = data.get('algorithm', []) self.load_algorithm(algorithm_data) self.__end_group() # Workbook loaded dlg.setValue(8) dlg.deleteLater() # File type option align (ignore previous one) self.prefer.file_type_option = data.get('file_type', 0) # Show overview dialog dlg = OverviewDialog(self.parent(), QFileInfo(file_name).baseName(), storage_data, i_attr, path_data, collection_data, config_data, algorithm_data) dlg.show() dlg.exec_() dlg.deleteLater()