def initUI(self):      

        cal = QCalendarWidget(self)
        cal.setGridVisible(True)
        cal.move(20, 20)
        cal.clicked[QDate].connect(self.showDate)
        
        self.lbl = QLabel(self)
        date = cal.selectedDate()
        self.lbl.setText(date.toString())
        self.lbl.move(130, 260)
        
        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle('Calendar')
        self.show()
Ejemplo n.º 2
0
 def select_date(self, button):
     d = WindowModalDialog(self, _("Select date"))
     d.setMinimumSize(600, 150)
     d.date = None
     vbox = QVBoxLayout()
     def on_date(date):
         d.date = date
     cal = QCalendarWidget()
     cal.setGridVisible(True)
     cal.clicked[QDate].connect(on_date)
     vbox.addWidget(cal)
     vbox.addLayout(Buttons(OkButton(d), CancelButton(d)))
     d.setLayout(vbox)
     if d.exec_():
         if d.date is None:
             return None
         date = d.date.toPyDate()
         button.setText(self.format_date(date))
         return datetime.datetime(date.year, date.month, date.day)
Ejemplo n.º 3
0
    def select_date(self, button):
        d = WindowModalDialog(self, _("Select date"))
        d.setMinimumSize(600, 150)
        d.date = None
        vbox = QVBoxLayout()

        def on_date(date):
            d.date = date

        cal = QCalendarWidget()
        cal.setGridVisible(True)
        cal.clicked[QDate].connect(on_date)
        vbox.addWidget(cal)
        vbox.addLayout(Buttons(OkButton(d), CancelButton(d)))
        d.setLayout(vbox)
        if d.exec_():
            if d.date is None:
                return None
            date = d.date.toPyDate()
            button.setText(self.format_date(date))
            return datetime.datetime(date.year, date.month, date.day)
Ejemplo n.º 4
0
    def initUI(self):

        vbox = QVBoxLayout(self)

        cal = QCalendarWidget(self)
        cal.setGridVisible(True)
        cal.clicked[QDate].connect(self.showDate)

        vbox.addWidget(cal)

        self.lbl = QLabel(self)
        date = cal.selectedDate()
        self.lbl.setText('开始时间 ' + date.toString())

        vbox.addWidget(self.lbl)

        self.setLayout(vbox)

        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle('Calendar')
        self.show()
Ejemplo n.º 5
0
        def pick_time(start_or_end):
            """Date picker."""
            dlg = QDialog(self)
            gridc = QVBoxLayout()
            dlg.setLayout(gridc)
            if (start_or_end == "start"):
                title_str = "Start date"
            else:
                title_str = "End date"
            titlelabel = QLabel(title_str)
            gridc.addWidget(titlelabel)

            my_calendar = QCalendarWidget()
            my_calendar.setGridVisible(True)
            my_calendar.move(10, 20)
            gridc.addWidget(my_calendar)

            labeldate = QLabel("")
            gridc.addWidget(labeldate)

            def dial_exit():
                dlg.done(1)

            buttonc = QPushButton("Close")
            buttonc.clicked.connect(dial_exit)
            gridc.addWidget(buttonc)

            def show_date():
                date = my_calendar.selectedDate()
                date_string = date.toString('yyyy-MM-dd')
                if (start_or_end == "start"):
                    self.time_start_box.setText(date_string + " 00:00:01")
                else:
                    self.time_end_box.setText(date_string + " 23:59:59")
                labeldate.setText(date_string)

            my_calendar.clicked[QDate].connect(show_date)

            dlg.setWindowTitle("Calendar")
            dlg.exec_()
Ejemplo n.º 6
0
class QCalendarWidgetDemo(QWidget):
    def __init__(self):
        super(QCalendarWidgetDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('日历控件测试')
        self.resize(300, 600)
        self.cal = QCalendarWidget(self)
        self.cal.setMinimumDate(QDate(1997, 6, 20))
        self.cal.setMaximumDate(QDate(2020, 6, 20))
        self.cal.setGridVisible(True)  # 设置网格
        self.cal.move(20, 20)

        self.cal.clicked.connect(self.SelectDate)

        self.label = QLabel(self)
        self.label.setText(self.cal.selectedDate().toString('yyyy/MM/dd dddd'))
        self.label.move(20, 300)

    def SelectDate(self):
        self.label.setText(self.cal.selectedDate().toString('yyyy/MM/dd dddd'))
Ejemplo n.º 7
0
class calendarDemo(QWidget):
    def __init__(self):
        super(calendarDemo, self).__init__()
        self.initUI()
        self.resize(500, 500)

    def initUI(self):
        self.cal = QCalendarWidget(self)
        self.cal.setMinimumDate(QDate(1988, 1, 1))
        self.cal.setMaximumDate(QDate(2088, 1, 1))
        self.cal.setGridVisible(True)  # 以网格形式显示

        self.cal.clicked.connect(self.showDate)
        self.label = QLabel(self)
        date = self.cal.selectedDate()
        self.label.setText(date.toString("yyyy-MM-dd dddd"))
        self.label.move(100, 400)

    def showDate(self, date):
        # self.label.setText((date.toString("yyyy-MM-dd dddd")))
        self.label.setText(
            (self.cal.selectedDate().toString("yyyy-MM-dd dddd")))
Ejemplo n.º 8
0
    def initUI(self):

        vbox = QVBoxLayout(self)

        cal = QCalendarWidget(self)  # 创建一个QCalendarWidget
        cal.setGridVisible(True)
        cal.clicked[QDate].connect(
            self.showDate
        )  # 选择一个日期时,QDate的点击信号就触发了,把这个信号和我们自定义的showDate()方法关联起来

        vbox.addWidget(cal)

        self.lbl = QLabel(self)
        date = cal.selectedDate()  # 使用selectedDate()方法获取选中的日期
        self.lbl.setText(date.toString())  # 把日期对象转换成字符串,在标签里面显示出来

        vbox.addWidget(self.lbl)
        self.setLayout(vbox)

        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle('Calendar')
        self.show()
Ejemplo n.º 9
0
class Demo(QWidget):
    def __init__(self):
        super(Demo, self).__init__()
        self.calendar = QCalendarWidget(self)
        self.calendar.setMinimumDate(
            QDate(1946, 2, 14))                        # 2
        self.calendar.setMaximumDate(
            QDate(2099, 6, 6))                         # 3
        # self.calendar.setDateRange(QDate(1946, 2, 14), QDate(6666, 6, 6))
        # self.calendar.setFirstDayOfWeek(
        #     Qt.Monday)                            # 4
        # self.calendar.setSelectedDate(QDate(1946, 2, 14))                     # 5
        self.calendar.setGridVisible(
            True)                                      # 6
        self.calendar.clicked.connect(
            self.show_emotion_func)                   # 6

        # 7
        print(self.calendar.minimumDate())
        print(self.calendar.maximumDate())
        print(self.calendar.selectedDate())

        # 8
        self.label = QLabel(self)
        self.label.setAlignment(Qt.AlignCenter)

        weekday = self.calendar.selectedDate().toString('ddd')                  # 9
        self.label.setText(EMOTION[weekday])

        self.v_layout = QVBoxLayout()
        self.v_layout.addWidget(self.calendar)
        self.v_layout.addWidget(self.label)

        self.setLayout(self.v_layout)
        self.setWindowTitle('QCalendarWidget')

    def show_emotion_func(self):                                                # 10
        weekday = self.calendar.selectedDate().toString('ddd')
        self.label.setText(EMOTION[weekday])
    def initUI(self):
        VBox = QVBoxLayout()
        calendar = QCalendarWidget(self)
        calendar.setGridVisible(True)
        # calendar.move(20, 20)
        calendar.clicked[QDate].connect(self.showDate)

        label = QLabel(self)
        date = calendar.selectedDate()
        label.setText(self.getDate(date))
        # label.move(130, 260)
        label.setAlignment(Qt.AlignCenter)
        self.label = label

        self.calendar = calendar

        VBox.addWidget(calendar, 5)
        VBox.addWidget(label, 1)

        self.setLayout(VBox)

        clearButton = QPushButton("不限", self)
        confirmButton = QPushButton("选择", self)
        cancelButton = QPushButton("取消", self)
        clearButton.clicked.connect(self.clearCallback)
        confirmButton.clicked.connect(self.acceptCallback)
        cancelButton.clicked.connect(self.reject)
        Hbox = QHBoxLayout()
        Hbox.addWidget(clearButton)
        Hbox.addWidget(confirmButton)
        Hbox.addWidget(cancelButton)

        VBox.addLayout(Hbox)

        self.resize(350, 300)
        self.center()
        self.setWindowTitle('日历控件')
        self.show()
Ejemplo n.º 11
0
    def initUI(self):

        vbox = QVBoxLayout(self)

        # 初始化一个日期控件
        cal = QCalendarWidget(self)
        cal.setGridVisible(True)
        # 将选择日期和显示日期绑定
        cal.clicked[QDate].connect(self.showDate)

        vbox.addWidget(cal)

        self.lbl = QLabel(self)
        date = cal.selectedDate()
        self.lbl.setText(date.toString())

        vbox.addWidget(self.lbl)

        self.setLayout(vbox)

        self.setGeometry(300, 300, 280, 170)
        self.setWindowTitle('进度条')
        self.show()
Ejemplo n.º 12
0
class SelectorFechaVentana(QMainWindow):
    def __init__(self):
        super().__init__()

        self.inicializarGui()

    def inicializarGui(self):
        self.setWindowTitle('Selector Fecha')
        self.setFixedSize(300, 300)

        self.calendario = QCalendarWidget(self)
        self.calendario.setGridVisible(True)
        self.calendario.move(30, 20)
        self.calendario.setFixedWidth(200)
        self.calendario.setFixedHeight(200)
        self.calendario.clicked[QDate].connect(self.mostrar_fecha_seleccionada)

        self.lbl_fecha_seleccionada = QLabel('', self)
        self.lbl_fecha_seleccionada.move(30, 220)
        self.lbl_fecha_seleccionada.setFixedWidth(250)

    def mostrar_fecha_seleccionada(self, fecha):
        self.lbl_fecha_seleccionada.setText(fecha.toString())
Ejemplo n.º 13
0
class CalendarDialog(QDialog):
    def __init__(self, *arg, **kwargs):
        super().__init__(*arg, **kwargs)
        self.setWindowTitle("Выберите дату")
        vbox = QVBoxLayout(self)
        self.calendar = QCalendarWidget()
        self.calendar.setGridVisible(True)
        self.calendar.setDateEditEnabled(False)
        button_save = QPushButton("Ок")
        button_save.clicked.connect(self.accept)
        vbox.addWidget(self.calendar)
        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(button_save)
        vbox.addLayout(hbox)

    def get_date(self):
        date = self.calendar.selectedDate().toString(Qt.ISODate)
        date = datetime.strptime(date, "%Y-%m-%d").date()
        return date

    def set_date(self, date):
        self.calendar.setSelectedDate(date)
Ejemplo n.º 14
0
    def initUI(self):
        cal = QCalendarWidget(self)
        cal.setGridVisible(True)
        cal.clicked[QDate].connect(self.showDate)

        self.lbl = QLabel(self)
        date = cal.selectedDate()
        self.lbl.setText(date.toString())

        self.calText = QTextEdit()
        self.calText.setText("")

        vbox = QVBoxLayout()
        vbox.addWidget(cal)
        vbox.addWidget(self.lbl)
        vbox.addWidget(self.calText)

        self.setLayout(vbox)
        self.readGoogleCal()
        self.verify()

        self.setWindowTitle('QCalendarWidget')
        self.setGeometry(300, 300, 400, 300)
        self.show()
Ejemplo n.º 15
0
    def initUI(self):
        vBox = QVBoxLayout(self)

        # 创建一个QCalendarWidget
        cal = QCalendarWidget(self)
        cal.setGridVisible(True)
        # 选择一个日期,QDate 的点击信号就触发了,把这个信号和我们自己定义的
        # showDate()方法关联起来
        cal.clicked[QDate].connect(self.showDate)

        vBox.addWidget(cal)

        self.lbl = QLabel(self)
        # 使用 selectDate()方法获取选中的日期
        date = cal.selectedDate()
        self.lbl.setText(date.toString())

        vBox.addWidget(self.lbl)

        self.setLayout(vBox)

        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle('Calender')
        self.show()
Ejemplo n.º 16
0
class Ui_PostX_Calendar(object):
    def setupUi(self, PostX_Calendar):
        PostX_Calendar.setObjectName(_fromUtf8("PostX_Calendar"))
        PostX_Calendar.resize(500, 300)
        palette = QPalette()
        brush = QBrush(QColor(245, 245, 225))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.WindowText, brush)
        brush = QBrush(QColor(59, 58, 55))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.Button, brush)
        brush = QBrush(QColor(88, 87, 82))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.Light, brush)
        brush = QBrush(QColor(73, 72, 68))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.Midlight, brush)
        brush = QBrush(QColor(29, 29, 27))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.Dark, brush)
        brush = QBrush(QColor(39, 38, 36))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.Mid, brush)
        brush = QBrush(QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.Text, brush)
        brush = QBrush(QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.BrightText, brush)
        brush = QBrush(QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.ButtonText, brush)
        brush = QBrush(QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.Base, brush)
        brush = QBrush(QColor(59, 58, 55))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.Window, brush)
        brush = QBrush(QColor(0, 0, 74))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.Shadow, brush)
        brush = QBrush(QColor(29, 29, 27))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.AlternateBase, brush)
        brush = QBrush(QColor(255, 255, 220))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.ToolTipBase, brush)
        brush = QBrush(QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.ToolTipText, brush)
        brush = QBrush(QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.WindowText, brush)
        brush = QBrush(QColor(59, 58, 55))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.Button, brush)
        brush = QBrush(QColor(88, 87, 82))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.Light, brush)
        brush = QBrush(QColor(73, 72, 68))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.Midlight, brush)
        brush = QBrush(QColor(29, 29, 27))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.Dark, brush)
        brush = QBrush(QColor(39, 38, 36))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.Mid, brush)
        brush = QBrush(QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.Text, brush)
        brush = QBrush(QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.BrightText, brush)
        brush = QBrush(QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.ButtonText, brush)
        brush = QBrush(QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.Base, brush)
        brush = QBrush(QColor(59, 58, 55))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.Window, brush)
        brush = QBrush(QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.Shadow, brush)
        brush = QBrush(QColor(29, 29, 27))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.AlternateBase, brush)
        brush = QBrush(QColor(255, 255, 220))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.ToolTipBase, brush)
        brush = QBrush(QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.ToolTipText, brush)
        brush = QBrush(QColor(29, 29, 27))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.WindowText, brush)
        brush = QBrush(QColor(59, 58, 55))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.Button, brush)
        brush = QBrush(QColor(88, 87, 82))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.Light, brush)
        brush = QBrush(QColor(73, 72, 68))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.Midlight, brush)
        brush = QBrush(QColor(29, 29, 27))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.Dark, brush)
        brush = QBrush(QColor(39, 38, 36))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.Mid, brush)
        brush = QBrush(QColor(29, 29, 27))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.Text, brush)
        brush = QBrush(QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.BrightText, brush)
        brush = QBrush(QColor(29, 29, 27))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.ButtonText, brush)
        brush = QBrush(QColor(59, 58, 55))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.Base, brush)
        brush = QBrush(QColor(59, 58, 55))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.Window, brush)
        brush = QBrush(QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.Shadow, brush)
        brush = QBrush(QColor(59, 58, 55))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.AlternateBase, brush)
        brush = QBrush(QColor(255, 255, 220))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.ToolTipBase, brush)
        brush = QBrush(QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.ToolTipText, brush)
        PostX_Calendar.setPalette(palette)
        PostX_Calendar.setWindowOpacity(1.0)
        self.horizontalLayout = QHBoxLayout(PostX_Calendar)
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        self.calendarWidget = QCalendarWidget(PostX_Calendar)
        palette = QPalette()
        brush = QBrush(QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.WindowText, brush)
        brush = QBrush(QColor(97, 97, 97))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.Button, brush)
        brush = QBrush(QColor(146, 146, 146))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.Light, brush)
        brush = QBrush(QColor(121, 121, 121))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.Midlight, brush)
        brush = QBrush(QColor(48, 48, 48))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.Dark, brush)
        brush = QBrush(QColor(64, 64, 64))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.Mid, brush)
        brush = QBrush(QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.Text, brush)
        brush = QBrush(QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.BrightText, brush)
        brush = QBrush(QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.ButtonText, brush)
        brush = QBrush(QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.Base, brush)
        brush = QBrush(QColor(97, 97, 97))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.Window, brush)
        brush = QBrush(QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.Shadow, brush)
        brush = QBrush(QColor(48, 48, 48))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.AlternateBase, brush)
        brush = QBrush(QColor(255, 255, 220))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.ToolTipBase, brush)
        brush = QBrush(QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.ToolTipText, brush)
        brush = QBrush(QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.WindowText, brush)
        brush = QBrush(QColor(97, 97, 97))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.Button, brush)
        brush = QBrush(QColor(146, 146, 146))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.Light, brush)
        brush = QBrush(QColor(121, 121, 121))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.Midlight, brush)
        brush = QBrush(QColor(48, 48, 48))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.Dark, brush)
        brush = QBrush(QColor(64, 64, 64))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.Mid, brush)
        brush = QBrush(QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.Text, brush)
        brush = QBrush(QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.BrightText, brush)
        brush = QBrush(QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.ButtonText, brush)
        brush = QBrush(QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.Base, brush)
        brush = QBrush(QColor(97, 97, 97))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.Window, brush)
        brush = QBrush(QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.Shadow, brush)
        brush = QBrush(QColor(48, 48, 48))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.AlternateBase, brush)
        brush = QBrush(QColor(255, 255, 220))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.ToolTipBase, brush)
        brush = QBrush(QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.ToolTipText, brush)
        brush = QBrush(QColor(48, 48, 48))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.WindowText, brush)
        brush = QBrush(QColor(97, 97, 97))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.Button, brush)
        brush = QBrush(QColor(146, 146, 146))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.Light, brush)
        brush = QBrush(QColor(121, 121, 121))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.Midlight, brush)
        brush = QBrush(QColor(48, 48, 48))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.Dark, brush)
        brush = QBrush(QColor(64, 64, 64))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.Mid, brush)
        brush = QBrush(QColor(48, 48, 48))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.Text, brush)
        brush = QBrush(QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.BrightText, brush)
        brush = QBrush(QColor(48, 48, 48))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.ButtonText, brush)
        brush = QBrush(QColor(97, 97, 97))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.Base, brush)
        brush = QBrush(QColor(97, 97, 97))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.Window, brush)
        brush = QBrush(QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.Shadow, brush)
        brush = QBrush(QColor(97, 97, 97))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.AlternateBase, brush)
        brush = QBrush(QColor(255, 255, 220))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.ToolTipBase, brush)
        brush = QBrush(QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.ToolTipText, brush)
        self.calendarWidget.setPalette(palette)
        font = QFont()
        font.setFamily(_fromUtf8("Monospace"))
        font.setPointSize(12)
        font.setStyleStrategy(QFont.PreferAntialias)
        self.calendarWidget.setFont(font)
        self.calendarWidget.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu)
        self.calendarWidget.setFirstDayOfWeek(QtCore.Qt.Monday)
        self.calendarWidget.setGridVisible(True)
        self.calendarWidget.setHorizontalHeaderFormat(
            QCalendarWidget.ShortDayNames)
        self.calendarWidget.setDateEditEnabled(True)
        self.calendarWidget.setObjectName(_fromUtf8("calendarWidget"))
        self.horizontalLayout.addWidget(self.calendarWidget)

        self.retranslateUi(PostX_Calendar)
        QtCore.QMetaObject.connectSlotsByName(PostX_Calendar)

    def retranslateUi(self, PostX_Calendar):
        PostX_Calendar.setWindowTitle(
            _translate("PostX_Calendar", "PostX-Calendar-QT5", None))
        PostX_Calendar.setToolTip(
            _translate("PostX_Calendar", "PostX-Calendar", None))
        self.calendarWidget.setToolTip(
            _translate("PostX_Calendar", "PostX-Calendar", None))
Ejemplo n.º 17
0
class MainWindow(QMainWindow):

    mySignal = pyqtSignal(dict)
    acquireDataSignal = pyqtSignal(str)

    acquireMostCommonEmojis = pyqtSignal()

    loadNewFileSignal = pyqtSignal(str)

    setMinDateSignal = pyqtSignal(object)
    setMaxDateSignal = pyqtSignal(object)

    def makeConnections(self, otherObject):
        self.mySignal.connect(otherObject.onJob)

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

        QMainWindow.__init__(self)

        self.currentData = {}
        self.indx = 0
        self.indxPlotTable = {
            0: 'Emojis',
            1: 'Words',
            2: 'Messages by user',
            3: 'Media messages by user'
        }
        self.currentFile = ""

        self.title = 'Whatsapp Statisic Application'

        self.mindataToDisplay = date(1900, 1, 1)
        self.currentMinData = date(1900, 1, 1)

        self.maxdataToDisplay = date(2100, 12, 31)
        self.currentMaxData = date(2100, 12, 31)

        self.setWindowTitle(self.title)
        self.setGeometry(30, 30, 1280, 1024)
        self.statusBar().showMessage('Ready')

        self.initMenubar()
        self.initToolBar()
        self.plotWidget = WidgetPlot(self)

        widget = QWidget(self)
        self.setCentralWidget(widget)
        vlay = QVBoxLayout(widget)

        self.nameLabel = QLabel('Min Date', self)
        self.nameLabel2 = QLabel('Max Date', self)

        self.nameLabel.setFont(QFont('Arial', 20))
        self.nameLabel2.setFont(QFont('Arial', 20))

        self.pyCal = QCalendarWidget()
        self.pyCal.setGridVisible(True)
        self.pyCal.clicked[QDate].connect(self.sendMinDate)

        self.pyCal2 = QCalendarWidget()
        self.pyCal2.setGridVisible(True)
        self.pyCal2.clicked[QDate].connect(self.sendMaxDate)

        grid = QGridLayout()
        grid.addWidget(self.nameLabel, 0, 0, Qt.AlignCenter)
        grid.addWidget(self.nameLabel2, 0, 1, Qt.AlignCenter)
        grid.addWidget(self.pyCal, 1, 0)
        grid.addWidget(self.pyCal2, 1, 1)

        vlay.addLayout(grid)
        vlay.addWidget(self.plotWidget)

    def sendMinDate(self, date):
        self.currentMinData = date.toPyDate()
        self.setMinDateSignal.emit(self.currentMinData)

    def sendMaxDate(self, date):
        self.currentMaxData = date.toPyDate()
        self.setMaxDateSignal.emit(self.currentMaxData)

    def initMenubar(self):
        mainMenu = self.menuBar()
        mainMenu.setNativeMenuBar(False)
        fileMenu = mainMenu.addMenu('File')
        helpMenu = mainMenu.addMenu('Help')

        loadButton = QAction(QIcon('load24.png'), 'Load', self)
        loadButton.setShortcut('Ctrl+O')
        loadButton.setStatusTip('Load File')
        loadButton.triggered.connect(self.loadFile)
        fileMenu.addAction(loadButton)

        exitButton = QAction(QIcon('exit24.png'), 'Exit', self)
        exitButton.setShortcut('Ctrl+Q')
        exitButton.setStatusTip('Exit application')
        exitButton.triggered.connect(self.close)
        fileMenu.addAction(exitButton)

    def initToolBar(self):
        self.toolbar = self.addToolBar('Open')

        open_action = QAction(
            QIcon('resources\Icons\Icon_New_File_256x256.png'), '&Save', self)
        open_action.setShortcut('Ctrl+O')
        open_action.setStatusTip('Open File')
        open_action.triggered.connect(self.loadFile)
        self.toolbar.addAction(open_action)

        prevPlot_action = QAction(
            QIcon('resources\Icons\iconfinder_arrow-left_227602.png'), '&Save',
            self)
        prevPlot_action.setShortcut('Left')
        prevPlot_action.setStatusTip('Previous Plot')
        prevPlot_action.triggered.connect(self.prevPlot)
        self.toolbar.addAction(prevPlot_action)

        nextPlot_action = QAction(
            QIcon('resources\Icons\iconfinder_arrow-right_227601.png'),
            '&Save', self)
        nextPlot_action.setShortcut('Right')
        nextPlot_action.setStatusTip('Next Plot')
        nextPlot_action.triggered.connect(self.nextPlot)
        self.toolbar.addAction(nextPlot_action)

    def loadFile(self):
        fname = QFileDialog.getOpenFileName(self, 'Open file', 'c:\\',
                                            "Text files (*.txt)")
        if fname[0]:
            self.currentFile = fname[0]
            self.plotWidget.canvas.clearPlot()
            self.loadNewFileSignal.emit(self.currentFile)

    def clickMethod(self):
        print('Clicked Pyqt button.')
        print('Emit signal')
        self.mySignal.emit(dict())

        if self.line.text() == '':
            self.statusBar().showMessage('Not a Number')
        else:
            print('Number: {}'.format(float(self.line.text()) * 2))
            self.statusBar().showMessage('Introduction of a number')
            self.nameLabel2.setText(str(float(self.line.text()) * 2))

    def nextPlot(self):
        self.plotWidget.canvas.clearPlot()
        if self.currentFile != "":
            if self.indx + 1 >= len(self.indxPlotTable):
                self.indx = 0
            else:
                self.indx = self.indx + 1

            self.acquireDataSignal.emit(self.indxPlotTable[self.indx])

    def prevPlot(self):
        self.plotWidget.canvas.clearPlot()
        if self.currentFile != "":
            if self.indx - 1 < 0:
                self.indx = len(self.indxPlotTable) - 1
            else:
                self.indx = self.indx - 1

            self.acquireDataSignal.emit(self.indxPlotTable[self.indx])

    def clearPlot(self):
        self.plotWidget.canvas.clearPlot()

    @pyqtSlot(dict)
    def onData(self, data):
        self.currentData = data
        self.plotWidget.canvas.clearPlot()
        title = self.indxPlotTable[
            self.indx] + " between " + self.currentMinData.strftime(
                "%d.%m.%Y") + " and " + self.currentMaxData.strftime(
                    "%d.%m.%Y")
        self.plotWidget.canvas.plot(self.currentData, title)

    @pyqtSlot(object)
    def setMinDateInCalendar(self, minData):
        self.mindataToDisplay = minData
        self.currentMinData = minData
        self.pyCal.setMinimumDate(
            QDate(minData.year, minData.month, minData.day))
        self.pyCal2.setMinimumDate(
            QDate(minData.year, minData.month, minData.day))
        self.pyCal.setSelectedDate(
            QDate(minData.year, minData.month, minData.day))

    @pyqtSlot(object)
    def setMaxDateInCalendar(self, maxData):
        self.maxdataToDisplay = maxData
        self.currentMaxData = maxData
        self.pyCal.setMaximumDate(
            QDate(maxData.year, maxData.month, maxData.day))
        self.pyCal2.setMaximumDate(
            QDate(maxData.year, maxData.month, maxData.day))
        self.pyCal2.setSelectedDate(
            QDate(maxData.year, maxData.month, maxData.day))
