class Window(QWidget):

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

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

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

        self.edit1.setMinimumDate(datetime.date(year=2017, month=9, day=1))
        self.edit2.setMinimumDate(datetime.date(year=2017, month=9, day=1))
        self.edit3.setMinimumDate(datetime.date(year=2017, month=9, day=1))

        self.edit1.setMaximumDate(datetime.date(year=2020, month=9, day=1))
        self.edit2.setMaximumDate(datetime.date(year=2020, month=9, day=1))
        self.edit3.setMaximumDate(datetime.date(year=2020, month=9, day=1))

        self.edit1.setDate(datetime.datetime.now().date())
        self.edit2.setDate(datetime.datetime.now().date())
        self.edit3.setDate(datetime.datetime.now().date())

        self.edit1.setCalendarPopup(True)
        self.edit2.setCalendarPopup(True)
        self.edit3.setCalendarPopup(True)

        # Format: see http://doc.qt.io/qt-5/qdatetime.html#toString-2
        self.edit1.setDisplayFormat("yyyy-MM-dd")
        self.edit2.setDisplayFormat("dd/MM/yyyy")
        self.edit3.setDisplayFormat("dddd d MMMM yyyy")

        self.btn = QPushButton("Print")

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

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

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

        vbox = QVBoxLayout()

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

        vbox.addWidget(self.btn)

        self.setLayout(vbox)

    def printText(self):
        print(self.edit1.text())
        print(self.edit2.text())
        print(self.edit3.text())
