示例#1
0
    def _on_export_data(self):
        """
        Handler function that is called when the Export Data button is pressed
        """
        all_filters = ";;".join(['*.ecsv'])
        path, fmt = compat.getsavefilename(filters=all_filters)

        if path and fmt:
            try:
                plot_data_item = self.current_item
                self.export_data_item(plot_data_item, path, fmt)

                message_box = QMessageBox()
                message_box.setText("Data exported successfully.")
                message_box.setIcon(QMessageBox.Information)
                message_box.setInformativeText(
                    "Data set '{}' has been exported to '{}'".format(
                        plot_data_item.data_item.name, path))

                message_box.exec()
            except Exception as e:
                logging.error(e)

                message_box = QMessageBox()
                message_box.setText("Error exporting data set.")
                message_box.setIcon(QMessageBox.Critical)
                message_box.setInformativeText("{}\n{}".format(
                    sys.exc_info()[0],
                    sys.exc_info()[1].__repr__()[:100]))

                message_box.exec()
示例#2
0
    def _select_spectra_to_load(self, specs_by_name):

        selection_dialog = SpectrumSelection(self)
        selection_dialog.populate(specs_by_name.keys())
        selection_dialog.exec_()

        names_to_keep = selection_dialog.get_selected()

        if not names_to_keep:
            logging.warning('No spectra selected')

            message_box = QMessageBox()
            message_box.setText("No spectra were selected.")
            message_box.setIcon(QMessageBox.Warning)
            message_box.setInformativeText('No data has been loaded.')
            message_box.exec()

            return {}

        to_load = OrderedDict()
        for name, spectrum in specs_by_name.items():
            if name in names_to_keep:
                to_load[name] = spectrum

        return to_load
示例#3
0
文件: dialogs.py 项目: glue-viz/glue
def dialog(title, text, icon, setting=None, default=None):

    if not getattr(settings, setting.upper()):
        return True

    check = QCheckBox()
    check.setText('Dont show this message again (can be reset via the preferences)')

    info = QMessageBox()
    info.setIcon(icon)
    info.setText(title)
    info.setInformativeText(text)
    info.setCheckBox(check)
    info.setStandardButtons(info.Cancel | info.Ok)
    if default == 'Cancel':
        info.setDefaultButton(info.Cancel)

    result = info.exec_()

    if result == info.Cancel:
        return False

    if check.isChecked():
        setattr(settings, setting.upper(), False)
        save_settings()

    return True
示例#4
0
    def load_from_file(self, fname):
        try:
            self.I_meas, self.sigma = np.loadtxt(
                                        fname, skiprows=2, unpack=True)
        except (ValueError, TypeError):
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Warning)
            msg.setText("Could not Load File")
            msg.setInformativeText(
                "The chosen file does not match the formatting.")
            msg.setWindowTitle("Warning")
            msg.resize(900, 300)
            msg.exec_()
            return
        with open(fname, 'r') as f:
            self.plane_meas = f.readline().split()[-1]

        if self.plane_meas == 'x':
            self.line_sigmax.set_xdata(self.I_meas)
            self.line_sigmax.set_ydata(np.array(self.sigma)*1e3)
        else:
            self.line_sigmay.set_xdata(self.I_meas)
            self.line_sigmay.set_ydata(np.array(self.sigma)*1e3)
        self.fig_sigma.figure.axes[0].set_xlim(
                [min(self.I_meas)*(1-DT*10), max(self.I_meas)*(1+DT*10)])
        self.fig_sigma.figure.axes[0].set_ylim(
                [min(self.sigma)*(1-DT)*1e3, max(self.sigma)*(1+DT)*1e3])
        self.fig_sigma.figure.canvas.draw()
示例#5
0
    def _select_spectra_to_load(self, specs_by_name):

        selection_dialog = SpectrumSelection(self)
        selection_dialog.populate(specs_by_name.keys())
        selection_dialog.exec_()

        names_to_keep = selection_dialog.get_selected()

        if not names_to_keep:
            logging.warning('No spectra selected')

            message_box = QMessageBox()
            message_box.setText("No spectra were selected.")
            message_box.setIcon(QMessageBox.Warning)
            message_box.setInformativeText('No data has been loaded.')
            message_box.exec()

            return {}

        to_load = OrderedDict()
        for name, spectrum in specs_by_name.items():
            if name in names_to_keep:
                to_load[name] = spectrum

        return to_load
