예제 #1
0
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 save_to_file(self):
        """Save table values to file."""
        df = _utils.table_to_data_frame(self.tbl_table)
        if df is None:
            msg = _QCoreApplication.translate('', 'Empty table.')
            title = _QCoreApplication.translate('', 'Failure')
            _QMessageBox.critical(self, title, msg, _QMessageBox.Ok)
            return

        filename = _QFileDialog.getSaveFileName(
            self,
            caption='Save measurements file.',
            directory=self.directory,
            filter="Text files (*.txt *.dat)")

        if isinstance(filename, tuple):
            filename = filename[0]

        if len(filename) == 0:
            return

        try:
            if (not filename.endswith('.txt')
                    and not filename.endswith('.dat')):
                filename = filename + '.txt'
            df.to_csv(filename, sep='\t')

        except Exception:
            _traceback.print_exc(file=_sys.stdout)
            msg = _QCoreApplication.translate('',
                                              'Failed to save data to file.')
            title = _QCoreApplication.translate('', 'Failure')
            _QMessageBox.critical(self, title, msg, _QMessageBox.Ok)
예제 #3
0
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)

        if is_required_version(required_version='5.10.0', version=qVersion()):
            app.setAttribute(Qt.AA_DisableWindowContextHelpButton)

    return app
예제 #4
0
 def setUpClass(cls):
     QCoreApplication.setApplicationName("test1")
     QCoreApplication.setOrganizationName("org1")
     QSettings.setDefaultFormat(QSettings.IniFormat)
     cls.settings_dir = tempfile.TemporaryDirectory()
     QSettings.setPath(QSettings.IniFormat, QSettings.UserScope,
                       cls.settings_dir.name)
예제 #5
0
def main(argv: Sequence[str] = None) -> int:
    argv = argv if argv is not None else sys.argv

    command_line_args = parse_commandline(argv)
    exit_code_str = command_line_args.exit_code
    exit_code = int(exit_code_str)
    if mantid.config['usagereports.enabled'] != '1':
        return exit_code

    # On Windows/macOS the plugin locations need to be known before starting
    # QApplication
    if command_line_args.qtdir is not None:
        QCoreApplication.addLibraryPath(command_line_args.qtdir)

    # Qt resources must be imported before QApplication starts
    importlib.import_module(f'mantidqt.dialogs.errorreports.resources_qt{QT_VERSION[0]}')

    if sys.platform == 'darwin':
        qtutils.force_layer_backing_BigSur()

    from qtpy.QtWidgets import QApplication
    app = QApplication(argv)
    # The strings APPNAME, ORG_DOMAIN, ORGANIZATION are duplicated from workbench.config
    app.setOrganizationName(command_line_args.org_name)
    app.setOrganizationDomain(command_line_args.org_domain)
    app.setApplicationName(command_line_args.application)
    QSettings.setDefaultFormat(QSettings.IniFormat)
    form = CrashReportPage(show_continue_terminate=False)
    presenter = ErrorReporterPresenter(form, exit_code_str, command_line_args.application)
    presenter.show_view()
    app.exec_()

    return exit_code
예제 #6
0
 def check_driver_connection(self):
     if not _driver.connected:
         msg = _QCoreApplication.translate('', 'Driver not connected.')
         title = _QCoreApplication.translate('', 'Failure')
         _QMessageBox.critical(self, title, msg, _QMessageBox.Ok)
         return False
     return True       
예제 #7
0
    def on_conn_fail(self) -> None:
        """
        If the API failed to connect, the app will be closed.
        """

        print("Timed out waiting for the connection")
        QCoreApplication.exit(1)
예제 #8
0
    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)