class EditWindow(QWidget):
    """Käyttöliittymäluokka edit-ikkunalle. Perii QWidget-luokan.
    
    Attributes:
        id: elokuvan id
        title: elokuvan nimi
    """
    def __init__(self, movie_id, movie_title, movie_release):
        """Luokan konstruktori.

        Args:
            movie_id: elokuvan tietokanta-id
            movie_title: elokuvan nimi
            movie_release: elokuvan julkaisupäivä
        """

        super().__init__()
        self.id = movie_id
        self.title = movie_title
        self.release = movie_release
        self.setup_ui()

    def setup_ui(self):
        """Alustaa ikkunan käyttöliittymäkomponentit.
        """

        minimum_date = QDate.fromString(self.release, "yyyy-MM-dd")
        maximum_date = QDate.currentDate()
        self.title_label = QLabel(self.title)
        self.review_label = QLabel("Review:")
        self.watch_date_label = QLabel("Watch date:")
        self.review_entry = QComboBox()
        self.watch_date_entry = QDateEdit(QDate.currentDate())
        self.watch_date_entry.setDisplayFormat("yyyy-MM-dd")
        self.watch_date_entry.setMinimumDate(minimum_date)
        self.watch_date_entry.setMaximumDate(maximum_date)
        self.update_button = QPushButton("Update")
        self.review_entry.addItems(
            ["", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"])
        self.setup_layout()

    def setup_layout(self):
        """Alustaa ikkunan käyttöliittymäasettelun
        """

        layout = QVBoxLayout()
        review_layout = QHBoxLayout()
        watch_date_layout = QHBoxLayout()
        review_layout.addWidget(self.review_label)
        review_layout.addWidget(self.review_entry)
        watch_date_layout.addWidget(self.watch_date_label)
        watch_date_layout.addWidget(self.watch_date_entry)
        layout.addWidget(self.title_label)
        layout.addLayout(review_layout)
        layout.addLayout(watch_date_layout)
        layout.addWidget(self.update_button)

        self.setLayout(layout)
Example #3
0
    def initWidget(self):
        layout = QGridLayout(self)
        layout.setSpacing(0)

        # lbl = QLabel()
        # lbl.setText(self.inputName)
        # lbl.setContentsMargins(-10,10,10,10)

        dateDiff = math.floor(
            (self.maxValue.year() - self.minValue.year()) / 2
        )  # difference between the first date and last date, used to handle min and max values for the sliders

        minScroller = QSlider(Qt.Horizontal, self)
        minScroller.setMinimum(self.minValue.year())
        minScroller.setMaximum(self.maxValue.year())
        minScroller.setTickInterval(1)
        minScroller.setSingleStep(1)
        minScroller.setSliderPosition(self.minValue.year())

        maxScroller = QSlider(Qt.Horizontal, self)
        maxScroller.setMinimum(self.minValue.year())
        maxScroller.setMaximum(self.maxValue.year())
        maxScroller.setTickInterval(1)
        maxScroller.setSingleStep(1)
        maxScroller.setSliderPosition(self.maxValue.year())

        minEdit = QDateEdit()
        minEdit.setDate(self.minValue)
        minEdit.setDisplayFormat("yyyy")
        minEdit.setMinimumDate(self.minValue)
        minEdit.setMaximumDate(self.maxValue)

        maxEdit = QDateEdit()
        maxEdit.setDate(self.maxValue)
        maxEdit.setDisplayFormat("yyyy")
        maxEdit.setMaximumDate(self.maxValue)
        maxEdit.setMinimumDate(self.minValue)

        minScroller.valueChanged.connect(self._updateMinEdit)
        minEdit.dateChanged.connect(self._updateMinSlider)
        maxScroller.valueChanged.connect(self._updateMaxEdit)
        maxEdit.dateChanged.connect(self._updateMaxSlider)

        # layout.addWidget(lbl,0,0,0,1,QtCore.Qt.AlignCenter)

        layout.addWidget(minScroller, 1, 2)
        layout.addWidget(minEdit, 1, 3)

        layout.addWidget(maxScroller, 2, 2)
        layout.addWidget(maxEdit, 2, 3)

        self.setLayout(layout)
        self.minScroller = minScroller
        self.minEdit = minEdit
        self.maxEdit = maxEdit
        self.maxScroller = maxScroller
    def createEditor(self, parent, option, index):
        editor = QDateEdit(parent=parent)

        editor.setMinimumDate(datetime.datetime(year=2017, month=9, day=1))
        editor.setMaximumDate(datetime.datetime(year=2020, month=9, day=1))
        editor.setDisplayFormat("yyyy-MM-dd")
        editor.setCalendarPopup(True)

        # setFrame(): tell whether the line edit draws itself with a frame.
        # If enabled (the default) the line edit draws itself inside a frame, otherwise the line edit draws itself without any frame.
        editor.setFrame(False)

        return editor
    def createEditor(self, parent, option, index):
        editor = QDateEdit(parent=parent)

        editor.setMinimumDate(datetime.datetime(year=2017, month=9, day=1))
        editor.setMaximumDate(datetime.datetime(year=2020, month=9, day=1))
        editor.setDisplayFormat("yyyy-MM-dd")
        editor.setCalendarPopup(True)

        # setFrame(): tell whether the line edit draws itself with a frame.
        # If enabled (the default) the line edit draws itself inside a frame, otherwise the line edit draws itself without any frame.
        editor.setFrame(False)

        return editor
Example #6
0
 def createEditor(self, parent, option, index):
     if (index.column() == ACTIONID and index.model().data(
             index, Qt.DisplayRole) == ACQUIRED):  # Acquired is read-only
         return
     if index.column() == DATE:
         editor = QDateEdit(parent)
         editor.setMaximumDate(QDate.currentDate())
         editor.setDisplayFormat("yyyy-MM-dd")
         if PYQT_VERSION_STR >= "4.1.0":
             editor.setCalendarPopup(True)
         editor.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
         return editor
     else:
         return QSqlRelationalDelegate.createEditor(self, parent, option,
                                                    index)
Example #7
0
    def initUI(self):
        lbl = QLabel('QDateEdit')

        dateedit = QDateEdit(self)
        dateedit.setDate(QDate.currentDate())
        dateedit.setMinimumDate(QDate(1900, 1, 1))
        dateedit.setMaximumDate(QDate(2100, 12, 31))
        # dateedit.setDateRange(QDate(1900, 1, 1), QDate(2100, 12, 31))

        vbox = QVBoxLayout()
        vbox.addWidget(lbl)
        vbox.addWidget(dateedit)
        vbox.addStretch()

        self.setLayout(vbox)

        self.show_basic()
    def initUI(self):
        label = QLabel('QDateEdit')

        date_edit = QDateEdit(self)
        date_edit.setDate(QDate.currentDate())
        date_edit.setMinimumDate(QDate(1900, 1, 1))
        date_edit.setMaximumDate(QDate(2100, 12, 31))
        # date_edit.setDateRange(QDate(1900, 1, 1), QDate(2100, 12, 31))

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

        self.setLayout(vbox)

        self.setWindowTitle('QDateEdit')
        self.setGeometry(300, 300, 300, 200)
        self.show()
class MyApp(QWidget):

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

    def initUI(self):
        lbl = QLabel('QDateEdit')

        self.dateEditWidget = QDateEdit()
        # theDate = QDate()
        # self.dateEditWidget.setDate(theDate.currentDate())    # 현재 날짜
        # theDate.setDate()
        # self.dateEditWidget.setDate(QDate.currentDate())    # 현재 날짜
        self.dateEditWidget.setMinimumDate(QDate(2000, 1, 1))
        self.dateEditWidget.setMaximumDate(QDate(2100, 12, 31))
        self.dateEditWidget.setDisplayFormat('yyyy.MM.dd')
        self.dateEditWidget.setCalendarPopup(True)
        self.dateEditWidget.setDate(QDate(2020, 5, 1))    # 지정한 날짜

        # self.dateEditWidget.setDate(QDate.currentDate())

        self.dateEditWidget.dateChanged.connect(self.__dateChanged)

        vbox = QVBoxLayout()
        vbox.addWidget(lbl)
        vbox.addWidget(self.dateEditWidget)
        vbox.addStretch()

        self.setLayout(vbox)

        self.setWindowTitle('QDateEdit')
        self.setGeometry(300, 300, 300, 200)

    def __dateChanged(self):
        varQDate = self.dateEditWidget.date()   # QDate
        print(varQDate)
        print(varQDate.toString('yyyy-MM-dd'))
        print(f'Year:{varQDate.year()} Month:{varQDate.month()} Day:{varQDate.day()}')
        print('5 Years later:\t', varQDate.addYears(5).toString('yyyy-MM-dd'))
        print('5 Months later:\t', varQDate.addMonths(5).toString('yyyy-MM-dd'))
        print('5 Days later:\t', varQDate.addDays(5).toString('yyyy-MM-dd'))
Example #10
0
    def initUI(self):
        lbl = QLabel('QDateEdit')

        dateedit = QDateEdit(self)
        dateedit.setDate(QDate.currentDate())
        dateedit.setMinimumDate(QDate(1900, 1, 1))
        dateedit.setMaximumDate(QDate(2100, 12, 31))
        # QDateEdit 클래스를 이용해서 날짜 편집 위젯을 하나 만들어줍니다.
        #
        # setDate 메서드에 QDate.currentDate()를 입력해서 프로그램이 실행될 때
        # 현재 날짜로 표시되도록 합니다.
        #
        # setMinimumDate와 setMaximumDate를 이용하면 사용자가
        # 선택할 수 있는 날짜의 범위를 제한할 수 있습니다.
        #
        # 최소 날짜는 디폴트로 1752년 9월 14일로 설정되어 있고,
        # 최대 날짜는 9999년 12월 31일로 설정되어 있습니다.
        #
        # 최소 날짜는 최소 100년 1월 1일 이상이어야합니다.

        # dateedit.setDateRange(QDate(1900, 1, 1), QDate(2100, 12, 31))
        # setDateRange 메서드는 setMinimumDate와 setMaximumDate를
        # 동시에 사용하는 것과 같습니다.

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

        self.setLayout(vbox)

        self.setWindowTitle('QDateEdit')
        self.setGeometry(300, 300, 300, 200)
        self.show()
Example #11
0
class Window(QWidget):
    def __init__(self):
        super().__init__()

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

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

        self.edit1.setMinimumDate(datetime.date(year=2017, month=9, day=1))
        self.edit2.setMinimumDate(datetime.date(year=2017, month=9, day=1))
        self.edit3.setMinimumDate(datetime.date(year=2017, month=9, day=1))

        self.edit1.setMaximumDate(datetime.date(year=2020, month=9, day=1))
        self.edit2.setMaximumDate(datetime.date(year=2020, month=9, day=1))
        self.edit3.setMaximumDate(datetime.date(year=2020, month=9, day=1))

        self.edit1.setDate(datetime.datetime.now().date())
        self.edit2.setDate(datetime.datetime.now().date())
        self.edit3.setDate(datetime.datetime.now().date())

        self.edit1.setCalendarPopup(True)
        self.edit2.setCalendarPopup(True)
        self.edit3.setCalendarPopup(True)

        # Format: see http://doc.qt.io/qt-5/qdatetime.html#toString-2
        self.edit1.setDisplayFormat("yyyy-MM-dd")
        self.edit2.setDisplayFormat("dd/MM/yyyy")
        self.edit3.setDisplayFormat("dddd d MMMM yyyy")

        self.btn = QPushButton("Print")

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

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

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

        vbox = QVBoxLayout()

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

        vbox.addWidget(self.btn)

        self.setLayout(vbox)

    def printText(self):
        print(self.edit1.text())
        print(self.edit2.text())
        print(self.edit3.text())
Example #12
0
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)
Example #13
0
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()
Example #14
0
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)
Example #15
0
class Widget(QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        self._initUI()
        self.controller = _Controller(self)
        self.requireDepartments.emit()

    _requireDepartments = pyqtSignal(name='requireDepartments')
    _requireRooms = pyqtSignal(str, name='requireRooms')

    def refresh(self):
        self.requireDepartments.emit()
        self.idEdit.setFocus()

    def setDepartments(self, array):
        self.departmentCmb.clear()
        self.departmentCmb.addItems(array)
        self.requireRooms.emit(self.department)

    def setRooms(self, array):
        self.roomsCmb.clear()
        self.roomsCmb.addItems(array)

    def _initUI(self):
        self.idLabel = QLabel('Id')
        self.nameLabel = QLabel('Name')
        self.modelLabel = QLabel('Model')
        self.costLabel = QLabel('Cost')
        self.purchaseDateLabel = QLabel('Purchase date')
        self.departmentLabel = QLabel('Department')
        self.roomLabel = QLabel('Room')

        self.idEdit = QLineEdit()
        self.idEdit.setPlaceholderText('Use for editing/removing operations')
        self.nameEdit = QLineEdit()
        self.modelEdit = QLineEdit()
        self.costEdit = QLineEdit()
        self.purchaseDateEdit = QDateEdit()
        self.purchaseDateEdit.setDisplayFormat('dd.MM.yyyy')
        self.purchaseDateEdit.setCalendarPopup(True)
        self.purchaseDateEdit.setDate(QDate.currentDate())
        self.purchaseDateEdit.setMinimumDate(QDate(1900, 1, 1))
        self.purchaseDateEdit.setMaximumDate(QDate(2099, 31, 12))
        self.departmentCmb = QComboBox()
        self.roomsCmb = QComboBox()

        self.submitButton = QPushButton('Submit')
        self.editButton = QPushButton('Edit')
        self.removeButton = QPushButton('Remove')

        layout = QVBoxLayout()
        layout.addWidget(self.idLabel)
        layout.addWidget(self.idEdit)
        layout.addSpacing(20)
        layout.addWidget(self.nameLabel)
        layout.addWidget(self.nameEdit)
        layout.addSpacing(10)
        layout.addWidget(self.modelLabel)
        layout.addWidget(self.modelEdit)
        layout.addSpacing(10)
        layout.addWidget(self.costLabel)
        layout.addWidget(self.costEdit)
        layout.addSpacing(10)
        layout.addWidget(self.purchaseDateLabel)
        layout.addWidget(self.purchaseDateEdit)
        layout.addSpacing(10)
        layout.addWidget(self.departmentLabel)
        layout.addWidget(self.departmentCmb)
        layout.addSpacing(10)
        layout.addWidget(self.roomLabel)
        layout.addWidget(self.roomsCmb)
        layout.addStretch(2)
        layout.addWidget(self.submitButton)
        layout.addWidget(self.editButton)
        layout.addWidget(self.removeButton)

        hlayout = QHBoxLayout()
        hlayout.addStretch()
        hlayout.addLayout(layout)
        hlayout.addStretch()

        self.setLayout(hlayout)

    @property
    def id(self):
        return self.idEdit.text()

    @id.setter
    def id(self, value):
        self.idEdit.setText(value)

    @property
    def name(self):
        return self.nameEdit.text()

    @name.setter
    def name(self, value):
        self.nameEdit.setText(value)

    @property
    def model(self):
        return self.modelEdit.text()

    @model.setter
    def model(self, value):
        self.modelEdit.setText(value)

    @property
    def cost(self):
        return self.costEdit.text()

    @cost.setter
    def cost(self, value):
        self.costEdit.setText(value)

    @property
    def purchaseDate(self):
        return self.purchaseDateEdit.date().toPyDate()

    @property
    def department(self):
        return self.departmentCmb.currentText()

    @property
    def room(self):
        return self.roomsCmb.currentText()
Example #16
0
class EntryEditDialog(QDialog):
    GROUP_NAME = ''
    ORGANIZATION_NAME = ''

    def __init__(self, person, is_new=False):
        super().__init__(GlobalAccess().get_main_window())
        self.is_ok = {}
        assert (isinstance(person, Person))
        self.current_object = person
        self.is_new = is_new

        self.time_format = 'hh:mm:ss'
        time_accuracy = race().get_setting('time_accuracy', 0)
        if time_accuracy:
            self.time_format = 'hh:mm:ss.zzz'

    def exec(self):
        self.init_ui()
        self.set_values_from_model()
        return super().exec()

    def init_ui(self):
        self.setWindowTitle(_('Entry properties'))
        self.setWindowIcon(QIcon(config.ICON))
        self.setSizeGripEnabled(False)
        self.setModal(True)

        self.layout = QFormLayout(self)
        self.label_surname = QLabel(_('Last name'))
        self.item_surname = QLineEdit()
        self.layout.addRow(self.label_surname, self.item_surname)

        self.label_name = QLabel(_('First name'))
        self.item_name = AdvComboBox()
        self.item_name.addItems(get_names())
        self.layout.addRow(self.label_name, self.item_name)

        self.label_group = QLabel(_('Group'))
        self.item_group = AdvComboBox()
        self.item_group.addItems(get_race_groups())
        self.layout.addRow(self.label_group, self.item_group)

        self.label_team = QLabel(_('Team'))
        self.item_team = AdvComboBox()
        self.item_team.addItems(get_race_teams())
        self.layout.addRow(self.label_team, self.item_team)

        use_birthday = Config().configuration.get('use_birthday', False)
        if use_birthday:
            self.label_birthday = QLabel(_('Birthday'))
            self.item_birthday = QDateEdit()
            self.item_birthday.setObjectName('BirthdayDateEdit')
            self.item_birthday.setDate(date.today())
            self.item_birthday.setMaximumDate(date.today())
            self.layout.addRow(self.label_birthday, self.item_birthday)
        else:
            self.label_year = QLabel(_('Year of birth'))
            self.item_year = QSpinBox()
            self.item_year.setObjectName('YearSpinBox')
            self.item_year.setMinimum(0)
            self.item_year.setMaximum(date.today().year)
            self.item_year.editingFinished.connect(self.year_change)
            self.layout.addRow(self.label_year, self.item_year)

        self.label_qual = QLabel(_('Qualification'))
        self.item_qual = AdvComboBox()
        for i in list(Qualification):
            self.item_qual.addItem(i.get_title())
        self.layout.addRow(self.label_qual, self.item_qual)

        self.is_ok['bib'] = True
        self.label_bib = QLabel(_('Bib'))
        self.item_bib = QSpinBox()
        self.item_bib.setMinimum(0)
        self.item_bib.setMaximum(Limit.BIB)
        self.item_bib.valueChanged.connect(self.check_bib)
        self.layout.addRow(self.label_bib, self.item_bib)

        self.label_bib_info = QLabel('')
        self.layout.addRow(QLabel(''), self.label_bib_info)

        self.label_start = QLabel(_('Start time'))
        self.item_start = QTimeEdit()
        self.item_start.setDisplayFormat(self.time_format)
        self.layout.addRow(self.label_start, self.item_start)

        self.label_start_group = QLabel(_('Start group'))
        self.item_start_group = QSpinBox()
        self.item_start_group.setMinimum(0)
        self.item_start_group.setMaximum(99)
        self.layout.addRow(self.label_start_group, self.item_start_group)

        self.is_ok['card'] = True
        self.label_card = QLabel(_('Punch card #'))
        self.item_card = QSpinBox()
        self.item_card.setMinimum(0)
        self.item_card.setMaximum(9999999)
        self.item_card.valueChanged.connect(self.check_card)
        self.layout.addRow(self.label_card, self.item_card)

        self.label_card_info = QLabel('')
        self.layout.addRow(QLabel(''), self.label_card_info)

        self.item_rented = QCheckBox(_('rented card'))
        self.item_paid = QCheckBox(_('is paid'))
        self.item_out_of_competition = QCheckBox(_('out of competition'))
        self.item_personal = QCheckBox(_('personal participation'))
        self.layout.addRow(self.item_rented, self.item_out_of_competition)
        self.layout.addRow(self.item_paid, self.item_personal)

        self.label_comment = QLabel(_('Comment'))
        self.item_comment = QTextEdit()
        self.item_comment.setTabChangesFocus(True)
        self.layout.addRow(self.label_comment, self.item_comment)

        def cancel_changes():
            self.close()

        def apply_changes():
            try:
                self.apply_changes_impl()
            except Exception as e:
                logging.error(str(e))
            self.close()

        button_box = QDialogButtonBox(QDialogButtonBox.Ok
                                      | QDialogButtonBox.Cancel)
        self.button_ok = button_box.button(QDialogButtonBox.Ok)
        self.button_ok.setText(_('OK'))
        self.button_ok.clicked.connect(apply_changes)
        self.button_cancel = button_box.button(QDialogButtonBox.Cancel)
        self.button_cancel.setText(_('Cancel'))
        self.button_cancel.clicked.connect(cancel_changes)
        self.layout.addRow(button_box)

        self.show()

    def year_change(self):
        """
        Convert 2 digits of year to 4
        2 -> 2002
        11 - > 2011
        33 -> 1933
        56 -> 1956
        98 - > 1998
        0 -> 0 exception!
        """
        widget = self.sender()
        assert isinstance(widget, QSpinBox)
        year = widget.value()
        if 0 < year < 100:
            cur_year = date.today().year
            new_year = cur_year - cur_year % 100 + year
            if new_year > cur_year:
                new_year -= 100
            widget.setValue(new_year)

    def items_ok(self):
        ret = True
        for item_name in self.is_ok.keys():
            if self.is_ok[item_name] is not True:
                ret = False
                break
        return ret

    def check_bib(self):
        bib = self.item_bib.value()
        self.label_bib_info.setText('')
        if bib:
            person = find(race().persons, bib=bib)
            if person:
                if person.bib == self.current_object.bib:
                    self.button_ok.setEnabled(True)
                    return
                self.button_ok.setDisabled(True)
                self.is_ok['bib'] = False
                info = '{}\n{}'.format(_('Number already exists'),
                                       person.full_name)
                if person.group:
                    info = '{}\n{}: {}'.format(info, _('Group'),
                                               person.group.name)
                self.label_bib_info.setText(info)
            else:
                self.label_bib_info.setText(_('Number is unique'))
                self.is_ok['bib'] = True
                if self.items_ok():
                    self.button_ok.setEnabled(True)
        else:
            self.button_ok.setEnabled(True)

    def check_card(self):
        number = self.item_card.value()
        self.label_card_info.setText('')
        if number:
            person = None
            for _p in race().persons:
                if _p.card_number and _p.card_number == number:
                    person = _p
                    break
            if person:
                if person.card_number == self.current_object.card_number:
                    self.button_ok.setEnabled(True)
                    return
                self.button_ok.setDisabled(True)
                self.is_ok['card'] = False
                info = '{}\n{}'.format(_('Card number already exists'),
                                       person.full_name)
                if person.group:
                    info = '{}\n{}: {}'.format(info, _('Group'),
                                               person.group.name)
                if person.bib:
                    info = '{}\n{}: {}'.format(info, _('Bib'), person.bib)
                self.label_card_info.setText(info)
            else:
                self.label_card_info.setText(_('Card number is unique'))
                self.is_ok['card'] = True
                if self.items_ok():
                    self.button_ok.setEnabled(True)
        else:
            self.button_ok.setEnabled(True)

    def set_values_from_model(self):
        self.item_surname.setText(self.current_object.surname)
        self.item_surname.selectAll()
        self.item_name.setCurrentText(self.current_object.name)
        if self.current_object.group is not None:
            self.item_group.setCurrentText(self.current_object.group.name)
        else:
            self.item_group.setCurrentText(self.GROUP_NAME)
        if self.current_object.organization is not None:
            self.item_team.setCurrentText(
                self.current_object.organization.name)
        else:
            self.item_team.setCurrentText(self.ORGANIZATION_NAME)
        if self.current_object.qual:
            self.item_qual.setCurrentText(self.current_object.qual.get_title())
        if self.current_object.bib:
            self.item_bib.setValue(int(self.current_object.bib))
        if self.current_object.start_time is not None:
            time = time_to_qtime(self.current_object.start_time)
            self.item_start.setTime(time)
        if self.current_object.start_group is not None:
            self.item_start_group.setValue(int(
                self.current_object.start_group))

        if self.current_object.card_number:
            self.item_card.setValue(self.current_object.card_number)

        self.item_out_of_competition.setChecked(
            self.current_object.is_out_of_competition)
        self.item_paid.setChecked(self.current_object.is_paid)
        self.item_paid.setChecked(self.current_object.is_paid)
        self.item_personal.setChecked(self.current_object.is_personal)
        self.item_rented.setChecked(self.current_object.is_rented_card)

        self.item_comment.setText(self.current_object.comment)

        use_birthday = Config().configuration.get('use_birthday', False)
        if use_birthday:
            if self.current_object.birth_date:
                self.item_birthday.setDate(self.current_object.birth_date)
        else:
            if self.current_object.get_year():
                self.item_year.setValue(self.current_object.get_year())

    def apply_changes_impl(self):
        person = self.current_object
        assert (isinstance(person, Person))
        if self.is_new:
            race().persons.insert(0, person)
        if person.name != self.item_name.currentText():
            person.name = self.item_name.currentText()
        if person.surname != self.item_surname.text():
            person.surname = self.item_surname.text()
        if (person.group is not None and person.group.name != self.item_group.currentText()) or\
                (person.group is None and len(self.item_group.currentText()) > 0):
            person.group = find(race().groups,
                                name=self.item_group.currentText())
        if (person.organization is not None and person.organization.name != self.item_team.currentText()) or \
                (person.organization is None and len(self.item_team.currentText()) > 0):
            organization = find(race().organizations,
                                name=self.item_team.currentText())
            if organization is None:
                organization = Organization()
                organization.name = self.item_team.currentText()
                race().organizations.append(organization)
                Teamwork().send(organization.to_dict())
            person.organization = organization
        if person.qual.get_title() != self.item_qual.currentText():
            person.qual = Qualification.get_qual_by_name(
                self.item_qual.currentText())
        if person.bib != self.item_bib.value():
            person.bib = self.item_bib.value()

        new_time = time_to_otime(self.item_start.time())
        if person.start_time != new_time:
            person.start_time = new_time

        if person.start_group != self.item_start_group.value(
        ) and self.item_start_group.value():
            person.start_group = self.item_start_group.value()

        if (not person.card_number or int(person.card_number) != self.item_card.value()) \
                and self.item_card.value:
            race().person_card_number(person, self.item_card.value())

        if person.is_out_of_competition != self.item_out_of_competition.isChecked(
        ):
            person.is_out_of_competition = self.item_out_of_competition.isChecked(
            )

        if person.is_paid != self.item_paid.isChecked():
            person.is_paid = self.item_paid.isChecked()

        if person.is_rented_card != self.item_rented.isChecked():
            person.is_rented_card = self.item_rented.isChecked()

        if person.is_personal != self.item_personal.isChecked():
            person.is_personal = self.item_personal.isChecked()

        if person.comment != self.item_comment.toPlainText():
            person.comment = self.item_comment.toPlainText()

        use_birthday = Config().configuration.get('use_birthday', False)
        if use_birthday:
            new_birthday = qdate_to_date(self.item_birthday.date())
            if person.birth_date != new_birthday and new_birthday:
                if person.birth_date or new_birthday != date.today():
                    person.birth_date = new_birthday
        else:
            if person.get_year() != self.item_year.value():
                person.set_year(self.item_year.value())

        ResultCalculation(race()).process_results()
        GlobalAccess().get_main_window().refresh()
        Teamwork().send(person.to_dict())
class Tabless_Widget(QTableWidget):
    """
     subclass of QTableWidget. 
     Purpose to have signal-slot connection with Tree custom class
    """
    sig2 = pyqtSignal(int)
    sig2t = pyqtSignal(int, str, str, str, str)

    def __init__(self):
        super(Tabless_Widget, self).__init__()
        self.init_ui()

    def init_ui(self):
        self.sitetable1 = QTableWidget()
        self.status = QLabel()
        self.sitetable1.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.summary = QTextEdit()
        self.summary.setSizeAdjustPolicy(
            QtWidgets.QAbstractScrollArea.AdjustToContents)
        self.summary.setReadOnly(True)
        self.summary.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.summary.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.summary.setSizePolicy(
            QSizePolicy.Expanding,
            QSizePolicy.Expanding)  # horizontal, vertical
        self.summary.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.sitetable1.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)
        self.sitetable1.setShowGrid(False)
        self.sitetable1.setStyleSheet(
            'QTableView::item {background-color: white;}')

    def show_table_rows(self):
        for jj in range(self.sitetable1.rowCount()):
            self.sitetable1.showRow(jj)

    def make_connection_2_tree(self, tree_object):
        print("Make connection")
        tree_object.getExperiment.connect(self.get_tree)
        tree_object.getTreatment.connect(self.get_treatment)
        tree_object.getNewOperation.connect(self.get_operation)
        tree_object.getOperation.connect(self.get_existingoperation)
        tree_object.informUser.connect(self.informuser)
        #return cstatus

    @pyqtSlot(int, str, str)
    def get_tree(self, intval, str_experimentname, str_cropname):
        #print("debug: tablewithsignalslot:get_tree: val,cropname=",intval, str_cropname)
        if intval == 1:
            ### works only for avoiding silent crash on multiple clicks on ADD NEW Experiment
            if self.sitetable1.isVisible() == False:
                self.showNewExperimentDialog('New', str_cropname)
            self.sitetable1.setVisible(True)
        elif intval == 0:
            self.sitetable1.clear()
            self.sitetable1.reset()
            self.sitetable1.clearContents()
            self.sitetable1.setRowCount(0)
            self.sitetable1.setVisible(False)
        elif intval == 5:
            self.showDeleteExperimentDialog('Delete', str_experimentname,
                                            str_cropname)
            self.sitetable1.setVisible(True)

    @pyqtSlot(int, str, str, str)
    def get_treatment(self, intval, str_experimentname, str_cropname,
                      str_treatmentname):
        print("get_treatment works. val=", intval)
        if intval == 2:
            self.showNewTreatmentDialog(
                'New', str_experimentname,
                str_cropname)  #  experimentname,cropname
            self.sitetable1.setVisible(True)
        elif intval == 0:
            self.sitetable1.setVisible(False)
        elif intval == 6:
            if self.sitetable1.isHidden() == False:
                self.sitetable1.clear()
                self.sitetable1.reset()
                self.sitetable1.hide()
            #  experimentname,cropname
            self.showDeleteTreatmentDialog('Delete', str_experimentname,
                                           str_cropname, str_treatmentname)
            self.sitetable1.setVisible(True)

    @pyqtSlot(int, str)
    def informuser(self, intval, tree_str):
        print("informuser val & tree_str=", intval, tree_str)
        if intval == 0:
            self.showUserInformationDialog(
                'New Treatment Node addded',
                tree_str)  #  experimentname,cropname
        elif intval == 1:
            self.sitetable1.setVisible(False)

    @pyqtSlot(int, str, str, str)
    def get_operation(self, intval, strval1, strval2, strval3):
        print("get_operation works. val=", intval)
        if intval == 3:
            self.showNewOperationDialog(
                'New', strval1, strval2,
                strval3)  # treatmentname, experimentname,cropname
            self.sitetable1.setVisible(True)
        elif intval == 0:
            self.sitetable1.setVisible(False)

    @pyqtSlot(int, str, str, str, str, QModelIndex)
    def get_existingoperation(self, intval, strval1, strval2, strval3, strval4,
                              index):
        #print("Debug: tableWithSignalSlot.get_existingoperation() val=",intval)
        if intval == 4:
            # treatmentname, experimentname,cropname,operationname
            self.showExistingOperationDialog('New', strval1, strval2, strval3,
                                             strval4)
            self.sitetable1.setVisible(True)
        elif intval == 0:
            self.sitetable1.setVisible(False)

    def showUserInformationDialog(self, value, tree_str):
        """
        QTable object. This will inform the USER what to do after adding "Add new Experiment/Treatment/Operation"
        """
        self.savebutton1 = QPushButton("Ok")
        tmp_str2 = tree_str + "Treatment node added in the left panel. All operations are added. Please \
check their operations dates and correct them if needed."

        self.summary.setText(tmp_str2)
        self.sitetable1.clearContents()
        self.sitetable1.setRowCount(
            0)  # necessary. It will clean the table internally
        self.sitetable1.clear()
        self.sitetable1.reset()
        self.sitetable1.setRowCount(6)
        self.sitetable1.setColumnCount(2)
        self.show_table_rows()

        header = self.sitetable1.horizontalHeader()
        header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
        header.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)

        self.sitetable1.horizontalHeader().hide()
        self.sitetable1.verticalHeader().hide()
        self.sitetable1.setSpan(0, 0, 3, 2)
        self.sitetable1.setCellWidget(0, 0, self.summary)
        self.sitetable1.setCellWidget(4, 1, self.savebutton1)
        self.sitetable1.setVisible(True)
        self.sitetable1.resizeColumnsToContents()
        self.sitetable1.resizeRowsToContents()
        self.savebutton1.clicked.connect(self.on_okbutton_informuser_clicked)

    def showNewExperimentDialog(self, value, str_cropname):
        """
         QTable object. Ask user to enter the name of new experiment.
         Need to verify the USEr input is SAFE for database. After verification, insert this entry to 
         table: Experiment
        """
        self.strval = str_cropname
        self.cropname = str_cropname
        self.experimentname = QLineEdit()
        self.udialog = QLabel()
        regexp_alphanum = QtCore.QRegExp('\w+')
        validator_alphanum = QtGui.QRegExpValidator(regexp_alphanum)
        test1state = self.experimentname.setValidator(validator_alphanum)
        self.savebutton1 = QPushButton("Save")

        # creating local summary1 object as C++ class and python wrapper for it were not synching well
        # with operation of (delete/ create)
        # important; to have preserve a reference this way and proper cleaning of cell widget inside a
        # qtablewidget
        self.summary1 = QTextEdit(
            "EXPERIMENT Name represents broader hierarchical dataset name, for \
example `Summer 2018`. Underneath it, one can define specific TREATMENT. Provide a unique experiment \
name, click SAVE. Once it is registered in left panel, you add new treatment(s)"
        )
        self.summary1.setSizeAdjustPolicy(
            QtWidgets.QAbstractScrollArea.AdjustToContents)
        self.summary1.setReadOnly(True)
        self.summary1.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.summary1.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.summary1.setSizePolicy(
            QSizePolicy.Expanding,
            QSizePolicy.Expanding)  # horizontal, vertical
        self.summary1.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.sitetable1.clear()
        self.sitetable1.reset()
        self.sitetable1.clearContents()
        self.sitetable1.setRowCount(
            0)  # necessary. It will clean the table internally
        self.sitetable1.setRowCount(6)
        self.sitetable1.setColumnCount(2)
        self.show_table_rows()

        header = self.sitetable1.horizontalHeader()
        header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
        header.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)

        self.sitetable1.horizontalHeader().hide()
        self.sitetable1.verticalHeader().hide()
        self.sitetable1.setSpan(0, 0, 3, 2)
        self.sitetable1.setCellWidget(0, 0, self.summary1)
        self.sitetable1.setItem(3, 0,
                                QTableWidgetItem("Enter New Experiment Name"))
        self.sitetable1.setCellWidget(3, 1, self.experimentname)
        self.sitetable1.setCellWidget(4, 1, self.savebutton1)
        self.sitetable1.setCellWidget(5, 0, self.udialog)
        self.sitetable1.setVisible(True)
        self.sitetable1.resizeColumnsToContents()
        self.sitetable1.resizeRowsToContents()
        ##self.savebutton1.disconnect()
        self.savebutton1.clicked.connect(self.on_savebutton_experiment_clicked)

