Esempio n. 1
0
 def getOptions(self) -> Tuple[List[QDateTime], bool, bool]:
     dates = list()
     byTime: bool = self.body.byTime.isChecked()
     byDate: bool = self.body.byDate.isChecked()
     for row in self.__layoutRows:
         date: QDate = self.body.gLayout.itemAtPosition(row,
                                                        0).widget().date()
         time: QTime = self.body.gLayout.itemAtPosition(row,
                                                        2).widget().time()
         if byDate and byTime:
             datetime = QDateTime(date, time, Qt.UTC)
         elif not byTime:
             # Date only
             datetime = QDateTime(date, self.DEFAULT_TIME, Qt.UTC)
         elif not byDate:
             # Time only
             datetime = QDateTime(self.DEFAULT_DATE, time, Qt.UTC)
         else:
             flogging.appLogger.error(
                 'Invalid byDate/byTime combination: {}, {}'.format(
                     byDate, byTime))
             raise ValueError(
                 'Unexpected error: unsupported datetime input arguments')
         dates.append(datetime)
     return dates, byDate, byTime
Esempio n. 2
0
    def __init__(self, parent=None):
        super(MyWidget, self).__init__(parent)

        self.view = View()
        self.grid = DateTimeGrid()
        self.model = QStandardItemModel()
        self.slider = QSlider()
        self.view.setGraphicsView(MyGraphicsView())

        ## proxyModel.setSourceModel( &model );
        for h in range(0, 2):
            self.model.appendRow([
                MyStandardItem("Item " + str(h)),
                MyStandardItem(KDGantt.TypeTask),
                MyStandardItem(QDateTime.currentDateTime().addDays(h),
                               KDGantt.StartTimeRole),
                MyStandardItem(QDateTime.currentDateTime().addDays(h + 1),
                               KDGantt.EndTimeRole),
                MyStandardItem(50)
            ])

        self.slider.setOrientation(Qt.Horizontal)
        self.slider.setRange(1, 10000)
        self.slider.setValue(100)
        l = QVBoxLayout(self)
        l.addWidget(self.view)
        l.addWidget(self.slider)
        self.grid.setStartDateTime(QDateTime.currentDateTime().addDays(-3))
        self.grid.setDayWidth(100)
        ## grid.setNoInformationBrush( Qt::NoBrush );
        self.view.setGrid(self.grid)
        self.view.setModel(self.model)

        self.slider.valueChanged.connect(self.slotZoom)
Esempio n. 3
0
    def initialize_code(self):
        self.cboPeriod.currentTextChanged.connect(self.selectPeriod)
        self.cboPeriod.setCurrentIndex(3)   # This Week
        # self.cboPeriod.setCurrentIndex(5)   # This Month
        self.listTimers.currentItemChanged.connect(self.selectTimer)
        self.listTimers.itemClicked.connect(self.selectTimer)
        self.listTimers.itemDoubleClicked.connect(self.startTimer)
        self.btnStart.hide()
        self.btnStart.clicked.connect(self.startTimer)
        self.btnAddLap.hide()
        self.btnAddLap.clicked.connect(self.addLap)
        self.btnDeleteTimer.setEnabled(0)
        self.btnDeleteTimer.clicked.connect(self.deleteTimer)
        self.btnDeleteTimer.setEnabled(False)
        self.btnPencil.clicked.connect(self.btnPencil_Clicked)
        self.btnEditLaps.clicked.connect(self.btnEditLaps_Clicked)

        today = datetime.today()
        yesterday = today - timedelta(days=1)
        self.dtFromFilter.setDateTime(QDateTime(yesterday.year, yesterday.month, yesterday.day, 0, 0, 0))
        self.dtToFilter.setDateTime(QDateTime(today.year, today.month, today.day, 0, 0, 0))
        # self.dtFromFilter.show()
        # self.dtToFilter.show()

        # Initialise Timer state:
        periodFilter = self.cboPeriod.currentText();
        for timer in self.timers.timers:
            timer.set_period_filter(periodFilter)

        self.redraw_timers()    # Populate Timers for the first time:
