Example #1
0
 def clicked_force_shutdown(self):
     process_checker = ProcessChecker()
     if process_checker.already_running:
         core_pid = process_checker.get_pid_from_lock_file()
         os.kill(int(core_pid), 9)
     # Stop the Qt application
     QApplication.quit()
Example #2
0
 def _quit(self):
     """
     This method maps the quit action to actual quit. Before quitting
     it checks for unsaved changes.
     """
     if self._check_for_unsaved_changes():
         QApplication.quit()
Example #3
0
 def closeEvent(self, event):
     try:
         self.player.stop()
         self.player.shutdown()
     except Exception as e:
         pass
     QApplication.quit()
Example #4
0
    def close_tribler(self):
        if not self.core_manager.shutting_down:
            def show_force_shutdown():
                self.window().force_shutdown_btn.show()

            self.delete_tray_icon()
            self.show_loading_screen()
            self.hide_status_bar()
            self.loading_text_label.setText("Shutting down...")
            if self.debug_window:
                self.debug_window.setHidden(True)

            self.shutdown_timer = QTimer()
            self.shutdown_timer.timeout.connect(show_force_shutdown)
            self.shutdown_timer.start(SHUTDOWN_WAITING_PERIOD)

            self.gui_settings.setValue("pos", self.pos())
            self.gui_settings.setValue("size", self.size())

            if self.core_manager.use_existing_core:
                # Don't close the core that we are using
                QApplication.quit()

            self.core_manager.stop()
            self.core_manager.shutting_down = True
            self.downloads_page.stop_loading_downloads()
            request_queue.clear()

            # Stop the token balance timer
            if self.token_refresh_timer:
                self.token_refresh_timer.stop()
Example #5
0
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 exit(*args):
    # TODO: Stop all services
    print("Shutdown initiated, stopping all services...")

    # Terminate entire process group, just in case.
    # os.killpg(0, signal.SIGINT)

    QApplication.quit()
    def launch_exit_dialog(self):
        if cfg.core.project.is_open() == False:
            QApplication.quit()

        result = self.launch_close_dialog()
        if result == QMessageBox.Cancel:
            return QMessageBox.Cancel
        QApplication.quit()
Example #8
0
def running_warning(message=None, critical=False):
    if not message:
        message = 'OSF-Sync is already running. Check out the system tray.'
    warn_app = QApplication(sys.argv)
    if critical:
        QMessageBox.critical(None, 'Systray', message)
    else:
        QMessageBox.information(None, 'Systray', message)
    warn_app.quit()
Example #9
0
 def closeEvent(self, event):
     event.accept()
     if self.app.model.results.is_modified:
         title = tr("Unsaved results")
         msg = tr("You have unsaved results, do you really want to quit?")
         if not self.app.confirm(title, msg):
             event.ignore()
     if event.isAccepted():
         QApplication.quit()
Example #10
0
def running_warning():
    warn_app = QApplication(sys.argv)
    QMessageBox.information(
        None,
        "Systray",
        "OSF-Offline is already running. Check out the system tray."
    )
    warn_app.quit()
    sys.exit(0)
Example #11
0
 def closeEvent(self, event):
     """Override the PyQt close event in order to handle save playlist on close."""
     playlist = "{}/.m3u" .format(self.playlist_location)
     if defaults.Settings().save_playlist_on_close:
         self.playlist.save(QUrl().fromLocalFile(playlist), "m3u")
     else:
         if os.path.exists(playlist):
             os.remove(playlist)
     QApplication.quit()
Example #12
0
    def closeEvent(self, event):
        if not self.exit_logger():
            event.ignore()
            return

        self.exit_brickv()
        event.accept()
        async_stop_thread()

        # Without this, the quit event seems to not reach the main loop under OSX.
        QApplication.quit()
Example #13
0
class Render(QWebPage):  
  def __init__(self, url):  
    self.app = QApplication(sys.argv)  
    QWebPage.__init__(self)  
    self.loadFinished.connect(self._loadFinished)  
    self.mainFrame().load(QUrl(url))  
    self.app.exec_()  
  
  def _loadFinished(self, result):  
    self.frame = self.mainFrame()  
    self.app.quit()  
Example #14
0
def main(argv=None):
    if not argv:
        argv = sys.argv

    app = QApplication(argv)
    lw = LoginWindow()
    if lw.exec_() == 1:
        mw = MainWindow(lw.server, lw.user, lw.pw)
        mw.show()
    else:
        app.quit()
        return
    return app.exec_()
Example #15
0
    def unload(self):
        #THIS NEEDS TO WORK (IT DOES CURRENTLY)
        #The closeEvent handler of the dialog is what saves config:
        self.__dashboardDialog.close()
        
        #Doesn't work -- dunno why:
        #self.__mapWidget.close()

        #do any cleanup here
        self.mapWidget.done(0)
        self.__dashboardDialog.done(0)
        
        QApplication.quit()
