示例#1
0
    def __init__(self, operand_range: tuple, operators: tuple, parent=None):
        super(ArithmeticWidget, self).__init__(parent)

        self.operator_dict = {
            '+': self.add,
            '-': self.sub,
            '*': self.mul,
            '//': self.floordiv
        }

        self.operand_range = operand_range
        self.operators = operators
        self.operand_left = None
        self.operand_right = None
        self.correct_answer = None
        self.counter = 0

        main_box = QVBoxLayout()

        # backend timer
        self.time = QTime(0, 0, 0)
        self.timer = QTimer()
        self.timer.start(1000)
        self.timer.timeout.connect(self.change_time)

        # counter examples and timer
        self.counter_label = QLabel(str(self.counter))
        self.counter_label.setAlignment(Qt.AlignLeft)
        self.time_label = QLabel('0:00:00')
        self.time_label.setAlignment(Qt.AlignRight)
        h_box = QHBoxLayout()
        h_box.setContentsMargins(50, 20, 50, 0)
        h_box.addWidget(self.counter_label)
        h_box.addWidget(self.time_label)
        main_box.addLayout(h_box)

        # labels of nums and sign
        self.num_1_label = QLabel()
        self.num_1_label.setAlignment(Qt.AlignRight)
        self.num_2_label = QLabel()
        self.num_2_label.setAlignment(Qt.AlignLeft)
        self.sign_label = QLabel()
        self.sign_label.setFixedWidth(20)
        self.sign_label.setAlignment(Qt.AlignHCenter)
        h_box = QHBoxLayout()
        h_box.setContentsMargins(80, 0, 80, 0)
        h_box.addWidget(self.num_1_label)
        h_box.addWidget(self.sign_label)
        h_box.addWidget(self.num_2_label)
        main_box.addLayout(h_box)

        # answer field
        self.answer_field = QLineEdit()
        self.answer_field.returnPressed.connect(self.check_answer)
        self.answer_field.setAlignment(Qt.AlignCenter)
        self.answer_field.setValidator(QIntValidator())
        h_box = QHBoxLayout()
        h_box.setContentsMargins(80, 0, 80, 0)
        h_box.addWidget(self.answer_field)
        main_box.addLayout(h_box)

        # buttons
        self.confirm_btn = MyButton(btn_text='Enter',
                                    bg_color='rgb(138, 226, 52)',
                                    text_color='black',
                                    delay=False)
        self.confirm_btn.clicked.connect(self.check_answer)
        h_box = QHBoxLayout()
        h_box.addWidget(self.confirm_btn)
        main_box.addLayout(h_box)

        self.skip_btn = MyButton(btn_text='Skip',
                                 bg_color='rgb(252, 233, 79)',
                                 text_color='black',
                                 delay=False)
        self.skip_btn.clicked.connect(self.show_next_example)

        self.stop_btn = MyButton(btn_text='Stop',
                                 bg_color='red',
                                 text_color='white')
        self.stop_btn.clicked.connect(self.stop_session)
        h_box = QHBoxLayout()
        h_box.addWidget(self.skip_btn)
        h_box.addWidget(self.stop_btn)
        main_box.addLayout(h_box)

        self.setLayout(main_box)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.show_next_example()
示例#2
0
 def __init__(self):
     self.time = QTime()
     self.time.start()
     self.cur_time = timedelta(milliseconds=self.time.elapsed())
 def handle_label(self):
     self.time_viewer.clear()
     mtime = QTime(0, 0, 0, 0)
     self.time = mtime.addMSecs(self.media_player.position())
     self.time_viewer.setText(self.time.toString())
     self.frame_viewer.setText(str(self.media_player.position()))
示例#4
0
文件: bar.py 项目: iggy/qutebrowser
    def __init__(self, win_id, parent=None):
        super().__init__(parent)
        objreg.register('statusbar', self, scope='window', window=win_id)
        self.setObjectName(self.__class__.__name__)
        self.setAttribute(Qt.WA_StyledBackground)
        style.set_register_stylesheet(self)

        self.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed)

        self._win_id = win_id
        self._option = None
        self._stopwatch = QTime()

        self._hbox = QHBoxLayout(self)
        self._hbox.setContentsMargins(0, 0, 0, 0)
        self._hbox.setSpacing(5)

        self._stack = QStackedLayout()
        self._hbox.addLayout(self._stack)
        self._stack.setContentsMargins(0, 0, 0, 0)

        self.cmd = command.Command(win_id)
        self._stack.addWidget(self.cmd)
        objreg.register('status-command',
                        self.cmd,
                        scope='window',
                        window=win_id)

        self.txt = textwidget.Text()
        self._stack.addWidget(self.txt)
        self._timer_was_active = False
        self._text_queue = collections.deque()
        self._text_pop_timer = usertypes.Timer(self, 'statusbar_text_pop')
        self._text_pop_timer.timeout.connect(self._pop_text)
        self.set_pop_timer_interval()
        objreg.get('config').changed.connect(self.set_pop_timer_interval)

        self.prompt = prompt.Prompt(win_id)
        self._stack.addWidget(self.prompt)
        self._previous_widget = PreviousWidget.none

        self.cmd.show_cmd.connect(self._show_cmd_widget)
        self.cmd.hide_cmd.connect(self._hide_cmd_widget)
        self._hide_cmd_widget()
        prompter = objreg.get('prompter', scope='window', window=self._win_id)
        prompter.show_prompt.connect(self._show_prompt_widget)
        prompter.hide_prompt.connect(self._hide_prompt_widget)
        self._hide_prompt_widget()

        self.keystring = keystring.KeyString()
        self._hbox.addWidget(self.keystring)

        self.url = url.UrlText()
        self._hbox.addWidget(self.url)

        self.percentage = percentage.Percentage()
        self._hbox.addWidget(self.percentage)

        # We add a parent to Progress here because it calls self.show() based
        # on some signals, and if that happens before it's added to the layout,
        # it will quickly blink up as independent window.
        self.prog = progress.Progress(self)
        self._hbox.addWidget(self.prog)