Esempio n. 4
0
    def create(self, name_project):
        """
        
        :param name_project: Name of the project
        :return: path of the settings file
        """
        from PySide2.QtCore import QDateTime
        self.name_project = name_project
        #print("from python " + self.name_project)
        self.settings = QSettings("Nebula", self.name_project)
        
        self.settings.beginGroup("Project")
        self.settings.setValue("Path", os.path.join(os.environ['HOME'], '.config/Nebula', self.name_project + '.conf'))
        self.settings.setValue("Name", self.name_project)
        self.settings.setValue("Date", QDateTime.currentDateTime().toString())
        self.settings.setValue("LastEdit", QDateTime.currentDateTime().toString())
        self.settings.endGroup()
        
        self.settings.beginGroup("SignalFiles")
        self.settings.setValue("Path", "None")  # Paths of the signals
        self.settings.setValue("ValuePath", "None")  # Value paths of the signals -numpy file
        self.settings.endGroup()

        self.settings.beginGroup("Info")
        self.settings.endGroup()
        
        print(self.settings.fileName())
        
        return self.settings.fileName()
    async def _requestMore(self):
        logger.debug("Request more messages from channel %s", self.channelId)
        url = BASE_URL + 'channels.history'
        params = {
            'token': self.slackService.token,
            'channel': self.channelId,
            'count': MESSAGE_REQUEST_COUNT,
            'latest': self._latest
        }
        async with self.slackService.session.get(url,
                                                 headers=HEADERS,
                                                 params=params) as resp:
            logger.debug("response: %s", resp)
            data = await resp.json()
            #logger.debug("data: %s", data)
            messageData = data['messages']
            if messageData:
                self._latest = messageData[0]['ts']
            messages = [
                MessagesItem(ts=QDateTime.fromMSecsSinceEpoch(
                    float(m['ts']) * 1000),
                             date=QDateTime.fromMSecsSinceEpoch(
                                 float(m['ts']) * 1000).date(),
                             time=QDateTime.fromMSecsSinceEpoch(
                                 float(m['ts']) * 1000).time(),
                             user=m.get('username', m.get('user')),
                             text=m['text']) for m in data['messages']
                if m['type'] == 'message'
            ]

            self.addItems(list(reversed(messages)))
Esempio n. 6
0
def createMailModel(parent):
    model = QStandardItemModel(0, 3, parent)

    model.setHeaderData(SUBJECT, Qt.Horizontal, "Subject")
    model.setHeaderData(SENDER, Qt.Horizontal, "Sender")
    model.setHeaderData(DATE, Qt.Horizontal, "Date")

    addMail(model, "Happy New Year!", "Grace K. <*****@*****.**>",
            QDateTime(QDate(2006, 12, 31), QTime(17, 3)))
    addMail(model, "Radically new concept",
            "Grace K. <*****@*****.**>",
            QDateTime(QDate(2006, 12, 22), QTime(9, 44)))
    addMail(model, "Accounts", "*****@*****.**",
            QDateTime(QDate(2006, 12, 31), QTime(12, 50)))
    addMail(model, "Expenses", "Joe Bloggs <*****@*****.**>",
            QDateTime(QDate(2006, 12, 25), QTime(11, 39)))
    addMail(model, "Re: Expenses", "Andy <*****@*****.**>",
            QDateTime(QDate(2007, 1, 2), QTime(16, 5)))
    addMail(model, "Re: Accounts", "Joe Bloggs <*****@*****.**>",
            QDateTime(QDate(2007, 1, 3), QTime(14, 18)))
    addMail(model, "Re: Accounts", "Andy <*****@*****.**>",
            QDateTime(QDate(2007, 1, 3), QTime(14, 26)))
    addMail(model, "Sports", "Linda Smith <*****@*****.**>",
            QDateTime(QDate(2007, 1, 5), QTime(11, 33)))
    addMail(model, "AW: Sports", "Rolf Newschweinstein <*****@*****.**>",
            QDateTime(QDate(2007, 1, 5), QTime(12, 0)))
    addMail(model, "RE: Sports", "Petra Schmidt <*****@*****.**>",
            QDateTime(QDate(2007, 1, 5), QTime(12, 1)))

    return model
Esempio n. 7
0
def transform_date(utc, timezone=None):
    utc_fmt = "yyyy-MM-ddTHH:mm:ss.zzzZ"
    new_date = QDateTime().fromString(utc, utc_fmt)
    if timezone:
        new_date.setTimeZone(timezone)

    return new_date
Esempio n. 8
0
    def __init__(self):
        QMainWindow.__init__(self)

        # 设置时间
        self.__time = QDateTime()

        # 创建图形界面
        self.__SetupUI()

        self.__ConfigureFileToolBar()

        self.__ConfigureTranslateToolBar()

        self.__ConfigureMainLayout()

        # 设置ComboBox的显示内容
        self.__ConfigureComboBox()

        # 设置保存文件的信息
        self.__currentPath = QDir.currentPath()

        self.__ConfigureSysIniFile()

        self.__ConfigureHistoryFile()

        salt = random.randint(1466000000, 1467000000)
        self.__salt = str(salt)

        self.__httpClient = None

        self.__statusBar.showMessage(
            self.__GetCurrentTime() + " - Please choose a file or enter data!",
            2000)

        self.show()