Example #16
0
def window(api_port):
    core_manager.START_FAKE_API = True
    tribler_gui.defs.DEFAULT_API_PORT = api_port

    app = TriblerApplication("triblerapp-guitest", sys.argv)
    window = TriblerWindow(settings=QSettings(), api_port=api_port)  # pylint: disable=W0621
    app.set_activation_window(window)
    QTest.qWaitForWindowExposed(window)

    screenshot(window, name="tribler_loading")
    wait_for_signal(window.core_manager.events_manager.tribler_started)
    window.downloads_page.can_update_items = True
    yield window
    QApplication.quit()
Example #17
0
class UI():
   def __init__(self):
      self.app = QApplication(sys.argv)
      self.main_window = None

      if "username" in config.user and "password" in config.user:
         self.finished_auto = False
         self.autoLogin()
      else:
         self.createLogin()

   def autoLogin(self):
      self.client_socket = network.ClientSocket("localhost", 6667)
      self.client_socket.authenticateUser(config.user["username"], config.user["password"])
      self.client_socket.authenticate_success.connect(self.createMain)
      self.client_socket.authenticate_failure.connect(self.createLogin)

   def autoLoginSuccess(self):
      self.finished_auto = True
      self.auto_success  = True

   def autoLoginFailure(self):
      self.finished_auto = True
      self.auto_success  = False

   def createLogin(self):
      self.login_window = LoginWindow()
      self.login_window.loggedIn.connect(self.finishLogin)
      self.login_window.exit.connect(self.closeApplication)

   def finishLogin(self):
      self.login_window.close()
      self.client_socket = self.login_window.client_socket
      self.createMain()

   def createMain(self):
      self.main_window = MainWindow(self.client_socket, self.app.processEvents)

   def closeApplication(self):
      self.app.quit()

   def searchUser(self, query):
      self.client_socket.searchUser(query)

   def exec(self):
      return self.app.exec_()

   def disconnect(self):
      if not self.main_window == None:
         self.main_window.disconnect()
Example #18
0
    def closeEvent(self, event):
        """Close application.

        Parameters
        ----------
        event : QEvent
            Close event.
        """
        self._write_settings()
        if self.history:
            print("\nCommand History")
            print("===============")
            print("\n".join(self.history))
        QApplication.quit()
Example #19
0
def crash_handler():
    """Implements minimal handling of an exception crashing the application.
    This function tries to log the exception to a log file and display
    a minimal crash dialog to the user.
    This function is supposed to be called from inside an except blog.
    """
    import sys

    # Allow disabling the graphical crash handler for debugging and CI purposes.
    if set(sys.argv) & {'--no-crash-dialog', '-v', '--version', '-V', '--long-version', '-h', '--help'}:
        return

    # First try to get traceback information and write it to a log file
    # with minimum chance to fail.
    from tempfile import NamedTemporaryFile
    import traceback
    trace = traceback.format_exc()
    logfile = None
    try:
        with NamedTemporaryFile(suffix='.log', prefix='picard-crash-', delete=False) as f:
            f.write(trace.encode(errors="replace"))
            logfile = f.name
    except:  # noqa: E722,F722 # pylint: disable=bare-except
        print("Failed writing log file {0}".format(logfile), file=sys.stderr)
        logfile = None

    # Display the crash information to the user as a dialog. This requires
    # importing Qt5 and has some potential to fail if things are broken.
    from PyQt5.QtCore import QCoreApplication, Qt, QUrl
    from PyQt5.QtWidgets import QApplication, QMessageBox
    app = QCoreApplication.instance()
    if not app:
        app = QApplication(sys.argv)
    msgbox = QMessageBox()
    msgbox.setIcon(QMessageBox.Icon.Critical)
    msgbox.setWindowTitle("Picard terminated unexpectedly")
    msgbox.setTextFormat(Qt.TextFormat.RichText)
    msgbox.setText(
        'An unexpected error has caused Picard to crash. '
        'Please report this issue on the <a href="https://tickets.metabrainz.org/projects/PICARD">MusicBrainz bug tracker</a>.')
    if logfile:
        logfile_url = QUrl.fromLocalFile(logfile)
        msgbox.setInformativeText(
            'A logfile has been written to <a href="{0}">{1}</a>.'
            .format(logfile_url.url(), logfile))
    msgbox.setDetailedText(trace)
    msgbox.setStandardButtons(QMessageBox.StandardButton.Close)
    msgbox.setDefaultButton(QMessageBox.StandardButton.Close)
    msgbox.exec_()
    app.quit()
Example #20
0
    def close_tribler(self):
        if not self.core_manager.shutting_down:
            self.show_loading_screen()

            self.gui_settings.setValue("pos", self.pos())
            self.gui_settings.setValue("size", self.size())

            if self.core_manager.use_existing_core:
                # Don't close the core that we are using
                QApplication.quit()

            self.core_manager.stop()
            self.core_manager.shutting_down = True
            self.downloads_page.stop_loading_downloads()
