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')
def test_print_preorder(self): # python test_integration.py TestEditOrderParts.test_print_preorder app = self.app widget = self.widget self._make_basic_preorder() self._encode_imputable_operation("Description2") self._encode_imputable_operation("Description3") QTest.keyEvent(QTest.Click, app.focusWidget(), Qt.Key_S, Qt.ControlModifier) # modifier, delay app.processEvents() # We're going to have a modal dialog for the # preorder print. So we prepare to click on it. timer = QTimer() timer.timeout.connect(self._fill_preorder_print_dialog) timer.setSingleShot(True) timer.start(250) self.prepare_to_click_dialog("set_preorder_sent_state", 3) widget.preorderPrint() order = dao.order_dao.find_by_id(widget._current_order.order_id) self.assertEqual("ZuluHeader", order.preorder_print_note) self.assertEqual("ZuluFooter", order.preorder_print_note_footer)
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)
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)
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)
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)
class ColumnResizer(QObject): def __init__(self): super(ColumnResizer, self).__init__() self._widgets = [] self._gridColumnInfoList = [] self._updateTimer = QTimer(self) self._updateTimer.setSingleShot(True) self._updateTimer.setInterval(0) self._updateTimer.timeout.connect(self._updateWidth) # Public methods def addWidgetsFromLayout(self, layout, column): """ :type layout: QGridLayout :type column: int """ assert column >= 0 if isinstance(layout, QGridLayout): self._addWidgetsFromGridLayout(layout, column) else: print "ColumnResizerResizer does not support layouts of type:", type(layout) def eventFilter(self, obj, event): """ Overrides QObject.eventFilter() """ if event.type() == QEvent.Resize: self._scheduleWidthUpdate() return False # Private methods @Slot() def _updateWidth(self): width = 0 for widget in self._widgets: width = max(widget.sizeHint().width(), width) for info in self._gridColumnInfoList: info[0].setColumnMinimumWidth(info[1], width) def _addWidget(self, widget): self._widgets.append(widget) widget.installEventFilter(self) self._scheduleWidthUpdate() def _addWidgetsFromGridLayout(self, layout, column): for row in range(layout.rowCount()): item = layout.itemAtPosition(row, column) if not item: continue widget = item.widget() if not widget: continue self._addWidget(widget) self._gridColumnInfoList.append([layout, column]) def _scheduleWidthUpdate(self): self._updateTimer.start()
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")))
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)
class SessionService(QObject): session_started = Signal(SessionModel) session_paused = Signal(SessionModel) session_resumed = Signal(SessionModel) session_stopped = Signal() timer_updated = Signal(float) def __init__(self): super(SessionService, self).__init__() self.session_dao = SessionDao() self.time = 0 self.state = SessionState.STOPPED self.timer = QTimer(self) self.timer.timeout.connect(self._timer_timeout) self.current_session = None def start_session(self, project): self.time = 0 self.current_session = SessionModel(start = time.time(), project_id = project.id) self.current_session = self.session_dao.save(self.current_session) self.timer.start(1000) self.state = SessionState.ACTIVE self.session_started.emit(self.current_session) def pause_session(self): self.timer.stop() self.state = SessionState.PAUSED self.session_paused.emit(self.current_session) def resume_session(self): self.timer.start(1000) self.state = SessionState.ACTIVE self.current_pause = None self.session_resumed.emit(self.current_session) def stop_session(self): self.state = SessionState.STOPPED self.timer.stop() if self.current_session: self.current_session.end = time.time() self.current_session.duration = self.time self.session_dao.save(self.current_session) self.session_stopped.emit() self.current_session = None self.time = 0 def get_state(self): return self.state def get_table_model(self, project): 'Returns a table model with sessions for the specified project' return SessionTableModel(self, project, self.session_dao) def _timer_timeout(self): self.time += 1 self.timer_updated.emit(self.time)
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 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)
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)
def test_encode_wrong_order_id(self): # python test_edit_timetracks.py TestEditTimetracks.test_encode_wrong_order_id app = self.app widget = self.widget today = date.today() widget.set_employee_and_date(self.employee.employee_id, today) QTest.keyEvent(QTest.Click, app.focusWidget(), Qt.Key_F5, Qt.ShiftModifier) # modifier, delay app.processEvents() QTest.keyEvent(QTest.Click, app.focusWidget(), Qt.Key_9) # modifier, delay app.processEvents() QTest.keyEvent(QTest.Click, app.focusWidget(), Qt.Key_9) # modifier, delay app.processEvents() QTest.keyEvent(QTest.Click, app.focusWidget(), Qt.Key_9) # modifier, delay app.processEvents() timer = QTimer() timer.timeout.connect(self._click_order_inexistant_box) timer.setSingleShot(True) timer.start(250) self.test_sucess = False QTest.keyEvent(QTest.Click, app.focusWidget(), Qt.Key_Enter) app.processEvents() assert self.test_sucess
class Panel(QWidget): def __init__(self, parent=None, instr=None, lock=None, title="Instrument Panel"): # This class derivates from a Qt Widget so we have to call # the class builder ".__init__()" QWidget.__init__(self) # "self" is now a Qt Widget, then we load the user interface # generated with QtDesigner and call it self.ui self.ui = Keithley6221_Ui.Ui_Panel() # Now we have to feed the GUI building method of this object (self.ui) # with the current Qt Widget 'self', but the widgets from the design will actually be built as children # of the object self.ui self.ui.setupUi(self) self.setWindowTitle(title) self.reserved_access_to_instr = lock self.instr = instr self.monitor_timer = QTimer() # The timer would not wait for the completion of the task otherwise self.monitor_timer.setSingleShot(True) self.monitor_timer.timeout.connect(self.monitor) self.firsttime = 0 # bug: if the box is checked in the .ui file, the system freezes # if self.ui.monitor.isChecked():self.monitor() def monitor(self, state=1): if state != 1: self.monitor_timer.stop() elif state and not (self.monitor_timer.isActive()): with self.reserved_access_to_instr: I = self.instr.query_current_source_amplitude() Vcomp = self.instr.query_voltage_compliance() outstate = self.instr.query_output_ON() self.ui.I_disp.setText(str(I * 1e6) + u" μA") self.ui.V_disp.setText(str(Vcomp) + " V") self.ui.outputON.setChecked(outstate) self.monitor_timer.start(self.ui.refresh_rate.value() * 1000) def update_timer_timeout(self, secs): # The value must be converted to milliseconds self.monitor_timer.setInterval(secs * 1000) def change_I(self, value=0): with self.reserved_access_to_instr: self.instr.set_current_source_amplitude(value * 1e6) def change_V_comp(self, value=0): with self.reserved_access_to_instr: self.instr.set_voltage_compliance(value) def switch_output(self, value=False): if value: with self.reserved_access_to_instr: self.instr.output_ON() else: with self.reserved_access_to_instr: self.instr.output_OFF() def reset_inst(self): with self.reserved_access_to_instr: self.instr.reset()
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()
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()
class PhotoListModel(QAbstractListModel): URL_ROLE = Qt.UserRole + 1 IMAGE_URL_ROLE = Qt.UserRole + 2 HEIGHT_ROLE = Qt.UserRole + 3 WIDTH_ROLE = Qt.UserRole + 4 def __init__(self, album, parent=None): super(PhotoListModel, self).__init__(parent) self._album = album self._photos = [] self._cache = [] self._done = False keys = {} keys[PhotoListModel.URL_ROLE] = "url" keys[PhotoListModel.IMAGE_URL_ROLE] = "imageUrl" keys[PhotoListModel.HEIGHT_ROLE] = "height" keys[PhotoListModel.WIDTH_ROLE] = "width" self.setRoleNames(keys) self._load = PhotoLoad(self) self._load.start() self._timer = QTimer() self._timer.setInterval(1000) self._timer.timeout.connect(self.loadCache) self._timer.start() def rowCount(self, index): return len(self._photos) def appendCache(self, itens): self._cache += itens def loadCache(self): self.beginInsertRows(QModelIndex(), len(self._photos), len(self._photos) + len(self._cache)) self._photos += self._cache self.endInsertRows() self._cache = [] if self._done: self._timer.stop() def data(self, index, role): if not index.isValid(): return None if index.row() > len(self._photos): return None img = self._photos[index.row()] if role == PhotoListModel.URL_ROLE: return img.url elif role == PhotoListModel.IMAGE_URL_ROLE: return img.imageUrl elif role == PhotoListModel.HEIGHT_ROLE: return img.height elif role == PhotoListModel.WIDTH_ROLE: return img.width else: return None
class Window(QWidget): def __init__(self): QWidget.__init__(self) self.players = [Player('Antho', 30, 5), Player('Tanguy', 30, 5)] self.button_begin1 = QPushButton("1 Begin") self.button_begin1.clicked.connect(self._begin) self.button_begin1.player = 0 self.button_end1 = QPushButton("1 End") self.button_end1.clicked.connect(self._end) self.button_end1.player = 0 self.button_begin2 = QPushButton("2 Begin") self.button_begin2.clicked.connect(self._begin) self.button_begin2.player = 1 self.button_end2 = QPushButton("2 End") self.button_end2.clicked.connect(self._end) self.button_end2.player = 1 self.label_status1 = QLabel() self.label_status2 = QLabel() layout = QGridLayout(self) layout.addWidget(self.label_status1, 0, 0, 1, 2) layout.addWidget(self.button_begin1, 1, 0) layout.addWidget(self.button_end1, 1, 1) layout.addWidget(self.label_status2, 0, 2, 1, 2) layout.addWidget(self.button_begin2, 1, 2) layout.addWidget(self.button_end2, 1, 3) self.refresh_timer = QTimer() self.refresh_timer.timeout.connect(self._timeout) self.refresh_timer.start(100) def _begin(self): self.players[self.sender().player].timer.begin_turn() def _end(self): self.players[self.sender().player].timer.end_turn() def _timeout(self): time_left1 = self.players[0].timer.time_left() if time_left1 == -1: self.label_status1.setText("Not started") else: self.label_status1.setText("Time left {}".format(int(time_left1))) time_left2 = self.players[1].timer.time_left() if time_left2 == -1: self.label_status2.setText("Not started") else: self.label_status2.setText("Time left {}".format(int(time_left2)))
class Demo(object): def __init__(self, device, framerate): self.device = device self.timer = QTimer() self.timer.timeout.connect(self.update) self.timer.start(1000.0 / framerate) def update(self): pass
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)
def create_timer(self, milliseconds, handler): """ Creates and returns a timer which will call *handler* every *milliseconds* milliseconds. The timer can be cancelled by calling the returned object with no arguments. """ timer = QTimer() QObject.connect(timer, SIGNAL("timeout()"), handler) timer.start(int(milliseconds)) return timer.stop
def __init__(self): QWidget.__init__(self) self.setWindowTitle('My Digital Clock') timer=QTimer(self) self.connect(timer,SIGNAL('timeout()'),self.updtTime) self.myTimeDisplay=QLCDNumber(self) self.myTimeDisplay.setSegmentStyle(QLCDNumber.Filled) self.myTimeDisplay.setDigitCount(8) self.myTimeDisplay.resize(500,150) timer.start(1000)
def __init__(self): QWidget.__init__(self) self.setWindowTitle("My Digital Clock") timer = QTimer(self) self.connect(timer, SIGNAL("timeout()"), self.updtTime) self.myTimeDisplay = QLCDNumber(self) self.myTimeDisplay.setSegmentStyle(QLCDNumber.Filled) self.myTimeDisplay.setDigitCount(8) self.myTimeDisplay.resize(500, 150) timer.start(1000)
def __init__(self): QWidget.__init__(self) self.setWindowTitle("My digital Clock") timer = QTimer(self) self.connect(timer, SIGNAL("timeout()"), self.updtTime) self.myTimeDisplay = QLCDNumber(self) # Choix du type d'apparence self.myTimeDisplay.setSegmentStyle(QLCDNumber.Filled) self.myTimeDisplay.setDigitCount(8) # Nombre de chiffres affichés self.myTimeDisplay.resize(500, 150) timer.start(1000) # Bouclage tout le 1 sec
def __init__(self, *args, **kwargs): MyMplCanvas.__init__(self, right_edge=0.85, *args, **kwargs) timer = QTimer(self) # Tie the "update_figure" function to the timer timer.timeout.connect(self.update_figure) # Millisecond Timer, Assign the update time based on the value returned by # the API call, store the API call data in an object-global data variable # to reduce the number of API calls required to initialize the plot timer.start(300000) self.compute_initial_figure()
class Watcher(QObject): fileDeleted = Signal((str,str,)) fileAdded = Signal((str,str,)) fileChanged = Signal((str,str,bool,)) checked = Signal() ioError = Signal((str,)) TOLERANCE = 15 def __init__(self, parent=None): super(Watcher, self).__init__(parent) self.fileAdded.connect(self.added) self.fileChanged.connect(self.changed) self.fileDeleted.connect(self.deleted) @Slot() def checkout(self): raise NotImplementedError @Slot() def startCheckout(self): self.checkTimer = QTimer() self.checkTimer.setInterval(self.interval) self.checkTimer.timeout.connect(self.checkout) self.checkTimer.start() @Slot(str, str) def added(self, location, serverpath): print 'Added {0}: {1}'.format(self.LOCATION, serverpath) @Slot(str, str) def changed(self, location, serverpath): print 'Changed {0}: {1}'.format(self.LOCATION, serverpath) @Slot(str, str) def deleted(self, location, serverpath): print 'Deleted {0}: {1}'.format(self.LOCATION, serverpath) def localFromServer(self, serverpath): # Removing leading '/' so `os.path.join` doesn't treat # `localpath` as an absolute path localpath = serverpath[1:] if serverpath.startswith('/') else serverpath localpath = QDir.toNativeSeparators(localpath) localpath = os.path.join(self.localdir, localpath) return localpath def serverFromLocal(self, localpath): serverpath = localpath.replace(self.localdir, '') serverpath = QDir.fromNativeSeparators(serverpath) return serverpath
class FunnySpiral(QGLWidget): """ Renders a spiral on a Qt widget. """ def __init__(self, parent=None): QGLWidget.__init__(self, parent) self.timer = QTimer(self) # the timer, which drives the animation self.timer.timeout.connect(self.update) # the angle, by which the spiral is rotated self.angle = 0 self.spiral = self.update_spiral() def start_rotation(self): self.timer.start(100) def stop_rotation(self): self.timer.stop() def update_spiral(self): # create a polygon providing the corner points of the spiral polygon = QPolygon() for i in xrange(self.window().width()): x = int(math.cos(i * 0.16) * i) y = int(math.sin(i * 0.16) * i) polygon.append(QPoint(x, y)) return polygon def resizeEvent(self, evt): # re-create the spiral, if the widget is resized self.spiral = self.update_spiral() def paintEvent(self, evt): # create a painter with paint(self) as painter: # adjust the width of the pen pen = QPen() pen.setWidth(5) painter.setPen(pen) # enable high quality antialiasing painter.setRenderHint(QPainter.Antialiasing) painter.setRenderHint(QPainter.HighQualityAntialiasing) # move the center of the coordinate system to the widgets center painter.translate(self.width() / 2, self.height() / 2) # rotate the coordinate system by the given angle painter.rotate(self.angle) # draw the spiral painter.drawPolyline(self.spiral) # end painting and free resources # update the angle self.angle += 30 self.angle %= 360
def test_change_order_customer_cancelled(self): customer2 = self._customer_dao.make( "AAAA") # Name chosen so it happens first int he customer dialog self._customer_dao.save(customer2) app = self.app widget = self.widget mw = self.mw self._make_basic_preorder() self._encode_imputable_operation("Description2") self._encode_imputable_operation("Description3") QTest.keyEvent(QTest.Click, app.focusWidget(), Qt.Key_S, Qt.ControlModifier) # modifier, delay app.processEvents() # Make sure the test is set up correctly preorder = self.order_dao.find_by_id_frozen( widget._current_order.order_id) assert preorder.customer_id == self.customer.customer_id # We're going to have a modal dialog for the new # customer name. So we prepare to click on it. timer = QTimer() timer.timeout.connect(self._cancel_dialog) timer.setSingleShot(True) timer.start(1000) # Had 250, my linux seems to prefer 1000 widget.change_customer() # blocks app.processEvents() # app.exec_() # Wait for the timer to shoot widget.setFocus( Qt.OtherFocusReason) # This refocus was introduced for linux for i in range(1000): app.processEvents() # Linux needs a break mainlog.debug("Pressing ctrl-S on this widget : {}".format( app.focusWidget())) # app.exec_() QTest.keyEvent(QTest.Click, app.focusWidget(), Qt.Key_S, Qt.ControlModifier) # modifier, delay app.processEvents() preorder = self.order_dao.find_by_id_frozen( widget._current_order.order_id) assert preorder.customer_id == self.customer.customer_id self.order_dao.delete(preorder.order_id) self.dao.customer_dao.delete(customer2.customer_id)
class SyncThread(QThread): """Sync notes with evernote thread""" force_sync_signal = Signal() sync_state_changed = Signal(int) def __init__(self, app, *args, **kwargs): QThread.__init__(self, *args, **kwargs) self.app = app self.status = STATUS_NONE self.last_sync = datetime.now() self.timer = QTimer() self.timer.timeout.connect(self.sync) self.update_timer() self.wait_condition = QWaitCondition() self.mutex = QMutex() def update_timer(self): self.timer.stop() delay = int(self.app.settings.value('sync_delay') or 0) or DEFAULT_SYNC_DELAY if delay != SYNC_MANUAL: self.timer.start(delay) def run(self): self.session = get_db_session() self.sq = self.session.query self.auth_token = get_auth_token() self.note_store = get_note_store(self.auth_token) self.perform() while True: self.mutex.lock() self.wait_condition.wait(self.mutex) self.perform() self.mutex.unlock() def force_sync(self): self.timer.stop() self.sync() self.update_timer() @Slot() def sync(self): self.wait_condition.wakeAll() def perform(self): """Perform all sync""" self.status = STATUS_SYNC self.last_sync = datetime.now() self.sync_state_changed.emit(SYNC_STATE_START) try: self.local_changes() self.remote_changes() except Exception, e: # maybe log this self.session.rollback() finally:
def test_change_order_customer(self): customer2 = self._customer_dao.make( "AAAA") # Name chosen so it happens first int he customer dialog self._customer_dao.save(customer2) app = self.app widget = self.widget mw = self.mw self._make_basic_preorder() self._encode_imputable_operation("Description2") self._encode_imputable_operation("Description3") QTest.keyEvent(QTest.Click, app.focusWidget(), Qt.Key_S, Qt.ControlModifier) # modifier, delay app.processEvents() # Make sure the test is set up correctly preorder = self.order_dao.find_by_id_frozen( widget._current_order.order_id) assert preorder.customer_id == self.customer.customer_id # We're going to have a modal dialog for the new # customer name. So we prepare to click on it. timer = QTimer() timer.timeout.connect(self._lookup) timer.setSingleShot(True) timer.start(1000) widget.change_customer() # app.exec_() # Wait for the timer to shoot mainlog.debug("test_change_order_customer" * 10) mainlog.debug(app.focusWidget()) widget.setFocus( Qt.OtherFocusReason) # This refocus was introduced for linux app.processEvents() QTest.keyEvent(QTest.Click, app.focusWidget(), Qt.Key_S, Qt.ControlModifier) # modifier, delay app.processEvents() mainlog.debug("test_change_order_customer") preorder = self.order_dao.find_by_id_frozen( widget._current_order.order_id) assert preorder.customer_id == customer2.customer_id mainlog.debug("test_change_order_customer") self.order_dao.delete(preorder.order_id) self.dao.customer_dao.delete(customer2.customer_id)
class FpsDraw(object): def __init__(self, parent): self.ctimer = QTimer() self.ctimer.start(0) self.parent = parent self.prev = time.time() self.ctimer.timeout.connect(self.parent.update) def draw(self): self.cur = time.time() elapsed = self.cur - self.prev self.prev = self.cur
def onLoopRequested(loopRequest): print 'l: ', l if l: l.pop() led.toggle(not led.isToggled()) ledTimer = QTimer(toggleObject) ledTimer.setSingleShot(True) ledTimer.setInterval(200) ledTimer.timeout.connect( partial(loopRequest.completeRequest, True if l else False)) ledTimer.start() if not l: l.extend(range(20))
class Reader(QThread): data = Signal(Meter) warning = Signal(str) error = Signal(str) def __init__(self, port): QThread.__init__(self) self._port = port self._serial = None self._parser = Parser() self._cancel = False self._timeout = None def run(self): self._timeout = QTimer() self._timeout.setInterval(2000) self._timeout.timeout.connect(self.__onTimeout) try: self._serial = serial.Serial(self._port, baudrate=19200, bytesize=serial.SEVENBITS, stopbits=serial.STOPBITS_ONE, parity=serial.PARITY_ODD, timeout=1) self._serial.dtr = True self._serial.rts = False while not self._cancel: if not self._timeout.isActive(): self._timeout.start() data = self._serial.readline() data = data.strip() if len(data) == 12: timestamp = time.time() result = self._parser.parse(data, timestamp) if result is not None: self._timeout.stop() self.data.emit(result) else: self.warning.emit('Invalid data received') QApplication.processEvents() self._serial.close() except serial.SerialException as e: self.error.emit(e.message) def __onTimeout(self): self.warning.emit('No data received') def stop(self): self._cancel = True
def __init__(self, process_manager): super(MainWindow, self).__init__(None) self.resize(731, 475) central_widget = QWidget(self) grid_layout = QGridLayout(central_widget) self.clients_label = QLabel(self) self.clients_label.setText("Connected clients: ") grid_layout.addWidget(self.clients_label, 0, 0, 1, 1) start_clients_button = QPushButton(self) start_clients_button.setText("Start Clients") start_clients_button.clicked.connect(self.start_clients_clicked) grid_layout.addWidget(start_clients_button, 0, 1, 1, 1) self.my_widgets = {} for id, process in enumerate(process_manager.get_process_descriptions()): xpos = 0 ypos = id+1 name_label = QLabel(self) name_label.setText(process.id) grid_layout.addWidget(name_label, ypos, xpos, 1, 1) xpos += 1 host_label = QLabel(self) host_label.setText(process.target_host) grid_layout.addWidget(host_label, ypos, xpos, 1, 1) xpos += 1 status_label = QLabel(self) status_label.setText(ProcessStati.INIT.name) grid_layout.addWidget(status_label, ypos, xpos, 1, 1) xpos += 1 start_button = QPushButton(self) start_button.setText("Start "+process.id) start_button.clicked.connect(self.button_clicked) grid_layout.addWidget(start_button, ypos, xpos, 1, 1) xpos += 1 log_button = QPushButton(self) log_button.setText("Update-log "+process.id) log_button.clicked.connect(self.log_button_clicked) grid_layout.addWidget(log_button, ypos, xpos, 1, 1) xpos += 1 self.my_widgets[process.id] = [name_label, status_label, start_button, log_button] self.setCentralWidget(central_widget) self.clients = process_manager.get_client_stati() self.start_clients_dialog = ClientStartDialog(self, self.clients) self.process_manager = process_manager self.status_dialogs = {} timer = QTimer(self) self.connect(timer, SIGNAL("timeout()"), self.update_stati) timer.start(1000)
class _ThreadPoolStatus(object): def __init__(self, q): self.activeThreadCount = 0 self.refreshTimer = QTimer(q) self.refreshTimer.setInterval(500) self.refreshTimer.timeout.connect(self.refresh) self.refreshTimer.start() def refresh(self): value = QThreadPool.globalInstance().activeThreadCount() if self.activeThreadCount != value: self.activeThreadCount = value self.q.threadCountChanged.emit(value)
def __init__(self): """ Constructor Function """ QWidget.__init__(self) self.setWindowTitle('My Digital Clock') timer = QTimer(self) timer.timeout.connect(self.updtTime) #update runtime connect self.myTimeDisplay = QLCDNumber(self) self.myTimeDisplay.setSegmentStyle(QLCDNumber.Flat) self.myTimeDisplay.setDigitCount(8) self.myTimeDisplay.resize(500, 150) timer.start(1000)
class FpsDraw(object): def __init__(self, parent): self.ctimer = QTimer() self.ctimer.start(0) self.parent = parent self.prev = time.time() self.ctimer.timeout.connect(self.parent.update) def draw(self): self.cur = time.time() elapsed = self.cur - self.prev self.prev = self.cur print 1 / elapsed
def __init__(self): """constructor function""" title="my digital clock" QWidget.__init__(self) self.setWindowTitle(title) timer=QTimer(self) self.connect(timer, SIGNAL("timeout()"), self.updtTime) self.myTimeDisplay=QLCDNumber(self) self.myTimeDisplay.setSegmentStyle(QLCDNumber.Filled) self.myTimeDisplay.setDigitCount(8) self.myTimeDisplay.resize(500, 150) timer.start(1000)
class MyGlWidget(QGLWidget): "PySideApp uses Qt library to create an opengl context, listen to keyboard events, and clean up" def __init__(self, renderer, glformat, app): "Creates an OpenGL context and a window, and acquires OpenGL resources" super(MyGlWidget, self).__init__(glformat) self.renderer = renderer self.app = app # Use a timer to rerender as fast as possible self.timer = QTimer(self) self.timer.setSingleShot(True) self.timer.setInterval(0) self.timer.timeout.connect(self.render_vr) # Accept keyboard events self.setFocusPolicy(Qt.StrongFocus) def __enter__(self): "setup for RAII using 'with' keyword" return self def __exit__(self, type_arg, value, traceback): "cleanup for RAII using 'with' keyword" self.dispose_gl() def initializeGL(self): if self.renderer is not None: self.renderer.init_gl() self.timer.start() def paintGL(self): "render scene one time" self.renderer.render_scene() self.swapBuffers() # Seems OK even in single-buffer mode def render_vr(self): self.makeCurrent() self.paintGL() self.doneCurrent() self.timer.start() # render again real soon now def disposeGL(self): if self.renderer is not None: self.makeCurrent() self.renderer.dispose_gl() self.doneCurrent() def keyPressEvent(self, event): "press ESCAPE to quit the application" key = event.key() if key == Qt.Key_Escape: self.app.quit()
def test_change_order_part_state(self): order = self._make_order() order_part = self._order_part_dao.make(order) order_part.description = u"Part 2" order_part.position = 2 self._order_part_dao.save(order_part) order_part = self._order_part_dao.make(order) order_part.description = u"Part 3" order_part.position = 3 self._order_part_dao.save(order_part) self._order_dao.change_order_state( order.order_id, OrderStatusType.order_ready_for_production) # self.order_overview_widget.month_today() self.order_overview_widget.refresh_action() self.order_overview_widget.retake_focus() # self.app.exec_() # Select the first order part (we assume they are properly ordered) v = self.order_overview_widget.current_orders_overview.table_view v.setCurrentIndex(v.model().index(0, 0)) QTest.mouseMove(v) # QTest.mouseClick(self.order_overview_widget.current_orders_overview.table_view, # Qt.RightButton, delay=500) # self.order_overview_widget.current_orders_overview.popup_parts() timer = QTimer() timer.timeout.connect(self._click_context_menu) timer.setSingleShot(True) timer.start(1000) # I can't have the menu to popup using museClicks, so I # do it this way. FIXME Taht's not right because nothing prooves # that my context menu is shown on mouse clicks... self.app.sendEvent( self.order_overview_widget.current_orders_overview.table_view, QContextMenuEvent(QContextMenuEvent.Keyboard, QPoint(10, 10))) # self.app.exec_() order = self.order_dao.find_by_id(order.order_id) self.assertEqual(OrderPartStateType.aborted, order.parts[0].state) self.assertEqual(OrderPartStateType.ready_for_production, order.parts[1].state) self.assertEqual(OrderPartStateType.ready_for_production, order.parts[2].state)
class MidiMonitorUnit(unit.Sink, unit.Unit): def __init__(self, style='hex', show_time=False, *args, **kwargs): unit.Unit.__init__(self, *args, **kwargs) unit.Sink.__init__(self) self._style = style self._show_time = show_time self.messages = list() self._max_messages = 100 self._client = jackpatch.Client('jackdaw-monitor') self._client.activate() self._sink_type = 'midi' self._sink_port = jackpatch.Port(client=self._client, name='capture', flags=jackpatch.JackPortIsInput) self._timer = QTimer() self._timer.setInterval(0) self._timer.timeout.connect(self.receive) self._timer.start() @property def style(self): return(self._style) @style.setter def style(self, value): if (value != self._style): self._style = value self.on_change() @property def show_time(self): return(self._show_time) @show_time.setter def show_time(self, value): if (value != self._show_time): self._show_time = value self.on_change() def receive(self): message_added = False while (True): result = self._sink_port.receive() if (result is None): break (data, time) = result self.messages.append((data, time)) message_added = True if (message_added): # trim the message list if it gets too long to conserve memory if (len(self.messages) > self._max_messages): self.messages = self.messages[-self._max_messages:] self.on_change() def serialize(self): obj = unit.Unit.serialize(self) obj['style'] = self.style obj['show_time'] = self.show_time return(obj)
def downlaod(self, url, timeout=60): loop = QEventLoop() timer = QTimer() timer.setSingleShot(True) timer.timeout.connect(loop.quit) self.loadFinished.connect(loop.quit) self.load(QUrl(url)) timer.start(timeout * 1000) loop.exec_() if timer.isActive(): timer.stop() return self.html() else: print 'Request timed out: ' + url
def TCP_connect(self): self.clo = 0 self.pushButton_2.setEnabled(False) self.pushButton.setEnabled(True) # 等待一个新连接 self.textEdit_2.insertPlainText('Waiting for connection...\r\n') # 接受一个新连接 # 创建新线程来处理TCP连接 timer = QTimer(self) timer.timeout.connect(self.fresh) timer.start(200) t = threading.Thread(target=self.tcplink) t.setDaemon(True) t.start()
class InputHandler(observable.Object): def __init__(self, port, target): observable.Object.__init__(self) # store the source port and the target to send data to self._port = port self._target = target # add an idle timer to check for input self._timer = QTimer() self._timer.setInterval(0) self._timer.timeout.connect(self.receive) self._timer.start() def destroy(self): self._timer.timeout.disconnect(self.receive) self._timer.stop() @property def port(self): return(self._port) @property def target(self): return(self._target) # check for input def receive(self, limit_time=True): # limit processing time to maintain responsiveness time_limit = time.time() + 0.100 # wrap the target in a change block so each midi event doesn't waste a lot # of time causing cascading changes target_and_refs = (self._target,) try: target_and_refs += self._target.model_refs except AttributeError: pass for model in target_and_refs: try: model.begin_change_block() except AttributeError: pass while (True): result = self._port.receive() if (result is None): break (data, msg_time) = result self.handle_message(data, msg_time) # handle at least one message per run, but limit overall processing time # to keep the UI responsive, allowing the jackpatch buffer to handle # the backlog if ((limit_time) and (time.time() > time_limit)): break for model in target_and_refs: try: model.end_change_block() except AttributeError: pass # handle input, reimplement to pass data to the target def handle_message(data, time): pass
class Animation(): _SetterGetter = 0; _SetAttr = 1; def __init__(self,obj,property_name_or_setter,getter=None): # decide how the property will be set if getter != None: self._setmethod = Animation._SetterGetter self._setter = property_name_or_setter; self._getter = getter else: self._propname = property_name_or_setter self._setmethod = Animation._SetAttr self._anim_obj = obj # initialize some variables self.startvalue = True self.endvalue = True self.duration = 1000 self.interval = 5 self.interpolator = True # the interpolator gives values for the animation self._previousvalue = QColor(0,0,0) # this is given to the interpolator in Animation.update() self.isvisual = True # this is used to tell whether to call QWidget.update() on self._anim_obj self._timer = QTimer() # this is used for timing the animation...duh self._timer.timeout.connect(self._update) def setBySetter(self,value): self._setter(value) def setBySetAttr(self,value): setattr(self._anim_obj,self._propname,value) def start(self): if type(self.startvalue) == QColor: # if we're working with colors, use a ColorInterpolator self.interpolator = ColorInterpolator(self.startvalue, self.endvalue, self.duration, self.interval, self.stop) else: raise NotImplementedError("There is no interpolator for ", str(type(self.start()))) self._previousvalue = self.startvalue self._timer.start(self.interval) def _update(self): self._previousvalue = self.interpolator.getnextvalue(self._previousvalue) if self.isvisual: self._anim_obj.update() def stop(self): print "Stopped\n" self._timer.timeout.connect(self._blankmethod) self._timer.stop() def _blankmethod(self): print "blankmethod"
def setup(self, icon_painter, painter, rect): if self.parent_widget not in self.info: timer = QTimer() timer.timeout.connect(lambda: self._update(self.parent_widget)) self.info[self.parent_widget] = [timer, 0, self.step] timer.start(self.interval) else: timer, angle, self.step = self.info[self.parent_widget] x_center = rect.width() * 0.5 y_center = rect.height() * 0.5 painter.translate(x_center, y_center) painter.rotate(angle) painter.translate(-x_center, -y_center)
class Network(QObject): messageReceived = Signal(str) serverClosed = Signal() def __init__(self, parent): super(Network, self).__init__(parent) self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._isConnected = False self.log = logger.Logger('client') self.threadRecv = None self.timerConnect = QTimer(self) self.timerConnect.timeout.connect(self.connect_) parent.updated.connect(self.slotUpdated) def state(self): return self._state def connect_(self): try: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect((socket.gethostname(), cst.PORT)) self._isConnected = True self.timerConnect.stop() self.threadRecv = ThreadRecv(self.socket, self.log) self.threadRecv.receivedMessage.connect(self.slotMessage) self.threadRecv.start() self.log.info('client connected') self.send('send-state') except: self._isConnected = False self.timerConnect.start(100) def slotMessage(self, msg): self.log.recv(msg) if msg == 'socket-closed': self._isConnected = False self.timerConnect.start(100) self.serverClosed.emit() else: self.messageReceived.emit(msg) def send(self, msg): if self._isConnected: try: self.socket.send(msg) self.log.send(msg) except socket.error, msg: self.log.warning('sending failed: %s', msg)
def gui_execute(plasm): if HAS_GUI: # Create a Qt application app = QApplication(sys.argv) # Create and show the form form = DynamicReconfigureForm(plasm) timer = QTimer(form) timer.timeout.connect(form.exec_one) timer.start() form.show() # Run the main Qt loop return app.exec_() else: print >> sys.stderr, "Could not import PySide. Please install python-pyside." sys.exit(1)
class Timer(QObject): onTimer=None def __init__(self, interval): super(Timer, self).__init__() self.timer = QTimer(self) self.timer.timeout.connect(self.handleTimer) self.timer.start(interval) def stop(self): self.timer.stop() @Slot() def handleTimer(self): if self.onTimer: self.onTimer()
class WidgetLed(QWidget): def __init__(self, parent, colour='#000000'): QWidget.__init__(self, parent) self._colour = QColor(colour) self.setMinimumSize(20, 20) self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self._lit = False self._timer = QTimer(self) self._timer.setInterval(200) self._timer.timeout.connect(self.__flash_off) def paintEvent(self, event): painter = QPainter() painter.begin(self) colour = self._colour if not self._lit: colour = self._colour.darker(300) painter.setPen(QPen(Qt.black, 1)) painter.setBrush(QBrush(colour)) rect = event.rect() radius = min(rect.width(), rect.height()) / 3 painter.drawEllipse(rect.center(), radius, radius) painter.end() def __flash_off(self): self._timer.stop() self._lit = False self.repaint() def flash(self): self._lit = True self._timer.start() self.repaint() def light(self, on): self._timer.stop() self._lit = on self.repaint() def set_colour(self, colour): self._colour = QColor(colour)
def open(self, url, timeout=60): """Wait for download to complete and return result""" loop = QEventLoop() timer = QTimer() timer.setSingleShot(True) timer.timeout.connect(loop.quit) self.loadFinished.connect(loop.quit) self.load(QUrl(url)) timer.start(timeout * 1000) loop.exec_() # delay here until download finished if timer.isActive(): # downloaded successfully timer.stop() return self.html() else: # timed out print 'Request timed out:', url