Exemplo n.º 1
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())
Exemplo n.º 2
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())
Exemplo n.º 3
0
class EditSMSLink(QDialog):
    def __init__(self, sms_data, *args, **kwargs):
        super(EditSMSLink, self).__init__(*args, **kwargs)
        layout = QVBoxLayout(margin=0)
        print(sms_data)
        self.sms_id = sms_data['id']
        # 时间布局
        date_time_layout = QHBoxLayout()
        self.date_edit = QDateEdit(QDate.fromString(sms_data['date'], 'yyyy-MM-dd'))
        self.date_edit.setCalendarPopup(True)
        self.date_edit.setDisplayFormat('yyyy-MM-dd')
        date_time_layout.addWidget(QLabel('日期:'))
        date_time_layout.addWidget(self.date_edit)
        date_time_layout.addWidget(QLabel('时间:'))
        self.time_edit = QTimeEdit(QTime.fromString(sms_data['time'], 'HH:mm:ss'))
        self.time_edit.setDisplayFormat('HH:mm:ss')
        date_time_layout.addWidget(self.time_edit)
        date_time_layout.addStretch()
        layout.addLayout(date_time_layout)
        self.show_tips = QLabel()
        self.text_edit = QTextEdit(textChanged=self.set_show_tips_null)
        self.text_edit.setPlainText(sms_data['content'])
        layout.addWidget(self.text_edit)
        layout.addWidget(self.show_tips)
        layout.addWidget(QPushButton('确定', clicked=self.commit_sms_edited), alignment=Qt.AlignRight)
        self.setLayout(layout)
        self.resize(420, 240)
        self.setWindowTitle('编辑短信通')

    def set_show_tips_null(self):
        self.show_tips.setText('')

    # 确定提交修改
    def commit_sms_edited(self):
        text = self.text_edit.toPlainText().strip(' ')
        if not text:
            self.show_tips.setText('请输入内容。')
            return
        # 提交
        try:
            r = requests.put(
                url=settings.SERVER_ADDR + 'info/sms/' + str(self.sms_id) + '/?mc=' + settings.app_dawn.value('machine'),
                headers={'AUTHORIZATION': settings.app_dawn.value('AUTHORIZATION')},
                data=json.dumps({
                    'date': self.date_edit.text(),
                    'time': self.time_edit.text(),
                    'content': text
                })
            )
            response = json.loads(r.content.decode('utf-8'))
            if r.status_code != 201:
                raise ValueError(response['message'])
        except Exception as e:
            QMessageBox.information(self, '错误', str(e))
        else:
            QMessageBox.information(self,'成功', '修改成功!')
            self.close()
Exemplo n.º 4
0
class CreateNewTradePolicyPopup(QDialog):
    def __init__(self, *args, **kwargs):
        super(CreateNewTradePolicyPopup, self).__init__(*args, **kwargs)
        layout = QVBoxLayout(margin=0)
        # 时间布局
        date_time_layout = QHBoxLayout()
        self.date_edit = QDateEdit(QDate.currentDate())
        self.date_edit.setCalendarPopup(True)
        self.date_edit.setDisplayFormat('yyyy-MM-dd')
        date_time_layout.addWidget(QLabel('日期:'))
        date_time_layout.addWidget(self.date_edit)
        date_time_layout.addWidget(QLabel('时间:'))
        self.time_edit = QTimeEdit(QTime.currentTime())
        self.time_edit.setDisplayFormat('HH:mm:ss')
        date_time_layout.addWidget(self.time_edit)
        date_time_layout.addStretch()
        layout.addLayout(date_time_layout)
        self.text_edit = QTextEdit(textChanged=self.set_show_tips_null)
        layout.addWidget(self.text_edit)
        self.show_tips = QLabel()
        layout.addWidget(self.show_tips)
        layout.addWidget(QPushButton('确定', clicked=self.commit_trade_policy), alignment=Qt.AlignRight)
        self.setLayout(layout)
        self.resize(400, 200)
        self.setWindowTitle('新建短信通')

    def set_show_tips_null(self):
        self.show_tips.setText('')

    # 确定增加
    def commit_trade_policy(self):
        text = self.text_edit.toPlainText().strip(' ')
        if not text:
            self.show_tips.setText('请输入内容。')
            return
        # 提交
        try:
            r = requests.post(
                url=settings.SERVER_ADDR + 'info/trade-policy/?mc=' + settings.app_dawn.value('machine'),
                headers={'AUTHORIZATION': settings.app_dawn.value('AUTHORIZATION')},
                data=json.dumps({
                    'date': self.date_edit.text(),
                    'time': self.time_edit.text(),
                    'content': text
                })
            )
            response = json.loads(r.content.decode('utf-8'))
            if r.status_code != 201:
                raise ValueError(response['message'])
        except Exception as e:
            self.show_tips.setText(str(e))
        else:
            self.show_tips.setText(response['message'])
Exemplo n.º 5
0
class CreateNewSMSLink(QDialog):
    def __init__(self, *args, **kwargs):
        super(CreateNewSMSLink, self).__init__(*args, **kwargs)
        self.setAttribute(Qt.WA_DeleteOnClose)
        layout = QVBoxLayout()
        # 时间布局
        date_time_layout = QHBoxLayout()
        self.date_edit = QDateEdit(QDate.currentDate())
        self.date_edit.setCalendarPopup(True)
        self.date_edit.setDisplayFormat('yyyy-MM-dd')
        date_time_layout.addWidget(QLabel('日期:'))
        date_time_layout.addWidget(self.date_edit)
        date_time_layout.addWidget(QLabel('时间:'))
        self.time_edit = QTimeEdit(QTime.currentTime())
        self.time_edit.setDisplayFormat('HH:mm:ss')
        date_time_layout.addWidget(self.time_edit)
        date_time_layout.addStretch()
        layout.addLayout(date_time_layout)
        self.text_edit = QTextEdit()
        layout.addWidget(self.text_edit)
        layout.addWidget(QPushButton('确定', clicked=self.commit_sms), alignment=Qt.AlignRight)
        self.setLayout(layout)
        self.setFixedSize(400, 200)
        self.setWindowTitle('新建短信通')


    # 确定增加
    def commit_sms(self):
        text = self.text_edit.toPlainText().strip()
        if not text:
            QMessageBox.information(self,'错误', '请输入内容。')
            return
        # 提交
        try:
            r = requests.post(
                url=settings.SERVER_ADDR + 'advise/shortmessage/',
                headers={'Content-Type': 'application/json;charset=utf8'},
                data=json.dumps({
                    'utoken':settings.app_dawn.value('AUTHORIZATION'),
                    'custom_time': self.date_edit.text() + ' ' + self.time_edit.text(),
                    'content': text
                })
            )
            response = json.loads(r.content.decode('utf-8'))
            if r.status_code != 201:
                raise ValueError(response['message'])
        except Exception as e:
            QMessageBox.information(self,'错误', str(e))
        else:
            QMessageBox.information(self,'成功', "新增成功")
            self.close()
    def addRemoveInvoiceTIme(self):
        self.toolFrame = QFrame()
        self.toolFrame.setWindowTitle("Platinum Sql Date Corrector")
        self.toolFrame.setWindowIcon(QIcon("C:\Platinum\Icons\icon_p.ico"))
        self.toolFrame.resize(600, 300)

        startDate = QDateEdit()
        startDate.setDisplayFormat("yyyy-MM-dd")
        startTime = QTimeEdit()
        startTime.setDisplayFormat("HH:mm:ss")

        endDate = QDateEdit()
        endDate.setDisplayFormat("yyyy-MM-dd")
        endTime = QTimeEdit()
        endTime.setDisplayFormat("HH:mm:ss")

        timeToAdd = QTimeEdit()
        timeToAdd.setDisplayFormat("HH:mm:ss")

        runButton = QPushButton("Add Script")
        runButton.clicked.connect(
            lambda: self.runScript(startDate.text(), startTime.text(
            ), endDate.text(), endTime.text(), timeToAdd.text()))

        subTractScript = QPushButton("Subtract Script")
        subTractScript.clicked.connect(
            lambda: self.runScript2(startDate.text(), startTime.text(
            ), endDate.text(), endTime.text(), timeToAdd.text()))

        maingrid = QGridLayout()
        maingrid.addWidget(QLabel("Start Date"), 0, 0)
        maingrid.addWidget(startDate, 0, 1)
        maingrid.addWidget(QLabel("Start Time"), 1, 0)
        maingrid.addWidget(startTime, 1, 1)
        maingrid.addWidget(QLabel("End Date"), 0, 2)
        maingrid.addWidget(endDate, 0, 3)
        maingrid.addWidget(QLabel("End Time"), 1, 2)
        maingrid.addWidget(endTime, 1, 3)
        maingrid.addWidget(QLabel("Time"), 2, 0)
        maingrid.addWidget(timeToAdd, 2, 1)
        maingrid.addWidget(runButton, 3, 0, 1, 4)
        maingrid.addWidget(subTractScript, 4, 0, 1, 4)

        self.toolFrame.setLayout(maingrid)
        self.toolFrame.show()
