Ejemplo n.º 1
0
class QTimeInputDialog(QDialog):

    def __init__(self, title='', description='', initial=QtCore.QTime(),
                 minValue=QtCore.QTime(), maxValue=QtCore.QTime(),
                 dformat='mm.ss', parent=None):
        super().__init__(parent)

        self.setWindowTitle(title)

        self.setWindowModality(QtCore.Qt.ApplicationModal)
        self.setMaximumSize(300, 110)
        self.setMinimumSize(300, 110)
        self.resize(300, 130)

        self.label = QLabel(description, self)
        self.label.setGeometry(10, 0, 280, 20)
        self.label.setAlignment(QtCore.Qt.AlignCenter)

        self.time = QTimeEdit(self)
        self.time.setDisplayFormat(dformat)
        self.time.setMaximumTime(maxValue)
        self.time.setMinimumTime(minValue)
        self.time.setTime(initial)
        self.time.setGeometry(10, 30, 280, 25)

        self.acceptButton = QPushButton(self)
        self.acceptButton.setGeometry(QtCore.QRect(180, 80, 100, 25))
        self.acceptButton.setText("Ok")

        self.rejectButton = QPushButton(self)
        self.rejectButton.setGeometry(QtCore.QRect(60, 80, 100, 25))
        self.rejectButton.setText("Cancel")

        self.rejectButton.clicked.connect(self.reject)
        self.acceptButton.clicked.connect(self.accept)
Ejemplo n.º 2
0
    def initUI(self):
        lbl = QLabel('QTimeEdit')

        timeedit = QTimeEdit(self)
        timeedit.setTime(QTime.currentTime())
        timeedit.setTimeRange(QTime(3, 00, 00), QTime(23, 30, 00))
        # QTimeEdit 클래스를 이용해서 시간 편집 위젯(timeedit)을 하나 만들어줍니다.
        #
        # setTime 메서드에 QTime.currentTime()를 입력해서 프로그램이
        # 실행될 때 현재 시간으로 표시되도록 합니다.
        #
        # setTimeRange 이용하면 사용자가 선택할 수 있는 시간의 범위를 제한할 수 있습니다.
        #
        # 최소 시간은 디폴트로 00시 00분 00초 000밀리초로 설정되어 있고,
        # 최대 시간은 23시 59분 59초 999밀리초로 설정되어 있습니다.
        timeedit.setDisplayFormat('hh:mm:ss')
        # setDisplayFormat 메서드를 이용해서 시간이 'hh:mm:ss'의
        # 형식으로 표시되도록 설정했습니다.

        vbox = QVBoxLayout()
        vbox.addWidget(lbl)
        vbox.addWidget(timeedit)
        vbox.addStretch()
        # 수직 박스 레이아웃을 이용해서 라벨과 시간 편집 위젯을 수직으로 배치하고,
        # 전체 위젯의 레이아웃으로 설정합니다.

        self.setLayout(vbox)

        self.setWindowTitle('QTimeEdit')
        self.setGeometry(300, 300, 300, 200)
        self.show()
Ejemplo n.º 3
0
class ClassTimePicker(QWidget):
    def __init__(self, parent=None):
        super(ClassTimePicker, self).__init__(parent=parent)
        self.time_selector = QTimeEdit()
        self.time_selector.sizePolicy().setRetainSizeWhenHidden(False)
        self.time_selector.setDisplayFormat("hh:mm AP")
        self.time_selector.setTime(QTime(12, 0, 0))

        self.day_picker = DayPicker()
        self.day_picker.sizePolicy().setRetainSizeWhenHidden(False)

        self.layout = QHBoxLayout()
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.addWidget(self.time_selector)
        self.layout.addWidget(self.day_picker)
        self.setLayout(self.layout)

    def get_time(self):
        return self.time_selector.time()

    def set_time(self, time: QTime):
        self.time_selector.setTime(time)

    def set_day(self, day):
        for b in self.day_picker.buttons:
            if b.text() == day:
                b.click()

    def is_valid(self):
        return self.day_picker.get_day() is not None
Ejemplo n.º 4
0
    def MyTime(self):
        vbox = QVBoxLayout()
        time = QTime()
        time.setHMS(13, 15, 40)
        timeedit = QTimeEdit()
        timeedit.setFont(QtGui.QFont("Sanserif", 15))
        timeedit.setTime(time)

        vbox.addWidget(timeedit)
        self.setLayout(vbox)
Ejemplo n.º 5
0
def get_widget_from_ranking(ranking):
    assert isinstance(ranking, RankingItem)
    qual = ranking.qual.name
    qual_checkbox = QCheckBox(ranking.qual.get_title())
    qual_checkbox.setFixedWidth(50)
    qual_checkbox.setObjectName(qual + '_checkbox')

    type_combo = AdvComboBox()
    type_combo.addItems({_('Rank'), _('Max place'), _('Result time')})
    type_combo.setFixedWidth(150)
    type_combo.setObjectName(qual + '_combo')

    max_place = QSpinBox()
    max_place.setValue(0)
    max_place.setFixedWidth(70)
    max_place.setObjectName(qual + '_place')

    max_time = QTimeEdit()
    max_time.setFixedWidth(70)
    max_time.setDisplayFormat("hh:mm:ss")
    max_time.setObjectName(qual + '_time')

    def select_type():
        text = type_combo.currentText()
        max_place.setVisible(text == _('Max place'))
        max_time.setVisible(text == _('Result time'))

    def set_enabled():
        flag = qual_checkbox.isChecked()
        type_combo.setEnabled(flag)
        max_place.setEnabled(flag)
        max_time.setEnabled(flag)

    type_combo.currentIndexChanged.connect(select_type)
    qual_checkbox.stateChanged.connect(set_enabled)

    if ranking.use_scores:
        type_combo.setCurrentText(_('Rank'))
    elif ranking.max_place:
        type_combo.setCurrentText(_('Max place'))
        max_place.setValue(ranking.max_place)
    else:
        type_combo.setCurrentText(_('Result time'))
        max_time.setTime(time_to_qtime(ranking.max_time))

    qual_checkbox.setChecked(ranking.is_active)
    select_type()
    set_enabled()

    layout = QHBoxLayout()
    layout.addWidget(qual_checkbox)
    layout.addWidget(type_combo)
    layout.addWidget(max_place)
    layout.addWidget(max_time)
    return layout
Ejemplo n.º 6
0
    def my_time(self):
        vbox = QVBoxLayout()

        time = QtCore.QTime()
        time.setHMS(13, 15, 20)

        time_edit = QTimeEdit()
        time_edit.setFont(QtGui.QFont("Sanserif", 30))
        time_edit.setTime(time)

        vbox.addWidget(time_edit)
        self.setLayout(vbox)
    def initUI(self):
        label = QLabel('QTimeEdit')
        label.setAlignment(Qt.AlignCenter)

        time = QTimeEdit(self)
        time.setTime(QTime.currentTime())
        time.setTimeRange(QTime(00, 00, 00), QTime.currentTime())
        time.setDisplayFormat('a:hh:mm:ss.zzz')

        label2 = QLabel('QDateEdit')
        label2.setAlignment(Qt.AlignCenter)

        self.date_edit = QDateEdit(self)
        self.date_edit.setDate(QDate.currentDate())
        self.date_edit.setDateRange(QDate(2000, 1, 1), QDate.currentDate())
        # self.date_edit.setDisplayFormat('yyyy년 MMMM d일')
        self.date_edit.dateChanged.connect(self.dateChange)

        self.label3 = QLabel('이곳에 QDateEdit에서 선택된 값이 나타납니다.')
        self.label3.setAlignment(Qt.AlignCenter)

        label4 = QLabel('QDateTimeEdit')
        label4.setAlignment(Qt.AlignCenter)

        label5 = QLabel(self)
        label5.setAlignment(Qt.AlignCenter)
        label5.setText(
            f'QDateTime \n 현재 시간은 {QDateTime.currentDateTime().toString("yyyy년 MMMM d일 ap hh시 mm분 ss초.zzz")} 입니다.'
        )

        dt_edit = QDateTimeEdit(self)
        dt_edit.setDateTimeRange(QDateTime(2020, 1, 1, 00, 00, 00),\
                                 QDateTime(2021, 1, 1, 00, 00, 00))
        dt_edit.setDisplayFormat('yyyy.MM.dd hh:mm:ss')

        vbox = QVBoxLayout()
        vbox.addWidget(label)
        vbox.addWidget(time)
        vbox.addWidget(label2)
        vbox.addWidget(self.date_edit)
        vbox.addWidget(self.label3)
        vbox.addWidget(label4)
        vbox.addWidget(label5)
        vbox.addWidget(dt_edit)

        self.setLayout(vbox)

        self.setWindowTitle('QTime, QDateEdit, QDateTimeEdit')
        self.setGeometry(300, 300, 400, 300)
        self.show()
Ejemplo n.º 8
0
 def addAllIntervals(self):
     fromTimeEdit = QTimeEdit()
     toTimeEdit = QTimeEdit()
     fromTimeEdit.setDisplayFormat("H.m.s.zzz")
     toTimeEdit.setDisplayFormat("H.m.s.zzz")
     for i in range(self.alternativeIntervals_comboBox.count()):
         timeFromInterval, timeToInterval = self.insertIntervalInTimeEdits(
             self.alternativeIntervals_comboBox.itemText(i))
         fromTimeEdit.setTime(timeFromInterval)
         toTimeEdit.setTime(timeToInterval)
         self.addInterval(fromTimeEdit=fromTimeEdit,
                          toTimeEdit=toTimeEdit,
                          warnings=False)
     self.updateComboBoxes()
Ejemplo n.º 9
0
    def __set_uhrzeit_datum(self, uhrzeit: str, widget: QtWidgets.QTimeEdit):
        """
        Setzt die Uhrzeit in einem QTimeEdit in der GUI.
        
        Args:
            uhrzeit: Uhrzeit des Termins im Format h:m
            widget: QTimeEdit, welches gesezt wird

        Raise:
            AssertionError: Zeitangabe fehlerhaft
        """

        time = QTime.fromString(uhrzeit, 'h:m')
        assert(QTime.isValid(time))
        widget.setTime(time)
Ejemplo n.º 10
0
 def group_time_spinbox(self):
     group2 = QGroupBox('QTimeEdit')
     lbl = QLabel('QTimeEdit')
     timeedit = QTimeEdit(self)
     timeedit.setTime(QTime.currentTime())
     timeedit.setTimeRange(QTime(3, 00, 00), QTime(23, 30, 00))
     timeedit.setDisplayFormat('hh:mm:ss')
     timeedit.timeChanged.connect(self.time_value_change)
     # dateedit.setDateRange(QDate(1900, 1, 1), QDate(2100, 12, 31))
     # self.lbl4 = QLabel(QTime.toString(timeedit.dateTime, 'hh:mm:ss'))
     self.lbl4 = QLabel(timeedit.time().toString('hh:mm:ss'))
     layout_group4 = QHBoxLayout()
     layout_group4.addWidget(lbl)
     layout_group4.addWidget(timeedit)
     layout_group4.addWidget(self.lbl4)
     return layout_group4
Ejemplo n.º 11
0
    def initUI(self):
        lb = QLabel('QTimeEdit')

        te = QTimeEdit(self)
        te.setTime(QTime.currentTime())
        te.setTimeRange(QTime(3, 00, 00), QTime(23, 30, 00))
        te.setDisplayFormat('hh:mm:ss')

        vbox = QVBoxLayout()
        vbox.addWidget(lb)
        vbox.addWidget(te)
        vbox.addStretch()

        self.setLayout(vbox)

        self.show_basic()
Ejemplo n.º 12
0
    def initUI(self):
        label = QLabel('QTimeEdit')

        time_edit = QTimeEdit(self)
        time_edit.setTime(QTime.currentTime())
        time_edit.setTimeRange(QTime(3, 00, 00), QTime(23, 30, 00))
        time_edit.setDisplayFormat('hh:mm:ss')

        vbox = QVBoxLayout()
        vbox.addWidget(label)
        vbox.addWidget(time_edit)
        vbox.addStretch()

        self.setLayout(vbox)

        self.setWindowTitle('QTimeEdit')
        self.setGeometry(300, 300, 300, 200)
        self.show()
Ejemplo n.º 13
0
class PresetSrcSettings(SettingsPage):
    ELEMENT = PresetSrc
    Name = ELEMENT.Name

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.setLayout(QVBoxLayout())
        self.layout().setAlignment(Qt.AlignTop)

        self.functionGroup = QGroupBox(self)
        self.functionGroup.setTitle(translate('PresetSrcSettings', 'Presets'))
        self.functionGroup.setLayout(QVBoxLayout())
        self.layout().addWidget(self.functionGroup)

        self.functionCombo = QComboBox(self.functionGroup)
        self.functionGroup.layout().addWidget(self.functionCombo)

        for function in sorted(PresetSrc.PRESETS.keys()):
            self.functionCombo.addItem(function)

        self.functionDuration = QTimeEdit(self.functionGroup)
        self.functionDuration.setDisplayFormat('HH.mm.ss.zzz')
        self.functionGroup.layout().addWidget(self.functionDuration)

    def enable_check(self, enabled):
        self.functionGroup.setCheckable(enabled)
        self.functionGroup.setChecked(False)

    def get_settings(self):
        if not (self.functionGroup.isCheckable()
                and not self.functionGroup.isChecked()):
            return {
                'preset': self.functionCombo.currentText(),
                'duration':
                self.functionDuration.time().msecsSinceStartOfDay()
            }

        return {}

    def load_settings(self, settings):
        self.functionCombo.setCurrentText(settings.get('preset', ''))
        self.functionDuration.setTime(
            QTime.fromMSecsSinceStartOfDay(settings.get('duration', 0)))
Ejemplo n.º 14
0
class LstWidget(QWidget):
    def __init__(self, value, lst_base_date, parent=None):
        super().__init__(parent)
        layout = QHBoxLayout(self)
        self.lst_base_date = lst_base_date
        # offset to lst base edit
        self.days = QSpinBox(self)
        self.days.setMinimum(-10) # somewhat arbitrary value
        self.days.setValue((value.date() - lst_base_date).days)
        layout.addWidget(self.days)
        self.time = QTimeEdit(self)
        self.time.setDisplayFormat("hh:mm:ss")
        self.time.setTime(value.time())
        layout.addWidget(self.time)

    def dateTime(self):
        # will be called by .get of the dialog, expecting a QDateTime return
        return QDateTime(datetime.combine(self.lst_base_date, 
                                          self.time.time().toPyTime()) +
                         timedelta(days=self.days.value()))
Ejemplo n.º 15
0
 def joinIntervals(self, interval1, interval2):
     interval = interval1.split(' - ')[1] + ' - ' + interval2.split(
         ' - ')[0]
     innerIntervals = [
         self.intervals_listBox.item(i).text()
         for i in range(self.intervals_listBox.count())
         if isIntersectionIntervals(interval,
                                    self.intervals_listBox.item(i).text())
     ]
     if len(innerIntervals) == 0:
         timeFromInterval, timeToInterval = self.insertIntervalInTimeEdits(
             interval=interval)
         self.fromInterval_timeEdit.setTime(timeFromInterval)
         self.toInterval_timeEdit.setTime(timeToInterval)
     else:
         beginInterval, endInterval = interval.split(' - ')
         fromTimeEdit = QTimeEdit()
         toTimeEdit = QTimeEdit()
         fromTimeEdit.setDisplayFormat("H.m.s.zzz")
         toTimeEdit.setDisplayFormat("H.m.s.zzz")
         for i in range(len(innerIntervals) + 1):
             if i == 0:
                 innerInterval = innerIntervals[i].split(' - ')
                 current_interval = beginInterval + ' - ' + innerInterval[0]
                 beginInterval = innerInterval[1]
             elif i == len(innerIntervals):
                 innerInterval = innerIntervals[i - 1].split(' - ')
                 current_interval = innerInterval[1] + ' - ' + endInterval
             else:
                 innerInterval = innerIntervals[i].split(' - ')
                 current_interval = beginInterval + ' - ' + innerInterval[0]
                 beginInterval = innerInterval[1]
             timeFromInterval, timeToInterval = self.insertIntervalInTimeEdits(
                 current_interval)
             fromTimeEdit.setTime(timeFromInterval)
             toTimeEdit.setTime(timeToInterval)
             self.addInterval(fromTimeEdit=fromTimeEdit,
                              toTimeEdit=toTimeEdit,
                              warnings=False)
     self.updateComboBoxes()
Ejemplo n.º 16
0
class TimeEntry(QWidget):
    def __init__(self, parent, name, start, end):
        super().__init__(parent=parent)
        self.layout = QHBoxLayout()
        self.name = name
        self.__setup(start, end)

    def __setup(self, start, end):
        self.setLayout(self.layout)
        self.target_box = QSpinBox(parent=self)
        self.target_box.setValue(50)
        self.start_edit = QTimeEdit(parent=self)
        self.end_edit = QTimeEdit(parent=self)
        self.start_edit.setTime(QTime(start, 0))
        self.end_edit.setTime(QTime(end, 0))

        self.layout.addWidget(QLabel(self.name))
        self.layout.addWidget(self.target_box)
        self.layout.addItem(
            QSpacerItem(1, 1, QSizePolicy.Expanding,
                        QSizePolicy.MinimumExpanding))
        self.layout.addWidget(QLabel("from"))
        self.layout.addWidget(self.start_edit)
        self.layout.addWidget(QLabel(" to "))
        self.layout.addWidget(self.end_edit)

    @property
    def target(self):
        return self.target_box.value()

    @property
    def start(self):
        return self.start_edit.time()

    @property
    def end(self):
        return self.end_edit.time()
Ejemplo n.º 17
0
class Window(QWidget):

    def __init__(self):
        super().__init__()

        # Make widgets #################

        self.edit1 = QTimeEdit()
        self.edit2 = QTimeEdit()
        self.edit3 = QTimeEdit()

        self.edit1.setMinimumTime(datetime.time(hour=8, minute=30, second=30))
        self.edit2.setMinimumTime(datetime.time(hour=8, minute=30, second=30))
        self.edit3.setMinimumTime(datetime.time(hour=8, minute=30, second=30))

        self.edit1.setMaximumTime(datetime.time(hour=18, minute=30, second=30))
        self.edit2.setMaximumTime(datetime.time(hour=18, minute=30, second=30))
        self.edit3.setMaximumTime(datetime.time(hour=18, minute=30, second=30))

        self.edit1.setTime(datetime.datetime.now().time())
        self.edit2.setTime(datetime.datetime.now().time())
        self.edit3.setTime(datetime.datetime.now().time())

        # Format: see http://doc.qt.io/qt-5/qdatetime.html#toString-2
        self.edit1.setDisplayFormat("HH:mm")
        self.edit2.setDisplayFormat("HH:mm:ss t")
        self.edit3.setDisplayFormat("h m AP")

        self.btn = QPushButton("Print")

        # Set button slot ##############

        self.btn.clicked.connect(self.printText)

        # Set the layout ###############

        vbox = QVBoxLayout()

        vbox.addWidget(self.edit1)
        vbox.addWidget(self.edit2)
        vbox.addWidget(self.edit3)

        vbox.addWidget(self.btn)

        self.setLayout(vbox)

    def printText(self):
        print(self.edit1.text())
        print(self.edit2.text())
        print(self.edit3.text())