############## delete experiment

    def showDeleteExperimentDialog(self, value, str_experimentname,
                                   str_cropname):
        """
         Delete the experiment
         QTable object. 
        """
        self.cropname = str_cropname
        self.experimentname = QLineEdit(str_experimentname)
        self.experimentname.setReadOnly(True)
        self.udialog = QLabel()
        self.yesbutton = QPushButton("Yes")
        self.nobutton = QPushButton("No")
        self.sitetable1.clear()
        self.sitetable1.reset()
        self.sitetable1.clearContents()
        self.sitetable1.setRowCount(
            0)  # necessary. It will clean the table internally
        self.sitetable1.setRowCount(3)
        self.sitetable1.setColumnCount(2)
        self.show_table_rows()
        self.sitetable1.horizontalHeader().hide()
        self.sitetable1.verticalHeader().hide()
        self.sitetable1.setItem(
            0, 0, QTableWidgetItem("Do you want to delete the experiment:"))
        self.sitetable1.setCellWidget(0, 1, self.experimentname)
        self.sitetable1.setCellWidget(1, 0, self.yesbutton)
        self.sitetable1.setCellWidget(1, 1, self.nobutton)
        self.sitetable1.setCellWidget(2, 0, self.udialog)
        self.sitetable1.setVisible(True)
        self.sitetable1.resizeColumnsToContents()
        self.sitetable1.resizeRowsToContents()
        self.yesbutton.clicked.connect(self.on_yesbutton_experiment_clicked)
        self.nobutton.clicked.connect(self.on_nobutton_experiment_clicked)

    def on_okbutton_informuser_clicked(self):
        if self.sitetable1.isHidden() == False:
            self.sitetable1.clear()
            self.sitetable1.reset()
        #return true

    def on_savebutton_experiment_clicked(self, value):
        if len(self.experimentname.text()) == 0:
            self.udialog.setText(
                "Empty string. Please, provide valid EXPERIMENT name. Hint: Alphanumeric "
            )
        else:
            self.udialog.setText("")
            #call database insert command
            status = check_and_update_experimentDB(self.experimentname.text(),
                                                   self.cropname)
            if status:
                self.udialog.setText(
                    self.experimentname.text() +
                    " added in left panel and Add New Treatment to it.")
                if self.sitetable1.isHidden() == False:
                    self.sitetable1.hide()
                # goes to update3, insert data inot datatree instead of re-loading the datatree (causing crash, due
                # to improper handling)
                self.sig2t.emit(4, self.experimentname.text(), self.cropname,
                                "blank_treament", "blank_operation")
            else:
                self.udialog.setText(
                    "Experiment name exist. Use different name !!")

    def on_yesbutton_experiment_clicked(self, value):
        self.udialog.setText("")
        #call database delete command
        status = check_and_delete_experimentDB(self.experimentname.text(),
                                               self.cropname)
        print("status=", status)
        if status:
            print("status=", status)
            self.udialog.setText("Success " + self.experimentname.text())
            self.sitetable1.clear()
            self.sitetable1.hide()
            # this way no need to re-load the data after deletion. Delete from database and delete from tree
            self.sig2.emit(3)

    def on_nobutton_experiment_clicked(self, value):
        self.udialog.setText("ok, no action taken")
        self.sig2t.emit(2, self.experimentname.text(), self.strval)

    def on_yesbutton_treatment_clicked(self, value):
        self.udialog.setText("")
        #call database delete command
        status = 1
        status = check_and_delete_treatmentDB(self.treatmentname.text(),
                                              self.ename, self.cname)
        if status:
            self.udialog.setText("Success " + self.treatmentname.text())
            self.sitetable1.clear()
            self.sitetable1.reset()
            self.sitetable1.clearContents()
            self.sitetable1.setRowCount(
                0)  # necessary. It will clean the table internally
            self.sitetable1.hide()
            self.sig2.emit(6)

    def on_nobutton_treatment_clicked(self, value):
        self.sitetable1.clear()
        self.sitetable1.reset()
        self.sitetable1.clearContents()
        self.sitetable1.setRowCount(
            0)  # necessary. It will clean the table internally
        self.sitetable1.hide()

    def on_savebutton_treatment_clicked(self, value):
        if len(self.treatmentname.text()) == 0:
            self.udialog.setText(
                "Empty string. Please, provide valid TREATMENT name. Hint: Alphanumeric "
            )
        else:
            self.udialog.setText("")
            #call database insert command
            status = check_and_update_treatmentDB(self.treatmentname.text(),
                                                  self.strval1, self.strval2)
            if status:
                #self.udialog.setText("Success")
                if self.sitetable1.isHidden() == False:
                    self.sitetable1.hide()
                # faultline check self.informuser(0,'hello')
                # will send it update(), deletes the current tree and re-load the datatree from database
                self.sig2.emit(66)
            else:
                self.udialog.setText(
                    "Treatment name exist. Use different name !!")

    def showNewTreatmentDialog(self, value, strval1, strval2):
        """
         QTable object. Ask user to enter the name of new experiment.
         Need to verify the USEr input is SAFE for database. After verification, insert this entry to 
         table: Experiment
        """
        self.strval1 = strval1
        self.strval2 = strval2
        self.treatmentname = QLineEdit()
        self.udialog = QLabel()
        regexp_alphanum = QtCore.QRegExp('\w+')
        validator_alphanum = QtGui.QRegExpValidator(regexp_alphanum)
        test1state = self.treatmentname.setValidator(validator_alphanum)
        self.savebutton1 = QPushButton("Save")
        self.sitetable1.clear()
        self.sitetable1.reset()
        self.sitetable1.clearContents()
        self.sitetable1.setRowCount(
            0)  # necessary. It will clean the table internally

        self.sitetable1.setRowCount(3)
        self.sitetable1.setColumnCount(2)
        self.show_table_rows()

        self.sitetable1.horizontalHeader().hide()
        self.sitetable1.verticalHeader().hide()
        self.sitetable1.setItem(0, 0, QTableWidgetItem("Enter New Treatment"))
        self.sitetable1.setCellWidget(0, 1, self.treatmentname)
        self.sitetable1.setCellWidget(1, 1, self.savebutton1)
        self.sitetable1.setCellWidget(2, 0, self.udialog)
        self.sitetable1.resizeColumnsToContents()
        self.sitetable1.resizeRowsToContents()
        self.savebutton1.clicked.connect(self.on_savebutton_treatment_clicked)

    def getTreatmentSummary(ename, cname, tname):
        conn = sqlite3.connect(dbDir + '\\crop.db')
        c = conn.cursor()
        if not c:
            print("database not open")
            return False

        #Get treatment id
        search_tuple = (tname, ename, cname)
        c1 = c.execute(
            "SELECT tid FROM treatment where name = ? and t_exid = (select exid from experiment where name =? and crop = ?)",
            search_tuple)
        tid = c1.fetchone()
        operationSummary = "<b>Treatment Summary</b><br>"
        if tid != None:
            # Get all operations associated with this treatment
            op = c.execute(
                "SELECT name, odate, quantity, pop, yseed, eomult, rowSpacing, cultivar, fDepth, autoirrigation, \
                            DATE(year||'-'||month||'-'||day) as dt_frmtd FROM (SELECT *, CASE WHEN LENGTH(substr(odate, 1, \
                            instr(odate,'/')-1)) = 2 THEN substr(odate, 1, instr(odate,'/')-1) ELSE '0'|| substr(odate, 1, instr(odate,'/')-1) \
                            END as month, CASE WHEN LENGTH(substr(substr(odate, instr(odate,'/')+1), 1, instr(substr(odate, instr(odate,'/')+1),\
                            '/')-1)) = 2 THEN substr(substr(odate, instr(odate,'/')+1), 1, instr(substr(odate, instr(odate,'/')+1),'/')-1) ELSE \
                            '0'|| substr(substr(odate, instr(odate,'/')+1), 1, instr(substr(odate, instr(odate,'/')+1),'/')-1) END AS day, CASE \
                            WHEN LENGTH(substr(substr(odate, instr(odate,'/')+1), instr(substr(odate, instr(odate,'/')+1),'/')+1)) = 4 THEN \
                            substr(substr(odate, instr(odate,'/')+1), instr(substr(odate, instr(odate,'/')+1),'/')+1) END AS year FROM operations) \
                            where o_t_exid=? order by dt_frmtd", tid)
            op_rows = op.fetchall()
            for op_row in op_rows:
                if (op_row[0] == "Initial Field Values"):
                    loc = "Middle"
                    if (op_row[5] == 0.5):
                        loc = "Left"
                    if (op_row[9] == 1):
                        irrigFlag = "Yes"
                    else:
                        irrigFlag = "No"
                    operationSummary += "Cultivar: " + op_row[7] + "<br>Plant Density (number of plants/m2): " + str(op_row[3]) + "<br>" + \
                                        "Seed Depth (cm): " + str(op_row[4]) + "<br>Row Spacing (cm): " + str(op_row[6]) + "<br>" + \
                                        "Auto Irrigation : " + irrigFlag + "<br>Location of Planting Grid: " + loc + "<br>"
                else:
                    operationSummary += op_row[0] + " Date: " + op_row[
                        1] + "<br>"

                if (op_row[0] == "Fertilizer-N"):
                    operationSummary += "Quantity (kg/ha): " + str(
                        op_row[2]) + "<br>Fertilizer Depth (cm): " + str(
                            op_row[8]) + "<br>"

        conn.close()
        return operationSummary