예제 #9
0
    def __init__(self, chb_names, parent=None):
        """Set up the ui and create connections."""
        super().__init__(parent)
        self.setWindowTitle(_QCoreApplication.translate('', "Select Tabs"))
        self.resize(250, 400)
        self.setFont(_font)

        main_layout = _QVBoxLayout()
        vertical_layout = _QVBoxLayout()
        group_box = _QGroupBox(
            _QCoreApplication.translate('', "Select Tabs to Show"))
        group_box.setLayout(vertical_layout)
        group_box.setFont(_font_bold)
        main_layout.addWidget(group_box)
        self.setLayout(main_layout)

        self.chb_names = chb_names
        for name in self.chb_names:
            name_split = name.split('_')
            label = ' '.join([s.capitalize() for s in name_split])
            chb = _QCheckBox(_QCoreApplication.translate('', label))
            setattr(self, 'chb_' + name, chb)
            vertical_layout.addWidget(chb)
            chb.setFont(_font)

        self.pbt_apply = _QPushButton(
            _QCoreApplication.translate('', "Apply Changes"))
        self.pbt_apply.setMinimumSize(_QSize(0, 40))
        self.pbt_apply.setFont(_font_bold)
        vertical_layout.addWidget(self.pbt_apply)

        self.pbt_apply.clicked.connect(self.emit_tab_selection_signal)
    def edit_comment(self):
        try:
            table_name = self.twg_database.get_current_table_name()
            if table_name is None:
                return

            idn = self.twg_database.get_table_selected_id(table_name)
            if idn is None:
                return

            object_class = self._table_object_dict[table_name]
            obj = object_class(
                database_name=self.database_name,
                mongo=self.mongo, server=self.server)
            obj.db_read(idn)
            prev_comments = obj.comments

            title = _QCoreApplication.translate('', 'Edit Comments')
            label = _QCoreApplication.translate('', 'Comments:')
            new_comments, resp = _QInputDialog.getText(
                self, title, label, text=prev_comments)

            if not resp:
                return

            obj.comments = new_comments
            obj.db_update(idn)

            self.update_database_tables()

        except Exception:
            _traceback.print_exc(file=_sys.stdout)
예제 #11
0
    def test_first_time_focus_uses_correct_default_save_directory(self, mock_load_cal,
                                                                  mock_enggutils_focus_run, mock_get_output_path):

        default_save_location = path.join(path.expanduser("~"), "Engineering_Mantid")
        QCoreApplication.setApplicationName("Engineering_Diffraction_test_calib_model")
        presenter = settings_presenter.SettingsPresenter(mock.create_autospec(settings_model.SettingsModel),
                                                         mock.create_autospec(settings_view.SettingsView))
        presenter.settings = {  # "save_location" is not defined
                              "full_calibration": "cal",
                              "logs": "some,logs",
                              "primary_log": "some",
                              "sort_ascending": True,
                              "default_peak": "BackToBackExponential"
                              }
        presenter._validate_settings()  # save_location now set to the default value at runtime
        self.assertEqual(presenter.settings['save_location'], default_save_location)

        # this is the runtime return from output_settings.get_output_path()
        # if called at define time in a default parameter value then this value is not used
        mock_get_output_path.return_value = default_save_location

        mock_load_cal.return_value = "full_calibration"
        self.calibration.group = GROUP.BOTH

        self.model.focus_run(["305761"], "fake/van/path", plot_output=False, rb_num=None,
                             calibration=self.calibration)  # save_dir not given

        mock_enggutils_focus_run.assert_called_once_with(["305761"], "fake/van/path", False, None, self.calibration,
                                                         default_save_location, "full_calibration")
        # sample_paths, vanadium_path, plot_output, rb_num, calibration, save_dir, full_calib
        QCoreApplication.setApplicationName(APPNAME)  # reset to 'mantidworkbench' in case required by other tests
예제 #12
0
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:
        # attributes that must be set before creating QApplication
        QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts)

        argv = sys.argv[:]
        argv[0] = APPNAME  # replace application name
        # Workaround a segfault importing readline with PyQt5
        # This is because PyQt5 messes up pystate (internal) modules_by_index
        # so PyState_FindModule will return null instead of the module address.
        # Readline (so far) is the only module that falls over during init as it blindly uses FindModules result
        # The workaround mentioned in https://groups.google.com/forum/#!topic/leo-editor/ghiIN7irzY0
        if sys.platform == "linux" or sys.platform == "linux2" or sys.platform == "darwin":
            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)

        app.setAttribute(Qt.AA_UseHighDpiPixmaps)
        if hasattr(Qt, 'AA_DisableWindowContextHelpButton'):
            app.setAttribute(Qt.AA_DisableWindowContextHelpButton)

    return app