示例#6
0
    def show_about(self):
        """Show About dialog."""
        msg_box = QMessageBox(self)
        text = (f"<img src='{image_path('mnelab_logo.png')}'>"
                f"<p>MNELAB {__version__}</p>")
        msg_box.setText(text)

        mnelab_url = "github.com/cbrnr/mnelab"
        mne_url = "github.com/mne-tools/mne-python"

        pkgs = []
        for key, value in have.items():
            if value:
                pkgs.append(f"{key}&nbsp;({value})")
            else:
                pkgs.append(f"{key}&nbsp;(not installed)")

        text = (f'<nobr><p>This program uses Python '
                f'{".".join(str(k) for k in version_info[:3])} and the '
                f'following packages:</p></nobr>'
                f'<p>{", ".join(pkgs)}</p>'
                f'<nobr><p>MNELAB repository: '
                f'<a href=https://{mnelab_url}>{mnelab_url}</a></p></nobr>'
                f'<nobr><p>MNE repository: '
                f'<a href=https://{mne_url}>{mne_url}</a></p></nobr>'
                f'<p>Licensed under the BSD 3-clause license.</p>'
                f'<p>Copyright 2017-2020 by Clemens Brunner.</p>')
        msg_box.setInformativeText(text)
        msg_box.exec_()
示例#7
0
    def load_files(self):
        dial = MultipleLoadDialog(self.load_register,
                                  self.settings.get_path_history())
        dial.setDirectory(
            self.settings.get("io.multiple_open_directory", str(Path.home())))
        dial.selectNameFilter(
            self.settings.get("io.multiple_open_filter",
                              next(iter(self.load_register.keys()))))
        self.error_list = []
        if dial.exec_():
            result = dial.get_result()
            load_dir = os.path.dirname(result.load_location[0])
            self.settings.set("io.multiple_open_directory", load_dir)
            self.settings.add_path_history(load_dir)
            self.settings.set("io.multiple_open_filter",
                              result.selected_filter)

            dial_fun = ExecuteFunctionDialog(
                self.execute_load_files, [result],
                exception_hook=load_data_exception_hook)
            dial_fun.exec_()
            if self.error_list:
                errors_message = QMessageBox()
                errors_message.setText("There are errors during load files")
                errors_message.setInformativeText(
                    "During load files cannot found some of files on disc")
                errors_message.setStandardButtons(QMessageBox.Ok)
                text = "\n".join("File: " + x[0] + "\n" + str(x[1])
                                 for x in self.error_list)
                errors_message.setDetailedText(text)
                errors_message.exec_()
示例#8
0
    def _on_export_data(self):
        """
        Handler function that is called when the Export Data button is pressed
        """
        all_filters = ";;".join(['*.ecsv'])
        path, fmt = compat.getsavefilename(filters=all_filters)

        if path and fmt:
            try:
                plot_data_item = self.current_item
                self.export_data_item(plot_data_item, path, fmt)

                message_box = QMessageBox()
                message_box.setText("Data exported successfully.")
                message_box.setIcon(QMessageBox.Information)
                message_box.setInformativeText(
                    "Data set '{}' has been exported to '{}'".format(
                        plot_data_item.data_item.name, path))

                message_box.exec()
            except Exception as e:
                logging.error(e)

                message_box = QMessageBox()
                message_box.setText("Error exporting data set.")
                message_box.setIcon(QMessageBox.Critical)
                message_box.setInformativeText(
                    "{}\n{}".format(
                        sys.exc_info()[0], sys.exc_info()[1].__repr__()[:100])
                )

                message_box.exec()
示例#9
0
    def create_error_dlg(self,
                         message,
                         info=None,
                         detail=None,
                         ignore_buttons=True):
        dlg = QMessageBox()
        dlg.setText(message)

        if info:
            dlg.setInformativeText(info)

        if detail:
            dlg.setDetailedText(detail)

        dlg.setWindowTitle(self.name + self.tr(" - Error"))
        dlg.setIcon(QMessageBox.Critical)

        if ignore_buttons:
            dlg.setStandardButtons(QMessageBox.Abort | QMessageBox.Ignore)
            dlg.btn_ignoreall = dlg.addButton(self.tr("Ignore A&ll"),
                                              QMessageBox.ActionRole)
            dlg.setDefaultButton(QMessageBox.Ignore)
        else:
            dlg.setDefaultButton(QMessageBox.NoButton)

        return dlg
示例#10
0
文件: dialogs.py 项目: sunn-e/glue
def dialog(title, text, icon, setting=None, default=None):

    if not getattr(settings, setting.upper()):
        return True

    check = QCheckBox()
    check.setText(
        'Dont show this message again (can be reset via the preferences)')

    info = QMessageBox()
    info.setIcon(icon)
    info.setText(title)
    info.setInformativeText(text)
    info.setCheckBox(check)
    info.setStandardButtons(info.Cancel | info.Ok)
    if default == 'Cancel':
        info.setDefaultButton(info.Cancel)

    result = info.exec_()

    if result == info.Cancel:
        return False

    if check.isChecked():
        setattr(settings, setting.upper(), False)
        save_settings()

    return True