Esempio n. 9
0
 def _timeSpan(self):
     tmin = np.inf
     tmax = -np.inf
     for p in self._portToIdx:
         t = self._currentFile["streams"][p][0]["rcvTimestamp"]
         tmin = min(t, tmin)
         t = self._currentFile["streams"][p][-1]["rcvTimestamp"]
         tmax = max(t, tmax)
     return QDateTime.fromMSecsSinceEpoch(tmin//1000), QDateTime.fromMSecsSinceEpoch(tmax//1000)
Esempio n. 10
0
    def testQDateTimeNull(self):
        '''QDataStream <<>> QDateTime - null'''

        self.stream << QDateTime()

        res = QDateTime()

        self.read_stream >> res
        self.assertEqual(res, QDateTime())
        self.assertFalse(res.isValid())
        self.assertTrue(res.isNull())
Esempio n. 11
0
 def __init__(self, db):
     self.db = db
     self.current = []
     self.current_seq = -1
     self.balances_view = None
     self.holdings_view = None
     self.balance_active_only = 1
     self.balance_currency = None
     self.balance_date = QDateTime.currentSecsSinceEpoch()
     self.holdings_date = QDateTime.currentSecsSinceEpoch()
     self.holdings_currency = None
Esempio n. 12
0
 def onReportRangeChange(self, range_index):
     report_ranges = {
         0: lambda: (0, 0),
         1: ManipulateDate.Last3Months,
         2: ManipulateDate.RangeYTD,
         3: ManipulateDate.RangeThisYear,
         4: ManipulateDate.RangePreviousYear
     }
     begin, end = report_ranges[range_index]()
     self.ReportFromDate.setDateTime(QDateTime.fromSecsSinceEpoch(begin))
     self.ReportToDate.setDateTime(QDateTime.fromSecsSinceEpoch(end))
Esempio n. 13
0
    def connect(self):
        if self.checkbox.isChecked():
            print("connecting " + self.ip)
            self.timer.start(sample_interval_secs * 1000)
            self.tti = ttiPsu(self.ip, self.channel)

            dtime = datetime.datetime.now()
            self.time.setText(dtime.strftime('%c'))

            #get data
            data = self.tti.GetData()
            data.print()

            self.name.setText(data.identity)
            self.target_voltage_input.setText("{0:.3f}".format(
                data.target_volts))
            self.target_voltage_output.setText("setpoint: {0:.3f}".format(
                data.target_volts))
            self.output_voltage.setText("{0:.3f}".format(data.out_volts))
            self.current_limit_input.setText("{0}".format(
                int(data.target_amps * 1000)))
            self.current_limit_output.setText("setpoint: {0}".format(
                int(data.target_amps * 1000)))
            self.output_current.setText("{0}".format(int(data.out_amps *
                                                         1000)))
            isON = self.tti.getOutputIsEnabled()

            if data.is_enabled:
                self.switch_output.setText("Output is ON")
            else:
                self.switch_output.setText("Output is OFF")

            self.series_voltage.append(
                QDateTime().currentDateTime().toMSecsSinceEpoch(),
                data.out_volts)
            self.series_current.append(
                QDateTime().currentDateTime().toMSecsSinceEpoch(),
                data.out_amps * 1000)
            self.axisX.setMin(QDateTime().currentDateTime().addSecs(-60))
            self.axisX.setMax(QDateTime().currentDateTime())

        else:
            print("disconnecting...")
            self.timer.stop()
            self.tti.setLocal()
            del self.tti

            self.name.setText("")
            self.time.setText("")
            self.output_voltage.setText("")
            self.output_current.setText("")
            self.switch_output.setText("")
            print("disconnect successfully.")
Esempio n. 14
0
    def widgets(self):
        self.scroll = QScrollArea()
        self.scroll.setWidgetResizable(True)

        # Top layout widgets
        self.addIssueImg = QLabel()
        self.img = QPixmap('assets/icons/create-issue.png')
        self.addIssueImg.setPixmap(self.img)
        self.addIssueImg.setAlignment(Qt.AlignCenter)
        self.titleText = QLabel("Add issue")
        self.titleText.setAlignment(Qt.AlignCenter)
        # Middle layout widgets
        self.issueInfoTitleText = QLabel("Issue info")
        self.issueInfoTitleText.setAlignment(Qt.AlignCenter)
        self.dateEntry = QDateTimeEdit()
        self.dateEntry.setDateTime(QDateTime.currentDateTime())
        self.priorityEntry = QComboBox()
        self.priorityEntry.setEditable(True)
        self.observerEntry = QComboBox()
        self.observerEntry.setEditable(True)
        self.revisionTeamEntry = QComboBox()
        self.revisionTeamEntry.setEditable(True)
        self.inspectionNameEntry = QComboBox()
        self.inspectionNameEntry.setEditable(True)
        self.observationThemeEntry = QComboBox()
        self.observationThemeEntry.setEditable(True)
        self.facilityEntry = QComboBox()
        self.facilityEntry.setEditable(True)
        self.facilitySupervisorEntry = QComboBox()
        self.facilitySupervisorEntry.setEditable(True)
        self.specificLocationEntry = QTextEdit()
        self.inspectedDepartmentEntry = QComboBox()
        self.inspectedDepartmentEntry.setEditable(True)
        self.inspectedContractorEntry = QComboBox()
        self.inspectedContractorEntry.setEditable(True)
        self.inspectedSubcontractorEntry = QComboBox()
        self.inspectedSubcontractorEntry.setEditable(True)
        self.deadlineEntry = QDateTimeEdit()
        self.deadlineEntry.setDateTime(QDateTime.currentDateTime())

        # Bottom layout widgets
        self.attachFilesBtn = QPushButton("Attach files")
        self.addActionBtn = QPushButton("Add action")

        self.rootCauseEntry = QComboBox()
        self.rootCauseEntry.setEditable(True)
        self.rootCauseDetailsEntry = QTextEdit()
        self.rootCauseActionPartyEntry = QComboBox()
        self.rootCauseActionPartyEntry.setEditable(True)
        self.addRootCauseBtn = QPushButton("Add root cause")

        self.submitObservationBtn = QPushButton("Add issue")
        self.submitObservationBtn.clicked.connect(self.addIssue)
Esempio n. 15
0
    def testQDateTimeValid(self):
        '''QDataStream <<>> QDateTime - valid'''
        time = QTime(23, 23, 23)
        date = QDate(2009, 1, 1)

        self.stream << QDateTime(date, time)

        res = QDateTime()

        self.read_stream >> res
        self.assertEqual(res, QDateTime(date, time))
        self.assertTrue(res.isValid())
        self.assertFalse(res.isNull())
Esempio n. 16
0
 def Timeupdate(self):  # 用于实时获取时间
     self.timer.setText(
         QDateTime.currentDateTime().toString('yyyy-MM-dd hh:mm:ss dddd'))
     current_time = QDateTime.currentDateTime().toString(
         'yyyy-MM-dd hh:mm:ss dddd')
     if (int(current_time[11]) >= 2 and int(current_time[12]) >= 3) or (int(
             current_time[11]) == 0 and int(current_time[12]) <= 4):
         if int(current_time[5]) == 0 and int(current_time[6]) == 4 and int(
                 current_time[8]) == 1 and int(
                     current_time[9]) == 7:  # 生日特殊处理
             self.greetings.setText('21岁生日快乐,' + self.username)
         else:
             self.greetings.setText('夜深了,' + self.username)
Esempio n. 17
0
    def __init__(self, x, y, width, height, text):
        """
        A Rectangle with some text in it
        :param text: str
        :param x: float
        :param y: float
        :param height: float
        :param width: float
        """
        self.id = LaunchButton.ID
        LaunchButton.ID += 1
        print("my self.id = ", str(self.id))
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.text = text
        # super(SelectFolderButton, self).__init__(self.x, self.y, self.width, self.height)
        QObject.__init__(self)
        QGraphicsRectItem.__init__(self, self.x, self.y, self.width, self.height)
        self.setAcceptHoverEvents(True)

        # self.text = HText("Select Folder", self.x + self.width - 20, self.y + height / 2, self, 45)
        # self.text = HText("Select Folder", self.x + 5, self.y + 5, self, 45)

        # simple state array, represented as a numpy array, 0 = False, 1 = True
        # [0] = ZIPPED, [1] = SENT, [2] = SUBMITTED, [3] = FINISHED, [4] = DELIVERED
        self.state = np.zeros(5)
        self.state[0] = 1
        print(self.state.any())
        # indexes = np.array(np.where(self.state == 1))
        # indexes = list(np.where(self.state == 1))
        indexes = np.where(self.state == 1)
        print("TYPE")
        print(type(indexes))
        # indexes.append(3)
        print("index state = ", indexes)
        print("len = ", len(indexes))

        print("state = \n", self.state)

        self.mpen = scene_objects.initialize_qpen(QColor(7, 133, 192), width=2)

        # main block color
        self.current_color = QColor(7, 133, 192)

        # self.current_color_1 = Qt.gray
        # self.current_color_2 = Qt.gray
        self.i = 0
        self.qdate_time = QDateTime()
        print("################################################################################\n")
Esempio n. 18
0
 def toQtCookie(PyCookie):
     qc = QNetworkCookie(PyCookie.name, PyCookie.value)
     qc.setSecure(PyCookie.secure)
     if PyCookie.path_specified:
         qc.setPath(PyCookie.path)
     if PyCookie.domain != "":
         qc.setDomain(PyCookie.domain)
     if PyCookie.expires and PyCookie.expires != 0:
         t = QDateTime()
         t.setTime_t(PyCookie.expires)
         qc.setExpirationDate(t)
     # not yet handled(maybe less useful):
     #   py cookie.rest / QNetworkCookie.setHttpOnly()
     return qc
Esempio n. 19
0
    def testQDateTime6arg(self):
        dateTime = datetime.datetime(2010, 4, 23, 11, 14, 7)
        other = QDateTime(dateTime)

        otherDate = other.date()
        self.assertEqual(dateTime.year, otherDate.year())
        self.assertEqual(dateTime.month, otherDate.month())
        self.assertEqual(dateTime.day, otherDate.day())

        otherTime = other.time()
        self.assertEqual(dateTime.hour, otherTime.hour())
        self.assertEqual(dateTime.minute, otherTime.minute())
        self.assertEqual(dateTime.second, otherTime.second())
        self.assertEqual(dateTime.microsecond/1000, otherTime.msec())

        self.assertEqual(dateTime, other.toPython())
 def from_string(self, text, original_value):
     if isinstance(original_value, QColor):
         match = self.color_exp.match(text)
         return QColor(min(int(match.captured(1)), 255),
                       min(int(match.captured(2)), 255),
                       min(int(match.captured(3)), 255),
                       min(int(match.captured(4)), 255))
     if isinstance(original_value, QDate):
         value = QDate.fromString(text, Qt.ISODate)
         return value if value.isValid() else None
     if isinstance(original_value, QDateTime):
         value = QDateTime.fromString(text, Qt.ISODate)
         return value if value.isValid() else None
     if isinstance(original_value, QTime):
         value = QTime.fromString(text, Qt.ISODate)
         return value if value.isValid() else None
     if isinstance(original_value, QPoint):
         match = self.point_exp.match(text)
         return QPoint(int(match.captured(1)),
                       int(match.captured(2)))
     if isinstance(original_value, QRect):
         match = self.rect_exp.match(text)
         return QRect(int(match.captured(1)),
                      int(match.captured(2)),
                      int(match.captured(3)),
                      int(match.captured(4)))
     if isinstance(original_value, QSize):
         match = self.size_exp.match(text)
         return QSize(int(match.captured(1)),
                      int(match.captured(2)))
     if isinstance(original_value, list):
         return text.split(',')
     return type(original_value)(text)
Esempio n. 21
0
    def createBottomRightGroupBox(self):
        self.bottomRightGroupBox = QGroupBox("Group 3")
        self.bottomRightGroupBox.setCheckable(True)
        self.bottomRightGroupBox.setChecked(True)

        lineEdit = QLineEdit('s3cRe7')
        lineEdit.setEchoMode(QLineEdit.Password)

        spinBox = QSpinBox(self.bottomRightGroupBox)
        spinBox.setValue(50)

        dateTimeEdit = QDateTimeEdit(self.bottomRightGroupBox)
        dateTimeEdit.setDateTime(QDateTime.currentDateTime())

        slider = QSlider(Qt.Horizontal, self.bottomRightGroupBox)
        slider.setValue(40)

        scrollBar = QScrollBar(Qt.Horizontal, self.bottomRightGroupBox)
        scrollBar.setValue(60)

        dial = QDial(self.bottomRightGroupBox)
        dial.setValue(30)
        dial.setNotchesVisible(True)

        layout = QGridLayout()
        layout.addWidget(lineEdit, 0, 0, 1, 2)
        layout.addWidget(spinBox, 1, 0, 1, 2)
        layout.addWidget(dateTimeEdit, 2, 0, 1, 2)
        layout.addWidget(slider, 3, 0)
        layout.addWidget(scrollBar, 4, 0)
        layout.addWidget(dial, 3, 1, 2, 1)
        layout.setRowStretch(5, 1)
        self.bottomRightGroupBox.setLayout(layout)
Esempio n. 22
0
def computeAxisValue(axis: Optional[QtCharts.QAbstractAxis],
                     value: float) -> str:
    """ Provide the label to be visualized at coordinate 'value' of the specified axis """
    if not axis:
        return '-'
    if axis.type() == QtCharts.QAbstractAxis.AxisTypeDateTime:
        axis: QtCharts.QDateTimeAxis
        try:
            qDate = QDateTime.fromMSecsSinceEpoch(int(value))
        except OverflowError as e:
            flogging.appLogger.warning('Axis value error: {}'.format(str(e)))
            text = '-'
        else:
            text = qDate.toString(axis.format())
    elif axis.type() == QtCharts.QAbstractAxis.AxisTypeBarCategory:
        axis: QtCharts.QBarCategoryAxis
        categories = axis.categories()
        if 0 <= round(value) < len(categories):
            text = axis.at(round(value))
        else:
            text = '-'
    elif axis.type() == QtCharts.QAbstractAxis.AxisTypeCategory:
        axis: QtCharts.QCategoryAxis
        categories = axis.categoriesLabels()
        if 0 <= round(value) < len(categories):
            text = axis.categoriesLabels()[round(value)]
        else:
            text = '-'
    else:
        text = '{0:.2f}'.format(value)
    return text
Esempio n. 23
0
    def testQDateTime6arg(self):
        dateTime = datetime.datetime(2010, 4, 23, 11, 14, 7)
        other = QDateTime(dateTime)

        otherDate = other.date()
        self.assertEqual(dateTime.year, otherDate.year())
        self.assertEqual(dateTime.month, otherDate.month())
        self.assertEqual(dateTime.day, otherDate.day())

        otherTime = other.time()
        self.assertEqual(dateTime.hour, otherTime.hour())
        self.assertEqual(dateTime.minute, otherTime.minute())
        self.assertEqual(dateTime.second, otherTime.second())
        self.assertEqual(dateTime.microsecond/1000, otherTime.msec())

        self.assertEqual(dateTime, other.toPython())
Esempio n. 24
0
 def __init__(self, mainwindow):
     super(self.__class__, self).__init__()
     self.setupUi(self)
     self.setStyleSheet(qss)
     self.mainwindow = mainwindow
     self.k_thread = QThreadPool()
     # calendar
     self.start.setCalendarPopup(True)
     self.end.setCalendarPopup(True)
     self.start.setDisplayFormat('yyyy-MM-dd HH:mm:ss')
     self.end.setDisplayFormat('yyyy-MM-dd HH:mm:ss')
     now = datetime.now() - timedelta(days=30)
     self.start.setDate(QDate(now.year, now.month, now.day))
     self.end.setDateTime(QDateTime.currentDateTime())
     #
     for local_symbol in sorted(G.all_contracts):
         self.symbol_list.addItem(local_symbol + contract_space + G.all_contracts[local_symbol])  # 添加下拉框
     self.symbol_list.currentIndexChanged.connect(self.symbol_change_slot)
     self.frq.addItems(['1min', '3min', '15min', '30min', '60min'])
     # table
     self.tick_table.setRowCount(0)
     self.tick_row = len(G.order_tick_row_map)
     self.tick_table.horizontalHeader().setStretchLastSection(True)  # 最后一列自适应表格宽度
     # self.tick_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)  # 所有列自适应表格宽度
     self.tick_table.setEditTriggers(QTableWidget.NoEditTriggers)  # 单元格不可编辑
     self.tick_table.horizontalHeader().setVisible(False)  # 水平表头不可见
     self.tick_table.verticalHeader().setVisible(False)  # 垂直表头不可见
     # btn
     self.source_btn.clicked.connect(self.source_btn_slot)
     self.hide_btn.clicked.connect(self.hide_btn_slot)
     self.reload_btn.clicked.connect(self.k_line_reload)
     self.hide_btn_slot()  # 默认隐藏
     self.mainwindow.job.kline_tick_signal.connect(self.set_tick_slot)
     self.ready_action()
Esempio n. 25
0
    def paintEvent(self, event: QPaintEvent) -> None:
        width: int = self.width()
        height: int = self.height()
        side: int = min(width, height)

        # 绘制准备工作,启用反锯齿,平移坐标轴中心,等比例缩放
        painter: QPainter = QPainter(self)
        painter.setRenderHints(QPainter.Antialiasing
                               | QPainter.TextAntialiasing)
        painter.translate(width / 2.0, height / 2.0)
        painter.scale(side / 200.0, side / 200.0)

        # 绘制时圆弧
        n_now: QDateTime = QDateTime.currentDateTime()
        n_time: QTime = n_now.time()
        n_hour: int = n_time.hour() - 12 if n_time.hour(
        ) >= 12 else n_time.hour()
        n_min: int = n_time.minute()
        n_sec: int = n_time.second()
        n_msec: int = n_time.msec()

        n_dsec: float = n_sec + n_msec / 1000.0
        n_dmin: float = n_min + n_dsec / 60.0
        n_dhour: float = n_hour + n_dmin / 60.0

        # 绘制时圆弧
        self.drawArc(painter, 94, n_dhour * 30, self.__hourColor)
        # 绘制分圆弧
        self.drawArc(painter, 81, n_dmin * 6, self.__minuteColor)
        # 绘制秒圆弧
        self.drawArc(painter, 68, n_dsec * 6, self.__secondColor)
        # 绘制时间文本
        self.drawText(painter)
Esempio n. 26
0
    def add_series(self, name, columns):
        self.series = QtCharts.QLineSeries()
        self.series.setName(name)

        for i in range(self.model.rowCount()):
            t = self.model.index(i, 0).data()
            date_fmt = "yyyy-MM-dd HH:mm:ss.zzz"

            x = QDateTime().fromString(t, date_fmt).toSecsSinceEpoch()
            y = float(self.model.index(i, 1).data())

            if x > 0 and y > 0:
                self.series.append(x, y)

        self.chart.addSeries(self.series)

        self.axis_x = QtCharts.QDateTimeAxis()
        self.axis_x.setTickCount(10)
        self.axis_x.setFormat("dd.MM (h:mm)")
        self.axis_x.setTitleText("Date")
        self.chart.addAxis(self.axis_x, Qt.AlignBottom)
        self.series.attachAxis(self.axis_x)

        self.axis_y = QtCharts.QValueAxis()
        self.axis_y.setTickCount(10)
        self.axis_y.setLabelFormat("%.2f")
        self.axis_y.setTitleText("Magnitude")
        self.chart.addAxis(self.axis_y, Qt.AlignLeft)
        self.series.attachAxis(self.axis_y)

        self.model.color = "{}".format(self.series.pen().color().name())
        print(self.model.color)
Esempio n. 27
0
def bracketDataSlot():
    global frameCount
    global lastFpsKey
    global customPlot
    secs = QCPAxisTickerDateTime.dateTimeToKey(QDateTime.currentDateTime())

    # update data to make phase move:
    n = 500
    phase = secs * 5
    k = 3
    x = [0.0] * n
    y = [0.0] * n
    for i in range(0, n):
        x[i] = i / (n - 1) * 34 - 17
        y[i] = math.exp(-x[i] * x[i] / 20.0) * math.sin(k * x[i] + phase)

    customPlot.graph().setData(x, y)

    itemDemoPhaseTracer.setGraphKey(
        (8 * math.pi + math.fmod(math.pi * 1.5 - phase, 6 * math.pi)) / k)

    customPlot.replot()

    # calculate frames per second:
    key = secs
    frameCount += 1

    if key - lastFpsKey > 2:  # average fps over 2 seconds
        fps = float(frameCount) / (float)(key - lastFpsKey)
        fps_str = '{:3.2f}'.format(fps)
        customPlot.setWindowTitle('Real Time Data Demo FPS: ' + fps_str)
        lastFpsKey = key
        frameCount = 0
Esempio n. 28
0
 def player_kill_count_date(self):
     self.cursor.execute("SELECT username,killcam_path, date FROM griefers")
     self.player_kc_dict = {}
     for tup in (self.cursor.fetchall()):
         if tup[0] in self.player_kc_dict and QDateTime.fromString(
                 tup[2]) < QDateTime.fromString(
                     self.player_kc_dict[tup[0]][1]):
             self.player_kc_dict[tup[0]] = (self.player_kc_dict[tup[0]][0] +
                                            1, tup[2])
         elif tup[0] in self.player_kc_dict and QDateTime.fromString(
                 tup[2]) >= QDateTime.fromString(
                     self.player_kc_dict[tup[0]][1]):
             self.player_kc_dict[tup[0]][0] += 1
         else:
             self.player_kc_dict[tup[0]] = [1, tup[2]]
     return self.player_kc_dict
Esempio n. 29
0
 def __init_username_jobname_widget__(self, parent=None):
     self.__username_jobname_widget = QFrame(parent)
     self.__username_jobname_widget.setSizePolicy(QSizePolicy.Maximum,
                                                  QSizePolicy.Maximum)
     username_label = QLabel("Username",
                             parent=self.__username_jobname_widget)
     username_edit = QLineEdit(parent=self.__username_jobname_widget)
     username_edit.setText(self.dlp_controller.username)
     username_edit.textChanged.connect(self.dlp_controller.set_username)
     jobname_label = QLabel("Print Job Name",
                            parent=self.__username_jobname_widget)
     jobname_edit = QLineEdit(parent=self.__username_jobname_widget)
     jobname_edit.setText(self.dlp_controller.print_job_name)
     jobname_edit.textChanged.connect(self.dlp_controller.set_printjob_name)
     etc = self.dlp_controller.evaluate_time_estimate()
     self.etc_label = QLabel(
         "ETC: " +
         QDateTime.fromTime_t(etc / 1000.0).toUTC().toString('hh:mm:ss'),
         self.__username_jobname_widget)
     self.dlp_controller.etc_updated_signal.connect(
         self.update_time_estimate)
     username_jobname_layout = QHBoxLayout(self.__username_jobname_widget)
     username_jobname_layout.addWidget(self.etc_label)
     username_jobname_layout.addWidget(username_label)
     username_jobname_layout.addWidget(username_edit)
     username_jobname_layout.addWidget(jobname_label)
     username_jobname_layout.addWidget(jobname_edit)
     self.__username_jobname_widget.setLayout(username_jobname_layout)
Esempio n. 30
0
 def new_record(self):
     # 此时已经点了确定按钮,可以开始计时
     time = QDateTime.currentDateTime().toTime_t()
     true_paper = Record(is_practice=False, start_datetime=time)
     self.session.add(true_paper)
     self.session.commit()
     # 用真题一一对应再建一套虚拟问题
     # 查询真题对应的所有question,然后放到虚拟问题里
     questions = self.session.query(Question).filter_by(
         paper_id=self.paper_id).all()
     # print(questions)
     # 找到刚才建立的记录id
     record_id = self.session.query(Record).filter_by(finished=False)[0].id
     v_questions = []
     i = 1
     for question in questions:
         v_question = V_Question(record_id=record_id,
                                 v_num=i,
                                 question_id=question.id)
         v_questions.append(v_question)
         i += 1
     self.session.add_all(v_questions)
     self.session.commit()
     v_questions = (self.session.query(V_Question).filter_by(
         record_id=record_id).all())
     q_records = []
     q_properties = []
     for v_question in v_questions:
         q_records.append(Q_Record(v_question_id=v_question.id))
         q_properties.append(Q_Property(v_question_id=v_question.id))
     self.session.add_all(q_records)
     self.session.add_all(q_properties)
     self.session.commit()
     self.session.close()
     return record_id
Esempio n. 31
0
    def drawText(self, painter: QPainter) -> None:
        painter.save()
        painter.setPen(Qt.NoPen)

        font: QFont = QFont()
        font.setBold(True)
        font.setPointSize(10)
        painter.setFont(font)

        now: QDateTime = QDateTime.currentDateTime()
        fm: QFontMetricsF = QFontMetricsF(font)
        textList: List[AnyStr] = [
            now.toString("MM月dd日yyyy"),
            now.toString("hh:mm:ss.zzz")
        ]

        # 绘制文本路径
        textPath: QPainterPath = QPainterPath()
        textPath.addText(-fm.width(textList[0]) / 2.0, -fm.lineSpacing() / 2.0,
                         font, textList[0])
        textPath.addText(-fm.width(textList[1]) / 2.0,
                         fm.lineSpacing() / 2.0, font, textList[1])

        strokeColor: QColor = self.__textColor.light(80)
        strokeColor.setAlphaF(0.2)
        painter.strokePath(
            textPath,
            QPen(strokeColor, self.__shadowWidth, Qt.SolidLine, Qt.RoundCap,
                 Qt.RoundJoin))
        painter.setBrush(self.__textColor)
        painter.drawPath(textPath)

        painter.restore()
Esempio n. 32
0
def transform_date(utc, timezone=None):
    """значение timezone по умолчаннию=None, timezone-не обязательный параметр """
    utc_fmt = "yyyy-MM-ddTHH:mm:ss.zzzZ"
    new_date = QDateTime().fromString(utc, utc_fmt)
    """ Класс QDateTime предоставляет функции даты и времени.
    Функция fromString () возвращает QDateTime , учитывая строку и формат даты, используемый для интерпретации даты в строке,
    ИЗ СТРОКИ ВОЗВРАЩАЕТ ДАТУ В ЧИСЛОВОМ ФОРМАТЕ
    
    """
    if timezone:
        new_date.setTimeZone(timezone)
        """ setTimeZone Возвращает часовой пояс даты и времени, произведет преобразования с числом, добавив или отнимит какое число
        в зависимости от зоны
        """
    return new_date
    """ возвращается модифицированная дата """
Esempio n. 33
0
 def add_operation_time(self, operation):
     question_operation = Q_Operation(
         v_question_id=self.current_v_question_id,
         operation=operation,
         datetime=QDateTime.currentDateTime().toTime_t(),
     )
     self.session.add(question_operation)
     self.session.commit()
Esempio n. 34
0
    def testInsert(self):
        myHash = {}
        qdate = QDate.currentDate()
        qdatetime = QDateTime.currentDateTime()
        qtime = QTime.currentTime()
        qurl = QUrl("http://www.pyside.org")
        qpoint = QPoint(12, 42)

        myHash[qdate] = "QDate"
        myHash[qdatetime] = "QDateTime"
        myHash[qtime] = "QTime"
        myHash[qurl] = "QUrl"
        myHash[qpoint] = "QPoint"

        self.assertEqual(myHash[qdate], "QDate")
        self.assertEqual(myHash[qdatetime], "QDateTime")
        self.assertEqual(myHash[qtime], "QTime")
        self.assertEqual(myHash[qurl], "QUrl")
        self.assertEqual(myHash[qpoint], "QPoint")