def run(self): self._timeout = QTimer() self._timeout.setInterval(2000) self._timeout.timeout.connect(self.__onTimeout) try: self._serial = serial.Serial(self._port, baudrate=19200, bytesize=serial.SEVENBITS, stopbits=serial.STOPBITS_ONE, parity=serial.PARITY_ODD, timeout=1) self._serial.dtr = True self._serial.rts = False while not self._cancel: if not self._timeout.isActive(): self._timeout.start() data = self._serial.readline() data = data.strip() if len(data) == 12: timestamp = time.time() result = self._parser.parse(data, timestamp) if result is not None: self._timeout.stop() self.data.emit(result) else: self.warning.emit('Invalid data received') QApplication.processEvents() self._serial.close() except serial.SerialException as e: self.error.emit(e.message)
def main(): app = QApplication([]) webview = QWebView() loop = QEventLoop() # 创建QEventLoop对象,该对象用于创建本地时间循环 webview.loadFinished.connect(loop.quit) # QWebView对象的loadFinished回调连接了QEventLoop的quit方法,从而可以在网页加载完成之后停止事件循环 webview.load(QUrl('http://example.webscraping.com/places/default/search')) loop.exec_() # QwebView的加载方法是异步的,执行过程会在网页加载时立即传入下一行, # 但我们希望等待网页加载完成,因此需要在事件循环启动时调用loop.exec_() webview.show() # 调用QWebViewGUI的show()方法来显示渲染窗口,以方便调试 frame = webview.page().mainFrame() # 创建一个指代框架的变量 # 使用CSS模式在框架中定位元素,然后设置搜索参数 frame.findFirstElement('#search_term').setAttribute('Value', '.') frame.findFirstElement('#page_size option:checked').setPlainText('1000') # 使用evaluate JavaScript()方法提交事件,模拟点击事件 frame.findFirstElement('#search').evaluateJavaScript('this.click()') app.exec_() # 进入应用的事件循环,可以对表单操作进行复查,如果没有使用该方法,脚本就会直接结束 # 等待结果,三种方法处理: # 1、等待一定时间,期望AJAX事件能够在此时刻之前完成 # 2、重写Qt的网络管理器,跟踪URL请求完成的事件 # 3、轮询网页,等待特定内容出现,下面采用第三种方法 elements = None while not elements: app.processEvents() # 用于给Qt事件循环执行任务的事件,比如响应点击事件和更新GUI elements = frame.findAllElements('#results a') countries = [e.toPlainText().strip() for e in elements] print countries
def __enter__(self): for widget in self.widgets: widget.setEnabled(False) if not self.forModalDialog: QApplication.setOverrideCursor(Qt.WaitCursor) QApplication.sendPostedEvents(None, 0) QApplication.processEvents()
def main(): app = QApplication(sys.argv) import qdarkstyle # setup stylesheet app.setStyleSheet(qdarkstyle.load_stylesheet()) pixmap = QPixmap(os.path.join(_resourcepath('images'), "splash.png")) splash = QSplashScreen(pixmap, Qt.WindowStaysOnTopHint) splash.setMask(pixmap.mask()) splash_font = splash.font() splash_font.setPixelSize(14) splash.setFont(splash_font) splash.show() splash.showMessage('Initialising...', Qt.AlignBottom | Qt.AlignLeft | Qt.AlignAbsolute, Qt.white) app.processEvents() """ for count in range(1, 6): splash.showMessage('Processing {0}...'.format(count), Qt.AlignBottom | Qt.AlignLeft, Qt.white) QApplication.processEvents() QThread.msleep(1000) """ frame = ConfiguratorWindow() frame.show_and_raise() splash.finish(frame) sys.exit(app.exec_())
def tableExtractSelectedRowData(table): """ Get the **selected** contents of a GUI table :param table: The ``QTableView`` object to gather data from :return: A list of raw row data --> List of lists """ colCount = table.model().columnCount() # Only check selected rows selectionModel = table.selectionModel() selectedRows = selectionModel.selectedRows() if len(selectedRows) == 0: QtGui.QMessageBox.critical(Globals.ui.tabWidgetMain, Strings.messageBoxErrorTitle, Strings.rowSelectionHint, QtGui.QMessageBox.Ok) return rawData = [] for row in selectedRows: # Don't let the GUI freeze QApplication.processEvents() rowData = [] for colIdx in range(colCount): curItemValue = table.model().getValue(row.row(), colIdx) rowData.append( curItemValue if curItemValue is not None else "") rawData.append(rowData) return rawData
def __LaunchProcess(self, arg_parse_result): ''' after the arguments have been parsed, launch the UI in a forked process ''' # Initialize concurrency limit as early as possible so that it is # respected by subsequent imports. from pxr import Work Work.SetConcurrencyLimitArgument(arg_parse_result.numThreads) from mainWindow import MainWindow if arg_parse_result.clearSettings: MainWindow.clearSettings() # find the resource directory resourceDir = os.path.dirname(os.path.realpath(__file__)) + "/" # Create the Qt application app = QApplication(sys.argv) # apply the style sheet to it sheet = open(os.path.join(resourceDir, 'usdviewstyle.qss'), 'r') sheetString = sheet.read().replace('RESOURCE_DIR', resourceDir) app.setStyleSheet(sheetString) mainWindow = MainWindow(None, arg_parse_result) if arg_parse_result.quitAfterStartup: # Before we quit, process events one more time to make sure the # UI is fully populated (and to capture all the timing information # we'd want). app.processEvents() sys.exit(0) app.exec_()
def analyse(self, query): try: start_time = time() sentence = self.form.components['labels_panel'].labels['sentence'] language = self.form.components['labels_panel'].labels['language'] result = self.form.components['labels_panel'].labels['result'] elapsed_time = self.form.components['labels_panel'].labels['time'] sentence.setText('Sentence in english: Loading ...') language.setText('Original language: Loading ...') result.setText('Prediction: Loading ...') elapsed_time.setText('Elapsed Time: Loading ...') for lang in language_codes: if lang['alpha2'] == detect(query): language.setText('Original language: ' + lang['English'] + '\n') translated_query = translator.translate(query, 'en', detect(query)) chunked_text = '' for chunk in chunkstring( 'Sentence in english: ' + translated_query, 90): chunked_text += (chunk + '\n') sentence.setText(chunked_text + '\n') sentence.repaint() result.repaint() result.setText('Prediction: ' + self.core.predict(translated_query)) elapsed_time.setText('Elapsed Time: ' + str(round((time() - start_time) * 1000)) + ' ms') result.repaint() QApplication.processEvents() except Exception as e: print e self.stop()
def openXix(self, filename=None): if self.isReadOnly( filename if filename is not None else self.filename): return self.closeXix() if filename is not None: self.filename = filename try: self.recent_files.remove(self.filename) self.updateRecentFilesMenu() except ValueError: pass # No problem if it isn't there to be removed self.state.indexPath = os.path.dirname(self.filename) QApplication.setOverrideCursor(Qt.WaitCursor) try: say("Opening {}…".format(os.path.normpath(self.filename))) QApplication.processEvents() self.state.entryPanel.clearForm() self._openModel("Opened") self.state.entryPanel.termEdit.setFocus() self.state.updateUi() self.updateWorkTime() self.updateLanguageIndicator() self.state.setMode(ModeKind.VIEW) self.refreshBookmarks() finally: QApplication.restoreOverrideCursor()
def read_response(self, until="ok", ignoreInitialize = False): """ read lines from the grbl until the expected matching line appears (usually "ok"), or just the first line if until is None. """ result = [] while True: while not self.serial.inWaiting > 0: QApplication.processEvents() line = self.serial.readline().strip() #print "Received line:", line if pycnc_config.SERIAL_DEBUG: if line == "": self.serial.write("\n") if line.startswith("error:") or line.startswith("ALARM:"): self.analyzer.undo() self.grbl_error.emit(line) break if not ignoreInitialize and line.startswith("Grbl"): # a spontaneous reset is detected? # restore work coordinates self.do_command("G10 P0 L20 X%.4f Y%.4f Z%.4f" % (self.analyzer.x, self.analyzer.y, self.analyzer.z)) break result.append(line) if line == until or until == None: break time.sleep(0.1) return '\n'.join(result)
def _increaseProgressCounter(self, d): """Increaes the current value of the progress dialog.""" if d.wasCanceled(): return True QApplication.processEvents() d.setValue(d.value() + 1) return False
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.current_profileid = "" self.setupUi(self) self.logger = get_logger('desuratools', 'desuratools.log') self.logger.info('Logger Created') boldfont = QApplication.font() boldfont.setBold(True) self.addToSteam_action = self.action_factory("Add to Steam", self.add_to_steam) self.addToSteam_action.setFont(boldfont) self.installGame_action = self.action_factory("Install", self.install_game) self.installGame_action.setFont(boldfont) self.desuraPage_action = self.action_factory("View Profile", self.open_desura_page) self.uninstallGame_action = self.action_factory("Uninstall", self.uninstall_game) self.verifyGame_action = self.action_factory("Verify", self.verify_game) self.ownedGames_menu = QMenu(self) self.ownedGames_menu.addActions([ self.installGame_action, self.desuraPage_action ]) self.installedGames_menu = QMenu(self) self.installedGames_menu.addActions([ self.addToSteam_action, self.desuraPage_action, self.uninstallGame_action, self.verifyGame_action ]) self.selectAllButton.clicked.connect(self.select_all_games) self.desuraAccountName_verify.clicked.connect(self.populate_owned_games) self.installButton.clicked.connect(self.process_install_button) self.generateDesuraReport_action.activated.connect(self.generate_report) self.tabWidget.currentChanged.connect(self.swap_tabs) self.ownedGames_list.itemSelectionChanged.connect(self.update_gameinfo) self.installedGames_list.itemSelectionChanged.connect(self.update_gameinfo) self.refreshButton.clicked.connect(self.refresh_list) self.refreshLists_action.activated.connect(self.refresh_all) self.installedGames_list.customContextMenuRequested.connect(self.show_game_context) self.installedGames_list.doubleClicked.connect(self.add_to_steam) self.installedGames_list.setSelectionMode(QAbstractItemView.ExtendedSelection) self.ownedGames_list.setSelectionMode(QAbstractItemView.ExtendedSelection) self.steamID_input.addItems(steamutils.get_customurls_on_machine()) self.ownedGames_list.addItem("Verify your Desura username to see your owned games") QApplication.processEvents() self.loading_dialog = ProgressBarDialog() self.loading_dialog.show() QApplication.processEvents() self.populate_installed_games() self.load_data() self.loading_dialog.close() self.raise_()
def animate(self, shapes): self.start_signal.emit() time.sleep(self.start_delay) self.running = True self.ended = False max_radius = [] original_clips = [] centers = [] animating_radius = [] inc_rate = [] for s in shapes: # Setting max of width or height as radius, ergo "circular" reveal, # not "oval" reveal target = max(s.width, s.height) max_radius.append(target) # Starting from the zero reaching the max animating_radius.append(0) # Getting the original masks; Used in case of cancelation original_clips.append(s.clip) # Center of the shape, considering margin centers.append(QPoint((s.width / 2) + s.margin_start, (s.height / 2) + s.margin_top)) # Calculating the increase rate using the good ol' formula inc_rate.append((target / self.fps) * (1000 / self.duration)) while self.running or self.paused: if self.canceled: for i, s in enumerate(shapes): s.clip = original_clips[i] self.cancel_signal.emit() return elif self.ended: self.end_signal.emit() return elif self.paused: # Handling the pause self.pause_signal.emit() while not self.paused: pass self.resume_signal.emit() else: # Setting FPS from the animator time.sleep(1 / self.fps) completed = False for i, s in enumerate(shapes): if animating_radius[i] < max_radius[i]: path = QPainterPath() path.addEllipse(centers[i], animating_radius[i], animating_radius[i]) s.clip = path s.update() QApplication.processEvents() animating_radius[i] += inc_rate[i] else: completed = True # No need to check on every iteration, duration is same so # all objects are gonna end at the same time if completed: self.end_signal.emit() self.started = False self.ended = True return
class BrowserRender(QWebView): def __init__(self,show=True): self.app = QApplication(sys.argv) QWebView.__init__(self) if show: self.show()#显示浏览器 def download(self,url,timeout=60): loop = QEventLoop() timer = QTimer() timer.setSingleShot(True)#让定时器只执行一次 timer.timeout.connect(loop.quit) self.loadFinished.connect(loop.quit) self.load(QUrl(url)) timer.start(timeout*1000) loop.exec_() if timer.isActive(): timer.stop() return self.html() else: print('请求超时:'+url) def html(self): return self.page().mainFrame().toHtml() def find(self, pattern): return self.page().mainFrame().findAllElements(pattern) def attr(self,pattern,name,value): ''' 设置value属性值 :param pattern: :param name: :param value: :return: ''' for e in self.find(pattern): e.setAttribute(name,value) def text(self,pattern,value): for e in self.find(pattern): e.setPlainText(value) def click(self,pattern): for e in self.find(pattern): e.evaluateJavaScript('this.click()') def wait_load(self,pattern,timeout=60): deadline = time.time() + timeout while time.time()<deadline: self.app.processEvents() matches = self.find(pattern) if matches: return matches print('等待超时')
def join(self, delay=0.1): """ Calls `QApplication.processEvents()` every `delay` until the task has finished. """ QApplication.processEvents() while not self.hasFinished: sleep(delay) QApplication.processEvents()
class BrowserRender(QWebView): def __init__(self, display=True): self.app = QApplication([]) QWebView.__init__(self) if display: self.show() # show the browser def open(self, url, timeout=60): """Wait for download to complete and return result""" loop = QEventLoop() timer = QTimer() timer.setSingleShot(True) timer.timeout.connect(loop.quit) self.loadFinished.connect(loop.quit) self.load(QUrl(url)) timer.start(timeout * 1000) loop.exec_() # delay here until download finished if timer.isActive(): # downloaded successfully timer.stop() return self.html() else: # timed out print 'Request timed out:', url def html(self): """Shortcut to return the current HTML""" return self.page().mainFrame().toHtml() def find(self, pattern): """Find all elements that match the pattern""" return self.page().mainFrame().findAllElements(pattern) def attr(self, pattern, name, value): """Set attribute for matching elements""" for e in self.find(pattern): e.setAttribute(name, value) def text(self, pattern, value): """Set attribute for matching elements""" for e in self.find(pattern): e.setPlainText(value) def click(self, pattern): """Click matching elements""" for e in self.find(pattern): e.evaluateJavaScript("this.click()") def wait_load(self, pattern, timeout=60): """Wait for this pattern to be found in webpage and return matches""" deadline = time.time() + timeout while time.time() < deadline: self.app.processEvents() matches = self.find(pattern) if matches: return matches print 'Wait load timed out'
def run(self): # Action taken by thread upon start print("*Running %s" % self.name) initializeLog() print("*File initialized, Headers created, Logging Started") self.parent.Log_Status.setText("Log Running") printLog(self.parent, self.name, 1) # 'Endless' Loop - exits via flag print("*Stopping " + self.name) self.parent.Log_Status.setText("Log Standby") QApplication.processEvents() # forces update of GUI
def populate_qlistwidget(self, game, qlistwidget, iconurls=False): if iconurls: itemicon = self.qpixmap_from_url(game.icon) QApplication.processEvents() else: itemicon = QPixmap(game.icon) QApplication.processEvents() item = QListWidgetItem(itemicon, game.name, qlistwidget) item.setData(Qt.UserRole, game) qlistwidget.addItem(item)
def animate(self, steps=None): """ This function animates the initial animation of ripple :return: None """ s = 0 while self.__r < self.__maxRadius: if steps is not None and s == steps: return if self.__flag == 1: self.destroy() self.update() self.__finished = True break # checking of origin and target case are the same points if self.__origin != self.__target_center: # moving x coord of origin towards x of target_center if self.__origin.x() > self.__target_center.x(): self.__origin.setX(self.__origin.x() - 1) elif self.__origin.x() < self.__target_center.x(): self.__origin.setX(self.__origin.x() + 1) else: pass # moving y coord of origin towards y of target_center if self.__origin.y() > self.__target_center.y(): self.__origin.setY(self.__origin.y() - 1) elif self.__origin.y() < self.__target_center.y(): self.__origin.setY(self.__origin.y() + 1) else: pass self.__r += 1 self.__maxOpacity = 255 - (255 * self.__r) / self.__maxRadius if self.__maxOpacity <= self.__minOpacity: self.__maxOpacity = self.__minOpacity # repainting the canvas self.update() QApplication.processEvents() # animation speed time.sleep(self.__speed) # increasing step count try: if self.__origin == self.__target_center and self.__r == self.__maxRadius and self.__maxOpacity == self.__maxOpacity: self.__finished = True except AttributeError: pass s += 1 # setting the flag finished True, once the animation is performed to its full # checking if the mouse button is released yet or not if self.__release: # performing mouse release animation if steps is None: self.releaseAnimate(None) else: self.releaseStepAnimate() return
class BrowserRender(QWebView): def __init__(self, display=True): self.app = QApplication([]) QWebView.__init__(self) if display: self.show() # show the browser def open(self, url, timeout=60): """wait for download to complete and return result""" loop = QEventLoop() timer = QTimer() timer.setSingleShot(True) # True表示触发定时器后,仅执行事件一次 timer.timeout.connect(loop.quit) # 若超时,则连接loop.quit,退出事件循环 self.loadFinished.connect(loop.quit) self.load(url) timer.start(timeout * 1000) # 定时器以ms为单位,设置超时时间为60s loop.exec_() # 等待网页加载完成后,在执行后面的代码 if timer.isActive(): # downloaded successfully timer.stop() return self.html() else: # timed out print 'Request timed out:', url def html(self): """shortcut to return the current HTML""" return self.page().mainFrame().toHtml() def find(self, pattern): return self.page().mainFrame().findAllElements(pattern) def attr(self, pattern, name, value): for e in self.find(pattern): e.setAttribute(name, value) def text(self, pattern, value): for e in self.find(pattern): e.setPalintext(value) def click(self, pattern): for e in self.find(pattern): e.evaluateJavaScript("this.click()") def wait_load(self, pattern, timeout=60): """wait for this pattern to be found in webpage and return matches""" deadline = time.time() + timeout while time.time() < deadline: self.app.processEvents() matches = self.find(pattern) if matches: return matches print 'wait load timed out'
def _prepare_window(self, ld): """ Prepares the dialog so the events get processed and focus is attributed to the right widget. """ from PySide.QtGui import QApplication ld.show() ld.raise_() QApplication.processEvents()
def run(url, filename, image_crop, translate_page): app=QApplication.instance() if not app: app = QApplication(sys.argv) app.setApplicationName('myWindow') r = Render(url, filename, image_crop, translate_page) r.show() while not r.finished: app.processEvents() time.sleep(0.01) return r.filepath
def run(url, filename, image_crop, translate_page): app = QApplication.instance() if not app: app = QApplication(sys.argv) app.setApplicationName('myWindow') r = Render(url, filename, image_crop, translate_page) r.show() while not r.finished: app.processEvents() time.sleep(0.01) return r.filepath
def main(): app = QApplication(sys.argv) view = QWebView() frame = view.page().mainFrame() printer = ConsolePrinter() view.setHtml(html) frame.addToJavaScriptWindowObject('printer', printer) frame = frame #frame.evaluateJavaScript("alert('Hello');") #frame.evaluateJavaScript("printer.text('Goooooooooo!');") view.show() app.processEvents() app.exec_()
def add_to_steam(self): if not self.check_if_steam_running(): return gamelist = self.get_current_list() if gamelist[1] == 0: for item in gamelist[0].selectedItems(): game = item.data(Qt.UserRole) if 'ID64:' in self.steamID_input.currentText(): steamid = long(self.steamID_input.currentText().replace('ID64:', '')) else: steamid = steam_user_manager.communityid64_from_name(self.steamID_input.currentText()) QApplication.processEvents() if not steamutils.check_steam_version(steamid, game.name): if not steamutils.shortcut_exists(self.get_steam_manager(), game.name): steamutils.insert_shortcut(self.get_steam_manager(), game.name, game.exe, icons.choose_icon(game)) self.statusBar.showMessage("Added {0} to the Steam library".format(game.name)) QApplication.processEvents() else: self.statusBar.showMessage("{0} already exists in the Steam library".format(game.name)) QApplication.processEvents() else: self.statusBar.showMessage("Steam account {0} already owns the Steam version of {1}".format( self.steamID_input.currentText(), game.name) ) QApplication.processEvents()
def add_to_steam(self): if not self.check_if_steam_running(): return gamelist = self.get_current_list() if gamelist[1] == 0: for item in gamelist[0].selectedItems(): game = item.data(Qt.UserRole) if 'ID64:' in self.steamID_input.currentText(): steamid = long(self.steamID_input.currentText().replace( 'ID64:', '')) else: steamid = steam_user_manager.communityid64_from_name( self.steamID_input.currentText()) QApplication.processEvents() if not steamutils.check_steam_version(steamid, game.name): if not steamutils.shortcut_exists(self.get_steam_manager(), game.name): steamutils.insert_shortcut(self.get_steam_manager(), game.name, game.exe, icons.choose_icon(game)) self.statusBar.showMessage( "Added {0} to the Steam library".format(game.name)) QApplication.processEvents() else: self.statusBar.showMessage( "{0} already exists in the Steam library".format( game.name)) QApplication.processEvents() else: self.statusBar.showMessage( "Steam account {0} already owns the Steam version of {1}" .format(self.steamID_input.currentText(), game.name)) QApplication.processEvents()
def doubleEncryptPrivKeys(self, secondPass): if any([addr.doubleEncrypted is True for addr in self.addresses]): raise DataError('Some keys are already double encrypted') for addr in self.addresses: oldpk = addr.priv if addr.sharedKey is None: addr.sharedKey = 'BitPurse' addr.priv = self.encryptPK(addr.priv, secondPass, addr.sharedKey) addr.doubleEncrypted = True assert oldpk == self.decryptPK(addr.priv, secondPass, addr.sharedKey) QApplication.processEvents() self.settings.useDoubleEncryption = False
def runOnGlobalInstance(self, wait=False): """ Run this ProgressRunnable on the global QThreadPool instance. If `wait` is True, process the UI events while waiting for the ProgressRunnable to finish. """ QThreadPool.globalInstance().start(self) if wait: # self.__finishedCalled is made True by the setHasFinished() # method, which is called from try/finally blocks so guaranteed # to be called even if there are exceptions. while not self.__finishedCalled: sleep(0.01) QApplication.processEvents()
def doubleDecryptPrivKeys(self, secondPass): if any([addr.doubleEncrypted is False for addr in self.addresses]): raise DataError('Some keys are not double encrypted') self.testDoublePK(secondPass) for addr in self.addresses: if addr.sharedKey is None: addr.sharedKey = 'BitPurse' addr.priv = self.decryptPK(addr.priv, secondPass, addr.sharedKey) addr.doubleEncrypted = False assert addr.addr == getAddrFromPrivateKey(addr.priv) QApplication.processEvents() self.settings.useDoubleEncryption = True
class QtTest(unittest.TestCase): def setUp(self): """ Initialize our QApplication :return: None """ # We need to be able to test our code without a real device. So we setup # our Mock server here. Then we connect our client to that mock server. self.server = MockServer(('localhost', 0), MockHandler) self.listen_ip, self.listen_port = self.server.server_address self.server_thread = threading.Thread(target=self.server.serve_forever) self.server_thread.daemon = False self.server_thread.start() self.app = QApplication.instance() if self.app is None: self.app = QApplication([]) self.main_window = MainWindow(None) def tearDown(self): self.server.shutdown() self.main_window.clean_up() def testNames(self): self.cnt = 0 def _watch(msg): self.cnt += 1 # We know our mock server should emit 3 messages to the message_signal. So # we can use this as a way to count that all 3 have been sent before trying # to verify that our names list was updated correctly. self.main_window.network_manager.message_signal.connect(_watch) # This is how we normally would start the connection. Just now we are pointing # to our mock server. self.main_window.start_api(self.listen_ip, self.listen_port) # We know our mock server is going to send 3 names. So keep processing # until all 3 have been sent. while self.cnt < 3: if self.app.hasPendingEvents(): self.app.processEvents() # Finally, assert that our end goal has been met. assert self.main_window.names_list.count() == 3
class BrowserRender(QWebView): def __init__(self, display=True): self.app = QApplication([]) QWebView.__init__(self) if display: self.show() # show the browser def downlaod(self, url, timeout=60): loop = QEventLoop() timer = QTimer() timer.setSingleShot(True) timer.timeout.connect(loop.quit) self.loadFinished.connect(loop.quit) self.load(QUrl(url)) timer.start(timeout * 1000) loop.exec_() if timer.isActive(): timer.stop() return self.html() else: print 'Request timed out: ' + url def html(self): return self.page().mainFrame().toHtml() def find(self, pattern): return self.page().mainFrame().findAllElements(pattern) def attr(self, pattern, name, value): for e in self.find(pattern): e.setAttribute(name, value) def text(self, pattern, value): for e in self.find(pattern): e.setPlainText(value) def click(self, pattern): for e in self.find(pattern): e.evaluateJavaScript("this.click()") def wait_load(self, pattern, timeout=60): deadline = time.time() + timeout while time.time() < deadline: self.app.processEvents() matches = self.find(pattern) if matches: return matches print 'Wait load timed out'
def test_submit_failing_callback(): 'Test delayed execution of successful call-backs' application = Application(['a', 'b']) def add(a, b): 'Dummy function that add two elements.' return a + b future = application.submit(add, 3, 'CINQUE') assert isinstance(future, FutureCall) assert not future.done QApplication.processEvents(maxtime=5000) assert future.done assert isinstance(future.exception, TypeError)
def doubleEncryptPrivKeys(self, secondPass): if any([addr.doubleEncrypted is True for addr in self.addresses if not addr.watchOnly]): raise DataError('Some keys are already double encrypted') for addr in [address for address in self.addresses if not address.watchOnly]: oldpk = addr.priv if addr.sharedKey is None: addr.sharedKey = 'BitPurse' addr.priv = self.encryptPK(addr.priv, secondPass, addr.sharedKey) addr.doubleEncrypted = True assert oldpk == self.decryptPK(addr.priv, secondPass, addr.sharedKey) QApplication.processEvents() self.settings.useDoubleEncryption = False
def iterateCommand (self, state, address, length, func, buffer_size): loops = length / buffer_size tail = length % buffer_size if tail: loops += 1 result = bytearray () self.changed.emit (_(state)) self.progressUpdated.emit (0) for i in xrange (loops): offset = i * buffer_size self.setAddress (address + offset) result += func (offset, tail if tail and i == loops - 1 else buffer_size) self.progressUpdated.emit (100.0 / loops * (i + 1)) QApplication.processEvents () self.changed.emit (_('Done')) self.progressUpdated.emit (100) return bytes (result)
def doubleDecryptPrivKeys(self, secondPass): if any([addr.doubleEncrypted is False for addr in self.addresses if not addr.watchOnly]): raise DataError('Some keys are not double encrypted') self.testDoublePK(secondPass) for addr in [address for address in self.addresses if not address.watchOnly]: if addr.sharedKey is None: addr.sharedKey = 'BitPurse' addr.priv = self.decryptPK(addr.priv, secondPass, addr.sharedKey) addr.doubleEncrypted = False assert addr.addr == getAddrFromPrivateKey(addr.priv) QApplication.processEvents() self.settings.useDoubleEncryption = True
def main(): app = QApplication([]) webview = QWebView() loop = QEventLoop() webview.loadFinished.connect(loop.quit) webview.load(QUrl('http://example.webscraping.com/search')) loop.exec_() webview.show() frame = webview.page().mainFrame() frame.findFirstElement('#search_term').setAttribute('value', '.') frame.findFirstElement('#page_size option:checked').setPlainText('1000') frame.findFirstElement('#search').evaluateJavaScript('this.click()') elements = None while not elements: app.processEvents()
def action(shape, speed=0.016667): t = False if shape.isScaleAnimationRunning(): shape.setScaleAnimationRunning(False) time.sleep(speed + 0.001) if not shape.isScaleAnimationRunning(): shape.setScaleAnimationRunning(True) while not t: if not shape.isScaleAnimationRunning(): return False t = MScaleIn.stepForward(shape) shape.update() QApplication.processEvents() time.sleep(speed) shape.setScaleAnimationRunning(False) return True else: return False
def closeEvent(self, event): # Updated 12/28/16 ''' Tasks to carry out if 'X' clicked ''' systemOff() # puts system into standby mode if not run_q.empty(): run_q.get() # remove item from run_q if log_q.empty(): log_q.put(1) # putting something in log_q stops loggings time_now = 0; time_start = time.time(); while time_now < log_interval*2: self.System_Mode.setText("Shutting Down...") time_now = time.time()-time_start QApplication.processEvents() # forces update of GUI? event.accept()
def newXix(self, filename): if self.isReadOnly(filename): return self.closeXix() self.filename = filename QApplication.setOverrideCursor(Qt.WaitCursor) try: say("Creating {}…".format(os.path.normpath(self.filename)), SAY_TIMEOUT) QApplication.processEvents() self._openModel("Created") self.state.updateUi() self.updateWorkTime() self.state.entryPanel.clearForm() self.updateLanguageIndicator() self.state.setMode(ModeKind.VIEW) finally: QApplication.restoreOverrideCursor()
def main(): app = QApplication([]) webview = QWebView() loop = QEventLoop() webview.loadFinished.connect(loop.quit) webview.load(QUrl('http://example.webscraping.com/places/default/search')) loop.exec_() webview.show() frame = webview.page().mainFrame() frame.findFirstElement('#search_term').setAttribute('value', '.') frame.findFirstElement('#page_size option').setPlainText('1000') #设置纯文本 frame.findFirstElement('#search').evaluateJavaScript('this.click()') app.exec_() elements = None while not elements: app.processEvents() elements = frame.findAllElements('#results a') countries = [e.toPlainText().strip() for e in elements] print countries
def set_btn_size(self, size): """ Changes the Toolbar's icons size :type size: int :param size: The Icons' size preset """ self.base.toolbar_size = size button_size = QSize(size, size) half_size = QSize(size * .5, size * .5) for btn in self.buttons: btn.setMinimumWidth(size + 10) btn.setIconSize(button_size) for btn in [self.loaded_btn, self.db_btn]: # btn.setMinimumWidth(size + 10) btn.setIconSize(half_size) # noinspection PyArgumentList QApplication.processEvents()
def populate_owned_games(self): self.statusBar.showMessage("Waiting for Desura... Please Wait") try: if not self.set_current_account(): if len(self.desuraAccountName_input.text()) > 0: self.statusBar.showMessage("Invalid Desura Account") else: self.statusBar.showMessage("") return self.ownedGames_list.clear() self.loading_dialog.setAccount( gameslist.username_from_profile_id(self.current_profileid)) QApplication.processEvents() self.loading_dialog.setMaximum( len(gameslist.GamesList(self.current_profileid).get_games())) QApplication.processEvents() for game in gameslist.GamesList( self.current_profileid).get_games(): self.populate_qlistwidget(game, self.ownedGames_list, True) QApplication.processEvents() self.loading_dialog.increment(1, game.name) QApplication.processEvents() self.logger.info("Added Game {0}".format(game.name)) self.statusBar.showMessage("Added Game {0}".format(game.name)) except gameslist.PrivateProfileError: self.logger.error("Failed to load games - Private Desura Profile") self.statusBar.showMessage( "Failed to load games - Private Desura Profiles not supported") error_message( "The Desura Profile {0} is set to Private. <br/>DesuraTools works only with public Desura Profiles." .format(self.current_profileid)).exec_() return except gameslist.NoSuchProfileError: self.logger.error( "Failed to load games - Desura account not found") self.statusBar.showMessage( "Failed to load games - Desura account not found") return except gameslist.InvalidDesuraProfileError: self.logger.error( "Failed to load games - Desura Profile ID invalid") self.ownedGames_list.customContextMenuRequested.connect( self.show_game_context) self.ownedGames_list.doubleClicked.connect(self.install_game) self.statusBar.showMessage( "All owned Desura games loaded for account {0}".format( gameslist.username_from_profile_id(self.current_profileid))) self.logger.info( "All owned Desura games loaded for Desura profile id {0}".format( self.current_profileid))
def setSortAsRules(self, name, prefix=None, reportProgress=None): rules = SortAs.RulesForName[name] say("Updating Sort As texts for “{}” rules…".format(rules.name)) self.setMode(ModeKind.CHANGE) QApplication.sendPostedEvents(None, 0) QApplication.processEvents() try: eid = self.viewAllPanel.view.selectedEid self.model.setSortAsRules(name, prefix, reportProgress) self.window.sortAsRuleLabel.setText( LABEL_TEMPLATE.format(rules.abbrev)) self.window.sortAsRuleLabel.setToolTip(Lib.rulesTip(rules.tip)) self.viewAllPanel.view.gotoEid(eid) finally: say("Updated Sort As texts for “{}” rules".format(rules.name), SAY_TIMEOUT) self.setMode(ModeKind.VIEW) QApplication.sendPostedEvents(None, 0) QApplication.processEvents()
def onUpdateFinish(self, exitCode): print("EXIT CODE IS: " + str(exitCode)) if exitCode == 1: # process did not start QMessageBox.critical(None, langmodule.attention, langmodule.restartUpdate, QMessageBox.Ok | QMessageBox.Default, QMessageBox.NoButton) if hasattr(self, 'theUpdateChecker'): self.theUpdateChecker.exit() if hasattr(self, 'theUpdater'): self.theUpdater.exit() elif exitCode == 0 | exitCode == 255: # nornal process termination # print(str(self.theUpdater.isRunning())) # signals need to be disconnected in both cases self.theUpdater.started.disconnect() self.theUpdater.sigUpdateTerminated.disconnect() self.theUpdater.sigWriteUpdate.disconnect() self.theUpdateChecker.sigDstarted.disconnect() if exitCode == 0: self._theMainWindow.theUpdate.theUpdateProgress.btnExit.setEnabled(True) if exitCode == 299: # abnormalTermination if self._theMainWindow.theUpdate.theUpdateProgress.isVisible(): self._theMainWindow.theUpdate.theUpdateProgress.hide ### cleanup code, always runs ### if hasattr(self, 'theUpdateChecker'): print("here 1") self.theUpdateChecker.exit() while self.theUpdateChecker.isRunning(): print("here 2") self.theUpdateChecker.exit() QApplication.processEvents() if hasattr(self, 'theUpdateChecker'): del self.theUpdateChecker if hasattr(self, 'theUpdater'): while self.theUpdater.isRunning(): print("now waiting updater...") self.theUpdater.exit() QApplication.processEvents() if hasattr(self, 'theUpdater'): print("trying to delete the updater") del self.theUpdater #if self._theMainWindow.theUpdate.theUpdateProgress.isVisible(): #print("set it") gc.collect()
def importIndex(self, filename, inFilename): if self.isReadOnly(filename): return self.closeXix() Lib.remove_file(filename) # Don't want to merge! self.filename = filename QApplication.setOverrideCursor(Qt.WaitCursor) try: say("Importing {}…".format(os.path.normpath(self.filename)), SAY_TIMEOUT) QApplication.processEvents() self._importIndex(filename, inFilename) self.state.entryPanel.termEdit.setFocus() self.state.updateUi() self.updateWorkTime() self.updateLanguageIndicator() self.state.setMode(ModeKind.VIEW) finally: QApplication.restoreOverrideCursor()
def main(): app = QApplication([]) webview = QWebView() loop = QEventLoop() webview.loadFinished.connect(loop.quit) webview.load(QUrl('http://example.webscraping.com/search')) loop.exec_() webview.show() frame = webview.page().mainFrame() frame.findFirstElement('#search_term').setAttribute('value', '.') frame.findFirstElement('#page_size option:checked').setPlainText('1000') frame.findFirstElement('#search').evaluateJavaScript('this.click()') elements = None while not elements: app.processEvents() elements = frame.findAllElements('#results a') countries = [e.toPlainText().strip() for e in elements] print countries
def readBytes (self, length): stop = time.time () + self.timeout if length is None: res = bytearray () while True: if time.time () > stop: raise IOError (_('Sync timeout')) if self.serial.inWaiting () > 0: b = self.serial.read () res.append (b) if b == const.RESP_STK_OK: return bytes (res) QApplication.processEvents () while self.serial.inWaiting () < length: if time.time () > stop: raise IOError (_('Sync timeout')) QApplication.processEvents () return self.serial.read (length)
def releaseAnimate(self, steps=None): """ This function creates the animation to be performed when mouse is released :return: None """ s = 0 while self.__i < self.__releaseSpeed: if steps is not None and steps == s: return if self.__flag == 1: self.destroy() self.update() break # reducing alpha to zero, in 23 steps self.__maxOpacity = self.__minOpacity - (self.__minOpacity * self.__i) / self.__releaseSpeed self.__i += 1 # repainting the canvas self.update() QApplication.processEvents() # animation speed time.sleep(self.__speed) s += 1
def open (self, port, baudrate = 115200): try: self.serial.port = port self.serial.baudrate = baudrate self.serial.parity = serial.PARITY_NONE self.serial.stopbits = serial.STOPBITS_ONE self.serial.datasize = serial.EIGHTBITS self.serial.timeout = self.timeout self.serial.open () self.reset () for _i in xrange (10): self.serial.write (const.CMD_STK_GET_SYNC + const.SYNC_CRC_EOP) self.serial.flushInput () QThread.msleep (10) self.waiting = True while self.waiting: self.serial.flushInput () self.serial.write (const.CMD_STK_GET_SYNC + const.SYNC_CRC_EOP) QThread.msleep (random.randrange (500, 1000)) QApplication.processEvents () if self.serial.inWaiting () < 2: continue if self.readBytes (2) == const.RESP_STK_INSYNC + const.RESP_STK_OK: break self.changed.emit (_('Connected')) self.progressUpdated.emit (0) return True except Exception as e: traceback.print_exc () try: self.serial.close () except: pass self.setError (e) return False
def __LaunchProcess(self, arg_parse_result): ''' after the arguments have been parsed, launch the UI in a forked process ''' # Initialize concurrency limit as early as possible so that it is # respected by subsequent imports. from pxr import Work Work.SetConcurrencyLimitArgument(arg_parse_result.numThreads) from mainWindow import MainWindow if arg_parse_result.clearSettings: MainWindow.clearSettings() # Find the resource directory resourceDir = os.path.dirname(os.path.realpath(__file__)) + "/" # Create the Qt application app = QApplication(sys.argv) # Apply the style sheet to it sheet = open(os.path.join(resourceDir, 'usdviewstyle.qss'), 'r') # Qt style sheet accepts only forward slashes as path separators sheetString = sheet.read().replace('RESOURCE_DIR', resourceDir.replace("\\", "/")) app.setStyleSheet(sheetString) mainWindow = MainWindow(None, arg_parse_result) if arg_parse_result.quitAfterStartup: # Before we quit, process events one more time to make sure the # UI is fully populated (and to capture all the timing information # we'd want). app.processEvents() sys.exit(0) app.exec_()
def populate_owned_games(self): self.statusBar.showMessage("Waiting for Desura... Please Wait") try: if not self.set_current_account(): if len(self.desuraAccountName_input.text()) > 0: self.statusBar.showMessage("Invalid Desura Account") else: self.statusBar.showMessage("") return self.ownedGames_list.clear() self.loading_dialog.setAccount(gameslist.username_from_profile_id(self.current_profileid)) QApplication.processEvents() self.loading_dialog.setMaximum(len(gameslist.GamesList(self.current_profileid).get_games())) QApplication.processEvents() for game in gameslist.GamesList(self.current_profileid).get_games(): self.populate_qlistwidget(game, self.ownedGames_list, True) QApplication.processEvents() self.loading_dialog.increment(1, game.name) QApplication.processEvents() self.logger.info("Added Game {0}".format(game.name)) self.statusBar.showMessage("Added Game {0}".format(game.name)) except gameslist.PrivateProfileError: self.logger.error("Failed to load games - Private Desura Profile") self.statusBar.showMessage("Failed to load games - Private Desura Profiles not supported") error_message( "The Desura Profile {0} is set to Private. <br/>DesuraTools works only with public Desura Profiles." .format(self.current_profileid) ).exec_() return except gameslist.NoSuchProfileError: self.logger.error("Failed to load games - Desura account not found") self.statusBar.showMessage("Failed to load games - Desura account not found") return except gameslist.InvalidDesuraProfileError: self.logger.error("Failed to load games - Desura Profile ID invalid") self.ownedGames_list.customContextMenuRequested.connect(self.show_game_context) self.ownedGames_list.doubleClicked.connect(self.install_game) self.statusBar.showMessage("All owned Desura games loaded for account {0}".format( gameslist.username_from_profile_id(self.current_profileid)) ) self.logger.info("All owned Desura games loaded for Desura profile id {0}".format(self.current_profileid))
def animate(self, shapes): self.start_signal.emit() # Sleeping to account the start_delay print(self.target) time.sleep(self.start_delay) self.running = True self.ended = False # Used to store the original opacities of the shapes original_opacity = [] # Used to store opacity to be reduced bu each frame rate_of_change = [] # Getting the original opacities of shapes in case the animation is # canceled in between for s in shapes: original_opacity.append(s.opacity) # Uses formula (((start - target) / fps) * (1000 / duration)) rate_of_change.append( ((self.target - s.opacity) / self.fps) * (1000 / self.duration) ) # Main thread loop while self.running or self.paused: if self.canceled: # Restoring the opacity to the original in case the animation # was canceled for i, s in enumerate(shapes): s.opacity = original_opacity[i] # Emitting cancel signal self.cancel_signal.emit() return elif self.ended: # Setting the opacity to the final value, i.e. target # in case if the animation was ended for s in shapes: s.opacity = self.target # Emitting end signal self.end_signal.emit() return elif self.paused: # Emitting pause signal self.pause_signal.emit() # Loop which will hold the thread until the animation is # paused while not self.paused: # If you want the current state, pause the # animation and then cancel it if self.canceled: self.ended = True self.started = False self.cancel_signal.emit() return # Emitting resume signal self.resume_signal.emit() else: # Sleeping for 1/60 seconds, for 60fps time.sleep(1 / self.fps) # Flag to find out even if one shape is left to complete the # whole fade out animation completed = False for shape_counter, s in enumerate(shapes): if rate_of_change[shape_counter] > 0: if s.opacity < self.target: s.opacity = \ float( "%.6f" % (s.opacity + rate_of_change[shape_counter]) ) else: completed = True else: if s.opacity > self.target: s.opacity = \ float( "%.6f" % (s.opacity + rate_of_change[shape_counter]) ) else: completed = True s.update() QApplication.processEvents() if completed: # Emitting end signal print("And.... scene!") self.end_signal.emit() self.started = False self.ended = True # Complete the thread if all shapes are faded to # its target return
class QtTest(unittest.TestCase, QObject): done = Signal() def __init__(self, *args, **kwargs): super(QtTest, self).__init__(*args, **kwargs) QObject.__init__(self) def setUp(self): """ Initialize our QApplication :return: None """ self.app = QApplication.instance() if self.app is None: self.app = QApplication([]) self.main_window = MainWindow(None) def tearDown(self): self.main_window.clean_up() def testGreeting(self): self.main_window.name_text.setText('Ryan') self.main_window.submit_button.click() assert self.main_window.hello_label.text() == u"{} {}".format(GREETING, 'Ryan') def testNamesList(self): self.done.connect(self.main_window.name_manager_thread.quit) self.main_window.name_text.setText('Ryan') self.main_window.submit_button.click() self.main_window.name_text.setText('Meg') self.main_window.submit_button.click() assert self.main_window.names_list.count() == 2 assert self.main_window.names_list.item(0).text() == 'Ryan' assert self.main_window.names_list.item(1).text() == 'Meg' assert wait_for(lambda: len(self.main_window.name_manager.names) == 2, 2) is True def testClearList(self): self.main_window.name_text.setText('Ryan') self.main_window.submit_button.click() self.main_window.name_text.setText('Meg') self.main_window.submit_button.click() self.main_window.clear_list_button.click() assert self.main_window.names_list.count() == 0 def testRestoreList(self): """ Using this method to test the Restore List procedure, we need to know exactly how many signals are going to be emitted. This could change over time without affecting our desired functionality. :return: """ self.main_window.name_text.setText('Ryan') self.main_window.submit_button.click() self.main_window.name_text.setText('Meg') self.main_window.submit_button.click() assert self.main_window.names_list.count() == 2 assert wait_for(lambda: len(self.main_window.name_manager.names) == 2, 2) is True self.main_window.clear_list_button.click() assert self.main_window.names_list.count() == 0 # This is running in another thread and we can't test # it the same way we tested other methods! self.main_window.restore_list_button.click() # First a signal is emitted to the NameManager thread to # get all the names. We have to process this event manually. self.app.processEvents() # The NameManager thread emits all the names to its names_signal. # We have to process this event as well! self.app.processEvents() # There must be a better way assert self.main_window.names_list.count() == 2 def testRestoreListBetter(self): """ Now we just keep processing events until we run out of work to do. Then we should have a deterministic state that we can test. :return: """ self.main_window.name_text.setText('Ryan') self.main_window.submit_button.click() self.main_window.name_text.setText('Meg') self.main_window.submit_button.click() assert self.main_window.names_list.count() == 2 assert wait_for(lambda: len(self.main_window.name_manager.names) == 2, 2) is True self.main_window.clear_list_button.click() assert self.main_window.names_list.count() == 0 # Simulate our restore button click self.main_window.restore_list_button.click() # While there is work to do, do it. while self.app.hasPendingEvents(): self.app.processEvents() # Now let's see what our state is assert self.main_window.names_list.count() == 2
def animate(self, shapes): self.start_signal.emit() # Sleeping to account the start_delay # TODO: Sleeping here's not gonna work, think somewhere else time.sleep(self.start_delay) self.running = True self.ended = False # Used to store the original opacities of the shapes original_opacity = [] # Used to store opacity to be reduced bu each frame rate_of_change = [] # Getting the original opacities of shapes in case the animation is # canceled in between try: if self.value_animators is None: pass except AttributeError: self.value_animators = [] for s in shapes: print("target is", self.target) self.value_animators.append(MValueAnimator(s.opacity, self.target, self.duration, self.fps)) # Main thread loop if self.running or self.paused: if self.canceled: # Restoring the opacity to the original in case the animation # was canceled for i, s in enumerate(shapes): s.opacity = self.value_animators[i].get_original_value() s.fading = False # Emitting cancel signal self.cancel_signal.emit() return elif self.ended: # Setting the opacity to the final value, i.e. target # in case if the animation was ended for s in shapes: s.fading = False s.opacity = self.target # Emitting end signal self.end_signal.emit() return elif self.paused: # Emitting pause signal self.pause_signal.emit() # Loop which will hold the thread until the animation is # paused # If you want the current state, pause the # animation and then cancel it if self.canceled: self.ended = True self.started = False self.cancel_signal.emit() for s in shapes: s.fading = False return # Emitting resume signal self.resume_signal.emit() else: # Flag to find out even if one shape is left to complete the # whole fade out animation if self.stop_whatever_you_are_doing_and_cancel_the_animation_right_there is False: completed = False for shape_counter, s in enumerate(shapes): try: s.opacity = self.value_animators[shape_counter].step() except MFinalValueReachedException: print("we're done, bruh") completed = True break s.update() QApplication.processEvents() else: self.stop_whatever_you_are_doing_and_cancel_the_animation_right_there = False completed = True if completed: # Emitting end signal for s in shapes: s.fading = False self.end_signal.emit() self.started = False self.ended = True # Complete the thread if all shapes are faded to # its target return False
def animate(self, shapes): self.start_signal.emit() # Sleeping to account the start_delay time.sleep(self.start_delay) self.running = True self.ended = False # Used to store the original opacities of the shapes original_opacity = [] # Used to store opacity to be reduced bu each frame reduce_rate = [] # Getting the original opacities of shapes in case the animation is # canceled in between for s in shapes: original_opacity.append(s.opacity) # Uses formula (((start - target) / fps) * (1000 / duration))x reduce_rate.append((s.opacity / self.fps) * (1000 / self.duration)) # Main thread loop while self.running or self.paused: if self.canceled: # Restoring the opacity to the original in case the animation # was canceled for i, s in enumerate(shapes): s.opacity = original_opacity[i] # Emitting cancel signal self.cancel_signal.emit() return elif self.ended: # Setting the opacity to the final value, i.e. min_opacity # in case if the animation was ended for s in shapes: s.opacity = s.min_opacity # Emitting end signal self.end_signal.emit() return elif self.paused: # Emitting pause signal self.pause_signal.emit() # Loop which will hold the thread until the animation is # paused while not self.paused: pass # Emitting resume signal self.resume_signal.emit() else: # Sleeping for 1/60 seconds, for 60fps time.sleep(1 / self.fps) # Flag to find out even if one shape is left to complete the # whole fade out animation completed = False for shape_counter, s in enumerate(shapes): if s.opacity > s.min_opacity: # Reducing the opacity by 0.1 if the opacity is not # already below minimum s.opacity = float("%.6f" % (s.opacity - reduce_rate[shape_counter])) s.update() QApplication.processEvents() else: completed = True if completed: # Emitting end signal self.end_signal.emit() self.started = False self.ended = True # Complete the thread if all shapes are faded out to # its minimum opacity return
splash = QSplashScreen(pixmap, QtCore.Qt.WindowStaysOnTopHint) splash.show() splash.setStyleSheet(""" font-family: inherit; font-weight: normal; font-size: 11pt; """) def splash_write(msg): if not splash is None: splash.showMessage("\t"+msg+"\n", color=QtCore.Qt.white, alignment=QtCore.Qt.AlignBottom) splash_write(NAME+" "+VERSION) app.processEvents() app.installTranslator(qtTranslator) if trasnlations: app.installTranslator(translator) frame = PinguinoIDE(splash_write=splash_write) frame.show() if not splash is None: splash.finish(frame) #For PyInstaller compatibility if app is None: from PySide.QtGui import QApplication QApplication.instance().exec_() else: