示例#1
0
    class _SkWindowObject(object):
        def __init__(self, q, wid=0, pyobj=None):
            if not pyobj:
                pyobj = SkWindowPyObject(wid)
            self.obj = pyobj
            self.valid = self.obj.valid

            # Refresh timer
            self.refreshTimer = QTimer(q)
            self.refreshTimer.setInterval(200)
            self.refreshTimer.timeout.connect(q.refresh)

            self.refreshCount = 0  # int

        def reset(self):
            """Reset cached fields"""
            self.valid = False
            if hasattr(self, 'geometry'):
                del self.geometry
            if hasattr(self, 'visible'):
                del self.visible
            if hasattr(self, 'windowState'):
                del self.windowState
            if hasattr(self, 'contentSize'):
                del self.contentSize

        def updateWindowState(self):
            self.windowState = (
                Qt.WindowFullScreen if self.obj.fullscreen else
                Qt.WindowMinimized if self.obj.minimized else Qt.WindowNoState)
示例#2
0
class MainWindow(QDeclarativeView):

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setWindowTitle("Title on Main Window")
        # Renders 'view.qml'
        self.setSource(QUrl.fromLocalFile('view.qml'))
        # QML resizes to main window
        self.setResizeMode(QDeclarativeView.SizeRootObjectToView)

        con = Console()
        rotatevalue = RotateValue()

        context = self.rootContext()
        context.setContextProperty('con', con)
        context.setContextProperty('rotatevalue', rotatevalue)

        root = self.rootObject()
        root.textRotationChanged.connect(self.rotationStatus)
        button = root.findChild(QObject, 'btnMouseArea')
        button.clicked.connect(lambda: con.outputStr('click button'))

        self.timer = QTimer()
        self.timer.start(2000)
        self.timer.timeout.connect(root.updateRotater)

    def rotationStatus(self, r):
        print 'rotation ' + str(r)
示例#3
0
class TestTimeoutSignal(UsesQCoreApplication):
    '''Test case to check if the signals are really being caught'''
    def setUp(self):
        #Acquire resources
        UsesQCoreApplication.setUp(self)
        self.watchdog = WatchDog(self)
        self.timer = QTimer()
        self.called = False

    def tearDown(self):
        #Release resources
        del self.watchdog
        del self.timer
        del self.called
        UsesQCoreApplication.tearDown(self)

    def callback(self, *args):
        #Default callback
        self.called = True

    def testTimeoutSignal(self):
        #Test the QTimer timeout() signal
        refCount = sys.getrefcount(self.timer)
        QObject.connect(self.timer, SIGNAL('timeout()'), self.callback)
        self.timer.start(4)
        self.watchdog.startTimer(10)

        self.app.exec_()

        self.assert_(self.called)
        self.assertEqual(sys.getrefcount(self.timer), refCount)
示例#4
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_()
示例#5
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)

        self.setWindowIcon(QIcon(':/ifmon.png'))

        try:
            self.model = BandwidthTableModel(self)
        except dberrors.OperationalError as e:
            QMessageBox.critical(self, 'Database Error',
                    'Could not access database.\nERROR: %s' % e)
            sys.exit(QApplication.exit())

        self.tableView.setModel(self.model)
        self.tableView.horizontalHeader().setResizeMode(QHeaderView.Stretch)
        self.tableView.horizontalHeader().setResizeMode(0, QHeaderView.ResizeToContents)
        self.tableView.setAlternatingRowColors(True)

        self.dateFrom.setDate(self.model.settings.start)
        self.dateTo.setDate(self.model.settings.start + timedelta(days=29))
        self.updateTotal()

        self.actionAbout.triggered.connect(self.about)

        self.timer = QTimer()
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.updateUsage)
        self.timer.start()