Ejemplo n.º 18
0
class Window(QWidget):
    def __init__(self):
        super().__init__()

        # Make widgets #################

        self.edit1 = QTimeEdit()
        self.edit2 = QTimeEdit()
        self.edit3 = QTimeEdit()

        self.edit1.setMinimumTime(datetime.time(hour=8, minute=30, second=30))
        self.edit2.setMinimumTime(datetime.time(hour=8, minute=30, second=30))
        self.edit3.setMinimumTime(datetime.time(hour=8, minute=30, second=30))

        self.edit1.setMaximumTime(datetime.time(hour=18, minute=30, second=30))
        self.edit2.setMaximumTime(datetime.time(hour=18, minute=30, second=30))
        self.edit3.setMaximumTime(datetime.time(hour=18, minute=30, second=30))

        self.edit1.setTime(datetime.datetime.now().time())
        self.edit2.setTime(datetime.datetime.now().time())
        self.edit3.setTime(datetime.datetime.now().time())

        # Format: see http://doc.qt.io/qt-5/qdatetime.html#toString-2
        self.edit1.setDisplayFormat("HH:mm")
        self.edit2.setDisplayFormat("HH:mm:ss t")
        self.edit3.setDisplayFormat("h m AP")

        self.btn = QPushButton("Print")

        # Set button slot ##############

        self.btn.clicked.connect(self.printText)

        # Set the layout ###############

        vbox = QVBoxLayout()

        vbox.addWidget(self.edit1)
        vbox.addWidget(self.edit2)
        vbox.addWidget(self.edit3)

        vbox.addWidget(self.btn)

        self.setLayout(vbox)

    def printText(self):
        print(self.edit1.text())
        print(self.edit2.text())
        print(self.edit3.text())
