示例#1
0
    def startApplication(self, first_start=True):
        self.m_server = QLocalServer()
        if self.m_server.listen(self.sock_file):
            if "--testnet" in sys.argv[1:]:
                print("Starting app... TESTNET MODE")
            else:
                print("Starting app...")
            self.appMain.run()
        else:
            if not first_start:
                print("Error listening the socket. App can't start!",
                      file=sys.stderr)
                QTimer.singleShot(250, self.quit)
                return

            # remove the listener path file and try to restart app one more time
            print("Error listening the socket. Try to restart application...",
                  file=sys.stderr)
            if sys.platform != 'win32':
                try:
                    os.unlink(self.sock_file)
                except Exception, err:
                    print(err, file=sys.stderr)

            QTimer.singleShot(250,
                              lambda: self.startApplication(first_start=False))
示例#2
0
def wait_for_signal(signal, timeout=10000):
    """Waits the given signal to be emitted, or breaks after a timeout

    This context manager wraps a method of using a nested event loop to
    wait for a signal, but additionally adds a timeout in case the signal
    was prematurely emitted (in which case we will never catch it) or if
    there is some kind of error and the signal is never emitted.

    This context manager used here is inspired by code from a blob by John
    Reaver, of which an archive can be found here:

    https://web.archive.org/web/20160126155634/http://jdreaver.com/
    posts/2014-07-03-waiting-for-signals-pyside-pyqt.html
    """
    loop = QEventLoop()

    # When the signal is caught, the loop will break
    signal.connect(loop.quit)

    # The content in the context manager will now be executed
    # The timeout doesn't start until this block is finished, so make sure
    # there is no blocking calls in the with block.
    yield

    if timeout is not None:  # Not False as possible 0ms timeout would be False
        QTimer.singleShot(timeout, loop.quit)
    loop.exec_()
示例#3
0
 def testFontInfo(self):
     w = MyWidget()
     w._app = self.app
     w._info = None
     QTimer.singleShot(300, w.show)
     self.app.exec_()
     self.assert_(w._info)
示例#4
0
文件: Window.py 项目: ra2003/xindex
 def initialize(self):
     self.setWindowTitle("{}".format(QApplication.applicationName()))
     self.state.updateDisplayFonts()
     self.filename = None
     if len(sys.argv) > 1:
         filename = sys.argv[1]
         if (filename.lower().endswith(EXTENSION)
                 and os.path.exists(filename)):
             self.filename = filename
     if self.filename is None:
         settings = QSettings()
         filename = settings.value(Gopt.Key.MainForm_Filename,
                                   Gopt.Default.MainForm_Filename)
         if (filename and filename.lower().endswith(EXTENSION)
                 and os.path.exists(filename)):
             self.filename = filename
     if self.filename is None:
         say("Click File→New or File→Open to create or open an index")
         self.updateWorkTime()
         self.state.updateUi()
     else:
         say("Opening {}".format(os.path.normpath(self.filename)))
         QTimer.singleShot(5, self.openXix)
     self.updateRecentFilesMenu()
     self.updateToolTips()
     Lib.maybe_register_filetype(self.debug)
示例#5
0
    def speak_ai(self, word):
        # AIのトークを表示
        # ディレイを使ってテンポを整える
        def wrapper():
            self.ai_txtarea.append(word)

        QTimer.singleShot(TALK_DELAY, wrapper)
示例#6
0
文件: bug_750.py 项目: Hasimir/PySide
 def testFontInfo(self):
     w = MyWidget()
     w._app = self.app
     w._info = None
     QTimer.singleShot(300, w.show)
     self.app.exec_()
     self.assert_(w._info)
示例#7
0
  def __init__(self):

    global gEnableResourceMonitoring
    self.enableResourceMonitoring  = gEnableResourceMonitoring
    self.bar = hiero.ui.mainWindow().statusBar()

    self.updateMonitorIntervalMS = gUpdateIntervalMS # The monitor update time in milliseconds.
    self.timer = QTimer()
    self.timer.setSingleShot(False)
    self.timer.timeout.connect(self.updateStatusBar)

    self.currentDiskIOBytes = psutil.disk_io_counters().read_bytes
    self.currentNetworkBytesReceived = psutil.net_io_counters().bytes_recv

    # This observes the current pid (the App process id) via psutil, and reports back
    if self.enableResourceMonitoring:
      self.processHelper = PSUtilProcessWrapper()

    # The frameServer instance
    self.frameServerInstance = nukestudio.frameServer

    # Initialise the Status Bar
    self.setupUI()

    # We haven't started monitoring at this point
    self.isMonitoring = False

    # Begin monitoring after a few secs to give frame server time to start up properly
    QTimer.singleShot(gInitialDelayMS, self.startMonitoring)