예제 #13
0
    def enable_encoder_reading(self):
        """Enable encoder reading."""
        try:
            encoder_res = self.advanced_options.integrator_encoder_resolution

            if self.ui.chb_encoder.isChecked():
                if not self.check_integrator_connection():
                    self.stop_encoder_update = True
                    self.ui.lcd_encoder.setEnabled(False)
                    self.ui.chb_encoder.setChecked(False)
                    return

                if _integrator.configure_encoder_reading(encoder_res):
                    self.stop_encoder_update = False
                    self.timer.start(self._update_encoder_interval*1000)
                    self.ui.lcd_encoder.setEnabled(True)
                else:
                    msg = _QCoreApplication.translate(
                        '', 'Failed to configure encoder reading.')
                    title = _QCoreApplication.translate('', 'Failure')
                    _QMessageBox.critical(
                        self, title, msg, _QMessageBox.Ok)
                    self.stop_encoder_update = True
                    self.ui.lcd_encoder.setEnabled(False)
                    self.ui.chb_encoder.setChecked(False)
            else:
                self.ui.lcd_encoder.setEnabled(False)
                self.stop_encoder_update = True
                self.timer.stop()

        except Exception:
            _traceback.print_exc(file=_sys.stdout)
            self.ui.lcd_encoder.setEnabled(False)
            self.stop_encoder_update = True
            self.timer.stop()
예제 #14
0
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
예제 #15
0
 def retranslateUi(self, Form):
     Form.setWindowTitle(QCoreApplication.translate("Form", u"About", None))
     self.textBrowser.setHtml(
         QCoreApplication.translate(
             "Form",
             u"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
             "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
             "p, li { white-space: pre-wrap; }\n"
             "</style></head><body style=\" font-family:'Ubuntu'; font-size:11pt; font-weight:400; font-style:normal;\">\n"
             "<p align=\"center\" style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:'Sans'; font-size:16pt;\">Brightness Controller v2.3.4</span></p>\n"
             "<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:'Sans'; font-size:9pt; font-weight:600;\">Author: </span><span style=\" font-family:'Sans'; font-size:9pt;\">Amit Seal Ami, </span></p>\n"
             "<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:'Sans'; font-s"
             "ize:9pt;\">Bangladesh,</span></p>\n"
             "<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:'Sans'; font-size:9pt;\">[email protected]</span></p>\n"
             "<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:'Sans'; font-size:9pt; font-weight:600;\">Contributors</span></p>\n"
             "<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:'Sans'; font-size:9pt;\">Significant contributors are listed alphabetically.</span></p>\n"
             "<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:'Sans'; font-size:9pt;\">- Archisman Panigrahi</span></p>\n"
             "<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:"
             "0; text-indent:0px;\"><span style=\" font-family:'Sans'; font-size:9pt;\">- Jahan Addison</span></p>\n"
             "<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:'Sans'; font-size:9pt;\">- Zlatan Vasovi\u0107</span></p>\n"
             "<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:'Sans'; font-size:9pt; font-weight:600;\">Special thanks to:</span></p>\n"
             "<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:'Sans'; font-size:9pt;\">- 2to3 tool for porting to Python 3</span></p>\n"
             "<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:'Sans'; font-size:9pt;\">- Numerous Stack Overflow users</span></p>\n"
             "<p style=\" margin-top:12px; margi"
             "n-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:'Sans'; font-size:9pt;\">For full list of authors and details, please check </span><a href=\"https://github.com/lordamit/Brightness\"><span style=\" font-family:'Noto Sans'; font-size:10pt; text-decoration: underline; color:#3484e2;\">https://github.com/lordamit/Brightness</span></a></p></body></html>",
             None))
예제 #16
0
    def _event(self, E):
        _log.debug('event1 %s', E)
        # called on PVA worker thread
        if isinstance(E, Cancelled):
            return

        QCoreApplication.postEvent(self, CBEvent(E))