Exemplo n.º 7
0
class AddBookingDetails(QMainWindow):

    closing = pyqtSignal(int)

    def __init__(self, parent, update, id=None):
        super().__init__(parent)

        self.db = DB()

        self.initUI(update, id)

    def initUI(self, update, id):

        self.setWindowModality(Qt.ApplicationModal)

        frame = QFrame()
        # frame.setStyleSheet("background-color: rgb(30, 45, 66);")
        frame.setFrameShape(QFrame.StyledPanel)
        frame.setFrameShadow(QFrame.Raised)
        # frame.setMinimumWidth(430)
        # frame.setFixedHeight(395)
        # frame.setStyleSheet("border: none")

        add_booking_button = QLabel(frame)
        add_booking_button.setAlignment(Qt.AlignCenter)
        add_booking_button.setGeometry(QRect(110, 30, 210, 41))
        add_booking_button.setStyleSheet("font: 75 12pt \"MS Shell Dlg 2\";\n"
                                         "background-color: rgb(30, 45, 66);\n"
                                         "color: rgb(255, 255, 255);")
        add_booking_button.setText("Add Reservation Details")

        # tablelabel = QLabel(frame)
        # tablelabel.setText("Table")
        # tablelabel.setGeometry(QRect(50, 120, 81, 20))
        #
        # tabletextbox = QComboBox(frame)
        # tabletextbox.setGeometry(QRect(170, 110, 181, 31))
        # tabletextbox.setFixedWidth(180)
        # tabletextbox.addItems(["Table 1", "Table 2"])

        customernamelabel = QLabel(frame)
        customernamelabel.setText("Customer Name")
        customernamelabel.setGeometry(QRect(50, 120, 100, 20))

        self.customernametextbox = QLineEdit(frame)
        self.customernametextbox.setGeometry(QRect(170, 110, 181, 31))
        self.customernametextbox.setFixedWidth(180)

        customercontactlabel = QLabel(frame)
        customercontactlabel.setText("Customer Contact")
        customercontactlabel.setGeometry(QRect(50, 160, 145, 19))

        self.customercontacttextbox = QLineEdit(frame)
        self.customercontacttextbox.setGeometry(QRect(170, 150, 181, 31))
        self.customercontacttextbox.setFixedWidth(180)

        datelabel = QLabel(frame)
        datelabel.setText("Date")
        datelabel.setGeometry(QRect(50, 200, 145, 19))

        self.datetextbox = QDateEdit(frame)
        self.datetextbox.setGeometry(QRect(170, 190, 181, 31))
        self.datetextbox.setFixedWidth(180)
        self.datetextbox.setDate(QDate.currentDate())
        self.datetextbox.setMinimumDate(QDate.currentDate())
        self.datetextbox.setDisplayFormat("dd-MM-yyyy")

        starttimelabel = QLabel(frame)
        starttimelabel.setText("Start Time")
        starttimelabel.setGeometry(QRect(50, 240, 121, 16))

        self.starttimetextbox = QTimeEdit(frame)
        self.starttimetextbox.setGeometry(QRect(170, 230, 181, 31))
        self.starttimetextbox.setFixedWidth(180)
        # self.starttimetextbox.setTime(QDate.currentDate())
        # self.starttimetextbox.setMinimumDate(QDate.currentDate())

        self.addbutton = QPushButton(frame)
        self.addbutton.setText("Add Booking")
        self.addbutton.setGeometry(QRect(160, 300, 151, 31))
        self.addbutton.setStyleSheet("font: 75 12pt \"MS Shell Dlg 2\";\n"
                                     "background-color: rgb(30, 45, 66);\n"
                                     "color: rgb(255, 255, 255);")
        # self.addbutton.clicked.connect(lambda: self.add_button_click("reservations"))

        if update == 'add':
            print("Add")
            print(id)
            self.addbutton.setText("Add Reservation")
            self.addbutton.clicked.connect(
                lambda: self.add_button_click("reservations"))
        else:
            print("Update")
            print(id)
            self.addbutton.setText("Update Reservation")
            self.addbutton.clicked.connect(
                lambda: self.update_button_click("reservations", id))

        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(frame)

        centralWidget = QWidget()
        centralWidget.setLayout(layout)

        self.setCentralWidget(centralWidget)

        # self.setLayout(layout)

        self.setWindowTitle("Add Reservation Details")
        self.resize(430, 395)
        self.show()

        self.center()

    def center(self):
        '''centers the window on the screen'''
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width() - size.width()) / 2,
                  (screen.height() - size.height()) / 2)

    def update_button_click(self, where, id):
        if where == "reservations":
            print("Tables Finally here")

            customer_name = self.customernametextbox.text()
            customer_contact = self.customercontacttextbox.text()
            start_time = self.starttimetextbox.text()

            try:
                date = datetime.datetime.strptime(self.datetextbox.text(),
                                                  "%d-%m-%Y")
                booking_date = datetime.datetime.strftime(date, "%Y-%m-%d")
            except Exception as e:
                ''' Make sure to add an error message. '''
                print(e)
                return

            if customer_name != "" and customer_contact != "":

                query = "update customerBooking set `customer_name`=%s, " \
                        "`phone_number`=%s, `booking_date`=concat(%s, ' ', %s)" \
                        "where id=%s;"
                values = (customer_name, customer_contact, booking_date,
                          start_time, id)

                result = self.db.execute(query, values)

                self.closeEvent = self.message()

    def add_button_click(self, where):
        if where == "reservations":
            print("Finally here")

            customer_name = self.customernametextbox.text()
            customer_contact = self.customercontacttextbox.text()
            start_time = self.starttimetextbox.text()

            try:
                date = datetime.datetime.strptime(self.datetextbox.text(),
                                                  "%d-%m-%Y")
                booking_date = datetime.datetime.strftime(date, "%Y-%m-%d")
            except Exception as e:
                ''' Make sure to add an error message. '''
                print(e)
                return

            if customer_name != "" and customer_contact != "":

                print("Got Here")

                query = "insert into customerBooking (`customer_name`, `phone_number`, `booking_date`)" \
                        "values (%s, %s, concat(%s, ' ', %s));"
                values = (customer_name, customer_contact, booking_date,
                          start_time)

                result = self.db.execute(query, values)

                self.closeEvent = self.message()

    def message(self):
        self.closing.emit(1)
        self.close()
Exemplo n.º 8
0
    def showDialog(self,
                   block,
                   show_calendar: bool = True,
                   date: QDate = None):
        """
        this will show the user a dialog of the the reminders
        :param block: Element to block by dialog
        :param show_calendar: Whether to include calendar or not
        :param date: Pre-defined date if calendar is not shown
        """
        logging.info("showDialog: displays reminders dialog")

        # Set the default date format

        format_date_def: str = "yyyy-MM-dd"
        # ------------------------------#
        input_title = QLineEdit()
        input_title.setPlaceholderText("Title")
        # ------------------------------#

        # ------------------------------#
        # QPlain text edit allows text on multiple lines
        input_description = QPlainTextEdit()
        input_description.setMaximumHeight(120)

        def limitCharCount():
            """
            Limits the maximum number of characters allowed in description box
            """
            # Limits the number of characters in input_description box
            text_content = input_description.toPlainText()
            length = len(text_content)
            max_length = 150
            if length > max_length:
                logging.info("Description too long!")
                # Get the cursor and position
                cursor = input_description.textCursor()
                position = cursor.position()
                # Strip the text and set
                new_text = text_content[:max_length]
                input_description.setPlainText(new_text)
                # Restore cursor position
                cursor.setPosition(position - 1)
                input_description.setTextCursor(cursor)

        # Assign text limit listener
        input_description.textChanged.connect(limitCharCount)
        input_description.setPlaceholderText("Description")
        # ------------------------------#

        # ------------------------------#
        input_calendar = CalendarWidget()
        input_time = QTimeEdit()

        def updateTitle():
            """
            Updates title of the dialog box to selected date and time
            """
            new_date: QDate = input_calendar.selectedDate()
            formatted_date = new_date.toString(format_date_def)
            new_time: QTime = input_time.time()
            formatted_time = new_time.toString("h:mm ap")
            new_title = formatted_date + " at " + formatted_time

            logging.debug("Update input_title %s", new_title)
            dialog.setTitleText(new_title)

        input_calendar.setFixedHeight(300)
        input_calendar.selectionChanged.connect(updateTitle)
        input_time.timeChanged.connect(updateTitle)
        # initial update of title with default values

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

        dialog = DialogBuilder(block, "Add reminder")

        dialog.addWidget(input_title)
        dialog.addWidget(input_description)

        # Determine whether to use calendar in dialog or not
        if show_calendar is True or date is None:
            dialog.addWidget(input_calendar)
        else:
            input_calendar.setSelectedDate(date)
        dialog.addWidget(input_time)
        updateTitle()

        button_box = QDialogButtonBox(QDialogButtonBox.Cancel
                                      | QDialogButtonBox.Ok)
        dialog.addButtonBox(button_box)
        # Set size constrains for looks
        dialog.setFixedWidth(input_calendar.sizeHint().width())
        dialog.setFixedHeight(dialog.sizeHint().height())
        if dialog.exec():
            if len(input_title.text()) != 0:

                if date is None:
                    date = input_calendar.selectedDate()

                self.addReminder(date, input_time.text(), input_title.text(),
                                 input_description.toPlainText())
            else:
                dialog_rem_error = DialogBuilder(block, "Error")
                dialog_rem_error.setTitleText(
                    "This reminder does not have a title")
                dialog_rem_error.setMsgText("Reminder must contain a title.")
                dialog_buttons = QDialogButtonBox(QDialogButtonBox.Ok)
                dialog_rem_error.addButtonBox(dialog_buttons)
                # dialog_rem_error.show()
                if dialog_rem_error.exec():
                    self.showDialog(None, None, None)

        else:
            logging.info("Clicked cancel")