示例#8
0
文件: zne.py 项目: z25/pyZNodeEditor
    def __init__(self, parent):
        super(QNEMainWindow, self).__init__(parent)

        self.logger = logging.getLogger("zne")
        self.logger.setLevel(logging.DEBUG)

        self.setMinimumSize(560,360)
        self.setWindowTitle("ZOCP Node Editor")
        self.setWindowIcon(QIcon('assets/icon.png'))

        self.scene = QGraphicsScene(self)
        self.view = QGraphicsView(self)
        self.view.setScene(self.scene)
        self.setCentralWidget(self.view)

        self.nodesEditor = QNodesEditor(self, self.scene, self.view)

        self.nodesEditor.onAddConnection = self.onAddConnection
        self.nodesEditor.onRemoveConnection = self.onRemoveConnection
        self.nodesEditor.onBlockMoved = self.onBlockMoved

        self.scale = 1
        self.installActions()

        self.initZOCP()

        self.nodes = {}
        self.pendingSubscribers = {}

        QTimer.singleShot(250, lambda: self.scene.invalidate())
示例#9
0
 def error(self, error):
     if error == QNetworkSession.UnknownSessionError:
         msgBox = QMessageBox(self.parent())
         msgBox.setText('This application requires network access to function.')
         msgBox.setInformativeText('Press Cancel to quit the application.')
         msgBox.setStandardButtons(QMessageBox.Retry | QMessageBox.Cancel)
         msgBox.setIcon(QMessageBox.Information)
         msgBox.setDefaultButton(QMessageBox.Retry)
         ret = msgBox.exec_()
         if ret == QMessageBox.Retry:
             QTimer.singleShot(0, self.session.open)
         elif ret == QMessageBox.Cancel:
             self.close()
     elif error == QNetworkSession.SessionAbortedError:
         msgBox = QMessageBox(self.parent())
         msgBox.setText('Out of range of network')
         msgBox.setInformativeText('Move back into range and press Retry, or press Cancel to quit the application')
         msgBox.setStandardButtons(QMessageBox.Retry | QMessageBox.Cancel)
         msgBox.setIcon(QMessageBox.Information)
         msgBox.setDefaultButton(QMessageBox.Retry)
         ret = msgBox.exec_()
         if ret == QMessageBox.Retry:
             QTimer.singleShot(0, self.session.open)
         elif ret == QMessageBox.Cancel:
             self.close()
示例#10
0
    def __init__(self, parent):
        super(QNEMainWindow, self).__init__(parent)

        self.logger = logging.getLogger("zne")
        self.logger.setLevel(logging.DEBUG)

        self.setMinimumSize(560, 360)
        self.setWindowTitle("ZOCP Node Editor")
        self.setWindowIcon(QIcon('assets/icon.png'))

        self.scene = QGraphicsScene(self)
        self.view = QGraphicsView(self)
        self.view.setScene(self.scene)
        self.setCentralWidget(self.view)

        self.nodesEditor = QNodesEditor(self, self.scene, self.view)

        self.nodesEditor.onAddConnection = self.onAddConnection
        self.nodesEditor.onRemoveConnection = self.onRemoveConnection
        self.nodesEditor.onBlockMoved = self.onBlockMoved

        self.scale = 1
        self.installActions()

        self.initZOCP()

        self.nodes = {}
        self.pendingSubscribers = {}

        QTimer.singleShot(250, lambda: self.scene.invalidate())