Ejemplo n.º 18
0
    def __init__(self):
        super().__init__()
        self.title = "ESS VRL Unavailability Tool"
        self.top = 400
        self.left = 400
        self.width = 400
        self.height = 400
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        f = open("tdb.txt", "r")
        startdate = f.readline()
        starr = startdate.split(".")
        print(starr)

        #date = QDate.fromString()

        vbox = QVBoxLayout()
        calendar = QCalendarWidget()
        calendar.setGridVisible(True)
        calendar.setFirstDayOfWeek(QtCore.Qt.Thursday)
        #calendar.setSelectedDate()

        lbl = QLabel()
        lbl.setText("Select a Thursday date to start week with")
        vbox.addWidget(lbl)

        vbox.addWidget(calendar)

        #self.setLayout(grid)
        f = open("tdb.txt", "r")
        startdate = f.readline()
        enddate = f.readline()
        times = []
        temp_times = []

        for n in range(0, 7):
            temp_times = f.readline().split()
            times.append(temp_times)
        print(times)

        grid = QGridLayout()

        day = ["Thurs", "Fri", "Sat", "Sun", "Mon", "Tues", "Weds"]
        for i in range(1, 8):
            daycount = QLabel()
            daycount.setText(day[i - 1])
            grid.addWidget(daycount, i, 0)
            for j in range(2, 6):
                box = QLineEdit()
                box.setText(times[i - 1][j - 2])
                grid.addWidget(box, i, j)

        def handleButton():
            date = calendar.selectedDate()
            strdate = QDate.toPyDate(date)
            enddate = strdate + timedelta(days=6)

            strdate = str(strdate)
            strdate = strdate.split("-")
            enddate = str(enddate)
            enddate = enddate.split("-")
            print(strdate)
            print(enddate)
            #FILE READING
            f = open("tdb.txt", "r")
            startdate = f.readline()
            enddate = f.readline()

            times = []
            temp_times = []

            for n in range(0, 7):
                temp_times = f.readline().split()
                times.append(temp_times)
                #print(temp_times)
            msg = f.readline()
            #FILE WRITING
            f = open("tdb.txt", "w")
            f.write(strdate[2] + "." + strdate[1] + "." + strdate[0] + "\n")
            f.write(
                str(enddate[2]) + "." + str(enddate[1]) + "." +
                str(enddate[0]) + "\n")

        bbox = QVBoxLayout()
        button = QPushButton()
        button.setText("Set Unavailability")
        button.clicked.connect(handleButton)
        bbox.addWidget(button)

        vall = QVBoxLayout()
        vall.addLayout(vbox)
        vall.addLayout(grid)
        vall.addLayout(bbox)
        self.setLayout(vall)

        self.show()
Ejemplo n.º 19
0
class Add_Daily_Bill(QDialog, Ui_Daily_bill):
    def __init__(self, parent=None):
        super(Add_Daily_Bill, self).__init__(parent)
        self.setupUi(self)

        self.setWindowTitle("Daily Bill")

        self.onlyint = QtGui.QIntValidator()
        self.phone_le.setValidator(self.onlyint)
        self.bill_le.setValidator(self.onlyint)
        self.total_le.setValidator(self.onlyint)
        self.recieved_le.setValidator(self.onlyint)
        self.due_le.setValidator(self.onlyint)

        self.total_le.setEnabled(False)
        self.total_le.setText(str(0))

        self.due_le.setEnabled(False)
        self.due_le.setText(str(0))

        #self.recieved_le.setText(str(0))
        self.recieved_le.setPlaceholderText(str(0))
        self.recieved_le.textChanged.connect(self.amountdue)

        self.cal_tool_btn.clicked.connect(self.delivery_calender)
        self.new_row_btn.clicked.connect(self.newrowbtn)
        self.remove_btn.clicked.connect(self.deleterow)
        self.save_btn.clicked.connect(self.savebtn)
        self.clear_btn.clicked.connect(self.clearbtn)
        self.close_btn.clicked.connect(self.closebtn)
        self.print_btn.clicked.connect(self.printbill)

        self.total_le.textChanged.connect(self.amountdue)

        self.bill_generator()
        self.current_date()
        self.table_records()
        #self.connectdb()
        #self.totalamount()

        config_name = 'daily_bill.cfg'

        # determine if application is a script file or frozen exe
        if getattr(sys, 'frozen', False):
            application_path = os.path.dirname(sys.executable)
        elif __file__:
            application_path = os.path.dirname(__file__)

        config_path = os.path.join(application_path, config_name)

        icon_image = os.path.join(application_path, "images", "VASA_ICON.png")
        save_image = os.path.join(application_path, "images", "save.png")
        print_image = os.path.join(application_path, "images", "print.png")
        clear_image = os.path.join(application_path, "images", "clear.png")
        close_image = os.path.join(application_path, "images", "close.png")
        self.calender_image = os.path.join(application_path, "images",
                                           "calender.png")

        self.setWindowIcon(QtGui.QIcon(icon_image))

        self.save_btn.setIcon(QtGui.QIcon(save_image))
        self.save_btn.setIconSize(QtCore.QSize(30, 30))

        self.print_btn.setIcon(QtGui.QIcon(print_image))
        self.print_btn.setIconSize(QtCore.QSize(30, 30))

        self.clear_btn.setIcon(QtGui.QIcon(clear_image))
        self.clear_btn.setIconSize(QtCore.QSize(30, 30))

        self.close_btn.setIcon(QtGui.QIcon(close_image))
        self.close_btn.setIconSize(QtCore.QSize(30, 30))

    def connectdb(self):
        global cur
        global connect
        cur, con = Add_Odbc_Connection.connectdb(self)
        connect = con

        return cur
        '''global cur
        global connect

        connect = pyodbc.connect('Driver={ODBC Driver 17 for SQL Server};'
                                 'Server=DHANALAKSHMI_PC\SQLEXPRESS;'
                                 'Database=VASADB;'
                                 'Trusted_Connection=yes;')
        cur = connect.cursor()
        return cur'''

    def table_records(self):
        self.viewtable.setRowCount(0)
        self.viewtable.verticalHeader().setVisible(False)
        header = self.viewtable.horizontalHeader()
        header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
        header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
        header.setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)
        header.setSectionResizeMode(3, QtWidgets.QHeaderView.Stretch)
        header.setSectionResizeMode(4, QtWidgets.QHeaderView.ResizeToContents)
        header.setSectionResizeMode(5, QtWidgets.QHeaderView.Stretch)
        header.setStyleSheet("QHeaderView::section { border: 1px solid ;}")

        self.existingvaluechange()

        self.viewtable.itemChanged.connect(self.totalamount)

    def newrowbtn(self):
        self.combovalue()
        rowvalue = self.viewtable.rowCount()
        print('the row value is ', rowvalue)
        self.viewtable.insertRow(rowvalue)
        self.newrow()

    def newrow(self):

        self.combo1 = QComboBox()
        self.combo2 = QComboBox()
        self.combo1.addItems(self.combolist)
        self.combo1.setCurrentText('NA')

        self.combo2.addItems(self.framelist)
        self.combo2.setCurrentText('NA')

        self.rowposition = self.viewtable.rowCount() - 1
        print('The number of rows is ', self.rowposition)

        self.viewtable.setItem(self.rowposition, 0,
                               QTableWidgetItem(str(self.rowposition + 1)))
        self.viewtable.setCellWidget(self.rowposition, 1, self.combo1)
        self.viewtable.setCellWidget(self.rowposition, 2, self.combo2)
        self.combo1.currentIndexChanged.connect(self.framecomboassign)
        self.combo1.currentIndexChanged.connect(self.ratevalue)
        #self.combo2.currentIndexChanged.connect(self.ratevalue)

        print('the value is ', self.combo1.currentText())
        if self.combo1.currentText() == 'FRAME':
            self.combo2.setEnabled(True)
        else:
            self.combo2.setEnabled(False)

    def deleterow(self):
        rownum = self.viewtable.currentRow()
        print('the rownum is ', rownum)

        if rownum == -1:
            QMessageBox.warning(self, 'Warning',
                                'Please select a row for delete')
        else:

            self.viewtable.removeRow(rownum)

            rowcount = self.viewtable.rowCount()

            print('the row number is ', rowcount)

            for i in range(rowcount):
                value = i + 1
                print('the row numbers is ', i)
                rowvalue = QTableWidgetItem()
                rowvalue.setText(str(value))
                self.viewtable.setItem(i, 0, rowvalue)

            total = 0
            for row in range(rowcount):
                rowvalue = float(self.viewtable.item(row, 5).text())
                total += rowvalue
            self.total_le.setText(str(total))

    def framecomboassign(self):
        rownum = self.viewtable.currentRow()
        print('The row number value is ', rownum)
        current_value = self.combo1.currentText()
        print(current_value)
        if current_value == 'FRAME':
            self.combo2.setEnabled(True)

        else:
            self.combo2.setEnabled(False)

    def ratevalue(self):
        rownum = self.viewtable.currentRow()
        curr_value = self.combo1.currentText()
        if curr_value != 'FRAME':
            SEL_QUERY = " SELECT PRICE from dbo.PROD_DETAILS WHERE PROD_TYPE ='DAILY' AND PROD_NAME =?"

            cur.execute(SEL_QUERY, curr_value)
            result = cur.fetchall()
            rate_value = str(result[0][0])
            rate_table = QTableWidgetItem()
            rate_table.setText(rate_value)
            rate_table.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
            self.viewtable.setItem(rownum, 3, rate_table)

            self.viewtable.itemChanged.connect(self.amount_rate_calculation)

            print('the result value is ', rate_value)
            print(type(rate_value))
        else:

            self.combo2.currentIndexChanged.connect(self.frame_rate_value)

    def frame_rate_value(self):
        SEL_QUERY = "SELECT PRICE from dbo.PROD_DETAILS WHERE PROD_TYPE ='DAILY' AND PROD_NAME =? AND SIZE=?"
        frame_curr_value = self.combo2.currentText()
        curr_value = self.combo1.currentText()
        rownum = self.viewtable.currentRow()

        cur.execute(SEL_QUERY, (curr_value, frame_curr_value))
        result = cur.fetchall()
        rate_value = str(result[0][0])
        rate_table = QTableWidgetItem()
        rate_table.setText(rate_value)
        rate_table.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
        self.viewtable.setItem(rownum, 3, rate_table)

        self.viewtable.itemChanged.connect(self.amount_rate_calculation)

    def amount_rate_calculation(self, item):
        rownum = item.row()
        colnum = item.column()

        print('the row number is ', rownum)

        print('the column number is ', colnum)

        if colnum == 4:
            rate_value = self.viewtable.item(rownum, 3).text()
            print('the rate value is ', rate_value, ' and its type is ',
                  type(rate_value))

            qty_value = self.viewtable.item(rownum, 4).text()
            print('the qty value is ', qty_value)

            int_rate_value = int(rate_value)
            int_qty_value = int(qty_value)

            amount_value = int_rate_value * int_qty_value
            print('the amount value is', amount_value)
            amount_table = QTableWidgetItem()
            amount_table.setText(str(amount_value))
            amount_table.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

            self.viewtable.setItem(rownum, 5, amount_table)

    def totalamount(self, item):
        self.total_le.setEnabled(False)
        if item.column() == 5:

            rowcount = self.viewtable.rowCount()

            if rowcount == 0:
                self.total_le.setText(str(0))

            else:
                total = 0
                for row in range(rowcount):
                    rowvalue = float(self.viewtable.item(row, 5).text())
                    total += rowvalue
                self.total_le.setText(str(total))

    def amountdue(self):
        print('Amount due function in')

        print("the test value is ", self.total_le.text())
        totalamount = float(self.total_le.text())
        if self.recieved_le.text() == "":
            Recievedamount = float(0)
        else:
            Recievedamount = float(self.recieved_le.text())
        print('Amount due is ', totalamount)
        print('amoint  recieved is ', Recievedamount)

        balance = float(totalamount - Recievedamount)

        print('The balanced amount is ', balance)

        self.due_le.setText(str(balance))

    def existingvaluechange(self):
        rownum = self.viewtable.cellWidget(0, 1)
        print('The row number value is ', rownum)
        #print('The value in Row is ',self.viewtable.item(rownum,1))

    def combovalue(self):
        self.combolist = set()
        self.framelist = set()
        sel_query = "SELECT PROD_NAME from dbo.PROD_DETAILS WHERE PROD_TYPE ='DAILY'"
        self.connectdb()
        cur.execute(sel_query)
        result = cur.fetchall()

        for i in result:

            x = i[0]
            self.combolist.add(x)
        self.combolist.add('NA')

        frame_query = "SELECT SIZE FROM dbo.PROD_DETAILS WHERE PROD_TYPE ='DAILY' AND PROD_NAME ='FRAME' AND SIZE IS NOT NULL AND SIZE !=''"

        cur.execute(frame_query)
        frame_result = cur.fetchall()

        for j in frame_result:
            x = j[0]
            self.framelist.add(x)
        self.framelist.add('NA')

    def bill_generator(self):
        sel_query = 'SELECT MAX(BILL_NO) FROM dbo.BILLING_TABLE'
        self.connectdb()
        cur.execute(sel_query)
        result = cur.fetchall()
        value = result[0][0]

        if value != None:
            value = value + 1
            print(value)
        else:
            value = 1
            print('The else condition ', value)
            print(type(value))

        self.bill_le.setText(str(value))

    def current_date(self):
        now = QDate.currentDate()
        print(now)
        print(now.toString(Qt.ISODate))

        today = datetime.date.today()
        self.billdate = today.strftime("%d/%m/%Y")
        date_format = today.strftime("%d/%m/%Y %A")
        print(date_format)

        self.date_le.setText(date_format)

    def delivery_calender(self):
        self.calender = QCalendarWidget()
        self.calender.setMinimumDate(QDate(1900, 1, 1))
        self.calender.setMaximumDate(QDate(2999, 12, 31))
        self.calender.setGridVisible(True)
        self.calender.clicked.connect(self.updatedate)
        self.calender.setWindowModality(Qt.ApplicationModal)
        self.calender.setWindowTitle("Delivery Date")

        self.calender.setWindowIcon(QtGui.QIcon(self.calender_image))

        self.calender.show()

    def updatedate(self, *args):

        getdate = self.calender.selectedDate().toString("dd/MM/yyyy")
        print('get date value is ', getdate)
        self.delivery_date_le.setText(getdate)
        self.calender.deleteLater()

    def savebtn(self):

        if self.customer_le.text() == '' or self.phone_le.text() == '':
            QMessageBox.warning(self, 'Warning',
                                'Please enter the customer information')
        elif self.viewtable.rowCount() == 0:
            QMessageBox.warning(self, 'Warning', 'Please add the bill entry')

        else:
            billno = self.bill_le.text()
            orderdate = datetime.datetime.now().date()

            print('the order date value is ', orderdate, ' and type is ',
                  type(orderdate))

            customername = self.customer_le.text()
            phoneno = self.phone_le.text()
            totalamount = self.total_le.text()
            if self.recieved_le.text() == "":
                amountreceived = 0
            else:
                amountreceived = self.recieved_le.text()

            dueamount = self.due_le.text()
            deliverydate = self.delivery_date_le.text()

            phoneno = int(phoneno)
            #orderdate =
            #orderdate = datetime.datetime.strptime(orderdate,'%d/%m/%Y').date()
            #orderdate= datetime.date.today()
            print('The order date is ', orderdate, ' and type is ',
                  type(orderdate))
            totalamount = float(totalamount)
            amountreceived = float(amountreceived)
            dueamount = float(dueamount)
            billno = int(billno)

            bill_type = 'DAILY'

            if deliverydate != '':

                deliverydate = datetime.datetime.strptime(
                    deliverydate, '%d/%m/%Y').date()
            else:
                deliverydate = datetime.date(9999, 12, 31)

            print('the deliver date value is ', deliverydate, ' and type is ',
                  type(deliverydate))

            sql_order_date = orderdate.strftime("%d/%m/%Y")
            sql_delivery_date = deliverydate.strftime("%d/%m/%Y")

            ins_query = 'INSERT INTO dbo.BILLING_TABLE VALUES(?,?,?,?,?,?,?,?,?,?)'
            ins_query1 = "INSERT INTO dbo.BILLING_TABLE (BILL_NO,CUSTOMER_NAME,PHONE_NO,BILLING_DATE,DELIVERY_DATE,TOTAL_AMOUNT) VALUES(?,?,?,?,?,?)"
            data = (billno, customername, phoneno, orderdate, deliverydate,
                    totalamount, amountreceived, dueamount, None, bill_type)
            data1 = (billno, customername, phoneno, orderdate, deliverydate,
                     totalamount)

            cur.execute(ins_query, data)
            connect.commit()
            connect.close()

            # order details in order_table:

            max_order_id_query = " SELECT MAX(ORDER_ID) FROM DBO.ORDER_DETAILS"
            self.connectdb()
            cur.execute(max_order_id_query)
            result = cur.fetchall()
            order_value = result[0][0]

            if order_value != None:
                order_value = order_value + 1
                print("The order_id Value is ", order_value)
            else:
                order_value = 1
                print('The new Order Id value is ', order_value)
                print(type(order_value))

            category_list = [
                self.viewtable.cellWidget(row, 1).currentText()
                for row in range(self.viewtable.rowCount())
            ]
            frame_size_list = [
                self.viewtable.cellWidget(row, 2).currentText()
                for row in range(self.viewtable.rowCount())
            ]
            rate_list = [
                self.viewtable.item(row, 3).text()
                for row in range(self.viewtable.rowCount())
            ]
            qty_list = [
                self.viewtable.item(row, 4).text()
                for row in range(self.viewtable.rowCount())
            ]
            amount_list = [
                self.viewtable.item(row, 5).text()
                for row in range(self.viewtable.rowCount())
            ]

            print('the category values are', category_list)
            print('the frame values are', frame_size_list)
            print('the rate values are', rate_list)
            print('the qty values are', qty_list)
            print('the amount values are', amount_list)

            # finding Prd_id
            prd_id_list = []

            for category, frame in zip(category_list, frame_size_list):
                if category != 'FRAME':
                    prd_select_query = "SELECT PROD_ID FROM dbo.PROD_DETAILS WHERE PROD_TYPE ='DAILY' AND PROD_NAME =?"
                    cur.execute(prd_select_query, category)
                    result = cur.fetchall()
                    print('the result value is ', result[0][0])
                    prd_id_list.append(result[0][0])
                else:
                    prd_select_query = "SELECT PROD_ID FROM dbo.PROD_DETAILS WHERE PROD_TYPE ='DAILY' AND PROD_NAME ='FRAME' AND SIZE =?"
                    cur.execute(prd_select_query, frame)
                    result = cur.fetchall()
                    prd_id_list.append(result[0][0])

            print("The PRD_ID list values are ", prd_id_list)

            # insert data into ORDER_DETAILS table:

            for prd_id, category, size, rate, qty, amount in zip(
                    prd_id_list, category_list, frame_size_list, rate_list,
                    qty_list, amount_list):
                insert_qry_order_table = "INSERT INTO dbo.ORDER_DETAILS VALUES (?,?,?,?,?,?,?,?)"
                cur.execute(insert_qry_order_table,
                            (order_value, billno, prd_id, category, size, rate,
                             qty, amount))

            connect.commit()
            connect.close()

            self.billno = billno
            self.customer_name = customername
            self.phone_number = phoneno
            self.total_amount = totalamount
            self.amount_recieved = amountreceived
            self.due_amount = dueamount
            self.prod_details = category_list
            self.prod_size = frame_size_list
            self.qty_list = qty_list
            self.amount_list = amount_list

            QMessageBox.information(self, 'Message', 'Data saved successfully')
            self.save_btn.setEnabled(False)

    def clearbtn(self):
        columns_list = [self.customer_le, self.phone_le, self.delivery_date_le]

        for i in columns_list:
            i.clear()

        self.viewtable.setRowCount(0)

        self.total_le.setText(str(0))
        print("the clearbtn total amt value is ", self.total_le.text())
        self.recieved_le.setText(str(0))
        self.due_le.setText(str(0))

    def closebtn(self):

        self.close()

    def billcontent(self):
        folder_path = "D:\\Python\\Project\\bills\\"
        timenow = datetime.datetime.now()
        year = str(timenow.year)
        month = timenow.strftime("%B")
        print("the year is", year)
        print("the month is ", month)
        time = str(timenow.strftime("%H-%M"))
        footer_time = str(timenow.strftime("%I:%M %p"))
        print("the footer time is ", footer_time)
        today = datetime.date.today()

        bill_number = str(self.billno)
        cust_name = self.customer_name
        place = 'Mannargudi'
        lines = "\n===================================================================="
        today_date = today.strftime("%d/%m/%Y")

        product = self.prod_details
        size = self.prod_size
        qty = self.qty_list
        amount = self.amount_list
        total_amount = self.total_amount
        amount_paid = self.amount_recieved
        amount_due = self.due_amount

        print("the time is ", time, " and the format is ", type(time))

        folder = folder_path + year + "\\" + month + "\\" + str(today) + '\\'
        filename = str(folder) + "Daily_Bill_" + str(time) + ".rtf"

        print("the file name is ", filename)

        if not os.path.exists(folder):
            os.makedirs(folder)

        file = open(filename, 'w+')

        # file = open('D:/Python/bills/2019-12-30/Daily_Bill_16:49:50.docx','w+')

        # file =open('C:\\bill\\Daily_Bill.rtf','w')

        header = "\n\n\t\t\t\t VASA PHOTOGRAPHY"
        address1 = "\n\t\t\t   No.100, Balakrishna Nagar,"
        address2 = "\n\t\t\t\tKeerthi Clinic [opp],"
        address3 = "\n\t\t\t\t Mannargudi -614001"
        address4 = "\n\n Phone: 9944332270"
        address5 = "\t\t\t\tEmail: [email protected]"
        title = "\n\n\t\t\t\t\t\"CASH BILL\"\n===================================================================="
        bill_section = "\n\n Bill No\t: " + bill_number + "\t\t\t\tName  : " + cust_name
        bill_section2 = "\n Date\t\t: " + today_date + "\t\t\tAddr  : " + place + "\n\n===================================================================="
        table_header = "\n SL.No\tPRODUCT\t\t\tSIZE\t\tQTY\t\tAMOUNT\n===================================================================="

        final = header + address1 + address2 + address3 + address4 + address5 + title + bill_section + bill_section2 + table_header
        file.write(final)

        slno = 1
        table_data = ''

        for prd, size, qty, amt in zip(product, size, qty, amount):
            if len(prd) < 6 and prd != 'FRAME':
                table_value = "\n   " + str(
                    slno) + "\t\t" + prd + "\t\t\t\t" + size + "\t\t" + str(
                        qty) + "\t\t" + str(amt)
                file.write(table_value)
            elif len(prd) > 5 and prd != 'FRAME':
                table_value = "\n   " + str(
                    slno) + "\t\t" + prd + "\t\t\t" + size + "\t\t" + str(
                        qty) + "\t\t" + str(amt)
                file.write(table_value)
            elif prd == 'FRAME' and len(size) > 5:
                table_value = "\n   " + str(
                    slno) + "\t\t" + prd + "\t\t\t\t" + size + "\t" + str(
                        qty) + "\t\t" + str(amt)
                file.write(table_value)
            else:
                table_value = "\n   " + str(
                    slno) + "\t\t" + prd + "\t\t\t\t" + size + "\t\t" + str(
                        qty) + "\t\t" + str(amt)
                file.write(table_value)
            slno += 1
            table_data = table_data + table_value
        file.write(lines)

        footer1 = "\n\n  TIME  :" + footer_time + "\t\t\t\t\tSUB TOTAL\t:\t" + str(
            float(total_amount))
        footer2 = "\n\t\t\t\t\t\t\tAMT.PAID\t:\t" + str(float(amount_paid))
        footer3 = "\n  SIGN  :\t\t\t\t\t\tAMT.DUE\t:\t" + str(
            float(amount_due))

        footer_final = footer1 + footer2 + footer3

        file.write(footer_final)
        file.write(lines)

        message = "\n\t\t*** THANK YOU... PLEASE VISIT US AGAIN ***"
        file.write(message)

        self.file_name = filename

        file.close()

    def printbill(self):
        print("the save btn status is ", self.save_btn.isEnabled())
        if not self.save_btn.isEnabled():
            self.billcontent()
            os.startfile(self.file_name, 'print')
        else:
            QMessageBox.warning(
                self, 'Warning',
                'Please save the data first before printing the bill.')