예제 #17
0
 def retranslateUi(self, Form):
     Form.setWindowTitle(QCoreApplication.translate("Form", u"Help", None))
     self.textBrowser.setHtml(
         QCoreApplication.translate(
             "Form",
             u"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
             "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
             "p, li { white-space: pre-wrap; }\n"
             "</style></head><body style=\" font-family:'Padauk'; font-size:12pt; font-weight:400; font-style:normal;\">\n"
             "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:'Sans'; font-size:9pt;\">Using Brightness Controller is easy. Most of the parts are self explanatory. Only the advanced parts are discussed here.</span></p>\n"
             "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans'; font-size:9pt;\"><br /></p>\n"
             "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:'Sans'; font-size:9pt; font-weight:600"
             ";\">Reverse Control</span></p>\n"
             "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:'Sans'; font-size:9pt;\">Check it only when your primary display is being detected as secondary display. This reverses the control of your monitor. Only available when multiple displays are connected.</span></p>\n"
             "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans'; font-size:9pt;\"><br /></p>\n"
             "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:'Sans'; font-size:9pt; font-weight:600;\">Color Temperature</span></p>\n"
             "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:'Sans'; font-size:9pt;\">Assigns color temperature, also kn"
             "own as color tones to display.</span></p>\n"
             "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans'; font-size:9pt;\"><br /></p>\n"
             "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:'Sans'; font-size:9pt; font-weight:600;\">Save Settings</span></p>\n"
             "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:'Sans'; font-size:9pt;\">Saves your current color configurations.</span></p>\n"
             "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans'; font-size:9pt;\"><br /></p>\n"
             "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" fon"
             "t-family:'Sans'; font-size:9pt; font-weight:600;\">Save Settings As Default</span></p>\n"
             "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:'Sans'; font-size:9pt;\">Saves your current color configurations as the default that will load on each start of the application</span></p>\n"
             "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans'; font-size:9pt;\"><br /></p>\n"
             "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:'Sans'; font-size:9pt; font-weight:600;\">Load Settings</span></p>\n"
             "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:'Sans'; font-size:9pt;\">Loads your saved color configuration.</span></p></body>"
             "</html>", None))
예제 #18
0
    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()
예제 #19
0
    def __init__(self, log=None):
        super().__init__()
        if log:
            self.log = log.getChild('Conf')
            self.log.setLevel(30)
        else:
            self.log = logging.getLogger()
            self.log.setLevel(99)
        self.log.debug('Initializing')
        self.qsettings = QSettings()
        self.qsettings.setIniCodec('UTF-8')

        self.options = None
        self.option_spec = self.load_option_spec()
        self.options = self.load_options()
        self.full_name = "{} {}".format(QCoreApplication.applicationName(),
                                        QCoreApplication.applicationVersion())

        # options that need fast access are also defined as attributes, which
        # are updated by calling update_attributes()
        # (on paper it's 4 times faster, but I don't think it matters in my case)
        self.logger_table_font = None
        self.logger_table_font_size = None
        self.logger_row_height = None
        self.benchmark_interval = None

        self.update_attributes()
예제 #20
0
 def stop_func(self) -> bool:
     """Return dialog status."""
     try:
         QCoreApplication.processEvents()
         return self.wasCanceled()
     except ValueError:
         return False
예제 #21
0
def translation_context(name, category=u'core'):

	"""
	desc:
		A factory that generates a translation method with a fixed context.

	arguments:
		name:
			desc:	The name to use for the context.
			type:	str

	keywords:
		name:
			desc:	The category to use for the context.
			type:	str

	returns:
		desc:	A translation function.
		type:	FunctionType
	"""

	_context = u'%s_%s' % (category, name)
	if os.environ[u'QT_API'] == u'pyqt5':
		# PyQt5 3 doesn't require an encoding
		return lambda s, context=None: QCoreApplication.translate(_context,
			s)
	return lambda s, context=None: QCoreApplication.translate(_context, s,
		encoding=QCoreApplication.UnicodeUTF8)
예제 #22
0
def main() -> int:
    command_line_args = parse_commandline()
    exit_code_str = command_line_args.exit_code
    exit_code = int(exit_code_str)
    if mantid.config['usagereports.enabled'] != '1':
        return exit_code

    # On Windows/macOS the plugin locations need to be known before starting
    # QApplication
    if command_line_args.qtdir is not None:
        QCoreApplication.addLibraryPath(command_line_args.qtdir)

    # Qt resources must be imported before QApplication starts
    importlib.import_module(
        f'mantidqt.dialogs.errorreports.resources_qt{QT_VERSION[0]}')

    from qtpy.QtWidgets import QApplication
    app = QApplication(sys.argv)
    form = CrashReportPage(show_continue_terminate=False)
    presenter = ErrorReporterPresenter(form, exit_code_str,
                                       command_line_args.application)
    presenter.show_view()
    app.exec_()

    return exit_code