示例#11
0
文件: wc.py 项目: Jonney/Khweeteur
def wc(stream_update=None, object_transfer=None):
    """
    Connect to the woodchuck server and initialize any state.

    stream_update is a function that is passed two arguments: an
    account identifier and the name of the stream to update (e.g.,
    'HomeTimeline').

    object_transfer is a function that is passed three arguments: an
    account identifier, a name of the stream and the post to transfer.

    If channel_update and episode_download are None, then Woodchuck
    upcalls will be disabled.
    """
    global _w
    if _w is not None:
        return _w

    _w = mywoodchuck(stream_update, object_transfer)

    if not _w.available():
        logging.info(
            "Woodchuck support disabled: unable to contact Woodchuck server.")
        print "Woodchuck support disabled: unable to contact Woodchuck server."
        return

    logging.info("Woodchuck appears to be available.")

    if stream_update is not None:
        QTimer.singleShot(10 * 1000, _w.synchronize_config)

    return _w
示例#12
0
 def reverseCalculationWorker(self, seconds_before_start):
     self.message.sendMessage('second_' + str(seconds_before_start))
     if seconds_before_start == 0:
         self.timer.start()
         self.animation_timer.start()
         QTimer.singleShot(1000, self.message.noMessage)
     self.repaint()
示例#13
0
 def gifs2lossy(self):
     emoji_dict = {
         Emoji(emoji).filename: Emoji(emoji)
         for emoji in self.files_in_folder(self.project_folder)
         if Emoji(emoji)
     }
     for index, item in enumerate(emoji_dict.keys()):
         if not emoji_dict[item].has_lossy or settings.overwrite_gifs:
             print(emoji_dict[item].name,
                   'lossy file missing, creating one')
             # Get the proper lossy value for the gifsicle
             if '136' in emoji_dict[item].resolution:
                 lossy_factor = self.lossy_factor['136']
             elif '280' in emoji_dict[item].resolution:
                 lossy_factor = self.lossy_factor['280']
             GifSicle(emoji_dict[item],
                      lossy_factor,
                      self.color_map,
                      to_lossy=True)
             self.conversion2.emit(index + 1, len(emoji_dict) - 1)
         else:
             print(
                 'Lossy file for {} already exists, skipping lossy creation'
                 .format(emoji_dict[item].name))
     QTimer.singleShot(1, self.conversion2_done)
示例#14
0
文件: python.py 项目: wiz21b/koi
def make_screenshot():
    global window


    from PySide.QtCore import QTimer
    from PySide.QtGui import QPixmap

    def screenshot_callback():
        screenshot = QPixmap.grabWidget(window)
        screenshot = QPixmap.grabWindow(QApplication.desktop().winId())
        screenshot.save("screenshot-main.png")

    def screenshot_callback2():
        window._qaction_triggered_FinancialKPIPanel()
        screenshot = QPixmap.grabWidget(window)
        screenshot.save("screenshot-financial.png")

    def screenshot_callback3a():
        window.show_presence_overview()
        window.presence_overview_widget.table_view.setCurrentIndex( window.presence_overview_widget.table_view.model().index(1,1))
        window.presence_overview_widget.table_view.setCurrentIndex( window.presence_overview_widget.table_view.model().index(4,4))

    def screenshot_callback3():
        window.show_presence_overview()

        screenshot = QPixmap.grabWidget(window)
        screenshot = QPixmap.grabWindow(QApplication.desktop().winId())
        screenshot.save("screenshot-presence.png")

    QTimer.singleShot(1000, screenshot_callback)
    QTimer.singleShot(3000, screenshot_callback2)
    QTimer.singleShot(4000, screenshot_callback2)
    QTimer.singleShot(6000, screenshot_callback3a)
    QTimer.singleShot(8000, screenshot_callback3)
    mainlog.info("Screenshots done")
示例#15
0
    def __init__(self):

        global gEnableResourceMonitoring
        self.enableResourceMonitoring = gEnableResourceMonitoring
        self.bar = hiero.ui.mainWindow().statusBar()

        self.updateMonitorIntervalMS = gUpdateIntervalMS  # The monitor update time in milliseconds.
        self.timer = QTimer()
        self.timer.setSingleShot(False)
        self.timer.timeout.connect(self.updateStatusBar)

        self.currentDiskIOBytes = psutil.disk_io_counters().read_bytes
        self.currentNetworkBytesReceived = psutil.net_io_counters().bytes_recv

        # This observes the current pid (the App process id) via psutil, and reports back
        if self.enableResourceMonitoring:
            self.processHelper = PSUtilProcessWrapper()

        # The frameServer instance
        self.frameServerInstance = nukestudio.frameServer

        # Initialise the Status Bar
        self.setupUI()

        # We haven't started monitoring at this point
        self.isMonitoring = False

        # Begin monitoring after a few secs to give frame server time to start up properly
        QTimer.singleShot(gInitialDelayMS, self.startMonitoring)
