Python PyQt5.QtWidgets.QMessageBox.Cancel() Examples

The following are 30 code examples of PyQt5.QtWidgets.QMessageBox.Cancel(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module PyQt5.QtWidgets.QMessageBox , or try the search function .
Example #1
Source File: test_logic.py    From mu with GNU General Public License v3.0 6 votes vote down vote up
def test_check_usb_when_selecting_mode_is_silent():
    """
    Ensure the check_usb doesn't ask to change mode if the user has the mode
    selection dialog active (indicated by the selecting_mode flag.
    """
    view = mock.MagicMock()
    view.show_confirmation = mock.MagicMock(return_value=QMessageBox.Cancel)
    ed = mu.logic.Editor(view)
    ed.change_mode = mock.MagicMock()
    mode_py = mock.MagicMock()
    mode_py.name = "Python3"
    mode_py.runner = None
    mode_py.find_device.return_value = (None, None)
    mode_cp = mock.MagicMock()
    mode_cp.name = "CircuitPlayground"
    mode_cp.find_device.return_value = ("/dev/ttyUSB1", "12345")
    ed.modes = {"circuitplayground": mode_cp, "python": mode_py}
    ed.show_status_message = mock.MagicMock()
    ed.selecting_mode = True
    ed.check_usb()
    expected = "Detected new CircuitPlayground device."
    ed.show_status_message.assert_called_with(expected)
    assert view.show_confirmation.call_count == 0
    ed.change_mode.assert_not_called() 
Example #2
Source File: test_logic.py    From mu with GNU General Public License v3.0 6 votes vote down vote up
def test_check_usb_change_mode_cancel():
    """
    Ensure the check_usb doesn't change mode if confirmation cancelled by user.
    """
    view = mock.MagicMock()
    view.show_confirmation = mock.MagicMock(return_value=QMessageBox.Cancel)
    ed = mu.logic.Editor(view)
    ed.change_mode = mock.MagicMock()
    mode_py = mock.MagicMock()
    mode_py.name = "Python3"
    mode_py.runner = None
    mode_py.find_device.return_value = (None, None)
    mode_cp = mock.MagicMock()
    mode_cp.name = "CircuitPlayground"
    mode_cp.find_device.return_value = ("/dev/ttyUSB1", "12345")
    ed.modes = {"circuitplayground": mode_cp, "python": mode_py}
    ed.show_status_message = mock.MagicMock()
    ed.check_usb()
    expected = "Detected new CircuitPlayground device."
    ed.show_status_message.assert_called_with(expected)
    assert view.show_confirmation.called
    ed.change_mode.assert_not_called() 
Example #3
Source File: main_dlg.py    From dash-masternode-tool with MIT License 6 votes vote down vote up
def on_btnCancelEditingMn_clicked(self, checked):
        if self.app_config.is_modified():
            if WndUtils.queryDlg('Configuration modified. Discard changes?',
                                 buttons=QMessageBox.Yes | QMessageBox.Cancel,
                                 default_button=QMessageBox.Cancel, icon=QMessageBox.Warning) == QMessageBox.Yes:
                # reload the configuration (we don't keep the old values)
                sel_mn_idx = self.app_config.masternodes.index(self.cur_masternode)
                # reload the configuration from file
                self.load_configuration_from_file(self.app_config.app_config_file_name, ask_save_changes=False)
                self.editing_enabled = False
                if sel_mn_idx >= 0 and sel_mn_idx < len(self.app_config.masternodes):
                    self.cur_masternode = self.app_config.masternodes[sel_mn_idx]
                    self.display_masternode_config(sel_mn_idx)
                self.wdg_masternode.set_edit_mode(self.editing_enabled)
                self.update_edit_controls_state()
        else:
            if self.cur_masternode and self.cur_masternode.new:
                idx = self.app_config.masternodes.index(self.cur_masternode)
                if idx >= 0:
                    self.app_config.masternodes.remove(self.cur_masternode)
                    self.cboMasternodes.removeItem(self.cboMasternodes.currentIndex())
            self.editing_enabled = False
            self.wdg_masternode.set_edit_mode(self.editing_enabled)
            self.update_edit_controls_state()
        self.update_mn_controls_state() 
Example #4
Source File: hw_setup_dlg.py    From dash-masternode-tool with MIT License 6 votes vote down vote up
def on_btnEnDisPass_clicked(self):
        try:
            if self.hw_session and self.hw_session.hw_client:
                if self.passphrase_protection is True:
                    # disable passphrase
                    if self.queryDlg('Do you really want to disable passphrase protection of your %s?' % self.main_ui.getHwName(),
                                     buttons=QMessageBox.Yes | QMessageBox.Cancel, default_button=QMessageBox.Cancel,
                                     icon=QMessageBox.Warning) == QMessageBox.Yes:
                        hw_intf.enable_passphrase(self.hw_session, passphrase_enabled=False)
                        self.read_hw_features()
                        self.updateControlsState()
                elif self.passphrase_protection is False:
                    # enable passphrase
                    if self.queryDlg('Do you really want to enable passphrase protection of your %s?' % self.main_ui.getHwName(),
                                     buttons=QMessageBox.Yes | QMessageBox.Cancel, default_button=QMessageBox.Cancel,
                                     icon=QMessageBox.Warning) == QMessageBox.Yes:
                        hw_intf.enable_passphrase(self.hw_session, passphrase_enabled=True)
                        self.read_hw_features()
                        self.updateControlsState()

        except Exception as e:
            self.errorMsg(str(e)) 
Example #5
Source File: test_logic.py    From mu with GNU General Public License v3.0 6 votes vote down vote up
def test_quit_modified_cancelled_from_event():
    """
    If the user quits and there's unsaved work, and they cancel the "quit" then
    do nothing.
    """
    view = mock.MagicMock()
    view.modified = True
    view.show_confirmation = mock.MagicMock(return_value=QMessageBox.Cancel)
    ed = mu.logic.Editor(view)
    mock_open = mock.MagicMock()
    mock_open.return_value.__enter__ = lambda s: s
    mock_open.return_value.__exit__ = mock.Mock()
    mock_open.return_value.write = mock.MagicMock()
    mock_event = mock.MagicMock()
    mock_event.ignore = mock.MagicMock(return_value=None)
    with mock.patch("sys.exit", return_value=None), mock.patch(
        "builtins.open", mock_open
    ):
        ed.quit(mock_event)
    assert view.show_confirmation.call_count == 1
    assert mock_event.ignore.call_count == 1
    assert mock_open.call_count == 0 
Example #6
Source File: test_logic.py    From mu with GNU General Public License v3.0 6 votes vote down vote up
def test_quit_modified_cancelled_from_button():
    """
    If the user quits and there's unsaved work, and they cancel the "quit" then
    do nothing.
    """
    view = mock.MagicMock()
    view.modified = True
    view.show_confirmation = mock.MagicMock(return_value=QMessageBox.Cancel)
    ed = mu.logic.Editor(view)
    mock_open = mock.MagicMock()
    mock_open.return_value.__enter__ = lambda s: s
    mock_open.return_value.__exit__ = mock.Mock()
    mock_open.return_value.write = mock.MagicMock()
    with mock.patch("sys.exit", return_value=None), mock.patch(
        "builtins.open", mock_open
    ):
        ed.quit()
    assert view.show_confirmation.call_count == 1
    assert mock_open.call_count == 0 
Example #7
Source File: fileManager.py    From openMotor with GNU General Public License v3.0 6 votes vote down vote up
def unsavedCheck(self):
        if self.savedVersion != self.currentVersion:
            msg = QMessageBox()

            msg.setText("The current file has unsaved changes. Close without saving?")
            msg.setWindowTitle("Close without saving?")
            msg.setStandardButtons(QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)

            res = msg.exec_()
            if res == QMessageBox.Save:
                self.save()
                return True
            if res == QMessageBox.Discard:
                return True
            return False

        return True

    # Outputs the filename component of the title 
Example #8
Source File: centralwidget.py    From autokey with GNU General Public License v3.0 6 votes vote down vote up
def promptToSave(self):
        if cm.ConfigManager.SETTINGS[cm.PROMPT_TO_SAVE]:
            # TODO: i18n
            result = QMessageBox.question(
                self.window(),
                "Save changes?",
                "There are unsaved changes. Would you like to save them?",
                QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel
            )

            if result == QMessageBox.Yes:
                return self.on_save()
            elif result == QMessageBox.Cancel:
                return True
            else:
                return False
        else:
            # don't prompt, just save
            return self.on_save()

    # ---- Signal handlers 
Example #9
Source File: gui.py    From payment-proto-interface with MIT License 6 votes vote down vote up
def make_further_instructions(self, pr):
        def further_instructions():
            response = QMessageBox.information(self, "Next Step", "To continue, send the necessary amounts of Bitcoin to the addresses specified in the 'Outputs' field above. Once broadcast, press Yes to Continue or Cancel to quit.", QMessageBox.Cancel | QMessageBox.Yes, QMessageBox.Cancel)
            if response == QMessageBox.Cancel:
                sys.exit()
            elif response == QMessageBox.Yes:
                if pr.details.payment_url:
                    raw_tx, okPressed1 = QInputDialog.getText(self, "Enter Raw Transaction","Enter the hex of the transaction that was just made:", QLineEdit.Normal, "")
                    if okPressed1 and raw_tx != '':
                        ref_addr, okPressed2 = QInputDialog.getText(self, "Enter Refund Address","Enter a refund address:", QLineEdit.Normal, "")
                        if okPressed2 and ref_addr != '':
                            try:
                                result = pr.send_ack(raw_tx.strip(), ref_addr.strip())
                                if result[0]:
                                    QMessageBox.information(self, "Complete!", "Payment request successful: " + result[1] + "\n\nClick Ok to exit", QMessageBox.Ok, QMessageBox.Ok)
                                    sys.exit()
                                else:
                                    QMessageBox.error(self, "Error!", "Payment request was not successful: " + result[1] + "\n\nClick Ok to exit", QMessageBox.Ok, QMessageBox.Ok)
                                    sys.exit()
                            except:
                                QMessageBox.error(self, "Error!", "There was an error parsing the raw transaction or address. Please restart and try again.\n\nClick Ok to exit", QMessageBox.Ok, QMessageBox.Ok)
                                sys.exit()
                                
        return further_instructions 
Example #10
Source File: test_msgbox.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def test_attributes(qtbot):
    """Test basic QMessageBox attributes."""
    title = 'title'
    text = 'text'
    parent = QWidget()
    qtbot.add_widget(parent)
    icon = QMessageBox.Critical
    buttons = QMessageBox.Ok | QMessageBox.Cancel

    box = msgbox.msgbox(parent=parent, title=title, text=text, icon=icon,
                        buttons=buttons)
    qtbot.add_widget(box)
    if not utils.is_mac:
        assert box.windowTitle() == title
    assert box.icon() == icon
    assert box.standardButtons() == buttons
    assert box.text() == text
    assert box.parent() is parent 
Example #11
Source File: Messages.py    From DownloaderForReddit with GNU General Public License v3.0 5 votes vote down vote up
def update_reddit_objects_message(self):
        text = "Saved reddit objects are from a previous version of the program and are no\n" \
               "longer compatible. These objects will now be updated to the latest version\n" \
               "and the application will be saved. All of the objects settings and download list\n" \
               "will be carried over to new objects.\n" \
               "If you do not update these objects, the saved objects will not work correctly\n" \
               "and will most likely cause the application to crash"
        reply = message.information(self, "Update Reddit Objects", text, message.Ok, message.Cancel)
        return reply == message.Ok 
Example #12
Source File: test_main.py    From mu with GNU General Public License v3.0 5 votes vote down vote up
def test_Window_show_confirmation_default(qtapp):
    """
    Ensure the show_confirmation method configures a QMessageBox in the
    expected manner with default args.
    """
    mock_qmb = mock.MagicMock()
    mock_qmb.setText = mock.MagicMock(return_value=None)
    mock_qmb.setWindowTitle = mock.MagicMock(return_value=None)
    mock_qmb.setInformativeText = mock.MagicMock(return_value=None)
    mock_qmb.setIcon = mock.MagicMock(return_value=None)
    mock_qmb.Warning = mock.MagicMock()
    mock_qmb.setStandardButtons = mock.MagicMock(return_value=None)
    mock_qmb.Cancel = mock.MagicMock()
    mock_qmb.Ok = mock.MagicMock()
    mock_qmb.setDefaultButton = mock.MagicMock(return_value=None)
    mock_qmb.exec = mock.MagicMock(return_value=None)
    mock_qmb_class = mock.MagicMock(return_value=mock_qmb)
    w = mu.interface.main.Window()
    message = "foo"
    with mock.patch("mu.interface.main.QMessageBox", mock_qmb_class):
        w.show_confirmation(message)
    mock_qmb.setText.assert_called_once_with(message)
    mock_qmb.setWindowTitle.assert_called_once_with("Mu")
    assert mock_qmb.setInformativeText.call_count == 0
    mock_qmb.setIcon.assert_called_once_with(mock_qmb.Warning)
    mock_qmb.setStandardButtons.assert_called_once_with(
        mock_qmb.Cancel | mock_qmb.Ok
    )
    mock_qmb.setDefaultButton.assert_called_once_with(mock_qmb.Cancel)
    mock_qmb.exec.assert_called_once_with() 
Example #13
Source File: test_main.py    From mu with GNU General Public License v3.0 5 votes vote down vote up
def test_Window_show_confirmation(qtapp):
    """
    Ensure the show_confirmation method configures a QMessageBox in the
    expected manner.
    """
    mock_qmb = mock.MagicMock()
    mock_qmb.setText = mock.MagicMock(return_value=None)
    mock_qmb.setWindowTitle = mock.MagicMock(return_value=None)
    mock_qmb.setInformativeText = mock.MagicMock(return_value=None)
    mock_qmb.setIcon = mock.MagicMock(return_value=None)
    mock_qmb.Information = mock.MagicMock()
    mock_qmb.setStandardButtons = mock.MagicMock(return_value=None)
    mock_qmb.Cancel = mock.MagicMock()
    mock_qmb.Ok = mock.MagicMock()
    mock_qmb.setDefaultButton = mock.MagicMock(return_value=None)
    mock_qmb.exec = mock.MagicMock(return_value=None)
    mock_qmb_class = mock.MagicMock(return_value=mock_qmb)
    w = mu.interface.main.Window()
    message = "foo"
    information = "bar"
    icon = "Information"
    with mock.patch("mu.interface.main.QMessageBox", mock_qmb_class):
        w.show_confirmation(message, information, icon)
    mock_qmb.setText.assert_called_once_with(message)
    mock_qmb.setWindowTitle.assert_called_once_with("Mu")
    mock_qmb.setInformativeText.assert_called_once_with(information)
    mock_qmb.setIcon.assert_called_once_with(mock_qmb.Information)
    mock_qmb.setStandardButtons.assert_called_once_with(
        mock_qmb.Cancel | mock_qmb.Ok
    )
    mock_qmb.setDefaultButton.assert_called_once_with(mock_qmb.Cancel)
    mock_qmb.exec.assert_called_once_with() 
Example #14
Source File: controller.py    From artisan with GNU General Public License v3.0 5 votes vote down vote up
def disconnect_confirmed():
    string = QApplication.translate("Plus","Disconnect artisan.plus?", None)
    aw = config.app_window
    reply = QMessageBox.question(aw,QApplication.translate("Plus","Disconnect?", None),string,
                                QMessageBox.Ok | QMessageBox.Cancel)
    if reply == QMessageBox.Ok:
        return True
    else:
        return False 
Example #15
Source File: Messages.py    From DownloaderForReddit with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        """
        A small class to display an unfinished dialog message to the user.  It is made into its own class so the names
        of the buttons can be renamed to be better understood in the situation it is used in
        """
        QDialog.__init__(self)
        self.setupUi(self)

        self.button_box.button(QDialogButtonBox.Ok).setText('Close Anyway')
        self.button_box.button(QDialogButtonBox.Cancel).setText('Do Not Close')

        self.button_box.accepted.connect(self.accept)
        self.button_box.rejected.connect(self.close) 
Example #16
Source File: Messages.py    From DownloaderForReddit with GNU General Public License v3.0 5 votes vote down vote up
def restore_defaults_warning(self):
        text = 'Defaults have been restored. If you save now, any settings controlled from this window will be ' \
               'restored to their original values.\n\nAny user or subreddit who\'s custom settings have been changed ' \
               'will also be restored to their default values.\n\nDo you wish to proceed?'
        reply = message.warning(self, 'Defaults Restored', text, message.Ok, message.Cancel)
        return reply == message.Ok 
Example #17
Source File: Messages.py    From DownloaderForReddit with GNU General Public License v3.0 5 votes vote down vote up
def downloader_running_warning(self):
        text = 'The user finder is still currently running.  Closing now may cause unexpected behaviour and corrupted '\
               'files.  Are you sure you want to close?'
        reply = message.warning(self, 'User Finder Still Running', text, message.Ok, message.Cancel)
        return reply == message.Ok 
Example #18
Source File: Messages.py    From DownloaderForReddit with GNU General Public License v3.0 5 votes vote down vote up
def remove_subreddit_list(self):
        text = 'Are you sure you want to remove this list? Information for every subreddit in the list will be lost'
        reply = message.warning(self, 'Remove Subreddit List?', text, message.Ok, message.Cancel)
        return reply == message.Ok 
Example #19
Source File: Messages.py    From DownloaderForReddit with GNU General Public License v3.0 5 votes vote down vote up
def remove_user_list(self):
        text = 'Are you sure you want to remove this list? Information for every user in the list will be lost'
        reply = message.warning(self, 'Remove User List?', text, message.Ok, message.Cancel)
        return reply == message.Ok 
Example #20
Source File: version_layout.py    From Blender-Version-Manager with GNU General Public License v3.0 5 votes vote down vote up
def delete(self):
        msgBox = QMessageBox.question(
            self.parent, "Blender Version Manager",
            "Are you sure you want to delete\n'" + self.btnOpen.text() + "'?",
            QMessageBox.Yes | QMessageBox.Cancel, QMessageBox.Yes)

        if msgBox == QMessageBox.Yes:
            threading.Thread(target=lambda: asyncio.run(
                self.delete_tread())).start() 
Example #21
Source File: EditorWidget.py    From grap with MIT License 5 votes vote down vote up
def _onCloseClicked(self):
        text = self.text_widget.toPlainText()
        if text != self.saved_text:
            msg_box = QMessageBox(self)
            r = msg_box.question(self, 'Warning', ('The pattern has not been saved to file, close the editor anyway?'), QMessageBox.Yes | QMessageBox.Cancel, QMessageBox.Cancel)
            if r != QMessageBox.Yes:
                return

        index = self.parent.tabs.indexOf(self)
        self.parent.tabs.removeTab(index) 
Example #22
Source File: uamodeler.py    From opcua-modeler with GNU General Public License v3.0 5 votes vote down vote up
def try_close_model(self):
        if self._model_mgr.modified:
            reply = QMessageBox.question(
                self.modeler,
                "OPC UA Modeler",
                "Model is modified, do you really want to close model?",
                QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel
            )
            if reply != QMessageBox.Yes:
                return False
        self._model_mgr.close_model(force=True)
        return True 
Example #23
Source File: main_dlg.py    From dash-masternode-tool with MIT License 5 votes vote down vote up
def on_action_clear_proposals_cache_triggered(self, checked):
        if self.queryDlg('Do you really want to clear the proposals cache?',
                         buttons=QMessageBox.Yes | QMessageBox.Cancel,
                         default_button=QMessageBox.Cancel, icon=QMessageBox.Warning) == QMessageBox.Yes:
            db_cursor = self.app_config.db_intf.get_cursor()
            try:
                db_cursor.execute('drop table proposals')
                db_cursor.execute('drop table voting_results')
                self.app_config.db_intf.create_structures()
            finally:
                self.app_config.db_intf.release_cursor()
            self.infoMsg('Proposals cache cleared.') 
Example #24
Source File: main_dlg.py    From dash-masternode-tool with MIT License 5 votes vote down vote up
def on_action_clear_wallet_cache_triggered(self, checked):
        if self.queryDlg('Do you really want to clear the wallet cache?',
                         buttons=QMessageBox.Yes | QMessageBox.Cancel,
                         default_button=QMessageBox.Cancel, icon=QMessageBox.Warning) == QMessageBox.Yes:
            db_cursor = self.app_config.db_intf.get_cursor()
            try:
                db_cursor.execute('drop table address')
                db_cursor.execute('drop table hd_tree')
                db_cursor.execute('drop table tx_input')
                db_cursor.execute('drop table tx_output')
                db_cursor.execute('drop table tx')
                self.app_config.db_intf.create_structures()
            finally:
                self.app_config.db_intf.release_cursor()
            self.infoMsg('Wallet cache cleared.') 
Example #25
Source File: main_dlg.py    From dash-masternode-tool with MIT License 5 votes vote down vote up
def load_configuration_from_file(self, file_name: str, ask_save_changes = True,
                                     update_current_file_name = True) -> None:
        """
        Load configuration from a file.
        :param file_name: A name of the configuration file to be loaded into the application.
        """
        if self.app_config.is_modified() and ask_save_changes:
            ret = self.queryDlg('Current configuration has been modified. Save?',
                                buttons=QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel,
                                default_button=QMessageBox.Yes, icon=QMessageBox.Warning)
            if ret == QMessageBox.Yes:
                self.save_configuration()
            elif ret == QMessageBox.Cancel:
                self.update_config_files_mru_menu_items()
                return

        try:
            self.disconnect_hardware_wallet()
            dash_network_sav = self.app_config.dash_network
            self.app_config.read_from_file(hw_session=self.hw_session, file_name=file_name,
                                           update_current_file_name=update_current_file_name)
            self.editing_enabled = False
            self.configuration_to_ui()
            self.dashd_intf.reload_configuration()
            self.app_config.modified = False
            file_name = self.app_config.app_config_file_name
            if file_name:
                self.add_item_to_config_files_mru_list(file_name)
                self.update_config_files_mru_menu_items()
                if dash_network_sav != self.app_config.dash_network:
                    self.disconnect_hardware_wallet()
                    self.app_config.reset_network_dependent_dyn_params()
            self.display_window_title()
        except CancelException:
            self.update_config_files_mru_menu_items() 
Example #26
Source File: masternode_details.py    From dash-masternode-tool with MIT License 5 votes vote down vote up
def generate_priv_key(self, pk_type:str, edit_control: QLineEdit, compressed: bool):
        if edit_control.text():
            if WndUtils.queryDlg(
                    f'This will overwrite the current {pk_type} private key value. Do you really want to proceed?',
                     buttons=QMessageBox.Yes | QMessageBox.Cancel,
                     default_button=QMessageBox.Yes, icon=QMessageBox.Warning) != QMessageBox.Yes:
                return None

        if pk_type == 'operator':
            pk = dash_utils.generate_bls_privkey()
        else:
            pk = dash_utils.generate_wif_privkey(self.app_config.dash_network, compressed=compressed)
        edit_control.setText(pk)
        return pk 
Example #27
Source File: optimize5.py    From pyxll-examples with The Unlicense 4 votes vote down vote up
def optimize5():
    """
    Trigger optimization of a spreadsheet model that
    takes the named range "Inputs" as inputs and
    produces output in the named range "Output".
    """
    xl = xl_app()
    qt_app = get_qt_app()  # pragma noqc
    # Get the initial values of the input cells
    msgBox = OpDialog()
    result = msgBox.exec_()
    if not result:  # user cancelled
        return

    in_range = get_range(msgBox.in_range.text())
    out_cell = get_range(msgBox.out_cell.text())
    in_values = list(in_range.Value)
    X = np.array([x[0] for x in in_values])

    orig_calc_mode = xl.Calculation
    try:
        # switch Excel to manual calculation
        # and disable screen updating
        xl.Calculation = constants.xlManual
        xl.ScreenUpdating = False

        # run the minimization routine
        xl_obj_func = partial(obj_func, xl, in_range, out_cell)
        print(f"X = {X}")
        result = minimize(xl_obj_func, X, method="nelder-mead")
        in_range.Value = [(float(x),) for x in result.x]
        xl.ScreenUpdating = True
        mbox = QMessageBox()
        mbox.setIcon(QMessageBox.Information)
        mbox.setText("Optimization results shown below." "\nMake changes permanent?")
        mbox.setWindowTitle("Optimization Complete")
        mbox.setInformativeText(
            "\n".join(
                [
                    "Successful:       %s" % result.success,
                    result.message,
                    "After %d iterations" % result.nit,
                ]
            )
        )
        mbox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
        yes_no = mbox.exec_()
        if yes_no != QMessageBox.Ok:
            in_range.Value = in_values
        else:
            in_range.Value = [(float(x),) for x in result.x]

    finally:
        # restore the original calculation
        # and screen updating mode
        xl.ScreenUpdating = True
        xl.Calculation = orig_calc_mode 
Example #28
Source File: optimize4.py    From pyxll-examples with The Unlicense 4 votes vote down vote up
def optimize4():
    """
    Trigger optimization of a spreadsheet model that
    takes the named range "Inputs" as inputs and
    produces output in the named range "Output".
    """
    qt_app = get_qt_app()  # pragma noqc
    xl = xl_app()
    # Get the initial values of the input cells
    in_values = list(xl.Range("Inputs").Value)
    X = np.array([x[0] for x in in_values])

    orig_calc_mode = xl.Calculation
    try:
        # switch Excel to manual calculation
        # and disable screen updating
        xl.Calculation = constants.xlManual
        xl.ScreenUpdating = False

        # run the minimization routine
        xl_obj_func = partial(obj_func, xl)
        result = minimize(xl_obj_func, X, method="nelder-mead")
        xl.ScreenUpdating = True
        mbox = QMessageBox()
        mbox.setIcon(QMessageBox.Information)
        mbox.setText("Optimization results shown below." "\nMake changes permanent?")
        mbox.setWindowTitle("Optimization Complete")
        mbox.setInformativeText(
            "\n".join(
                [
                    "Successful:       %s" % result.success,
                    result.message,
                    "After %d iterations" % result.nit,
                ]
            )
        )
        mbox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
        yes_no = mbox.exec_()
        if yes_no != QMessageBox.Ok:
            xl.Range("Inputs").Value = in_values
        else:
            xl.Range("Inputs").Value = [(float(x),) for x in result.x]

    finally:
        # restore the original calculation
        # and screen updating mode
        xl.Calculation = orig_calc_mode 
Example #29
Source File: centralwidget.py    From autokey with GNU General Public License v3.0 4 votes vote down vote up
def on_new_topfolder(self):
        logger.info("User initiates top-level folder creation")
        message_box = QMessageBox(
            QMessageBox.Question,
            "Create Folder",
            "Create folder in the default location?",
            QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel,
            self.window()

        )
        message_box.button(QMessageBox.No).setText("Create elsewhere")  # TODO: i18n
        result = message_box.exec_()

        self.window().app.monitor.suspend()

        if result == QMessageBox.Yes:
            logger.debug("User creates a new top-level folder.")
            self.__createFolder(None)

        elif result == QMessageBox.No:
            logger.debug("User creates a new folder and chose to create it elsewhere")
            QMessageBox.warning(
                self.window(), "Beware",
                "AutoKey will take the full ownership of the directory you are about to select or create. "
                "It is advisable to only choose empty directories or directories that contain data created by AutoKey "
                "previously.\n\nIf you delete or move the directory from within AutoKey "
                "(for example by using drag and drop), all files unknown to AutoKey will be deleted.",
                QMessageBox.Ok)
            path = QFileDialog.getExistingDirectory(
                self.window(),
                "Where should the folder be created?"
            )
            if path != "":
                path = pathlib.Path(path)
                if list(path.glob("*")):
                    result = QMessageBox.warning(
                        self.window(), "The chosen directory already contains files",
                        "The selected directory already contains files. "
                        "If you continue, AutoKey will take the ownership.\n\n"
                        "You may lose all files in '{}' that are not related to AutoKey if you select this directory.\n"
                        "Continue?".format(path),
                        QMessageBox.Yes|QMessageBox.No) == QMessageBox.Yes
                else:
                    result = True
                if result:
                    folder = model.Folder(path.name, path=str(path))
                    new_item = ak_tree.FolderWidgetItem(None, folder)
                    self.treeWidget.addTopLevelItem(new_item)
                    self.configManager.folders.append(folder)
                    self.window().app.config_altered(True)

            self.window().app.monitor.unsuspend()
        else:
            logger.debug("User canceled top-level folder creation.")
            self.window().app.monitor.unsuspend() 
Example #30
Source File: logic.py    From mu with GNU General Public License v3.0 4 votes vote down vote up
def quit(self, *args, **kwargs):
        """
        Exit the application.
        """
        if self._view.modified:
            # Alert the user to handle unsaved work.
            msg = _(
                "There is un-saved work, exiting the application will"
                " cause you to lose it."
            )
            result = self._view.show_confirmation(msg)
            if result == QMessageBox.Cancel:
                if args and hasattr(args[0], "ignore"):
                    # The function is handling an event, so ignore it.
                    args[0].ignore()
                return
        paths = []
        for widget in self._view.widgets:
            if widget.path:
                paths.append(os.path.abspath(widget.path))
        # Make sure the mode's stop method is called so
        # everything is cleaned up.
        self.modes[self.mode].stop()
        session = {
            "theme": self.theme,
            "mode": self.mode,
            "paths": paths,
            "envars": self.envars,
            "minify": self.minify,
            "microbit_runtime": self.microbit_runtime,
            "zoom_level": self._view.zoom_position,
            "window": {
                "x": self._view.x(),
                "y": self._view.y(),
                "w": self._view.width(),
                "h": self._view.height(),
            },
        }
        session_path = get_session_path()
        with open(session_path, "w") as out:
            logger.debug("Session: {}".format(session))
            logger.debug("Saving session to: {}".format(session_path))
            json.dump(session, out, indent=2)
        # Clean up temporary mu.pth file if needed (Windows only).
        if sys.platform == "win32" and "pythonw.exe" in sys.executable:
            if site.ENABLE_USER_SITE:
                site_path = site.USER_SITE
                path_file = os.path.join(site_path, "mu.pth")
                if os.path.exists(path_file):
                    try:
                        os.remove(path_file)
                        logger.info("{} removed.".format(path_file))
                    except Exception as ex:
                        logger.error("Unable to delete {}".format(path_file))
                        logger.error(ex)
        logger.info("Quitting.\n\n")
        sys.exit(0)