##### delete treatment #str_experimentname,str_cropname,str_treatmentname

    def showDeleteTreatmentDialog(self, value, strval1, strval2, strval3):
        """
         Deletes the treatment. Recursive to operation
        """
        self.ename = strval1
        self.cname = strval2
        self.tname = strval3
        self.treatmentname = QLineEdit(self.tname)
        self.treatmentname.setReadOnly(True)
        self.udialog = QLabel()
        self.yesbutton = QPushButton("Yes")
        self.nobutton = QPushButton("No")
        self.treatmentSummary = Tabless_Widget.getTreatmentSummary(
            self.ename, self.cname, self.tname)
        self.udialog.setText(self.treatmentSummary)

        self.sitetable1.clearContents()
        self.sitetable1.setRowCount(0)
        self.sitetable1.clear()
        self.sitetable1.reset()
        self.sitetable1.setRowCount(3)
        self.sitetable1.setColumnCount(2)
        self.show_table_rows()
        self.sitetable1.horizontalHeader().hide()
        self.sitetable1.verticalHeader().hide()
        self.sitetable1.setItem(
            0, 0, QTableWidgetItem("Do you want to delete the treatment"))
        self.sitetable1.setCellWidget(0, 1, self.treatmentname)
        self.sitetable1.setCellWidget(1, 0, self.yesbutton)
        self.sitetable1.setCellWidget(1, 1, self.nobutton)
        self.sitetable1.setCellWidget(2, 0, self.udialog)
        self.sitetable1.setVisible(True)
        self.sitetable1.resizeColumnsToContents()
        self.sitetable1.resizeRowsToContents()
        self.yesbutton.clicked.connect(self.on_yesbutton_treatment_clicked)
        self.nobutton.clicked.connect(self.on_nobutton_treatment_clicked)

    def showNewOperationDialog(self, value, strval1, strval2, strval3):
        """
         QTable object. Asks user to SELECT operation from the given set of operation.
         Need to verify the USEr input is SAFE for database. After verification, insert this 
         entry to table: Operation
        """
        self.udialog = QLabel()
        self.treatmentname = strval1
        self.experimentname = strval2
        self.cropname = strval3
        self.calendar = QDateEdit()

        lastoperation_date = getme_date_of_last_operationDB(
            self.treatmentname, self.experimentname, self.cropname)
        # first find out if this the new operation or there is a operation defined for this treatment.
        # So we use the calendar date logic
        if len(lastoperation_date) > 0:
            lastoperation_date_parts = lastoperation_date[0].split(
                "/")  # 10/20/2006
            self.calendar.setMinimumDate(
                QDate(int(lastoperation_date_parts[2]),
                      int(lastoperation_date_parts[0]),
                      int(lastoperation_date_parts[1])))
            print("debug:tabless_widget: last operation date=",
                  lastoperation_date, " ", lastoperation_date_parts[2], " ",
                  lastoperation_date_parts[1])
        else:
            self.calendar.setMinimumDate(QDate(1900, 1, 1))

        self.calendar.setMaximumDate(QDate(2200, 1, 1))
        self.calendar.setDisplayFormat("MM/dd/yyyy")
        self.calendar.setCalendarPopup(True)
        self.savebutton1 = QPushButton("Save")
        self.combo1 = QComboBox()
        self.combocropvariety = QComboBox()
        self.comboeomult = QComboBox()
        self.yseedlabel = QLabel("Seed Depth (cm)")
        self.quantitylabel = QLabel("Quantity (kg/ha)")
        self.fDepthlabel = QLabel("Fertilizer Depth (cm)")
        self.seedMasslabel = QLabel("Seedpiece Mass (g)")
        self.datelabel = QLabel("Date")
        self.cropvarietylabel = QLabel("Cultivars")
        self.poplabel = QLabel("Plant Density (number of plants/m2)")
        self.rowspacinglabel = QLabel("Row Spacing (cm)")
        self.autoirrigationlabel = QLabel("Auto Irrigation")
        self.eomultlabel = QLabel("Location of Planting Grid")

        self.blanklabeledit = QLineEdit("")
        self.quantitylabeledit = QLineEdit("")
        self.poplabeledit = QLineEdit("6.5")
        self.yseedlabeledit = QLineEdit("5")
        self.rowspacinglabeledit = QLineEdit("75")
        self.autoirrigationlabeledit = QLineEdit("0")
        self.fDepthlabeledit = QLineEdit("")
        self.seedMasslabeledit = QLineEdit("0")
        # Create and populate autoIrrigation combo
        self.comboAutoIrrig = QComboBox()
        self.comboAutoIrrig.addItem("Yes")  # val = 1
        self.comboAutoIrrig.addItem("No")  # val = 0

        #checking USER input for NUMERIC values
        regexp_num = QtCore.QRegExp('^\d*[.]?\d*$')
        validator_num = QtGui.QRegExpValidator(regexp_num)
        test1state = self.quantitylabeledit.setValidator(validator_num)
        test1state = self.poplabeledit.setValidator(validator_num)
        test1state = self.yseedlabeledit.setValidator(validator_num)
        test1state = self.rowspacinglabeledit.setValidator(validator_num)
        test1state = self.fDepthlabeledit.setValidator(validator_num)
        test1state = self.seedMasslabeledit.setValidator(validator_num)

        #The operation will only show if quantity_flag=1 on defaultoperations table.
        self.readlist = read_defaultOperationsDB()
        self.combo1.clear()
        self.combo1.addItem("Select Operation")
        for record in sorted(self.readlist):
            if record[3] == 1:
                self.combo1.addItem(record[1])

        self.sitetable1.clearContents()
        self.sitetable1.setRowCount(
            0)  # necessary. It will clean the table internally
        self.sitetable1.clear()
        self.sitetable1.reset()

        self.sitetable1.setRowCount(16)
        self.sitetable1.setColumnCount(3)
        self.show_table_rows()
        self.sitetable1.horizontalHeader().hide()
        self.sitetable1.verticalHeader().hide()
        self.sitetable1.setCellWidget(0, 1, self.combo1)

        self.sitetable1.setCellWidget(1, 0, self.datelabel)
        self.sitetable1.setCellWidget(2, 0, self.quantitylabel)
        self.sitetable1.setCellWidget(3, 0, self.cropvarietylabel)
        # Plant density
        self.sitetable1.setCellWidget(4, 0, self.poplabel)
        # Seed depth
        self.sitetable1.setCellWidget(5, 0, self.yseedlabel)
        self.sitetable1.setCellWidget(6, 0, self.rowspacinglabel)
        self.sitetable1.setCellWidget(7, 0, self.eomultlabel)
        self.sitetable1.setCellWidget(8, 0, self.fDepthlabel)
        self.sitetable1.setCellWidget(9, 0, self.seedMasslabel)
        self.sitetable1.setCellWidget(10, 0, self.autoirrigationlabel)

        self.sitetable1.setCellWidget(1, 1, self.calendar)
        self.sitetable1.setCellWidget(2, 1, self.quantitylabeledit)
        self.sitetable1.setCellWidget(3, 1, self.combocropvariety)
        self.sitetable1.setCellWidget(4, 1, self.poplabeledit)
        self.sitetable1.setCellWidget(5, 1, self.yseedlabeledit)
        self.sitetable1.setCellWidget(6, 1, self.rowspacinglabeledit)
        self.sitetable1.setCellWidget(7, 1, self.comboeomult)
        self.sitetable1.setCellWidget(8, 1, self.fDepthlabeledit)
        self.sitetable1.setCellWidget(9, 1, self.seedMasslabeledit)
        self.sitetable1.setCellWidget(10, 1, self.comboAutoIrrig)
        self.sitetable1.setCellWidget(11, 1, self.savebutton1)

        self.sitetable1.resizeColumnsToContents()
        self.sitetable1.resizeRowsToContents()
        self.sitetable1.setShowGrid(False)

        self.sitetable1.hideRow(1)
        self.sitetable1.hideRow(2)
        self.sitetable1.hideRow(3)
        self.sitetable1.hideRow(4)
        self.sitetable1.hideRow(5)
        self.sitetable1.hideRow(6)
        self.sitetable1.hideRow(7)
        self.sitetable1.hideRow(8)
        self.sitetable1.hideRow(9)
        self.sitetable1.hideRow(10)
        self.sitetable1.hideRow(11)
        self.sitetable1.hideRow(12)
        self.combo1.currentIndexChanged.connect(self.oncomboactivated)

    def showExistingOperationDialog(self, value, strval1, strval2, strval3,
                                    strval4):
        """
         str_treatmentname,str_experimentname,str_cropname,str_operationname
         QTable object. 
         Will show the existing operation. Will allow  to modify its values.
         Create the field table. Query the OPERATION table and get the flag values
        """
        self.udialog = QLabel()
        self.treatmentname = strval1
        self.experimentname = strval2
        self.cropname = strval3
        # strval4 contains operation_id and operation_name concatenated with '_' character
        self.operationname = strval4.split('_')[1]
        self.op_id = strval4.split('_')[0]
        #print("treat = ", self.treatmentname, " expir = ", self.experimentname, " crop nm = ", self.cropname, " op name = ", self.operationname, " op_id = ",self.op_id)
        self.record = list(read_operation_valuesDB2(self.op_id))
        #print("debug: record=",self.record)
        self.calendar = QDateEdit()
        self.calendar.setMinimumDate(QDate(1900, 1, 1))
        self.calendar.setMaximumDate(QDate(2200, 1, 1))
        self.calendar.setDisplayFormat("MM/dd/yyyy")
        self.calendar.setCalendarPopup(True)
        fformat = QtGui.QTextCharFormat()
        fformat.setForeground(QtGui.QColor(151, 180, 152))

        self.savebutton1 = QPushButton("Update")
        self.deletebutton = QPushButton("Delete")

        self.combo1 = QComboBox()
        self.combocropvariety = QComboBox()
        self.comboeomult = QComboBox()
        self.comboAutoIrrig = QComboBox()
        self.yseedlabel = QLabel("Seed Depth (cm)")
        self.quantitylabel = QLabel("Quantity (kg/ha)")
        self.datelabel = QLabel("Date")
        self.cropvarietylabel = QLabel("Cultivars")
        self.poplabel = QLabel("Plant Density (number of plants/m2)")
        self.rowspacinglabel = QLabel("Row Spacing (cm)")
        self.fDepthlabel = QLabel("Fertilizer Depth (cm)")
        self.seedMasslabel = QLabel("Seedpiece Mass (g)")
        self.autoirrigationlabel = QLabel("Auto Irrigation")
        self.eomultlabel = QLabel("Location of Planting Grid")

        self.blanklabeledit = QLineEdit("")
        self.quantitylabeledit = QLineEdit("")
        self.poplabeledit = QLineEdit("")
        self.yseedlabeledit = QLineEdit("")
        self.rowspacinglabeledit = QLineEdit("")
        self.fDepthlabeledit = QLineEdit("")
        self.seedMasslabeledit = QLineEdit("")

        #checking USER input for NUMERIC values
        regexp_num = QtCore.QRegExp('\.d+')
        validator_num = QtGui.QRegExpValidator(regexp_num)
        test1state = self.quantitylabeledit.setValidator(validator_num)
        test1state = self.poplabeledit.setValidator(validator_num)
        test1state = self.yseedlabeledit.setValidator(validator_num)
        test1state = self.rowspacinglabeledit.setValidator(validator_num)
        test1state = self.fDepthlabeledit.setValidator(validator_num)
        test1state = self.seedMasslabeledit.setValidator(validator_num)

        self.sitetable1.clearContents()
        self.sitetable1.setRowCount(
            0)  # necessary. It will clean the table internally
        self.sitetable1.clear()
        self.sitetable1.reset()

        self.sitetable1.setRowCount(16)
        self.sitetable1.setColumnCount(3)
        self.show_table_rows()
        self.sitetable1.horizontalHeader().hide()
        self.sitetable1.verticalHeader().hide()

        self.sitetable1.setCellWidget(1, 0, self.datelabel)
        self.sitetable1.setCellWidget(2, 0, self.quantitylabel)
        self.sitetable1.setCellWidget(3, 0, self.cropvarietylabel)
        self.sitetable1.setCellWidget(4, 0, self.poplabel)
        self.sitetable1.setCellWidget(5, 0, self.yseedlabel)
        self.sitetable1.setCellWidget(6, 0, self.rowspacinglabel)
        self.sitetable1.setCellWidget(7, 0, self.eomultlabel)
        self.sitetable1.setCellWidget(8, 0, self.fDepthlabel)
        self.sitetable1.setCellWidget(9, 0, self.seedMasslabel)
        self.sitetable1.setCellWidget(10, 0, self.autoirrigationlabel)
        if (self.operationname == "Fertilizer-N"):
            self.sitetable1.setCellWidget(11, 0, self.deletebutton)

        self.sitetable1.setCellWidget(1, 1, self.calendar)
        self.sitetable1.setCellWidget(2, 1, self.quantitylabeledit)
        self.sitetable1.setCellWidget(3, 1, self.combocropvariety)
        self.sitetable1.setCellWidget(4, 1, self.poplabeledit)
        self.sitetable1.setCellWidget(5, 1, self.yseedlabeledit)
        self.sitetable1.setCellWidget(6, 1, self.rowspacinglabeledit)
        self.sitetable1.setCellWidget(7, 1, self.comboeomult)
        self.sitetable1.setCellWidget(8, 1, self.fDepthlabeledit)
        self.sitetable1.setCellWidget(9, 1, self.seedMasslabeledit)
        self.sitetable1.setCellWidget(10, 1, self.comboAutoIrrig)
        self.sitetable1.setCellWidget(11, 1, self.savebutton1)

        header = self.sitetable1.horizontalHeader()
        header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
        header.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)
        self.sitetable1.verticalHeader().setSectionResizeMode(
            QtWidgets.QHeaderView.ResizeToContents)
        self.sitetable1.verticalHeader().setSectionResizeMode(
            0, QtWidgets.QHeaderView.Stretch)

        self.sitetable1.resizeColumnsToContents()
        self.sitetable1.resizeRowsToContents()
        self.sitetable1.setShowGrid(False)

        if (self.operationname == "Initial Field Values"):
            self.readcropvarietylist = read_cultivar_DB(self.cropname)
            for record2 in sorted(self.readcropvarietylist):
                self.combocropvariety.addItem(record2)
            matchedindex = self.combocropvariety.findText(str(self.record[18]))
            if matchedindex >= 0:
                self.combocropvariety.setCurrentIndex(matchedindex)

            # Build eomult picklist
            self.comboeomult.addItem("Left")  # val = 0.5
            self.comboeomult.addItem("Middle")  # val = 1.0
            if (self.record[16] == 0.5):
                matchedindex = self.comboeomult.findText("Left")
            else:
                matchedindex = self.comboeomult.findText("Middle")
            self.comboeomult.setCurrentIndex(matchedindex)

            # Create and populate autoIrrigation combo
            self.comboAutoIrrig.addItem("Yes")  # val = 1
            self.comboAutoIrrig.addItem("No")  # val = 0
            if (self.record[11] == 1):
                matchedindex = self.comboAutoIrrig.findText("Yes")
            else:
                matchedindex = self.comboAutoIrrig.findText("No")
            self.comboAutoIrrig.setCurrentIndex(matchedindex)

            self.poplabeledit.setText(str(self.record[10]))
            self.yseedlabeledit.setText(str(self.record[14]))
            self.rowspacinglabeledit.setText(str(self.record[17]))
            self.seedMasslabeledit.setText(str(self.record[20]))

            self.sitetable1.hideRow(1)
            self.sitetable1.showRow(3)
            self.sitetable1.showRow(4)
            self.sitetable1.showRow(5)
            self.sitetable1.showRow(6)
            self.sitetable1.showRow(7)
            self.sitetable1.showRow(10)
            if (re.search("potato", self.cropname)):
                self.sitetable1.showRow(9)
            else:
                self.sitetable1.hideRow(9)
        else:
            # Calendar
            self.sitetable1.showRow(1)
            # recover the mm,dd,yyyy and set the calendar
            record_parts = self.record[7].split("/")

            currentYear = record_parts[2]
            self.calendar.setDate(
                QDate(int(currentYear), int(record_parts[0]),
                      int(record_parts[1])))

            self.sitetable1.hideRow(3)
            self.sitetable1.hideRow(4)
            self.sitetable1.hideRow(5)
            self.sitetable1.hideRow(6)
            self.sitetable1.hideRow(7)
            self.sitetable1.hideRow(9)
            self.sitetable1.hideRow(10)

        # Quantity
        if (self.operationname == "Fertilizer-N"):
            self.sitetable1.showRow(2)
            self.sitetable1.showRow(8)
            self.quantitylabeledit.setText(str(self.record[6]))
            self.fDepthlabeledit.setText(str(self.record[19]))
        else:
            self.sitetable1.hideRow(2)
            self.sitetable1.hideRow(8)

        self.sitetable1.showRow(11)
        self.sitetable1.resizeColumnsToContents()
        self.sitetable1.resizeRowsToContents()
        self.sitetable1.setShowGrid(False)
        self.savebutton1.clicked.connect(self.on_savebutton_operation_clicked)
        self.deletebutton.clicked.connect(
            self.on_deletebutton_operation_clicked)

    def oncomboactivated(self, listindex):
        print("text=", listindex)
        self.record = [
            element for element in self.readlist
            if element[1] == self.combo1.currentText()
        ][0]
        op = self.record[1]

        if (op == "Initial Field Values"):
            self.readcropvarietylist = read_cultivar_DB(self.cropname)
            for record2 in sorted(self.readcropvarietylist):
                self.combocropvariety.addItem(record2)
            matchedindex = self.combocropvariety.findText(str(self.record[17]))

            # Build eomult picklist
            self.comboeomult.addItem("Left")  # value 0.5
            self.comboeomult.addItem("Middle")  # value 1.0

            self.sitetable1.hideRow(1)
            self.sitetable1.showRow(3)
            self.sitetable1.showRow(4)
            self.sitetable1.showRow(5)
            self.sitetable1.showRow(6)
            self.sitetable1.showRow(7)
            if (re.search("potato", self.cropname)):
                self.sitetable1.showRow(9)
        else:
            self.sitetable1.showRow(1)
            self.sitetable1.hideRow(3)
            self.sitetable1.hideRow(4)
            self.sitetable1.hideRow(5)
            self.sitetable1.hideRow(6)
            self.sitetable1.hideRow(7)
            self.sitetable1.hideRow(9)

        # Quantity
        if (op == "Fertilizer-N"):
            print("Debug inside fertilizer-N")
            self.sitetable1.showRow(2)
            self.sitetable1.showRow(8)
        else:
            self.sitetable1.hideRow(2)
            self.sitetable1.hideRow(8)

        self.sitetable1.showRow(11)
        self.savebutton1.clicked.connect(self.on_savebutton_operation_clicked)
        self.sitetable1.resizeColumnsToContents()
        self.sitetable1.resizeRowsToContents()
        self.sitetable1.setShowGrid(False)

    def on_savebutton_operation_clicked(self, value):
        #print("Inside save operation")
        #print("value=",value)
        #print("treatment=", self.treatmentname)
        #print("experiment=", self.experimentname)
        #print("cropment=", self.cropname)
        op_id = self.record[0]
        #print("operation_id=",op_id)

        op = self.record[1]
        #print("operation=",op)

        print("record save=", self.record)
        # Quantity
        if (op == "Fertilizer-N"):
            if (self.quantitylabeledit.text() != ""):
                self.record[6] = float(self.quantitylabeledit.text())
            else:
                messageUser("Quantity should be a number.")

            if (self.fDepthlabeledit.text() != ""):
                self.record[19] = float(self.fDepthlabeledit.text())
            else:
                messageUser("Fertilizer Depth should be a number.")

        if (op == "Initial Field Values"):
            print("cultivar= ", self.combocropvariety.currentText())
            self.record[10] = float(self.poplabeledit.text())
            self.record[14] = float(self.yseedlabeledit.text())
            self.record[17] = float(self.rowspacinglabeledit.text())
            self.record[18] = self.combocropvariety.currentText()
            self.record[20] = float(self.seedMasslabeledit.text())
            # Validate row spacing
            if (self.record[17] < 1 or self.record[17] > 200):
                messageUser(
                    "Row spacing should be a value between 1 and 200 cm.")
                return False
            if self.cropname == "corn":
                # Validate plant density
                if (self.record[10] < 1 or self.record[10] > 20):
                    messageUser(
                        "Plant density for corn should be a value between 1 and 20 number of plants/m2."
                    )
                    return False
                # Validate seed depth
                if (self.record[14] < 2 or self.record[14] > 7):
                    messageUser(
                        "Seed depth for corn should be a value between 2 and 7 cm."
                    )
                    return False
            elif self.cropname == "potato":
                # Validate plant density
                if (self.record[10] < 1 or self.record[10] > 300):
                    messageUser(
                        "Plant density for potato should be a value between 1 and 25 number of plants/m2."
                    )
                    return False
                # Validate seed depth
                if (self.record[14] < 1 or self.record[14] > 20):
                    messageUser(
                        "Seed depth for potato should be a value between 1 and 20 cm."
                    )
                    return False
                # Validate seedpiece mass
                if (self.record[20] < 0 or self.record[20] > 50):
                    messageUser(
                        "Seedpiece mass for potato should be a value between 0 and 50 g."
                    )
                    return False
            if (self.comboeomult.currentText() == "Left"):
                self.record[16] = 0.5
            if (self.comboeomult.currentText() == "Middle"):
                self.record[16] = 1.0
            if (self.comboAutoIrrig.currentText() == "Yes"):
                self.record[11] = 1
            if (self.comboAutoIrrig.currentText() == "No"):
                self.record[11] = 0
            new_record = self.record[1:]
        else:
            new_record = self.record[1:]
            new_date = self.calendar.date().toString("MM/dd/yyyy")
            print("new date= ", new_date)
            new_record[6] = new_date

        print("record before save=", self.record)
        status = check_and_update_operationDB(op_id, self.treatmentname,
                                              self.experimentname,
                                              self.cropname, new_record)

        if status:
            self.udialog.setText("Success")
            self.sitetable1.setVisible(False)
            self.sig2.emit(1)

    def on_deletebutton_operation_clicked(self, value):
        print("Inside delete operation")
        print("value=", value)
        print("treatment=", self.treatmentname)
        print("experiment=", self.experimentname)
        print("cropment=", self.cropname)
        print("operation =", self.operationname)
        print("record=", self.record)
        op_id = self.record[0]
        print("operation_id=", op_id)

        status = check_and_delete_operationDB(op_id)
        if status:
            self.udialog.setText("Success")
            self.sitetable1.setVisible(False)
            self.sig2.emit(3)