示例#16
0
def wait_for_signal(signal, timeout=10000):
    """Waits the given signal to be emitted, or breaks after a timeout

    This context manager wraps a method of using a nested event loop to
    wait for a signal, but additionally adds a timeout in case the signal
    was prematurely emitted (in which case we will never catch it) or if
    there is some kind of error and the signal is never emitted.

    This context manager used here is inspired by code from a blob by John
    Reaver, of which an archive can be found here:

    https://web.archive.org/web/20160126155634/http://jdreaver.com/
    posts/2014-07-03-waiting-for-signals-pyside-pyqt.html
    """
    loop = QEventLoop()

    # When the signal is caught, the loop will break
    signal.connect(loop.quit)

    # The content in the context manager will now be executed
    # The timeout doesn't start until this block is finished, so make sure
    # there is no blocking calls in the with block.
    yield

    if timeout is not None:  # Not False as possible 0ms timeout would be False
        QTimer.singleShot(timeout, loop.quit)
    loop.exec_()
 def periodic_update(self):
     self.current_value += 5
     if self.current_value >= self.target_value:
         self.current_value = self.target_value
     else:
         QTimer.singleShot(200, self.periodic_update)
     self.bar.setValue(self.current_value)
示例#18
0
文件: wc.py 项目: khertan/Khweeteur
def wc(stream_update=None, object_transfer=None):
    """
    Connect to the woodchuck server and initialize any state.

    stream_update is a function that is passed two arguments: an
    account identifier and the name of the stream to update (e.g.,
    'HomeTimeline').

    object_transfer is a function that is passed three arguments: an
    account identifier, a name of the stream and the post to transfer.

    If channel_update and episode_download are None, then Woodchuck
    upcalls will be disabled.
    """
    global _w
    if _w is not None:
        return _w

    _w = mywoodchuck(stream_update, object_transfer)

    if not _w.available():
        logging.info("Woodchuck support disabled: unable to contact Woodchuck server.")
        print "Woodchuck support disabled: unable to contact Woodchuck server."
        return _w

    logging.info("Woodchuck appears to be available.")

    if stream_update is not None:
        QTimer.singleShot(10 * 1000, _w.synchronize_config)

    return _w
示例#19
0
文件: main.py 项目: jlehtoma/MaeBird
    def __init__(self, parent=None):
        super(MaeBird, self).__init__(parent)
        
        self.models = ModelFactory()

        self.table = None
        self.languages = {'perimary': 'Fin', 'secondary': 'Eng', 
                         'tertiary': 'Swe'}
        
        self.dbtype = __DB__
        self.dbfile = None
        self.db = None
        
        self.matches = []
        self.currentsearchitem = 0
        
        self.fullscreen = False
        self.setupUi(self)
        
        self.setWindowTitle(__APPNAME__ + ' ' + __VERSION__)
        
        # TODO: loading settings should be moved to a separate method
        settings = QSettings()
        
        # Set up logging
        loggingdir = settings.value("Logging/loggingDir")
        if loggingdir is None:
            loggingdir = __USER_DATA_DIR__
        self.logger = Logger('root', loggingdir=loggingdir)
        if settings.value("Settings/debugging"):
            self.logger.debugging = int(settings.value("Settings/debugging"))
            self.logger.debug('Logging initialized')
        
        # Try to load previous session
        if settings.value("Settings/saveSettings"):
            self.saveSettings = int(settings.value("Settings/saveSettings"))
        else:
            self.saveSettings = 1
                      
        if self.saveSettings:
            QTimer.singleShot(0, self.load_initial_data)
            #QTimer.singleShot(0, self.load_initial_model)
        
        self.header = self.tableView.horizontalHeader()
        self.header.sectionDoubleClicked.connect(self.sort_table)
        
        self.search.textEdited.connect(self.update_ui)
        self.search.setFocus()
        self.searchNextButton.clicked.connect(self.update_ui)
        self.searchPrevButton.clicked.connect(self.update_ui)
        
        self.tableView.pressed.connect(self.update_ui)
        
        self.tableView.doubleClicked.connect(
                    lambda: self.handle_observation(ObservationDialog.SHOW))
        self.addButton.clicked.connect(
                    lambda: self.handle_observation(ObservationDialog.ADD))
        self.deleteButton.clicked.connect(
                    lambda: self.handle_observation(ObservationDialog.DELETE))