示例#6
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
示例#7
0
    def run(self):
        self._timeout = QTimer()
        self._timeout.setInterval(2000)
        self._timeout.timeout.connect(self.__onTimeout)

        try:
            self._serial = serial.Serial(self._port,
                                         baudrate=19200,
                                         bytesize=serial.SEVENBITS,
                                         stopbits=serial.STOPBITS_ONE,
                                         parity=serial.PARITY_ODD,
                                         timeout=1)
            self._serial.dtr = True
            self._serial.rts = False

            while not self._cancel:
                if not self._timeout.isActive():
                    self._timeout.start()
                data = self._serial.readline()
                data = data.strip()
                if len(data) == 12:
                    timestamp = time.time()
                    result = self._parser.parse(data, timestamp)
                    if result is not None:
                        self._timeout.stop()
                        self.data.emit(result)
                    else:
                        self.warning.emit('Invalid data received')
                QApplication.processEvents()
            self._serial.close()
        except serial.SerialException as e:
            self.error.emit(e.message)
示例#8
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())
示例#9
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
示例#10
0
文件: HelpForm.py 项目: ra2003/xindex
 def __init__(self, home, parent=None, *, stayOnTop=False, debug=False):
     super().__init__(parent)
     if stayOnTop:
         flags = self.windowFlags()
         flags |= Qt.WindowStaysOnTopHint
         self.setWindowFlags(flags)
     self.home = home
     self.debug = debug
     self.filenamesForWord = {}
     self.titleForFilename = {}
     self.createWidgets()
     self.createLayout()
     self.createConnections()
     self.createShortcuts()
     self.changePage(self.home)
     self.updateUi()
     if self.debug:
         self.mtime = 0
         self.timer = QTimer(self)
         self.timer.start(250)
         self.timer.timeout.connect(self.timeout)
     self.loadSettings()
     with open(Lib.get_path("doc/xix_style.css"), "r",
               encoding=UTF8) as file:
         self.css = file.read()
     self.browser.setFocus()
     self.setWindowTitle("Help — {}".format(
         QApplication.applicationName()))
示例#11
0
文件: python.py 项目: wiz21b/koi
class StatusWidget2(QWidget):
    def __init__(self,parent,text):
        super(StatusWidget2,self).__init__(parent)
        self.base_text = text

        self.msg_label = QLabel()
        l = QHBoxLayout()
        l.addStretch()
        l.addWidget(self.msg_label)
        self.setLayout(l)

        self.updateMessage()
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.updateMessage) # timerUpdate)
        self.timer.start(60*1000 - 1) # -1 so we never miss a minute


    @Slot()
    def updateMessage(self):

        # An attempt to prevent the router from closing an inactive
        # connection

        # NO commit so we don't risk closing ongoing transaction
        # although we don't do multithread right now

        if datetime.now().minute % 10 == 0:
            mainlog.debug("Reset connection")
            session().connection().execute("SELECT NULL");

        self.msg_label.setText(u"{}, {}".format(self.base_text, datetime.now().strftime("%A, %d %B %Y, %H:%M")))
示例#12
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")
示例#13
0
    def __init__(self, parent=None):
        QWidget.__init__(self)
        self.setMinimumSize(640, 480)
        self.setMaximumSize(self.minimumSize())

        # register this callbacks to interact with the faces and the camera
        # image before the widget will view the frame
        self.image_callback = None
        self.face_callback = None

        # init view with correct size, depth, channels
        self.frame = cv.CreateImage((640, 480), cv.IPL_DEPTH_8U, 3)

        self.storage = cv.CreateMemStorage()
        self.capture = cv.CaptureFromCAM(0)
        self.face_cascade = cv.Load(CSC_PATH +
                                    "haarcascade_frontalface_alt.xml")
        self.fd_wait_frames = 1
        self._fd_wait = self.fd_wait_frames

        # get first frame
        self._query_frame()

        # set refresh rate
        self.timer = QTimer(self)
        self.timer.timeout.connect(self._query_frame)
        self.timer.start(75)
示例#14
0
class TestTimeoutSignal(UsesQCoreApplication):
    '''Test case to check if the signals are really being caught'''

    def setUp(self):
        #Acquire resources
        UsesQCoreApplication.setUp(self)
        self.watchdog = WatchDog(self)
        self.timer = QTimer()
        self.called = False

    def tearDown(self):
        #Release resources
        del self.watchdog
        del self.timer
        del self.called
        UsesQCoreApplication.tearDown(self)

    def callback(self, *args):
        #Default callback
        self.called = True

    def testTimeoutSignal(self):
        #Test the QTimer timeout() signal
        refCount = sys.getrefcount(self.timer)
        QObject.connect(self.timer, SIGNAL('timeout()'), self.callback)
        self.timer.start(4)
        self.watchdog.startTimer(10)

        self.app.exec_()

        self.assert_(self.called)
        self.assertEqual(sys.getrefcount(self.timer), refCount)
示例#15
0
 def __init__(self, countdown, parent=None):
     QLabel.__init__(self, parent)
     self.countdown = countdown
     self.setText(self.countdown.toString(Qt.ISODate))
     # setup the countdown timer
     self.timer = QTimer(self)
     self.timer.timeout.connect(self._update_time)
示例#16
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)
示例#17
0
 def __init__(self, text, replaceColor=Qt.yellow, highlightColor=Qt.red, replaceTimeout=2):
   super(SearchReplaceLabel, self).__init__(text, highlightColor)
   self._replace_color = replaceColor
   self.replace_committed.connect(self._replaceText)
   self._replacement_fade_timer = QTimer()
   self._replacement_fade_timer.setSingleShot(replaceTimeout)
   self._replacement_fade_timer.timeout.connect(self._putOriginalText)
示例#18
0
 def __init__(self):
     self.network_manager = CustomNetworkAccessManager.getInstance()
     self.axis = []
     self.human_events = {}
     self.node_collected_data = {}
     self.last_url = None   
     self.current_url = QUrl()
     self.current_axis_id = None
     self.crossed_axis_method = None
     self.crossed_axes = []
     self.crossed_axes_string = ''
     
     self.cross_axis_delay = QTimer()
     self.cross_axis_delay.setSingleShot(True)
     self.cross_axis_delay.timeout.connect(self.crossedAxis)
     self.cross_axis_params = None
     
     self.loading_timeout = QTimer()
     self.loading_timeout.setSingleShot(True)
     self.loading_timeout.setInterval(30000)
     self.loading_timeout.timeout.connect(self.loadingTimeoutAction)
     
     self.inactivity_timeout = QTimer()
     self.inactivity_timeout.setSingleShot(True)
     self.inactivity_timeout.setInterval(10000)
     self.inactivity_timeout.timeout.connect(self.inactivityTimeoutAction)
     
     self.page_reloads = 0
     
     Logger.getLoggerFor(self.__class__)
示例#19
0
class RecomenDesktopApp(TaskTrayApp):
    def __init__(self, parent=None):
        super(RecomenDesktopApp, self).__init__(parent)

        # :: DBへのアップデートチェック
        self.updateChecker = DBUpdateChecker()
        self.updateChecker.start()

        self.updateChecker.finished.connect(self.add_news)

        # :: DBの新規更新の定期チェック
        self.updateCheck_timer = QTimer()
        self.updateCheck_timer.setInterval(10)

        self.stack = []

    @Slot()
    def add_news(self, news):
        print "add_news"
        if not news.hasupdate:
            return

        for new in news.get_datas():
            if new in self.get_local_db():
                print "Non News late"
                continue
            self.add_stack(new)
            print "add stack"

    def add_stack(self, n):
        self.stack.append(n)


    def get_local_db(self):
        return [2,3,4,5]
