def start(self, path): """ Public slot to start the tags command. @param path name of directory to list conflicts for (string) """ self.errorGroup.hide() QApplication.processEvents() self.intercept = False dname, fname = self.vcs.splitPath(path) # find the root of the repo self.__repodir = dname while not os.path.isdir( os.path.join(self.__repodir, self.vcs.adminDir)): self.__repodir = os.path.dirname(self.__repodir) if os.path.splitdrive(self.__repodir)[1] == os.sep: return self.activateWindow() self.raise_() self.conflictsList.clear() self.__started = True self.__getEntries()
def main(latus_appdata_folder): latus.logger.log.info("latus_app_data: %s" % latus_appdata_folder) # check if we should run the setup wizard first if latus.preferences.preferences_db_exists(latus_appdata_folder): pref = latus.preferences.Preferences(latus_appdata_folder) else: pref = None app = QApplication(sys.argv) # need this even for the GUIWizard if not pref or (pref and not pref.folders_are_set()): latus.logger.log.info('not all preferences are set - starting WizardGUI') app_gui_wizard = latus.gui_wizard.GUIWizard(latus_appdata_folder) app_gui_wizard.exec_() pref = latus.preferences.Preferences(latus_appdata_folder) if pref and pref.folders_are_set(): app.setQuitOnLastWindowClosed(False) # so popup dialogs don't close the system tray icon system_tray = LatusSystemTrayIcon(app, latus_appdata_folder) system_tray.start_latus() system_tray.show() app.exec_() else: msg = 'Incomplete configuration.\n\nPlease re-run Latus and complete the Latus Setup Wizard.\n\nExiting ...' mb = message_box(msg) mb.exec() latus.logger.log.warn(msg.replace('\n', ' ')) # don't put newlines in the log sys.exit(1)
def main(): app = QApplication(sys.argv) w = MainWidget() w.setWindowTitle("Игра \"Жизнь\"") w.setFixedSize(w.geometry().width(), w.geometry().height()) w.show() return app.exec_()
def findFiles(self, files, text): progressDialog = QProgressDialog(self) progressDialog.setCancelButtonText("&Cancel") progressDialog.setRange(0, files.count()) progressDialog.setWindowTitle("Find Files") foundFiles = [] for i in range(files.count()): progressDialog.setValue(i) progressDialog.setLabelText("Searching file number %d of %d..." % (i, files.count())) QApplication.processEvents() if progressDialog.wasCanceled(): break inFile = QFile(self.currentDir.absoluteFilePath(files[i])) if inFile.open(QIODevice.ReadOnly): stream = QTextStream(inFile) while not stream.atEnd(): if progressDialog.wasCanceled(): break line = stream.readLine() if text in line: foundFiles.append(files[i]) break progressDialog.close() return foundFiles
def __finish(self): """ Private slot called when the user pressed the button. """ QApplication.restoreOverrideCursor() self.buttonBox.button(QDialogButtonBox.Cancel).setEnabled(False) self.buttonBox.button(QDialogButtonBox.Close).setEnabled(True) self.buttonBox.button(QDialogButtonBox.Close).setDefault(True) tc = self.contents.textCursor() tc.movePosition(QTextCursor.Start) self.contents.setTextCursor(tc) self.contents.ensureCursorVisible() self.filesCombo.addItem(self.tr("<Start>"), 0) self.filesCombo.addItem(self.tr("<End>"), -1) for oldFile, newFile, pos in sorted(self.__fileSeparators): if oldFile != newFile: self.filesCombo.addItem( "{0}\n{1}".format(oldFile, newFile), pos) else: self.filesCombo.addItem(oldFile, pos) self._cancel()
def pixmap(name, size, mode, state): """Returns a (possibly cached) pixmap of the name and size with the default text color. The state argument is ignored for now. """ if mode == QIcon.Selected: color = QApplication.palette().highlightedText().color() else: color = QApplication.palette().text().color() key = (name, size.width(), size.height(), color.rgb(), mode) try: return _pixmaps[key] except KeyError: i = QImage(size, QImage.Format_ARGB32_Premultiplied) i.fill(0) painter = QPainter(i) # render SVG symbol QSvgRenderer(os.path.join(__path__[0], name + ".svg")).render(painter) # recolor to text color painter.setCompositionMode(QPainter.CompositionMode_SourceIn) painter.fillRect(i.rect(), color) painter.end() # let style alter the drawing based on mode, and create QPixmap pixmap = QApplication.style().generatedIconPixmap(mode, QPixmap.fromImage(i), QStyleOption()) _pixmaps[key] = pixmap return pixmap
def QVTKRenderWidgetConeExample(): """A simple example that uses the QVTKRenderWindowInteractor class.""" # every QT app needs an app app = QApplication(['QVTKRenderWindowInteractor']) # create the widget widget = QVTKRenderWindowInteractor() widget.Initialize() widget.Start() # if you dont want the 'q' key to exit comment this. widget.AddObserver("ExitEvent", lambda o, e, a=app: a.quit()) ren = vtk.vtkRenderer() widget.GetRenderWindow().AddRenderer(ren) cone = vtk.vtkConeSource() cone.SetResolution(8) coneMapper = vtk.vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) coneActor = vtk.vtkActor() coneActor.SetMapper(coneMapper) ren.AddActor(coneActor) # show the widget widget.show() # start event processing app.exec_()
def test_spectrum(self): port = self.__get_free_port() spectrum_dialog = self.__get_spectrum_dialog() spectrum_dialog.device.set_server_port(port) spectrum_dialog.ui.btnStart.click() self.assertEqual(len(spectrum_dialog.scene_manager.peak), 0) data = np.array([complex(1, 1), complex(2, 2), complex(3, 3)], dtype=np.complex64) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.connect(("127.0.0.1", port)) sock.sendall(data.tostring()) sock.shutdown(socket.SHUT_RDWR) sock.close() QApplication.instance().processEvents() QTest.qWait(self.SEND_RECV_TIMEOUT) self.assertGreater(len(spectrum_dialog.scene_manager.peak), 0) spectrum_dialog.ui.btnStop.click() self.__close_dialog(spectrum_dialog)
def test_send(self): port = self.__get_free_port() receive_dialog = self.__get_recv_dialog() receive_dialog.device.set_server_port(port) receive_dialog.ui.btnStart.click() send_dialog = self.__get_send_dialog() send_dialog.device.set_client_port(port) send_dialog.ui.spinBoxNRepeat.setValue(2) send_dialog.ui.btnStart.click() QApplication.instance().processEvents() QTest.qWait(self.SEND_RECV_TIMEOUT) self.assertEqual(receive_dialog.device.current_index, 2 * self.signal.num_samples) self.assertTrue(np.array_equal(receive_dialog.device.data[:receive_dialog.device.current_index // 2], self.signal.data)) self.assertEqual(send_dialog.send_indicator.rect().width(), self.signal.num_samples) self.assertFalse(send_dialog.ui.btnClear.isEnabled()) send_dialog.on_clear_clicked() self.assertEqual(send_dialog.send_indicator.rect().width(), 0) send_dialog.ui.btnStop.click() self.assertFalse(send_dialog.ui.btnStop.isEnabled()) receive_dialog.ui.btnStop.click() self.assertFalse(receive_dialog.ui.btnStop.isEnabled()) self.__close_dialog(receive_dialog) self.__close_dialog(send_dialog)
def __init__(self): super().__init__() self.player = Player(self) self.player_mode_manager = PlayerModeManager(self) self.request = Request(self) self.server = Server(self) self.theme_manager = ThemeManager(self) self.tips_manager = TipsManager(self) self.hotkey_manager = Hotkey(self) self.plugins_manager = PluginsManager(self) self.version_manager = VersionManager(self) self.theme_manager.set_theme(DEFAULT_THEME_NAME) self.ui = Ui(self) self._init_managers() self.player_pixmap = None self.resize(960, 600) self.setObjectName('app') QApplication.setWindowIcon(QIcon(APP_ICON)) self.set_theme_style() self.bind_signal() self.test()
def make_zip(self): """Try to make a ZIP file.""" try: # iterate over lists of folders to backup for folder_to_backup in self.origins: percentage = int(self.origins.index(folder_to_backup) / len(self.origins) * 100) self.setLabelText(self.template.format( folder_to_backup[:99], self.destination.lower()[:99], self._date, datetime.now().isoformat()[:-7], self.seconds_time_to_human_str(time.time() - self._time), len(self.origins) - self.origins.index(folder_to_backup), percentage)) self.setValue(percentage) QApplication.processEvents() # Forces the UI to Update log.info("Folder to backup: {}.".format(folder_to_backup)) shutil.make_archive(folder_to_backup, "zip", folder_to_backup, logger=log) self.move_zip(folder_to_backup + ".zip") except Exception as reason: log.warning(reason) else: log.info("Copia de Seguridad Backup Termino bien.") finally: log.info("Finished BackUp from {} to {}.".format( self.origins, self.destination))
def openFile(self): path, _ = QFileDialog.getOpenFileName( self, self.tr("Open File"), '', platformSpecific.fileFormat ) if path: QApplication.instance().openFile(path)
def __searchingFinished(self, hits): """ Private slot to handle the end of the search. @param hits number of hits (integer) (unused) """ QApplication.restoreOverrideCursor()
def main(args): app = QApplication([]) main_frame = QFrame() layout = QVBoxLayout(main_frame) number_edit = PyQtExtras.NumberEdit() number_edit.set_value(10) print "Current value of 1 is: " + str(number_edit.get_value()) number_edit2 = PyQtExtras.NumberEdit(max_length=2) number_edit2.set_value(2) print "Current value of 2 is: " + str(number_edit2.get_value()) number_edit2.set_value(20) print "Current value of 2 is: " + str(number_edit2.get_value()) number_edit3 = PyQtExtras.NumberEdit(max_length=1) number_edit3.set_value(2) print "Current value of 3 is: " + str(number_edit3.get_value()) number_edit3.set_value(50) print "Current values of 3 is: " + str(number_edit3.get_value()) number_edit3.set_value(25) print "Current value of 3 is: " + str(number_edit3.get_value()) number_edit3.set_value("text") print "Current value of 3 is: " + str(number_edit3.get_value()) layout.addWidget(number_edit) layout.addWidget(number_edit2) layout.addWidget(number_edit3) main_frame.show() app.exec_()
def saveFileDialog(self): fname = self.filename() if fname == None: directory = "." else: directory = QFileInfo(fname).path() if util.isWindows(): # required for native looking file window fname = QFileDialog.getSaveFileName( self.win, "%s - Save As" % QApplication.applicationName(), directory, "%s (*.json)" % QApplication.applicationName()) self.writeDocumentToFile(fname) else: # access through non-blocking callback fdialog = QFileDialog( self.win, "%s - Save As" % QApplication.applicationName(), directory, "%s (*.json)" % QApplication.applicationName()) fdialog.setAcceptMode(QFileDialog.AcceptSave) fdialog.setWindowFlags(Qt.Sheet) fdialog.setWindowModality(Qt.WindowModal) self.filesavedialog = fdialog self.filesavedialog.filesSelected.connect( self.saveFileDialogCallback) fdialog.open()
def test_receive(self): port = self.__get_free_port() receive_dialog = self.__get_recv_dialog() receive_dialog.device.set_server_port(port) receive_dialog.ui.btnStart.click() data = np.array([complex(1, 2), complex(3, 4), complex(5, 6)], dtype=np.complex64) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.connect(("127.0.0.1", port)) sock.sendall(data.tostring()) sock.shutdown(socket.SHUT_RDWR) sock.close() QApplication.instance().processEvents() QTest.qWait(self.SEND_RECV_TIMEOUT) self.assertEqual(receive_dialog.device.current_index, 3) self.assertTrue(np.array_equal(receive_dialog.device.data[:3], data)) receive_dialog.ui.btnStop.click() receive_dialog.ui.btnClear.click() self.assertEqual(receive_dialog.device.current_index, 0) self.__close_dialog(receive_dialog)
def _die(message, exception=None): """Display an error message using Qt and quit. We import the imports here as we want to do other stuff before the imports. Args: message: The message to display. exception: The exception object if we're handling an exception. """ from PyQt5.QtWidgets import QApplication, QMessageBox from PyQt5.QtCore import Qt if ("--debug" in sys.argv or "--no-err-windows" in sys.argv) and exception is not None: print(file=sys.stderr) traceback.print_exc() app = QApplication(sys.argv) if "--no-err-windows" in sys.argv: print(message, file=sys.stderr) print("Exiting because of --no-err-windows.", file=sys.stderr) else: message += "<br/><br/><br/><b>Error:</b><br/>{}".format(exception) msgbox = QMessageBox(QMessageBox.Critical, "qutebrowser: Fatal error!", message) msgbox.setTextFormat(Qt.RichText) msgbox.resize(msgbox.sizeHint()) msgbox.exec_() app.quit() sys.exit(1)
def __finish(self): """ Private slot called when the process finished or the user pressed the button. """ QApplication.restoreOverrideCursor() self.buttonBox.button(QDialogButtonBox.Close).setEnabled(True) self.buttonBox.button(QDialogButtonBox.Cancel).setEnabled(False) self.buttonBox.button(QDialogButtonBox.Close).setDefault(True) self.refreshButton.setEnabled(True) self.__updateButtons() self.__updateCommitButton() self.__statusFilters.sort() self.__statusFilters.insert(0, "<{0}>".format(self.tr("all"))) self.statusFilterCombo.addItems(self.__statusFilters) for act in self.menuactions: act.setEnabled(True) self.__resizeColumns() self.__resort() self._cancel()
def run(): """ Creates all the top-level assets for the application, sets things up and then runs the application. """ setup_logging() logging.info('Starting Mu {}'.format(__version__)) # The app object is the application running on your computer. app = QApplication(sys.argv) # Display a friendly "splash" icon. splash = QSplashScreen(load_pixmap('icon')) splash.show() # Create the "window" we'll be looking at. editor_window = Window() # Create the "editor" that'll control the "window". editor = Editor(view=editor_window) # Setup the window. editor_window.closeEvent = editor.quit editor_window.setup(editor.theme) editor.restore_session() # Connect the various buttons in the window to the editor. button_bar = editor_window.button_bar button_bar.connect("new", editor.new, "Ctrl+N") button_bar.connect("load", editor.load, "Ctrl+O") button_bar.connect("save", editor.save, "Ctrl+S") button_bar.connect("flash", editor.flash) button_bar.connect("repl", editor.toggle_repl) button_bar.connect("zoom-in", editor.zoom_in) button_bar.connect("zoom-out", editor.zoom_out) button_bar.connect("theme", editor.toggle_theme) button_bar.connect("quit", editor.quit) # Finished starting up the application, so hide the splash icon. splash.finish(editor_window) # Stop the program after the application finishes executing. sys.exit(app.exec_())
def copy_tree(self): """Copy the tree to the clipboard.""" items = [] inval_index = QModelIndex() it = QTreeWidgetItemIterator(self) prev_depth = 0 while it.value(): depth = 0 item = it.value() parent = item.parent() while parent: depth += 1 parent = parent.parent() if depth < prev_depth: items.extend([" |"*depth, "\n"]) if depth: items.extend([" |"*depth, "--", item.text(0), "\n"]) else: items.extend([item.text(0), "\n"]) prev_depth = depth it += 1 QApplication.clipboard().setText("".join(items))
class App(object): def __init__(self): self.settings = SettingsManager() self.app = QApplication([]) self.gui = MainWindow(app=self) self.setup() def setup(self): self.gui.show() self.gui.resize(self.settings.get('application_width_initial'), self.settings.get('application_height_initial')) def open(self): self.app.exec_() def suspend(self): pass def close(self): self.exit() def exit(self): """ Runs cleanup and then closes the app """ self.app.exit() sys.exit()
def _copy_nodeid(self): node = self.get_current_node() if node: text = node.nodeid.to_string() else: text = "" QApplication.clipboard().setText(text)
def main(): """ Main function for the program """ parser = argparse.ArgumentParser( description="Loop a video between 2 points in time based on rules in " "a text file." ) parser.add_argument('timestamp_filename', metavar='F', nargs='?', help='the location of the timestamp file') parser.add_argument('--video_filename', metavar='V', help='the location of the video file') args = parser.parse_args() app = QApplication(sys.argv) with open("gui/application.qss", "r") as theme_file: app.setStyleSheet(theme_file.read()) main_window = MainWindow() if args.timestamp_filename: timestamp_filename = os.path.abspath(args.timestamp_filename) main_window.set_timestamp_filename(timestamp_filename) if args.video_filename: video_filename = os.path.abspath(args.video_filename) main_window.set_video_filename(video_filename) sys.exit(app.exec_())
def restartService(self, language, forceKill=False): """ Public method to restart a given lanuage. @param language to restart (str) @keyparam forceKill flag to kill a running task (bool) """ try: proc, interpreter = self.processes.pop(language) except KeyError: return # Don't kill a process if it's still working if not forceKill: while self.isWorking is not None: QApplication.processEvents() conn = self.connections.pop(language, None) if conn: conn.blockSignals(True) conn.close() if proc: proc.close() port = self.serverPort() process = self.__startExternalClient(interpreter, port) if process: self.processes[language] = process, interpreter
def _clientLoginCallback(self, realm, username, may_save): """ Protected method called by the client to get login information. @param realm name of the realm of the requested credentials (string) @param username username as supplied by subversion (string) @param may_save flag indicating, that subversion is willing to save the answers returned (boolean) @return tuple of four values (retcode, username, password, save). Retcode should be True, if username and password should be used by subversion, username and password contain the relevant data as strings and save is a flag indicating, that username and password should be saved. """ from .SvnLoginDialog import SvnLoginDialog cursor = QApplication.overrideCursor() if cursor is not None: QApplication.restoreOverrideCursor() parent = isinstance(self, QWidget) and self or None dlg = SvnLoginDialog(realm, username, may_save, parent) res = dlg.exec_() if cursor is not None: QApplication.setOverrideCursor(Qt.WaitCursor) if res == QDialog.Accepted: loginData = dlg.getData() return (True, loginData[0], loginData[1], loginData[2]) else: return (False, "", "", False)
def __compileAllInterfaces(self): """ Private method to compile all interfaces to python. """ if self.omniidl is not None: numIDLs = len(self.project.pdata["INTERFACES"]) progress = E5ProgressDialog( self.tr("Compiling interfaces..."), self.tr("Abort"), 0, numIDLs, self.tr("%v/%m Interfaces"), self) progress.setModal(True) progress.setMinimumDuration(0) progress.setWindowTitle(self.tr("Interfaces")) i = 0 for fn in self.project.pdata["INTERFACES"]: progress.setValue(i) if progress.wasCanceled(): break proc = self.__compileIDL(fn, True, progress) if proc is not None: while proc.state() == QProcess.Running: QApplication.processEvents() QThread.msleep(300) QApplication.processEvents() else: break i += 1 progress.setValue(numIDLs)
def __compileAllResources(self): """ Private method to compile all resources to source files. """ if self.hooks["compileAllResources"] is not None: self.hooks["compileAllResources"](self.project.pdata["RESOURCES"]) else: numResources = len(self.project.pdata["RESOURCES"]) progress = E5ProgressDialog( self.tr("Compiling resources..."), self.tr("Abort"), 0, numResources, self.tr("%v/%m Resources"), self) progress.setModal(True) progress.setMinimumDuration(0) progress.setWindowTitle(self.tr("Resources")) i = 0 for fn in self.project.pdata["RESOURCES"]: progress.setValue(i) if progress.wasCanceled(): break proc = self.__compileQRC(fn, True, progress) if proc is not None: while proc.state() == QProcess.Running: QApplication.processEvents() QThread.msleep(300) QApplication.processEvents() else: break i += 1 progress.setValue(numResources)
def __compileSelectedInterfaces(self): """ Private method to compile selected interfaces to python. """ if self.omniidl is not None: items = self.getSelectedItems() files = [self.project.getRelativePath(itm.fileName()) for itm in items] numIDLs = len(files) progress = E5ProgressDialog( self.tr("Compiling interfaces..."), self.tr("Abort"), 0, numIDLs, self.tr("%v/%m Interfaces"), self) progress.setModal(True) progress.setMinimumDuration(0) progress.setWindowTitle(self.tr("Interfaces")) i = 0 for fn in files: progress.setValue(i) if progress.wasCanceled(): break proc = self.__compileIDL(fn, True, progress) if proc is not None: while proc.state() == QProcess.Running: QApplication.processEvents() QThread.msleep(300) QApplication.processEvents() else: break i += 1 progress.setValue(numIDLs)
def download_catalogs(self): dialog = QDialog() dialog.setWindowTitle('Download Catalogs') dialog.setLayout(QVBoxLayout()) dialog.layout().addWidget(QLabel('Select catalogues to be downloaded')) checkboxes = dict([(c, QCheckBox(c)) for c in self.reference_catalogues.catalogues]) for name, checkbox in checkboxes.items(): checkbox.setChecked(True) dialog.layout().addWidget(checkbox) buttonbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttonbox.accepted.connect(dialog.accept) buttonbox.rejected.connect(dialog.reject) dialog.layout().addWidget(buttonbox) if dialog.exec() == QDialog.Rejected: return for cat, checkbox in checkboxes.items(): if not checkbox.isChecked(): continue spectra = self.reference_catalogues.spectra(cat) progress = QProgressDialog('Downloading spectra from catalog {}'.format(cat), 'Cancel', 0, len(spectra)) progress.setWindowTitle('Downloading catalogs') progress.setWindowModality(Qt.WindowModal) progress.show() for index, spectrum in enumerate(spectra): progress.setValue(index) if progress.wasCanceled(): return; QApplication.instance().processEvents() self.reference_catalogues.fits(spectrum)
def __generateContextDiff(self, a, b, fromfile, tofile, fromfiledate, tofiledate): """ Private slot to generate a context diff output. @param a first sequence of lines (list of strings) @param b second sequence of lines (list of strings) @param fromfile filename of the first file (string) @param tofile filename of the second file (string) @param fromfiledate modification time of the first file (string) @param tofiledate modification time of the second file (string) """ paras = 0 for line in context_diff(a, b, fromfile, tofile, fromfiledate, tofiledate): if line.startswith('+ '): format = self.cAddedFormat elif line.startswith('- '): format = self.cRemovedFormat elif line.startswith('! '): format = self.cReplacedFormat elif (line.startswith('*** ') or line.startswith('--- ')) and \ paras > 1: format = self.cLineNoFormat else: format = self.cNormalFormat self.__appendText(line, format) paras += 1 if not (paras % self.updateInterval): QApplication.processEvents() if paras == 0: self.__appendText( self.tr('There is no difference.'), self.cNormalFormat)