class FCMUi(QMainWindow):
    """Fldigi Control Maintenance View (GUI)."""
    def __init__(self):
        """View initializer"""
        super().__init__()
        self.setWindowTitle('Fldigi Controller Maintenance')
        self.db = SQLiteDB(db_type="fldigi_control.db")
        self.setInitialWindowValues()
        self.setInitialFormValues()
        self.setInitialButtonValues()
        self.setInitialProgramsTableValues()
        self.setInitialAppValues()
        self.setupMethods()
        self.loadComboBoxes()
        self.loadProgramsTable()

    def setInitialAppValues(self):
        ''' Catch all for various application values. '''
        self.setFieldStatus(status=ac.DISABLE)
        self.setButtonStatus(ac.APP_STARTUP)
        self.dbPending = ac.DBPENDING_NONE
        self.primary_key = None

    def setInitialButtonValues(self):
        ''' Setup a button bar and related button group. '''
        self.buttonLayout = QHBoxLayout()
        self.generalLayout.addLayout(self.buttonLayout)
        self.buttonGroup = QButtonGroup()
        self.addPushButtons(self.buttonGroup)

    def setInitialFormValues(self):
        ''' Setup a form for data entry. '''
        self.frmLayout = QFormLayout()
        self.generalLayout.addLayout(self.frmLayout)
        self.createFormFields()

    def setInitialWindowValues(self):
        ''' Setup the basic window system. '''
        self.generalLayout = QVBoxLayout()
        self.centralwidget = QWidget(self)
        self.setCentralWidget(self.centralwidget)
        self.centralwidget.setLayout(self.generalLayout)

    def setInitialProgramsTableValues(self):
        ''' Setup a table to contain data specific to Fldigi Control values. '''
        self.tblPrograms = QTableWidget(self.centralwidget)
        self.hboxTable = QHBoxLayout()
        self.hboxTable.addWidget(self.tblPrograms)
        self.generalLayout.addLayout(self.hboxTable)
        self.tblPrograms.setEnabled(True)
        self.tblPrograms.setColumnCount(0)
        self.tblPrograms.setRowCount(0)
        self.tblPrograms.horizontalHeader().setVisible(True)
        self.tblPrograms.verticalHeader().setVisible(False)
        headerLabels = [
            "Id", "Program", "Station", "Freq", "Mode", "BW", "Modem", "Cntr",
            "Day", "UTC Time", "Active", "Notes"
        ]
        self.tblPrograms.setColumnCount(len(headerLabels))
        self.tblPrograms.setHorizontalHeaderLabels(headerLabels)
        #The following column widths follow headerLabels coded above. Id column is set to zero to hide it.
        self.tblPrograms.setColumnWidth(0, 0)
        self.tblPrograms.setColumnWidth(1, 200)
        self.tblPrograms.setColumnWidth(2, 100)
        self.tblPrograms.setColumnWidth(3, 100)
        self.tblPrograms.setColumnWidth(4, 100)
        self.tblPrograms.setColumnWidth(5, 100)
        self.tblPrograms.setColumnWidth(6, 100)
        self.tblPrograms.setColumnWidth(7, 100)
        self.tblPrograms.setColumnWidth(8, 100)
        self.tblPrograms.setColumnWidth(9, 100)
        self.tblPrograms.setColumnWidth(10, 100)
        self.tblPrograms.setColumnWidth(11, 200)

    def loadComboBoxes(self):
        values = []
        select_constants = [
            ac.RADIO_FREQUENCIES, ac.CENTER_DATA_FREQUENCIES, ac.MODES,
            ac.MODEMS, ac.RADIO_STATIONS, ac.BANDWIDTHS
        ]
        combo_boxes = [
            self.frmComboFreq, self.frmComboCenterFreq, self.frmComboMode,
            self.frmComboModem, self.frmComboStation, self.frmComboBandwidth
        ]

        for index, select_constant in enumerate(select_constants):
            result = self.db.select(retrieveSQL(select_constant))
            combo_boxes[index].addItems([x[0] for x in result])

        self.frmComboDOW.addItems(
            ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'))

    def loadProgramsTable(self):
        ''' Load the table from the database. '''
        self.tblPrograms.setRowCount(0)
        self.dbPending = ac.DBPENDING_SELECT
        result = self.handleDatabaseRequest()
        self.tblPrograms.setRowCount(len(result))
        self.tblPrograms.setSortingEnabled(ac.DISABLE)
        for record in enumerate(result):
            for item in enumerate(record[1]):
                self.tblPrograms.setItem(int(record[0]), int(item[0]),
                                         QTableWidgetItem(str(item[1])))

    def setupMethods(self):
        '''Uses the button group to connect a button via its constant to a method director.'''
        self.buttonGroup.buttonClicked[int].connect(self.methodDirector)
        self.tblPrograms.clicked.connect(self.tblProgramsClicked)
        self.frmComboFreq.currentIndexChanged[str].connect(self.handleComboBox)

    def handleComboBox(self):
        self.frmComboFreq.currentData()

    def methodDirector(self, buttonid):
        '''Identifies a button and its related method using a constant and the button id.'''
        if buttonid == ac.PUSHBUTTON_QUIT:
            self.close()
        elif buttonid == ac.PUSHBUTTON_ADD:
            self.addButtonAction()
        elif buttonid == ac.PUSHBUTTON_CANCEL:
            self.cancelButtonAction()
        elif buttonid == ac.PUSHBUTTON_SAVE:
            self.saveButtonAction()
        elif buttonid == ac.PUSHBUTTON_EDIT:
            self.editButtonAction()
        elif buttonid == ac.PUSHBUTTON_DELETE:
            self.deleteButtonAction()

    def tblProgramsClicked(self):
        self.clearFields()
        '''Note the explicit creation of a tuple in the next line. This is to keep Sqlite happy.'''
        self.primary_key = (self.tblPrograms.item(
            self.tblPrograms.currentRow(), 0).text(), )
        self.setButtonStatus(ac.APP_LISTCHANGE)

    def deleteButtonAction(self):
        ''' Set the database pending value, handle the database action, and set button status. '''
        self.dbPending = ac.DBPENDING_DELETE
        self.handleDatabaseRequest()
        self.setButtonStatus(status=ac.APP_DELETE)

    def editButtonAction(self):
        ''' Set the database pending value, handle the database action, and set button status. '''
        self.dbPending = ac.DBPENDING_UPDATE
        self.setFieldStatus(status=ac.ENABLE)
        self.setButtonStatus(ac.APP_EDIT)
        tabledata = self.extractTableData()
        self.populateFields(tabledata)
        self.frmFieldProgram.setFocus()

    def populateFields(self, tabledata):
        self.primary_key = tabledata[0]
        tabledata = tabledata[1:]
        fieldlist = [
            self.frmFieldProgram, self.frmComboStation, self.frmComboFreq,
            self.frmComboMode, self.frmComboBandwidth, self.frmComboModem,
            self.frmComboCenterFreq, self.frmComboDOW, self.frmUTCTimeEdit,
            self.frmCheckBoxActive, self.frmTextEditNotes
        ]

        for list_index, item in enumerate(fieldlist):
            if isinstance(item, QCheckBox):
                if tabledata[list_index] == "Yes":
                    item.setChecked(True)
                else:
                    item.setChecked(False)
            elif isinstance(item, QComboBox):
                item.setCurrentIndex(item.findText(tabledata[list_index]))
            elif isinstance(item, QTimeEdit):
                self.frmUTCTimeEdit.setTime(
                    QTime.fromString(tabledata[list_index], 'hh:mm'))
            elif isinstance(item, QLineEdit) or isinstance(item, QTextEdit):
                item.setText(tabledata[list_index])

    def extractTableData(self):
        '''This method primarily gathers data from the Program table widget and places the data into a list which is returned.'''
        tabledata = []
        for column_number in range(0, self.tblPrograms.columnCount()):
            tabledata.append(
                self.tblPrograms.item(self.tblPrograms.currentRow(),
                                      column_number).text())
        return tabledata

    def saveButtonAction(self):
        ''' Set the database pending value, handle the database action, and set button status. '''
        self.setButtonStatus(status=ac.APP_SAVE)
        self.handleDatabaseRequest()
        self.clearFields()

    def handleDatabaseRequest(self):
        result = None
        field_data = None
        if self.dbPending == ac.DBPENDING_SELECT:
            result = self.db.select(retrieveSQL(ac.SQL_SELECT_ALL))
        elif self.dbPending == ac.DBPENDING_INSERT:
            field_data = self.extractFieldData()
            self.db.insertData(retrieveSQL(ac.SQL_INSERT), (field_data, ))
            self.loadProgramsTable()
        elif self.dbPending == ac.DBPENDING_DELETE:
            self.db.deleteRow(retrieveSQL(ac.SQL_DELETE), (self.primary_key))
            self.loadProgramsTable()
        elif self.dbPending == ac.DBPENDING_UPDATE:
            field_data = self.extractFieldData()
            field_data.append(self.primary_key)
            self.db.updateData(retrieveSQL(ac.SQL_UPDATE), field_data)
            self.loadProgramsTable()
        return result

    def extractFieldData(self):
        fielddata = []
        fieldList = [
            self.frmFieldProgram, self.frmComboStation, self.frmComboFreq,
            self.frmComboMode, self.frmComboBandwidth, self.frmComboModem,
            self.frmComboCenterFreq, self.frmComboDOW, self.frmUTCTimeEdit,
            self.frmCheckBoxActive, self.frmTextEditNotes
        ]
        for item in fieldList:
            item_text = ''
            if isinstance(item, QCheckBox):
                item_text = "Yes" if item.isChecked() else "No"
            elif isinstance(item, QTextEdit):
                item_text = item.toPlainText()
            elif isinstance(item, QComboBox):
                item_text = item.currentText()
            elif isinstance(item, QLineEdit):
                item_text = item.displayText()
            elif isinstance(item, QTimeEdit):
                item_text = item.time().toString('hh:mm')
            fielddata.append(item_text)
        return fielddata

    def cancelButtonAction(self):
        '''Perform actions related to the cancel button click.'''
        self.dbPending = ac.DBPENDING_NONE
        self.clearFields()
        self.setFieldStatus(ac.DISABLE)
        self.setButtonStatus(ac.APP_CANCEL)

    def addButtonAction(self):
        '''Perform actions related to the add button click.'''
        self.dbPending = ac.DBPENDING_INSERT
        self.clearFields()
        self.setFieldStatus(status=ac.ENABLE)
        self.setButtonStatus(status=ac.APP_ADD)
        self.frmFieldProgram.setFocus()

    def setButtonStatus(self, status=0):
        '''Set buttons on or off depending on the state of the app.'''
        # Set default status of all buttons which all but the quit are disabled.
        self.btnAdd.setEnabled(False)
        self.btnEdit.setEnabled(False)
        self.btnCancel.setEnabled(False)
        self.btnSave.setEnabled(False)
        self.btnDelete.setEnabled(False)
        self.btnQuit.setEnabled(True)

        # Now, using the status word, set buttons on or off.
        if status in (ac.APP_STARTUP, ac.APP_SAVE):
            self.btnAdd.setEnabled(True)
        elif status == ac.APP_LISTCHANGE:
            self.btnAdd.setEnabled(True)
            self.btnEdit.setEnabled(True)
            self.btnDelete.setEnabled(True)
        elif status == ac.APP_ADD:
            self.btnAdd.setEnabled(False)
            self.btnCancel.setEnabled(True)
            self.btnSave.setEnabled(True)
        elif status == ac.APP_CANCEL:
            self.btnAdd.setEnabled(True)
        elif status == ac.APP_DELETE:
            self.btnAdd.setEnabled(True)
        elif status == ac.APP_EDIT:
            self.btnCancel.setEnabled(True)
            self.btnSave.setEnabled(True)

    def setFieldStatus(self, status):
        '''Turns data fields on or off.'''
        self.frmFieldProgram.setEnabled(status)
        self.frmCheckBoxActive.setEnabled(status)
        self.frmTextEditNotes.setEnabled(status)
        self.frmComboFreq.setEnabled(status)
        self.frmComboMode.setEnabled(status)
        self.frmComboCenterFreq.setEnabled(status)
        self.frmComboModem.setEnabled(status)
        self.frmComboStation.setEnabled(status)
        self.frmUTCTimeEdit.setEnabled(status)
        self.frmComboBandwidth.setEnabled(status)
        self.frmComboDOW.setEnabled(status)

    def clearFields(self):
        '''Clear all fields of any information.'''
        self.frmFieldProgram.setText("")
        self.frmCheckBoxActive.setChecked(True)
        self.frmTextEditNotes.setText("")

    def addPushButtons(self, buttonGroup):
        self.btnAdd = QPushButton("&Add", self.centralwidget)
        self.buttonLayout.addWidget(self.btnAdd)
        buttonGroup.addButton(self.btnAdd, ac.PUSHBUTTON_ADD)
        self.btnEdit = QPushButton("&Edit", self.centralwidget)
        self.buttonLayout.addWidget(self.btnEdit)
        buttonGroup.addButton(self.btnEdit, ac.PUSHBUTTON_EDIT)
        self.btnCancel = QPushButton("&Cancel", self.centralwidget)
        self.buttonLayout.addWidget(self.btnCancel)
        buttonGroup.addButton(self.btnCancel, ac.PUSHBUTTON_CANCEL)
        self.btnSave = QPushButton("&Save", self.centralwidget)
        self.buttonLayout.addWidget(self.btnSave)
        buttonGroup.addButton(self.btnSave, ac.PUSHBUTTON_SAVE)
        self.btnDelete = QPushButton("&Delete", self.centralwidget)
        self.buttonLayout.addWidget(self.btnDelete)
        buttonGroup.addButton(self.btnDelete, ac.PUSHBUTTON_DELETE)
        self.btnQuit = QPushButton("&Quit", self.centralwidget)
        self.buttonLayout.addWidget(self.btnQuit)
        buttonGroup.addButton(self.btnQuit, ac.PUSHBUTTON_QUIT)

    def createFormFields(self):
        self.frmFieldProgram = QLineEdit(self.centralwidget)
        self.frmLayout.addRow("Program:", self.frmFieldProgram)

        self.frmComboStation = QComboBox(self.centralwidget)
        self.frmLayout.addRow("Station:", self.frmComboStation)
        self.frmComboFreq = QComboBox(self.centralwidget)
        self.frmLayout.addRow("Station Frequency:", self.frmComboFreq)
        self.frmComboMode = QComboBox(self.centralwidget)
        self.frmLayout.addRow("Modulation Mode:", self.frmComboMode)
        self.frmComboBandwidth = QComboBox(self.centralwidget)
        self.frmLayout.addRow("Bandwidth:", self.frmComboBandwidth)
        self.frmComboModem = QComboBox(self.centralwidget)
        self.frmLayout.addRow("Modem:", self.frmComboModem)
        self.frmComboCenterFreq = QComboBox(self.centralwidget)
        self.frmLayout.addRow("Center Frequency:", self.frmComboCenterFreq)
        #Day of Week = DOW
        self.frmComboDOW = QComboBox(self.centralwidget)
        self.frmLayout.addRow("UTC Day of Week:", self.frmComboDOW)

        self.frmUTCTimeEdit = QTimeEdit(self.centralwidget)
        self.frmLayout.addRow("UTC Time:", self.frmUTCTimeEdit)
        self.frmUTCTimeEdit.setDisplayFormat('hh:mm')
        utctime = QTime.fromString('00:00', 'hh:mm')
        self.frmUTCTimeEdit.setTime(utctime)

        self.frmCheckBoxActive = QCheckBox(self.centralwidget)
        self.frmCheckBoxActive.setChecked(True)
        self.frmLayout.addRow("Active:", self.frmCheckBoxActive)
        self.frmTextEditNotes = QTextEdit(self.centralwidget)
        self.frmLayout.addRow("Notes:", self.frmTextEditNotes)
Ejemplo n.º 20
0
class MainWindow(QMainWindow):
    """The main window of the application."""
    def __init__(self):
        """Construct a MainWindow."""
        super().__init__()
        self.logger = logging.getLogger(__name__)
        self.day_actions = dict()
        self.task_model = None
        self.task_view = None
        self.result_view = None
        self.result_model = SummaryModel(self)
        self.week_edit = None
        self.week_wrapper = None
        self.year_edit = None
        self.week_time_edit = None
        self.man_day_edit = None
        self.current_day_label = None
        self.week_time_lcd = None
        self.remaining_week_time_lcd = None
        self.day_time_lcd = None
        self.catch_up_lcd = None
        self.total_annual_lcd = None

    def closeEvent(self, event):
        """When application is about to close."""
        close_database()

    def __set_window_size(self):
        """Set the window size."""
        w = 700
        h = 400
        self.setMinimumWidth(w)
        self.setMinimumHeight(h)
        self.showMaximized()

    @staticmethod
    def __disable_headers_click(table):
        """Disable click on table headers."""
        table.horizontalHeader().setSectionsClickable(False)
        table.setCornerButtonEnabled(False)
        table.verticalHeader().setSectionsClickable(False)

    @staticmethod
    def __init_current_cell_color(table):
        """Initialize current cell color."""
        palette = table.palette()
        current_cell_color = SettingModel.current_cell_color()
        current_text_color = contrast_color(current_cell_color.name())
        palette.setBrush(QPalette.Highlight,
                         QBrush(QColor(current_cell_color)))
        palette.setBrush(QPalette.HighlightedText,
                         QBrush(QColor(current_text_color)))
        table.setPalette(palette)

    def __set_task_delegate(self, table):
        """Set a task delegate on a table."""
        delegate = TaskNameDelegate(table)
        table.setItemDelegateForColumn(TaskColumn.Task.value, delegate)

    def __resize_task_headers(self):
        """Resize task headers."""
        self.task_view.hideColumn(TaskColumn.Id.value)
        self.task_view.horizontalHeader().setSectionResizeMode(
            TaskColumn.Task.value, QHeaderView.Stretch)
        self.task_view.horizontalHeader().setSectionResizeMode(
            TaskColumn.Start_Time.value, QHeaderView.Fixed)
        self.task_view.horizontalHeader().resizeSection(
            TaskColumn.Start_Time.value, 70)

        self.task_view.horizontalHeader().setSectionResizeMode(
            TaskColumn.End_Time.value, QHeaderView.Fixed)
        self.task_view.horizontalHeader().resizeSection(
            TaskColumn.End_Time.value, 70)

    def __resize_result_headers(self):
        """Resize result headers."""
        self.result_view.horizontalHeader().setSectionResizeMode(
            ResultColumn.Task.value, QHeaderView.Stretch)
        self.result_view.horizontalHeader().setSectionResizeMode(
            ResultColumn.Time.value, QHeaderView.Fixed)
        self.result_view.horizontalHeader().setSectionResizeMode(
            ResultColumn.Man_Day.value, QHeaderView.Fixed)
        self.result_view.horizontalHeader().resizeSection(
            ResultColumn.Time.value, 70)
        self.result_view.horizontalHeader().resizeSection(
            ResultColumn.Man_Day.value, 70)

    def __init_layout(self):
        """Initialize the central widget layout."""
        main_widget = QWidget(self)
        self.setCentralWidget(main_widget)

        main_layout = QGridLayout()
        main_layout.setRowStretch(0, 1)
        main_layout.setRowStretch(1, 1)
        main_layout.setRowStretch(2, 20)
        main_layout.setRowStretch(3, 1)
        main_layout.setColumnStretch(0, 1)
        main_layout.setColumnStretch(1, 1)
        main_layout.setSpacing(0)
        main_layout.setContentsMargins(0, 0, 0, 0)

        header_layout = FlowLayout()

        self.year_edit = QSpinBox(self)
        self.year_edit.setMinimum(2010)
        self.year_edit.setMaximum(2050)
        self.year_edit.setValue(datetime.datetime.now().year)

        year_widget = QWidget(self)
        year_layout = QHBoxLayout()
        year_widget.setLayout(year_layout)
        year_label = QLabel(self.tr('Year'), self)
        year_layout.addWidget(year_label)
        year_layout.addWidget(self.year_edit)

        self.week_edit = QSpinBox(self)
        self.week_edit.setMinimum(1)
        self.__update_week_edit(self.year_edit.value())
        self.week_edit.setValue(datetime.date.today().isocalendar()[1])

        week_widget = QWidget(self)
        week_layout = QHBoxLayout()
        week_widget.setLayout(week_layout)
        week_label = QLabel(self.tr('Week'), self)
        week_layout.addWidget(week_label)
        week_layout.addWidget(self.week_edit)

        self.week_edit.valueChanged.connect(self.__week_changed)
        self.year_edit.valueChanged.connect(self.__year_changed)

        self.week_time_edit = DurationEdit(parent=self, hour_length=2)

        week_time_widget = QWidget(self)
        week_time_layout = QHBoxLayout()
        week_time_widget.setLayout(week_time_layout)
        week_time_label = QLabel(self.tr('Week time'), self)
        week_time_layout.addWidget(week_time_label)
        week_time_layout.addWidget(self.week_time_edit)

        self.week_time_edit.valueChanged.connect(self.__week_time_changed)

        self.man_day_edit = QTimeEdit(SettingModel.default_man_day_time(),
                                      self)

        man_day_widget = QWidget(self)
        man_day_layout = QHBoxLayout()
        man_day_widget.setLayout(man_day_layout)
        man_day_label = QLabel(self.tr('Man day time'), self)
        man_day_layout.addWidget(man_day_label)
        man_day_layout.addWidget(self.man_day_edit)

        self.man_day_edit.timeChanged.connect(self.__update_week_summary)

        header_layout.addWidget(year_widget)
        header_layout.addWidget(week_widget)
        header_layout.addWidget(week_time_widget)
        header_layout.addWidget(man_day_widget)

        main_layout.addLayout(header_layout, 0, 0, 1, 2)

        self.current_day_label = self.__build_title_label('')
        summary_label = self.__build_title_label(self.tr('Week summary'))

        main_layout.addWidget(self.current_day_label, 1, 0)
        main_layout.addWidget(summary_label, 1, 1)

        main_layout.addWidget(self.task_view, 2, 0)
        main_layout.addWidget(self.result_view, 2, 1)

        week_time_label = QLabel(self.tr('Week time'), self)
        self.week_time_lcd = self.__build_lcd_number_widget()

        remaining_week_label = QLabel(self.tr('Remaining week time'), self)
        self.remaining_week_time_lcd = self.__build_lcd_number_widget()

        day_label = QLabel(self.tr('Day time'), self)
        self.day_time_lcd = self.__build_lcd_number_widget()
        self.__change_day_color(QColor('#0000ff'))

        catch_up_label = QLabel(self.tr('Catch-up time'), self)
        self.catch_up_lcd = self.__build_lcd_number_widget()

        total_annual_label = QLabel(self.tr('Total annual time'), self)
        self.total_annual_lcd = self.__build_lcd_number_widget()

        footer_layout = QGridLayout()
        footer_layout.addWidget(day_label, 0, 0, Qt.AlignHCenter)
        footer_layout.addWidget(week_time_label, 0, 1, Qt.AlignHCenter)
        footer_layout.addWidget(remaining_week_label, 0, 2, Qt.AlignCenter)
        footer_layout.addWidget(catch_up_label, 0, 3, Qt.AlignCenter)
        footer_layout.addWidget(total_annual_label, 0, 4, Qt.AlignCenter)
        footer_layout.addWidget(self.day_time_lcd, 1, 0)
        footer_layout.addWidget(self.week_time_lcd, 1, 1)
        footer_layout.addWidget(self.remaining_week_time_lcd, 1, 2)
        footer_layout.addWidget(self.catch_up_lcd, 1, 3)
        footer_layout.addWidget(self.total_annual_lcd, 1, 4)

        main_layout.addLayout(footer_layout, 3, 0, 1, 2)

        main_widget.setLayout(main_layout)

    def __set_day_title(self, title):
        """Set the day title on top of the table view."""
        self.logger.info('Set day title: %s', title)
        self.current_day_label.setText(str(title))

    def __change_week_color(self, color):
        """Change the lcd week color."""
        self.__change_lcd_number_color(self.week_time_lcd, color)
        self.__change_lcd_number_color(self.remaining_week_time_lcd, color)

    def __change_day_color(self, color):
        """Change the lcd day color."""
        self.__change_lcd_number_color(self.day_time_lcd, color)

    def __change_catch_up_color(self, color):
        """Change the lcd catch-up color."""
        self.__change_lcd_number_color(self.catch_up_lcd, color)

    @staticmethod
    def __change_lcd_number_color(lcd_widget, color):
        """Change a given lcd number color with a given color."""
        if isinstance(color, QColor) and isinstance(lcd_widget, QLCDNumber):
            palette = QPalette()
            palette.setColor(QPalette.WindowText, color)
            lcd_widget.setPalette(palette)

    def init_ui(self):
        """Initialize the user interface."""
        self.setWindowTitle(self.tr('Task counter'))
        self.setWindowIcon(QIcon(':/tasks.png'))
        self.statusBar()

        self.__set_window_size()
        self.__create_toolbars_and_menus()

        self.task_view = QTableView(self)
        self.__init_current_cell_color(self.task_view)
        self.__disable_headers_click(self.task_view)
        self.task_view.setSelectionMode(QTableView.SingleSelection)
        self.__set_task_delegate(self.task_view)

        self.result_view = QTableView(self)
        self.__init_current_cell_color(self.result_view)
        self.__disable_headers_click(self.result_view)
        self.result_view.setAlternatingRowColors(True)
        self.result_view.setModel(self.result_model)
        self.result_view.setSelectionBehavior(QTableView.SelectRows)
        self.__init_layout()

        self.__validate_week_and_year()

        self.show()

    def __create_toolbars_and_menus(self):
        """Create the toolbars and menus."""
        toolbar_weeks = QToolBar(self)
        self.addToolBar(Qt.TopToolBarArea, toolbar_weeks)
        toolbar_application = QToolBar(self)
        self.addToolBar(Qt.TopToolBarArea, toolbar_application)
        self.addToolBarBreak()
        toolbar_days = QToolBar(self)
        self.addToolBar(Qt.TopToolBarArea, toolbar_days)

        days_action_group = QActionGroup(self)
        for counter, day in enumerate(WeekDay, start=1):

            if day == WeekDay.Monday:
                tr_name = self.tr('Monday')
            elif day == WeekDay.Tuesday:
                tr_name = self.tr('Tuesday')
            elif day == WeekDay.Wednesday:
                tr_name = self.tr('Wednesday')
            elif day == WeekDay.Thursday:
                tr_name = self.tr('Thursday')
            elif day == WeekDay.Friday:
                tr_name = self.tr('Friday')
            elif day == WeekDay.Saturday:
                tr_name = self.tr('Saturday')
            elif day == WeekDay.Sunday:
                tr_name = self.tr('Sunday')

            action = QAction(QIcon(':/' + day.name.lower() + '.png'), tr_name,
                             self)
            action.setObjectName(day.name)
            action.setShortcut('Alt+' + str(counter))
            action.setCheckable(True)
            action.setStatusTip(self.tr('Go to {day}').format(day=tr_name))
            action.triggered.connect(self.__change_current_day)
            days_action_group.addAction(action)
            self.day_actions[day] = action
            toolbar_days.addAction(action)

        previous_act = QAction(QIcon(':/previous.png'),
                               self.tr('Previous Week'), self)
        previous_act.setShortcut('Ctrl+P')
        previous_act.triggered.connect(self.__previous_week)
        previous_act.setStatusTip(self.tr('Go to Previous Week'))

        next_act = QAction(QIcon(':/next.png'), self.tr('Next Week'), self)
        next_act.setShortcut('Ctrl+N')
        next_act.triggered.connect(self.__next_week)
        next_act.setStatusTip(self.tr('Go to Next Week'))

        today_act = QAction(QIcon(':/today.png'), self.tr('Today'), self)
        today_act.setShortcut('Ctrl+T')
        today_act.triggered.connect(self.__today)
        today_act.setStatusTip(self.tr('Go to today'))

        about_act = QAction(QIcon(':/info.png'), self.tr('About'), self)
        about_act.triggered.connect(self.__about)
        about_act.setStatusTip(self.tr('About this application'))

        about_qt_act = QAction(self.tr('About Qt'), self)
        about_qt_act.triggered.connect(qApp.aboutQt)
        about_qt_act.setStatusTip(self.tr('About Qt'))

        settings_act = QAction(QIcon(':/settings.png'), self.tr('Preferences'),
                               self)
        settings_act.triggered.connect(self.__edit_preferences)
        settings_act.setStatusTip(self.tr('Edit preferences'))

        exit_act = QAction(QIcon(':/exit.png'), self.tr('&Quit'), self)
        exit_act.setShortcut('Ctrl+Q')
        exit_act.setStatusTip(self.tr('Quit application'))
        exit_act.triggered.connect(self.close)

        export_act = QAction(QIcon(':/export.png'), self.tr('Export'), self)
        export_act.setShortcut('Ctrl+E')
        export_act.setStatusTip(self.tr('Export week summary as html table'))
        export_act.triggered.connect(self.__export)

        toolbar_weeks.addAction(today_act)
        toolbar_weeks.addAction(previous_act)
        toolbar_weeks.addAction(next_act)
        toolbar_weeks.addAction(export_act)

        toolbar_application.addAction(exit_act)
        toolbar_application.addAction(settings_act)
        toolbar_application.addAction(about_act)

        menu_bar = self.menuBar()
        menu_bar.setNativeMenuBar(True)

        app_menu = menu_bar.addMenu(self.tr('Application'))
        app_menu.addAction(about_act)
        app_menu.addAction(about_qt_act)
        app_menu.addAction(settings_act)
        app_menu.addAction(exit_act)

        weeks_menu = menu_bar.addMenu(self.tr('Weeks'))
        weeks_menu.addAction(today_act)
        weeks_menu.addAction(previous_act)
        weeks_menu.addAction(next_act)
        weeks_menu.addAction(export_act)

        days_menu = menu_bar.addMenu(self.tr('Days'))
        for action in days_action_group.actions():
            days_menu.addAction(action)

    def __validate_week_and_year(self):
        """Validate the week and the year and update a WeekModel."""
        self.week_wrapper = WeekModel(self.year_edit.value(),
                                      self.week_edit.value(), self)
        self.logger.debug('Week wrapper: %s', self.week_wrapper)

        self.week_time_edit.blockSignals(True)
        self.week_time_edit.minutes = self.week_wrapper.minutes_to_work
        self.week_time_edit.blockSignals(False)

        if (self.year_edit.value() == datetime.datetime.now().year
                and self.week_edit.value()
                == datetime.date.today().isocalendar()[1]):
            self.day_actions[weekday_from_date(
                datetime.date.today())].activate(QAction.Trigger)
        else:
            self.day_actions[WeekDay.Monday].activate(QAction.Trigger)

    @pyqtSlot()
    def __previous_week(self):
        """Go to the previous week."""
        current_week = int(self.week_edit.value())
        if current_week - 1 == 0:
            current_year = int(self.year_edit.value())
            weeks_of_previous_year = weeks_for_year(current_year - 1)
            self.week_edit.setValue(weeks_of_previous_year)
            self.year_edit.setValue(current_year - 1)
        else:
            self.week_edit.setValue(current_week - 1)

    @pyqtSlot()
    def __next_week(self):
        """Go to the next week."""
        current_week = int(self.week_edit.value())
        current_year = int(self.year_edit.value())
        weeks_of_current_year = weeks_for_year(current_year)
        if current_week + 1 > weeks_of_current_year:
            self.week_edit.setValue(1)
            self.year_edit.setValue(current_year + 1)
        else:
            self.week_edit.setValue(current_week + 1)

    @pyqtSlot()
    def __today(self):
        """Go to the current day, today."""
        self.year_edit.setValue(datetime.datetime.now().year)
        self.__update_week_edit(self.year_edit.value())
        self.week_edit.setValue(datetime.date.today().isocalendar()[1])
        self.__validate_week_and_year()

    @pyqtSlot()
    def __about(self):
        """Open the about page."""
        about = AboutDialog(self)
        about.exec_()

    @pyqtSlot()
    def __export(self):
        """Export data."""
        self.__export_cells_as_table()

    @pyqtSlot()
    def __edit_preferences(self):
        """Edit preferences."""
        settings = SettingDialog(self)
        settings.exec_()

        self.__update_settings()

    @pyqtSlot()
    def __change_current_day(self):
        """Change the current day for edition."""
        sender = self.sender()
        if self.week_wrapper:
            if self.task_model:
                self.task_model.dataChanged.disconnect()
            self.task_model = self.week_wrapper[WeekDay[sender.objectName()]]
            self.__update_time()
            self.task_model.dataChanged.connect(self.__update_time)

            # set readable date in title
            self.__set_day_title(self.task_model.date.strftime('%A %d %B %Y'))
            self.task_view.setModel(self.task_model)

            self.__resize_task_headers()

            # the table takes the focus
            self.task_view.setFocus(Qt.OtherFocusReason)

            # the last task cell is selected
            flags = QItemSelectionModel.ClearAndSelect
            index = self.task_model.last_task_cell_index
            self.task_view.selectionModel().setCurrentIndex(index, flags)

    @pyqtSlot(int)
    def __year_changed(self, year):
        """Change the current year, event."""
        self.__update_week_edit(year)
        self.__validate_week_and_year()

    @pyqtSlot()
    def __week_changed(self):
        """Change the current week, event."""
        self.__validate_week_and_year()

    def __update_week_edit(self, year):
        """Update the week edit max value for a given year."""
        weeks = weeks_for_year(int(year))
        self.week_edit.setMaximum(weeks)

    @pyqtSlot()
    def __update_time(self):
        """Update time counters."""
        self.__update_day_time_counter()
        self.__update_week_time_counter()
        self.__update_catch_up_time_counter()
        self.__update_total_annual_time_counter()
        self.__update_week_summary()

    def __update_day_time_counter(self):
        """Update the day time counter."""
        self.day_time_lcd.display(
            minutes_to_time_str(self.task_model.minutes_of_day))

    def __update_week_time_counter(self):
        """Update the week time counters."""
        self.week_time_lcd.display(
            minutes_to_time_str(self.week_wrapper.minutes_of_week))
        self.remaining_week_time_lcd.display(
            minutes_to_time_str(
                max(
                    0, self.week_wrapper.minutes_to_work -
                    self.week_wrapper.minutes_of_week)))

        self.__update_week_counter_color()

    def __update_catch_up_time_counter(self):
        """Update the catch-up time counter."""
        to_work = self.week_wrapper.total_time_to_work
        worked = self.week_wrapper.total_time_worked

        catch_up_time = worked - to_work
        abs_time = abs(catch_up_time)
        time_str = minutes_to_time_str(abs_time)

        if catch_up_time >= 0:
            self.__change_catch_up_color(SettingModel.valid_color())
            self.catch_up_lcd.setToolTip('+' + time_str)
        else:
            self.__change_catch_up_color(SettingModel.invalid_color())
            self.catch_up_lcd.setToolTip('-' + time_str)

        if abs_time >= 6000:
            self.catch_up_lcd.display(abs_time // 60)
        else:
            self.catch_up_lcd.display(time_str)

    def __update_total_annual_time_counter(self):
        """Update the total annual time counter."""
        total = get_total_annual_worked_hours(self.year_edit.value())
        self.total_annual_lcd.display(total)

    def __build_lcd_number_widget(self):
        """Build a LCD Number widget."""
        lcdnumber = QLCDNumber(self)
        lcdnumber.setSegmentStyle(QLCDNumber.Filled)
        lcdnumber.setFixedHeight(40)
        lcdnumber.setFrameStyle(QFrame.NoFrame)
        return lcdnumber

    @pyqtSlot()
    def __week_time_changed(self):
        """Change the work time of the week, event."""
        self.__update_week_time()

    def __update_week_time(self):
        """Update the work time of the week."""
        minutes_time = self.week_time_edit.minutes
        if self.week_wrapper:
            self.week_wrapper.minutes_to_work = minutes_time
        self.__update_week_counter_color()
        self.__update_catch_up_time_counter()
        self.__update_week_time_counter()

    def __update_week_counter_color(self):
        """Update the week counter color depending on the time percentage."""
        percent = 1
        if self.week_wrapper.minutes_to_work:
            # denominator cannot be zero
            percent = (self.week_wrapper.minutes_of_week /
                       self.week_wrapper.minutes_to_work)

        color = color_between(SettingModel.invalid_color().name(),
                              SettingModel.valid_color().name(), percent)
        self.__change_week_color(QColor(color))

    def __build_title_label(self, title):
        """Build a label widget with a given title."""
        label = QLabel(title, self)
        label.setAlignment(Qt.AlignCenter)
        label.setMargin(5)
        font = label.font()
        font.setBold(True)
        font.setPointSize(16)
        label.setFont(font)
        return label

    def __update_week_summary(self):
        """Update the week summary."""
        if self.week_wrapper:

            man_day_time = self.man_day_edit.time()
            man_day_minutes = man_day_time.hour() * 60 + man_day_time.minute()

            tasks = self.week_wrapper.week_summary(man_day_minutes)
            self.result_model.tasks = tasks
            self.__resize_result_headers()

    def __export_cells_as_table(self):
        """Copy tasks and time cells as html table."""
        model = self.result_view.model()

        table_text = '<html><head>'
        table_text += '<meta http-equiv="content-type" '
        table_text += 'content="text/html; charset=utf-8">'
        table_text += '</head><body>'
        table_text += '<table cellpadding="0" cellspacing="0" border="0" '
        table_text += 'style="width:100%;">'

        table_text += '<tr>'
        table_text += ('<th style="border:2px solid black;'
                       'margin:0;padding:2px;text-align:center;'
                       'background-color:#ddd;">' + self.tr('Task') + '</th>')
        table_text += ('<th style="border:2px solid black;'
                       'margin:0;padding:2px;text-align:center;'
                       'background-color:#ddd;width:20%;">' + self.tr('Time') +
                       '</th>')
        table_text += '</tr>'

        rows = model.rowCount()
        columns_to_export = (ResultColumn.Task.value, ResultColumn.Time.value)

        for i in range(0, rows):
            table_text += '<tr>'
            for j in columns_to_export:
                content = model.data(model.index(i, j), Qt.DisplayRole)
                if j == 0:
                    table_text += ('<td style="border:2px solid black;'
                                   'margin:0;padding:2px;text-align:left;">'
                                   '{}</td>').format(content)
                else:
                    table_text += ('<td style="border:2px solid black;'
                                   'margin:0;padding:2px;text-align:center;'
                                   'width:20%;">{}</td>').format(content)
            table_text += '</tr>'

        table_text += '</tr></table></body></html>'

        clipboard = QApplication.clipboard()
        mime_data = QMimeData()
        bytes_array = QByteArray()
        bytes_array.append(table_text)
        mime_data.setData('text/html', bytes_array)

        clipboard.setMimeData(mime_data, QClipboard.Clipboard)

    def __update_settings(self):
        """Update user interface with new settings."""
        self.__init_current_cell_color(self.task_view)
        self.__init_current_cell_color(self.result_view)
        self.__update_time()
        self.man_day_edit.setTime(SettingModel.default_man_day_time())
Ejemplo n.º 21
0
class MediaCueSettings(SettingsPage):
    Name = 'Media-Cue'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.setLayout(QVBoxLayout(self))

        # Start time
        self.startGroup = QGroupBox(self)
        self.startGroup.setLayout(QHBoxLayout())
        self.layout().addWidget(self.startGroup)

        self.startEdit = QTimeEdit(self.startGroup)
        self.startEdit.setDisplayFormat('HH.mm.ss.zzz')
        self.startGroup.layout().addWidget(self.startEdit)

        self.startLabel = QLabel(self.startGroup)
        self.startLabel.setAlignment(Qt.AlignCenter)
        self.startGroup.layout().addWidget(self.startLabel)

        # Stop time
        self.stopGroup = QGroupBox(self)
        self.stopGroup.setLayout(QHBoxLayout())
        self.layout().addWidget(self.stopGroup)

        self.stopEdit = QTimeEdit(self.stopGroup)
        self.stopEdit.setDisplayFormat('HH.mm.ss.zzz')
        self.stopGroup.layout().addWidget(self.stopEdit)

        self.stopLabel = QLabel(self.stopGroup)
        self.stopLabel.setAlignment(Qt.AlignCenter)
        self.stopGroup.layout().addWidget(self.stopLabel)

        # Loop
        self.loopGroup = QGroupBox(self)
        self.loopGroup.setLayout(QHBoxLayout())
        self.layout().addWidget(self.loopGroup)

        self.spinLoop = QSpinBox(self.loopGroup)
        self.spinLoop.setRange(-1, 1000000)
        self.loopGroup.layout().addWidget(self.spinLoop)

        self.loopLabel = QLabel(self.loopGroup)
        self.loopLabel.setAlignment(Qt.AlignCenter)
        self.loopGroup.layout().addWidget(self.loopLabel)

        self.retranslateUi()

    def retranslateUi(self):
        self.startGroup.setTitle('Start time')
        self.stopLabel.setText('Stop position of the media')
        self.stopGroup.setTitle('Stop time')
        self.startLabel.setText('Start position of the media')
        self.loopGroup.setTitle('Loop')
        self.loopLabel.setText('Repetition after first play (-1 = infinite)')

    def get_settings(self):
        conf = {'_media_': {}}
        checkable = self.startGroup.isCheckable()

        if not (checkable and not self.startGroup.isChecked()):
            time = self.startEdit.time().msecsSinceStartOfDay()
            conf['_media_']['start_time'] = time
        if not (checkable and not self.stopGroup.isChecked()):
            time = self.stopEdit.time().msecsSinceStartOfDay()
            conf['_media_']['stop_time'] = time
        if not (checkable and not self.loopGroup.isChecked()):
            conf['_media_']['loop'] = self.spinLoop.value()

        return conf

    def enable_check(self, enable):
        self.startGroup.setCheckable(enable)
        self.startGroup.setChecked(False)

        self.stopGroup.setCheckable(enable)
        self.stopGroup.setChecked(False)

        self.loopGroup.setCheckable(enable)
        self.loopGroup.setChecked(False)

    def load_settings(self, settings):
        if '_media_' in settings:
            if 'loop' in settings['_media_']:
                self.spinLoop.setValue(settings['_media_']['loop'])
            if 'start_time' in settings['_media_']:
                t = self._to_qtime(settings['_media_']['start_time'])
                self.startEdit.setTime(t)
            if 'stop_time' in settings['_media_']:
                t = self._to_qtime(settings['_media_']['stop_time'])
                self.stopEdit.setTime(t)

            t = self._to_qtime(settings['_media_'].get('duration', 0))
            self.startEdit.setMaximumTime(t)
            self.stopEdit.setMaximumTime(t)

    def _to_qtime(self, m_seconds):
        return QTime.fromMSecsSinceStartOfDay(m_seconds)
class WindowEmployeeUpdate(QDialog):
    def __init__(self):
        super(WindowEmployeeUpdate, self).__init__()

        self.setWindowTitle("Update Employee Details")
        self.set_layout()

    def set_layout(self):
        #Set up basic Stuff here
        vbox = QVBoxLayout()
        group1 = QGroupBox("Employee Update")
        form1 = QFormLayout()
        group1.setLayout(form1)
        #Set Nane
        self.namelabel = QLabel("Name")
        self.nameLineEdit = QLineEdit("")
        self.nameLineEdit.setEnabled(False)
        form1.setWidget(0, QFormLayout.LabelRole, self.namelabel)
        form1.setWidget(0, QFormLayout.FieldRole, self.nameLineEdit)

        #Set Date Label
        self.datelabel = QLabel("Date Started")
        self.dateLineEdit = QDateEdit()
        self.dateLineEdit.setDate(QDate(2021, 1, 1))
        self.dateLineEdit.setCalendarPopup(True)
        form1.setWidget(1, QFormLayout.LabelRole, self.datelabel)
        form1.setWidget(1, QFormLayout.FieldRole, self.dateLineEdit)

        # set Time Started
        self.timestartlabel = QLabel("Time Started")
        self.updatestartLineEdit = QTimeEdit()
        # Set time constrain
        self.updatestartLineEdit.timeChanged.connect(self.connect_start_end)
        #Add to form Widget
        form1.setWidget(2, QFormLayout.LabelRole, self.timestartlabel)
        form1.setWidget(2, QFormLayout.FieldRole, self.updatestartLineEdit)
        # set Time Ended
        self.timeendedlabel = QLabel("Time Ended")
        self.updateendeLineEdit = QTimeEdit()
        # connect min time of endtime as starttime
        self.updateendeLineEdit.timeChanged.connect(
            self.connect_min_time)  #you can use lambda function to get 1 line
        # Add to form Widget
        form1.setWidget(3, QFormLayout.LabelRole, self.timeendedlabel)
        form1.setWidget(3, QFormLayout.FieldRole, self.updateendeLineEdit)

        ##ADD BUTTON
        self.updatebtn = QPushButton("Update Employee")
        self.updatebtn.clicked.connect(self.saved_messagebox)

        ## ADD ITEMS TO LAYOUT
        vbox.addWidget(group1)
        vbox.addWidget(self.updatebtn, 0, Qt.AlignHCenter)
        self.setLayout(vbox)

    def connect_start_end(self):
        self.updateendeLineEdit.setTime(self.updatestartLineEdit.time())

    def connect_min_time(self):
        self.updateendeLineEdit.setMinimumTime(self.updateendeLineEdit.time())

    def saved_messagebox(self):
        if self.nameLineEdit.text() != "":
            QMessageBox.information(self, "Information",
                                    "Details Updated Successfully")
            self.accept()
        elif self.nameLineEdit.text() == "":
            QMessageBox.warning(self, "Warning", "All Boxes Must be Filled")
Ejemplo n.º 23
0
class MainWidget(QWidget):

    def __init__(self):
        QWidget.__init__(self)

        # Set Time One Group
        self.time_one_calendar = QCalendarWidget()
        self.time_one_country_combobox = QComboBox()
        self.time_one_vbox = QVBoxLayout()
        self.time_one_groupbox = QGroupBox("Time One")
        self.time_one_bottom_hbox = QHBoxLayout()
        self.time_one_time_edit = QTimeEdit()
        self.time_one_default_button = QPushButton()
        self.time_one_default_button.setIcon(QIcon("%s/gnome-set-time.png" % icon_path))
        self.time_one_default_button.setMaximumSize(50, 50)
        self.time_one_bottom_hbox.addWidget(self.time_one_time_edit)
        self.time_one_bottom_hbox.addWidget(self.time_one_default_button)
        self.time_one_vbox.addWidget(self.time_one_country_combobox)
        self.time_one_vbox.addWidget(self.time_one_calendar)
        self.time_one_vbox.addLayout(self.time_one_bottom_hbox)
        self.time_one_groupbox.setLayout(self.time_one_vbox)

        # Set Time Two Group
        self.time_two_groupbox = QGroupBox("Time Two")
        self.time_two_calendar = QCalendarWidget()
        self.time_two_vbox = QVBoxLayout()
        self.time_two_country_combobox = QComboBox()
        self.time_two_bottom_hbox = QHBoxLayout()
        self.time_two_time_edit = QTimeEdit()
        self.time_two_default_button = QPushButton()
        self.time_two_default_button.setIcon(QIcon("%s/gnome-set-time.png" % icon_path))
        self.time_two_default_button.setMaximumSize(50, 50)
        self.time_two_bottom_hbox.addWidget(self.time_two_time_edit)
        self.time_two_bottom_hbox.addWidget(self.time_two_default_button)
        self.time_two_vbox.addWidget(self.time_two_country_combobox)
        self.time_two_vbox.addWidget(self.time_two_calendar)
        self.time_two_vbox.addLayout(self.time_two_bottom_hbox)
        self.time_two_groupbox.setLayout(self.time_two_vbox)

        # Set main layout
        self.main_layout = QHBoxLayout()
        self.main_layout.addWidget(self.time_one_groupbox)
        self.main_layout.addWidget(self.time_two_groupbox)
        self.setLayout(self.main_layout)

        # Wire-up your widgets!
        self.time_one_connect()
        self.time_two_connect()
        self.time_one_default_button.clicked.connect(self.set_local_time_one)
        self.time_two_default_button.clicked.connect(self.set_local_time_two)

        # Set the local time for time one
        self.set_local_country()
        self.set_local_time_one()

        # Finally, convert the second time based on the first
        self.convert_timeone_to_timetwo()

    def set_local_country(self):
        global_timezone_list = timezone_info.get_global_timezone_list()
        local_tz_index = global_timezone_list.index(str(self.get_local_timezone()))
        self.time_one_country_combobox.addItems(global_timezone_list)
        self.time_one_country_combobox.setCurrentIndex(local_tz_index)
        self.time_two_country_combobox.addItems(global_timezone_list)

    # To-do: Current solution works for Debian systems. Need to find repo solution that
    # allows for something like "from tzlocal import get_localzone"
    @staticmethod
    def get_local_timezone():
        timezone_file = '/etc/timezone'
        try:
            file = open(timezone_file, 'r')
            system_timezone = file.read().rstrip()
        except IOError:
            print("Unable to open %s") & timezone_file
            system_timezone = 'UTC'

        return system_timezone

    @staticmethod
    def get_local_times():
        local_hour = datetime.datetime.now().strftime("%H")
        local_minute = datetime.datetime.now().strftime("%M")
        local_current_time = QTime(int(local_hour), int(local_minute), 0, 0)

        return local_current_time

    def set_local_time_one(self):

        # Set time for one time
        local_current_time = self.get_local_times()
        self.time_one_time_edit.setTime(local_current_time)

        # Set date for one calendar
        self.time_one_calendar.setSelectedDate(QDate.currentDate())

        # Convert the second time based on the first
        self.convert_timeone_to_timetwo()

    def set_local_time_two(self):

        # Set time for one time
        local_current_time = self.get_local_times()
        self.time_two_time_edit.setTime(local_current_time)

        # Set date for one calendar
        self.time_two_calendar.setSelectedDate(QDate.currentDate())

        # Convert the first time based on the second
        self.convert_timetwo_to_timeone()

    def time_one_connect(self):
        self.time_one_country_combobox.activated.connect(self.convert_timeone_to_timetwo)
        self.time_one_calendar.clicked.connect(self.convert_timeone_to_timetwo)
        self.time_one_calendar.currentPageChanged.connect(self.convert_timeone_to_timetwo)
        self.time_one_time_edit.timeChanged.connect(self.convert_timeone_to_timetwo)

    def time_two_connect(self):
        self.time_two_country_combobox.activated.connect(self.convert_timeone_to_timetwo)
        self.time_two_calendar.clicked.connect(self.convert_timetwo_to_timeone)
        self.time_two_calendar.currentPageChanged.connect(self.convert_timetwo_to_timeone)
        self.time_two_time_edit.timeChanged.connect(self.convert_timetwo_to_timeone)

    def time_one_disconnect(self):
        self.time_one_calendar.clicked.disconnect()
        self.time_one_country_combobox.activated.disconnect()
        self.time_one_time_edit.timeChanged.disconnect()

    def time_two_disconnect(self):
        self.time_two_calendar.clicked.disconnect()
        self.time_two_country_combobox.activated.disconnect()
        self.time_two_time_edit.timeChanged.disconnect()

    def clear_combo_boxes(self):
        self.time_one_country_combobox.clear()
        self.time_two_country_combobox.clear()

    def __amend_country_region(self):
        """
        Used to add the regional header before converting if a region outside of global is used.
        """

        current_region = timezone_info.get_city_region(self.time_one_country_combobox.currentText())
        time_one_country = self.time_one_country_combobox.currentText()
        time_two_country = self.time_two_country_combobox.currentText()

        if '/' not in time_one_country:
            time_one_country = current_region+'/'+self.time_one_country_combobox.currentText()
            time_two_country = current_region+'/'+self.time_two_country_combobox.currentText()

        return time_one_country, time_two_country

    def convert_timeone_to_timetwo(self):
        # Disconnect time two widgets,so that they do not run
        self.time_two_disconnect()

        time_one_country, time_two_country = self.__amend_country_region()

        date_time_one = datetime.datetime(self.time_one_calendar.yearShown(),
                                          self.time_one_calendar.monthShown(),
                                          self.time_one_calendar.selectedDate().day(),
                                          self.time_one_time_edit.time().hour(),
                                          self.time_one_time_edit.time().minute())

        first_tz = timezone(time_one_country)
        second_tz = timezone(time_two_country)

        first_dt = first_tz.localize(date_time_one)
        second_dt = first_dt.astimezone(second_tz)

        new_date_two = QDate(second_dt.year, second_dt.month, second_dt.day)
        self.time_two_calendar.setSelectedDate(new_date_two)

        new_time_two = QTime(int(second_dt.hour), int(second_dt.minute))
        self.time_two_time_edit.setTime(new_time_two)

        # Reconnect time one widgets.
        self.time_two_connect()

    def convert_timetwo_to_timeone(self):

        # Disconnect time one widgets,so that they do not run
        self.time_one_disconnect()

        time_one_country, time_two_country = self.__amend_country_region()

        date_time_two = datetime.datetime(self.time_two_calendar.yearShown(),
                                          self.time_two_calendar.monthShown(),
                                          self.time_two_calendar.selectedDate().day(),
                                          self.time_two_time_edit.time().hour(),
                                          self.time_two_time_edit.time().minute())

        first_tz = timezone(time_one_country)
        second_tz = timezone(time_two_country)

        second_dt = second_tz.localize(date_time_two)
        first_dt = second_dt.astimezone(first_tz)

        new_date_one = QDate(first_dt.year, first_dt.month, first_dt.day)
        self.time_one_calendar.setSelectedDate(new_date_one)

        new_time_one = QTime(int(first_dt.hour), int(first_dt.minute))
        self.time_one_time_edit.setTime(new_time_one)

        # Reconnect time one widgets
        self.time_one_connect()
Ejemplo n.º 24
0
class FrameSelectWidget(QWidget):
    frameSelectionChanged = pyqtSignal(int, QTime)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setMaximumWidth(960)

        layout = QVBoxLayout()
        layout.setContentsMargins(4, 4, 4, 4)
        layout.setSpacing(4)
        self.setLayout(layout)

        self.imageView = QImageView(self)
        layout.addWidget(self.imageView)

        self.slider = Slider(self)
        self.slider.setOrientation(Qt.Horizontal)
        self.slider.valueChanged.connect(self.handleSliderChange)
        self.slider.setTickInterval(1)
        layout.addWidget(self.slider)

        hlayout = QHBoxLayout()
        layout.addLayout(hlayout)

        self.prevLabel = QLabel(self)
        self.currentIndex = QSpinBox(self)
        self.currentIndex.valueChanged.connect(self.handleIndexChange)
        self.currentTime = QTimeEdit(self)
        self.currentTime.setDisplayFormat("H:mm:ss.zzz")
        self.currentTime.timeChanged.connect(self.handleTimeChange)
        self.nextLabel = QLabel(self)

        hlayout.addWidget(self.prevLabel)
        hlayout.addStretch()
        hlayout.addWidget(QLabel("Frame index:", self))
        hlayout.addWidget(self.currentIndex)
        hlayout.addWidget(QLabel("Timestamp:", self))
        hlayout.addWidget(self.currentTime)
        hlayout.addStretch()
        hlayout.addWidget(self.nextLabel)

        hlayout = QHBoxLayout()
        hlayout.setContentsMargins(0, 0, 0, 0)
        hlayout.setSpacing(4)
        layout.addLayout(hlayout)

        self.okayBtn = QPushButton("&OK", self)
        self.cancelBtn = QPushButton("&Cancel", self)

        hlayout.addStretch()
        hlayout.addWidget(self.okayBtn)
        hlayout.addWidget(self.cancelBtn)
        self.setFrameSource(None, None)

    def sizeHint(self):
        widgetHeights = (
            self.slider.height()
            + max([self.okayBtn.height(), self.cancelBtn.height()])
            + max([self.currentIndex.height(), self.currentTime.height()])
        )

        if isinstance(self.filters, BaseFilter):
            w, h = self.filters.width, self.filters.height
            sar = self.filters.sar

        elif isinstance(self.source, (Track, BaseFilter)):
            w, h = self.source.width, self.source.height
            sar = self.source.sar

        else:
            return super().sizeHint()

        dar = w*sar/h
        W, H = min([
            max([(w, h/sar), (w*sar, h)]),
            (960 - 8, (960 - 8)/dar),
            ((720 - 20 - widgetHeights)*dar, 720 - 20 - widgetHeights)
        ])

        return QSize(int(W + 8), int(H + 20 + widgetHeights))

    def setFrameSource(self, source, filters=None):
        self.source = source

        if source is not None:
            self.slider.setMaximum(self.source.framecount - 1)
            self.currentIndex.setMaximum(self.source.framecount - 1)
            self.filters = filters

            if self.filters is not None:
                lastpts = self.filters.pts_time[-1]
                self.slider.setSnapValues(self.filters.keyframes)

            else:
                lastpts = self.source.pts_time[-1]

                if isinstance(self.source, BaseFilter):
                    self.slider.setSnapValues(self.source.keyframes)

                else:
                    self.slider.setSnapValues(None)

            ms = int(lastpts*1000 + 0.5)
            s, ms = divmod(ms, 1000)
            m, s = divmod(s, 60)
            h, m = divmod(m, 60)
            self.currentTime.setMaximumTime(QTime(h, m, s, ms))
            self.slider.setValue(0)
            self._frameChange(0)

        else:
            self.slider.setSnapValues(None)

        self.update()

    def handleIndexChange(self, n):
        self._frameChange(n)

        self.slider.blockSignals(True)
        self.slider.setValue(n)
        self.slider.blockSignals(False)

    def handleSliderChange(self, n):
        self._frameChange(n)

        self.currentIndex.blockSignals(True)
        self.currentIndex.setValue(n)
        self.currentIndex.blockSignals(False)

    def _frameChange(self, n):
        if self.source is not None:
            if self.filters is not None:
                nn = n
                m = -1

                while m < 0 and nn < len(self.filters.indexMap):
                    m = self.filters.indexMap[nn]
                    nn += 1

                try:
                    pts = self.filters.pts_time[m]

                except Exception:
                    pts = None

                try:
                    frame = next(self.filters.iterFrames(
                        m, whence="framenumber"))

                except StopIteration:
                    frame = None

                sar = self.filters.sar

            else:
                try:
                    pts = self.source.pts_time[n]

                except IndexError:
                    pts = None

                try:
                    frame = next(self.source.iterFrames(
                        n, whence="framenumber"))

                except StopIteration:
                    frame = None

                sar = self.source.sar

            if frame is not None:
                im = frame.to_image()
                self.imageView.setFrame(im.toqpixmap())
                self.imageView.setSar(sar)

            if pts is not None:
                ms = int(pts*1000+0.5)
                s, ms = divmod(ms, 1000)
                m, s = divmod(s, 60)
                h, m = divmod(m, 60)

                self.currentTime.blockSignals(True)
                self.currentTime.setTime(QTime(h, m, s, ms))
                self.currentTime.blockSignals(False)

            self.frameSelectionChanged.emit(n, self.currentTime.time())

    def handleTimeChange(self, t):
        if self.source is not None:
            if self.filters is not None:
                pts = t.msecsSinceStartOfDay()/1000
                n = self.filters.frameIndexFromPtsTime(pts, dir="-")

            else:
                pts = t.msecsSinceStartOfDay()/1000
                n = self.source.frameIndexFromPtsTime(pts, dir="-")

            self.slider.blockSignals(True)
            self.slider.setValue(n)
            self.slider.blockSignals(False)

            self.currentIndex.blockSignals(True)
            self.currentIndex.setValue(n)
            self.currentIndex.blockSignals(False)

            self._frameChange(n)
Ejemplo n.º 25
0
class SeekSettings(SettingsPage):
    Name = 'Seek Settings'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.cue_id = -1
        self.setLayout(QVBoxLayout(self))

        self.cueDialog = CueListDialog(
            cues=Application().cue_model.filter(MediaCue), parent=self)

        self.cueGroup = QGroupBox(self)
        self.cueGroup.setLayout(QVBoxLayout())
        self.layout().addWidget(self.cueGroup)

        self.cueButton = QPushButton(self.cueGroup)
        self.cueButton.clicked.connect(self.select_cue)
        self.cueGroup.layout().addWidget(self.cueButton)

        self.cueLabel = QLabel(self.cueGroup)
        self.cueLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.cueGroup.layout().addWidget(self.cueLabel)

        self.seekGroup = QGroupBox(self)
        self.seekGroup.setLayout(QHBoxLayout())
        self.layout().addWidget(self.seekGroup)

        self.seekEdit = QTimeEdit(self.seekGroup)
        self.seekEdit.setDisplayFormat('HH.mm.ss.zzz')
        self.seekGroup.layout().addWidget(self.seekEdit)

        self.seekLabel = QLabel(self.seekGroup)
        self.seekLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.seekGroup.layout().addWidget(self.seekLabel)

        self.layout().addSpacing(200)

        self.retranslateUi()

    def retranslateUi(self):
        self.cueGroup.setTitle('Cue')
        self.cueButton.setText('Click to select')
        self.cueLabel.setText('Not selected')
        self.seekGroup.setTitle('Seek')
        self.seekLabel.setText('Time to reach')

    def select_cue(self):
        if self.cueDialog.exec_() == self.cueDialog.Accepted:
            cue = self.cueDialog.selected_cues()[0]

            self.cue_id = cue.id
            self.seekEdit.setMaximumTime(
                QTime.fromMSecsSinceStartOfDay(cue.media.duration))
            self.cueLabel.setText(cue.name)

    def enable_check(self, enabled):
        self.cueGroup.setCheckable(enabled)
        self.cueGroup.setChecked(False)

        self.seekGroup.setCheckable(enabled)
        self.seekGroup.setChecked(False)

    def get_settings(self):
        return {'target_id': self.cue_id,
                'time': self.seekEdit.time().msecsSinceStartOfDay()}

    def load_settings(self, settings):
        if settings is not None:
            cue = Application().cue_model.get(settings['target_id'])
            if cue is not None:
                self.cue_id = settings['target_id']
                self.seekEdit.setTime(
                    QTime.fromMSecsSinceStartOfDay(settings['time']))
                self.seekEdit.setMaximumTime(
                    QTime.fromMSecsSinceStartOfDay(cue.media.duration))
                self.cueLabel.setText(cue.name)
class WindowEmployeeAdd(QDialog):
    def __init__(self):
        super(WindowEmployeeAdd, self).__init__()

        self.setWindowTitle("Add Employee")
        self.set_layout()

    def set_layout(self):
        # Set up basic Stuff here
        vbox = QVBoxLayout()
        group1 = QGroupBox("Employee")
        form1 = QFormLayout()
        group1.setLayout(form1)

        self.namelabel = QLabel("Name")
        self.nameLineEdit = QLineEdit("")
        self.nameLineEdit.setPlaceholderText("Enter Employee Name")
        form1.setWidget(0, QFormLayout.LabelRole, self.namelabel)
        form1.setWidget(0, QFormLayout.FieldRole, self.nameLineEdit)

        datelabel = QLabel("Date Started")
        self.dateLineEdit = QDateEdit()
        self.dateLineEdit.setDate(QDate(2021, 1, 1))
        self.dateLineEdit.setCalendarPopup(True)
        form1.setWidget(1, QFormLayout.LabelRole, datelabel)
        form1.setWidget(1, QFormLayout.FieldRole, self.dateLineEdit)

        self.timestartlabel = QLabel("Time Started")
        self.timestartLineEdit = QTimeEdit()
        self.timestartLineEdit.setTime(QTime(7, 0, 0))
        # Set time constrain
        self.timestartLineEdit.timeChanged.connect(self.connect_start_end)
        form1.setWidget(2, QFormLayout.LabelRole, self.timestartlabel)
        form1.setWidget(2, QFormLayout.FieldRole, self.timestartLineEdit)

        timeendedlabel = QLabel("Time Ended")
        self.timeendeLineEdit = QTimeEdit()
        self.timeendeLineEdit.setTime(QTime(self.timestartLineEdit.time()))
        # connect min time of endtime as starttime
        self.timeendeLineEdit.timeChanged.connect(
            self.set_min_time)  # you can use lambda function to get 1 line
        form1.setWidget(3, QFormLayout.LabelRole, timeendedlabel)
        form1.setWidget(3, QFormLayout.FieldRole, self.timeendeLineEdit)

        ##Group 2 (Employer)
        group2 = QGroupBox("Employer")
        form2 = QFormLayout()
        group2.setLayout(form2)
        # Add items to form
        amountlabel = QLabel("Amount Paid Per Hour")
        self.amountLine = QLineEdit("$5.00")
        self.amountLine.setEnabled(False)

        form2.setWidget(0, QFormLayout.LabelRole, amountlabel)
        form2.setWidget(0, QFormLayout.FieldRole, self.amountLine)

        ##ADD BUTTON
        self.addbtn = QPushButton("Add Emmployee")
        self.addbtn.clicked.connect(self.saved_messagebox)

        ## ADD ITEMS TO LAYOUT
        vbox.addWidget(group1)
        vbox.addWidget(group2)
        vbox.addWidget(self.addbtn, 0, Qt.AlignHCenter)
        self.setLayout(vbox)

    def connect_start_end(self):
        self.timeendeLineEdit.setTime(self.timestartLineEdit.time())

    def set_min_time(self):
        self.timeendeLineEdit.setMinimumTime(self.timestartLineEdit.time())

    def saved_messagebox(self):
        if self.nameLineEdit.text() != "":
            QMessageBox.information(self, "Information",
                                    "Details Saved Successfully")
            self.accept()
        elif self.nameLineEdit.text() == "":
            QMessageBox.warning(self, "Warning", "All Boxes Must be Filled")
Ejemplo n.º 27
0
class CountdownWidget(QWidget):
    """Define custom widget as countdown control panel."""
    def __init__(self, ctrl, parent=None):
        """Init completer."""
        super().__init__(parent)
        self.controller = ctrl
        self.createLayout()
        self.loadSettings()
        self.connect()

    def createLayout(self):
        """Create widget to control the countdown browser source."""
        layout = QGridLayout()
        self.rb_static = QRadioButton(_("Static Countdown to date:"), self)
        layout.addWidget(self.rb_static, 0, 0)
        self.rb_dynamic = QRadioButton(_("Dynamic Countdown duration:"), self)
        self.rb_dynamic.setChecked(True)
        self.rb_dynamic.toggled.connect(self.toggleRadio)
        layout.addWidget(self.rb_dynamic, 1, 0)
        self.te_datetime = QDateTimeEdit()
        self.te_datetime.setCalendarPopup(True)
        self.te_datetime.setContextMenuPolicy(Qt.CustomContextMenu)
        self.te_datetime.customContextMenuRequested.connect(
            self.openDateTimeMenu)
        layout.addWidget(self.te_datetime, 0, 1)
        self.te_duration = QTimeEdit()
        self.te_duration.setDisplayFormat("HH 'h' mm 'm' ss 's'")
        self.te_duration.setContextMenuPolicy(Qt.CustomContextMenu)
        self.te_duration.customContextMenuRequested.connect(
            self.openDurationMenu)
        layout.addWidget(self.te_duration, 1, 1)
        self.event_label = QLabel(' ' + _('Event description:'))
        layout.addWidget(self.event_label, 0, 2)
        self.le_desc = QLineEdit()
        self.le_desc.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.le_desc, 0, 3, 1, 2)
        self.cb_restart = QCheckBox(
            _('Restart countdown when source becomes active'))
        layout.addWidget(self.cb_restart, 1, 2, 1, 2)
        self.pb_start = QPushButton(" " + _('Start Countdown') + " ")
        layout.addWidget(self.pb_start, 1, 4)
        layout.setColumnStretch(2, 1)
        layout.setColumnStretch(3, 2)
        self.setLayout(layout)

    def openDateTimeMenu(self, position):
        """Open menu to set date to today."""
        menu = QMenu()
        act1 = QAction(_("Set Today"))
        act1.triggered.connect(self.setToday)
        menu.addAction(act1)
        menu.exec_(QCursor.pos())

    def openDurationMenu(self, position):
        """Open menu to set the duration."""
        menu = QMenu()
        for duration in [15, 10, 5, 3, 1]:
            act = QAction(_("Set {} min").format(duration), menu)
            act.triggered.connect(
                lambda x, duration=duration: self.setDuration(duration))
            menu.addAction(act)
        menu.exec_(QCursor.pos())

    def setToday(self):
        """Set date to today."""
        today = QDateTime.currentDateTime()
        today.setTime(self.te_datetime.time())
        self.te_datetime.setDateTime(today)

    def setFromTimestamp(self, timestamp):
        """Set time and date based on timestamp."""
        self.te_datetime.setDateTime(QDateTime.fromTime_t(int(timestamp)))

    def setDuration(self, duration):
        """Set the duration."""
        self.te_duration.setTime(QTime(0, duration, 0))

    def toggleRadio(self):
        """Toggle radio buttion."""
        static = self.rb_static.isChecked()
        self.te_datetime.setEnabled(static)
        self.te_duration.setEnabled(not static)
        self.cb_restart.setEnabled(not static)
        self.pb_start.setEnabled(not static)

    def loadSettings(self):
        """Load data from settings."""
        static = scctool.settings.config.parser.getboolean(
            "Countdown", "static")
        if static:
            self.rb_static.setChecked(True)
        else:
            self.rb_dynamic.setChecked(True)
        description = scctool.settings.config.parser.get(
            'Countdown', 'description')
        self.le_desc.setText(description.strip())
        restart = scctool.settings.config.parser.getboolean(
            "Countdown", "restart")
        self.cb_restart.setChecked(restart)

        duration = QTime()
        string = scctool.settings.config.parser.get('Countdown',
                                                    'duration').strip()
        duration = QTime.fromString(string, 'HH:mm:ss')
        self.te_duration.setTime(duration)

        string = scctool.settings.config.parser.get('Countdown',
                                                    'datetime').strip()
        datetime = QDateTime.fromString(string, 'yyyy-MM-dd HH:mm')
        self.te_datetime.setDateTime(datetime)

    def connect(self):
        """Connect all form elements."""
        self.le_desc.textChanged.connect(self.changed_description)
        self.cb_restart.toggled.connect(self.changed_restart)
        self.te_datetime.dateTimeChanged.connect(self.changed_datetime)
        self.te_duration.timeChanged.connect(self.changed_duration)
        self.rb_static.toggled.connect(self.changed_static)
        self.pb_start.pressed.connect(self.start_pressed)

    def changed_description(self):
        """Change the description."""
        desc = self.le_desc.text().strip()
        scctool.settings.config.parser.set('Countdown', 'description', desc)
        self.controller.websocketThread.sendData2Path('countdown', "DESC",
                                                      desc)

    def changed_restart(self):
        """Handle change of restart option."""
        restart = self.cb_restart.isChecked()
        scctool.settings.config.parser.set('Countdown', 'restart',
                                           str(restart))
        self.controller.websocketThread.sendData2Path('countdown', "RESTART",
                                                      restart)

    def changed_datetime(self, time):
        """Handle change of datetime."""
        datetime = time.toString('yyyy-MM-dd HH:mm')
        scctool.settings.config.parser.set('Countdown', 'datetime', datetime)
        self.sendData()

    def changed_duration(self, time):
        """Handle change of duration."""
        duration = time.toString('HH:mm:ss')
        scctool.settings.config.parser.set('Countdown', 'duration', duration)
        self.sendData()

    def changed_static(self):
        """Handle change of static/dynamic."""
        static = self.rb_static.isChecked()
        scctool.settings.config.parser.set('Countdown', 'static', str(static))
        self.sendData()

    def start_pressed(self):
        """Handle press of the start button."""
        self.controller.websocketThread.sendData2Path('countdown', 'START')

    def sendData(self):
        """Send the data to the websocket."""
        self.controller.websocketThread.sendData2Path(
            'countdown', "DATA",
            self.controller.websocketThread.getCountdownData())
Ejemplo n.º 28
0
class SeekCueSettings(SettingsPage):
    Name = QT_TRANSLATE_NOOP('SettingsPageName', 'Seek Settings')

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.setLayout(QVBoxLayout())
        self.layout().setAlignment(QtCore.Qt.AlignTop)

        self.cue_id = -1

        self.cueDialog = CueSelectDialog(
            cues=Application().cue_model.filter(MediaCue), parent=self)

        self.cueGroup = QGroupBox(self)
        self.cueGroup.setLayout(QVBoxLayout())
        self.layout().addWidget(self.cueGroup)

        self.cueButton = QPushButton(self.cueGroup)
        self.cueButton.clicked.connect(self.select_cue)
        self.cueGroup.layout().addWidget(self.cueButton)

        self.cueLabel = QLabel(self.cueGroup)
        self.cueLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.cueGroup.layout().addWidget(self.cueLabel)

        self.seekGroup = QGroupBox(self)
        self.seekGroup.setLayout(QHBoxLayout())
        self.layout().addWidget(self.seekGroup)

        self.seekEdit = QTimeEdit(self.seekGroup)
        self.seekEdit.setDisplayFormat('HH.mm.ss.zzz')
        self.seekGroup.layout().addWidget(self.seekEdit)

        self.seekLabel = QLabel(self.seekGroup)
        self.seekLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.seekGroup.layout().addWidget(self.seekLabel)

        self.retranslateUi()

    def retranslateUi(self):
        self.cueGroup.setTitle(translate('SeekCue', 'Cue'))
        self.cueButton.setText(translate('SeekCue', 'Click to select'))
        self.cueLabel.setText(translate('SeekCue', 'Not selected'))
        self.seekGroup.setTitle(translate('SeekCue', 'Seek'))
        self.seekLabel.setText(translate('SeekCue', 'Time to reach'))

    def select_cue(self):
        if self.cueDialog.exec_() == self.cueDialog.Accepted:
            cue = self.cueDialog.selected_cue()

            if cue is not None:
                self.cue_id = cue.id
                self.seekEdit.setMaximumTime(
                    QTime.fromMSecsSinceStartOfDay(cue.media.duration))
                self.cueLabel.setText(cue.name)

    def enable_check(self, enabled):
        self.cueGroup.setCheckable(enabled)
        self.cueGroup.setChecked(False)

        self.seekGroup.setCheckable(enabled)
        self.seekGroup.setChecked(False)

    def get_settings(self):
        return {
            'target_id': self.cue_id,
            'time': self.seekEdit.time().msecsSinceStartOfDay()
        }

    def load_settings(self, settings):
        if settings is not None:
            cue = Application().cue_model.get(settings.get('target_id'))
            if cue is not None:
                self.cue_id = settings['target_id']
                self.seekEdit.setMaximumTime(
                    QTime.fromMSecsSinceStartOfDay(cue.media.duration))
                self.cueLabel.setText(cue.name)

            self.seekEdit.setTime(
                QTime.fromMSecsSinceStartOfDay(settings.get('time', 0)))
Ejemplo n.º 29
0
class MainWindow(PageWindow):
    def __init__(self):
        super().__init__()
        #self.ser = serial.Serial(port='COM3', baudrate=115200, bytesize=8, parity='N', stopbits=1)

        self.seperator_vertical = QVSeperationLine()
        self.seperator_horizontal = QHSeperationLine()
        self.initUI()
        self.setWindowTitle("MainWindow")

    def initUI(self):
        self.homeUI()

    def homeUI(self):
        self.preview_widget = QWidget()
        self.footer_widget = QWidget()
        self.home = True
        self.viewfinder = QCameraViewfinder()
        self.viewfinder.show()
        self.setCentralWidget(self.viewfinder)
        self.cap = None  #  -capture <-> +cap
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout2 = QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.verticalLayout = QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.image_label = QLabel()
        self.image_label.setText("")
        self.image_label.setObjectName("image_label")

        self.temp = QLabel()
        self.temp.setText("Temperature:")
        self.temp.setObjectName("temp")

        self.temp_reading = QLabel()
        self.temp_reading.setText("temp_reading")
        self.temp_reading.setObjectName("temp_reading")

        self.temp2 = QLabel()
        self.temp2.setText("Temperature 2:")
        self.temp2.setObjectName("temp2")

        self.temp2_reading = QLabel()
        self.temp2_reading.setText("Temperature2 Reading")
        self.temp2_reading.setObjectName("temp2_reading")

        self.image_label.setScaledContents(True)

        self.matplotlibWidget = MatplotlibWidget(self)
        self.threadSample = ThreadSample(self)
        self.threadSample.newSample.connect(self.on_threadSample_newSample)
        self.threadSample.finished.connect(self.on_threadSample_finished)

        self.gridLayout = QGridLayout(self)
        self.gridLayout.addWidget(self.temp, 0, 0)
        self.gridLayout.addWidget(self.temp_reading, 0, 1)
        self.gridLayout.addWidget(self.temp2, 1, 0)
        self.gridLayout.addWidget(self.temp2_reading, 1, 1)

        self.horizontalLayout.addWidget(self.image_label)
        self.horizontalLayout.addWidget(self.seperator_vertical)
        self.horizontalLayout.addLayout(self.gridLayout)

        self.preview_widget.setLayout(self.horizontalLayout)
        self.preview_widget.setMinimumHeight(200)
        self.preview_widget.setMaximumHeight(200)
        self.preview_widget.setMinimumWidth(600)
        self.preview_widget.setMaximumWidth(600)

        self.horizontalLayout2.addWidget(self.matplotlibWidget)
        self.horizontalLayout2.addWidget(self.seperator_vertical)
        #self.horizontalLayout2.addWidget(self.clock)
        self.clock(self.horizontalLayout2)

        self.footer_widget.setLayout(self.horizontalLayout2)
        self.footer_widget.setMinimumHeight(250)
        self.footer_widget.setMaximumHeight(250)
        self.footer_widget.setMinimumWidth(600)
        self.footer_widget.setMaximumWidth(600)

        self.verticalLayout.addWidget(self.preview_widget)
        self.verticalLayout.addWidget(self.seperator_horizontal)
        self.verticalLayout.addWidget(self.footer_widget)
        #self.verticalLayout.addWidget(self.image_label2)

        self.timer = QTimer(self, interval=5)
        self.timer.timeout.connect(self.update_frame)
        self._image_counter = 0
        centralWidget = QWidget(self)
        self.setCentralWidget(centralWidget)
        self.centralWidget().setLayout(self.verticalLayout)
        #         self.setCentralWidget(self.scroll)
        self.setGeometry(300, 300, 400, 700)

    def read_temp(self):
        temp = []
        while True:
            self.ser.write(b'0x55,0xAA,5,1,4')
            response = self.ser.readline()
            #print(str(response))
            if 'body' in str(response):
                temp.append(str(response))
                #print("temp-"+str(response))
                #print(temp)
            elif 'Vbat' in str(response):
                if len(temp) != 0:
                    print("Done-" + ' '.join(temp))
                    self.start_webcam()
                    self.update_frame(self.filter(''.join(temp)))
                temp = []

    def filter(self, text):

        text = text.replace('bTbody', 'body')
        text = text.replace('\'', '')

        text = text.replace('\\r\n\'b\'Tbody', '-')
        text = text.replace('\\r', '')
        text = text.replace('\r', '')
        text = text.replace('\\xa8', '')
        text = text.replace('\\xa1\\xe6', '')
        text = text.replace('\\n', '-')
        text = text.replace(' ', '')
        text = text.replace(', ', ',')
        text = text.replace('=', '_')
        text = text.replace(',', '-')
        return text

    @QtCore.pyqtSlot()
    def start_webcam(self):
        if self.cap is None:
            self.cap = cv2.VideoCapture(0)
            self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
            self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
        self.timer.start()

    def closeEvent(self, event):
        print("closing PyQtTest")
        self.cap.close()

    @QtCore.pyqtSlot()
    def update_frame(self, file_name):
        ret, image = self.cap.read()
        self.face_detect(image, file_name)
        simage = cv2.flip(image, 1)
        self.displayImage(image, True)

    def face_detect(self, image, file_name):
        frame = image
        face_locations = []
        face_encodings = []
        face_names = []
        process_this_frame = True
        i = 0
        face_detect = True
        # Resize frame of video to 1/4 size for faster face recognition processing
        small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)

        # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
        rgb_small_frame = small_frame[:, :, ::-1]
        self.dirname = 'd:'
        # Only process every other frame of video to save time
        if process_this_frame:
            # Find all the faces and face encodings in the current frame of video
            face_locations = face_recognition.face_locations(rgb_small_frame)
            face_encodings = face_recognition.face_encodings(
                rgb_small_frame, face_locations)

            face_names = []
            for face_encoding in face_encodings:
                # See if the face is a match for the known face(s)
                face_detect = False
                name = "Unknown"
                cv2.imwrite(
                    os.path.abspath(
                        os.path.join(
                            self.dirname,
                            (datetime.today().strftime('%Y-%m-%d') + '-' +
                             file_name + '-' + str(++i) + '.png'))), frame)
                #self.storage.upload(self.dirname,(datetime.today().strftime('%Y-%m-%d')+'-'+file_name+'-'+str(i)+'.png'))

                i = i + 1

                print("I see someone named {}!".format(name))
                # # If a match was found in known_face_encodings, just use the first one.
                # if True in matches:
                #     first_match_index = matches.index(True)
                #     name = known_face_names[first_match_index]

                # Or instead, use the known face with the smallest distance to the new face

                process_this_frame = not process_this_frame

    @staticmethod
    @QtCore.pyqtSlot()
    def capture_image(self):
        flag, frame = self.cap.read()
        timestamp = time.strftime("%d-%b-%Y-%H_%M_%S")

        self.save_seq += 1

        path = self.save_path  #
        if flag:
            QtWidgets.QApplication.beep()
            name = "my_image.jpg"
            cv2.imwrite(
                os.path.join(
                    self.save_path, "%s-%04d-%s.jpg" %
                    (self.current_camera_name, self.save_seq, timestamp)),
                frame)
            self._image_counter += 1

    def displayImage(self, img, window=True):
        qformat = QImage.Format_Indexed8
        if len(img.shape) == 3:
            if img.shape[2] == 4:
                qformat = QImage.Format_RGBA8888
            else:
                qformat = QImage.Format_RGB888
        outImage = QImage(img, img.shape[1], img.shape[0], img.strides[0],
                          qformat)
        outImage = outImage.rgbSwapped()
        if window:
            self.image_label.setStyleSheet("""
        QLabel {
            height:300px !important;
            
            }
        """)

            self.image_label.setPixmap(QPixmap.fromImage(outImage))

    def clock(self, layout):
        self.verticalLayoutClock = QVBoxLayout(self)
        self.dateEdit = QDateEdit(self)
        self.dateEdit.setDisplayFormat("MMM dd yyyy")
        self.dateEdit.setDisabled(True)
        self.verticalLayoutClock.addWidget(self.dateEdit)
        self.timeEdit = QTimeEdit(self)
        self.timeEdit.setDisplayFormat("hh:mm:ss AP")
        self.timeEdit.setDisabled(True)
        self.verticalLayoutClock.addWidget(self.timeEdit)
        self.updateTime()
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.updateTime)
        self.timer.start(1000)
        layout.addLayout(self.verticalLayoutClock)

    @QtCore.pyqtSlot(list)
    def on_threadSample_newSample(self, sample):
        self.matplotlibWidget.axis.plot(sample)
        self.matplotlibWidget.canvas.draw()

    @QtCore.pyqtSlot()
    def on_threadSample_finished(self):
        self.samples += 1
        if self.samples <= 2:
            self.threadSample.start()

    @QtCore.pyqtSlot()
    def on_pushButtonPlot_clicked(self):
        self.samples = 0
        self.matplotlibWidget.axis.clear()
        self.threadSample.start()

    def updateTime(self):
        current = QtCore.QDateTime.currentDateTime()
        self.dateEdit.setDate(current.date())
        self.timeEdit.setTime(current.time())