示例#11
0
    def delete_patches(self):
        if self.mainwin.selection.hasSelection():
            rows = sorted(
                [r.row() for r in self.mainwin.selection.selectedRows()])
            patches = tuple(self.patches.get_row(r).displayname for r in rows)
            msg_box = QMessageBox()

            if len(rows) == 1:
                msg_box.setText(
                    self.tr("Delete patch '{}'?").format(patches[0]))
            else:
                msg_box.setText(
                    self.tr("Delete {} patches?").format(len(rows)))
                msg_box.setDetailedText('\n'.join(patches))

            msg_box.setInformativeText(
                self.tr("Patches can only be restored by re-importing them."))
            msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel)
            msg_box.setDefaultButton(QMessageBox.Cancel)
            msg_box.setIcon(QMessageBox.Warning)

            if msg_box.exec_() == QMessageBox.Yes:
                with self.session.begin():
                    for n, row in enumerate(rows):
                        self.patches.removeRows(row - n)
示例#12
0
    def load_data(self, file_path, file_loader, display=False):
        """
        Load spectral data given file path and loader.

        Parameters
        ----------
        file_path : str
            Path to location of the spectrum file.
        file_loader : str
            Format specified for the astropy io interface.
        display : bool
            Automatically add the loaded spectral data to the plot.

        Returns
        -------
        : :class:`~specviz.core.items.DataItem`
            The `DataItem` instance that has been added to the internal model.
        """
        try:
            spec = Spectrum1D.read(file_path, format=file_loader)
            name = file_path.split('/')[-1].split('.')[0]
            data_item = self.model.add_data(spec, name=name)

            return data_item
        except:
            message_box = QMessageBox()
            message_box.setText("Error loading data set.")
            message_box.setIcon(QMessageBox.Critical)
            message_box.setInformativeText("{}\n{}".format(
                sys.exc_info()[0],
                sys.exc_info()[1]))

            message_box.exec()
示例#13
0
文件: ux.py 项目: zzz9999/guiscrcpy
 def closeEvent(self, event):
     # do stuff
     message_box = QMessageBox()
     message_box.setText("Save changes and exit?")
     vals = [
         "{} → {}".format(x, self.core.config[x]) for x in self.core.config
     ]
     message_box.setInformativeText(
         "Mapper has unsaved mappings: {val}. Do you want to save the "
         "current mappings?".format(val=', '.join(vals)))
     message_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No
                                    | QMessageBox.Cancel)
     user_message_box_response = message_box.exec()
     if user_message_box_response == QMessageBox.Yes:
         print("Registration process completed.")
         print("Registered mappings are : ", self.core.config)
         print("Writing configuration file...")
         self.core.create_configuration()
         print("Mapper completed successfully!")
         event.accept()
     elif user_message_box_response == QMessageBox.No:
         print("Not saving mapper configuration to json file")
         event.accept()
     else:
         event.ignore()
示例#14
0
    def save_register_new_loader(self, filename):
        filename = "{}.py".format(
            filename) if not filename.endswith(".py") else filename

        string = self.as_new_loader()

        with open(filename, 'w') as f:
            f.write(string)

        # If a loader by this name exists, delete it
        if self.new_loader_dict['name'] in registry.get_formats()['Format']:
            registry.unregister_reader(self.new_loader_dict['name'],
                                       Spectrum1D)
            registry.unregister_identifier(self.new_loader_dict['name'],
                                           Spectrum1D)

        # Add new loader to registry
        spec = importlib.util.spec_from_file_location(
            os.path.basename(filename)[:-3], filename)
        mod = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(mod)

        message_box = QMessageBox()
        message_box.setText("Loader saved successful.")
        message_box.setIcon(QMessageBox.Information)
        message_box.setInformativeText("Custom loader was saved successfully.")

        message_box.exec()
示例#15
0
 def show_failure_msg(self, msg, info, details):
     self.viz_tab.set_message(msg)
     msgBox = QMessageBox()
     msgBox.setIcon(QMessageBox.Critical)
     msgBox.setText(msg)
     msgBox.setInformativeText(info)
     msgBox.setDetailedText(details)
     msgBox.exec()
示例#16
0
 def _plotting_error(self, msg, trace):
     msg_box = QMessageBox(self)
     msg_box.setIcon(QMessageBox.Critical)
     msg_box.setText('Plotting Error')
     msg_box.setInformativeText(msg)
     msg_box.setDetailedText(trace)
     msg_box.setStandardButtons(QMessageBox.Close)
     msg_box.exec_()