示例#5
0
    def __init__(self, parent, persepolis_setting):
        super().__init__(persepolis_setting)
        self.persepolis_setting = persepolis_setting
        self.parent = parent
        self.grandparent = parent.persepolis_main

        self.persepolis_setting.beginGroup('settings')

        # initialization
        self.tries_spinBox.setValue(
            int(self.persepolis_setting.value('max-tries')))
        self.wait_spinBox.setValue(
            int(self.persepolis_setting.value('retry-wait')))
        self.time_out_spinBox.setValue(
            int(self.persepolis_setting.value('timeout')))
        self.connections_spinBox.setValue(
            int(self.persepolis_setting.value('connections')))
        self.rpc_port_spinbox.setValue(
            int(self.persepolis_setting.value('rpc-port')))

        # add support for other languages
        locale = str(self.persepolis_setting.value('settings/locale'))
        QLocale.setDefault(QLocale(locale))
        self.translator = QTranslator()
        if self.translator.load(':/translations/locales/ui_' + locale, 'ts'):
            QCoreApplication.installTranslator(self.translator)

        # wait_queue
        wait_queue_list = self.persepolis_setting.value('wait-queue')
        q_time = QTime(int(wait_queue_list[0]), int(wait_queue_list[1]))
        self.wait_queue_time.setTime(q_time)

        # change aria2 path
        self.aria2_path_pushButton.clicked.connect(self.changeAria2Path)
        self.aria2_path_checkBox.toggled.connect(self.ariaCheckBoxToggled)
        aria2_path = self.persepolis_setting.value('settings/aria2_path')

        self.aria2_path_lineEdit.setEnabled(False)
        if aria2_path != None:
            self.aria2_path_checkBox.setChecked(True)
            self.aria2_path_lineEdit.setText(str(aria2_path))

        self.ariaCheckBoxToggled('aria2')

        if os_type == 'Linux' or os_type == 'FreeBSD' or os_type == 'OpenBSD':
            for widget in self.aria2_path_checkBox, self.aria2_path_lineEdit, self.aria2_path_pushButton:
                widget.hide()

        # save_as_tab
        self.download_folder_lineEdit.setText(
            str(self.persepolis_setting.value('download_path')))
        self.temp_download_lineEdit.setText(
            str(self.persepolis_setting.value('download_path_temp')))

        # subfolder
        if str(self.persepolis_setting.value('subfolder')) == 'yes':
            self.subfolder_checkBox.setChecked(True)
        else:
            self.subfolder_checkBox.setChecked(False)

        # notifications_tab
        self.volume_label.setText(
            'Volume : ' + str(self.persepolis_setting.value('sound-volume')))
        self.volume_dial.setValue(
            int(self.persepolis_setting.value('sound-volume')))

        # set style
        # if style_comboBox is changed, self.styleComboBoxChanged is called.
        self.style_comboBox.currentIndexChanged.connect(
            self.styleComboBoxChanged)

        # find available styles(It's depends on operating system and desktop environments).
        available_styles = QStyleFactory.keys()
        for style in available_styles:
            # 'GTK' or 'gtk' styles may cause to crashing! Eliminate them!
            if 'gtk' not in str(style) and 'GTK' not in str(style):
                self.style_comboBox.addItem(style)

        # System >> for system default style
        # when user select System for style section, the default system style is using.
        self.style_comboBox.addItem('System')

        current_style_index = self.style_comboBox.findText(
            str(self.persepolis_setting.value('style')))
        if current_style_index != -1:
            self.style_comboBox.setCurrentIndex(current_style_index)

        # available language
        available_language = [
            'en_US', 'fa_IR', 'zh_CN', 'fr_FR', 'pl_PL', 'nl_NL', 'pt_BR',
            'es_ES'
        ]
        for lang in available_language:
            self.lang_comboBox.addItem(str(QLocale(lang).nativeLanguageName()),
                                       lang)

        current_locale = self.lang_comboBox.findData(
            str(self.persepolis_setting.value('locale')))
        self.lang_comboBox.setCurrentIndex(current_locale)
        self.lang_comboBox.currentIndexChanged.connect(
            self.styleComboBoxChanged)
        self.styleComboBoxChanged()

        current_color_index = self.color_comboBox.findText(
            str(self.persepolis_setting.value('color-scheme')))
        self.color_comboBox.setCurrentIndex(current_color_index)

        self.current_icon = self.persepolis_setting.value('icons')

        # icon size
        size = ['128', '64', '48', '32', '24', '16']
        self.icons_size_comboBox.addItems(size)
        current_icons_size_index = self.icons_size_comboBox.findText(
            str(self.persepolis_setting.value('toolbar_icon_size')))
        self.icons_size_comboBox.setCurrentIndex(current_icons_size_index)

        # call iconSizeComboBoxCanged if index is changed
        self.icons_size_comboBox.currentIndexChanged.connect(
            self.iconSizeComboBoxCanged)

        self.iconSizeComboBoxCanged(1)

        # set notification
        notifications = ['Native notification', 'QT notification']
        self.notification_comboBox.addItems(notifications)
        current_notification_index = self.notification_comboBox.findText(
            str(self.persepolis_setting.value('notification')))
        self.notification_comboBox.setCurrentIndex(current_notification_index)

        # set font
        font_setting = QFont()
        font_setting.setFamily(str(self.persepolis_setting.value('font')))
        self.fontComboBox.setCurrentFont(font_setting)

        self.font_size_spinBox.setValue(
            int(self.persepolis_setting.value('font-size')))

        # sound frame
        self.sound_frame.setEnabled(False)
        self.enable_notifications_checkBox.toggled.connect(self.soundFrame)
        if str(self.persepolis_setting.value('sound')) == 'yes':
            self.enable_notifications_checkBox.setChecked(True)
        else:
            self.enable_notifications_checkBox.setChecked(False)

        # connect folder buttons
        self.download_folder_lineEdit.setEnabled(False)
        self.download_folder_pushButton.clicked.connect(
            self.downloadFolderPushButtonClicked)
        self.temp_download_lineEdit.setEnabled(False)
        self.temp_download_pushButton.clicked.connect(
            self.tempDownloadPushButtonClicked)

        # dial
        self.volume_dial.setNotchesVisible(True)
        self.volume_dial.valueChanged.connect(self.dialChanged)

        # start_persepolis_if_browser_executed_checkBox
        if str(self.persepolis_setting.value('browser-persepolis')) == 'yes':
            self.start_persepolis_if_browser_executed_checkBox.setChecked(True)
        else:
            self.start_persepolis_if_browser_executed_checkBox.setChecked(
                False)

        # hide window
        if str(self.persepolis_setting.value('hide-window')) == 'yes':
            self.hide_window_checkBox.setChecked(True)
        else:
            self.hide_window_checkBox.setChecked(False)

        # tray icon
        if str(self.persepolis_setting.value('tray-icon')) == 'yes':
            self.enable_system_tray_checkBox.setChecked(True)
        else:
            self.enable_notifications_checkBox.setChecked(False)

        # show_menubar
        if str(self.persepolis_setting.value('show-menubar')) == 'yes':
            self.show_menubar_checkbox.setChecked(True)
        else:
            self.show_menubar_checkbox.setChecked(False)

        if platform.system() == 'Darwin':
            self.show_menubar_checkbox.setChecked(True)
            self.show_menubar_checkbox.hide()

        # show_sidepanel
        if str(self.persepolis_setting.value('show-sidepanel')) == 'yes':
            self.show_sidepanel_checkbox.setChecked(True)
        else:
            self.show_sidepanel_checkbox.setChecked(False)

        # show ProgressWindow
        if str(self.persepolis_setting.value('show-progress')) == 'yes':
            self.show_progress_window_checkbox.setChecked(True)
        else:
            self.show_progress_window_checkbox.setChecked(False)

        # after download dialog
        if str(self.persepolis_setting.value('after-dialog')) == 'yes':
            self.after_download_checkBox.setChecked(True)
        else:
            self.after_download_checkBox.setChecked(False)

        # run persepolis at startup checkBox
        if str(self.persepolis_setting.value('startup')) == 'yes':
            self.startup_checkbox.setChecked(True)
        else:
            self.startup_checkbox.setChecked(False)

        # font_checkBox
        if str(self.persepolis_setting.value('custom-font')) == 'yes':
            self.font_checkBox.setChecked(True)
        else:
            self.font_checkBox.setChecked(False)

        self.fontCheckBoxState(self.font_checkBox)

        # keep_awake_checkBox
        if str(self.persepolis_setting.value('awake')) == 'yes':
            self.keep_awake_checkBox.setChecked(True)
        else:
            self.keep_awake_checkBox.setChecked(False)

        # columns_tab
        if str(self.persepolis_setting.value('column0')) == 'yes':
            self.column0_checkBox.setChecked(True)
        else:
            self.column0_checkBox.setChecked(False)

        if str(self.persepolis_setting.value('column1')) == 'yes':
            self.column1_checkBox.setChecked(True)
        else:
            self.column1_checkBox.setChecked(False)

        if str(self.persepolis_setting.value('column2')) == 'yes':
            self.column2_checkBox.setChecked(True)
        else:
            self.column2_checkBox.setChecked(False)

        if str(self.persepolis_setting.value('column3')) == 'yes':
            self.column3_checkBox.setChecked(True)
        else:
            self.column3_checkBox.setChecked(False)

        if str(self.persepolis_setting.value('column4')) == 'yes':
            self.column4_checkBox.setChecked(True)
        else:
            self.column4_checkBox.setChecked(False)

        if str(self.persepolis_setting.value('column5')) == 'yes':
            self.column5_checkBox.setChecked(True)
        else:
            self.column5_checkBox.setChecked(False)

        if str(self.persepolis_setting.value('column6')) == 'yes':
            self.column6_checkBox.setChecked(True)
        else:
            self.column6_checkBox.setChecked(False)

        if str(self.persepolis_setting.value('column7')) == 'yes':
            self.column7_checkBox.setChecked(True)
        else:
            self.column7_checkBox.setChecked(False)

        if str(self.persepolis_setting.value('column10')) == 'yes':
            self.column10_checkBox.setChecked(True)
        else:
            self.column10_checkBox.setChecked(False)

        if str(self.persepolis_setting.value('column11')) == 'yes':
            self.column11_checkBox.setChecked(True)
        else:
            self.column11_checkBox.setChecked(False)

        if str(self.persepolis_setting.value('column12')) == 'yes':
            self.column12_checkBox.setChecked(True)
        else:
            self.column12_checkBox.setChecked(False)

        # video_finder
        try:  # Integer casting may raise exception.
            self.max_links_spinBox.setValue(
                int(persepolis_setting.value('video_finder/max_links', 3)))
        except:
            pass

        # shortcuts
        self.qshortcuts_list = [
            self.parent.exitAction_shortcut,
            self.parent.minimizeAction_shortcut,
            self.parent.removeSelectedAction_shortcut,
            self.parent.deleteSelectedAction_shortcut,
            self.parent.moveUpSelectedAction_shortcut,
            self.parent.moveDownSelectedAction_shortcut,
            self.parent.addlinkAction_shortcut,
            self.parent.videoFinderAddLinkAction_shortcut,
            self.parent.addtextfileAction_shortcut
        ]

        self.shortcuts_list = [
            self.parent.exitAction_shortcut.key().toString(),
            self.parent.minimizeAction_shortcut.key().toString(),
            self.parent.removeSelectedAction_shortcut.key().toString(),
            self.parent.deleteSelectedAction_shortcut.key().toString(),
            self.parent.moveUpSelectedAction_shortcut.key().toString(),
            self.parent.moveDownSelectedAction_shortcut.key().toString(),
            self.parent.addlinkAction_shortcut.key().toString(),
            self.parent.videoFinderAddLinkAction_shortcut.key().toString(),
            self.parent.addtextfileAction_shortcut.key().toString()
        ]

        # add shortcuts to the shortcut_table
        j = 0
        for shortcut in self.shortcuts_list:
            item = QTableWidgetItem(shortcut)

            # align center
            item.setTextAlignment(0x0004 | 0x0080)

            # insert item in shortcut_table
            self.shortcut_table.setItem(j, 1, item)

            j = j + 1

        # If user doubleclicks on a row, then run showCaptureKeyboardWindow method
        self.shortcut_table.itemDoubleClicked.connect(
            self.showCaptureKeyboardWindow)

        # ok cancel default button
        self.cancel_pushButton.clicked.connect(self.close)
        self.defaults_pushButton.clicked.connect(
            self.defaultsPushButtonPressed)
        self.ok_pushButton.clicked.connect(self.okPushButtonPressed)

        # font_checkBox connect
        self.font_checkBox.stateChanged.connect(self.fontCheckBoxState)

        # saving initial value of self.persepolis_setting in self.first_key_value_dict
        # at the end! in the okPushButtonPressed method, first_key_value_dict will compared with second_key_value_dict.
        # if any thing changed , then a message box notify user about "some changes take effect after restarting persepolis".
        self.first_key_value_dict = {}
        for member in self.persepolis_setting.allKeys():
            self.first_key_value_dict[member] = str(
                self.persepolis_setting.value(member))

        self.persepolis_setting.endGroup()

        # setting window size and position
        size = self.persepolis_setting.value('PreferencesWindow/size',
                                             QSize(578, 565))
        position = self.persepolis_setting.value('PreferencesWindow/position',
                                                 QPoint(300, 300))

        self.resize(size)
        self.move(position)
示例#6
0
def dateToStamps(dateAry: tuple):
    start, end = dateAry
    qtime = QTime(0, 0)
    start = QDateTime(start, qtime)
    end = QDateTime(end, qtime)
    return (start.toTime_t(), end.toTime_t())
示例#7
0
文件: ui.py 项目: zhangzhii/FeelUOwn
 def on_duration_changed(self, duration):
     m, s = parse_ms(duration)
     t = QTime(0, m, s)
     self.duration_label.setText(t.toString('mm:ss'))