Example #18
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.textSuffix = QTextEdit(self.centralwidget)
        self.textSuffix.setGeometry(QRect(20, 230, 261, 31))
        self.textSuffix.setObjectName("textSuffix")
        self.textRiskf = QTextEdit(self.centralwidget)
        self.textRiskf.setGeometry(QRect(20, 360, 261, 31))
        self.textRiskf.setObjectName("textRiskf")
        self.label = QLabel(self.centralwidget)
        self.label.setGeometry(QRect(20, 330, 261, 20))
        self.label.setObjectName("label")
        self.label_2 = QLabel(self.centralwidget)
        self.label_2.setGeometry(QRect(20, 270, 281, 21))
        self.label_2.setObjectName("label_2")
        self.label_3 = QLabel(self.centralwidget)
        self.label_3.setGeometry(QRect(20, 200, 261, 16))
        self.label_3.setObjectName("label_3")
        self.label_4 = QLabel(self.centralwidget)
        self.label_4.setGeometry(QRect(20, 130, 261, 21))
        self.label_4.setObjectName("label_4")
        self.label_5 = QLabel(self.centralwidget)
        self.label_5.setGeometry(QRect(20, 60, 261, 21))
        self.label_5.setObjectName("label_5")
        self.startButton = QPushButton(self.centralwidget)
        self.startButton.setGeometry(QRect(20, 510, 111, 31))
        self.startButton.setObjectName("startButton")
        self.label_6 = QLabel(self.centralwidget)
        self.label_6.setGeometry(QRect(20, 10, 261, 41))
        font = QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(12)
        font.setBold(True)
        font.setUnderline(True)
        font.setWeight(75)
        self.label_6.setFont(font)
        self.label_6.setObjectName("label_6")
        self.resultBrowser = QTextBrowser(self.centralwidget)
        self.resultBrowser.setGeometry(QRect(310, 30, 461, 501))
        self.resultBrowser.setObjectName("resultBrowser")
        self.DateStart = QDateEdit(self.centralwidget)
        self.DateStart.setGeometry(QRect(20, 90, 121, 31))
        self.DateStart.setMaximumDate(QDate(2050, 12, 31))
        self.DateStart.setMinimumDate(QDate(1990, 12, 31))
        self.DateStart.setDate(QDate(2018, 1, 1))
        self.DateStart.setObjectName("DateStart")
        self.DateEnd = QDateEdit(self.centralwidget)
        self.DateEnd.setGeometry(QRect(19, 163, 121, 31))
        self.DateEnd.setDateTime(QDateTime(QDate(2018, 1, 1), QTime(0, 0, 0)))
        self.DateEnd.setMaximumDateTime(QDateTime(QDate(2050, 12, 31), QTime(23, 59, 59)))
        self.DateEnd.setMinimumDate(QDate(1990, 12, 31))
        self.DateEnd.setObjectName("DateEnd")
        self.spinBoxMode = QSpinBox(self.centralwidget)
        self.spinBoxMode.setGeometry(QRect(20, 290, 71, 31))
        self.spinBoxMode.setMinimum(1)
        self.spinBoxMode.setMaximum(3)
        self.spinBoxMode.setObjectName("spinBoxMode")
        self.label_7 = QLabel(self.centralwidget)
        self.label_7.setGeometry(QRect(170, 300, 101, 21))
        self.label_7.setObjectName("label_7")
        self.endButton = QPushButton(self.centralwidget)
        self.endButton.setGeometry(QRect(160, 510, 121, 31))
        self.endButton.setObjectName("endButton")
        self.fileButton = QPushButton(self.centralwidget)
        self.fileButton.setGeometry(QRect(20, 410, 261, 31))
        self.fileButton.setObjectName("fileButton")
        self.pathBrowser = QTextBrowser(self.centralwidget)
        self.pathBrowser.setGeometry(QRect(20, 450, 261, 41))
        self.pathBrowser.setObjectName("pathBrowser")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QRect(0, 0, 800, 23))
        self.menubar.setObjectName("menubar")
        self.menuAnalysis = QMenu(self.menubar)
        self.menuAnalysis.setObjectName("menuAnalysis")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.menubar.addAction(self.menuAnalysis.menuAction())

        self.retranslateUi(MainWindow)
        QMetaObject.connectSlotsByName(MainWindow)
        ####################################################

        self.mythread = MyThread()
        self.mainthread = MyMainThread()

        self.fileButton.clicked.connect(lambda : self.file_path())
        self.mythread.trigger.connect(self.update_text)
        self.mainthread.result.connect(self.update_result)

        self.startButton.clicked.connect(lambda : self.input_Parameters())
        self.startButton.clicked.connect(lambda : self.mainthread.start())
        self.startButton.clicked.connect(lambda : self.mythread.start())
        self.endButton.clicked.connect(lambda : self.end_calculation())

        
    def input_Parameters(self):
        self.aa = str(self.DateStart.date().toString("yyyyMMdd"))
        self.bb = str(self.DateEnd.date().toString("yyyyMMdd"))
        self.cc = str(self.textSuffix.toPlainText())
        self.dd = int(self.spinBoxMode.value())
        self.ee = float(self.textRiskf.toPlainText())

        if self.dd==1:
            self.dx='p1f1'
        elif self.dd==2:
            self.dx='p0f1'
        elif self.dd==3:
            self.dx='p1f0'
        else:
            raise Exception('Running Mode is wrong')

        self.mainthread.parameters_in = [self.aa ,self.bb, self.cc, self.dx, self.ee, self.directory1]


    def file_path(self):  
        self.directory1 = QFileDialog.getExistingDirectory(self.centralwidget,"Please choose folder","/")+'/'
        self.pathBrowser.append(str(self.directory1))

    def update_text(self, message):
        self.resultBrowser.append(str(message))
    
    def update_result(self,message):
        self.mythread.stop_()
        sleep(1)
        self.resultBrowser.append(str(message))
        print(self.mainthread.str_result)
        for i in self.mainthread.str_result:
            print(i)
            self.resultBrowser.append(i)

    def end_calculation(self):
        self.mythread.stop_()
        self.mainthread.stop_()
        sleep(1)
        self.resultBrowser.append('\nCalculation terminated by user...')


    def retranslateUi(self, MainWindow):
        _translate = QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "Please input risk free rate(0.035)"))
        self.label_2.setText(_translate("MainWindow", "Choose a running mode(e.g (1)p1f1/(2)p0f1"))
        self.label_3.setText(_translate("MainWindow", "Please input the suffix for result file"))
        self.label_4.setText(_translate("MainWindow", "Please input earliest date(e.g 2018-01-01)"))
        self.label_5.setText(_translate("MainWindow", "Please input latest date(e.g 2018-12-30)"))
        self.startButton.setText(_translate("MainWindow", "Start Analysis"))
        self.label_6.setText(_translate("MainWindow", "Barra Contribution Analysis(v_test)"))
        self.label_7.setText(_translate("MainWindow", " (3)p1f0"))
        self.endButton.setText(_translate("MainWindow", "End Process"))
        self.fileButton.setText(_translate("MainWindow", "Choose a folder"))
        self.menuAnalysis.setTitle(_translate("MainWindow", "Analysis"))