Example #21
0
    def closeEvent(self, event):
        """Close application.

        Parameters
        ----------
        event : QEvent
            Close event.
        """
        write_settings(geometry=self.saveGeometry(), state=self.saveState())
        if self.model.history:
            print("\nCommand History")
            print("===============")
            print("\n".join(self.model.history))
        QApplication.quit()
Example #22
0
    def closeEvent(self, event):
        if not any(copter.connected for copter in Client.clients.values()):
            event.accept()
            return

        reply = QMessageBox.question(
            self, "Confirm exit", "There are copters connected to the server. "
            "Are you sure you want to exit?", QMessageBox.No | QMessageBox.Yes,
            QMessageBox.No)

        if reply != QMessageBox.Yes:
            event.ignore()
        else:
            event.accept()
            QApplication.quit()
class Page(QWebEnginePage):
    def __init__(self, url):
        self.app = QApplication(sys.argv)
        QWebEnginePage.__init__(self)
        self.html = ''
        self.loadFinished.connect(self._on_load_finished)
        self.load(QUrl(url))
        self.app.exec_()

    def _on_load_finished(self):
        self.html = self.toHtml(self.Callable)

    def Callable(self, html_str):
        self.html = html_str
        self.app.quit()
Example #24
0
 def saveAndQuit(self):
     global navOptions
     navOptions = NavOptions(
         navOptions.groupOption,
         navOptions.groupRadius,
         navOptions.pixelSize,
         navOptions.numGroups,
         navOptions.ptsPerGroup,
         int(self.cbAcquire.isChecked()),
     )
     global pts
     global finalPts
     finalPts = pts
     self.parentWidget().parentWidget().writeSettings()
     QApplication.quit()
class Render(QWebEngineView):            # 子类Render继承父类QWebEngineView
    def __init__(self, url):
        self.html = ''
        self.app = QApplication(sys.argv)
        QWebEngineView.__init__(self)    # 子类构造函数继承父类,这种写法python2和3通用,还可以是super().__init__()
        self.loadFinished.connect(self._loadFinished)
        self.load(QUrl(url))
        self.app.exec()

    def _loadFinished(self):
        self.page().toHtml(self.callable)

    def callable(self, data):
        self.html = data
        self.app.quit()
Example #26
0
    def on_report_sent(self, response):
        if not response:
            return
        sent = response[u'sent']

        success_text = "Successfully sent the report! Thanks for your contribution."
        error_text = "Could not send the report! Please post this issue on GitHub."

        box = QMessageBox(self.window())
        box.setWindowTitle("Report Sent" if sent else "ERROR: Report Sending Failed")
        box.setText(success_text if sent else error_text)
        box.setStyleSheet("QPushButton { color: white; }")
        box.exec_()

        QApplication.quit()
Example #27
0
class TestFirstStartSummaryWidget(unittest.TestCase):
    def setUp(self):
        self.app = QApplication([])
        self.testSummaryWidget = FirstStartSummaryWidget()

    def tearDown(self):
        self.testSummaryWidget.deleteLater()
        self.app.deleteLater()
        self.app.quit()

    def test_can_always_go_back(self):
        self.assertTrue(self.testSummaryWidget.canGoBack())

    def test_can_never_proceed(self):
        self.assertFalse(self.testSummaryWidget.canProceed())
class Render(QWebEnginePage):
	def __init__(self, url):
		self.app = QApplication(sys.argv)
		QWebEnginePage.__init__(self)
		self.html = ''
		self.loadFinished.connect(self._loadFinished)
		self.load(QUrl(url))
		self.app.exec_()

	def _loadFinished(self, result):
		self.toHtml(self.Callable)
		print('Load finished')

	def Callable(self, html_str):
		self.html = html_str
		self.app.quit()
Example #29
0
class Render(QWebPage):  
  def __init__(self, url):  
    self.app = QApplication(sys.argv)  
    QWebPage.__init__(self)  
    self.loadFinished.connect(self._loadFinished)  
    self.mainFrame().load(QUrl(url))  

    #issue:QNetworkReplyImplPrivate::error: Internal problem, this method must only be called once.
    #self.mainFrame().wait_load()   #https://github.com/jeanphix/Ghost.py/issues/62

    self.app.exec_()  

  
  def _loadFinished(self, result):  
    self.frame = self.mainFrame()  
    self.app.quit()  