示例#20
0
def app_exec(timeout=1000):
    debugon()

    from PySide.QtCore import QTimer
    from Qt5.QtWidgets import QApplication
    app = QApplication(sys.argv)
    QTimer.singleShot(timeout, app.quit)
    return app.exec_()
示例#21
0
 def handbrake(self):
     emoji_list = [
         Emoji(emoji) for emoji in self.files_in_folder(self.project_folder)
         if Emoji(emoji)
     ]
     Handbrake(emoji_list[0])
     self.conversion4.emit(1, 1)
     QTimer.singleShot(1, self.conversion4_done)
示例#22
0
 def testSetPenWithPenStyleEnum(self):
     '''Calls QPainter.setPen with both enum and integer. Bug #511.'''
     w = Painting()
     w.show()
     QTimer.singleShot(1000, self.app.quit)
     self.app.exec_()
     self.assertEqual(w.penFromEnum.style(), Qt.NoPen)
     self.assertEqual(w.penFromInteger.style(), Qt.SolidLine)
示例#23
0
 def connectToExistingApp(self):
     if len(sys.argv)>1 and sys.argv[1] is not None:
         self.m_socket.write(sys.argv[1])
         self.m_socket.bytesWritten.connect(self.quit)
     else:
         QMessageBox.warning(None, self.tr("Already running"), self.tr("The program is already running."))
         # Quit application in 250 ms
         QTimer.singleShot(250, self.quit)
示例#24
0
文件: qt_gui.py 项目: gonicus/clacks
    def discover(self):
        mwin = WaitForServiceProvider()
        mwin.show()

        QTimer.singleShot(1000, self.zdiscover)
        self.app.exec_()

        return self.url
示例#25
0
def onReadNodeCreated():
    """ Callback when a Read node is created.  Note that the knob values
  don't seem to be set when this callback occurs.  Defer the check with
  a QTimer, which will cause the views check to be done when the Qt event
  loop next sends events.
  """
    read = nuke.thisNode()
    QTimer.singleShot(0, lambda: checkReadNodeViews(read))
示例#26
0
 def handleExitAction(self, show_confirmation=False):
     reply = QMessageBox.No
     if show_confirmation:
         reply=QMessageBox.question(self,'Exit %s?' % APP_NAME,
                 "Are you sure to exit %s?" % APP_NAME, QMessageBox.Yes,QMessageBox.No)
     if not show_confirmation or reply==QMessageBox.Yes:
         self.trayIcon.hide()
         QTimer.singleShot(250, self.app.quit)
示例#27
0
 def testSetPenWithPenStyleEnum(self):
     """Calls QPainter.setPen with both enum and integer. Bug #511."""
     w = Painting()
     w.show()
     QTimer.singleShot(1000, self.app.quit)
     self.app.exec_()
     self.assertEqual(w.penFromEnum.style(), Qt.NoPen)
     self.assertEqual(w.penFromInteger.style(), Qt.SolidLine)
示例#28
0
 def onLoadFinished(self, result):
     global functionID
     self.assertEqual(self._functionID, functionID)
     if self._functionID == (len(FUNCTIONS_LIST) - 1):
         QTimer.singleShot(300, self.app.quit)
     else:
         #new test
         self._functionID += 1
         self.createInstance()
示例#29
0
文件: bug_959.py 项目: Hasimir/PySide
 def onLoadFinished(self, result):
     global functionID
     self.assertEqual(self._functionID, functionID)
     if self._functionID == (len(FUNCTIONS_LIST) - 1):
         QTimer.singleShot(300, self.app.quit)
     else:
         #new test
         self._functionID += 1
         self.createInstance()
示例#30
0
        def setUp(self, timeout=100):
            '''Setups this Application.

            timeout - timeout in milisseconds'''
            global _timed_instance
            if _timed_instance is None:
                _timed_instance = QApplication([])

            self.app = _timed_instance
            QTimer.singleShot(timeout, self.app.quit)