示例#8
0
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.textSuffix = QTextEdit(self.centralwidget)
        self.textSuffix.setGeometry(QRect(20, 230, 261, 31))
        self.textSuffix.setObjectName("textSuffix")
        self.textRiskf = QTextEdit(self.centralwidget)
        self.textRiskf.setGeometry(QRect(20, 360, 261, 31))
        self.textRiskf.setObjectName("textRiskf")
        self.label = QLabel(self.centralwidget)
        self.label.setGeometry(QRect(20, 330, 261, 20))
        self.label.setObjectName("label")
        self.label_2 = QLabel(self.centralwidget)
        self.label_2.setGeometry(QRect(20, 270, 281, 21))
        self.label_2.setObjectName("label_2")
        self.label_3 = QLabel(self.centralwidget)
        self.label_3.setGeometry(QRect(20, 200, 261, 16))
        self.label_3.setObjectName("label_3")
        self.label_4 = QLabel(self.centralwidget)
        self.label_4.setGeometry(QRect(20, 130, 261, 21))
        self.label_4.setObjectName("label_4")
        self.label_5 = QLabel(self.centralwidget)
        self.label_5.setGeometry(QRect(20, 60, 261, 21))
        self.label_5.setObjectName("label_5")
        self.startButton = QPushButton(self.centralwidget)
        self.startButton.setGeometry(QRect(20, 510, 111, 31))
        self.startButton.setObjectName("startButton")
        self.label_6 = QLabel(self.centralwidget)
        self.label_6.setGeometry(QRect(20, 10, 261, 41))
        font = QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(12)
        font.setBold(True)
        font.setUnderline(True)
        font.setWeight(75)
        self.label_6.setFont(font)
        self.label_6.setObjectName("label_6")
        self.resultBrowser = QTextBrowser(self.centralwidget)
        self.resultBrowser.setGeometry(QRect(310, 30, 461, 501))
        self.resultBrowser.setObjectName("resultBrowser")
        self.DateStart = QDateEdit(self.centralwidget)
        self.DateStart.setGeometry(QRect(20, 90, 121, 31))
        self.DateStart.setMaximumDate(QDate(2050, 12, 31))
        self.DateStart.setMinimumDate(QDate(1990, 12, 31))
        self.DateStart.setDate(QDate(2018, 1, 1))
        self.DateStart.setObjectName("DateStart")
        self.DateEnd = QDateEdit(self.centralwidget)
        self.DateEnd.setGeometry(QRect(19, 163, 121, 31))
        self.DateEnd.setDateTime(QDateTime(QDate(2018, 1, 1), QTime(0, 0, 0)))
        self.DateEnd.setMaximumDateTime(QDateTime(QDate(2050, 12, 31), QTime(23, 59, 59)))
        self.DateEnd.setMinimumDate(QDate(1990, 12, 31))
        self.DateEnd.setObjectName("DateEnd")
        self.spinBoxMode = QSpinBox(self.centralwidget)
        self.spinBoxMode.setGeometry(QRect(20, 290, 71, 31))
        self.spinBoxMode.setMinimum(1)
        self.spinBoxMode.setMaximum(3)
        self.spinBoxMode.setObjectName("spinBoxMode")
        self.label_7 = QLabel(self.centralwidget)
        self.label_7.setGeometry(QRect(170, 300, 101, 21))
        self.label_7.setObjectName("label_7")
        self.endButton = QPushButton(self.centralwidget)
        self.endButton.setGeometry(QRect(160, 510, 121, 31))
        self.endButton.setObjectName("endButton")
        self.fileButton = QPushButton(self.centralwidget)
        self.fileButton.setGeometry(QRect(20, 410, 261, 31))
        self.fileButton.setObjectName("fileButton")
        self.pathBrowser = QTextBrowser(self.centralwidget)
        self.pathBrowser.setGeometry(QRect(20, 450, 261, 41))
        self.pathBrowser.setObjectName("pathBrowser")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QRect(0, 0, 800, 23))
        self.menubar.setObjectName("menubar")
        self.menuAnalysis = QMenu(self.menubar)
        self.menuAnalysis.setObjectName("menuAnalysis")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.menubar.addAction(self.menuAnalysis.menuAction())

        self.retranslateUi(MainWindow)
        QMetaObject.connectSlotsByName(MainWindow)
        ####################################################

        self.mythread = MyThread()
        self.mainthread = MyMainThread()

        self.fileButton.clicked.connect(lambda : self.file_path())
        self.mythread.trigger.connect(self.update_text)
        self.mainthread.result.connect(self.update_result)

        self.startButton.clicked.connect(lambda : self.input_Parameters())
        self.startButton.clicked.connect(lambda : self.mainthread.start())
        self.startButton.clicked.connect(lambda : self.mythread.start())
        self.endButton.clicked.connect(lambda : self.end_calculation())
 def transform_to_qtime(self, time_str):
     time_list = time_str.split(':')
     return QTime(int(time_list[0]), int(time_list[1]))
示例#10
0
    def load_file(self):
        """ Function to populate fields with the info from the edf header
        """
        name = self.data.fn
        self.input_fn = name
        self.input_fn_text = name.split('/')[-1]
        if len(name.split('/')[-1]) > 15:
            self.input_fn_text = name.split('/')[-1][0:15] + "..."
        self.lbl_fn.setText(self.input_fn_text)
        self.btn_anonfile.setDisabled(0)
        self.cbox_copyoriginal.setEnabled(1)
        self.cbox_setdefaults.setEnabled(1)
        self.cbox_setdefaults.setChecked(1)
        # Setup all fields to anonymize
        for i in range(len(self.pt_id_fields)):
            self.pt_id_fields[i].setDisabled(0)
        for i in range(len(self.rec_info_fields)):
            self.rec_info_fields[i].setDisabled(0)
        for i in range(len(self.date_time_lbls)):
            self.datetimefield_inputs[i].setDisabled(0)
        # Open the file
        with open(self.input_fn, 'rb') as f:
            file = f.read(200)
        file = bytearray(file)
        pt_id_text = file[8:88].decode("utf-8").split(" ")
        rec_info_text = file[88:168].decode("utf-8").split(" ")
        # Error checking
        if len(pt_id_text) > 1:
            if not (pt_id_text[1] in {"X", "F", "M"}):
                pt_id_text[1] = "X"
            if len(pt_id_text) > 2:
                if self._valid_date(pt_id_text[2]) == -1:
                    pt_id_text[2] = "01-JAN-2001"
        if len(pt_id_text) == 0:
            pt_id_text = ["X", "X", "01-JAN-2001", "X"]
        elif len(pt_id_text) == 1:
            pt_id_text.append("X")
            pt_id_text.append("01-JAN-2001")
            pt_id_text.append("X")
        elif len(pt_id_text) == 2:
            pt_id_text.append("01-JAN-2001")
            pt_id_text.append("X")
        elif len(pt_id_text) == 3:
            pt_id_text.append("X")
        elif len(pt_id_text) >= 4:
            if pt_id_text[0] == " " or pt_id_text[0] == "":
                pt_id_text[0] = "X"
            if pt_id_text[3] == " " or pt_id_text[3] == "":
                pt_id_text[3] = "X"

        if len(rec_info_text) > 1:
            if self._valid_date(rec_info_text[1]) == -1:
                rec_info_text[1] = "01-JAN-2001"
        if len(rec_info_text) == 0:
            rec_info_text = ["Startdate", "01-JAN-2001", "X", "X", "X"]
        elif len(rec_info_text) == 1:
            rec_info_text.append("01-JAN-2001")
            rec_info_text.append("X")
            rec_info_text.append("X")
            rec_info_text.append("X")
        elif len(rec_info_text) == 2:
            rec_info_text.append("X")
            rec_info_text.append("X")
            rec_info_text.append("X")
        elif len(rec_info_text) == 3:
            rec_info_text.append("X")
            rec_info_text.append("X")
        elif len(rec_info_text) == 4:
            rec_info_text.append("X")
        elif len(rec_info_text) >= 5:
            if rec_info_text[2] == " " or rec_info_text[2] == "":
                rec_info_text[2] = "X"
            if rec_info_text[3] == " " or rec_info_text[3] == "":
                rec_info_text[3] = "X"
            if rec_info_text[4] == " " or rec_info_text[4] == "":
                rec_info_text[4] = "X"
        self.oldpt_id_fields[0].setText(pt_id_text[0])
        if pt_id_text[1] == "F":
            self.radio_pt_id_f2.setChecked(1)
        elif pt_id_text[1] == "M":
            self.radio_pt_id_m2.setChecked(1)
        else:
            self.radio_pt_id_x2.setChecked(1)
        if pt_id_text[2] == "X":
            self.radio_pt_id_date_x2.setChecked(1)
        else:
            self.radio_pt_id_date2.setChecked(1)
            yr = int(pt_id_text[2].split("-")[2])
            mth = self.MONTHS.index(pt_id_text[2].split("-")[1]) + 1
            day = int(pt_id_text[2].split("-")[0])
            self.dob.setDate(QDate(yr, mth, day))
        self.oldpt_id_fields[3].setText(pt_id_text[3])
        if len(pt_id_text) > 4:
            self.oldpt_id_fields[4].setText("".join(pt_id_text[4:]))
        else:
            self.oldpt_id_fields[4].setText("")

        if rec_info_text[1] == "X":
            self.rec_info_date_x2.setChecked(1)
        else:
            self.rec_info_date2.setChecked(1)
            yr = int(rec_info_text[1].split("-")[2])
            mth = self.MONTHS.index(rec_info_text[1].split("-")[1]) + 1
            day = int(rec_info_text[1].split("-")[0])
            self.startdate.setDate(QDate(yr, mth, day))
        self.oldrec_info_fields[1].setText(rec_info_text[2])
        self.oldrec_info_fields[2].setText(rec_info_text[3])
        self.oldrec_info_fields[3].setText(rec_info_text[4])
        if len(rec_info_text) > 5:
            self.oldrec_info_fields[4].setText("".join(rec_info_text[5:]))
        else:
            self.oldrec_info_fields[4].setText("")

        yrs = int(file[174:176].decode("utf-8"))
        if yrs > 20:
            yrs = yrs + 1900
        else:
            yrs = yrs + 2000
        mths = int(file[171:173].decode("utf-8"))
        dys = int(file[168:170].decode("utf-8"))
        hrs = int(file[176:178].decode("utf-8"))
        minutes = int(file[179:181].decode("utf-8"))
        sec = int(file[182:184].decode("utf-8"))
        self.olddatetimefield_inputs[0].setDate(QDate(yrs, mths, dys))
        self.olddatetimefield_inputs[1].setTime(QTime(hrs, minutes, sec))