示例#17
0
 def new_message_box(self, text, info=None, icon=QMessageBox.Warning):
     message_box = QMessageBox()
     message_box.setText(text)
     message_box.setIcon(icon)
     if info is not None:
         message_box.setInformativeText(info)
     message_box.exec()
     return
示例#18
0
    def __init__(
        self,
        config_folder: Union[str, Path, None] = None,
        title="PartSeg",
        settings: Optional[BaseSettings] = None,
        load_dict: Optional[Register] = None,
        signal_fun=None,
    ):
        if settings is None:
            if config_folder is None:
                raise ValueError("wrong config folder")
            if not os.path.exists(config_folder):
                import_config()
            settings: BaseSettings = self.get_setting_class()(config_folder)
            errors = settings.load()
            if errors:
                errors_message = QMessageBox()
                errors_message.setText("There are errors during start")
                errors_message.setInformativeText(
                    "During load saved state some of data could not be load properly\n"
                    "The files has prepared backup copies in "
                    " state directory (Help > State directory)")
                errors_message.setStandardButtons(QMessageBox.Ok)
                text = "\n".join("File: " + x[0] + "\n" + str(x[1])
                                 for x in errors)
                errors_message.setDetailedText(text)
                errors_message.exec_()

        super().__init__()
        if signal_fun is not None:
            self.show_signal.connect(signal_fun)
        self.settings = settings
        self._load_dict = load_dict
        self.viewer_list: List[Viewer] = []
        self.files_num = 1
        self.setAcceptDrops(True)
        self.setWindowTitle(title)
        self.title_base = title
        app = QApplication.instance()
        if app is not None:
            app.setStyleSheet(settings.style_sheet)
        self.settings.theme_changed.connect(self.change_theme)
        self.channel_info = ""
        self.multiple_files = None
        self.settings.request_load_files.connect(self.read_drop)
        self.recent_file_menu = QMenu("Open recent")
        self._refresh_recent()
        self.settings.connect_(FILE_HISTORY, self._refresh_recent)
        self.settings.napari_settings.appearance.events.theme.connect(
            self.change_theme)
        self.settings.set_parent(self)
        self.console = None
        self.console_dock = QDockWidget("console", self)
        self.console_dock.setAllowedAreas(Qt.LeftDockWidgetArea
                                          | Qt.BottomDockWidgetArea)
        # self.console_dock.setWidget(self.console)
        self.console_dock.hide()
        self.addDockWidget(Qt.BottomDockWidgetArea, self.console_dock)
示例#19
0
    def bootstrap_mapper(self):
        mapper_config_path = os.path.join(self.config_manager.get_cfgpath(),
                                          "guiscrcpy.mapper.json")
        if os.path.exists(mapper_config_path):
            from guiscrcpy.lib.mapper.mapper import MapperAsync

            _, identifier = self.current_device_identifier()
            self.mp = MapperAsync(
                self,
                device_id=identifier,
                config_path=mapper_config_path,
                adb=self.adb,
                initialize=False,
            )
            self.mp.start()
            self.private_message_box_adb.setText(
                "guiscrcpy-mapper has started")
        else:
            message_box = QMessageBox()
            message_box.setText(
                "guiscrcpy mapper is not initialized yet. Do you want to "
                "initialize it now?")
            message_box.setInformativeText(
                "Before you initialize, make sure your phone is connected and "
                "the display is switched on to map the points.")
            message_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            user_message_box_response = message_box.exec()
            values_devices_list = self.scan_devices_update_list_view()
            self.check_devices_status_and_select_first_if_only_one(
                values_devices_list=values_devices_list)
            # TODO: allow enabling mapper from inside
            if user_message_box_response == QMessageBox.Yes:
                self.private_message_box_adb.setText("Initializing mapper...")
                print("Make sure your phone is connected and display is "
                      "switched on")
                print("Reset mapper if you missed any "
                      "steps by 'guiscrcpy --mapper-reset'")
                print()
                print("If at first you don't succeed... "
                      "reset, reset and reset again! :D")
                print()
                _, identifier = self.current_device_identifier()
                executable = get_self()
                from .lib.utils import shellify as sx, open_process

                open_process(
                    sx("{} mapper".format(executable)),
                    stdout=sys.stdout,
                    stdin=sys.stdin,
                    stderr=sys.stderr,
                    cwd=os.getcwd(),
                )
                print("Mapper started")
                self.private_message_box_adb.setText("Mapper initialized")