示例#20
0
    def __init__(self, opc=None):
        super(MainWindow, self).__init__()

        self.opc = opc

        self.setWindowTitle('OPC DA Datalogger')

        self.layout = QHBoxLayout(self)

        self.configuration = Configuration(self, opc)
        self.configuration_dock = QDockWidget("Configuration", self)
        self.configuration_dock.setWidget(self.configuration)
        self.configuration_dock.setFeatures(QDockWidget.NoDockWidgetFeatures)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.configuration_dock)

        self.logging_area = LoggingArea(self)
        self.logging_dock = QDockWidget("Logging", self)
        self.logging_dock.setWidget(self.logging_area)
        self.logging_dock.setFeatures(QDockWidget.NoDockWidgetFeatures)
        self.addDockWidget(Qt.RightDockWidgetArea, self.logging_dock)

        self.setLayout(self.layout)
        self.resize(900, 600)

        self.logging_timer = QTimer(self)
        self.logging_timer.timeout.connect(self._loogging_callback)
示例#21
0
class WidgetFader(object):
    '''
    For a given widget in the UI, this fader attaches a timer 
    that hides that widget after a specified interval
    '''
    
    def make_active(self):
        '''
        shows the widget then sets the hide timer
        '''
        self.controls.show()
        self.timer.start(self.time_out)
    
    def make_inactive(self):
        self.controls.hide()

    def __init__(self, controls, time_out=1500):
        '''
        Constructor
        '''
        self.timer = QTimer()
        self.timer.timeout.connect(self.make_inactive)
        self.timer.setSingleShot(True)
        
        self.time_out = time_out
        self.controls = controls
        self.controls.hide()
示例#22
0
    def __init__(self, parent=None):
        # Set up everything
        QMainWindow.__init__(self, parent)
        self.setWindowTitle("USB4000 Control")

        self.make_main_frame()

        self.spectra_timer = QTimer()
        self.spectra_timer.timeout.connect(self.update_spectrum)

        self.temp_timer = QTimer()
        self.temp_timer.timeout.connect(self.update_temp)

        self.worker = Usb4000Thread()
        self.wavelength_mapping = self.worker.dev.get_wavelength_mapping()

        self.curves = []         
        self.persistence_sb.valueChanged.connect(self.change_persistence)
        self.change_persistence()
        
        self.background = 1
        self.bg_min = 0

        self.use_background = False

        self.abs645 = pg.InfiniteLine(angle=90, movable=False)
        self.abs663 = pg.InfiniteLine(angle=90, movable=False)

        self.plot.addItem(self.abs645, ignoreBounds=True)
        self.plot.addItem(self.abs663, ignoreBounds=True)
        
        self.abs645.setPos(645)
        self.abs663.setPos(663)
        
        self.conc_deque = deque(maxlen=20)
示例#23
0
    def speak_ai(self, word):
        # AIのトークを表示
        # ディレイを使ってテンポを整える
        def wrapper():
            self.ai_txtarea.append(word)

        QTimer.singleShot(TALK_DELAY, wrapper)
示例#24
0
 def __init__(self, myInput, parent=None):
     super(FlashingInputButton, self).__init__(myInput, parent)
     self.flashing = False
     self._flashState = 0
     self._timer = QTimer()
     self._timer.timeout.connect(self._flash)
     self._timer.start(500)
示例#25
0
 def start_video(self, framerate=None):
     timer = QTimer()
     timer.timeout.connect(self._wait_for_frame)
     self.camera.start_live_video(framerate)
     timer.start(int(1000/self.camera.framerate))
     self.timer = timer
     self.centerOn(self.camera.width/2, self.camera.height/2)
示例#26
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_()
示例#27
0
 def start_video(self, framerate=None):
     timer = QTimer()
     timer.timeout.connect(self._wait_for_frame)
     self.camera.start_live_video(framerate)
     timer.start(int(1000 / self.camera.framerate))
     self.timer = timer
     self.centerOn(self.camera.width / 2, self.camera.height / 2)