示例#11
0
    def init_ui(self):
        """ Setup the UI
        """
        layout = QGridLayout()

        font = QFont()
        font.setPointSize(16)
        lbl_info = QLabel("Update fields and click anonymize " +
                          "and save to select location for new file.")
        lbl_info.setAlignment(Qt.AlignCenter)
        lbl_info.setFont(font)
        layout.addWidget(lbl_info, 0, 0, 1, 3)

        # ---- Add in all subfields ---- #
        pt_id_rec_info_fields = QGridLayout()

        lbloriginal = QLabel("Original")
        lbloriginal.setAlignment(Qt.AlignCenter)
        pt_id_rec_info_fields.addWidget(lbloriginal, 0, 2)
        lblnew = QLabel("Modified")
        lblnew.setAlignment(Qt.AlignCenter)
        pt_id_rec_info_fields.addWidget(lblnew, 0, 3)
        self.cbox_copyoriginal = QCheckBox("Copy original values")
        self.cbox_copyoriginal.setEnabled(0)
        pt_id_rec_info_fields.addWidget(self.cbox_copyoriginal, 1, 3)
        self.cbox_setdefaults = QCheckBox("Set default values")
        self.cbox_setdefaults.setEnabled(0)
        pt_id_rec_info_fields.addWidget(self.cbox_setdefaults, 2, 3)

        lbl_pt_id = QLabel("Patient ID:")
        pt_id_rec_info_fields.addWidget(lbl_pt_id, 3, 0, 5, 1)
        lbl_rec_info = QLabel("Recording information:")
        pt_id_rec_info_fields.addWidget(lbl_rec_info, 8, 0, 5, 1)

        lblhospcode = QLabel("Hospital code:")
        lblsex = QLabel("Sex:")
        lbldob = QLabel("Date of birth:")
        lblptname = QLabel("Patient name:")
        lblother = QLabel("Other:")
        self.pt_id_lbls = [lblhospcode, lblsex, lbldob, lblptname, lblother]
        hospcodeedit = QLineEdit()
        groupbox_sex_edit = QGroupBox()
        self.radio_pt_id_f = QRadioButton("F")
        self.radio_pt_id_m = QRadioButton("M")
        self.radio_pt_id_x = QRadioButton("X")
        self.radio_pt_id_x.setChecked(True)
        hbox = QHBoxLayout()
        hbox.addWidget(self.radio_pt_id_f)
        hbox.addWidget(self.radio_pt_id_m)
        hbox.addWidget(self.radio_pt_id_x)
        groupbox_sex_edit.setLayout(hbox)
        groupbox_date_edit = QGroupBox()
        self.radio_pt_id_date = QRadioButton("")
        self.radio_pt_id_date_x = QRadioButton("X")
        self.radio_pt_id_date_x.setChecked(True)
        self.dobedit = QDateEdit(QDate(2001, 1, 1))
        self.dobedit.setDisplayFormat("MM/dd/yyyy")
        hbox2 = QHBoxLayout()
        hbox2.addWidget(self.radio_pt_id_date)
        hbox2.addWidget(self.dobedit)
        hbox2.addWidget(self.radio_pt_id_date_x)
        groupbox_date_edit.setLayout(hbox2)
        ptnameedit = QLineEdit()
        ptidotheredit = QLineEdit()
        self.pt_id_fields = [
            hospcodeedit, groupbox_sex_edit, groupbox_date_edit, ptnameedit,
            ptidotheredit
        ]
        hospcode = QLineEdit()
        groupbox_sex = QGroupBox()
        self.radio_pt_id_f2 = QRadioButton("F")
        self.radio_pt_id_m2 = QRadioButton("M")
        self.radio_pt_id_x2 = QRadioButton("X")
        self.radio_pt_id_f2.setChecked(True)
        hbox3 = QHBoxLayout()
        hbox3.addWidget(self.radio_pt_id_f2)
        hbox3.addWidget(self.radio_pt_id_m2)
        hbox3.addWidget(self.radio_pt_id_x2)
        groupbox_sex.setLayout(hbox3)
        groupbox_date = QGroupBox()
        self.radio_pt_id_date2 = QRadioButton("")
        self.radio_pt_id_date_x2 = QRadioButton("X")
        self.radio_pt_id_date2.setChecked(True)
        self.dob = QDateEdit(QDate(2001, 1, 1))
        self.dob.setDisplayFormat("MM/dd/yyyy")
        hbox4 = QHBoxLayout()
        hbox4.addWidget(self.radio_pt_id_date2)
        hbox4.addWidget(self.dob)
        hbox4.addWidget(self.radio_pt_id_date_x2)
        groupbox_date.setLayout(hbox4)
        ptname = QLineEdit()
        ptidother = QLineEdit()
        self.oldpt_id_fields = [
            hospcode, groupbox_sex, groupbox_date, ptname, ptidother
        ]

        for i, l in enumerate(self.pt_id_lbls):
            pt_id_rec_info_fields.addWidget(l, i + 3, 1)
            pt_id_rec_info_fields.addWidget(self.oldpt_id_fields[i], i + 3, 2)
            pt_id_rec_info_fields.addWidget(self.pt_id_fields[i], i + 3, 3)
            self.oldpt_id_fields[i].setDisabled(1)
            self.pt_id_fields[i].setDisabled(1)

        pt_id_rec_info_fields.addWidget(QHLine(),
                                        len(self.pt_id_lbls) + 3, 0, 1, 4)

        lblstartdate = QLabel("Startdate:")
        lblhospadmincode = QLabel("Hospital admin code:")
        lbltechcode = QLabel("Technician code:")
        lblequip = QLabel("Equipment code:")
        lblother = QLabel("Other:")
        self.rec_info_lbls = [
            lblstartdate, lblhospadmincode, lbltechcode, lblequip, lblother
        ]
        groupbox_date_editrec_info = QGroupBox()
        self.rec_info_date = QRadioButton("")
        self.rec_info_date_x = QRadioButton("X")
        self.rec_info_date_x.setChecked(True)
        self.startdateedit = QDateEdit(QDate(2001, 1, 1))
        self.startdateedit.setDisplayFormat("MM/dd/yyyy")
        hb = QHBoxLayout()
        hb.addWidget(self.rec_info_date)
        hb.addWidget(self.startdateedit)
        hb.addWidget(self.rec_info_date_x)
        groupbox_date_editrec_info.setLayout(hb)
        hospadmincodeedit = QLineEdit()
        techcodeedit = QLineEdit()
        equipcodeedit = QLineEdit()
        recinfootheredit = QLineEdit()
        self.rec_info_fields = [
            groupbox_date_editrec_info, hospadmincodeedit, techcodeedit,
            equipcodeedit, recinfootheredit
        ]
        groupbox_daterec_info = QGroupBox()
        self.rec_info_date2 = QRadioButton("")
        self.rec_info_date_x2 = QRadioButton("X")
        self.rec_info_date2.setChecked(True)
        self.startdate = QDateEdit(QDate(2001, 1, 1))
        self.startdate.setDisplayFormat("MM/dd/yyyy")
        hb = QHBoxLayout()
        hb.addWidget(self.rec_info_date2)
        hb.addWidget(self.startdate)
        hb.addWidget(self.rec_info_date_x2)
        groupbox_daterec_info.setLayout(hb)
        hospadmincode = QLineEdit()
        techcode = QLineEdit()
        equipcode = QLineEdit()
        recinfoother = QLineEdit()
        self.oldrec_info_fields = [
            groupbox_daterec_info, hospadmincode, techcode, equipcode,
            recinfoother
        ]
        for i, l in enumerate(self.rec_info_lbls):
            pt_id_rec_info_fields.addWidget(l,
                                            i + len(self.oldpt_id_fields) + 4,
                                            1)
            pt_id_rec_info_fields.addWidget(self.oldrec_info_fields[i],
                                            i + len(self.oldpt_id_fields) + 4,
                                            2)
            pt_id_rec_info_fields.addWidget(self.rec_info_fields[i],
                                            i + len(self.oldpt_id_fields) + 4,
                                            3)
            self.rec_info_fields[i].setDisabled(1)
            self.oldrec_info_fields[i].setDisabled(1)

        pt_id_rec_info_fields.addWidget(
            QHLine(),
            len(self.pt_id_lbls) + len(self.oldpt_id_fields) + 4, 0, 1, 4)
        layout.addLayout(pt_id_rec_info_fields, 3, 0, 1, 3)

        lbl_start_date = QLabel("Start date:")
        lbl_start_time = QLabel("Start time:")
        oldinput_start_date = QDateEdit(QDate(2001, 1, 1))
        oldinput_start_date.setDisplayFormat("MM/dd/yyyy")
        oldinput_start_time = QTimeEdit(QTime(1, 1, 1))
        oldinput_start_time.setDisplayFormat("hh:mm:ss")
        inputStartDate = QDateEdit(QDate(2001, 1, 1))
        inputStartDate.setDisplayFormat("MM/dd/yyyy")
        inputStartTime = QTimeEdit(QTime(1, 1, 1))
        inputStartTime.setDisplayFormat("hh:mm:ss")

        self.date_time_lbls = [lbl_start_date, lbl_start_time]
        self.olddatetimefield_inputs = [
            oldinput_start_date, oldinput_start_time
        ]
        self.datetimefield_inputs = [inputStartDate, inputStartTime]
        for i, l in enumerate(self.date_time_lbls):
            pt_id_rec_info_fields.addWidget(
                l, i + len(self.oldpt_id_fields) + len(self.pt_id_lbls) + 6, 1)
            self.olddatetimefield_inputs[i].setDisabled(1)
            self.datetimefield_inputs[i].setDisabled(1)
            pt_id_rec_info_fields.addWidget(
                self.olddatetimefield_inputs[i],
                i + len(self.oldpt_id_fields) + len(self.pt_id_lbls) + 6, 2)
            pt_id_rec_info_fields.addWidget(
                self.datetimefield_inputs[i],
                i + len(self.oldpt_id_fields) + len(self.pt_id_lbls) + 6, 3)

        # Set defaults
        self.pt_id_fields[0].setText("X")

        self.pt_id_fields[3].setText("X")
        self.pt_id_fields[4].setText("")

        self.rec_info_fields[1].setText("X")
        self.rec_info_fields[2].setText("X")
        self.rec_info_fields[3].setText("X")
        self.rec_info_fields[4].setText("")

        # ---- -------------------- ---- #

        self.lbl_fn = QLabel("No file loaded.")
        self.lbl_fn.setFont(font)
        layout.addWidget(self.lbl_fn, 1, 1, 1, 1)
        layout.addWidget(QHLine(), 2, 0, 1, 3)

        layout.addWidget(QHLine(), len(self.date_time_lbls) + 5, 0, 1, 3)
        self.btn_anonfile = QPushButton("Anonymize and save file", self)
        layout.addWidget(self.btn_anonfile,
                         len(self.date_time_lbls) + 6, 0, 1, 3)
        self.btn_anonfile.setDisabled(True)

        self.setWindowTitle(self.title)
        self.setLayout(layout)

        self.set_signals_slots()
        self.show()
示例#12
0
 def on_duration_changed(self, duration):
     duration = duration * 1000
     m, s = parse_ms(duration)
     t = QTime(0, m, s)
     self.progress_slider.set_duration(duration)
     self.duration_label.setText(t.toString('mm:ss'))
示例#13
0
 def update_rest_end_time(self):
     self.restEndTime = QTime(self.restHoursSpinBox.value(),
                              self.restMinutesSpinBox.value(),
                              self.restSecondsSpinBox.value())
示例#14
0
 def update_work_end_time(self):
     self.workEndTime = QTime(self.workHoursSpinBox.value(),
                              self.workMinutesSpinBox.value(),
                              self.workSecondsSpinBox.value())
示例#15
0
 def handleLabel(self):
         self.lbl.clear()
         mtime = QTime(0,0,0,0)
         self.time = mtime.addMSecs(self.mediaPlayer.position())
         self.lbl.setText(self.time.toString())
