def send_key_to_server(self, key: str): check = False msg = QMessageBox() msg.setIcon(QMessageBox.Information) try: sock = socket.socket() sock.settimeout(2) sock.connect((self.HOST, self.PORT)) data = json.dumps([self.current_machine_id, key]).encode("utf-8") sock.send(data) data = sock.recv(1024) sock.close() password = str(data, encoding="utf-8") if self.xor(self.current_machine_id, key) == password: self.set_activation(password=password, key=key) msg.setText("Активация успешно пройдена") check = True else: msg.setText("Ключ не верен или не действителен!") except Exception as E: print(E.args) # соединение разорвано msg.setText("Не удалось подключиться к серверу") msg.setWindowTitle("Активация") msg.exec_() if check is True: self.activationWindow.close() self.mainWindow.closed.disconnect(self.mainWindow_closed) self.mainWindow.show()
def aviso(txt): msg = QMessageBox() msg.setText(" Aviso ") msg.setInformativeText(txt) msg.setIcon(QMessageBox.Warning) msg.setStandardButtons(QMessageBox.Ok) msg.exec_()
def open_case(self): """ Gives the user a file dialog to find their existing project and opens that. :return: None """ open_dialog = QFileDialog() user_location = open_dialog.getOpenFileName()[ 0] # Index 0 because user can't pick more than one file. if user_location == '': return # User most likely pressed cancel. case = Case.open_from_disk(user_location) if case is None: # Something bad must have happened. Tell the user that the file is corrupt. Or invalid. alert = QMessageBox() alert.setText("Corrupt case file or invalid file type.") alert.setIcon(QMessageBox.Critical) alert.exec_() return else: # Successfully open a case! case_controller = CaseController(case) self.open_window(case_controller)
def btn_recog_clicked(self): self.update() savePath = "./recog.jpg" image = self.__canvas.get_current_image() image.save(savePath) save_path = os.path.abspath(savePath) self.label_log.append("image saved in path:\n{}".format(save_path)) method_text = self.__box_method.currentText() self.label_log.append('method: {}'.format(method_text)) predict = self.METHOD_KERNEL.set_kernel(savePath, method_text) # pic = QTextImageFormat() # pic.setName('./feature_map.jpg') # pic.setHeight(100) # pic.setWidth(100) showImage = QImage('./feature_map.jpg').scaled(100, 100) self.feature_map.setPixmap(QPixmap.fromImage(showImage)) # self.label_log.append('feature map:\n') # self.label_log.textCursor().insertImage('./feature_map.jpg') self.label_log.append("recognition result is: {}".format(predict)) # self.label_log.moveCursor(QTextCursor.End) # self.label_log.textCursor().clearSelection() # del pic message = QMessageBox() message.setText("recognition result is: {}".format(predict)) # message.addButton() message.exec_()
def ok_button_clicked(self): """Is executed when the OK button is clicked. Merges the two nodes.""" node_name1 = self.combo_node1.currentText() node_name2 = self.combo_node2.currentText() if node_name1 == node_name2: msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setText("Please select two different nodes") msg.setInformativeText( "It makes to sense to merge a node with itself") msg.setWindowTitle("Cannot merge") msg.exec_() return new_name = self.tf_new_name.text() if new_name == '': msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setText("Please provide the name for the resulting node.") msg.setInformativeText("The resulting node should have a name.") msg.setWindowTitle("No new name given") msg.exec_() return connection_mode = ConnectionMergeMode[ self.combo_connection_transfer_mode.currentText().upper()] global_properties = GlobalProperties.get_instance() global_properties.mpdj_data.merge_two_nodes_into_one( node_name1, node_name2, new_name, connection_mode) self.close()
def new_map(self): # метод класса Edit_Map, новая карта if (not self.input_col.text().isdigit() or not self.input_row.text().isdigit()) or \ (int(self.input_col.text()) < 14 or int(self.input_row.text()) < 14): # проверяем значения x, y. Если не числа, то выводим окно ошибки msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("Error") # текст окна msg msg.setWindowTitle("Error") # название окна msg msg.exec_() return self._col = int(self.input_col.text()) # запоминаем новое значение x self._row = int(self.input_row.text()) # запоминаем новое значение y self._sp_map = [[0 for i in range(self._col)] for j in range(self._row) ] # создаем список 0 по размерам x, y self.input_col.setVisible(False) # прячем строку для ввода x self.input_row.setVisible(False) # прячем строку для ввода y self.button_new_map.setVisible(False) # прячем кнопку "СОЗДАТЬ КАРТУ" edit_map.move_button( ) # Расширяем окно и меняем положение кнопок "ОТКРЫТЬ", "НАЗАД", "СОЗДАТЬ", "СОХРАНИТЬ" self.button_back.setVisible(True) # показываем кнопку "НАЗАД" self.button_save.setVisible(True) # показываем кнопку "СОХРАНИТЬ" self.button_open.setVisible(True) # показываем кнопку "ОТКРЫТЬ" self.button_create.setVisible(True) # показываем кнопку "СОЗДАТЬ" self.center() # отцентровываем окно относительно экрана for i in range( PIC ): # записываем в elem_map изображения из которых будет состоять карта self._elem_map.append(QPixmap()) self._elem_map[i].load(resource_path("PIC/" + str(i) + "_0.png")) self._flag_1 = True
def msgBox(self): msgBox = QMessageBox() msgBox.setWindowTitle("경고창") # 메세지창의 상단 제목 msgBox.setText("돌이 이미 있습니다") # 메세지 내용 msgBox.setStandardButtons(QMessageBox.Yes) msgBox.exec_() msgBox.show()
def display_info(self, text: str): message_box = QMessageBox() message_box.setIcon(QMessageBox.Information) message_box.setWindowTitle("Information") message_box.setText(text) message_box.setStandardButtons(QMessageBox.Ok) message_box.exec_()
def display_error(self, text: str): message_box = QMessageBox() message_box.setIcon(QMessageBox.Critical) message_box.setWindowTitle("Error") message_box.setText(text) message_box.setStandardButtons(QMessageBox.Ok) message_box.exec_()
def display_error(text: str): """Displays an error message to the user.""" message = QMessageBox() message.setIcon(QMessageBox.Critical) message.setWindowTitle("Error") message.setText(text) message.setStandardButtons(QMessageBox.Ok) message.exec_()
def lataaja(self, tiedosto): '''Hoitaa muuttujien lataamisen annetusta tiedostosta''' lataus = False try: '''Yrittää avata annetun tiedoston. Ilmoittaa jos tulee virhe''' file = open(tiedosto, "r") rivi = file.readline() rivi = rivi.strip() if rivi != "Lujuusanalysaattori": '''Kerrotaan käyttäjälle, että tiedosto oli virheellinen''' msgBox = QMessageBox() msgBox.setText("Tiedoston lukeminen ei onnistu: Virheellinen tiedosto") msgBox.setWindowTitle("Virhe") msgBox.setMinimumWidth(50) msgBox.addButton(QPushButton('OK'), QMessageBox.NoRole) msgBox.exec_() return lataus except FileNotFoundError: return lataus try: '''Ohitetaan päivämäärä''' rivi = file.readline() '''Luetaan arvot ja tallennetaan ne ominaisuudet luokan avulla''' '''Palkin pituus''' rivi = file.readline() Ominaisuudet.palkin_pituus(self, int(rivi)) '''Palkin pituuden yksikko''' rivi = file.readline() Ominaisuudet.yksikko(self, int(rivi)) '''Voiman suuruus''' rivi = file.readline() Ominaisuudet.voima(self, int(rivi)) '''Voiman yksikkö''' rivi = file.readline() Ominaisuudet.yksikko_voima(self, int(rivi)) '''Materiaali''' rivi = file.readline() Ominaisuudet.materiaali(self, int(rivi)) '''Tuen tyyppi''' rivi = int(file.readline()) Ominaisuudet.tuki(self, rivi) '''Onko ulkoinen voima asetettu 0=ei, 1=kyllä''' rivi = file.readline() Ominaisuudet.ulkoinen_voima(self, int(rivi)) return True except AttributeError: pass
def check(self): word = self.infEntry.text().upper() if word in self.wordList: msgBox = QMessageBox() msgBox.setText(word + ' already in dictionary') msgBox.exec_() else: msgBox = QMessageBox() msgBox.setText(word + ' not in dictionary yet') msgBox.exec_()
def tallenna_rakenne(self): '''Hoitaa rakenteen tallentamisen''' tallennus = Tallennin.tallenin(self) if tallennus == True: '''Kerrotaan käyttäjälle, että tallennus onnistui''' msgBox = QMessageBox() msgBox.setText("Tallennus onnistui!") msgBox.setWindowTitle("Onnistunut Tallennus") msgBox.setMinimumWidth(50) msgBox.addButton(QPushButton('OK'), QMessageBox.NoRole) msgBox.exec_()
def lataa_tallennettu_rakenne(self): '''Metodi avaa QFileDialog ikkunan, josta käyttäjä valitsee tiedoston, jossa aiemmin tallennettu rakenne sijaitsee. Vain .txt -tiedostot ovat ladattavissa ''' options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog tiedosto, _ = QFileDialog.getOpenFileName(self, "Valitse tiedosto", "", "txt Files (*.txt)", options=options) lataus = Lataaja.lataaja(self, tiedosto) if lataus == False: return if lataus == True: self.uusi_rakenne() Lataaja.lataaja(self, tiedosto) tuen_tyyppi = Ominaisuudet.palauta_tuen_tyyppi(self) '''Jos tuki on seinästä, piirretään sitä vastaava grafiikka''' if tuen_tyyppi == 0: self.nayta_seina_tuki() self.gradient_seina_tuki() '''Jos tuki on alhaalta, piirretään sitä vastaava grafiikka''' if tuen_tyyppi == 1: self.nayta_tuki_alhaalta() self.gradient_alatuki() if tuen_tyyppi != 2: self.vaihda_tuki.show() self.lisaa_tuki.hide() '''Jos ulkoinen voima on asetettu, piirretään se''' ulkoinen_voima = int( Ominaisuudet.onko_ulkoinen_voima_asetettu(self)) if ulkoinen_voima == 1: self.nayta_ulkoinen_voima() self.nayta_palkki() Laskin.laskin(self) self.paivita_tulos_teksti() self.tulos.show() self.sp.setValue(float(Ominaisuudet.palauta_palkin_pituus(self))) self.uusiAction.setEnabled(True) self.simuloi.setEnabled(True) '''Kerrotaan käyttäjälle, että kaikki onnistui''' msgBox = QMessageBox() msgBox.setText("Lataus onnistui!") msgBox.setWindowTitle("Onnistunut lataus") msgBox.addButton(QPushButton('OK'), QMessageBox.NoRole) msgBox.exec_()
def _saveFile(self, annotationFilePath): #self.canvas.overrideCursor(WAIT_CURSOR) error_info = self.checkShapes() if error_info is not None: msg = QMessageBox() msg.setIcon(QMessageBox.Warning) msg.setText("Save File Failed! Error:\n" + error_info) msg.exec_() return False if annotationFilePath and self.saveLabels(annotationFilePath): self.setClean() self.statusBar().showMessage('Saved to %s' % annotationFilePath) self.statusBar().show() return True
def step_dialog(parent, title, msg, det_msg=''): d = QMessageBox(parent) d.setWindowTitle(title) d.setText(msg) d.setStandardButtons(QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Cancel) return d.exec_() & QMessageBox.StandardButton.Cancel
def finish_check(self): if self.valid_book_ids: is_filesize_exceeded = len(self.valid_book_ids) < self.books_count is_total_books_exceeded = self.limits[ 'total_books'] and self.books_count > self.limits['total_books'] if is_filesize_exceeded or is_total_books_exceeded: if self.limits['message']: msg_box = QMessageBox(self) msg_box.setWindowTitle('BookFusion Sync') msg_box.addButton(QMessageBox.No) msg_box.addButton(QMessageBox.Yes) msg_box.setText(self.limits['message']) msg_box.setDefaultButton(QMessageBox.Yes) reply = msg_box.exec_() if reply == QMessageBox.Yes: self.start_sync() else: self.in_progress = False self.msg.setText('Canceled.') self.finish_sync() else: self.start_sync() else: self.start_sync() else: if self.in_progress: self.in_progress = False self.msg.setText('No supported books selected.') self.finish_sync()
def msgbox(cls, typename, text, button0, button1=None, button2=None, title=None, form=None): if form: logger.warn("MessageBox: Se intentó usar form, y no está implementado.") icon = QMessageBox.NoIcon if not title: title = "Pineboo" if typename == "question": icon = QMessageBox.Question if not title: title = "Question" elif typename == "information": icon = QMessageBox.Information if not title: title = "Information" elif typename == "warning": icon = QMessageBox.Warning if not title: title = "Warning" elif typename == "critical": icon = QMessageBox.Critical if not title: title = "Critical" # title = unicode(title,"UTF-8") # text = unicode(text,"UTF-8") msg = QMessageBox(icon, title, text) msg.addButton(button0) if button1: msg.addButton(button1) if button2: msg.addButton(button2) return msg.exec_()
def _save_dialog(self, parent, title, msg, det_msg=''): d = QMessageBox(parent) d.setWindowTitle(title) d.setText(msg) d.setStandardButtons(QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel) return d.exec_()
def save_mpdj_data_to_file(self, p_file_name: str): """Saves the current mpdj data to the file by the path given in p_file_name.""" try: global_properties = GlobalProperties.get_instance() global_properties.save_mpdj_data_to_file(p_file_name) self.statusBar().showMessage('Saved to {}'.format(p_file_name), 5000) except (OSError, IOError) as exception: message_box = QMessageBox() message_box.setText('Error saving the file: {}'.format( str(exception))) message_box.setWindowTitle('Error saving the file.') message_box.setStandardButtons(QMessageBox.Ok) message_box.setIcon(QMessageBox.Warning) message_box.exec_()
def show_messagebox(message, title, icon=QMessageBox.Information): msg_box = QMessageBox() msg_box.setIcon(icon) msg_box.setText(message) # msg_box.setInformativeText(message) msg_box.setWindowTitle(title) # msg_box.setDetailedText("The details are as follows:") msg_box.setStandardButtons(QMessageBox.Ok) retval = msg_box.exec_()
def _next_actions(self): try: # Clean Input a Bit # # Change variables to string type wav_files = [str(self._filenames_list.item(i).text()) for i in range(self._filenames_list.count())] output_directory = self._output_directory.text() network_location = self._network_location.text() # Substring network location to give true value needed network_location = network_location[0:network_location.rindex(".")] self._step2 = EvalWizardStep2Window(wav_files, output_directory, network_location) self._step2.show() self.close() except: msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("There was an error. Double check your input files and try again.") msg.setWindowTitle("Error") msg.exec_()
def message_box(self, text, informative, icon, buttons=QMessageBox.Ok): """Wraps up the QMessageBox""" msg = QMessageBox(self) msg.setStandardButtons(buttons) msg.setDefaultButton(QMessageBox.Ok) msg.setText(text) msg.setInformativeText(informative) msg.setIcon(icon) return msg.exec_()
def timeout(self): time_left = self.get_activation()[3] time_left -= 1 if time_left < 0: time_left = 0 self.set_activation(time_left=time_left) self.activationWindow.set_label_time(time_left) if time_left % 60 == 0 and time_left != 0: msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setText("У Вас осталось времени: {0} мин. {1} сек.".format(int(time_left/60), time_left % 60)) msg.setWindowTitle("Активация") msg.exec_() if time_left <= 0: self.timer.stop() self.activationWindow.pushFree.setEnabled(False) self.activationWindow.show() self.mainWindow.close()
def documentIsNotSave(parent): msgBox = QMessageBox(parent) msgBox.setWindowTitle('The document has been modified') msgBox.setText('The document has been modified') msgBox.setInformativeText('Do you want to save your change?') msgBox.setStandardButtons(QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel) msgBox.setDefaultButton(QMessageBox.Save) msgBox.setIcon(QMessageBox.Warning) return msgBox.exec_()
def file_load(self): """Loads mpdj data from a file. Opens a file dialog which asks for the file to load.""" global_properties = GlobalProperties.get_instance() file_name = self.file_dialog(load_save_type=QFileDialog.AcceptOpen) if file_name: if global_properties.changes_happened_since_last_save: retval = show_discard_data_ok_cancel_message() if not global_properties.changes_happened_since_last_save or retval == QMessageBox.Ok: try: global_properties.load_mpdjdata_from_file(file_name) except AttributeError as err: message_box = QMessageBox() message_box.setText( 'Error reading your MPDJ-File: {}'.format(err)) message_box.setWindowTitle('Load error.') message_box.setStandardButtons(QMessageBox.Ok) message_box.setIcon(QMessageBox.Warning) message_box.exec_()
def message_yes_no_cancel(self, question: str, yes: str, no: str) -> int: box = QMessageBox() box.setIcon(QMessageBox.Question) box.setWindowTitle("Photocopieuse") box.setText(question) box.setStandardButtons(QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel) btYes = box.button(QMessageBox.Yes) btYes.setText(yes) btNo = box.button(QMessageBox.No) btNo.setText(no) return box.exec_()
def show_discard_data_ok_cancel_message(): """Shows a QMessageBox to ask if the current mpdj data should be discarded. Contains an OK and an Cancel Button.""" msg = QMessageBox() msg.setIcon(QMessageBox.Question) msg.setText("You have unsaved changes in your current Data. Discard\ unsaved changes and proceed?") msg.setInformativeText("Unsaved changes will be lost.") msg.setWindowTitle("Unsaved changes") msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) retval = msg.exec_() return retval
def __init__(self, parent=None, window_title='Select a File', start_dir=os.getcwd(), *args): QFileDialog.__init__(self, parent, window_title, start_dir, *args) self.setWindowFlag(QtCore.Qt.WindowStaysOnTopHint) if sys.platform == 'darwin': self.setOption(QFileDialog.DontUseNativeDialog) self.data = None title = 'Select a csv file to plot' while True: self.file_path: str = self.getOpenFileName(self, title)[0] if self.file_path[-3:] == 'csv': with open(file=self.file_path, mode='r') as csvfile: self.data = csvfile.read() break elif self.file_path == "": break else: dialog = QMessageBox(icon=QMessageBox.Warning) dialog.setText('Please, select a csv file!') dialog.exec_() dialog.show() continue
def close_application(self, event): """ Opens a message box to handle program exit properly asking the user if the project should be saved first. Args: event(`QCloseEvent`): A QCloseEvent Returns: status_code (`int`): 0 when process finished correctly, otherwise >0 """ self.settings.setValue('display_on_startup', self.qi.display_on_startup) msg_box = QMessageBox() msg_box.setWindowIcon( QtGui.QIcon( resource_path( os.path.join("ui", "icons", "pyIMD_logo_icon.ico")))) msg_box.setWindowTitle('pyIMD :: Quit Program') msg_box.setText( 'Do you want to save changes before quitting the program?') save_btn = QPushButton('Save') save_btn.setIcon(QApplication.style().standardIcon( QStyle.SP_DialogSaveButton)) msg_box.addButton(save_btn, QMessageBox.YesRole) no_save_btn = QPushButton('Don\'t save') no_save_btn.setIcon(QApplication.style().standardIcon( QStyle.SP_DialogNoButton)) msg_box.addButton(no_save_btn, QMessageBox.NoRole) abort_btn = QPushButton('Cancel') abort_btn.setIcon(QApplication.style().standardIcon( QStyle.SP_DialogCancelButton)) msg_box.addButton(abort_btn, QMessageBox.RejectRole) ret = msg_box.exec_() if ret == 0: self.save_project() if not event: self.close() else: event.accept() elif ret == 1: if not event: self.close() else: event.accept() else: self.print_to_console("Program quit aborted") if not event: return else: event.ignore()
def select_load_dataset_mode(self): box = QMessageBox() box.setIcon(QMessageBox.Question) box.setWindowTitle('load seed') box.setText( "Please Select the way to load the seed, " "you can load in new config or load in current config (will overwrite current seeds)!" ) box.setStandardButtons(QMessageBox.Ok | QMessageBox.No | QMessageBox.Cancel) creat_config = box.button(QMessageBox.Ok) creat_config.setText('New') replace_config = box.button(QMessageBox.No) replace_config.setText('Replace') box.exec_() if box.clickedButton() == creat_config: self.on_createConfig_clicked() self.load_seeds(seed_path=self.ui.seedPath.text()) elif box.clickedButton() == replace_config: self.load_seeds(seed_path=self.ui.seedPath.text()) else: self.ui.seedPath.setText('')
def _save_dialog(self, parent, title, msg, det_msg=''): d = QMessageBox(parent) d.setWindowTitle(title) d.setText(msg) d.setStandardButtons(QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel) return d.exec_()
def step_dialog(parent, title, msg, det_msg=''): d = QMessageBox(parent) d.setWindowTitle(title) d.setText(msg) d.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) return d.exec_() & QMessageBox.Cancel