Ejemplo n.º 20
0
class VistaNuovaPrenotazione(QWidget):

    def __init__(self, email_cliente, aggiorna_dati_prenotazioni, parent=None):
        super(VistaNuovaPrenotazione, self).__init__(parent)
        self.font = QFont("Arial", 16)
        self.email_cliente = email_cliente
        self.aggiorna_dati_prenotazioni = aggiorna_dati_prenotazioni

        self.layout = QGridLayout()

        # prenotazione data inizio vacanza
        self.label_inizio = QLabel("Seleziona la data di inizio della vacanza:")
        self.label_inizio.setStyleSheet("font: 200 14pt \"Papyrus\";\n""color: rgb(0, 0, 0);\n"
                                        "background-color: rgb(178, 225, 255);\n""selection-color: rgb(170, 255, 0);")
        self.layout.addWidget(self.label_inizio, 0, 0)

        self.calendario_inizio = QCalendarWidget()
        self.calendario_inizio.setGridVisible(True)
        self.calendario_inizio.setVerticalHeaderFormat(QCalendarWidget.NoVerticalHeader)
        if datetime.now() > datetime(2021, 6, 1):
            self.calendario_inizio.setMinimumDate(QDate(datetime.now().year, datetime.now().month, datetime.now().day))
        else:
            self.calendario_inizio.setMinimumDate(QDate(2021, 6, 1))
        self.calendario_inizio.setMaximumDate(QDate(2021, 9, 15))

        cell_inizio_start = QTextCharFormat()
        cell_inizio_start.setBackground(QColor("yellow"))
        cell_inizio_stop = QTextCharFormat()
        cell_inizio_stop.setBackground(QColor("red"))
        self.calendario_inizio.setDateTextFormat(self.calendario_inizio.selectedDate(), cell_inizio_start)
        self.calendario_inizio.setDateTextFormat(QDate(2021,9,14), cell_inizio_stop)

        self.layout.addWidget(self.calendario_inizio, 1, 0)

        # prenotazione data fine vacanza
        self.label_fine = QLabel("Seleziona la data di fine della vacanza:")
        self.label_fine.setStyleSheet("font: 200 14pt \"Papyrus\";\n"
                                                      "color: rgb(0, 0, 0);\n"
                                                      "background-color: rgb(178, 225, 255);\n"
                                                      "selection-color: rgb(170, 255, 0);")
        self.layout.addWidget(self.label_fine, 0, 1)

        self.calendario_fine = QCalendarWidget()
        self.calendario_fine.setGridVisible(True)
        self.calendario_fine.setVerticalHeaderFormat(QCalendarWidget.NoVerticalHeader)
        if datetime.now() > datetime(2021, 6, 1):
            self.calendario_fine.setMinimumDate(QDate(datetime.now().year, datetime.now().month, datetime.now().day))
        else:
            self.calendario_fine.setMinimumDate(QDate(2021, 6, 1))
        self.calendario_fine.setMaximumDate(QDate(2021, 9, 15))

        cell_fine_stop = QTextCharFormat()
        cell_fine_stop.setBackground(QColor("red"))
        self.calendario_fine.setDateTextFormat(QDate(2021, 9, 15), cell_fine_stop)

        self.layout.addWidget(self.calendario_fine, 1, 1)

        # selezione numero di persone
        self.label_numero_persone = QLabel("Seleziona il numero di persone:")
        self.label_numero_persone.setStyleSheet("font: 200 14pt \"Papyrus\";\n"
                                          "color: rgb(0, 0, 0);\n"
                                          "background-color: rgb(178, 225, 255);\n"
                                          "selection-color: rgb(170, 255, 0);")
        self.layout.addWidget(self.label_numero_persone, 3, 0)

        # selezione tipologia di alloggio
        self.label_alloggio = QLabel("Seleziona il tipo di alloggio:")
        self.label_alloggio.setStyleSheet("font: 200 14pt \"Papyrus\";\n"
                                                      "color: rgb(0, 0, 0);\n"
                                                      "background-color: rgb(178, 225, 255);\n"
                                                      "selection-color: rgb(170, 255, 0);")
        self.layout.addWidget(self.label_alloggio, 5, 0)

        # selezione tipologia di ristorazione
        self.label_ristorazione = QLabel("Seleziona il tipo di ristorazione:")
        self.label_ristorazione.setStyleSheet("font: 200 14pt \"Papyrus\";\n"
                                                      "color: rgb(0, 0, 0);\n"
                                                      "background-color: rgb(178, 225, 255);\n"
                                                      "selection-color: rgb(170, 255, 0);")
        self.layout.addWidget(self.label_ristorazione, 8, 0)

        # selezione servizi aggiuntivi
        self.label_servizi_aggiuntivi = QLabel("Seleziona i servizi aggiunitvi:")
        self.label_servizi_aggiuntivi.setStyleSheet("font: 200 14pt \"Papyrus\";\n"
                                                      "color: rgb(0, 0, 0);\n"
                                                      "background-color: rgb(178, 225, 255);\n"
                                                      "selection-color: rgb(170, 255, 0);")
        self.layout.addWidget(self.label_servizi_aggiuntivi, 3, 1)

        self.get_servizi()

        # bottone finale di conferma
        self.bottone_conferma = QPushButton("Conferma")
        self.bottone_conferma.setFont(QFont("Arial", 15, 15, True))
        self.bottone_conferma.setStyleSheet("background-color: rgb(0,255,0);")
        self.bottone_conferma.clicked.connect(self.aggiungi_prenotazione)
        self.shortcut_open = QShortcut(QKeySequence('Return'), self)
        self.shortcut_open.activated.connect(self.aggiungi_prenotazione)
        self.layout.addWidget(self.bottone_conferma, 9, 1)

        self.setLayout(self.layout)
        self.resize(1000, 600)
        self.setWindowTitle("Aggiungi Prenotazione")

    def get_servizi(self):
        self.liste_servizi = ListeServizi()

        self.font_combo_box = QFont("Arial", 12)

        # menu a tendina per stabilire il servizio di aloggio
        self.menu_alloggio = QComboBox()
        self.menu_alloggio.setFont(self.font_combo_box)
        self.model_menu_alloggio = QStandardItemModel(self.menu_alloggio)

        # menu a tendina per stabilire il numero di persone
        self.menu_numero_persone = QComboBox()
        self.menu_numero_persone.setFont(self.font_combo_box)
        self.model_menu_numero_persone = QStandardItemModel(self.menu_numero_persone)

        for servizio_alloggio in self.liste_servizi.get_servizi_alloggio():
            item = QStandardItem()
            item.setText(servizio_alloggio.nome + "(max " + str(servizio_alloggio.numero_persone_max) + " persone)")
            item.setEditable(False)
            self.model_menu_alloggio.appendRow(item)
        self.menu_alloggio.setModel(self.model_menu_alloggio)

        for numero in [1, 2, 3, 4, 5, 6, 7, 8]:
            item = QStandardItem()
            item.setText(str(numero))
            item.setEditable(False)
            self.model_menu_numero_persone.appendRow(item)
        self.menu_numero_persone.setModel(self.model_menu_numero_persone)

        self.layout.addWidget(self.menu_alloggio, 6, 0)
        self.layout.addWidget(self.menu_numero_persone, 4, 0)

        # menu a tendina per stabilire il servizio ristorazione
        self.menu_ristorazione = QComboBox()
        self.menu_ristorazione.setFont(self.font_combo_box)
        self.model_menu_ristorazione = QStandardItemModel(self.menu_ristorazione)

        for servizio_ristorazione in self.liste_servizi.get_servizi_ristorazione():
            item = QStandardItem()
            item.setText(servizio_ristorazione.nome)
            item.setEditable(False)
            self.model_menu_ristorazione.appendRow(item)
        self.menu_ristorazione.setModel(self.model_menu_ristorazione)
        self.layout.addWidget(self.menu_ristorazione, 9, 0)

        #Checkbox servizi agginitivi
        self.checkbox_noleggio = QCheckBox("Noleggio Mezzi Elettrici")
        self.checkbox_noleggio.setFont(self.font_combo_box)
        self.layout.addWidget(self.checkbox_noleggio, 4, 1)

        self.checkbox_spa = QCheckBox("Centro Benessere")
        self.checkbox_spa.setFont(self.font_combo_box)
        self.layout.addWidget(self.checkbox_spa, 5, 1)

        self.checkbox_escursione = QCheckBox("Escursione Turistica")
        self.checkbox_escursione.setFont(self.font_combo_box)
        self.layout.addWidget(self.checkbox_escursione, 6, 1)

    #Controlla i dati inseriti nella prenotazione e se sono corretti registra la prenotazione
    def aggiungi_prenotazione(self):
        #Trasforma le date prese dal calendario da QDate a datetime
        data_inizio_q = self.calendario_inizio.selectedDate()
        data_inizio = datetime(data_inizio_q.year(), data_inizio_q.month(), data_inizio_q.day())

        data_fine_q = self.calendario_fine.selectedDate()
        data_fine = datetime(data_fine_q.year(), data_fine_q.month(), data_fine_q.day())

        #Controlla che la data di fine non sai precedente a quella di inizio
        if data_fine <= data_inizio:
            QMessageBox.critical(self, "Errore", "La data di fine non può essere precedente la data di inizio della vacanza", QMessageBox.Ok, QMessageBox.Ok)
            return

        #Controlla che la data di inizio della prenotazione sia almeno domani
        if data_inizio == datetime(datetime.now().year, datetime.now().month, datetime.now().day):
            QMessageBox.critical(self, "Errore", "La prenotazione non può partire da oggi", QMessageBox.Ok, QMessageBox.Ok)
            return

        #COntrolla che la prenotazione duri almeno 3 giorni
        if data_fine-data_inizio < timedelta(days=3):
            QMessageBox.critical(self, "Errore", "La prenotazione deve essere di almeno 3 giorni", QMessageBox.Ok, QMessageBox.Ok)
            return

        #indici dei servizi selezionati
        servizio_alloggio = self.liste_servizi.get_servizi_alloggio()[self.menu_alloggio.currentIndex()]
        numero_persone = self.menu_numero_persone.currentIndex()+1
        servizio_ristorazione = self.liste_servizi.get_servizi_ristorazione()[self.menu_ristorazione.currentIndex()]
        servizi_aggiuntivi = []

        if self.checkbox_noleggio.isChecked():
            servizi_aggiuntivi.append(self.liste_servizi.get_servizi_aggiuntivi()[0])

        if self.checkbox_escursione.isChecked():
            servizi_aggiuntivi.append(self.liste_servizi.get_servizi_aggiuntivi()[1])

        if self.checkbox_spa.isChecked():
            servizi_aggiuntivi.append(self.liste_servizi.get_servizi_aggiuntivi()[2])

        #Controlla la disponibilità dell'alloggio per le date selezionate
        if not self.controlla_disponibilita(data_inizio, data_fine, servizio_alloggio):
            QMessageBox.critical(self, "Ci Dispiace", "Nelle date per le quali vuoi prenotare non sono disponibili posti per il tipo di alloggio scelto", QMessageBox.Ok, QMessageBox.Ok)
            return

        #In base al valore ritornato dalla funzione controlla_disponibilità, assegna un codice all'ombrellone del cliente
        if servizio_alloggio.nome == "Suite" or servizio_alloggio.nome == "Bungalow":
            codice_ombrellone = str(self.controlla_disponibilita(data_inizio, data_fine, servizio_alloggio)) + servizio_alloggio.nome[0]
        else:
            codice_ombrellone = str(self.controlla_disponibilita(data_inizio, data_fine, servizio_alloggio)) + servizio_alloggio.nome[0] + servizio_alloggio.nome[7]

        #Controlla che il numero di persone inserite sia inferiore al numero di persone massimo per il tipo di alloggio scelto
        if numero_persone > servizio_alloggio.numero_persone_max:
            QMessageBox.critical(self, "Errore", "Il numero di persone selezionato è troppo alto per il tipo di alloggio scelto", QMessageBox.Ok, QMessageBox.Ok)
            return

        prenotazione = Prenotazione(self.email_cliente, data_inizio, data_fine, numero_persone, servizio_ristorazione, servizio_alloggio, servizi_aggiuntivi, codice_ombrellone)

        #Chiede la conferma per la prenotazione
        risposta = QMessageBox.question(self, "Conferma", "Il costo della prenotazione è "
                                        + str(prenotazione.get_prezzo_totale()) + " € totali. \nDovrai versare una caparra di "
                                        + str(prenotazione.get_prezzo_totale()*20/100.0) + " €. \n\nConfermare?",
                                        QMessageBox.Yes, QMessageBox.No)
        if risposta == QMessageBox.No:
            return
        else:
            controllore_lista_prenotazioni = ControlloreListaPrenotazioni()
            controllore_lista_prenotazioni.aggiungi_prenotazione(prenotazione)
            QMessageBox.about(self, "Confermata", "La Prenotazione è stata Confermata")
            controllore_lista_prenotazioni.save_data()
            self.aggiorna_dati_prenotazioni()
            self.close()

    #Controlla la disponibilità dell'alloggio scelto nel periodo selezionato e in caso di disponibilità ritorna il numero
    #degli alloggi dello stesso tipo occupati nel primo giorno della prenotazione
    #Questo ritorno verrà utilizzato per assegnare il codice dell'ombrellone
    def controlla_disponibilita(self, data_inizio, data_fine, servizio_alloggio):
        controllore_lista_prenotazioni = ControlloreListaPrenotazioni()
        one_day = timedelta(days=1)
        data_controllo = data_inizio

        numero_ombrellone = 0

        disponibilita_giornaliera_alloggio = servizio_alloggio.disponibilita_giornaliera
        while data_controllo <= data_fine:
            disponibilita_giornaliera_rimanente = disponibilita_giornaliera_alloggio
            for prenotazione in controllore_lista_prenotazioni.get_lista_prenotazioni():
                if data_controllo >= prenotazione.data_inizio and data_controllo <= prenotazione.data_fine and prenotazione.servizio_alloggio == servizio_alloggio:
                    disponibilita_giornaliera_rimanente = disponibilita_giornaliera_rimanente-1
            if disponibilita_giornaliera_rimanente < 1:
                return False
            if data_controllo == data_inizio:
                numero_ombrellone = disponibilita_giornaliera_rimanente
            data_controllo = data_controllo + one_day
        return numero_ombrellone
Ejemplo n.º 21
0
    def ajoutRechercheBonDeTravail(self):
        # Recuperation des differents attributs
        self.bonDeTravailManager = BonTravailManager(pathBonTravailDatabase)
        try:
            fichierConf = open(pathFichierConf, 'r')  # try: ouvrir le fichier et le lire
            with fichierConf:
                self._conf = yaml.load(fichierConf)
        except IOError:  # attrape l'erreur IOError si elle se présente et renvoie
            print("Could not read file: ", pathFichierConf)  # définir ce qu'il faut faire pour corriger

        self.listeCategorieEquipement = list(self._conf['CategorieEquipement'])
        self.listeCategorieEquipement.sort()
        self.listeUnite = list(self._conf['Unite'])
        self.listeUnite.sort()
        self.listeEtatService = list(self._conf['EtatService'])
        self.listeEtatService.sort()

        #Mise a jour des differentes listes deroulantes
        self.comboBoxCategorieEquipement.clear()
        self.comboBoxCategorieEquipement.addItem("")
        self.comboBoxCategorieEquipement.addItems(self.listeCategorieEquipement)
        self.comboBoxEtat.clear()
        self.comboBoxEtat.addItem("")
        self.comboBoxEtat.addItems(self.listeEtatService)
        self.comboBoxUnite.clear()
        self.comboBoxUnite.addItem("")
        self.comboBoxUnite.addItems(self.listeUnite)

        fichierConf.close()

        self.signalRechercheBon = Communicate()
        self.signalRechercheBon.aucunResultat.connect(self.aucunResultat)
        self.signalRechercheBon.remplirTableau.connect(self.remplirTableau)
        self.signalRechercheBon.nouvelleRecherche.connect(self.nouvelleRecherche)

        #modification calendrier
        calendrierApres = QCalendarWidget()
        calendrierApres.setStyleSheet("background :#F5F5F5;\n color: black;")
        calendrierApres.setGridVisible(True)
        self.calendrierApres.setCalendarWidget(calendrierApres)
        calendrierApres.setVerticalHeaderFormat(QCalendarWidget.NoVerticalHeader)
        self.calendrierApres.setLocale(QLocale(QLocale.French, QLocale.France))
        calendrierAvant = QCalendarWidget()
        calendrierAvant.setStyleSheet("background :#F5F5F5;\n color: black;")
        calendrierAvant.setVerticalHeaderFormat(QCalendarWidget.NoVerticalHeader)
        calendrierAvant.setGridVisible(True)
        self.calendrierAvant.setCalendarWidget(calendrierAvant)
        self.calendrierAvant.setLocale(QLocale(QLocale.French, QLocale.France))

        self.calendrierAvant.setDate(QDate.currentDate())
        self.calendrierApres.setDate(QDate.currentDate())

        #Creation des differents colonnes pour le tableau de resultat
        self.listeCleDonnees = list(["IdEquipement", "NumeroBonTravail", "CategorieEquipement", "Modele", "Unite", "EtatBDT", "Date", "DescriptionSituation"])
        
        #liste contenant les bons résultant de la recherche
        self.listeResultat = list()
        #liste contenant les informations des bons a afficher
        self.listeDonnees = list()

        self.tableResultats.setColumnCount(len(self.listeCleDonnees))
        self.listeHeaders = ["Id de l'équipement", "Numero du bon de travail", "Catégorie d'équipement", "Modèle", "Unité", "État BDT", "Date", "Description de la situation"]
        self.tableResultats.setHorizontalHeaderLabels(self.listeHeaders)
        self.tableResultats.resizeColumnsToContents()
        self.tableResultats.setRowCount(0)
        self.dictionnaireRecherche = dict()

        #Connexion des differentes recherches pour la mise a jour automatique
        self.comboBoxCategorieEquipement.currentTextChanged.connect(self.rechercheCategorieEquipement)
        self.comboBoxEtat.currentTextChanged.connect(self.rechercheEtatDeService)
        self.comboBoxUnite.currentTextChanged.connect(self.rechercheUnite)
        self.calendrierAvant.dateChanged.connect(self.rechercheDateAvant)
        self.lineEditDescriptionSituation.returnPressed.connect(self.rechercheDescriptionSituation)
        self.calendrierApres.dateChanged.connect(self.rechercheDateApres)
        self.boutonNouvelleRecherche.clicked.connect(self.signalRechercheBon.nouvelleRecherche.emit)
        self.tableResultats.horizontalHeader().sectionClicked.connect(self.trier)
        self.boutonActualiser.clicked.connect(self.rechercherBonTravailThread)
        self.colonneClique = None
        self.nombreClique = 0
        # Empeche la modification de la table
        self.tableResultats.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers);
        self.tableResultats.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
        self.tableResultats.cellDoubleClicked.connect(self.choisirBonDeTravail)
        self.bonDeTravailSelectionne = None