示例#16
0
def extractProfilePetronciniCSV(file, _):
    res = {}  # the interpreted data set

    res["samplinginterval"] = 1.0

    csvFile = io.open(file, 'r', newline="", encoding='utf-8')
    data = csv.reader(csvFile, delimiter=';')
    #read file header
    next(data)  # skip "Export path"
    next(data)  # skip path
    header = [i.strip() for i in next(data)]

    roast_date = None
    power = None  # holds last processed heater event value
    power_last = None  # holds the heater event value before the last one
    power_event = False  # set to True if a heater event exists
    specialevents = []
    specialeventstype = []
    specialeventsvalue = []
    specialeventsStrings = []
    timex = []
    temp1 = []  # outlet temperature as ET
    temp2 = []  # bean temperature
    extra1 = []  # inlet temperature
    extra2 = []  # burner percentage
    timeindex = [
        -1, 0, 0, 0, 0, 0, 0, 0
    ]  #CHARGE index init set to -1 as 0 could be an actal index used
    i = 0
    for row in data:
        if row == []:
            continue
        i = i + 1
        items = list(zip(header, row))
        item = {}
        for (name, value) in items:
            item[name] = value.strip()
        # take i as time in seconds
        timex.append(i)
        # extract roast_date
        if roast_date is None and 'Year' in item and 'Month' in item and 'Day' in item and 'Hour' in item and 'Minute' in item and 'Second' in item:
            try:
                date = QDate(int(item['Year']), int(item['Month']),
                             int(item['Day']))
                time = QTime(int(item['Hour']), int(item['Minute']),
                             int(item['Second']))
                roast_date = QDateTime(date, time)
            except:
                passs
        #
        if 'Outlet Temperature' in item:
            temp1.append(float(item['Outlet Temperature']))
        else:
            temp1.append(-1)
        if 'Beans Temperature' in item:
            temp2.append(float(item['Beans Temperature'].replace(",", ".")))
        else:
            temp2.append(-1)
        # mark CHARGE
        if not timeindex[0] > -1:
            timeindex[0] = i
        # mark DROP
        if timeindex[0] > -1 and i > 0:
            timeindex[6] = i - 1
        # add ror, power, speed and pressure
        if 'Inlet Temperature' in item:
            extra1.append(float(item['Inlet Temperature']))
        else:
            extra1.append(-1)
        if 'Burner Percentage' in item:
            extra2.append(float(item['Burner Percentage']))
        else:
            extra2.append(-1)

        if "Burner Percentage" in item:
            try:
                v = float(item["Burner Percentage"])
                if v != power:
                    # power value changed
                    if v == power_last:
                        # just a fluctuation, we remove the last added power value again
                        power_last_idx = next(
                            i for i in reversed(range(len(specialeventstype)))
                            if specialeventstype[i] == 3)
                        del specialeventsvalue[power_last_idx]
                        del specialevents[power_last_idx]
                        del specialeventstype[power_last_idx]
                        del specialeventsStrings[power_last_idx]
                        power = power_last
                        power_last = None
                    else:
                        power_last = power
                        power = v
                        power_event = True
                        v = v / 10. + 1
                        specialeventsvalue.append(v)
                        specialevents.append(i)
                        specialeventstype.append(3)
                        specialeventsStrings.append(item["power"] + "%")
                else:
                    power_last = None
            except Exception:
                pass

    csvFile.close()

    res["timex"] = timex
    res["temp1"] = replace_duplicates(temp1)
    res["temp2"] = replace_duplicates(temp2)
    res["timeindex"] = timeindex

    res["extradevices"] = [25]
    res["extratimex"] = [timex[:]]

    res["extraname1"] = ["IT"]
    res["extratemp1"] = [extra1]
    res["extramathexpression1"] = [""]

    res["extraname2"] = ["burner"]
    res["extratemp2"] = [replace_duplicates(extra2)]
    res["extramathexpression2"] = [""]

    # set date
    if roast_date is not None and roast_date.isValid():
        res["roastdate"] = encodeLocal(roast_date.date().toString())
        res["roastisodate"] = encodeLocal(roast_date.date().toString(
            Qt.ISODate))
        res["roasttime"] = encodeLocal(roast_date.time().toString())
        res["roastepoch"] = int(roast_date.toTime_t())
        res["roasttzoffset"] = libtime.timezone

    if len(specialevents) > 0:
        res["specialevents"] = specialevents
        res["specialeventstype"] = specialeventstype
        res["specialeventsvalue"] = specialeventsvalue
        res["specialeventsStrings"] = specialeventsStrings
        if power_event or speed_event:
            # first set etypes to defaults
            res["etypes"] = [
                QApplication.translate("ComboBox", "Air", None),
                QApplication.translate("ComboBox", "Drum", None),
                QApplication.translate("ComboBox", "Damper", None),
                QApplication.translate("ComboBox", "Burner", None), "--"
            ]
    return res
示例#17
0
 def __init__(self):
     super().__init__()
     self.initUI()
     # Флаг, чтобы функция вызова будильника не вызвыалась с каждым тиком
     self.flag_get_up = True
     # Нулевое время для сброса часов
     self.zero_time = QTime(0, 0)
     # Пустая ссылка
     self.url = QUrl()
     # Инициализируем плеер и плейлист, который после зацикливаем
     self.playlist = QMediaPlaylist(self)
     self.playlist.setPlaybackMode(QMediaPlaylist.Loop)
     self.player = QMediaPlayer()
     # Кнопка для выбора файла с музыкой
     self.btn_getfile = QPushButton('Выбрать файл', self)
     self.btn_getfile.setFont(QFont('Times', 10))
     self.btn_getfile.move(142.5, 25)
     self.btn_getfile.resize(215, 50)
     self.btn_getfile.setVisible(False)
     self.btn_getfile.clicked.connect(self.getfile)
     # Радио-кнопка для включения будильника
     self.radio_btn1 = QRadioButton('вкл', self)
     self.radio_btn1.move(0, 15)
     self.radio_btn1.setFont(QFont('Times', 10))
     self.radio_btn1.toggled.connect(self.on_off)
     # Радио-кнопка для выключения будильника
     self.radio_btn2 = QRadioButton('выкл', self)
     self.radio_btn2.move(0, 40)
     self.radio_btn2.setChecked(True)
     self.radio_btn2.setFont(QFont('Times', 10))
     self.radio_btn2.toggled.connect(self.on_off)
     # Значение будильника
     self.timer_edit = QTimeEdit(self)
     self.timer_edit.setDisplayFormat('hh:mm')
     self.timer_edit.move(200, 110)
     self.timer_edit.resize(100, 50)
     self.timer_edit.setFont(QFont('Times', 18, QFont.Bold))
     self.timer_edit.setVisible(False)
     # Бирка
     self.lbl = QLabel('Будильник:', self)
     self.lbl.move(0, 0)
     self.lbl.setFont(QFont('Times', 10))
     # Подсказка для кнопки выбора мелодии
     self.lbl2 = QLabel('Выберите мелодию для будильника:', self)
     self.lbl2.move(142.5, 0)
     self.lbl2.setVisible(False)
     self.lbl2.setFont(QFont('Times', 10))
     # Бирка
     self.lbl3 = QLabel('Будильник установлен на:', self)
     self.lbl3.move(175, 185)
     self.lbl3.setFont(QFont('Times', 10))
     self.lbl3.setVisible(False)
     # Бирка
     self.lbl4 = QLabel('Установите время будильника:', self)
     self.lbl4.move(150, 85)
     self.lbl4.setFont(QFont('Times', 10))
     self.lbl4.setVisible(False)
     # Кнопка выключения будильника, когда он сработает
     self.btn = QPushButton('Выключить\nбудильник', self)
     self.btn.clicked.connect(self.awake)
     self.btn.resize(100, 100)
     self.btn.move(200, 200)
     self.btn.setFont(QFont('Times', 11, QFont.ExtraBold))
     self.btn.setVisible(False)
     # Дисплей для вывода значения будильника
     self.dis2 = QLCDNumber(self)
     self.dis2.move(200, 210)
     self.dis2.resize(100, 50)
     self.dis2.setVisible(False)
     # Дисплей с текущим временем
     self.dis1 = QLCDNumber(self)
     self.dis1.move(375, 25)
     self.dis1.resize(100, 50)
     # Бирка
     self.lbl5 = QLabel('Сейчас:', self)
     self.lbl5.move(375, 0)
     self.lbl5.setFont(QFont('Times', 10))
     # Таймер
     self.nTimer = QTimer()
     self.nTimer.timeout.connect(self.repeatTime)
     self.nTimer.start()
示例#18
0
 def on_player_position_changed(cls, ms):
     time_text = QTime(0, (ms / 60000) % 60, (ms / 1000) % 60)
     cls.ui.SONG_COUNTDOWN_LABEL.setText(time_text.toString("mm:ss"))
     cls.ui.SONG_PROGRESS_SLIDER.setValue(ms / 1000)
     ControllerApi.desktop_mini.content.set_value(ms / 1000)
     ControllerApi.lyric_widget.show_lyric_while_visible(ms)
示例#19
0
 def set_sys_time(self):
     self.hack_time(QTime().currentTime())
示例#20
0
    def __init__(self, screenW, screenH):

        super().__init__()
        self.title = "Simple Timer"
        self.width = 640
        self.height = 480
        self.left = (screenW / 2) - (self.width / 2)
        self.top = (screenH / 2) - (self.height / 2)

        #Create button horizontal layout
        btnBox = QHBoxLayout()
        btnBox.addStretch(.5)
        #Create button instaces
        self.startBtn = QPushButton('Start', self)
        self.startBtn.clicked.connect(self.handleStartBtn)
        self.stopBtn = QPushButton('Stop', self)
        self.stopBtn.clicked.connect(self.handleStopBtn)
        self.resetBtn = QPushButton('Reset', self)
        self.resetBtn.clicked.connect(self.handleResetBtn)
        self.closeBtn = QPushButton('Close', self)
        self.closeBtn.clicked.connect(self.handleCloseBtn)
        #Add buttons to layout
        btnBox.addWidget(self.startBtn)
        btnBox.addWidget(self.stopBtn)
        btnBox.addWidget(self.resetBtn)
        btnBox.addWidget(self.closeBtn)
        btnBox.addStretch(.5)

        #Create Update Calls for All Clocks
        self.curTimeTimer = QTimer(self)
        self.curTimeTimer.timeout.connect(self.updateTime)
        self.curTimeTimer.start(87)

        #Create Three Info Clocks
        timeFont = QFont("Ariel", 40)
        #Set the initial current time at start
        curTimeBox = QHBoxLayout()
        curTimeBox.addStretch(.5)
        self.curTime = QLabel(self.formatTime(), self)
        self.curTime.setFont(timeFont)
        curTimeBox.addWidget(self.curTime)
        curTimeBox.addStretch(.5)
        #Set the initial timer time at start
        curTimerBox = QHBoxLayout()
        curTimerBox.addStretch(.5)
        self.curTimer = QLabel("00:00:00:000 ms", self)
        self.curTimer.setFont(timeFont)
        curTimerBox.addWidget(self.curTimer)
        curTimerBox.addStretch(.5)
        #Set the initial elapsed time at start
        self.stopwatchTime = QTime(0, 0, 0, 0)
        curElapseBox = QHBoxLayout()
        curElapseBox.addStretch(.5)
        self.curElapse = QLabel("00:00:00:000 ms", self)
        self.curElapse.setFont(timeFont)
        curElapseBox.addWidget(self.curElapse)
        curElapseBox.addStretch(.5)

        #Create timer input feilds
        inputBox = QHBoxLayout()
        self.introInput = QLabel('Set timer to -', self)
        self.hourInput = QLabel(' Hours:', self)
        self.hourInputFeild = QLineEdit()
        self.minInput = QLabel(' Minutes:', self)
        self.minInputFeild = QLineEdit()
        self.secInput = QLabel(' Seconds:', self)
        self.secInputFeild = QLineEdit()
        self.statusInput = QLabel('Awaiting Input!', self)
        self.statusInput.setStyleSheet('color: orange')
        inputBox.addStretch(.2)
        inputBox.addWidget(self.introInput)
        inputBox.addStretch(.3)
        inputBox.addWidget(self.hourInput)
        inputBox.addWidget(self.hourInputFeild)
        inputBox.addWidget(self.minInput)
        inputBox.addWidget(self.minInputFeild)
        inputBox.addWidget(self.secInput)
        inputBox.addWidget(self.secInputFeild)
        inputBox.addStretch(.3)
        inputBox.addWidget(self.statusInput)
        inputBox.addStretch(.2)

        #Connect input signals to the apropriate function
        self.hourInputFeild.textChanged.connect(self.updateTimer)
        self.minInputFeild.textChanged.connect(self.updateTimer)
        self.secInputFeild.textChanged.connect(self.updateTimer)

        #Create all static labels
        titleFont = QFont("Courier", 20)
        self.curTimeTitle = QLabel('Current Time:', self)
        self.curTimeTitle.setFont(titleFont)
        self.curTimerTitle = QLabel('Time Remaining:', self)
        self.curTimerTitle.setFont(titleFont)
        self.curElapseTitle = QLabel('Elapsed Time:', self)
        self.curElapseTitle.setFont(titleFont)

        #Create and populate root layout
        rootBox = QVBoxLayout()
        rootBox.addWidget(self.curTimeTitle)
        rootBox.addLayout(curTimeBox)
        rootBox.addStretch(.165)
        rootBox.addWidget(self.horLine())
        rootBox.addStretch(.165)
        rootBox.addWidget(self.curTimerTitle)
        rootBox.addLayout(curTimerBox)
        rootBox.addStretch(.165)
        rootBox.addWidget(self.horLine())
        rootBox.addStretch(.165)
        rootBox.addWidget(self.curElapseTitle)
        rootBox.addLayout(curElapseBox)
        rootBox.addStretch(.165)
        rootBox.addWidget(self.horLine())
        rootBox.addStretch(.165)
        rootBox.addLayout(inputBox)
        rootBox.addLayout(btnBox)

        self.setLayout(rootBox)

        self.initWindow()
