def test_pydmdrawing_paintEvent(qtbot, signals, alarm_sensitive_content): """ Test the paintEvent handling of the widget. This test method will also execute PyDMDrawing alarm_severity_changed and draw_item(). Expectations: The paintEvent will be triggered, and the widget's brush color is correctly set. NOTE: This test depends on the default stylesheet having different values for 'qproperty-brush' for different alarm states of PyDMDrawing. Parameters ---------- qtbot : fixture Window for widget testing signals : fixture The signals fixture, which provides access signals to be bound to the appropriate slots alarm_sensitive_content : bool True if the widget will be redraw with a different color if an alarm is triggered; False otherwise. """ QApplication.instance().make_main_window() main_window = QApplication.instance().main_window qtbot.addWidget(main_window) pydm_drawing = PyDMDrawing(parent=main_window, init_channel='fake://tst') qtbot.addWidget(pydm_drawing) pydm_drawing.alarmSensitiveContent = alarm_sensitive_content brush_before = pydm_drawing.brush.color().name() signals.new_severity_signal.connect(pydm_drawing.alarmSeverityChanged) signals.new_severity_signal.emit(PyDMWidget.ALARM_MAJOR) brush_after = pydm_drawing.brush.color().name() if alarm_sensitive_content: assert brush_before != brush_after else: assert brush_before == brush_after
def test_no_menu_with_one_file(qtbot): QApplication.instance().make_main_window() main_window = QApplication.instance().main_window main_window.setWindowTitle("Related Display Button Test") qtbot.addWidget(main_window) button = PyDMRelatedDisplayButton(parent=main_window) button.filenames = [test_ui_path] qtbot.addWidget(button) button._rebuild_menu() assert button.menu() is None
def test_menu_goes_away_when_files_all_blank(qtbot): QApplication.instance().make_main_window() main_window = QApplication.instance().main_window main_window.setWindowTitle("Related Display Button Test") qtbot.addWidget(main_window) button = PyDMRelatedDisplayButton(parent=main_window) button.filenames = ["", ""] button.titles = ["", ""] qtbot.addWidget(button) button._rebuild_menu() assert button.menu() is None
def set_font_size(self, old, new): current_font = self.app.font() current_font.setPointSizeF(current_font.pointSizeF()/old*new) QApplication.instance().setFont(current_font) for w in self.app.allWidgets(): w_c_f = w.font() w_c_f.setPointSizeF(w_c_f.pointSizeF()/old*new) w.setFont(w_c_f) QTimer.singleShot(0, self.resizeForNewDisplayWidget)
def test_press_without_filename(qtbot): QApplication.instance().make_main_window() main_window = QApplication.instance().main_window main_window.setWindowTitle("Related Display Button Test") qtbot.addWidget(main_window) button = PyDMRelatedDisplayButton(parent=main_window) qtbot.addWidget(button) button._rebuild_menu() qtbot.mouseRelease(button, Qt.LeftButton) qtbot.wait(250) assert "Form" not in QApplication.instance().main_window.windowTitle()
def setAppIcon(self): """ Set up the Qudi application icon. """ iconpath = 'artwork/logo/logo-qudi-' self.appIcon = QIcon() self.appIcon.addFile('{0}16x16.png'.format(iconpath), QSize(16, 16)) self.appIcon.addFile('{0}24x24.png'.format(iconpath), QSize(24, 24)) self.appIcon.addFile('{0}32x32.png'.format(iconpath), QSize(32, 32)) self.appIcon.addFile('{0}48x48.png'.format(iconpath), QSize(48, 48)) self.appIcon.addFile('{0}256x256.png'.format(iconpath), QSize(256, 256)) QApplication.instance().setWindowIcon(self.appIcon)
def test_label_alarms(qtbot, signals, alarm_severity, alarm_sensitive_content, alarm_sensitive_border): """ Test the widget's appearance changes according to changes in alarm severity. Expectations: 1. The widget receives the correct alarm severity 2. The appearance changes to check for are the alarm content (alarm color), and the widget's border appearance, e.g. solid, transparent, etc. 3. The alarm color and border appearance will change only if each corresponding Boolean flag is set to True NOTE: This test depends on the default stylesheet having different values for 'color' for different alarm states of PyDMLabel. Parameters ---------- qtbot : fixture pytest-qt window for widget testing signals : fixture The signals fixture, which provides access signals to be bound to the appropriate slots alarm_severity : int The severity of an alarm (NONE, MINOR, MAJOR, INVALID, or DISCONNECTED) alarm_sensitive_content : bool True if the widget will change color accordingly to the alarm's severity; False if not alarm_sensitive_border : bool True if the widget's border will change color and thickness accordingly to the alarm's severity; False if not """ QApplication.instance().make_main_window() main_window = QApplication.instance().main_window qtbot.addWidget(main_window) pydm_label = PyDMLabel(parent=main_window, init_channel="ca://FOOO") qtbot.addWidget(pydm_label) pydm_label.alarmSensitiveContent = alarm_sensitive_content pydm_label.alarmSensitiveBorder = alarm_sensitive_border signals.connection_state_signal.connect(pydm_label.connectionStateChanged) signals.connection_state_signal.emit(True) signals.new_severity_signal.connect(pydm_label.alarmSeverityChanged) initial_severity = pydm_label._alarm_state option = QStyleOption() option.initFrom(pydm_label) before_color = option.palette.text().color().name() signals.new_severity_signal.emit(alarm_severity) assert pydm_label._alarm_state == alarm_severity option = QStyleOption() option.initFrom(pydm_label) after_color = option.palette.text().color().name() if alarm_sensitive_content and (alarm_severity != initial_severity): assert after_color != before_color else: assert after_color == before_color
def test_press_with_filename(qtbot): QApplication.instance().make_main_window() main_window = QApplication.instance().main_window main_window.setWindowTitle("Related Display Button Test") qtbot.addWidget(main_window) button = PyDMRelatedDisplayButton(parent=main_window) button.filenames = [test_ui_path] qtbot.addWidget(button) button._rebuild_menu() qtbot.mouseRelease(button, Qt.LeftButton) def check_title(): assert "Form" in QApplication.instance().main_window.windowTitle() qtbot.waitUntil(check_title)
def init_qt_clipboard(): # $DISPLAY should exist # Try to import from qtpy, but if that fails try PyQt5 then PyQt4 try: from qtpy.QtWidgets import QApplication except ImportError: try: from PyQt5.QtWidgets import QApplication except ImportError: from PyQt4.QtGui import QApplication app = QApplication.instance() if app is None: app = QApplication([]) def copy_qt(text): cb = app.clipboard() cb.setText(text) def paste_qt(): cb = app.clipboard() return str(cb.text()) return copy_qt, paste_qt
def closeEvent(self, event): # Check whether or not to save project if not self.project.saved: # Offer save if self.project.offer_save(self): # Cancel has been clicked event.ignore() return # Close editors if self.editor.app_closing(): self.writeSettings(CONF) # write current window information to global settings object # Close all open plots # We don't want this at module scope here import matplotlib.pyplot as plt # noqa plt.close('all') app = QApplication.instance() if app is not None: app.closeAllWindows() event.accept() else: # Cancel was pressed when closing an editor event.ignore()
def qapplication(): """Either return a reference to an existing application instance or create a new one :return: A reference to the QApplication object """ app = QApplication.instance() if app is None: QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts) argv = sys.argv[:] argv[0] = APPNAME # replace application name # Workaround a segfault with the IPython console when using Python 3.5 + PyQt 5 # Without this using this fix the above combination causes a segfault when the IPython # console is started # The workaround mentioned in https://groups.google.com/forum/#!topic/leo-editor/ghiIN7irzY0 # is to ensure readline is imported before the QApplication object is created if sys.version_info[0] == 3 and sys.version_info[1] == 5: importlib.import_module("readline") app = QApplication(argv) app.setOrganizationName(ORGANIZATION) app.setOrganizationDomain(ORG_DOMAIN) app.setApplicationName(APPNAME) app.setApplicationVersion(mantid_version_str()) # Spin up the usage service and set the name for the usage reporting # The report is sent when the FrameworkManager kicks up UsageService.setApplicationName(APPNAME) return app
def init_qt_clipboard(): global QApplication # $DISPLAY should exist # Try to import from qtpy, but if that fails try PyQt5 then PyQt4 try: from qtpy.QtWidgets import QApplication except: try: from PyQt5.QtWidgets import QApplication except: from PyQt4.QtGui import QApplication app = QApplication.instance() if app is None: app = QApplication([]) def copy_qt(text): text = _stringifyText(text) # Converts non-str values to str. cb = app.clipboard() cb.setText(text) def paste_qt(): cb = app.clipboard() return STR_OR_UNICODE(cb.text()) return copy_qt, paste_qt
def test_menu_goes_away_when_files_removed(qtbot): QApplication.instance().make_main_window() main_window = QApplication.instance().main_window main_window.setWindowTitle("Related Display Button Test") qtbot.addWidget(main_window) button = PyDMRelatedDisplayButton(parent=main_window) main_window.set_display_widget(button) button.filenames = ["one.ui", "two.ui"] button.titles = ["One", "Two"] qtbot.addWidget(button) button._rebuild_menu() assert button.menu() is not None button.filenames = [] button.titles = [] button._rebuild_menu() assert button.menu() is None
def __init__(self, channel, address, protocol=None, parent=None): super(PyDMConnection, self).__init__(parent) self.protocol = protocol self.address = address self.connected = False self.value = None self.listener_count = 0 self.app = QApplication.instance()
def qapplication(): """Either return a reference to an existing application instance or create a new one :return: A reference to the QApplication object """ app = QApplication.instance() if app is None: app = QApplication(['Mantid Workbench']) return app
def __init__(self, target, executable=None, name=None, extra_args=None, libs=None, cwd=None, env=None): super(AsyncClient, self).__init__() self.executable = executable or sys.executable self.extra_args = extra_args self.target = target self.name = name or self self.libs = libs self.cwd = cwd self.env = env self.is_initialized = False self.closing = False self.context = zmq.Context() QApplication.instance().aboutToQuit.connect(self.close) # Set up the heartbeat timer. self.timer = QTimer(self) self.timer.timeout.connect(self._heartbeat)
def test_old_display_filename_property(qtbot): # This test is mostly only checking that the related display button # doesn't totally explode when the old 'displayFilename' property is used. QApplication.instance().make_main_window() main_window = QApplication.instance().main_window main_window.setWindowTitle("Related Display Button Test") qtbot.addWidget(main_window) button = PyDMRelatedDisplayButton(parent=main_window) with pytest.warns(None) as record: button.displayFilename = test_ui_path assert len(record) >= 1 assert button.filenames[0] == test_ui_path qtbot.addWidget(button) button._rebuild_menu() qtbot.mouseRelease(button, Qt.LeftButton) def check_title(): assert "Form" in QApplication.instance().main_window.windowTitle() qtbot.waitUntil(check_title)
def test_menu_with_additional_files(qtbot): QApplication.instance().make_main_window() main_window = QApplication.instance().main_window main_window.setWindowTitle("Related Display Button Test") qtbot.addWidget(main_window) button = PyDMRelatedDisplayButton(parent=main_window) main_window.set_display_widget(button) button.filenames = [test_ui_path, test_ui_path] button.titles = ["One", "Two"] qtbot.addWidget(button) button._rebuild_menu() assert button.menu() is not None qtbot.mouseRelease(button, Qt.LeftButton) qtbot.waitExposed(button.menu()) qtbot.mouseClick(button.menu(), Qt.LeftButton) button.menu().actions()[0].trigger() def check_title(): assert "Form" in QApplication.instance().main_window.windowTitle() qtbot.waitUntil(check_title)
def setStyleSheet(self, stylesheetpath): """ Set qss style sheet for application. @param str stylesheetpath: path to style sheet file """ with open(stylesheetpath, 'r') as stylesheetfile: stylesheet = stylesheetfile.read() # see issue #12 on qdarkstyle github if platform.system().lower() == 'darwin' and stylesheetpath.endswith('qdark.qss'): mac_fix = ''' QDockWidget::title { background-color: #31363b; text-align: center; height: 12px; } ''' stylesheet += mac_fix QApplication.instance().setStyleSheet(stylesheet)
def destroy(self, *args): # check for qApp first, as PySide deletes it in its atexit handler if QApplication.instance() is None: return if self.window._destroying: return self.window._destroying = True self.window.destroyed.connect(self._widgetclosed) if self.toolbar: self.toolbar.destroy() self.window.close()
def __init__(self, parent=None): QFrame.__init__(self, parent) PyDMPrimitiveWidget.__init__(self) self._template_filename = "" self._count_shown_in_designer = 1 self._data_source = "" self._data = [] self._cached_template = None self._layout_type = LayoutType.Vertical self.app = QApplication.instance() self.rebuild()
def __init__(self, callee): self.qApp = QApplication.instance() QObject.__init__(self) self.moveToThread(self.qApp.thread()) self.callee = callee # Help should then give the correct doc self.__call__.__func__.__doc__ = callee.__doc__ self._args = None self._kwargs = None self._result = None self._exc_info = None
def get_qapplication(): ''' Example usage: app, within_mantid = get_qapplication() reducer = eventFilterGUI.MainWindow() # the main ui class in this file reducer.show() if not within_mantid: sys.exit(app.exec_())''' app = QApplication.instance() if app: return app, app.applicationName().lower().startswith('mantid') else: return QApplication(sys.argv), False
def __init__(self, parent=None, init_channel=None): QWidget.__init__(self, parent) PyDMWidget.__init__(self, init_channel=init_channel) if 'Index' not in PyDMSymbol.RULE_PROPERTIES: PyDMSymbol.RULE_PROPERTIES = PyDMWidget.RULE_PROPERTIES.copy() PyDMSymbol.RULE_PROPERTIES.update( {'Index': ['set_current_key', object]}) self.app = QApplication.instance() self._current_key = 0 self._state_images_string = "" self._state_images = {} # Keyed on state values (ints), values are (filename, qpixmap or qsvgrenderer) tuples. self._aspect_ratio_mode = Qt.KeepAspectRatio self._sizeHint = self.minimumSizeHint() self._painter = QPainter()
def __init__(self, channel, pv, protocol=None, parent=None): super(Connection, self).__init__(channel, pv, protocol, parent) self.app = QApplication.instance() self._value = None self._severity = None self._precision = None self._enum_strs = None self._unit = None self._upper_ctrl_limit = None self._lower_ctrl_limit = None self.pv = epics.get_pv(pv, connection_callback=self.send_connection_state, form='ctrl', auto_monitor=SubscriptionType.DBE_VALUE|SubscriptionType.DBE_ALARM|SubscriptionType.DBE_PROPERTY, access_callback=self.send_access_state) self.pv.add_callback(self.send_new_value, with_ctrlvars=True) self.add_listener(channel)
def __init__(self, parent=None, init_channel=None): QLineEdit.__init__(self, parent) PyDMWritableWidget.__init__(self, init_channel=init_channel) self.app = QApplication.instance() self._display = None self._scale = 1 self.returnPressed.connect(self.send_value) self.unitMenu = QMenu('Convert Units', self) self.create_unit_options() self._display_format_type = self.DisplayFormat.Default self._string_encoding = "utf_8" if utilities.is_pydm_app(): self._string_encoding = self.app.get_string_encoding()
def on_install(self, editor): """ Extends :meth:`spyder.api.EditorExtension.on_install` method to set the editor instance as the parent widget. .. warning:: Don't forget to call **super** if you override this method! :param editor: editor instance :type editor: spyder.plugins.editor.widgets.codeeditor.CodeEditor """ EditorExtension.on_install(self, editor) self.setParent(editor) self.setPalette(QApplication.instance().palette()) self.setFont(QApplication.instance().font()) self.editor.panels.refresh() self._background_brush = QBrush(QColor( self.palette().window().color())) self._foreground_pen = QPen(QColor( self.palette().windowText().color())) if self.position == self.Position.FLOATING: self.setAttribute(Qt.WA_TransparentForMouseEvents)
def __init__(self, parent=None, init_channel=None): QLabel.__init__(self, parent) PyDMWidget.__init__(self, init_channel=init_channel) if 'Text' not in PyDMLabel.RULE_PROPERTIES: PyDMLabel.RULE_PROPERTIES = PyDMWidget.RULE_PROPERTIES.copy() PyDMLabel.RULE_PROPERTIES.update( {'Text': ['value_changed', str]}) self.app = QApplication.instance() self.setTextFormat(Qt.PlainText) self.setTextInteractionFlags(Qt.NoTextInteraction) self.setText("PyDMLabel") self._display_format_type = self.DisplayFormat.Default self._string_encoding = "utf_8" if is_pydm_app(): self._string_encoding = self.app.get_string_encoding()
def __init__(self, creator, tester): """ Initialise ModalTester. :param creator: Function without arguments that creates a modal widget. Can be a class name. A modal widget must have exec_() method. :param tester: A function taking a widget as its argument that does testing. """ self.app = QApplication.instance() if self.app is None: self.app = QApplication(['']) self.creator = creator self.tester = tester self.widget = None self.timer = None self.passed = False
def qapplication(translate=True, test_time=3): """Return QApplication instance Creates it if it doesn't already exist""" app = QApplication.instance() if app is None: app = QApplication(['Conda-Manager']) app.setApplicationName('Conda-Manager') if translate: install_translator(app) test_travis = os.environ.get('TEST_CI', None) if test_travis is not None: timer_shutdown = QTimer(app) timer_shutdown.timeout.connect(app.quit) timer_shutdown.start(test_time*1000) return app
def closeEvent(self, event): if self.project.is_saving or self.project.is_loading: event.ignore() self.project.inform_user_not_possible() return # Check whether or not to save project if not self.project.saved: # Offer save if self.project.offer_save(self): # Cancel has been clicked event.ignore() return # Close editors if self.editor.app_closing(): # write out any changes to the mantid config file ConfigService.saveConfig(ConfigService.getUserFilename()) # write current window information to global settings object self.writeSettings(CONF) # Close all open plots # We don't want this at module scope here import matplotlib.pyplot as plt # noqa plt.close('all') app = QApplication.instance() if app is not None: app.closeAllWindows() # Kill the project recovery thread and don't restart should a save be in progress and clear out current # recovery checkpoint as it is closing properly self.project_recovery.stop_recovery_thread() self.project_recovery.closing_workbench = True self.project_recovery.remove_current_pid_folder() self.interface_manager.closeHelpWindow() event.accept() else: # Cancel was pressed when closing an editor event.ignore()
def get_sheet(selected: bool=False, app: Optional[QApplication]=None) -> str: if app is None: app = QApplication.instance() pal = app.palette() if KColorScheme is not None: scheme = KColorScheme(QPalette.Active, KColorScheme.Window) positive, neutral, negative = map(scheme.foreground, [KColorScheme.PositiveText, KColorScheme.NeutralText, KColorScheme.NegativeText]) else: positive, neutral, negative = [pal.windowText()] * 3 colors = [ pal.highlightedText() if selected else pal.windowText(), pal.highlight() if selected else pal.window(), pal.highlightedText() if selected else pal.highlight(), positive, neutral, negative, ] return STYLESHEET_TEMPLATE.format(*[c.color().name() for c in colors])
def destroy(self, *args): # check for qApp first, as PySide deletes it in its atexit handler if QApplication.instance() is None: return if self.window._destroying: return self.window._destroying = True if self.toolbar: self.toolbar.destroy() self._ads_observer.observeAll(False) del self._ads_observer for id in self._cids: self.canvas.mpl_disconnect(id) self.window.close() try: Gcf.destroy(self.num) except AttributeError: pass
def __init__(self, parent=None, prefix=VACA_PREFIX): super().__init__(parent) self.setObjectName('ASApp') self.setWindowTitle('Efficiency Monitor') color = get_appropriate_color('AS') self.setWindowIcon(qta.icon('mdi.percent-outline', color=color)) self._prefix = prefix self._eff_list = ( # ('LI-SI Inj', 'AS-Glob:AP-CurrInfo:InjEff-Mon', 'magenta'), ('BO-SI Inj', 'SI-Glob:AP-CurrInfo:InjEff-Mon', 'blue'), ('TS', 'TS-Glob:AP-CurrInfo:TranspEff-Mon', 'black'), ('BO Ramp', 'BO-Glob:AP-CurrInfo:RampEff-Mon', 'green'), # ('LI-BO Inj', 'BO-Glob:AP-CurrInfo:InjEff-Mon', 'darkRed'), ('TB', 'TB-Glob:AP-CurrInfo:TranspEff-Mon', 'darkCyan'), ('LI', 'LI-Glob:AP-CurrInfo:TranspEff-Mon', 'red'), ) self._app = QApplication.instance() font = self._app.font() font.setPointSize(32) self._app.setFont(font) self._setupUi()
def __init__(self, widget, parent=None): super(DroEditor, self).__init__(parent) self.widget = widget self.app = QApplication.instance() uic.loadUi(UI_FILE, self) self.axisCombo.setCurrentIndex(self.widget.axisNumber) self.refTypCombo.setCurrentIndex(self.widget.referenceType) self.inFmtEntry.setText(self.widget.inchFormat) self.mmFmtEntry.setText(self.widget.millimeterFormat) self.degFmtEntry.setText(self.widget.degreeFormat) self.latheModeCombo.setCurrentIndex(self.widget.latheMode) bb = self.buttonBox bb.button(QDialogButtonBox.Apply).setDefault(True) bb.button(QDialogButtonBox.Cancel).setDefault(False) bb.button(QDialogButtonBox.Apply).clicked.connect(self.accept)
def _slice_browser(renderer_interactive_pyvistaqt): from qtpy.QtWidgets import QApplication from mne.gui._core import SliceBrowser app = QApplication.instance() if app is None: app = QApplication(["Slice Browser"]) # Use a fixture to create these classes so we can ensure that they # are closed at the end of the test guis = list() def fun(*args, **kwargs): guis.append(SliceBrowser(*args, **kwargs)) return guis[-1] yield fun for gui in guis: try: gui.close() except Exception: pass
def showDialog(name): """Show Dialog Args: name (str) : The name of the dialog to show. """ dialog = getDialog(name) if dialog is None: msg = "The requested dialog <b>{}</b> was not found.".format(name) QMessageBox.critical(None, "Dialog not found!", msg) return win = QApplication.instance().activeWindow() win_pos = win.mapToGlobal(win.rect().center()) dialog.move(win_pos.x() - dialog.width() / 2, win_pos.y() - dialog.height() / 2) dialog.show() ACTIVE_DIALOGS.append(dialog)
def test_stylesheet_apply(qtbot): # Backup of the variable env_backup = os.getenv("PYDM_STYLESHEET", None) # Backup of the GLOBAL_STYLESHEET path backup_global = stylesheet.GLOBAL_STYLESHEET os.environ["PYDM_STYLESHEET"] = "" assert os.getenv("PYDM_STYLESHEET", None) == "" # Retrieve instance of the application so we can test with it app = QApplication.instance() # Ensure that the app stylesheet is clean assert not app.styleSheet() stylesheet.clear_cache() # Exercise apply stylesheet to app stylesheet.apply_stylesheet() assert app.styleSheet() is not None # Backup of the GLOBAL_STYLESHEET path backup_global = stylesheet.GLOBAL_STYLESHEET stylesheet.clear_cache() # Exercise when there is no stylesheet available stylesheet.GLOBAL_STYLESHEET = "invalid_file.none" app.setStyleSheet("") assert not app.styleSheet() # Test apply stylesheet to app stylesheet.apply_stylesheet() assert not app.styleSheet() # Restore the variable if env_backup: os.environ["PYDM_STYLESHEET"] = env_backup stylesheet.GLOBAL_STYLESHEET = backup_global
def gui_qt(*, startup_logo=False): """Start a Qt event loop in which to run the application. Parameters ---------- startup_logo : bool Show a splash screen with the napari logo during startup. Notes ----- This context manager is not needed if running napari within an interactive IPython session. In this case, use the ``%gui qt`` magic command, or start IPython with the Qt GUI event loop enabled by default by using ``ipython --gui=qt``. """ splash_widget = None app = QApplication.instance() if not app: # automatically determine monitor DPI. # Note: this MUST be set before the QApplication is instantiated QApplication.setAttribute(Qt.AA_EnableHighDpiScaling) # if this is the first time the Qt app is being instantiated, we set # the name, so that we know whether to raise_ in Window.show() app = QApplication(sys.argv) app.setApplicationName('napari') if startup_logo: logopath = join(dirname(__file__), '..', 'resources', 'logo.png') pm = QPixmap(logopath).scaled( 360, 360, Qt.KeepAspectRatio, Qt.SmoothTransformation ) splash_widget = QSplashScreen(pm) splash_widget.show() yield app # if the application already existed before this function was called, # there's no need to start it again. By avoiding unnecessary calls to # ``app.exec_``, we avoid blocking. if app.applicationName() == 'napari': if splash_widget and startup_logo: splash_widget.close() app.exec_()
def test_construct(qtbot): """ Test the construction of the widget. Expectations: All the default values are correctly assigned. Parameters ---------- qtbot : fixture Window for widget testing """ pydm_spinbox = PyDMSpinbox() qtbot.addWidget(pydm_spinbox) assert pydm_spinbox.valueBeingSet is False assert pydm_spinbox.isEnabled() is False assert pydm_spinbox._show_step_exponent is True assert pydm_spinbox.step_exponent == 0 assert pydm_spinbox.decimals() == 0 assert pydm_spinbox.app == QApplication.instance() assert pydm_spinbox.isAccelerated() is True
def _create_qApp(): """ Create QApplicaiton if one does not exist. Return QApplication.instance(). Vendored from matplotlib.backends.backend_qt5 with changes: - Assume Qt5, removing tolerance for Qt4. - Applicaiton has been changed (matplotlib -> bluesky). """ global qApp if qApp is None: app = QApplication.instance() if app is None: # check for DISPLAY env variable on X11 build of Qt try: from PyQt5 import QtX11Extras # noqa is_x11_build = True except ImportError: is_x11_build = False else: is_x11_build = hasattr(QtGui, "QX11Info") if is_x11_build: display = os.environ.get('DISPLAY') if display is None or not re.search(r':\d', display): raise RuntimeError('Invalid DISPLAY variable') try: QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling) except AttributeError: # Attribute only exists for Qt>=5.6. pass qApp = QApplication(["bluesky"]) qApp.lastWindowClosed.connect(qApp.quit) else: qApp = app try: qApp.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps) except AttributeError: pass
def show_notification(cls, notification: Notification): from ...utils.settings import get_settings settings = get_settings() # after https://github.com/napari/napari/issues/2370, # the os.getenv can be removed (and NAPARI_CATCH_ERRORS retired) if (os.getenv("NAPARI_CATCH_ERRORS") not in ('0', 'False') and notification.severity >= settings.application.gui_notification_level): application_instance = QApplication.instance() if application_instance: # Check if this is running from a thread if application_instance.thread() != QThread.currentThread(): dispatcher = getattr(application_instance, "_dispatcher", None) if dispatcher: dispatcher.sig_notified.emit(notification) return cls.from_notification(notification).show()
def is_pydm_app(app=None): """ Check whether or not `QApplication.instance()` is a PyDMApplication. Parameters ---------- app : QApplication, Optional The app to inspect. If no application is provided the current running `QApplication` will be queried. Returns ------- bool True if it is a PyDMApplication, False otherwise. """ from ..application import PyDMApplication from qtpy.QtWidgets import QApplication if app is None: app = QApplication.instance() if isinstance(app, PyDMApplication): return True else: return False
def getMenuAction(self, menu_action, title='notitle', action_name='noaction', args=[], kwargs={}): # ToDo: Clean this up, it is very hacky env = { 'app': QApplication.instance(), 'win': self, 'action': actions, } if action_name is not None: try: mod, action = action_name.split('.', 1) method = getattr(env.get(mod, self), action) if menu_action.isCheckable(): menu_action.triggered.connect(method) else: menu_action.triggered.connect( lambda checked: method(*args, **kwargs)) return except: pass try: actions.bindWidget(menu_action, action_name) return except actions.InvalidAction: LOG.exception('Error binding menu action %s', action_name) msg = "The <b>{}</b> action specified for the " \ "<b>{}</b> menu item could not be triggered. " \ "Check the YAML config file for errors." \ .format(action_name or '', title.replace('&', '')) menu_action.triggered.connect( lambda: QMessageBox.critical(self, "Menu Action Error!", msg))
def __init__( self, title='napari', ndisplay=2, order=None, axis_labels=None, show=True, ): # instance() returns the singleton instance if it exists, or None app = QApplication.instance() # if None, raise a RuntimeError with the appropriate message if app is None: message = ( "napari requires a Qt event loop to run. To create one, " "try one of the following: \n" " - use the `napari.gui_qt()` context manager. See " "https://github.com/napari/napari/tree/master/examples for" " usage examples.\n" " - In IPython or a local Jupyter instance, use the " "`%gui qt` magic command.\n" " - Launch IPython with the option `--gui=qt`.\n" " - (recommended) in your IPython configuration file, add" " or uncomment the line `c.TerminalIPythonApp.gui = 'qt'`." " Then, restart IPython.") raise RuntimeError(message) logopath = join(dirname(__file__), 'resources', 'logo.png') app.setWindowIcon(QIcon(logopath)) super().__init__( title=title, ndisplay=ndisplay, order=order, axis_labels=axis_labels, ) qt_viewer = QtViewer(self) self.window = Window(qt_viewer, show=show) self.update_console = self.window.qt_viewer.console.push
def icon(self, *names, **kwargs): """Return a QIcon object corresponding to the provided icon name.""" cache_key = '{}{}'.format(names, kwargs) if names and 'fa.' in names[0]: warnings.warn( "The FontAwesome 4.7 ('fa' prefix) icon set will be " "removed in a future release in favor of FontAwesome 6. " "We recommend you to move to FontAwesome 5 ('fa5*' prefix) " "to prevent any issues in the future", DeprecationWarning) if cache_key not in self.icon_cache: options_list = kwargs.pop('options', [{}] * len(names)) general_options = kwargs if len(options_list) != len(names): error = '"options" must be a list of size {0}'.format( len(names)) raise Exception(error) if QApplication.instance() is not None: parsed_options = [] for i in range(len(options_list)): specific_options = options_list[i] parsed_options.append( self._parse_options(specific_options, general_options, names[i])) # Process high level API api_options = parsed_options self.icon_cache[cache_key] = self._icon_by_painter( self.painter, api_options) else: warnings.warn("You need to have a running " "QApplication to use QtAwesome!") return QIcon() return self.icon_cache[cache_key]
def register_app_launchservices( uniform_type_identifier="public.python-script", role='editor'): """ Register app to the Apple launch services so it can open Python files """ app = QApplication.instance() # If top frame is MAC_APP_NAME, set ourselves to open files at startup origin_filename = get_origin_filename() if MAC_APP_NAME in origin_filename: bundle_idx = origin_filename.find(MAC_APP_NAME) old_handler = als.get_bundle_identifier_for_path( origin_filename[:bundle_idx] + MAC_APP_NAME) else: # Else, just restore the previous handler old_handler = als.get_UTI_handler( uniform_type_identifier, role) app._original_handlers[(uniform_type_identifier, role)] = old_handler # Restore previous handle when quitting app.aboutToQuit.connect(restore_launchservices) if not app._never_shown: bundle_identifier = als.get_bundle_identifier() als.set_UTI_handler( uniform_type_identifier, role, bundle_identifier) return # Wait to be visible to set ourselves as the UTI handler def handle_applicationStateChanged(state): if state == Qt.ApplicationActive and app._never_shown: app._never_shown = False bundle_identifier = als.get_bundle_identifier() als.set_UTI_handler( uniform_type_identifier, role, bundle_identifier) app.applicationStateChanged.connect(handle_applicationStateChanged)
def __init__(self): QMainWindow.__init__(self) qapp = QApplication.instance() qapp.setAttribute(Qt.AA_UseHighDpiPixmaps) if hasattr(Qt, 'AA_EnableHighDpiScaling'): qapp.setAttribute(Qt.AA_EnableHighDpiScaling, True) self.setWindowTitle("Mantid Workbench") # -- instance attributes -- self.window_size = None self.window_position = None self.maximized_flag = None # widgets self.messagedisplay = None self.ipythonconsole = None self.workspacewidget = None self.editor = None self.algorithm_selector = None self.plot_selector = None self.widgets = [] # Widget layout map: required for use in Qt.connection self._layout_widget_info = None # Menus self.file_menu = None self.file_menu_actions = None self.editor_menu = None self.view_menu = None self.view_menu_actions = None # Allow splash screen text to be overridden in set_splash self.splash = SPLASH # Layout self.setDockOptions(self.DOCKOPTIONS)
def __init__(self, width=800, height=600, parent=None): # Start app self._app = QApplication.instance() if self._app is None: self._app = QApplication([]) super(ViewerQt, self).__init__(parent) # Window settings self.setWindowTitle('pyOCCT') _icon = os.path.dirname(__file__) + '/_resources/icon.png' _qicon = QIcon(_icon) self.setWindowIcon(_qicon) # Create the OCCT view frame = QFrame(self) layout = QVBoxLayout(frame) layout.setContentsMargins(0, 0, 0, 0) self._the_view = QOpenCascadeWidget() layout.addWidget(self._the_view) self.setCentralWidget(frame) self.show() self.resize(width, height) self.view.my_view.MustBeResized()
def execlaunch(self): """ Launch the mainwindow """ if not self._launching: self._launching = True app = QApplication.instance() from xicam.gui.windows.mainwindow import XicamMainWindow self.mainwindow = XicamMainWindow() self.timer.stop() # Show the QMainWindow self.mainwindow.show() self.mainwindow.raise_() self.mainwindow.activateWindow() app.setActiveWindow(self.mainwindow) # Stop splashing self.hide() self.movie.stop() self.finish(self.mainwindow)
def func_wrapper(*args, **kwargs): app = QApplication.instance() if app.current_workspace is None: return parent = app.current_workspace.current_plot_window.tool_bar action = QAction(parent) action.setText(name) if icon is not None: action.setIcon(icon) if location is not None: for level in location.split('/'): parent = self.get_action(parent, level) before_action = [ x for x in parent.actions() if x.isSeparator() ].pop() parent.insertAction(before_action, action) action.triggered.connect(lambda: func(*args, **kwargs))
def __init__(self, parent=None): QFrame.__init__(self, parent) PyDMPrimitiveWidget.__init__(self) self.app = QApplication.instance() self._filename = None self._macros = None self._embedded_widget = None self._disconnect_when_hidden = True self._is_connected = False self._only_load_when_shown = True self._needs_load = True self._load_error_timer = None self._load_error = None self.layout = QVBoxLayout(self) self.err_label = QLabel(self) self.err_label.setAlignment(Qt.AlignHCenter) self.layout.addWidget(self.err_label) self.layout.setContentsMargins(0, 0, 0, 0) self.err_label.hide() if not is_pydm_app(): self.setFrameShape(QFrame.Box) else: self.setFrameShape(QFrame.NoFrame)
def _main(args, exec=True): # import pydm # app = QApplication([]) # app = pydm.PyDMApplication() app = QApplication.instance() or QApplication([]) signal.signal(signal.SIGINT, signal.SIG_DFL) from xicam.gui.windows import splash from xicam.core import msg if getattr(args, 'verbose', False): QErrorMessage.qtHandler() # start splash in subprocess splash_proc = QProcess() # splash_proc.started.connect(lambda: print('started splash')) # splash_proc.finished.connect(lambda: print('finished splashing')) log_file = msg.file_handler.baseFilename initial_length = os.path.getsize(log_file) splash_proc.start(sys.executable, [splash.__file__, log_file, str(initial_length)]) from xicam.gui.windows.mainwindow import XicamMainWindow mainwindow = XicamMainWindow() while splash_proc.state() != QProcess.NotRunning: app.processEvents() # splash_proc.waitForFinished() mainwindow.show() mainwindow.activateWindow() # splash = splash.XicamSplashScreen(args=args) if exec: return app.exec_() else: return mainwindow
def __init__(self, parent=None): super(AlarmTreeEditorDisplay, self).__init__(parent=parent) self.app = QApplication.instance() # set up the ui self.setup_ui() # allow add and remove row self.add_button.clicked.connect(self.insertChild) self.remove_button.clicked.connect(self.removeItem) self.remove_button.setEnabled(True) # connect save changes self.button_box.accepted.connect(self.save_property_changes) # upon tree view selection, change the item view self.tree_view.selectionModel().selectionChanged.connect( self.handle_selection) self.tree_view.tree_model.dataChanged.connect(self.item_change) self.file_dialog = QFileDialog() self.open_config_action = QAction("Open", self) self.open_config_action.triggered.connect(self.open_file) self.toolbar.addAction(self.open_config_action) self.save_config_action = QAction("Save", self) self.save_config_action.triggered.connect(self.save_configuration) self.toolbar.addAction(self.save_config_action) # update configuration name self.tree_label.editingFinished.connect(self._update_config_name) # default open size self.resize(800, 600) self.config_tool = PhoebusConfigTool()
def __init__(self, qt_viewer: QtViewer, parent=None) -> None: super().__init__(parent) self.qt_viewer = qt_viewer self._quit_app = False self.setWindowIcon(QIcon(self._window_icon)) self.setAttribute(Qt.WA_DeleteOnClose) self.setUnifiedTitleAndToolBarOnMac(True) center = QWidget(self) center.setLayout(QHBoxLayout()) center.layout().addWidget(qt_viewer) center.layout().setContentsMargins(4, 0, 4, 0) self.setCentralWidget(center) self.setWindowTitle(qt_viewer.viewer.title) self._maximized_flag = False self._preferences_dialog = None self._preferences_dialog_size = QSize() self._status_bar = self.statusBar() # set SETTINGS plugin defaults. SETTINGS._defaults['plugins'].call_order = plugin_manager.call_order() # set the values in plugins to match the ones saved in SETTINGS if SETTINGS.plugins.call_order is not None: plugin_manager.set_call_order(SETTINGS.plugins.call_order) _QtMainWindow._instances.append(self) # Connect the notification dispacther to correctly propagate # notifications from threads. See: `napari._qt.qt_event_loop::get_app` application_instance = QApplication.instance() if application_instance: application_instance._dispatcher.sig_notified.connect( self.show_notification)
def eventFilter(self, watched: QObject, event: QEvent) -> bool: ''' Eventfilter Parameters ---------- watched : QObject Unused event : QEvent Returns ------- value : bool ''' #pylint: disable=unused-argument if event.type() == QEvent.MouseButtonRelease: logger.debug('MouseButtonRelease') if self.d.dragging_state == DragState.floating_widget: qapp = QApplication.instance() qapp.removeEventFilter(self) logger.debug('FloatingWidget.eventFilter QEvent.MouseButtonRelease') self.d.title_mouse_release_event() return False
def create_window(window): def _create(): browser = BrowserView(window) _main_window_created.set() if window.minimized: # showMinimized does not work on start without showNormal first # looks like a bug in QT browser.showNormal() browser.showMinimized() elif not window.hidden: browser.show() if window.uid == 'master': global _app _app = QApplication.instance() or QApplication([]) _create() _app.exec_() else: _main_window_created.wait() i = list(BrowserView.instances.values())[0] # arbitrary instance i.create_window_trigger.emit(_create)
def title_mouse_release_event(self): self.set_state(DragState.inactive) if not self.drop_container: return dock_manager = self.dock_manager dock_area_overlay = dock_manager.dock_area_overlay() container_overlay = dock_manager.container_overlay() if any(widget.drop_area_under_cursor() != DockWidgetArea.invalid for widget in (dock_area_overlay, container_overlay)): # Resize the floating widget to the size of the highlighted drop area # rectangle overlay = container_overlay if not overlay.drop_overlay_rect().isValid(): overlay = dock_area_overlay rect = overlay.drop_overlay_rect() if rect.isValid(): public = self.public frame_width = (public.frameSize().width() - public.rect().width()) // 2 title_bar_height = int(public.frameSize().height() - public.rect().height() - frame_width) top_left = overlay.mapToGlobal(rect.topLeft()) top_left.setY(top_left.y() + title_bar_height) geom = QRect(top_left, QSize(rect.width(), rect.height() - title_bar_height)) self.public.setGeometry(geom) qapp = QApplication.instance() qapp.processEvents() self.drop_container.drop_floating_widget(self.public, QCursor.pos()) container_overlay.hide_overlay() dock_area_overlay.hide_overlay()
def closeEvent(self, event): """ Handling saving state before application when application is being closed. """ settings = QtCore.QSettings() settings.setValue("main_WindowGeometry", self.saveGeometry()) settings.setValue("mainWindowState", self.saveState()) self.settings.save(settings) #screen_shape = QtGui.QDesktopWidget().screenGeometry() main_window = self.window() width = main_window.frameGeometry().width() height = main_window.frameGeometry().height() settings.setValue('screen_shape', (width, height)) qpos = self.pos() pos = qpos.x(), qpos.y() settings.setValue('pos', pos) q_app = QApplication.instance() if q_app is None: sys.exit() q_app.quit()
def gui_qt(*, startup_logo=False): """Start a Qt event loop in which to run the application. Parameters ---------- startup_logo : bool Show a splash screen with the napari logo during startup. Notes ----- This context manager is not needed if running napari within an interactive IPython session. In this case, use the ``%gui qt`` magic command, or start IPython with the Qt GUI event loop enabled by default by using ``ipython --gui=qt``. """ app = QApplication.instance() or QApplication(sys.argv) if startup_logo: logopath = join(dirname(__file__), '..', 'resources', 'logo.png') splash_widget = QSplashScreen(QPixmap(logopath).scaled(400, 400)) splash_widget.show() yield if startup_logo: splash_widget.close() app.exec_()