Example #19
0
class FilterView(FixedWidthLabel):
    def __init__(self, controller, model):
        self.controller = controller
        self.model = model
        self.width = self.model.static_data.width
        super().__init__(self.width)

        self._init_UI()

    def _init_UI(self) -> None:
        data = self.model.static_data
        self.layout = QVBoxLayout()
        self.layout.setSpacing(4)
        self.layout.setContentsMargins(8, 2, 8, 2)
        self.layout.setAlignment(Qt.AlignTop)
        self.setLayout(self.layout)

        self.title = FixedSizeLabel(self.width - 6, 40, 'Problem Filter')
        self.title.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
        self.title.set_colours(data.bg_colour, data.text_colour)

        self.dateedit_start = QDateEdit()
        self.dateedit_start.setCalendarPopup(True)
        self.dateedit_start.userDateChanged.connect(
            self._on_start_date_changed)
        self.dateedit_end = QDateEdit()
        self.dateedit_end.setCalendarPopup(True)
        self.dateedit_end.userDateChanged.connect(self._on_end_date_changed)

        self.layout_date = QFormLayout()
        self.layout_date.setFormAlignment(Qt.AlignTop)
        self.layout_date.setLabelAlignment(Qt.AlignRight)
        self.layout_date.setContentsMargins(2, 2, 2, 2)
        self.layout_date.setSpacing(4)

        self.layout_date.addRow('Start Date:', self.dateedit_start)
        self.layout_date.addRow('End Date :', self.dateedit_end)

        self.layout_RIC = QHBoxLayout()
        self.layout_RIC.setSpacing(4)
        self.layout_RIC.setContentsMargins(0, 0, 0, 0)
        self.layout_RIC.setAlignment(Qt.AlignTop)

        self.layout_other = QGridLayout()
        self.layout_other.setSpacing(4)
        self.layout_other.setContentsMargins(0, 0, 0, 0)
        self.layout_other.setAlignment(Qt.AlignTop)

        self.button_reset = QPushButton('Reset')
        self.button_reset.clicked.connect(self._reset_filters)

        self.layout.addWidget(self.title)
        self.layout.addLayout(self.layout_date)
        self.layout.addLayout(self.layout_RIC)
        self.layout.addLayout(self.layout_other)
        self.layout.addWidget(self.button_reset)
        self._add_all_widgets()

    def set_data(self, arg: bool) -> None:
        self._remove_all_widgets()
        self._add_all_widgets()

    def _add_all_widgets(self) -> None:
        self._add_RIC_widgets()
        self._add_other_widgets()

    def _add_RIC_widgets(self) -> None:
        if len(self.model.views) >= 3:
            for widget in self.model.views[0:3]:
                self.layout_RIC.addWidget(widget, alignment=Qt.AlignTop)

    def _add_other_widgets(self) -> None:
        if len(self.model.views) >= 3:
            for index, widget in enumerate(self.model.views[3:]):
                self.layout_other.addWidget(widget,
                                            index // 2,
                                            index % 2,
                                            alignment=Qt.AlignTop)

    def _remove_all_widgets(self) -> None:
        self._remove_widgets_from(self.layout_RIC)
        self._remove_widgets_from(self.layout_other)

    def _remove_widgets_from(self, layout: QLayout) -> None:
        for index in reversed(range(layout.count())):
            widget = layout.itemAt(index).widget()
            layout.removeWidget(widget)
            widget.setParent(None)

    def _on_start_date_changed(self, date) -> None:
        self.controller.on_start_date_changed(date)

    def _on_end_date_changed(self, date) -> None:
        self.controller.on_end_date_changed(date)

    def set_min_date(self, date) -> None:
        self.dateedit_start.setMinimumDate(date)
        self.dateedit_end.setMinimumDate(date)
        self.dateedit_start.setDate(date)

    def set_max_date(self, date) -> None:
        self.dateedit_start.setMaximumDate(date)
        self.dateedit_end.setMaximumDate(date)
        self.dateedit_end.setDate(date)

    def _reset_filters(self) -> None:
        min_date = self.dateedit_start.minimumDate()
        self.dateedit_start.setDate(min_date)
        max_date = self.dateedit_end.maximumDate()
        self.dateedit_end.setDate(max_date)
        self._unselect_all_widgets_in(self.layout_RIC)
        self._unselect_all_widgets_in(self.layout_other)
        self.controller.reset()

    def _unselect_all_widgets_in(self, layout: QLayout) -> None:
        for index in reversed(range(layout.count())):
            widget = layout.itemAt(index).widget()
            widget.clear_selection()