Ejemplo n.º 22
0
class COMPONENTS(QWidget):
    def __init__(self):
        super().__init__()
        self.APP_URL = "http://127.0.0.1:8000"
        # self.APP_URL = "https://face-recog-server.herokuapp.com"
        self.msg = QMessageBox()

        self.grid = QGridLayout()
        self.group_box = QGroupBox()

        # PROFILE PICTURE
        self.profile_pic = QLabel()
        self.profile_pic.setAlignment(Qt.AlignCenter)
        self.profile_pic.setMaximumSize(130, 130)
        self.profile_pic.setScaledContents(True)

        # PROFILE PICTURE LAYOUT
        self.pro_pic_view = QVBoxLayout()
        self.change_pro = QPushButton()
        self.change_pro.setIcon(QIcon("./assets/icons/capture.png"))

        self.pro_pic_view.addWidget(self.profile_pic)
        self.pro_pic_view.addWidget(self.change_pro)

        self.cam_btn = QPushButton("Capture")

        # FIRST NAME
        self.f_name = QLabel("First Name")
        self.f_name.setObjectName("Label")
        self.f_name_input = QLineEdit()

        # MIDDLE NAME
        self.m_name = QLabel("Middle Name")
        self.m_name.setObjectName("Label")
        self.m_name_input = QLineEdit()

        # LAST NAME
        self.l_name = QLabel("Last Name")
        self.l_name.setObjectName("Label")
        self.l_name_input = QLineEdit()

        # DATE OF BIRTH
        self.dob_label = QLabel("Date of Birth")
        self.dob_label.setObjectName("Label")
        self.dob_date_label = QLabel("Choose Date..")
        self.dob_date_label.setStyleSheet("font-weight: normal;")
        self.dob_date_choose = QPushButton()
        self.dob_date_choose.setIcon(QIcon("./assets/icons/calendar.png"))
        self.dob_date_choose.setIconSize(QSize(25, 25))
        self.dob_layout = QHBoxLayout()
        self.dob_date_choose.clicked.connect(self.calender_show)
        self.dob_layout.addWidget(self.dob_date_label)
        self.dob_layout.addWidget(self.dob_date_choose)

        # AGE
        self.age = QLabel("Age")
        self.age.setObjectName("Label")
        self.age_input = QLineEdit()
        self.age_input.setValidator(QIntValidator())
        self.age_input.setMaxLength(3)

        # GENDER
        self.gender = QLabel("Gender")
        self.gender.setObjectName("Label")
        self.gender_1 = QRadioButton("MALE")
        self.gender_2 = QRadioButton("FEMALE")
        self.gender_1.setChecked(True)
        self.gender_layout = QHBoxLayout()
        self.gender_layout.addWidget(self.gender_1)
        self.gender_layout.addWidget(self.gender_2)

        # NATIONAILTY
        self.nationality = QLabel("Nationality")
        self.nationality.setObjectName("Label")
        self.nationality_input = QLineEdit()

        # STATE OF ORIGIN
        self.state_origin = QLabel("State of Origin")
        self.state_origin.setObjectName("Label")
        self.state_origin_input = QLineEdit()

        # LGA OF ORIGIN
        self.lga_origin = QLabel("LGA")
        self.lga_origin.setObjectName("Label")
        self.lga_origin_input = QLineEdit()

        # MARITAL STATUS
        self.marital = QLabel("Marital Status")
        self.marital.setObjectName("Label")
        self.marital_select = QComboBox()
        self.marital_select.addItems(
            ["SINGLE", "SEPERATED", "DIVORCED", "MARRIED", "WIDOWED"])

        self.profession = QLabel("Profession")
        self.profession.setObjectName("Label")
        self.profession_input = QLineEdit()

        # JAMB NUMBER
        self.j_num = QLabel("JAMB No.")
        self.j_num.setObjectName("Label")
        self.j_num_input = QLineEdit()
        self.j_num_input.setMaxLength(10)

        # COLLEGE
        self.college = QLabel("College")
        self.college.setObjectName("Label")
        self.college_select = QComboBox()
        self.college_select.addItems([
            "CAERSE",
            "CASAP",
            "CAFST",
            "CCSS",
            "COED",
            "CEET",
            "CGSC",
            "COLMAS",
            "CNREM",
            "COLNAS",
            "COLPAS",
            "CVM",
        ])

        # DEPARTMENT
        self.dept = QLabel("Department")
        self.dept.setObjectName("Label")
        self.dept_select = QComboBox()
        self.dept_select.addItems([
            "AGRIBUSINESS MANAGEMENT",
            "AGRICULTURAL ECONOMICS",
            "AGRICULTURAL EXTENSION AND RURAL SOCIOLOGY",
        ])

        # LEVEL
        self.level = QLabel("Level")
        self.level.setObjectName("Label")
        self.level_select = QComboBox()
        self.level_select.addItems(["100L", "200L", "300L", "400L"])

        # MATRIC NUMBER
        self.m_num = QLabel("Matriculation No.")
        self.m_num.setObjectName("Label")
        self.m_num_input = QLineEdit()

        # HOME ADDRESS
        self.address = QLabel("Home Address")
        self.address.setObjectName("Label")
        self.address_input = QLineEdit()

        # CELL PHONE
        self.phone = QLabel("Cell Phone")
        self.phone.setObjectName("Label")
        self.phone_input = QLineEdit()
        # self.phone_input.setValidator(QIntValidator
        self.phone_input.setMaxLength(11)

        # EMAIL
        self.email = QLabel("Email")
        self.email.setObjectName("Label")
        self.email.setObjectName("Label")
        self.email_input = QLineEdit()

        # PARENT NAME
        self.p_name = QLabel("Parent's/Sponsor's Name")
        self.p_name.setObjectName("Label")
        self.p_name_input = QLineEdit()

        # PARENT EMAIL
        self.p_email = QLabel("Parent's/Sponsor's Email")
        self.p_email.setObjectName("Label")
        self.p_email_input = QLineEdit()

        # PARENT PHONE
        self.p_phone = QLabel("Parent's/Sponsor's Phone")
        self.p_phone.setObjectName("Label")
        self.p_phone_input = QLineEdit()
        self.p_phone_input.setMaxLength(11)

        # DATE OF REGISTRATION
        self.dor = QLabel("Date of Registration")
        self.dor.setObjectName("Label")
        self.dor_text = QLineEdit()
        date = QDate.currentDate().toString(Qt.ISODate)
        self.dor_text.setText(date)

        # Next
        self._next = QPushButton("Next")

        # Prev
        self._prev = QPushButton("Previous")

    def calender_show(self):

        self.initial_layout = QVBoxLayout()

        self.calender_view = QWidget()
        self.calender_view.setWindowTitle("Choose Date")

        self.calender = QCalendarWidget()
        self.calender.setGridVisible(True)

        self.flags = Qt.WindowFlags(Qt.WindowStaysOnTopHint)
        self.calender_view.setWindowFlags(self.flags)

        self.initial_layout.addWidget(self.calender)
        self.calender_view.setLayout(self.initial_layout)

        self.calender_view.show()
        self.calender_view.resize(350, 250)

        self.calender.clicked[QDate].connect(self.select_date)

    def select_date(self):
        self.dob_date_label.setText(self.calender.selectedDate().toString(
            Qt.ISODate))
        self.calender_view.hide()

    def _start_video(self, super_layout):
        self.video_widget = QWidget()
        self.video_init_layout = QVBoxLayout()

        self.back_btn = QCommandLinkButton()
        self.back_btn.setIcon(QIcon("./assets/icons/back.png"))
        self.back_btn.setIconSize(QSize(30, 30))
        self.back_btn.setMaximumWidth(45)

        # Create Camera View
        self.cam_view = QLabel()

        self.video_init_layout.addWidget(self.back_btn)
        self.video_init_layout.addWidget(self.cam_view)
        self.video_init_layout.addWidget(self.cam_btn)

        self.video_widget.setLayout(self.video_init_layout)

        super_layout.addWidget(self.video_widget)
        super_layout.setCurrentWidget(self.video_widget)

        # create a timer
        self.timer = QTimer()

        # set timer timeout callback function
        self.timer.timeout.connect(self._video)

        if not self.timer.isActive():
            self.cam = cv2.VideoCapture(0)
            self.timer.start(1)

    def _video(self):
        face_cascade = cv2.CascadeClassifier(
            "./assets/classifier/haarcascade_frontalface_alt2.xml")

        ret, self.image = self.cam.read()

        image_copy = self.image.copy()

        # Capture Image-by-Image
        gray = cv2.cvtColor(image_copy, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(
            gray,
            scaleFactor=1.1,
            minNeighbors=5,
            minSize=(40, 40),
            flags=cv2.CASCADE_SCALE_IMAGE,
        )
        for (x, y, w, h) in faces:
            cv2.rectangle(image_copy, (x, y), (x + w, y + h), (255, 255, 255),
                          1)

        self.image_shown = cv2.cvtColor(image_copy, cv2.COLOR_BGR2RGB)

        # get image infos
        self.height, self.width, self.channel = self.image_shown.shape
        self.step = self.channel * self.width

        # create QImage from image
        self.qImg = QImage(
            self.image_shown.data,
            self.width,
            self.height,
            self.step,
            QImage.Format_RGB888,
        )

        # Set the data from qImg to cam_view
        self.cam_view.setPixmap(QPixmap.fromImage(self.qImg))

    def isConnected(self):
        try:
            r = requests.get(url=f"{self.APP_URL}")
            print(r.text)
            return True
        except requests.exceptions.ConnectionError as e:
            self.msg.setIconPixmap(QPixmap("./assets/icons/no_connection.png"))
            self.msg.setWindowTitle("Error!")
            self.msg.setWindowIcon(QIcon("./assets/icons/error.png"))
            self.msg.setText("Connect to the Internet to use app!")
            self.msg.show()
            self.msg.exec_()
            return False
        except requests.exceptions.Timeout as e:
            self.msg.setIconPixmap(
                QPixmap("./assets/icons/network_timeout.png"))
            self.msg.setWindowIcon(QIcon("./assets/icons/error.png"))
            self.msg.setWindowTitle("Information")
            self.msg.setWindowIcon(QIcon("./assets/icons/error.png"))
            self.msg.setText("Poor Network Connection!")
            self.msg.show()
            self.msg.exec_()
            return False
Ejemplo n.º 23
0
class Calendar(QWidget):
    # keep the current time as class variable for reference
    currentDay = datetime.now().day
    currentMonth = datetime.now().month
    currentYear = datetime.now().year

    def __init__(self):
        super().__init__()
        folder = path.dirname(__file__)
        self.icon_folder = path.join(folder, "icons")

        self.setWindowTitle("Planner")
        self.setWindowIcon(
            QtGui.QIcon(path.join(self.icon_folder, 'window.png')))

        self.setGeometry(300, 200, 600, 400)
        self.initUI()

    def initUI(self):
        self.calendar = QCalendarWidget()
        self.calendar.setGeometry(0, 0, 300, 300)
        self.calendar.setGridVisible(True)

        # don't allow going back to past months in calendar
        self.calendar.setMinimumDate(
            QDate(self.currentYear, self.currentMonth, 1))

        # format for dates in calendar that have events
        self.fmt = QTextCharFormat()
        self.fmt.setBackground(QColor(255, 165, 0, 100))

        # format for the current day
        cur_fmt = QTextCharFormat()
        cur_fmt.setBackground(QColor(0, 255, 90, 70))

        # format to change back to if all events are deleted
        self.delfmt = QTextCharFormat()
        self.delfmt.setBackground(Qt.transparent)

        # check if json file exists, if it does load the data from it
        file_exists = path.isfile(
            path.join(path.dirname(__file__), "data.json"))
        if file_exists:
            with open("data.json", "r") as json_file:
                self.data = json.load(json_file)
        else:
            self.data = {}

        # delete data from days prior to the current day
        cur = QDate.currentDate()
        for date in list(self.data.keys()):
            check_date = QDate.fromString(date, "dMyyyy")
            if cur.daysTo(check_date) <= 0 and cur != check_date:
                self.data.pop(date)
            else:
                self.calendar.setDateTextFormat(check_date, self.fmt)

        # mark current day in calendar
        current = str(self.currentDay) + str(self.currentMonth) + str(
            self.currentYear)
        self.calendar.setDateTextFormat(QDate.fromString(current, "dMyyyy"),
                                        cur_fmt)

        # organize buttons and layouts for display
        addButton = QPushButton("Add Event")
        addButton.clicked.connect(self.addNote)
        editButton = QPushButton("Edit")
        editButton.clicked.connect(self.editNote)
        delButton = QPushButton("Delete")
        delButton.clicked.connect(self.delNote)

        self.calendar.selectionChanged.connect(self.showDateInfo)
        self.calendar.selectionChanged.connect(self.labelDate)
        self.calendar.selectionChanged.connect(self.highlightFirstItem)

        self.note_group = QListWidget()
        self.note_group.setSortingEnabled(True)
        self.note_group.setStyleSheet("QListView::item {height: 40px;}")

        self.label = QLabel()
        label_font = QtGui.QFont("Gabriola", 18)
        self.label.setFont(label_font)
        self.labelDate()
        self.showDateInfo()

        labelp = QLabel()
        pixmap = QPixmap(path.join(self.icon_folder, 'calendar.png'))
        labelp.setPixmap(pixmap)

        # set up a timer that automatically updates every second
        self.lcd = QLCDNumber()
        self.lcd.setSegmentStyle(QLCDNumber.Filled)
        self.lcd.setMinimumWidth(80)
        timer = QTimer(self)
        timer.timeout.connect(self.showTime)
        timer.start(1000)
        self.showTime()

        hbox1 = QHBoxLayout()
        hbox1.addStretch(1)
        hbox1.addWidget(self.label)
        hbox1.addStretch(1)

        hbox2 = QHBoxLayout()
        hbox2.addWidget(addButton)
        hbox2.addWidget(editButton)
        hbox2.addWidget(delButton)

        hbox3 = QHBoxLayout()
        hbox3.addStretch(1)
        hbox3.addWidget(labelp)
        hbox3.addWidget(self.lcd)

        vbox = QVBoxLayout()
        vbox.addLayout(hbox1)
        vbox.addWidget(self.note_group)
        vbox.addLayout(hbox2)
        vbox.addLayout(hbox3)

        hbox = QHBoxLayout()
        hbox.addWidget(self.calendar)
        hbox.addLayout(vbox)

        self.setLayout(hbox)

    def showDateInfo(self):
        # add events to selected date
        date = self.getDate()
        self.note_group.clear()
        if date in self.data:
            self.note_group.addItems(self.data[date])

    def addNote(self):
        # adding notes for selected date
        # if a note starts with any number other than 0, 1, 2
        # add a 0 before it so that we can easily sort events
        # by start time
        date = self.getDate()
        row = self.note_group.currentRow()
        title = "Add {}".format("event")
        string, ok = QInputDialog.getText(self, title, title)

        if ok and string:
            if string[0].isdigit() and string[0] not in ["0", "1", "2"]:
                string = string.replace(string[0], "0" + string[0])
            self.note_group.insertItem(row, string)
            self.calendar.setDateTextFormat(QDate.fromString(date, "dMyyyy"),
                                            self.fmt)
            if date in self.data:
                self.data[date].append(string)
            else:
                self.data[date] = [string]

    def delNote(self):
        # delete the currently selected item
        date = self.getDate()
        row = self.note_group.currentRow()
        item = self.note_group.item(row)

        if not item:
            return
        reply = QMessageBox.question(self, "Remove", "Remove",
                                     QMessageBox.Yes | QMessageBox.No)

        if reply == QMessageBox.Yes:
            item = self.note_group.takeItem(row)
            self.data[date].remove(item.text())
            if not self.data[date]:
                del (self.data[date])
                self.calendar.setDateTextFormat(
                    QDate.fromString(date, "dMyyyy"), self.delfmt)
            del (item)

    def editNote(self):
        # edit the currently selected item
        date = self.getDate()
        row = self.note_group.currentRow()
        item = self.note_group.item(row)

        if item:
            copy = item.text()
            title = "Edit event"
            string, ok = QInputDialog.getText(self, title, title,
                                              QLineEdit.Normal, item.text())

            if ok and string:
                self.data[date].remove(copy)
                self.data[date].append(string)
                if string[0].isdigit() and string[0] not in ["0", "1", "2"]:
                    string = string.replace(string[0], "0" + string[0])
                item.setText(string)

    def getDate(self):
        # parse the selected date into usable string form
        select = self.calendar.selectedDate()
        date = str(select.day()) + str(select.month()) + str(select.year())
        return date

    def labelDate(self):
        # label to show the long name form of the selected date
        # format US style like "Thursday, February 20, 2020"
        select = self.calendar.selectedDate()
        weekday, month = select.dayOfWeek(), select.month()
        day, year = str(select.day()), str(select.year())
        week_day, word_month = QDate.longDayName(weekday), QDate.longMonthName(
            month)
        self.label.setText(week_day + ", " + word_month + " " + day + ", " +
                           year)

    def highlightFirstItem(self):
        # highlight the first item immediately after switching selection
        if self.note_group.count() > 0:
            self.note_group.setCurrentRow(0)

    def showTime(self):
        # keep the current time updated
        time = QTime.currentTime()
        text = time.toString("hh:mm")
        if time.second() % 2 == 0:
            text.replace(text[2], '')
        self.lcd.display(text)

    def closeEvent(self, e):
        # save all data into json file when user closes app
        with open("data.json", "w") as json_file:
            json.dump(self.data, json_file)
        e.accept()
Ejemplo n.º 24
0
    def initUI(self):
        # checkbox
        cb = QCheckBox('Show title', self)
        cb.move(20, 160)
        cb.toggle()
        cb.stateChanged.connect(self.changeTitle)

        # toggle button
        self.col = QColor(0, 0, 0)
        redb = QPushButton('Red', self)
        redb.setCheckable(True)
        redb.move(10, 10)
        redb.clicked[bool].connect(self.setColor)
        redb = QPushButton('Green', self)
        redb.setCheckable(True)
        redb.move(10, 60)
        redb.clicked[bool].connect(self.setColor)
        blueb = QPushButton('Blue', self)
        blueb.setCheckable(True)
        blueb.move(10, 110)
        blueb.clicked[bool].connect(self.setColor)
        self.square = QFrame(self)
        self.square.setGeometry(150, 20, 100, 100)
        self.square.setStyleSheet("QWidget { background-color: %s }" %
                                  self.col.name())

        # slider
        sld = QSlider(Qt.Horizontal, self)
        sld.setFocusPolicy(Qt.NoFocus)
        sld.setGeometry(30, 210, 100, 30)
        sld.valueChanged[int].connect(self.changeValue)

        # pixmap
        self.label = QLabel(self)
        self.label.setPixmap(QPixmap('web.png'))
        self.label.setGeometry(160, 210, 80, 30)

        # process bar
        self.pbar = QProgressBar(self)
        self.pbar.setGeometry(30, 260, 200, 25)
        self.btn = QPushButton('Start', self)
        self.btn.move(40, 310)
        self.btn.clicked.connect(self.doAction)
        self.timer = QBasicTimer()
        self.step = 0

        # calendar
        cal = QCalendarWidget(self)
        cal.setGridVisible(True)
        cal.move(300, 10)
        cal.clicked[QDate].connect(self.showDate)
        self.lbl = QLabel(self)
        date = cal.selectedDate()
        self.lbl.setText(date.toString())
        self.lbl.move(300, 260)

        # line edit
        self.lbl2 = QLabel(self)
        qle = QLineEdit(self)
        qle.move(300, 310)
        self.lbl2.move(480, 310)
        qle.textChanged[str].connect(self.onChanged)

        self.setGeometry(300, 300, 640, 480)
        self.setWindowTitle('QCheckBox')
        self.show()
Ejemplo n.º 25
0
class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()

        self.createPreviewGroupBox()
        self.createGeneralOptionsGroupBox()
        self.createDatesGroupBox()
        self.createTextFormatsGroupBox()

        layout = QGridLayout()
        layout.addWidget(self.previewGroupBox, 0, 0)
        layout.addWidget(self.generalOptionsGroupBox, 0, 1)
        layout.addWidget(self.datesGroupBox, 1, 0)
        layout.addWidget(self.textFormatsGroupBox, 1, 1)
        layout.setSizeConstraint(QLayout.SetFixedSize)
        self.setLayout(layout)

        self.previewLayout.setRowMinimumHeight(
            0,
            self.calendar.sizeHint().height())
        self.previewLayout.setColumnMinimumWidth(
            0,
            self.calendar.sizeHint().width())

        self.setWindowTitle("Calendar Widget")

    def localeChanged(self, index):
        self.calendar.setLocale(self.localeCombo.itemData(index))

    def firstDayChanged(self, index):
        self.calendar.setFirstDayOfWeek(
            Qt.DayOfWeek(self.firstDayCombo.itemData(index)))

    def selectionModeChanged(self, index):
        self.calendar.setSelectionMode(
            QCalendarWidget.SelectionMode(
                self.selectionModeCombo.itemData(index)))

    def horizontalHeaderChanged(self, index):
        self.calendar.setHorizontalHeaderFormat(
            QCalendarWidget.HorizontalHeaderFormat(
                self.horizontalHeaderCombo.itemData(index)))

    def verticalHeaderChanged(self, index):
        self.calendar.setVerticalHeaderFormat(
            QCalendarWidget.VerticalHeaderFormat(
                self.verticalHeaderCombo.itemData(index)))

    def selectedDateChanged(self):
        self.currentDateEdit.setDate(self.calendar.selectedDate())

    def minimumDateChanged(self, date):
        self.calendar.setMinimumDate(date)
        self.maximumDateEdit.setDate(self.calendar.maximumDate())

    def maximumDateChanged(self, date):
        self.calendar.setMaximumDate(date)
        self.minimumDateEdit.setDate(self.calendar.minimumDate())

    def weekdayFormatChanged(self):
        format = QTextCharFormat()
        format.setForeground(
            Qt.GlobalColor(
                self.weekdayColorCombo.itemData(
                    self.weekdayColorCombo.currentIndex())))

        self.calendar.setWeekdayTextFormat(Qt.Monday, format)
        self.calendar.setWeekdayTextFormat(Qt.Tuesday, format)
        self.calendar.setWeekdayTextFormat(Qt.Wednesday, format)
        self.calendar.setWeekdayTextFormat(Qt.Thursday, format)
        self.calendar.setWeekdayTextFormat(Qt.Friday, format)

    def weekendFormatChanged(self):
        format = QTextCharFormat()
        format.setForeground(
            Qt.GlobalColor(
                self.weekendColorCombo.itemData(
                    self.weekendColorCombo.currentIndex())))

        self.calendar.setWeekdayTextFormat(Qt.Saturday, format)
        self.calendar.setWeekdayTextFormat(Qt.Sunday, format)

    def reformatHeaders(self):
        text = self.headerTextFormatCombo.currentText()
        format = QTextCharFormat()

        if text == "Bold":
            format.setFontWeight(QFont.Bold)
        elif text == "Italic":
            format.setFontItalic(True)
        elif text == "Green":
            format.setForeground(Qt.green)

        self.calendar.setHeaderTextFormat(format)

    def reformatCalendarPage(self):
        if self.firstFridayCheckBox.isChecked():
            firstFriday = QDate(self.calendar.yearShown(),
                                self.calendar.monthShown(), 1)

            while firstFriday.dayOfWeek() != Qt.Friday:
                firstFriday = firstFriday.addDays(1)

            firstFridayFormat = QTextCharFormat()
            firstFridayFormat.setForeground(Qt.blue)

            self.calendar.setDateTextFormat(firstFriday, firstFridayFormat)

        # May 1st in Red takes precedence.
        if self.mayFirstCheckBox.isChecked():
            mayFirst = QDate(self.calendar.yearShown(), 5, 1)

            mayFirstFormat = QTextCharFormat()
            mayFirstFormat.setForeground(Qt.red)

            self.calendar.setDateTextFormat(mayFirst, mayFirstFormat)

    def createPreviewGroupBox(self):
        self.previewGroupBox = QGroupBox("Preview")

        self.calendar = QCalendarWidget()
        self.calendar.setMinimumDate(QDate(1900, 1, 1))
        self.calendar.setMaximumDate(QDate(3000, 1, 1))
        self.calendar.setGridVisible(True)
        self.calendar.currentPageChanged.connect(self.reformatCalendarPage)

        self.previewLayout = QGridLayout()
        self.previewLayout.addWidget(self.calendar, 0, 0, Qt.AlignCenter)
        self.previewGroupBox.setLayout(self.previewLayout)

    def createGeneralOptionsGroupBox(self):
        self.generalOptionsGroupBox = QGroupBox("General Options")

        self.localeCombo = QComboBox()

        curLocaleIndex = -1
        index = 0

        this_language = self.locale().nativeLanguageName()
        this_country = self.locale().nativeCountryName()

        for locale in QLocale.matchingLocales(QLocale.AnyLanguage,
                                              QLocale.AnyScript,
                                              QLocale.AnyCountry):
            language = locale.nativeLanguageName()
            country = locale.nativeCountryName()

            if language == this_language and country == this_country:
                curLocaleIndex = index

            self.localeCombo.addItem('%s/%s' % (language, country), locale)
            index += 1

        if curLocaleIndex != -1:
            self.localeCombo.setCurrentIndex(curLocaleIndex)

        self.localeLabel = QLabel("&Locale")
        self.localeLabel.setBuddy(self.localeCombo)

        self.firstDayCombo = QComboBox()
        self.firstDayCombo.addItem("Sunday", Qt.Sunday)
        self.firstDayCombo.addItem("Monday", Qt.Monday)
        self.firstDayCombo.addItem("Tuesday", Qt.Tuesday)
        self.firstDayCombo.addItem("Wednesday", Qt.Wednesday)
        self.firstDayCombo.addItem("Thursday", Qt.Thursday)
        self.firstDayCombo.addItem("Friday", Qt.Friday)
        self.firstDayCombo.addItem("Saturday", Qt.Saturday)

        self.firstDayLabel = QLabel("Wee&k starts on:")
        self.firstDayLabel.setBuddy(self.firstDayCombo)

        self.selectionModeCombo = QComboBox()
        self.selectionModeCombo.addItem("Single selection",
                                        QCalendarWidget.SingleSelection)
        self.selectionModeCombo.addItem("None", QCalendarWidget.NoSelection)
        self.selectionModeLabel = QLabel("&Selection mode:")
        self.selectionModeLabel.setBuddy(self.selectionModeCombo)

        self.gridCheckBox = QCheckBox("&Grid")
        self.gridCheckBox.setChecked(self.calendar.isGridVisible())

        self.navigationCheckBox = QCheckBox("&Navigation bar")
        self.navigationCheckBox.setChecked(True)

        self.horizontalHeaderCombo = QComboBox()
        self.horizontalHeaderCombo.addItem(
            "Single letter day names", QCalendarWidget.SingleLetterDayNames)
        self.horizontalHeaderCombo.addItem("Short day names",
                                           QCalendarWidget.ShortDayNames)
        self.horizontalHeaderCombo.addItem("Long day names",
                                           QCalendarWidget.LongDayNames)
        self.horizontalHeaderCombo.addItem("None",
                                           QCalendarWidget.NoHorizontalHeader)
        self.horizontalHeaderCombo.setCurrentIndex(1)

        self.horizontalHeaderLabel = QLabel("&Horizontal header:")
        self.horizontalHeaderLabel.setBuddy(self.horizontalHeaderCombo)

        self.verticalHeaderCombo = QComboBox()
        self.verticalHeaderCombo.addItem("ISO week numbers",
                                         QCalendarWidget.ISOWeekNumbers)
        self.verticalHeaderCombo.addItem("None",
                                         QCalendarWidget.NoVerticalHeader)

        self.verticalHeaderLabel = QLabel("&Vertical header:")
        self.verticalHeaderLabel.setBuddy(self.verticalHeaderCombo)

        self.localeCombo.currentIndexChanged.connect(self.localeChanged)
        self.firstDayCombo.currentIndexChanged.connect(self.firstDayChanged)
        self.selectionModeCombo.currentIndexChanged.connect(
            self.selectionModeChanged)
        self.gridCheckBox.toggled.connect(self.calendar.setGridVisible)
        self.navigationCheckBox.toggled.connect(
            self.calendar.setNavigationBarVisible)
        self.horizontalHeaderCombo.currentIndexChanged.connect(
            self.horizontalHeaderChanged)
        self.verticalHeaderCombo.currentIndexChanged.connect(
            self.verticalHeaderChanged)

        checkBoxLayout = QHBoxLayout()
        checkBoxLayout.addWidget(self.gridCheckBox)
        checkBoxLayout.addStretch()
        checkBoxLayout.addWidget(self.navigationCheckBox)

        outerLayout = QGridLayout()
        outerLayout.addWidget(self.localeLabel, 0, 0)
        outerLayout.addWidget(self.localeCombo, 0, 1)
        outerLayout.addWidget(self.firstDayLabel, 1, 0)
        outerLayout.addWidget(self.firstDayCombo, 1, 1)
        outerLayout.addWidget(self.selectionModeLabel, 2, 0)
        outerLayout.addWidget(self.selectionModeCombo, 2, 1)
        outerLayout.addLayout(checkBoxLayout, 3, 0, 1, 2)
        outerLayout.addWidget(self.horizontalHeaderLabel, 4, 0)
        outerLayout.addWidget(self.horizontalHeaderCombo, 4, 1)
        outerLayout.addWidget(self.verticalHeaderLabel, 5, 0)
        outerLayout.addWidget(self.verticalHeaderCombo, 5, 1)
        self.generalOptionsGroupBox.setLayout(outerLayout)

        self.firstDayChanged(self.firstDayCombo.currentIndex())
        self.selectionModeChanged(self.selectionModeCombo.currentIndex())
        self.horizontalHeaderChanged(self.horizontalHeaderCombo.currentIndex())
        self.verticalHeaderChanged(self.verticalHeaderCombo.currentIndex())

    def createDatesGroupBox(self):
        self.datesGroupBox = QGroupBox(self.tr("Dates"))

        self.minimumDateEdit = QDateEdit()
        self.minimumDateEdit.setDisplayFormat('MMM d yyyy')
        self.minimumDateEdit.setDateRange(self.calendar.minimumDate(),
                                          self.calendar.maximumDate())
        self.minimumDateEdit.setDate(self.calendar.minimumDate())

        self.minimumDateLabel = QLabel("&Minimum Date:")
        self.minimumDateLabel.setBuddy(self.minimumDateEdit)

        self.currentDateEdit = QDateEdit()
        self.currentDateEdit.setDisplayFormat('MMM d yyyy')
        self.currentDateEdit.setDate(self.calendar.selectedDate())
        self.currentDateEdit.setDateRange(self.calendar.minimumDate(),
                                          self.calendar.maximumDate())

        self.currentDateLabel = QLabel("&Current Date:")
        self.currentDateLabel.setBuddy(self.currentDateEdit)

        self.maximumDateEdit = QDateEdit()
        self.maximumDateEdit.setDisplayFormat('MMM d yyyy')
        self.maximumDateEdit.setDateRange(self.calendar.minimumDate(),
                                          self.calendar.maximumDate())
        self.maximumDateEdit.setDate(self.calendar.maximumDate())

        self.maximumDateLabel = QLabel("Ma&ximum Date:")
        self.maximumDateLabel.setBuddy(self.maximumDateEdit)

        self.currentDateEdit.dateChanged.connect(self.calendar.setSelectedDate)
        self.calendar.selectionChanged.connect(self.selectedDateChanged)
        self.minimumDateEdit.dateChanged.connect(self.minimumDateChanged)
        self.maximumDateEdit.dateChanged.connect(self.maximumDateChanged)

        dateBoxLayout = QGridLayout()
        dateBoxLayout.addWidget(self.currentDateLabel, 1, 0)
        dateBoxLayout.addWidget(self.currentDateEdit, 1, 1)
        dateBoxLayout.addWidget(self.minimumDateLabel, 0, 0)
        dateBoxLayout.addWidget(self.minimumDateEdit, 0, 1)
        dateBoxLayout.addWidget(self.maximumDateLabel, 2, 0)
        dateBoxLayout.addWidget(self.maximumDateEdit, 2, 1)
        dateBoxLayout.setRowStretch(3, 1)

        self.datesGroupBox.setLayout(dateBoxLayout)

    def createTextFormatsGroupBox(self):
        self.textFormatsGroupBox = QGroupBox("Text Formats")

        self.weekdayColorCombo = self.createColorComboBox()
        self.weekdayColorCombo.setCurrentIndex(
            self.weekdayColorCombo.findText("Black"))

        self.weekdayColorLabel = QLabel("&Weekday color:")
        self.weekdayColorLabel.setBuddy(self.weekdayColorCombo)

        self.weekendColorCombo = self.createColorComboBox()
        self.weekendColorCombo.setCurrentIndex(
            self.weekendColorCombo.findText("Red"))

        self.weekendColorLabel = QLabel("Week&end color:")
        self.weekendColorLabel.setBuddy(self.weekendColorCombo)

        self.headerTextFormatCombo = QComboBox()
        self.headerTextFormatCombo.addItem("Bold")
        self.headerTextFormatCombo.addItem("Italic")
        self.headerTextFormatCombo.addItem("Plain")

        self.headerTextFormatLabel = QLabel("&Header text:")
        self.headerTextFormatLabel.setBuddy(self.headerTextFormatCombo)

        self.firstFridayCheckBox = QCheckBox("&First Friday in blue")

        self.mayFirstCheckBox = QCheckBox("May &1 in red")

        self.weekdayColorCombo.currentIndexChanged.connect(
            self.weekdayFormatChanged)
        self.weekendColorCombo.currentIndexChanged.connect(
            self.weekendFormatChanged)
        self.headerTextFormatCombo.currentIndexChanged.connect(
            self.reformatHeaders)
        self.firstFridayCheckBox.toggled.connect(self.reformatCalendarPage)
        self.mayFirstCheckBox.toggled.connect(self.reformatCalendarPage)

        checkBoxLayout = QHBoxLayout()
        checkBoxLayout.addWidget(self.firstFridayCheckBox)
        checkBoxLayout.addStretch()
        checkBoxLayout.addWidget(self.mayFirstCheckBox)

        outerLayout = QGridLayout()
        outerLayout.addWidget(self.weekdayColorLabel, 0, 0)
        outerLayout.addWidget(self.weekdayColorCombo, 0, 1)
        outerLayout.addWidget(self.weekendColorLabel, 1, 0)
        outerLayout.addWidget(self.weekendColorCombo, 1, 1)
        outerLayout.addWidget(self.headerTextFormatLabel, 2, 0)
        outerLayout.addWidget(self.headerTextFormatCombo, 2, 1)
        outerLayout.addLayout(checkBoxLayout, 3, 0, 1, 2)
        self.textFormatsGroupBox.setLayout(outerLayout)

        self.weekdayFormatChanged()
        self.weekendFormatChanged()

        self.reformatHeaders()
        self.reformatCalendarPage()

    def createColorComboBox(self):
        comboBox = QComboBox()
        comboBox.addItem("Red", Qt.red)
        comboBox.addItem("Blue", Qt.blue)
        comboBox.addItem("Black", Qt.black)
        comboBox.addItem("Magenta", Qt.magenta)

        return comboBox
class Calendar(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self)
        self.parent = parent
        self.initUI()
        self.defaultDate()

    def initUI(self):

        self.layout = QHBoxLayout()

        self.groupboxCal = QGroupBox("Calendar")
        self.groupboxDataset = QGroupBox("Dataset")
        self.groupboxCal.setStyleSheet("QGroupBox { padding-top: 20 px;border: 1px solid gray; border-radius: 3px}")
        self.groupboxDataset.setStyleSheet("QGroupBox { padding-top: 20 px;border: 1px solid gray; border-radius: 3px}")
        self.layoutCal = QVBoxLayout()
        self.layoutDataset = QGridLayout()
        self.groupboxCal.setLayout(self.layoutCal)
        self.groupboxDataset.setLayout(self.layoutDataset)

        self.layout_but = QHBoxLayout()
        self.cal = QCalendarWidget(self)
        self.cal.setGridVisible(True)
        self.cal.clicked[QDate].connect(self.showDate)
        self.lbl = QLabel(self)
        date = self.cal.selectedDate()

        self.lbl.setText(date.toString())
        self.buttonSave = QPushButton("Save")
        self.buttonSave.clicked.connect(self.closeEvent)

        self.checkboxRealTime = QCheckBox("Real Time Data Monitoring")
        self.checkboxPastRuns = QCheckBox("Visualize Past Runs")
        self.spinboxDays = QSpinBox()
        self.spinboxDays.setRange(1, 100)
        self.spinboxDays.setValue(1)
        self.checkboxRealTime.stateChanged.connect(self.realTimeMode)
        self.checkboxPastRuns.stateChanged.connect(self.oldData)

        self.checkboxRealTime.setCheckState(2)

        self.layoutDataset.addWidget(self.checkboxRealTime, 0, 0, 2, 1)

        self.layoutDataset.addWidget(QLabel("Duration (Days)"), 2, 1, 1, 1)
        self.layoutDataset.addWidget(self.checkboxPastRuns, 3, 0, 1, 1)
        self.layoutDataset.addWidget(self.spinboxDays, 3, 1, 1, 1)

        self.layoutCal.addWidget(self.cal)
        self.layout_but.addWidget(self.lbl)
        self.layout_but.addWidget(self.buttonSave)
        self.layoutCal.addLayout(self.layout_but)

        self.layout.addWidget(self.groupboxCal)
        self.layout.addWidget(self.groupboxDataset)
        self.setLayout(self.layout)
        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle('Calendar')
        self.setWindowModality(Qt.WindowModal)
        self.show()

    def defaultDate(self):
        mydate = datetime.datetime(datetime.datetime.today().year, datetime.datetime.today().month,
                                   datetime.datetime.today().day)
        self.mydatetime = mydate
        self.mydate_num = self.parent.db.convertTimetoAstro(mydate.strftime("%d/%m/%Y %H:%M:%S"))

    def getChosenDate(self):
        mydate = datetime.datetime.combine(self.cal.selectedDate().toPyDate(), datetime.datetime.min.time())
        self.mydatetime = mydate
        self.mydate_num = self.parent.db.convertTimetoAstro(mydate.strftime("%d/%m/%Y %H:%M:%S"))

    def showDate(self, date):

        self.lbl.setText(date.toString())

    def realTimeMode(self):

        if self.checkboxRealTime.isChecked():
            self.parent.dataset = "real_time"
            self.checkboxPastRuns.setCheckState(0)
        else:
            self.checkboxPastRuns.setCheckState(2)

    def oldData(self):
        if self.checkboxPastRuns.isChecked():
            self.parent.dataset = "past_run"
            self.checkboxRealTime.setCheckState(0)
        else:
            self.checkboxRealTime.setCheckState(2)

    def closeEvent(self, event):
        self.hide()
        self.getChosenDate()
        try:
            event.accept()
        except AttributeError:
            pass
Ejemplo n.º 27
0
class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()

        self.createPreviewGroupBox()
        self.createGeneralOptionsGroupBox()
        self.createDatesGroupBox()
        self.createTextFormatsGroupBox()

        layout = QGridLayout()
        layout.addWidget(self.previewGroupBox, 0, 0)
        layout.addWidget(self.generalOptionsGroupBox, 0, 1)
        layout.addWidget(self.datesGroupBox, 1, 0)
        layout.addWidget(self.textFormatsGroupBox, 1, 1)
        layout.setSizeConstraint(QLayout.SetFixedSize)
        self.setLayout(layout)

        self.previewLayout.setRowMinimumHeight(0,
                self.calendar.sizeHint().height())
        self.previewLayout.setColumnMinimumWidth(0,
                self.calendar.sizeHint().width())

        self.setWindowTitle("Calendar Widget")

    def localeChanged(self, index):
        self.calendar.setLocale(self.localeCombo.itemData(index))

    def firstDayChanged(self, index):
        self.calendar.setFirstDayOfWeek(
                Qt.DayOfWeek(self.firstDayCombo.itemData(index)))

    def selectionModeChanged(self, index):
        self.calendar.setSelectionMode(
                QCalendarWidget.SelectionMode(
                        self.selectionModeCombo.itemData(index)))

    def horizontalHeaderChanged(self, index):
        self.calendar.setHorizontalHeaderFormat(
                QCalendarWidget.HorizontalHeaderFormat(
                        self.horizontalHeaderCombo.itemData(index)))

    def verticalHeaderChanged(self, index):
        self.calendar.setVerticalHeaderFormat(
                QCalendarWidget.VerticalHeaderFormat(
                        self.verticalHeaderCombo.itemData(index)))

    def selectedDateChanged(self):
        self.currentDateEdit.setDate(self.calendar.selectedDate())

    def minimumDateChanged(self, date):
        self.calendar.setMinimumDate(date)
        self.maximumDateEdit.setDate(self.calendar.maximumDate())

    def maximumDateChanged(self, date):
        self.calendar.setMaximumDate(date)
        self.minimumDateEdit.setDate(self.calendar.minimumDate())

    def weekdayFormatChanged(self):
        format = QTextCharFormat()
        format.setForeground(
                Qt.GlobalColor(
                        self.weekdayColorCombo.itemData(
                                self.weekdayColorCombo.currentIndex())))

        self.calendar.setWeekdayTextFormat(Qt.Monday, format)
        self.calendar.setWeekdayTextFormat(Qt.Tuesday, format)
        self.calendar.setWeekdayTextFormat(Qt.Wednesday, format)
        self.calendar.setWeekdayTextFormat(Qt.Thursday, format)
        self.calendar.setWeekdayTextFormat(Qt.Friday, format)

    def weekendFormatChanged(self):
        format = QTextCharFormat()
        format.setForeground(
                Qt.GlobalColor(
                        self.weekendColorCombo.itemData(
                                self.weekendColorCombo.currentIndex())))

        self.calendar.setWeekdayTextFormat(Qt.Saturday, format)
        self.calendar.setWeekdayTextFormat(Qt.Sunday, format)

    def reformatHeaders(self):
        text = self.headerTextFormatCombo.currentText()
        format = QTextCharFormat()

        if text == "Bold":
            format.setFontWeight(QFont.Bold)
        elif text == "Italic":
            format.setFontItalic(True)
        elif text == "Green":
            format.setForeground(Qt.green)

        self.calendar.setHeaderTextFormat(format)

    def reformatCalendarPage(self):
        if self.firstFridayCheckBox.isChecked():
            firstFriday = QDate(self.calendar.yearShown(),
                    self.calendar.monthShown(), 1)

            while firstFriday.dayOfWeek() != Qt.Friday:
                firstFriday = firstFriday.addDays(1)

            firstFridayFormat = QTextCharFormat()
            firstFridayFormat.setForeground(Qt.blue)

            self.calendar.setDateTextFormat(firstFriday, firstFridayFormat)

        # May 1st in Red takes precedence.
        if self.mayFirstCheckBox.isChecked():
            mayFirst = QDate(self.calendar.yearShown(), 5, 1)

            mayFirstFormat = QTextCharFormat()
            mayFirstFormat.setForeground(Qt.red)

            self.calendar.setDateTextFormat(mayFirst, mayFirstFormat)

    def createPreviewGroupBox(self):
        self.previewGroupBox = QGroupBox("Preview")

        self.calendar = QCalendarWidget()
        self.calendar.setMinimumDate(QDate(1900, 1, 1))
        self.calendar.setMaximumDate(QDate(3000, 1, 1))
        self.calendar.setGridVisible(True)
        self.calendar.currentPageChanged.connect(self.reformatCalendarPage)

        self.previewLayout = QGridLayout()
        self.previewLayout.addWidget(self.calendar, 0, 0, Qt.AlignCenter)
        self.previewGroupBox.setLayout(self.previewLayout)
 
    def createGeneralOptionsGroupBox(self):
        self.generalOptionsGroupBox = QGroupBox("General Options")

        self.localeCombo = QComboBox()

        curLocaleIndex = -1
        index = 0

        this_language = self.locale().nativeLanguageName()
        this_country = self.locale().nativeCountryName()

        for locale in QLocale.matchingLocales(QLocale.AnyLanguage, QLocale.AnyScript, QLocale.AnyCountry):
            language = locale.nativeLanguageName()
            country = locale.nativeCountryName()

            if language == this_language and country == this_country:
                curLocaleIndex = index

            self.localeCombo.addItem('%s/%s' % (language, country), locale)
            index += 1

        if curLocaleIndex != -1:
            self.localeCombo.setCurrentIndex(curLocaleIndex)

        self.localeLabel = QLabel("&Locale")
        self.localeLabel.setBuddy(self.localeCombo)

        self.firstDayCombo = QComboBox()
        self.firstDayCombo.addItem("Sunday", Qt.Sunday)
        self.firstDayCombo.addItem("Monday", Qt.Monday)
        self.firstDayCombo.addItem("Tuesday", Qt.Tuesday)
        self.firstDayCombo.addItem("Wednesday", Qt.Wednesday)
        self.firstDayCombo.addItem("Thursday", Qt.Thursday)
        self.firstDayCombo.addItem("Friday", Qt.Friday)
        self.firstDayCombo.addItem("Saturday", Qt.Saturday)

        self.firstDayLabel = QLabel("Wee&k starts on:")
        self.firstDayLabel.setBuddy(self.firstDayCombo)

        self.selectionModeCombo = QComboBox()
        self.selectionModeCombo.addItem("Single selection",
                QCalendarWidget.SingleSelection)
        self.selectionModeCombo.addItem("None",
                QCalendarWidget.NoSelection)
        self.selectionModeLabel = QLabel("&Selection mode:")
        self.selectionModeLabel.setBuddy(self.selectionModeCombo)

        self.gridCheckBox = QCheckBox("&Grid")
        self.gridCheckBox.setChecked(self.calendar.isGridVisible())

        self.navigationCheckBox = QCheckBox("&Navigation bar")
        self.navigationCheckBox.setChecked(True)

        self.horizontalHeaderCombo = QComboBox()
        self.horizontalHeaderCombo.addItem("Single letter day names",
                QCalendarWidget.SingleLetterDayNames)
        self.horizontalHeaderCombo.addItem("Short day names",
                QCalendarWidget.ShortDayNames)
        self.horizontalHeaderCombo.addItem("Long day names",
                QCalendarWidget.LongDayNames)
        self.horizontalHeaderCombo.addItem("None",
                QCalendarWidget.NoHorizontalHeader)
        self.horizontalHeaderCombo.setCurrentIndex(1)

        self.horizontalHeaderLabel = QLabel("&Horizontal header:")
        self.horizontalHeaderLabel.setBuddy(self.horizontalHeaderCombo)

        self.verticalHeaderCombo = QComboBox()
        self.verticalHeaderCombo.addItem("ISO week numbers",
                QCalendarWidget.ISOWeekNumbers)
        self.verticalHeaderCombo.addItem("None",
                QCalendarWidget.NoVerticalHeader)

        self.verticalHeaderLabel = QLabel("&Vertical header:")
        self.verticalHeaderLabel.setBuddy(self.verticalHeaderCombo)

        self.localeCombo.currentIndexChanged.connect(self.localeChanged)
        self.firstDayCombo.currentIndexChanged.connect(self.firstDayChanged)
        self.selectionModeCombo.currentIndexChanged.connect(
                self.selectionModeChanged)
        self.gridCheckBox.toggled.connect(self.calendar.setGridVisible)
        self.navigationCheckBox.toggled.connect(
                self.calendar.setNavigationBarVisible)
        self.horizontalHeaderCombo.currentIndexChanged.connect(
                self.horizontalHeaderChanged)
        self.verticalHeaderCombo.currentIndexChanged.connect(
                self.verticalHeaderChanged)

        checkBoxLayout = QHBoxLayout()
        checkBoxLayout.addWidget(self.gridCheckBox)
        checkBoxLayout.addStretch()
        checkBoxLayout.addWidget(self.navigationCheckBox)

        outerLayout = QGridLayout()
        outerLayout.addWidget(self.localeLabel, 0, 0)
        outerLayout.addWidget(self.localeCombo, 0, 1)
        outerLayout.addWidget(self.firstDayLabel, 1, 0)
        outerLayout.addWidget(self.firstDayCombo, 1, 1)
        outerLayout.addWidget(self.selectionModeLabel, 2, 0)
        outerLayout.addWidget(self.selectionModeCombo, 2, 1)
        outerLayout.addLayout(checkBoxLayout, 3, 0, 1, 2)
        outerLayout.addWidget(self.horizontalHeaderLabel, 4, 0)
        outerLayout.addWidget(self.horizontalHeaderCombo, 4, 1)
        outerLayout.addWidget(self.verticalHeaderLabel, 5, 0)
        outerLayout.addWidget(self.verticalHeaderCombo, 5, 1)
        self.generalOptionsGroupBox.setLayout(outerLayout)

        self.firstDayChanged(self.firstDayCombo.currentIndex())
        self.selectionModeChanged(self.selectionModeCombo.currentIndex())
        self.horizontalHeaderChanged(self.horizontalHeaderCombo.currentIndex())
        self.verticalHeaderChanged(self.verticalHeaderCombo.currentIndex())
 
    def createDatesGroupBox(self):
        self.datesGroupBox = QGroupBox(self.tr("Dates"))

        self.minimumDateEdit = QDateEdit()
        self.minimumDateEdit.setDisplayFormat('MMM d yyyy')
        self.minimumDateEdit.setDateRange(self.calendar.minimumDate(),
                                          self.calendar.maximumDate())
        self.minimumDateEdit.setDate(self.calendar.minimumDate())

        self.minimumDateLabel = QLabel("&Minimum Date:")
        self.minimumDateLabel.setBuddy(self.minimumDateEdit)

        self.currentDateEdit = QDateEdit()
        self.currentDateEdit.setDisplayFormat('MMM d yyyy')
        self.currentDateEdit.setDate(self.calendar.selectedDate())
        self.currentDateEdit.setDateRange(self.calendar.minimumDate(),
                self.calendar.maximumDate())

        self.currentDateLabel = QLabel("&Current Date:")
        self.currentDateLabel.setBuddy(self.currentDateEdit)

        self.maximumDateEdit = QDateEdit()
        self.maximumDateEdit.setDisplayFormat('MMM d yyyy')
        self.maximumDateEdit.setDateRange(self.calendar.minimumDate(),
                self.calendar.maximumDate())
        self.maximumDateEdit.setDate(self.calendar.maximumDate())

        self.maximumDateLabel = QLabel("Ma&ximum Date:")
        self.maximumDateLabel.setBuddy(self.maximumDateEdit)

        self.currentDateEdit.dateChanged.connect(self.calendar.setSelectedDate)
        self.calendar.selectionChanged.connect(self.selectedDateChanged)
        self.minimumDateEdit.dateChanged.connect(self.minimumDateChanged)
        self.maximumDateEdit.dateChanged.connect(self.maximumDateChanged)
 
        dateBoxLayout = QGridLayout()
        dateBoxLayout.addWidget(self.currentDateLabel, 1, 0)
        dateBoxLayout.addWidget(self.currentDateEdit, 1, 1)
        dateBoxLayout.addWidget(self.minimumDateLabel, 0, 0)
        dateBoxLayout.addWidget(self.minimumDateEdit, 0, 1)
        dateBoxLayout.addWidget(self.maximumDateLabel, 2, 0)
        dateBoxLayout.addWidget(self.maximumDateEdit, 2, 1)
        dateBoxLayout.setRowStretch(3, 1)

        self.datesGroupBox.setLayout(dateBoxLayout)

    def createTextFormatsGroupBox(self):
        self.textFormatsGroupBox = QGroupBox("Text Formats")

        self.weekdayColorCombo = self.createColorComboBox()
        self.weekdayColorCombo.setCurrentIndex(
                self.weekdayColorCombo.findText("Black"))

        self.weekdayColorLabel = QLabel("&Weekday color:")
        self.weekdayColorLabel.setBuddy(self.weekdayColorCombo)

        self.weekendColorCombo = self.createColorComboBox()
        self.weekendColorCombo.setCurrentIndex(
                self.weekendColorCombo.findText("Red"))

        self.weekendColorLabel = QLabel("Week&end color:")
        self.weekendColorLabel.setBuddy(self.weekendColorCombo)

        self.headerTextFormatCombo = QComboBox()
        self.headerTextFormatCombo.addItem("Bold")
        self.headerTextFormatCombo.addItem("Italic")
        self.headerTextFormatCombo.addItem("Plain")

        self.headerTextFormatLabel = QLabel("&Header text:")
        self.headerTextFormatLabel.setBuddy(self.headerTextFormatCombo)

        self.firstFridayCheckBox = QCheckBox("&First Friday in blue")

        self.mayFirstCheckBox = QCheckBox("May &1 in red")

        self.weekdayColorCombo.currentIndexChanged.connect(
                self.weekdayFormatChanged)
        self.weekendColorCombo.currentIndexChanged.connect(
                self.weekendFormatChanged)
        self.headerTextFormatCombo.currentIndexChanged.connect(
                self.reformatHeaders)
        self.firstFridayCheckBox.toggled.connect(self.reformatCalendarPage)
        self.mayFirstCheckBox.toggled.connect(self.reformatCalendarPage)

        checkBoxLayout = QHBoxLayout()
        checkBoxLayout.addWidget(self.firstFridayCheckBox)
        checkBoxLayout.addStretch()
        checkBoxLayout.addWidget(self.mayFirstCheckBox)

        outerLayout = QGridLayout()
        outerLayout.addWidget(self.weekdayColorLabel, 0, 0)
        outerLayout.addWidget(self.weekdayColorCombo, 0, 1)
        outerLayout.addWidget(self.weekendColorLabel, 1, 0)
        outerLayout.addWidget(self.weekendColorCombo, 1, 1)
        outerLayout.addWidget(self.headerTextFormatLabel, 2, 0)
        outerLayout.addWidget(self.headerTextFormatCombo, 2, 1)
        outerLayout.addLayout(checkBoxLayout, 3, 0, 1, 2)
        self.textFormatsGroupBox.setLayout(outerLayout)

        self.weekdayFormatChanged()
        self.weekendFormatChanged()

        self.reformatHeaders()
        self.reformatCalendarPage()
 
    def createColorComboBox(self):
        comboBox = QComboBox()
        comboBox.addItem("Red", Qt.red)
        comboBox.addItem("Blue", Qt.blue)
        comboBox.addItem("Black", Qt.black)
        comboBox.addItem("Magenta", Qt.magenta)

        return comboBox
Ejemplo n.º 28
0
class VistaListaPrenotazioni(QWidget):
    global currentYear, currentMonth

    currentMonth = datetime.now().month
    currentYear = datetime.now().year

    def __init__(self):
        super(VistaListaPrenotazioni, self).__init__()
        grid_layout = QGridLayout()
        self.controller = ControlloreListaPrenotazioni()
        self.list_view = QListView()

        self.calendar = QCalendarWidget(self)
        self.calendar.move(20, 20)
        self.calendar.setGridVisible(True)
        self.calendar.setMinimumDate(QDate(currentYear, currentMonth - 1, 1))
        self.calendar.setMaximumDate(
            QDate(currentYear, currentMonth + 1,
                  calendar.monthrange(currentYear, currentMonth)[1]))
        self.calendar.setSelectedDate(QDate(currentYear, currentMonth, 1))
        self.calendar.clicked.connect(self.printInfo)

        buttons_layout = QVBoxLayout()
        add_button = QPushButton("Aggiungi prenotazione")
        add_button.clicked.connect(self.aggiungi_prenotazione)
        buttons_layout.addWidget(add_button)

        delete_button = QPushButton("Elimina prenotazione")
        delete_button.clicked.connect(self.elimina_prenotazione)
        buttons_layout.addWidget(delete_button)

        grid_layout.addWidget(self.calendar, 0, 0)
        grid_layout.addLayout(buttons_layout, 0, 1)
        grid_layout.addWidget(self.list_view, 1, 0)

        self.resize(600, 400)
        self.setWindowTitle('Lista Prenotazioni')
        self.setLayout(grid_layout)

    def printInfo(self, qDate):
        self.listview_model = QStandardItemModel(self.list_view)
        item = QStandardItem()
        fontstd = QFont("DejaVu Sans Mono", 10)
        fontstd.setFamily('Monospace')
        fontstd.setFixedPitch(True)
        item.setFont(fontstd)
        item.setText("{0:<15}{1:<12}{2:<10}{3}".format("Nome: ", "Telefono:",
                                                       "Persone:", "Orario:"))
        item.setEditable(False)
        font = item.font()
        font.setPointSize(12)
        item.setFont(font)
        self.listview_model.appendRow(item)

        for prenotazione in self.controller.get_prenotazioni_by_data(
                datetime(qDate.year(), qDate.month(), qDate.day())):
            item = QStandardItem()
            fontstd = QFont("DejaVu Sans Mono", 10)
            fontstd.setFamily('Monospace')
            fontstd.setFixedPitch(True)
            item.setFont(fontstd)
            item.setText("{0:<15}{1:<12}{2:<10}{3}".format(
                prenotazione.nome, prenotazione.telefono,
                prenotazione.num_persone, prenotazione.data.hour))
            item.setEditable(False)
            font = item.font()
            font.setPointSize(12)
            item.setFont(font)
            self.listview_model.appendRow(item)
        self.list_view.setModel(self.listview_model)

    def aggiungi_prenotazione(self):
        self.vista_aggiungi_prenotazione = VistaPrenotazione(self.controller)
        self.vista_aggiungi_prenotazione.show()

    def elimina_prenotazione(self):
        pass
Ejemplo n.º 29
0
Archivo: gui.py Proyecto: kharyuk/astro
class DateInputW(QFrame):
    def __init__(self, parent):
        super(DateInputW, self).__init__()
        
        self.layout = QGridLayout()
        self.parent = parent
        
        self.title1 = QLabel(u'Начало:', self)
        self.title1.move(5, 5)
        self.cal1 = QCalendarWidget()
        self.cal1.setGridVisible(True)
        self.cal1.setDateEditEnabled(True)

        self.cal1.clicked.connect(self.setDateStart)
        self.cal1.setFixedSize(200, 160)
        ymd1 = [parent.day_start.year, parent.day_start.month, parent.day_start.day]
        qdate1 = QDate()
        qdate1.setDate(ymd1[0], ymd1[1], ymd1[2])
        self.cal1.setSelectedDate(qdate1)
        
        self.lbl1 = QLabel(self)
        self.lbl1.setText(parent.day_start.strftime('%d/%m/%Y'))
        self.lbl1.move(5, 25)
        
        self.title2 = QLabel(u'Конец:', self)
        self.title2.move(325, 5)
        self.cal2 = QCalendarWidget()
        self.cal2.setGridVisible(True)
        self.cal2.setDateEditEnabled(True)

        self.cal2.clicked.connect(self.setDateEnd)
        self.cal2.setFixedSize(200, 160)
        ymd2 = [parent.day_end.year, parent.day_end.month, parent.day_end.day]
        qdate2 = QDate()
        qdate2.setDate(ymd2[0], ymd2[1], ymd2[2])
        self.cal2.setSelectedDate(qdate2)
        
        self.lbl2 = QLabel(self)
        self.lbl2.setText(parent.day_end.strftime('%d/%m/%Y'))
        self.lbl2.move(325, 25)
        
        self.layout.addWidget(self.cal1, 1, 0)
        self.layout.addWidget(self.cal2, 1, 1)
        
        self.setAutoFillBackground(True)
        palette = self.palette()
        palette.setColor(self.backgroundRole(), QColor('white'))
        self.setPalette(palette)
        
        self.setFrameShape(_frameShape)
        self.setFrameShadow(_frameShadow)
        self.setLineWidth(_lineWidth)
        self.setMidLineWidth(_midLineWidth)
        
        #change NavBar background color
        child = self.cal1.children()[3]
        palette = child.palette()
        palette.setColor(child.backgroundRole(), QColor('silver'))
        child.setPalette(palette)
        
        child = self.cal2.children()[3]
        palette = child.palette()
        palette.setColor(child.backgroundRole(), QColor('silver'))
        child.setPalette(palette)
        
        # change cell color
        brush = self.cal1.paintCell
        
        
        #self.cal1.setWeekdayTextFormat(headerForm)
        
       #parent.layout.addLayout(self.layout, 1, 0, 1, 2)

        

        
    def setDateStart(self):
        date = self.cal1.selectedDate()
        date = date.toPyDate()
        self.parent.day_start = datetime.datetime(date.year, date.month, date.day)
        self.lbl1.setText(self.parent.day_start.strftime('%d/%m/%Y'))
        
        minDate_dt = self.parent.day_start + datetime.timedelta(days=1)
        minDate = QDate()
        minDate.setDate(minDate_dt.year, minDate_dt.month, minDate_dt.day)
        self.cal2.setMinimumDate(minDate)

    def setDateEnd(self):
        date = self.cal2.selectedDate()
        date = date.toPyDate()
        self.parent.day_end = datetime.datetime(date.year, date.month, date.day)
        self.lbl2.setText(self.parent.day_end.strftime('%d/%m/%Y'))
        
        maxDate_dt = self.parent.day_end - datetime.timedelta(days=1)
        maxDate = QDate()
        maxDate.setDate(maxDate_dt.year, maxDate_dt.month, maxDate_dt.day)
        self.cal1.setMaximumDate(maxDate)
Ejemplo n.º 30
0
    def initUI(self):
        # checkBox
        cb = QCheckBox('show title', self)
        cb.move(10, 10)
        cb.toggle()
        cb.stateChanged.connect(self.changeTitle)

        # 颜色混合
        self.col = QColor(0, 0, 0)
        redb = QPushButton('Red', self)
        redb.setCheckable(True)
        redb.move(10, 30)
        redb.clicked[bool].connect(self.setColor)

        grnb = QPushButton('Green', self)
        grnb.setCheckable(True)
        grnb.move(10, 60)
        grnb.clicked[bool].connect(self.setColor)

        blueb = QPushButton('Blue', self)
        blueb.setCheckable(True)
        blueb.move(10, 90)
        blueb.clicked[bool].connect(self.setColor)

        self.square = QFrame(self)
        self.square.setGeometry(150, 20, 50, 50)
        self.square.setStyleSheet("QWidget { background-color: %s}" %
                                  self.col.name())

        # slider 滚动条
        sld = QSlider(Qt.Horizontal, self)
        sld.setFocusPolicy(Qt.NoFocus)
        sld.setGeometry(10, 120, 100, 10)
        sld.valueChanged[int].connect(self.changeValue)

        self.label = QLabel(self)
        self.label.setPixmap(QPixmap('1.png'))
        self.label.setGeometry(150, 90, 80, 80)

        # 进度条ProgressBar
        self.pbar = QProgressBar(self)
        self.pbar.setGeometry(10, 170, 200, 20)
        self.btn = QPushButton('Start', self)
        self.btn.move(10, 200)
        self.btn.clicked.connect(self.doAction)

        self.timer = QBasicTimer()
        self.step = 0

        # Calendar 日历
        cal = QCalendarWidget(self)
        cal.setGridVisible(True)
        cal.move(10, 230)
        cal.clicked[QDate].connect(self.showDate)
        self.lbl = QLabel(self)
        date = cal.selectedDate()
        self.lbl.setText(date.toString())
        self.lbl.move(80, 440)

        self.setGeometry(300, 200, 300, 500)
        self.setWindowTitle('Toggle')
        self.show()
class Calendar(QWidget):
    def __init__(self, dateplot):
        self.dateplot = dateplot
        QWidget.__init__(self)
        self.layout = QHBoxLayout()

        self.cal = QCalendarWidget(self)
        self.cal.setGridVisible(True)
        self.cal.clicked[QDate].connect(self.showDate)
        self.cal.activated.connect(self.hide)

        gbCalendar = QGroupBox('Calendar')
        gbDataset = QGroupBox('Dataset')
        gbCalendar.setStyleSheet('QGroupBox { padding-top: 20 px;border: 1px solid gray; border-radius: 3px}')
        gbDataset.setStyleSheet('QGroupBox { padding-top: 20 px;border: 1px solid gray; border-radius: 3px}')

        self.confAuto = QCheckBox('Configuration : Auto')
        self.checkboxRealTime = QCheckBox('Real-time')
        self.checkboxPastRuns = QCheckBox('Archived')
        self.spinboxDays = QSpinBox()
        self.spinboxDays.setRange(1, 100)
        self.spinboxDays.setValue(1)

        self.confAuto.setChecked(0)

        self.confAuto.stateChanged.connect(self.dateplot.loadConf)
        self.checkboxRealTime.stateChanged.connect(self.realtime)
        self.checkboxPastRuns.stateChanged.connect(self.archivedData)

        self.checkboxRealTime.setCheckState(2)
        layoutDataset = QGridLayout()
        layoutDataset.addWidget(self.confAuto, 0, 0, 2, 1)
        layoutDataset.addWidget(self.checkboxRealTime, 2, 0, 2, 1)
        layoutDataset.addWidget(QLabel('Duration (Days)'), 4, 1, 1, 1)
        layoutDataset.addWidget(self.checkboxPastRuns, 5, 0, 1, 1)
        layoutDataset.addWidget(self.spinboxDays, 5, 1, 1, 1)

        layoutCalendar = QVBoxLayout()
        layoutCalendar.addWidget(self.cal)

        gbCalendar.setLayout(layoutCalendar)
        gbDataset.setLayout(layoutDataset)

        self.layout.addWidget(gbCalendar)
        self.layout.addWidget(gbDataset)
        self.setLayout(self.layout)
        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle('Calendar')
        self.setWindowModality(Qt.WindowModal)

    def showDate(self, date=None):
        date = self.cal.selectedDate() if date is None else date

        date = dt.datetime.combine(date.toPyDate(), dt.datetime.min.time())
        self.dateplot.updateDate(date)

    def closeEvent(self, event):
        self.hide()
        try:
            event.accept()
        except AttributeError:
            pass

    def realtime(self):
        state = 0 if self.checkboxRealTime.isChecked() else 2
        self.checkboxPastRuns.setCheckState(state)

    def archivedData(self):
        state = 0 if self.checkboxPastRuns.isChecked() else 2
        self.checkboxRealTime.setCheckState(state)
Ejemplo n.º 32
0
    def initUI(self):

        # checkbox
        cb = QCheckBox('show title', self)
        cb.move(20, 20)
        cb.toggle()
        cb.stateChanged.connect(self.changeTitle)

        # toggle button
        self.col = QColor(0, 0, 0)

        redb = QPushButton('red', self)
        redb.setCheckable(True)
        redb.move(20, 40)
        redb.clicked[bool].connect(self.setColor)

        greenb = QPushButton('green', self)
        greenb.setCheckable(True)
        greenb.move(20, 60)
        greenb.clicked[bool].connect(self.setColor)

        blueb = QPushButton('blue', self)
        blueb.setCheckable(True)
        blueb.move(20, 80)
        blueb.clicked[bool].connect(self.setColor)

        self.square = QFrame(self)
        self.square.setGeometry(150, 20, 100, 100)
        self.square.setStyleSheet('QWidget {background-color: %s}' %
            self.col.name())

        # slider
        sld = QSlider(Qt.Horizontal, self)
        sld.setFocusPolicy(Qt.NoFocus)
        sld.setGeometry(20, 160, 100, 20)
        sld.valueChanged[int].connect(self.changeValue)

        self.label = QLabel('0', self)
        self.label.setGeometry(140, 155, 80, 30)

        # progressbar
        self.pbar = QProgressBar(self)
        self.pbar.setGeometry(20, 200, 200, 25)

        self.btn = QPushButton('start', self)
        self.btn.move(20, 230)
        self.btn.clicked.connect(self.doAction)

        self.timer = QBasicTimer()
        self.step = 0

        # calendar
        cal = QCalendarWidget(self)
        cal.setGridVisible(True)
        cal.move(20, 300)
        cal.clicked[QDate].connect(self.showDate)

        self.lbl = QLabel(self)
        date = cal.selectedDate()
        self.lbl.setText(date.toString())
        self.lbl.move(20, 280)

        self.setGeometry(300, 300, 400, 550)
        self.setWindowTitle('widgets')
        self.show()
Ejemplo n.º 33
0
class Tab(QTabWidget):
    def __init__(self):
        super(Tab, self).__init__()
        self.initGUI()

    def initGUI(self):

        self.setGeometry(500, 300, 800, 650)
        self.setWindowTitle("CollegeBoard")

        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tab3 = QWidget()
        self.tab4 = QWidget()
        self.tab5 = QWidget()

        self.addTab(self.tab1, "Personal information")
        self.addTab(self.tab2, "Choose a major")
        self.addTab(self.tab3, "Personal statement")
        self.addTab(self.tab4, "Register for a test")
        self.addTab(self.tab5, "Registration completed!")


        self.tab_1()
        self.tab_2()
        self.tab_3()
        self.tab_4()
        self.tab_5()

        self.setTabsClosable(True)
        self.tabCloseRequested.connect(self.closeTab)

        self.show()



    def closeTab(self, currentIndex):
        currentQWidget = self.widget(currentIndex)
        currentQWidget.deleteLater()
        self.removeTab(currentIndex)

    def tab_1(self):
        layout = QFormLayout()
        self.tab1.setLayout(layout)

        self.progressbar = QProgressBar(self)
        self.progressbar.setValue(0)
        layout.addRow(self.progressbar)

        self.btn1 = QPushButton('Next Page', self)
        self.btn1.clicked.connect(self.nextPage)
        self.btn1.move(650,600)

        self.txt1 = QLineEdit(self)
        self.txt1.setPlaceholderText("Cici")
        layout.addRow("First name", self.txt1)
        self.txt2 = QLineEdit(self)
        self.txt2.setPlaceholderText("Chen")
        layout.addRow("Last name", self.txt2)
        self.txt3 = QLineEdit(self)
        self.txt3.setPlaceholderText("")
        layout.addRow("Address", self.txt3)
        self.txt4 = QLineEdit(self)
        self.txt4.setPlaceholderText("")
        layout.addRow("Phone number", self.txt4)
        layout.addWidget(QLabel("Gender"))
        layout.addWidget(QCheckBox("Male"))
        layout.addWidget(QCheckBox("Female"))
        self.txt5 = QLineEdit(self)
        self.txt5.setPlaceholderText("")
        layout.addRow("Student ID", self.txt5)
        self.txt6 = QLineEdit(self)
        self.txt6.setPlaceholderText("mm/dd/yyyy")
        layout.addRow("Birthday", self.txt6)
        self.txt7 = QLineEdit(self)
        self.txt7.setPlaceholderText("Pacific American School")
        layout.addRow("High School", self.txt7)

        self.comboBox1 = QComboBox(self)
        self.comboBox1.addItem("January")
        self.comboBox1.addItem("February")
        self.comboBox1.addItem("March")
        self.comboBox1.addItem("April")
        self.comboBox1.addItem("May")
        self.comboBox1.addItem("June")
        self.comboBox1.addItem("July")
        self.comboBox1.addItem("August")
        self.comboBox1.addItem("September")
        self.comboBox1.addItem("October")
        self.comboBox1.addItem("November")
        self.comboBox1.addItem("December")
        layout.addRow("Graduation month", self.comboBox1)
        self.comboBox2 = QComboBox(self)
        self.comboBox2.addItem("2016")
        self.comboBox2.addItem("2017")
        self.comboBox2.addItem("2018")
        self.comboBox2.addItem("2019")
        self.comboBox2.addItem("2020")
        self.comboBox2.addItem("2021")
        self.comboBox2.addItem("2022")
        layout.addRow("Graduation year", self.comboBox2)

        self.btn2 = QPushButton('Change a photo', self)
        layout.addRow("", self.btn2)
        self.label1 = QLabel(self)
        layout.addRow(self.label1)
        self.label1.move(300, 60)
        self.label1.setPixmap(QPixmap('picture.jpg'))
        self.label1.resize(430, 60)



    def tab_2(self):
        layout = QFormLayout()
        self.tab2.setLayout(layout)

        self.btn1 = QPushButton('Next Page', self)
        self.btn1.clicked.connect(self.nextPage)
        self.btn1.move(650,600)

        self.progressbar = QProgressBar(self)
        self.progressbar.setValue(25)
        layout.addRow(self.progressbar)

        # -- add a checkbox
        self.check = QCheckBox('Biology', self)
        self.check.setTristate(True) # allowing tristate
        layout.addRow(self.check)
        self.check = QCheckBox('Chemistry', self)
        self.check.setTristate(True) # allowing tristate
        layout.addRow(self.check)
        self.check = QCheckBox('Computer science', self)
        self.check.setTristate(True) # allowing tristate
        layout.addRow(self.check)
        self.check = QCheckBox('Engineering', self)
        self.check.setTristate(True) # allowing tristate
        layout.addRow(self.check)
        self.check = QCheckBox('Arts & design', self)
        self.check.setTristate(True) # allowing tristate
        layout.addRow(self.check)
        self.check = QCheckBox('Literature', self)
        self.check.setTristate(True) # allowing tristate
        layout.addRow(self.check)
        self.check = QCheckBox('History', self)
        self.check.setTristate(True) # allowing tristate
        layout.addRow(self.check)
        self.check = QCheckBox('Language', self)
        self.check.setTristate(True) # allowing tristate
        layout.addRow(self.check)
        self.check = QCheckBox('Media', self)
        self.check.setTristate(True) # allowing tristate
        layout.addRow(self.check)
        self.check = QCheckBox('Philosophy', self)
        self.check.setTristate(True) # allowing tristate
        self.check.stateChanged.connect(self.dosth)
        layout.addRow(self.check)


    def dosth(self):
        state = self.check.checkState()
        if state == 0:
            self.setWindowTitle('You have deselected this major')
        elif state == 1:
            self.setWindowTitle('You are unsure of this major')
        elif state == 2:
            self.setWindowTitle('You have selected this major')


    def tab_3(self):
        layout = QFormLayout()
        self.tab3.setLayout(layout)

        self.btn1 = QPushButton('Next Page', self)
        self.btn1.clicked.connect(self.nextPage)
        self.btn1.move(650,600)

        self.progressbar = QProgressBar(self)
        self.progressbar.setValue(50)
        layout.addRow(self.progressbar)

        self.txt1 = QLineEdit('', self)
        self.txt2 = QLineEdit('', self)
        self.txt3 = QLineEdit('', self)
        self.txt4 = QLineEdit('', self)
        self.txt5 = QLineEdit('', self)

        self.dock1 = QDockWidget('Personal statement', self)
        self.dock1.move(20, 20)
        self.dock1.setWidget(self.txt1)

        self.dock1.setFloating(False)
        self.dock1.setFeatures(self.dock1.DockWidgetMovable)

        layout.addRow(self.dock1)
        layout.addRow('Please write a short statement about yourself.', self.txt1)
        layout.addRow(self.txt1)
        layout.addRow('What is your hobby?', self.txt2)
        layout.addRow(self.txt2)
        layout.addRow('What characteristics do you have that differs from others?', self.txt3)
        layout.addRow(self.txt3)
        layout.addRow('Which college do you want to go to and why?', self.txt4)
        layout.addRow(self.txt4)
        layout.addRow('Which after school activities did you attend in high school?', self.txt5)
        layout.addRow(self.txt5)



    def tab_4(self):
        layout = QFormLayout()
        self.tab4.setLayout(layout)

        self.btn1 = QPushButton('Next Page', self)
        self.btn1.clicked.connect(self.nextPage)
        self.btn1.move(650,600)

        self.progressbar = QProgressBar(self)
        self.progressbar.setValue(75)
        layout.addRow(self.progressbar)

        self.cal = QCalendarWidget(self)
        self.cal.setWindowTitle('Calendar')
        self.cal.setGridVisible(True) #one of the function
        self.cal.move(20, 100)
        self.cal.clicked[QDate].connect(self.showDate)
        self.label = QLabel(self)
        self.date = self.cal.selectedDate() #another function
        self.label.setText(self.date.toString())
        self.label.move(100, 500)
        layout.addRow(self.cal)
        layout.addRow(self.label)


        # -- add a checkbox
        self.check1 = QCheckBox('SAT w/ essay', self)
        layout.addRow(self.check1)
        self.check2 = QCheckBox('Chinese w/ listening', self)
        layout.addRow(self.check2)
        self.check3 = QCheckBox('Physics', self)
        layout.addRow(self.check3)
        self.check4 = QCheckBox('Math I', self)
        layout.addRow(self.check4)
        self.check5 = QCheckBox('Math II', self)
        layout.addRow(self.check5)
        self.check6 = QCheckBox('Biology', self)
        layout.addRow(self.check6)
        self.check7 = QCheckBox('US History', self)
        layout.addRow(self.check7)
        self.check8 = QCheckBox('Literature', self)
        layout.addRow(self.check8)
        self.check9 = QCheckBox('Spanish', self)
        layout.addRow(self.check9)
        self.check10 = QCheckBox('French', self)
        layout.addRow(self.check10)

        # add a button
        self.btn1 = QPushButton('Reset', self)
        self.btn1.setToolTip('This button resets the checkbox!')
        self.btn1.resize(250, 90)
        self.btn1.move(100, 100)
        self.btn1.clicked.connect(self.reset)
        layout.addRow(self.btn1)




    def reset(self):
        self.check1.setChecked(False)
        self.check2.setChecked(False)
        self.check3.setChecked(False)
        self.check4.setChecked(False)
        self.check5.setChecked(False)
        self.check6.setChecked(False)
        self.check7.setChecked(False)
        self.check8.setChecked(False)
        self.check9.setChecked(False)
        self.check10.setChecked(False)



    def tab_5(self):
        layout = QFormLayout()
        self.tab5.setLayout(layout)

        self.label1 = QLabel(self)
        layout.addRow("Your registration have been successfully recorded. ☑️", self.label1)

    def showDate(self, date):
        self.label.setText(date.toString())

    def nextPage(self):
        self.setCurrentIndex(self.currentIndex() + 1)
Ejemplo n.º 34
0
class Update_Daily_Bill(QDialog, Ui_Update_Daily_bill):
    def __init__(self, parent=None):
        super(Update_Daily_Bill, self).__init__(parent)
        self.setupUi(self)

        self.setWindowTitle("Update Daily Bill")

        self.onlyint = QtGui.QIntValidator()
        self.phone_le.setValidator(self.onlyint)
        self.bill_le.setValidator(self.onlyint)
        self.total_le.setValidator(self.onlyint)
        self.recieved_le.setValidator(self.onlyint)
        self.due_le.setValidator(self.onlyint)
        self.pay_le.setValidator(self.onlyint)
        self.balance_le.setValidator(self.onlyint)

        self.pay_le.setPlaceholderText(str(0))
        self.cal_tool.clicked.connect(self.delivery_calender)
        self.save_btn.clicked.connect(self.savebtn)
        self.print_btn.clicked.connect(self.printbill)
        self.close_btn.clicked.connect(self.closebtn)

        self.pay_le.textChanged.connect(self.amountdue)
        self.current_date()
        self.connectdb()

        config_name = 'update_daily_bill.cfg'

        # determine if application is a script file or frozen exe
        if getattr(sys, 'frozen', False):
            application_path = os.path.dirname(sys.executable)
        elif __file__:
            application_path = os.path.dirname(__file__)

        config_path = os.path.join(application_path, config_name)

        icon_image = os.path.join(application_path, "images", "VASA_ICON.png")

        self.setWindowIcon(QtGui.QIcon(icon_image))

        save_image = os.path.join(application_path, "images", "save.png")
        print_image = os.path.join(application_path, "images", "print.png")
        clear_image = os.path.join(application_path, "images", "clear.png")
        close_image = os.path.join(application_path, "images", "close.png")
        self.calender_image = os.path.join(application_path, "images",
                                           "calender.png")

        self.setWindowIcon(QtGui.QIcon(icon_image))

        self.save_btn.setIcon(QtGui.QIcon(save_image))
        self.save_btn.setIconSize(QtCore.QSize(35, 35))

        self.print_btn.setIcon(QtGui.QIcon(print_image))
        self.print_btn.setIconSize(QtCore.QSize(35, 35))

        self.delete_btn.setIcon(QtGui.QIcon(clear_image))
        self.delete_btn.setIconSize(QtCore.QSize(35, 35))

        self.close_btn.setIcon(QtGui.QIcon(close_image))
        self.close_btn.setIconSize(QtCore.QSize(35, 35))

        shortcut = QtWidgets.QShortcut(
            QtGui.QKeySequence(QtCore.Qt.Key_Tab),
            self.bill_le,
            context=QtCore.Qt.WidgetWithChildrenShortcut,
            activated=self.bill_value_fetch)

    def connectdb(self):
        global cur
        global connect
        cur, con = Add_Odbc_Connection.connectdb(self)
        connect = con

        return cur
        '''global cur
        global connect

        connect = pyodbc.connect('Driver={ODBC Driver 17 for SQL Server};'
                                 'Server=DHANALAKSHMI_PC\SQLEXPRESS;'
                                 'Database=VASADB;'
                                 'Trusted_Connection=yes;')
        cur = connect.cursor()
        return cur'''

    def current_date(self):
        now = QDate.currentDate()
        print(now)
        print(now.toString(Qt.ISODate))

        today = datetime.date.today()
        self.billdate = today.strftime("%d/%m/%Y")
        date_format = today.strftime("%d/%m/%Y %A")
        print(date_format)

        self.date_le.setText(date_format)

    def delivery_calender(self):
        self.calender = QCalendarWidget()
        self.calender.setMinimumDate(QDate(1900, 1, 1))
        self.calender.setMaximumDate(QDate(2999, 12, 31))
        self.calender.setGridVisible(True)
        self.calender.clicked.connect(self.updatedate)
        self.calender.setWindowModality(Qt.ApplicationModal)
        self.calender.setWindowTitle("Delivery Date")

        self.calender.setWindowIcon(QtGui.QIcon(self.calender_image))

        self.calender.show()

    def updatedate(self, *args):

        getdate = self.calender.selectedDate().toString("dd/MM/yyyy")
        print('get date value is ', getdate)
        self.delivery_date_le.setText(getdate)
        self.calender.deleteLater()

    def table_records(self):
        self.viewtable.setRowCount(0)
        self.viewtable.setColumnCount(7)
        header_label = [
            'Sl.No', 'Category', 'Size', 'Rate', 'Qty', 'Amount', 'Date'
        ]
        self.viewtable.verticalHeader().setVisible(False)
        self.viewtable.setHorizontalHeaderLabels(header_label)
        for i in range(0, 7):
            self.viewtable.horizontalHeaderItem(i).setTextAlignment(
                Qt.AlignCenter)
        header = self.viewtable.horizontalHeader()
        font = QtGui.QFont()
        font.setFamily("Calibri")
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        header.setFont(font)
        header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
        header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
        header.setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)
        header.setSectionResizeMode(3, QtWidgets.QHeaderView.Stretch)
        header.setSectionResizeMode(4, QtWidgets.QHeaderView.ResizeToContents)
        header.setSectionResizeMode(5, QtWidgets.QHeaderView.Stretch)
        header.setSectionResizeMode(6, QtWidgets.QHeaderView.Stretch)
        header.setStyleSheet("QHeaderView::section { border: 1px solid ;}")

    def bill_value_fetch(self):
        print("This function get passed")
        bill_no = self.bill_le.text()
        print('The bill no is ', bill_no)
        self.table_records()

        select_query = "SELECT ORD.CATEGORY,ORD.SIZE,ORD.RATE,ORD.QTY,ORD.TOTAL_AMOUNT,BILL.BILLING_DATE,\
                        BILL.TOTAL_AMOUNT,BILL.AMOUNT_RECIEVED,BILL.AMOUNT_DUE\
                        FROM DBO.ORDER_DETAILS ORD INNER JOIN DBO.BILLING_TABLE BILL ON\
                        ORD.BILL_NO = BILL.BILL_NO\
                        AND BILL.BILL_NO = ? AND BILL_TYPE ='DAILY'"

        cur.execute(select_query, bill_no)

        result = cur.fetchall()

        result_check = len(result)

        print('the test result value is', result_check)

        if result_check >= 1:

            new_result = []

            for i in range(len(result)):
                tuple_value = result[i]
                tuple_value = list(tuple_value)
                tuple_value[5] = tuple_value[5].strftime('%d/%m/%Y')
                tuple_value = [
                    str(value) for value in tuple_value if type(value) != 'str'
                ]
                print('the modified tuple value is ', tuple_value)
                new_result.append(tuple_value)

            print('The new result value is ', new_result)

            print("the length is ", len(new_result))
            print("the column range is ", range(self.viewtable.columnCount()))
            print("the row range is ", range(len(new_result)))
            for row in range(0, len(new_result)):
                self.viewtable.insertRow(row)
                self.viewtable.setItem(
                    row, 0,
                    self.table_item(str(row + 1),
                                    Qt.ItemIsSelectable | Qt.ItemIsEnabled))
                for column in range(1, self.viewtable.columnCount()):
                    print(
                        ' the result value for ' + str(row - 1) + ' and ' +
                        str(column) + ' is ',
                        new_result[(row - 1)][(column - 1)])
                    value = new_result[(row - 1)][(column - 1)]
                    print('the value is ', value, ' and type is ', type(value))
                    self.viewtable.setItem(
                        row, column,
                        self.table_item(value, Qt.ItemIsSelectable
                                        | Qt.ItemIsEnabled))
                    print('The value inserted in row ', row, ' and column ',
                          column, ' is :', new_result[(row - 1)][(column - 1)])

            bill_select_query = "SELECT CUSTOMER_NAME,PHONE_NO,DELIVERY_DATE FROM \
                                dbo.BILLING_TABLE WHERE BILL_TYPE='DAILY' AND BILL_NO =?"

            cur.execute(bill_select_query, bill_no)

            bill_result = cur.fetchall()

            print(" The bill result value is", bill_result)
            bill_tuple_list = list(bill_result[0])
            print("the new bill result is ", bill_tuple_list)
            bill_tuple_list[2] = bill_tuple_list[2].strftime('%d/%m/%Y')
            bill_tuple_list = [
                str(data) for data in bill_tuple_list if type(data) != 'str'
            ]
            print("the new value for bill list is ", bill_tuple_list)

            db_total_amount = new_result[0][6]
            db_amount_recieved = new_result[0][7]
            db_amount_due = new_result[0][8]
            db_customer_name = bill_tuple_list[0]
            db_phone_no = bill_tuple_list[1]
            db_delivery_date = bill_tuple_list[2]

            self.total_le.setText(db_total_amount)
            self.recieved_le.setText(db_amount_recieved)
            self.due_le.setText(db_amount_due)
            self.customer_le.setText(db_customer_name)
            self.phone_le.setText(db_phone_no)
            self.delivery_date_le.setText(db_delivery_date)
        else:
            QMessageBox.warning(self, 'Error', 'Please enter correct Bill No.')

    def table_item(self, text, flag):

        tablewidgetitem = QTableWidgetItem(text)
        tablewidgetitem.setFlags(flag)
        return tablewidgetitem

    def amountdue(self):

        print('Amount due function in')

        print("the test value is ", self.due_le.text())
        amount_due = float(self.due_le.text())
        if self.pay_le.text() == "":
            Recievedamount = float(0)
        else:
            Recievedamount = float(self.pay_le.text())
        print('Amount due is ', amount_due)
        print('amount  recieved is ', Recievedamount)

        balance = float(amount_due - Recievedamount)

        print('The balanced amount is ', balance)

        self.balance_le.setText(str(balance))

    def savebtn(self):
        if self.bill_le.text() != "":
            billno = int(self.bill_le.text())
            customer_name = self.customer_le.text()
            phone_no = self.phone_le.text()
            delivery_date = self.delivery_date_le.text()
            amount_paid_now = self.pay_le.text()
            amount_recieved_prev = int(float(self.recieved_le.text()))

            if amount_paid_now == '':
                amount_paid_now = '0'

            print('amount paid now is ', amount_paid_now)
            print('amount paid previous is ', amount_recieved_prev)

            amount_recieved = int(amount_recieved_prev + int(amount_paid_now))

            print('amount received sum is', amount_recieved)

            if self.balance_le.text() == '':
                self.balance_le.setText('0')
            amount_due = float(self.balance_le.text())
            int_phone_no = int(phone_no)

            delivery_date = datetime.datetime.strptime(delivery_date,
                                                       '%d/%m/%Y').date()
            int_amount_due = int(amount_due)

            update_query = "UPDATE dbo.BILLING_TABLE SET CUSTOMER_NAME =?,PHONE_NO =?,DELIVERY_DATE =?,\
                            AMOUNT_RECIEVED=?,AMOUNT_DUE=? WHERE BILL_NO =? AND BILL_TYPE='DAILY'"

            update_data = [
                customer_name, int_phone_no, delivery_date, amount_recieved,
                int_amount_due, billno
            ]
            print("the update data is ", update_data)

            cur.execute(update_query, update_data)
            connect.commit()

            category_list = [
                self.viewtable.item(row, 1).text()
                for row in range(self.viewtable.rowCount())
            ]
            frame_size_list = [
                self.viewtable.item(row, 2).text()
                for row in range(self.viewtable.rowCount())
            ]
            rate_list = [
                self.viewtable.item(row, 3).text()
                for row in range(self.viewtable.rowCount())
            ]
            qty_list = [
                self.viewtable.item(row, 4).text()
                for row in range(self.viewtable.rowCount())
            ]
            amount_list = [
                self.viewtable.item(row, 5).text()
                for row in range(self.viewtable.rowCount())
            ]

            self.billno = billno
            self.customer_name = customer_name
            self.phone_number = phone_no
            self.total_amount = self.total_le.text()
            self.amount_recieved = amount_paid_now
            self.due_amount = amount_due
            self.prod_details = category_list
            self.prod_size = frame_size_list
            self.qty_list = qty_list
            self.amount_list = amount_list

            print('the category list is', category_list)
            print('the frame size list is ', frame_size_list)
            print('the rate list is ', rate_list)
            print('the qty list is', qty_list)
            print('the amount list is ', amount_list)

            if int(amount_due) == 0 and int(amount_paid_now) != 0:
                QMessageBox.information(self, 'Message',
                                        'Bill is successfully closed')
            else:
                QMessageBox.information(self, 'Message',
                                        'Bill is updated Successfully')

            self.save_btn.setEnabled(False)
        else:
            QMessageBox.warning(self, "Warning", "Please enter a bill no")

    def billcontent(self):
        folder_path = "D:\\Python\\Project\\bills\\"
        timenow = datetime.datetime.now()
        year = str(timenow.year)
        month = timenow.strftime("%B")
        print("the year is", year)
        print("the month is ", month)
        time = str(timenow.strftime("%H-%M"))
        footer_time = str(timenow.strftime("%I:%M %p"))
        print("the footer time is ", footer_time)
        today = datetime.date.today()

        bill_number = str(self.billno)
        cust_name = self.customer_name
        place = 'Mannargudi'
        lines = "\n===================================================================="
        today_date = today.strftime("%d/%m/%Y")

        product = self.prod_details
        size = self.prod_size
        qty = self.qty_list
        amount = self.amount_list
        total_amount = self.total_amount
        amount_paid = self.amount_recieved
        amount_due = self.due_amount

        print("the time is ", time, " and the format is ", type(time))

        folder = folder_path + year + "\\" + month + "\\" + str(today) + '\\'
        filename = str(folder) + "Update_Daily_Bill_" + str(time) + ".rtf"

        print("the file name is ", filename)

        if not os.path.exists(folder):
            os.makedirs(folder)

        file = open(filename, 'w+')

        # file = open('D:/Python/bills/2019-12-30/Daily_Bill_16:49:50.docx','w+')

        # file =open('C:\\bill\\Daily_Bill.rtf','w')

        header = "\n\n\t\t\t\t VASA PHOTOGRAPHY"
        address1 = "\n\t\t\t   No.100, Balakrishna Nagar,"
        address2 = "\n\t\t\t\tKeerthi Clinic [opp],"
        address3 = "\n\t\t\t\t Mannargudi -614001"
        address4 = "\n\n Phone: 9944332270"
        address5 = "\t\t\t\tEmail: [email protected]"
        title = "\n\n\t\t\t\t\t\"CASH BILL\"\n===================================================================="
        bill_section = "\n\n Bill No\t: " + bill_number + "\t\t\t\tName  : " + cust_name
        bill_section2 = "\n Date\t\t: " + today_date + "\t\t\tAddr  : " + place + "\n\n===================================================================="
        table_header = "\n SL.No\tPRODUCT\t\t\tSIZE\t\tQTY\t\tAMOUNT\n===================================================================="

        final = header + address1 + address2 + address3 + address4 + address5 + title + bill_section + bill_section2 + table_header
        file.write(final)

        slno = 1
        table_data = ''

        for prd, size, qty, amt in zip(product, size, qty, amount):
            if len(prd) < 6 and prd != 'FRAME':
                table_value = "\n   " + str(
                    slno) + "\t\t" + prd + "\t\t\t\t" + size + "\t\t" + str(
                        qty) + "\t\t" + str(amt)
                file.write(table_value)
            elif len(prd) > 5 and prd != 'FRAME':
                table_value = "\n   " + str(
                    slno) + "\t\t" + prd + "\t\t\t" + size + "\t\t" + str(
                        qty) + "\t\t" + str(amt)
                file.write(table_value)
            elif prd == 'FRAME' and len(size) > 5:
                table_value = "\n   " + str(
                    slno) + "\t\t" + prd + "\t\t\t\t" + size + "\t" + str(
                        qty) + "\t\t" + str(amt)
                file.write(table_value)
            else:
                table_value = "\n   " + str(
                    slno) + "\t\t" + prd + "\t\t\t\t" + size + "\t\t" + str(
                        qty) + "\t\t" + str(amt)
                file.write(table_value)
            slno += 1
            table_data = table_data + table_value
        file.write(lines)
        netamount = 'NET AMOUNT'  #'''{\\rtf1 \\b Net Amount \\b0\line\}'''
        footer1 = "\n\n  TIME  :" + footer_time + "\t\t\t\t\tTOTAL AMT\t:\t" + str(
            float(total_amount))
        footer_net_amount = "\n\n\t\t\t\t\t" + netamount + "\t\tRs. " + str(
            float(total_amount))
        footer2 = "\n\t\t\t\t\t\tAMT. RECIEVED\t:\t" + str(float(amount_paid))
        footer3 = "\n  SIGN  :\t\t\t\t\t\tAMT. DUE\t:\t" + str(
            float(amount_due))

        footer_final = footer1 + footer_net_amount + lines + footer2 + footer3

        file.write(footer_final)
        file.write(lines)

        message = "\n\t\t*** THANK YOU... PLEASE VISIT US AGAIN ***"
        file.write(message)

        self.file_name = filename

        file.close()

    def printbill(self):
        print("the save btn status is ", self.save_btn.isEnabled())
        if not self.save_btn.isEnabled():
            self.billcontent()
            os.startfile(self.file_name, 'print')
        else:
            QMessageBox.warning(
                self, 'Warning',
                'Please save the data first before printing the bill.')

    def closebtn(self):
        self.close()