예제 #23
0
파일: window.py 프로젝트: keshabb/vidify
    def wait_for_connection(self) -> None:
        """
        Function called by start() to check every second if the connection
        has been established.
        """

        # Saving the starting timestamp for the audiosync feature
        start_time = time.time()

        # Changing the loading message for the connection one if the first
        # connection attempt was unsuccessful.
        if self.conn_counter == 1:
            self.layout.removeWidget(self.loading_label)
            self.loading_label.hide()
            self.conn_label.show()

        # The APIs should raise `ConnectionNotReady` if the first attempt
        # to get metadata from Spotify was unsuccessful.
        logging.info("Connection attempt %d", self.conn_counter + 1)
        try:
            self.conn_fn()
        except ConnectionNotReady:
            pass
        else:
            logging.info("Succesfully connected to the API")

            # Stopping the timer and changing the label to the loading one.
            self.conn_timer.stop()
            self.layout.removeWidget(self.conn_label)
            del self.conn_timer
            self.layout.removeWidget(self.conn_label)
            self.conn_label.hide()
            del self.conn_label
            self.layout.removeWidget(self.loading_label)
            del self.loading_label

            # Loading the player and more
            self.setStyleSheet(f"background-color:{Colors.black};")
            self.layout.addWidget(self.player)
            self.play_video(self.api.artist, self.api.title, start_time)

            # Connecting to the signals generated by the API
            self.api.new_song_signal.connect(self.play_video)
            self.api.position_signal.connect(self.change_video_position)
            self.api.status_signal.connect(self.change_video_status)

            # Starting the event loop if it was initially passed as
            # a parameter.
            if self.event_loop_interval is not None:
                self.start_event_loop(self.api.event_loop,
                                      self.event_loop_interval)

        self.conn_counter += 1

        # If the maximum amount of attempts is reached, the app is closed.
        if self.conn_counter >= self.conn_attempts:
            print("Timed out waiting for the connection")
            self.conn_timer.stop()
            QCoreApplication.exit(1)
예제 #24
0
    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)
예제 #25
0
 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)
예제 #26
0
 def refresh_window_title(self):
     s = "%s %s" % (QCoreApplication.applicationName(),
                    QCoreApplication.applicationVersion())
     if self.filename is not None:
         s += " - " + self.filename
     if self.dirty:
         s += "*"
     self.setWindowTitle(s)
예제 #27
0
 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)
예제 #28
0
    def check_advanced_options(self):
        if not self.advanced_options.valid_data():
            msg = _QCoreApplication.translate(
                '', 'Invalid advanced options.')
            title = _QCoreApplication.translate('', 'Failure')
            _QMessageBox.critical(self, title, msg, _QMessageBox.Ok)
            return False

        return True
예제 #29
0
def use_software_rendering():
    """
    Instruct Qt to use software rendering.

    This is necessary for some buggy graphics drivers (e.g. nvidia).
    This function should be run before the QApplication is created.
    """
    QCoreApplication.setAttribute(Qt.AA_UseSoftwareOpenGL)
    QQuickWindow.setSceneGraphBackend(QSGRendererInterface.Software)
예제 #30
0
    def homing(self):
        self.stop = False

        try:
            if not self.check_driver_connection():
                return

            if not self.check_integrator_connection():
                return

            wait = 0.1

            driver_address = self.advanced_options.motor_driver_address
            resolution = self.advanced_options.motor_resolution
            rotation_direction = self.advanced_options.motor_rotation_direction
            velocity = self.advanced_options.motor_velocity
            acceleration = self.advanced_options.motor_acceleration

            mode = 0
            steps = int(int(resolution))

            if not _driver.config_motor(
                    driver_address,
                    mode,
                    rotation_direction,
                    resolution,
                    velocity,
                    acceleration,
                    steps):
                msg = _QCoreApplication.translate(
                    '', 'Failed to send configuration to motor.')
                title = _QCoreApplication.translate('', 'Failure')
                _QMessageBox.critical(
                    self, title, msg, _QMessageBox.Ok)
                return

            encoder_dir = self.advanced_options.integrator_encoder_direction

            _integrator.configure_homing(encoder_dir)
            _time.sleep(wait)

            if self.stop:
                return

            _driver.move_motor(driver_address)
            _time.sleep(wait)
            while not _driver.ready(driver_address) and not self.stop:
                _time.sleep(wait)
                _QApplication.processEvents()

        except Exception:
            _traceback.print_exc(file=_sys.stdout)
            msg = _QCoreApplication.translate('', 'Homing failed.')
            title = _QCoreApplication.translate('', 'Failure')
            _QMessageBox.critical(self, title, msg, _QMessageBox.Ok)
            return