示例#21
0
文件: ui.py 项目: zhangzhii/FeelUOwn
 def on_position_changed(self, position):
     m, s = parse_ms(position)
     t = QTime(0, m, s)
     self.position_label.setText(t.toString('mm:ss'))
示例#22
0
    def __init__(self, parent, callback, gid, persepolis_setting, video_finder_dictionary=None):
        super().__init__(persepolis_setting)

        self.parent = parent
        self.persepolis_setting = persepolis_setting
        self.video_finder_dictionary = video_finder_dictionary

        self.download_later_pushButton.hide()  # hide download_later_pushButton
        self.change_name_checkBox.hide()  # hide change_name_checkBox
        self.change_name_lineEdit.hide()  # hide change_name_lineEdit

        # add new QLineEdit and QLineEdit for audio link if we have video finder links
        if self.video_finder_dictionary:

            self.link_label_2 = QLabel(self.link_frame)
            self.link_horizontalLayout.addWidget(self.link_label_2)

            self.link_lineEdit_2 = QLineEdit(self.link_frame)
            self.link_horizontalLayout.addWidget(self.link_lineEdit_2)
            self.link_lineEdit_2.textChanged.connect(self.linkLineChanged)

            self.link_label.setText(QCoreApplication.translate("addlink_ui_tr", "Video Link: "))
            self.link_label_2.setText(QCoreApplication.translate("addlink_ui_tr", "Audio Link: "))

            # gid_1 >> video_gid , gid_2 >> audio_gid
            self.gid_1 = self.video_finder_dictionary['video_gid']
            self.gid_2 = self.video_finder_dictionary['audio_gid']

        else:

            self.gid_1 = gid

        self.callback = callback

# detect_proxy_pushButton
        self.detect_proxy_pushButton.clicked.connect(
            self.detectProxy)

# connect folder_pushButton
        self.folder_pushButton.clicked.connect(self.changeFolder)
        self.download_folder_lineEdit.setEnabled(False)

        self.ok_pushButton.setEnabled(False)
        self.link_lineEdit.textChanged.connect(self.linkLineChanged)

# connect OK and canel button

        self.cancel_pushButton.clicked.connect(self.close)
        self.ok_pushButton.clicked.connect(self.okButtonPressed)

#frames and checkBoxes
        self.proxy_frame.setEnabled(False)
        self.proxy_checkBox.toggled.connect(self.proxyFrame)

        self.download_frame.setEnabled(False)
        self.download_checkBox.toggled.connect(self.downloadFrame)

        self.limit_frame.setEnabled(False)
        self.limit_checkBox.toggled.connect(self.limitFrame)

        self.start_frame.setEnabled(False)
        self.start_checkBox.toggled.connect(self.startFrame)

        self.end_frame.setEnabled(False)
        self.end_checkBox.toggled.connect(self.endFrame)

        # get information from data base
        self.add_link_dictionary_1 = self.parent.persepolis_db.searchGidInAddLinkTable(self.gid_1)
        self.download_table_dict_1 = self.parent.persepolis_db.searchGidInDownloadTable(self.gid_1)

        if video_finder_dictionary:
            self.add_link_dictionary_2 = self.parent.persepolis_db.searchGidInAddLinkTable(self.gid_2)
            self.download_table_dict_2 = self.parent.persepolis_db.searchGidInDownloadTable(self.gid_2)

        # create a copy from add_link_dictionary for checking changes finally!
        self.add_link_dictionary_1_backup = {}
        for key in self.add_link_dictionary_1.keys():
            self.add_link_dictionary_1_backup[key] = self.add_link_dictionary_1[key]

        if video_finder_dictionary:
            self.add_link_dictionary_2_backup = {}
            for key in self.add_link_dictionary_2.keys():
                self.add_link_dictionary_2_backup[key] = self.add_link_dictionary_2[key]


# initialization
# disable folder_frame when download is complete
        if self.video_finder_dictionary:
            if self.video_finder_dictionary['video_completed'] == 'yes' or self.video_finder_dictionary['audio_completed'] == 'yes':
                self.folder_frame.setEnabled(False)
        else:
            if self.download_table_dict_1['status'] == 'complete':
                self.folder_frame.setEnabled(False)


# link
        self.link_lineEdit.setText(self.add_link_dictionary_1['link'])

        if self.video_finder_dictionary:
            self.link_lineEdit_2.setText(self.add_link_dictionary_2['link'])

# ip_lineEdit initialization
        if self.add_link_dictionary_1['ip']:
            self.proxy_checkBox.setChecked(True)
            self.ip_lineEdit.setText(self.add_link_dictionary_1['ip'])
# port_spinBox initialization
            try:
                self.port_spinBox.setValue(
                    int(self.add_link_dictionary_1['port']))
            except:
                pass
# proxy user lineEdit initialization
            try:
                self.proxy_user_lineEdit.setText(
                    self.add_link_dictionary_1['proxy_user'])
            except:
                pass
# proxy pass lineEdit initialization
            try:
                self.proxy_pass_lineEdit.setText(
                    self.add_link_dictionary_1['proxy_passwd'])
            except:
                pass


# download UserName initialization
        if self.add_link_dictionary_1['download_user']:
            self.download_checkBox.setChecked(True)
            self.download_user_lineEdit.setText(
                self.add_link_dictionary_1['download_user'])
# download PassWord initialization
            try:
                self.download_pass_lineEdit.setText(
                    self.add_link_dictionary_1['download_passwd'])
            except:
                pass

# folder_path
        try:
            self.download_folder_lineEdit.setText(
                self.add_link_dictionary_1['download_path'])
        except:
            pass

# connections
        try:
            self.connections_spinBox.setValue(
                int(self.add_link_dictionary_1['connections']))
        except:
            pass

# get categories name and add them to add_queue_comboBox
        categories_list = self.parent.persepolis_db.categoriesList()
        for queue in categories_list:
            if queue != 'All Downloads':
                self.add_queue_comboBox.addItem(queue)

        # finding current queue and setting it!
        self.current_category = self.download_table_dict_1['category']

        current_category_index = self.add_queue_comboBox.findText(
            self.current_category)
        self.add_queue_comboBox.setCurrentIndex(current_category_index)


# add_queue_comboBox event
        self.add_queue_comboBox.currentIndexChanged.connect(self.queueChanged)


# limit speed
        limit = str(self.add_link_dictionary_1['limit_value'])
        if limit != '0':
            self.limit_checkBox.setChecked(True)
            limit_number = limit[0:-1]
            limit_unit = limit[-1]
            self.limit_spinBox.setValue(float(limit_number))
            if limit_unit == "K":
                self.limit_comboBox.setCurrentIndex(0)
            else:
                self.limit_comboBox.setCurrentIndex(1)

# start_time
        if self.add_link_dictionary_1['start_time']:
            # get hour and minute
            hour, minute = self.add_link_dictionary_1['start_time'].split(':')

            # set time
            q_time = QTime(int(hour), int(minute))
            self.start_time_qDataTimeEdit.setTime(q_time)

            self.start_checkBox.setChecked(True)
# end_time
        if self.add_link_dictionary_1['end_time']:
            # get hour and minute
            hour, minute = self.add_link_dictionary_1['end_time'].split(':')

            # set time
            q_time = QTime(int(hour), int(minute))
            self.end_time_qDateTimeEdit.setTime(q_time)

            self.end_checkBox.setChecked(True)

        # referer
        if self.add_link_dictionary_1['referer']:
            self.referer_lineEdit.setText(str(self.add_link_dictionary_1['referer']))

        if self.add_link_dictionary_1['header']:
            self.header_lineEdit.setText(str(self.add_link_dictionary_1['header']))

        if self.add_link_dictionary_1['user_agent']:
            self.user_agent_lineEdit.setText(str(self.add_link_dictionary_1['user_agent']))

        if self.add_link_dictionary_1['load_cookies']:
            self.load_cookies_lineEdit.setText((self.add_link_dictionary_1['load_cookies']))


# set window size and position
        size = self.persepolis_setting.value(
            'PropertiesWindow/size', QSize(520, 425))
        position = self.persepolis_setting.value(
            'PropertiesWindow/position', QPoint(300, 300))
        self.resize(size)
        self.move(position)