Ejemplo n.º 30
0
class BlinkWindow(QMainWindow):
    def __init__(self, parent, *arg, **kwargs):
        '''
        Initialize the Window.
        '''

        super().__init__(parent)
        self.parent = parent

        self.setWindowTitle('TopWatch - Setup blinking')
        self.setWindowFlags(Qt.Dialog)
        sizeObject = QDesktopWidget().screenGeometry(-1)
        self.setGeometry(sizeObject.width() // 2,
                         sizeObject.height() // 2,
                         self.geometry().width(),
                         self.geometry().height())

        # Time edit label
        self.teditTxt = QLabel()
        self.teditTxt.setText('Period (hh:mm:ss)')

        # Time edit widget
        self.tedit = QTimeEdit(self)
        self.tedit.setDisplayFormat('hh:mm:ss')
        self.tedit.setTime(self.parent.blinkPeriod)

        # Duration edit label
        self.lenTxt = QLabel()
        self.lenTxt.setText('Duration (ms)')

        # Duration edit widget
        self.lenedit = QDoubleSpinBox(self)
        self.lenedit.setDecimals(0)
        self.lenedit.setMaximum(10000)
        self.lenedit.setMinimum(50)
        self.lenedit.setValue(self.parent.blinkFreq)

        # Blink number edit label
        self.blnbTxt = QLabel()
        self.blnbTxt.setText('Blink number')

        # Blink number edit widget
        self.blnbedit = QDoubleSpinBox(self)
        self.blnbedit.setValue(self.parent.blinkNb)
        self.blnbedit.setDecimals(0)
        self.blnbedit.setMinimum(1)

        # Ok button setup
        self.okButton = QPushButton(self)
        self.okButton.setText('Ok')
        self.okButton.clicked.connect(self.ok)
        self.okButton.setToolTip("Activate blinking")

        # Cancel button setup
        self.cancelButton = QPushButton(self)
        self.cancelButton.setText('Cancel')
        self.cancelButton.clicked.connect(self.cancel)
        self.cancelButton.setToolTip("Cancel blinking setup")

        # Layout
        self.layout = QGridLayout()

        self.layout.addWidget(self.teditTxt, 0, 0)
        self.layout.addWidget(self.tedit, 1, 0)

        self.layout.addWidget(self.lenTxt, 2, 0)
        self.layout.addWidget(self.lenedit, 3, 0)

        self.layout.addWidget(self.blnbTxt, 2, 1)
        self.layout.addWidget(self.blnbedit, 3, 1)

        self.layout.addWidget(self.okButton, 4, 0)
        self.layout.addWidget(self.cancelButton, 4, 1)

        self.mainWidget = QWidget()
        self.mainWidget.setLayout(self.layout)
        self.setCentralWidget(self.mainWidget)

    ###############################
    #           Methods           #
    ###############################

    def cancel(self, *args, **kwargs):
        '''When cancel is pressed blinking parameters are updated it the user wants to save later on.'''

        self.parent.blinkNb = self.blnbedit.value()
        self.parent.blinkPeriod = self.tedit.time()
        self.parent.blinkFreq = self.lenedit.value()
        self.close()
        return

    def keyPressEvent(self, e, *args, **kwargs):
        '''Actions taken when a key is pressed.'''

        if e.key() == Qt.Key_Escape:
            self.cancel(*args, **kwargs)
        elif e.key() == Qt.Key_Return:
            self.ok(*args, **kwargs)
        return

    def ok(self, *args, **kwargs):
        '''Start blinking when ok is pressed.'''

        self.parent.start_blink(self.lenedit.value(), self.tedit.time(),
                                self.blnbedit.value())
        self.close()
        return