예제 #31
0
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)
        app = QApplication(['Mantid Workbench'])
    return app
예제 #32
0
    def _run_async_code(self, code, filename=None, line_no=0):
        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, line_no, filename)
        task.join()
        QCoreApplication.sendPostedEvents()

        return executor, recv
예제 #33
0
 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()
예제 #34
0
 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()
예제 #35
0
 def show_info(self):
     QMessageBox.about(
         self, QApplication.applicationName(),
         "%s %s\n"
         "Copyright (c) by %s" %
         (
             QCoreApplication.applicationName(),
             QCoreApplication.applicationVersion(),
             QCoreApplication.organizationName(),
         )
     )
예제 #36
0
    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
예제 #37
0
def main():
    from qtpy.QtCore import Qt, QCoreApplication
    from qtpy.QtWidgets import QApplication
    from qtpy import API

    import hyperspyui.info
    from hyperspyui.settings import Settings

    QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts)
    # Need to set early to make QSettings accessible
    QCoreApplication.setApplicationName("HyperSpyUI")
    QCoreApplication.setOrganizationName("Hyperspy")
    QCoreApplication.setApplicationVersion(hyperspyui.info.__version__)

    # First, clear all default settings!
    # TODO: This will cause a concurrency issue with multiple launch
    Settings.clear_defaults()
    # Setup default for single/multi-instance
    settings = Settings(group="General")
    settings.set_default('allow_multiple_instances', False)
    if settings['allow_multiple_instances', bool]:
        # Using multiple instances, get a new application
        app = QApplication(sys.argv)
    else:
        # Make sure we only have a single instance
        from hyperspyui.singleapplication import get_app
        app = get_app('hyperspyui')

    splash = get_splash()

    log_file = _get_logfile()
    if log_file:
        sys.stdout = sys.stderr = log_file
    else:
        @contextmanager
        def dummy_context_manager(*args, **kwargs):
            yield
        log_file = dummy_context_manager()

    with log_file:
        # Need to have import here, since QApplication needs to be called first
        from hyperspyui.mainwindow import MainWindow

        form = MainWindow(splash=splash)
        if not settings['allow_multiple_instances', bool]:
            if "pyqt" in API:
                app.messageAvailable.connect(form.handleSecondInstance)
            elif API == 'pyside':
                app.messageReceived.connect(form.handleSecondInstance)
        form.showMaximized()

        form.splash.hide()
        form.load_complete.emit()
        # Ensure logging is OK
        import hyperspy.api as hs
        hs.set_log_level(LOGLEVEL)

        app.exec_()
예제 #38
0
    def closeEvent(self, event):
        if self.dirty:
            res = QMessageBox.question(
                self,
                QCoreApplication.applicationName(),
                self.tr("Save changes to file '%s'?" %
                        self.filename
                        if self.filename is not None else "unknown"),
                QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel
            )
            if res == QMessageBox.Cancel:
                event.ignore()
                return
            elif res == QMessageBox.Yes:
                self.save_file()

        self.save_settings()

        try:
            self.worker.quit()
        except AttributeError:
            pass

        try:
            self.serial.close()
        except (SerialException, AttributeError):
            pass
예제 #39
0
def test():
    """测试函数"""
    import sys
    from datetime import datetime
    from qtpy.QtCore import QCoreApplication
    
    def simpletest(event):
        print(u'处理每秒触发的计时器事件:{}'.format(str(datetime.now())))
    
    app = QCoreApplication(sys.argv)
    
    ee = EventEngine2()
    #ee.register(EVENT_TIMER, simpletest)
    ee.registerGeneralHandler(simpletest)
    ee.start()
    
    app.exec_()
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')
예제 #41
0
    def connect(self):
        # Load port setting
        port = self.settings.get(PORT_SETTING)
        baudrate = self.settings.get(BAUDRATE_SETTING)

        # If no port has been selected before show serial settings dialog
        if port is None:
            if self.show_serialdlg() == QDialog.Rejected:
                return
            port = self.settings.get(PORT_SETTING)
            baudrate = self.settings.get(BAUDRATE_SETTING)

        # Serial connection
        try:
            self.serial.port = port
            self.serial.baudrate = baudrate
            self.serial.open()
        except ValueError:
            QMessageBox.critical(
                self, QCoreApplication.applicationName(),
                self.tr("Serial parameters e.g. baudrate, databits are out "
                        "of range.")
            )
        except SerialException:
            QMessageBox.critical(
                self, QCoreApplication.applicationName(),
                self.tr("The device '%s' can not be found or can not be "
                        "configured." % port)
            )
        else:
            self.worker = SerialWorker(self.serial, self)
            self.worker.data_received.connect(self.receive_serialdata)
            self.worker.start()

            self.connectAction.setText(self.tr("Disconnect"))
            self.connectAction.setIcon(QIcon(pixmap("network-disconnect-3.png")))
            self.serialdlgAction.setEnabled(False)
            self.connectionstateLabel.setText(
                self.tr("Connected to %s") % port)
            self._connected = True
            self.objectexplorer.refresh()