示例#20
0
 def pb_analyse_data_clicked(self):
     if self.I_meas is None or self.sigma is None:
         msg = QMessageBox()
         msg.setIcon(QMessageBox.Warning)
         msg.setText("Could Perform Analysis")
         msg.setInformativeText(
             "No data in memory. Please make a measurement or load the data.")
         msg.setWindowTitle("Warning")
         msg.resize(900, 300)
         msg.exec_()
         return
     self._perform_analysis()
示例#21
0
    def display_load_data_error(self, exp):
        """
        Display error message box when attempting to load a data set.

        Parameters
        ----------
        exp : str
            Error text.
        """
        message_box = QMessageBox()
        message_box.setText("Error loading data set.")
        message_box.setIcon(QMessageBox.Critical)
        message_box.setInformativeText(str(exp))
        message_box.exec()
示例#22
0
def permission_box_to_prepend_import():
    msg_box = QMessageBox()
    msg_box.setWindowTitle("Mantid Workbench")
    msg_box.setWindowIcon(QIcon(':/images/MantidIcon.ico'))
    msg_box.setText("It looks like this python file uses a Mantid "
                    "algorithm but does not import the Mantid API.")
    msg_box.setInformativeText("Would you like to add a line to import "
                               "the Mantid API?")
    msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
    msg_box.setDefaultButton(QMessageBox.Yes)
    permission = msg_box.exec_()
    if permission == QMessageBox.Yes:
        return True
    return False
示例#23
0
    def display_load_data_error(self, exp):
        """
        Display error message box when attempting to load a data set.

        Parameters
        ----------
        exp : str
            Error text.
        """
        message_box = QMessageBox()
        message_box.setText("Error loading data set.")
        message_box.setIcon(QMessageBox.Critical)
        message_box.setInformativeText(str(exp))
        message_box.exec()
示例#24
0
def permission_box_to_prepend_import():
    msg_box = QMessageBox()
    msg_box.setWindowTitle("Mantid Workbench")
    msg_box.setWindowIcon(QIcon(':/images/MantidIcon.ico'))
    msg_box.setText("It looks like this python file uses a Mantid "
                    "algorithm but does not import the Mantid API.")
    msg_box.setInformativeText("Would you like to add a line to import "
                               "the Mantid API?")
    msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
    msg_box.setDefaultButton(QMessageBox.Yes)
    permission = msg_box.exec_()
    if permission == QMessageBox.Yes:
        return True
    return False
示例#25
0
    def show_mongo_query_help(self):
        "Launch a Message Box with instructions for custom queries."
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Information)
        msg.setText("For advanced search capability, enter a valid Mongo query.")
        msg.setInformativeText("""
Examples:

{'plan_name': 'scan'}
{'proposal': 1234},
{'$and': ['proposal': 1234, 'sample_name': 'Ni']}
""")
        msg.setWindowTitle("Custom Mongo Query")
        msg.setStandardButtons(QMessageBox.Ok)
        msg.exec_()
示例#26
0
 def pb_save_data_clicked(self):
     if self.I_meas is None or self.sigma is None:
         msg = QMessageBox()
         msg.setIcon(QMessageBox.Warning)
         msg.setText("Could not Save")
         msg.setInformativeText(
             "There are no data saved in Memory. Make a measurement First.")
         msg.setWindowTitle("Warning")
         msg.resize(900, 300)
         msg.exec_()
         return
     fname = QFileDialog.getSaveFileName(
             self, 'Save file', '', 'Text Files (*.txt *.dat)')
     if fname[0]:
         self.save_to_file(fname[0])
示例#27
0
 def save_list_to_file(self):
     filename, filters = QFileDialog.getSaveFileName(
         self, "Save connection list", "", "Text Files (*.txt)")
     try:
         with open(filename, "w") as f:
             for conn in self.table_view.model().connections:
                 f.write("{p}://{a}\n".format(p=conn.protocol,
                                              a=conn.address))
         self.save_status_label.setText("File saved to {}".format(filename))
     except Exception as e:
         msgBox = QMessageBox()
         msgBox.setText("Couldn't save connection list to file.")
         msgBox.setInformativeText("Error: {}".format(str(e)))
         msgBox.setStandardButtons(QMessageBox.Ok)
         msgBox.exec_()
示例#28
0
    def __createMsgBox(self, title, message, details):
        msg_box = QMessageBox(self.parent())
        msg_box.setText(title)
        msg_box.setInformativeText(message)

        if len(details) > 0:
            msg_box.setDetailedText(details)

        horizontal_spacer = QSpacerItem(
            500, 0, QSizePolicy.MinimumExpanding, QSizePolicy.Expanding
        )
        layout = msg_box.layout()
        layout.addItem(horizontal_spacer, layout.rowCount(), 0, 1, layout.columnCount())

        return msg_box