Ejemplo n.º 31
0
class Downtime(QDialog):
    """
        Class who create Downtime QDialog for hosts/services
    """
    def __init__(self, parent=None):
        super(Downtime, self).__init__(parent)
        self.setWindowTitle('Request a Downtime')
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setStyleSheet(get_css())
        self.setWindowIcon(QIcon(get_image_path('icon')))
        self.setMinimumSize(360, 460)
        # Fields
        self.fixed = True
        self.duration = QTimeEdit()
        self.start_time = QDateTimeEdit()
        self.end_time = QDateTimeEdit()
        self.comment_edit = QTextEdit()

    def initialize(self, item_type, item_name, comment):
        """
        Initialize Downtime QDialog

        :param item_type: type of item to acknowledge : host | service
        :type item_type: str
        :param item_name: name of the item to acknowledge
        :type item_name: str
        :param comment: the default comment of action
        :type comment: str
        """

        # Main layout
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(0, 0, 0, 0)

        main_layout.addWidget(get_logo_widget(self))

        downtime_widget = QWidget()
        downtime_widget.setObjectName('login')
        downtime_layout = QGridLayout(downtime_widget)

        ack_title = QLabel('<h2>Request a downtime</h2>')
        downtime_layout.addWidget(ack_title, 0, 0, 1, 3)

        host_label = QLabel('<h2>%s: %s</h2>' %
                            (item_type.capitalize(), item_name))
        downtime_layout.addWidget(host_label, 1, 0, 1, 1)

        options_label = QLabel('Downtime options:')
        options_label.setObjectName('actions')
        downtime_layout.addWidget(options_label, 2, 0, 1, 1)

        fixed_checkbox = QCheckBox()
        fixed_checkbox.setObjectName('actions')
        fixed_checkbox.setChecked(self.fixed)
        fixed_checkbox.setFixedSize(18, 18)
        downtime_layout.addWidget(fixed_checkbox, 2, 1, 1, 1)

        fixed_label = QLabel('Fixed')
        fixed_label.setObjectName('actions')
        downtime_layout.addWidget(fixed_label, 2, 2, 1, 1)

        fixed_info = QLabel(
            '<i>If checked, downtime will start and end at the times specified'
            ' by the “start time” and “end time” fields.</i>')
        fixed_info.setWordWrap(True)
        downtime_layout.addWidget(fixed_info, 3, 0, 1, 3)

        duration_label = QLabel('Duration')
        duration_label.setObjectName('actions')
        downtime_layout.addWidget(duration_label, 4, 0, 1, 1)

        duration_clock = QLabel()
        duration_clock.setPixmap(QPixmap(get_image_path('clock')))
        downtime_layout.addWidget(duration_clock, 4, 1, 1, 1)
        duration_clock.setFixedSize(16, 16)
        duration_clock.setScaledContents(True)

        self.duration.setTime(QTime(4, 00))
        self.duration.setDisplayFormat("HH'h'mm")
        downtime_layout.addWidget(self.duration, 4, 2, 1, 1)

        duration_info = QLabel(
            '<i>Sets the duration if it is a non-fixed downtime.</i>')
        downtime_layout.addWidget(duration_info, 5, 0, 1, 3)

        date_range_label = QLabel('Downtime date range')
        date_range_label.setObjectName('actions')
        downtime_layout.addWidget(date_range_label, 6, 0, 1, 1)

        calendar_label = QLabel()
        calendar_label.setPixmap(QPixmap(get_image_path('calendar')))
        calendar_label.setFixedSize(16, 16)
        calendar_label.setScaledContents(True)
        downtime_layout.addWidget(calendar_label, 6, 1, 1, 1)

        start_time_label = QLabel('Start time:')
        downtime_layout.addWidget(start_time_label, 7, 0, 1, 1)

        self.start_time.setCalendarPopup(True)
        self.start_time.setDateTime(datetime.datetime.now())
        self.start_time.setDisplayFormat("dd/MM/yyyy HH'h'mm")
        downtime_layout.addWidget(self.start_time, 7, 1, 1, 2)

        end_time_label = QLabel('End time:')
        downtime_layout.addWidget(end_time_label, 8, 0, 1, 1)

        self.end_time.setCalendarPopup(True)
        self.end_time.setDateTime(datetime.datetime.now() +
                                  datetime.timedelta(hours=2))
        self.end_time.setDisplayFormat("dd/MM/yyyy HH'h'mm")
        downtime_layout.addWidget(self.end_time, 8, 1, 1, 2)

        self.comment_edit.setText(comment)
        self.comment_edit.setMaximumHeight(60)
        downtime_layout.addWidget(self.comment_edit, 9, 0, 1, 3)

        request_btn = QPushButton('REQUEST DOWNTIME', self)
        request_btn.clicked.connect(self.handle_accept)
        request_btn.setObjectName('valid')
        request_btn.setMinimumHeight(30)
        request_btn.setDefault(True)
        downtime_layout.addWidget(request_btn, 10, 0, 1, 3)

        main_layout.addWidget(downtime_widget)

    def duration_to_seconds(self):
        """
        Return "duration" QTimeEdit value in seconds

        :return: "duration" in seconds
        :rtype: int
        """

        return QTime(0, 0).secsTo(self.duration.time())

    def handle_accept(self):
        """
        Check if end_time timestamp is not lower than start_time

        """

        if self.start_time.dateTime().toTime_t() > self.end_time.dateTime(
        ).toTime_t():
            logger.warning(
                'Try to add Downtime with "End Time" lower than "Start Time"')
        else:
            self.accept()

    def mousePressEvent(self, event):
        """ QWidget.mousePressEvent(QMouseEvent) """

        self.offset = event.pos()

    def mouseMoveEvent(self, event):
        """ QWidget.mousePressEvent(QMouseEvent) """

        try:
            x = event.globalX()
            y = event.globalY()
            x_w = self.offset.x()
            y_w = self.offset.y()
            self.move(x - x_w, y - y_w)
        except AttributeError as e:
            logger.warning('Move Event %s: %s', self.objectName(), str(e))