예제 #42
0
파일: mapper.py 프로젝트: a-stark/qudi
    def revert(self):
        """
        Takes the data stored in the models and displays them in the widgets.
        """
        # make sure it is called from main thread
        if (not QThread.currentThread() == QCoreApplication.instance(
        ).thread()):
            QTimer.singleShot(0, self.revert)
            return

        for key in self._mappings:
            self._on_model_notification(key)
예제 #43
0
파일: shell.py 프로젝트: ShenggaoZhu/spyder
    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
예제 #44
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)
예제 #45
0
    def export_csv(self):
        filename, _ = QFileDialog.getSaveFileName(
            self, QCoreApplication.applicationName(),
            filter="CSV files(*.csv);;All files (*.*)"
        )

        if filename == "":
            return

        # get current dataframe and export to csv
        df = self.recordWidget.dataframe
        decimal = self.settings.get(DECIMAL_SETTING)
        df = df.applymap(lambda x: str(x).replace(".", decimal))
        df.to_csv(
            filename, index_label="time",
            sep=self.settings.get(SEPARATOR_SETTING)
        )
예제 #46
0
파일: mapper.py 프로젝트: a-stark/qudi
    def submit(self):
        """
        Submits the current values stored in the widgets to the models.
        """
        # make sure it is called from main thread
        if (not QThread.currentThread() == QCoreApplication.instance(
        ).thread()):
            QTimer.singleShot(0, self.submit)
            return

        submit_policy = self._submit_policy
        self.submit_policy = SUBMIT_POLICY_AUTO
        try:
            for key in self._mappings:
                self._on_widget_property_notification(key)
        finally:
            self.submit_policy = submit_policy
예제 #47
0
    def __init__(self, text_edit, hide_timer_on=False):
        """ Create a call tip manager that is attached to the specified Qt
            text edit widget.
        """
        assert isinstance(text_edit, (QTextEdit, QPlainTextEdit))
        super(CallTipWidget, self).__init__(None, Qt.ToolTip)
        self.app = QCoreApplication.instance()

        self.hide_timer_on = hide_timer_on
        self._hide_timer = QBasicTimer()
        self._text_edit = text_edit

        self.setFont(text_edit.document().defaultFont())
        self.setForegroundRole(QPalette.ToolTipText)
        self.setBackgroundRole(QPalette.ToolTipBase)
        self.setPalette(QToolTip.palette())

        self.setAlignment(Qt.AlignLeft)
        self.setIndent(1)
        self.setFrameStyle(QFrame.NoFrame)
        self.setMargin(1 + self.style().pixelMetric(QStyle.PM_ToolTipLabelFrameWidth, None, self))
예제 #48
0
파일: calltip.py 프로젝트: impact27/spyder
    def __init__(self, parent=None, as_tooltip=False):
        """
        Shows tooltips that can be styled with the different themes.
        """
        super(ToolTipWidget, self).__init__(parent, Qt.ToolTip)

        # Variables
        self.app = QCoreApplication.instance()
        self.as_tooltip = as_tooltip
        self.tip = None

        # Setup
        self.setForegroundRole(QPalette.ToolTipText)
        self.setBackgroundRole(QPalette.ToolTipBase)
        self.setPalette(QToolTip.palette())
        self.setAlignment(Qt.AlignLeft)
        self.setIndent(1)
        self.setFrameStyle(QFrame.NoFrame)
        style = self.style()
        delta_margin = style.pixelMetric(QStyle.PM_ToolTipLabelFrameWidth,
                                         None, self)
        self.setMargin(1 + delta_margin)