示例#29
0
    def show_mongo_query_help(self):
        "Launch a Message Box with instructions for custom queries."
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Information)
        msg.setText("For advanced search capability, enter a valid Mongo query.")
        msg.setInformativeText("""
Examples:

{'plan_name': 'scan'}
{'proposal': 1234},
{'$and': ['proposal': 1234, 'sample_name': 'Ni']}
""")
        msg.setWindowTitle("Custom Mongo Query")
        msg.setStandardButtons(QMessageBox.Ok)
        msg.exec_()
示例#30
0
 def _ok_to_close(self, entity):
     if entity.widget in self.modified_widgets:
         mb = QMessageBox()
         mb.setText("The tab contents may have been modified.")
         mb.setInformativeText("Do you want to save your changes?")
         mb.setStandardButtons(QMessageBox.Save | QMessageBox.Discard
                               | QMessageBox.Cancel)
         mb.setDefaultButton(QMessageBox.Save)
         ans = mb.exec()
         if ans == QMessageBox.Cancel:
             return False
         elif ans == QMessageBox.Save:
             saved = self.save()
             if not saved:
                 return False
     return True
示例#31
0
文件: _qt.py 项目: mh105/mne-python
    def _dialog_create(self,
                       title,
                       text,
                       info_text,
                       callback,
                       *,
                       icon='Warning',
                       buttons=[],
                       modal=True,
                       window=None):
        window = self._window if window is None else window
        widget = QMessageBox(window)
        widget.setWindowTitle(title)
        widget.setText(text)
        # icon is one of _QtDialog.supported_icon_names
        icon_id = getattr(QMessageBox, icon)
        widget.setIcon(icon_id)
        widget.setInformativeText(info_text)

        if not buttons:
            buttons = ["Ok"]

        button_ids = list()
        for button in buttons:
            # button is one of _QtDialog.supported_button_names
            button_id = getattr(QMessageBox, button)
            button_ids.append(button_id)
        standard_buttons = default_button = button_ids[0]
        for button_id in button_ids[1:]:
            standard_buttons |= button_id
        widget.setStandardButtons(standard_buttons)
        widget.setDefaultButton(default_button)

        @safe_event
        def func(button):
            button_id = widget.standardButton(button)
            for button_name in _QtDialog.supported_button_names:
                if button_id == getattr(QMessageBox, button_name):
                    widget.setCursor(QCursor(Qt.WaitCursor))
                    try:
                        callback(button_name)
                    finally:
                        widget.unsetCursor()
                        break

        widget.buttonClicked.connect(func)
        return _QtDialogWidget(widget, modal)
示例#32
0
 def save_list_to_file(self):
     filename, filters = QFileDialog.getSaveFileName(self,
                                                     "Save connection list",
                                                     "",
                                                     "Text Files (*.txt)")
     try:
         with open(filename, "w") as f:
             for conn in self.table_view.model().connections:
                 f.write(
                     "{p}://{a}\n".format(p=conn.protocol, a=conn.address))
         self.save_status_label.setText("File saved to {}".format(filename))
     except Exception as e:
         msgBox = QMessageBox()
         msgBox.setText("Couldn't save connection list to file.")
         msgBox.setInformativeText("Error: {}".format(str(e)))
         msgBox.setStandardButtons(QMessageBox.Ok)
         msgBox.exec_()
示例#33
0
文件: config.py 项目: ZLLentz/atef
    def welcome_user(self):
        """
        On open, ask the user what they'd like to do (new config? load?)

        TODO: only show when we don't get a file cli argument to start.
        """
        welcome_box = QMessageBox()
        welcome_box.setIcon(QMessageBox.Question)
        welcome_box.setWindowTitle('Welcome')
        welcome_box.setText('Welcome to atef config!')
        welcome_box.setInformativeText('Please select a startup action')
        open_button = welcome_box.addButton(QMessageBox.Open)
        new_button = welcome_box.addButton('New', QMessageBox.AcceptRole)
        welcome_box.addButton(QMessageBox.Close)
        open_button.clicked.connect(self.open_file)
        new_button.clicked.connect(self.new_file)
        welcome_box.exec()