示例#23
0
    def defaultsPushButtonPressed(self, button):

        self.persepolis_setting.beginGroup('settings')

        self.setting_dict = returnDefaultSettings()

        self.tries_spinBox.setValue(int(self.setting_dict['max-tries']))
        self.wait_spinBox.setValue(int(self.setting_dict['retry-wait']))
        self.time_out_spinBox.setValue(int(self.setting_dict['timeout']))
        self.connections_spinBox.setValue(int(
            self.setting_dict['connections']))

        self.rpc_port_spinbox.setValue(int(self.setting_dict['rpc-port']))
        self.aria2_path_lineEdit.setText('')
        self.aria2_path_checkBox.setChecked(False)

        # wait-queue
        wait_queue_list = self.setting_dict['wait-queue']
        q_time = QTime(wait_queue_list[0], wait_queue_list[1])
        self.wait_queue_time.setTime(q_time)

        # save_as_tab
        self.download_folder_lineEdit.setText(
            str(self.setting_dict['download_path']))
        self.temp_download_lineEdit.setText(
            str(self.setting_dict['download_path_temp']))

        self.subfolder_checkBox.setChecked(True)

        # notifications_tab
        self.volume_label.setText('Volume : ' +
                                  str(self.setting_dict['sound-volume']))
        self.volume_dial.setValue(int(self.setting_dict['sound-volume']))

        # set style
        current_style_index = self.style_comboBox.findText(
            str(self.setting_dict['style']))
        self.style_comboBox.setCurrentIndex(current_style_index)

        # set language
        current_locale = self.lang_comboBox.findData(
            str(self.setting_dict['locale']))
        self.lang_comboBox.setCurrentIndex(current_locale)

        # set color_scheme
        current_color_index = self.color_comboBox.findText(
            str(self.setting_dict['color-scheme']))
        self.color_comboBox.setCurrentIndex(current_color_index)

        # set icons
        current_icons_index = self.icon_comboBox.findText(
            str(self.setting_dict['icons']))
        self.icon_comboBox.setCurrentIndex(current_icons_index)

        # set icons size
        current_icons_size_index = self.icons_size_comboBox.findText(
            str(self.setting_dict['toolbar_icon_size']))
        self.icons_size_comboBox.setCurrentIndex(current_icons_size_index)

        # set notification
        current_notification_index = self.notification_comboBox.findText(
            str(self.setting_dict['notification']))
        self.notification_comboBox.setCurrentIndex(current_notification_index)

        # set font
        self.font_checkBox.setChecked(False)
        font_setting = QFont()
        font_setting.setFamily(str(self.setting_dict['font']))
        self.fontComboBox.setCurrentFont(font_setting)

        self.font_size_spinBox.setValue(int(self.setting_dict['font-size']))

        # sound frame
        self.enable_notifications_checkBox.setChecked(True)

        # start_persepolis_if_browser_executed_checkBox
        self.start_persepolis_if_browser_executed_checkBox.setChecked(True)

        # hide window
        self.hide_window_checkBox.setChecked(True)

        # tray icon
        self.enable_system_tray_checkBox.setChecked(True)

        # after_download_checkBox
        self.after_download_checkBox.setChecked(True)

        # hide menubar for linux
        if platform.system == 'Darwin':
            self.show_menubar_checkbox.setChecked(True)
        else:
            self.show_menubar_checkbox.setChecked(False)

        # show side panel
        self.show_sidepanel_checkbox.setChecked(True)

        # show progress window
        self.show_progress_window_checkbox.setChecked(True)

        # run persepolis at startup checkBox
        self.startup_checkbox.setChecked(False)

        # keep_awake_checkBox
        self.keep_awake_checkBox.setChecked(False)

        # columns_tab
        self.column0_checkBox.setChecked(True)
        self.column1_checkBox.setChecked(True)
        self.column2_checkBox.setChecked(True)
        self.column3_checkBox.setChecked(True)
        self.column4_checkBox.setChecked(True)
        self.column5_checkBox.setChecked(True)
        self.column6_checkBox.setChecked(True)
        self.column7_checkBox.setChecked(True)
        self.column10_checkBox.setChecked(True)
        self.column11_checkBox.setChecked(True)
        self.column12_checkBox.setChecked(True)

        # video finder
        self.max_links_spinBox.setValue(3)

        # shortcuts
        self.shortcuts_list = [
            self.setting_dict['shortcuts/quit_shortcut'],
            self.setting_dict['shortcuts/hide_window_shortcut'],
            self.setting_dict['shortcuts/remove_shortcut'],
            self.setting_dict['shortcuts/delete_shortcut'],
            self.setting_dict['shortcuts/move_up_selection_shortcut'],
            self.setting_dict['shortcuts/move_down_selection_shortcut'],
            self.setting_dict['shortcuts/add_new_download_shortcut'],
            self.setting_dict['shortcuts/video_finder_shortcut'],
            self.setting_dict['shortcuts/import_text_shortcut']
        ]

        # add shortcuts to the shortcut_table
        j = 0
        for shortcut in self.shortcuts_list:
            item = QTableWidgetItem(shortcut)

            # align center
            item.setTextAlignment(0x0004 | 0x0080)

            # insert item in shortcut_table
            self.shortcut_table.setItem(j, 1, item)

            j = j + 1

        self.persepolis_setting.endGroup()
示例#24
0
    def alterTable3(self, newMTD):
        if self.hasCheckColumn(newMTD):
            return False

        oldMTD = newMTD
        fieldList = oldMTD.fieldList()

        renameOld = "%salteredtable%s" % (oldMTD.name()[0:5], QDateTime(
        ).currentDateTime().toString("ddhhssz"))

        self.db_.dbAux().transaction()

        q = FLSqlQuery(None, self.db_.dbAux())

        constraintName = "%s_key" % oldMTD.name()

        if self.constraintExists(constraintName) and not q.exec_(
                "ALTER TABLE %s DROP CONSTRAINT %s" %
            (oldMTD.name(), constraintName)):
            self.db_.dbAux().rollback()
            return False

        for oldField in fieldList:
            if oldField.isCheck():
                return False
            if oldField.isUnique():
                constraintName = "%s_%s_key" % (oldMTD.name(), oldField.name())
                if self.constraintExists(constraintName) and not q.exec_(
                        "ALTER TABLE %s DROP CONSTRAINT %s" %
                    (oldMTD.name(), constraintName)):
                    self.db_.dbAux().rollback()
                    return False

        if not q.exec_("ALTER TABLE %s RENAME TO %s" %
                       (oldMTD.name(), renameOld)):
            self.db_.dbAux().rollback()
            return False

        if not self.db_.manager().createTable(newMTD):
            self.db_.dbAux().rollback()
            return False

        oldCursor = FLSqlCursor(renameOld, True, self.db_.dbAux())
        oldCursor.setModeAccess(oldCursor.Browse)
        oldCursor.select()

        fieldList = newMTD.fieldList()

        if not fieldList:
            self.db_.dbAux().rollback()
            return False

        oldCursor.select()
        totalSteps = oldCursor.size()
        progress = QProgressDialog(
            qApp.tr("Reestructurando registros para %1...").arg(
                newMTD.alias()), qApp.tr("Cancelar"), 0, totalSteps)
        progress.setLabelText(qApp.tr("Tabla modificada"))

        step = 0
        newBuffer = None
        newField = None
        listRecords = []
        newBufferInfo = self.recordInfo2(newMTD.name())
        oldFieldsList = {}
        newFieldsList = {}
        defValues = {}
        v = None

        for newField in fieldList:
            oldField = oldMTD.field(newField.name())
            defValues[str(step)] = None
            if not oldField or not oldCursor.field(oldField.name()):
                if not oldField:
                    oldField = newField
                if not newField.type() == "serial":
                    v = newField.defaultValue()
                    defValues[str(step)] = v

            newFieldsList[str(step)] = newField
            oldFieldsList[str(step)] = oldField
            step = step + 1

        ok = True
        while oldCursor.next():
            newBuffer = newBufferInfo

            for reg in defValues.keys():
                newField = newFieldsList[reg]
                oldField = oldFieldsList[reg]
                if defValues[reg]:
                    v = defValues[reg]
                else:
                    v = oldCursor.value(newField.name())
                    if (not oldField.allowNull or not newField.allowNull()
                        ) and not v and not newField.type() == "serial":
                        defVal = newField.defaultValue()
                        if defVal is not None:
                            v = defVal

                    if v is not None and not newBuffer.field(
                            newField.name()).type() == newField.type():
                        print("FLManager::alterTable : " + qApp.tr(
                            "Los tipos del campo %1 no son compatibles. Se introducirá un valor nulo."
                        ).arg(newField.name()))

                    if v is not None and newField.type(
                    ) == "string" and newField.length() > 0:
                        v = str(v)[0:newField.length()]

                    if (not oldField.allowNull()
                            or not newField.allowNull()) and v is None:
                        if oldField.type() == "serial":
                            v = int(
                                self.nextSerialVal(newMTD.name(),
                                                   newField.name()))
                        elif oldField.type() in ("int", "uint", "bool",
                                                 "unlock"):
                            v = 0
                        elif oldField.type() == "double":
                            v = 0.0
                        elif oldField.type() == "time":
                            v = QTime().currentTime()
                        elif oldField.type() == "date":
                            v = QDate().currentDate()
                        else:
                            v = "NULL"[0:newField.length()]

                    newBuffer.setValue(newField.name(), v)

                listRecords.append(newBuffer)

            # if not self.insertMulti(newMTD.name(), listRecords):
            #    ok = False
            #    listRecords.clear()
            #    break

            # listRecords.clear()

        if len(listRecords) > 0:
            if not self.insertMulti(newMTD.name(), listRecords):
                ok = False
            listRecords.clear()

        if ok:
            self.db_.dbAux().commit()
        else:
            self.db_.dbAux().rollback()
            return False

        force = False  # FIXME
        if force and ok:
            q.exec_("DROP TABLE %s CASCADE" % renameOld)
        return True
示例#25
0
    def go_btn_slot(self):
        new_position = QTime(0, 0).secsTo(self.time_edit.time()) * 1000
        self.input_manager.set_position(new_position)

        self.done(0)