Ejemplo n.º 32
0
class TimersDialog(QDialog):
    sendCommand = pyqtSignal(str, str)

    def __init__(self, device, *args, **kwargs):
        super(TimersDialog, self).__init__(*args, **kwargs)
        self.device = device
        self.timers = {}
        self.setWindowTitle("Timers [{}]".format(
            self.device.p['FriendlyName1']))

        vl = VLayout()

        self.gbTimers = GroupBoxV("Enabled", spacing=5)
        self.gbTimers.setCheckable(True)
        self.gbTimers.toggled.connect(self.toggleTimers)

        self.cbTimer = QComboBox()
        self.cbTimer.addItems(["Timer{}".format(nr + 1) for nr in range(16)])
        self.cbTimer.currentTextChanged.connect(self.loadTimer)

        hl_tmr_arm_rpt = HLayout(0)
        self.cbTimerArm = QCheckBox("Arm")
        self.cbTimerArm.clicked.connect(lambda x: self.describeTimer())
        self.cbTimerRpt = QCheckBox("Repeat")
        self.cbTimerRpt.clicked.connect(lambda x: self.describeTimer())
        hl_tmr_arm_rpt.addWidgets([self.cbTimerArm, self.cbTimerRpt])

        hl_tmr_out_act = HLayout(0)
        self.cbxTimerOut = QComboBox()
        self.cbxTimerOut.addItems(self.device.power().keys())
        self.cbxTimerOut.currentIndexChanged.connect(
            lambda x: self.describeTimer())
        self.cbxTimerAction = QComboBox()
        self.cbxTimerAction.addItems(["Off", "On", "Toggle", "Rule"])
        self.cbxTimerAction.currentIndexChanged.connect(
            lambda x: self.describeTimer())
        hl_tmr_out_act.addWidgets([self.cbxTimerOut, self.cbxTimerAction])

        self.TimerMode = QButtonGroup()
        rbTime = QRadioButton("Time")
        rbSunrise = QRadioButton("Sunrise ({})".format(
            self.device.p['Sunrise']))
        rbSunset = QRadioButton("Sunset ({})".format(self.device.p['Sunset']))
        self.TimerMode.addButton(rbTime, 0)
        self.TimerMode.addButton(rbSunrise, 1)
        self.TimerMode.addButton(rbSunset, 2)
        self.TimerMode.buttonClicked.connect(lambda x: self.describeTimer())
        gbTimerMode = GroupBoxH("Mode")
        gbTimerMode.addWidgets(self.TimerMode.buttons())

        hl_tmr_time = HLayout(0)
        self.cbxTimerPM = QComboBox()
        self.cbxTimerPM.addItems(["+", "-"])
        self.cbxTimerPM.currentIndexChanged.connect(
            lambda x: self.describeTimer())

        self.TimerMode.buttonClicked[int].connect(
            lambda x: self.cbxTimerPM.setEnabled(x != 0))
        self.teTimerTime = QTimeEdit()
        self.teTimerTime.setButtonSymbols(QTimeEdit.NoButtons)
        self.teTimerTime.setAlignment(Qt.AlignCenter)
        self.teTimerTime.timeChanged.connect(lambda x: self.describeTimer())

        lbWnd = QLabel("Window:")
        lbWnd.setAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.cbxTimerWnd = QComboBox()
        self.cbxTimerWnd.addItems([str(x).zfill(2) for x in range(0, 16)])
        self.cbxTimerWnd.currentIndexChanged.connect(
            lambda x: self.describeTimer())

        hl_tmr_days = HLayout(0)
        self.TimerWeekday = QButtonGroup()
        self.TimerWeekday.setExclusive(False)
        for i, wd in enumerate(
            ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]):
            cb = QCheckBox(wd)
            cb.clicked.connect(lambda x: self.describeTimer())
            hl_tmr_days.addWidget(cb)
            self.TimerWeekday.addButton(cb, i)

        gbTimerDesc = GroupBoxV("Timer description", 5)
        gbTimerDesc.setMinimumHeight(200)
        self.lbTimerDesc = QLabel()
        self.lbTimerDesc.setAlignment(Qt.AlignCenter)
        self.lbTimerDesc.setWordWrap(True)
        gbTimerDesc.layout().addWidget(self.lbTimerDesc)

        hl_tmr_time.addWidgets(
            [self.cbxTimerPM, self.teTimerTime, lbWnd, self.cbxTimerWnd])

        self.gbTimers.layout().addWidget(self.cbTimer)
        self.gbTimers.layout().addLayout(hl_tmr_arm_rpt)
        self.gbTimers.layout().addLayout(hl_tmr_out_act)
        self.gbTimers.layout().addWidget(gbTimerMode)
        self.gbTimers.layout().addLayout(hl_tmr_time)
        self.gbTimers.layout().addLayout(hl_tmr_days)

        btns = QDialogButtonBox(QDialogButtonBox.Save | QDialogButtonBox.Close)
        reload = btns.addButton("Reload", QDialogButtonBox.ResetRole)

        btns.accepted.connect(self.saveTimer)
        btns.rejected.connect(self.reject)
        reload.clicked.connect(
            lambda: self.loadTimer(self.cbTimer.currentText()))

        vl.addWidgets([self.gbTimers, gbTimerDesc, btns])
        self.setLayout(vl)

    def toggleTimers(self, state):
        self.sendCommand.emit(self.device.cmnd_topic('timers'),
                              "ON" if state else "OFF")

    def loadTimer(self, timer=""):
        if not timer:
            timer = self.cbTimer.currentText()
        payload = self.timers[timer]

        if payload:
            self.blockSignals(True)
            self.cbTimerArm.setChecked(payload['Arm'])
            self.cbTimerRpt.setChecked(payload['Repeat'])
            self.cbxTimerAction.setCurrentIndex(payload['Action'])

            output = payload.get('Output')
            if output:
                self.cbxTimerOut.setEnabled(True)
                self.cbxTimerOut.setCurrentIndex(output - 1)
            else:
                self.cbxTimerOut.setEnabled(False)

            mode = payload.get('Mode', 0)
            self.TimerMode.button(mode).setChecked(True)

            h, m = map(int, payload["Time"].split(":"))
            if h < 0:
                self.cbxTimerPM.setCurrentText("-")
                h *= -1
            self.teTimerTime.setTime(QTime(h, m))
            self.cbxTimerWnd.setCurrentText(str(payload['Window']).zfill(2))
            for wd, v in enumerate(payload['Days']):
                self.TimerWeekday.button(wd).setChecked(int(v))

            self.blockSignals(False)
            self.describeTimer()

    def describeTimer(self):
        if self.cbTimerArm.isChecked():
            desc = {
                'days': '',
                'repeat': '',
                'timer': self.cbTimer.currentText().upper()
            }
            repeat = self.cbTimerRpt.isChecked()
            out = self.cbxTimerOut.currentText()
            act = self.cbxTimerAction.currentText()
            mode = self.TimerMode.checkedId()
            pm = self.cbxTimerPM.currentText()
            time = self.teTimerTime.time()
            wnd = int(self.cbxTimerWnd.currentText()) * 60

            if mode == 0:
                if wnd == 0:
                    desc['time'] = "at {}".format(time.toString("hh:mm"))
                else:
                    desc['time'] = "somewhere between {} and {}".format(
                        time.addSecs(wnd * -1).toString("hh:mm"),
                        time.addSecs(wnd).toString("hh:mm"))
            else:
                prefix = "before" if pm == "-" else "after"
                mode_desc = "sunrise" if mode == 1 else "sunset"
                window = "somewhere in a {} minute window centered around ".format(
                    wnd // 30)
                desc['time'] = "{}h{}m {} {}".format(time.hour(),
                                                     time.minute(), prefix,
                                                     mode_desc)

                if wnd > 0:
                    desc['time'] = window + desc['time']

            if repeat:
                day_names = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
                days = [cb.isChecked() for cb in self.TimerWeekday.buttons()]
                if days.count(True) == 7:
                    desc['days'] = "everyday"
                else:
                    days_list = [day_names[d] for d in range(7) if days[d]]
                    desc['days'] = "on every {}".format(", ".join(days_list))
            else:
                desc['repeat'] = "only ONCE"

            if act == "Rule":
                desc['action'] = "trigger clock#Timer={}".format(
                    self.cbTimer.currentIndex() + 1)
                text = "{timer} will {action} {time} {days} {repeat}".format(
                    **desc)

            elif self.cbxTimerOut.count() > 0:

                if act == "Toggle":
                    desc['action'] = "TOGGLE {}".format(out.upper())
                else:
                    desc['action'] = "set {} to {}".format(
                        out.upper(), act.upper())

                text = "{timer} will {action} {time} {days} {repeat}".format(
                    **desc)
            else:
                text = "{timer} will do nothing because there are no relays configured.".format(
                    **desc)

            self.lbTimerDesc.setText(text)

        else:
            self.lbTimerDesc.setText(
                "{} is not armed, it will do nothing.".format(
                    self.cbTimer.currentText().upper()))

    def saveTimer(self):
        payload = {
            "Arm":
            int(self.cbTimerArm.isChecked()),
            "Mode":
            self.TimerMode.checkedId(),
            "Time":
            self.teTimerTime.time().toString("hh:mm"),
            "Window":
            self.cbxTimerWnd.currentIndex(),
            "Days":
            "".join([
                str(int(cb.isChecked())) for cb in self.TimerWeekday.buttons()
            ]),
            "Repeat":
            int(self.cbTimerRpt.isChecked()),
            "Output":
            self.cbxTimerOut.currentIndex() + 1,
            "Action":
            self.cbxTimerAction.currentIndex()
        }
        self.sendCommand.emit(
            self.device.cmnd_topic(self.cbTimer.currentText()), dumps(payload))
        QMessageBox.information(
            self, "Timer saved",
            "{} data sent to device.".format(self.cbTimer.currentText()))

    @pyqtSlot(str, str)
    def parseMessage(self, topic, msg):
        if self.device.matches(topic):
            if self.device.reply == "RESULT" or self.device.reply == "TIMERS":
                try:
                    payload = loads(msg)
                    first = list(payload)[0]

                except JSONDecodeError as e:
                    error = "Timer loading error", "Can't load the timer from device.\n{}".format(
                        e)
                    logging.critical(error)
                    QMessageBox.critical(self, error)

                else:
                    if first == 'Timers':
                        self.gbTimers.setChecked(payload[first] == "ON")

                    elif first.startswith('Timers'):
                        self.timers.update(payload[first])

                    if first == 'Timers4':
                        self.loadTimer(self.cbTimer.currentText())
Ejemplo n.º 33
0
class VCTimeCounter(QWidget):
    timeChanged = pyqtSignal(QTime)

    def __init__(self, parent=None):
        super(VCTimeCounter, self).__init__(parent)
        self.parent = parent
        self.timeedit = QTimeEdit(QTime(0, 0))
        self.timeedit.setObjectName('timeCounter')
        self.timeedit.setStyle(QStyleFactory.create('Fusion'))
        self.timeedit.setFrame(False)
        self.timeedit.setDisplayFormat('hh:mm:ss.zzz')
        self.timeedit.timeChanged.connect(self.timeChangeHandler)
        separator = QLabel('/')
        separator.setObjectName('timeSeparator')
        self.duration = QLabel('00:00:00.000')
        self.duration.setObjectName('timeDuration')
        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(5)
        layout.addWidget(self.timeedit)
        layout.addWidget(separator)
        layout.addWidget(self.duration)
        self.setLayout(layout)

    def setRange(self, minval: str, maxval: str) -> None:
        self.timeedit.setTimeRange(QTime.fromString(minval, 'hh:mm:ss.zzz'),
                                   QTime.fromString(maxval, 'hh:mm:ss.zzz'))

    def setMinimum(self, val: str = None) -> None:
        if val is None:
            self.timeedit.setMinimumTime(QTime(0, 0))
        else:
            self.timeedit.setMinimumTime(QTime.fromString(val, 'hh:mm:ss.zzz'))

    def setMaximum(self, val: str) -> None:
        self.timeedit.setMaximumTime(QTime.fromString(val, 'hh:mm:ss.zzz'))

    def setTime(self, time: str) -> None:
        self.timeedit.setTime(QTime.fromString(time, 'hh:mm:ss.zzz'))

    def setDuration(self, time: str) -> None:
        self.duration.setText(time)
        self.setMaximum(time)

    def clearFocus(self) -> None:
        self.timeedit.clearFocus()

    def hasFocus(self) -> bool:
        if self.timeedit.hasFocus():
            return True
        return super(VCTimeCounter, self).hasFocus()

    def reset(self) -> None:
        self.timeedit.setTime(QTime(0, 0))
        self.setDuration('00:00:00.000')

    def setReadOnly(self, readonly: bool) -> None:
        self.timeedit.setReadOnly(readonly)
        if readonly:
            self.timeedit.setButtonSymbols(QAbstractSpinBox.NoButtons)
        else:
            self.timeedit.setButtonSymbols(QAbstractSpinBox.UpDownArrows)

    @pyqtSlot(QTime)
    def timeChangeHandler(self, newtime: QTime) -> None:
        if self.timeedit.hasFocus():
            self.timeChanged.emit(newtime)
Ejemplo n.º 34
0
class MediaCueGeneral(CueGeneral):

    Name = 'Cue Settings'

    def __init__(self, size, cue=None, parent=None):
        super().__init__(size, cue=cue, parent=parent)

        # Start at
        self.startGroup = QGroupBox(self)
        self.startGroup.setLayout(QHBoxLayout())

        self.startEdit = QTimeEdit(self.startGroup)
        self.startEdit.setDisplayFormat('HH.mm.ss.zzz')
        self.startGroup.layout().addWidget(self.startEdit)

        self.startLabel = QLabel(self.startGroup)
        self.startLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.startGroup.layout().addWidget(self.startLabel)

        self.layout().addWidget(self.startGroup)

        # Loop
        self.loopGroup = QGroupBox(self)
        self.loopGroup.setLayout(QHBoxLayout())

        self.spinLoop = QSpinBox(self.loopGroup)
        self.spinLoop.setRange(-1, 1000000)
        self.loopGroup.layout().addWidget(self.spinLoop)

        self.loopLabel = QLabel(self.loopGroup)
        self.loopLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.loopGroup.layout().addWidget(self.loopLabel)

        self.layout().addWidget(self.loopGroup)

        # Checks
        self.checkPause = QCheckBox(self)
        self.layout().addWidget(self.checkPause)

        self.retranslateUi()

    def retranslateUi(self):
        self.startGroup.setTitle('Start time')
        self.startLabel.setText('Amount of skip time')
        self.loopGroup.setTitle("Loop")
        self.loopLabel.setText("Repetition after first play (-1 = infinite)")
        self.checkPause.setText("Enable Pause")

    def get_configuration(self):
        conf = super().get_configuration()
        conf['media'] = {}

        checkable = self.startGroup.isCheckable()

        if not (checkable and not self.startGroup.isChecked()):
            time = self.startEdit.time().msecsSinceStartOfDay()
            conf['media']['start_at'] = time
        if not (checkable and not self.loopGroup.isChecked()):
            conf['media']['loop'] = self.spinLoop.value()
        if self.checkPause.checkState() != QtCore.Qt.PartiallyChecked:
            conf['pause'] = self.checkPause.isChecked()

        return conf

    def enable_check(self, enable):
        super().enable_check(enable)

        self.startGroup.setCheckable(enable)
        self.startGroup.setChecked(False)

        self.loopGroup.setCheckable(enable)
        self.loopGroup.setChecked(False)

        self.checkPause.setTristate(enable)
        if enable:
            self.checkPause.setCheckState(QtCore.Qt.PartiallyChecked)

    def set_configuration(self, conf):
        super().set_configuration(conf)

        if 'pause' in conf:
            self.checkPause.setChecked(conf['pause'])
        if 'media' in conf:
            if 'loop' in conf['media']:
                self.spinLoop.setValue(conf['media']['loop'])
            if 'duration' in conf['media'] and conf['media']['duration'] > 0:
                t = QTime().fromMSecsSinceStartOfDay(conf['media']['duration'])
                self.startEdit.setMaximumTime(t)
            if 'start_at' in conf['media']:
                t = QTime().fromMSecsSinceStartOfDay(conf['media']['start_at'])
                self.startEdit.setTime(t)
Ejemplo n.º 35
0
class MainWindow(PageWindow):
    def __init__(self, dir):
        super().__init__()

        self.storage = firebase.screening()
        try:
            self.ser = serial.Serial(port='COM3',
                                     baudrate=115200,
                                     bytesize=8,
                                     parity='N',
                                     stopbits=1)
        except Exception as ex:

            message = template.format(type(ex).__name__, ex.args)
            print(message)
        self.dirname = dir

        self.seperator_vertical = QVSeperationLine()
        self.seperator_horizontal = QHSeperationLine()
        self.initUI()

        self.setWindowTitle("MainWindow")
        self.overlay = Overlay(self.centralWidget())
        self.available_cameras = QCameraInfo.availableCameras()
        if not self.available_cameras:
            pass  #quit
        self.select_camera(0)

    def initUI(self):
        self.homeUI()

    def homeUI(self):
        self.preview_widget = QWidget()
        self.footer_widget = QWidget()
        self.grid_widget = QWidget()
        self.graph_widget = QWidget()
        self.home = True
        self.viewfinder = QCameraViewfinder()
        self.viewfinder.show()
        self.setCentralWidget(self.viewfinder)
        self.cap = None  #  -capture <-> +cap
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout2 = QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.verticalLayout = QVBoxLayout()
        self.chartLayout = QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.image_label = QLabel()
        self.image_label.setText("")
        self.image_label.setObjectName("image_label")
        self.image_label.setStyleSheet("QLabel { margin-right:4px;  }")

        self.temp = QLabel()
        self.temp.setText("TEMPERATURE : ")
        self.temp.setObjectName("temp")
        self.temp.setFont(QFont("Gadugi", 15, weight=QFont.Bold))
        #self.temp.setAlignment(QtCore.Qt.AlignCenter)
        self.temp_reading = QLabel()
        self.temp_reading.setText("READING...")
        self.temp_reading.setObjectName("temp_reading")
        self.temp_reading.setFont(QFont("Gadugi", 15, weight=QFont.Bold))
        #self.temp_reading.setAlignment(QtCore.Qt.AlignCenter)

        self.temp2 = QLabel()
        self.temp2.setText("ROOM READING : ")
        self.temp2.setFont(QFont("Gadugi", 15, weight=QFont.Bold))
        self.temp2.setObjectName("temp2")
        #self.temp2.setAlignment(QtCore.Qt.AlignCenter)

        self.temp2_reading = QLabel()
        self.temp2_reading.setText("READING...")
        self.temp2_reading.setFont(QFont("Gadugi", 15, weight=QFont.Bold))
        #self.temp2_reading.setAlignment(QtCore.Qt.AlignCenter)
        self.temp2_reading.setObjectName("temp2_reading")

        self.image_label.setScaledContents(True)

        self.matplotlibWidget = MatplotlibWidget(self)
        self.threadSample = ThreadSample(self)
        self.threadSample.newSample.connect(self.on_threadSample_newSample)
        self.threadSample.finished.connect(self.on_threadSample_finished)

        self.gridLayout = QGridLayout(self)
        self.gridLayout.addWidget(self.temp, 0, 0, 1, 1)
        self.gridLayout.addWidget(self.temp_reading, 0, 1, 1, 3)
        self.gridLayout.addWidget(self.temp2, 2, 0, 1, 1)
        self.gridLayout.addWidget(self.temp2_reading, 2, 1, 1, 3)
        self.clock(self.gridLayout, 3, 0, 3, 3)

        self.grid_widget.setLayout(self.gridLayout)
        self.grid_widget.setMinimumHeight(250)
        self.grid_widget.setMaximumHeight(250)
        self.grid_widget.setMinimumWidth(600)
        self.grid_widget.setMaximumWidth(600)

        self.horizontalLayout.addWidget(self.image_label)
        #self.horizontalLayout.addWidget(self.seperator_vertical)
        self.horizontalLayout.addWidget(self.graph_widget)

        self.preview_widget.setLayout(self.horizontalLayout)
        self.preview_widget.setMinimumHeight(200)
        self.preview_widget.setMaximumHeight(200)
        self.preview_widget.setMinimumWidth(600)
        self.preview_widget.setMaximumWidth(600)

        # self.chartLayout.addWidget(self.matplotlibWidget)
        # self.graph_widget.setLayout(self.chartLayout)
        self.graph_widget.setMinimumHeight(250)
        self.graph_widget.setMaximumHeight(250)
        self.graph_widget.setMinimumWidth(250)
        self.graph_widget.setMaximumWidth(250)

        self.horizontalLayout2.addWidget(self.grid_widget)
        #         self.horizontalLayout2.addWidget(self.seperator_vertical)
        #self.horizontalLayout2.addWidget(self.clock)
        #self.clock(self.horizontalLayout2)

        self.footer_widget.setLayout(self.horizontalLayout2)
        self.footer_widget.setMinimumHeight(250)
        self.footer_widget.setMaximumHeight(250)
        self.footer_widget.setMinimumWidth(600)
        self.footer_widget.setMaximumWidth(600)

        self.verticalLayout.addWidget(self.preview_widget)
        self.verticalLayout.addWidget(self.seperator_horizontal)
        self.verticalLayout.addWidget(self.footer_widget)
        #self.verticalLayout.addWidget(self.image_label2)

        self.timer = QTimer(self, interval=5)
        self.timer.timeout.connect(self.update_frame)
        self._image_counter = 0
        centralWidget = QWidget(self)
        self.setCentralWidget(centralWidget)
        self.centralWidget().setLayout(self.verticalLayout)
        self.start_webcam()
        self.update_frame()
        #         self.setCentralWidget(self.scroll)
        self.setGeometry(300, 300, 400, 700)
        thread = Thread(target=self.read_temp)
        thread.daemon = True
        thread.start()

    def select_camera(self, i):
        self.camera = QCamera(self.available_cameras[i])
        self.camera.setViewfinder(self.viewfinder)
        self.camera.setCaptureMode(QCamera.CaptureStillImage)
        self.camera.error.connect(
            lambda: self.alert(self.camera.errorString()))
        self.camera.start()

        self.capture = QCameraImageCapture(self.camera)
        self.capture.error.connect(lambda i, e, s: self.alert(s))
        self.capture.imageCaptured.connect(lambda d, i: self.statusmessage(
            "Image %04d captured" % self.save_seq))

        self.current_camera_name = self.available_cameras[i].description()
        self.save_seq = 0

    def read_temp(self):
        temp = []
        while True:
            self.ser.write(b'0x55,0xAA,5,1,4')
            response = self.ser.readline()
            print(str(response))
            if 'body' in str(response):
                temp.append(str(response))
                #print("temp-"+str(response))
                #print(temp)
            elif 'Vbat' in str(response):
                if len(temp) != 0:

                    temp[1] = temp[1].replace('b\'T body =', '')
                    temp[1] = temp[1].replace("\\r\\n'", '')
                    temp[0] = temp[0].replace('b\'T body =', '')
                    temp[0] = temp[0].replace("compensate\\r\\n'", '')
                    self.findFaces('-'.join(temp))
                    self.update_label(temp[0], temp[1], '12')
                temp = []
                time.sleep(1)

        # start = time.clock()
        # while True:
        #     if True:
        #         if True:
        #             temp.append(str(random.randint(0,100)))
        #             temp.append(str(random.randint(0,100)))
        #             self.overlay.show()
        #             self.findFaces('-'.join(temp))
        #             self.update_label(temp[0],temp[1],'12')
        #             self.overlay.hide()

        #             print("Done-"+ ' '.join(temp))

        #         temp = []
        #         time.sleep(1)

    def statusmessage(self, msg):
        self.statusBar().showMessage(msg)

    def update_label(self, temp1, temp2, time):
        print(temp1)
        temp2 = self.getTemp(str(temp2))
        temp1 = self.getTemp(str(temp1))
        if temp2 >= 36.1 and temp2 <= 37.2:
            pal = self.temp_reading.palette()
            pal.setColor(QPalette.WindowText, QColor("green"))
            self.temp_reading.setPalette(pal)
        else:
            pal = self.temp_reading.palette()
            pal.setColor(QPalette.WindowText, QColor("red"))
            self.temp_reading.setPalette(pal)

#         if temp2>=36.1 and temp2<=37.2:
#             pal = self.temp_reading.palette()
#             pal.setColor(QPalette.WindowText, QColor("black"))
#             self.temp2_reading.setPalette(pal)
#         else:
#             pal = self.temp_reading.palette()
#             pal.setColor(QPalette.WindowText, QColor("black"))
#             self.temp2_reading.setPalette(pal)

        self.temp_reading.setText(str(temp2) + " °C")

        self.temp2_reading.setText(str(temp1) + " °C")
        #self.temp2_reading.setColor(QPalette.WindowText, QtGui.QColor("red"))

    def getTemp(self, inp):
        temp = re.findall(r"[-+]?\d*\.\d+|\d+", inp)
        temp = ''.join(temp)
        if temp == '':
            return 0
        else:
            return float(temp)

    def filter(self, text):

        text = text.replace('bTbody', 'body')
        text = text.replace('\'', '')

        text = text.replace('\\r\n\'b\'Tbody', '-')
        text = text.replace('\\r', '')
        text = text.replace('\r', '')
        text = text.replace('\\xa8', '')
        text = text.replace('\\xa1\\xe6', '')
        text = text.replace('\\n', '-')
        text = text.replace(' ', '')
        text = text.replace(', ', ',')
        text = text.replace('=', '_')
        text = text.replace(',', '-')
        return text

    def alert(self, s):
        """
        Handle errors coming from QCamera dn QCameraImageCapture by displaying alerts.
        """
        err = QErrorMessage(self)
        err.showMessage(s)

    @QtCore.pyqtSlot()
    def start_webcam(self):
        if self.cap is None:
            self.cap = cv2.VideoCapture(0)
            self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
            self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
        self.timer.start()

    def start_cam(self):
        self.cap.open(0)

    def stop_webcam(self):
        self.cap.release()

    def closeEvent(self, event):
        print("closing PyQtTest")
        self.cap.close()

    @QtCore.pyqtSlot()
    def update_frame(self):
        if self.cap.isOpened():
            ret, image = self.cap.read()
            #self.face_detect(image,file_name)
            simage = cv2.flip(image, 1)
            self.displayImage(image, True)

    def findFaces(self, file_name):
        face_detect = True
        while face_detect:
            if self.cap.isOpened():
                ret, frame = self.cap.read()
                face_locations = fl(frame)

                print("I found {} face(s) in this photograph.".format(
                    len(face_locations)))
                #self.statusmessage("I found {} face(s) in this photograph.".format(len(face_locations)))
                for face_location in face_locations:
                    face_detect = False
                    # Print the location of each face in this image
                    top, right, bottom, left = face_location
                    print(
                        "A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}"
                        .format(top, left, bottom, right))
                    # ts = time.time()
                    # You can access the actual face itself like this:
                    face_image = frame[top - 100:bottom + 100,
                                       left - 100:right + 100]
                    ts = datetime.now().strftime('%Y_%m_%d-%H_%M_%S')
                    cv2.imwrite(
                        os.path.abspath(
                            os.path.join(self.dirname,
                                         (ts + '-' + file_name + '.jpg'))),
                        face_image)
                    self.storage.upload(self.dirname,
                                        (ts + '-' + file_name + '.jpg'))

    def face_detect(self, file_name):

        face_locations = []
        face_encodings = []
        face_names = []
        process_this_frame = True
        i = 0
        face_detect = True
        # Resize frame of video to 1/4 size for faster face recognition processing
        while face_detect:
            ret, frame = self.cap.read()
            #self.face_detect(image,file_name)
            #simage     = cv2.flip(image, 1)
            small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)

            # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
            rgb_small_frame = small_frame[:, :, ::-1]

            # Only process every other frame of video to save time
            if process_this_frame:
                # Find all the faces and face encodings in the current frame of video
                face_locations = face_recognition.face_locations(
                    rgb_small_frame)
                face_encodings = face_recognition.face_encodings(
                    rgb_small_frame, face_locations)

                face_names = []
                for face_encoding in face_encodings:
                    # See if the face is a match for the known face(s)
                    face_detect = False
                    name = "Unknown"
                    cv2.imwrite(
                        os.path.abspath(
                            os.path.join(
                                self.dirname,
                                (datetime.today().strftime('%Y-%m-%d') + '-' +
                                 file_name + '-' + str(++i) + '.png'))), frame)
                    #self.storage.upload(self.dirname,(datetime.today().strftime('%Y-%m-%d')+'-'+file_name+'-'+str(i)+'.png'))

                    i = i + 1

                    print("I see someone named {}!".format(name))
                    # # If a match was found in known_face_encodings, just use the first one.
                    # if True in matches:
                    #     first_match_index = matches.index(True)
                    #     name = known_face_names[first_match_index]

                    # Or instead, use the known face with the smallest distance to the new face

                    process_this_frame = not process_this_frame

    @QtCore.pyqtSlot()
    def capture_image(self):
        if self.cap.isOpened():
            flag, frame = self.cap.read()
            timestamp = time.strftime("%d-%b-%Y-%H_%M_%S")

            self.save_seq += 1

            path = self.dirname  #
            if flag:
                QtWidgets.QApplication.beep()
                name = "my_image.jpg"
                cv2.imwrite(
                    os.path.join(
                        self.dirname, "%s-%04d-%s.jpg" %
                        (self.current_camera_name, self.save_seq, timestamp)),
                    frame)
                self.alert('Image Store Successfully.')
                self._image_counter += 1

    def displayImage(self, img, window=True):
        qformat = QImage.Format_Indexed8
        if len(img.shape) == 3:
            if img.shape[2] == 4:
                qformat = QImage.Format_RGBA8888
            else:
                qformat = QImage.Format_RGB888
        outImage = QImage(img, img.shape[1], img.shape[0], img.strides[0],
                          qformat)
        outImage = outImage.rgbSwapped()
        if window:
            self.image_label.setStyleSheet("""
        QLabel {
            height:300px !important;
            
            }
        """)

            self.image_label.setPixmap(QPixmap.fromImage(outImage))

    def clock(self, layout, row, col, row_span, col_span):
        self.verticalLayoutClock = QVBoxLayout(self)
        self.dateEdit = QDateEdit(self)
        self.dateEdit.setDisplayFormat("MMM dd yyyy")
        self.dateEdit.setDisabled(True)
        self.verticalLayoutClock.addWidget(self.dateEdit)
        self.timeEdit = QTimeEdit(self)
        self.timeEdit.setDisplayFormat("hh:mm:ss AP")
        self.timeEdit.setDisabled(True)
        self.verticalLayoutClock.addWidget(self.timeEdit)
        self.updateTime()
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.updateTime)
        self.timer.start(1000)
        layout.addLayout(self.verticalLayoutClock, row, col, row_span,
                         col_span)

    @QtCore.pyqtSlot(list)
    def on_threadSample_newSample(self, sample):
        self.matplotlibWidget.axis.plot(sample)
        self.matplotlibWidget.canvas.draw()

    @QtCore.pyqtSlot()
    def on_threadSample_finished(self):
        self.samples += 1
        if self.samples <= 2:
            self.threadSample.start()

    @QtCore.pyqtSlot()
    def on_pushButtonPlot_clicked(self):
        self.samples = 0
        self.matplotlibWidget.axis.clear()
        self.threadSample.start()

    def updateTime(self):
        current = QtCore.QDateTime.currentDateTime()
        self.dateEdit.setDate(current.date())
        self.timeEdit.setTime(current.time())