示例#34
0
def excepthook(exctype, excvalue, tracebackobj):
    """
    Global function to catch unhandled exceptions.

    @param exctype exception type
    @param excvalue exception value
    @param tracebackobj traceback object
    """
    app = SiriusApplication.instance()
    if app is None:
        app = SiriusApplication(None, sys.argv)

    separator = '-' * 120 + '\n'
    notice = \
        'An unhandled exception occurred. Please report the problem '\
        'via email to <{}>.\nA log has {{}}been written to "{}".\n\n'\
        'Error information:\n'.format("*****@*****.**", LOGFILE)
    timestring = time.strftime("%Y-%m-%d, %H:%M:%S") + '\n'

    tbinfofile = StringIO()
    traceback.print_tb(tracebackobj, None, tbinfofile)
    tbinfofile.seek(0)
    tbinfo = tbinfofile.read()

    errmsg = '%s: \n%s\n' % (str(exctype), str(excvalue))
    sections = [timestring, errmsg, tbinfo]
    msg = separator.join(sections)
    try:
        with open(LOGFILE, 'a') as fil:
            fil.write('\n' + msg + '\n')
        try:
            os.chmod(LOGFILE, 0o666)
        except OSError:
            pass
    except PermissionError:
        notice = notice.format('NOT ')
    else:
        notice = notice.format('')
    errorbox = QMessageBox()
    errorbox.setText(notice)
    errorbox.setInformativeText(msg)
    errorbox.setIcon(QMessageBox.Critical)
    errorbox.setWindowTitle('Error')
    errorbox.setStyleSheet('#qt_msgbox_informativelabel {min-width: 40em;}')
    errorbox.exec_()
示例#35
0
 def _ok_to_quit(self):
     if not hasattr(self, "_main_window"):
         return True
     if self.modified:
         mb = QMessageBox()
         mb.setText("The project may have been modified.")
         mb.setInformativeText("Do you want to save your changes?")
         mb.setStandardButtons(QMessageBox.Save | QMessageBox.Discard
                               | QMessageBox.Cancel)
         mb.setDefaultButton(QMessageBox.Save)
         ans = mb.exec()
         if ans == QMessageBox.Cancel:
             return False
         elif ans == QMessageBox.Save:
             saved = self.save()
             if not saved:
                 return False
     return True
示例#36
0
 def launch(self):
     if self.prepare.result is None:
         self.close()
         return
     if self.prepare.errors:
         errors_message = QMessageBox()
         errors_message.setText("There are errors during start")
         errors_message.setInformativeText(
             "During load saved state some of data could not be load properly\n"
             "The files has prepared backup copies in  state directory (Help > State directory)"
         )
         errors_message.setStandardButtons(QMessageBox.Ok)
         text = "\n".join(["File: " + x[0] + "\n" + str(x[1]) for x in self.prepare.errors])
         errors_message.setDetailedText(text)
         errors_message.exec()
     wind = self.prepare.result(title=self.final_title, signal_fun=self.window_shown)
     wind.show()
     self.wind = wind
示例#37
0
    def _export_shape_file(self, *args, **kwargs):
        # show files
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Information)
        msg.setText("You are about to create shape files.")
        msg.setInformativeText(
            "Please select an output directory after click \"OK\"\n"
            "For the list of .edi files (stations) included in the creation, please click \"Show Details\""
        )
        msg.setWindowTitle("Note")
        msg.setDetailedText("\n".join([
            "{station} ({fn})".format(
                station=station, fn=self._file_handler.station2ref(station))
            for station in self._station_viewer.selected_stations
        ]))
        msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)

        if msg.exec_() == QMessageBox.Ok:
            dialog = QFileDialog(self)
            dir_name = None
            dialog.setWindowTitle("Selecting Output Directory ...")
            dialog.setFileMode(QFileDialog.DirectoryOnly)
            while dir_name is None:
                if dialog.exec_() == QDialog.Accepted:
                    dir_name = dialog.selectedFiles()[0]
                    dir_name = str(dir_name)
                    if not os.path.isdir(dir_name):
                        QMessageBox.information(
                            self, "NOTE",
                            "Please select a directory to save the created shape files."
                        )
                        dir_name = None  # will read again
                else:
                    break
            if dir_name is not None:
                collect = EdiCollection(mt_objs=[
                    self._file_handler.get_MT_obj(
                        self._file_handler.station2ref(station))
                    for station in self._station_viewer.selected_stations
                ])
                collect.create_mt_station_gdf(dir_name)
                QMessageBox.information(self, "Creation Completed",
                                        "Output written to %s" % dir_name)
                webbrowser.open(dir_name)
示例#38
0
    def _on_change_color(self):
        """
        Listens for color changed events in plot windows, gets the currently
        selected item in the data list view, and changes the stored color
        value.
        """
        # If there is no currently selected rows, raise an error
        if self.current_item is None:
            message_box = QMessageBox()
            message_box.setText("No item selected, cannot change color.")
            message_box.setIcon(QMessageBox.Warning)
            message_box.setInformativeText(
                "There is currently no item selected. Please select an item "
                "before changing its plot color.")

            message_box.exec()
            return

        color = QColorDialog.getColor(options=QColorDialog.ShowAlphaChannel)

        if color.isValid():
            self.current_item.color = color.toRgb()
            self.color_changed.emit(self.current_item, self.current_item.color)