示例#31
0
 def loop(self, emoji, lossy_factor, color_map):
     self.tp = TasksPool()
     # Make consecutive damaged files
     self.add(input_file=emoji.gif_path,
              lossy_factor=lossy_factor,
              color_map=color_map,
              delay=emoji.delay,
              output_file=emoji.damaged_path)
     self.run()
     QTimer.singleShot(0, self.loop_done)
示例#32
0
 def del_(self):
     """Explicitly called destructor.
     Removes widget from the qpart
     """
     self._closeIfNotUpdatedTimer.stop()
     self._qpart.removeEventFilter(self)
     self._qpart.cursorPositionChanged.disconnect(self._onCursorPositionChanged)
     
     # if object is deleted synchronously, Qt crashes after it on events handling
     QTimer.singleShot(0, lambda: self.setParent(None))
示例#33
0
 def _check_download():
     if entry.stop_download:
         handler.remove()
         entry.remove_file()
     self._update_pause_state(entry, handler)
     if handler.finished or entry.stop_download:
         self.downloaded.emit(entry, tick)
     else:
         QTimer.singleShot(100, _check_download)
     self.download_progress.emit(entry, handler.percent)
        def setUp(self, timeout=100):
            '''Setups this Application.

            timeout - timeout in milisseconds'''
            global _timed_instance
            if _timed_instance is None:
                _timed_instance = QApplication([])

            self.app = _timed_instance
            QTimer.singleShot(timeout, self.app.quit)
示例#35
0
 def __init__(self, state, parent=None):
     super().__init__(parent)
     self.setContextMenuPolicy(Qt.ActionsContextMenu)
     self.state = state
     self.clear()
     self.methodForKeyPress = self.mapMethodToKeyPress()
     self.createWidgets()
     self.layoutWidgets()
     self.createConnections()
     self.setFocusPolicy(Qt.WheelFocus)
     QTimer.singleShot(250, lambda: self._setBackgroundColor(False))
示例#36
0
文件: bug_959.py 项目: PySide/PySide
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)
示例#37
0
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)
示例#38
0
    def test_qt():
        a = QApplication(sys.argv)
        w = QWebView()
        w.show()

        g = GoogleTtsPlayer('qt')
        g.setParentWidget(w)
        QTimer.singleShot(1000, lambda: g.speak(q, language='ja'))

        ret = a.exec_()
        print "leave: ret = %i" % ret
示例#39
0
    def generateEvent(self):
        o = QTest.touchEvent(self)
        o.press(0, QPoint(10, 10))
        o.commit()
        del o

        QTest.touchEvent(self).press(0, QPoint(10, 10))
        QTest.touchEvent(self).stationary(0).press(1, QPoint(40, 10))
        QTest.touchEvent(self).move(0, QPoint(12, 12)).move(1, QPoint(45, 5))
        QTest.touchEvent(self).release(0, QPoint(12, 12)).release(1, QPoint(45, 5))

        QTimer.singleShot(200, self.deleteLater)
示例#40
0
文件: guiMain.py 项目: Xifax/suzu_ei
    def hideQuizAndWaitForNext(self):
        self.stats.postQuizEnded()

        self.status.hide()
        self.info.hide()
        self.allInfo.hide()
        self.resetButtonsActions()

        self.setWindowOpacity(1)
        self.fade()
        QTimer.singleShot(1000, self.hide)
        self.waitUntilNextTimeslot()
    def test_setParentItem(self):
        global qgraphics_item_painted

        scene = QGraphicsScene()
        scene.addText("test")
        view = QGraphicsView(scene)

        rect = self.createRoundRect(scene)
        view.show()
        QTimer.singleShot(1000, self.quit_app)
        self.app.exec_()
        self.assert_(qgraphics_item_painted)
示例#42
0
    def testSignalStarted(self):
        #QThread.started() (signal)
        obj = Dummy()
        QObject.connect(obj, SIGNAL('started()'), self.cb)
        obj.start()

        self._thread = obj
        QTimer.singleShot(1000, self.abort_application)
        self.app.exec_()

        self.assertEqual(obj.qobj.thread(), obj) # test QObject.thread() method
        self.assert_(self.called)