示例#28
0
    def __init__(self, process, input_queue, output_queue):
        super(MainWidget, self).__init__()
        self.done = False
        layout = QtGui.QVBoxLayout()

        logo = QtGui.QLabel()
        logo.setPixmap('./data/logo.png')
        logo.setAlignment(Qt.AlignVCenter | Qt.AlignHCenter)
        layout.addWidget(logo)

        status_list = self.status_list = QtGui.QListWidget()
        status_list.addItem('Chowdren, the blazingly fast runtime for '
                            'Clickteam Fusion.')
        status_list.addItem(u'Copyright (c) Mathias K\xe6rlev 2012-2015.')
        status_list.addItem('Applications made with Chowdren are subject to '
                            'the GNU General Public License.')

        layout.addWidget(status_list)

        self.setLayout(layout)

        timer = QTimer(self)
        timer.setInterval(100)
        timer.timeout.connect(self.process_console)
        timer.start()

        self.process = process
        self.output_queue = output_queue
        self.input_queue = input_queue

        self.log = open('chowdrenlog.txt', 'wb')
示例#29
0
	def __init__(self, parent=None):
		super(MainWindow, self).__init__(parent)

		self.setWindowTitle("arrows")
		self.resize(800, 600)

		self.objects = []

		self.circR = 20
		self.arrSize = 10

		self.direction = "down"

		self.add(Circle(150, 150, self.circR))
		self.flyer = Circle(300, 50, self.circR)
		self.add(self.flyer)
		self.add(Circle(600, 300, self.circR))
		self.arrA = Arrow(150, 150, 300, 50, self.circR, self.arrSize)
		self.add(self.arrA)
		self.arrB = Arrow(300, 50, 600, 300, self.circR, self.arrSize)
		self.add(self.arrB)

		timer = QTimer(self)
		timer.timeout.connect(self.frameUpdate)
		timer.start(20)
示例#30
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())
示例#31
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()
示例#32
0
class Star(QWidget):
    def __init__(self, enlightened):

        p = enlightened.parent()
        while p.parent():
            p = p.parent()

        super(Star, self).__init__(p)

        self.enlightened = enlightened

        # self.parent = parent
        self.setMinimumSize(50, 50)

        self.setAttribute(Qt.WA_TransparentForMouseEvents)

        self.timer = QTimer()
        self.timer.timeout.connect(self.update)
        self.timer.start(20)

        self.progress = self.progress2 = 0
        self.enabled = True

    def paintEvent(self, pe):

        if not self.enlightened.isVisible() or not self.enabled:
            return

        g = self.enlightened.mapToGlobal(QPoint(0, 0))
        pos = self.parent().mapFromGlobal(g)
        self.setGeometry(
            QRect(pos.x(), pos.y(), self.minimumWidth(), self.minimumHeight()))

        p = QPainter(self)
        p.setRenderHint(QPainter.Antialiasing)

        pen = QPen()
        pen.setColor(QColor(128, 128, 255))
        pen.setWidth(2)

        p.setBrush(QBrush(QColor(225 + math.sin(self.progress) * 30, 225,
                                 255)))
        self.progress += 0.09 * 2
        self.progress2 += 0.109 * 2

        p.setPen(pen)

        s = 10
        sz = 7
        w = s * 1.1 + sz
        p.drawEllipse(0 + s * math.sin(self.progress + 0.5) + w,
                      s * math.cos(self.progress) + w, sz, sz)

        p.drawEllipse(s * 1.1 * math.sin(self.progress2) + w,
                      s * math.cos(self.progress + 0.5) + w, sz - 2, sz - 2)

        p.drawEllipse(
            s * math.sin(self.progress + 1) + w,
            s * 1.1 * math.cos(self.progress2 / 2 + self.progress / 2) + w,
            sz - 4, sz - 4)
    def __init__(self, url, filename, image_crop, translate_page, parent=None):
        super(Render, self).__init__(parent)
        self.image_crop = image_crop
        self.fileName = time.strftime("%Y%m%d%H%M%S",
                                      time.localtime()) + "_test.jpg"
        self.finished = False

        # Settings
        s = self.page().settings()
        s.setAttribute(QWebSettings.AutoLoadImages, True)
        s.setAttribute(QWebSettings.PluginsEnabled, True)
        s.setAttribute(QWebSettings.JavascriptEnabled, True)
        s.setAttribute(QWebSettings.JavaEnabled, False)
        s.setAttribute(QWebSettings.JavascriptCanOpenWindows, False)
        s.setAttribute(QWebSettings.DeveloperExtrasEnabled, True)

        #self.page().mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff)
        self.page().mainFrame().setScrollBarPolicy(Qt.Vertical,
                                                   Qt.ScrollBarAlwaysOff)

        self.timerScreen = QTimer()
        self.timerScreen.setInterval(10000)
        self.timerScreen.setSingleShot(True)
        self.timerScreen.timeout.connect(self.takeScreenshot)

        self.loadFinished.connect(self.timerScreen.start)
        self.load(QUrl(url))