示例#39
0
    def show(self):
        """
        Parses the current plot window information and displays the unit change
        dialog with the appropriate available units to which the current
        plot's units can be changed.
        """
        # If there is no plot item, don't even try to process unit info
        if self.hub.plot_item is None or len(self.hub.visible_plot_items) == 0:
            message_box = QMessageBox()
            message_box.setText("No item plotted, cannot parse unit information.")
            message_box.setIcon(QMessageBox.Warning)
            message_box.setInformativeText(
                "There is currently no items plotted. Please plot an item "
                "before changing unit.")

            message_box.exec_()
            return

        # Prevents duplicate units from showing up each time this is executed
        self.ui.comboBox_units.clear()
        self.ui.comboBox_spectral.clear()

        # If the units in PlotWidget are not set, do not allow the user to click the OK button
        if not self.hub.plot_widget.data_unit:
            self.ui.comboBox_units.setEnabled(False)

        if not self.hub.plot_widget.spectral_axis_unit:
            self.ui.comboBox_spectral.setEnabled(False)

        if not (self.hub.plot_widget.data_unit or self.hub.plot_widget.spectral_axis_unit):
            self.ui.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)

        # Gets all possible conversions from current spectral_axis_unit
        self.spectral_axis_unit_equivalencies = u.Unit(
            self.hub.data_item.spectral_axis.unit).find_equivalent_units(
                equivalencies=u.spectral())

        # Gets all possible conversions for flux from current spectral axis and corresponding units
        # np.sum for spectral_axis so that it does not return a Quantity with zero scale
        self.data_unit_equivalencies = u.Unit(
            self.hub.plot_widget.data_unit).find_equivalent_units(
                equivalencies=u.spectral_density(np.sum(self.hub.data_item.spectral_axis)), include_prefix_units=False)

        # Current data unit and spectral axis unit
        self.current_data_unit = self.hub.plot_widget.data_unit
        self.current_spectral_axis_unit = self.hub.plot_widget.spectral_axis_unit

        # Add current spectral axis units to equivalencies
        if u.Unit(self.hub.plot_widget.spectral_axis_unit) not in self.spectral_axis_unit_equivalencies:
            self.spectral_axis_unit_equivalencies.append(u.Unit(self.hub.plot_widget.spectral_axis_unit))

        # Add original spectral axis units to equivalencies
        if u.Unit(self.hub.data_item.spectral_axis.unit) not in self.spectral_axis_unit_equivalencies:
            self.spectral_axis_unit_equivalencies.append(u.Unit(self.hub.data_item.spectral_axis.unit))

        # Add current data units to equivalencies
        if u.Unit(self.hub.plot_widget.data_unit) not in self.data_unit_equivalencies:
            self.data_unit_equivalencies.append(u.Unit(self.hub.plot_widget.data_unit))

        # Add original flux units to equivalencies
        if u.Unit(self.hub.data_item.flux.unit) not in self.data_unit_equivalencies:
            self.data_unit_equivalencies.append(u.Unit(self.hub.data_item.flux.unit))

        # Sort units by to_string()
        self.spectral_axis_unit_equivalencies = sorted(self.spectral_axis_unit_equivalencies, key=lambda x: x.to_string())
        self.data_unit_equivalencies = sorted(self.data_unit_equivalencies, key=lambda y: y.to_string())

        # Create lists with the "pretty" versions of unit names
        self.spectral_axis_unit_equivalencies_titles = [
            u.Unit(unit).name
            if u.Unit(unit) == u.Unit("Angstrom")
            else u.Unit(unit).long_names[0].title() if (hasattr(u.Unit(unit), "long_names") and len(u.Unit(unit).long_names) > 0)
            else u.Unit(unit).to_string()
            for unit in self.spectral_axis_unit_equivalencies]
        self.data_unit_equivalencies_titles = [
            u.Unit(unit).name
            if u.Unit(unit) == u.Unit("Angstrom")
            else u.Unit(unit).long_names[0].title() if (hasattr(u.Unit(unit), "long_names") and len(u.Unit(unit).long_names) > 0)
            else u.Unit(unit).to_string()
            for unit in self.data_unit_equivalencies]

        # This gives the user the option to use their own units. These units are checked by u.Unit()
        # and PlotDataItem.is_spectral_axis_unit_compatible(spectral_axis_unit) and
        # PlotDataItem.is_data_unit_compatible(data_unit)
        self.spectral_axis_unit_equivalencies_titles.append("Custom")
        self.data_unit_equivalencies_titles.append("Custom")

        self.setup_ui()
        self.setup_connections()

        super().show()