def convert(self): ''' Converts the input file and writes to the output file. ''' input_path = self.input_path.text() # Should be set below when opening input the file. output_path = self.output_path.text() try: input_path, output_path = validate(input_path, output_path) except OutputExistsError as e: # E128 Technically this should be indented more, but I feel that # hurts readability in this case. overwrite = QMessageBox.warning(self, self.tr('JWPCE conversion'), self.tr('The output file already exits. Overwrite it?'), QMessageBox.Yes | QMessageBox.No) # noqa: E128 if overwrite == QMessageBox.No: return except ValidateError as e: QMessageBox.warning(self, self.tr('JWPCE conversion'), self.tr(str(e)), QMessageBox.Ok) return # TODO - add in some kind of progress indicator? contents = read_file(input_path) write_file(output_path, contents) QMessageBox.information(self, self.tr('JWPCE conversion'), self.tr('The conversion is complete.'), QMessageBox.Ok)
def saveRecord(self, where): ''' Method saves the current row in the self.mapper and moves the data model cursor to a given location. ''' if self.sppLineEdit.text() == "": QMessageBox.warning(self, "Warning", "You must enter a species name!", QMessageBox.Ok) return # Get the current index and submit changes to the underlying model row = self.mapper.currentIndex() self.mapper.submit() # Move the data model cursor to a given location if where == ObservationDialog.FIRST: row = 0 elif where == ObservationDialog.PREV: row = 0 if row <= 1 else row - 1 elif where == ObservationDialog.NEXT: row += 1 if row >= self.model.rowCount(): row = self.model.rowCount() - 1 elif where == ObservationDialog.LAST: row = self.model.rowCount() - 1 self.mapper.setCurrentIndex(row)
def on_pushButtonEnviar_clicked(self): sCF = self.lineEditQtdCF.text() # recebe Quantidade de Cupom Fiscal do LineEdit sItem = self.lineEditQtdItem.text() # recebe Quantidade de Item do LineEdit regAlterarValor_Daruma("ECF\\RetornarAvisoErro","1") iRetornoAbrir = iCFAbrirPadrao_ECF_Daruma() if (iRetornoAbrir == 1): for cf in range(1,sCF): iCFAbrirPadrao_ECF_Daruma() for item in range(1,sItem): #QMessageBox.information(self,"DarumaFramework - Python/Qt","Entrou no vender") iRetorno = iCFVender_ECF_Daruma("I1","1,00","1,00","D$","0,00","123456789012","UN","ITEM") iCFTotalizarCupomPadrao_ECF_Daruma() iCFEfetuarPagamentoPadrao_ECF_Daruma() iCFEncerrar_ECF_Daruma("0","Teste de Venda de Item Sem Parar. Mensagem Promocional com até 8 linhas!") QMessageBox.information(self,"DarumaFramework - Python/Qt","Processo Concluido.") if (iRetornoAbrir != 1): tratarRetornoFiscal(iRetornoAbrir, self) QMessageBox.warning(self,"DarumaFramework - Python/Qt","Erro Primeira Venda. Cancelando Processo") iCFCancelar_ECF_Daruma() if ((sCF == "") and (sItem =="")): QMessageBox.information(self,"DarumaFramework - Python/Qt","Preencha todos os campos!")
def sendCommand(self): try: command = Command(self.commandInput.text()) self.radio.send(command) self.commandInput.clear() except exceptions.InvalidCommandError as exception: QMessageBox.warning(self, 'Invalid Command', str(exception))
def setData( self, index, value, role ): if ( not index.isValid() ): return False if( role == Qt.EditRole ): grid = self._data[index.row()] column = GridManagerColumns.Columns[index.column()] # Are we editing the column Name? if( column == GridManagerColumns.Name ): # Has the name changed? if( value == getattr(grid, column.name) ): # Then we got nothing to do here return True else: # we need to check if the new name is already in use is_new_name_already_used = False for grid_plane in self._data: if( grid_plane.name == value ): is_new_name_already_used = True break # We can't allow two equal names, because they are used as the primary key in the list of the VoxelGrid class. if( is_new_name_already_used ): QMessageBox.warning( None, "Zoxel", "The new name is already in use by another grid. Try a different name." ) return False # In a normal scenario, we just pass the value to the GridPlane object setattr(grid, column.name, value ) # Emitting a dataChanged signal, so that it reflects in the view self.dataChanged.emit(index, index) # And we also call GLWidget.refresh to send the new data to the OpenGL area. self._voxel_widget.refresh() return True else: return False
def delete(self): if(self.get_item(self.tree.currentItem()).parent == None): QMessageBox.warning(None, 'cannot delete the root node', 'cannot delete the root node') return delete(self.get_item(self.tree.currentItem())) self.tree.currentItem().parent().removeChild(self.tree.currentItem())
def on_Enviar_clicked(self): if ((self.lineEditValor.text()=="")): QMessageBox.warning(self,"DarumaFramework - Qt C++","Preencha todos os Campos!") else: StrValor = self.lineEditValor.text() tratarRetornoDUAL(regPortaComunicacao_DUAL_DarumaFramework(StrValor), self)
def submit_data(self): self._model.insertRow(0) data = self.extract_input() for key,val in data.items(): self._model.setData(self._model.index(0, self.column[key]), val) # try to commit a record if not self._model.submitAll(): self.log.error(self._model.lastError().text()) message = unicode("Erro de transação\n\n""Não foi possível salvar no banco de dados".decode('utf-8')) QMessageBox.critical(self, "Seareiros - Cadastro de Atividade", message) return False else: # successfully added an associate, adding it's activities activities = self.extract_activities_input() error = False if len(activities) > 0: associate_id = self.get_added_record().value("id") for id in activities: self._act_model.insertRow(0) self._act_model.setData(self._act_model.index(0, 0), associate_id) self._act_model.setData(self._act_model.index(0, 1), id) ok = self._act_model.submitAll() if not ok: error = True self.log.error(self._act_model.lastError().text()) if not error: message = unicode("Sucesso!\n\n""O associado foi salvo com êxito no banco de dados".decode('utf-8')) QMessageBox.information(self, "Seareiros - Cadastro de Associado", message) else: message = unicode("Erro\n\n""Associado cadastrado, " "porém ocorreu um problema ao salvar suas atividades".decode('utf-8')) QMessageBox.warning(self, "Seareiros - Cadastro de Associado", message) return True
def submit_data(self): data = self.extract_input() # checking fields that aren't inserted yet for val, model in [ ("author", self._author_model), ("s_author", self._s_author_model), ("publisher", self._publisher_model), ]: if isinstance(data[val], unicode): # needs to be inserted model.insertRow(0) model.setData(model.index(0, 1), data[val]) data[val] = submit_and_get_id(self, model, self.log) if not data[val]: # won't proceed if this fails return False # filling a book row self._model.insertRow(0) for key, val in data.items(): self._model.setData(self._model.index(0, self.column[key]), val) book_id = submit_and_get_id(self, self._model, self.log) if book_id: # for use in selection docks self.setBookId(book_id) # book sucessfully added, now associating related subjects subjects, new_subjects = self.extract_subjects_input() for subj in new_subjects: self._subject_model.insertRow(0) self._subject_model.setData(self._subject_model.index(0, 1), subj) id = submit_and_get_id(self, self._subject_model, self.log) if not id: # issue saving new subject return False subjects.append(int(id)) # associating book and it's subjects error = False for subj_id in subjects: self._book_in_subj_model.insertRow(0) self._book_in_subj_model.setData(self._book_in_subj_model.index(0, 0), book_id) self._book_in_subj_model.setData(self._book_in_subj_model.index(0, 1), subj_id) ok = self._book_in_subj_model.submitAll() if not ok: error = True break if error: self.log.error(self._book_in_subj_model.lastError.text()) message = unicode( "Erro\n\n" "Livro cadastrado, porém ocorreu um problema ao" " salvar os temas a que está associado".decode("utf-8") ) QMessageBox.warning(self, "Seareiros - Cadastro de Livro", message) return False else: message = unicode("Sucesso!\n\n" "O livro foi salvo com êxito no banco de dados".decode("utf-8")) QMessageBox.information(self, "Seareiros - Cadastro de Livro", message) return True # failed to insert a row return False
def submit_data(self): # I should block empty orders I guess if len(self._product_list) == 0: message = unicode( "Venda vazia!\n\n" "" "É necessário adicionar um produto antes de concluir uma venda".decode("utf-8") ) QMessageBox.critical(self, "Seareiros - Vendas do Bazar", message) self.edProductName.setFocus() return False data = self.extract_input() # filling a product order self._model.insertRow(0) for key, val in data.items(): self._model.setData(self._model.index(0, self.column[key]), val) order_id = submit_and_get_id(self, self._model, self.log) if order_id: # order creation success, placing items error = False for item in self._product_list: product_name = item[0] product_price = item[1] product_quantity = item[2] self._items_model.insertRow(0) self._items_model.setData(self._items_model.index(0, 1), order_id) self._items_model.setData(self._items_model.index(0, 2), product_name) self._items_model.setData(self._items_model.index(0, 3), product_price) self._items_model.setData(self._items_model.index(0, 4), product_quantity) ok = self._items_model.submitAll() if not ok: error = True break if error: self.log.error(self._items_model.lastError().text()) message = unicode( "Erro\n\n" "Venda registrada e contabilizada, porém ocorreu um problema e" " não será possível visualizar seus itens.".decode("utf-8") ) QMessageBox.warning(self, "Seareiros - Vendas do Bazar", message) return False else: # all went fine # retrieving some brief info of the order to display at the main window if "associate" in data: desc = "Venda do bazar no valor de R$ %s para %s" % ( self._locale.toString(data["total"], "f", 2).replace(".", ""), self.lblNickname.text(), ) else: desc = "Venda do bazar no valor de R$ %s" % self._locale.toString(data["total"], "f", 2).replace( ".", "" ) if not log_to_history(self._model.database(), "venda_bazar", order_id, desc): self.log.error(self._model.lastError().text()) message = unicode("Sucesso!\n\n" "Venda concluída.".decode("utf-8")) QMessageBox.information(self, "Seareiros - Vendas do Bazar", message) return True # failed to insert a row return False
def on_pushButtonEnviar_clicked(self): if ((self.comboBoxTipo.currentIndex() == 0 ) and (self.lineEditValor.text() == "") and (self.lineEditSeparador.text() == "")): QMessageBox.warning(self, "DarumaFramework - Python/Qt","Preencha todos os Campos!") else: StrTipo = self.comboBoxTipo.currentText() StrValor = self.lineEditValor.text() StrSeparador = self.lineEditSeparador.text() tratarRetornoFiscal(confCadastrar_ECF_Daruma(StrTipo,StrValor,StrSeparador), self)
def connectToExistingApp(self): if len(sys.argv)>1 and sys.argv[1] is not None: self.m_socket.write(sys.argv[1]) self.m_socket.bytesWritten.connect(self.quit) else: QMessageBox.warning(None, self.tr("Already running"), self.tr("The program is already running.")) # Quit application in 250 ms QTimer.singleShot(250, self.quit)
def load_model(self, modelname): ''' Loads a specific database model and sets it to view. ''' try: model = self.models.get_model(modelname) except NotImplementedError, e: QMessageBox.warning(self, "Database model", "Database Model Error: %s" % str(e)) return
def open_dialog(self): dialog = Dialog() if dialog.exec_(): # If dialog returns True (accept) self.label1.setText("SpinBox value is " + str(dialog.spin_box.value())) self.label2.setText("CheckBox is " + str(dialog.check_box.isChecked())) else: # Dialog rejected QMessageBox.warning(self, "Warning", "Dialog canceled")
def _onRemove(self): selection = self._lst_available.selectionModel().selection().indexes() if len(selection) == 0: QMessageBox.warning(self, "Queue", "Select an options") return model = self._lst_available.model() for row in sorted(map(methodcaller('row'), selection), reverse=True): model.popOptions(row)
def on_pushButtonEnviar_clicked(self): if ((self.lineEditLocal.text()=="") or (self.lineEditTexto.text()=="") or (self.lineEditSegundos.text()=="")): QMessageBox.warning(self,"DarumaFramework - Python/Qt","Preencha todos os Campos!") else: Local = self.lineEditLocal.text() Texto = self.lineEditTexto.text() Segundos = self.lineEditSegundos.text() tratarRetornoDUAL(iAutenticarDocumento_DUAL_DarumaFramework(Texto, Local,Segundos), self)
def _onRemove(self): selection = self._tbl_layers.selectionModel().selection().indexes() if len(selection) == 0: QMessageBox.warning(self, "Layer", "Select a row") return model = self._tbl_layers.model() for row in sorted(map(methodcaller('row'), selection), reverse=True): model.removeRow(row)
def load_device_action(self): try: dumpey.attached_devices() self.mainview.load_apk_from_device() except Exception: print '-'*60 traceback.print_exc(file=sys.stdout) print '-'*60 QMessageBox.warning(self, "Error", "No device has been detected. Are you sure an Android device is connected? Make sure adb is on your path.") return
def __CheckForExistenceOfVideoFiles(self): if Progress.statuses['NoVideoFilesFound'] == True: Progress.statuses['NoVideoFilesFound'] = 0 QMessageBox.warning(self, 'Warning', "There were no video files ending with the video file type(s) of \"{}\" located " "in the specified source directory. Please verify the file extensions of your " "videos and try again.".format(self.target.qleVideoTypes.text()) , QMessageBox.Ok) self.target.ResetStats() self.target.EnableGuiElements() self.target.qlProcessingSpeed.setText("")
def addawordtodb(self): eng = self.dlg.lineEdit.text() tam = self.dlg.lineEdit_2.text() if len(eng) != 0 and len(tam) != 0: cur.execute("INSERT INTO ENGTAM(ENGW, TAMW) VALUES(?, ?)", (eng, tam, )) self.dlg.close() QMessageBox.information(self, "Nigandu Eng -> Tam Dictionary", "Added Successfully. . .") else: self.dlg.lineEdit.setFocus() self.dlg.close() QMessageBox.warning(self, "Nigandu Eng -> Tam Dictionary", "Invalid Entry. . .")
def start(self): try: x, y = getGraph(self.host.text(), self.plotType) if None == x or None == y: return self.plotWidget.plot(x, y) self.updateTimer.start(1000) except UnicodeError, e: QMessageBox.warning(self, u'Ошибка', u'Проверь IP адрес')
def main(): app = QApplication(sys.argv) if not ei.initialized: msg = QCoreApplication.translate( pkginfo.package_name, "Dependencies of '{0}' are not ready. \n\n".format(pkginfo.package_name) + "Test 'initialized' value in '_easy_import_' to find the reason.") QMessageBox.warning(None, pkginfo.package_name, msg) return sys.exit(app.exec_()) window = MyMain() obj1 = IComboEntry("Entry without text") obj2 = Aggregate() combo_entry2 = IComboEntry("Entry with text2") combo_entry2.setObjectName("Combo Entry 2") obj2.add(combo_entry2) itext2 = IText2("This is a text for label 2") itext2.setObjectName("IText 2 (IText2)") obj2.add(itext2) obj3 = Aggregate() combo_entry3 = IComboEntry("Entry with text 1 and text 2") combo_entry3.setObjectName("Combo Entry 3") obj3.add(combo_entry3) itext31 = IText1("I love PySide!") itext31.setObjectName("IText 3 - 1 (IText1)") obj3.add(itext31) itext32 = IText2("There are software companies...") itext32.setObjectName("IText 3 - 2 (IText2)") obj3.add(itext32) obj4 = Aggregate() combo_entry4 = IComboEntry("Entry with text 1 and text 3") combo_entry4.setObjectName("Combo Entry 4") obj4.add(combo_entry4) itext41 = IText1("Some text written here.") itext41.setObjectName("IText 4 - 1 (IText1)") obj4.add(itext41) itext42 = IText3("I'm a troll.") itext42.setObjectName("IText 4 -2 (IText3") obj4.add(itext42) # the API takes IComboEntries, so we convert them to it # the MyMain objects takes the ownership of the whole aggregations window.add(aggregation.query(obj1, IComboEntry)) window.add(aggregation.query(obj2, IComboEntry)) window.add(aggregation.query(obj3, IComboEntry)) window.add(aggregation.query(obj4, IComboEntry)) window.show() app.exec_()
def on_pushButtonEnviar_clicked(self): # Definiçao do Tamanho do Vetor de Recebimento da informação cRetorno = create_string_buffer(100) iIndice = self.comboBoxIndice.currentIndex() if(self.comboBoxIndice.currentIndex()==0): QMessageBox.warning(self,"DarumaFramework - Python/Qt","Selecione o Indice!") else: # Execuçao do Método de Retorno da Informação*** */ tratarRetornoFiscal(rInfoEstendida_ECF_Daruma(iIndice,cRetorno),self) StrRetorno = cRetorno # Devolve o retorno da DLL para o campo de texto QMessageBox.information(self,"DarumaFramework - Python/Qt","Informaçao: "+ StrRetorno)
def addEnvelope(self): env_name = self.__ui.leNewEnvelope.text().strip().lower() if env_name in (v.name.lower() for v in self.__envMgr.envelopes.values()): QMessageBox.warning(self, "Warning", "Envelope with given name already exists") return try: env = self.__envMgr.addEnvelope(env_name, u'some envelope description here') self.addRowForEnvelope(env) self.__ui.leNewEnvelope.setText('') self.setupAutoCompletion() except Exception as e: logging.exception("Error while adding envelope")
def displayBatteryStatus(self, status): if status == QSystemDeviceInfo.BatteryCritical: msg = " Battery is Critical (4% or less), please save your work or plug in the charger." QMessageBox.critical(self, "QSystemInfo", msg) elif status == QSystemDeviceInfo.BatteryVeryLow: msg = "Battery is Very Low (10%), please plug in the charger soon" QMessageBox.warning(self, "QSystemInfo", msg); elif status == QSystemDeviceInfo.BatteryLow: msg = "Battery is Low (40% or less)"; QMessageBox.information(self, "QSystemInfo", msg) elif status == QSystemDeviceInfo.BatteryNormal: msg = "Battery is Normal (greater than 40%)"; QMessageBox.information(self, "QSystemInfo", msg)
def save(self, filename=None): ''' Saves the current model with the given filename. @param filename: Filename to save the model to @type filename: str ''' try: self.sbmlModel.save(filename) self.Dirty = False except Exception, e: QMessageBox.warning(self.networkView, "Filename is not valid.", "Please, try to select another filename.") logging.warning("Selected an invalid filename: %s\nException: %s" % (filename, e))
def focusOutEvent(self, event): #Override if self.text() == '': Progress.statuses['DirectoryChanged'] = True QLineEdit.focusOutEvent(self, event) return fm = FileManip() if fm.VerifyExists(self.text()) != True: QMessageBox.warning(self, 'Error', "The path you specified cannot be located.\n\n Could not find: \"{}\"".format(self.text()), QMessageBox.Ok) self.setFocus() return Progress.statuses['DirectoryChanged'] = True QLineEdit.focusOutEvent(self, event)
def accept(self): if len(self.id_lineedit.text().strip()) == 0: QMessageBox.warning(self, "Error: Relief Device ID Blank", "The relief device must be given an ID.", QMessageBox.Ok) self.id_lineedit.setFocus() return selected_area = self.area_combobox.itemData(self.area_combobox.currentIndex()) for device in selected_area.children: if device.name == self.id_lineedit.text(): QMessageBox.warning(self, "Error: Relief Device ID Already Exists", "Cannot add relief device because that relief device ID already exists. Please create a new relief device ID.", QMessageBox.Ok) self.id_lineedit.setFocus() self.id_lineedit.setSelection(0, self.id_lineedit.maxLength()) return QDialog.accept(self)
def _onModelRemove(self): models = self._tbl_model.currentModels() if len(models) == 0: QMessageBox.warning(self, "Model", "Select a row") return cb_model = self._cb_model.model() for model in models: cb_model.add(model) # Show model in combo box self._tbl_model.removeModel(model) if self._cb_model.currentIndex() < 0: self._cb_model.setCurrentIndex(0)
def _onAddToQueue(self): selection = self._lst_available.selectionModel().selection().indexes() if len(selection) == 0: QMessageBox.warning(self, "Queue", "Select an options") return model = self._lst_available.model() for row in sorted(map(methodcaller('row'), selection), reverse=True): options = model.options(row) try: self._runner.put(options) except Exception as ex: messagebox.exception(self, ex) return
def _updateOntology_(self, ontology): """ QT Slot which handles the update ontology action when it is triggered. Parameter : - ontology : The ontology to update. """ if not ontology is None and ontology.url is None: QMessageBox.warning( self, "Can not perform an update.", "The ontology " + ontology.name + " has no url specified in it's configuration to perform an update.", QMessageBox.Ok, QMessageBox.Ok) return update( ontology, lambda x: RWWidget.SyntaxController.add_ontology( ontology, newversion=x.getvalue().decode('utf8'))) self.synchronize()
def guiMessage(self, title, msg, show=False): '''guiMessage(title, msg, show=False) Handle op related GUI messages to user''' if msg is not None: self.guiMsgs.append((title, msg)) if show is True: if FreeCAD.GuiUp and len(self.guiMsgs) > 0: # self.guiMsgs.pop(0) # remove formatted place holder. from PySide.QtGui import QMessageBox # from PySide import QtGui for entry in self.guiMsgs: (title, msg) = entry QMessageBox.warning(None, title, msg) # QtGui.QMessageBox.warning(None, title, msg) self.guiMsgs = [] # Reset messages return True # Types: information, warning, critical, question return False
def view_tx_detail(self, height, tx_id): if height > 0: transfers = self.ui.wallet_rpc_manager.rpc_request.get_transfers( filter_by_height=True, min_height=height - 1, max_height=height) else: transfers = self.ui.wallet_rpc_manager.rpc_request.get_transfers( tx_pending=True, tx_in_pool=True) tx = self._find_tx(transfers, tx_id, self.ui.target_height) if not tx: self.on_tx_detail_found_event.emit('{"status": "ERROR"}') QMessageBox.warning( self.ui, "Transaction Details", "Transaction id: %s <br><br>not found!" % tx_id) return self.on_tx_detail_found_event.emit(json.dumps(tx))
def log(msg, level, msgbox=False, parent="auto", stack=None): """docstring for error""" if stack is None: stack = inspect.stack()[1][0] #print inspect.stack() #print stack #print inspect.getmodule(stack) if inspect.getmodule(stack) is None: mod = inspect.stack()[1][1] else: mod = inspect.getmodule(stack).__name__ lineno = stack.f_lineno if mod == "__main__": mod = "__main__:" + os.path.basename(__main__.__file__) logging.log(level, msg, extra={"mod": mod, "line": lineno}) if msgbox: if parent == "auto": qapp = QApplication.instance() if qapp is None: qapp = QApplication([]) qapp.setStyle(QStyleFactory.create("plastique") ) palette = QPalette(QColor(62, 62, 62), QColor(62, 62, 62)) palette.setColor(palette.Highlight, QColor(255*0.6, 198*0.6, 0)) qapp.setPalette(palette) parent = qapp.activeWindow() if level == logging.DEBUG: QMessageBox.info(parent, logging.getLevelName(level).capitalize(), msg) elif level == logging.INFO: QMessageBox.information(parent, logging.getLevelName(level).capitalize(), msg) elif level == logging.WARNING: QMessageBox.warning(parent, logging.getLevelName(level).capitalize(), msg) elif level == logging.ERROR: QMessageBox.critical(parent, logging.getLevelName(level).capitalize(), msg) elif level == logging.CRITICAL: QMessageBox.critical(parent, logging.getLevelName(level).capitalize(), msg)
def showPluginLoadError(pluginRef, unloading=False): doing = "loading" loadError = pluginRef.loadError if unloading: doing = "unloading" loadError = pluginRef.unloadError if loadError[0] == ImportError: if 'pymclevel' in loadError[1].message: QMessageBox.warning(None, ("MCEdit 1.0 Filters not supported"), ( "The file `{filename}` is an MCEdit 1.0 filter, which cannot be used in this version of MCEdit.\n\nRemove it from your plugins folder to avoid this error." ).format(filename=os.path.basename(pluginRef.filename))) return showErrorDialog("%s while %s plugin \"%s\"" % (loadError[0].__name__, doing, pluginRef.displayName), loadError, fatal=False, report=False)
def validate(self, text_input, parent=None): if self._msgbox: return False if len(text_input) == 0: if len(self._name): msg = "The input for {0} is empty! Please enter a number between {1} and {2}".format( self._name, self._lower, self._upper) else: msg = "The input is empty! Please enter a number between {0} and {1}".format( self._lower, self._upper) self._msgbox = True QMessageBox.warning(parent, "Warning", msg) self._msgbox = False return False try: num = float(text_input) except ValueError: if len(self._name): msg = "Invalid input for {0}! Please enter a number between {1} and {2}".format( self._name, self._lower, self._upper) else: msg = "Invalid input! Please enter a number between {0} and {1}".format( self._lower, self._upper) self._msgbox = True QMessageBox.warning(parent, "Warning", msg) self._msgbox = False return False if num < self._lower: if len(self._name): msg = "Invalid input for {0}! Please enter a number greater or equal to {1}".format( self._name, self._lower) else: msg = "Invalid input! Please enter a number greater or equal to {0}".format( self._lower) self._msgbox = True QMessageBox.warning(parent, "Warning", msg) self._msgbox = False return False elif num > self._upper: if len(self._name): msg = "Invalid input for {0}! Please enter a number less or equal to {1}".format( self._name, self._upper) else: msg = "Invalid input! Please enter a number less or equal to {0}".format( self._upper) self._msgbox = True QMessageBox.warning(parent, "Warning", msg) self._msgbox = False return False else: return True
def updateStrategy(self): """Updates a strategy.""" old_func = self.selectedTitles( self.ui.listWidgetStrategy.selectedItems()) new_func = str(self.ui.lineEditStrategy.text()) if len(old_func) != 1: QMessageBox.warning( self, self.tr('Update'), self.tr('Please select just one item to update.'), QMessageBox.Ok) elif new_func != '': if self.updateQuestion("Strategy", (old_func[0], new_func)) == QMessageBox.Yes: self.container.update(strategy=[(new_func, old_func[0])]) self.showMessageOnStatusBar( 'Strategy "{}" was updated to "{}".'.format( old_func[0], new_func)) self.updateStrategyView()
def on_Enviar_clicked(self): if ((self.lineEditIndice.text() == "") and (self.lineEditTipo.text() == "")): QMessageBox.warning(self, "DarumaFramework - Python/Qt", "Preencha todos os Campos!") else: # Definiçao do Tamanho do Vetor de Recebimento da informação impressoraStatus = create_string_buffer(32) StrIndice = self.lineEditIndice.text() StrTipo = self.lineEditTipo.text() tratarRetornoDUAL( rConsultaStatusImpressora_DUAL_DarumaFramework( StrIndice, StrTipo, impressoraStatus), self) StrStatus = impressoraStatus.decode('utf-8') # Devolve o retorno da DLL para o campo de texto QMessageBox.information(self, "DarumaFramework - Python/Qt", "Status: " + StrStatus)
def updateSection(self): """Updates old section with new section.""" old_sec = self.selectedTitles( self.ui.listWidgetSection.selectedItems()) new_sec = str(self.ui.lineEditSection.text()) if len(old_sec) != 1: QMessageBox.warning( self, self.tr('Update'), self.tr('Please select just one item to update.'), QMessageBox.Ok) elif new_sec != '': if self.updateQuestion("Section", (old_sec[0], new_sec)) == QMessageBox.Yes: self.container.update(section=[(new_sec, old_sec[0])]) self.showMessageOnStatusBar( 'Section "{}" was updated to "{}".'.format( old_sec[0], new_sec)) self.updateSectionView()
def updateComponent(self): """Updates one component.""" old_subs = self.selectedTitles( self.ui.listWidgetComponent.selectedItems()) new_subs = str(self.ui.lineEditComponent.text()) if len(old_subs) != 1: QMessageBox.warning( self, self.tr('Update'), self.tr('Please select just one item to update.'), QMessageBox.Ok) elif new_subs != '': if self.updateQuestion("Component", (old_subs[0], new_subs)) == QMessageBox.Yes: self.container.update(component=[(new_subs, old_subs[0])]) self.showMessageOnStatusBar( 'Component "{}" was updated to "{}".'.format( old_subs[0], new_subs)) self.updateComponentView()
def quit(self): if self.dirty: text = ('Save changes to ' + (self.filename or DEFAULT_FILENAME) + ' before closing?') reply = QMessageBox.warning(self, self.app.applicationName(), text, QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel, QMessageBox.Yes) if reply == QMessageBox.Cancel: return elif reply == QMessageBox.Yes and not self.save_selected(): return self.app.exit()
def setObjectLineWeight(self, lineWeight): """ TOWRITE :param `lineWeight`: TOWRITE :type `lineWeight`: qreal """ self.objPen.setWidthF(0) # NOTE: The objPen will always be cosmetic if lineWeight < 0: if lineWeight == OBJ_LWT_BYLAYER: self.lwtPen.setWidthF(0.35) # TODO: getLayerLineWeight elif lineWeight == OBJ_LWT_BYBLOCK: self.lwtPen.setWidthF(0.35) # TODO: getBlockLineWeight else: QMessageBox.warning(0, QObject.tr("Error - Negative Lineweight"), QObject.tr("Lineweight: %f" % lineWeight)) qDebug("Lineweight cannot be negative! Inverting sign.") self.lwtPen.setWidthF(-lineWeight) else: self.lwtPen.setWidthF(lineWeight)
def actionBack(self): if self.draw_timer.isActive(): ret = QMessageBox.warning(self, u"警告", u"测量正在进行中,是否中断测量", QMessageBox.Yes | QMessageBox.No) if ret == QMessageBox.No: return else: self.draw_timer.stop() self.clear() self.actionOrder('init') self.tcp_link.close() self.ST_flag = False
def OnSaveFilePath(self, filePath): """""" file = QFile(filePath) if not file.open(QFile.WriteOnly | QFile.Text): QMessageBox.warning(self, self.tr('Warning'), self.tr('Cannot write file') + ' %s:\n%s.' % (filePath, file.errorString())) return False outf = QTextStream(file) QApplication.setOverrideCursor(Qt.WaitCursor) outf << self.toPlainText() QApplication.restoreOverrideCursor() self.DoSetCurrentFilePath(filePath) # Clear the Modified Flag. self.document().setModified(False) self.setWindowModified(False) self.setWindowTitle('%s[*]' % self.fileName) return True
def guiMessage(self, title, msg, show=False): '''guiMessage(title, msg, show=False) Handle op related GUI messages to user''' if msg is not None: self.guiMsgs.append((title, msg)) if show is True: if len(self.guiMsgs) > 0: if FreeCAD.GuiUp: from PySide.QtGui import QMessageBox for entry in self.guiMsgs: (title, msg) = entry QMessageBox.warning(None, title, msg) self.guiMsgs = [] # pylint: disable=attribute-defined-outside-init return True else: for entry in self.guiMsgs: (title, msg) = entry PathLog.warning("{}:: {}".format(title, msg)) self.guiMsgs = [] # pylint: disable=attribute-defined-outside-init return True return False
def askSaveChanges(self): if self.editor.document().isModified(): response = QMessageBox.warning( self, self.trUtf8(b'Save changes?'), self.trUtf8(b'The document has been modified.\n' 'Do you want to save your changes?'), QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel, QMessageBox.Save) if response == QMessageBox.Cancel: return False if response == QMessageBox.Save: return self.saveFile() return True
def __writeConfigFile(self): try: fileName = self.configFileName[0] except: fileName = "" if (not os.path.exists(fileName)): if (self.__validateForm()): self.configFileName = QFileDialog.getSaveFileName() else: QMessageBox.warning(self, "Error", "Please, fill all form before save!", QMessageBox.Ok) return cfgFile = open(self.configFileName[0], 'w') asterixIp = self.leAsterixIP.text() asterixPort = self.leAsterixPort.text() asterixSic = self.leAsterixSic.text() graylogIp = self.leGraylogIP.text() graylogPort = self.leGraylogPort.text() graylogHttpPort = self.leGraylogHttpPort.text() iamodPort = self.leIamodPort.text() iamodThreshold = self.leIamodThreshold.text() self.configFile.set("asterix", "server", asterixIp) self.configFile.set("asterix", "port", asterixPort) self.configFile.set("asterix", "sic", asterixSic) self.configFile.set("graylog", "server", graylogIp) self.configFile.set("graylog", "port", graylogPort) self.configFile.set("graylog", "httpPort", graylogHttpPort) self.configFile.set("iamod", "port", iamodPort) self.configFile.set("iamod", "threshold", iamodThreshold) self.configFile.write(cfgFile)
def importFile(self): """Import file with extension.""" # This is not general and should be moved to tips about importing # This should be here, because without this information # you cant open a csv file. We need to put more information # about other types too. #@TODO: show a dialog to choose separator and id QMessageBox.information( self, self.tr('Import File'), self. tr('Please, before you try import the file, ensure that if it is a:\ \nCSV: separator is ; (semi collon)\ \n quote char is " (double quote) and \ \n quoting is for All elements.\ \n Example: "SECTION";"COMPONENT";"STRATEGY";"SENTENCE";"REFERENCE"\ \n "Abstract";"Gap";"Importance";"However, this problem still unsolved";""\ \nJSON: fields are list of list: \ \n Example: [["SECTION", "COMPONENT", "STRATEGY", "SENTENCE", "REFERENCE"],\ \n ["Abstract","Gap","Importance","However, this problem still unsolved",""]]' ), QMessageBox.Ok) path = QFileDialog.getOpenFileName( self, self.tr('Import File'), self.tr(os.path.dirname(str(self.workspace))), self.tr('(*.xml *.csv *.json)'))[0] if path != '': try: self.container.import_(path) except Exception as e: self.clearAll() QMessageBox.warning( self, self.tr('Import File'), self.tr('We could not import the file. \nError:{}'.format( str(e))), QMessageBox.Ok) self.updateSectionView() self.updateSentenceView()
def __handleRpmOperationResult(self, retValList): """ Analyze the return values contained in `retValList` and display a message if one if different from 0. """ message = None packageToRefreshList = [x[0] for x in retValList] err = False packageErr = [] for (pkg, r) in retValList: if r != 0: err = True packageErr.append(pkg) if err: message = u"Operations on %s may have failed (return code != 0)\n" % ",".join( packageErr) if message is not None: message += u"You should check the log to find any error." QMessageBox.warning(self.mainWindow, u"Bad exit status", message)
def performQuickFixes(self): plugin_dict = {} plugin = self._ui.listWidget.selectedItems()[0].text().split(' - ')[0] plugin_directory = self.locatePluginForHotfix(plugin) plugin_init_update, plugin_resources_update, plugin_syntax_update, plugin_tabbed_indentation, resourcesDirs, tabbed_modules = performPluginAnalysis( plugin_directory, plugin, self._resourceFiles) plugin_dict[plugin] = [ plugin_directory, plugin_init_update, plugin_resources_update, plugin_syntax_update, plugin_tabbed_indentation, os.path.join(plugin_directory, plugin, '__init__.py'), resourcesDirs, tabbed_modules ] _, failure = applyPluginUpdates(plugin_dict) if failure: QMessageBox.warning( self, 'Warning', '\nCould not update plugin. Please examine program logs for more info. \t', QMessageBox.Ok) else: self._ui.listWidget.takeItem( self._ui.listWidget.row( self._ui.listWidget.selectedItems()[0])) self._hotfixExecuted = True
def showErrors(type_, **extra_args): """Show variety of error dialogs.""" app = QApplication.instance() if not app: app = init() { 'dbError': lambda hint='': QMessageBox.critical( None, app.translate('Errors', 'Failed to access database'), app.translate( 'Errors', 'SQLite3: %s.\n\nPlease check database path(have permission?). ' 'If it\'s corrupt, you may have to recover this file by hand or restore ' 'from backups.') % hint), 'dbLocked': lambda: QMessageBox.warning( None, app.translate('Errors', 'Multiple access error'), app.translate('Errors', 'This diary book is already open.')), 'cantFile': lambda info: QMessageBox.warning( None, app.translate('Errors', 'Failed to access file'), app.translate('Errors', info)) }[type_](**extra_args)
def __init__(self, edit_cat_id=None, parent=None): super(AddEditCatDialog, self).__init__(parent) self.setupUi(self) # If editing self.edit_cat_id = edit_cat_id if self.edit_cat_id: try: with session_scope() as session: category = session.query(Category).get( int(self.edit_cat_id)) self.addEditCatLineEdit.setText(category.category_name) except Exception as cexc: logger.error(str(cexc)) QMessageBox.warning(self, "Unexpected Error", unicode('Could not set category name.')) return # Preventitive validation self.addEditCatLineEdit.setMaxLength(50) self.addEditCatButtonBox.button( QDialogButtonBox.Save).setEnabled(False) self.addEditCatLineEdit.textChanged.connect(self.disableAddButton)
def try_save(self): if self.editor.document().isModified(): ret = QMessageBox.warning( self, "Blah Blah Blah", "That's an awfully nice modified document you've got there" ". It'd be a shame if anything... happened to it. Catch " "my drift?", QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel) if ret == QMessageBox.Save: self.action_save() elif ret == QMessageBox.Cancel: return False return True
def AskToSaveBeforeClosing(self): """""" if self.document().isModified(): ret = QMessageBox.warning( self, 'Warning', 'The document has been modified.' '\n' 'Do you want to save your changes?', QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel) if ret == QMessageBox.Save: return self.OnSave() elif ret == QMessageBox.Cancel: if gMainWin.isEmbroidermodderMainWindowClosing: gMainWin.isEmbroidermodderMainWindowClosing = False # Cancel closing the app. return False return True
def validatePage(self): if not self.isComplete(): return False readonly = self._isSelectedProjectReadOnly() if readonly: msg = u"Warning: the project you selected is read only!\n" msg += u"You won't be able to push modifications.\n\n" msg += u"Do you want to import it anyway?" result = QMessageBox.warning(self, u"Read only project", msg, buttons=QMessageBox.Yes | QMessageBox.Cancel, defaultButton=QMessageBox.Yes) return result == QMessageBox.Yes return True
def unc2XDriver(self): directory = os.path.realpath(self.edit.text()) if not os.path.exists(directory): QMessageBox.warning(self, u"警告", u"%s - 路径不存在" % directory) return os.system(r"subst X: /D") command = r"subst X: %s" % directory val = os.system(command) if val != 0: QMessageBox.warning(self, u"警告", u"%s" % val) return user_path = os.path.expanduser('~') startup_path = os.path.join( user_path, r"AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup") if os.path.exists(startup_path): bat_path = os.path.join(startup_path, "substXDriver.bat") with open(bat_path, 'w', encoding="utf-8") as f: f.write(command) QMessageBox.warning(self, u"通知", u"%s - 映射成功" % directory)
def open_existing_wallet(self): current_wallet_password, result = self._custom_input_dialog(self.ui, \ "Wallet Password", "Current wallet password:"******"Incorrect Wallet Password", "Wallet password is not correct!") return dlg = QFileDialog(self.ui, "Open Wallet File", wallet_dir_path, "Wallet files (*.bin)") dlg.setFileMode(QFileDialog.ExistingFile) wallet_filename = None if dlg.exec_(): wallet_filename = dlg.selectedFiles()[0] else: self.on_open_existing_wallet_complete_event.emit() return if not wallet_filename: return wallet_key_filename = wallet_filename + '.keys' if not os.path.exists(wallet_key_filename): QMessageBox.warning(self.ui, \ 'Open Wallet File',\ """Error: Key file does not exist!<br> Please make sure to select correct wallet file""") return if os.path.normpath(os.path.dirname( wallet_filename)) != os.path.normpath(wallet_dir_path): QMessageBox.warning(self.ui, \ 'Open Wallet File',\ """Error: Only wallet files at default location are available for opening.<br> You can import wallet via 'New... > Import' feature instead.""") return if os.path.basename(wallet_filename) == os.path.basename( self.ui.wallet_info.wallet_filepath): QMessageBox.warning(self.ui, \ 'Open Wallet File',\ """Error: Cannot open the same wallet!""") return while True: wallet_password, result = self._custom_input_dialog(self.ui, \ "Wallet Password", "Enter wallet password for opening:", QLineEdit.Password) if result: if not wallet_password: QMessageBox.warning(self.ui, \ 'Wallet Password',\ "You must provide password to open wallet") continue else: break else: return self.ui.stop_update_wallet_info_timer() self.on_open_existing_wallet_start_event.emit() current_wallet_filename = self.ui.wallet_info.wallet_filepath try: ret = self.ui.wallet_rpc_manager.rpc_request.stop_wallet() if ret['status'] == "ERROR": error_message = ret['message'] QMessageBox.critical(self.ui, \ 'Error Closing Current Wallet',\ "Error: %s" % error_message) raise Exception(error_message) self.ui.wallet_rpc_manager.set_ready(False) self.ui.run_wallet_rpc() while not self.ui.wallet_rpc_manager.is_ready(): self.app_process_events(0.1) ret = self.ui.wallet_rpc_manager.rpc_request.open_wallet( os.path.basename(wallet_filename), wallet_password) if ret['status'] == "ERROR": error_message = ret['message'] QMessageBox.critical(self.ui, 'Error Opening Wallet', error_message) raise Exception(error_message) self.ui.reset_wallet(False) self.ui.wallet_info.wallet_password = hashlib.sha256( wallet_password).hexdigest() self.ui.wallet_info.wallet_filepath = wallet_filename self.ui.wallet_info.is_loaded = True self.ui.wallet_info.save() while not self.ui.wallet_rpc_manager.is_ready(): self.app_process_events(0.1) except Exception, err: log(str(err), LEVEL_ERROR) ret = self.ui.wallet_rpc_manager.rpc_request.open_wallet( os.path.basename(current_wallet_filename), current_wallet_password) self.ui.wallet_info.wallet_password = hashlib.sha256( current_wallet_password).hexdigest() self.ui.wallet_info.wallet_filepath = current_wallet_filename self.ui.wallet_info.is_loaded = True self.ui.wallet_info.save() self.on_open_existing_wallet_complete_event.emit()
def validateSelection(self): if len(self._ui.lineEdit.text()) == 0: QMessageBox.warning(self, 'Error', '\n No file selected!\t', QMessageBox.Ok) else: self.accept()
def change_wallet_password(self): old_password, result = self._custom_input_dialog(self.ui, \ "Wallet Password", "Enter current wallet password:"******"", "") QMessageBox.warning(self.ui, "Incorrect Wallet Password", "Wallet password is not correct!") return new_password = None while True: new_password, result = self._custom_input_dialog(self.ui, \ "Wallet New Password", "Set new wallet password:"******"Password must contain at least 1 character [a-zA-Z] or number [0-9]\ <br>or special character like !@#$%^&* and not contain spaces" ) continue confirm_password, result = self._custom_input_dialog(self.ui, \ 'Wallet New Password', \ "Confirm new wallet password:"******"Confirm password does not match new password!\ <br>Please re-enter password" ) continue else: break else: return else: return if new_password is not None: if new_password == old_password: QMessageBox.information( self.ui, "Wallet Password", "New wallet password is the same as old one. Nothing changed!" ) return ret = self.ui.wallet_rpc_manager.rpc_request.change_wallet_password( old_password, new_password) if ret['status'] == "ERROR": error_message = ret['message'] QMessageBox.critical(self.ui, \ 'Error Changing Wallet Password',\ "Error: %s" % error_message) return self.ui.wallet_info.wallet_password = hashlib.sha256( new_password).hexdigest() self.ui.wallet_info.save() QMessageBox.information( self.ui, "Wallet Password Changed", "Wallet password successfully changed!<br>Please make sure you never lose it." )
from ObsLight.obslight_starter import alreadyRunning, userIsRoot, writePidFile from ObsLight.obslight_starter import getpidFilePath, getPidFromFile, wasStoppedCorrectly from ObsLight.obslight_starter import shouldUpgradeMessage # a QApplication instance is required in order to display message boxes qApplication = QApplication(sys.argv) if userIsRoot(): QMessageBox.critical(u"Cannot run as root", u"OBS Light cannot run as root!") sys.exit(0) if alreadyRunning(): pid = getPidFromFile() message = u"OBS Light is already running (PID: %d).\n" % pid QMessageBox.warning(None, u"Already running", message) sys.exit(1) if not wasStoppedCorrectly(): message = u"It seems that OBS Light has not been shut down correctly.\n" message += u"Please close it and re-launch it so it can clean itself." QMessageBox.warning(None, u"Shutdown problem", message) shouldUpgradeMsg = shouldUpgradeMessage() if shouldUpgradeMsg is not None: QMessageBox.information(None, u"Upgrade recommended", shouldUpgradeMsg) writePidFile() from ObsLight import babysitter, ObsLightManager from ObsLightGui.Gui import Gui