Example #20
0
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()
Example #21
0
class MySpinBox(QGroupBox):
    def __init__(self):
        super().__init__()
        self.setTitle('QSpinBox')
        self.init_ui()

    def init_ui(self):
        layout_group1 = self.group_int_spinbox()
        layout_group2 = self.group_double_spinbox()
        layout_group3 = self.group_date_spinbox()
        layout_group4 = self.group_time_spinbox()
        layout_group5 = self.group_datetime_spinbox()

        layout = QVBoxLayout()
        layout.addLayout(layout_group1)
        layout.addLayout(layout_group2)
        layout.addLayout(layout_group3)
        layout.addLayout(layout_group4)
        layout.addLayout(layout_group5)

        self.setLayout(layout)

    def group_datetime_spinbox(self):
        group2 = QGroupBox('QDateTimeEdit')
        lbl = QLabel('QDateTimeEdit')
        date_time_edit = QDateTimeEdit(self)
        date_time_edit.setDateTime(QDateTime.currentDateTime())
        date_time_edit.setDateTimeRange(QDateTime(1900, 1, 1, 00, 00, 00),
                                        QDateTime(2100, 1, 1, 00, 00, 00))
        date_time_edit.setDisplayFormat('yyyy-MM-dd hh:mm:ss')
        date_time_edit.dateTimeChanged.connect(self.datetime_value_change)
        self.lbl5 = QLabel(
            date_time_edit.dateTime().toString('yyyy-MM-dd hh:mm:ss'))
        layout_group5 = QHBoxLayout()
        layout_group5.addWidget(lbl)
        layout_group5.addWidget(date_time_edit)
        layout_group5.addWidget(self.lbl5)
        return layout_group5

    def group_time_spinbox(self):
        group2 = QGroupBox('QTimeEdit')
        lbl = QLabel('QTimeEdit')
        timeedit = QTimeEdit(self)
        timeedit.setTime(QTime.currentTime())
        timeedit.setTimeRange(QTime(3, 00, 00), QTime(23, 30, 00))
        timeedit.setDisplayFormat('hh:mm:ss')
        timeedit.timeChanged.connect(self.time_value_change)
        # dateedit.setDateRange(QDate(1900, 1, 1), QDate(2100, 12, 31))
        # self.lbl4 = QLabel(QTime.toString(timeedit.dateTime, 'hh:mm:ss'))
        self.lbl4 = QLabel(timeedit.time().toString('hh:mm:ss'))
        layout_group4 = QHBoxLayout()
        layout_group4.addWidget(lbl)
        layout_group4.addWidget(timeedit)
        layout_group4.addWidget(self.lbl4)
        return layout_group4

    def group_date_spinbox(self):
        lbl = QLabel('QDateEdit')
        group2 = QGroupBox('QDateEdit')
        self.dateedit = QDateEdit(self)
        self.dateedit.setDate(QDate.currentDate())
        self.dateedit.setMinimumDate(QDate(1900, 1, 1))
        self.dateedit.setMaximumDate(QDate(2100, 12, 31))
        self.dateedit.setDisplayFormat('yyyy-MM-dd')
        self.dateedit.dateChanged.connect(self.date_value_change)
        # dateedit.setDateRange(QDate(1900, 1, 1), QDate(2100, 12, 31))
        self.lbl3 = QLabel(QDate.toString(self.dateedit.date(), 'yyyy-MM-dd'))
        layout_group3 = QHBoxLayout()
        layout_group3.addWidget(lbl)
        layout_group3.addWidget(self.dateedit)
        layout_group3.addWidget(self.lbl3)
        return layout_group3

    def group_double_spinbox(self):
        group2 = QGroupBox('Double QSpinbox')
        lbl = QLabel('QDoubleSpinBox')
        self.dspinbox = QDoubleSpinBox()
        self.dspinbox.setRange(0, 100)
        self.dspinbox.setSingleStep(0.5)
        self.dspinbox.setPrefix('$ ')
        self.dspinbox.setDecimals(1)
        self.lbl2 = QLabel('$ 0.0')
        self.dspinbox.valueChanged.connect(self.double_value_changed)
        layout_group2 = QHBoxLayout()
        layout_group2.addWidget(lbl)
        layout_group2.addWidget(self.dspinbox)
        layout_group2.addWidget(self.lbl2)
        return layout_group2

    def group_int_spinbox(self):
        group1 = QGroupBox('Integer QSpinBox')
        lbl = QLabel('QSpinBox')
        self.spinbox = QSpinBox()
        self.spinbox.setMinimum(-10)
        self.spinbox.setMaximum(30)
        # self.spinbox.setRange(-10, 30)
        self.spinbox.setSingleStep(2)
        self.lbl1 = QLabel(str(self.spinbox.value()))
        self.spinbox.valueChanged.connect(self.int_value_changed)
        layout_group1 = QHBoxLayout()
        layout_group1.addWidget(lbl)
        layout_group1.addWidget(self.spinbox)
        layout_group1.addWidget(self.lbl1)
        return layout_group1

    def int_value_changed(self):
        self.lbl1.setText(str(self.spinbox.value()))

    def double_value_changed(self):
        self.lbl2.setText(str(self.dspinbox.value()))

    def date_value_change(self, t):
        self.lbl3.setText(QDate.toString(t, 'yyyy-MM-dd'))

    def time_value_change(self, t):
        self.lbl4.setText(t.toString('hh:mm:ss'))

    def datetime_value_change(self, dt):
        self.lbl5.setText(dt.toString('yyyy-MM-dd hh:mm:ss'))