Exemplo n.º 9
0
class SongList(QWidget):
    def __init__(self, parent=None):
        super(SongList, self).__init__(parent)

        os.chdir(os.path.dirname(os.path.abspath(__file__)))
        resourcesPath = os.getcwd()
        resourcesPath = os.path.join(resourcesPath, "resources")

        self.PLAY_ICON = QIcon(QPixmap(os.path.join(resourcesPath, "play.png")))
        self.PAUSE_ICON = QIcon(QPixmap(os.path.join(resourcesPath, "pause.png")))
        self.STOP_ICON = QIcon(QPixmap(os.path.join(resourcesPath, "stop.png")))
        self.DELETE_ICON = QIcon(QPixmap(os.path.join(resourcesPath, "delete.png")))

        self.setupMediaPlayer()
        self.setupUi()

    def setupMediaPlayer(self):
        self.mediaPlayer = QMediaPlayer()

        self.mediaPlayer.setNotifyInterval(1)
        self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.mediaPlayer.positionChanged.connect(self.positionChanged)
        self.mediaPlayer.durationChanged.connect(self.durationChanged)

    def setupUi(self):
        self.setWindowTitle("List of songs")
        mainLayout = QHBoxLayout(self)

        verticalListLayout = QVBoxLayout()
        self.songsListWidget = QListWidget()
        self.songsListWidget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.songsListWidget.customContextMenuRequested.connect(self.listWidgetRightClick)
        verticalListLayout.addWidget(self.songsListWidget)

        miniHorizontalLayout = QHBoxLayout()
        locatorLine = QLineEdit()
        locatorLine.setPlaceholderText("Locator")
        locatorBox = QComboBox()
        items = ["Title", "Status", "Description", "Style", "All"]
        locatorBox.addItems(items)
        locatorBox.setCurrentIndex(len(items)-1)

        miniHorizontalLayout.addWidget(locatorLine)
        miniHorizontalLayout.addWidget(locatorBox)

        locatorLine.textChanged.connect(lambda:self.populateList(locatorLine.text(), locatorBox.currentText()))

        verticalListLayout.addLayout(miniHorizontalLayout)

        self.mainForm = QGroupBox()
        self.mainForm.setTitle("Details")

        mainLayout.addLayout(verticalListLayout)
        mainLayout.addWidget(self.mainForm)

        self.populateList()
        self.mainFormSetupUi()
        #self.show()

        self.songsListWidget.currentRowChanged.connect(self.changePage)
    
    def mainFormSetupUi(self):

        """title, status style, duration, descriptin, location, project,
        variation_another_song, timestamp"""

        mainLayout = QVBoxLayout(self.mainForm)

        #Horizontal Layout 1
        horizontalLayout1 = QHBoxLayout()

        titleLabel = QLabel("Song name:")
        self.titleEdit = QLineEdit()

        self.titleEdit.editingFinished.connect(self.checkSong)
        self.titleEdit.textChanged.connect(self.validateSong)

        horizontalLayout1.addWidget(titleLabel)
        horizontalLayout1.addWidget(self.titleEdit)


        #Horizontal Layout 2
        horizontalLayout2 = QHBoxLayout()
        statusLabel = QLabel("Status:")
        self.statusBox = QComboBox()

        dateLabel = QLabel("Date:")
        self.dateEdit = QDateTimeEdit()
        self.dateEdit.setCalendarPopup(True)

        horizontalLayout2.addWidget(statusLabel)
        horizontalLayout2.addWidget(self.statusBox)
        horizontalLayout2.addStretch(1)
        horizontalLayout2.addWidget(dateLabel)
        horizontalLayout2.addWidget(self.dateEdit)


        #Style Groupbox, widgets added automatically
        self.styleGroupBox = QGroupBox()
        self.styleGroupBox.setTitle("Style:")
        self.styleLayout = QGridLayout(self.styleGroupBox)

        horizontalLayout3 = QHBoxLayout()
        durationLabel = QLabel("Duration:")
        self.durationLine = QTimeEdit()
        self.durationLine.setDisplayFormat("mm:ss")

        projectLabel = QLabel("Project")

        self.projectComboBox = QComboBox()
        self.projectComboBox.setEditable(True)

        horizontalLayout3.addWidget(durationLabel)
        horizontalLayout3.addWidget(self.durationLine)
        horizontalLayout3.addWidget(projectLabel)
        horizontalLayout3.addWidget(self.projectComboBox)

        horizontalLayout4 = QHBoxLayout()
        descriptionLabel = QLabel("Description:")
        variationLabel = QLabel("Variation from another song: ")
        self.variationLine = QLineEdit()

        horizontalLayout4.addWidget(descriptionLabel)
        horizontalLayout4.addStretch(1)
        horizontalLayout4.addWidget(variationLabel)
        horizontalLayout4.addWidget(self.variationLine)

        self.descriptionTextEdit = QTextEdit()

        horizontalLayout5 = QHBoxLayout()
        locationLabel = QLabel("Location:")
        self.locationLine = QLineEdit()
        self.locationButton = QPushButton("...")
        self.locationButton.clicked.connect(self.locateFile)


        horizontalLayout5.addWidget(locationLabel)
        horizontalLayout5.addWidget(self.locationLine)
        horizontalLayout5.addWidget(self.locationButton)

        horizontalLayout6 = QHBoxLayout()
        self.slider = QSlider(Qt.Horizontal)
        self.slider.sliderReleased.connect(self.playSlider)
        self.slider.setStyleSheet("QSlider::handle:horizontal { border: 1px solid #777; background:#b55858;}")
        horizontalLayout6.addWidget(self.slider)

        horizontalLayout7 = QHBoxLayout()
        self.playButton = QPushButton()
        self.stopButton = QPushButton()

        self.playButton.setIcon(self.PLAY_ICON)
        self.stopButton.setIcon(self.STOP_ICON)

        self.playButton.clicked.connect(self.playSong)
        self.stopButton.clicked.connect(self.stopSong)

        horizontalLayout7.addStretch(1)
        horizontalLayout7.addWidget(self.playButton)
        horizontalLayout7.addWidget(self.stopButton)
        horizontalLayout7.addStretch(1)


        horizontalLayout8 = QHBoxLayout()
        self.saveButton = QPushButton()
        self.saveButton.setText("Save")
        self.saveButton.clicked.connect(self.saveSong)

        horizontalLayout8.addStretch(1)
        horizontalLayout8.addWidget(self.saveButton)

        mainLayout.addLayout(horizontalLayout1)
        mainLayout.addLayout(horizontalLayout2)
        mainLayout.addWidget(self.styleGroupBox)
        mainLayout.addLayout(horizontalLayout3)
        mainLayout.addLayout(horizontalLayout4)
        mainLayout.addWidget(self.descriptionTextEdit)
        mainLayout.addLayout(horizontalLayout5)
        mainLayout.addLayout(horizontalLayout6)
        mainLayout.addLayout(horizontalLayout7)
        mainLayout.addLayout(horizontalLayout8)

    def clearForm(self):
        self.titleEdit.clear()
        self.statusBox.clear()
        for widget in self.styleGroupBox.children():
            if not isinstance(widget, QGridLayout):
                widget.deleteLater()

        self.durationLine.clear()
        self.projectComboBox.clear()
        self.variationLine.clear()
        self.descriptionTextEdit.clear()
        self.locationLine.clear()

    def changePage(self, index):
        title = self.songsListWidget.item(index).data(Qt.UserRole)
        self.clearForm()
        self.populateForm(title)
        self.slider.setValue(0)

    def populateForm(self, title): #title is the primary key
        listArray = queries("""SELECT title, status, style, duration, description,
        location, project, variation_another_song, timestamp from songs WHERE title = ?""", (title,))
        print(listArray)
        if len(listArray) != 0:
            title = listArray[0][0]
            status = listArray[0][1]

            styles = []
            styleArray = listArray[0][2]
            if styleArray != None:
                if "," in styleArray:
                    styles = styleArray.split(",")
                else:
                    styles.append(styleArray)
            duration = listArray[0][3]
            description = listArray[0][4]
            location = listArray[0][5]
            project = listArray[0][6]
            variation_another_song = listArray[0][7]
            timestamp = listArray[0][8]
        else:
            title = None
            status = None
            styles = None
            duration = None
            description = None
            location = None
            project = None
            variation_another_song = None
            timestamp = None

        if title != None: self.titleEdit.setText(title)

        self.statusBox.addItems(["Select...", "Demo", "WIP", "Idea", "Unfinished song", "EQ", "Master", "Finished"])
        if status != None: self.statusBox.setCurrentText(status)
        if timestamp != None: self.dateEdit.setDateTime(datetime.strptime(timestamp, '%d/%m/%Y %H:%M'))
        else: self.dateEdit.setDateTime(datetime.now())#default

        styleArray = queries("select style from songs where style is not null")

        """
        print(styleArray)
        if styleArray != None:
            styleArray = styleArray[0][0]
            if "," in styleArray:
                styles = styleArray.split(",")
            else:
                styles.append(styleArray)"""

        stylesArray = []

        query = queries("select style from songs where style is not null")
        if len(query) != 0:
            for style in query:
                stylesMiniArray = style[0].split(",")
                stylesMiniArray = list(filter(None, stylesMiniArray))
                for item in stylesMiniArray:
                    if item not in stylesArray:
                        if item != '':
                            stylesArray.append(item)

        self.x = 0
        self.y = 0

        if len(stylesArray) != 0:
            for style in stylesArray:
                    print("style", style)
                    checkBox = QCheckBox(style)
                    self.styleLayout.addWidget(checkBox, self.x, self.y)
                    self.checkBoxPositionAsignment()
        self.addStyle()

        if styles!= None:
            if len(styles) != 0:
                for style in styles:
                    for checkbox in self.styleGroupBox.children():
                        if isinstance(checkbox, QCheckBox):
                            if checkbox.text() == style:
                                checkbox.setChecked(True)

        if duration != None:
                time = QTime(0,0,0)
                self.durationLine.setTime(time.addSecs(duration))

        projectsArray = ["Select..."]
        projectsArrayQuery = queries("SELECT project from songs")
        if len(projectsArrayQuery) != 0:
            for project in projectsArrayQuery[0]:
                if project not in projectsArray:
                    projectsArray.append(project)
        if project != None: self.projectComboBox.setCurrentText(project)

        if variation_another_song != None: self.variationLine.setText(variation_another_song)
        if description != None: self.descriptionTextEdit.setText(description)

        available = False
        if location != None:
            self.locationLine.setText(location)
        if len(self.locationLine.text()) != 0:
            try:
                self.playlist = QMediaPlaylist()
                self.playlist.addMedia(QMediaContent(QUrl.fromLocalFile(location)))
                self.mediaPlayer.setPlaylist(self.playlist)
            except:
                pass
            available = True#I know this is stupid but just in case

        self.slider.setVisible(available)
        self.playButton.setVisible(available)
        self.stopButton.setVisible(available)

    def populateList(self, locatorItem=None, locatorColumn=None):
        print(locatorItem, locatorColumn)
        self.songsListWidget.blockSignals(True)
        self.songsListWidget.clear()
        if locatorItem == None or locatorItem == "":
            listArray = queries("""SELECT title, status, timestamp from songs """)
            print(listArray)
        else:
            if locatorColumn != "All": #No strings concatenation, no security holes
                if locatorColumn == "Title":
                    sql = """SELECT title, status, timestamp from songs where title LIKE ?"""
                elif locatorColumn == "Status":
                    sql = """SELECT title, status, timestamp from songs where status LIKE ?"""
                elif locatorColumn == "Description":
                    sql = """SELECT title, status, timestamp from songs where description LIKE ?"""
                elif locatorColumn == "Style":
                    sql = """SELECT title, status, timestamp from songs where style LIKE ?"""

                locatorItem = "%" + locatorItem + "%"
                listArray = queries(sql, (locatorItem,))
            else:
                locatorItem = "%" + locatorItem + "%"
                variables = [locatorItem, locatorItem, locatorItem, locatorItem, locatorItem]
                listArray = queries("""SELECT title, status, timestamp from songs
                where title LIKE ? OR type LIKE ? OR original_song LIKE ? OR link LIKE ?
                OR description LIKE ?""", variables)
        for item in listArray:
            title = item[0]
            status = item[1]
            timestamp = item[2]
            try:
                timestamp = datetime.strptime(timestamp, "%d/%m/%Y %H:%M")
                timestamp = timestamp.strftime("%d/%m/%Y")
            except:
                timestamp = ""

            text = "%s %s %s" % (title, status, timestamp)
            qItem = QListWidgetItem(text)
            qItem.setData(Qt.UserRole, title)
            self.songsListWidget.addItem(qItem)
        #new idea
        qItem = QListWidgetItem("New song...")
        qItem.setData(Qt.UserRole, "New song...") #otherwise that would be an error
        self.songsListWidget.addItem(qItem)
        self.songsListWidget.blockSignals(False)

    def listWidgetRightClick(self, position):
        widgetItem = self.songsListWidget.itemAt(position)
        if widgetItem != None: #quick lazy text fix
            if widgetItem.text() != "New song...":
                print(widgetItem.text())
                menu = QMenu()
                deleteAction = QAction(self.DELETE_ICON, "Delete song")
                menu.addAction(deleteAction)
                action = menu.exec(self.mapToGlobal(position)) 

                if action == deleteAction:
                    msg = QMessageBox.question(None, "Delete?", "Are you sure you want to delete this entry?")
                    if msg == QMessageBox.Yes:
                        title = widgetItem.data(Qt.UserRole)
                        queries("DELETE from songs where title = ?", (title,))
                        self.populateList()
                        self.songsListWidget.setCurrentRow(0)

    def songVariations(self):
        sql = "SELECT title from songs"
        songArray = []
        for song in queries(sql)[0]:
            songArray.append(song)
        return songArray
    def checkBoxPositionAsignment(self):
            self.y += 1
            if self.y == 4:
                self.y = 0
                self.x += 1
    def addStyle(self, text=""):
        "text = "" if comes from outside"

        self.styleEdit = QLineEdit()
        self.styleEdit.setPlaceholderText("Style")
        self.styleEdit.textChanged.connect(self.validateStyle)
        self.styleEdit.returnPressed.connect(lambda: self.addStyle(self.styleEdit.text()))

        if text != "":
            self.styleLayout.takeAt(self.styleLayout.count()-1).widget().deleteLater()

            styleCheckBox = QCheckBox()
            styleCheckBox.setText(text)
            print(text)
            self.styleLayout.addWidget(styleCheckBox, self.x, self.y)
            self.checkBoxPositionAsignment()
            print(self.durationLine.text())
        self.styleLayout.addWidget(self.styleEdit)


    def checkSong(self):
        text = self.titleEdit.text()
        sql = "SELECT title from songs where title = ?"
        if len(queries(sql, (text,))) != 0:
            self.titleEdit.setText("")
    def validateSong(self):
        pass
        #VALIDATE REG EXP

    def validateStyle(self, text):
        if "," in text:
            self.styleEdit.undo()

    def playSong(self):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.mediaPlayer.pause()
        else:
            self.mediaPlayer.play()

    def mediaStateChanged(self):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.playButton.setIcon(self.PAUSE_ICON)
        else:
            self.playButton.setIcon(self.PLAY_ICON)
    def positionChanged(self, position):
        if position != self.mediaPlayer.duration():
            self.slider.setValue(position)
    def durationChanged(self, duration):
        if duration != self.mediaPlayer.position():
            print("duration chagned")
            self.slider.setRange(0, duration)
    def playSlider(self):
        self.mediaPlayer.setPosition(self.slider.value())

    def stopSong(self):
        self.mediaPlayer.stop()

    def locateFile(self):
        self.fileSystem = QFileDialog(filter="Sound files (*.wav *.mp3 *.flac)")
        self.fileSystem.show()
        self.fileSystem.fileSelected.connect(self.fileLoaded)

    def fileLoaded(self, path):
        self.locationLine.setText(path)
        try:
            self.playlist = QMediaPlaylist()
            self.playlist.addMedia(QMediaContent(QUrl.fromLocalFile(path)))
            self.mediaPlayer.setPlaylist(self.playlist)
        except:
            print("fail")
        self.slider.setVisible(True)
        self.playButton.setVisible(True)
        self.stopButton.setVisible(True)

    def saveSong(self):
        title = self.titleEdit.text()
        status = self.statusBox.currentText()
        date = self.dateEdit.text()
        style = ""

        print(status, style)
        x = 0
        for checkBox in self.styleGroupBox.children():
            if isinstance(checkBox, QCheckBox):
                if checkBox.isChecked():
                    style += (checkBox.text()) + ","
                    x+=1
        if x != 0: style = style.rstrip(",")
        else: style = None

        duration = self.durationLine.time()
        duration = QTime(0, 0).secsTo(duration)

        project = self.projectComboBox.currentText()
        variation = self.variationLine.text()
        description = self.descriptionTextEdit.toPlainText()
        location = self.locationLine.text()

        variables = [title, status, description, location, project,\
        variation, date, style, duration]

        print("---------", variables)

        sql = """INSERT OR REPLACE into songs
        (title, status, description, location, project,
        variation_another_song, timestamp, style, duration)

        values
        (?,      ?,       ?,          ?,     ?,
         ?,                     ?,         ?,      ?)"""

        queries(sql, variables)
        self.populateList()