Example #30
0
class MenuApp(QObject):
    selected = pyqtSignal(str)
    dismissed = pyqtSignal()

    def __init__(self, title=None):
        super(MenuApp, self).__init__()

        self.app = QApplication(sys.argv)
        self.menu = Menu()
        self.frontend = Frontend(self.menu)

        self.menu.connect(self.frontend)

        self.menu.selected.connect(self.selected.emit)
        self.menu.dismissed.connect(self.dismissed.emit)

    def setup(self, *args, **kw):
        title = kw.pop('title', None)
        self.menu.setup(*args, **kw)
        self.restore(title=title)

    def minimize(self):
        self.frontend.view.hide()

    def restore(self, title=None):
        self.frontend.view.show(title=title)

    def exec_(self):
        return self.app.exec_()

    def quit(self):
        return self.app.quit()
Example #31
0
def main():
    # ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("AirMemo_appid")
    app = QApplication(sys.argv)
    serverName = 'rest_clock'
    socket = QLocalSocket()
    socket.connectToServer(serverName)

    # 如果连接成功,表明server已经存在,当前已有实例在运行
    if socket.waitForConnected(500):
        sys.exit(app.quit())

    # 没有实例运行,创建服务器
    localServer = QLocalServer()
    localServer.listen(serverName)
    try:
        set_app(app)
        tray = clock_tray()
        timeout_win = Ui_Timeout(tray)
        settings_win = Ui_Settings(tray)
        tran_win = TranSignalWidget()
        tran_win.showSignal.connect(timeout_win.show)
        win_dict = {"timeout_win": timeout_win, 'settings_win': settings_win}
        tray.set_menu(win_dict)
        set_aps(tran_win)
        timeout_win.show()
        TIME_MISSION.set_aps_mission()
        MYAPS.start()
        logging.debug('APS jobs {}'.format(MYAPS.get_jobs()))
        sys.exit(app.exec_())
    finally:
        localServer.close()
Example #32
0
class Page(QWebEnginePage):
    def __init__(self, url):
        self.app = QApplication(sys.argv)
        QWebEnginePage.__init__(self)
        self.html = ''
        self.loadFinished.connect(self._on_load_finished)
        self.load(QUrl(url))
        self.app.exec_()

    def _on_load_finished(self):
        # set the html attribute which will later be used by BS parsing
        self.html = self.toHtml(self.Callable)

    def Callable(self, html_str):
        self.html = html_str
        self.app.quit()
Example #33
0
    class Client(QWebEnginePage):
        def __init__(self, url):
            global app
            self.app = QApplication(sys.argv)
            QWebEnginePage.__init__(self)
            self.html = ""
            self.loadFinished.connect(self.on_load_finished)
            self.load(QUrl(url))
            self.app.exec_()

        def on_load_finished(self):
            self.html = self.toHtml(self.Callable)

        def Callable(self, data):
            self.html = data
            self.app.quit()
Example #34
0
        def __init__(self, url):
            self.html = None

            _app = QApplication([])
            self._page = QWebEnginePage()
            self._page.load(QUrl(url))
            self._page.loadFinished.connect(self._load_finished_handler)

            # Ожидание загрузки страницы и получения его содержимого
            # Этот цикл асинхронный код делает синхронным
            while self.html is None:
                _app.processEvents()

            _app.quit()

            self._page = None
Example #35
0
    def changeFileMenu(self):
        newFileAction = QAction(QIcon("new.png"), 'New File', self)
        newFileAction.setShortcut("Ctrl+N")
        newFileAction.setStatusTip("New file")
        newFileAction.triggered.connect(lambda: self.newFile.emit())

        openFileAction = QAction(QIcon("open.png"), 'Open File', self)
        openFileAction.setShortcut("Ctrl+O")
        openFileAction.setStatusTip("Open file")
        openFileAction.triggered.connect(lambda: self.openFile.emit())

        saveFileAction = QAction(QIcon("save.png"), 'Save File', self)
        saveFileAction.setShortcut("Ctrl+S")
        saveFileAction.setStatusTip("Save file")
        saveFileAction.triggered.connect(lambda: self.saveFile.emit())

        saveFileAsAction = QAction(QIcon("save.png"), 'Save File As', self)
        saveFileAsAction.setShortcut("Ctrl+Shift+S")
        saveFileAsAction.setStatusTip("Save file as")
        saveFileAsAction.triggered.connect(lambda: self.saveFileAs.emit())

        quitAction = QAction(QIcon("quit.png"), 'Quit', self)
        quitAction.setShortcut("Ctrl+Q")
        quitAction.setStatusTip("Quit EasyEdit")
        quitAction.triggered.connect(lambda: QApplication.quit())

        self.fileMenu = self.addMenu("File")
        self.fileMenu.addAction(newFileAction)
        self.fileMenu.addAction(openFileAction)
        self.fileMenu.addAction(saveFileAction)
        self.fileMenu.addAction(saveFileAsAction)
        self.fileMenu.addAction(quitAction)