Ejemplo n.º 35
0
class OutcomeEventClaster(QDialog):
    def __init__(self, header, outComeEventNames, outComeCategory, units, currency, parent = None):
        QDialog.__init__(self, parent)
        self._acceptState = False
        self._dataContainer = {}
        self._header = header
        self._Currency = currency
        self._units = units
        self._category = outComeCategory
        self._EventNames = outComeEventNames
        
        self.InitUI()
        self.addRowWidgets()
        self.show()
#++++++++++++++++++++++++++++++ InitUI ++++++++++++++++++++++++++++++++
    def InitUI(self):
        self.setWindowTitle("მონაცემთა შეტანა")
        self.setWindowIcon(QtGui.QIcon("icon/outcome.svg"))
        self.setFixedSize(1300, 900)
        vbox = QVBoxLayout()
        hbox = QHBoxLayout()
        vbox.setContentsMargins(2, 2, 2, 2)
############################## Calendar ###############################
        self.calendar = QCalendarWidget()
        self.calendar.setGridVisible(True)
        self.calendar.setFirstDayOfWeek(Qt.Monday)
############################### Table #################################
        self.table = QTableWidget()
        self.table.setRowCount(1)
        self.table.setColumnCount(len(self._header))
        self.table.setHorizontalHeaderLabels(self._header)
        self.table.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        self.table.resizeRowsToContents()
        self.table.setSortingEnabled(False)
        self.table.setWordWrap(True)
        self.rowNumb = self.table.rowCount()-1