Exemplo n.º 10
0
class WindowAudiencias(QWidget):
    def __init__(self, db, parent=None):
        super(WindowAudiencias, self).__init__(parent)
        self.db = db
        self.setWindowIcon(QIcon("static/logo.ico"))
        self.setWindowTitle("Audiências do Tribunal de Justiça")
        self.resize(800, 600)
        self.filtered_date = False
        self.filtered_vara = False

        # buttons
        x_btn = 600
        y_btn_gap = 20
        y_btn_step = 50

        self.btn_font = QFont()
        self.btn_font.setBold(True)
        self.btn_font.setPixelSize(12)

        def create_button(window, on_click, text, tip, pos):
            button = QPushButton(text, window)
            button.setToolTip(tip)
            button.move(x_btn, y_btn_gap + y_btn_step * pos)
            button.clicked.connect(on_click)
            button.resize(150, 40)
            button.setFont(self.btn_font)
            return button

        self.btn_insert_audiencia = create_button(
            self, self.on_click_insert_audiencia, 'Inserir Audiência',
            'Criar uma nova Audiência no banco de dados.', 0)
        self.btn_update_audiencia = create_button(
            self, self.on_click_update_audiencia, 'Atualizar Audiência',
            'Atualizar uma Audiência do banco de dados.', 1)
        self.btn_delete_audiencia = create_button(
            self, self.on_click_delete_audiencia, 'Remover Audiência',
            'Remover uma Audiência do banco de dados.', 2)
        self.btn_atividades = create_button(
            self, self.on_click_open_atividades, 'Atividades Audiência',
            'Abrir a janela de atividades da Audiência.', 3)

        # filter buttons
        def create_filter_button(window, on_click, icon, tip, x):
            filter_button = create_button(window, on_click, '', tip, 3.5)
            filter_button.setIcon(QIcon('./static/{}'.format(icon)))
            filter_button.resize(40, 40)
            filter_button.move(x, y_btn_gap + y_btn_step * 3.5)
            filter_button.setIconSize(QSize(30, 30))
            return filter_button

        self.btn_filter_vara = create_filter_button(
            self, self.on_click_filter_vara, 'filter_vara.png',
            'Filtrar Audiências pela Vara.', 300)
        self.btn_filter_date = create_filter_button(
            self, self.on_click_filter_date, 'filter_data.png',
            'Filtrar Audiências por data da Audiência.', 350)
        self.btn_remove_filter_date = create_filter_button(
            self, self.on_click_remove_filters, 'rm_filter.png',
            'Remover filtros das Audiências.', 400)

        # labels
        def create_label(window, text, x, pos):
            label = QLabel(window)
            label.setText(text)
            y_gap = 20
            y_step = 50
            label.move(x, y_gap + pos * y_step)
            return label

        x_in_1 = 50
        x_in_2 = 220

        create_label(self, 'Vara', x_in_1, 0)
        create_label(self, 'Processo', x_in_1, 1)
        create_label(self, 'Tipo', x_in_1, 2)
        create_label(self, 'Audiências', x_in_1, 4)

        create_label(self, 'Horário', x_in_2, 0)
        create_label(self, 'Data Audiência', x_in_2, 1)
        create_label(self, 'Data Despacho', x_in_2, 2)

        # line edit
        y_gap = 37
        y_step = 50

        def create_line_edit(window, x, pos):
            line_edit = QLineEdit(window)
            line_edit.move(x, y_gap + pos * y_step)
            line_edit.resize(150, 24)
            return line_edit

        self.line_processo = create_line_edit(self, x_in_1, 1)

        # date edit
        def create_date_edit(window, x, pos):
            date_edit = QDateEdit(self)
            date_edit.move(x, y_gap + pos * y_step)
            date_edit.resize(150, 24)
            return date_edit

        self.date_data_audiencia = create_date_edit(self, x_in_2, 1)
        self.date_data_despacho = create_date_edit(self, x_in_2, 2)

        # time edit
        self.time_horario = QTimeEdit(self)
        self.time_horario.move(x_in_2, y_gap + 0 * y_step)
        self.time_horario.resize(150, 24)

        # combo-box
        def create_cb(window, list_items, x, pos):
            combo_box = QComboBox(window)
            combo_box.addItems(list_items)
            combo_box.move(x, y_gap + pos * y_step)
            combo_box.resize(150, 24)
            return combo_box

        self.cb_vara = create_cb(self, ["1", "2"], x_in_1, 0)
        self.cb_tipo = create_cb(self, [
            "Instrução e Julgamento", "Oitiva", "Interrogatório",
            "Depoimento Especial", "UNA", "Continuação", "Carta Precatória"
        ], x_in_1, 2)

        # check-box
        self.ck_urgente = QCheckBox("Urgente", self)
        self.ck_urgente.move(x_in_1, y_gap - 17 + 3 * y_step)

        # table
        self.table_audiencias = QTableWidget(self)
        self.table_audiencias.move(50, 240)
        self.table_audiencias.resize(700, 300)
        self.table_audiencias.itemSelectionChanged.connect(
            self.table_audiencias_select)
        self.set_table_audiencias_content(self.filtered_date,
                                          self.filtered_vara)

    # table functions
    def set_table_audiencias_content(self, filtered_date, filtered_vara):
        audiencias = self.db.get_audiencias()
        self.table_audiencias.clear()

        headers = list(self.db.get_audiencia_columns())
        n_rows = len(audiencias)
        self.table_audiencias.setRowCount(n_rows)
        if (n_rows <= 0):
            return

        self.table_audiencias.setColumnCount(len(audiencias[0]))
        self.table_audiencias.setHorizontalHeaderLabels(headers)

        ignored_rows = []
        for row, record in enumerate(audiencias):
            ignore_row = False
            for column, content in enumerate(record):
                self.table_audiencias.setItem(row, column,
                                              QTableWidgetItem(content))

                if (filtered_date):
                    if (headers[column] == 'data_audiencia'
                            and content != self.get_date_data_audiencia()):
                        if (row not in ignored_rows):
                            ignored_rows.append(row)

                if (filtered_vara):
                    if (headers[column] == 'vara'
                            and content != self.get_cb_vara()):
                        if (row not in ignored_rows):
                            ignored_rows.append(row)

        for i, row in enumerate(ignored_rows):
            self.table_audiencias.removeRow(row - i)

    def table_audiencias_select(self):
        currentRow = self.table_audiencias.currentRow()
        self.table_audiencias.selectRow(currentRow)

        vara_index = self.cb_vara.findText(
            self.table_audiencias.item(currentRow, 0).text())
        self.cb_vara.setCurrentIndex(vara_index)

        tipo_index = self.cb_tipo.findText(
            self.table_audiencias.item(currentRow, 2).text())
        self.cb_tipo.setCurrentIndex(tipo_index)

        status_urgente = self.table_audiencias.item(currentRow, 3).text()
        status_urgente = 2 if status_urgente == 'Sim' else 0
        self.ck_urgente.setCheckState(status_urgente)

        txt_horario = self.table_audiencias.item(currentRow, 4).text()
        self.time_horario.setTime(self.transform_to_qtime(txt_horario))

        select_processo = self.table_audiencias.item(currentRow, 1)
        select_data_audiencia = self.table_audiencias.item(currentRow, 5)

        if (select_processo and select_data_audiencia):
            select_processo = select_processo.text()
            self.line_processo.setText(select_processo)

            date_to_set = self.transform_to_qdate(select_data_audiencia.text())
            self.date_data_audiencia.setDate(date_to_set)

        select_data_despacho = self.table_audiencias.item(currentRow, 6)
        if (select_data_despacho):
            date_to_set = self.transform_to_qdate(select_data_despacho.text())
            self.date_data_despacho.setDate(date_to_set)

    # get data functions
    def transform_to_qdate(self, date_str):
        date_list = date_str.split('/')
        return QDate(int(date_list[2]), int(date_list[1]), int(date_list[0]))

    def transform_to_qtime(self, time_str):
        time_list = time_str.split(':')
        return QTime(int(time_list[0]), int(time_list[1]))

    def get_ck_urgente(self):
        return self.ck_urgente.checkState()

    def get_cb_vara(self):
        return self.cb_vara.currentText()

    def get_cb_tipo(self):
        return self.cb_tipo.currentText()

    def get_line_processo(self):
        return self.line_processo.text()

    def get_time_horario(self):
        return self.time_horario.text()

    def get_date_data_audiencia(self):
        return self.date_data_audiencia.text()

    def get_date_data_despacho(self):
        return self.date_data_despacho.text()

    # button functions
    def on_click_filter_date(self):
        self.filtered_date = True
        self.set_table_audiencias_content(self.filtered_date,
                                          self.filtered_vara)

    def on_click_filter_vara(self):
        self.filtered_vara = True
        self.set_table_audiencias_content(self.filtered_date,
                                          self.filtered_vara)

    def on_click_remove_filters(self):
        self.filtered_date = False
        self.filtered_vara = False
        self.set_table_audiencias_content(self.filtered_date,
                                          self.filtered_vara)

    def on_click_insert_audiencia(self):
        self.db.insert_audiencia(vara=self.get_cb_vara(),
                                 processo=self.get_line_processo(),
                                 tipo=self.get_cb_tipo(),
                                 urgente=self.get_ck_urgente(),
                                 horario=self.get_time_horario(),
                                 data_audiencia=self.get_date_data_audiencia(),
                                 data_despacho=self.get_date_data_despacho())
        self.set_table_audiencias_content(self.filtered_date,
                                          self.filtered_vara)

    def on_click_delete_audiencia(self):
        currentRow = self.table_audiencias.currentRow()
        drop_processo = self.table_audiencias.item(currentRow, 1)
        drop_data_audiencia = self.table_audiencias.item(currentRow, 5)

        if (drop_processo and drop_data_audiencia):
            drop_processo = drop_processo.text()
            drop_data_audiencia = drop_data_audiencia.text()
            self.db.delete_audiencia(drop_processo, drop_data_audiencia)

            print('Audiência removida do banco de dados.')
            self.set_table_audiencias_content(self.filtered_date,
                                              self.filtered_vara)

    def on_click_update_audiencia(self):
        currentRow = self.table_audiencias.currentRow()
        update_processo = self.table_audiencias.item(currentRow, 1)
        update_data_audiencia = self.table_audiencias.item(currentRow, 5)

        if (update_processo and update_data_audiencia):
            update_processo = update_processo.text()
            update_data_audiencia = update_data_audiencia.text()
            self.db.update_audiencia(
                vara=self.get_cb_vara(),
                processo=update_processo,
                tipo=self.get_cb_tipo(),
                urgente=self.get_ck_urgente(),
                horario=self.get_time_horario(),
                data_audiencia=update_data_audiencia,
                data_despacho=self.get_date_data_despacho())
            self.set_table_audiencias_content(self.filtered_date,
                                              self.filtered_vara)

    def on_click_open_atividades(self):
        use_processo = self.get_line_processo()
        use_data_audiencia = self.get_date_data_audiencia()

        if (len(use_processo) != 13 or len(use_data_audiencia) != 10):
            print('Audiência selecionada é inválida.')
        else:
            self.windowAtividades = WindowAtividades(self.db, use_processo,
                                                     use_data_audiencia,
                                                     self.get_cb_vara())
            self.windowAtividades.show()