Example #36
0
File: pysb.py Project: klasbj/pysb
def main():
    app = QApplication(sys.argv)

    io = InputHandler()

    # Set up signal handler to manage Ctrl+c
    signal.signal(signal.SIGINT, lambda *_: QApplication.quit())
    global timer
    timer = QTimer()
    timer.start(500)
    timer.timeout.connect(lambda: None) # let python run every 500ms

    desktop = app.desktop()
    sgeom = desktop.screenGeometry()

    global bars
    bars.append(dict())
    bars[0][Dock.top] = Bar(sgeom.left(), sgeom.top(), sgeom.width(), BAR_HEIGHT, flags=Qt.Widget | Qt.BypassWindowManagerHint)
    bars[0][Dock.bottom] = Bar(sgeom.left(), sgeom.bottom()-BAR_HEIGHT+1, sgeom.width(), BAR_HEIGHT, flags=Qt.Widget | Qt.BypassWindowManagerHint)

    print(bars, file=sys.stderr)

    for bar in bars[0].values():
        bar.show()
        #bar.lower()

    io.line.connect(handle_input)

    sys.exit(app.exec_())
Example #37
0
def main():
    import sys
    app = QApplication(sys.argv)
    translator = QTranslator()
    locale = QLocale.system().name()
    translateFile = os.path.join(BASEDIR, 'i18n\\translations', '{}.qm'.format(locale))
    if translator.load(translateFile):
        app.installTranslator(translator)

    # QApplication.setStyle(QStyleFactory.create('Fusion'))

    if boolean(conf.value('General/LargeFont')):
        font = QFont('Courier New', 14)
        app.setFont(font)

    serverName = 'Tafor'
    socket = QLocalSocket()
    socket.connectToServer(serverName)

    # 如果连接成功,表明server已经存在,当前已有实例在运行
    if socket.waitForConnected(500):
        return(app.quit())

    # 没有实例运行,创建服务器     
    localServer = QLocalServer()
    localServer.listen(serverName)

    try:          
        window = MainWindow()
        window.show()
        sys.exit(app.exec_())
    except Exception as e:
        logger.error(e, exc_info=True)
    finally:  
        localServer.close()
Example #38
0
def qt_schedule():
    import signal
    import sys
    from apscheduler.schedulers.qt import QtScheduler

    try:
        from PyQt5.QtWidgets import QApplication, QLabel
    except ImportError:
        try:
            from PyQt4.QtGui import QApplication, QLabel
        except ImportError:
            from PySide.QtGui import QApplication, QLabel

    def tick():
        label.setText('Tick! The time is: %s' % datetime.now())

    app = QApplication(sys.argv)

    # This enables processing of Ctrl+C keypresses
    signal.signal(signal.SIGINT, lambda *args: QApplication.quit())

    label = QLabel('The timer text will appear here in a moment!')
    label.setWindowTitle('QtScheduler example')
    label.setFixedSize(280, 50)
    label.show()

    scheduler = QtScheduler()
    scheduler.add_job(tick, 'interval', seconds=3)
    scheduler.start()

    # Execution will block here until the user closes the windows or Ctrl+C is pressed.
    app.exec_()
Example #39
0
    def keyPressEvent(self, event: QtGui.QKeyEvent):
        key = event.key()

        if key == QtCore.Qt.Key_Escape:
            sys.exit(QApplication.quit())
        else:
            self.view.keyPressEvent(event)
 def cont_response(self, i):
     # print(i.text())
     if i.text() == "&No":
         QApplication.quit()
     else:
         self.__moves = 0
         self.__winning_move = False
         self.__board = [['', '', '', ''], \
                         ['', '', '', ''], \
                         ['', '', '', ''], \
                         ['', '', '', '']]
         self.generate_game()
         while self.is_solvable() != True or self.repeats_present() == True:
             self.generate_game()
         self.__Mii_on = True
         self.__Mii.play()
    def quit_clicked(self, event):
        if not self.model.developing:
            reply = QMessageBox.question(self.view, 'Message',
                                     "Are you sure to quit?", QMessageBox.Yes |
                                     QMessageBox.No, QMessageBox.No)

            if reply == QMessageBox.Yes:
                self.logger.info('Closing')
                self.model.kill_observes()
                QApplication.quit()
            else:
                event.ignore()
        else:
            self.logger.info('Closing')
            self.model.remove_tables()
            QApplication.quit()
Example #42
0
def qt_schedule():
    import signal
    import sys
    from apscheduler.schedulers.qt import QtScheduler

    try:
        from PyQt5.QtWidgets import QApplication, QLabel
    except ImportError:
        try:
            from PyQt4.QtGui import QApplication, QLabel
        except ImportError:
            from PySide.QtGui import QApplication, QLabel

    def tick():
        label.setText('Tick! The time is: %s' % datetime.now())

    app = QApplication(sys.argv)

    # This enables processing of Ctrl+C keypresses
    signal.signal(signal.SIGINT, lambda *args: QApplication.quit())

    label = QLabel('The timer text will appear here in a moment!')
    label.setWindowTitle('QtScheduler example')
    label.setFixedSize(280, 50)
    label.show()

    scheduler = QtScheduler()
    scheduler.add_job(tick, 'interval', seconds=3)
    scheduler.start()

    # Execution will block here until the user closes the windows or Ctrl+C is pressed.
    app.exec_()
