def timeout(self): """ 타임아웃 이벤트가 발생하면 호출되는 메서드 """ # 어떤 타이머에 의해서 호출되었는지 확인 sender = self.sender() if self.in_processing: return # 메인 타이머 if id(sender) == id(self.timer): current_time = QTime.currentTime().toString("hh:mm:ss") # 상태바 설정 state = "" if self.kiwoom.get_connect_state() == 1: state = self.server_gubun + " 서버 연결중" else: state = "서버 미연결" self.statusbar.showMessage("현재시간: " + current_time + " | " + state) # log if self.kiwoom.msg: self.logTextEdit.append(self.kiwoom.msg) self.kiwoom.msg = "" elif id(sender) == id(self.timer_stock): automatic_order_time = QTime.currentTime().toString("hhmm") # 자동 주문 실행 # 1100은 11시 00분을 의미합니다. print("current time: %d" % int(automatic_order_time)) if self.is_automatic_order and int(automatic_order_time) >= 900 and int(automatic_order_time) <= 930: self.is_automatic_order = False self.automatic_order() self.set_automated_stocks() # 실시간 조회 타이머 else: if self.realtimeCheckBox.isChecked(): self.inquiry_balance()
def tick(self): if self.paused or not self.effect: return t = self.tickTimer.msecsTo(QTime.currentTime()) self.tickTimer = QTime.currentTime() self.effect.tick(t / 10.0)
def checkDeadDateTime(self): print(QDate.currentDate()) print(QTime.currentTime()) datetime=QDateTime(QDate.currentDate(),QTime.currentTime()) if(datetime<=self.deaddatetime): return True else: return False
def set_settings(self): if self.traffic_id: query = """SELECT Position, Data, Table_Data, Note FROM staff_worker_traffic WHERE Id = %s""" sql_traffic = my_sql.sql_select(query, (self.traffic_id, )) if "mysql.connector.errors" in str(type(sql_traffic)): QMessageBox.critical(self, "Ошибка sql получения записей", sql_traffic.msg, QMessageBox.Ok) return False self.le_position.setText(str(sql_traffic[0][0])) self.dt_date.setDateTime(sql_traffic[0][1]) self.le_note.setText(sql_traffic[0][3]) if sql_traffic[0][2]: self.dt_tabel_date.setDateTime(sql_traffic[0][2]) else: min = sql_traffic[0][1].minute if 0 <= min <= 15: tab_date = sql_traffic[0][1].replace(minute=0) elif 16 <= min <= 45: tab_date = sql_traffic[0][1].replace(minute=30) else: tab_date = sql_traffic[0][1].replace(minute=0) hour_up = sql_traffic[0][1].hour + 1 if hour_up < 24: tab_date = tab_date.replace(hour=hour_up) else: day = sql_traffic[0][1].day tab_date = tab_date.replace(day=day + 1, hour=hour_up-24) self.dt_tabel_date.setDateTime(tab_date) else: date = self.select_date or QDateTime.currentDateTime() datetime = QDateTime(date, QTime.currentTime()) self.dt_date.setDateTime(datetime) self.dt_tabel_date.setDateTime(datetime)
def __init__(self, parent=None): super(GLWidget, self).__init__(parent) midnight = QTime(0, 0, 0) random.seed(midnight.secsTo(QTime.currentTime())) self.object = 0 self.xRot = 0 self.yRot = 0 self.zRot = 0 self.image = QImage() self.bubbles = [] self.lastPos = QPoint() self.trolltechGreen = QColor.fromCmykF(0.40, 0.0, 1.0, 0.0) self.trolltechPurple = QColor.fromCmykF(0.39, 0.39, 0.0, 0.0) self.animationTimer = QTimer() self.animationTimer.setSingleShot(False) self.animationTimer.timeout.connect(self.animate) self.animationTimer.start(25) self.setAutoFillBackground(False) self.setMinimumSize(200, 200) self.setWindowTitle("Overpainting a Scene")
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. Please 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 showTime(self): time = QTime.currentTime() text = time.toString('hh:mm') if (time.second() % 2) == 0: text = text[:2] + ' ' + text[3:] self.display(text)
def __init__(self, mode=QPrinter.ScreenResolution): """ Constructor @param mode mode of the printer (QPrinter.PrinterMode) """ super(Printer, self).__init__(mode) self.setMagnification(Preferences.getPrinter("Magnification")) if Preferences.getPrinter("ColorMode"): self.setColorMode(QPrinter.Color) else: self.setColorMode(QPrinter.GrayScale) if Preferences.getPrinter("FirstPageFirst"): self.setPageOrder(QPrinter.FirstPageFirst) else: self.setPageOrder(QPrinter.LastPageFirst) self.setPageMargins( Preferences.getPrinter("LeftMargin") * 10, Preferences.getPrinter("TopMargin") * 10, Preferences.getPrinter("RightMargin") * 10, Preferences.getPrinter("BottomMargin") * 10, QPrinter.Millimeter ) printerName = Preferences.getPrinter("PrinterName") if printerName: self.setPrinterName(printerName) self.time = QTime.currentTime().toString(Qt.LocalDate) self.date = QDate.currentDate().toString(Qt.LocalDate) self.headerFont = Preferences.getPrinter("HeaderFont")
def onTimeChanged(self, time): c_time = QTime.currentTime() if (c_time > time): self.ui.timeEdit.setTime(c_time) return diff = Alarm.__get_diff(self.ui.timeEdit.time().addSecs(60)) print("TIME CHANGED", time, diff) self.timer.timer.start(diff + (60*1000))
def updateClock(self): # What time is it ? cur = QTime.currentTime() self.from_time_updater = True self.ui.timeEdit.setTime(cur) self.from_time_updater = False
def updateClock(self): time = QTime.currentTime() if settings.fullscreenSettings.get("clock-show-seconds", True): timeStr = time.toString("hh:mm:ss") else: timeStr = time.toString("hh:mm") self.setText(timeStr)
def handle_time_update(self): time = QTime.currentTime() if self.mode == "hour": self.setRotation(time.hour() * 360. / 12. + time.minute() * 360. / (60*12)) elif self.mode == "minute": self.setRotation(time.minute() * 360. / 60. + time.second() / 60. * 360. / 60.) elif self.mode == "second": self.setRotation(time.second() * 360. / 60.)
def timeout(self): """ 타임아웃 이벤트가 발생하면 호출되는 메서드 """ # 어떤 타이머에 의해서 호출되었는지 확인 sender = self.sender() # 메인 타이머 if id(sender) == id(self.timer): currentTime = QTime.currentTime().toString("hh:mm:ss") automaticOrderTime = QTime.currentTime().toString("hhmm") # 상태바 설정 state = "" if self.kiwoom.getConnectState() == 1: state = self.serverGubun + " 서버 연결중" else: state = "서버 미연결" self.statusbar.showMessage("현재시간: " + currentTime + " | " + state) # 자동 주문 실행 # 1100은 11시 00분을 의미합니다. if self.isAutomaticOrder and int(automaticOrderTime) >= 1100: self.isAutomaticOrder = False self.automaticOrder() self.setAutomatedStocks() # log if self.kiwoom.msg: self.logTextEdit.append(self.kiwoom.msg) self.kiwoom.msg = "" # 실시간 조회 타이머 else: if self.realtimeCheckBox.isChecked(): self.inquiryBalance()
def paintEvent(self, event): side = min(self.width(), self.height()) time = QTime.currentTime() time = time.addSecs(self.timeZoneOffset * 3600) painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.Antialiasing) painter.translate(self.width() / 2, self.height() / 2) painter.scale(side / 200.0, side / 200.0) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(self.hourColor)) painter.save() painter.rotate(30.0 * ((time.hour() + time.minute() / 60.0))) painter.drawConvexPolygon(self.hourHand) painter.restore() painter.setPen(self.hourColor) for i in range(0, 12): painter.drawLine(84, 0, 96, 0) painter.rotate(30.0) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(self.minuteColor)) painter.save() painter.rotate(6.0 * (time.minute() + time.second() / 60.0)) painter.drawConvexPolygon(self.minuteHand) painter.restore() painter.setPen(QPen(self.minuteColor)) for j in range(0, 60): if (j % 5) != 0: painter.drawLine(90, 0, 96, 0) painter.rotate(6.0) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(self.secondColor)) painter.save() painter.rotate(6.0 * time.second()) painter.drawConvexPolygon(self.secondHand) painter.restore() painter.end()
def measureFps(self): # Calculate time difference. t = self.fpsTime.msecsTo(QTime.currentTime()) if t == 0: t = 0.01 self.currentFps = (1000.0 / t) self.fpsHistory.append(self.currentFps) self.fpsTime = QTime.currentTime() # Calculate median. size = len(self.fpsHistory) if size == 10: self.fpsHistory.sort() self.fpsMedian = self.fpsHistory[int(size / 2)] if self.fpsMedian == 0: self.fpsMedian = 0.01 self.fpsHistory = [] return True return False
def __init__(self): super(Alarm, self).__init__() self.ui = Ui_Form() self.ui.setupUi(self) self.ui.lineEdit.textChanged.connect(self.onTextChanged) self.ui.timeEdit.timeChanged.connect(self.onTimeChanged) self.ui.groupBox.toggled.connect(self.onGBToggle) self.ui.toolButton.clicked.connect(self.onToolButton) self.go = True self.ui.timeEdit.setTime(QTime.currentTime().addSecs(60)) self.timer = QTimer(self) self.timer.timeout.connect(self.__alarm) self.timer.start(Alarm.__get_diff(self.ui.timeEdit.time())) self.music = "alarm.mp3" self.ui.track_label.setText("DEFAULT")
def animationStarted(self, id): if id == DemoItemAnimation.ANIM_IN: if self.doIntroTransitions: # Make all letters disappear. for letter in self.letterList: letter.setPos(1000, 0) self.switchToNextEffect() self.useGuideQt() self.scale = 1.0 # The first time we run, we have a rather large delay to # perform benchmark before the ticker shows. But now, since we # are showing, use a more appropriate value. self.currentAnimation.setStartDelay(1500) elif self.effect is not None: self.effect.useSheepDog = False self.tickTimer = QTime.currentTime()
def paintEvent(self, e): time = QTime.currentTime() qp = QPainter() qp.begin(self) #qp.setRenderHint(QPainter.Antialiasing) # 开启这个抗锯齿,会很占cpu的! qp.translate(self.width() / 2, self.height() / 2) qp.scale(self.side / 200.0, self.side / 200.0) qp.setPen(QtCore.Qt.NoPen) qp.setBrush(self.hourColor) qp.save() qp.rotate(30.0 * ((time.hour() + time.minute()/ 60.0))) qp.drawConvexPolygon(self.hourHand) qp.restore() qp.setPen(self.minuteColor) qp.drawText(0,0,"Testdddddddddddddd") for i in range(12): qp.drawLine(88, 0, 96, 0) qp.rotate(30.0) qp.setPen(QtCore.Qt.NoPen) qp.setBrush(self.minuteColor) qp.save() qp.rotate(6.0 * ((time.minute() + (time.second()+time.msec()/1000.0) / 60.0))) qp.drawConvexPolygon(self.minuteHand) qp.restore() qp.setPen(self.minuteColor) for i in range(60): if (i % 5) is not 0: qp.drawLine(92, 0, 96, 0) qp.rotate(6.0) qp.setPen(QtCore.Qt.NoPen) qp.setBrush(self.secondColor) qp.save() qp.rotate(6.0*(time.second()+time.msec()/1000.0)) qp.drawConvexPolygon(self.secondHand) qp.restore() qp.end()
def createDateTimeEdits(self): self.editsGroup = QGroupBox("Date and time spin boxes") dateLabel = QLabel() dateEdit = QDateEdit(QDate.currentDate()) dateEdit.setDateRange(QDate(2005, 1, 1), QDate(2010, 12, 31)) dateLabel.setText("Appointment date (between %s and %s):" % (dateEdit.minimumDate().toString(Qt.ISODate), dateEdit.maximumDate().toString(Qt.ISODate))) timeLabel = QLabel() timeEdit = QTimeEdit(QTime.currentTime()) timeEdit.setTimeRange(QTime(9, 0, 0, 0), QTime(16, 30, 0, 0)) timeLabel.setText("Appointment time (between %s and %s):" % (timeEdit.minimumTime().toString(Qt.ISODate), timeEdit.maximumTime().toString(Qt.ISODate))) self.meetingLabel = QLabel() self.meetingEdit = QDateTimeEdit(QDateTime.currentDateTime()) formatLabel = QLabel("Format string for the meeting date and time:") formatComboBox = QComboBox() formatComboBox.addItem('yyyy-MM-dd hh:mm:ss (zzz \'ms\')') formatComboBox.addItem('hh:mm:ss MM/dd/yyyy') formatComboBox.addItem('hh:mm:ss dd/MM/yyyy') formatComboBox.addItem('hh:mm:ss') formatComboBox.addItem('hh:mm ap') formatComboBox.activated[str].connect(self.setFormatString) self.setFormatString(formatComboBox.currentText()) editsLayout = QVBoxLayout() editsLayout.addWidget(dateLabel) editsLayout.addWidget(dateEdit) editsLayout.addWidget(timeLabel) editsLayout.addWidget(timeEdit) editsLayout.addWidget(self.meetingLabel) editsLayout.addWidget(self.meetingEdit) editsLayout.addWidget(formatLabel) editsLayout.addWidget(formatComboBox) self.editsGroup.setLayout(editsLayout)
def switchTimerOnOff(self, on): ticker = MenuManager.instance().ticker if ticker and ticker.scene(): ticker.tickOnPaint = not on or Colors.noTimerUpdate if on and not Colors.noTimerUpdate: self.useTimer = True self.fpsTime = QTime.currentTime() self.updateTimer.start(int(1000 / Colors.fps)) update_mode = QGraphicsView.NoViewportUpdate else: self.useTimer = False self.updateTimer.stop() if Colors.noTicker: update_mode = QGraphicsView.MinimalViewportUpdate else: update_mode = QGraphicsView.SmartViewportUpdate self.setViewportUpdateMode(update_mode)
def ircTimestamp(): """ Module method to generate a time stamp string. @return time stamp (string) """ if Preferences.getIrc("ShowTimestamps"): if Preferences.getIrc("TimestampIncludeDate"): if QApplication.isLeftToRight(): f = "{0} {1}" else: f = "{1} {0}" formatString = f.format(Preferences.getIrc("DateFormat"), Preferences.getIrc("TimeFormat")) else: formatString = Preferences.getIrc("TimeFormat") return '<font color="{0}">[{1}]</font> '.format( Preferences.getIrc("TimestampColour"), QTime.currentTime().toString(formatString)) else: return ""
def paintEvent(self, event): side = min(self.width(), self.height()) time = QTime.currentTime() painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) painter.translate(self.width() / 2, self.height() / 2) painter.scale(side / 200.0, side / 200.0) painter.setPen(Qt.NoPen) painter.setBrush(ShapedClock.hourColor) painter.save() painter.rotate(30.0 * ((time.hour() + time.minute() / 60.0))) painter.drawConvexPolygon(ShapedClock.hourHand) painter.restore() painter.setPen(ShapedClock.hourColor) for i in range(12): painter.drawLine(88, 0, 96, 0) painter.rotate(30.0) painter.setPen(Qt.NoPen) painter.setBrush(ShapedClock.minuteColor) painter.save() painter.rotate(6.0 * (time.minute() + time.second() / 60.0)) painter.drawConvexPolygon(ShapedClock.minuteHand) painter.restore() painter.setPen(ShapedClock.minuteColor) for j in range(60): if (j % 5) != 0: painter.drawLine(92, 0, 96, 0) painter.rotate(6.0)
def showTime(self): time = QTime.currentTime() text = time.toString('hh:mm') date = QDate.currentDate() dateFinal = date.toString("dddd, d MMMM yyyy") #print('date is ',dateFinal) #if (time.second() % 2) == 0: #text = text[:2] + ':' + text[3:] QQmlProperty.write(self.digitalClock, "clockTime",str(text) ) QQmlProperty.write(self.digitalClock, "dateInfoQTime",str(dateFinal) ) #if __name__ == '__main__': #import sys #app = QApplication(sys.argv) #clock = DigitalClock() #clock.show() #sys.exit(app.exec_()) ##
def paint(self, painter, option, widget): time = QTime.currentTime() minuteNow = time.minute() + (time.second() / 60.0) angleSecondsElapsed = 16*(360*self._seconds_elapsed / 60. / 60.) angleSecondsRemaining = 16*(360*self._seconds_remaining / 60. / 60.) thetaNow = 16*(90 - 360 * minuteNow / 60.) PADDING = 0.5*self._thickness # Time left painter.setPen(QPen(QColor(self._color.red(), self._color.green(), self._color.blue(), 255), self._thickness, Qt.SolidLine, #Qt.FlatCap if abs(theta3-thetaNow) < 16*20 else Qt.RoundCap, Qt.FlatCap #Qt.RoundCap )) painter.setBrush(Qt.NoBrush) painter.drawArc(PADDING, PADDING, self._sz-2*PADDING, self._sz-2*PADDING, thetaNow, -angleSecondsRemaining) # Elapsed time painter.setPen(QPen(QColor(self._color.red(), self._color.green(), self._color.blue(), 64), self._thickness, Qt.SolidLine, Qt.FlatCap, )) painter.drawArc(PADDING, PADDING, self._sz-2*PADDING, self._sz-2*PADDING, thetaNow, angleSecondsElapsed)
pass class GraphicsView(QGraphicsView): def resizeEvent(self, e): pass if __name__ == "__main__": import sys import math app = QApplication(sys.argv) qsrand(QTime(0, 0, 0).secsTo(QTime.currentTime())) scene = QGraphicsScene(-200, -200, 400, 400) for i in range(10): item = ColorItem() angle = i * 6.28 / 10.0 item.setPos(math.sin(angle) * 150, math.cos(angle) * 150) scene.addItem(item) robot = Robot() robot.setTransform(QTransform.fromScale(1.2, 1.2), True) robot.setPos(0, -20) scene.addItem(robot) view = GraphicsView(scene)
def showTime(self): date = QDate.currentDate() time = QTime.currentTime() self.timeEdit.setTime(time) self.dateEdit.setDate(date)
def startParty(self): self.partyStarted.emit(QTime.currentTime())
def showTime(self): time = QTime.currentTime() text = time.toString('hh:mm:ss') if (time.second() % 2) == 0: text = text[:2] + ' ' + text[3:5] + ' ' + text[6:] self.display(text)
class Archiver_Viewer(QMainWindow): def __init__(self): QMainWindow.__init__(self) loadUi('Archiver_Viewer.ui',self) self.setWindowTitle('Archiver Viewer') self.toTime=QTime() self.toDate=QDate() self.currentTime=self.toTime.currentTime() self.currentDate=self.toDate.currentDate() self.toDateTimeEdit.setTime(self.currentTime) self.toDateTimeEdit.setDate(self.currentDate) self.fromDateTimeEdit.setDate(self.currentDate) self.fromTime=self.currentTime.addSecs(-3600) self.fromDateTimeEdit.setTime(self.fromTime) fname='archiver_PVs.txt' self.readPV=ReadPVList(fname=fname) self.pvList=self.readPV.pvList self.checkMotor=self.readPV.checkMotor self.update_pvTree() self.init_signals() self.unit={} def init_signals(self): self.fetchDataPushButton.clicked.connect(self.fetchData) self.exportDataPushButton.clicked.connect(self.exportData) def update_pvTree(self): self.pvTreeWidget.clear() for category in self.pvList.keys(): categ=QTreeWidgetItem([category]) for pv in self.pvList[category].keys(): if self.checkMotor[pv]: mot=QTreeWidgetItem([pv]) for motorPV in self.pvList[category][pv].keys(): motPV=QTreeWidgetItem([motorPV, self.pvList[category][pv][motorPV]]) mot.addChild(motPV) categ.addChild(mot) else: apv=QTreeWidgetItem([pv,self.pvList[category][pv]]) categ.addChild(apv) self.pvTreeWidget.setColumnCount(3) self.pvTreeWidget.addTopLevelItem(categ) self.pvTreeWidget.header().setSectionResizeMode(QHeaderView.ResizeToContents) def fetchData(self): fr=self.fromDateTimeEdit.dateTime().toUTC().toString(Qt.ISODate) to=self.toDateTimeEdit.dateTime().toUTC().toString(Qt.ISODate) self.unit={} self.xraw={} self.x={} self.y={} prg_dlg=QProgressDialog(self) prg_dlg.setAutoClose(True) items=self.pvTreeWidget.selectedItems() prg_dlg.setMaximum(len(items)) prg_dlg.setMinimum(0) prg_dlg.show() self.datafull={} for i, item in enumerate(items): pv=item.text(1) # url='http://164.54.162.104:17668/retrieval/data/getData.json?pv=15ID:BLEPS:TEMP1_CURRENT&from=2019-06-17T13:20:00%%C2%B10700&to=2019-06-17T14:20:00%%C2%B10700' url = 'http://164.54.162.104:17668/retrieval/data/getData.json?pv=%s&from=%s&to=%s' % (pv, fr, to) print(url) http = urllib3.PoolManager() r = http.request('GET', url) try: data = json.loads(r.data) except: QMessageBox.warning(self,'Fetch Error','The data from %s cannot be obtained from the server'%pv,QMessageBox.Ok) return try: self.unit[pv] = data[0]['meta']['EGU'] except: self.unit[pv] = 'Unit Not Available' self.xraw[pv]=pl.array([item['secs'] for item in data[0]['data']]) self.x[pv] = pl.array([datetime.datetime.fromtimestamp(item['secs']) for item in data[0]['data']],dtype='datetime64') self.y[pv] = pl.array([item['val'] for item in data[0]['data']]) self.datafull[pv]=pl.vstack((self.xraw[pv],self.y[pv])) prg_dlg.setValue(i + 1) if bool(self.unit): self.updatePlot() def updatePlot(self): try: self.axes2.remove() except: pass if len(self.unit.keys())!=2: axis_color='k' self.mplWidget.canvas.axes.clear() self.mplWidget.canvas.axes.set_xlabel('Time') last = None ylabel = '' for pv in self.unit.keys(): if self.unit[pv]!=last: ylabel+='%s '%self.unit[pv] self.mplWidget.canvas.axes.step(self.x[pv], self.y[pv],label=pv) last=self.unit[pv] self.mplWidget.canvas.axes.tick_params(axis='y', labelcolor=axis_color) self.mplWidget.canvas.axes.set_ylabel(ylabel,color=axis_color) leg=self.mplWidget.canvas.axes.legend(loc='best') else: self.mplWidget.canvas.axes.clear() pv=list(self.unit.keys()) color = 'tab:red' self.mplWidget.canvas.axes.set_ylabel(pv[0]+'[%s]'%self.unit[pv[0]],color=color) self.mplWidget.canvas.axes.step(self.x[pv[0]], self.y[pv[0]],color=color,label=pv) self.mplWidget.canvas.axes.tick_params(axis='y',labelcolor=color) self.axes2=self.mplWidget.canvas.axes.twinx() color = 'tab:blue' self.axes2.set_ylabel(pv[1]+'[%s]'%self.unit[pv[1]], color=color) self.axes2.step(self.x[pv[1]], self.y[pv[1]],color=color, label=pv) self.axes2.tick_params(axis='y', labelcolor=color) self.mplWidget.canvas.draw() self.mplWidget.canvas.flush_events() pl.gcf().autofmt_xdate() def exportData(self): if bool(self.unit): self.dir=QFileDialog.getExistingDirectory(self,'Select a directory to save data') if self.dir!='': for pv in self.unit.keys(): fheader='Data saved on %s\n'%(time.asctime()) fheader+='col_names=["time[secs]","pv[%s]"]'%self.unit[pv] fname=pv+'_%s.txt'%(time.strftime('%Y%m%d')) fname=os.path.join(self.dir,fname.replace(':','_')) pl.savetxt(fname,self.datafull[pv],header=fheader,comments='#') else: QMessageBox.warning(self,'Data Error','No data fetched to save',QMessageBox.Ok)
def update_time(self): self.current_time = QTime.currentTime() time_on_display = self.current_time.toString('hh:mm') self.label_clock.setText(time_on_display)
def updateTime(self): self.timeChanged.emit(QTime.currentTime())
def showTime(self): currentTime = QTime.currentTime() displayTxt = currentTime.toString("hh:mm:ss") # print(displayTxt) self.lbl.setText(displayTxt)
from PyQt5.QtCore import QDate, QTime, QDateTime, Qt now = QDate.currentDate() # QDate.currentDate()가 현재 날짜 정보 반환 print(now.toString(Qt.ISODate)) # ISO(국제 표준 날짜 형식) 포맷을 사용하여 문자열 형태로 출력 print(now.toString(Qt.DefaultLocaleLongDate)) # 기본 포맷을 사용하여 문자열 형태로 출력 datetime = QDateTime.currentDateTime( ) # QDateTime.currentDateTime()이 현재 날짜와 시간 정보 반환 print(datetime.toString()) # 현재 날짜와 시간을 문자열 형태로 출력 time = QTime.currentTime() # QTime.currentTime()이 현재 시간 정보 반환 print(time.toString(Qt.DefaultLocaleLongDate)) # 현재 시간을 문자열 형태로 출력
def do_timer_timeout(self): ##定时中断响应 curTime = QTime.currentTime() #获取当前时间 self.ui.LCDHour.display(curTime.hour()) self.ui.LCDMin.display(curTime.minute()) self.ui.LCDSec.display(curTime.second())
def tick(self): hora = QTime.currentTime() hora_texto = hora.toString('hh:mm') self.ui.lcd_hora.display(hora_texto)
def _update(self): """ Update display every second""" hours_minutes, am_pm = QTime.currentTime().toString( 'hh:mm ap').upper().split(' ') self.display(hours_minutes)
# 本教程来源于 # http://zetcode.com/gui/pyqt5/ from PyQt5.QtCore import QDate, QTime, QDateTime, Qt # 得到现在的日期 date = QDate.currentDate() print(date.toString(Qt.ISODate)) print(date.toString(Qt.DefaultLocaleLongDate)) # 获取当前时间 time = (QTime.currentTime()).toString() print(time) # 获取当前时间 now = (QDateTime.currentDateTime()).toString(Qt.DefaultLocaleLongDate) print(now)
def consoleAppend(self, topic, msg, retained=False): if self.device.matches(topic): tstamp = QTime.currentTime().toString("HH:mm:ss") self.console.appendPlainText("[{}] {} {}".format( tstamp, topic, msg))
def _update(self): """ Update display each one second """ time = QTime.currentTime().toString() self.display(time)
def time(self): return QTime.currentTime().toString('hh:mm')
def _process_started(self): time_str = QTime.currentTime().toString("hh:mm:ss") text = time_str + " Running: " + self.process_name self.outputw.append_text(text) self.outputw.setReadOnly(False)
def pause(self, on): self.paused = on self.tickTimer = QTime.currentTime()
def paintEvent(self, _: QPaintEvent): hourHand = [QPoint(0, 10), QPoint(3, 6), QPoint(0, -40), QPoint(-3, 6)] minuteHand = [ QPoint(0, 15), QPoint(3, 4), QPoint(0, -70), QPoint(-3, 4) ] secondHand = [ QPoint(0, 20), QPoint(2, 3), QPoint(0, -90), QPoint(-2, 3) ] hourColor = QColor(255, 0, 0) minuteColor = QColor(0, 255, 0, 191) secondColor = QColor(255, 127, 0, 191) side = min(self.width(), self.height()) # time = self._get_ntp_time() time = QTime.currentTime() painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) painter.translate(self.width() / 2, self.height() / 2) painter.scale(side / 200.0, side / 200.0) painter.setPen(Qt.NoPen) painter.setBrush(hourColor) painter.save() painter.rotate(30.0 * ((time.hour() + time.minute() / 60.0))) painter.drawConvexPolygon(QPolygon(hourHand)) painter.restore() painter.setPen(hourColor) for _ in range(12): painter.drawLine(88, 0, 96, 0) painter.rotate(30.0) painter.setPen(Qt.NoPen) painter.setBrush(minuteColor) painter.save() painter.rotate(6.0 * (time.minute() + time.second() / 60.0)) painter.drawConvexPolygon(QPolygon(minuteHand)) painter.restore() painter.setPen(minuteColor) for j in range(60): if (j % 5) != 0: painter.drawLine(92, 0, 96, 0) painter.rotate(6.0) painter.setPen(Qt.NoPen) painter.setBrush(secondColor) painter.save() painter.rotate(6.0 * time.second()) painter.drawConvexPolygon(QPolygon(secondHand)) painter.restore()
def viewCam(self): # 输出系统时间 current_time = QTime.currentTime() time_string = current_time.toString() self.ui.time_label.setText(time_string) # 读取一个BGR格式的图像帧 ret, raw_frame = self.cap.read() # 把图像帧缩小到1/4,从而实行更快的人脸识别处理 small_frame = cv2.resize(raw_frame, (0, 0), fx=0.25, fy=0.25) # 把摄像头采集的BGR图像转换成RGB图像 rgb_small_frame = cv2.cvtColor(small_frame, cv2.COLOR_BGR2RGB) if True: # 在视频当前帧中找到所有的脸部,并进行脸部信息编码 face_locations = face_recognition.face_locations(rgb_small_frame) face_encodings = face_recognition.face_encodings( rgb_small_frame, face_locations) face_names = [] name = "NULL" for face_encoding in face_encodings: # 检测图像帧中的脸是否和已知的脸部信息匹配 matches = face_recognition.compare_faces( known_face_encodings, face_encoding) # 将新的脸部信息和它的face_distances最接近的已知脸部信息匹配 face_distances = face_recognition.face_distance( known_face_encodings, face_encoding) best_match_index = np.argmin(face_distances) # 设置匹配阈值,满足条件的就和已知信息匹配,如果不满足就设置成未知 if face_distances[best_match_index] < 0.55 and matches[ best_match_index]: name = known_face_names[best_match_index] else: name = "Unknown" face_names.append(name) # 显示识别结果(用矩形框将识别到的人脸标记出来) for (top, right, bottom, left), name in zip(face_locations, face_names): # 由于之前将图像帧缩小了1/4,现在将尺度放大四倍,以便和原始图片尺寸匹配 top *= 4 right *= 4 bottom *= 4 left *= 4 # 在图像帧中的人脸部位画标记框 cv2.rectangle(raw_frame, (left, top), (right, bottom), (0, 0, 255), 2) # 将经过标记处理的原始图像帧从BGR格式转换成RGB格式 frame = cv2.cvtColor(raw_frame, cv2.COLOR_BGR2RGB) # 获取图像帧信息 height, width, channel = frame.shape step = channel * width # 将图像帧转换成pyqt可以显示的格式 qImg = QImage(frame.data, width, height, step, QImage.Format_RGB888) # 用pyqt显示图像帧 self.ui.image_label.setPixmap(QPixmap.fromImage(qImg)) # (1)当视频帧中存在已知人脸且未打卡时,若打卡时间早于截止时间,输出打卡时间、人员姓名、打卡成功等信息;若打卡时间迟于截止时间,输出人员姓名、迟到等信息 # (2)当视频帧中存在已知人脸且已打卡时,输出人员姓名、已打卡等信息 # (3)当视频帧中存在未知人脸时,输出“未注册人脸信息” # (4)当视频帧中不存在人脸时,输出为空 if (name == "NULL"): self.ui.textBrowser.clear() self.lastname = "NULL" elif (name == "Unknown"): self.ui.textBrowser.setText("未注册人脸信息") self.lastname = "Unknown" elif (name == self.lastname): self.lastname = name elif (name in self.check_success): self.ui.textBrowser.setText(name + "已打卡") else: # 判断当前打卡时间是否迟到 dead_time = self.ui.dead_time.time() if (dead_time.hour() < current_time.hour()): isLate = 1 elif (dead_time.hour() == current_time.hour() and dead_time.minute() < current_time.minute()): isLate = 1 elif (dead_time.minute() == current_time.minute() and dead_time.second() < current_time.second()): isLate = 1 else: isLate = 0 # 如果isLate=1,输出迟到信息;如果isLate=01,输出打卡成功信息; if (isLate): self.ui.textBrowser.setText(name + "迟到") else: self.ui.textBrowser.setText(time_string + ":\n" + name + "打卡成功") self.check_success.append(name) self.lastname = name
def showlcd(self): time = QTime.currentTime() text = time.toString('hh:mm:ss') self.lcd.display(text)
def updateTime(self): time = QTime.currentTime().toString() self.time_label.setText(str(time) + "\n" + store.output) if (store.output == 'Completed..Now you may check the file'): self.calc.terminate()
dx = math.sin(self.angle) * 10 self.mouseEyeDirection = 0.0 if qAbs(dx / 5) < 1 else dx / 5 self.setRotation(self.rotation() + dx) self.setPos(self.mapToParent(0, -(3 + math.sin(self.speed) * 3))) if __name__ == '__main__': import sys MouseCount = 7 app = QApplication(sys.argv) qsrand(QTime(0, 0, 0).secsTo(QTime.currentTime())) scene = QGraphicsScene() scene.setSceneRect(-300, -300, 600, 600) scene.setItemIndexMethod(QGraphicsScene.NoIndex) for i in range(MouseCount): mouse = Mouse() mouse.setPos( math.sin((i * 6.28) / MouseCount) * 200, math.cos((i * 6.28) / MouseCount) * 200) scene.addItem(mouse) view = QGraphicsView(scene) view.setRenderHint(QPainter.Antialiasing) view.setBackgroundBrush(QBrush(QPixmap(':/images/cheese.jpg')))
import sys from PyQt5.QtWidgets import QApplication, QMainWindow from PyQt5.QtCore import QDate, QTime, QDateTime, Qt now = QDate.currentDate() print(now.toString()) print(now.toString("d.M.yy")) print(now.toString("dd.MM.yyyy")) print(now.toString("dd.MMMM.yyyy")) print(now.toString(Qt.ISODate)) print(now.toString(Qt.DefaultLocaleLongDate)) time_now = QTime.currentTime() print(time_now.toString()) print(time_now.toString("h.m.s")) print(time_now.toString("hh:mm:ss")) print(time_now.toString(Qt.DefaultLocaleLongDate)) print(time_now.toString(Qt.DefaultLocaleShortDate)) date_time = QDateTime.currentDateTime() print(date_time.toString()) print(date_time.toString("d.M.yy hh:mm:ss")) print(date_time.toString("dd.MM.yy, hh:mm:ss")) print(date_time.toString(Qt.DefaultLocaleLongDate)) print(date_time.toString(Qt.DefaultLocaleShortDate)) class MyApp(QMainWindow): def __init__(self): super().__init__() self.date = QDate.currentDate() self.initUI()
def get_time(self): time = QTime.currentTime().toString("hh:mm") self.lcdTime.display(time)
def __postText(self, text): if self.checkBoxTimestamp.isChecked(): time = QTime.currentTime().toString() self.textEditTraffic.append("%s - %s" % (time, text)) else: self.textEditTraffic.append(text)
def delay(self, time_in_sec=1.0): dice_time = QTime.currentTime().addSecs(time_in_sec) while QTime.currentTime() < dice_time: QCoreApplication.processEvents(QEventLoop.AllEvents, 100)
def showTime(self): time = QTime.currentTime() self.textEdit.setText(time.toString(Qt.DefaultLocaleShortDate))
def __init__(self): super().__init__() self.date = QDate.currentDate() self.time = QTime.currentTime() self.initUI()
def to_now(self): now = QTime.currentTime() self._now = now.toString(damgvar.fmts) self.__now__ = now.toString(damgvar.fmtl) return self._now, self.__now__
def updateScreenData(self): self.lastTemperatures = database_manager.get_last_temperatures(self.db) # Lettura delle impostazioni, se sono differenti con quelle precedenti # allora la configuration è stata cambiata dal sito e non dall'interfaccia self.configuration = database_manager.get_configuration(self.db) if (self.configuration["rooms_settings"][self.actualRoomIndex]["program"]["MFM"] != "" and \ self.configuration["rooms_settings"][self.actualRoomIndex]["program"]["MFE"] != "" and \ self.configuration["rooms_settings"][self.actualRoomIndex]["program"]["MFN"] != "" and \ self.configuration["rooms_settings"][self.actualRoomIndex]["program"]["WEM"] != "" and \ self.configuration["rooms_settings"][self.actualRoomIndex]["program"]["WEE"] != "" and \ self.configuration["rooms_settings"][self.actualRoomIndex]["program"]["WEN"] != ""): # MONDAY - FRIDAY date = QDate.currentDate() time = QTime.currentTime() if (date.dayOfWeek() >= 1 and date.dayOfWeek() <= 5): if (time.hour() >= 6 and time.hour() < 12): self.roomTempProgram = self.configuration[ "rooms_settings"][ self.actualRoomIndex]["program"]["MFM"] if (time.hour() >= 12 and time.hour() <= 23): self.roomTempProgram = self.configuration[ "rooms_settings"][ self.actualRoomIndex]["program"]["MFE"] if (time.hour() >= 0 and time.hour() < 6): self.roomTempProgram = self.configuration[ "rooms_settings"][ self.actualRoomIndex]["program"]["MFN"] # WEEKEND elif (date.dayOfWeek() >= 6 and date.dayOfWeek() <= 7): if (time.hour() >= 6 and time.hour() < 12): self.roomTempProgram = self.configuration[ "rooms_settings"][ self.actualRoomIndex]["program"]["WEM"] if (time.hour() >= 12 and time.hour() <= 23): self.roomTempProgram = self.configuration[ "rooms_settings"][ self.actualRoomIndex]["program"]["WEE"] if (time.hour() >= 0 and time.hour() < 6): self.roomTempProgram = self.configuration[ "rooms_settings"][ self.actualRoomIndex]["program"]["WEN"] else: self.roomTempProgram = "00" if (self.lastModifiedBy == "GUI"): self.newConfiguration = self.configuration self.newConfiguration["rooms_settings"][ self.actualRoomIndex]["info"]["temp"] = self.roomTempSet self.newConfiguration["rooms_settings"][ self.actualRoomIndex]["season"] = self.season self.newConfiguration["rooms_settings"][ self.actualRoomIndex]["mode"] = self.mode self.newConfiguration["rooms_settings"][ self.actualRoomIndex]["info"]["weekend"] = self.weekend print("\t --> COMMIT: ") print("\t\tID: " + str(self.actualRoomID)) print("\t\tTemp: " + str(self.roomTempSet)) print("\t\tSeason: " + str(self.season)) print("\t\tMode: " + str(self.mode)) print("\t\tWeekend: " + str(self.weekend)) database_manager.update_configuration(self.db, self.newConfiguration) self.lastModifiedBy = "WEB" else: # WEB self.roomTempSet = self.configuration["rooms_settings"][ self.actualRoomIndex]["info"]["temp"] self.season = self.configuration["rooms_settings"][ self.actualRoomIndex]["season"] self.mode = self.configuration["rooms_settings"][ self.actualRoomIndex]["mode"] self.weekend = self.configuration["rooms_settings"][ self.actualRoomIndex]["info"]["weekend"] self.reloadRoomData() self.LCDTempAct.display(str("o")) for el in self.lastTemperatures: if (str(el["room"]) == str(self.actualRoomID)): self.LCDTempAct.display("%.1f" % round(el["temperature"], 1)) break
# -*- coding: utf-8 -*- """ Created on Thu Mar 4 12:35:18 2021 Ejercicios de la Sección de PyQt5 date and time @author: ChrisLe """ from PyQt5.QtCore import QDate, QTime, QDateTime, Qt now = QDate.currentDate() print('Formato ISO: ' + now.toString(Qt.ISODate)) print('Formato Fecha Extendida: ' + now.toString(Qt.DefaultLocaleLongDate)) datetime = QDateTime.currentDateTime() print('Formato Fecha Objeto QDateTime: ' + datetime.toString()) time = QTime.currentTime() print('Formato Hora Objeto QTime' + time.toString(Qt.DefaultLocaleLongDate))
def init_widget(self): self.widget.setTime(QTime.currentTime()) self.widget.setDisplayFormat(self.format)