示例#43
0
    def retry(self, f, *args, **kwargs):
        """Start daemon and call the function after a short delay."""
        self.start_daemon()
        if hasattr(self, '_iface'):
            del self._iface

        def cb(self, args, kwargs):
            def doit():
                return f(*args, **kwargs)
            return doit
        logging.debug("Started daemon.  Retrying call in 5 seconds.")
        QTimer.singleShot(5 * 1000, cb(self, args, kwargs))
    def testIt(self):

        self.textEdit = QTextEdit()
        self.textEdit.show()

        interface = Foo()
        self.textEdit.document().documentLayout().registerHandler(QAbstractTextDocumentLayoutTest.objectType, interface)

        QTimer.singleShot(0, self.foo)
        self.app.exec_()

        self.assertTrue(Foo.called)
    def testIt(self):

        self.textEdit = QTextEdit()
        self.textEdit.show()

        interface = Foo()
        self.textEdit.document().documentLayout().registerHandler(QAbstractTextDocumentLayoutTest.objectType, interface)

        QTimer.singleShot(0, self.foo)
        self.app.exec_()

        self.assertTrue(Foo.called)
    def test_setParentItem(self):
        global qgraphics_item_painted

        scene = QGraphicsScene()
        scene.addText("test")
        view = QGraphicsView(scene)

        rect = self.createRoundRect(scene)
        view.show()
        QTimer.singleShot(1000, self.quit_app)
        self.app.exec_()
        self.assert_(qgraphics_item_painted)
示例#47
0
文件: guiMain.py 项目: Xifax/suzu_ei
 def hideQuizAndWaitForNext(self):
     self.stats.postQuizEnded()
     
     self.status.hide()
     self.info.hide()
     self.allInfo.hide()
     self.resetButtonsActions()
     
     self.setWindowOpacity(1)
     self.fade()
     QTimer.singleShot(1000, self.hide)
     self.waitUntilNextTimeslot()
示例#48
0
文件: game.py 项目: nvbn/findZbomb
 def redraw(self):
     if self.old_cp != self.map.cur_position:
         #self.draw_map()
         self.old_cp = self.map.cur_position
         if hasattr(self, 'robot'):
             self.rootObject().set_map_count(self.robot.moves)
             self.rootObject().robot_to_active_pos(*self.robot.position)
     if self.exception:
         if hasattr(self, 'robot'):
             self.robot.stop = True
         self.rootObject().show_exception(unicode(self.exception))
         self.exception = None
     QTimer.singleShot(300, self.redraw)
示例#49
0
    def testSignalFinished(self):
        #QThread.finished() (signal)
        obj = Dummy()
        QObject.connect(obj, SIGNAL('finished()'), self.cb)
        mutex.lock()
        obj.start()
        mutex.unlock()

        self._thread = obj
        QTimer.singleShot(1000, self.abort_application)
        self.app.exec_()

        self.assert_(self.called)
示例#50
0
    def testSignalStarted(self):
        #QThread.started() (signal)
        obj = Dummy()
        QObject.connect(obj, SIGNAL('started()'), self.cb)
        obj.start()

        self._thread = obj
        QTimer.singleShot(1000, self.abort_application)
        self.app.exec_()

        self.assertEqual(obj.qobj.thread(),
                         obj)  # test QObject.thread() method
        self.assert_(self.called)
示例#51
0
 def redraw(self):
     if self.old_cp != self.map.cur_position:
         #self.draw_map()
         self.old_cp = self.map.cur_position
         if hasattr(self, 'robot'):
             self.rootObject().set_map_count(self.robot.moves)
             self.rootObject().robot_to_active_pos(*self.robot.position)
     if self.exception:
         if hasattr(self, 'robot'):
             self.robot.stop = True
         self.rootObject().show_exception(unicode(self.exception))
         self.exception = None
     QTimer.singleShot(300, self.redraw)
示例#52
0
    def testSignalFinished(self):
        #QThread.finished() (signal)
        obj = Dummy()
        QObject.connect(obj, SIGNAL('finished()'), self.cb)
        mutex.lock()
        obj.start()
        mutex.unlock()

        self._thread = obj
        QTimer.singleShot(1000, self.abort_application)
        self.app.exec_()

        self.assert_(self.called)
