def initUI(self): frame = QFrame() # frame.setStyleSheet("background-color: rgb(30, 45, 66);") frame.setFrameShape(QFrame.StyledPanel) frame.setFrameShadow(QFrame.Raised) # frame.setMinimumWidth(430) # frame.setFixedHeight(395) frame.setStyleSheet("border: none") add_employee_button = QLabel(frame) add_employee_button.setAlignment(Qt.AlignCenter) add_employee_button.setGeometry(QRect(110, 30, 210, 41)) add_employee_button.setStyleSheet( "font: 75 12pt \"MS Shell Dlg 2\";\n" "background-color: rgb(30, 45, 66);\n" "color: rgb(255, 255, 255);") add_employee_button.setText("Add Product Details") namelabel = QLabel(frame) namelabel.setText("Name") namelabel.setGeometry(QRect(70, 100, 47, 13)) nametextbox = QLineEdit(frame) nametextbox.setGeometry(QRect(160, 90, 181, 31)) nametextbox.setFixedWidth(180) categorylabel = QLabel(frame) categorylabel.setText("Category") categorylabel.setGeometry(QRect(70, 140, 61, 16)) categorytextbox = QComboBox(frame) categorytextbox.setGeometry(QRect(160, 130, 181, 31)) categorytextbox.setFixedWidth(180) categorytextbox.addItems(["Pizza", "Burger"]) quantitylabel = QLabel(frame) quantitylabel.setText("Quantity") quantitylabel.setGeometry(QRect(70, 180, 47, 13)) quantitytextbox = QLineEdit(frame) quantitytextbox.setGeometry(QRect(160, 170, 181, 31)) quantitytextbox.setFixedWidth(180) pricelabel = QLabel(frame) pricelabel.setText("Price") pricelabel.setGeometry(QRect(70, 220, 47, 13)) pricetextbox = QLineEdit(frame) pricetextbox.setGeometry(QRect(160, 210, 181, 31)) pricetextbox.setFixedWidth(180) sellingpricelabel = QLabel(frame) sellingpricelabel.setText("Selling Price") sellingpricelabel.setGeometry(QRect(70, 260, 90, 16)) sellingpricetextbox = QDateEdit(frame) sellingpricetextbox.setGeometry(QRect(160, 250, 181, 31)) sellingpricetextbox.setFixedWidth(180) sellingpricetextbox.setDate(QDate.currentDate()) sellingpricetextbox.setMinimumDate(QDate.currentDate()) addbutton = QPushButton(frame) addbutton.setText("Add Product") addbutton.setGeometry(QRect(160, 300, 111, 31)) addbutton.setStyleSheet("font: 75 12pt \"MS Shell Dlg 2\";\n" "background-color: rgb(30, 45, 66);\n" "color: rgb(255, 255, 255);") layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(frame) self.setLayout(layout) self.setWindowTitle("Add Employee Details") self.resize(430, 395) self.show() self.center()
class nuevoCliente(QDialog): def __init__(self, parent=None): super(nuevoCliente, self).__init__() self.setWindowIcon(QIcon("Imagenes/new.jpg")) self.setWindowTitle("Новый клиент") self.setWindowFlags(Qt.WindowCloseButtonHint | Qt.MSWindowsFixedSizeDialogHint) self.setFixedSize(320, 478) self.initUI() def initUI(self): self.groupBoxDatosGenerales = QGroupBox("Новый клиент", self) self.groupBoxDatosGenerales.setFixedSize(300, 223) self.groupBoxDatosGenerales.move(10, 13) labelNombre = QLabel("<font color='#FF3300'>*</font> Имя", self.groupBoxDatosGenerales) labelNombre.move(15, 28) self.lineEditNombre = QLineEdit(self.groupBoxDatosGenerales) self.lineEditNombre.setValidator(QRegExpValidator(QRegExp("[a-zA-Z ]+"), self.lineEditNombre)) self.lineEditNombre.setMaxLength(30) self.lineEditNombre.setFixedWidth(270) self.lineEditNombre.setFocus() self.lineEditNombre.move(15, 46) labelApellido = QLabel("<font color='#FF3300'>*</font> Фамилия", self.groupBoxDatosGenerales) labelApellido.move(15, 74) self.lineEditApellido = QLineEdit(self.groupBoxDatosGenerales) self.lineEditApellido.setValidator(QRegExpValidator(QRegExp("[a-zA-Z ]+"), self.lineEditApellido)) self.lineEditApellido.setMaxLength(30) self.lineEditApellido.setFixedWidth(270) self.lineEditApellido.move(15, 92) labelSexo = QLabel("<font color='#FF3300'>*</font> Пол", self.groupBoxDatosGenerales) labelSexo.move(15, 120) self.comboBoxSexo = QComboBox(self.groupBoxDatosGenerales) self.comboBoxSexo.addItems(["М", "Ж"]) self.comboBoxSexo.setCurrentIndex(-1) self.comboBoxSexo.setFixedWidth(270) self.comboBoxSexo.move(15, 138) labelFechaNacimiento = QLabel("<font color='#FF3300'>*</font> Дата рождения", self.groupBoxDatosGenerales) labelFechaNacimiento.move(15, 166) self.dateEditFechaNacimiento = QDateEdit(self.groupBoxDatosGenerales) self.dateEditFechaNacimiento.setDate(QDate.currentDate()) self.dateEditFechaNacimiento.setMaximumDate(QDate.currentDate()) self.dateEditFechaNacimiento.setDisplayFormat("dd/MM/yyyy") self.dateEditFechaNacimiento.setCalendarPopup(True) self.dateEditFechaNacimiento.setCursor(Qt.PointingHandCursor) self.dateEditFechaNacimiento.setFixedWidth(270) self.dateEditFechaNacimiento.move(15, 184) self.groupBoxUbicacion = QGroupBox("Проживание", self) self.groupBoxUbicacion.setFixedSize(300, 86) self.groupBoxUbicacion.move(10, 250) labelPais = QLabel("<font color='#FF3300'>*</font> Страна", self.groupBoxUbicacion) labelPais.move(15, 28) self.lineEditPais = QLineEdit(self.groupBoxUbicacion) self.lineEditPais.setMaxLength(30) self.lineEditPais.setFixedWidth(270) self.lineEditPais.move(15, 48) self.groupBoxContacto = QGroupBox("Контакты", self) self.groupBoxContacto.setFixedSize(300, 86) self.groupBoxContacto.move(10, 350) labelTelCel = QLabel("<font color='#FF3300'>*</font> Номер телефона", self.groupBoxContacto) labelTelCel.move(15, 28) self.lineEditTelCel = QLineEdit(self.groupBoxContacto) self.lineEditTelCel.setInputMask("9999999999999999; ") self.lineEditTelCel.setFixedWidth(270) self.lineEditTelCel.move(15, 48) # ========================================================== labelInformacion = QLabel("<font color='#FF3300'>*</font> Обязательные поля.", self) labelInformacion.move(10, 445) buttonAceptar = QPushButton("Сохранить", self) buttonAceptar.setCursor(Qt.PointingHandCursor) buttonAceptar.move(154, 445) buttonCerrar = QPushButton("Закрыть", self) buttonCerrar.setCursor(Qt.PointingHandCursor) buttonCerrar.move(236, 445) buttonAceptar.clicked.connect(self.Aceptar) buttonCerrar.clicked.connect(self.close) def Aceptar(self): nombre = " ".join(self.lineEditNombre.text().split()).title() apellido = " ".join(self.lineEditApellido.text().split()).title() sexo = self.comboBoxSexo.currentText() fecNacimiento = self.dateEditFechaNacimiento.text() pais = " ".join(self.lineEditPais.text().split()).title() telCel = self.lineEditTelCel.text() if not nombre: self.lineEditNombre.setFocus() elif not apellido: self.lineEditApellido.setFocus() elif not sexo: self.comboBoxSexo.setFocus() elif not pais: self.lineEditPais.setFocus() elif not telCel: self.lineEditTelCel.setFocus() else: if QFile.exists("DB_SIACLE/DB_SIACLE.db"): conexion = sqlite3.connect("DB_SIACLE/DB_SIACLE.db") cursor = conexion.cursor() try: datos = [nombre, apellido, sexo, fecNacimiento, pais, telCel] cursor.execute("INSERT INTO CLIENTES (NOMBRE, APELLIDO, SEXO, " "FECHA_NACIMIENTO, PAIS, TELEFONO_CELULAR) " "VALUES (?,?,?,?,?,?)", datos) conexion.commit() conexion.close() self.lineEditNombre.clear() self.lineEditApellido.clear() self.comboBoxSexo.setCurrentIndex(-1) self.dateEditFechaNacimiento.setDate(QDate.currentDate()) self.lineEditPais.clear() self.lineEditTelCel.clear() QMessageBox.information(self, "Новый клиент", "Клиент зарегестрирован. ", QMessageBox.Ok) except: conexion.close() QMessageBox.critical(self, "Новый клиент", "Неизвестная ошибка. ", QMessageBox.Ok) else: QMessageBox.critical(self, "Новый клиент", "База данных не найдена." " ", QMessageBox.Ok) self.lineEditNombre.setFocus()
class AddBookingDetails(QMainWindow): closing = pyqtSignal(int) def __init__(self, parent, update, id=None): super().__init__(parent) self.db = DB() self.initUI(update, id) def initUI(self, update, id): self.setWindowModality(Qt.ApplicationModal) frame = QFrame() # frame.setStyleSheet("background-color: rgb(30, 45, 66);") frame.setFrameShape(QFrame.StyledPanel) frame.setFrameShadow(QFrame.Raised) # frame.setMinimumWidth(430) # frame.setFixedHeight(395) # frame.setStyleSheet("border: none") add_booking_button = QLabel(frame) add_booking_button.setAlignment(Qt.AlignCenter) add_booking_button.setGeometry(QRect(110, 30, 210, 41)) add_booking_button.setStyleSheet("font: 75 12pt \"MS Shell Dlg 2\";\n" "background-color: rgb(30, 45, 66);\n" "color: rgb(255, 255, 255);") add_booking_button.setText("Add Reservation Details") # tablelabel = QLabel(frame) # tablelabel.setText("Table") # tablelabel.setGeometry(QRect(50, 120, 81, 20)) # # tabletextbox = QComboBox(frame) # tabletextbox.setGeometry(QRect(170, 110, 181, 31)) # tabletextbox.setFixedWidth(180) # tabletextbox.addItems(["Table 1", "Table 2"]) customernamelabel = QLabel(frame) customernamelabel.setText("Customer Name") customernamelabel.setGeometry(QRect(50, 120, 100, 20)) self.customernametextbox = QLineEdit(frame) self.customernametextbox.setGeometry(QRect(170, 110, 181, 31)) self.customernametextbox.setFixedWidth(180) customercontactlabel = QLabel(frame) customercontactlabel.setText("Customer Contact") customercontactlabel.setGeometry(QRect(50, 160, 145, 19)) self.customercontacttextbox = QLineEdit(frame) self.customercontacttextbox.setGeometry(QRect(170, 150, 181, 31)) self.customercontacttextbox.setFixedWidth(180) datelabel = QLabel(frame) datelabel.setText("Date") datelabel.setGeometry(QRect(50, 200, 145, 19)) self.datetextbox = QDateEdit(frame) self.datetextbox.setGeometry(QRect(170, 190, 181, 31)) self.datetextbox.setFixedWidth(180) self.datetextbox.setDate(QDate.currentDate()) self.datetextbox.setMinimumDate(QDate.currentDate()) self.datetextbox.setDisplayFormat("dd-MM-yyyy") starttimelabel = QLabel(frame) starttimelabel.setText("Start Time") starttimelabel.setGeometry(QRect(50, 240, 121, 16)) self.starttimetextbox = QTimeEdit(frame) self.starttimetextbox.setGeometry(QRect(170, 230, 181, 31)) self.starttimetextbox.setFixedWidth(180) # self.starttimetextbox.setTime(QDate.currentDate()) # self.starttimetextbox.setMinimumDate(QDate.currentDate()) self.addbutton = QPushButton(frame) self.addbutton.setText("Add Booking") self.addbutton.setGeometry(QRect(160, 300, 151, 31)) self.addbutton.setStyleSheet("font: 75 12pt \"MS Shell Dlg 2\";\n" "background-color: rgb(30, 45, 66);\n" "color: rgb(255, 255, 255);") # self.addbutton.clicked.connect(lambda: self.add_button_click("reservations")) if update == 'add': print("Add") print(id) self.addbutton.setText("Add Reservation") self.addbutton.clicked.connect( lambda: self.add_button_click("reservations")) else: print("Update") print(id) self.addbutton.setText("Update Reservation") self.addbutton.clicked.connect( lambda: self.update_button_click("reservations", id)) layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(frame) centralWidget = QWidget() centralWidget.setLayout(layout) self.setCentralWidget(centralWidget) # self.setLayout(layout) self.setWindowTitle("Add Reservation Details") self.resize(430, 395) self.show() self.center() def center(self): '''centers the window on the screen''' screen = QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2) def update_button_click(self, where, id): if where == "reservations": print("Tables Finally here") customer_name = self.customernametextbox.text() customer_contact = self.customercontacttextbox.text() start_time = self.starttimetextbox.text() try: date = datetime.datetime.strptime(self.datetextbox.text(), "%d-%m-%Y") booking_date = datetime.datetime.strftime(date, "%Y-%m-%d") except Exception as e: ''' Make sure to add an error message. ''' print(e) return if customer_name != "" and customer_contact != "": query = "update customerBooking set `customer_name`=%s, " \ "`phone_number`=%s, `booking_date`=concat(%s, ' ', %s)" \ "where id=%s;" values = (customer_name, customer_contact, booking_date, start_time, id) result = self.db.execute(query, values) self.closeEvent = self.message() def add_button_click(self, where): if where == "reservations": print("Finally here") customer_name = self.customernametextbox.text() customer_contact = self.customercontacttextbox.text() start_time = self.starttimetextbox.text() try: date = datetime.datetime.strptime(self.datetextbox.text(), "%d-%m-%Y") booking_date = datetime.datetime.strftime(date, "%Y-%m-%d") except Exception as e: ''' Make sure to add an error message. ''' print(e) return if customer_name != "" and customer_contact != "": print("Got Here") query = "insert into customerBooking (`customer_name`, `phone_number`, `booking_date`)" \ "values (%s, %s, concat(%s, ' ', %s));" values = (customer_name, customer_contact, booking_date, start_time) result = self.db.execute(query, values) self.closeEvent = self.message() def message(self): self.closing.emit(1) self.close()
class actualizarCliente(QDialog): def __init__(self, indice, datos, parent=None): super(actualizarCliente, self).__init__() self.parent = parent self.indice = indice self.datos = datos self.setWindowIcon(QIcon("Imagenes/ch.png")) self.setWindowTitle("Обновление клиента") self.setWindowFlags(Qt.WindowCloseButtonHint | Qt.MSWindowsFixedSizeDialogHint) self.setFixedSize(320, 478) self.initUI() def initUI(self): self.groupBoxDatosGenerales = QGroupBox("Общие данные ", self) self.groupBoxDatosGenerales.setFixedSize(300, 223) self.groupBoxDatosGenerales.move(10, 13) labelNombre = QLabel("<font color='#FF3300'>*</font> Имя", self.groupBoxDatosGenerales) labelNombre.move(15, 28) self.lineEditNombre = QLineEdit(self.groupBoxDatosGenerales) self.lineEditNombre.setValidator(QRegExpValidator(QRegExp("[a-zA-Z ]+"), self.lineEditNombre)) self.lineEditNombre.setMaxLength(30) self.lineEditNombre.setFixedWidth(270) self.lineEditNombre.setFocus() self.lineEditNombre.move(15, 46) labelApellido = QLabel("<font color='#FF3300'>*</font> Фамилия", self.groupBoxDatosGenerales) labelApellido.move(15, 74) self.lineEditApellido = QLineEdit(self.groupBoxDatosGenerales) self.lineEditApellido.setValidator(QRegExpValidator(QRegExp("[a-zA-Z ]+"), self.lineEditApellido)) self.lineEditApellido.setMaxLength(30) self.lineEditApellido.setFixedWidth(270) self.lineEditApellido.move(15, 92) labelSexo = QLabel("<font color='#FF3300'>*</font> Пол", self.groupBoxDatosGenerales) labelSexo.move(15, 120) self.comboBoxSexo = QComboBox(self.groupBoxDatosGenerales) self.comboBoxSexo.addItems(["М", "Ж"]) self.comboBoxSexo.setCurrentIndex(-1) self.comboBoxSexo.setFixedWidth(270) self.comboBoxSexo.move(15, 138) labelFechaNacimiento = QLabel("<font color='#FF3300'>*</font> Дата рождения", self.groupBoxDatosGenerales) labelFechaNacimiento.move(15, 166) self.dateEditFechaNacimiento = QDateEdit(self.groupBoxDatosGenerales) self.dateEditFechaNacimiento.setDate(QDate.currentDate()) self.dateEditFechaNacimiento.setMaximumDate(QDate.currentDate()) self.dateEditFechaNacimiento.setDisplayFormat("dd/MM/yyyy") self.dateEditFechaNacimiento.setCalendarPopup(True) self.dateEditFechaNacimiento.setCursor(Qt.PointingHandCursor) self.dateEditFechaNacimiento.setFixedWidth(270) self.dateEditFechaNacimiento.move(15, 184) self.groupBoxUbicacion = QGroupBox("Проживание", self) self.groupBoxUbicacion.setFixedSize(300, 86) self.groupBoxUbicacion.move(10, 250) labelPais = QLabel("<font color='#FF3300'>*</font> Страна", self.groupBoxUbicacion) labelPais.move(15, 28) self.lineEditPais = QLineEdit(self.groupBoxUbicacion) self.lineEditPais.setMaxLength(30) self.lineEditPais.setFixedWidth(270) self.lineEditPais.move(15, 48) self.groupBoxContacto = QGroupBox("Контакты", self) self.groupBoxContacto.setFixedSize(300, 86) self.groupBoxContacto.move(10, 350) labelTelCel = QLabel("<font color='#FF3300'>*</font> Номер телефона", self.groupBoxContacto) labelTelCel.move(15, 28) self.lineEditTelCel = QLineEdit(self.groupBoxContacto) self.lineEditTelCel.setInputMask("9999999999999999; ") self.lineEditTelCel.setFixedWidth(270) self.lineEditTelCel.move(15, 48) labelInformacion = QLabel("<font color='#FF3300'>*</font> Обязательные поля.", self) labelInformacion.move(10, 445) buttonActualizar = QPushButton("Обновить", self) buttonActualizar.setCursor(Qt.PointingHandCursor) buttonActualizar.move(154, 445) buttonCerrar = QPushButton("Закрыть", self) buttonCerrar.setCursor(Qt.PointingHandCursor) buttonCerrar.move(236, 445) buttonActualizar.clicked.connect(self.Actualizar) buttonCerrar.clicked.connect(self.close) self.cargarDatos(self.datos) def cargarDatos(self, datos): self.lineEditNombre.setText(datos[1]) self.lineEditApellido.setText(datos[2]) itemsComboBox = [self.comboBoxSexo.itemText(i) for i in range(self.comboBoxSexo.count())] if datos[3] in itemsComboBox: posicionItem = itemsComboBox.index(datos[3]) self.comboBoxSexo.setCurrentIndex(posicionItem) else: self.comboBoxSexo.setCurrentIndex(-1) self.dateEditFechaNacimiento.setDate(QDate.fromString(datos[4], "dd/MM/yyyy")) self.lineEditPais.setText(datos[5]) self.lineEditTelCel.setText(datos[6]) return def Actualizar(self): nombre = " ".join(self.lineEditNombre.text().split()).title() apellido = " ".join(self.lineEditApellido.text().split()).title() sexo = self.comboBoxSexo.currentText() fecNacimiento = self.dateEditFechaNacimiento.text() pais = " ".join(self.lineEditPais.text().split()).title() telCel = self.lineEditTelCel.text() if not nombre: self.lineEditNombre.setFocus() elif not apellido: self.lineEditApellido.setFocus() elif not sexo: self.comboBoxSexo.setFocus() elif not pais: self.lineEditPais.setFocus() elif not telCel: self.lineEditTelCel.setFocus() else: if QFile.exists("DB_SIACLE/DB_SIACLE.db"): conexion = sqlite3.connect("DB_SIACLE/DB_SIACLE.db") cursor = conexion.cursor() try: datos = [nombre, apellido, sexo, fecNacimiento, pais, telCel, self.datos[0]] cursor.execute("UPDATE CLIENTES SET NOMBRE = ?, APELLIDO = ?, SEXO = ?, " "FECHA_NACIMIENTO = ?, PAIS = ?, TELEFONO_CELULAR = ? " "WHERE ID = ?", datos) conexion.commit() conexion.close() nuevos_datos = (str(self.datos[0]), nombre, apellido, sexo, fecNacimiento, pais, telCel) self.parent.tabla.removeRow(self.indice) numFilas = self.parent.tabla.rowCount() self.parent.tabla.insertRow(numFilas) for indice, dato in enumerate(nuevos_datos): dato = QTableWidgetItem(dato) if indice == 0: dato.setTextAlignment(Qt.AlignCenter) self.parent.tabla.setItem(numFilas, indice, dato) self.lineEditNombre.clear() self.lineEditApellido.clear() self.comboBoxSexo.setCurrentIndex(-1) self.dateEditFechaNacimiento.setDate(QDate.currentDate()) self.lineEditPais.clear() self.lineEditTelCel.clear() QMessageBox.information(self, "Обновление клиента ", "Клиент обновлен." " ", QMessageBox.Ok) self.close() except: conexion.close() QMessageBox.critical(self, "Обновление клиента", "Неизвестная ошибка. ", QMessageBox.Ok) else: QMessageBox.critical(self, "Обновление клиента", "База не найдена " "datos. ", QMessageBox.Ok)
class nuevoCliente(QDialog): def __init__(self, parent=None): super(nuevoCliente, self).__init__() self.setWindowIcon(QIcon("Imagenes/Qt.png")) self.setWindowTitle("Nuevo cliente") self.setWindowFlags(Qt.WindowCloseButtonHint | Qt.MSWindowsFixedSizeDialogHint) self.setFixedSize(320, 478) self.initUI() def initUI(self): # =========== WIDGETS GROUPBOX DATOS GENERALES ============= self.groupBoxDatosGenerales = QGroupBox("Datos generales", self) self.groupBoxDatosGenerales.setFixedSize(300, 223) self.groupBoxDatosGenerales.move(10, 13) labelNombre = QLabel("<font color='#FF3300'>*</font> Nombre", self.groupBoxDatosGenerales) labelNombre.move(15, 28) self.lineEditNombre = QLineEdit(self.groupBoxDatosGenerales) self.lineEditNombre.setValidator(QRegExpValidator(QRegExp("[a-zA-Zá-úÁ-ÚñÑ ]+"), self.lineEditNombre)) self.lineEditNombre.setMaxLength(30) self.lineEditNombre.setFixedWidth(270) self.lineEditNombre.setFocus() self.lineEditNombre.move(15, 46) labelApellido = QLabel("<font color='#FF3300'>*</font> Apellido", self.groupBoxDatosGenerales) labelApellido.move(15, 74) self.lineEditApellido = QLineEdit(self.groupBoxDatosGenerales) self.lineEditApellido.setValidator(QRegExpValidator(QRegExp("[a-zA-Zá-úÁ-ÚñÑ ]+"), self.lineEditApellido)) self.lineEditApellido.setMaxLength(30) self.lineEditApellido.setFixedWidth(270) self.lineEditApellido.move(15, 92) labelSexo = QLabel("<font color='#FF3300'>*</font> Sexo", self.groupBoxDatosGenerales) labelSexo.move(15, 120) self.comboBoxSexo = QComboBox(self.groupBoxDatosGenerales) self.comboBoxSexo.addItems(["Masculino", "Femenino"]) self.comboBoxSexo.setCurrentIndex(-1) self.comboBoxSexo.setFixedWidth(270) self.comboBoxSexo.move(15, 138) labelFechaNacimiento = QLabel("<font color='#FF3300'>*</font> Fecha de nacimiento", self.groupBoxDatosGenerales) labelFechaNacimiento.move(15, 166) self.dateEditFechaNacimiento = QDateEdit(self.groupBoxDatosGenerales) self.dateEditFechaNacimiento.setDate(QDate.currentDate()) self.dateEditFechaNacimiento.setMaximumDate(QDate.currentDate()) self.dateEditFechaNacimiento.setDisplayFormat("dd/MM/yyyy") self.dateEditFechaNacimiento.setCalendarPopup(True) self.dateEditFechaNacimiento.setCursor(Qt.PointingHandCursor) self.dateEditFechaNacimiento.setFixedWidth(270) self.dateEditFechaNacimiento.move(15, 184) # ============== WIDGETS GROUPBOX UBICACIÓN ================ self.groupBoxUbicacion = QGroupBox("Ubicación", self) self.groupBoxUbicacion.setFixedSize(300, 86) self.groupBoxUbicacion.move(10, 250) labelPais = QLabel("<font color='#FF3300'>*</font> País", self.groupBoxUbicacion) labelPais.move(15, 28) self.lineEditPais = QLineEdit(self.groupBoxUbicacion) self.lineEditPais.setMaxLength(30) self.lineEditPais.setFixedWidth(270) self.lineEditPais.move(15, 48) # ============== WIDGETS GROUPBOX CONTACTO ================= self.groupBoxContacto = QGroupBox("Contacto", self) self.groupBoxContacto.setFixedSize(300, 86) self.groupBoxContacto.move(10, 350) labelTelCel = QLabel("<font color='#FF3300'>*</font> Teléfono o celular", self.groupBoxContacto) labelTelCel.move(15, 28) self.lineEditTelCel = QLineEdit(self.groupBoxContacto) self.lineEditTelCel.setInputMask("9999999999999999; ") self.lineEditTelCel.setFixedWidth(270) self.lineEditTelCel.move(15, 48) # ========================================================== labelInformacion = QLabel("<font color='#FF3300'>*</font> Campos obligatorios.", self) labelInformacion.move(10, 445) # ======================== BOTONES ========================= buttonAceptar = QPushButton("Aceptar", self) buttonAceptar.setCursor(Qt.PointingHandCursor) buttonAceptar.move(154, 445) buttonCerrar = QPushButton("Cerrar", self) buttonCerrar.setCursor(Qt.PointingHandCursor) buttonCerrar.move(236, 445) # ==================== EVENTOS BOTONES ===================== buttonAceptar.clicked.connect(self.Aceptar) buttonCerrar.clicked.connect(self.close) # ========================= FUNCIONES ========================== def Aceptar(self): nombre = " ".join(self.lineEditNombre.text().split()).title() apellido = " ".join(self.lineEditApellido.text().split()).title() sexo = self.comboBoxSexo.currentText() fecNacimiento = self.dateEditFechaNacimiento.text() pais = " ".join(self.lineEditPais.text().split()).title() telCel = self.lineEditTelCel.text() if not nombre: self.lineEditNombre.setFocus() elif not apellido: self.lineEditApellido.setFocus() elif not sexo: self.comboBoxSexo.setFocus() elif not pais: self.lineEditPais.setFocus() elif not telCel: self.lineEditTelCel.setFocus() else: if QFile.exists("DB_SIACLE/DB_SIACLE.db"): conexion = sqlite3.connect("DB_SIACLE/DB_SIACLE.db") cursor = conexion.cursor() try: datos = [nombre, apellido, sexo, fecNacimiento, pais, telCel] cursor.execute("INSERT INTO CLIENTES (NOMBRE, APELLIDO, SEXO, " "FECHA_NACIMIENTO, PAIS, TELEFONO_CELULAR) " "VALUES (?,?,?,?,?,?)", datos) conexion.commit() conexion.close() self.lineEditNombre.clear() self.lineEditApellido.clear() self.comboBoxSexo.setCurrentIndex(-1) self.dateEditFechaNacimiento.setDate(QDate.currentDate()) self.lineEditPais.clear() self.lineEditTelCel.clear() QMessageBox.information(self, "Nuevo cliente", "Cliente registrado. ", QMessageBox.Ok) except: conexion.close() QMessageBox.critical(self, "Nuevo cliente", "Error desconocido. ", QMessageBox.Ok) else: QMessageBox.critical(self, "Nuevo cliente", "No se encontro la base de datos." " ", QMessageBox.Ok) self.lineEditNombre.setFocus()
class actualizarCliente(QDialog): def __init__(self, indice, datos, parent=None): super(actualizarCliente, self).__init__() self.parent = parent self.indice = indice self.datos = datos self.setWindowIcon(QIcon("Imagenes/Qt.png")) self.setWindowTitle("Actualizar cliente") self.setWindowFlags(Qt.WindowCloseButtonHint | Qt.MSWindowsFixedSizeDialogHint) self.setFixedSize(320, 478) self.initUI() def initUI(self): # =========== WIDGETS GROUPBOX DATOS GENERALES ============= self.groupBoxDatosGenerales = QGroupBox("Datos generales", self) self.groupBoxDatosGenerales.setFixedSize(300, 223) self.groupBoxDatosGenerales.move(10, 13) labelNombre = QLabel("<font color='#FF3300'>*</font> Nombre", self.groupBoxDatosGenerales) labelNombre.move(15, 28) self.lineEditNombre = QLineEdit(self.groupBoxDatosGenerales) self.lineEditNombre.setValidator(QRegExpValidator(QRegExp("[a-zA-Zá-úÁ-ÚñÑ ]+"), self.lineEditNombre)) self.lineEditNombre.setMaxLength(30) self.lineEditNombre.setFixedWidth(270) self.lineEditNombre.setFocus() self.lineEditNombre.move(15, 46) labelApellido = QLabel("<font color='#FF3300'>*</font> Apellido", self.groupBoxDatosGenerales) labelApellido.move(15, 74) self.lineEditApellido = QLineEdit(self.groupBoxDatosGenerales) self.lineEditApellido.setValidator(QRegExpValidator(QRegExp("[a-zA-Zá-úÁ-ÚñÑ ]+"), self.lineEditApellido)) self.lineEditApellido.setMaxLength(30) self.lineEditApellido.setFixedWidth(270) self.lineEditApellido.move(15, 92) labelSexo = QLabel("<font color='#FF3300'>*</font> Sexo", self.groupBoxDatosGenerales) labelSexo.move(15, 120) self.comboBoxSexo = QComboBox(self.groupBoxDatosGenerales) self.comboBoxSexo.addItems(["Masculino", "Femenino"]) self.comboBoxSexo.setCurrentIndex(-1) self.comboBoxSexo.setFixedWidth(270) self.comboBoxSexo.move(15, 138) labelFechaNacimiento = QLabel("<font color='#FF3300'>*</font> Fecha de nacimiento", self.groupBoxDatosGenerales) labelFechaNacimiento.move(15, 166) self.dateEditFechaNacimiento = QDateEdit(self.groupBoxDatosGenerales) self.dateEditFechaNacimiento.setDate(QDate.currentDate()) self.dateEditFechaNacimiento.setMaximumDate(QDate.currentDate()) self.dateEditFechaNacimiento.setDisplayFormat("dd/MM/yyyy") self.dateEditFechaNacimiento.setCalendarPopup(True) self.dateEditFechaNacimiento.setCursor(Qt.PointingHandCursor) self.dateEditFechaNacimiento.setFixedWidth(270) self.dateEditFechaNacimiento.move(15, 184) # ============== WIDGETS GROUPBOX UBICACIÓN ================ self.groupBoxUbicacion = QGroupBox("Ubicación", self) self.groupBoxUbicacion.setFixedSize(300, 86) self.groupBoxUbicacion.move(10, 250) labelPais = QLabel("<font color='#FF3300'>*</font> País", self.groupBoxUbicacion) labelPais.move(15, 28) self.lineEditPais = QLineEdit(self.groupBoxUbicacion) self.lineEditPais.setMaxLength(30) self.lineEditPais.setFixedWidth(270) self.lineEditPais.move(15, 48) # ============== WIDGETS GROUPBOX CONTACTO ================= self.groupBoxContacto = QGroupBox("Contacto", self) self.groupBoxContacto.setFixedSize(300, 86) self.groupBoxContacto.move(10, 350) labelTelCel = QLabel("<font color='#FF3300'>*</font> Teléfono o celular", self.groupBoxContacto) labelTelCel.move(15, 28) self.lineEditTelCel = QLineEdit(self.groupBoxContacto) self.lineEditTelCel.setInputMask("9999999999999999; ") self.lineEditTelCel.setFixedWidth(270) self.lineEditTelCel.move(15, 48) # ========================================================== labelInformacion = QLabel("<font color='#FF3300'>*</font> Campos obligatorios.", self) labelInformacion.move(10, 445) # ======================== BOTONES ========================= buttonActualizar = QPushButton("Actualizar", self) buttonActualizar.setCursor(Qt.PointingHandCursor) buttonActualizar.move(154, 445) buttonCerrar = QPushButton("Cerrar", self) buttonCerrar.setCursor(Qt.PointingHandCursor) buttonCerrar.move(236, 445) # ==================== EVENTOS BOTONES ===================== buttonActualizar.clicked.connect(self.Actualizar) buttonCerrar.clicked.connect(self.close) # ================= FUNCIONES AUTOMÁTICAS ================== self.cargarDatos(self.datos) # ========================= FUNCIONES ========================== def cargarDatos(self, datos): # datos = ["Id", "Nombre", "Apellido", "Sexo", "Fecha de nacimiento", "País", # "Teléfono o celular"] self.lineEditNombre.setText(datos[1]) self.lineEditApellido.setText(datos[2]) itemsComboBox = [self.comboBoxSexo.itemText(i) for i in range(self.comboBoxSexo.count())] if datos[3] in itemsComboBox: posicionItem = itemsComboBox.index(datos[3]) self.comboBoxSexo.setCurrentIndex(posicionItem) else: self.comboBoxSexo.setCurrentIndex(-1) self.dateEditFechaNacimiento.setDate(QDate.fromString(datos[4], "dd/MM/yyyy")) self.lineEditPais.setText(datos[5]) self.lineEditTelCel.setText(datos[6]) return def Actualizar(self): nombre = " ".join(self.lineEditNombre.text().split()).title() apellido = " ".join(self.lineEditApellido.text().split()).title() sexo = self.comboBoxSexo.currentText() fecNacimiento = self.dateEditFechaNacimiento.text() pais = " ".join(self.lineEditPais.text().split()).title() telCel = self.lineEditTelCel.text() if not nombre: self.lineEditNombre.setFocus() elif not apellido: self.lineEditApellido.setFocus() elif not sexo: self.comboBoxSexo.setFocus() elif not pais: self.lineEditPais.setFocus() elif not telCel: self.lineEditTelCel.setFocus() else: if QFile.exists("DB_SIACLE/DB_SIACLE.db"): conexion = sqlite3.connect("DB_SIACLE/DB_SIACLE.db") cursor = conexion.cursor() try: datos = [nombre, apellido, sexo, fecNacimiento, pais, telCel, self.datos[0]] cursor.execute("UPDATE CLIENTES SET NOMBRE = ?, APELLIDO = ?, SEXO = ?, " "FECHA_NACIMIENTO = ?, PAIS = ?, TELEFONO_CELULAR = ? " "WHERE ID = ?", datos) conexion.commit() conexion.close() nuevos_datos = (str(self.datos[0]), nombre, apellido, sexo, fecNacimiento, pais, telCel) self.parent.tabla.removeRow(self.indice) numFilas = self.parent.tabla.rowCount() self.parent.tabla.insertRow(numFilas) for indice, dato in enumerate(nuevos_datos): dato = QTableWidgetItem(dato) if indice == 0: dato.setTextAlignment(Qt.AlignCenter) self.parent.tabla.setItem(numFilas, indice, dato) self.lineEditNombre.clear() self.lineEditApellido.clear() self.comboBoxSexo.setCurrentIndex(-1) self.dateEditFechaNacimiento.setDate(QDate.currentDate()) self.lineEditPais.clear() self.lineEditTelCel.clear() QMessageBox.information(self, "Actualizar cliente", "Cliente actualizado." " ", QMessageBox.Ok) self.close() except: conexion.close() QMessageBox.critical(self, "Actualizar cliente", "Error desconocido. ", QMessageBox.Ok) else: QMessageBox.critical(self, "Actualizar cliente", "No se encontro la base de " "datos. ", QMessageBox.Ok)
class AddEmployeeDetails(QMainWindow): closing = pyqtSignal(int) def __init__(self, parent, update, id=None): super().__init__(parent) self.parent = parent self.db = DB() self.initUI(update, id) def initUI(self, update, id): self.setWindowModality(Qt.ApplicationModal) frame = QFrame() # frame.setStyleSheet("background-color: rgb(30, 45, 66);") frame.setFrameShape(QFrame.StyledPanel) frame.setFrameShadow(QFrame.Raised) # frame.setMinimumWidth(430) # frame.setFixedHeight(395) frame.setStyleSheet("border: none") add_employee_button = QLabel(frame) add_employee_button.setAlignment(Qt.AlignCenter) add_employee_button.setGeometry(QRect(110, 30, 210, 41)) add_employee_button.setStyleSheet("font: 75 12pt \"MS Shell Dlg 2\";\n" "background-color: rgb(30, 45, 66);\n" "color: rgb(255, 255, 255);") add_employee_button.setText("Add Employee Details") # name = QHBoxLayout() # jobtitle = QHBoxLayout() # salary = QHBoxLayout() # bonus = QHBoxLayout() # joindate = QHBoxLayout() namelabel = QLabel(frame) namelabel.setText("Name") namelabel.setGeometry(QRect(80, 100, 47, 13)) self.nametextbox = QLineEdit(frame) self.nametextbox.setGeometry(QRect(160, 90, 181, 31)) self.nametextbox.setFixedWidth(180) jobtitlelabel = QLabel(frame) jobtitlelabel.setText("Job Title") jobtitlelabel.setGeometry(QRect(80, 140, 61, 16)) self.jobtitletextbox = QComboBox(frame) self.jobtitletextbox.setGeometry(QRect(160, 130, 181, 31)) self.jobtitletextbox.setFixedWidth(180) self.jobtitletextbox.addItems(["Manager", "Waiter", "Chef", "Security"]) salarylabel = QLabel(frame) salarylabel.setText("Salary") salarylabel.setGeometry(QRect(80, 180, 47, 13)) self.salarytextbox = QLineEdit(frame) self.salarytextbox.setGeometry(QRect(160, 170, 181, 31)) self.salarytextbox.setFixedWidth(180) self.salarytextbox.setValidator(QIntValidator()) # bonuslabel = QLabel(frame) # bonuslabel.setText("Bonus") # bonuslabel.setGeometry(QRect(80, 220, 47, 13)) # bonustextbox = QLineEdit(frame) # bonustextbox.setGeometry(QRect(160, 210, 181, 31)) # bonustextbox.setFixedWidth(180) joindatelabel = QLabel(frame) joindatelabel.setText("Start Date") joindatelabel.setGeometry(QRect(80, 260, 71, 16)) self.joindatetextbox = QDateEdit(frame) self.joindatetextbox.setGeometry(QRect(160, 250, 181, 31)) self.joindatetextbox.setFixedWidth(180) self.joindatetextbox.setDate(QDate.currentDate()) self.joindatetextbox.setMinimumDate(QDate.currentDate()) self.joindatetextbox.setDisplayFormat("dd-MM-yyyy") self.addbutton = QPushButton(frame) self.addbutton.setGeometry(QRect(160, 300, 111, 31)) self.addbutton.setStyleSheet("font: 75 12pt \"MS Shell Dlg 2\";\n" "background-color: rgb(30, 45, 66);\n" "color: rgb(255, 255, 255);") if update == 'add': print("Add") print(id) self.addbutton.setText("Add Employee") self.addbutton.clicked.connect(lambda: self.add_button_click("employee")) else: print("Update") print(id) self.addbutton.setText("Update Employee") self.addbutton.clicked.connect(lambda: self.update_button_click("employee", id)) layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(frame) centralWidget = QWidget() centralWidget.setLayout(layout) self.setCentralWidget(centralWidget) # self.setLayout(layout) self.setWindowTitle("Add Employee Details") self.resize(430, 395) self.show() self.center() def center(self): '''centers the window on the screen''' screen = QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2) def update_button_click(self, where, id): if where == "employee": print("Employees Finally here") print(self.nametextbox.text()) print(self.jobtitletextbox.currentText()) print(self.salarytextbox.text()) print(self.joindatetextbox.text()) employee_name = self.nametextbox.text() job_title = self.jobtitletextbox.currentText() salary = self.salarytextbox.text() try: date = datetime.datetime.strptime(self.joindatetextbox.text(), "%d-%m-%Y") joining_date = datetime.datetime.strftime(date, "%Y-%m-%d") except: ''' Make sure to add an error message. ''' return if employee_name != "" and salary != "": query = "update employee set `employee_name`=%s, `job_title`=%s, `salary`=%s, " \ "`joining_date`=%s where id=%s" values = (employee_name, job_title, salary, joining_date, id) result = self.db.execute(query, values) self.closeEvent = self.message() def add_button_click(self, where): if where == "employee": print("Employees Finally here") print(self.nametextbox.text()) print(self.jobtitletextbox.currentText()) print(self.salarytextbox.text()) print(self.joindatetextbox.text()) employee_name = self.nametextbox.text() job_title = self.jobtitletextbox.currentText() salary = self.salarytextbox.text() try: date = datetime.datetime.strptime(self.joindatetextbox.text(), "%d-%m-%Y") joining_date = datetime.datetime.strftime(date, "%Y-%m-%d") except: ''' Make sure to add an error message. ''' return if employee_name != "" and salary != "": query = "insert into employee (`employee_name`, `job_title`,`salary`, `joining_date`)" \ "values (%s, %s, %s, %s);" values = (employee_name, job_title, salary, joining_date) result = self.db.execute(query, values) self.closeEvent = self.message() def message(self): self.closing.emit(1) self.close() # def closeEvent(self, event): # print("Closed") # self.closing.emit() # # self.parent.update()
class TaskView(QWidget): close = pyqtSignal() def __init__(self, model): super().__init__() self.header = QLabel('') self.desc = QLineEdit() self.date = QDateEdit() self.time = QTimeEdit() self.init_ui() self.mapper = QDataWidgetMapper() self.mapper.setModel(model) self.mapper.setSubmitPolicy(QDataWidgetMapper.ManualSubmit) self.mapper.addMapping(self.desc, TaskModel.col_desc) self.mapper.addMapping(self.date, TaskModel.col_date) self.mapper.addMapping(self.time, TaskModel.col_time) def set_task(self, index): self.mapper.setCurrentIndex(index) self.header.setText('РЕДАКТИРОВАНИЕ ЗАДАЧИ') # text = 'НОВАЯ ЗАДАЧА' # self.date.setDate(QDate().currentDate()) def create_date(self): self.date.setDisplayFormat('dd.MM.yyyy') self.date.setCalendarPopup(True) self.date.setFixedWidth(120) return self.date def create_time(self): self.time.setDisplayFormat('hh.mm') self.time.setFixedWidth(120) return self.time def create_date_buttons(self): date_lt = QHBoxLayout() btn_now = QPushButton('сегодня') btn_now.clicked.connect(lambda: self.date.setDate(QDate().currentDate())) date_lt.addWidget(btn_now, 0, Qt.AlignCenter) btn_tomorrow = QPushButton('завтра') btn_tomorrow.clicked.connect(lambda: self.date.setDate(QDate().currentDate().addDays(1))) date_lt.addWidget(btn_tomorrow, 0, Qt.AlignCenter) btn_week_later = QPushButton('через неделю') btn_week_later.clicked.connect(lambda: self.date.setDate(QDate().currentDate().addDays(7))) date_lt.addWidget(btn_week_later, 0, Qt.AlignCenter) return date_lt # def create_time_choice(self): # self.time.setMaxVisibleItems(15) # self.time.setStyleSheet('QComboBox { combobox-popup: 0; }') # for it in range(24): # self.time.insertItem(it * 2 + 0, '%.2d:00' % it) # self.time.insertItem(it * 2 + 1, '%.2d:30' % it) # # return self.time def save(self): print('save', self.mapper.submit()) self.close.emit() def cancel(self): self.close.emit() def remove(self): self.mapper.model().removeRow(self.mapper.currentIndex()) self.close.emit() def create_control_buttons(self): control_lt = QHBoxLayout() btn_save = QPushButton('Сохранить') btn_save.clicked.connect(self.save) control_lt.addWidget(btn_save, 0, Qt.AlignCenter) btn_cancel = QPushButton('Отменить') btn_cancel.clicked.connect(self.cancel) control_lt.addWidget(btn_cancel, 0, Qt.AlignCenter) btn_remove = QPushButton('Удалить') btn_remove.clicked.connect(self.remove) control_lt.addWidget(btn_remove, 1, Qt.AlignRight) return control_lt def create_main_form(self): fm = QFormLayout() fm.addRow(self.header) fm.addRow(QLabel('')) fm.addRow(self.desc) fm.addRow(QLabel('')) fm.addRow(QLabel('Когда это нужно сделать?')) fm.addRow(self.create_date()) fm.addRow(self.create_date_buttons()) fm.addRow(QLabel('')) fm.addRow(QLabel('Во сколько?')) fm.addRow(self.create_time()) return fm def init_ui(self): layout = QVBoxLayout() layout.addLayout(self.create_main_form()) layout.addStretch() layout.addLayout(self.create_control_buttons()) self.setLayout(layout)