def on_styleActionGroup_triggered(self, action): """ Change current editor style """ self.ui.genericEditor.currentStyle = styles.getStyle(action.text()) stylesheet = "" if action.text() == "Dark": try: import qdarkstyle stylesheet = qdarkstyle.load_stylesheet() except ImportError: print "Failed to use the qdarkstyle. Please execute <pip install qdarkstyle> to fully use this theme." QApplication.instance().setStyleSheet(stylesheet)
def link_click_handler(self, url): if url.path() == u'blank': if url.hasFragment(): if url.fragment() == u'quit': QApplication.instance().quit() else: QDesktopServices.openUrl(url)
def _download(self): """Start downloading""" self._downloading = True self.model.stop_download = False QApplication.instance().need_download(self.model) self._update_download_status() self.pauseButton.setChecked(False)
def onLogin(self, host, username, passwd, ssl): """ Slot. Triggers a log in request to the server. :param host: Indicates the hostname of the FTP server :param username: Username to log in into the FTP server :param passwd: Password to log in into the FTP server :param ssl: Indicates whether the FTP needs SSL support """ self.sync = Sync(host, ssl) self.syncStarted.connect(self.sync.initQueue) self.sync.server.downloadProgress.connect(self.onDownloadProgress) self.sync.server.uploadProgress.connect(self.onUploadProgress) self.sync.server.fileEvent.connect(self.onFileEvent) self.sync.server.badFilenameFound.connect(self.badNameWarning) self.sync.server.loginCompleted.connect(self.onLoginCompleted) self.sync.server.fileEventCompleted.connect(self.onFileEventCompleted) self.sync.server.ioError.connect(self.onIOError) # Added by Si self.sync.server.textStatus.connect(self.setStatus) self.sync.statusChanged.connect(self.setStatus) self.loginRequested.connect(self.sync.server.onLogin) self.syncThread = QThread() self.sync.moveToThread(self.syncThread) self.syncThread.start() QApplication.instance().lastWindowClosed.connect(self.syncThread.quit) self.loginRequested.emit(username, passwd)
def __init__(self, interval): # make sure we actually have a qapp if QApplication.instance() is None: QApplication(sys.argv) Thread.__init__(self) self.interval = interval self.event = Event() self.qtapp = QApplication.instance()
def testInstanceObject(self): TestObject.createApp() app1 = QApplication.instance() app2 = QApplication.instance() app1.setObjectName("MyApp") self.assertEqual(app1, app2) self.assertEqual(app2.objectName(), app1.objectName()) app1.destroyed.connect(self.appDestroyed)
def eventFilter(self, obj, event): if obj and not obj.isEnabled() and event.type() == QEvent.Wheel: newEvent = QWheelEvent(obj.mapToParent(event.pos()), event.globalPos(), event.delta(), event.buttons(), event.modifiers(), event.orientation()) QApplication.instance().postEvent(obj.parent(), newEvent) return True return QObject.eventFilter(self, obj, event)
def event(self, event): if ((event.type() == QEvent.RequestSoftwareInputPanel) and (self.settings.hideVKB)): #Hacky way to do, but event is already processed when #python got the hand closeEvent = QEvent(QEvent.CloseSoftwareInputPanel) QApplication.instance().postEvent(self, closeEvent) return True return QtDeclarative.QDeclarativeView.event(self, event)
def custom_except_hook(exctype, value, tb): if isinstance(value, KeyboardInterrupt): log.info("KeyboardInterrupt caught. Exiting...") from PySide.QtGui import QApplication QApplication.instance().quit() return s = ''.join(traceback.format_exception(exctype, value, tb)) log.exception(s) dialog = ErrorReportDialog(None, s) dialog.exec_()
def spin(self): for thread in self.threads.values(): thread.start() # QApplication.instance().exec_() is blocking, so start a timer and give it a slice # of the action every now and then to check if it should shut things down for us. if not self.disable_qt_management: self.timer.timeout.connect(self.watchdog) self.timer.start(200) if QApplication.instance() is not None: QApplication.instance().exec_() for thread in self.threads.values(): thread.join()
def distinguish(): """Distinguish GUI from other projects This adds a green line to the top of Maya's GUI """ QApplication.instance().setStyleSheet(""" QMainWindow > QMenuBar { border-bottom: 1px solid lightgreen; } """)
def isFocusWidget(): """ return true if the global qApp has any focused widgets """ from PySide.QtGui import QApplication, QCursor focus = False if QApplication.instance(): if QApplication.instance().focusWidget(): window = QApplication.instance().focusWidget().window() geom = window.geometry() focus = geom.contains( QCursor.pos() ) return focus
def __init__(self, *args, **kwargs): QDialog.__init__(self, *args, **kwargs) self.app = QApplication.instance() self.closed = False self.startup_path = os.path.expanduser('~/.config/autostart/') if not os.path.exists(self.startup_path): os.makedirs(self.startup_path) self.startup_file = os.path.join(self.startup_path, 'everpad.desktop') self.ui = Ui_Dialog() self.ui.setupUi(self) self.ui.webView.hide() self.setWindowIcon(get_icon()) for delay in (5, 10, 15, 30): self.ui.syncDelayBox.addItem(self.tr('%d minutes') % delay, userData=str(delay * 60 * 1000), ) self.ui.syncDelayBox.addItem(self.tr('One hour'), userData='3600000') self.ui.syncDelayBox.addItem(self.tr('Manual'), userData='-1') active_index = self.ui.syncDelayBox.findData(str( self.app.provider.get_sync_delay(), )) self.ui.syncDelayBox.setCurrentIndex(active_index) self.ui.syncDelayBox.currentIndexChanged.connect(self.delay_changed) self.ui.tabWidget.currentChanged.connect(self.update_tabs) self.ui.authBtn.clicked.connect(self.change_auth) self.ui.autoStart.stateChanged.connect(self.auto_start_state) self.ui.noteFont.currentFontChanged.connect(self.font_changed) self.ui.noteSize.valueChanged.connect(self.font_size_changed) self.ui.blackTray.stateChanged.connect(self.tray_changed) self.ui.progressCheckBox.stateChanged.connect(self.progress_changed) self.update_tabs()
def setupActions(self): action_slots = dict( New=self.newFile, Open=self.askOpenFile, Save=self.saveFile, SaveAs=self.askSaveFile, Print=self.askPrint, Quit=self.close, Undo=self.editor.undo, Redo=self.editor.redo, Cut=self.editor.cut, Copy=self.editor.copy, Paste=self.editor.paste, Find=self.toggleSearchDock, FindNext=self.find, FindPrevious=partial(self.find, backwards=True), SelectAll=self.editor.selectAll, GoToLine=self.askGoToLine, AboutQt=QApplication.instance().aboutQt, About=self.about) for action in self.findChildren(QAction): object_name = action.objectName() if not object_name: continue action_name = object_name[len(self.ACTION_PREFIX):] icon_name = self.ACTION_ICONS.get(action_name) if icon_name: action.setIcon(QIcon.fromTheme(icon_name)) key = self.ACTION_KEYS.get(action_name) if key: action.setShortcut(key) slot = action_slots.get(action_name) if slot: action.triggered.connect(slot) if action_name in self.DISABLED_ACTIONS: action.setEnabled(False) for action in self.menuEdit.actions(): self.editor.addAction(action)
def __init__(self, *args, **kwargs): QMainWindow.__init__(self, *args, **kwargs) self.app = QApplication.instance() self.closed = False self.sort_order = None self.ui = Ui_List() self.ui.setupUi(self) self.setWindowIcon(get_icon()) self.app.data_changed.connect(self._reload_notebooks_list) self.notebooksModel = QStandardItemModel() self.ui.notebooksList.setModel(self.notebooksModel) self.ui.notebooksList.selection.connect(self.selection_changed) self.ui.notebooksList.setContextMenuPolicy(Qt.CustomContextMenu) self.ui.notebooksList.customContextMenuRequested.connect(self.notebook_context_menu) self.notesModel = QStandardItemModel() self.notesModel.setHorizontalHeaderLabels( [self.tr('Title'), self.tr('Last Updated')]) self.ui.notesList.setModel(self.notesModel) self.ui.notesList.doubleClicked.connect(self.note_dblclicked) self.ui.notesList.setContextMenuPolicy(Qt.CustomContextMenu) self.ui.notesList.customContextMenuRequested.connect(self.note_context_menu) self.ui.notesList.header().sortIndicatorChanged.connect(self.sort_order_updated) self.ui.newNotebookBtn.setIcon(QIcon.fromTheme('folder-new')) self.ui.newNotebookBtn.clicked.connect(self.new_notebook) self.ui.newNoteBtn.setIcon(QIcon.fromTheme('document-new')) self.ui.newNoteBtn.clicked.connect(self.new_note) self.ui.newNoteBtn.setShortcut(QKeySequence(self.tr('Ctrl+n'))) self.ui.newNotebookBtn.setShortcut(QKeySequence(self.tr('Ctrl+Shift+n'))) QShortcut(QKeySequence(self.tr('Ctrl+q')), self, self.close)
def about(self): app = QApplication.instance() args = {'name': app.applicationName(), 'version': app.applicationVersion()} title = self.trUtf8(b'{name} {version}').format(**args) text = self.trUtf8("""\ <h1>{name} {version}</h1> <p>An trivial text editor implemented in Qt</p> <p>Copyright © 2011 <a href="mailto:[email protected]">Sebastian Wiesner</a></p> <p>Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:<p> <ul><li>The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.</li></ul> <p><strong>The software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the software.</strong></p>""").format(**args) QMessageBox.about(self, title, text)
def _apply_style(): """ Apply the current style to the application. """ # Rebind for easier use and log. style = _current_style log.info('Applying style %r.' % style.data['name']) # Get the app. app = QApplication.instance() if not app: raise RuntimeError("You can't apply a style without a QApplication.") # Enable or disable Aero. if _aeroglass: if style.aero: _aeroglass.enable() else: _aeroglass.disable() # Set the widget style. app.setStyle(style.ui if style.ui else profile.get('siding/widget-style')) # Load the main stylesheet. app.setStyleSheet(load_qss('application.qss')) # Restyle every styled widget. for ref in _managed_widgets.keys(): _style_widget(ref)
def update_title(self): if self.current_file: title = os.path.basename(self.current_file) else: title = "Untitled" self.setWindowTitle("%s - %s" % (title, QApplication.instance().applicationName()))
def setup_gui(self): """Sets up a sample gui interface.""" central_widget = QWidget(self) central_widget.setObjectName('central_widget') self.label = QLabel('Hello World') self.input_field = QLineEdit() change_button = QPushButton('Change text') close_button = QPushButton('close') quit_button = QPushButton('quit') central_layout = QVBoxLayout() button_layout = QHBoxLayout() central_layout.addWidget(self.label) central_layout.addWidget(self.input_field) # a separate layout to display buttons horizontal button_layout.addWidget(change_button) button_layout.addWidget(close_button) button_layout.addWidget(quit_button) central_layout.addLayout(button_layout) central_widget.setLayout(central_layout) self.setCentralWidget(central_widget) # create a system tray icon. Uncomment the second form, to have an # icon assigned, otherwise you will only be seeing an empty space in # system tray self.systemtrayicon = QSystemTrayIcon(self) self.systemtrayicon.show() # set a fancy icon self.systemtrayicon.setIcon(QIcon.fromTheme('help-browser')) change_button.clicked.connect(self.change_text) quit_button.clicked.connect(QApplication.instance().quit) close_button.clicked.connect(self.hide) # show main window, if the system tray icon was clicked self.systemtrayicon.activated.connect(self.icon_activated)
def __init__(self, note, *args, **kwargs): QMainWindow.__init__(self, *args, **kwargs) # Configure logger. self.logger = logging.getLogger("everpad-editor") self.logger.setLevel(logging.DEBUG) fh = logging.FileHandler(os.path.expanduser("~/.everpad/logs/everpad.log")) fh.setLevel(logging.DEBUG) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") fh.setFormatter(formatter) self.logger.addHandler(fh) self.app = QApplication.instance() self.timer = QBasicTimer() self.note = note self.closed = False self.ui = Ui_Editor() self.ui.setupUi(self) self.setWindowIcon(get_icon()) self.alternatives_template = self.ui.alternativeVersions.text() self.init_controls() self.load_note(note) self.update_title() self.mark_untouched() geometry = self.app.settings.value("note-geometry-%d" % self.note.id) if not geometry: geometry = self.app.settings.value("note-geometry-default") if geometry: self.restoreGeometry(geometry) self.resource_edit.note = note self.timer.start(10000, self)
def apply(self): """ Apply this style to the application. """ log.info('Applying style: %s' % self.name) app = QApplication.instance() if self.data.get('aero'): self._enable_aero() else: self._disable_aero() # The Widget Style ui = self.data.get('ui', profile.get('siding/widget-style')) app.setStyle(ui) # Now, load the application QSS. qss = self.load_qss('application.qss') app.setStyleSheet(qss) # Restyle every styled widget. for ref in _managed_widgets.keys(): self.style_widget(None, ref) # Set this as the current style. if not self.active: loaded_styles[None] = self
def ticked(fnc, *args, **kwargs): """Check app tick""" if 'tick' in kwargs: tick = kwargs['tick'] else: tick = args[-1] if tick == QApplication.instance().tick: return fnc(*args, **kwargs)
def __init__(self, *args, **kwargs): QSystemTrayIcon.__init__(self, *args, **kwargs) self.app = QApplication.instance() self.menu = QMenu() self.setContextMenu(self.menu) self.menu.aboutToShow.connect(self.update) self.opened_notes = {} self.activated.connect(self._activated)
def __init__(self, parent, widget, on_change): """Init and connect signals""" self.parent = parent self.app = QApplication.instance() self.widget = widget for notebook_struct in self.app.provider.list_notebooks(): notebook = Notebook.from_tuple(notebook_struct) self.widget.addItem(notebook.name, userData=notebook.id) self.widget.currentIndexChanged.connect(Slot()(on_change))
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 __init__(self, *args, **kwargs): QMainWindow.__init__(self, *args, **kwargs) self.app = QApplication.instance() self.closed = False self.sort_order = None self._init_interface() self.app.data_changed.connect(self._reload_data) self._init_notebooks() self._init_tags() self._init_notes()
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 createNextWebView(): global functionID nListCount = len(FUNCTIONS_LIST) - 1 functionID = functionID + 1 print functionID if functionID < nListCount: createWebView( functionID ) else: QTimer.singleShot(300, QApplication.instance().quit)
def render(self, ok): if ok: print('Loaded {0}'.format(self.url.toString())) self.webpage.setViewportSize( self.webpage.mainFrame().contentsSize()) image = QImage(self.webpage.viewportSize(), QImage.Format_ARGB32) painter = QPainter(image) self.webpage.mainFrame().render(painter) painter.end() if image.save(self.image_path): print('Saved image to {0}'.format(self.image_path)) else: print('Could not save to {0}'.format(self.image_path)) else: print('Could not load {0.toString()}'.format(self.url)) QApplication.instance().quit()
def __init__(self, name, session): # export this object to dbus dbus.service.Object.__init__(self, name, session) # create a simple widget self.widget = QPushButton() self.widget.resize(200, 50) # To export a Qt signal as a DBus-signal, you need to connect it to a method in this class. # The method MUST have the signal annotation, so python-dbus will export it as a dbus-signal QObject.connect(self.widget, SIGNAL("clicked()"), self.clicked) QObject.connect(QApplication.instance(), SIGNAL("lastWindowClosed()"), self.lastWindowClosed)
def setUpClass(cls): super(TestDeliverySlipGUI, cls).setUpClass() app = QApplication.instance() if app is None: app = QApplication(sys.argv) cls.app = app
def findSets(tokens): operatorPriority = { '^NOT': 3, '^AND': 2, '^OR': 1, '$BASE': 0, } logicFunctions = { '^AND': lambda x, y: set(x).intersection(set(y)), '^OR': lambda x, y: set(x).union(set(y)), '^NOT': lambda x, y: set(x).difference(set(y)) } operatorStack = Stack() docStack = Stack() indexer = QApplication.instance().indexer def doOperation(): operation = operatorStack.pop() try: setB = docStack.pop() if not isinstance(setB, set): setB = setB.documentSet setA = docStack.pop() if not isinstance(setA, set): setA = setA.documentSet docStack.push(logicFunctions[operation](setA, setB)) except StackError: QMessageBox.information(QMainWindow(), "No items found", "There was an error parsing your request", QMessageBox.Ok) def repeatOperation(operator): try: if operator == "^NOT" and operatorStack.top() == "^NOT": pass else: while len(docStack) > 1 and len( operatorStack) and operatorPriority[ operatorStack.top()] >= operatorPriority[operator]: doOperation() except StackError: pass if len(tokens) == 1 and tokens[0] not in logicFunctions: if indexer.data['WORDS'].has_word(tokens[0].encode('ascii')): return QApplication.instance().indexer.data['WORDS'].getData( tokens[0]).documentSet else: QMessageBox.information( QMainWindow(), "Word not found", "The word " + tokens[0].encode('ascii') + " is not in any documents. Did you mean " + indexer.data['WORDS'].getSimilar(tokens[0].encode('ascii')) + "?", QMessageBox.Ok) raise ValueError phraseCounter = 0 phrase = "" for token in tokens: if token not in logicFunctions: if indexer.data['WORDS'].has_word(token.encode('ascii')): docStack.push( QApplication.instance().indexer.data['WORDS'].getData( token).documentSet) phraseCounter += 1 phrase += token.encode('ascii') + " " else: QMessageBox.information( QMainWindow(), "Word not found", "The word " + token.encode('ascii') + " is not in any documents. Did you mean " + indexer.data['WORDS'].getSimilar(token.encode('ascii')) + "?", QMessageBox.Ok) raise ValueError else: if phraseCounter > 1: while phraseCounter > 0: setB = docStack.pop() if not isinstance(setB, set): setB = setB.documentSet setA = docStack.pop() if not isinstance(setA, set): setA = setA.documentSet docStack.push(logicFunctions["^AND"](setA, setB)) properSet = set() for doc in docStack.pop(): with open(doc, 'r') as document: content = document.read() document.close() if bool(re.search(phrase.strip(), content)): properSet.add(doc) docStack.push(properSet) phraseCounter -= 2 phrase = "" phraseCounter = 0 if token == "^NOT": docStack.push(indexer.data['FILES']) if not operatorStack.isEmpty(): repeatOperation(token) operatorStack.push(token) if phraseCounter > 1: while phraseCounter > 0: setB = docStack.pop() if not isinstance(setB, set): setB = setB.documentSet setA = docStack.pop() if not isinstance(setA, set): setA = setA.documentSet docStack.push(logicFunctions["^AND"](setA, setB)) properSet = set() for doc in docStack.pop(): with open(doc, 'r') as document: content = document.read() document.close() if bool(re.search(phrase.strip(), content)): properSet.add(doc) docStack.push(properSet) phraseCounter -= 2 repeatOperation('$BASE') if len(docStack) == 1: return docStack.pop() else: QMessageBox.information(QMainWindow(), "No items found", "There was an error parsing your request", QMessageBox.Ok) raise ValueError
def initialize(args=None, **kwargs): """ Initialize the style system. You may use the following arguments to configure the style system: ============== ============ ============ Argument Default Description ============== ============ ============ safe_mode ``False`` When safe mode is enabled, styles won't be loaded automatically. style The name of the style to load. This overrides the profile value. default_style ``default`` The name of the default style to use if one isn't chosen. ============== ============ ============ In addition, you can provide a list of command line arguments to have siding load them automatically. Example:: siding.style.initialize(sys.argv[1:]) The following command line arguments are supported: ================ ============ Argument Description ================ ============ ``--safe-mode`` When safe mode is enabled, styles won't be loaded automatically. ``--style`` The name of the style to load. ================ ============ """ global safe_mode # Set the defaults now. safe_mode = kwargs.get('safe_mode', safe_mode) style = kwargs.get('style') default_style = kwargs.get('default_style', 'default') # We require the profile for this. if not profile.settings: raise RuntimeError( "siding.style requires you to call siding.profile.initialize() first." ) # Now, parse the options we've got. if args: if args is True: args = sys.argv[1:] parser = argparse.ArgumentParser(add_help=False) parser.add_argument('--safe-mode', action='store_true', default=None) parser.add_argument('--style') options = parser.parse_known_args(args)[0] # Store that then. if options.safe_mode is not None: safe_mode = options.safe_mode if options.style: style = options.style # If we don't have a style, get it from the profile or fall back to if not style: style = profile.get('siding/current-style', default_style) # Save the current widget style. widget_style = QApplication.instance().style().metaObject().className() widget_style = STYLE_KEYS.get(widget_style) if widget_style: profile.set('siding/widget-style', widget_style) # Load the style. That is, if safe mode isn't on. if safe_mode: log.info('Not loading style %r due to safe mode.' % style) return try: load(style) except (IOError, ValueError): # If we weren't using the default style, then eat the error and try # loading the default style. if style != default_style: try: load(default_style) except (IOError, ValueError): pass
def __init__(self): QMainWindow.__init__(self) # the user interface, consisting of a progress bar above a plain # text edit, which logs all actions. container = QWidget(self) container.setLayout(QVBoxLayout(container)) self.setCentralWidget(container) progressbar = QProgressBar(container) container.layout().addWidget(progressbar) log = QPlainTextEdit(container) container.layout().addWidget(log) # the actual worker thread counter = Counter(100, self) # an action to quit the windows exit = QAction(QIcon.fromTheme('application-exit'), 'exit', self) # add two actions to start and stop the worker to the toolbar of the # main window start_counting = QAction(QIcon.fromTheme('media-playback-start'), 'Start counting', self) stop_counting = QAction(QIcon.fromTheme('media-playback-stop'), 'Stop counting', self) # initially no counter runs, so we can disable the stop action stop_counting.setEnabled(False) # add all actions to a toolbar actions = self.addToolBar('Actions') actions.addAction(exit) actions.addSeparator() actions.addAction(start_counting) actions.addAction(stop_counting) # quit the application, if the quit action is triggered exit.triggered.connect(QApplication.instance().quit) # start and stop the counter, if the corresponding actions are # triggered. start_counting.triggered.connect(counter.start) stop_counting.triggered.connect(counter.stop) # adjust the minimum and the maximum of the progress bar, if # necessary. Not really required in this snippet, but added for the # purpose of demonstrating it counter.minimumChanged.connect(progressbar.setMinimum) counter.maximumChanged.connect(progressbar.setMaximum) # switch the enabled states of the actions according to whether the # worker is running or not counter.started.connect(partial(start_counting.setEnabled, False)) counter.started.connect(partial(stop_counting.setEnabled, True)) counter.finished.connect(partial(start_counting.setEnabled, True)) counter.finished.connect(partial(stop_counting.setEnabled, False)) # update the progess bar continuously counter.progress.connect(progressbar.setValue) # log all actions in our logging widget counter.started.connect( partial(self.statusBar().showMessage, 'Counting')) counter.finished.connect(partial(self.statusBar().showMessage, 'Done')) # log a forced stop stop_counting.triggered.connect(partial(log.appendPlainText, 'Stopped')) # log all counted values counter.progress.connect(lambda v: log.appendPlainText(str(v))) # and finally show the current state in the status bar. counter.started.connect(partial(log.appendPlainText, 'Counting')) counter.finished.connect(partial(log.appendPlainText, 'Done'))
def __init__(self, user_agent=default_user_agent, wait_timeout=8, wait_callback=None, log_level=logging.WARNING, display=False, viewport_size=(800, 600), ignore_ssl_errors=True, cache_dir=os.path.join(tempfile.gettempdir(), "ghost.py"), plugins_enabled=False, java_enabled=False, plugin_path=[ '/usr/lib/mozilla/plugins', ], download_images=True, qt_debug=False, show_scroolbars=True): self.http_resources = [] self.user_agent = user_agent self.wait_timeout = wait_timeout self.wait_callback = wait_callback self.ignore_ssl_errors = ignore_ssl_errors self.loaded = True if not sys.platform.startswith('win') and not 'DISPLAY' in os.environ\ and not hasattr(Ghost, 'xvfb'): try: os.environ['DISPLAY'] = ':99' Ghost.xvfb = subprocess.Popen(['Xvfb', ':99']) except OSError: raise Error('Xvfb is required to a ghost run outside ' + 'an X instance') self.display = display if not Ghost._app: Ghost._app = QApplication.instance() or QApplication(['ghost']) qInstallMsgHandler(QTMessageProxy(qt_debug)) if plugin_path: for p in plugin_path: Ghost._app.addLibraryPath(p) self.popup_messages = [] self.page = GhostWebPage(Ghost._app, self) QtWebKit.QWebSettings.setMaximumPagesInCache(0) QtWebKit.QWebSettings.setObjectCacheCapacities(0, 0, 0) QtWebKit.QWebSettings.globalSettings().setAttribute( QtWebKit.QWebSettings.LocalStorageEnabled, True) self.page.setForwardUnsupportedContent(True) self.page.settings().setAttribute(QtWebKit.QWebSettings.AutoLoadImages, download_images) self.page.settings().setAttribute(QtWebKit.QWebSettings.PluginsEnabled, plugins_enabled) self.page.settings().setAttribute(QtWebKit.QWebSettings.JavaEnabled, java_enabled) if not show_scroolbars: self.page.mainFrame().setScrollBarPolicy( QtCore.Qt.Vertical, QtCore.Qt.ScrollBarAlwaysOff) self.page.mainFrame().setScrollBarPolicy( QtCore.Qt.Horizontal, QtCore.Qt.ScrollBarAlwaysOff) self.set_viewport_size(*viewport_size) # Page signals self.page.loadFinished.connect(self._page_loaded) self.page.loadStarted.connect(self._page_load_started) self.page.unsupportedContent.connect(self._unsupported_content) self.manager = self.page.networkAccessManager() self.manager.finished.connect(self._request_ended) self.manager.sslErrors.connect(self._on_manager_ssl_errors) # Cache self.cache = QNetworkDiskCache() self.cache.setCacheDirectory(cache_dir) self.manager.setCache(self.cache) # Cookie jar self.cookie_jar = QNetworkCookieJar() self.manager.setCookieJar(self.cookie_jar) # User Agent self.page.setUserAgent(self.user_agent) self.page.networkAccessManager().authenticationRequired\ .connect(self._authenticate) self.page.networkAccessManager().proxyAuthenticationRequired\ .connect(self._authenticate) self.main_frame = self.page.mainFrame() logger.setLevel(log_level) if self.display: class MyQWebView(QtWebKit.QWebView): def sizeHint(self): return QSize(*viewport_size) self.webview = MyQWebView() if plugins_enabled: self.webview.settings().setAttribute( QtWebKit.QWebSettings.PluginsEnabled, True) if java_enabled: self.webview.settings().setAttribute( QtWebKit.QWebSettings.JavaEnabled, True) self.webview.setPage(self.page) self.webview.show() else: self.webview = None
def setUpClass(cls): super(TestFindOrderGUI, cls).setUpClass() app = QApplication.instance() if app is None: app = QApplication(sys.argv) cls.app = app
def setUpClass(cls): super(TestCustomerDialog,cls).setUpClass() app = QApplication.instance() if app is None: app = QApplication(sys.argv) cls.app = app
def __init__(self): try: self.app = _QtApp(sys.argv) except RuntimeError: self.app = _QtApp.instance() # if QApplication already exists self.dialog = runtime.CalcDialog()
def __init__(self, *args, **kwargs): self.app = QApplication.instance() dbus.service.Object.__init__(self, *args, **kwargs)
def sizeHint(self): desktop = QApplication.instance().desktop() geom = desktop.availableGeometry() return QSize(geom.width() / 2, geom.height() / 2)
import sys from PySide.QtGui import QApplication, QTreeWidgetItem, QWidget, QTreeWidget from engine.engine import Engine from core.cache import Singleton, MainCache mainCache = Singleton(MainCache) if __name__ == '__main__': app = 0 if QApplication.instance(): app = QApplication.instance() else: app = QApplication(sys.argv) w = QWidget() w.resize(510, 210) tw = QTreeWidget(w) tw.resize(500, 200) tw.setColumnCount(3) tw.setHeaderLabels(["Asset", "Gross Amount", "Net Amount", "Payment Date"]) mainCache = Singleton(MainCache) mainCache.refreshReferenceData() Engine.buildCorporateEventPosition() for key, cep in mainCache.corporateEventPositionDictAsset.items(): l1 = QTreeWidgetItem([key, str(cep.accGrossAmount), str(cep.accNetAmount)]) for ce in cep.corporateEventList: l1_child = QTreeWidgetItem([None, str(ce.grossAmount), str(ce.netAmount),str(ce.paymentDate)]) l1.addChild(l1_child) tw.addTopLevelItem(l1)
def setUpClass(cls): super(TestUserLogin,cls).setUpClass() app = QApplication.instance() if app is None: app = QApplication(sys.argv) cls.app = app f = tempfile.NamedTemporaryFile(mode='w',delete=False) mainlog.debug(f.name) f.write(r"""[Database] url = postgresql://tester:@localhost:5432/horse_test echo_query = False recreate_table = False user = tester password = "" db_name = horse_test [Proxy] # proxy_url=127.0.0.1 #proxy_port=5865 proxy_url = "" proxy_port = "" [MediaFire] email = [email protected] password = Smals23081 appid = 33522 sessionkey = 8zcfzgxq614j0a1ivyb2mllm402x443zxms99iul [Backup] prefix = horse_backup dirname = horse_backup # Size in megabytes size = integer(default=9) encryption_key = AZEDSFKHSDFIZERBDSFISRBAZEIRA3244234AZE434 backup_directory = c:\tmp [Commands] pg_dump_cmd = C:\PORT-STC\opt\pgsql\bin\pg_dump.exe zip = zip encrypt_cmd = string(default="C:\PORT-STC\opt\aescrypt.exe") dropdb_cmd = string(default="C:\PORT-STC\opt\pgsql\bin\dropdb.exe") createdb_cmd = string(default="C:\PORT-STC\opt\pgsql\bin\createdb.exe") pg_restore_cmd = string(default="C:\PORT-STC\opt\pgsql\bin\pg_restore.exe") [Mail] SMTPServer = string sender = [email protected] destination = [email protected] SMTPUser = fb569808 SMTPPassword = xjb6pqrx [DownloadSite] port = 8079 current_version = 1.0.10 client_path = c:\port-stc\pl-private\src\horse\dist\horse-%(current_version)s.zip db_url = postgresql://horse_clt:[email protected]:5432/horsedb """) f.close() configuration.load(f.name, os.path.join( resource_dir, 'config-check.cfg'))
def initCentral(self): QApplication.instance().webview = DocumentView( os.getcwd() + "\\res\\ProjectGreeter.html") self.setCentralWidget(QApplication.instance().webview)