Exemplo n.º 11
0
class SchoolInfoForm(QWidget):
    def __init__(self, parent=None, footer_ref=None):
        super().__init__(parent)

        """used to point to the footer widget which will have the 'next', 'back' buttons.
                    Footer will also have required function to control the warning prompts"""
        self.footerWidgetRef = footer_ref

        # variable dependencies
        self.screenCount = 0                        # used for changing index for stacked widgets
        self.InvalidInputFields = []
        self.ignoredWarnings = []               # same as InvalidInputFields variable, but used only for waring purpose
        self.workingDaysCheckboxes = []    # contains all the checkboxes generated for working days
        self.streamCheckboxes = []              # contains all the checkboxes generated for streams
        self.daysSelected = []
        self.streamSelected = []

        # list of warnings that would be prompted on the GUI on respective invalid input (a dictionary type)
        # {"input_field_number": "warning on invalid input for the field"}
        self.warningMessages = {
            "1": "[Invalid Name] Check numbers, spaces and special characters.",
            "2": "[Invalid Address] Check special characters (except - or ,).",
            "3": "[No input] Please select a board.",
            "4": "[No input] Please select an education level.",
            "5": "[No input] Please select at least 1 stream.",
            "6": "[Invalid classrooms no.] Value must be less than 71.",
            "7": "[Invalid teachers no.] Value must be less than 71.",
            "8": "[No input] Please select no. of shifts.",
            "9": "[Invalid Time] Start and End time cannot be same.",
            "10": "[No input] Select at least 1 working day."
        }

        # list of all major Boards in India
        self.boardList = [
            '-- Select --',
            'Central Board of Secondary Education',
            'Indian Certificate of Secondary Education/Indian School Certificate',
            'State Board'
        ]

        # list of education levels
        self.educationLevels = [
            '-- Select --',
            'Up to 5th class (Primary)',
            'Up to 8th class',
            'Up to 10th class (High School)',
            'Up to 12th class (Intermediate)'
        ]

        # possible stream combination (must be exported from a dedicated file/DB)
        self.streams = [
            'Science (Physics, Chemistry, Maths) with Computers',
            'Science (Physics, Chemistry, Maths) without Computers',
            'Science (Physics, Chemistry, Biology) without Computers',
            'Commerce'
        ]

        # main layout of the widget
        self.mainLayout = QFormLayout(self)

        # font family, size and color
        form_font = QFont("Trebuchet")
        form_font.setPointSize(10)
        self.setFont(form_font)

        # appearance of the window (changing background as dark)
        self.setAutoFillBackground(True)
        self.formPalette = self.palette()
        self.formPalette.setColor(self.foregroundRole(), QColor('white'))
        self.setPalette(self.formPalette)

        # input fields widgets
        # text widgets for the window
        self.schoolNameLabel = QLabel('1) School Name')
        self.schoolAddressLabel = QLabel('2) School Address')
        self.boardLabel = QLabel('3) Board Affiliated to')
        self.educationLevelLabel = QLabel('4) Offers classes')
        self.streamLabel = QLabel('5) Streams available')
        self.workingDaysLabel = QLabel('10) Operates on')

        """" input fields of the window """
        # for school name input
        self.schoolNameField = QLineEdit()                         # input field 1
        self.schoolNameField.textChanged.connect(lambda: self.check_name_field_validity())
        self.schoolNameField.setFixedWidth(450)

        # for school address (3 liner) input
        self.schoolAddressFieldPart1 = QLineEdit()            # input field 2 (line 1)
        self.schoolAddressFieldPart1.textChanged.connect(lambda: self.check_address_field_validity())
        self.schoolAddressFieldPart1.setFixedWidth(450)
        self.schoolAddressFieldPart2 = QLineEdit()            # Line 2 (part 2)
        self.schoolAddressFieldPart2.textChanged.connect(lambda: self.check_address_field_validity())
        self.schoolAddressFieldPart2.setFixedWidth(450)
        self.schoolAddressFieldPart3 = QLineEdit()            # Line 3 (part 3)
        self.schoolAddressFieldPart3.textChanged.connect(lambda: self.check_address_field_validity())
        self.schoolAddressFieldPart3.setFixedWidth(450)

        # for board name selection
        self.boardField = QComboBox(self)                         # input field 3
        self.boardField.addItems(self.boardList)                # the passed list values must be fetch from DB
        self.boardField.currentIndexChanged.connect(lambda: self.check_board_field_validity())
        self.boardField.setFixedWidth(450)

        # for education level selection
        self.educationLevelField = QComboBox(self)          # input field 4
        self.educationLevelField.addItems(self.educationLevels)  # the passed list values must be fetch from DB
        self.educationLevelField.currentIndexChanged.connect(lambda: self.check_education_level_field_validity())
        self.educationLevelField.setFixedWidth(450)

        # for stream selection
        # container/area for containing all checkboxes of each stream combinations
        self.streamsInputArea = QWidget(self)                   # input field 5
        self.streamsInputAreaLayout = QVBoxLayout(self.streamsInputArea)
        # generating checkboxes...
        for index in range(len(self.streams)):
            stream_checkbox = self.generate_stream_options_for(index, self.streams[index])
            self.streamCheckboxes.append(stream_checkbox)

        # ########
        # form asking about assets of the school (ie classrooms and teachers)
        self.assetFormArea = QWidget(self)
        self.assetFormAreaLayout = QFormLayout(self.assetFormArea)
        self.classCountLabel = QLabel('6) No. of classrooms')
        self.classCountField = QLineEdit()  # input field 6
        self.classCountField.textChanged.connect(lambda: self.check_classes_field_validity())
        self.classCountField.setFixedWidth(70)
        self.teacherCountLabel = QLabel('7) No. of teachers')
        self.teacherCountField = QLineEdit()  # input field 7
        self.teacherCountField.textChanged.connect(lambda: self.check_teachers_field_validity())
        self.teacherCountField.setFixedWidth(70)
        self.assetFormAreaLayout.addRow(self.classCountLabel, self.classCountField)
        self.assetFormAreaLayout.addRow(self.teacherCountLabel, self.teacherCountField)

        # widget for timing form
        self.timingInputArea = QWidget(self)
        self.timingInputAreaLayout = QFormLayout(self.timingInputArea)
        self.shiftLabel = QLabel('8) Total Shifts')
        self.shiftField = QComboBox(self.timingInputArea)  # input field 8
        self.shiftField.addItems(["Select", "1", "2", "3", "4"])
        self.shiftField.currentIndexChanged.connect(lambda: self.check_shifts_field_validity())
        self.shiftField.setFixedWidth(70)
        self.schoolHoursLabel = QLabel('9) School hours')

        # widget for storing 2 input fields (for start timing and end timing) into single row
        self.startEndFields = QWidget(self.timingInputArea)
        self.startEndFieldsLayout = QHBoxLayout(self.startEndFields)
        self.schoolStartTimeField = QTimeEdit()  # input field 9 (a)
        self.schoolStartTimeField.timeChanged.connect(lambda: self.check_school_hours_field_validity())
        self.schoolStartTimeField.setFixedWidth(100)
        self.schoolEndTimeField = QTimeEdit()  # input field 9 (b)
        self.schoolEndTimeField.timeChanged.connect(lambda: self.check_school_hours_field_validity())
        self.schoolEndTimeField.setFixedWidth(100)
        self.startEndFieldsLayout.addWidget(self.schoolStartTimeField)
        self.startEndFieldsLayout.addWidget(QLabel(' to '))
        self.startEndFieldsLayout.addWidget(self.schoolEndTimeField)
        self.startEndFieldsLayout.addStretch(1)

        # adding widgets to timing form layout
        self.timingInputAreaLayout.addRow(self.shiftLabel, self.shiftField)
        self.timingInputAreaLayout.addRow(self.schoolHoursLabel, self.startEndFields)

        # widgets for placing checkboxes for working days
        self.workingDaysCheckboxArea = QWidget(self)
        self.workingDaysCheckboxAreaLayout = QHBoxLayout(self.workingDaysCheckboxArea)
        self.daysList = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        # generating checkboxes...
        for index in range(len(self.daysList)):             # input field 10
            day_checkbox = self.create_working_days_checkbox_for(index, self.daysList[index])
            self.workingDaysCheckboxes.append(day_checkbox)

        # adding all widgets into main layout
        self.mainLayout.addRow(self.schoolNameLabel, self.schoolNameField)
        self.mainLayout.addRow(self.schoolAddressLabel, self.schoolAddressFieldPart1)
        self.mainLayout.addRow(QLabel(''), self.schoolAddressFieldPart2)
        self.mainLayout.addRow(QLabel(''), self.schoolAddressFieldPart3)
        self.mainLayout.addRow(self.boardLabel, self.boardField)
        self.mainLayout.addRow(self.educationLevelLabel, self.educationLevelField)
        self.mainLayout.addRow(self.streamLabel, self.streamsInputArea)
        self.mainLayout.addRow(self.assetFormArea, self.timingInputArea)
        self.mainLayout.addRow(self.workingDaysLabel, self.workingDaysCheckboxArea)
        self.mainLayout.setContentsMargins(10, 20, 0, 0)
        self.setLayout(self.mainLayout)

        # calling validation functions for each field at initial stage
        self.check_if_all_valid()
    # ####################################################################
    # ##################### GUI ENDS HERE ###################################
    # ####################################################################

    # ####################################################################
    # ############ GUI COMPONENTS CREATING FUNCTIONS STARTS HERE #############
    # ####################################################################

    # function which generates the stream options checkboxes
    def generate_stream_options_for(self, checkbox_index, stream_value):
        stream_option_checkbox = QCheckBox(stream_value)
        stream_option_checkbox.toggled.connect(lambda: self.process_stream_checkbox(checkbox_index))
        self.streamsInputAreaLayout.addWidget(stream_option_checkbox)
        return stream_option_checkbox

    # function to create checkboxes for working days
    def create_working_days_checkbox_for(self, checkbox_index, checkbox_value):
        working_day_checkbox = QCheckBox(checkbox_value)
        working_day_checkbox.toggled.connect(lambda: self.process_working_days_checkbox(checkbox_index))
        self.workingDaysCheckboxAreaLayout.addWidget(working_day_checkbox)
        return working_day_checkbox

    # ####################################################################
    # ############# GUI COMPONENTS CREATING FUNCTIONS ENDS HERE ##############
    # ####################################################################

    # ####################################################################
    # ############## INPUT FIELDS VALIDATING FUNCTIONS STARTS HERE ##############
    # ####################################################################

    """ 
    Function definitions for each input field for its respective validation. 
    These functions make use of following one or more "helper functions":
    
    [Function available in Global/Functions/independent_functions.py file]
      *     check_if_pure_string()
      *     check_if_alpha_numeric()
      *     check_if_special_string()
      *     check_if_numeric()
      
      [Functions available in current class]
      *     add_validity()
      *     remove_validity()    
    """
    # function to validate "school name" input field (ie FIELD 1)
    def check_name_field_validity(self):
        # number of "name" input field => 1
        valid_input = check_if_pure_string(self.schoolNameField.text())
        if valid_input:
            self.add_validity(self.InvalidInputFields, 1)
            self.add_validity(self.ignoredWarnings, 1)
            self.update_warnings(1, True)
        else:
            self.remove_validity(self.InvalidInputFields, 1)
            self.remove_validity(self.ignoredWarnings, 1)
            self.update_warnings(1, False)

        # updating status of "next" button accordingly
        self.check_next_button_validity()

    # function to validate "school address" input field (ie FIELD 2)
    def check_address_field_validity(self):
        # number of "address" input field => 2

        # validation of address (ie field 2, part 1 only)
        address_valid = check_if_special_string(self.schoolAddressFieldPart1.text())

        # validation for part2 and part3 of address; checked only if they have non empty strings
        if self.schoolAddressFieldPart2.text() != "":
            part2_valid = check_if_special_string(self.schoolAddressFieldPart2.text())
            address_valid = address_valid and part2_valid
        if self.schoolAddressFieldPart3.text() != "":
            part3_valid = check_if_special_string(self.schoolAddressFieldPart3.text())
            address_valid = address_valid and part3_valid

        if address_valid:
            self.add_validity(self.InvalidInputFields, 2)
            self.add_validity(self.ignoredWarnings, 2)
            self.update_warnings(2, True)
        else:
            self.remove_validity(self.InvalidInputFields, 2)
            self.remove_validity(self.ignoredWarnings, 2)
            self.update_warnings(2, False)

        # updating status of "next" button accordingly
        self.check_next_button_validity()

    # function to validate "board" input field (ie FIELD 3)
    def check_board_field_validity(self):
        # number of "board" input field => 3
        self.validate_combobox(self.boardField, 3)

    # function to validate "eduction level" input field (ie FIELD 4)
    def check_education_level_field_validity(self):
        # number of "board" input field => 4
        self.validate_combobox(self.educationLevelField, 4)

    # function to validate "stream offered" input field (ie FIELD 5)
    def check_stream_field_validity(self):
        # number of "stream offered" input field => 5
        # checking if at least one of the streams is selected
        if len(self.streamSelected) == 0:
            self.remove_validity(self.InvalidInputFields, 5)
            self.remove_validity(self.ignoredWarnings, 5)
            self.update_warnings(5, False)
        else:
            self.add_validity(self.InvalidInputFields, 5)
            self.add_validity(self.ignoredWarnings, 5)
            self.update_warnings(5, True)

        # updating status of "next" button accordingly
        self.check_next_button_validity()

    # function to validate "No. of class rooms" input field (ie FIELD 6)
    def check_classes_field_validity(self):
        # number of "No. of class rooms" input field => 6
        # checking if number of classes is given and it is less than 70
        max_class_limit = 70
        total_classes = self.classCountField.text()
        # giving total classes a value of 0 if it is left blank
        if total_classes == "":
            self.remove_validity(self.InvalidInputFields, 6)
            self.remove_validity(self.ignoredWarnings, 6)
            self.update_warnings(6, False)
        else:
            valid_class_input = check_if_numeric(str(total_classes))
            if valid_class_input and (max_class_limit >= int(total_classes) > 0):
                self.add_validity(self.InvalidInputFields, 6)
                self.add_validity(self.ignoredWarnings, 6)
                self.update_warnings(6, True)
            else:
                self.remove_validity(self.InvalidInputFields, 6)
                self.remove_validity(self.ignoredWarnings, 6)
                # self.send_warning_to_prompt_area_for(6)
                self.update_warnings(6, False)

        # updating status of "next" button accordingly
        self.check_next_button_validity()

    # function to validate "No. of teachers" input field (ie FIELD 7)
    def check_teachers_field_validity(self):
        # number of "No. of teachers" input field => 7
        # checking if number of teachers is given and it is less than 70
        max_teacher_limit = 70
        total_teachers = self.teacherCountField.text()
        # giving total teachers a value of 0 if it is left blank
        if total_teachers == "":
            self.remove_validity(self.InvalidInputFields, 7)
            self.remove_validity(self.ignoredWarnings, 7)
            self.update_warnings(7, False)
        else:
            valid_teacher_input = check_if_numeric(str(total_teachers))
            if valid_teacher_input and (max_teacher_limit >= int(total_teachers) > 0):
                self.add_validity(self.InvalidInputFields, 7)
                self.add_validity(self.ignoredWarnings, 7)
                self.update_warnings(7, True)
            else:
                self.remove_validity(self.InvalidInputFields, 7)
                self.remove_validity(self.ignoredWarnings, 7)
                self.update_warnings(7, False)

        # updating status of "next" button accordingly
        self.check_next_button_validity()

    # function to validate "Total Shifts" input field (ie FIELD 8)
    def check_shifts_field_validity(self):
        # number of "shifts" input field => 8
        # checking if any no of shift is selected or not
        self.validate_combobox(self.shiftField, 8)

    # function to validate "School Hours" input field (ie FIELD 9)
    def check_school_hours_field_validity(self):
        start_time = self.schoolStartTimeField.text()
        end_time = self.schoolEndTimeField.text()

        if start_time == end_time:
            self.remove_validity(self.InvalidInputFields, 9)
            self.remove_validity(self.ignoredWarnings, 9)
            self.update_warnings(9, False)
        else:
            self.add_validity(self.InvalidInputFields, 9)
            self.add_validity(self.ignoredWarnings, 9)
            self.update_warnings(9, True)

        # updating status of "next" button accordingly
        self.check_next_button_validity()

    # function to validate "Operates on" input field (ie FIELD 10)
    def check_working_days_field_validity(self):
        # number of "Operates on" input field => 10
        # checking if at least one of the days is selected
        if len(self.daysSelected) == 0:
            self.remove_validity(self.InvalidInputFields, 10)
            self.remove_validity(self.ignoredWarnings, 10)
            self.update_warnings(10, False)
        else:
            self.add_validity(self.InvalidInputFields, 10)
            self.add_validity(self.ignoredWarnings, 10)
            self.update_warnings(10, True)

        # updating status of "next" button accordingly
        self.check_next_button_validity()

    # function to check validity of all field. To be called only once at the beginning
    def check_if_all_valid(self):
        self.check_name_field_validity()
        self.check_address_field_validity()
        self.check_board_field_validity()
        self.check_education_level_field_validity()
        self.check_stream_field_validity()
        self.check_classes_field_validity()
        self.check_teachers_field_validity()
        self.check_shifts_field_validity()
        self.check_school_hours_field_validity()
        self.check_working_days_field_validity()

        # hiding any warning message generated before even giving any input
        self.footerWidgetRef.hide_warning()
        self.ignoredWarnings = []   # resetting the list
        print(f"Warnings have been reset. ({len(self.ignoredWarnings)})")

    # function for checking if all required fields have been validated
    def check_next_button_validity(self):
        # if all fields are valid, size of "InvalidInputFields" will be 0, which would, then enable the next button
        if len(self.InvalidInputFields) == 0:
            self.footerWidgetRef.nextButton.setEnabled(True)
        else:
            self.footerWidgetRef.nextButton.setEnabled(False)

    # ####################################################################
    # ############## INPUT FIELDS VALIDATING FUNCTIONS ENDS HERE ###############
    # ####################################################################

    # process working days checkboxes on toggling
    def process_working_days_checkbox(self, checkbox_index):
        if self.workingDaysCheckboxes[checkbox_index].isChecked():
            self.daysSelected.append(self.daysList[checkbox_index])
        else:
            self.daysSelected.remove(self.daysList[checkbox_index])

        # validating the field after processing
        self.check_working_days_field_validity()

    # process working days checkboxes on toggling
    def process_stream_checkbox(self, checkbox_index):
        if self.streamCheckboxes[checkbox_index].isChecked():
            self.streamSelected.append(self.streams[checkbox_index])
        else:
            self.streamSelected.remove(self.streams[checkbox_index])

        # validating the field after some option is selected
        self.check_stream_field_validity()

    # function to check if any option (from the drop-down) is selected or not
    def validate_combobox(self, combobox, field_number):
        combobox_index = combobox.currentIndex()

        # checking if 1st option is selected; 1st option is not a real option (like "-- select --", "choose one" etc)
        if combobox_index == 0:
            self.remove_validity(self.InvalidInputFields, field_number)
            self.remove_validity(self.ignoredWarnings, field_number)
            self.update_warnings(field_number, False)
        else:
            self.add_validity(self.InvalidInputFields, field_number)
            self.add_validity(self.ignoredWarnings, field_number)
            self.update_warnings(field_number, True)

        # function added later, to re-check all fields validity and enable/disable "next" button accordingly
        if len(self.InvalidInputFields) == 0:
            self.footerWidgetRef.nextButton.setEnabled(True)
        else:
            self.footerWidgetRef.nextButton.setEnabled(False)

    # function to display updated warnings after some input (either wrong or right)
    def update_warnings(self, current_field_no, field_validity_status):
        # following will be used to put correct field name in warning at run time.
        fields_name = [
            "Name", "Address", "Board", "Education", "Stream", "Classes", "Teachers", "Shift", "Time", "Days"
        ]
        # debugging
        print(f"called by {fields_name[current_field_no - 1]}")
        print(f"current value of no. of warnings: {len(self.ignoredWarnings)}")

        if len(self.ignoredWarnings) > 1:
            print(f"\nIF CASE: total warnings = {len(self.ignoredWarnings)}")
            warning_to_send = f"" \
                f"[Multiple warnings] " \
                f"Invalid {fields_name[current_field_no - 1]} field " \
                f"and {len(self.ignoredWarnings) - 1} more fields. "

            self.footerWidgetRef.show_warning(warning_to_send)
        elif len(self.ignoredWarnings) == 1:
            print(f"ELIF CASE: total warnings = {len(self.ignoredWarnings)}")
            if field_validity_status:
                # getting 1st invalid field (from ignoredWarnings)
                new_field_no = self.ignoredWarnings[0]
                self.send_warning_to_prompt_area_for(new_field_no)
            else:
                self.send_warning_to_prompt_area_for(current_field_no)

        else:       # len(self.ignoredWarnings) == 0
            print(f"ELSE CASE: total warnings = {len(self.ignoredWarnings)}")
            self.footerWidgetRef.hide_warning()

    @staticmethod
    # mark given field as invalid
    def remove_validity(the_list, field_number):
        if not index_exists_in(the_list, field_number):
            the_list.append(field_number)

    @staticmethod
    # mark given field as valid
    def add_validity(the_list, field_number):
        if index_exists_in(the_list, field_number):
            the_list.remove(field_number)

    # function to send suitable waring message to Settings_Footer's prompt area
    def send_warning_to_prompt_area_for(self, field_no):
        print(f"\nNo. of Warnings: {len(self.ignoredWarnings)}")
        warning_to_send = self.warningMessages[f"{field_no}"]
        self.footerWidgetRef.show_warning(warning_to_send)

    # store information into the database (called upon clicking of "next" button)
    def initialize_school_configurations(self):
        school_name = self.schoolNameField.text()
        address_line1 = self.schoolAddressFieldPart1.text()
        address_line2 = self.schoolAddressFieldPart2.text()
        address_line3 = self.schoolAddressFieldPart3.text()
        school_address = f'{address_line1} \n {address_line2} \n {address_line3}'
        board_name = self.boardField.currentText()
        education_level = self.educationLevelField.currentText()
        no_of_shifts = self.shiftField.currentText()
        total_classes = self.classCountField.text()
        total_teachers = self.teacherCountField.text()
        start_timing = self.schoolStartTimeField.text()
        end_timing = self.schoolEndTimeField.text()

        print(f'Opted values are as follow:'
              f'School Name: {school_name}\n'
              f'School Address: {school_address}\n'
              f'board Name: {board_name}\n'
              f'Education Level: {education_level}\n'
              f'Streams available: {self.streamSelected}\n'
              f'Working Days: {self.daysSelected}\n'
              f'No. of Classes: {total_classes}\n'
              f'No. of teacher: {total_teachers}\n'
              f'No. of Shifts: {no_of_shifts}\n'
              f'Timings: From {start_timing} to {end_timing}')