示例#53
0
	def changeState(self,newState):
		self._d("Entering critical area")
		self.waiting+=1
		self.lock.acquire()
		self.waiting-=1
		self._d("inside critical area")
		
		if self.state == 0:
			if newState == 2:
				self.state = 1
				self.do_login();
				
		elif self.state == 1:
			#raise Exception("mutex violated! I SHOULDN'T BE HERE !!!")
			if newState == 0:
				self.retry = False
			elif newState == 2:
				self.retry = True
			elif newState == 3: #failed
				if self.retry:
					
					
					if self.connTries >= 3:
						self._d("%i or more failed connections. Will try again in 30 seconds" % self.connTries)
						QTimer.singleShot(30000,self.retryLogin)
						self.connTries-=1
						
					else:	
						self.do_login()
						self.connTries+=1
				else:
					self.connTries = 0
					self.state = 0
					self.retry = True
					
			elif newState == 4:#connected
				self.connTries = 0
				self.retry = True
				self.state = 2
		elif self.state == 2:
			if newState == 2:
				self.disconnect()
				self.state = 1
				self.do_login()
			elif newState == 0:
				self.disconnect()
				self.state = 0
		
		
		self._d("Releasing lock")
		self.lock.release()
示例#54
0
    def testPlugin(self):
        view = QWebView()
        fac = PluginFactory()
        view.page().setPluginFactory(fac)
        QWebSettings.globalSettings().setAttribute(QWebSettings.PluginsEnabled, True)

        view.load(QUrl(os.path.join(os.path.abspath(os.path.dirname(__file__)), "qmlplugin", "index.html")))

        view.resize(840, 600)
        view.show()

        QTimer.singleShot(500, self.app.quit)

        self.app.exec_()
示例#55
0
    def save_data_cache(self, lazily=True):
        filename = self.getCacheFolder() + '-data-cache'

        def closure(data_cache):
            def doit():
                with open(filename, 'wb') as fhandle:
                    pickle.dump(data_cache, fhandle,
                                pickle.HIGHEST_PROTOCOL)
            return doit

        func = closure(self.data_cache)
        if lazily:
            QTimer.singleShot(0, func)
        else:
            func()
示例#56
0
    def testBasic(self):
        '''QStateMachine.configuration converting QSet to python set'''
        machine = QStateMachine()
        s1 = QState()
        machine.addState(s1)
        machine.setInitialState(s1)
        machine.start()

        QTimer.singleShot(100, self.app.quit)
        self.app.exec_()

        configuration = machine.configuration()

        self.assert_(isinstance(configuration, set))
        self.assert_(s1 in configuration)
示例#57
0
 def _check_download():
     if (
         entry.subtitle.wait_for_file and
         not entry.subtitle.downloaded
         and os.path.exists(entry.path)
     ):
         self.subtitles.download(entry.subtitle)
     if entry.stop_download:
         handler.remove()
         entry.remove_file()
     self._update_pause_state(entry, handler)
     if handler.finished or entry.stop_download:
         self.downloaded.emit(entry, tick)
     else:
         QTimer.singleShot(100, _check_download)
     self.download_progress.emit(entry, handler.percent)
示例#58
0
文件: guiMain.py 项目: Xifax/suzu
    def timeIsOut(self):
        self.stats.musingsStopped()
        self.stats.postQuizStarted()
        
        QTimer.singleShot(50, self.hideButtonsQuiz)     #NB: slight artificial lag to prevent recursive repaint crush (when mouse is suddenly over repainted button)
        self.getReadyPostLayout()
        
        self.srs.answeredWrong()
        self.stats.quizAnsweredWrong()

        self.checkTranslationSize(self.srs.getCurrentSentenceTranslation())
        
        self.status.achievements.wrongAnswer()
        self.showSessionMessage(u'<font color=tomato>Timeout! Should be: ' + self.srs.getCorrectAnswer() + '</font>\t|\tNext quiz: ' + self.srs.getNextQuizTime()
                                + '\t|\t<font color=' + self.srs.getLeitnerGradeAndColor()['color'] +  '>Grade: ' + self.srs.getLeitnerGradeAndColor()['grade'] 
                                + ' (' + self.srs.getLeitnerGradeAndColor()['name'] + ')<font>')    
        self.refocusQuiz()