我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用PyQt5.QtWidgets.QMessageBox.critical()。
def __init__(self, link_url: str, dl_path: str, parent=None): super(Downloader, self).__init__(parent) self.parent = parent self.dltool_cmd = find_executable(self.download_cmd) self.download_link = link_url self.download_path = dl_path if self.dltool_cmd.strip(): self.dltool_args = self.dltool_args.format(dl_path=self.download_path, dl_link=self.download_link) self.console = QTextEdit(self.parent) self.console.setWindowTitle('%s Downloader' % qApp.applicationName()) self.proc = QProcess(self.parent) layout = QVBoxLayout() layout.addWidget(self.console) self.setLayout(layout) self.setFixedSize(QSize(400, 300)) else: QMessageBox.critical(self.parent, 'DOWNLOADER ERROR', '<p>The <b>aria2c</b> executable binary could not ' + 'be found in your installation folders. The binary comes packaged with this ' + 'application so it is likely that it was accidentally deleted via human ' + 'intervntion or incorrect file permissions are preventing access to it.</p>' + '<p>You may either download and install <b>aria2</b> manually yourself, ensuring ' + 'its installation location is globally accessible via PATH environmnt variables or ' + 'simply reinstall this application again. If the issue is not resolved then try ' + 'to download the application again incase the orignal you installed already was ' + 'corrupted/broken.', buttons=QMessageBox.Close)
def trainSystem(self): """ Orders the AppController to train a model based on the selected database. Parameters ---------- None Return ---------- None """ if self.path_train: trained = self.controller.train(self.path_train, self.comboBoxDatabaseTrain.currentText()) self.path_train = None if not trained: QMessageBox.critical(self.train, "Message", "File columns or labels mismatch.") else: QMessageBox.information(self.train, "Message", "Training succesful.") else: QMessageBox.warning(self.train, "Message", "Must pick a database file.")
def _start(self, flash, erase): self._flash_output = bytearray() self.outputEdit.setPlainText("") python_path = self.pythonPathEdit.text() if not python_path: QMessageBox.critical(self, "Error", "Python2 path was not set.") return firmware_file = None if flash: firmware_file = self.firmwarePathEdit.text() if not firmware_file: QMessageBox.critical(self, "Error", "Firmware file was not set.") return self._port = self._connection_scanner.port_list[self.portComboBox.currentIndex()] job_thread = Thread(target=self._flash_job, args=[python_path, firmware_file, erase]) job_thread.setDaemon(True) job_thread.start() self.eraseButton.setEnabled(False) self.flashButton.setEnabled(False) self._flashing = True
def scrape(self, pagenum: int) -> None: try: url = self.source_url.format(pagenum + 1) req = requests.get(url, headers={'User-Agent': self.user_agent}, proxies=self.proxy) bs = BeautifulSoup(req.text, 'lxml') posts = bs('div', class_='post') for post in posts: dlsize = post.find('h2').get_text().strip() table_row = [ post.find('div', class_='p-c p-c-time').get_text().strip(), post.find('a', class_='p-title').get('href').strip(), post.find('a', class_='p-title').get_text().strip(), dlsize[dlsize.rfind('(') + 1:len(dlsize) - 1] ] self.addRow.emit(table_row) except HTTPError: sys.stderr.write(sys.exc_info()[0]) QMessageBox.critical(self, 'ERROR NOTIFICATION', sys.exc_info()[0]) # self.exit()
def connect(self, endpoint: str, payload: object=None) -> object: try: headers = { 'Authorization': 'Bearer %s' % self.api_token, 'Content-Type': 'application/x-www-form-urlencoded', 'Cache-Control': 'no-cache' } res = requests.post('%s%s' % (self.api_url, endpoint), headers=headers, data=payload, proxies=self.proxy, verify=False) return res.json() except HTTPError: print(sys.exc_info()) QMessageBox.critical(self, 'ERROR NOTIFICATION', '<h3>Real-Debrid API Error</h3>' + 'A problem occurred whilst communicating with Real-Debrid. Please check your ' 'Internet connection.<br/><br/>' + '<b>ERROR LOG:</b><br/>(Error Code %s) %s<br/>%s' % (qApp.applicationName(), HTTPError.code, HTTPError.reason), QMessageBox.Ok) # self.exit()
def setup_runtime(uconfig): from bot.duel_links_runtime import DuelLinkRunTime from bot import logger from bot.providers import get_provider os.makedirs(uconfig.get('locations', 'log'), exist_ok=True) setup_logging() scheduler = BackgroundScheduler() dlRuntime = DuelLinkRunTime(uconfig, scheduler) dlRuntime.stop = False # Need to Ensure that it runs scheduler.start() try: dlRuntime.set_provider(get_provider(uconfig.get('bot', 'provider'))(scheduler, uconfig, dlRuntime)) except Exception as e: logger.critical("Could not get a provider, take a look at your config file") logger.critical(e) sys.exit(1) try: dlRuntime.get_provider().sleep_factor = uconfig.getint('bot', 'sleep_factor') except Exception as e: logger.critical("Could not set sleep factor, take a look at your config file") logger.critical(e) sys.exit(1) return dlRuntime
def gui(start, config_file): if start: import sys from PyQt5.QtWidgets import QSystemTrayIcon from PyQt5.QtWidgets import QMessageBox from PyQt5.QtWidgets import QApplication from bot.utils.common import make_config_file, default_config from bot.duel_links_runtime import DuelLinkRunTime from bot.dl_gui import DuelLinksGui app = QApplication(sys.argv) if not QSystemTrayIcon.isSystemTrayAvailable(): QMessageBox.critical(None, "Systray", "Systray not dected on system.") sys.exit(1) QApplication.setQuitOnLastWindowClosed(False) uconfig = default_config() uconfig.read(config_file) dlRuntime = setup_runtime(uconfig) dlRuntime.main() window = DuelLinksGui(dlRuntime) window.show() sys.exit(app.exec_())
def __init__(self, parent=None): super(VideoService, self).__init__(parent) self.parent = parent self.logger = logging.getLogger(__name__) try: self.backends = VideoService.findBackends() self.proc = VideoService.initProc() if hasattr(self.proc, 'errorOccurred'): self.proc.errorOccurred.connect(self.cmdError) self.lastError = '' self.media, self.source = None, None self.keyframes = [] self.streams = Munch() except FFmpegNotFoundException as e: self.logger.exception(e.msg, exc_info=True) QMessageBox.critical(getattr(self, 'parent', None), 'Missing libraries', e.msg, QMessageBox.Ok)
def showDocInAssistant(self, name): url = self.resolveDocUrl(name) Colors.debug("Sending URL to Assistant:", url) # Start assistant if it's not already running. if self.assistantProcess.state() != QProcess.Running: app = QLibraryInfo.location(QLibraryInfo.BinariesPath) + QDir.separator() if sys.platform == 'darwin': app += 'Assistant.app/Contents/MacOS/Assistant' else: app += 'assistant' args = ['-enableRemoteControl'] self.assistantProcess.start(app, args) if not self.assistantProcess.waitForStarted(): QMessageBox.critical(None, "PyQt Demo", "Could not start %s." % app) return # Send command through remote control even if the process was just # started to activate assistant and bring it to the front. cmd_str = QTextStream(self.assistantProcess) cmd_str << 'SetSource ' << url << '\n'
def connect2machine(self, vmid, vmname): """ Description: Connecting to the machine involves two steps, this method does both and makes sure everything is ok to call virt-viewer afterwards. Arguments: 1. vmid: The VM UUID in oVirt-format. 2. vmname: Just for displaying purposes, the VM name Returns: Nothing. Opens the view-viewer display. """ viewer_ticket = self.get_viewer_ticket(vmid) filename = self.store_vv_file(vmid, viewer_ticket) if filename: self.create_viewer_thread(vmname, filename) else: if vmname in self.openviewer_vms: self.openviewer_vms.remove(vmname) # Remove the VM from the list of opened viewers QMessageBox.critical(None, _('apptitle') + ': ' + _('error'), _('no_viewer_file'))
def acquire_vm_from_vmpool(self, rowid): """ Description: A machine will be acquired by a user if they click on the icon of a VmPool Arguments: The row id that has been clicked. This relationship is stored using the VmData class. Returns: Nothing """ self.lastclick = int(time()) # Last click timestamp update vmtype = self.vmdata[rowid].vmtype if vmtype == 'vmpool': try: QMessageBox.information(None, _('apptitle') + ': ' + _('info'), _('acquiring_vm_from_pool')) vmp = conf.OVIRTCONN.vmpools.get(id=self.vmdata[rowid].vmid) vmp.allocatevm() self.refresh_grid() except ConnectionError: QMessageBox.critical(None, _('apptitle') + ': ' + _('error'), _('unexpected_connection_drop')) quit() except RequestError: QMessageBox.critical(None, _('apptitle') + ': ' + _('error'), _('cannot_attach_vm_to_user')) else: QMessageBox.warning(None, _('apptitle') + ': ' + _('warning'), _('object_is_not_a_vmpool'))
def __init__(self): self.anki = AnkiBridge() self.server = AjaxServer(self.handler) try: self.server.listen() self.timer = QTimer() self.timer.timeout.connect(self.advance) self.timer.start(TICK_INTERVAL) except: QMessageBox.critical( self.anki.window(), 'AnkiConnect', 'Failed to listen on port {}.\nMake sure it is available and is not in use.'.format(NET_PORT) )
def upgrade(self): response = QMessageBox.question( self.anki.window(), 'AnkiConnect', 'Upgrade to the latest version?', QMessageBox.Yes | QMessageBox.No ) if response == QMessageBox.Yes: data = download(URL_UPGRADE) if data is None: QMessageBox.critical(self.anki.window(), 'AnkiConnect', 'Failed to download latest version.') else: path = os.path.splitext(__file__)[0] + '.py' with open(path, 'w') as fp: fp.write(makeStr(data)) QMessageBox.information(self.anki.window(), 'AnkiConnect', 'Upgraded to the latest version, please restart Anki.') return True return False
def calculate(self): inputs = self.validate_input(); if (inputs is not False): Jmax,Kmax,Mmax = inputs; self.setEnabled(False); self.update(); QMessageBox.information(self,'Responsiveness','This user interface will be irresponsive while the calculation is carried out.\n\nSorry about that!'); try: U2dcalc.set_num_threads(multiprocessing.cpu_count()); U2dcalc.precalculate_matrix_elements(Jmax,Kmax,Mmax); self.update_available(); QMessageBox.information(self,'Success!','Calculation done.'); self.close(); except BaseException as e: QMessageBox.critical(self,'Failed to calculate matrix elements',str(e)); self.setEnabled(True); else: QMessageBox.critical(self,'Validation error',"Invalid input");
def delete_group(self, group_item: ProtocolTreeItem): if self.rootItem.childCount() == 1: QMessageBox.critical(self.controller, self.tr("Group not deletable"), self.tr( "You can't delete the last group. Think about the children, they would be homeless!")) return group_id = self.rootItem.index_of(group_item) if group_id == 0: new_group_index = 1 else: new_group_index = group_id - 1 new_group = self.rootItem.children[new_group_index] for i in reversed(range(group_item.childCount())): new_group.appendChild(group_item.children[i]) self.removeRow(group_id, QModelIndex()) self.group_deleted.emit(group_id, new_group_index)
def hackrf_not_found(): w = QWidget() if sys.platform == "win32": msg = "Could not connect to HackRF. Try these solutions:" \ "<br/><br/> 1. Ensure HackRF is plugged in." \ "<br/> 2. <b>Install HackRF USB driver</b> with <a href='http://zadig.akeo.ie/'>Zadig</a>." else: msg = "Could not connect to HackRF. Try these solutions:" \ "<br/><br/> 1. Ensure HackRF is plugged in." \ "<br/> 2. Run the command <b>hackrf_info</b> in terminal as root." \ "<br/> 3. If 2. works for you, follow the instructions " \ "<a href='https://github.com/mossmann/hackrf/wiki/FAQ'>here</a>." QMessageBox.critical(w, w.tr("HackRF not found"), w.tr(msg))
def get_action(self, parent, undo_stack: QUndoStack, sel_range, protocol: ProtocolAnalyzer, view: int): """ :type parent: QTableView :type undo_stack: QUndoStack :type protocol_analyzers: list of ProtocolAnalyzer """ min_row, max_row, start, end = sel_range if min_row == -1 or max_row == -1 or start == -1 or end == -1: return None if max_row != min_row: QMessageBox.critical(parent, self.tr("Error in MessageBreak"), self.tr("You can only break one line per action.")) return None end = protocol.convert_index(end, view, 0, True, message_indx=min_row)[0] # factor = 1 if view == 0 else 4 if view == 1 else 8 self.command = MessageBreakAction(protocol, max_row, end) action = QAction(self.command.text(), parent) action.triggered.connect(self.action_triggered) self.undo_stack = undo_stack return action
def set_databaseconnection(): ''' Setting connection with SQLite ''' # TODO explicitly close database connection on exit filepath = os.path.join(os.path.dirname(__file__), '..', '..', '..', 'ResourceFiles', 'Database', 'Intg_osdag.sqlite') db = QSqlDatabase.addDatabase("QSQLITE") db.setDatabaseName(filepath) if not db.open(): QMessageBox.critical(None, qApp.tr("Cannot open database"), qApp.tr("Unable to establish a database connection.\n" "This example needs SQLite support. Please read " "the Qt SQL driver documentation for information " "how to build it.\n\n" "Click Cancel to exit."), QMessageBox.Cancel) return False
def validateSystem(self): """ Orders the AppController to validate a model based on the selected database. Parameters ---------- None Return ---------- None """ if self.path_validate: checked, validated, accuracy, precision, sensitivity, specificity, kappa = self.controller.validate(self.path_validate, self.spinBoxFolds.value(), self.comboBoxDatabaseValidate.currentText()) self.path_validate = None if not validated: QMessageBox.warning(self.validate, "Message", "Classifier for "+ self.comboBoxDatabaseValidate.currentText() + " database is not trained.") self.clearValidateLineEdits() else: self.lineEditAccuracy.setText(str(accuracy)) self.lineEditPrecision.setText(str(precision)) self.lineEditSensitivity.setText(str(sensitivity)) self.lineEditSpecificity.setText(str(specificity)) self.lineEditKappa.setText(str(kappa)) QMessageBox.information(self.train, "Message", "Validation finished.") if not checked: QMessageBox.critical(self.validate, "Message", "File columns or labels mismatch.") self.clearValidateLineEdits() else: QMessageBox.warning(self.validate, "Message", "Must pick a database file.") self.clearValidateLineEdits()
def _save_local(self): path = self.localPathEdit.text() if not path: QMessageBox.warning(self, "Invalid path", "Enter correct path for local file.") return try: with open(path, "w") as file: file.write(self.codeEdit.toPlainText()) except IOError: QMessageBox.critical(self, "Save operation failed", "Couldn't save the file. Check path and permissions.")
def _flash_finished(self, code): Logger.log("Flash output contents:\r\n") Logger.log(self._flash_output) if code == 0: self._flash_output.extend(b"Rebooting from flash mode...\n") self._update_output() try: s = serial.Serial(self._port, 115200) s.dtr = False s.rts = True time.sleep(0.1) s.rts = False time.sleep(0.1) self._flash_output.extend(b"Done, you may now use the device.\n") self._update_output() except (OSError, serial.SerialException): QMessageBox.critical(self, "Flashing Error", "Failed to reboot into working mode.") elif code == -1: QMessageBox.critical(self, "Flashing Error", "Failed to run script.\nCheck that path to python is correct.") else: QMessageBox.critical(self, "Flashing Error", "Failed to flash new firmware") self.eraseButton.setEnabled(True) self.flashButton.setEnabled(True) self._flashing = False
def cmd_error(self, error: QProcess.ProcessError) -> None: if error != QProcess.Crashed: QMessageBox.critical(self.parent, 'Error calling an external process', self.proc.errorString(), buttons=QMessageBox.Close)
def get_hoster_links(self) -> None: try: req = self.scraper.get(self.link_url, proxies=self.proxy) bs = BeautifulSoup(req.text, 'lxml') links = bs.select('div.post h2[style="text-align: center;"]') self.setHosters.emit(links) except HTTPError: print(sys.exc_info()[0]) QMessageBox.critical(self, 'ERROR NOTIFICATION', sys.exc_info()[0]) QThread.currentThread().quit() except IndexError: self.noLinks.emit() QThread.currentThread().quit()
def file_opener(self, filename: str) -> None: try: if QFileInfo(filename).suffix() == 'vcp': self.cutter.openProject(project_file=filename) if filename == os.path.join(QDir.tempPath(), MainWindow.TEMP_PROJECT_FILE): os.remove(os.path.join(QDir.tempPath(), MainWindow.TEMP_PROJECT_FILE)) else: self.cutter.loadMedia(filename) except (FileNotFoundError, PermissionError): QMessageBox.critical(self, 'Error loading file', sys.exc_info()[0]) logging.exception('Error loading file') qApp.restoreOverrideCursor() self.restart()
def log_uncaught_exceptions(cls, exc, tb) -> None: logging.critical(''.join(traceback.format_tb(tb))) logging.critical('{0}: {1}'.format(cls, exc))
def errorHandler(self, msg: str, title: str=None) -> None: qApp.restoreOverrideCursor() QMessageBox.critical(self, 'An error occurred' if title is None else title, msg, QMessageBox.Ok) logging.error(msg)
def cmdError(self, error: QProcess.ProcessError) -> None: if error != QProcess.Crashed: QMessageBox.critical(self.parent, 'Error alert', '<h4>{0} Error:</h4><p>{1}</p>'.format(self.backends.ffmpeg, self.proc.errorString()), buttons=QMessageBox.Close) # noinspection PyUnresolvedReferences, PyProtectedMember
def start(self): key=self.textEdit.toPlainText() page=self.comboBox.currentText() if key: os.system('redis-cli flushdb') os.system('redis-cli lpush mycrawler:start_urls http://www.taobao.com') os.system('scrapy crawl tb -a key='+str(key)+' -a page='+str(page)+'') QMessageBox.critical(self,"??","?????") else: QMessageBox.critical(self,"??","?????????????") return #os.system('scrapy crawl jd -a key='+str(key)+' -a page='+str(page)+'')
def fatal(message): if QMessageBox: try: app = QApplication(sys.argv) QMessageBox.critical(None, 'Error', str(message)) except BaseException as exc: print('fatal:', message) print('during handling of the above error, following error occured') print('fatal:', exc) else: print('fatal:', message) sys.exit(1)
def launchError(self, error): if error != QProcess.Crashed: QMessageBox.critical(None, "Failed to launch the example", "Could not launch the example. Ensure that it has been " "built.", QMessageBox.Cancel)
def change_status(self, rowid): """ Description: If the user clicks on the column which determines VM's status, we'll allow them to change VM's status. This method shows a confirmation dialog and if accepted, it will be notified to oVirt. Arguments: The row id that has been clicked. This relationship is stored using the VmData class. Returns: Nothing """ global conf self.lastclick = int(time()) # Last click timestamp update curvmstatus = self.vmdata[rowid].vmstatus if curvmstatus != 'up' and curvmstatus != 'down': QMessageBox.warning(None, _('apptitle') + ': ' + _('warning'), _('vm_in_unchangeable_status')) return reply = QMessageBox.question(None, _('apptitle') + ': ' + _('confirm'), '%s <b>%s</b>. %s: <b>%s</b>.' % (_('current_vm_status'), self.current_vm_status(curvmstatus), _('confirm_vm_status_change'), self.toggle_vm_action(curvmstatus)), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: try: vm = conf.OVIRTCONN.vms.get(id=self.vmdata[rowid].vmid) except ConnectionError: QMessageBox.critical(None, _('apptitle') + ': ' + _('error'), _('unexpected_connection_drop')) quit() if curvmstatus == 'up': try: vm.shutdown() QMessageBox.information(None, _('apptitle') + ': ' + _('success'), _('shutting_down_vm')) except RequestError: QMessageBox.warning(None, _('apptitle') + ': ' + _('warning'), _('vm_in_unchangeable_status')) if curvmstatus == 'down': try: vm.start() QMessageBox.information(None, _('apptitle') + ': ' + _('success'), _('powering_up_vm')) except RequestError: QMessageBox.warning(None, _('apptitle') + ': ' + _('warning'), _('vm_in_unchangeable_status'))
def store_vv_file(self, vmid, ticket): """ Description: Connecting to the machine involves two steps, the second one is obtaining a 'vv' file with the connection parameters, which we can later pipe to virt-viewer and the connection will be opened. Arguments: 1. vmid: The VM UUID in oVirt-format. 2. ticket: The ticket obtained in the first step (method get_viewer_ticket) Returns: The temporary filename with all the parameters to connect to the machine (piped to virt-viewer) """ global conf if not ticket: return False req = urllib2.Request('%s/%s/%s/%s/%s' % (conf.CONFIG['ovirturl'], 'vms', vmid, 'graphicsconsoles', ticket)) base64str = encodestring('%s:%s' % (conf.USERNAME + '@' + conf.CONFIG['ovirtdomain'], conf.PASSWORD)).replace('\n', '') req.add_header('Authorization', 'Basic ' + base64str) req.add_header('Content-Type', 'application/xml') req.add_header('Accept', 'application/x-virt-viewer') req.add_header('filter', 'true') unverified_ctxt = SSLContext(PROTOCOL_TLSv1) try: contents = urllib2.urlopen(req, context=unverified_ctxt).read() if conf.CONFIG['fullscreen'] == '1': contents = contents.replace('fullscreen=0', 'fullscreen=1') filename = '/tmp/viewer-' + str(randint(10000, 99999)) f = open(filename, 'w') f.write(contents) f.close() return filename except urllib2.HTTPError, em: QMessageBox.critical(None, _('apptitle') + ': ' + _('error'), _('unexpected_request_error') + '(' + str(em.code) + '): ' + em.reason + '. ' + _('check_vm_config_updated')) return None
def connect(self, rowid): """ Description: Whenever the user clicks on the 'connect' row, this method will make sure the VM status is up and only then will call the connect2machine method. Arguments: The row id that has been clicked. This relationship is stored using the VmData class. Returns: Nothing """ self.lastclick = int(time()) # Last click timestamp update vmid = self.vmdata[rowid].vmid vmname = self.vmdata[rowid].vmname vmstatus = self.vmdata[rowid].vmstatus if vmstatus != 'up': QMessageBox.warning(None, _('apptitle') + ': ' + _('warning'), _('cannot_connect_if_vm_not_up')) return if vmname in self.openviewer_vms: QMessageBox.critical(None, _('apptitle') + ': ' + _('error'), _('cannot_open_more_viewer_sessions')) return self.openviewer_vms.append(vmname) self.refresh_grid() # Enforce a dashboard reload to make the icon refresh self.connect2machine(vmid, vmname)
def validation_error(self,message): if (self.hardcore): QMessageBox.critical(self,'Validation error',"Moron!"); else: QMessageBox.critical(self,'Validation error',message); raise ValueError(message);
def calcDone(self): self.enable_Go_button(); if (self.calc.error): QMessageBox.critical(self,'Calculation error',str(self.calc.error)); else: self.last_result = self.calc.result; self.enable_save_option(); self.present_results();
def on_btn_start_clicked(self): if self.ui.actionStart.text() == u'Start': try: self.jlink = jlink.Jlink(jlinkdllpath) self.jlink.get_hardware_verion() self.jlink.set_mode(jlink.JLINK_MODE_SWD) self.jlink.set_speed(4000) self.RTT_addr = self.get_RTT_addr() self.setup_ring_buffer() self.ui.statusbar.showMessage(u"??????") self.ui.actionStart.setText(u'Stop') except jlink.JlinkError as e: QMessageBox.critical(self, u"??", u"'{}'.".format(e)) #self.on_btn_dll_clicked() del self.jlink self.jlink = None except Exception as e: print(e) self.ui.statusbar.showMessage(u"??????") else: self.ui.actionStart.setText(u'Start') time.sleep(0.1) self.jlink.close() del self.jlink self.jlink = None self.ui.statusbar.showMessage(u"??????")
def on_received(self, bytesUp): try: self.ui.plainTextEdit.moveCursor(QtGui.QTextCursor.End) self.ui.plainTextEdit.insertPlainText(bytesUp.decode()) self.ui.plainTextEdit.moveCursor(QtGui.QTextCursor.End) self.lineLbl.setText(str(self.ui.plainTextEdit.document().lineCount())) except Exception as e: QMessageBox.critical(self, u"??", str(e))
def exception_hook(t, val, tb): QMessageBox.critical(None, "An exception was raised", "Exception type: {}".format(t)) old_exception_hook(t, val, tb)
def mine(self): d=self.path.text() name=self.exeline.text() if d!='Path to the file used to start miner' and d!='': if os.path.isfile(d)==True: d='/'.join(d.split('/')[:-1]) try: os.chdir(d) process.start(name) self.tnow=time.time() except PermissionError: QMessageBox.critical(self,"Error","Problems when accessing directory",QMessageBox.Ok) except FileNotFoundError: QMessageBox.critical(self,"Error","Bad directory path",QMessageBox.Ok)
def save_data_dialog(signal_name: str, data, wav_only=False, parent=None) -> str: filename = get_save_file_name(signal_name, wav_only) if filename: try: save_data(data, filename) except Exception as e: QMessageBox.critical(parent, "Error saving signal", e.args[0]) filename = None else: filename = None return filename
def generic_error(title: str, msg: str, detailed_msg: str = None): w = QWidget() if detailed_msg: msg = "Error: <b>" + msg.replace("\n", "<br>") + "</b>" + "<br><br>----------<br><br>" + detailed_msg.replace( "\n", "<br>") QMessageBox.critical(w, title, msg)
def no_device(): w = QWidget() QMessageBox.critical(w, w.tr("No devices"), w.tr("You have to choose at least one available " "device in Edit->Options->Device."))
def empty_selection(): w = QWidget() QMessageBox.critical(w, w.tr("No selection"), w.tr("Your selection is empty!"))
def usrp_found(): w = QWidget() QMessageBox.critical(w, w.tr("USRP not found"), w.tr("USRP could not be found . Is the IP " "correct?"))
def gnuradio_not_installed(): w = QWidget() QMessageBox.critical(w, w.tr("Gnuradio not found"), w.tr("You need to install Gnuradio for this " "feature."))
def empty_group(): w = QWidget() QMessageBox.critical(w, w.tr("Empty group"), w.tr("The group may not be empty."))