Exemplo n.º 12
0
class EditFinanceCalendarWidget(QWidget):
    def __init__(self):
        super(EditFinanceCalendarWidget, self).__init__()
        layout = QVBoxLayout(margin=0)
        layout.setParent(self)
        date_layout = QHBoxLayout()
        date_layout.addWidget(QLabel("日期:", self))
        self.date_edit = QDateEdit(QDate.currentDate(), self)
        self.date_edit.setDisplayFormat("yyyy-MM-dd")
        date_layout.addWidget(self.date_edit)
        date_layout.addStretch()
        layout.addLayout(date_layout)
        time_layout = QHBoxLayout()
        time_layout.addWidget(QLabel("时间:", self))
        self.time_edit = QTimeEdit(QTime.currentTime(), self)
        self.time_edit.setDisplayFormat('hh:mm:ss')
        time_layout.addWidget(self.time_edit)
        time_layout.addStretch()
        layout.addLayout(time_layout)
        area_layout = QHBoxLayout()
        area_layout.addWidget(QLabel('地区:', self))
        self.area_edit = QLineEdit(self)
        area_layout.addWidget(self.area_edit)
        layout.addLayout(area_layout)
        event_layout = QHBoxLayout()
        event_layout.addWidget(QLabel('事件:', self), alignment=Qt.AlignTop)
        self.event_edit = QTextEdit(self)
        self.event_edit.setFixedHeight(100)
        event_layout.addWidget(self.event_edit)
        layout.addLayout(event_layout)
        expected_layout = QHBoxLayout()
        expected_layout.addWidget(QLabel('预期值:', self))
        self.expected_edit = QLineEdit(self)
        expected_layout.addWidget(self.expected_edit)
        layout.addLayout(expected_layout)
        self.commit_button = QPushButton("提交", self)
        self.commit_button.clicked.connect(self.commit_financial_calendar)
        layout.addWidget(self.commit_button, alignment=Qt.AlignRight)
        self.setLayout(layout)

    def commit_financial_calendar(self):
        date = self.date_edit.text().strip()
        time = self.time_edit.text().strip()
        area = self.area_edit.text().strip()
        event = self.event_edit.toPlainText()
        expected = self.expected_edit.text().strip()

        if not all([date, time, area, event]):
            QMessageBox.information(self, "错误", "请填写完整信息")
            return
        try:
            r = requests.post(
                url=settings.SERVER_ADDR + 'fecalendar/',
                headers={"Content-Type": "application/json;charset=utf8"},
                data=json.dumps({
                    'utoken':
                    settings.app_dawn.value('AUTHORIZATION'),
                    'date':
                    date,
                    'time':
                    time,
                    'country':
                    area,
                    'event':
                    event,
                    'expected':
                    expected,
                }))
            response = json.loads(r.content.decode('utf8'))
            if r.status_code != 201:
                raise ValueError(response['message'])
        except Exception as e:
            QMessageBox.information(self, '错误', str(e))
        else:

            QMessageBox.information(self, "成功", response['message'])