Example #22
0
class WeatherDataGapfiller(QMainWindow):

    ConsoleSignal = QSignal(str)

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

        self._corrcoeff_update_inprogress = False
        self._pending_corrcoeff_update = None
        self._loading_data_inprogress = False

        self.__initUI__()

        # Setup the DataGapfillManager.
        self.gapfill_manager = DataGapfillManager()
        self.gapfill_manager.sig_task_progress.connect(
            self.progressbar.setValue)
        self.gapfill_manager.sig_status_message.connect(
            self.set_statusbar_text)

    def __initUI__(self):
        self.setWindowIcon(get_icon('master'))

        # Setup the toolbar at the bottom.
        self.btn_fill = QPushButton('Gapfill Data')
        self.btn_fill.setIcon(get_icon('fill_data'))
        self.btn_fill.setIconSize(get_iconsize('small'))
        self.btn_fill.setToolTip(
            "Fill the gaps in the daily weather data of the selected "
            "weather station.")
        self.btn_fill.clicked.connect(self._handle_gapfill_btn_clicked)

        widget_toolbar = QFrame()
        grid_toolbar = QGridLayout(widget_toolbar)
        grid_toolbar.addWidget(self.btn_fill, 0, 0)
        grid_toolbar.setContentsMargins(0, 0, 0, 0)
        grid_toolbar.setColumnStretch(0, 100)

        # ---- Target Station groupbox
        self.target_station = QComboBox()
        self.target_station.currentIndexChanged.connect(
            self._handle_target_station_changed)

        self.target_station_info = QTextEdit()
        self.target_station_info.setReadOnly(True)
        self.target_station_info.setMaximumHeight(110)

        self.btn_refresh_staList = QToolButton()
        self.btn_refresh_staList.setIcon(get_icon('refresh'))
        self.btn_refresh_staList.setToolTip(
            'Force the reloading of the weather data files')
        self.btn_refresh_staList.setIconSize(get_iconsize('small'))
        self.btn_refresh_staList.setAutoRaise(True)
        self.btn_refresh_staList.clicked.connect(
            lambda: self.load_data_dir_content(force_reload=True))

        self.btn_delete_data = QToolButton()
        self.btn_delete_data.setIcon(get_icon('delete_data'))
        self.btn_delete_data.setEnabled(False)
        self.btn_delete_data.setAutoRaise(True)
        self.btn_delete_data.setToolTip(
            'Remove the currently selected dataset and delete the input '
            'datafile. However, raw datafiles will be kept.')
        self.btn_delete_data.clicked.connect(self.delete_current_dataset)

        # Generate the layout for the target station group widget.
        self.target_widget = QWidget()
        target_station_layout = QGridLayout(self.target_widget)
        target_station_layout.setHorizontalSpacing(1)
        target_station_layout.setColumnStretch(0, 1)
        target_station_layout.setContentsMargins(0, 0, 0, 0)

        widgets = [self.target_station, self.btn_refresh_staList,
                   self.btn_delete_data]
        target_station_layout.addWidget(self.target_station, 1, 0)
        for col, widget in enumerate(widgets):
            target_station_layout.addWidget(widget, 1, col)

        # Setup the gapfill dates.
        label_From = QLabel('From :  ')
        self.date_start_widget = QDateEdit()
        self.date_start_widget.setDisplayFormat('dd / MM / yyyy')
        self.date_start_widget.setEnabled(False)
        self.date_start_widget.dateChanged.connect(
            self._update_corrcoeff_table)

        label_To = QLabel('To :  ')
        self.date_end_widget = QDateEdit()
        self.date_end_widget.setEnabled(False)
        self.date_end_widget.setDisplayFormat('dd / MM / yyyy')
        self.date_end_widget.dateChanged.connect(
            self._update_corrcoeff_table)

        self.fillDates_widg = QWidget()
        gapfilldates_layout = QGridLayout(self.fillDates_widg)
        gapfilldates_layout.addWidget(label_From, 0, 0)
        gapfilldates_layout.addWidget(self.date_start_widget, 0, 1)
        gapfilldates_layout.addWidget(label_To, 1, 0)
        gapfilldates_layout.addWidget(self.date_end_widget, 1, 1)
        gapfilldates_layout.setColumnStretch(2, 1)
        gapfilldates_layout.setContentsMargins(0, 0, 0, 0)

        # Create the gapfill target station groupbox.
        target_groupbox = QGroupBox("Fill data for weather station")
        target_layout = QGridLayout(target_groupbox)
        target_layout.addWidget(self.target_widget, 0, 0)
        target_layout.addWidget(self.target_station_info, 1, 0)
        target_layout.addWidget(self.fillDates_widg, 2, 0)

        # Setup the left panel.
        self._regression_model_groupbox = (
            self._create_regression_model_settings())
        self._station_selection_groupbox = (
            self._create_station_selection_criteria())

        self.left_panel = QFrame()
        left_panel_layout = QGridLayout(self.left_panel)
        left_panel_layout.addWidget(target_groupbox, 0, 0)
        left_panel_layout.addWidget(self._station_selection_groupbox, 3, 0)
        left_panel_layout.addWidget(self._regression_model_groupbox, 4, 0)
        left_panel_layout.addWidget(widget_toolbar, 5, 0)
        left_panel_layout.setRowStretch(6, 1)
        left_panel_layout.setContentsMargins(0, 0, 0, 0)

        # Setup the right panel.
        self.corrcoeff_textedit = QTextEdit()
        self.corrcoeff_textedit.setReadOnly(True)
        self.corrcoeff_textedit.setMinimumWidth(700)
        self.corrcoeff_textedit.setFrameStyle(0)
        self.corrcoeff_textedit.document().setDocumentMargin(10)

        self.sta_display_summary = QTextEdit()
        self.sta_display_summary.setReadOnly(True)
        self.sta_display_summary.setFrameStyle(0)
        self.sta_display_summary.document().setDocumentMargin(10)

        self.right_panel = QTabWidget()
        self.right_panel.addTab(
            self.corrcoeff_textedit, 'Correlation Coefficients')
        self.right_panel.addTab(
            self.sta_display_summary, 'Data Overview')

        # Setup the progressbar.
        self.progressbar = QProgressBar()
        self.progressbar.setValue(0)
        self.progressbar.hide()

        self.statustext = QLabel()
        self.statustext.setStyleSheet(
            "QLabel {background-color: transparent; padding: 0 0 0 3px;}")
        self.statustext.setMinimumHeight(self.progressbar.minimumHeight())

        # Setup the main widget.
        main_widget = QWidget()
        main_grid = QGridLayout(main_widget)
        main_grid.addWidget(self.left_panel, 0, 0)
        main_grid.addWidget(self.right_panel, 0, 1)
        main_grid.addWidget(self.progressbar, 1, 0, 1, 2)
        main_grid.addWidget(self.statustext, 1, 0, 1, 2)
        main_grid.setColumnStretch(1, 500)
        main_grid.setRowStretch(0, 500)
        self.setCentralWidget(main_widget)

    def _create_station_selection_criteria(self):
        Nmax_label = QLabel('Nbr. of stations :')
        self.Nmax = QSpinBox()
        self.Nmax.setRange(0, 99)
        self.Nmax.setMinimum(1)
        self.Nmax.setValue(CONF.get('gapfill_data', 'nbr_of_station', 4))
        self.Nmax.setAlignment(Qt.AlignCenter)

        ttip = ('<p>Distance limit beyond which neighboring stations'
                ' are excluded from the gapfilling procedure.</p>'
                '<p>This condition is ignored if set to -1.</p>')
        distlimit_label = QLabel('Max. Distance :')
        distlimit_label.setToolTip(ttip)
        self.distlimit = QSpinBox()
        self.distlimit.setRange(-1, 9999)
        self.distlimit.setSingleStep(1)
        self.distlimit.setValue(
            CONF.get('gapfill_data', 'max_horiz_dist', 100))
        self.distlimit.setToolTip(ttip)
        self.distlimit.setSuffix(' km')
        self.distlimit.setAlignment(Qt.AlignCenter)
        self.distlimit.valueChanged.connect(self._update_corrcoeff_table)

        ttip = ('<p>Altitude difference limit over which neighboring '
                ' stations are excluded from the gapfilling procedure.</p>'
                '<p>This condition is ignored if set to -1.</p>')
        altlimit_label = QLabel('Max. Elevation Diff. :')
        altlimit_label.setToolTip(ttip)
        self.altlimit = QSpinBox()
        self.altlimit.setRange(-1, 9999)
        self.altlimit.setSingleStep(1)
        self.altlimit.setValue(
            CONF.get('gapfill_data', 'max_vert_dist', 350))
        self.altlimit.setToolTip(ttip)
        self.altlimit.setSuffix(' m')
        self.altlimit.setAlignment(Qt.AlignCenter)
        self.altlimit.valueChanged.connect(self._update_corrcoeff_table)

        # Setup the main widget.
        widget = QGroupBox('Stations Selection Criteria')
        layout = QGridLayout(widget)

        layout.addWidget(Nmax_label, 0, 0)
        layout.addWidget(self.Nmax, 0, 1)
        layout.addWidget(distlimit_label, 1, 0)
        layout.addWidget(self.distlimit, 1, 1)
        layout.addWidget(altlimit_label, 2, 0)
        layout.addWidget(self.altlimit, 2, 1)
        layout.setColumnStretch(0, 1)

        return widget

    def _create_advanced_settings(self):
        self.full_error_analysis = QCheckBox('Full Error Analysis.')
        self.full_error_analysis.setChecked(True)

        fig_opt_layout = QGridLayout()
        fig_opt_layout.addWidget(QLabel("Figure output format : "), 0, 0)
        fig_opt_layout.addWidget(self.fig_format, 0, 2)
        fig_opt_layout.addWidget(QLabel("Figure labels language : "), 1, 0)
        fig_opt_layout.addWidget(self.fig_language, 1, 2)

        fig_opt_layout.setContentsMargins(0, 0, 0, 0)
        fig_opt_layout.setColumnStretch(1, 100)

        # Setup the main layout.
        widget = QFrame()
        layout = QGridLayout(widget)
        layout.addWidget(self.full_error_analysis, 0, 0)
        layout.addLayout(fig_opt_layout, 2, 0)
        layout.setRowStretch(layout.rowCount(), 100)
        layout.setContentsMargins(10, 0, 10, 0)

        return widget

    def _create_regression_model_settings(self):
        self.RMSE_regression = QRadioButton('Ordinary Least Squares')
        self.RMSE_regression.setChecked(
            CONF.get('gapfill_data', 'regression_model', 'OLS') == 'OLS')

        self.ABS_regression = QRadioButton('Least Absolute Deviations')
        self.ABS_regression.setChecked(
            CONF.get('gapfill_data', 'regression_model', 'OLS') == 'LAD')

        widget = QGroupBox('Regression Model')
        layout = QGridLayout(widget)
        layout.addWidget(self.RMSE_regression, 0, 0)
        layout.addWidget(self.ABS_regression, 1, 0)

        return widget

    def set_statusbar_text(self, text):
        self.statustext.setText(text)

    @property
    def workdir(self):
        return self._workdir

    def set_workdir(self, dirname):
        """
        Set the working directory to dirname.
        """
        self._workdir = dirname
        self.gapfill_manager.set_workdir(dirname)
        self.load_data_dir_content()

    def delete_current_dataset(self):
        """
        Delete the current dataset source file and force a reload of the input
        daily weather datafiles.
        """
        current_index = self.target_station.currentIndex()
        if current_index != -1:
            basename = self.gapfill_manager.worker().wxdatasets.fnames[
                current_index]
            filename = os.path.join(self.workdir, basename)
            delete_file(filename)
            self.load_data_dir_content()

    def _handle_target_station_changed(self):
        """Handle when the target station is changed by the user."""
        self.btn_delete_data.setEnabled(
            self.target_station.currentIndex() != -1)
        self.update_corrcoeff()

    def get_dataset_names(self):
        """
        Return a list of the names of the dataset that are loaded in
        memory and listed in the target station dropdown menu.
        """
        return [self.target_station.itemText(i) for i in
                range(self.target_station.count())]

    # ---- Correlation coefficients
    def update_corrcoeff(self):
        """
        Calculate the correlation coefficients and display the results
        in the GUI.
        """
        if self.target_station.currentIndex() != -1:
            station_id = self.target_station.currentData()
            if self._corrcoeff_update_inprogress is True:
                self._pending_corrcoeff_update = station_id
            else:
                self._corrcoeff_update_inprogress = True
                self.corrcoeff_textedit.setText('')
                self.gapfill_manager.set_target_station(
                    station_id, callback=self._handle_corrcoeff_updated)

    def _handle_corrcoeff_updated(self):
        self._corrcoeff_update_inprogress = False
        if self._pending_corrcoeff_update is None:
            self._update_corrcoeff_table()
        else:
            self._pending_corrcoeff_update = None
            self.update_corrcoeff()

    def _update_corrcoeff_table(self):
        """
        This method plot the correlation coefficient table in the display area.

        It is separated from the method "update_corrcoeff" because red
        numbers and statistics regarding missing data for the selected
        time period can be updated in the table when the user changes the
        values without having to recalculate the correlation coefficient
        each time.
        """
        if self.target_station.currentIndex() != -1:
            table, target_info = (
                self.gapfill_manager.worker().generate_correlation_html_table(
                    self.get_gapfill_parameters()))
            self.corrcoeff_textedit.setText(table)
            self.target_station_info.setText(target_info)

    # ---- Load Data
    def load_data_dir_content(self, force_reload=False):
        """
        Load weater data from valid files contained in the working directory.
        """
        self._pending_corrcoeff_update = None
        self._loading_data_inprogress = True
        self.left_panel.setEnabled(False)
        self.right_panel.setEnabled(False)

        self.corrcoeff_textedit.setText('')
        self.target_station_info.setText('')
        self.target_station.clear()

        self.gapfill_manager.load_data(
            force_reload=force_reload,
            callback=self._handle_data_dir_content_loaded)

    def _handle_data_dir_content_loaded(self):
        """
        Handle when data finished loaded from valid files contained in
        the working directory.
        """
        self.left_panel.setEnabled(True)
        self.right_panel.setEnabled(True)

        self.target_station.blockSignals(True)
        station_names = self.gapfill_manager.get_station_names()
        station_ids = self.gapfill_manager.get_station_ids()
        for station_name, station_id in zip(station_names, station_ids):
            self.target_station.addItem(
                '{} ({})'.format(station_name, station_id),
                userData=station_id)
        self.target_station.blockSignals(False)

        self.sta_display_summary.setHtml(
            self.gapfill_manager.worker().generate_html_summary_table())

        if len(station_names) > 0:
            self._setup_fill_and_save_dates()
            self.target_station.blockSignals(True)
            self.target_station.setCurrentIndex(0)
            self.target_station.blockSignals(False)
        self._handle_target_station_changed()
        self._loading_data_inprogress = False

    def _setup_fill_and_save_dates(self):
        """
        Set first and last dates of the 'Fill data for weather station'.
        """
        if self.gapfill_manager.count():
            self.date_start_widget.setEnabled(True)
            self.date_end_widget.setEnabled(True)

            mindate = (
                self.gapfill_manager.worker()
                .wxdatasets.metadata['first_date'].min())
            maxdate = (
                self.gapfill_manager.worker()
                .wxdatasets.metadata['last_date'].max())

            qdatemin = QDate(mindate.year, mindate.month, mindate.day)
            qdatemax = QDate(maxdate.year, maxdate.month, maxdate.day)

            self.date_start_widget.blockSignals(True)
            self.date_start_widget.setDate(qdatemin)
            self.date_start_widget.setMinimumDate(qdatemin)
            self.date_start_widget.setMaximumDate(qdatemax)
            self.date_start_widget.blockSignals(False)

            self.date_end_widget.blockSignals(True)
            self.date_end_widget.setDate(qdatemax)
            self.date_end_widget.setMinimumDate(qdatemin)
            self.date_end_widget.setMaximumDate(qdatemax)
            self.date_end_widget.blockSignals(False)

    # ---- Gapfill Data
    def get_gapfill_parameters(self):
        """
        Return a dictionary containing the parameters that are set in the GUI
        for gapfilling weather data.
        """
        return {
            'limitDist': self.distlimit.value(),
            'limitAlt': self.altlimit.value(),
            'date_start': self.date_start_widget.date().toString('dd/MM/yyyy'),
            'date_end': self.date_end_widget.date().toString('dd/MM/yyyy')
            }

    def _handle_gapfill_btn_clicked(self):
        """
        Handle when the user clicked on the gapfill button.
        """
        if self.gapfill_manager.count() == 0:
            QMessageBox.warning(
                self, 'Warning', "There is no data to fill.", QMessageBox.Ok)
            return

        # Check for dates errors.
        datetime_start = datetime_from_qdatedit(self.date_start_widget)
        datetime_end = datetime_from_qdatedit(self.date_end_widget)
        if datetime_start > datetime_end:
            QMessageBox.warning(
                self, 'Warning',
                ("<i>From</i> date is set to a later time than "
                 "the <i>To</i> date."),
                QMessageBox.Ok)
            return
        if self.target_station.currentIndex() == -1:
            QMessageBox.warning(
                self, 'Warning',
                "No weather station is currently selected",
                QMessageBox.Ok)
            return

        self.start_gapfill_target()

    def _handle_gapfill_target_finished(self):
        """
        Method initiated from an automatic return from the gapfilling
        process in batch mode. Iterate over the station list and continue
        process normally.
        """
        self.btn_fill.setIcon(get_icon('fill_data'))
        self.btn_fill.setEnabled(True)

        self.target_widget.setEnabled(True)
        self.fillDates_widg.setEnabled(True)
        self._regression_model_groupbox.setEnabled(True)
        self._station_selection_groupbox.setEnabled(True)
        self.progressbar.setValue(0)
        QApplication.processEvents()
        self.progressbar.hide()

    def start_gapfill_target(self):
        # Update the gui.
        self.btn_fill.setEnabled(False)
        self.fillDates_widg.setEnabled(False)
        self.target_widget.setEnabled(False)
        self._regression_model_groupbox.setEnabled(False)
        self._station_selection_groupbox.setEnabled(False)
        self.progressbar.show()

        # Start the gapfill thread.
        self.gapfill_manager.gapfill_data(
            time_start=datetime_from_qdatedit(self.date_start_widget),
            time_end=datetime_from_qdatedit(self.date_end_widget),
            max_neighbors=self.Nmax.value(),
            hdist_limit=self.distlimit.value(),
            vdist_limit=self.altlimit.value(),
            regression_mode=self.RMSE_regression.isChecked(),
            callback=self._handle_gapfill_target_finished
            )

    def close(self):
        CONF.set('gapfill_data', 'nbr_of_station', self.Nmax.value())
        CONF.set('gapfill_data', 'max_horiz_dist', self.distlimit.value())
        CONF.set('gapfill_data', 'max_vert_dist', self.altlimit.value())
        CONF.set('gapfill_data', 'regression_model',
                 'OLS' if self.RMSE_regression.isChecked() else 'LAD')
        super().close()