Example #43
0
    class Render(QWebEngineView):
        def __init__(self, html):
            self.html = None
            self.app = QApplication(sys.argv)
            QWebEngineView.__init__(self)
            self.loadFinished.connect(self._loadFinished)
            self.setHtml(html)
            while self.html is None:
                self.app.processEvents(QEventLoop.ExcludeUserInputEvents | QEventLoop.ExcludeSocketNotifiers | QEventLoop.WaitForMoreEvents)
            self.app.quit()

        def _callable(self, data):
            self.html = data

        def _loadFinished(self, result):
            self.page().toHtml(self._callable)
class Render(QWebEngineView):  # pylint: disable=too-few-public-methods
    # https://stackoverflow.com/questions/37754138/how-to-render-html-with-pyqt5s-qwebengineview
    def __init__(self, url):
        self.html = None
        self.app = QApplication(sys.argv)
        super().__init__()
        self.loadFinished.connect(self._load_finished)
        self.load(QUrl(url))
        self.app.exec_()

    def _callable(self, data):
        self.html = data
        self.app.quit()

    def _load_finished(self, result):  # pylint: disable=unused-argument
        self.page().toHtml(self._callable)
Example #45
0
class Client(QWebEnginePage):
    """docstring for Client"""
    def __init__(self, url):
        self.app = QApplication(sys.argv)
        QWebEnginePage.__init__(self)
        self.loadFinished.connect(self.on_page_load_finished)
        self.load(QUrl(url))
        self.app.exec_()

    def on_page_load_finished(self):
        self.html = self.toHtml(self.Callable)
        print("Load Finished")

    def Callable(self, html_str):
        self.html = html_str
        self.app.quit()
Example #46
0
def main():

    app = QApplication(sys.argv)
    channel_difference = ChannelDifference(["a1", "b1", "a2", "b2"])
    channel_difference.show()
    if channel_difference.exec_():
        channel_difference.get_selection()
    sys.exit(app.quit())
Example #47
0
def main():
    app = QApplication([])
    Screen = X4071("/dev/ttyUSB0")

    nArg = len(sys.argv)
    Command = sys.argv[1]

    if Command in ["mute"]:
        if not Screen.send_remote(Command):
            print("Command failed!")
        (_, Value) = Screen.ext_get_from_name(Command)
        MessageStr = "%s %s" % (Command, ONOFFCode[Value == 1])
    if Command in ["pip_preset_on", "pip_preset_on3"]:
        Input1 = InputExtCode[sys.argv[2]]
        Screen.ext_get_set_from_name("input", Input1, 0.5)
        Screen.ext_get_set_from_name("Audio input", 4, 0.5)
        Screen.ext_get_set_from_name("PIP right", 1, 0.5)
        Screen.ext_get_set_from_name("PIP bottom", 0, 0.5)
        Screen.ext_get_set_from_name("PIP input", InputExtCode[sys.argv[3]],
                                     0.5)
        if Command in ["pip_preset_on3"]:
            if Input1 == InputExtCode['HDMI1']:
                set_screen_size("1920x2160")
            Screen.ext_get_set_from_name("PIP PBP", 3, 1)
        else:
            if Input1 == InputExtCode['HDMI1']:
                set_screen_size("3840x2160")
            Screen.ext_get_set_from_name("PIP PBP", 1, 1)
        MessageStr = Command
    if Command in ["pip_preset_off"]:
        Input1 = InputExtCode[sys.argv[2]]
        if Input1 == InputExtCode['HDMI1']:
            set_screen_size("3840x2160")
        Screen.ext_get_set_from_name("PIP PBP", 0, 1.5)
        Screen.ext_get_set_from_name("input", Input1, 0.5)
        MessageStr = Command
    elif Command in ["vol+", "vol-"]:
        if not Screen.send_remote(Command):
            print("Command failed!")
        (_, Value) = Screen.ext_get_from_name("volume")
        MessageStr = "Volume %d%%" % Value

    messagebox = TimerMessageBox(MessageStr, 2)
    messagebox.exec_()
    app.quit()
    print("Done")
Example #48
0
class Client(QWebEnginePage):

	def __init__(self, url):
		self.app = QApplication(sys.argv)
		QWebEnginePage.__init__(self)
		self.loadFinished.connect(self.on_page_load)
		self.load(QUrl(url))
		self.app.exec_()

	#Quit application after load
	def on_page_load(self):
		self.html = self.toHtml(self.Callable)
		print('Load finished')

	def Callable(self, html_str):
		self.html = html_str
		self.app.quit()
