def sleep(self, ms): startTime = QTime.currentTime() while True: QApplication.processEvents(QEventLoop.AllEvents, 25) if startTime.msecsTo(QTime.currentTime()) > ms: break usleep(0.005)
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) uic.loadUi('mainwindow.ui', self) self.setWindowTitle('Merlins AFM sketching tool') self.setGeometry(500,100,1200,1000) self.plotFrame = PlotFrame() self.plotSplitter.addWidget(self.plotFrame) # self.splitter.setStretch(1,1) self.splitter.setStretchFactor(1,1) # self.tree_splitter.set self.show() # Set delegate self.tree_file.setItemDelegateForColumn(2,DoubleSpinBoxDelegate(self)) self.tree_file.setItemDelegateForColumn(4,DoubleSpinBoxDelegate(self)) self.settings = {} self.settings['measure'] = {} self.settings['plot'] = {} self.settings['measure']['time'] = QTime() self.s_time = str(QDate.currentDate().toString('yyyy-MM-dd_') + QTime.currentTime().toString('HH-mm-ss')) self.timer = QTime.currentTime() self.nextPosition = np.array([np.nan,np.nan]) self.sketching = False self.outDir = 'U:/' self.afmImageFolder = 'D:/lithography/afmImages/' self.storeFolder = 'D:/lithography/sketches/' + self.s_time + '/' self.sketchSubFolder = './' print '' print '' self.addToolbars() self.init_stores() self.newstores = False self.init_sketching() self.init_measurement() self.tree_settings.hide() # # Tree view # self.set_model = SetTreeModel(headers = ['Parameter', 'Value', 'type'], data = self.settings) # self.tree_settings.setModel(self.set_model) # self.tree_settings.setAlternatingRowColors(True) # self.tree_settings.setSortingEnabled(True) # self.tree_settings.setHeaderHidden(False) # self.tree_settings.expandAll() # for column in range(self.set_model.columnCount()): # self.tree_settings.resizeColumnToContents(column) # QtCore.QObject.connect(self.set_model, QtCore.SIGNAL('itemChanged(QModelIndex)'), self.test) # QtCore.QObject.connect(self.tree_settings, QtCore.SIGNAL('valueChanged(QModelIndex)'), self.test) self.log('log', 'init')
def addX(self,a): self.Xresult = [] self.Xindex = a if self.isProcess==False: self.dlineEdit_X.setText("X : " + str(self.df.columns[self.Xindex + 6])) self.Xresult = np.array(self.df[self.df.columns[self.Xindex + 6]]) if self.df.columns[self.Xindex + 6] == "Date": for tab in range(len(self.Xresult)): tempdate=QDate.fromString(self.Xresult[tab],"yy-MM-dd") tempdate.setYMD(tempdate.year()+100,tempdate.month(),tempdate.day()) self.Xresult[tab] =tempdate.toPyDate() elif self.df.columns[self.Xindex + 6] == "Time": for tab in range(len(self.Xresult)): self.Xresult[tab] = QTime.fromString(self.Xresult[tab]).toPyTime() #self.Xresult[tab]=np.datetime_as_string(self.Xresult[tab]) else: pass else: self.dlineEdit_X.setText("X : " + str(self.ts1.columns[0])) tempx=[] for tab in xrange(len(self.ts1[self.ts1.columns[0]])): #print self.ts1[self.ts1.columns[0]][0] #print type(self.ts1[self.ts1.columns[0]][0]) (val1,val2)=str(self.ts1[self.ts1.columns[0]][tab]).split(' ',1) tempx.append( QTime.fromString(val2).toPyTime()) self.Xresult = np.array(tempx)
def addX(self, a): self.Xresult = [] self.Xindex = a if self.isProcess == False: self.dlineEdit_X.setText("X : " + str(self.df.columns[self.Xindex + 6])) self.Xresult = np.array(self.df[self.df.columns[self.Xindex + 6]]) if self.df.columns[self.Xindex + 6] == "Date": for tab in range(len(self.Xresult)): tempdate = QDate.fromString(self.Xresult[tab], "yy-MM-dd") tempdate.setYMD(tempdate.year() + 100, tempdate.month(), tempdate.day()) self.Xresult[tab] = tempdate.toPyDate() elif self.df.columns[self.Xindex + 6] == "Time": for tab in range(len(self.Xresult)): self.Xresult[tab] = QTime.fromString( self.Xresult[tab]).toPyTime() #self.Xresult[tab]=np.datetime_as_string(self.Xresult[tab]) else: pass else: self.dlineEdit_X.setText("X : " + str(self.ts1.columns[0])) tempx = [] for tab in xrange(len(self.ts1[self.ts1.columns[0]])): #print self.ts1[self.ts1.columns[0]][0] #print type(self.ts1[self.ts1.columns[0]][0]) (val1, val2) = str(self.ts1[self.ts1.columns[0]][tab]).split(' ', 1) tempx.append(QTime.fromString(val2).toPyTime()) self.Xresult = np.array(tempx)
def run(self): time = QTime() eventLoop = QEventLoop() self.m_bStop = False # log.debug("Запускаем поток") #if not self.initThread(): #return while not self.m_bStop: self.m_nTactCounter += 1 # Добавить обнуление при переполнении time.start() eventLoop.processEvents() if not self.workThread(): self.m_bStop = True return workTime = time.elapsed() if 0 <= workTime < self.m_nTact: self.msleep(self.m_nTact - workTime) else: self.msleep(0) eventLoop.processEvents() self.exitThread()
def __init__(self, db, sql, parent=None): self.db = db.connector t = QTime() t.start() c = self.db._execute(None, unicode(sql)) self._secs = t.elapsed() / 1000.0 del t self._affectedRows = 0 data = [] header = self.db._get_cursor_columns(c) if header is None: header = [] try: if len(header) > 0: data = self.db._fetchall(c) self._affectedRows = c.rowcount except DbError: # nothing to fetch! data = [] header = [] BaseTableModel.__init__(self, header, data, parent) # commit before closing the cursor to make sure that the changes are stored self.db._commit() c.close() del c
def _import(self, attr_type, attr): """ Your attribute in self.cfg has the same name as the Qt widget controlling it Supported attr_type: * 'bool' for booleans * 'string' for string, unicode... <--> QString in lineEdit * 'time' for time in seconds <--> QTime in timeEdit """ value = getattr(self._cfg, attr) control = getattr(self, attr) if attr_type == 'bool': if value: check_state = Qt.Checked else: check_state = Qt.Unchecked control.setChecked(check_state) elif attr_type == 'string': if isinstance(control, QLineEdit): method = control.setText elif isinstance(control, QPlainTextEdit): method = control.setPlainText method(value) elif attr_type == 'time': time = QTime(0, 0, 0, 0) control.setTime(time.addSecs(value))
def main(): if settings.get('log:errors'): log_filename = settings.get('log:filename') if log_filename: try: log_file = open(log_filename, "w") print('Redirecting stderr/stdout... to %s' % log_filename) sys.stderr = log_file sys.stdout = log_file except IOError: print "Lector could not open log file '%s'!\n" % log_filename \ + " Redirecting will not work." else: print "Log file is not set. Pleaase set it in settings." app = QApplication(sys.argv) opts = [str(arg) for arg in app.arguments()[1:]] if '--no-scanner' in opts: scanner = False else: scanner = True qsrand(QTime(0, 0, 0).secsTo(QTime.currentTime())) locale = settings.get('ui:lang') if not locale: locale = QLocale.system().name() qtTranslator = QTranslator() if qtTranslator.load(":/translations/ts/lector_" + locale, 'ts'): app.installTranslator(qtTranslator) window = Window(scanner) window.show() app.exec_()
def _initInputUI(self, layout): self.setWindowTitle(self._title) messageLabel = QLabel(self._message, self) messageLabel.setWordWrap(True) layout.addWidget(messageLabel) inputWidget = QWidget(self) inputLayout = QHBoxLayout(inputWidget) inputLayout.setContentsMargins(0, 0, 0, 0) if type(self._initialBegin) != QTime: initialBegin = QTime.fromString(self._initialBegin, lunch_settings.LUNCH_TIME_FORMAT_QT) if type(self._initialEnd) != QTime: initialEnd = QTime.fromString(self._initialEnd, lunch_settings.LUNCH_TIME_FORMAT_QT) inputLayout.addWidget(QLabel("From", self)) self.beginEdit = QTimeEdit(self) self.beginEdit.setDisplayFormat("HH:mm") self.beginEdit.setTime(initialBegin) inputLayout.addWidget(self.beginEdit) inputLayout.addWidget(QLabel("to", self)) self.endEdit = QTimeEdit(self) self.endEdit.setDisplayFormat("HH:mm") self.endEdit.setTime(initialEnd) inputLayout.addWidget(self.endEdit) layout.addWidget(inputWidget, 0, Qt.AlignLeft)
def toQDateTime(dt): if isinstance(dt, datetime.date): return QDateTime(Serializeable.toQDate(dt), QTime()) elif isinstance(dt, datetime.datetime): return QDateTime(Serializeable.toQDate(dt), QTime(dt.hour, dt.minute, dt.second)) return QDateTime()
def testDateTimeTypes(self): vl = QgsVectorLayer( '%s table="qgis_test"."date_times" sql=' % (self.dbconn), "testdatetimes", "postgres") assert (vl.isValid()) fields = vl.dataProvider().fields() self.assertEqual( fields.at(fields.indexFromName('date_field')).type(), QVariant.Date) self.assertEqual( fields.at(fields.indexFromName('time_field')).type(), QVariant.Time) self.assertEqual( fields.at(fields.indexFromName('datetime_field')).type(), QVariant.DateTime) f = vl.getFeatures(QgsFeatureRequest()).next() date_idx = vl.fieldNameIndex('date_field') assert isinstance(f.attributes()[date_idx], QDate) self.assertEqual(f.attributes()[date_idx], QDate(2004, 3, 4)) time_idx = vl.fieldNameIndex('time_field') assert isinstance(f.attributes()[time_idx], QTime) self.assertEqual(f.attributes()[time_idx], QTime(13, 41, 52)) datetime_idx = vl.fieldNameIndex('datetime_field') assert isinstance(f.attributes()[datetime_idx], QDateTime) self.assertEqual(f.attributes()[datetime_idx], QDateTime(QDate(2004, 3, 4), QTime(13, 41, 52)))
def handleMouseMove(self, event): event.ignore() if not (event.buttons() & Qt.LeftButton): return if event in self.d.ignoreList: self.d.ignoreList.remove(event) return if self.d.state in (FlickablePrivate.Pressed, FlickablePrivate.Stop): delta = event.pos() - self.d.pressPos if delta.x() > self.d.threshold or delta.x() < -self.d.threshold or \ delta.y() > self.d.threshold or delta.y() < -self.d.threshold: self.d.timeStamp = QTime.currentTime() self.d.state = FlickablePrivate.ManualScroll self.d.delta = QPoint(0, 0) self.d.pressPos = QPoint(event.pos()) #event.accept() elif self.d.state == FlickablePrivate.ManualScroll: event.accept() delta = event.pos() - self.d.pressPos self.setScrollOffset(self.d.offset - delta) if self.d.timeStamp.elapsed() > 50: self.d.timeStamp = QTime.currentTime() self.d.speed = delta - self.d.delta self.d.delta = delta print("Delta", self.d.delta) self.emit(SIGNAL("scroll_to"), self.d.pressPos, self.d.delta)
def __init__(self, ganttWidget): super(XGanttWidgetItem, self).__init__() # set default properties self.setFixedHeight(ganttWidget.cellHeight()) for i in range(1, 20): self.setTextAlignment(i, Qt.AlignCenter) # define custom properties self._blockedAdjustments = {} self._viewItem = self.createViewItem() self._dateStart = QDate.currentDate() self._dateEnd = QDate.currentDate() self._allDay = True self._timeStart = QTime(0, 0, 0) self._timeEnd = QTime(23, 59, 59) self._name = "NONE" self._properties = {} self._itemStyle = XGanttWidgetItem.ItemStyle.Normal self._useGroupStyleWithChildren = True self._dependencies = {} self._reverseDependencies = {} self._dbEntry = None self._workdays = 0 self._ganttWidget = ganttWidget #self._calculateWeekdays = 0 #self._dbDepartmentAssignment = '' self.setPrivelages()
class MyApplication(QtGui.QApplication): def __init__(self, *args, **kwargs): super(MyApplication, self).__init__(*args, **kwargs) self.t = QTime() self.t.start() maxlen = 200 self.data_x = deque(maxlen=maxlen) self.data_y = deque(maxlen=maxlen) self.win = pg.GraphicsWindow(title="Basic plotting examples") self.win.resize(1000, 600) tai = TimeAxisItem(orientation='bottom') self.plot = self.win.addPlot( title='Timed data', axisItems={'bottom': TimeAxisItem(orientation='bottom')}) #self.plot.setYRange(0, 150) self.curve = self.plot.plot() self.tmr = QTimer() self.tmr.timeout.connect(self.update) self.tmr.start(100) self.y = 100 def update(self): #self.data.append({'x': self.t.elapsed(), 'y': np.random.randint(0, 100)}) x = now_timestamp() self.y = self.y + np.random.uniform(-1, 1) self.data_x.append(x) self.data_y.append(self.y) self.curve.setData(x=list(self.data_x), y=list(self.data_y))
class MyApplication(QtGui.QApplication): def __init__(self, *args, **kwargs): super(MyApplication, self).__init__(*args, **kwargs) self.t = QTime() self.t.start() self.data = deque(maxlen=20) self.win = pg.GraphicsWindow(title="Basic plotting examples") self.win.resize(1000, 600) self.plot = self.win.addPlot( title='Timed data', axisItems={'bottom': TimeAxisItem(orientation='bottom')}) self.curve = self.plot.plot() self.tmr = QTimer() self.tmr.timeout.connect(self.update) self.tmr.start(1000) def update(self): self.data.append({ 'x': self.t.elapsed() + 1323587062, 'y': np.random.randint(0, 100) }) x = [item['x'] for item in self.data] y = [item['y'] for item in self.data] self.curve.setData(x=x, y=y)
def Init(self, song, data, bitrate): """ Initialize with song. :param song: input song :type song: list :param data: input data from wav file :type data: numpy.array :param bitrate: bitrate of input file :type bitrate: int """ self.song = copy.deepcopy(song) self.index = self.song[0] self.name = self.song[1] self.ui.saveButton.setText(self.name) self.data = data self.resetData = copy.deepcopy(song) self.bitrate = bitrate h, m, s = EditForm.ParseTime(self.song[2]) self.ui.startTime.setTime(QTime(h, m, s)) h, m, s = EditForm.ParseTime(self.song[3]) self.ui.endTime.setTime(QTime(h, m, s)) end_time = datetime.timedelta(seconds=int(self.data.shape[0] / self.bitrate)) h, m, s = EditForm.ParseTime(str(end_time)) self.ui.endTime.setMaximumTime(QTime(h, m, s))
def testDateTimeWriteShapefile(self): """Check writing date and time fields to an ESRI shapefile.""" ml = QgsVectorLayer( ('Point?crs=epsg:4326&field=id:int&' 'field=date_f:date&field=time_f:time&field=dt_f:datetime'), 'test', 'memory') assert ml is not None, 'Provider not initialised' assert ml.isValid(), 'Source layer not valid' provider = ml.dataProvider() assert provider is not None ft = QgsFeature() ft.setGeometry(QgsGeometry.fromPoint(QgsPoint(10, 10))) ft.setAttributes([ 1, QDate(2014, 3, 5), QTime(13, 45, 22), QDateTime(QDate(2014, 3, 5), QTime(13, 45, 22)) ]) res, features = provider.addFeatures([ft]) assert res assert len(features) > 0 dest_file_name = os.path.join(str(QDir.tempPath()), 'datetime.shp') print(dest_file_name) crs = QgsCoordinateReferenceSystem() crs.createFromId(4326, QgsCoordinateReferenceSystem.EpsgCrsId) write_result = QgsVectorFileWriter.writeAsVectorFormat( ml, dest_file_name, 'utf-8', crs, 'ESRI Shapefile') self.assertEqual(write_result, QgsVectorFileWriter.NoError) # Open result and check created_layer = QgsVectorLayer(u'{}|layerid=0'.format(dest_file_name), u'test', u'ogr') fields = created_layer.dataProvider().fields() self.assertEqual( fields.at(fields.indexFromName('date_f')).type(), QVariant.Date) #shapefiles do not support time types, result should be string self.assertEqual( fields.at(fields.indexFromName('time_f')).type(), QVariant.String) #shapefiles do not support datetime types, result should be date self.assertEqual( fields.at(fields.indexFromName('dt_f')).type(), QVariant.Date) f = created_layer.getFeatures(QgsFeatureRequest()).next() date_idx = created_layer.fieldNameIndex('date_f') assert isinstance(f.attributes()[date_idx], QDate) self.assertEqual(f.attributes()[date_idx], QDate(2014, 3, 5)) time_idx = created_layer.fieldNameIndex('time_f') #shapefiles do not support time types assert isinstance(f.attributes()[time_idx], basestring) self.assertEqual(f.attributes()[time_idx], '13:45:22') #shapefiles do not support datetime types datetime_idx = created_layer.fieldNameIndex('dt_f') assert isinstance(f.attributes()[datetime_idx], QDate) self.assertEqual(f.attributes()[datetime_idx], QDate(2014, 3, 5))
def __init__(self): QThread.__init__(self) self.running = False self.scrollingTimer = QTimer() self.scrollingTimer.setSingleShot(True) self.scrollingTimer.timeout.connect(self.scrollEventStop) self.time = QTime() self.counter = 0
class OpenAnt(QApplication): def __init__(self): QApplication.__init__(self, sys.argv) # Set the default background color to a darker grey. self.setPalette( QPalette(self.palette().button().color(), QColor(192, 192, 192))) self.window = MainWindow() self.window.show() self.window.start() self.window.setWindowTitle('OpenAnt') # Game timer, used in the gameloop FPS calculations. self.game_timer = QTime() self.game_timer.start() # Draw map, set view to ground. self.map = Map() Globals.view = self.map.generateMap() self.map.spawnAnts() # Start the main loop. self.gameLoop() def gameLoop(self): TICKS_PER_SECOND = 20 SKIP_TICKS = 1000 / TICKS_PER_SECOND MAX_FRAMESKIP = 5 next_game_tick = self.getTickCount() Globals.game_is_running = True while Globals.game_is_running: loops = 0 while self.getTickCount( ) > next_game_tick and loops < MAX_FRAMESKIP: self.updateGame() next_game_tick += SKIP_TICKS loops += 1 interpolation = float(self.getTickCount() + SKIP_TICKS - next_game_tick) / float(SKIP_TICKS) self.updateDisplay(interpolation) def updateDisplay(self, interpolation): #lerp away if not 'nolerp' in sys.argv: if self.map.yellowAnt.moving: self.map.yellowAnt.lerpMoveSimple(interpolation) Globals.glwidget.updateGL() self.processEvents() # Let Qt process its events. def getTickCount(self): return self.game_timer.elapsed() def updateGame(self): self.map.update()
class AutoSaver(QObject): """ Class implementing the auto saver. """ AUTOSAVE_IN = 1000 * 3 MAXWAIT = 1000 * 15 def __init__(self, parent, save): """ Constructor @param parent reference to the parent object (QObject) @param save slot to be called to perform the save operation """ QObject.__init__(self, parent) if parent is None: raise RuntimeError("AutoSaver: parent must not be None.") self.__save = save self.__timer = QBasicTimer() self.__firstChange = QTime() def changeOccurred(self): """ Public slot handling a change. """ if self.__firstChange.isNull(): self.__firstChange.start() if self.__firstChange.elapsed() > self.MAXWAIT: self.saveIfNeccessary() else: self.__timer.start(self.AUTOSAVE_IN, self) def timerEvent(self, evt): """ Protected method handling timer events. @param evt reference to the timer event (QTimerEvent) """ if evt.timerId() == self.__timer.timerId(): self.saveIfNeccessary() else: QObject.timerEvent(self, evt) def saveIfNeccessary(self): """ Public method to activate the save operation. """ if not self.__timer.isActive(): return self.__timer.stop() self.__firstChange = QTime() self.__save()
def writeDataToSocket(self): hour = "%02d"%(QTime.currentTime().hour()) minute = "%02d"%(QTime.currentTime().minute()) second = "%02d"%(QTime.currentTime().second()) if self.teacherIp != "": ip = self.teacherIp name = "client-" + self.clientuuid data = name + "#" + hour + minute + second self.udpSocket.writeDatagram(data, QHostAddress(ip), self.porttwo)
def monitorDataInit(myData, csvPath): with open(csvPath, "r") as f: for line in f: try: resultados = map(int, line.split(',')) t_ms = QTime().msecsTo(QTime(resultados[3], resultados[4], resultados[5])) myData.update(t_ms, resultados[6], resultados[7], resultados[8], resultados[9], resultados[10]) except: pass
def HandleResetButton(self): """ Handle reset button. Resets to default configuration. """ self.ui.saveButton.setText(self.resetData[1]) h, m, s = EditForm.ParseTime(self.resetData[2]) self.ui.startTime.setTime(QTime(h, m, s)) h, m, s = EditForm.ParseTime(self.resetData[3]) self.ui.endTime.setTime(QTime(h, m, s))
class OpenAnt(QApplication): def __init__(self): QApplication.__init__(self, sys.argv) # Set the default background color to a darker grey. self.setPalette(QPalette(self.palette().button().color(), QColor(192, 192, 192))) self.window = MainWindow() self.window.show() self.window.start() self.window.setWindowTitle('OpenAnt') # Game timer, used in the gameloop FPS calculations. self.game_timer = QTime() self.game_timer.start() # Draw map, set view to ground. self.map = Map() Globals.view = self.map.generateMap() self.map.spawnAnts() # Start the main loop. self.gameLoop() def gameLoop(self): TICKS_PER_SECOND = 20 SKIP_TICKS = 1000 / TICKS_PER_SECOND MAX_FRAMESKIP = 5 next_game_tick = self.getTickCount() Globals.game_is_running = True while Globals.game_is_running: loops = 0 while self.getTickCount() > next_game_tick and loops < MAX_FRAMESKIP: self.updateGame() next_game_tick += SKIP_TICKS loops += 1 interpolation = float(self.getTickCount() + SKIP_TICKS - next_game_tick) / float(SKIP_TICKS) self.updateDisplay(interpolation) def updateDisplay(self, interpolation): #lerp away if not 'nolerp' in sys.argv: if self.map.yellowAnt.moving: self.map.yellowAnt.lerpMoveSimple(interpolation) Globals.glwidget.updateGL() self.processEvents() # Let Qt process its events. def getTickCount(self): return self.game_timer.elapsed() def updateGame(self): self.map.update()
def __init__(self, parent=None, testing=False, participantId=None): # Initialize object using ui_addParticipant super(EditParticipantDialog, self).__init__(parent) self.ui = Ui_AddParticipantDialog() self.ui.setupUi(self) # Initialize class variables self.testing = testing if participantId is None: QMessageBox.critical(self, 'Invalid Participant', "An invalid participant was chosen.", QMessageBox.Ok) self.reject() # if participantId[0] == 's': # self.participantId = participantId[1:] # else: # self.participantId = participantId self.participantId = participantId self.participant = dbInteractionInstance.getParticipantFromId(participantId) # Set up the contact self.contactId = self.participant.contact if self.contactId: c = dbInteractionInstance.getTeacherFromId(self.contactId) if c is not None: self.ui.contactPersonLineEdit.setText("{0} {1}".format(c.first, c.last)) # Initialize ui with variables self.ui.addParticipantBtn.setText("&Update Participant") self.setWindowTitle("Edit Participant") self.ui.firstNameLineEdit.setText(self.participant.first) self.ui.lastNameLineEdit.setText(self.participant.last) self.ui.addressLineEdit.setText(self.participant.address) self.ui.cityLineEdit.setText(self.participant.city) self.ui.postalCodeLineEdit.setText(humanPostalCodeFormat(self.participant.postal)) self.ui.homePhoneLineEdit.setText(humanPhoneNumberFormat(self.participant.home)) self.ui.cellPhoneLineEdit.setText(humanPhoneNumberFormat(self.participant.cell)) self.ui.emailLineEdit.setText(self.participant.email) self.ui.dateOfBirthDateEdit.setDate(QDate.fromString(self.participant.dob, "yyyy-MM-dd")) self.ui.ageLabel.setText("Age as of Jan. 1 {0}".format(QDate.currentDate().year())) self.ui.schoolAttendingLineEdit.setText(self.participant.schoolAttending) self.ui.parentLineEdit.setText(self.participant.parent) self.ui.schoolGradeLineEdit.setText(self.participant.schoolGrade) self.ui.groupNameLineEdit.setText(self.participant.groupName) self.ui.numberParticipantsLineEdit.setText(self.participant.numberParticipants) self.ui.schoolGradeLineEdit.setText(self.participant.schoolGrade) self.ui.averageAgeLineEdit.setText(self.participant.averageAge) if self.participant.earliestPerformanceTime != "": self.ui.timeConstraintsGroupBox.setChecked(True) self.ui.earliestPerformanceTimeTimeEdit.setTime(QTime.fromString(self.participant.earliestPerformanceTime, "h:mm A")) self.ui.latestPerformanceTimeTimeEdit.setTime(QTime.fromString(self.participant.latestPerformanceTime, "h:mm A")) self.ui.participantsTextEdit.setText(self.participant.participants) # Set the age display self.dob_changed() # Make the buttons do things self.connectSlots()
def timeval_to_label(self, val): """ Convert the tracks play-length into a format suitable for label widget and set """ trk_time = self.audio_object.totalTime() # FIXME: this is wrong n the transistion period trk_time = QTime(0, (trk_time / 60000) % 60, (trk_time / 1000) % 60) t_now = QTime(0, (val / 60000) % 60, (val / 1000) % 60) self.ui.progress_lbl.setText("%s | %s" % (t_now.toString('mm:ss'), trk_time.toString("mm:ss")))
def forceTime(val): if isinstance(val, QVariant): return val.toTime() if isinstance(val, QTime): return val if isinstance(val, QDateTime): return val.time() if val is None: return QTime() return QTime(val)
def __init__(self, parent=None): AbstractKeyboardMonitor.__init__(self, parent) self._keyboard_was_active = False self._old_keymap = array(b'B', b'\0' * 32) self._keyboard_timer = QTimer(self) self._keyboard_timer.timeout.connect(self._check_keyboard_activity) self._keyboard_timer.setInterval(self.DEFAULT_POLLDELAY) self._activity = QTime() self._keys_to_ignore = self.IGNORE_NO_KEYS self._keymap_mask = self._setup_mask() self._idle_time = self.DEFAULT_IDLETIME
def changerTempsChrono(self,nvTemps): """affichage du temps sous la forme h:mm:ss:ms dans un bouton""" temps0 = QTime(0, 0, 0) ## On augemente la précision, on ajoute les milisecondes au lieu des secondes ##### temps = temps0.addMSecs(nvTemps*self.echelle) ########################################################################################################### mn = str(temps.minute()).zfill(2) s = str(temps.second()).zfill(2) ms = str(temps.msec()).zfill(3) chrono = str(temps.hour())+':'+mn+':'+s+':'+ms self.tempsChrono.num = chrono self.tempsChrono.repaint()
def __new__(cls, value): """ Helper. Takes a date like value and attempts to convert it to a simple QTime type. """ if isinstance(value, QTime): return value if isinstance(value, datetime): return QTime.__new__(value.hour, value.minute) if isinstance(value, unicode): return QTime.__new__(parse(value).hour, parse(value).minute) if isinstance(value, str): return QTime.__new__(parse(value).hour, parse(value).minute)
def __init__(self, parent=None): super(AnimationFrame, self).__init__(parent) self.parent = parent self.animationUI = Animation_menu.Ui_dockAnimationWidget() self.animationUI.setupUi(self) if iface and not iface.mainWindow().restoreDockWidget(self): iface.mainWindow().addDockWidget(Qt.RightDockWidgetArea, self) self.mapObject = None self.addLayerMenu = None self.animationUI.progressBar.hide() self.animationUI.labelInfo.setText("") self.animationUI.animationSlider.sliderMoved.connect( self.onUserMovesSlider) #We disable controller to avoid accidental inputs self.animationUI.labelInfo.setEnabled(True) #self.animationUI.animationSlider.setEnabled(False) #self.animationUI.playButton.setEnabled(False) self.animationUI.cancelButton.hide() self.animationUI.addWCSButton.clicked.connect( self._onAddWCSLayerButtonClicked) self.animationUI.addWMSButton.clicked.connect( self._onAddWMSLayerButtonClicked) self.animationUI.addOtherButton.clicked.connect( self._onAddOtherLayerButtonClicked) self.animationUI.removeButton.clicked.connect( self._removeLayerFromAnimation) self.animationUI.cancelButton.clicked.connect(self._onCancelRequested) self.animationUI.playButton.clicked.connect(self.play) self.animationUI.buttonLoad.clicked.connect(self.prepareAnimation) self.layerInfoList = [] self.animationUI.frameRateSpinbox.valueChanged.connect( self._newFrameRateSelected) self.animationUI.timeFrameVariation.timeChanged.connect( self._timeVariationChanged) self.animationUI.daysFrameVariation.valueChanged.connect( self._timeVariationChanged) self.animationUI.timeTolerance.timeChanged.connect( self._toleranceChanged) self.animationUI.daysTolerance.valueChanged.connect( self._toleranceChanged) self.initController() self.animationUI.timeFrameVariation.setTime(QTime(1, 0, 0)) self._timeVariationChanged(QTime(1, 0, 0)) iface.addDockWidget(Qt.LeftDockWidgetArea, self)
def setTimeEnd(self, timeEnd): """ Sets the end time for this item. This method will only affect the start time if the end time is set to occur before its start, in which case it will set the start time as 60 minutes before. Otherwise, this method will scale the duration of the event. :param timeEnd | <QTime> """ timeEnd = QTime(timeEnd) if (timeEnd < self._timeStart): self._timeStart = timeEnd.addSecs(-60 * 60) self._timeEnd = timeEnd self.markForRebuild()
def run(self): while not self.quit: try: self.error.emit("can't not open %s,error code:%d" % ("com3", 12345)) self.timeout.emit("Wait write response timeout %s" % (QTime.currentTime().toString())) self.request.emit("RequesData: %s" % (QTime.currentTime().toString())) except TypeError as e: print('Got Error', e) finally: print("Continus working ...") time.sleep(0.5)
def setTimeEnd( self, timeEnd ): """ Sets the end time for this item. This method will only affect the start time if the end time is set to occur before its start, in which case it will set the start time as 60 minutes before. Otherwise, this method will scale the duration of the event. :param timeEnd | <QTime> """ timeEnd = QTime(timeEnd) if ( timeEnd < self._timeStart ): self._timeStart = timeEnd.addSecs(-60 * 60) self._timeEnd = timeEnd self.markForRebuild()
def mostrarTiempo(self): """Controla el aumento de los segundos""" self.nuevoTiempo = QTime() self.segundos = self.segundos + 1 self.nuevoTiempo = self.tiempo.addSecs(self.segundos) self.cronometro = self.nuevoTiempo.toString("hh:mm:ss") self.ui.contTiempo.display(self.cronometro)
def main(): if settings.get('log:errors'): log_filename = settings.get('log:filename') if log_filename: try: log_file = open(log_filename,"w") print ('Redirecting stderr/stdout... to %s' % log_filename) sys.stderr = log_file sys.stdout = log_file except IOError: print "Lector could not open log file '%s'!\n" % log_filename \ + " Redirecting will not work." else: print "Log file is not set. Pleaase set it in settings." app = QApplication(sys.argv) opts = [str(arg) for arg in app.arguments()[1:]] if '--no-scanner' in opts: scanner = False else: scanner = True qsrand(QTime(0, 0, 0).secsTo(QTime.currentTime())) locale = settings.get('ui:lang') if not locale: locale = QLocale.system().name() qtTranslator = QTranslator() if qtTranslator.load(":/translations/ts/lector_" + locale, 'ts'): app.installTranslator(qtTranslator) window = Window(scanner) window.show() app.exec_()
def InitializeDates(phases, due_date, duration): currentDate = due_date for phase in phases[::-1]: #enddate = currentDate-1 phase._enddate = currentDate - timedelta(days=1) #iterate through phases until there's a match if str(phase._idphases) in sharedDB.myPhases: myPhase = sharedDB.myPhases[str(phase._idphases)] #multiply duration(minutes) by _manHoursToMinuteRatio / work hours in a day daysGoal = math.ceil(QTime().secsTo(duration) / 60.0 * myPhase._manHoursToMinuteRatio / 8.0) #print daysGoal numdays = 0 #while numdays < work days while numdays < daysGoal: #subtract day from currentDate currentDate = currentDate - timedelta(days=1) #if workday if currentDate.weekday() < 5: numdays = numdays + 1 #phase start date = currentdate phase._startdate = currentDate return phases
def setTimeStart( self, timeStart ): """ Sets the start time for this item. This will automatically push the end time to match the length for this item. So if the item starts at 11a and ends on 1p, and the start time is changed to 12p the end time will change to 2p. To affect the length of the item, use either setLength, or setTimeEnd. :param timeStart | <QDate> """ timeStart = QTime(timeStart) length = self.length() # in minutes self._timeStart = timeStart self._timeEnd = timeStart.addSecs(length * 60) self.markForRebuild()
def tablevote_clicked(self, row, column): vote_place = self.ui.tableWidget.item(row, 0).text() vote_time = self.ui.tableWidget.item(row, 1).text() self.ui.comboBox.setCurrentIndex(self.ui.comboBox.findText(vote_place)) self.ui.timeEdit.setTime(QTime.fromString(vote_time, "HH:mm")) self.send_vote(vote_place, vote_time)
def __init__(self, parent=None): """ Class constructor. """ super(EditForm, self).__init__(parent) # UI setup self.ui = Ui_Form() self.ui.setupUi(self) self.ui.saveButton.clicked.connect(self.HandleSaveButton) self.ui.okButton.clicked.connect(self.HandleOkButton) self.ui.resetButton.clicked.connect(self.HandleResetButton) self.ui.deleteButton.clicked.connect(self.HandleDeleteButton) self.ui.musicButton.clicked.connect(self.HandleMusicButton) self.ui.saveFileButton.clicked.connect(self.HandleSaveFileButton) self.ui.startTime.setDisplayFormat('hh:mm:ss') self.ui.endTime.setDisplayFormat('hh:mm:ss') self.ui.startTime.setMinimumTime(QTime(0, 0, 0)) # Class members self.song = None self.data = None self.resetData = None self.bitrate = None self.name = None self.result = None self.index = None self.isPlaying = False
def formatValue(self, type_, v, upper): util = FLUtil.FLUtil() if self.driverName == "PGSql": s = None # TODO: psycopg2.mogrify ??? if type_ == "bool" or type_ == "unlock": s = text2bool(v) elif type_ == "date": s = "'%s'" % util.dateDMAtoAMD(v) elif type_ == "time": time = QTime(s) s = "'%s'" % time elif type_ == "uint" or type_ == "int" or type_ == "double" or type_ == "serial": s = v else: if upper == True and type_ == "string": v = v.upper() s = "'%s'" % v #print ("PNSqlDriver.formatValue(%s, %s) = %s" % (type_, v, s)) return s
def setTimeStart(self, timeStart): """ Sets the start time for this item. This will automatically push the end time to match the length for this item. So if the item starts at 11a and ends on 1p, and the start time is changed to 12p the end time will change to 2p. To affect the length of the item, use either setLength, or setTimeEnd. :param timeStart | <QDate> """ timeStart = QTime(timeStart) length = self.length() # in minutes self._timeStart = timeStart self._timeEnd = timeStart.addSecs(length * 60) self.markForRebuild()
def removeZZZfromJDStime(instr): if isTimeFormatZZZ(instr): form = QString("hh:mm:ss.zzz") inqstr = QString(instr) dts = QTime.fromString(inqstr, form) newtime = dts.toString("hh:mm:ss") return newtime
def get_talks_by_room_and_time(self, room): """Returns the talks hosted in a specified room, starting from the current date and time""" current_date = QDate.currentDate().toString(1) # yyyy-mm-dd current_time = QTime.currentTime().toString() # hh:mm:ss return QtSql.QSqlQuery('''SELECT * FROM presentations WHERE Room='{}' AND Date='{}' AND StartTime >= '{}' ORDER BY StartTime ASC'''.format(room, current_date, current_time))
def load(self,filename): """Load existing game from file""" debug("loadgame...read data from saved file") debug("loadgame...loading clues") self.story.loadClues() savedData = open(filename) nextLine = savedData.readline() # Parsing saved file while (nextLine): line = nextLine.split() if (len(line) == 4 and self.loadIsValid(line)): x = int(line[0]) y = int(line[1]) numClues = int(line[2])+1 self.story._clueList = self.story._clueList[:numClues] self.story.score = int(line[3]) debug("x: " + `x` + " y: " + `y` + " numCLue: " + `len(self.story._clueList)` + \ " score is: " + `int(line[3])`) nextLine = savedData.readline() savedData.close() self.story.currClue = self.story._clueList.pop() debug("loadgame...loading initial character and places") self.character = Character((x,y), "Character", "Character") self.places.loadLoc() debug("end of load") self.places.addLoc(self.character) # FIXME if QTime and QTimer should be stored in certain way self.gameTime = QTime() #self.frameTimer = QTimer() # Create Frame Timer self.launch()
def showIP(self): self.ui.ips.clear() for i in self.h3c.listHost(): item = QtGui.QListWidgetItem(i) current_time = QTime.currentTime() self.ui.ips.addItem(item) self.ui.ips.addItem(current_time)
def saveSketch(self): self.settings['measure']['time'].elapsed() self.sketchSubFolder = QDate.currentDate().toString('yyyy-MM-dd_') + QTime.currentTime().toString('HH-mm-ss') if not os.path.exists(self.storeFolder + self.sketchSubFolder): os.makedirs(self.storeFolder + self.sketchSubFolder) data = self.sketchFile self.sketchOutDir = str(self.storeFolder + self.sketchSubFolder+'/') fname = self.sketchOutDir + 'out.txt' f = open(fname, 'w') f.write(data) f.close() try: self.plotFrame.savePlot(self.sketchOutDir+'currentSketchView.png') except: pass try: filename = sorted(os.listdir(self.afmImageFolder))[-1] shutil.copy2(self.afmImageFolder + filename,self.sketchOutDir+filename) shutil.copy2('D:/lithography/current.png',self.sketchOutDir+'currentAFMImage.png') except: pass self.log('sketch', str(self.storeFolder + self.sketchSubFolder))
def getRecord(self, record): dateTime = QDateTime(self.edtDate.date(), QTime().currentTime()) record.setValue('dateTime', dateTime) i = self.cmbSocCodes.currentIndex() socCode = forceString(self.cmbSocCodes.itemData(i)) record.setValue('socCode', socCode) pregCard = forceInt(self.edtPregCard.text()) if pregCard > 0: record.setValue('pregCard', pregCard) else: record.setNull('pregCard') getRBComboBoxValue(self.cmbFinance, record, 'finance_id') record.setValue('mkb', toVariant(self.cmbMKB.text())) getRBComboBoxValue(self.cmbDrug, record, 'formularyItem_id') getLineEditValue(self.edtDosage, record, 'dosage') getSpinBoxValue(self.spbQnt, record, 'qnt') getLineEditValue(self.edtSigna, record, 'signa') getSpinBoxValue(self.spbDuration, record, 'duration') getSpinBoxValue(self.spbNumPerDay, record, 'numPerDay') record.setValue('isVk', int(self.rbtnVkYes.isChecked())) record.setValue('printMnn', int(self.rbtnPrintMNN.isChecked())) record.setValue('percentage', int(50 if self.rbtn50proc.isChecked() else 100)) getComboBoxValue(self.cmbTerm, record, 'term') record.setValue( 'status', self.modelRecipeStatus.getCode(self.cmbStatus.currentIndex())) record.setValue('deleted', 0)
def main(): """Function, executed on start """ # create application app = QApplication (sys.argv) app.setApplicationName( "fresh-examples" ) qsrand( QTime( 0, 0, 0 ).secsTo( QTime.currentTime() ) ) pSettings.setDefaultProperties(pSettings.Properties(app.applicationName(), \ "1.0.0", pSettings.Portable)) window = MainWindow() window.setWindowTitle( app.applicationName() ) window.show() # connection app.lastWindowClosed.connect(app.quit) # start application result = app.exec_() del window return result
def __init__(self, parent=None, piece=None): # Initialize object super(PieceWidget, self).__init__(parent) self.ui = Ui_PieceWidget() self.ui.setupUi(self) self.dance() # Slightly cheater way to start the ui properly # Initialize class variables self.disciplines = {'Dance' : self.dance, # For Pythonic switch-case 'Piano' : self.piano, 'Choral' : self.choral, 'Vocal' : self.vocal, 'Instrumental' : self.instrumental, 'Band' : self.band, 'Speech' : self.speech } # Initialize ui if piece was given if piece is not None: self.ui.titleLineEdit.setText(piece['title']) self.ui.titleOfMusicalLineEdit.setText(piece['titleOfMusical']) self.ui.composerLineEdit.setText(piece['composerArranger']) time = piece['performanceTime'] if len(piece['performanceTime']) < 5: # pad with leading 0 time = '0' + time self.ui.performanceTimeEdit.setTime(QTime.fromString(time, "mm:ss"))
def setScoreTime(self): self.ui.scoretable.repaint() QApplication.processEvents() try: row = self.ui.scoretable.selectedIndexes()[0].row() scoreStruct = self.scoreInfo["scoreStructs"][row] time = scoreStruct.time # Split string into date and time time = str(time).split() date = time[0].split('-') year = str(date[0]) month = str(date[1]) day = str(date[2]) calendaradj = QDate(int(year), int(month), int(day)) self.ui.calendarWidget.setSelectedDate(calendaradj) self.ui.timeEdit.setTime(QTime(int(time[1][:2]), int(time[1][3:5]))) self.ui.startButton.setEnabled(True) # User clicked a blank cell, stop here except IndexError: self.ui.statusText.setText("Error reading selected SCORE")
def __init__(self, book=10, chapter=1, verseFrom=6, verseTo=6, parent=None): "Initialises a Game given a book, a chapter, and the verses." QWidget.__init__(self) Ui_Game.__init__(self) # User interface configuration. self.setupUi(self) # Hide some stuff self.pushButton_cheatText.setChecked(False) self.pushButton_cheatText.setVisible(False) # Strong Parser self.StrongParser = StrongParser() self._highlighter = myHighlighter(self.plainTextEdit_original, self) # Settings self._book = book self._chapter = chapter self._verseFrom = verseFrom self._verseTo = verseTo self.BibleLoader = parent.BibleLoader self._startTime = QTime.currentTime() self._testLexicalForm = parent.comboBox_testLexicalForm.currentIndex()\ == 1 self._lessThan = parent.checkBox_lessThanOccurences.isChecked() * \ int(parent.comboBox_lessThanOccurences.currentText()) self._moreThan = parent.checkBox_moreThanOccurences.isChecked() * \ int(parent.comboBox_moreThanOccurences.currentText()) self._listDefRandom = parent.comboBox_sort.currentIndex() == 0 # Internal lists self._words = [] # Words as in the text self._lexicals = [] # Lexical form of the word self._strongs = [] # Strong number self._definitions = [] # Definition self._grammars = [] # Grammatical informations self._alreadyGuessed = [] # list of words ID already guessed # Signal / Slots self.listWidget_original.itemSelectionChanged\ .connect(self._highlighter.rehighlight) self.listWidget_original.itemDoubleClicked.connect(self.guessOnList) self.listWidget_translation.itemDoubleClicked.connect(self.guessOnList) self.listWidget_guesses.itemDoubleClicked.connect(self.undoGuess) self.pushButton_guess.clicked.connect(self.testGuess) self.pushButton_undoGuess.clicked.connect(self.undoGuess) self.plainTextEdit_original.cursorPositionChanged\ .connect(self.textSelectionChanged) self.pushButton_Validate.clicked.connect(self.validate) #self.pushButton_Validate.setEnabled(False) self.listWidget_original.setSortingEnabled(False) if self._listDefRandom: self.listWidget_translation.setSortingEnabled(False) # Get the party going self.loadText()
def __init__(self): ''' Constructor ''' self.cadenaAguardar = "" self.tiempo = QTime() self.nombre = "" self.nivel = "" self.matriz = [ [ 0 for i in range(9) ] for j in range(9) ] self.solucion = [ [ 0 for i in range(9) ] for j in range(9) ]
def saveIfNeccessary(self): """ Public method to activate the save operation. """ if not self.__timer.isActive(): return self.__timer.stop() self.__firstChange = QTime() self.__save()
def time_from_string(s): s = s.strip() if not s: return None from PyQt4.QtCore import QTime f = local_time_format() tm = QTime.fromString(s, f) if not tm.isValid(): raise ParsingError() return time( tm.hour(), tm.minute(), tm.second() )
def initCronometro(self): """Inicia el contador del cronometro""" self.tiempo = QTime() self.tiempo.setHMS(0,0,0,0) self.timer = QTimer() self.connect(self.timer, SIGNAL("timeout()"),self.mostrarTiempo) self.segundos = 0 self.text = self.tiempo.toString("hh:mm:ss") self.ui.contTiempo.display(self.text) self.timer.start(1000)