예제 #49
0
 def __init__(self, protocol, obj, widgets=[], refresh=1.0):
     """
     :param protocol: custom local protocol
                      only valid for input widgets and their children
     :type protocol:  str
     :param obj: object to use for this plugin
     :type obj:  object
     :param widgets: widgets to connect to obj
     :type widgets:  list of QWidget
     :param refresh: default seconds to wait before checking new values
                     refresh=0 means no auto-refresh by default
     :type refresh:  float or int
     """
     super(LocalPlugin, self).__init__()
     app = QCoreApplication.instance()
     standard_protocol = app.plugins.keys()
     if protocol in standard_protocol:
         err = "Protocol {} invalid, same as a standard protocol"
         raise Exception(err.format(protocol))
     self.base_protocol = protocol
     self.protocol = protocol + "://"
     self.connection_class = connection_class_factory(obj, refresh)
     self.add_widgets(widgets)
예제 #50
0
    from ErrorReporter import resources_qt5  # noqa
elif qtpy.PYQT4:
    from ErrorReporter import resources_qt4  # noqa
else:
    raise RuntimeError("Unknown QT version: {}".format(qtpy.QT_VERSION))

from qtpy import QtWidgets  # noqa

from ErrorReporter.error_report_presenter import ErrorReporterPresenter  # noqa
from ErrorReporter.errorreport import CrashReportPage  # noqa

# Set path to look for package qt libraries
if command_line_args.qtdir is not None:
    from qtpy.QtCore import QCoreApplication

    QCoreApplication.addLibraryPath(command_line_args.qtdir)


def main():
    if mantid.config['usagereports.enabled'] != '1':
        return int(command_line_args.exit_code)
    app = QtWidgets.QApplication(sys.argv)
    form = CrashReportPage(show_continue_terminate=False)
    presenter = ErrorReporterPresenter(form, command_line_args.exit_code, command_line_args.application)
    presenter.show_view()
    app.exec_()
    return int(command_line_args.exit_code)


if __name__ == '__main__':  # if we're running file directly and not importing it
    sys.exit(main())  # run the main function
예제 #51
0
def critical(parent, msg):
    QMessageBox.critical(parent, QCoreApplication.applicationName(), msg)
예제 #52
0
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()
예제 #53
0
            self.plotWidget.ymax = self.ymax
            self.plotWidget.draw()

    @property
    def xmin(self):
        return self.xminSpinBox.value()

    @property
    def xmax(self):
        return self.xmaxSpinBox.value()

    @property
    def ymin(self):
        return self.yminSpinBox.value()

    @property
    def ymax(self):
        return self.ymaxSpinBox.value()

    @property
    def autoscale(self):
        return self.autoscaleButtonGroup.checkedId()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    QCoreApplication.setApplicationName("USTempCtrl")
    QCoreApplication.setOrganizationName("KUZ")
    w = PlotSettingsWidget()
    w.show()
    app.exec_()
 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'])
예제 #55
0
	%--include: example.py--%
	~~~

license: |
	`QProgEdit` is released under the terms of the
	[General Public License v3](http://www.gnu.org/licenses/gpl-3.0.txt).
---
"""

version = __version__ = u'4.0.7'

from QProgEdit.py3compat import *

# A simple wrapper around the translate function
from qtpy.QtCore import QCoreApplication
_ = lambda s: QCoreApplication.translate(u'qprogedit', s)

import QProgEdit._qeditorconst as QEditorConst
import QProgEdit._qcolorscheme as QColorScheme
from QProgEdit._quiloader import QUiLoader
from QProgEdit._qsymboltreewidgetitem import QSymbolTreeWidgetItem
from QProgEdit._qeditorcfg import QEditorCfg
from QProgEdit._qeditorshortcut import QEditorShortcut
from QProgEdit._qlexer import QLexer
from QProgEdit._qlangmenu import QLangMenu
from QProgEdit._qeditor import QEditor
from QProgEdit._qeditorprefs import QEditorPrefs
from QProgEdit._qeditorfind import QEditorFind
from QProgEdit._qeditorstatus import QEditorStatus
from QProgEdit._qprogedit import QProgEdit
from QProgEdit._qtabcornerwidget import QTabCornerWidget