class Date(QWidget): def __init__(self): super(Date, self).__init__() self.calendar = QCalendarWidget(self) self.calendar.setMinimumDate(QDate(1946, 2, 14)) # 2 self.calendar.setMaximumDate(QDate(6666, 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 print(self.calendar.minimumDate()) # 7 print(self.calendar.maximumDate()) print(self.calendar.selectedDate()) self.label = QLabel(self) # 8 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])
class WindowClass(QWidget): def __init__(self, parent=None): super(WindowClass, self).__init__(parent) self.btn = QPushButton(self) #self参数则让该按钮显示当前窗体中 self.btn.setText("选择日期") self.btn.move(0, 0) self.btn.clicked.connect(self.openCalendar) self.le = QLabel(self) self.cal = QCalendarWidget(self) self.cal.setMinimumDate(QDate(2017, 1, 1)) #设置日期最小范围 self.cal.setMaximumDate(QDate(2019, 12, 30)) #设置日期最大范围 self.cal.setGridVisible(True) #是否显示日期之间的网格 self.cal.move(5, 30) self.cal.hide() #隐藏日期控件 self.cal.clicked[QDate].connect( self.showDate) #clicked[参数],即定义showDate是传入的参数类型设置 date = self.cal.selectedDate() #获取选中日期,默认当前系统时间 self.le.setText(date.toString('yyyy-MM-dd dddd')) self.le.move(100, 8) self.setGeometry(100, 100, 400, 350) #设置当前窗体位置和大小 self.setWindowTitle("日历控件使用") def showDate(self, date): self.le.setText(date.toString("yyyy-MM-dd dddd")) self.cal.close() #关闭日期控件 def openCalendar(self): self.cal.show() #显示日期控件
def home(self): """ Home page of the App. """ # Create and display calendar object. calendar = QCalendarWidget(self) calendar.setGridVisible(True) calendar.move(20, 50) calendar.resize(320, 200) calendar.setMinimumDate(QtCore.QDate(1995, 6, 16)) calendar.setMaximumDate(QtCore.QDate.currentDate()) calendar.clicked[QtCore.QDate].connect(self.get_apod_date) # Get date selected by calendar object and change date to desired # format. (YYMMDD) date = calendar.selectedDate() a_date = [int(str(date.year())[2:]), date.month(), date.day()] self.astro_date = ''.join(list(map(str, a_date))) # Create "See Picture" button. Connect it to get_picture function. see_button = QPushButton("See Picture", self) see_button.move(20, 280) see_button.clicked.connect(self.get_picture) # Display all objects in the window. self.show()
class CalendarDemo(QWidget): global currentYear, currentMonth currentYear = datetime.now().year currentMonth = datetime.now().month def __init__(self): super().__init__() self.setWindowTitle("Calendar PyQt5 & Python") self.setGeometry(300, 300, 450, 300) self.initUI() def initUI(self): 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.printDateInfo) def printDateInfo(self, qDate): print("{0}/{1}/{2}".format(qDate.month(), qDate.day(), qDate.year())) print("Day Number of the year: {}".format(qDate.dayOfYear())) print("Day Number of the week: {}".format(qDate.dayOfWeek()))
def Calendar(self, x, y, h, w): cal = QCalendarWidget(self) cal.setMinimumDate(QDate(1988, 1, 1)) cal.setMaximumDate(QDate(2088, 1, 1)) cal.setGridVisible(True) cal.move(x, y) cal.resize(w, h) return cal
class VistaListaPrenotazioni(QWidget): def __init__(self, parent=None): super(VistaListaPrenotazioni, self).__init__(parent) self.g_layout = QGridLayout() self.label_prenotazioni_by_data = QLabel("\nSeleziona una data, poi premi 'Vai' per vedere gli arrivi alla data selezionata: \n") self.label_prenotazioni_by_data.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.g_layout.addWidget(self.label_prenotazioni_by_data, 0, 0) self.calendario = QCalendarWidget() self.calendario.setGridVisible(True) self.calendario.setVerticalHeaderFormat(QCalendarWidget.NoVerticalHeader) self.calendario.setMinimumDate(QDate(2021, 6, 1)) self.calendario.setMaximumDate(QDate(2021, 9, 15)) self.g_layout.addWidget(self.calendario, 1, 0) self.h_layout = QHBoxLayout() self.create_button("Mostra tutte", self.go_lista_prenotazioni, "background-color:#FFD800;") self.create_button("Vai", self.go_lista_prenotazioni_by_data, "background-color:#00FF00;") self.g_layout.addLayout(self.h_layout, 2, 0) self.setLayout(self.g_layout) self.resize(700, 600) self.setWindowTitle("Lista Prenotazioni") #Crea un bottone con i parametri passati e lo aggiunge al layout orizzontale dei bottoni def create_button(self, testo, comando, background_color): bottone = QPushButton(testo) bottone.setFont(QFont("Arial", 15, 1, True)) bottone.setStyleSheet(background_color) bottone.clicked.connect(comando) self.h_layout.addWidget(bottone) #Visualizza la lista delle prenotazioni che iniziano nella data selezionata nel calendario def go_lista_prenotazioni_by_data(self): data_inizio_q = self.calendario.selectedDate() self.data_inizio = datetime(data_inizio_q.year(), data_inizio_q.month(), data_inizio_q.day()) self.lista_prenotazioni_by_data = VistaListaPrenotazioniAdmin(self.data_inizio) self.lista_prenotazioni_by_data.show() #Visualizza la lista completa delle prenotazioni def go_lista_prenotazioni(self): self.lista_prenotazioni = VistaListaPrenotazioniAdmin() self.lista_prenotazioni.show()
class WindowCal(QWidget): def __init__(self): super().__init__() self.create_calendar() layout = QVBoxLayout() layout.addWidget(self.calendar) self.setLayout(layout) self.setWindowTitle("Calendar") def create_calendar(self): self.calendar = QCalendarWidget() self.calendar.setMinimumDate(QDate(1900, 1, 1)) self.calendar.setMaximumDate(QDate(3000, 1, 1)) self.calendar.setGridVisible(True)
class Calendar(QDialog): currentDay = datetime.now().day currentMonth = datetime.now().month currentYear = datetime.now().year def __init__(self): super().__init__() self.setWindowTitle('Calendar') self.setGeometry(300, 300, 300, 300) self.initUI() def initUI(self): self.layout = QVBoxLayout() self.calendar = QCalendarWidget(self) self.calendar.setGridVisible(True) self.calendar.setMinimumDate( QDate(self.currentYear - 123, self.currentMonth, 1)) self.calendar.setMaximumDate( QDate(self.currentYear, self.currentMonth, self.currentDay)) self.calendar.setSelectedDate( QDate(self.currentYear, self.currentMonth, self.currentDay)) self.setDate(self.calendar.selectedDate()) self.calendar.clicked.connect(self.setDate) self.exit_button = QPushButton(text="Save", parent=self) self.exit_button.clicked.connect(self.close) self.layout.addWidget(self.calendar) self.layout.addWidget(self.exit_button) self.setLayout(self.layout) def printDateInfo(self, qDate): print('{0}/{1}/{2}'.format(qDate.day(), qDate.month(), qDate.year())) print(f'Day Number of the year: {qDate.dayOfYear()}') print(f'Day Number of the week: {qDate.dayOfWeek()}') def setDate(self, qDate): self.selectedDate = '{0} {1} {2}'.format( qDate.day(), qDate.longMonthName(qDate.month())[:3].capitalize(), qDate.year()) def getDate(self): return self.selectedDate
def on_date_edit_clicked(): dlg = QDialog(self.window) dlg.setWindowTitle(popup_title) layout = QVBoxLayout() cal = QCalendarWidget() cal.setMaximumDate(QDate(max_date)) cal.setSelectedDate(QDate(getattr(self.args, name))) cal.selectionChanged.connect(lambda: dlg.accept()) layout.addWidget(cal) okay = QPushButton('Select') okay.clicked.connect(lambda: dlg.accept()) layout.addWidget(okay) dlg.setLayout(layout) dlg.exec() setattr(self.args, name, cal.selectedDate().toPyDate()) date_edit.setText(str(getattr(self.args, name)))
def init_calendario(self): calendario = QCalendarWidget(self) currentMonth = datetime.now().month currentYear = datetime.now().year calendario.setMinimumDate(QDate(currentYear, currentMonth, 1)) calendario.setMaximumDate( QDate(currentYear + 1, currentMonth, calendar.monthrange(currentYear, currentMonth)[1])) calendario.setSelectedDate(QDate(currentYear, currentMonth, 1)) calendario.setFont(QFont('Georgia', 10)) calendario.setStyleSheet('background-color: lightblue') calendario.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) calendario.setGeometry(200, 200, 300, 200) calendario.setGridVisible(True) return calendario
class CalendarDemo(QWidget): global currentYear, currentMonth, final_date currentMonth = datetime.now().month currentYear = datetime.now().year final_date = '{0}-{1}-{2}'.format(datetime.now().day, datetime.now().month, datetime.now().year) def __init__(self): super().__init__() self.setWindowTitle('Calendario') self.setGeometry(300, 300, 680, 460) self.initUI() def initUI(self): self.calendar = QCalendarWidget(self) self.calendar.setGeometry(20, 20, 630, 410) self.calendar.setGridVisible(True) self.button = QPushButton('Confirmar') self.calendar.layout().addWidget(self.button) self.calendar.setMinimumDate(QDate(currentYear - 10, currentMonth, 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.printDateInfo) self.button.clicked.connect(self.on_button_clicked) def printDateInfo(self, qDate): self.final_date = '{0}-{1}-{2}'.format(qDate.day(), qDate.month(), qDate.year()) # print(self.final_date) # print(f'Day Number of the year: {qDate.dayOfYear()}') # print(f'Day Number of the week: {qDate.dayOfWeek()}') def on_button_clicked(self): # print(self.final_date) PullData.main(self.final_date) alert = QMessageBox() alert.setText('Baixando processos') alert.exec_()
class Demo(QWidget): def __init__(self): super(Demo, self).__init__() self.calendar = QCalendarWidget(self) # 通过setMinimumDate()和 # setMaximumDate()可以设置日历的最小和最大日期 # (可用setDateRange()替代),传入的参数为QDate。 self.calendar.setMinimumDate(QDate(1946, 2, 14)) # 2 self.calendar.setMaximumDate(QDate(6666, 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 # setGridVisible(bool)方法可以设置是否在日历上显示网格; self.calendar.setGridVisible(True) # 6 # 当点击到日历上的某个日期时,clicked信号就会被触发 self.calendar.clicked.connect(self.show_emotion_func) # 6 self.calendar.setFirstDayOfWeek(Qt.Sunday) print(self.calendar.minimumDate()) # 7 print(self.calendar.maximumDate()) print(self.calendar.selectedDate()) self.label = QLabel(self) # 8 self.label.setAlignment(Qt.AlignCenter) # setSelectedDate()方法可以设置日历初始化时所显示的日期 # ,如果不设置,则默认是当天日期; 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 __init__(self, tableData, *args): QTableWidget.__init__(self, *args) #Table widget specifications. self.tableData = tableData self.setData() self.resizeColumnsToContents() self.resizeRowsToContents() self.setWindowTitle("Premier league table") #Window specifications. self.top = 100 self.left = 100 self.width = 880 self.height = 490 self.setGeometry(self.top, self.left, self.width, self.height) #Instructions specifications. instructionLabel = QLabel(self) instructionLabel.move(450, 40) instructionLabel.setText(''' Instructions: Select an available date from the calendar to display a table of Premier League results determined only from the selected date until present.''') #Date picker specifications. cal = QCalendarWidget(self) cal.setGridVisible(True) cal.move(500, 140) #Limiting date picker to dates from the beginning of the current season to now. max_date = QDate.fromString( datetime.datetime.now().strftime("%Y-%m-%d"), 'yyyy-MM-dd') min_date = QDate.fromString(currentLeagueStartDate, 'yyyy-MM-dd') cal.setMaximumDate(max_date) cal.setMinimumDate(min_date) #Changing data displayed in table to reflect information only from the selected date. cal.clicked[QDate].connect( lambda: self.changeData(cal.selectedDate().toString("yyyy-MM-dd")))
class CalendarDemo(QWidget): """主窗口""" def __init__(self, parent=None): super().__init__(parent=parent) self.calendar = QCalendarWidget(parent=self) self.calendar.setMinimumDate(QDate(1980, 1, 1)) # 设置最小日期 self.calendar.setMaximumDate(QDate(3000, 1, 1)) # 设置最大日期 self.calendar.setGridVisible(True) # 设置网格可见 self.calendar.move(20, 20) self.calendar.clicked.connect(self.show_date) # 单击时会将点击到的QDate传递给槽函数 self.label = QLabel(parent=self) date = self.calendar.selectedDate() self.label.setText(date.toString("yyyy-MM-dd dddd")) self.label.move(20, 300) self.setGeometry(100, 100, 460, 360) self.setWindowTitle("QCalendarWidget 使用") def show_date(self, date): self.label.setText(date.toString("yyyy-MM-dd dddd"))
class MainWin(QWidget): def __init__(self, parent=None): super(MainWin, self).__init__(parent) self.cal = QCalendarWidget(self) self.cal.setMinimumDate(QDate(1980, 1, 1)) self.cal.setMaximumDate(QDate(3000, 1, 1)) self.cal.setGridVisible(True) self.cal.move(20, 20) self.cal.clicked[QDate].connect(self.showDate) self.lb = QLabel(self) date = self.cal.selectedDate() self.lb.setText(date.toString('yyyy-MM-dd dddd')) self.lb.move(20, 300) self.setGeometry(100, 100, 600, 350) self.setWindowTitle('Calendar') def showDate(self, date): self.lb.setText(date.toString('yyyy-MM-dd dddd'))
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'))
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")))
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.')
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
class CurrencyConverter(QDialog): def __init__(self, parent=None): super().__init__(parent) # initialize variables and download / parse the data file self.data = {} self.last_date = QDate().currentDate() self.currencies = [] self.period = [] self.download_unzip() # initialize widgets self.from_currency_label = QLabel("From currency:") self.from_currency = QComboBox() self.from_currency.addItems(self.currencies) self.to_currency_label = QLabel("To currency:") self.to_currency = QComboBox() self.to_currency.addItems(self.currencies) self.from_amount_label = QLabel("Amount to convert:") self.from_amount = QDoubleSpinBox() self.from_amount.setRange(0.01, 100000000.00) self.from_amount.setValue(1.00) self.to_amount_label = QLabel( "Result of conversion based on most recent rates: ") self.to_amount = QLabel("%.02f" % 1.00) self.from_date = QCalendarWidget() self.to_date = QCalendarWidget() self.rates_plot = pg.PlotWidget() self.legend = self.rates_plot.addLegend() # set widgets into layout grid = QGridLayout() grid.addWidget(self.from_currency_label, 0, 0) grid.addWidget(self.from_currency, 0, 1) grid.addWidget(self.to_currency_label, 0, 2) grid.addWidget(self.to_currency, 0, 3) grid.addWidget(self.from_amount_label, 1, 0) grid.addWidget(self.from_amount, 1, 1) grid.addWidget(self.to_amount_label, 1, 2) grid.addWidget(self.to_amount, 1, 3) grid.addWidget(self.from_date, 2, 0, 1, 2) grid.addWidget(self.to_date, 2, 2, 1, 2) grid.addWidget(self.rates_plot, 4, 0, 1, 4) self.setLayout(grid) self.setWindowTitle( "Currency Converter - Assignment 1 - Dommerc - 2982021") # refresh data today = QDate.currentDate() self.from_date.setSelectedDate(today.addDays(-10)) self.update_ui() # set event when input change (refresh ui) self.from_currency.currentIndexChanged.connect(self.update_ui) self.to_currency.currentIndexChanged.connect(self.update_ui) self.from_amount.valueChanged.connect(self.update_ui) self.from_date.selectionChanged.connect(self.update_ui) self.to_date.selectionChanged.connect(self.update_ui) # Method that return the 1st valid date by subtraction or addition one day def get_valid_date(self, date, sign): tmp = date while tmp not in self.data["USD"]: if sign == '+': tmp = tmp.addDays(+1) else: tmp = tmp.addDays(-1) return tmp # Method that set the period according to the two selected dates def set_period(self, from_date, to_date): tmp = from_date to_date = self.get_valid_date(to_date, '-') self.period.clear() while tmp <= to_date: tmp = self.get_valid_date(tmp, '+') if tmp <= to_date: self.period.append(tmp) tmp = tmp.addDays(+1) # Method that return rates according to the period and a currency def get_rates(self, currency): rates = [] for date in self.period: rates.append(self.data[currency][date]) return rates # Method that return conversion rates according to the rates of the two selected currencies @staticmethod def get_conversion_rates(rates_from, rates_to): rates_cv = [] i = 0 while i < len(rates_from): if rates_from[i] == 0 or rates_to[i] == 0: rates_cv.append(0) else: rates_cv.append(rates_to[i] / rates_from[i]) i += 1 return rates_cv # Refresh all data displayed in the window def update_ui(self): try: # set maximum and minimum date for the two date picker self.to_date.setMaximumDate(QDate.currentDate()) self.to_date.setMinimumDate(self.from_date.selectedDate()) self.from_date.setMaximumDate(self.to_date.selectedDate()) self.from_date.setMinimumDate(self.last_date) # compute the conversion value date = self.get_valid_date(QDate.currentDate(), '-') from_cur = self.from_currency.currentText() to_cur = self.to_currency.currentText() from_rate = self.data[from_cur][date] to_rate = self.data[to_cur][date] amount = self.from_amount.value() if from_rate > 0 and to_rate > 0: res = (to_rate / from_rate) * amount self.to_amount.setText("%.02f" % res) else: self.to_amount.setText("no data") # set period and get rates from_date = self.from_date.selectedDate() to_date = self.to_date.selectedDate() self.set_period(from_date, to_date) rates_from = self.get_rates(from_cur) rates_to = self.get_rates(to_cur) rates_cv = self.get_conversion_rates(rates_from, rates_to) # clear plots and legend self.rates_plot.clear() self.legend.scene().removeItem(self.legend) self.legend = self.rates_plot.addLegend() if len(self.period) == 0: return # set labels and ranges self.rates_plot.setLabel('left', 'Rate') self.rates_plot.setLabel('bottom', 'Days') date_range = range(0, len(self.period)) self.rates_plot.setXRange(0, len(self.period) - 1) min_ = min(min(rates_from), min(rates_to), min(rates_cv)) max_ = max(max(rates_from), max(rates_to), max(rates_cv)) self.rates_plot.setYRange(min_, max_) # set plots self.rates_plot.plot(date_range, rates_from, pen='b', symbol='o', symbolPen='b', symbolBrush=0.2, name=from_cur) self.rates_plot.plot(date_range, rates_to, pen='g', symbol='x', symbolPen='g', symbolBrush=0.2, name=to_cur) self.rates_plot.plot(date_range, rates_cv, pen="r", symbol='+', symbolPen='r', symbolBrush=0.2, name="conversion rate") except Exception as e: print(e) # Method that download data file and proceed to parsing def download_unzip(self): # download the file url = 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist.zip' raw, _ = urlretrieve(url) zip_file_object = zipfile.ZipFile(raw, 'r') first_file = zip_file_object.namelist()[0] file = zip_file_object.open(first_file) content = file.read() # parsing the file lines = content.decode().split("\n") print(len(lines)) # get the last date of the file last_line = lines[len(lines) - 1] array = last_line.split(",") array = array[0].split("-") self.last_date = QDate(int(array[0]), int(array[1]), int(array[2])) # get all available currencies self.currencies = lines[0].split(",") self.currencies.pop(0) self.currencies.pop(len(self.currencies) - 1) for cur in self.currencies: self.data[cur] = {} lines.pop(0) # get value of each currency for each date for line in lines: items = line.split(",") array = items[0].split("-") date = QDate(int(array[0]), int(array[1]), int(array[2])) items.pop(0) items.pop(len(items) - 1) for idx, item in enumerate(items): if item == "N/A": self.data[self.currencies[idx]][date] = 0.0000 else: self.data[self.currencies[idx]][date] = float(item)
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)
class Daily_Report_Page(QDialog,Ui_daily_report): def __init__(self,parent=None): super(Daily_Report_Page,self).__init__(parent) self.setupUi(self) self.setWindowTitle("Daily Bill Report") self.table_records() self.from_cal_tool_btn.clicked.connect(self.from_calender) self.to_cal_tool_btn.clicked.connect(self.to_calender) self.current_date() #self.table_population() self.show_btn.clicked.connect(self.table_population) self.export_btn.clicked.connect(self.exportbtn) self.close_btn.clicked.connect(self.closebtn) config_name = 'daily_report.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)) excel_image = os.path.join(application_path, "images", "excel.png") close_image = os.path.join(application_path, "images", "close.png") show_image = os.path.join(application_path, "images", "search.png") self.export_btn.setIcon(QtGui.QIcon(excel_image)) self.export_btn.setIconSize(QtCore.QSize(30, 30)) self.close_btn.setIcon(QtGui.QIcon(close_image)) self.close_btn.setIconSize(QtCore.QSize(30, 30)) self.show_btn.setIcon(QtGui.QIcon(show_image)) self.show_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.daily_table.setRowCount(0) self.daily_table.verticalHeader().setVisible(False) header = self.daily_table.horizontalHeader() header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents) header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents) header.setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch) header.setSectionResizeMode(3, QtWidgets.QHeaderView.Stretch) header.setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch) header.setSectionResizeMode(5, QtWidgets.QHeaderView.Stretch) header.setSectionResizeMode(6, QtWidgets.QHeaderView.Stretch) header.setSectionResizeMode(7, QtWidgets.QHeaderView.Stretch) header.setSectionResizeMode(8, QtWidgets.QHeaderView.Stretch) header.setSectionResizeMode(9, QtWidgets.QHeaderView.Stretch) header.setSectionResizeMode(10, QtWidgets.QHeaderView.Stretch) header.setSectionResizeMode(11, QtWidgets.QHeaderView.ResizeToContents) header.setStyleSheet("QHeaderView::section { border: 1px solid ;}") def from_calender(self): self.from_calender = QCalendarWidget() self.from_calender.setMinimumDate(QDate(1900,1,1)) self.from_calender.setMaximumDate(QDate(2999,12,31)) self.from_calender.setGridVisible(True) self.from_calender.clicked.connect(self.from_updatedate) self.from_calender.setWindowModality(Qt.ApplicationModal) self.from_calender.setWindowTitle("From Date") self.from_calender.show() def to_calender(self): self.to_calender = QCalendarWidget() self.to_calender.setMinimumDate(QDate(1900,1,1)) self.to_calender.setMaximumDate(QDate(2999,12,31)) self.to_calender.setGridVisible(True) self.to_calender.clicked.connect(self.to_updatedate) self.to_calender.setWindowModality(Qt.ApplicationModal) self.to_calender.setWindowTitle("To Date") self.to_calender.show() def from_updatedate(self,*args): getdate = self.from_calender.selectedDate().toString("dd-MMM-yyyy") print('From date value is ',getdate) self.from_date.setText(getdate) self.from_calender.deleteLater() def to_updatedate(self,*args): getdate = self.to_calender.selectedDate().toString("dd-MMM-yyyy") print('to date value is ',getdate) self.to_date.setText(getdate) self.to_calender.deleteLater() def current_date(self): now = QDate.currentDate() print(now) print(now.toString(Qt.ISODate)) today = datetime.date.today() date_format = today.strftime("%d-%b-%Y") print(date_format) self.from_date.setText(date_format) self.to_date.setText(date_format) def table_population(self): self.connectdb() self.daily_table.setRowCount(0) from_date = self.from_date.text() from_date =datetime.datetime.strptime(from_date,'%d-%b-%Y').date() self.table_from_date =from_date print("The from date value is ",from_date) to_date = self.to_date.text() to_date=datetime.datetime.strptime(to_date,'%d-%b-%Y').date() self.table_to_date = to_date select_query_all = "SELECT BILL.BILL_NO,ROW_NUMBER() OVER( PARTITION BY BILL.BILL_NO ORDER BY CATEGORY) SLNO,\ BILL.BILLING_DATE,CATEGORY,ORD.SIZE,ORD.RATE,ORD.QTY,ORD.TOTAL_AMOUNT,BILL.TOTAL_AMOUNT,BILL.AMOUNT_RECIEVED,\ BILL.AMOUNT_DUE,BILL.CUSTOMER_NAME,BILL.PHONE_NO \ FROM DBO.ORDER_DETAILS ORD INNER JOIN DBO.BILLING_TABLE BILL ON \ ORD.BILL_NO = BILL.BILL_NO \ WHERE BILL_TYPE ='DAILY' AND BILLING_DATE BETWEEN ? AND ? ORDER BY BILL.BILL_NO" select_query_due = "SELECT BILL.BILL_NO,ROW_NUMBER() OVER( PARTITION BY BILL.BILL_NO ORDER BY CATEGORY) SLNO,\ BILL.BILLING_DATE,CATEGORY,ORD.SIZE,ORD.RATE,ORD.QTY,ORD.TOTAL_AMOUNT,BILL.TOTAL_AMOUNT,BILL.AMOUNT_RECIEVED,\ BILL.AMOUNT_DUE,BILL.CUSTOMER_NAME,BILL.PHONE_NO \ FROM DBO.ORDER_DETAILS ORD INNER JOIN DBO.BILLING_TABLE BILL ON \ ORD.BILL_NO = BILL.BILL_NO \ WHERE BILL_TYPE ='DAILY' AND AMOUNT_DUE <> 0 AND BILLING_DATE BETWEEN ? AND ? \ ORDER BY BILL.BILL_NO" select_count_all = "SELECT COUNT(DISTINCT BILL.BILL_NO) BILL_COUNT ,(SELECT COUNT(A.AMOUNT_DUE) FROM \ (SELECT BILL.BILL_NO, AMOUNT_DUE FROM DBO.ORDER_DETAILS ORD INNER JOIN DBO.BILLING_TABLE BILL \ ON \ ORD.BILL_NO = BILL.BILL_NO \ WHERE BILL_TYPE ='DAILY' AND BILLING_DATE BETWEEN ? AND ? AND \ AMOUNT_DUE<>0 GROUP BY BILL.BILL_NO,AMOUNT_DUE) AS A) DUE_COUNT FROM DBO.ORDER_DETAILS ORD \ INNER JOIN DBO.BILLING_TABLE BILL ON \ ORD.BILL_NO = BILL.BILL_NO \ WHERE BILL_TYPE ='DAILY' AND BILLING_DATE BETWEEN ? AND ? " select_count_due = "SELECT COUNT(DISTINCT BILL.BILL_NO) BILL_COUNT ,(SELECT COUNT(A.AMOUNT_DUE) FROM \ (SELECT BILL.BILL_NO, AMOUNT_DUE FROM DBO.ORDER_DETAILS ORD INNER JOIN DBO.BILLING_TABLE BILL \ ON \ ORD.BILL_NO = BILL.BILL_NO \ WHERE BILL_TYPE ='DAILY' AND BILLING_DATE BETWEEN ? AND ? AND \ AMOUNT_DUE<>0 GROUP BY BILL.BILL_NO,AMOUNT_DUE) AS A) DUE_COUNT FROM DBO.ORDER_DETAILS ORD \ INNER JOIN DBO.BILLING_TABLE BILL ON \ ORD.BILL_NO = BILL.BILL_NO \ WHERE BILL_TYPE ='DAILY' AND BILLING_DATE BETWEEN ? AND ? AND AMOUNT_DUE<>0 " if self.show_all_radio.isChecked(): cur.execute(select_query_all, (from_date, to_date,)) result = cur.fetchall() cur.execute(select_count_all,(from_date,to_date,from_date, to_date)) count_result =cur.fetchone() else: cur.execute(select_query_due, (from_date, to_date)) result = cur.fetchall() cur.execute(select_count_due, (from_date, to_date,from_date, to_date)) count_result = cur.fetchone() print("result is", result) self.data_result = [data for data in result] result_check = len(result) self.total_amount = 0 self.amount_recieved = 0 self.due_amount = 0 self.prev_row_bill_no = None if result_check >= 1: new_result = [] column_count = self.daily_table.columnCount() for row in range(result_check): tuple_value = list(result[row]) tuple_value[2] = tuple_value[2].strftime('%d/%m/%Y') tuple_value = [str(value) for value in tuple_value if type(value) != 'str'] # tuple_value.extend(self.work_finish) print('the modified tuple value is ', tuple_value) current_row_bill_no = tuple_value[0] if (current_row_bill_no != self.prev_row_bill_no) or self.prev_row_bill_no== None: self.total_amount = self.total_amount+int(float(tuple_value[8])) self.amount_recieved = self.amount_recieved + int(float(tuple_value[9])) self.due_amount = self.due_amount+ int(float(tuple_value[10])) self.prev_row_bill_no =tuple_value[0] self.daily_table.insertRow(row) for column in range(column_count): value = tuple_value[column] self.daily_table.setItem(row, column, self.table_item(value, Qt.ItemIsSelectable | Qt.ItemIsEnabled)) print("The total amount value is ", self.total_amount) print("The total amount recieved value is ", self.amount_recieved) print("The total due amount value is ", self.due_amount) self.total_le.setText(str(round(float(self.total_amount), 2))) self.recieved_le.setText(str(round(float(self.amount_recieved), 2))) self.due_le.setText(str(round(float(self.due_amount), 2))) print("The count values are",count_result) bill_count = str(count_result[0]) due_count = str(count_result[1]) self.total_order_label_value.setText(bill_count) self.total_due_label_value.setText(due_count) def table_item(self, text, flag): tablewidgetitem = QTableWidgetItem(text) tablewidgetitem.setFlags(flag) return tablewidgetitem def exportbtn(self): if self.daily_table.rowCount() >=1: file_path =QFileDialog.getSaveFileName(self, 'Export to Excel', "Daily_Bill_Report_"+self.table_from_date.strftime("%d_%b_%Y")+ "_to_"+self.table_to_date.strftime("%d_%b_%Y")+".xlsx", 'Excel files (.xlsx) ;; All Files ()') if file_path != ('', ''): print("File path is",file_path) excel_book_name = file_path[0] workbook = xlsxwriter.Workbook(excel_book_name) worksheet = workbook.add_worksheet("Today Report") title_format = workbook.add_format({'bold' : True}) title_format.set_bg_color('yellow') title_format.set_font_color('brown') title_format.set_border() data = self.data_result cell_format = workbook.add_format() cell_format.set_border() money_format = workbook.add_format() money_format.set_border() money_format.set_num_format('#,##0.00') print("The first data is ",data) print("check value",data[0][0]) data_modified =[] list_value = [] data_modified = [tuple(str(item) for item in i) for i in data] print ( "The workbook Name is ",excel_book_name) title =["BILL_NO","SL_NO","DATE","CATEGORY","FRAME_SIZE","RATE","QTY","AMOUNT","TOTAL_AMOUNT","AMOUNT_RECIEVED", "AMOUNT_DUE","CUSTOMER_NAME","PHONE_NO"] title_size =[len(i) for i in title] print('the title size is',title_size) for col in range(0,len(title)): worksheet.write(0,col,title[col],title_format) for row_level in range(len(data_modified)): for col_level in range(len(data_modified[0])): col_list =[5,7,7,9,10] if col_level in col_list: value = int(float(data_modified[row_level][col_level])) worksheet.write(row_level + 1, col_level, value, money_format) else: value = data_modified[row_level][col_level] worksheet.write(row_level+1,col_level,value,cell_format) print ( " the row number value is",row_level) footer_list =["Total Order Amount :","Total Recieved :","Due Amount :"] total = int(float(self.total_amount)) recieved = int(float(self.amount_recieved)) due =int(float(self.due_amount)) footer_amt_list =[total,recieved,due] footer_format = workbook.add_format() footer_format.set_border() footer_format.set_bold(True) footer_format.set_font_size(14) footer_money_format = workbook.add_format() footer_money_format.set_border() footer_money_format.set_bold(True) footer_money_format.set_num_format('#,##0.00') footer_money_format.set_font_color('green') footer_money_format.set_font_size(14) footer_money_format_due = workbook.add_format() footer_money_format_due.set_border() footer_money_format_due.set_bold(True) footer_money_format_due.set_num_format('#,##0.00') footer_money_format_due.set_font_color('red') footer_money_format_due.set_font_size(14) row_num =row_level +6 for i in range(3): footer_format.set_font_color('black') worksheet.merge_range(row_num,0,row_num,2,footer_list[i],footer_format) if i==2: worksheet.set_column(row_num,3,12) worksheet.write(row_num, 3, footer_amt_list[i], footer_money_format_due) else: worksheet.set_column(row_num, 3, 12) worksheet.write(row_num, 3, footer_amt_list[i], footer_money_format) row_num+=1 worksheet.set_column(0,2,10) workbook.close() QMessageBox.information(self,"File Export","Daily Report Exported Successfully...") else: QMessageBox.warning(self,"Warning", "Please click show button to get data and then select Export") def closebtn(self): self.close()
class Add_Function_Bill(QDialog, Ui_new_function): def __init__(self, parent=None): super(Add_Function_Bill, self).__init__(parent) self.setupUi(self) self.setWindowTitle("Add Function 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.current_date() self.bill_generator() self.functioncombovalue() self.package_combo.setEnabled(False) self.package_combo.setStyleSheet( 'QPushButton: disabled{background - color:grey}') self.function_combo.currentIndexChanged['QString'].connect( self.comboindexchanged) self.total_le.textChanged.connect(self.amountdue) self.recieved_le.textChanged.connect(self.amountdue) self.cal_tool_btn.clicked.connect(self.delivery_calender) 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) config_name = 'function_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.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.clear_btn.setIcon(QtGui.QIcon(clear_image)) self.clear_btn.setIconSize(QtCore.QSize(35, 35)) self.close_btn.setIcon(QtGui.QIcon(close_image)) self.close_btn.setIconSize(QtCore.QSize(35, 35)) 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 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 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("Booking Calender") 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.booking_le.setText(getdate) self.calender.deleteLater() def functioncombovalue(self): self.combolist = set('', ) sel_query = "SELECT DISTINCT PROD_NAME from dbo.PROD_DETAILS WHERE PROD_TYPE ='FUNCTION'" self.connectdb() cur.execute(sel_query) result = cur.fetchall() for i in result: x = i[0] self.combolist.add(x) self.function_combo.addItems(self.combolist) def combopackagevalue(self): self.combolist = set('', ) self.package_combo.clear() sel_query = "SELECT PACKAGE_NAME from dbo.PACKAGE_DETAILS" self.connectdb() cur.execute(sel_query) result = cur.fetchall() for i in result: x = i[0] self.combolist.add(x) self.package_combo.addItems(self.combolist) self.package_combo.currentIndexChanged['QString'].connect( self.totalamount) def comboindexchanged(self): current_value = self.function_combo.currentText() print("The category combo box current value is ", current_value) if current_value == 'MARRIAGE': self.total_le.clear() self.package_combo.setEnabled(True) self.package_combo.setStyleSheet("border-radius:10px;\n" "border-style:outset;\n" "border-width:2px;\n" "border-color:black;\n" "font: 11pt \"Cambria\";\n" "font:bold") self.combopackagevalue() else: self.package_combo.clear() self.package_combo.setEnabled(False) self.package_combo.setStyleSheet( 'QPushButton: disabled{background - color:grey}') self.totalamount() def totalamount(self): print('the total amount function is in') function_name = self.function_combo.currentText() print('the function name is', function_name) if function_name != 'MARRIAGE': SEL_QUERY = " SELECT PRICE from dbo.PROD_DETAILS WHERE PROD_TYPE ='FUNCTION' AND PROD_NAME =?" cur.execute(SEL_QUERY, function_name) result = cur.fetchall() total_amount_value = str(result[0][0]) print("the total amount is ", total_amount_value) self.total_le.setText(total_amount_value) else: package_name = self.package_combo.currentText() print('the package name is', package_name) SEL_QUERY = " SELECT PROD.PRICE from dbo.PROD_DETAILS PROD JOIN dbo.PACKAGE_DETAILS PACKAGE ON PROD.PACKAGE_ID = PACKAGE.PACKAGE_ID AND PROD_TYPE ='FUNCTION' AND PROD_NAME ='MARRIAGE' AND PACKAGE.PACKAGE_NAME =?" cur.execute(SEL_QUERY, package_name) result = cur.fetchall() total_amount_value = str(result[0][0]) print("the total amount is ", total_amount_value) self.total_le.setText(total_amount_value) def amountdue(self): print('Amount due function in') print("the test value is ", self.total_le.text()) if self.total_le.text() == "": totalamount = float(0) else: totalamount = float(str(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('amount recieved is ', Recievedamount) balance = float(totalamount - Recievedamount) print('The balanced amount is ', balance) self.due_le.setText(str(balance)) def savebtn(self): if self.customer_le.text() == '' or self.phone_le.text() == '': QMessageBox.warning(self, 'Warning', 'Please enter the customer information') elif self.total_le.text() == '': QMessageBox.warning(self, 'Warning', 'Please select proper function details') 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() booking_date = self.booking_le.text() phoneno = int(phoneno) 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 = 'FUNCTION' if booking_date != '': bookingdate = datetime.datetime.strptime( booking_date, '%d/%m/%Y').date() else: bookingdate = datetime.date(9999, 12, 31) print('the deliver date value is ', bookingdate, ' and type is ', type(bookingdate)) sql_order_date = orderdate.strftime("%d/%m/%Y") sql_delivery_date = bookingdate.strftime("%d/%m/%Y") ins_query1 = 'INSERT INTO dbo.BILLING_TABLE VALUES(?,?,?,?,?,?,?,?,?)' ins_query = "INSERT INTO dbo.BILLING_TABLE (BILL_NO,CUSTOMER_NAME,PHONE_NO,BILLING_DATE,FUNCTION_BOOKING_DATE,TOTAL_AMOUNT,AMOUNT_RECIEVED,AMOUNT_DUE,BILL_TYPE) VALUES(?,?,?,?,?,?,?,?,?)" data = (billno, customername, phoneno, orderdate, bookingdate, totalamount, amountreceived, dueamount, bill_type) data1 = (billno, customername, phoneno, orderdate, bookingdate, 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)) function_name = self.function_combo.currentText() package_name = self.package_combo.currentText() total_amount = self.total_le.text() print('the function_name values are', function_name) print('the package_name values are', package_name) print('the total amount values are', total_amount) # finding Prd_id if function_name != 'MARRIAGE': prd_select_query = "SELECT PROD_ID FROM dbo.PROD_DETAILS WHERE PROD_TYPE ='FUNCTION' AND PROD_NAME =?" cur.execute(prd_select_query, function_name) result = cur.fetchall() print('the result value is ', result[0][0]) prd_id = result[0][0] else: prd_select_query = "SELECT PROD.PROD_ID from dbo.PROD_DETAILS PROD JOIN dbo.PACKAGE_DETAILS PACKAGE ON PROD.PACKAGE_ID = PACKAGE.PACKAGE_ID AND PROD_TYPE ='FUNCTION' AND PROD_NAME ='MARRIAGE' AND PACKAGE.PACKAGE_NAME =?" cur.execute(prd_select_query, package_name) result = cur.fetchall() prd_id = result[0][0] print("The PRD_ID values is ", prd_id) # insert data into ORDER_DETAILS table: size = 'NA' qty = 1 rate = total_amount insert_qry_order_table = "INSERT INTO dbo.ORDER_DETAILS VALUES (?,?,?,?,?,?,?,?)" cur.execute(insert_qry_order_table, (order_value, billno, prd_id, function_name, size, rate, qty, total_amount)) connect.commit() connect.close() self.billno = billno self.customer_name = customername self.phone_number = phoneno self.total_amount = total_amount self.amount_recieved = amountreceived self.due_amount = dueamount self.function_name = function_name self.package_name = package_name self.booking_date = bookingdate QMessageBox.information(self, 'Message', 'Data saved successfully') self.save_btn.setEnabled(False) def clearbtn(self): columns_list = [ self.customer_le, self.phone_le, self.booking_le, self.total_le, self.recieved_le, self.due_le ] for i in columns_list: i.clear() 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") phoneno = str(self.phone_number) total_amount = self.total_amount amount_paid = self.amount_recieved amount_due = self.due_amount function_name = self.function_name package_name = self.package_name book = str(self.booking_date) print("the time is ", time, " and the format is ", type(time)) folder = folder_path + year + "\\" + month + "\\" + str(today) + '\\' filename = str(folder) + "Function_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\"FUNCTION BILL\"\n====================================================================" bill_section = "\n\n Bill No\t: " + bill_number + "\t\t\t\tDate : " + today_date + "\n" bill_section2 = "\n\n Customer Name\t\t: " + cust_name bill_section21 = "\n\n Customer Phone No. \t: " + phoneno bill_section22 = "\n\n Function Name \t\t: " + function_name bill_section23 = "\n\n Booking Date \t\t: " + book bill_section_package = "\n\n Package Name \t\t: " + package_name bill_section_combined = bill_section2 + bill_section21 + bill_section22 + bill_section23 + "\n" + lines bill_section_combined_marriage = bill_section2 + bill_section21 + bill_section22 + bill_section_package + bill_section23 + "\n" + lines if function_name == 'MARRIAGE': final = header + address1 + address2 + address3 + address4 + address5 + title + bill_section + lines + bill_section_combined_marriage file.write(final) else: final = header + address1 + address2 + address3 + address4 + address5 + title + bill_section + lines + bill_section_combined file.write(final) footer1 = "\n\n TIME :" + footer_time + "\t\t\t\tTOTAL AMOUNT\t:\t" + str( float(total_amount)) footer2 = "\n\t\t\t\t\t\tAMOUNT PAID\t\t:\t" + str(float(amount_paid)) footer3 = "\n SIGN :\t\t\t\t\tAMOUNT DUE\t\t:\t" + str( float(amount_due)) + "\n" 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.')
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 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))
class Window(QWidget): def __init__(self): super(Window, self).__init__() self.setWindowTitle("Query Cocorahs") self.initUI() def initUI(self): self.createPreviewGroupBox() self.createDatesGroupBox() self.infoPanel() layout = QGridLayout() # layout.addWidget(self.previewGroupBox, 0, 0) layout.addWidget(self.datesGroupBox, 0, 1) layout.addWidget(self.infoPanelBox, 0, 2, 0, 1) layout.setSizeConstraint(QLayout.SetFixedSize) self.setLayout(layout) self.previewLayout.setRowMinimumHeight(0, self.calendar.sizeHint().height()) self.previewLayout.setColumnMinimumWidth(0, self.calendar.sizeHint().width()) def createPreviewGroupBox(self): self.previewGroupBox = QGroupBox("Calendar") self.calendar = QCalendarWidget() self.calendar.setMaximumDate(QDate(3000, 1, 1)) self.calendar.setGridVisible(True) self.previewLayout = QGridLayout() self.previewLayout.addWidget(self.calendar, 0, 0) self.previewGroupBox.setLayout(self.previewLayout) def createDatesGroupBox(self): self.datesGroupBox = QGroupBox(self.tr("Selections")) # QUERY self.queryButton = QPushButton("Query Cocorahs Database") self.queryButton.clicked.connect(self.query_on_click) # START DATES self.currentDateEdit = QDateEdit() self.currentDateEdit.setDisplayFormat('dd MMM yyyy') self.currentDateEdit.setDate(self.calendar.selectedDate()) self.currentDateEdit.setDateRange(self.calendar.minimumDate(), self.calendar.maximumDate()) self.currentDateLabel = QLabel("&Date:") self.currentDateLabel.setBuddy(self.currentDateEdit) # END DATES self.maximumDateEdit = QDateEdit() self.maximumDateEdit.setDisplayFormat('dd MMM yyyy') self.maximumDateEdit.setDate(self.calendar.selectedDate()) self.maximumDateEdit.setDateRange(self.calendar.minimumDate(), self.calendar.maximumDate()) self.maximumDateLabel = QLabel("&End Date:") self.maximumDateLabel.setBuddy(self.maximumDateEdit) # LONGITUDE self.textboxLong = QLineEdit(self) self.textboxLongLabel = QLabel("Target Longitude:") # LATITUDE self.textboxLat = QLineEdit(self) self.textboxLatLabel = QLabel("Target Latitude:") # STATES self.textboxStates = QLineEdit(self) self.textboxStatesLabel = QLabel("State(s): e.g., 'CO,NE,WY'") dateBoxLayout = QGridLayout() dateBoxLayout.addWidget(self.currentDateLabel, 1, 0) dateBoxLayout.addWidget(self.currentDateEdit, 1, 1, 1, 2) # dateBoxLayout.addWidget(self.maximumDateLabel, 2, 0) # dateBoxLayout.addWidget(self.maximumDateEdit, 2, 1, 1, 2) dateBoxLayout.addWidget(self.textboxLatLabel, 3, 0) dateBoxLayout.addWidget(self.textboxLat, 3, 1, 1, 2) dateBoxLayout.addWidget(self.textboxLongLabel, 4, 0) dateBoxLayout.addWidget(self.textboxLong, 4, 1, 1, 2) dateBoxLayout.addWidget(self.textboxStatesLabel, 5, 0) dateBoxLayout.addWidget(self.textboxStates, 5, 1, 1, 2) dateBoxLayout.addWidget(self.queryButton, 6, 0,1,3) dateBoxLayout.setRowStretch(5, 1) self.datesGroupBox.setLayout(dateBoxLayout) def infoPanel(self): self.infoPanelBox = QGroupBox(self.tr("Info Console")) self.infoConsole = QTextEdit(self) infoPanelBoxLayout = QGridLayout() infoPanelBoxLayout.addWidget(self.infoConsole, 0, 0, 1, 1) self.infoPanelBox.setLayout(infoPanelBoxLayout) def query_on_click(self): long = self.textboxLong.text() lat = self.textboxLat.text() startDate = self.currentDateEdit.date() endDate = self.maximumDateEdit.date() states = self.textboxStates.text() date_range = list(range(startDate.month(), endDate.month() + 1)) dateString = startDate.toString('MM/dd/yyyy') query(long=long, lat=lat, dateString=dateString, states=states)
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
class MyWidget(QWidget): def __init__(self, parent=None): super().__init__(parent) horizontalLayout = QHBoxLayout() self.dayView = QTableView() self.dayView.setFrameShape(QFrame.Box) self.dayView.horizontalHeader().setStretchLastSection(True) self.dayView.verticalHeader().setVisible(False) horizontalLayout.addWidget(self.dayView) verticalLayout = QVBoxLayout() self.calendarWidget = QCalendarWidget() self.calendarWidget.setMinimumSize(QSize(250, 200)) self.calendarWidget.setMaximumSize(QSize(250, 200)) self.calendarWidget.setMinimumDate(QDate(2017, 1, 1)) self.calendarWidget.setMaximumDate(QDate(2030, 1, 1)) self.calendarWidget.selectionChanged.connect(self.dataChange) self.calendarWidget.setSelectedDate(QDate.currentDate()) verticalLayout.addWidget(self.calendarWidget) titleFV = QLabel('Food View') verticalLayout.addWidget(titleFV) self.filterLine = QLineEdit() self.filterLine.setMaximumSize(QSize(200, 25)) self.filterLine.textChanged.connect(self.filterChange) buttonAdd = QPushButton(QIcon("images/add.png"), '', None) buttonAdd.setMaximumSize(QSize(20, 30)) buttonAdd.clicked.connect(self.addFood) buttonDell = QPushButton(QIcon("images/del.png"), '', None) buttonDell.setMaximumSize(QSize(20, 30)) buttonDell.clicked.connect(self.delFood) lineEditLayout = QHBoxLayout() lineEditLayout.addWidget(self.filterLine) lineEditLayout.addWidget(buttonAdd) lineEditLayout.addWidget(buttonDell) verticalLayout.addLayout(lineEditLayout) self.foodView = QTableView() self.foodView.setMinimumSize(QSize(0, 0)) self.foodView.setMaximumSize(QSize(250, 1000)) self.foodView.verticalHeader().setVisible(False) self.foodView.horizontalHeader().setStretchLastSection(True) verticalLayout.addWidget(self.foodView) horizontalLayout.addLayout(verticalLayout) self.setLayout(horizontalLayout) model_in = QSqlRelationalTableModel() model_in.setEditStrategy(QSqlTableModel.OnFieldChange) model_in.setTable("intake_food") id_food = model_in.fieldIndex("id_food") date = model_in.fieldIndex("food_date") mass = model_in.fieldIndex("mass") # Set model, hide ID column model_in.setRelation(id_food, QSqlRelation("food", "id", "name")) model_in.setHeaderData(id_food, Qt.Horizontal, "Food") model_in.setHeaderData(date, Qt.Horizontal, "Date") model_in.setHeaderData(mass, Qt.Horizontal, "Mass") if not model_in.select(): self.showError(model_in.lastError()) return self.proxyModel_in = QSortFilterProxyModel() self.proxyModel_in.setSourceModel(model_in) self.proxyModel_in.setFilterKeyColumn(2) self.dayView.setItemDelegate(FlipProxyDelegate()) self.dayView.setModel(self.proxyModel_in) self.dayView.setColumnHidden(0, True) self.dayView.setColumnHidden(2, True) self.dayView.setSelectionMode(QAbstractItemView.SingleSelection) self.dayView.setContextMenuPolicy(Qt.CustomContextMenu) self.dayView.customContextMenuRequested.connect(self.ShowContextMenu) # filter day food by calendar widget self.dataChange() self.model_f = QSqlRelationalTableModel() self.model_f.setEditStrategy(QSqlTableModel.OnFieldChange) self.model_f.setTable("food") self.model_f.setHeaderData(1, Qt.Horizontal, "Food") self.model_f.setHeaderData(2, Qt.Horizontal, "Rate") if not self.model_f.select(): self.showError(self.model_f.lastError()) return self.proxyModel_f = QSortFilterProxyModel() self.proxyModel_f.setSourceModel(self.model_f) self.proxyModel_f.setFilterKeyColumn(1) self.foodView.setModel(self.proxyModel_f) self.foodView.setColumnHidden(0, True) self.foodView.setSelectionMode(QAbstractItemView.SingleSelection) self.foodView.setColumnWidth(1, 150) self.foodView.setColumnWidth(2, 90) def showError(self, err): QMessageBox.critical(self, "Unable to initialize Database", "Error initializing database: " + err.text()) def filterChange(self): regExp = QRegExp(self.filterLine.text(), Qt.CaseInsensitive, QRegExp.FixedString) self.proxyModel_f.setFilterRegExp(regExp) def dataChange(self): date = self.calendarWidget.selectedDate().toString('dd.MM.yyyy') regExp = QRegExp(date, Qt.CaseInsensitive, QRegExp.FixedString) self.proxyModel_in.setFilterRegExp(regExp) def addFood(self): self.model_f.insertRow(self.model_f.rowCount()) def delFood(self): self.model_f.removeRow(self.foodView.currentIndex().row()) self.model_f.select() def resizeEvent(self, event): self.dayView.setColumnWidth(1, self.dayView.width() * 0.7) self.dayView.setColumnWidth(3, self.dayView.width() * 0.2) QWidget.resizeEvent(self, event) def ShowContextMenu(self, pos): contextMenu = QMenu("Context menu", self) action1 = QAction("Add food eaten", self) contextMenu.addAction(action1) contextMenu.exec(self.mapToGlobal(pos))
class Window(QWidget): def __init__(self): super().__init__() self.grid_layout = QGridLayout() self.setLayout(self.grid_layout) self.title = "臺鐵對號列車切票查詢系統" self.top = 100 self.left = 100 self.width = 800 self.height = 600 self.InitWindow() def InitWindow(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.labels() self.tb() self.cal() self.cbbox() self.btn() def labels(self): self.l = QLabel(self) self.l.setText("<h1>請選擇時間及起終點<\h1>") self.grid_layout.addWidget(self.l, 0, 0, 1, 8) self.l.setAlignment(Qt.AlignCenter) self.baffer = QLabel(self) self.grid_layout.addWidget(self.baffer, 4, 0, 1, 8) self.text1 = QLabel(self) self.text1.setText("<h3>出發站:<\h3>") self.grid_layout.addWidget(self.text1, 1, 4, 1, 1) self.text2 = QLabel(self) self.text2.setText("<h3>抵達站:<\h3>") self.grid_layout.addWidget(self.text2, 1, 6, 1, 1) self.text3 = QLabel(self) self.text3.setText("<h3>車次:<\h3>") self.grid_layout.addWidget(self.text3, 2, 4, 1, 1) self.text4 = QLabel(self) self.text4.setText("<h3>時間:<\h3>") self.grid_layout.addWidget(self.text4, 3, 4, 1, 1) def tb(self): self.onlyInt = QIntValidator() self.textbox = QLineEdit(self) self.textbox.setValidator(self.onlyInt) self.textbox.setFixedWidth(100) self.grid_layout.addWidget(self.textbox, 2, 5, 1, 1) def cal(self): self.c = QCalendarWidget(self) self.grid_layout.addWidget(self.c, 1, 0, 3, 4) self.c.setMinimumDate(QDate.currentDate()) if QDate.currentDate().dayOfWeek() == 5: self.c.setMaximumDate(QDate.currentDate().addDays(16)) else: self.c.setMaximumDate(QDate.currentDate().addDays(14)) def cbbox(self): self.cb1 = QComboBox(self) self.cb1.addItems(Tags.values()) self.grid_layout.addWidget(self.cb1, 1, 5, 1, 1) self.cb2 = QComboBox(self) self.cb2.addItems(Tags.values()) self.grid_layout.addWidget(self.cb2, 1, 7, 1, 1) self.cb3 = QComboBox(self) self.cb3.addItems(time) self.grid_layout.addWidget(self.cb3, 3, 5, 1, 1) self.time = str(self.cb3.currentText()) def btn(self): self.car = "" self.b1 = QPushButton("車次搜尋", self) self.b1.clicked.connect(self.clicknumber) self.grid_layout.addWidget(self.b1, 2, 6, 1, 2) self.b2 = QPushButton("時間搜尋", self) self.b2.clicked.connect(self.clicktime) self.grid_layout.addWidget(self.b2, 3, 6, 1, 2) def clicknumber(self): if self.textbox.text() == "": QtWidgets.QMessageBox.warning(self, "警告", "車次未填寫", QtWidgets.QMessageBox.Cancel) elif str(self.cb1.currentText()) == str(self.cb2.currentText()): QtWidgets.QMessageBox.warning(self, "警告", "起終點不能相同", QtWidgets.QMessageBox.Cancel) else: window3.axes.clear() path, ticketnum, Graph = algorithm.searchByTrainNo( self.c.selectedDate().toString("yyyy-MM-dd"), str(self.textbox.text()), str(self.cb1.currentText()), str(self.cb2.currentText())) self.drawMap(path, ticketnum, Graph) window3.toplb.setText("<h2>" + str(path) + "<\h2>") window3.mainlb.setText( "<h1>" + str(self.c.selectedDate().toString("yyyy-MM-dd")) + " " + str(self.textbox.text()) + " 車次 最佳切票建議</h1>") window3.midlbright.setText(str(ticketnum)) self.hide() window3.show() if len(path) == 0: window3.b1.setEnabled(False) else: window3.b1.setEnabled(True) def drawMap(self, path, maxTicketNum, Graph): Graph = Graph.subgraph(path) nodePos = {} for i in Graph.nodes(): staName = staPosDF.loc[staPosDF['Zh_tw'] == i]['Zh_tw'] lon = staPosDF.loc[staPosDF['Zh_tw'] == i]['PositionLon'] lat = staPosDF.loc[staPosDF['Zh_tw'] == i]['PositionLat'] try: nodePos[staName.iloc[0]] = m(lon.iloc[0], lat.iloc[0]) except: print(i) freeSeatDic = algorithm.UpdateEdgeLabel(Graph) # draw on map nx.draw_networkx(Graph, pos=nodePos, node_size=80, node_color='green', font_size=12, font_color='r', font_weight='bold', alpha=0.5, ax=window3.axes) nx.draw_networkx_edge_labels(Graph, pos=nodePos, edge_labels=freeSeatDic, font_size=10, ax=window3.axes) m.drawcoastlines() m.drawmapboundary(fill_color='w', linewidth=0) m.plot(120, 21, latlon=False, ax=window3.axes) window3.canvas.draw() def clicktime(self): if str(self.cb1.currentText()) == str(self.cb2.currentText()): QtWidgets.QMessageBox.warning(self, "警告", "起終點不能相同", QtWidgets.QMessageBox.Cancel) else: self.car = odata_api.timesearch( self.c.selectedDate().toString("yyyy-MM-dd"), str(self.cb3.currentText()), str(self.cb1.currentText()), str(self.cb2.currentText())) self.hide() window2.show() #print(str(self.car)) window2.table.setRowCount(self.car.shape[0]) for i in range(self.car.shape[0]): window2.table.setRowHeight(i, 40) for j in range(4): if j == 0: item = QTableWidgetItem(str(self.car.iloc[i, j])) item.setTextAlignment(Qt.AlignCenter) window2.table.setItem(i, j, item) elif j >= 2: item = QTableWidgetItem( str(self.car.iloc[i, j + 1].strftime("%H:%M"))) item.setTextAlignment(Qt.AlignCenter) window2.table.setItem(i, j, item) else: if str(self.car.iloc[i, j + 1]).find('柴聯') == -1: if str(self.car.iloc[i, 1]) in pp: trainIcon = QtGui.QIcon("./3.png") elif str(self.car.iloc[i, 1]) in GF: trainIcon = QtGui.QIcon("./4.png") elif str(self.car.iloc[i, 1]) in taroko: trainIcon = QtGui.QIcon("./1.png") elif str(self.car.iloc[i, 1]) in puyuma: trainIcon = QtGui.QIcon("./2.png") icon = QTableWidgetItem( trainIcon, str(self.car.iloc[i, j + 1])) # 圖片+文字 else: icon = QTableWidgetItem( QtGui.QIcon("./8.png"), str(self.car.iloc[i, j + 1])) window2.table.setItem(i, j, icon) #item = QTableWidgetItem(str(self.car.iloc[i,j+1])) #item.setTextAlignment(Qt.AlignCenter) #window2.table.setItem(i,j,item) btn = [] for i in range(self.car.shape[0]): btn.append(TrainBtn("確認", str(self.car.iloc[i, 0]), self)) window2.table.setCellWidget(i, 4, btn[i]) window2.header.setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch) window2.title.setText( "<h1>" + str(window.cb1.currentText()) + " 到 " + str(window.cb2.currentText()) + " " + self.c.selectedDate().toString("yyyy-MM-dd") + " " + str(self.cb3.currentText()) + " 出發 4小時內可搭乘對號列車</h1>")
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 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()
class AddCutplanDialog(QWidget): def setupUi(self, adddata=None, sqlfile=None, host=None): now = datetime.now() if host is None: self.host = '' else: self.host = host if adddata is None: self.addData = DataFrame( columns=['ID', 'Log Count', 'Description']) else: self.addData = adddata self.availData = None self.addPD = None self.avalPD = None # SQL if sqlfile is None: self.sqlfile = "support\\cpquery.sql" else: self.sqlfile = sqlfile # SERVER CONNECT QApplication.setOverrideCursor( QCursor(Qt.WaitCursor)) self.conn = connect(LogScanner) QApplication.restoreOverrideCursor() self.setObjectName("Dialog") # self.setWindowIcon(QIcon('images/icon.ico')) self.resize(250, 900) self.setStyleSheet( "#Dialog {\n" " background-color: white;\n" "}") self.installEventFilter(self) self.horizontalLayout = QVBoxLayout(self) self.horizontalLayout.setObjectName("horizontalLayout") self.calendarWidget = QCalendarWidget(self) font = QFont() font.setFamily("Tahoma") font.setPointSize(10) self.calendarWidget.setFont(font) self.calendarWidget.setStyleSheet( "#qt_calendar_prevmonth {\n" " qproperty-icon: url(\"images/prev.png\");\n" "}\n" "\n" "#qt_calendar_nextmonth {\n" " qproperty-icon: url(\"images/next.png\");\n" "}\n" "\n" "#qt_calendar_navigationbar {\n" " background-color: qlineargradient(spread:pad, x1:0, y1:0, " "x2:1, y2:1, stop:0 rgb(192, 221, 221), stop:1 rgb(180, 233, " "197));\n" "}\n" "\n" "#qt_calendar_monthbutton {\n" " color: rgb(0,115,119);\n" " font-size: 15px;\n" "}\n" "\n" "#qt_calendar_yearbutton {\n" " color: rgb(0,115,119);\n" " font-size: 15px;\n" "}\n" "\n" "QCalendarWidget QMenu {\n" " background-color: white;\n" " color: rgb(0,115,119);\n" "}\n" "\n" "QCalendarWidget QMenu::item:selected {\n" " background-color: rgb(192, 221, 221);\n" " color: rgb(0,115,119);\n" "}\n" "\n" "QCalendarWidget QSpinBox {\n" " color: rgb(0,115,119);\n" " selection-background-color: rgb(0, 115, 119);\n" " selection-color: white;\n" "}\n" "\n" "#qt_calendar_calendarview:enabled {\n" " background-color: rgb(192, 221, 221);\n" " alternate-background-color: white;\n" " color: rgb(0, 115, 119);\n" " selection-background-color: rgb(0, 115, 119);\n" " selection-color: white;\n" "}\n" "\n" "#qt_calendar_calendarview:disabled {\n" " color: #44acb0;\n" "}\n" "\n" "") btn = self.calendarWidget.findChild( QToolButton, "qt_calendar_prevmonth") btn.setCursor(QCursor(Qt.PointingHandCursor)) btn = self.calendarWidget.findChild( QToolButton, "qt_calendar_nextmonth") btn.setCursor(QCursor(Qt.PointingHandCursor)) self.calendarWidget.setVerticalHeaderFormat( QCalendarWidget.NoVerticalHeader) self.calendarWidget.setObjectName("calendarWidget") self.calendarWidget.setMinimumDate(QDate(2016, 1, 1)) self.calendarWidget.setMaximumDate( QDate(now.year, now.month, now.day)) btn = self.calendarWidget.findChild( QSpinBox, "qt_calendar_yearedit") btn.setAlignment(Qt.AlignCenter) btn.setButtonSymbols(QSpinBox.NoButtons) self.horizontalLayout.addWidget(self.calendarWidget) self.leftTV = QTableView(self) self.leftTV.setStyleSheet( "QTableView {" "border: 1px solid rgb(192, 221, 221);" "gridline-color: rgb(192, 221, 221);" "selection-background-color: rgb(192, 221, 221);" "selection-color: rgb(0,115,119);" "}" "QTableView::item::selected:!active {" "selection-color: rgb(0,115,119);" "}" ) self.leftTV.setObjectName("leftTV") self.leftTV.horizontalHeader().setDefaultSectionSize(65) self.leftTV.horizontalHeader().setStretchLastSection(True) self.leftTV.horizontalHeader().setStyleSheet( "QHeaderView::section {" "height: 25px;" "border: 1px outset rgb(192, 221, 221);" "background-color: white;" "selection-background-color: white;" "}" ) scrollbarss = """ QScrollBar:vertical { border: none; background: white; width: 5px; margin: 0 0 0 0; } QScrollBar::handle:vertical { background: rgb(192, 221, 221); border-radius: 2px; min-height: 20px; } QScrollBar::add-line:vertical { border: none; background: none; height: 0; subcontrol-position: none; subcontrol-origin: none; } QScrollBar::sub-line:vertical { border: none; background: none; height: 0; subcontrol-position: none; subcontrol-origin: none; } QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical { border: none; width: 0; height: 0; background: none; } QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical { background: none; } QScrollBar:horizontal { border: none; background: white; height: 5px; margin: 0 0 0 0; } QScrollBar::handle:horizontal { background: rgb(192, 221, 221); border-radius: 2px; min-width: 20px; } QScrollBar::add-line:horizontal { border: none; background: none; width: 0; } QScrollBar::sub-line:horizontal { border: none; background: none; width: 0; } QScrollBar::left-arrow:horizontal, QScrollBar::right-arrow:horizontal { border: none; width: 0; height: 0; background: none; } QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal { background: none; } """ self.leftTV.verticalScrollBar().setStyleSheet(scrollbarss) self.leftTV.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self.leftTV.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.leftFilter = HoverFilter() self.leftTV.horizontalHeader().installEventFilter(self.leftFilter) lcDelegate = LogCountDelegate() self.leftTV.setItemDelegateForColumn(1, lcDelegate) self.horizontalLayout.addWidget(self.leftTV) self.middleButtonsLayout = QHBoxLayout() self.middleButtonsLayout.setObjectName("middleButtonsLayout") self.addButton = QToolButton(self) self.addButton.setObjectName("addButton") buttonStyle = \ "QToolButton {\n"\ " background-color: qlineargradient(spread:pad, x1:0, y1:0, "\ "x2:1, y2:1, stop:0 rgba(0, 115, 119, 255), stop:1 rgb(4, 147, "\ "131));\n"\ " color: white;\n"\ " border: None;"\ " border-radius: 2px;"\ " font: 11pt \"Tahoma\";"\ "}" self.addButton.setStyleSheet(buttonStyle) self.addButton.setCursor( QCursor(Qt.PointingHandCursor)) self.middleButtonsLayout.addWidget(self.addButton) self.deleteButton = QToolButton(self) font = QFont() font.setPointSize(10) self.deleteButton.setFont(font) self.deleteButton.setObjectName("deleteButton") self.deleteButton.setStyleSheet(buttonStyle) self.deleteButton.setCursor( QCursor(Qt.PointingHandCursor)) self.middleButtonsLayout.addWidget(self.deleteButton) self.horizontalLayout.addLayout(self.middleButtonsLayout) self.rightTV = QTableView(self) self.rightTV.setStyleSheet( "QTableView {" "border: 1px solid rgb(192, 221, 221);" "gridline-color: rgb(192, 221, 221);" "selection-background-color: rgb(192, 221, 221);" "selection-color: rgb(0,115,119);" "}" "QTableView::item::selected:!active {" "selection-color: rgb(0,115,119);" "}" ) self.rightTV.setObjectName("rightTV") self.rightTV.verticalScrollBar().setStyleSheet(scrollbarss) self.rightTV.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self.rightTV.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.rightTV.horizontalHeader().setDefaultSectionSize(65) self.rightTV.horizontalHeader().setStretchLastSection(True) self.rightTV.horizontalHeader().setStyleSheet( "QHeaderView::section {" "height: 25px;" "border: 1px outset rgb(192, 221, 221);" "background-color: white;" "selection-background-color: white;" "}" ) self.rightFilter = HoverFilter() self.rightTV.horizontalHeader().installEventFilter(self.rightFilter) lcDelegate = LogCountDelegate() self.rightTV.setItemDelegateForColumn(1, lcDelegate) self.horizontalLayout.addWidget(self.rightTV) # self.horizontalLayout.addLayout(self.vertlayoutl) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setStyleSheet( "QDialogButtonBox QPushButton {\n" " background-color: ;\n" " background-color: qlineargradient(spread:pad, x1:0, y1:0, " "x2:1, y2:1, stop:0 rgba(0, 115, 119, 255), stop:1 rgb(4, 147, " "131));\n" " color: white;\n" " width: 70px;\n" " height: 25px;\n" " border: None;\n" " border-radius: 2px;\n" " \n" " font: 11pt \"Tahoma\";\n" "}") self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons( QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.buttonBox.setObjectName("buttonBox") for w in self.buttonBox.children(): if w.metaObject().className() == "QPushButton": w.setCursor(QCursor(Qt.PointingHandCursor)) self.horizontalLayout.addWidget(self.buttonBox) # DATA SET UP # self.onDateChange() # self.RTVSetUp() # EVENTS self.calendarWidget.selectionChanged.connect(self.onDateChange) self.addButton.clicked.connect(self.addFunction) self.deleteButton.clicked.connect(self.deleteFunction) self.retranslateUi(self) # self.buttonBox.button(QDialogButtonBox.Ok).clicked.connect( # self.accept) # self.buttonBox.rejected.connect(self.reject) QMetaObject.connectSlotsByName(self) def eventFilter(self, object, event): if object is self and event.type() == QEvent.KeyPress: if event.key() in (Qt.Key_Return, Qt.Key_Enter,): return True return super(AddCutplanDialog, self).eventFilter(object, event) def onDateChange(self): f = open(self.sqlfile, 'r') sqltext = f.read() selDate = self.calendarWidget.selectedDate().toPyDate() date1 = datetime(selDate.year, selDate.month, selDate.day, 4, 0, 0, 0) date2 = date1 + timedelta(1) sqltext = sqltext.replace( '@date1', str(date1)).replace('@date2', str(date2)) self.availData = read_sql(sqltext, self.conn) self.LTVSetUp() def LTVSetUp(self): self.availPD = PandasModel( self.availData ) for i in range(self.addData.shape[0]): for j in range(self.availData.shape[0]): if self.addData.ID[i] == self.availData.ID[j]: self.availPD.setCompleted(j) self.leftTV.setModel(self.availPD) self.leftTV.setSelectionBehavior(QTableView.SelectRows) self.leftTV.verticalHeader().setVisible(False) self.leftTV.setColumnWidth(0, 45) self.availPD.dataChanged.connect(self.updateAvailPD) def RTVSetUp(self): self.addPD = PandasModel( self.addData ) self.rightTV.setModel(self.addPD) self.rightTV.setSelectionBehavior(QTableView.SelectRows) self.rightTV.verticalHeader().setVisible(False) self.rightTV.setColumnWidth(0, 45) self.addPD.dataChanged.connect(self.updateAddPD) def updateAvailPD(self, index, index2): self.availData.iloc[index.row(), index.column()] = \ self.availPD._df.iloc[index.row(), index.column()] def updateAddPD(self, index, index2): self.addData.iloc[index.row(), index.column()] = \ self.addPD._df.iloc[index.row(), index.column()] def addFunction(self): sm = self.leftTV.selectionModel() if sm.hasSelection(): for r in sm.selectedRows(): if not self.availPD._completed[r.row()]: data = self.availData.iloc[r.row()] self.addData = self.addData.append(data, ignore_index=True) self.availPD.setCompleted(r.row()) self.RTVSetUp() def deleteFunction(self): sm = self.rightTV.selectionModel() if sm.hasSelection(): for r in sm.selectedRows(): for i in range(self.availData.shape[0]): if self.availData.ID[i] == self.addData.ID[r.row()]: self.availPD.setCompleted(i, False) self.addData = self.addData.drop(index=r.row()) self.addData = self.addData.reset_index().drop(columns='index') self.RTVSetUp() def retranslateUi(self, Dialog): _translate = QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Add Cutplans")) self.addButton.setText(_translate("Dialog", "Add ▼")) self.deleteButton.setText(_translate("Dialog", "▲ Remove"))