Ejemplo n.º 36
0
    def setupTab2(self, tab2):
        """Special widgets for preview panel"""
        scrollContainer = QVBoxLayout()
        scrollArea = QScrollArea()
        scrollArea.setWidgetResizable(True)
        mainWidget = QWidget()
        layout = QVBoxLayout()
        mainWidget.setLayout(layout)
        mainWidget.setMinimumSize(QSize(420, 800))
        scrollArea.setWidget(mainWidget)
        scrollContainer.addWidget(scrollArea)
        tab2.setLayout(scrollContainer)

        # Dialog
        group0 = QGroupBox("Dialog")
        group1Layout = QVBoxLayout()
        layoutRow1 = QHBoxLayout()
        layoutRow2 = QHBoxLayout()
        group1Layout.addLayout(layoutRow1)
        group1Layout.addLayout(layoutRow2)
        group0.setLayout(group1Layout)
        layout.addWidget(group0)

        b1 = QPushButton(self.tr("Info"))
        b1.clicked.connect(lambda: QMessageBox.information(
            self, "Info", self.tr("This is a message."), QMessageBox.Ok,
            QMessageBox.Ok))
        b2 = QPushButton(self.tr("Question"))
        b2.clicked.connect(lambda: QMessageBox.question(
            self, "question", self.tr("Are you sure?"), QMessageBox.No |
            QMessageBox.Yes, QMessageBox.Yes))
        b3 = QPushButton(self.tr("Warning"))
        b3.clicked.connect(lambda: QMessageBox.warning(
            self, "warning", self.tr("This is a warning."), QMessageBox.No |
            QMessageBox.Yes, QMessageBox.Yes))
        b4 = QPushButton(self.tr("Error"))
        b4.clicked.connect(lambda: QMessageBox.critical(
            self, "error", self.tr("It's a error."), QMessageBox.No |
            QMessageBox.Yes, QMessageBox.Yes))
        b5 = QPushButton(self.tr("About"))
        b5.clicked.connect(lambda: QMessageBox.about(
            self, "about", self.tr("About this software")))
        b6 = QPushButton(self.tr("Input"))  # ,"输入对话框"))
        b6.clicked.connect(lambda: QInputDialog.getInt(
            self, self.tr("input"), self.tr("please input int")))
        b6.clicked.connect(lambda: QInputDialog.getDouble(
            self, self.tr("input"), self.tr("please input float")))
        b6.clicked.connect(lambda: QInputDialog.getItem(
            self, self.tr("input"), self.tr("please select"), ["aaa", "bbb"]))
        b7 = QPushButton(self.tr("Color"))  # ,"颜色对话框"))
        b7.clicked.connect(lambda: QColorDialog.getColor())
        b8 = QPushButton(self.tr("Font"))  # ,"字体对话框"))
        b8.clicked.connect(lambda: QFontDialog.getFont())
        b9 = QPushButton(self.tr("OpenFile"))  # ,"打开对话框"))
        b9.clicked.connect(lambda: QFileDialog.getOpenFileName(
            self, "open", "", "Text(*.txt *.text)"))
        b10 = QPushButton(self.tr("SaveFile"))  # ,"保存对话框"))
        b10.clicked.connect(lambda: QFileDialog.getSaveFileName())
        layoutRow1.addWidget(b1)
        layoutRow1.addWidget(b2)
        layoutRow1.addWidget(b3)
        layoutRow1.addWidget(b4)
        layoutRow1.addWidget(b5)
        layoutRow2.addWidget(b6)
        layoutRow2.addWidget(b7)
        layoutRow2.addWidget(b8)
        layoutRow2.addWidget(b9)
        layoutRow2.addWidget(b10)

        # DateTime
        group1 = QGroupBox("DateTime")
        group1.setCheckable(True)
        group1Layout = QHBoxLayout()
        layoutRow1 = QVBoxLayout()
        layoutRow2 = QVBoxLayout()
        group1Layout.addLayout(layoutRow1)
        group1Layout.addLayout(layoutRow2)
        group1.setLayout(group1Layout)
        layout.addWidget(group1)

        group1.setMaximumHeight(240)
        dt1 = QDateEdit()
        dt1.setDate(QDate.currentDate())
        dt2 = QTimeEdit()
        dt2.setTime(QTime.currentTime())
        dt3 = QDateTimeEdit()
        dt3.setDateTime(QDateTime.currentDateTime())
        dt4 = QDateTimeEdit()
        dt4.setCalendarPopup(True)
        dt5 = QCalendarWidget()
        dt5.setMaximumSize(QSize(250, 240))
        layoutRow1.addWidget(dt1)
        layoutRow1.addWidget(dt2)
        layoutRow1.addWidget(dt3)
        layoutRow1.addWidget(dt4)
        layoutRow2.addWidget(dt5)

        # Slider
        group2 = QGroupBox("Sliders")
        group2.setCheckable(True)
        group2Layout = QVBoxLayout()
        layoutRow1 = QHBoxLayout()
        layoutRow2 = QHBoxLayout()
        group2Layout.addLayout(layoutRow1)
        group2Layout.addLayout(layoutRow2)
        group2.setLayout(group2Layout)
        layout.addWidget(group2)

        slider = QSlider()
        slider.setOrientation(Qt.Horizontal)
        slider.setMaximum(100)
        progress = QProgressBar()
        slider.valueChanged.connect(progress.setValue)
        slider.setValue(50)
        scroll1 = QScrollBar()
        scroll2 = QScrollBar()
        scroll3 = QScrollBar()
        scroll1.setMaximum(255)
        scroll2.setMaximum(255)
        scroll3.setMaximum(255)
        scroll1.setOrientation(Qt.Horizontal)
        scroll2.setOrientation(Qt.Horizontal)
        scroll3.setOrientation(Qt.Horizontal)
        c = QLabel(self.tr("Slide to change color"))  # , "拖动滑块改变颜色"))
        c.setAutoFillBackground(True)
        c.setAlignment(Qt.AlignCenter)
        # c.setStyleSheet("border:1px solid gray;")
        c.setStyleSheet("background:rgba(0,0,0,100);")

        def clr():
            # clr=QColor(scroll1.getValue(),scroll2.getValue(),scroll3.getValue(),100)
            # p=QPalette()
            # p.setColor(QPalette.Background,clr)
            # c.setPalette(p)
            c.setStyleSheet("background: rgba({},{},{},100);".format(
                scroll1.value(), scroll2.value(), scroll3.value()))

        scroll1.valueChanged.connect(clr)
        scroll2.valueChanged.connect(clr)
        scroll3.valueChanged.connect(clr)
        scroll1.setValue(128)
        layoutRow1.addWidget(slider)
        layoutRow1.addWidget(progress)
        layCol1 = QVBoxLayout()
        layCol1.addWidget(scroll1)
        layCol1.addWidget(scroll2)
        layCol1.addWidget(scroll3)
        layoutRow2.addLayout(layCol1)
        layoutRow2.addWidget(c)

        # Meter
        group3 = QGroupBox("Meters")
        group3.setCheckable(True)
        layRow = QHBoxLayout()
        group3.setLayout(layRow)
        layout.addWidget(group3)

        dial1 = QDial()
        dial2 = QDial()
        dial2.setNotchesVisible(True)
        dial1.valueChanged.connect(dial2.setValue)
        layRow.addWidget(dial1)
        layRow.addWidget(dial2)

        layout.addStretch(1)