Example #49
0
    class Render(QWebEngineView):
        def __init__(self, html):
            self.app = QApplication(sys.argv)
            QWebEngineView.__init__(self)
            self.loadFinished.connect(self._loadFinished)
            self.setHtml(html)
            self.app.exec_()

        def _loadFinished(self):
            # This is an async call, you need to wait for this
            # to be called before closing the app
            self.page().toHtml(self.callable)

        def callable(self, data):
            self.html = data
            # Data has been stored, it's safe to quit the app
            self.app.quit()
Example #50
0
def main():

    app = QApplication(sys.argv)
    user_input = UserInput("Question?")
    user_input.show()
    if user_input.exec_():
        user_input.get_selection()
    sys.exit(app.quit())
Example #51
0
def main():

    app = QApplication(sys.argv)
    display_text = DisplayText("Dispaly Text", "text")
    display_text.show()
    if display_text.exec_():
        pass
    sys.exit(app.quit())
Example #52
0
    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Escape:
            QApplication.quit()
        elif event.key() == Qt.Key_Q:
            QApplication.quit()
        elif event.key() == Qt.Key_F:
            self.toggleFullscreen()
        elif event.key() == Qt.Key_F1:
            #playList=QMediaPlaylist()
            #playList.setPlaybackMode(QMediaPlaylist.Loop)
            #playList.addMedia(QMediaContent(QUrl.fromLocalFile("f:/mp3/qh.mp3")))
            #player = QMediaPlayer()
            #player.setPlaylist(playList)
            #player.play()
            #print(player.metaData(QMediaMetaData.Author))
            #
            #m_device = QAudioDeviceInfo.defaultOutputDevice()
            #print(m_device)
            #self.xxx = QMediaPlayer()

            #self.xxx.setMedia(QMediaContent(QUrl.fromLocalFile("yinpin.wav")))
            #self.xxx.setMedia(QMediaContent(QUrl.fromUserInput("http://192.168.20.200/qh.mp3")))
            #self.xxx.play()
            #qq = QUrl()
            #qq.setPath("f:/mp3/")
            #qq = QUrl.fromUserInput("http://192.168.20.200/qh.mp3")

            #print(qq)
            #ss=QMediaContent(QUrl.fromLocalFile("yinpin.wav"))
            #sss=QMediaContent(QUrl.fromLocalFile(""))
            s = "这是一个正在开发的东西,慢慢来吧:\n"
            w = QWidget()
            s += "\n[色位深度]: %d" % w.depth()
            s += "\n[动画支持]: "
            s += "\n[bufferStatus]: "+str(self.homeAction.playObj.bufferStatus())
            s += "\n[position]: "+str(self.homeAction.playObj.position())
            s += "\n[state]: "+str(self.homeAction.playObj.state())
            s += "\n[filePath]: "+self.homeAction.openPath
            #s += "\n[xxxx]: "+str(ss)
            #s += "\n[sss]: "+str(sss)
            #s += "\n[qqq]: "+qq.scheme()
            #s += ["on", "off"][Colors.noAnimations]
            QMessageBox.information(None, "【F1】你想知道什么:", s)
        super(Ui_MainWindow, self).keyPressEvent(event)
Example #53
0
def sigint_handler(*args):
    """Handler for the SIGINT signal."""
    sys.stderr.write('\r')

    from settings import Settings
    s = Settings.get_instance()

    try:
        show_dialog = bool(s.get_setting("show_shutdown_dialog", True))
    except ValueError:
        s.set_setting("show_shutdown_dialog", True)
        show_dialog = True

    if show_dialog:
        if QMessageBox.question(None, 'Stopping', "Are you sure you want to quit?",
                                QMessageBox.Yes | QMessageBox.No,
                                QMessageBox.No) == QMessageBox.Yes:
            QApplication.quit()
    else:
        QApplication.quit()
Example #54
0
class Window(Driver, Gfx.Window):
    
    def __init__(self, size=(640, 480), title="qt.Graph", app=None):
        Gfx.Window.__init__(self, size, title)
        if app != None:
            self.app = app
        else:
            self.app = QApplication(sys.argv)

        self.pixmap = qt.QPixmap(size[0], size[1])
        self.pixmap.fill(qt.QColor(255,255,255))
        self.win = QLabel("", None)
        self.win.setPixmap(self.pixmap)        
        self.win.show()                       
        #self.win.setMinimumSize(size[0], size[1])
        #self.win.setMaximum(size[0], size[1])
        self.win.resize(size[0], size[1])
        if QT5:
            #self.lastClosedSignal = SIGNAL("lastWindowClosed()")
            self.app.lastWindowClosed.connect(self._qtEnd)
        else:
            QObject.connect(self.app, SIGNAL("lastWindowClosed()"), self._qtEnd)
        Driver.__init__(self, self.pixmap) 

    def refresh(self):
        self.win.setPixmap(self.pixmap)         
        self.win.update()

    def quit(self):
        self._qtEnd()
        self.win.close()
        self.win = None
        self.app.quit()

    def waitUntilClosed(self):
        self.refresh()  
        if QT3:
            self.app.exec_loop()
        else:          
            self.app.exec_()
    def closeEvent(self, event):
        """
        Gets called when the application wants to close the main window.
        We allow the plugins to cancel the close event in case they have
        unsaved state.

        Input:
            event[QEvent]: The event object
        """
        # closeEvent can get called multiple times, so this guard
        # just prevents going through all this again.
        if self._closed:
            return
        for name, plugin in self.tab_plugin._plugins.items():
            if not plugin.canClose():
                event.ignore()
                self._closed = False
                return
        self._cleanup()
        event.accept()
        QApplication.quit()
        self._closed = True