############################## add Row ################################
        self.addRowButton = QPushButton('დამატება')
        self.addRowButton.setMaximumWidth(100)
        self.addRowButton.setIcon(QIcon('icon/addRow.svg'))
        self.addRowButton.clicked.connect(self.addRow)
############################## del Row ################################
        self.delRowButton = QPushButton('წაშლა')
        self.delRowButton.setMaximumWidth(100)
        self.delRowButton.setIcon(QIcon('icon/DelRow.svg'))
        self.delRowButton.clicked.connect(self.delRow)
############################### test ##################################
        sumHboxLayout = QHBoxLayout()
        self.sumMoney = QLineEdit()
        self.equivalentSumMoney = QLineEdit()
        sumHboxLayout.addWidget(self.sumMoney)
        sumHboxLayout.addWidget(self.equivalentSumMoney)
        self.testButton = QPushButton('ტესტი')
        self.testButton.setIcon(QIcon('icon/test.png'))
        self.testButton.clicked.connect(self.test)
############################## Accept #################################
        self.acceptButton = QPushButton('დადასტურება', self)
        self.acceptButton.clicked.connect(self.acceptDialog)
############################## Reject #################################
        self.rejectButton = QPushButton('გაუქმება', self)
        self.rejectButton.clicked.connect(self.rejectDialog)