class DataWidget(QWidget):
    def __init__(self, parent, shared_data):
        super(DataWidget, self).__init__(parent)
        self.__shared_data = shared_data
        self.__shared_data.update_sync.emit()

        # Add the file selection controls
        self.__dir_picker_button = QPushButton()
        self.__dir_picker_button.setEnabled(True)
        self.__dir_picker_button.setText("Load data")
        self.__dir_picker_button.setIcon(self.style().standardIcon(QStyle.SP_DirIcon))
        self.__dir_picker_button.setToolTip('Select the directory using the file explorer')
        self.__dir_picker_button.clicked.connect(self.__open_dir_picker)

        # Add the sync controls
        self.__sync_time_label = QLabel()
        self.__sync_time_label.setText('Enter the timecode (HH:mm:ss:zzz) : ')

        self.__sync_time_edit = QTimeEdit()
        self.__sync_time_edit.setDisplayFormat('HH:mm:ss:zzz')
        self.__sync_time_edit.setEnabled(False)

        self.__sync_time_button = QPushButton()
        self.__sync_time_button.setText('Sync data')
        self.__sync_time_button.setEnabled(False)
        self.__sync_time_button.clicked.connect(self.__sync_data)

        # Create the layout for the file controls
        dir_layout = QHBoxLayout()
        dir_layout.setContentsMargins(0, 0, 0, 0)
        dir_layout.addWidget(self.__dir_picker_button)
        dir_layout.addStretch(1)
        dir_layout.addWidget(self.__sync_time_label)
        dir_layout.addWidget(self.__sync_time_edit)
        dir_layout.addWidget(self.__sync_time_button)

        # Create the axis and their viewbox
        self.__x_axis_item = AxisItem('left')
        self.__y_axis_item = AxisItem('left')
        self.__z_axis_item = AxisItem('left')

        self.__x_axis_viewbox = ViewBox()
        self.__y_axis_viewbox = ViewBox()
        self.__z_axis_viewbox = ViewBox()

        # Create the widget which will display the data
        self.__graphic_view = GraphicsView(background="#ecf0f1")
        self.__graphic_layout = GraphicsLayout()
        self.__graphic_view.setCentralWidget(self.__graphic_layout)

        # Add the axis to the widget
        self.__graphic_layout.addItem(self.__x_axis_item, row=2, col=3, rowspan=1, colspan=1)
        self.__graphic_layout.addItem(self.__y_axis_item, row=2, col=2, rowspan=1, colspan=1)
        self.__graphic_layout.addItem(self.__z_axis_item, row=2, col=1, rowspan=1, colspan=1)

        self.__plot_item = PlotItem()
        self.__plot_item_viewbox = self.__plot_item.vb
        self.__graphic_layout.addItem(self.__plot_item, row=2, col=4, rowspan=1, colspan=1)

        self.__graphic_layout.scene().addItem(self.__x_axis_viewbox)
        self.__graphic_layout.scene().addItem(self.__y_axis_viewbox)
        self.__graphic_layout.scene().addItem(self.__z_axis_viewbox)

        self.__x_axis_item.linkToView(self.__x_axis_viewbox)
        self.__y_axis_item.linkToView(self.__y_axis_viewbox)
        self.__z_axis_item.linkToView(self.__z_axis_viewbox)

        self.__x_axis_viewbox.setXLink(self.__plot_item_viewbox)
        self.__y_axis_viewbox.setXLink(self.__plot_item_viewbox)
        self.__z_axis_viewbox.setXLink(self.__plot_item_viewbox)

        self.__plot_item_viewbox.sigResized.connect(self.__update_views)
        self.__x_axis_viewbox.enableAutoRange(axis=ViewBox.XAxis, enable=True)
        self.__y_axis_viewbox.enableAutoRange(axis=ViewBox.XAxis, enable=True)
        self.__z_axis_viewbox.enableAutoRange(axis=ViewBox.XAxis, enable=True)

        # Create the final layout
        self.__v_box = QVBoxLayout()
        self.__v_box.addLayout(dir_layout)
        self.__v_box.addWidget(self.__graphic_view)

        self.setLayout(self.__v_box)

        self.__restore_state()

    def __open_dir_picker(self):
        self.__shared_data.data_file_path = QFileDialog.getOpenFileUrl(self, 'Open the Hexoskin data directory',
                                                                       QDir.homePath())[0]
        if self.__shared_data.data_file_path is not None:
            try:
                self.__load_data()
                self.__add_selector_acc_gyr()
                self.__show_data('ACC_X', 'ACC_Y', 'ACC_Z')
            except FileNotFoundError:
                pass
            except UnicodeDecodeError:
                pass

    def __load_data(self):
        if self.__shared_data.data_file_path is not None:
            self.__shared_data.import_parameter()

    def __show_data(self, field1, field2, field3):
        if self.__shared_data.parameter is not None:
            # Generate the timecodes if needed
            if len(self.__shared_data.parameter['TIMECODE']) == 0:
                if self.__shared_data.sampling_rate is None:
                    result = False
                    while not result and result == 0:
                        result = self.__show_sampling_rate_picker()

                self.__shared_data.add_timecode()

            self.__x_axis_viewbox.clear()
            self.__y_axis_viewbox.clear()
            self.__z_axis_viewbox.clear()

            # Show the 3 selected fields
            self.__x_axis_viewbox.addItem(PlotCurveItem(list(map(int, self.__shared_data.parameter.get(field1))),
                                                        pen='#34495e'))
            self.__y_axis_viewbox.addItem(PlotCurveItem(list(map(int, self.__shared_data.parameter.get(field2))),
                                                        pen='#9b59b6'))
            self.__z_axis_viewbox.addItem(PlotCurveItem(list(map(int, self.__shared_data.parameter.get(field3))),
                                                        pen='#3498db'))

            self.__x_axis_item.setLabel(field1, color="#34495e")
            self.__y_axis_item.setLabel(field2, color="#9b59b6")
            self.__z_axis_item.setLabel(field3, color="#3498db")

            # Add the middle line and the bottom timecodes
            timecodes = self.__shared_data.parameter['TIMECODE']
            middle = [0] * len(timecodes)
            self.__plot_item_viewbox.addItem(PlotCurveItem(middle, pen='#000000'))
            self.__plot_item.getAxis('bottom').setTicks(
                self.__generate_time_ticks(timecodes, self.__shared_data.sampling_rate))

            # Enable the controls
            self.__sync_time_edit.setEnabled(True)
            self.__sync_time_button.setEnabled(True)
            self.__dir_picker_button.setEnabled(False)
        self.__update_views()

    def __update_views(self):
        self.__x_axis_viewbox.setGeometry(self.__plot_item_viewbox.sceneBoundingRect())
        self.__y_axis_viewbox.setGeometry(self.__plot_item_viewbox.sceneBoundingRect())
        self.__z_axis_viewbox.setGeometry(self.__plot_item_viewbox.sceneBoundingRect())

    def __generate_time_ticks(self, timecodes, rate):
        ticks = list()

        steps = [rate * 30, rate * 15, rate * 5, rate]
        for step in steps:
            temp = list()
            i = step
            while i in range(len(timecodes)):
                temp.append((i, timecodes[i].strftime('%H:%M:%S:') + str(int(timecodes[i].microsecond / 1000))))
                i += step
            ticks.append(temp)

        return ticks

    def __sync_data(self):
        self.__shared_data.data_sync = self.__sync_time_edit.text()
        self.__shared_data.update_sync.emit()

    def __show_sampling_rate_picker(self) -> bool:
        self.__shared_data.sampling_rate, result = QInputDialog.getInt(self, 'Set sampling rate value', 'Sampling rate')
        return result

    def __add_selector_acc_gyr(self):
        if 'GYR_X' in self.__shared_data.parameter.keys() or 'GYR_Y' in self.__shared_data.parameter.keys() \
                or 'GYR_Z' in self.__shared_data.parameter.keys():
            show_acc = QPushButton()
            show_acc.setText('Show Accelerometer Axis')
            show_acc.clicked.connect(self.__show_acc)

            show_gyr = QPushButton()
            show_gyr.setText('Show Gyroscope Axis')
            show_gyr.clicked.connect(self.__show_gyr)

            layout = QHBoxLayout()
            layout.addWidget(show_acc)
            layout.addWidget(show_gyr)
            layout.addStretch(1)

            self.__v_box.addLayout(layout)

    def __show_acc(self):
        self.__show_data('ACC_X', 'ACC_Y', 'ACC_Z')

    def __show_gyr(self):
        self.__show_data('GYR_X', 'GYR_Y', 'GYR_Z')

    def __restore_state(self):
        if self.__shared_data.parameter is not None:
            self.__add_selector_acc_gyr()
            self.__show_data('ACC_X', 'ACC_Y', 'ACC_Z')
            print('trigger reimport')
        if self.__shared_data.data_sync is not None:
            text_time = self.__shared_data.data_sync.split(':')
            time = QTime()
            time.setHMS(int(text_time[0]), int(text_time[1]), int(text_time[2]), int(text_time[3]))
            self.__sync_time_edit.setTime(time)