示例#34
0
    def __init__(self, qpart, model):
        QListView.__init__(self, qpart.viewport())
        self.setItemDelegate(HTMLDelegate(self))
        
        self._qpart = qpart
        self.setFont(qpart.font())
        
        self.setCursor(QCursor(Qt.PointingHandCursor))
        self.setFocusPolicy(Qt.NoFocus)
        
        self.setModel(model)
        
        self._selectedIndex = -1
        
        # if cursor moved, we shall close widget, if its position (and model) hasn't been updated
        self._closeIfNotUpdatedTimer = QTimer()
        self._closeIfNotUpdatedTimer.setInterval(200)
        self._closeIfNotUpdatedTimer.setSingleShot(True)

        self._closeIfNotUpdatedTimer.timeout.connect(self._afterCursorPositionChanged)
        
        qpart.installEventFilter(self)
        
        qpart.cursorPositionChanged.connect(self._onCursorPositionChanged)
        
        self.clicked.connect(lambda index: self.itemSelected.emit(index.row()))
        
        self.updateGeometry()
        self.show()
        
        qpart.setFocus()
示例#35
0
 def testWithParent(self):
     self._destroyed = False
     p = QTimer()
     t = QTimer(p)
     t.destroyed[QObject].connect(self.onObjectDestroyed)
     del p
     self.assert_(self._destroyed)
示例#36
0
    def __init__(self,):
        QObject.__init__(self,)
        self.thread = None
        self._balance = '<b>0.00</b>000000'
        self._fiatSymbol = u'€'
        self._fiatRate = 0
        self._fiatBalance = u'0 €'
        self._wallet = Wallet()
        self._wallet.onNewTransaction.connect(self.notifyNewTx)
        self._walletUnlocked = False
        self.settings = Settings()
        self.addressesModel = AddressesModel()
        self.transactionsModel = TransactionsModel()
        self.timer = QTimer(self)
        self.timer.setInterval(900000)  # 15 min update
        self.timer.timeout.connect(self.update)
        self.timer.start()

        if self.settings.storePassKey:
            self._currentPassKey = self.settings.passKey
            try:
                self.unlockWallet(self._currentPassKey)
            except:
                self.onError.emit('Stored pass phrase is invalid')
        else:
            self._currentPassKey = None
        self._currentAddressIndex = 0
示例#37
0
 def __init__(self, parent=None):
     super(Recorder, self).__init__(parent)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     
     self.plotter = None
     self.session = None
     self.server = DelsysStation(parent=self)
     
     self.ui.dockWidget.setWidget(QWidget())
     
     self.dockLayout = QGridLayout(self.ui.dockWidget.widget())
     self.showSessionMeta = None
     self.showRunMeta = None
     self.plotWidget = None
     self.plots = []
     self.startTime = datetime.now()
     
     self.pinger = QTimer(self) # timer to read data from server whenever available
     self.runPinger = QTimer(self) # timer to call stop when run duration times out
     
     self.runPinger.setSingleShot(True)
     self.runPinger.timeout.connect(self.stop)
     self.pinger.timeout.connect(self.ping)
     self.kinectRecorder=None
     self.newpath=None
     self.notSavedState = False