###################### Add widgets on layouts #########################
        hbox.addWidget(self.addRowButton)
        hbox.addWidget(self.delRowButton)

        vbox.addWidget(self.calendar,5)
        vbox.addWidget(self.table,90)
        vbox.addLayout(hbox)
        vbox.addLayout(sumHboxLayout)
        vbox.addWidget(self.testButton,5)
        hboxAcceptReject = QHBoxLayout()
        hboxAcceptReject.addWidget(self.acceptButton)
        hboxAcceptReject.addWidget(self.rejectButton)
        vbox.addLayout(hboxAcceptReject)
        self.setLayout(vbox)
#++++++++++++++++++++++++++++ Add Row +++++++++++++++++++++++++++++++++
    def addRow(self):
        self.rowNumb = self.table.rowCount()
        self.table.insertRow(self.rowNumb)
        self.addRowWidgets()
#++++++++++++++++++++++++ Add Row Widgets +++++++++++++++++++++++++++++
    def addRowWidgets(self):
########################### emountEdit ################################
        quantityEdit = QLineEdit('1')
        quantityEdit.setValidator(QDoubleValidator())
        quantityEdit.setMaximumWidth(30)

        units = QComboBox()
        units.setToolTip("<h5>ერთეული")
        units.setMaximumWidth(70)
        units.addItems(self._units)

        quantityEditHlayout = QHBoxLayout()
        quantityEditHlayout.addWidget(quantityEdit,20)
        quantityEditHlayout.addWidget(units,80)

        quantityEditWidgets = QWidget()
        quantityEditWidgets.setLayout(quantityEditHlayout)
####################### Category Selector #############################
        outcomeCategorySelector = QComboBox()
        outcomeCategorySelector.addItems(self._category)
########################## Price Editor ###############################
        PriceEdit = QLineEdit()
        PriceEdit.setValidator(QDoubleValidator())
        PriceEdit.setToolTip("<h5>გადახდა")
        PriceEdit.setMaximumWidth(70)
#################### Equivalent Price Editor ##########################
        equivalentPriceEdit = QLineEdit()
        equivalentPriceEdit.setValidator(QDoubleValidator())
        equivalentPriceEdit.setText("--")
        equivalentPriceEdit.setToolTip("<h5>კონვერტაცია ვალუტაში")
        equivalentPriceEdit.setMaximumWidth(70)
####################### Currency Selector #############################
        CurrencySelector = QComboBox()
        for idx, key in enumerate(self._Currency):
            CurrencySelector.addItem(key)
            CurrencySelector.setItemData(idx, Qt.AlignCenter, Qt.TextAlignmentRole)
            CurrencySelector.setItemIcon(idx, QtGui.QIcon(self._Currency[key]))
################# Equivalent Currency Selector ########################
        EqviCurrencySelector = QComboBox()
        for idx, key in enumerate(self._Currency):
            EqviCurrencySelector.addItem(key)
            EqviCurrencySelector.setItemData(idx, Qt.AlignCenter, Qt.TextAlignmentRole)
            EqviCurrencySelector.setItemIcon(idx, QtGui.QIcon(self._Currency[key]))
###################### App widgets in cells ###########################
        priceHlayout = QHBoxLayout()
        priceHlayout.addWidget(PriceEdit)
        priceHlayout.addWidget(CurrencySelector)
        priceHlayout.addWidget(equivalentPriceEdit)
        priceHlayout.addWidget(EqviCurrencySelector)

        priceWidgets = QWidget()
        priceWidgets.setLayout(priceHlayout)

        PayMethodWidgets = QWidget()

        PayMethod = QCheckBox()
        PayMethod.setToolTip("<h5>ნაღდით გადახდა")
        PayMethodHlayout = QHBoxLayout()
        PayMethodHlayout.addWidget(PayMethod)
        PayMethodHlayout.setAlignment( Qt.AlignCenter )
        PayMethodWidgets.setLayout(PayMethodHlayout)

        eventContent = QTableWidgetItem('')
        self.table.setItem(self.rowNumb, 0, eventContent)
        eventContent.setData(Qt.UserRole, random.sample(self._EventNames, len(self._EventNames)))
        self.table.setItemDelegate(TableItemCompleter(self.table))

        self.table.setCellWidget(self.rowNumb, 1, quantityEditWidgets)
        self.table.setCellWidget(self.rowNumb, 2, outcomeCategorySelector)
        self.table.setCellWidget(self.rowNumb, 3, priceWidgets)
        self.table.setCellWidget(self.rowNumb, 4, PayMethodWidgets)
###################### Set Table Cell Widths ##########################
        self.table.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)

        self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeToContents)
        self.table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeToContents)
        self.table.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeToContents)
        self.table.horizontalHeader().setSectionResizeMode(4, QHeaderView.ResizeToContents)
# +++++++++++++ String to float number formater +++++++++++++++++++++++
    def _stingToFloatFormater(self, value):
        if ',' in value:
            value = value.replace(",", ".")
            return value
        else:
            return value
#++++++++++++++++++++++++++ Delete Row ++++++++++++++++++++++++++++++++
    def delRow(self):
        self.rowNumb = self.table.rowCount()
        if self.rowNumb > 1:
            selected_Row = self.table.currentRow()
            self.table.removeRow(selected_Row)
#++++++++++++++++++++++ Set calendar date +++++++++++++++++++++++++++++
    def setCalendarDate(self, date):
        self.calendar.setSelectedDate(QDate(date[0], date[1], date[2]))
#++++++++++++++++++++++ Make data claster +++++++++++++++++++++++++++++
    def makeDataClaster(self):
        self._dataContainer = {}
        dataContainerArray = []
        self.rowNumb = self.table.rowCount()
        self.colNumb = self.table.columnCount()
        for row in range(self.rowNumb):
            dataContainerTemp = []
            for column in range(self.colNumb):
                if column == 0:
                    dataContainerTemp.append({'cell_0'   : self.table.item(row,column).text()})
                elif column == 1:
                    dataContainerTemp.append({'cell_1.1' : self._stingToFloatFormater(self.table.cellWidget(row,column).children()[1].text()),
                                              'cell_1.2' : self.table.cellWidget(row,column).children()[2].currentIndex()})
                elif column == 2:
                    dataContainerTemp.append({'cell_2.1' : self.table.cellWidget(row,column).currentIndex()})
                elif column == 3:
                    dataContainerTemp.append({'cell_3.1' : self._stingToFloatFormater(self.table.cellWidget(row,column).children()[1].text()),
                                              'cell_3.2' : self.table.cellWidget(row,column).children()[2].currentIndex(),
                                              'cell_3.3' : self._stingToFloatFormater(self.table.cellWidget(row,column).children()[3].text()),
                                              'cell_3.4' : self.table.cellWidget(row,column).children()[4].currentIndex()})
                elif column == 4:
                    dataContainerTemp.append({'cell_4'   : self.table.cellWidget(row,column).children()[1].isChecked()})
            dataContainerArray.append(dataContainerTemp)
        self._dataContainer.update({self.calendar.selectedDate().toString("dd.MM.yyyy") : dataContainerArray})
#++++++++++++++++++++++ Edit data claster +++++++++++++++++++++++++++++
    def EditDataClaster(self, DataClasterComponent, timeStamp):
        for _ in range(len(DataClasterComponent)-1):
            self.addRow()
        self.setCalendarDate(QDate.fromString(timeStamp, 'dd.MM.yyyy').getDate())
        for row in range(len(DataClasterComponent)):
            self.table.item(row, 0).setText(DataClasterComponent[row][0]['cell_0'])
            self.table.cellWidget(row, 1).children()[1].setText(DataClasterComponent[row][1]['cell_1.1'])
            self.table.cellWidget(row, 1).children()[2].setCurrentIndex(DataClasterComponent[row][1]['cell_1.2'])
            self.table.cellWidget(row, 2).setCurrentIndex(DataClasterComponent[row][2]['cell_2.1'])
            self.table.cellWidget(row, 3).children()[1].setText(DataClasterComponent[row][3]['cell_3.1'])
            self.table.cellWidget(row, 3).children()[2].setCurrentIndex(DataClasterComponent[row][3]['cell_3.2'])
            self.table.cellWidget(row, 3).children()[3].setText(DataClasterComponent[row][3]['cell_3.3'])
            self.table.cellWidget(row, 3).children()[4].setCurrentIndex(DataClasterComponent[row][3]['cell_3.4'])
            self.table.cellWidget(row, 4).children()[1].setChecked(DataClasterComponent[row][4]['cell_4'])
#+++++++++++++++++++++++++++ Accept +++++++++++++++++++++++++++++++++++
    def acceptDialog(self):
        self.makeDataClaster()
        self._acceptState = True
        self.close()
#+++++++++++++++++++++++++++ Reject +++++++++++++++++++++++++++++++++++
    def rejectDialog(self):
        self._acceptState = False
        self.close()
#++++++++++++++++++++ Get data claster part +++++++++++++++++++++++++++
    def getDataClasterPart(self):
        return self._dataContainer, self._acceptState
#++++++++++++++++++++++++++++ Test ++++++++++++++++++++++++++++++++++++
    def test(self):
        print("Test")
        data =  {'22.01.1993': [  [	{'cell_0': 'პური'},
                                    {'cell_1.1': '2', 'cell_1.2': 1},
                                    {'cell_2.1': 2},
                                    {   'cell_3.1': '30',
                                        'cell_3.2': 1,
                                        'cell_3.3': '100',
                                        'cell_3.4': 0},
                                    {'cell_4': True}],
                                  [ {'cell_0': 'ლობიო'},
                                    {'cell_1.1': '5', 'cell_1.2': 1},
                                    {'cell_2.1': 3},
                                    {   'cell_3.1': '64',
                                        'cell_3.2': 2,
                                        'cell_3.3': '54',
                                        'cell_3.4': 3},
                                    {'cell_4': True}]]}
        #self.EditDataClaster(data)
        self.makeDataClaster()
        self.rowNumb = self.table.rowCount()
        sumMoney = 0
        equiSumMoney = 0
        for row in range(self.rowNumb):
            try:
                sumMoney = sumMoney + round(float(self.table.cellWidget(row,3).children()[1].text()), 2)
            except ValueError:
                pass
            try:
                equiSumMoney = equiSumMoney + round(float(self.table.cellWidget(row,3).children()[3].text()), 2)
            except ValueError:
                pass
        self.sumMoney.setText(str(sumMoney))
        self.equivalentSumMoney.setText(str(equiSumMoney))
