def toolsGenOptions(self): """Set general user preferences for all files. """ oldAutoSaveMinutes = globalref.genOptions['AutoSaveMinutes'] oldColorTheme = globalref.genOptions['ColorTheme'] dialog = options.OptionDialog(globalref.genOptions, QApplication.activeWindow()) dialog.setWindowTitle(_('General Options')) if (dialog.exec_() == QDialog.Accepted and globalref.genOptions.modified): globalref.genOptions.writeFile() self.recentFiles.updateOptions() if globalref.genOptions['MinToSysTray']: self.createTrayIcon() elif self.trayIcon: self.trayIcon.hide() autoSaveMinutes = globalref.genOptions['AutoSaveMinutes'] for control in self.localControls: for window in control.windowList: window.updateWinGenOptions() control.structure.undoList.setNumLevels() control.updateAll(False) if autoSaveMinutes != oldAutoSaveMinutes: control.resetAutoSave() if globalref.genOptions['ColorTheme'] != oldColorTheme: QMessageBox.warning( QApplication.activeWindow(), 'TreeLine', _('Application must be restarted for ' 'color theme changes to take effect'))
def interactiveImport(self, addWarning=False): """Prompt the user for import type & proceed with import. Return the structure if import is successful, otherwise None Arguments: addWarning - if True, add non-valid file warning to dialog """ dialog = miscdialogs.RadioChoiceDialog(_('Import File'), _('Choose Import Method'), methods.items(), QApplication.activeWindow()) if addWarning: fileName = self.pathObj.name dialog.addLabelBox( _('Invalid File'), _('"{0}" is not a valid TreeLine file.\n\n' 'Use an import filter?').format(fileName)) if dialog.exec_() != QDialog.Accepted: return None method = dialog.selectedButton() if not self.pathObj: filters = ';;'.join((globalref.fileFilters[fileFilters[method]], globalref.fileFilters['all'])) defaultFilePath = str(globalref.mainControl.defaultPathObj(True)) filePath, selFltr = QFileDialog.getOpenFileName( QApplication.activeWindow(), _('TreeLine - Import File'), defaultFilePath, filters) if not filePath: return None self.pathObj = pathlib.Path(filePath) self.errorMessage = '' try: QApplication.setOverrideCursor(Qt.WaitCursor) structure = getattr(self, method)() QApplication.restoreOverrideCursor() except IOError: QApplication.restoreOverrideCursor() QMessageBox.warning( QApplication.activeWindow(), 'TreeLine', _('Error - could not read file {0}').format(self.pathObj)) return None except UnicodeDecodeError: prevEncoding = globalref.localTextEncoding globalref.localTextEncoding = 'utf-8' structure = getattr(self, method)() globalref.localTextEncoding = prevEncoding QApplication.restoreOverrideCursor() if not structure: message = _('Error - improper format in {0}').format(self.pathObj) if self.errorMessage: message = '{0}\n{1}'.format(message, self.errorMessage) self.errorMessage = '' QMessageBox.warning(QApplication.activeWindow(), 'TreeLine', message) return structure
def checkAutoSave(self, pathObj): """Check for presence of auto save file & prompt user. Return True if OK to contimue, False if aborting or already loaded. Arguments: pathObj -- the base path object to search for a backup """ if not globalref.genOptions['AutoSaveMinutes']: return True basePath = pathObj pathObj = pathlib.Path(str(pathObj) + '~') if not pathObj.is_file(): return True msgBox = QMessageBox( QMessageBox.Information, 'TreeLine', _('Backup file "{}" exists.\nA previous ' 'session may have crashed').format(pathObj), QMessageBox.NoButton, QApplication.activeWindow()) restoreButton = msgBox.addButton(_('&Restore Backup'), QMessageBox.ApplyRole) deleteButton = msgBox.addButton(_('&Delete Backup'), QMessageBox.DestructiveRole) cancelButton = msgBox.addButton(_('&Cancel File Open'), QMessageBox.RejectRole) msgBox.exec_() if msgBox.clickedButton() == restoreButton: self.openFile(pathObj) if self.activeControl.filePathObj != pathObj: return False try: basePath.unlink() pathObj.rename(basePath) except OSError: QMessageBox.warning( QApplication.activeWindow(), 'TreeLine', _('Error - could not rename "{0}" to "{1}"').format( pathObj, basePath)) return False self.activeControl.filePathObj = basePath self.activeControl.updateWindowCaptions() self.recentFiles.removeItem(pathObj) self.recentFiles.addItem(basePath) return False elif msgBox.clickedButton() == deleteButton: try: pathObj.unlink() except OSError: QMessageBox.warning( QApplication.activeWindow(), 'TreeLine', _('Error - could not remove backup file {}').format( pathObj)) else: # cancel button return False return True
def showLectures(self): for i in range(len(self.lecture_list)): item = QListWidgetItem(self.viewer) custom_widget = lecture_group(self.lecture_list[i], QApplication.activeWindow(),self) item.setSizeHint(custom_widget.sizeHint()) self.viewer.setItemWidget(item, custom_widget) self.viewer.addItem(item) item = QListWidgetItem(self.viewer) custom_widget = lecture_group('add', QApplication.activeWindow(),self) item.setSizeHint(custom_widget.sizeHint()) self.viewer.setItemWidget(item, custom_widget) self.viewer.addItem(item)
def group_add(self, result_parse): if len(result_parse) == 3: self.close() msg = QMessageBox() msg.setStyleSheet("background-color:#FFFFFF") msg.setText(result_parse[1] + " " + result_parse[2]) group_add = msg.addButton('추가', QMessageBox.YesRole) group_cancel = msg.addButton('취소', QMessageBox.NoRole) msg.setWindowFlag(QtCore.Qt.FramelessWindowHint) msg.exec_() # 그룹 추가 if msg.clickedButton() == group_add: # 그룹 추가 서버로 요청 commend = "group_add " + result_parse[0] + " " + str(self.stuid) self.clientSocket.send(commend.encode('utf-8')) # 반환 결과 result = self.clientSocket.recv(1024) result = result.decode('utf-8') if result == 'already': msg = QMessageBox() msg.setStyleSheet("background-color:#FFFFFF") msg.setText("그룹에 이미 속해있습니다.") msg.setWindowFlag(QtCore.Qt.FramelessWindowHint) msg.exec_() else: self.lecId.append(result_parse[0]) self.viewer.clear() lecture_list = self.getLectureList() for i in range(len(lecture_list)): item = QListWidgetItem(self.viewer) custom_widget = lecture_group(lecture_list[i], QApplication.activeWindow(),self.lecture_list_widget) item.setSizeHint(custom_widget.sizeHint()) self.viewer.setItemWidget(item, custom_widget) self.viewer.addItem(item) item = QListWidgetItem(self.viewer) custom_widget = lecture_group('add', QApplication.activeWindow(), self.lecture_list_widget) item.setSizeHint(custom_widget.sizeHint()) self.viewer.setItemWidget(item, custom_widget) self.viewer.addItem(item) else: msg = QMessageBox() msg.setStyleSheet("background-color:#FFFFFF") msg.setText("그룹이 존재하지 않습니다.") msg.setWindowFlag(QtCore.Qt.FramelessWindowHint) msg.exec_()
def clearPictureCacheTriggered(self): title = tr("Clear Picture Cache") msg = tr("Do you really want to remove all your cached picture analysis?") if self.confirm(title, msg, QMessageBox.No): self.model.clear_picture_cache() active = QApplication.activeWindow() QMessageBox.information(active, title, tr("Picture cache cleared."))
def toolsCustomShortcuts(self): """Show dialog to customize keyboard commands. """ actions = self.activeControl.activeWindow.allActions dialog = miscdialogs.CustomShortcutsDialog(actions, QApplication.activeWindow()) dialog.exec_()
def open(self): desktop = QApplication.desktop() is_fullscreen = desktop.screenCount() > 1 other_screen_x = 1024 other_screen_x = 1024 if is_fullscreen: screen_widget_on = desktop.screenNumber( QApplication.activeWindow()) next_screen_not_in_use = (screen_widget_on + 1) % desktop.screenCount() other_screen_geometry = desktop.screenGeometry( next_screen_not_in_use) self.move(other_screen_geometry.x(), other_screen_geometry.y()) self.showFullScreen() else: self.resize(1024, 1024) self.show() self.scene().setSceneRect(0, 0, other_screen_geometry.width(), other_screen_geometry.height()) # self.scene().setSceneRect(-other_screen_geometry.width() / 2, # -other_screen_geometry.height() / 2, # other_screen_geometry.width(), # other_screen_geometry.height()) #self.scene().setSceneRect(0, 0, other_screen_geometry.width(), other_screen_geometry.height()) self.scene().update_background() #self.scene().background_image.setPos(self.scene().sceneRect().topLeft()) self.showFullScreen() if is_fullscreen else self.show() self.centerOn(self.scene().sceneRect().center())
def _get_parent_wnd(): parent = QApplication.activePopupWidget() if not parent: parent = QApplication.activePopupWidget() if not parent: parent = QApplication.activeWindow() return parent
def event(self, event: 'QEvent') -> bool: if event.type() == QEvent.KeyPress: for key_iter in self.__shortCutKeyList(self.__currentWidget()): if event.key() == key_iter - Qt.CTRL: ExecuteLogger.printLog( f'Exec ShortCut: {QKeySequence(key_iter).toString()} at {self.__currentWidget()}' ) func = self.__shortCutFunction(self.__currentWidget(), key_iter) func() if QApplication.activeWindow().activeView( ) != self.__currentWidget(): self.__current_widget = QApplication.activeWindow( ).activeView() return True return super().event(event)
def BuildShotUI(): global ex if ex is not None: ex.close() parent = QApplication.activeWindow() ex = convertWindow(parent) ex.show()
def spellCheck(self): """Spell check starting with the selected branches. """ parentWidget = QApplication.activeWindow() spellCheckDialog = SpellCheckDialog(self.spellCheckInterface, parentWidget) spellCheckDialog.misspellFound.connect(self.updateSelection) spellCheckDialog.changeRequest.connect(self.changeNode) origBranches = self.selectModel.selectedBranchSpots() if not origBranches: origBranches = self.controlRef.structure.rootSpots() result = (spellCheckDialog.startSpellCheck( self.textLineGenerator(origBranches))) self.selectModel.selectSpots(origBranches, expandParents=True) if result and origBranches[0].parentSpot.parentSpot: prompt = _('Finished checking the branch\nContinue from the top?') ans = QMessageBox.information(parentWidget, _('TreeLine Spell Check'), prompt, QMessageBox.Yes | QMessageBox.No) if ans == QMessageBox.Yes: generator = self.textLineGenerator( self.controlRef.structure.rootSpots()) result = spellCheckDialog.startSpellCheck(generator) self.selectModel.selectSpots(origBranches, expandParents=True) else: result = False if result: QMessageBox.information(parentWidget, _('TreeLine Spell Check'), _('Finished spell checking'))
def _get_tab_registry(win_id: _WindowTab, tab_id: _WindowTab) -> ObjectRegistry: """Get the registry of a tab.""" if tab_id is None: raise ValueError("Got tab_id None (win_id {})".format(win_id)) if tab_id == 'current' and win_id is None: window = QApplication.activeWindow() # type: typing.Optional[QWidget] if window is None or not hasattr(window, 'win_id'): raise RegistryUnavailableError('tab') win_id = window.win_id elif win_id is not None: window = window_registry[win_id] else: raise TypeError("window is None with scope tab!") if tab_id == 'current': tabbed_browser = get('tabbed-browser', scope='window', window=win_id) tab = tabbed_browser.widget.currentWidget() if tab is None: raise RegistryUnavailableError('window') tab_id = tab.tab_id tab_registry = get('tab-registry', scope='window', window=win_id) try: return tab_registry[tab_id].registry except AttributeError: raise RegistryUnavailableError('tab')
def register(self, nick, department): if self.regi_qual == 1: #새로운 아이디일때 (밑으로는 모두 한단계 indendation이 되었다.) commend = 'register ' + nick + " " + department + " " + self.studName + " " + self.studId self.clientSocket.send(commend.encode('utf-8')) res = self.clientSocket.recv(1024) if res.decode('utf-8') == 'registered': commend = 'courses_create ' + self.studId + " " + self.courses self.clientSocket.send(commend.encode('utf-8')) course_res = self.clientSocket.recv(1024).decode('utf-8') commend = 'login ' + self.studId self.clientSocket.send(commend.encode('utf-8')) # 결과 도착 server_msg = self.clientSocket.recv(1024) lectureId = server_msg.decode('utf-8') mainW = QApplication.activeWindow() self.afterLogin = after_login.App(mainW, self.studId, self.studName, lectureId) mainW.setCentralWidget(self.afterLogin) self.close() elif self.regi_qual == 0: send_noCheck = QMessageBox() send_noCheck.setStyleSheet("background-color:#FFFFFF") send_noCheck.setText("ERROR[확인X]: 중복검사 확인필요") send_noCheck.exec_()
def filePrintPdf(self): """Export to a PDF file with current options. """ filters = ';;'.join( (globalref.fileFilters['pdf'], globalref.fileFilters['all'])) defaultFilePath = str(globalref.mainControl.defaultPathObj()) defaultFilePath = os.path.splitext(defaultFilePath)[0] if os.path.basename(defaultFilePath): defaultFilePath = '{0}.{1}'.format(defaultFilePath, 'pdf') filePath, selectFilter = QFileDialog.getSaveFileName( QApplication.activeWindow(), _('TreeLine - Export PDF'), defaultFilePath, filters) if not filePath: return if not os.path.splitext(filePath)[1]: filePath = '{0}.{1}'.format(filePath, 'pdf') origFormat = self.printer.outputFormat() self.printer.setOutputFormat(QPrinter.PdfFormat) self.printer.setOutputFileName(filePath) self.adjustSpacing() self.setupData() self.paintData(self.printer) self.printer.setOutputFormat(origFormat) self.printer.setOutputFileName('') self.adjustSpacing()
def toolsCustomToolbars(self): """Show dialog to customize toolbar buttons. """ actions = self.activeControl.activeWindow.allActions dialog = miscdialogs.CustomToolbarDialog(actions, self.updateToolbars, QApplication.activeWindow()) dialog.exec_()
def filePrint(self): """Show dialog and print tree output based on current options. """ self.printer.setOutputFormat(QPrinter.NativeFormat) self.setupData() printDialog = QPrintDialog(self.printer, QApplication.activeWindow()) if printDialog.exec_() == QDialog.Accepted: self.paintData(self.printer)
def clearCacheTriggered(self): title = tr("Clear Cache") msg = tr( "Do you really want to clear the cache? This will remove all cached file hashes and picture analysis." ) if self.confirm(title, msg, QMessageBox.No): self.model.clear_picture_cache() self.model.clear_hash_cache() active = QApplication.activeWindow() QMessageBox.information(active, title, tr("Cache cleared."))
def getExistingDirectory( basedir: Optional[str] = None, title: str = "Pineboo" ) -> Optional[str]: """Show a dialog to choose a directory.""" dir_ = basedir if basedir and os.path.exists(basedir) else "%s/" % os.getenv("HOME") ret = QFileDialog.getExistingDirectory( QApplication.activeWindow(), title, dir_, QFileDialog.ShowDirsOnly ) return "%s/" % ret if ret else ret
def changeEvent(self, event): """Detect an activation of the main window and emit a signal. Arguments: event -- the change event object """ super().changeEvent(event) if (event.type() == QEvent.ActivationChange and QApplication.activeWindow() == self): self.winActivated.emit(self)
def printPreview(self): """Show a preview of printing results. """ self.setupData() previewDialog = printdialogs.PrintPreviewDialog( self, QApplication.activeWindow()) previewDialog.previewWidget.paintRequested.connect(self.paintData) if globalref.genOptions['SaveWindowGeom']: previewDialog.restoreDialogGeom() previewDialog.exec_()
def update(self): prev_cur_pos = self.dlgUI.logPTE.verticalScrollBar().value() self.dlgUI.logPTE.setPlainText(self.logtext) if QApplication.activeWindow() != self.qtDlg: self.dlgUI.logPTE.moveCursor(QTextCursor.End) self.dlgUI.logPTE.ensureCursorVisible() else: self.dlgUI.logPTE.moveCursor(QTextCursor.End) new_cur_pos = self.dlgUI.logPTE.verticalScrollBar().setValue(prev_cur_pos)
def activeWindow(): """Return the currently active MainWindow. Only returns None if there are no windows at all. """ if windows: w = QApplication.activeWindow() if w in windows: return w return windows[0]
def __init__(self, controlRef): """Initialize the spell check engine interface. Arguments: controlRef - the local control """ self.controlRef = controlRef self.selectModel = controlRef.currentSelectionModel() self.currentSpot = None self.currentField = '' self.lineNum = 0 self.textLine = '' parentWidget = QApplication.activeWindow() path = globalref.miscOptions['SpellCheckPath'] while True: try: self.spellCheckInterface = SpellCheckInterface(path, self.controlRef. spellCheckLang) return except SpellCheckError: if path: path = '' else: if sys.platform.startswith('win'): prompt = (_('Could not find either aspell.exe, ' 'ispell.exe or hunspell.exe\n' 'Browse for location?')) ans = QMessageBox.warning(parentWidget, _('Spell Check Error'), prompt, QMessageBox.Yes | QMessageBox.Cancel, QMessageBox.Yes) if ans == QMessageBox.Cancel: raise title = _('Locate aspell.exe, ipsell.exe or ' 'hunspell.exe') path, fltr = QFileDialog.getOpenFileName(parentWidget, title, '', _('Program (*.exe)')) if path: path = path[:-4] if ' ' in path: path = '"{0}"'.format(path) globalref.miscOptions.changeValue('SpellCheckPath', path) globalref.miscOptions.writeFile() else: prompt = (_('TreeLine Spell Check Error\nMake sure ' 'aspell, ispell or hunspell is installed')) QMessageBox.warning(parentWidget, 'TreeLine', prompt) raise
def cursor_busy(*args, **kwargs): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) try: return function(*args, **kwargs) except Exception as e: QMessageBox.warning(QApplication.activeWindow(), "Warning", "Error {}".format(e.args[0])) if config.DEBUG: print("Error {}".format(e.args[0])) raise e finally: QApplication.restoreOverrideCursor()
def closeEvent(self, evnt): res = QMessageBox.information( QApplication.activeWindow(), "Salir de Pineboo", "¿ Desea salir ?", QMessageBox.Yes, QMessageBox.No) if res == QMessageBox.No: evnt.ignore() self.saveState()
def fileOpen(self): """Prompt for a filename and open it. """ if (globalref.genOptions['OpenNewWindow'] or self.activeControl.checkSaveChanges()): filters = ';;'.join((globalref.fileFilters['trlnopen'], globalref.fileFilters['all'])) fileName, selFilter = QFileDialog.getOpenFileName( QApplication.activeWindow(), _('TreeLine - Open File'), str(self.defaultPathObj(True)), filters) if fileName: self.openFile(pathlib.Path(fileName))
def changeEvent(self, event): """Detect an activation of the main window and emit a signal. Arguments: event -- the change event object """ super().changeEvent(event) if (event.type() == QEvent.ActivationChange and QApplication.activeWindow() == self): self.winActivated.emit(self) elif (event.type() == QEvent.WindowStateChange and globalref.genOptions['MinToSysTray'] and self.isMinimized()): self.winMinimized.emit()
def showList(self): self.rightSideInfo.close() if self.menu_lec == None: self.menu_lec = lec.lecture_list(self.studId, self.lecId, QApplication.activeWindow()) self.rightSideInfo = self.menu_lec else: self.rightSideInfo = self.menu_lec self.rightSideInfo.show() self.rightSideInfo.setMinimumSize(300, 500) self.rightSideLayout.addWidget(self.rightSideInfo)
def eventFilter(self, obj, event): """Handle mouse clicks on swatches. """ if obj == self.swatch and event.type() == QEvent.MouseButtonRelease: color = QColorDialog.getColor( self.currentColor, QApplication.activeWindow(), _('Select {0} color').format(self.roleKey)) if color.isValid() and color != self.currentColor: self.currentColor = color self.changeSwatchColor() self.colorChanged.emit() return True return False
def helpViewBasic(self): """Display basic usage instructions. """ if not self.basicHelpView: path = self.findResourceFile('basichelp.html', 'doc', docPath) if not path: QMessageBox.warning(QApplication.activeWindow(), 'TreeLine', _('Error - basic help file not found')) return self.basicHelpView = helpview.HelpView(path, _('TreeLine Basic Usage'), globalref.toolIcons) self.basicHelpView.show()
def keep_position(*args, **kwargs): cls = args[clas_pos] try: expList = saveExpandedState(cls) return function(*args, **kwargs) except Exception as e: QMessageBox.warning(QApplication.activeWindow(), "Warning", "Error {}".format(e.args[0])) if config.DEBUG: print("Error {}".format(e.args[0])) raise e finally: restoreExpandedState(expList, cls)
def exception_message(log_lines, exc_info): stacktrace = traceback.format_exception(*exc_info) if exc_info else "" message = """ {log_lines} ---- {stacktrace} """.format(log_lines='\n'.join(log_lines), stacktrace='\n'.join(stacktrace)) mb = QMessageBox(QMessageBox.Critical, "Critical error", """A critical error occured. Select the details to display it. Please report it to <a href='https://github.com/duniter/sakia/issues/new/'>the developers github</a>""", QMessageBox.Ok, QApplication.activeWindow()) mb.setDetailedText(message) mb.setTextFormat(Qt.RichText) mb.exec()
def _parent(self): return QApplication.activeWindow()
def show_message(self, msg): window = QApplication.activeWindow() QMessageBox.information(window, '', msg)
def confirm(self, title, msg, default_button=QMessageBox.Yes): active = QApplication.activeWindow() buttons = QMessageBox.Yes | QMessageBox.No answer = QMessageBox.question(active, title, msg, buttons, default_button) return answer == QMessageBox.Yes