Example #56
0
def _die(message, exception=True):
    """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: Whether to print an exception with --debug.
    """
    from PyQt5.QtWidgets import QApplication, QMessageBox
    from PyQt5.QtCore import Qt
    if '--debug' in sys.argv and exception:
        print(file=sys.stderr)
        traceback.print_exc()
    app = QApplication(sys.argv)
    msgbox = QMessageBox(QMessageBox.Critical, "qutebrowser: Fatal error!",
                         message)
    msgbox.setTextFormat(Qt.RichText)
    msgbox.resize(msgbox.sizeHint())
    msgbox.exec_()
    app.quit()
    sys.exit(1)
Example #57
0
    def onQuit(self):
        # saving geometry BEFORE closing widgets, because state might be changed, when docks are closed
        self._saveState()
        self._saveGeometry()

        # request close all documents
        if not core.workspace().askToCloseAll():
            return

        core.aboutToTerminate.emit()
        self.hide()

        core.workspace().forceCloseAllDocuments()

        return QApplication.quit()
Example #58
0
 def on_error_occured(self, error):
     self.setMedia(QMediaContent())
     self.pause()
     if error == QMediaPlayer.FormatError or\
             error == QMediaPlayer.ServiceMissingError:
         m = QMessageBox(
             QMessageBox.Warning,
             u"错误提示",
             "第一次运行出现该错误可能是由于缺少解码器,"
             "请参考项目主页 https://github.com/cosven/FeelUOwn 。"
             "\n 也可能是网络已经断开,请检查您的网络连接",
             QMessageBox.Yes | QMessageBox.No)
         if m.exec() == QMessageBox.Yes:
             QApplication.quit()
         else:
             LOG.error(u'播放器出现error, 类型为' + str(error))
     if error == QMediaPlayer.NetworkError:
         if self._music_error_times >= self._music_error_maximum or \
                 self._current_index < 0 or\
                 self._current_index >= len(self._music_list):
             self._music_error_times = 0
             self._app_event_loop.call_later(
                 self._retry_latency, self.play_next)
             LOG.error(
                 u'播放器出现错误:网络连接失败,{}秒后尝试播放下一首'.
                 format(self._retry_latency))
         else:
             self._music_error_times += 1
             self._app_event_loop.call_later(
                 self._retry_latency,
                 self.play, self._music_list[self._current_index])
             LOG.error(u'播放器出现错误:网络连接失败, {}秒后重试'.
                       format(self._retry_latency))
     elif error == QMediaPlayer.ResourceError:
         LOG.error(u'播放器出现错误:缺少解码器')
     return
Example #59
0
    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Escape:
            QApplication.quit()
        elif event.key() == Qt.Key_F1:
            s = ""
            s += "\nAdapt: "
            s += ["on", "off"][Colors.noAdapt]
            s += "\nAdaption occured: "
            s += ["no", "yes"][Colors.adapted]
            w = QWidget()
            s += "\nColor bit depth: %d" % w.depth()
            s += "\nWanted FPS: %d" % Colors.fps
            s += "\nBenchmarked FPS: ";
            if Colors.benchmarkFps != -1:
                s += "%d" % Colors.benchmarkFps
            else:
                s += "not calculated"
            s += "\nAnimations: ";
            s += ["on", "off"][Colors.noAnimations]
            s += "\nBlending: ";
            s += ["on", "off"][Colors.useEightBitPalette]
            s += "\nTicker: ";
            s += ["on", "off"][Colors.noTicker]
            s += "\nPixmaps: ";
            s += ["off", "on"][Colors.usePixmaps]
            s += "\nRescale images on resize: ";
            s += ["on", "off"][Colors.noRescale]
            s += "\nTimer based updates: ";
            s += ["on", "off"][Colors.noTimerUpdate]
            s += "\nSeparate loop: ";
            s += ["no", "yes"][Colors.useLoop]
            s += "\nScreen sync: ";
            s += ["yes", "no"][Colors.noScreenSync]
            QMessageBox.information(None, "Current configuration", s)

        super(MainWindow, self).keyPressEvent(event)