示例#38
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)
示例#39
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)
示例#40
0
class WidgetFader(object):
    '''
    For a given widget in the UI, this fader attaches a timer 
    that hides that widget after a specified interval
    '''
    def make_active(self):
        '''
        shows the widget then sets the hide timer
        '''
        self.controls.show()
        self.timer.start(self.time_out)

    def make_inactive(self):
        self.controls.hide()

    def __init__(self, controls, time_out=1500):
        '''
        Constructor
        '''
        self.timer = QTimer()
        self.timer.timeout.connect(self.make_inactive)
        self.timer.setSingleShot(True)

        self.time_out = time_out
        self.controls = controls
        self.controls.hide()
示例#41
0
文件: qt.py 项目: ixokai/pants
def install(app=None, timeout=0.02):
    """
    Creates a :class:`~PySide.QtCore.QTimer` instance that will be triggered
    continuously to call :func:`Engine.poll() <pants.engine.Engine.poll>`,
    ensuring that Pants remains responsive.

    =========  ========  ============
    Argument   Default   Description
    =========  ========  ============
    app        None      *Optional.* The :class:`~PySide.QtCore.QCoreApplication` to attach to. If no application is provided, it will attempt to find an existing application in memory, or, failing that, create a new application instance.
    timeout    ``0.02``  *Optional.* The maximum time to wait, in seconds, before running :func:`Engine.poll() <pants.engine.Engine.poll>`.
    =========  ========  ============
    """
    global timer
    global _timeout

    Engine.instance()._install_poller(_Qt())

    if app is None:
        app = QCoreApplication.instance()
    if app is None:
        app = QCoreApplication([])

    _timeout = timeout * 1000

    timer = QTimer(app)
    timer.timeout.connect(do_poll)
    timer.start(_timeout)
示例#42
0
class Mlt(QtCore.QThread):
    s_producer_update = QtCore.Signal(object)
    s_play = QtCore.Signal(object)
    s_stop = QtCore.Signal(object)
    s_seek = QtCore.Signal(object)

    def __init__(self, parent=None):
        super(Mlt, self).__init__()
        self.parent = parent
        self.consumer = None
        self.producer = None
        self.movie_file = None
        self.profile = None

        self.position_timer = QTimer()
        self.position_timer.setInterval(125)
        self.position_timer.timeout.connect(self.onPositionTimeout)

    def onPositionTimeout(self):
        self.s_producer_update.emit(self.producer)

    def run(self):
        """
        starts thread
        """
        try:
            self.setup()
        except RuntimeError, err:
            print 'ERROR: Mlt.run: starting thread:', err
            self.quit()
示例#43
0
    def __init__(self, media, parent):
        super(MediaView, self).__init__(parent)
        self._parent = parent
        self._id = media['id']
        self._type = media['type']
        self._duration = media['duration']
        self._render = media['render']
        self._options = media['options']
        self._raws = media['raws']

        self._layout_id = media['_layout_id']
        self._schedule_id = media['_schedule_id']
        self._region_id = media['_region_id']
        self._save_dir = media['_save_dir']

        self._widget = None
        self._play_timer = QTimer(self)

        self._started = 0
        self._finished = 0

        self._errors = None
        # self.setObjectName('Media-%s-%s' % (self._type, self._id))
        # self._play_timer.setObjectName('%s-timer' % self.objectName())
        self._connect_signals()