Ejemplo n.º 36
0
class MyTable(QTableWidget):
	def __init__(self, r, c):
		super().__init__(r, c)
		self.FileOpenProcess = False
		self.ChangeDateProcess = False
		self.initUI()
		self.ProjectName = ""
		self.ProjectManager = ""
		self.Start = ""
		self.cal = QCalendarWidget(self)


	def initUI(self):
		self.cellChanged.connect(self.c_Current)
		self.cellClicked.connect(self.c_Clicked)
		self.show()

	def c_Current(self):
		if self.FileOpenProcess == False:
			row = self.currentRow()
			col = self.currentColumn()
			self.FileOpenProcess = True
			print ("row =" + str(row) + "coloumn = " + str(col) )
			try:
				if int(col) == 6 :
					print ("in calculation")
					endDate = self.calculateEndDate(row)
					print (endDate)
					self.setItem(row, 7, QTableWidgetItem(str(endDate)))
				elif int(col) in (2,4):
					if self.circularcheck() :
						print("in change dependency" )
						self.recalcDates(row)
			except:
				print ("in Exception")
				type, value, traceback = sys.exc_info()
				print (value)
				if (self.item(row,4) is None ):
					self.setItem(row,4,QTableWidgetItem("FS"))
				elif (self.item(row,2) is None ):
					self.setItem(row,2, QTableWidgetItem("0"))
				elif (self.item(row, 5) is None):
					self.setItem(row, 5, QTableWidgetItem(str(datetime.datetime.today())))
					if (self.item(row, 6) is None):
						self.setItem(row, 6, QTableWidgetItem("1d"))
				elif (self.item(row, 6) is None):
					self.setItem(row, 6, QTableWidgetItem("1d"))
					self.recalcDates(row)
				else:
					warn = QMessageBox(QMessageBox.Warning, "Error!",  "Could Not Calculate")
					warn.setStandardButtons(QMessageBox.Ok);
					warn.exec_()
					self.setItem(row, col, QTableWidgetItem(str("")))
			self.FileOpenProcess = False

	def c_Clicked(self):
		if self.FileOpenProcess == False:
			row = self.currentRow()
			col = self.currentColumn()
			self.FileOpenProcess == True
			if int(col) in(5,7):
				self.myCal()

	def myCal(self):
		self.cal.setGridVisible(True)
		self.cal.move(QtGui.QCursor.pos().x(), QtGui.QCursor.pos().y()-60)
		print (self.mapToGlobal(QtGui.QCursor.pos()))
		self.ChangeDateProcess = True
		self.cal.clicked.connect(self.getDate)
		self.cal.setGridVisible(True)	
		self.cal.show()
		
	def getDate(self):
		row = self.currentRow()
		col = self.currentColumn()
		if self.ChangeDateProcess:
			print (self.cal.selectedDate().toString())
			date = str(datetime.datetime.strptime( self.cal.selectedDate().toString(), '%a %b %d %Y') + datetime.timedelta(hours=8))
			self.setItem(row,col,QTableWidgetItem(date))
			print (date)
			self.ChangeDateProcess = False
			self.cal.hide()
		else:
			pass

	def recalcDates(self, row):
		type = self.item(int(row),4).text()
		print (type)
		if row !=0:
			if type.lower() == "fs":
				startDate = self.item(int(self.item(int(row), 2).text()), 7).text()
			elif type.lower() == 'ss':
				startDate = self.item(int(self.item(int(row-1), 2).text()), 5).text()
			self.setItem(int(row),5, QTableWidgetItem(str(startDate)))
			self.setItem(int(row),7, QTableWidgetItem(str(self.calculateEndDate (row))))


	def calculateEndDate(self, row):
		r = re.compile("([0-9]+)([a-zA-Z]+)")
		duration = str(self.item(row,6).text())
		print(duration)
		m = r.match(duration)
		duration = int(m.group(1))
		period = str(m.group(2))
		##2018-05-12 08:00:00
		endDate =  self.item(row,6).text()
		date = datetime.datetime.strptime( self.item(row,5).text() , '%Y-%m-%d %H:%M:%S')
		if period.lower() == 'h':
			enddate = date + datetime.timedelta(hours=int(duration))
			print  (endDate)
		elif period.lower() == 'm':
			enddate = date + datetime.timedelta(minutes=int(duration))
		elif period.lower() == 'd':
			enddate = date + datetime.timedelta(days=int(duration))
		elif period.lower() == 'w':
			enddate = date + datetime.timedelta(weeks=int(duration))
		else:
			QMessageBox.warning(self.view, 'Wrong Format', msg)

		return(enddate)

	def openProject(self):
		self.FileOpenProcess = True
		file = QFileDialog.getOpenFileName(self, 'Open NPF', os.getenv('HOME'), 'NPF(*.npf)')
		if file[0] != '':
			print (file[0])
			with open(file[0], newline='') as csv_file:
				self.setRowCount(0)
				self.setColumnCount(9)
				my_file = csv.reader(csv_file, dialect='excel')
				for row_data in my_file:
					row = self.rowCount()
					self.insertRow(row)
					if len(row_data) > 8:
						self.setColumnCount(len(row_data))
					for column, stuff in enumerate(row_data):
						item = QTableWidgetItem(stuff)
						self.setItem(row, column, item)
		self.FileOpenProcess = False

	def saveProject(self):
		path = QFileDialog.getSaveFileName(self, 'Save Project', os.getenv('HOME'), 'NPF(*.npf)')
		if path[0] != '':
			with open(path[0], 'w', newline = '') as csv_file:
				writer = csv.writer(csv_file, dialect='excel')
				for row in range(self.rowCount()):
					row_data = []
					for column in range(self.columnCount()):
						item = self.item(row, column)
						if item is not None:
							row_data.append(item.text())
						else:
							row_data.append('')
					writer.writerow(row_data)
					
	def add_row(self):
		rows = self.rowCount()
		self.setRowCount(self.rowCount() + 1)

	def remove_row(self):
		row = self.currentRow()
		cancel = False
		if row is not None:
			for i in range (0,8):
				data = self.item(row,i)
				if data is not None:
					reply = QMessageBox.question(
							self,
							'Confirm Delete, There is data in this row',
							'Are you sure you want to delete this row?',
							QMessageBox.Yes | QMessageBox.No,
							QMessageBox.No)
					if reply == QMessageBox.Yes:
						i = 9
						cancel = False
					else:
						cancel = True
	
			if cancel == False:
				self.removeRow(row)

	def indent_task(self):
		self.FileOpenProcess = True
		row = self.currentRow()
		print ("Current Row == " + str(row))
		if row != 0:
			currentItemIndent = len(str(self.item(row,2).text())) - len(str(self.item(row,2).text()).lstrip())
			parentrow = self.findParent(row,currentItemIndent)
			parent = str(self.item(parentrow,3).text())
			parentIndent = len(parent) - len(parent.lstrip())
			currentItem = str(self.item(row,3).text()).lstrip()
			print ("Indent Level == " + str(parentIndent+4))
			if currentItemIndent < parentIndent:
				futureIndent = parentIndent +4
			elif currentItemIndent == 0:
				futureIndent = 4
			elif currentItemIndent > parentIndent:
				futureIndent = parentIndent + 4

			for i in range (1,futureIndent):
				currentItem = " " + currentItem
			self.setItem(row, 3, QTableWidgetItem(currentItem))
			self.renumber()
		self.FileOpenProcess = False

	def findParent(self,row,currentItemIndent):
		parentrow = row
		for i in range (row,0, -1):
			parent_indent = len(str(self.item(i,3).text())) - len(str(self.item(i,3).text()).lstrip())
			if parent_indent > currentItemIndent:
				parentrow = i
				print ("Parent Indent = " + str (parent_indent) + "Current Indent ==" + str(currentItemIndent))
				break
		print (parentrow)
		return (parentrow -1)

	def renumber(self):
		rowsNo = int(self.rowCount())
		for i in range (0,rowsNo):
			if i == 0:
				self.setItem(i, 1, QTableWidgetItem("1.0"))
			else:
				#print ("i ====" + str(i))
				#print ("Previous Item Value ====" + self.item(i-1,3).text())
				#print("Previous WBS ID ====" + self.item(i-1,1).text())
				currentText = str(self.item(i,3).text())
				PrevWbsID = float(str(self.item(i-1,1).text()))
				prevIndent =  len(currentText) - len(currentText.lstrip())
				wbsDeapth = int(prevIndent/4)
				#print (wbsDeapth)
				self.setItem(i,1,QTableWidgetItem(str(PrevWbsID +1)))

	def outdent_task(self):
		row = self.currentRow()
		itemName = str(self.item(row,3).text())
		checkforSpaces = itemName[:4]
		print ('Left' + itemName[:4])
		if checkforSpaces.strip() == '':
			newText =itemName[4:]
			self.setItem(row,3,QTableWidgetItem(newText))  
Ejemplo n.º 37
0
class IncomeEventClaster(QDialog):
    def __init__(self, header, IncomeSourceCategory, currency, parent = None):
        QDialog.__init__(self, parent)
        self._acceptState = False
        self._dataContainer = {}
        self._header = header
        self._IncomeSourceCategory = IncomeSourceCategory
        self._Currency = currency
        self.date = [1993,1,22]

        self.InitUI()
        self.addRowWidgets()
        self.show()
#+++++++++++++++++++++++++++ InitUI +++++++++++++++++++++++++++++++++++
    def InitUI(self):
        self.setWindowTitle("მონაცემთა შეტანა")
        self.setWindowIcon(QtGui.QIcon("icon/income.svg"))
        self.setFixedSize(750, 900)
        vbox = QVBoxLayout()
        hbox = QHBoxLayout()
        vbox.setContentsMargins(2, 2, 2, 2)
########################### Calendar ##################################
        self.calendar = QCalendarWidget()
        self.calendar.setGridVisible(True)
        self.calendar.setFirstDayOfWeek(Qt.Monday)
############################ Table ####################################
        self.table = QTableWidget()
        self.table.setRowCount(1)
        self.table.setColumnCount(len(self._header))
        self.table.setHorizontalHeaderLabels(self._header)
        self.table.setSortingEnabled(False)
        self.table.setWordWrap(True)
        self.rowNumb = self.table.rowCount()-1
########################### add Row ###################################
        self.addRowButton = QPushButton('დამატება')
        self.addRowButton.setMaximumWidth(100)
        self.addRowButton.setIcon(QIcon('icon/addRow.svg'))
        self.addRowButton.clicked.connect(self.addRow)
########################### del Row ###################################
        self.delRowButton = QPushButton('წაშლა')
        self.delRowButton.setMaximumWidth(100)
        self.delRowButton.setIcon(QIcon('icon/DelRow.svg'))
        self.delRowButton.clicked.connect(self.delRow)
############################# test ####################################
        self.testButton = QPushButton('ტესტი')
        self.testButton.setIcon(QIcon('icon/test.png'))
        self.testButton.clicked.connect(self.test)
############################ Accept ###################################
        self.acceptButton = QPushButton('დადასტურება', self)
        self.acceptButton.clicked.connect(self.acceptDialog)
############################ Reject ###################################
        self.rejectButton = QPushButton('გაუქმება', self)
        self.rejectButton.clicked.connect(self.rejectDialog)
#################### Add widgets on layouts ###########################
        hbox.addWidget(self.addRowButton)
        hbox.addWidget(self.delRowButton)

        vbox.addWidget(self.calendar,5)
        vbox.addWidget(self.table,90)
        vbox.addLayout(hbox)
        vbox.addWidget(self.testButton,5)
        hboxAcceptReject = QHBoxLayout()
        hboxAcceptReject.addWidget(self.acceptButton)
        hboxAcceptReject.addWidget(self.rejectButton)
        vbox.addLayout(hboxAcceptReject)
        self.setLayout(vbox)
#++++++++++++++++++++++++++ Add Row +++++++++++++++++++++++++++++++++++
    def addRow(self):
        self.rowNumb = self.table.rowCount()
        self.table.insertRow(self.rowNumb)
        self.addRowWidgets()
#++++++++++++++++++++++ Add Row Widgets +++++++++++++++++++++++++++++++
    def addRowWidgets(self):
########################## emountEdit #################################
        quantityEdit = QLineEdit('')
        quantityEdit.setValidator(QDoubleValidator())
###################### Currency Selector ##############################
        CurrencySelector = QComboBox()
        for idx, key in enumerate(self._Currency):
            CurrencySelector.addItem(key)
            CurrencySelector.setItemData(idx, Qt.AlignCenter, Qt.TextAlignmentRole)
            CurrencySelector.setItemIcon(idx, QtGui.QIcon(self._Currency[key]))

        quantityEditHlayout = QHBoxLayout()
        quantityEditHlayout.addWidget(quantityEdit,50)
        quantityEditHlayout.addWidget(CurrencySelector,50)

        quantityEditWidgets = QWidget()
        quantityEditWidgets.setLayout(quantityEditHlayout)
################## Income Category Selector ###########################
        incomeCategorySelector = QComboBox()
        incomeCategorySelector.addItems(self._IncomeSourceCategory)

        self.table.setCellWidget(self.rowNumb, 0, incomeCategorySelector)
        self.table.setCellWidget(self.rowNumb, 1, quantityEditWidgets)
        self.table.cellWidget(self.rowNumb,0).activated.connect(self.incomeCategoryFormater)
################### Set Table Cell Widths #############################
        self.table.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
# +++++++++++++ String to float number formater +++++++++++++++++++++++
    def _stingToFloatFormater(self, value):
        if ',' in value:
            value = value.replace(",", ".")
            return value
        else:
            return value
#++++++++++++++++++++++++ Delete Row ++++++++++++++++++++++++++++++++++
    def delRow(self):
        self.rowNumb = self.table.rowCount()
        if self.rowNumb > 1:
            selected_Row = self.table.currentRow()
            self.table.removeRow(selected_Row)
        self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
#+++++++++++++++++++++ Set calendar date ++++++++++++++++++++++++++++++
    def setCalendarDate(self, date):
        self.calendar.setSelectedDate(QDate(date[0], date[1], date[2]))
#+++++++++++++++++++++ Make data claster ++++++++++++++++++++++++++++++
    def makeDataClaster(self):
        self._dataContainer = {}
        dataContainerArray = []
        self.rowNumb = self.table.rowCount()
        self.colNumb = self.table.columnCount()
        for row in range(self.rowNumb):
            dataContainerTemp = []
            for column in range(self.colNumb):
                if column == 0:
                    dataContainerTemp.append({'cell_0'   : self.table.cellWidget(row,column).currentIndex()})
                elif column == 1:
                    if len(self.table.cellWidget(row, 1).children()[0]) == 2:
                        dataContainerTemp.append({'cell_1.1' : self.table.cellWidget(row,column).children()[1].text(),
                                                  'cell_1.2' : self.table.cellWidget(row,column).children()[2].currentIndex()})
                    elif len(self.table.cellWidget(row, 1).children()[0]) == 4:
                        dataContainerTemp.append({'cell_1.1' : self._stingToFloatFormater(self.table.cellWidget(row,column).children()[1].text()),
                                                  'cell_1.2' : self.table.cellWidget(row,column).children()[2].currentIndex(),
                                                  'cell_1.3' : self._stingToFloatFormater(self.table.cellWidget(row,column).children()[3].text()),
                                                  'cell_1.4' : self.table.cellWidget(row,column).children()[4].currentIndex()})
            dataContainerArray.append(dataContainerTemp)
        self._dataContainer.update({self.calendar.selectedDate().toString("dd.MM.yyyy") : dataContainerArray})
#+++++++++++++++++++++ Edit data claster ++++++++++++++++++++++++++++++
    def EditDataClaster(self, DataClasterComponent, timeStamp):
        for _ in range(len(DataClasterComponent)-1):
            self.addRow()
        self.setCalendarDate(QDate.fromString(timeStamp, 'dd.MM.yyyy').getDate())
        
        for row, rowData in enumerate(DataClasterComponent):
            self.table.cellWidget(row, 0).setCurrentIndex(rowData[0]['cell_0'])
            self.table.cellWidget(row, 1).children()[1].setText(rowData[1]['cell_1.1'])
            self.table.cellWidget(row, 1).children()[2].setCurrentIndex(rowData[1]['cell_1.2'])
        
            if len(rowData[1]) == 4:
                quantityEdit = QLineEdit('')
                quantityEdit.setValidator(QDoubleValidator())
                CurrencySelector = QComboBox()
                for idx, key in enumerate(self._Currency):
                    CurrencySelector.addItem(key)
                    CurrencySelector.setItemData(idx, Qt.AlignCenter, Qt.TextAlignmentRole)
                    CurrencySelector.setItemIcon(idx, QtGui.QIcon(self._Currency[key]))

                self.table.cellWidget(row, 1).children()[0].addWidget(quantityEdit,50)
                self.table.cellWidget(row, 1).children()[0].addWidget(CurrencySelector,50)

                self.table.cellWidget(row, 1).children()[3].setText(rowData[1]['cell_1.3'])
                self.table.cellWidget(row, 1).children()[4].setCurrentIndex(rowData[1]['cell_1.4'])
        self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
#++++++++++++++++++++++++++ Accept ++++++++++++++++++++++++++++++++++++
    def acceptDialog(self):
        self.makeDataClaster()
        self._acceptState = True
        self.close()
#++++++++++++++++++++++++++ Reject ++++++++++++++++++++++++++++++++++++
    def rejectDialog(self):
        self._acceptState = False
        self.close()
#++++++++++++++++++ Get data claster part +++++++++++++++++++++++++++++
    def getDataClasterPart(self):
        return self._dataContainer, self._acceptState
#++++++++++++++++++ incomeCategoryFormater ++++++++++++++++++++++++++++
    def incomeCategoryFormater(self):
        changedSelectrorIndex = self.sender()
        self.rowNumb = self.table.rowCount()
        for  row in range (self.rowNumb):
            if self.table.cellWidget(row,0) == changedSelectrorIndex:
                if self.table.cellWidget(row,0).currentIndex() == 7:
                    if len(self.table.cellWidget(row, 1).children()[0]) == 2:
                        quantityEdit = QLineEdit('')
                        quantityEdit.setValidator(QDoubleValidator())
                        CurrencySelector = QComboBox()
                        for idx, key in enumerate(self._Currency):
                            CurrencySelector.addItem(key)
                            CurrencySelector.setItemData(idx, Qt.AlignCenter, Qt.TextAlignmentRole)
                            CurrencySelector.setItemIcon(idx, QtGui.QIcon(self._Currency[key]))

                        self.table.cellWidget(row, 1).children()[0].addWidget(quantityEdit,50)
                        self.table.cellWidget(row, 1).children()[0].addWidget(CurrencySelector,50)
                else:
                    try:
                        self.table.cellWidget(row, 1).children()[0].itemAt(2).widget().deleteLater()
                        self.table.cellWidget(row, 1).children()[0].itemAt(3).widget().deleteLater()
                    except AttributeError:
                        pass
        self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
    def read(self):
        return self._dataContainer
#+++++++++++++++++++++++++++ Test +++++++++++++++++++++++++++++++++++++
    def test(self):
        print("Test")
        self.makeDataClaster()
Ejemplo n.º 38
0
 def addCalendar(self):
     cal = QCalendarWidget(self)
     cal.setGridVisible(True)
     cal.clicked.connect(self.timeSelected)
     cal.move(300, 20)
class VistaAggiungiOrari(
        QWidget
):  # Apre la vista che consente di aggiungere un oraario per le prenotazioni.
    def __init__(self, tipo):
        super(VistaAggiungiOrari, self).__init__()
        self.tipo = tipo
        self.controller = ControllerListaPrenotazioni()

        self.stylesheet_frame = """
                           QFrame{
                               background-color: white;
                               border: 1px solid grey;
                           }
                       """

        self.stylesheet_window = """
                           QWidget{
                               background-color: #efefef;
                           }
                       """

        self.stylesheet_label = """
                           QLabel{
                               background-color: transparent;
                           }

                           QLineEdit{
                               background-color: white;
                               border: 2px solid #dfdfdf
                           }

                           QComboBox{
                               background-color: white;
                               border: 1px solid grey;
                               color: black;
                           }

                       """

        self.stylesheet_button_back = """
                           QPushButton{
                               border-radius: 15px;
                               background-color: transparent;
                           }

                           QPushButton::Pressed{
                               background-color: transparent;
                           }        
                       """

        self.stylesheet_button = """
                           QPushButton{
                               background-color: #cc3234;
                               color: white;
                               border-radius: 15px;
                           }

                           QPushButton::Pressed{
                               background-color: grey
                           }        
                       """

        self.stylesheet_calendar = """
                            QCalendarWidget QToolButton{
                                background-color : lightblue;
                            }
                            QCalendarWidget QWidget{
                                background-color : lightblue;
                            }
                """

        # Inserimento e impostazioni grafiche dell'immagine dello sfondo della finestra.
        self.imagePath = "Image/foto.png"
        self.image = QImage(self.imagePath)
        self.label = QLabel(self)
        self.label.setPixmap(QPixmap.fromImage(self.image))
        self.label.setScaledContents(True)
        self.label.setGeometry(0, 0, 1050, 600)

        # Inserimento e impostazioni grafiche dell'etichetta 'Nuovo Orario'.
        self.label = QLabel(self)
        self.font = QFont("Arial", 18, QFont.Bold)
        self.label.setText("Nuovo Orario")
        self.label.setFont(self.font)
        self.label.setStyleSheet(self.stylesheet_label)
        self.label.setGeometry(50, 55, 250, 40)

        # Inserimento e impostazioni grafiche del frame nella finestra.
        self.frame = QFrame(self)
        self.frame.setStyleSheet(self.stylesheet_frame)
        self.frame.setGeometry(50, 100, 950, 330)

        # Usa la funzione 'create_label' per creare un etichetta.
        self.create_label("Tipo", 150)

        # Inserimento e impostazioni grafiche del menù a tendina per scegliere l'orario di un nuovo servizio.
        self.edit_tipo = QComboBox(self)
        self.edit_tipo.addItem("Lezione")
        self.edit_tipo.addItem("Esame teorico")
        self.edit_tipo.addItem("Lezione guida")
        self.edit_tipo.addItem("Esame pratico")
        self.edit_tipo.setGeometry(250, 150, 200, 30)
        self.edit_tipo.setStyleSheet(self.stylesheet_label)

        # Inserimento e impostazioni grafiche dell'etichetta 'Data'.
        self.label_data = QLabel(self)
        self.label_data.setText("Data")
        self.label_data.setGeometry(500, 150, 100, 20)
        self.label_data.setStyleSheet(self.stylesheet_label)
        self.font_label = QFont("Times", 9)
        self.label_data.setFont(self.font_label)

        # Inserimento e impostazioni grafiche del calendario.
        self.calendar = QCalendarWidget(self)
        self.calendar.setGridVisible(True)
        self.calendar.setStyleSheet(self.stylesheet_calendar)
        self.calendar.setGeometry(575, 150, 350, 250)

        # Inserimento e impostazioni grafiche del bottone per tornare alla vista precedente.
        self.button_back = QPushButton(self)
        self.button_back.setIcon(QIcon('Image/back.png'))
        self.button_back.setIconSize(QSize(90, 90))
        self.button_back.setGeometry(50, 470, 90, 90)
        self.button_back.setStyleSheet(self.stylesheet_button_back)
        self.button_back.clicked.connect(self.go_back)

        # Inserimento e impostazioni grafiche per il bottone che permette di effettuare l'aggiunta dell'orario.
        self.button_prenota = QPushButton(self)
        self.button_prenota.setText("Aggiungi orario")
        self.font_button = QFont("Times", 11)
        self.button_prenota.setFont(self.font_button)
        self.button_prenota.setGeometry(750, 490, 200, 50)
        self.button_prenota.setStyleSheet(self.stylesheet_button)
        self.button_prenota.clicked.connect(self.go_aggiungi_orario)

        # Impostazioni grafiche generali della finestra del programma.
        self.setWindowTitle("Nuovo Orario")
        self.setStyleSheet(self.stylesheet_window)
        self.resize(1050, 600)
        self.setFixedSize(self.size())

    # == create_label ==
    # La funzione crea un etichetta con nome inserito in input alla funzione e posizione nella finestra
    # presa anch'essa in input. La funzione gestisce anche le impostazioni grafiche dell'etichetta.
    def create_label(self, nome, posizione):
        self.label_edit = QLabel(self)
        self.label_edit.setText(nome)
        self.label_edit.setGeometry(80, posizione, 110, 20)
        self.label_edit.setStyleSheet(self.stylesheet_label)
        self.font_label1 = QFont("Times", 9)
        self.label_edit.setFont(self.font_label1)

    # == go_back ==
    # La funzione si occupa di aprire la finestra precedente.
    def go_back(self):
        self.vista_home = VistaListaPrenotazioni.VistaListaPrenotazioni(
            self.tipo)
        self.vista_home.show()
        self.close()

    # == go_aggiungi_orario ==
    # La funzione aggiunge l'orario inserito alla lista delle prenotazioni, invia un messaggio di conferma
    # all'utente e reindirizza l'utente alla VistaListaPrenotazioni.
    def go_aggiungi_orario(self):
        trovato = False
        for orario in self.controller.get_lista_prenotazioni():
            self.controller_prenotazione = ControllerPrenotazione(orario)
            if self.calendar.selectedDate().toString("dd-MM") == self.controller_prenotazione.get_data() and \
                    self.edit_tipo.currentText() == self.controller_prenotazione.get_tipo():
                trovato = True
                QMessageBox.information(self, "Errore",
                                        "Orario già presente nel sistema",
                                        QMessageBox.Ok)
        if not trovato:
            self.controller.aggiungi_prenotazione(
                Prenotazione(self.edit_tipo.currentText(),
                             self.calendar.selectedDate().toString("dd-MM")))
            QMessageBox.information(self, "Confermato",
                                    "Orario aggiunto nel sistema",
                                    QMessageBox.Ok)
        self.go_lista_visite = VistaListaPrenotazioni.VistaListaPrenotazioni(
            self.tipo)
        self.go_lista_visite.show()
        self.close()