示例#26
0
    def alterTable2(self, mtd1, mtd2, key, force=False):

        util = FLUtil()

        oldMTD = None
        newMTD = None
        doc = QDomDocument("doc")
        docElem = None

        if not util.docDocumentSetContect(doc, mtd1):
            print("FLManager::alterTable : " +
                  qApp.tr("Error al cargar los metadatos."))
        else:
            docElem = doc.documentElement()
            oldMTD = self.db_.manager().metadata(docElem, True)

        if oldMTD and oldMTD.isQuery():
            return True

        if not util.docDocumentSetContect(doc, mtd2):
            print("FLManager::alterTable : " +
                  qApp.tr("Error al cargar los metadatos."))
            return False
        else:
            docElem = doc.documentElement()
            newMTD = self.db_.manager().metadata(docElem, True)

        if not oldMTD:
            oldMTD = newMTD

        if not oldMTD.name() == newMTD.name():
            print("FLManager::alterTable : " +
                  qApp.tr("Los nombres de las tablas nueva y vieja difieren."))
            if oldMTD and not oldMTD == newMTD:
                del oldMTD
            if newMTD:
                del newMTD

            return False

        oldPK = oldMTD.primaryKey()
        newPK = newMTD.primaryKey()

        if not oldPK == newPK:
            print("FLManager::alterTable : " +
                  qApp.tr("Los nombres de las claves primarias difieren."))
            if oldMTD and not oldMTD == newMTD:
                del oldMTD
            if newMTD:
                del newMTD

            return False

        if not self.db_.manager().checkMetaData(oldMTD, newMTD):
            if oldMTD and not oldMTD == newMTD:
                del oldMTD
            if newMTD:
                del newMTD

            return True

        if not self.db_.manager().existsTable(oldMTD.name()):
            print("FLManager::alterTable : " + qApp.tr(
                "La tabla %1 antigua de donde importar los registros no existe."
            ).arg(oldMTD.name()))
            if oldMTD and not oldMTD == newMTD:
                del oldMTD
            if newMTD:
                del newMTD

            return False

        fieldList = oldMTD.fieldList()
        oldField = None

        if not fieldList:
            print("FLManager::alterTable : " +
                  qApp.tr("Los antiguos metadatos no tienen campos."))
            if oldMTD and not oldMTD == newMTD:
                del oldMTD
            if newMTD:
                del newMTD

            return False

        renameOld = "%salteredtable%s" % (oldMTD.name()[0:5], QDateTime(
        ).currentDateTime().toString("ddhhssz"))

        if not self.db_.dbAux():
            if oldMTD and not oldMTD == newMTD:
                del oldMTD
            if newMTD:
                del newMTD

            return False

        self.db_.dbAux().transaction()

        if key and len(key) == 40:
            c = FLSqlCursor("flfiles", True, self.db_.dbAux())
            c.setForwardOnly(True)
            c.setFilter("nombre = '%s.mtd'" % renameOld)
            c.select()
            if not c.next():
                buffer = c.primeInsert()
                buffer.setValue("nombre", "%s.mtd" % renameOld)
                buffer.setValue("contenido", mtd1)
                buffer.setValue("sha", key)
                c.insert()

        q = FLSqlQuery("", self.db_.dbAux())
        constraintName = "%s_pkey" % oldMTD.name()

        if self.constraintExists(constraintName) and not q.exec_(
                "ALTER TABLE %s DROP CONSTRAINT %s" %
            (oldMTD.name(), constraintName)):
            print("FLManager : " + qApp.tr(
                "En método alterTable, no se ha podido borrar el índice %1_pkey de la tabla antigua."
            ).arg(oldMTD.name()))
            self.db_.dbAux().rollback()
            if oldMTD and not oldMTD == newMTD:
                del oldMTD
            if newMTD:
                del newMTD

            return False

        fieldsNamesOld = []
        for it in fieldList:
            if newMTD.field(it.name()):
                fieldsNamesOld.append(it.name())

            if it.isUnique():
                constraintName = "%s_%s_key" % (oldMTD.name(), it.name())
                if self.constraintExists(constraintName) and not q.exec_(
                        "ALTER TABLE %s DROP CONSTRAINT %s" %
                    (oldMTD.name(), constraintName)):
                    print("FLManager : " + qApp.tr(
                        "En método alterTable, no se ha podido borrar el índice %1_%2_key de la tabla antigua."
                    ).arg(oldMTD.name(), oldField.name()))
                    self.db_.dbAux().rollback()
                    if oldMTD and not oldMTD == newMTD:
                        del oldMTD
                    if newMTD:
                        del newMTD

                    return False

        if not q.exec_("ALTER TABLE %s RENAME TO %s" %
                       (oldMTD.name(), renameOld)):
            print("FLManager::alterTable : " +
                  qApp.tr("No se ha podido renombrar la tabla antigua."))

            self.db_.dbAux().rollback()
            if oldMTD and not oldMTD == newMTD:
                del oldMTD
            if newMTD:
                del newMTD

            return False

        if not self.db_.manager().createTable(newMTD):
            self.db_.dbAux().rollback()
            if oldMTD and not oldMTD == newMTD:
                del oldMTD
            if newMTD:
                del newMTD

            return False

        v = None
        ok = False

        if not force and not fieldsNamesOld:
            self.db_.dbAux().rollback()
            if oldMTD and not oldMTD == newMTD:
                del oldMTD
            if newMTD:
                del newMTD

            return self.alterTable2(mtd1, mtd2, key, True)

        oldCursor = FLSqlCursor(renameOld, True, self.db_.dbAux())
        oldCursor.setModeAccess(oldCursor.Browse)
        newCursor = FLSqlCursor(newMTD.name(), True, self.db_.dbAux())
        newCursor.setMode(newCursor.Insert)

        oldCursor.select()
        totalSteps = oldCursor.size()
        progress = QProgressDialog(
            qApp.tr("Reestructurando registros para %1...").arg(
                newMTD.alias()), qApp.tr("Cancelar"), 0, totalSteps)
        progress.setLabelText(qApp.tr("Tabla modificada"))

        step = 0
        newBuffer = None
        newField = None
        listRecords = []
        newBufferInfo = self.recordInfo2(newMTD.name())
        oldFieldsList = {}
        newFieldsList = {}
        defValues = {}
        v = None

        for newField in fieldList:
            oldField = oldMTD.field(newField.name())
            defValues[str(step)] = None
            if not oldField or not oldCursor.field(oldField.name()):
                if not oldField:
                    oldField = newField
                if not newField.type() == "serial":
                    v = newField.defaultValue()
                    defValues[str(step)] = v

            newFieldsList[str(step)] = newField
            oldFieldsList[str(step)] = oldField
            step = step + 1

        step = 0
        ok = True
        while oldCursor.next():
            newBuffer = newBufferInfo

            for reg in defValues.keys():
                newField = newFieldsList[reg]
                oldField = oldFieldsList[reg]
                if defValues[reg]:
                    v = defValues[reg]
                else:
                    v = oldCursor.value(newField.name())
                    if (not oldField.allowNull or not newField.allowNull()
                        ) and not v and not newField.type() == "serial":
                        defVal = newField.defaultValue()
                        if defVal is not None:
                            v = defVal

                    if v is not None and not newBuffer.field(
                            newField.name()).type() == newField.type():
                        print("FLManager::alterTable : " + qApp.tr(
                            "Los tipos del campo %1 no son compatibles. Se introducirá un valor nulo."
                        ).arg(newField.name()))

                if v is not None and newField.type(
                ) == "string" and newField.length() > 0:
                    v = str(v)[0:newField.length()]

                if (not oldField.allowNull()
                        or not newField.allowNull()) and v is None:
                    if oldField.type() == "serial":
                        v = int(
                            self.nextSerialVal(newMTD.name(), newField.name()))
                    elif oldField.type() in ("int", "uint", "bool", "unlock"):
                        v = 0
                    elif oldField.type() == "double":
                        v = 0.0
                    elif oldField.type() == "time":
                        v = QTime().currentTime()
                    elif oldField.type() == "date":
                        v = QDate().currentDate()
                    else:
                        v = "NULL"[0:newField.length()]

                newBuffer.setValue(newField.name(), v)

            listRecords.append(newBuffer)

            if not self.insertMulti(newMTD.name(), listRecords):
                ok = False
                listRecords.clear()
                break

            listRecords.clear()

        if len(listRecords) > 0:
            if not self.insertMulti(newMTD.name(), listRecords):
                ok = False
            listRecords.clear()

        progress.setProgress(totalSteps)

        if oldMTD and not oldMTD == newMTD:
            del oldMTD

        if newMTD:
            del newMTD

        if ok:
            self.db_.dbAux().commit()
        else:
            self.db_.dbAux().rollback()
            return False

        if force and ok:
            q.exec_("DROP TABLE %s CASCADE" % renameOld)

        return True
 def on_duration_changed(self, duration):
     self.position_slider.setRange(0, duration)
     mtime = QTime(0, 0, 0, 0)
     mtime = mtime.addMSecs(self.media_player.duration())
     self.full_time_viewer.setText(mtime.toString())
示例#28
0
 def durationChanged(self, duration):
     self.positionSlider.setRange(0, duration)
     mtime = QTime(0,0,0,0)
     mtime = mtime.addMSecs(self.mediaPlayer.duration())
     self.elbl.setText(mtime.toString())
示例#29
0
    #     painter.fillRect(rect.intersected(sceneRect), QBrush(gradient))
    #     painter.setBrush(Qt.NoBrush)
    #     painter.drawRect(sceneRect)

    # Text.
    # textRect = QRectF(sceneRect.left() + 4, sceneRect.top() + 4,
    #                   sceneRect.width() - 4, sceneRect.height() - 4)
    # message = "Click and drag the nodes around, and zoom with the " \
    #           "mouse wheel or the '+' and '-' keys"
    #
    # font = painter.font()
    # font.setBold(True)
    # font.setPointSize(14)
    # painter.setFont(font)
    # painter.setPen(Qt.lightGray)
    # painter.drawText(textRect.translated(2, 2), message)
    # painter.setPen(Qt.black)
    # painter.drawText(textRect, message)


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    qsrand(QTime(0, 0, 0).secsTo(QTime.currentTime()))

    widget = GraphWidget()
    widget.show()

    sys.exit(app.exec_())
示例#30
0
    def reset_forms_month(self):
        reset_time, reset_text = QTime(00, 00), "00:00"

        self.ui.form_month_1_time_start.setTime(reset_time)
        self.ui.form_month_2_time_start.setTime(reset_time)
        self.ui.form_month_3_time_start.setTime(reset_time)
        self.ui.form_month_4_time_start.setTime(reset_time)
        self.ui.form_month_5_time_start.setTime(reset_time)
        self.ui.form_month_6_time_start.setTime(reset_time)
        self.ui.form_month_7_time_start.setTime(reset_time)
        self.ui.form_month_8_time_start.setTime(reset_time)
        self.ui.form_month_9_time_start.setTime(reset_time)
        self.ui.form_month_10_time_start.setTime(reset_time)
        self.ui.form_month_11_time_start.setTime(reset_time)
        self.ui.form_month_12_time_start.setTime(reset_time)
        self.ui.form_month_13_time_start.setTime(reset_time)
        self.ui.form_month_14_time_start.setTime(reset_time)
        self.ui.form_month_15_time_start.setTime(reset_time)
        self.ui.form_month_16_time_start.setTime(reset_time)
        self.ui.form_month_17_time_start.setTime(reset_time)
        self.ui.form_month_18_time_start.setTime(reset_time)
        self.ui.form_month_19_time_start.setTime(reset_time)
        self.ui.form_month_20_time_start.setTime(reset_time)
        self.ui.form_month_21_time_start.setTime(reset_time)
        self.ui.form_month_22_time_start.setTime(reset_time)
        self.ui.form_month_23_time_start.setTime(reset_time)
        self.ui.form_month_24_time_start.setTime(reset_time)
        self.ui.form_month_25_time_start.setTime(reset_time)
        self.ui.form_month_26_time_start.setTime(reset_time)
        self.ui.form_month_27_time_start.setTime(reset_time)
        self.ui.form_month_28_time_start.setTime(reset_time)
        self.ui.form_month_29_time_start.setTime(reset_time)
        self.ui.form_month_30_time_start.setTime(reset_time)
        self.ui.form_month_31_time_start.setTime(reset_time)

        self.ui.form_month_1_time_end.setTime(reset_time)
        self.ui.form_month_2_time_end.setTime(reset_time)
        self.ui.form_month_3_time_end.setTime(reset_time)
        self.ui.form_month_4_time_end.setTime(reset_time)
        self.ui.form_month_5_time_end.setTime(reset_time)
        self.ui.form_month_6_time_end.setTime(reset_time)
        self.ui.form_month_7_time_end.setTime(reset_time)
        self.ui.form_month_8_time_end.setTime(reset_time)
        self.ui.form_month_9_time_end.setTime(reset_time)
        self.ui.form_month_10_time_end.setTime(reset_time)
        self.ui.form_month_11_time_end.setTime(reset_time)
        self.ui.form_month_12_time_end.setTime(reset_time)
        self.ui.form_month_13_time_end.setTime(reset_time)
        self.ui.form_month_14_time_end.setTime(reset_time)
        self.ui.form_month_15_time_end.setTime(reset_time)
        self.ui.form_month_16_time_end.setTime(reset_time)
        self.ui.form_month_17_time_end.setTime(reset_time)
        self.ui.form_month_18_time_end.setTime(reset_time)
        self.ui.form_month_19_time_end.setTime(reset_time)
        self.ui.form_month_20_time_end.setTime(reset_time)
        self.ui.form_month_21_time_end.setTime(reset_time)
        self.ui.form_month_22_time_end.setTime(reset_time)
        self.ui.form_month_23_time_end.setTime(reset_time)
        self.ui.form_month_24_time_end.setTime(reset_time)
        self.ui.form_month_25_time_end.setTime(reset_time)
        self.ui.form_month_26_time_end.setTime(reset_time)
        self.ui.form_month_27_time_end.setTime(reset_time)
        self.ui.form_month_28_time_end.setTime(reset_time)
        self.ui.form_month_29_time_end.setTime(reset_time)
        self.ui.form_month_30_time_end.setTime(reset_time)
        self.ui.form_month_31_time_end.setTime(reset_time)

        self.ui.form_month_total_results.setText(reset_text)