示例#44
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)
示例#45
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()
示例#46
0
文件: qt.py 项目: vasudevram/pants
def install(app=None, timeout=0.02, engine=None):
    """
    Creates a :class:`~PySide.QtCore.QTimer` instance that will be triggered
    continuously to call :func:`Engine.poll() <pants.engine.Engine.poll>`,
    ensuring that Pants remains responsive.

    =========  ========  ============
    Argument   Default   Description
    =========  ========  ============
    app        None      *Optional.* The :class:`~PySide.QtCore.QCoreApplication` to attach to. If no application is provided, it will attempt to find an existing application in memory, or, failing that, create a new application instance.
    timeout    ``0.02``  *Optional.* The maximum time to wait, in seconds, before running :func:`Engine.poll() <pants.engine.Engine.poll>`.
    engine               *Optional.* The :class:`pants.engine.Engine` instance to use.
    =========  ========  ============
    """
    global timer
    global _timeout
    global _engine

    _engine = engine or Engine.instance()
    _engine._install_poller(_Qt())

    if app is None:
        app = QCoreApplication.instance()
    if app is None:
        app = QCoreApplication([])

    _timeout = timeout * 1000

    timer = QTimer(app)
    timer.timeout.connect(do_poll)
    timer.start(_timeout)
示例#47
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))
示例#48
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))
示例#49
0
 def __init__(self, main):
     """ Constructor Function """
     QWidget.__init__(self)
     self.target = main
     timer = QTimer(self)
     self.connect(timer, SIGNAL("timeout()"), self.UpdateProgressStats)
     timer.start(100)
     pygame.init()
示例#50
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)
示例#51
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)
示例#52
0
    def __init__(self, parent=None):
        super(Clock, self).__init__(parent)
        self.setAlignment(Qt.AlignCenter)

        timer = QTimer(self)
        timer.timeout.connect(self.updateClock)
        timer.start(1000)
        self.updateClock()
示例#53
0
文件: qt_gui.py 项目: gonicus/clacks
    def discover(self):
        mwin = WaitForServiceProvider()
        mwin.show()

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

        return self.url
示例#54
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()
示例#55
0
class LogFilePositionSource(QGeoPositionInfoSource):
    def __init__(self, parent):
        QGeoPositionInfoSource.__init__(self, parent)
        self.logFile = QFile(self)
        self.timer = QTimer(self)

        self.timer.timeout.connect(self.readNextPosition)

        self.logFile.setFileName(translate_filename('simplelog.txt'))
        assert self.logFile.open(QIODevice.ReadOnly)

        self.lastPosition = QGeoPositionInfo()

    def lastKnownPosition(self, fromSatellitePositioningMethodsOnly):
        return self.lastPosition

    def minimumUpdateInterval(self):
        return 100

    def startUpdates(self):
        interval = self.updateInterval()

        if interval < self.minimumUpdateInterval():
            interval = self.minimumUpdateInterval()

        self.timer.start(interval)

    def stopUpdates(self):
        self.timer.stop()

    def requestUpdate(self, timeout):
        # For simplicity, ignore timeout - assume that if data is not available
        # now, no data will be added to the file later
        if (self.logFile.canReadLine()):
            self.readNextPosition()
        else:
            self.updateTimeout.emit()

    def readNextPosition(self):
        line = self.logFile.readLine().trimmed()

        if not line.isEmpty():
            data = line.split(' ')
            hasLatitude = True
            hasLongitude = True
            timestamp = QDateTime.fromString(str(data[0]), Qt.ISODate)
            latitude = float(data[1])
            longitude = float(data[2])
            if timestamp.isValid():
                coordinate = QGeoCoordinate(latitude, longitude)
                info = QGeoPositionInfo(coordinate, timestamp)
                if info.isValid():
                    self.lastPosition = info
                    # Currently segfaulting. See Bug 657
                    # http://bugs.openbossa.org/show_bug.cgi?id=657
                    self.positionUpdated.emit(info)
示例#56
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))
        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)
示例#58
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)