def showDialog(title, message, buttons: QMessageBox.StandardButtons): msgBox = QMessageBox() msgBox.setWindowTitle(title) msgBox.setIcon(QMessageBox.Icon.Information) msgBox.setText(message) msgBox.setStandardButtons(buttons) msgBox.exec()
def showInvalidParametersErrorMsg(self): msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText('It is physically impossible to produce an inductor from the given inductor parameters') msg.setInformativeText('Please adjust one or more of the inductor parameters and try again') msg.setWindowTitle("Error") msg.exec()
def dataError(): msg = QMessageBox() # msg.setIcon(QMessageBox.icon()) msg.setText("Date-time Error") msg.setInformativeText('Начальная дата обработки данных больше конечной') msg.setWindowTitle("Error") msg.exec()
def call_del_chose_user(self): if self._del_user: if self._del_user != self._config.name: self.user_num -= 1 self._config.del_user(self._del_user) self.user_btns[self._del_user].close() self._del_user = "" if self.user_num <= 1: self.del_user_btn.close() self.del_user_btn = None return else: title = '不能删除' msg = '不能删除当前登录账户,请先切换用户!' else: title = '请选择账户' msg = '请单击选择需要删除的账户\n\n注意不能删除当前账户(绿色)' message_box = QMessageBox(self) message_box.setIcon(QMessageBox.Icon.Critical) message_box.setStyleSheet(btn_style) message_box.setWindowTitle(title) message_box.setText(msg) message_box.setStandardButtons(QMessageBox.StandardButton.Close) buttonC = message_box.button(QMessageBox.StandardButton.Close) buttonC.setText('关闭') message_box.exec()
def excepthook(exc_type, exc_value, traceback_obj): # "redirect" stderr to an in memory buffer in order to capture output of sys.excepthook() for use in GUI message sys.stderr = _text_buffer _original_hook(exc_type, exc_value, traceback_obj) # This is for me using PyCharm. # It will cause the traceback to be printed in the "Run" window, # providing a clickable link to the offending line. print(_text_buffer.getvalue(), file=_original_stderr) # make traceback visible in GUI font = QFont("non-existent") font.setStyleHint(QFont.StyleHint.TypeWriter) error_box = QMessageBox() error_box.setFont(font) error_box.setIcon(QMessageBox.Critical) error_box.setWindowTitle( "Warning: Something Wicked This Way Comes...\t\t\t\t\t\t\t\t\t") error_box.setText("<h2>An unhandled exception occurred.</h2>") error_box.setInformativeText(_text_buffer.getvalue()) error_box.exec() # prevent accumulation of messages cluttering output _text_buffer.truncate(0) sys.stderr = _original_stderr
def delete_confirmation(parent, _id: str, action: Callable): msg = QMessageBox() msg.setText("Are you sure, you want to remove ?") msg.setStyleSheet(''' background-color: #1d251c; color: #bdc0bd; ''') msg.setParent(parent) msg.setWindowModality(Qt.WindowModality.WindowModal) style = ''' margin-top: 20px; border: none; ''' yes_btn = QPushButton(" Yes") yes_btn.setIcon(QIcon(full_path("assets/images/icons/trash-can.ico"))) yes_btn.setStyleSheet(style) no_btn = QPushButton(" Cancel") no_btn.setStyleSheet(style) no_btn.setIcon(QIcon(full_path("assets/images/icons/cancel.ico"))) yes_btn.setDefault(True) msg.addButton(no_btn, msg.ButtonRole.NoRole) msg.addButton(yes_btn, msg.ButtonRole.YesRole) msg.buttonClicked.connect(lambda x: action(_id) if x.text().lower().strip() == "yes" else do_nothing()) msg.exec()
def mostrar_mensaje(self): mensaje = QMessageBox() mensaje.setIcon(QMessageBox.Icon.Information) #Information, NoIcon, Question,Warning, Critical mensaje.setText('Ha hecho Click sobre el botón!!!') mensaje.setDetailedText('Hola..') mensaje.setWindowTitle('sdf') mensaje.exec()
def mostrar_acerca_de(self): mensaje = QMessageBox() mensaje.setIcon(QMessageBox.Icon.Information) mensaje.setText( 'A cerca de Aplicación captura de datos.\n\nAplicacion PyQt6.\nDesarrollador: Mauricio Posada.\nVersión: 1.0.0\n2021.' ) mensaje.exec()
def mostrar_acerca_de(self): mensaje = QMessageBox() mensaje.setWindowTitle('Acerca de') mensaje.setIcon(QMessageBox.Icon.Information) mensaje.setText( 'A cerca de Mi Aplicación.\n\nAplicacion PyQt6.\nDesarrollador: Mauricio Posada.\nVersion 1.0.0\n2021.' ) mensaje.exec()
def doit(self): try: year = int(self.y.currentText()) dates = self.getActiveDates(getDates(year)) except: dates = self.getActiveDates(getDates()) author = git.Actor(self.name.text(), self.email.text()) if not self.name.text() or not self.email.text(): self.err.setText('Did you enter your name and email? 🙄') self.err.exec() return repurl = "https://" + self.name.text() + ":" + self.passw.text( ) + "@" + self.repo.text()[8:] repname = repurl.split('/')[-1].split('.')[0] if not os.path.isdir(repname): try: git.cmd.Git().clone(repurl) except: self.err.setText( 'Could not clone the repo. Ensure that the remote repo exists and that you have access to it.' ) self.err.exec() return rep = git.Repo.init(repname) for date in dates: for n in range(self.nc.value()): rep.index.commit("committed for the lullzz!!", author=author, committer=author, author_date=date.isoformat()) try: rep.remotes.origin.set_url(repurl) except: rep.create_remote('origin', repurl) try: rep.remotes.origin.push() except: self.err.setText( 'Error pushing. Verify you have permissions to push to the repo and that the given credentials are correct' ) self.err.exec() return result = QMessageBox() text = f"Created {len(dates)*2} commits as {self.name.text()} <{self.email.text()}> in {repname} : {self.repo.text()}" result.setWindowIcon(QIcon('icon.png')) result.setWindowTitle('All Done!') result.setText(text) result.exec() os.remove(repname)
def mostrar_saludo(self): nombre = self.txt_nombre.text().strip() mensaje = QMessageBox() mensaje.setWindowTitle('Bienvenido!!!') if len(nombre): mensaje.setText(f'Hola, {nombre}!!!') mensaje.setIcon(QMessageBox.Icon.Information) else: mensaje.setText(f'No ha ingresado un nombre aún...') mensaje.setIcon(QMessageBox.Icon.Warning) mensaje.exec()
def window_prompt(title: str, prompt_text: str): """ Window prompt template used across the app. :param title: Window title. :param prompt_text: Text to prompt. :return: Nothing, just shows a window prompt. """ # Loads the current ui style and assigns it current_style = stylesheets.load_current_style() prompt = QMessageBox() prompt.setWindowTitle(title) prompt.setText(prompt_text) prompt.setStyleSheet(current_style) prompt.exec()
def closeEvent(self, event): if self.isEdited: # pop up dialog to alert user of unsaved edits. # offer then a chance to save before exiting. # messageBox = QMessageBox(self) messageBox.setIcon(QMessageBox.Icon.Question) messageBox.setWindowTitle("Close Check") messageBox.setText("You Have Unsaved Edits") messageBox.setInformativeText( "You have made edits that have not been saved.\nReally close and not save?" ) messageBox.setStandardButtons(QMessageBox.StandardButtons.Yes | QMessageBox.StandardButtons.No) # # change the default Yes and No buttons to really say # what then mean: Yes = Save and No = Quit. # the button actions then match exactly what the dialog # is saying and there should be no disonnance. # buttonSave = messageBox.button(QMessageBox.StandardButtons.Yes) buttonSave.setText("Save") buttonQuit = messageBox.button(QMessageBox.StandardButtons.No) buttonQuit.setText("Close") messageBox.setDefaultButton(QMessageBox.StandardButtons.Yes) buttonReply = messageBox.exec() if buttonReply == QMessageBox.StandardButtons.Yes: print("QMessageBox.Save") event.accept() else: print("QMessageBox.Close") else: print("Close event") event.accept()
def change_ok_btn(self): if self._user and self._pwd: if self._user not in self._config.users_name: self._cookie = None if self._cookie: up_info = {"name": self._user, "pwd": self._pwd, "cookie": self._cookie, "work_id": -1} if self.ok_btn.text() == "切换用户": self._config.change_user(self._user) else: self._config.set_infos(up_info) self.clicked_ok.emit() self.close() elif USE_WEB_ENG: self.web = LoginWindow(self._user, self._pwd) self.web.cookie.connect(self.get_cookie_by_web) self.web.setWindowModality(Qt.WindowModality.ApplicationModal) self.web.exec() elif os.path.isfile(self._cookie_assister): try: result = os.popen(f'{self._cookie_assister} {self._user} {self._pwd}') cookie = result.read() try: self._cookie = {kv.split("=")[0].strip(" "): kv.split("=")[1].strip(" ") for kv in cookie.split(";")} except: self._cookie = None if not self._cookie: return None up_info = {"name": self._user, "pwd": self._pwd, "cookie": self._cookie, "work_id": -1} self._config.set_infos(up_info) self.clicked_ok.emit() self.close() except: pass else: title = '请使用 Cookie 登录或是选择 登录辅助程序' msg = '没有输入 Cookie,或者没有找到登录辅助程序!\n\n' + \ '推荐使用浏览器获取 cookie 填入 cookie 输入框\n\n' + \ '如果不嫌文件体积大,请下载登录辅助程序:\n' + \ 'https://github.com/rachpt/lanzou-gui/releases' message_box = QMessageBox(self) message_box.setIcon(QMessageBox.Icon.Critical) message_box.setStyleSheet(btn_style) message_box.setWindowTitle(title) message_box.setText(msg) message_box.setStandardButtons(QMessageBox.StandardButton.Close) buttonC = message_box.button(QMessageBox.StandardButton.Close) buttonC.setText('关闭') message_box.exec()
def importImages(self): """Import the images a user selects, remove duplicates, and add items to the QListWidget.""" duplicate_images = [] # Store the names of duplicate images image_paths, _ = QFileDialog.getOpenFileNames(self, "Select Image Files", "", "Images (*.png *.xpm *.jpg *.jpeg)") if image_paths: if self.image_dir.exists(): for image_path in image_paths: # Pass image path to QFileInfo object image_info = QFileInfo(image_path) file_name = image_info.fileName() item_name = image_info.baseName() # Copy the files into the Images directory, check for files # with the same name new_name = self.image_dir.absolutePath() + f"/{file_name}" file_exists = QFile.copy(image_path, new_name) if file_exists == False: duplicate_images.append(image_path) else: self.createListItems(image_path, item_name, image_info, new_name) if self.is_delete_checked == True: # Handle deleting images QFile.moveToTrash(image_path) else: QMessageBox.warning(self, "Images Location Not Found", """<p>The Images Location cannot be found. Restart the application to recreate the directory.</p>""") # Display a custom dialog to inform the user of duplicate images if len(duplicate_images) != 0: duplicates_dialog = QMessageBox(self) duplicates_dialog.setIcon(QMessageBox.Icon.Information) duplicates_dialog.setWindowTitle("Duplicate Images") duplicates_dialog.setText("""<p>Some images were not imported because they already exist.</p>""") details = '\n'.join([item for item in duplicate_images]) duplicates_dialog.setDetailedText(details) duplicates_dialog.exec() duplicate_images.clear() # Clear the list # Check if window is still in focus. If not, give it focus if self.isActiveWindow() == False: self.activateWindow()
def noticeBox(self, msg, title="Notice!"): msgBox = QMessageBox() msgBox.setText(msg) msgBox.setWindowTitle(title) msgBox.setStandardButtons(QMessageBox.StandardButtons.Ok) returnValue = msgBox.exec() if returnValue == QMessageBox.StandardButtons.Ok: return
def start_uninstall(): if installer_first_form.brUnins_dirC.isChecked(): uninstall_path = 'C:\\PyPassMan' elif installer_first_form.brUnins_dirCProgramFiles.isChecked(): uninstall_path = 'C:\\Program Files\\PyPassMan' elif installer_first_form.brUnins_CustomLocation.isChecked(): uninstall_path = installer_first_form.Unins_CustomLocationInput.text( ) response = uninstall(uninstall_path) if response == 'not a directory': error = QMessageBox() error.setText('Not a valid directory!') error.exec() elif response == 'error deleting a file': error = QMessageBox() error.setText( 'Error while deleting a file, please refer to github page for how to manually uninstall!' ) error.exec() else: uninstalled = QMessageBox() uninstalled.setText('Successfully uninstalled the program!') uninstalled.exec()
def eliminar(self): confirmacion = QMessageBox(self) confirmacion.setText( f'Desea Eliminar el Producto con ID {self.txt_producto.text()}?') confirmacion.setIcon(QMessageBox.Icon.Question) confirmacion.setDetailedText( 'El producto se eliminará definitivamente...') confirmacion.setWindowTitle('Confirmación...') confirmacion.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No) boton_yes = confirmacion.button(QMessageBox.StandardButton.Yes) confirmacion.exec() if confirmacion.clickedButton() == boton_yes: self.lbl_resultado.setText( f'Se ha eliminado el producto con ID {self.txt_producto.text()}.' ) else: self.lbl_resultado.setText( f'No se ha eliminado el producto con ID {self.txt_producto.text()}.' )
def sumar(self): numero_1 = self.txt_numero_1.text().strip() numero_2 = self.txt_numero_2.text().strip() mensaje = QMessageBox() mensaje.setWindowTitle('Algo salió mal...') if len(numero_1): if len(numero_2): try: numero_1 = float(numero_1) except: mensaje.setIcon(QMessageBox.Icon.Warning) mensaje.setText( 'El número 1 debe ser un valor numérico...') mensaje.exec() return try: numero_2 = float(numero_2) except: mensaje.setIcon(QMessageBox.Icon.Warning) mensaje.setText( 'El número 2 debe ser un valor numérico...') mensaje.exec() return resultado = numero_1 + numero_2 self.lbl_resultado.setText(str(resultado)) else: mensaje.setIcon(QMessageBox.Icon.Warning) mensaje.setText('Debes digitar el Número 2...') mensaje.exec() else: mensaje.setIcon(QMessageBox.Icon.Warning) mensaje.setText('Debes digitar el Número 1...') mensaje.exec()
class App(QWidget): def __init__(self): super().__init__() self.setWindowTitle('GitHub Abuz!') self.setWindowIcon(QIcon('icon.png')) layout = QGridLayout() vl = QVBoxLayout() hl = QHBoxLayout() hl2 = QHBoxLayout() hl3 = QHBoxLayout() self.y = QComboBox() self.name = QLineEdit() self.email = QLineEdit() self.passw = QLineEdit() self.repo = QLineEdit() self.type = QLineEdit() self.fonts = QComboBox() self.err = QMessageBox() self.nc = QSpinBox() lbl = QLabel('Commits/day:') prev = QPushButton('Translate') invert = QPushButton('Invert') leggo = QPushButton('Do it') invert.clicked.connect(self.invert) leggo.clicked.connect(self.doit) prev.clicked.connect(self.textCheck) self.name.textChanged[str].connect(self.rmph) self.email.textChanged[str].connect(self.rmph) self.passw.textChanged[str].connect(self.rmph) self.type.textChanged[str].connect(self.rmph) self.repo.textChanged[str].connect(self.rmph) self.y.addItem('Year (default: last 52 weeks)') for yr in range(datetime.datetime.now().year + 5, datetime.datetime.now().year - 20, -1): self.y.addItem(str(yr)) self.fonts.addItems(os.listdir('Fonts')) self.name.setPlaceholderText('Committer name') self.email.setPlaceholderText('Committer email') self.passw.setPlaceholderText('Password') self.passw.setEchoMode(QLineEdit.EchoMode.Password) self.repo.setPlaceholderText('Link to repo') self.type.setPlaceholderText('Translate text to tile art!') self.nc.setMinimum(1) self.nc.setValue(1) self.err.setWindowIcon(QIcon('icon.png')) self.err.setWindowTitle('Error!') hl.addWidget(self.name) hl.addWidget(self.email) hl.addWidget(self.passw) hl3.addWidget(self.repo) hl3.addWidget(self.y) hl3.addWidget(lbl) hl3.addWidget(self.nc) hl2.addWidget(self.type) hl2.addWidget(self.fonts) hl2.addWidget(prev) hl2.addWidget(invert) vl.addLayout(hl) vl.addLayout(hl3) vl.addLayout(layout) vl.addLayout(hl2) vl.addWidget(leggo) self.setLayout(vl) self.checkM = [list() for i in range(7)] for i in range(7): for j in range(52): m = QCheckBox() layout.addWidget(m, i, j) self.checkM[i].append(m) def rmph(self): self.setStyleSheet(''' QLineEdit[text=""]{ border: 1px #30363d; border-radius: 3px; padding: 1px 18px 1px 3px; background-color: #1c2128; color: #8b949e; } QLineEdit{ border: 1px #30363d; border-radius: 3px; padding: 1px 18px 1px 3px; background-color: #1c2128; color: #f0f6fc; } QLineEdit:hover { border: 0.5px solid #c9d1d9; } QLineEdit:focus { border: 1px solid #c9d1d9; }''') def getActiveDates(self, dates): ad = [] for i in range(7): for j in range(52): if self.checkM[i][j].isChecked(): ad.append(dates[i][j]) return ad def doit(self): try: year = int(self.y.currentText()) dates = self.getActiveDates(getDates(year)) except: dates = self.getActiveDates(getDates()) author = git.Actor(self.name.text(), self.email.text()) if not self.name.text() or not self.email.text(): self.err.setText('Did you enter your name and email? 🙄') self.err.exec() return repurl = "https://" + self.name.text() + ":" + self.passw.text( ) + "@" + self.repo.text()[8:] repname = repurl.split('/')[-1].split('.')[0] if not os.path.isdir(repname): try: git.cmd.Git().clone(repurl) except: self.err.setText( 'Could not clone the repo. Ensure that the remote repo exists and that you have access to it.' ) self.err.exec() return rep = git.Repo.init(repname) for date in dates: for n in range(self.nc.value()): rep.index.commit("committed for the lullzz!!", author=author, committer=author, author_date=date.isoformat()) try: rep.remotes.origin.set_url(repurl) except: rep.create_remote('origin', repurl) try: rep.remotes.origin.push() except: self.err.setText( 'Error pushing. Verify you have permissions to push to the repo and that the given credentials are correct' ) self.err.exec() return result = QMessageBox() text = f"Created {len(dates)*2} commits as {self.name.text()} <{self.email.text()}> in {repname} : {self.repo.text()}" result.setWindowIcon(QIcon('icon.png')) result.setWindowTitle('All Done!') result.setText(text) result.exec() os.remove(repname) def textCheck(self): for r in self.checkM: for m in r: m.setChecked(False) text_to_render = self.type.text() font = Font(os.path.join('Fonts', self.fonts.currentText()), 8) try: text = repr(font.render_text(text_to_render, 52, 7)) text_by_weekday = text.split('\n') for i in range(7): for j in range(51): if text_by_weekday[i][j] == '#': self.checkM[i][j].setChecked(True) except: self.err.setText('You typed too long :(') self.err.exec() def invert(self): for r in self.checkM: for m in r: if m.isChecked(): m.setChecked(False) else: m.setChecked(True)
def loadGraphics(self): dbfilename = self.obsTb.dbFilename if dbfilename != None: self.session = connectDatabase(dbfilename) else: msg = QMessageBox() # msg.setIcon(QMessageBox.Icon.Information) msg.setText('The database file is not defined.') msg.setInformativeText( 'In order to set the database file, open the Observation Toolbox' ) msg.setIcon(QMessageBox.Icon.Critical) msg.exec() return for gitem in self.gView.scene().items(): if isinstance(gitem, QGraphicsItemGroup): self.gView.scene().removeItem(gitem) q_line = self.session.query(Line) q_zone = self.session.query(Zone) if q_line.all() == [] and q_zone.all() == []: QMessageBox.information(self, 'Warning!', 'There is no graphics to load!') return line_items = [] for line in q_line: p1 = line.points[0] p2 = line.points[1] if line.type != None: lineType = line.type.name else: lineType = None gItmGroup = self.generate_itemGroup([p1.x, p2.x], [p1.y, p2.y], str(line.idx), lineType) self.gScene.addItem(gItmGroup) line_items.append(str(line.idx)) self.obsTb.line_list_wdgt.clear() self.obsTb.line_list_wdgt.addItems(line_items) self.obsTb.line_list_wdgt.setCurrentRow(0) self.obsTb.line_newRecButton.setEnabled(False) self.obsTb.line_saveButton.setEnabled(True) self.obsTb.line_saveButton.setText('Edit line(s)') self.obsTb.line_saveButton.setIcon(QIcon('icons/edit.png')) zone_items = [] for zone in q_zone: if zone.type != None: zoneType = zone.type.name else: zoneType = None gItmGroup = self.generate_itemGroup( [point.x for point in zone.points], [point.y for point in zone.points], str(zone.idx), zoneType) self.gScene.addItem(gItmGroup) zone_items.append(str(zone.idx)) self.obsTb.zone_list_wdgt.clear() self.obsTb.zone_list_wdgt.addItems(zone_items) self.obsTb.zone_list_wdgt.setCurrentRow(0) self.obsTb.zone_newRecButton.setEnabled(False) self.obsTb.zone_saveButton.setEnabled(True) self.obsTb.zone_saveButton.setText('Edit zone(s)') self.obsTb.zone_saveButton.setIcon(QIcon('icons/edit.png'))