def buttonOpenClicked(self): fileDialog = QFileDialog( self, "打开历史数据文件", QApplication.applicationDirPath() + "/../data", "Database File (*.db *.mdb)" ) if fileDialog.exec_() == QDialog.Rejected: return # clear curve self.curveHistory.clear() # filePaths = fileDialog.selectedFiles() if filePaths.isEmpty(): return filePath = filePaths.first() if filePath.isEmpty(): return # open database if not DatabaseMgr().open(filePath): return # startTime = QDateTime.fromMSecsSinceEpoch(DatabaseMgr().startTime()) endTime = QDateTime.fromMSecsSinceEpoch(DatabaseMgr().endTime()) self.dateTimeEditStart.setDateTimeRange(startTime, endTime) self.dateTimeEditEnd.setDateTimeRange(startTime, endTime) self.dateTimeEditEnd.setDateTime(endTime) self.dateTimeEditStart.setDateTime(startTime) # title of curve self.curveHistory.setTitle("历史数据回放" + "(" + QFileInfo(filePath).fileName() + ")")
def __init__(self): self.id = 0 self.count = 0 self.date = QDateTime() self.url = QUrl() self.urlString = '' self.title = ''
def addEntryFunc(): dbobj = HistoryDbModel.select().where( HistoryDbModel.url == url.toString()).first() if dbobj: # update before = self.HistoryEntry() before.id = dbobj.id before.count = dbobj.count before.date = QDateTime.fromMSecsSinceEpoch(dbobj.date) before.url = url before.urlString = before.url.toEncoded().data().decode() before.title = dbobj.title after = self.HistoryEntry() after.id = dbobj.id after.count = dbobj.count + 1 after.date = QDateTime.currentDateTime() after.url = url after.urlString = after.url.toEncoded().data().decode() after.title = title after.fillDbobj(dbobj) dbobj.save() self.historyEntryEdited.emit(before, after) else: # insert dbobj = HistoryDbModel.create( **{ 'count': 1, 'date': QDateTime.currentMSecsSinceEpoch(), 'url': url.toString(), 'title': title, }) entry = self.HistoryEntry.CreateFromDbobj(dbobj) self.historyEntryAdded.emit(entry)
def pd_timestamp_to_q_datetime(pd_timestamp: datetime): if pd_timestamp is None or pd.isna(pd_timestamp): return QDateTime() return QDateTime( QDate(pd_timestamp.year, pd_timestamp.month, pd_timestamp.day), QTime(pd_timestamp.hour, pd_timestamp.minute, pd_timestamp.second, pd_timestamp.microsecond / 1000))
def inventory_available(self): ''' Update the Date range widgets with the rounded oldest, newest dates Don't connect date signals until date range available ''' self._log_location() # Reset the date range based on available annotations oldest = QDateTime(datetime.fromtimestamp(self.annotated_books_scanner.oldest_annotation)) oldest_day = QDateTime(datetime.fromtimestamp(self.annotated_books_scanner.oldest_annotation).replace(hour=0, minute=0, second=0)) newest = QDateTime(datetime.fromtimestamp(self.annotated_books_scanner.newest_annotation)) newest_day = QDateTime(datetime.fromtimestamp(self.annotated_books_scanner.newest_annotation).replace(hour=23, minute=59, second=59)) # Set 'From' date limits to inventory values self.find_annotations_date_from_dateEdit.setMinimumDateTime(oldest_day) self.find_annotations_date_from_dateEdit.current_val = oldest self.find_annotations_date_from_dateEdit.setMaximumDateTime(newest_day) # Set 'To' date limits to inventory values self.find_annotations_date_to_dateEdit.setMinimumDateTime(oldest_day) self.find_annotations_date_to_dateEdit.current_val = newest_day self.find_annotations_date_to_dateEdit.setMaximumDateTime(newest_day) # Connect the signals for date range changes self.find_annotations_date_from_dateEdit.dateTimeChanged.connect(partial(self.update_results, 'from_date')) self.find_annotations_date_to_dateEdit.dateTimeChanged.connect(partial(self.update_results, 'to_date')) self.update_results('inventory_available')
def step_qdatetime(control, fraction, interval, range_start, range_end): date_from = q_datetime_to_datetime(control.dateFrom) date_to = q_datetime_to_datetime(control.dateTo) range_start = q_datetime_to_datetime(range_start) range_end = q_datetime_to_datetime(range_end) delta = round_timedelta((date_to - date_from) * fraction, interval) date_from = max(date_from + delta, range_start) date_to = min(date_to + delta, range_end) if date_to - date_from > timedelta(0): control.dateTo = QDateTime(date_to) control.dateFrom = QDateTime(date_from)
def __init__(self, date_read, is_read_only=False, default_to_today=False, fmt=None): # debug_print("DateTableWidgetItem:__init__ - date_read=", date_read) if date_read is None or date_read == UNDEFINED_DATE and default_to_today: date_read = now() if is_read_only: super(DateTableWidgetItem, self).__init__(format_date(date_read, fmt)) self.setFlags(Qt.ItemIsSelectable|Qt.ItemIsEnabled) self.setData(Qt.DisplayRole, QDateTime(date_read)) else: super(DateTableWidgetItem, self).__init__('') self.setData(Qt.DisplayRole, QDateTime(date_read))
def setter(self, val): if val is None: val = self.main_widget.minimumDateTime() else: val = QDateTime(val) self.main_widget.setDateTime(val) self.ignore_change_signals = False
def historyEntryAdded(self, entry): ''' @param: entry HistoryEntry ''' if not self._todayItem: self.beginInsertRows(QModelIndex(), 0, 0) self._todayItem = HistoryItem(None) self._todayItem.canFetchMore = True self._todayItem.setStartTimestamp(-1) self._todayItem.setEndTimestamp( QDateTime(QDate.currentDate()).toMSecsSinceEpoch()) self._todayItem.title = _('Today') self._rootItem.prependChild(self._todayItem) self.endInsertRows() self.beginInsertRows(self.createIndex(0, 0, self._todayItem), 0, 0) item = HistoryItem() item.historyEntry = entry self._todayItem.prependChild(item) self.endInsertRows()
def startTimestamp(self): ''' @param: qint64 ''' if self._startTimestamp == -1: return QDateTime.currentDateTime().toMSecsSinceEpoch() return self._startTimestamp
def _finished(self): if self.DEBUG: print('DEBUG: %s::_finished' % self.__class__.__name__) success = False host = self._download.url().host() state = self._download.state() if state == QWebEngineDownloadItem.DownloadCompleted: success = True self._ui.downloadInfo.setText( _('Done - %s (%s)') % (host, QDateTime.currentDateTime().toString( Qt.DefaultLocaleShortDate))) elif state == QWebEngineDownloadItem.DownloadInterrupted: self._ui.donwloadInfo.setText(_('Error - %s') % host) elif state == QWebEngineDownloadItem.DownloadCancelled: self._ui.downloadInfo.setText(_('Cancelled = %s') % host) self._ui.progressBar.hide() self._ui.button.hide() self._ui.frame.hide() self._item.setSizeHint(self.sizeHint()) self._downloading = False if success and self._openFile: self.__openFile() self.downloadFinished.emit(True)
def setToDefault(wdgt=None): if isinstance(wdgt, QDoubleSpinBox) or isinstance(wdgt, QSpinBox): wdgt.setValue(-1) elif isinstance(wdgt, QCheckBox) or isinstance(wdgt, QGroupBox): wdgt.setChecked(False) elif isinstance(wdgt, QDateTimeEdit): val = QDateTime.currentDateTimeUtc() if isinstance(wdgt, QTimeEdit): val = QTime.fromString('0', '0') wdgt.setTime(val) else: wdgt.setDateTime(val) elif isinstance(wdgt, QDateEdit): wdgt.setDate(PyQt5.QtCore.QDate.currentDate()) elif isinstance(wdgt, QTimeEdit): val = QTime.fromString('0', '0') wdgt.setTime(val) elif isinstance(wdgt, QComboBox): wdgt.setCurrentIndex(0) else: wdgt.clear()
def _drawPulses(self, painter: QPainter): curTime = QDateTime.currentMSecsSinceEpoch() if curTime - self._animationStartTime <= DndWidget.ANIMATION_INITIAL_DELAY: return p = self._mousePos s = self.size() MAX_CIRCLE_RADIUS = max(p.x(), s.width() - p.x(), p.y(), s.height() - p.y()) outerRad = float(curTime - self._lastFrameTime) * (self._animationLoop + 1) outerRad *= DndWidget.ANIMATION_SPEED outerRadRatio = float(outerRad) / MAX_CIRCLE_RADIUS outerRad *= self._easingCurve.valueForProgress(outerRadRatio) INNER_RADIUS_DIFF = 20 innerRad = outerRad - INNER_RADIUS_DIFF logger.debug(f"outerRad={outerRad:.2f}, {(outerRadRatio * 100):.2f}%, " f"curTime={curTime}, lastFrameTime={self._lastFrameTime}") painter.setPen(QPen(QBrush(Qt.red), 3)) painter.drawEllipse(p, outerRad, outerRad) if innerRad > 0: painter.setPen(QPen(QBrush(Qt.blue), 3)) painter.drawEllipse(QPoint(p.x(), p.y()), innerRad, innerRad) if outerRad >= MAX_CIRCLE_RADIUS: self._animationLoop = 0
def render_bookmark_as_text(b, lines): lines.append(b['title']) date = QDateTime.fromString(b['timestamp'], Qt.DateFormat.ISODate).toLocalTime().toString(Qt.DateFormat.SystemLocaleShortDate) lines.append(date) lines.append('') lines.append('───') lines.append('')
def __init__(self, date_read, is_read_only=False, default_to_today=False, fmt=None): # debug_print("DateTableWidgetItem::__init__ - date_read=", date_read) if (date_read == UNDEFINED_DATE) and default_to_today: date_read = utcnow() if is_read_only: self.date_read = date_read if not date_read or date_read == UNDEFINED_DATE or date_read == '': date_read = '' else: date_read = format_date(date_read, fmt) QTableWidgetItem.__init__(self, date_read, QtGui.QTableWidgetItem.UserType) self.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) else: QTableWidgetItem.__init__(self, '', QtGui.QTableWidgetItem.UserType) dt = UNDEFINED_QDATETIME if date_read is None else QDateTime( date_read) # debug_print("DateTableWidgetItem::__init__ - dt=", dt) dt.setTimeSpec(Qt.UTC) dt = dt.toLocalTime() # debug_print("DateTableWidgetItem::__init__ - dt=", dt) self.setData(Qt.DisplayRole, dt) self.date_read = dt
class HistoryEntry: def __init__(self): self.id = 0 self.count = 0 self.date = QDateTime() self.url = QUrl() self.urlString = '' self.title = '' def fillDbobj(self, dbobj): for field in ('id', 'count', 'urlString', 'title'): setattr(dbobj, field, getattr(self, field)) dbobj.date = self.date.toMSecsSinceEpoch() dbobj.url = self.url.toString() @classmethod def CreateFromDbobj(cls, dbobj): entry = cls() entry.id = dbobj.id entry.count = dbobj.id entry.date = QDateTime.fromMSecsSinceEpoch(dbobj.date) entry.url = QUrl(dbobj.url) entry.urlString = entry.url.toEncoded().data().decode() entry.title = dbobj.title return entry
def _dialogAccepted(self): QApplication.setOverrideCursor(Qt.WaitCursor) if self._ui.history.isChecked(): start = QDateTime.currentMSecsSinceEpoch() end = 0 # QDate today = QDate.currentDate() week = today.addDays(1 - today.dayOfWeek()) month = QDate(today.year(), today.month(), 1) index = self._ui.historyLength.currentIndex() if index == 0: # Later Today end = QDateTime(today).toMSecsSinceEpoch() elif index == 1: # Week end = QDateTime(week).toMSecsSinceEpoch() elif index == 2: # Month end = QDateTime(month).toMSecsSinceEpoch() elif index == 3: # All end = 0 if end == 0: gVar.app.history().clearHistory() else: indexes = gVar.app.history().indexesFromTimeRange(start, end) gVar.app.history().deleteHistoryEntry(indexes) if self._ui.cookies.isChecked(): gVar.app.cookieJar().deleteAllCookies() if self._ui.cache.isChecked(): self.clearCache() if self._ui.databases.isChecked(): self.clearWebDatabases() if self._ui.localStorage.isChecked(): self.clearLocalStorage() QApplication.restoreOverrideCursor() self._ui.clear.setEnabled(False) self._ui.clear.setText(_('Done')) QTimer.singleShot(1000, self.close)
def dateTo(self, value): """function::dateTo(self, value) Auto property setter for dateTo """ value = value or QDateTime() if self._to_selector.dateTime() != value: self._to_selector.setDateTime(value) self.dateToChanged.emit(value)
def paste(self): md = QApplication.instance().clipboard().mimeData() if md.hasFormat(self.MIME_TYPE): self.setDateTime( QDateTime.fromString( md.data(self.MIME_TYPE).data().decode('ascii'), Qt.DateFormat.ISODate)) else: self.lineEdit().paste()
def __init__(self, searchString): super().__init__() self._timestamp = QDateTime.currentMSecsSinceEpoch() # qint64 self._searchString = searchString self._domainCompletion = '' self._items = [] # QList<QStandardItem> self._jobCancelled = False gVar.executor.submit(self._runJobWrap)
def keyPressEvent(self, ev): if ev.key() == Qt.Key_Minus: ev.accept() self.setDateTime(UNDEFINED_QDATETIME) elif ev.key() == Qt.Key_Equal: ev.accept() self.setDateTime(QDateTime.currentDateTime()) else: return QDateTimeEdit.keyPressEvent(self, ev)
def keyPressEvent(self, ev): if ev.key() == Qt.Key_Minus: ev.accept() self.setDateTime(self.minimumDateTime()) elif ev.key() == Qt.Key_Equal: ev.accept() self.setDateTime(QDateTime.currentDateTime()) else: return QDateTimeEdit.keyPressEvent(self, ev)
def paste(self): md = QApplication.instance().clipboard().mimeData() if md.hasFormat(self.MIME_TYPE): self.date_time_pasted.emit( QDateTime.fromString( md.data(self.MIME_TYPE).data().decode('ascii'), Qt.ISODate)) else: QLineEdit.paste(self)
def __init__(self, date_read, is_read_only=False, default_to_today=False): if date_read == UNDEFINED_DATE and default_to_today: date_read = now() if is_read_only: QTableWidgetItem.__init__(self, format_date(date_read, None), QtGui.QTableWidgetItem.UserType) self.setFlags(Qt.ItemIsSelectable|Qt.ItemIsEnabled) else: QTableWidgetItem.__init__(self, '', QtGui.QTableWidgetItem.UserType) self.setData(Qt.DisplayRole, QDateTime(date_read))
def CreateFromDbobj(cls, dbobj): entry = cls() entry.id = dbobj.id entry.count = dbobj.id entry.date = QDateTime.fromMSecsSinceEpoch(dbobj.date) entry.url = QUrl(dbobj.url) entry.urlString = entry.url.toEncoded().data().decode() entry.title = dbobj.title return entry
def render_highlight_as_text(hl, lines): lines.append(hl['highlighted_text']) date = QDateTime.fromString(hl['timestamp'], Qt.DateFormat.ISODate).toLocalTime().toString(Qt.DateFormat.SystemLocaleShortDate) lines.append(date) notes = hl.get('notes') if notes: lines.append('') lines.append(notes) lines.append('') lines.append('───') lines.append('')
def render_bookmark_as_text(b, lines, as_markdown=False, link_prefix=None): lines.append(b['title']) date = QDateTime.fromString(b['timestamp'], Qt.DateFormat.ISODate).toLocalTime().toString(Qt.DateFormat.SystemLocaleShortDate) if as_markdown and link_prefix and b['pos_type'] == 'epubcfi': link = (link_prefix + quote(b['pos'])).replace(')', '%29') date = f'[{date}]({link})' lines.append(date) lines.append('') if as_markdown: lines.append('-' * 20) else: lines.append('───') lines.append('')
def q_datetime_to_datetime(q_datetime: QDateTime): if q_datetime is None or not q_datetime.isValid(): return None return datetime(q_datetime.date().year(), q_datetime.date().month(), q_datetime.date().day(), q_datetime.time().hour(), q_datetime.time().minute(), q_datetime.time().second(), q_datetime.time().msec() * 1000)
def value(self, value): value = value or QDateTime() if not value.isValid( ) and self._start_date is not None and self._end_date is not None: date_time = self._start_date if self._default == self.Limit.min else self._end_date is_limit = True else: date_time = value is_limit = False if self.dateTime() != date_time: self.setDateTime(date_time) self.isLimit = is_limit self.valueChanged.emit(value)
def getHistoryEntry(self, text): ''' @param: text QString ''' dbobj = HistoryDbModel.select().where( HistoryDbModel.url == text).first() entry = self.HistoryEntry() if dbobj: entry.count = dbobj.count entry.date = QDateTime.fromMSecsSinceEpoch(entry.date) entry.id = dbobj.id entry.title = dbobj.title entry.url = QUrl(dbobj.url) return entry
def _init(self): from .History import History minTs = HistoryDbModel.select(peewee.fn.Min( HistoryDbModel.date)).scalar() if minTs <= 0: return today = QDate.currentDate() week = today.addDays(1 - today.dayOfWeek()) month = QDate(today.year(), today.month(), 1) currentTs = QDateTime.currentMSecsSinceEpoch() ts = currentTs while ts > minTs: tsDate = QDateTime.fromMSecsSinceEpoch(ts).date() endTs = 0 itemName = '' if tsDate == today: endTs = QDateTime(today).toMSecsSinceEpoch() itemName = _('Today') elif tsDate >= week: endTs = QDateTime(week).toMSecsSinceEpoch() itemName = _('This Week') elif tsDate.month() == month.month() and tsDate.year( ) == month.year(): endTs = QDateTime(month).toMSecsSinceEpoch() itemName = _('This Month') else: startDate = QDate(tsDate.year(), tsDate.month(), tsDate.daysInMonth()) endDate = QDate(startDate.year(), startDate.month(), 1) ts = QDateTime(startDate, QTime(23, 59, 59)).toMSecsSinceEpoch() endTs = QDateTime(endDate).toMSecsSinceEpoch() itemName = '%s %s' % (tsDate.year(), History.titleCaseLocalizedMonth( tsDate.month())) dbobj = HistoryDbModel.select().where( HistoryDbModel.date.between(endTs, ts)).first() if dbobj: item = HistoryItem(self._rootItem) item.setStartTimestamp(ts == currentTs and -1 or ts) item.setEndTimestamp(endTs) item.title = itemName item.canFetchMore = True if ts == currentTs: self._todayItem = item ts = endTs - 1
def mostVisited(self, count): ''' @param: count int @return: QVector<HistoryEntry> ''' result = [] for dbobj in HistoryDbModel.select().order_by( HistoryDbModel.count.desc()).limit(count): entry = self.HistoryEntry() entry.count = dbobj.count entry.date = QDateTime.fromMSecsSinceEpoch(dbobj.date) entry.id = dbobj.id entry.title = dbobj.title entry.url = QUrl(dbobj.url) result.append(entry) return result
def dispatch(self): # save as... self._serialRecv.unpack(bytes(self._pkgBuff)) # convert self._serialRecv.lMBrakeP = self.swapUint16(self._serialRecv.lMBrakeP) self._serialRecv.lABrakeP = self.swapUint16(self._serialRecv.lABrakeP) self._serialRecv.rMBrakeP = self.swapUint16(self._serialRecv.rMBrakeP) self._serialRecv.rABrakeP = self.swapUint16(self._serialRecv.rABrakeP) self._serialRecv.lMRotateP = self.swapUint16(self._serialRecv.lMRotateP) self._serialRecv.lARotateP = self.swapUint16(self._serialRecv.lARotateP) self._serialRecv.rMRotateP = self.swapUint16(self._serialRecv.rMRotateP) self._serialRecv.rARotateP = self.swapUint16(self._serialRecv.rARotateP) self._serialRecv.lWheelSpd = self.swapUint32(self._serialRecv.lWheelSpd) self._serialRecv.rWheelSpd = self.swapUint32(self._serialRecv.rWheelSpd) # emit self.displayRespond.emit(self._serialRecv, QDateTime.currentDateTime())
def __init__(self, parent = None): super(MainWidget, self).__init__(parent) # member variables self._lTheorySpd = 0 self._rTheorySpd = 0 self._serialSend = SerialSend() # mainWindow properties self.setObjectName('MainWidget') self.setWindowIcon(QIcon(':/image/default/app.icon')) self.setWindowTitle('%s V%s' % ( qApp.applicationDisplayName(), qApp.applicationVersion())) self.resize(800, 480) # mainWindow layout # top self.groupBoxTop = QGroupBox(self) self.groupBoxTop.setObjectName('groupBoxTop') # command dashboard buttonLeftPower = JSwitchButton(parent = self.groupBoxTop) buttonRightPower = JSwitchButton(parent = self.groupBoxTop) buttonSettings = QPushButton(self.groupBoxTop) buttonHistory = QPushButton(self.groupBoxTop) buttonQuit = QPushButton(self.groupBoxTop) buttonLeftPower.setObjectName('buttonLeftPower') buttonRightPower.setObjectName('buttonRightPower') buttonSettings.setObjectName('buttonSettings') buttonHistory.setObjectName('buttonHistory') buttonQuit.setObjectName('buttonQuit') areaPortState = QWidget(self) areaPortState.setObjectName('areaPortState') areaPortState.setStyleSheet('QWidget#areaPortState{border-radius:3px;' 'border:1px solid #505050;' 'background-color:rgba(64,64,64,50);}') vertLayoutPortState = QVBoxLayout(areaPortState) vertLayoutPortState.setContentsMargins(50, 2, 50, 2) vertLayoutPortState.setSpacing(3) buttonPortState = JSwitchButton(pixmap = QPixmap(':/carmonitor/image/button-port-state.png'), parent = areaPortState) buttonPortState.setObjectName('buttonPortState') vertLayoutPortState.addWidget(QLabel('串口', areaPortState), 0, Qt.AlignHCenter) vertLayoutPortState.addWidget(buttonPortState) # horiLayoutTop = QHBoxLayout(self.groupBoxTop) horiLayoutTop.setContentsMargins(0, 0, 0, 0) horiLayoutTop.addSpacing(25) horiLayoutTop.addWidget(buttonSettings, 0, Qt.AlignLeft) horiLayoutTop.addSpacing(20) horiLayoutTop.addWidget(buttonHistory, 0, Qt.AlignLeft) horiLayoutTop.addSpacing(65) horiLayoutTop.addWidget(buttonLeftPower) horiLayoutTop.addWidget(QLabel('左电源开关', self.groupBoxTop)) horiLayoutTop.addStretch() horiLayoutTop.addWidget(areaPortState, 0, Qt.AlignTop) horiLayoutTop.addStretch() horiLayoutTop.addWidget(QLabel('右电源开关', self.groupBoxTop)) horiLayoutTop.addWidget(buttonRightPower) horiLayoutTop.addSpacing(150) horiLayoutTop.addWidget(buttonQuit, 0, Qt.AlignRight) horiLayoutTop.addSpacing(25) # middle # curves self.curveLBP = CurveWidget(title = '左刹车压力(MPa)', parent = self) self.curveLRP = CurveWidget(title = '左转速(r/min)', parent = self) self.curveRBP = CurveWidget(title = '右刹车压力(MPa)', parent = self) self.curveRRP = CurveWidget(title = '右转速(r/min)', parent = self) self.curveLBP.setObjectName('curveLBP') self.curveLRP.setObjectName('curveLRP') self.curveRBP.setObjectName('curveRBP') self.curveRRP.setObjectName('curveRRP') # self.curveLBP.setAxisScale(QwtPlot.yLeft, 0, 30, 5) # areaMiddle self.areaMiddle = QWidget(self) self.areaMiddle.setObjectName('areaMiddle') self.areaMiddle.setFixedWidth(280) # groupBoxStatus = QGroupBox(self) groupBoxStatus.setObjectName('groupBoxStatus') # status-view gridLayoutStatus = QGridLayout(groupBoxStatus) gridLayoutStatus.setContentsMargins(5, 5, 5, 5) gridLayoutStatus.setHorizontalSpacing(8) gridLayoutStatus.setVerticalSpacing(3) # Brake-Command editLeftBrakeCmd = QLineEdit(groupBoxStatus) editRightBrakeCmd = QLineEdit(groupBoxStatus) editLeftBrakeCmd.setObjectName('editLeftBrakeCmd') editRightBrakeCmd.setObjectName('editRightBrakeCmd') editLeftBrakeCmd.setReadOnly(True) editRightBrakeCmd.setReadOnly(True) gridLayoutStatus.addWidget(QLabel('刹车指令:', groupBoxStatus), 0, 0, 1, 2, Qt.AlignCenter) gridLayoutStatus.addWidget(editLeftBrakeCmd, 1, 0, 1, 1) gridLayoutStatus.addWidget(editRightBrakeCmd, 1, 1, 1, 1) # Major Brake Pressure self.editMLeftBrakeP = QLineEdit(groupBoxStatus) self.editMRightBrakeP = QLineEdit(groupBoxStatus) self.editMLeftBrakeP.setObjectName('editMLeftBrakeP') self.editMRightBrakeP.setObjectName('editMRightBrakeP') self.editMLeftBrakeP.setReadOnly(True) self.editMRightBrakeP.setReadOnly(True) gridLayoutStatus.addWidget(QLabel('主刹车压力:', groupBoxStatus), 2, 0, 1, 2, Qt.AlignCenter) gridLayoutStatus.addWidget(self.editMLeftBrakeP, 3, 0, 1, 1) gridLayoutStatus.addWidget(self.editMRightBrakeP, 3, 1, 1, 1) # Assistant Brake Pressure self.editALeftBrakeP = QLineEdit(groupBoxStatus) self.editARightBrakeP = QLineEdit(groupBoxStatus) self.editALeftBrakeP.setObjectName('editALeftBrakeP') self.editARightBrakeP.setObjectName('editARightBrakeP') self.editALeftBrakeP.setReadOnly(True) self.editARightBrakeP.setReadOnly(True) gridLayoutStatus.addWidget(QLabel('副刹车压力:', groupBoxStatus), 4, 0, 1, 2, Qt.AlignCenter) gridLayoutStatus.addWidget(self.editALeftBrakeP, 5, 0, 1, 1) gridLayoutStatus.addWidget(self.editARightBrakeP, 5, 1, 1, 1) # Rotation Rate self.editLeftRotateRate = QLineEdit(groupBoxStatus) self.editRightRotateRate = QLineEdit(groupBoxStatus) self.editLeftRotateRate.setObjectName('editLeftRotateRate') self.editRightRotateRate.setObjectName('editRightRotateRate') gridLayoutStatus.addWidget(QLabel('实际转速:', groupBoxStatus), 6, 0, 1, 2, Qt.AlignCenter) gridLayoutStatus.addWidget(self.editLeftRotateRate, 7, 0, 1, 1) gridLayoutStatus.addWidget(self.editRightRotateRate, 7, 1, 1, 1) # Theory Rotation Rate self.editTheoryLeftRotateRate = QLineEdit(groupBoxStatus) self.editTheoryRightRotateRate = QLineEdit(groupBoxStatus) self.editTheoryLeftRotateRate.setObjectName('editTheoryLeftRotateRate') self.editTheoryRightRotateRate.setObjectName('editTheoryRightRotateRate') gridLayoutStatus.addWidget(QLabel('理论转速:', groupBoxStatus), 8, 0, 1, 2, Qt.AlignCenter) gridLayoutStatus.addWidget(self.editTheoryLeftRotateRate, 9, 0, 1, 1) gridLayoutStatus.addWidget(self.editTheoryRightRotateRate, 9, 1, 1, 1) # groupBoxCtrl = QGroupBox(self) groupBoxCtrl.setObjectName('groupBoxCtrl') # status-view gridLayoutCtrl = QGridLayout(groupBoxCtrl) gridLayoutCtrl.setContentsMargins(5, 5, 5, 5) gridLayoutCtrl.setSpacing(20) # left-button buttonLeftDashboard = JDashButton('左指令旋钮', groupBoxCtrl) buttonLeftSpeedGain = JDashButton('左转速增益', groupBoxCtrl) buttonLeftSpeedKnob = JDashButton('左转速增益', groupBoxCtrl) buttonLeftTracksip = JTracksipButton(parent = groupBoxCtrl) buttonLeftDashboard.setObjectName('buttonLeftDashboard') buttonLeftSpeedGain.setObjectName('buttonLeftSpeedGain') buttonLeftSpeedKnob.setObjectName('buttonLeftSpeedKnob') buttonLeftTracksip.setObjectName('buttonLeftTracksip') buttonLeftTracksip.setFixedSize(110, 45) # right-button buttonRightDashboard = JDashButton('右指令旋钮', groupBoxCtrl) buttonRightSpeedGain = JDashButton('右转速增益', groupBoxCtrl) buttonRightSpeedKnob = JDashButton('右转速增益', groupBoxCtrl) buttonRightTracksip = JTracksipButton(parent = groupBoxCtrl) buttonRightDashboard.setObjectName('buttonRightDashboard') buttonRightSpeedGain.setObjectName('buttonRightSpeedGain') buttonRightSpeedKnob.setObjectName('buttonRightSpeedKnob') buttonRightTracksip.setObjectName('buttonRightTracksip') buttonRightTracksip.setFixedSize(110, 45) horiLayoutTracksip = QHBoxLayout() horiLayoutTracksip.setContentsMargins(0, 0, 0, 0) horiLayoutTracksip.setSpacing(5) horiLayoutTracksip.addWidget(buttonLeftTracksip) horiLayoutTracksip.addWidget(QLabel('打滑', self), 0, Qt.AlignHCenter) horiLayoutTracksip.addWidget(buttonRightTracksip) gridLayoutCtrl.addLayout(horiLayoutTracksip, 0, 0, 1, 2) horiLayoutDashboard = QHBoxLayout() horiLayoutDashboard.setContentsMargins(0, 0, 0, 0) horiLayoutDashboard.setSpacing(5) horiLayoutDashboard.addWidget(buttonLeftDashboard) horiLayoutDashboard.addWidget(QLabel(' ', self), 0, Qt.AlignHCenter) horiLayoutDashboard.addWidget(buttonRightDashboard) gridLayoutCtrl.addLayout(horiLayoutDashboard, 1, 0, 1, 2) horiLayoutSpeedGain = QHBoxLayout() horiLayoutSpeedGain.setContentsMargins(0, 0, 0, 0) horiLayoutSpeedGain.setSpacing(5) horiLayoutSpeedGain.addWidget(buttonLeftSpeedGain) horiLayoutSpeedGain.addWidget(QLabel('(粗调)', self), 0, Qt.AlignHCenter) horiLayoutSpeedGain.addWidget(buttonRightSpeedGain) gridLayoutCtrl.addLayout(horiLayoutSpeedGain, 2, 0, 1, 2) horiLayoutSpeedKnob = QHBoxLayout() horiLayoutSpeedKnob.setContentsMargins(0, 0, 0, 0) horiLayoutSpeedKnob.setSpacing(5) horiLayoutSpeedKnob.addWidget(buttonLeftSpeedKnob) horiLayoutSpeedKnob.addWidget(QLabel('(细调)', self), 0, Qt.AlignHCenter) horiLayoutSpeedKnob.addWidget(buttonRightSpeedKnob) gridLayoutCtrl.addLayout(horiLayoutSpeedKnob, 3, 0, 1, 2) # vertLayoutMid = QVBoxLayout(self.areaMiddle) vertLayoutMid.setContentsMargins(0, 0, 0, 0) vertLayoutMid.setSpacing(0) vertLayoutMid.addWidget(groupBoxStatus) vertLayoutMid.addWidget(groupBoxCtrl) vertLayoutMid.addSpacing(20) # gridLayoutBottom = QGridLayout() gridLayoutBottom.setContentsMargins(0, 0, 0, 0) gridLayoutBottom.setSpacing(1) gridLayoutBottom.addWidget(self.curveLBP, 0, 0, 1, 1) gridLayoutBottom.addWidget(self.curveLRP, 1, 0, 1, 1) gridLayoutBottom.addWidget(self.areaMiddle, 0, 1, 2, 1) gridLayoutBottom.addWidget(self.curveRBP, 0, 2, 1, 1) gridLayoutBottom.addWidget(self.curveRRP, 1, 2, 1, 1) # main-layout vertLayoutMain = QVBoxLayout(self) vertLayoutMain.setContentsMargins(5, 5, 5, 5) vertLayoutMain.addWidget(self.groupBoxTop) vertLayoutMain.addLayout(gridLayoutBottom) # global properties qApp.setProperty('MainWidget', self) self._serialProxy = SerialPortProxy(self) self._serialProxy._serialSimulate = SerialSimulate(self._serialProxy) # qApp.setProperty('SerialProxy', self._serialProxy) # buttonSettings.clicked.connect(self.onButtonSettingsClicked) buttonHistory.clicked.connect(self.onButtonHistoryClicked) buttonPortState.clicked.connect(self.onButtonPortStateClicked) buttonQuit.clicked.connect(self.onButtonQuitClicked) # curves self.curveLBP.doubleClicked.connect(self.onCurveDoubleClicked) self.curveLRP.doubleClicked.connect(self.onCurveDoubleClicked) self.curveRBP.doubleClicked.connect(self.onCurveDoubleClicked) self.curveRRP.doubleClicked.connect(self.onCurveDoubleClicked) # switch-power buttonLeftPower.stateChanged.connect(self.onButtonLeftPowerStateChanged) buttonRightPower.stateChanged.connect(self.onButtonRightPowerStateChanged) # switch-tracksip buttonLeftTracksip.stateChanged.connect(self.onButtonLeftTracksipStateChanged) buttonRightTracksip.stateChanged.connect(self.onButtonRightTracksipStateChanged) self._serialProxy.stateChanged.connect(self.onSerialStateChanged) self._serialProxy.serialPortError.connect(self.onSerialPortError) self._serialProxy.displayRespond.connect(self.onSerialDisplayRespond) # buttonLeftSpeedGain.clicked.connect(self.execSliderWidget) buttonLeftSpeedKnob.clicked.connect(self.execSliderWidget) buttonRightSpeedGain.clicked.connect(self.execSliderWidget) buttonRightSpeedKnob.clicked.connect(self.execSliderWidget) # final initialization self.editMLeftBrakeP.setText('0 MPa') self.editMRightBrakeP.setText('0 MPa') self.editALeftBrakeP.setText('0 MPa') self.editARightBrakeP.setText('0 MPa') self.editLeftRotateRate.setText('0 r/min') self.editRightRotateRate.setText('0 r/min') self.editTheoryLeftRotateRate.setText('0 r/min') self.editTheoryRightRotateRate.setText('0 r/min') # c_memset(self._serialSend, 0, ctypes.sizeof(self._serialSend)) # SQL sqlName = applicationDirPath() \ + '/../data/cm-' \ + QDateTime.currentDateTime().toLocalTime().toString('yyyy-MM-dd-HH-mm-ss') \ + '.db' if not DatabaseMgr().create(sqlName): assert(False) # start serialport self._serialProxy.start() # buttonLeftTracksip.setState(self._serialSend.ctrlWord.lTracksip) buttonRightTracksip.setState(self._serialSend.ctrlWord.lTracksip)
def today_date(self): self.setDateTime(QDateTime.currentDateTime())
def __init__(self, window, rows, model, tab, refresh_books): ResizableDialog.__init__(self, window) Ui_MetadataBulkDialog.__init__(self) self.model = model self.db = model.db self.refresh_book_list.setChecked(gprefs['refresh_book_list_on_bulk_edit']) self.refresh_book_list.toggled.connect(self.save_refresh_booklist) self.ids = [self.db.id(r) for r in rows] self.first_title = self.db.title(self.ids[0], index_is_id=True) self.cover_clone.setToolTip(unicode(self.cover_clone.toolTip()) + ' (%s)' % self.first_title) self.box_title.setText('<p>' + _('Editing meta information for <b>%d books</b>') % len(rows)) self.write_series = False self.changed = False self.refresh_books = refresh_books self.comments = null self.comments_button.clicked.connect(self.set_comments) all_tags = self.db.all_tags() self.tags.update_items_cache(all_tags) self.remove_tags.update_items_cache(all_tags) self.initialize_combos() for f in sorted(self.db.all_formats()): self.remove_format.addItem(f) self.remove_format.setCurrentIndex(-1) self.series.currentIndexChanged[int].connect(self.series_changed) self.series.editTextChanged.connect(self.series_changed) self.tag_editor_button.clicked.connect(self.tag_editor) self.autonumber_series.stateChanged[int].connect(self.auto_number_changed) self.pubdate.setMinimumDateTime(UNDEFINED_QDATETIME) self.pubdate_cw = CalendarWidget(self.pubdate) self.pubdate.setCalendarWidget(self.pubdate_cw) pubdate_format = tweaks['gui_pubdate_display_format'] if pubdate_format is not None: self.pubdate.setDisplayFormat(pubdate_format) self.pubdate.setSpecialValueText(_('Undefined')) self.clear_pubdate_button.clicked.connect(self.clear_pubdate) self.pubdate.dateTimeChanged.connect(self.do_apply_pubdate) self.adddate.setDateTime(QDateTime.currentDateTime()) self.adddate.setMinimumDateTime(UNDEFINED_QDATETIME) adddate_format = tweaks['gui_timestamp_display_format'] if adddate_format is not None: self.adddate.setDisplayFormat(adddate_format) self.adddate.setSpecialValueText(_('Undefined')) self.clear_adddate_button.clicked.connect(self.clear_adddate) self.adddate.dateTimeChanged.connect(self.do_apply_adddate) if len(self.db.custom_field_keys(include_composites=False)) == 0: self.central_widget.removeTab(1) else: self.create_custom_column_editors() self.prepare_search_and_replace() self.button_box.clicked.connect(self.button_clicked) self.button_box.button(QDialogButtonBox.Apply).setToolTip(_( 'Immediately make all changes without closing the dialog. ' 'This operation cannot be canceled or undone')) self.do_again = False self.central_widget.setCurrentIndex(tab) geom = gprefs.get('bulk_metadata_window_geometry', None) if geom is not None: self.restoreGeometry(bytes(geom)) ct = gprefs.get('bulk_metadata_window_tab', 0) self.central_widget.setCurrentIndex(ct) self.languages.init_langs(self.db) self.languages.setEditText('') self.authors.setFocus(Qt.OtherFocusReason) self.exec_()
def drawGridX(self, painter): rect = self.getRectPlotter() if not rect.isValid(): return painter.save() painter.setFont(self._fontGrid) painter.setPen(QPen(Qt.black)) painter.setBrush(Qt.NoBrush) # Axis ticks dxmsec = rect.width() / self._plotterScale.Scale.X.span() fontMetricsF = QFontMetricsF(self._fontGrid) index = findIndex(fontMetricsF.width(' 00:00 ') / dxmsec, BasePlotter._mSecs_for_grid) msec0 = self._plotterScale.Scale.X.Min offset = findOffset(msec0, BasePlotter._mSecs_for_grid[index]) dx = dxmsec * BasePlotter._mSecs_for_grid[index] step = BasePlotter._mSecs_for_grid[index] for x in numpy.arange(rect.left() - dxmsec * offset, rect.right(), dx): if x < rect.left(): continue painter.save() heightTick = 3 datetimelabel = QDateTime.fromMSecsSinceEpoch(msec0, Qt.UTC) if step >= 60000: # больше минуты if step >= 86400000: # больше суток label = datetimelabel.toString('dd.MM.yy') if datetimelabel.time().minute() == 0: heightTick = 8 painter.setPen(Qt.SolidLine) else: t0 = QDateTime.fromMSecsSinceEpoch(self._plotterScale.Scale.X.Min, Qt.UTC) t1 = QDateTime.fromMSecsSinceEpoch(self._plotterScale.Scale.X.Max, Qt.UTC) if (datetimelabel.time().hour() == 0 and datetimelabel.time().minute() == 0) and ( t1.date() > t0.date()): # Метка даты. Появляется,если листаем график между днями font = QFont(painter.font().family(), painter.font().pointSize()) font.setBold(True) painter.setFont(font) label = datetimelabel.toString('dd.MM.yy') else: label = datetimelabel.toString('hh:mm') if datetimelabel.time().minute() == 0: heightTick = 8 painter.setPen(Qt.SolidLine) if datetimelabel.time().minute() == 30: heightTick = 6 painter.setPen(Qt.DashLine) if datetimelabel.time().minute() == 15 or datetimelabel.time().minute() == 45: heightTick = 4 painter.setPen(Qt.DashLine) else: label = datetimelabel.time().toString('hh:mm:ss') painter.drawLine(x, rect.bottom(), x, rect.top()) rect_label = QRectF(x - fontMetricsF.width(label) / 2, rect.bottom() + heightTick, fontMetricsF.width(label), 2 * fontMetricsF.height()) painter.drawLine(x, rect.bottom() - heightTick, x, rect.bottom() + heightTick) painter.drawText(rect_label, label) msec0 += step painter.restore() painter.restore()