def sql_qt_select(self): # Function for selection query = QtSql.QSqlQuery(self.qtsql_db) query.exec_("""SELECT * FROM u_dbtable;""") return query # values, QtSql module query.
def __init__(self, db, user, id=None, parent=None): """ Constructor @param parent reference to the parent widget @type QWidget """ super(addIncident, self).__init__(parent) self.setupUi(self) self.dbState = False self.db = db self.connectDB() self.type = '' self.serNumber = '' self.operator = user self.id = id self.dateCreationEdit.setDate(QDate.currentDate()) self.getTypesOfDevices() if id == None: pass else: # first get ID of device from incidents incidentQryTxt = "SELECT * FROM incidents WHERE idIncident = %d;" % self.id incidentQry = QtSql.QSqlQuery() ok = incidentQry.exec(incidentQryTxt) if ok: # get serial number and type of device in this incident incidentQry.first() getBasicInfoQryTxt = "SELECT serialNumber, type FROM allDevices WHERE id = %d" % incidentQry.value( 1) getBasicInfoQry = QtSql.QSqlQuery() ok = getBasicInfoQry.exec(getBasicInfoQryTxt) if ok: getBasicInfoQry.first() self.type = getBasicInfoQry.value(1) self.serNum = getBasicInfoQry.value(0) self.serialNumberEdit.setText(self.serNum) # fill other fields self.getInfo() self.dateCreationEdit.setDate(incidentQry.value(5)) self.desiredFinishDateCalendar.setSelectedDate( incidentQry.value(8)) for i in range(0, self.typeDevicesLayout.count()): if self.typeDevicesLayout.itemAt( i).widget().text() == self.type: self.typeDevicesLayout.itemAt(i).widget().setChecked( True) for i in range(0, self.brigadeLayout.count()): if self.brigadeLayout.itemAt( i).widget().text() == incidentQry.value(3): self.brigadeLayout.itemAt(i).widget().setChecked(True) # set problems, described in incident problems = [] otherProblems = "" getProblemsTxt = "SELECT typicalProblem FROM problems WHERE incident = %d;" % self.id getProblemsQry = QtSql.QSqlQuery() ok = getProblemsQry.exec(getProblemsTxt) if ok: while getProblemsQry.next(): problems.append(getProblemsQry.value(0)) getProblemsTxt = "SELECT otherProblem FROM problems WHERE incident = %d;" % self.id ok = getProblemsQry.exec(getProblemsTxt) while getProblemsQry.next(): if getProblemsQry.value(0) != "": otherProblems = getProblemsQry.value(0) for i in range(0, self.typicalProblemsLayout.count()): if self.typicalProblemsLayout.itemAt( i).widget().text() in problems: self.typicalProblemsLayout.itemAt( i).widget().setChecked(True) if otherProblems != "": self.moreButton.setChecked(True) self.commentEnabledToggle(True) self.commentEdit.setPlainText(otherProblems) self.buttonBox.accepted.disconnect(self.accept) self.buttonBox.accepted.connect(self.on_buttonBox_accepted_clicked) self.buttonBox.rejected.disconnect(self.reject) self.buttonBox.rejected.connect(self.on_buttonBox_rejected_clicked)
def anotar(self): '''Ejecuta la consulta de inserción de materias para el alumno''' self.control = self.control + 1 mat = [] self.materias = [] self.mat = [] '''Obtengo largo de la lista''' for i in self.lista: if isinstance(i, QtWidgets.QGroupBox): for c in i.findChildren(QtWidgets.QCheckBox): if c.isChecked(): mat.append(c.objectName()) self.mat.append(c.objectName()) self.materias.append("(") self.materias.append(c.objectName()) self.materias.append(", ") self.materias.append(self.dni) self.materias.append(")") self.materias.append(", ") self.materias.pop() l = "".join(self.materias) self.anotoMaterias(self.dni, l) self.AgregoFechaInscripcion() '''Obtengo el nombre del Alumno''' sql = "SELECT nombre from alumnos WHERE DNI = :dni" q = QtSql.QSqlQuery(self.db.database('asignaturas')) q.prepare(sql) q.bindValue(":dni", int(self.dni)) estado = self.ejecuto(q) formato = "portrait" while estado.next(): nombre = q.value(0) '''Obtengo la fecha actual''' fecha = QDate.currentDate() imp = Impresion() imp.creoEstilo() imp.creoStory() imp.definoEstilos() imp.agregoString("Inscripción a Materias") imp.agregoSpacer() imp.definoEstilos('txt', 10, "Helvetica", 12) txt = "Nombre del Alumno: " + nombre imp.agregoString(txt, 'txt') txt = "Fecha de Inscripción: " + fecha.toString("dd-MM-yyyy") imp.agregoString(txt, 'txt') nomMat = [] for i in mat: sql = "SELECT id_asignatura, nombre From asignaturas WHERE "\ "id_asignatura = :asig" q = QtSql.QSqlQuery(self.db.database('asignaturas')) q.prepare(sql) q.bindValue(":asig", int(i)) estado = self.ejecuto(q) # imp.definoEstilos('txt', 10, "Helvetica", 12) while estado.next(): imp.agregoSpacer() imp.agregoSpacer() imp.agregoString( "Código de Asignatura: " + str(estado.value(0)), 'txt') imp.agregoString("Nombre de Asignatura: " + estado.value(1), 'txt') imp.agregoSpacer() size = A4 imp.createPageTemplate(formato, size) imp.cierroStory() imp.imprimo() for i in mat: print(i) '''Chequeo que al menos una de las materias sea de las carreras''' if int(i) < 55: '''Chequeo que no haya pagado la matrícula''' util = Utilidades() year = util.devuelveCiclo() '''Si es así, agrego el coste de matrícula al alumno''' '''Obtengo el valor de matricula''' sql = "SELECT * FROM valores" q = self.querys(sql) estado = self.ejecuto(q) while estado.next(): if q.value(1) == 'Matricula': valor = q.value(2) descrip = q.value(1) elif q.value(1) == 'Cooperadora': descripAnual = "Cooperadora Anual" valorAnual = q.value(3) sql = "SELECT * from cuentas WHERE periodo = :per AND dni "\ "= :dni AND detalle = :det" '''sql = "INSERT INTO cuentas (Alumno, periodo, asignatura, "\ "importe, detalle, dni) VALUES (:alumno, :per, :asig, :imp, "\ ":det, :dni)"''' q = self.querys(sql) q.bindValue(":det", descrip) q.bindValue(":dni", int(self.dni)) q.bindValue(":per", year) estado = self.ejecuto(q) sql = "INSERT INTO cuentas (Alumno, periodo, asignatura, "\ "importe, detalle, dni) VALUES (:alumno, :per, :asig, :imp, "\ ":det, :dni)" if estado.size() == 0: c = util.MensajeOkNo("¿Cobrar cooperadora anual?") coop = c.exec_() if coop == 1024: q = self.querys(sql) q.bindValue(":alumno", nombre) q.bindValue(":per", year) q.bindValue(":asig", 0) q.bindValue(":imp", valorAnual) q.bindValue(":det", descripAnual) q.bindValue(":dni", int(self.dni)) estado = self.ejecuto(q) q = self.querys(sql) q.bindValue(":alumno", nombre) q.bindValue(":per", year) q.bindValue(":asig", 0) q.bindValue(":imp", valor) q.bindValue(":det", descrip) q.bindValue(":dni", int(self.dni)) estado = self.ejecuto(q) pass c = self.parentWidget() c.alumnos()
def cargaDatos(self): """ Modulos que se encarga de la importacion de los datos de un Excel :return: None :rtype: None Dependiendo de si ya existen los productos o no solo actualiza el stock, despues actualiza la tabla de Productos. """ try: documento = xlrd.open_workbook(str(var.fileimp)) productos = documento.sheet_by_index(0) filas_prod = productos.nrows cont = 0 for i in range(1, filas_prod): prod_nom = str(productos.cell_value(i, 0)) prod_precio = repr(productos.cell_value(i, 1)) prod_stock = int(productos.cell_value(i, 2)) query = QtSql.QSqlQuery() query.prepare( 'select codigo, precio, stock from articulos where nombre = :nombre' ) query.bindValue(':nombre', str(prod_nom)) if query.exec_(): while query.next(): cont = cont + 1 query1 = QtSql.QSqlQuery() query1.prepare( 'update articulos set precio=:precio, stock=:stock where nombre = :nombre' ) query1.bindValue(':nombre', str(prod_nom)) query1.bindValue(':precio', float(prod_precio)) stock = int(query.value(2)) + prod_stock query1.bindValue(':stock', int(stock)) if query1.exec_(): var.ui.lblstatus.setText( 'Articulos actualizados Fecha: ' + str(datetime.today().strftime( '%A, %d de %B de %Y'))) else: print("Error actualizando productos: ", query1.lastError().text()) if cont == 0: query2 = QtSql.QSqlQuery() query2.prepare( 'insert into articulos (nombre, precio, stock) VALUES (:nombre, :precio, :stock)' ) query2.bindValue(':nombre', str(prod_nom)) query2.bindValue(':precio', float(prod_precio)) query2.bindValue(':stock', int(prod_stock)) if query2.exec_(): var.ui.lblstatus.setText( 'Articulos añadidos Fecha: ' + str(datetime.today().strftime( '%A, %d de %B de %Y'))) else: print("Error añadiendo productos: ", query2.lastError().text()) conexion.Conexion.db_connect(var.filebd) conexion.Conexion.mostrarProducto(self) except Exception as error: print('Error en la carga de datos: %s' % str(error))
def Insertar(self): print("entro a insertar") print("Insertar" + str(self.dni)) # db = self.db.CreateConnection(self.usr, self.passw) # Obtengo un cursor de DB abierto print("Nombre de la conexión " + self.db.connectionName()) #Obtengo listado de campos de la tabla campos = "SHOW COLUMNS from alumnos WHERE Field <> 'IdAlumnos' AND Field <> 'Apellido' AND Field <> 'cohorte' AND Field <> 'Grupo_Sanguineo' AND Field <> 'Ántitetanica' AND Field <> 'Presion_Arterial' AND Field <> 'Enfermedades' AND Field <> 'Tratamiento' AND Field <> 'alergias' AND Field <> 'foto'" print("Nombre de la conexión " + self.db.connectionName()) q = QtSql.QSqlQuery(self.db.database('inscripciones')) q.prepare(campos) q.exec_() cadena = "" print("entro al while") while q.next(): cadena = cadena + q.value(0) + ", " total = len(cadena.rstrip()) cadena1 = cadena[0:total - 1] print("Cadena " + cadena1) #Preparo la cadena sql '''diccio = {'Nombre': :nombre, 'DNI': :dni, 'Lugar_Nacimiento': :lunac, 'Fecha_Nacimiento': ':fenac', 'Edad': ':edad', 'Domicilio': ':calle', 'numero': ':numero', 'piso': ':piso', 'depto': ':depto', 'Estado_Civil': ':civil', 'Localidad': ':local', 'Partido': ':partido', 'CP': ':cp', 'Telefono': ':tel', 'Celular': ':mov', 'Estudios_Cursados': ':ecurs', 'Otros': ':otros', 'Trabaja': ':trab', 'Ocupacion': ':activ', 'emergencias': ':emer', 'osocial': ':os', 'Sexo': ':sexo', 'Carrera': ':carrera', 'ciclo': ':anio', 'horario': ':hora', 'Nacionalidad': ':lugar', 'hijos': ':hijos', 'acargo': ':flia', 'mail': ':mail', 'egreso': ':egreso', 'insti_otros': ':insti', 'escuela': ':escuela', 'distrito': ':distri', 'doc_dni': ':doc_dni', 'doc_Tit': ':doc_Tit', 'doc_Reg': ':doc_reg', 'doc_fot': ':doc_fot', 'doc_cert': ':doc_cert'}''' sql = "UPDATE alumnos SET Nombre = :nombre, DNI = :dni, "\ " Lugar_Nacimiento = :lunac, Fecha_Nacimiento = :fenac, "\ "Edad = :edad, Domicilio = :calle, numero = :numero, "\ "piso = :piso, depto = :depto, Estado_Civil = :civil, "\ "Localidad = :local, Partido = :partido, CP = :cp, "\ "Telefono = :tel, Celular = :mov, "\ "Estudios_Cursados = :ecurs, Otros = :otros, "\ "Trabaja = :trab, Ocupacion = :activ, emergencias = :emer, "\ "osocial = :os, Sexo = :sexo, Carrera = :carrera, "\ "ciclo = :anio, horario = :hora, Nacionalidad = :lugar, "\ "hijos = :hijos, acargo = :flia, mail = :mail, "\ "egreso = :egreso, insti_otros = :insti, "\ "escuela = :escuela, distrito = :distri, doc_dni = :doc_dni, "\ "doc_Tit = :doc_Tit, doc_Reg = :doc_reg, doc_fot = :doc_fot, "\ "doc_cert = :doc_cert "\ " WHERE DNI = :selfdni" print(" Este sql " + str(sql)) # sql = "INSERT INTO alumnos(Nombre, DNI, Lugar_Nacimiento, Fecha_Nacimiento, Edad, Domicilio, numero, piso, depto, Estado_Civil, Localidad, Partido, CP, Telefono, Celular, Estudios_Cursados, Otros, Trabaja, Ocupacion, emergencias, osocial, Sexo, Carrera, ciclo, Nacionalidad, hijos, acargo, mail, egreso, insti_otros, escuela, distrito, doc_dni, doc_Tit, doc_Reg, doc_fot, doc_cert) VALUES (:nombre, :dni, :lugar, :fenac, :edad, :calle, :numero, :piso, :depto, :civil, :local, :partido, :cp, :tel, :mov, :ecurs, :otros, :trab, :activ, :emer, :os, :sexo, :carrera, :anio, :lunac, :hijos, :flia, :mail, :egreso, :insti, :escuela, :distri, :doc_dni, :doc_Tit, :doc_reg, :doc_fot, :doc_cert)" # , Fecha_Nacimiento, Edad, Domicilio, numero, piso, depto, Estado_Civil, Localidad, Partido, CP, Telefono, Celular, Estudios_Cursados, Otros, Trabaja, Ocupacion, emergencias, osocial, Sexo, Carrera, ciclo, Nacionalidad, hijos, acargo, mail, egreso, insti_otros, escuela, distrito, doc_dni, doc_Tit, doc_Reg, doc_fot, doc_cert) VALUES (:nombre,:dni,:lugar,:fenac,:edad,:calle,:numero,:piso,:depto,:civil,:local,:partido,:cp,:tel,:mov,:ecurs,:otros,:trab,:activ,:emer,:os,:sexo,:carrera,:anio,:lunac,:hijos,:flia,:mail,:egreso,:insti,:escuela :distri :doc_dni :doc_Tit :doc_reg :doc_fot)"''' #Creo el objeto para hacer la consulta print("Nombre de la conexión " + self.db.connectionName()) q = QtSql.QSqlQuery(self.db.database('inscripciones')) q.prepare(sql) q.bindValue(":nombre", self.Nombre) q.bindValue(":dni", self.dni) q.bindValue(":lugar", self.lnNa) q.bindValue(":fenac", self.fenac) q.bindValue(":edad", self.edad) q.bindValue(":calle", self.calle) q.bindValue(":numero", self.numero) q.bindValue(":piso", self.piso) q.bindValue(":depto", self.depto) q.bindValue(":civil", self.civil) q.bindValue(":local", self.local) q.bindValue(":partido", self.partido) q.bindValue(":cp", self.cp) q.bindValue(":tel", self.tel) # Validador q.bindValue(":mov", self.movil) # validador q.bindValue(":ecurs", self.titulo) q.bindValue(":otros", self.otros) q.bindValue(":trab", self.trab) q.bindValue(":activ", self.activ) q.bindValue(":emer", self.emergencia) q.bindValue(":os", self.os) q.bindValue(":sexo", self.sexo) q.bindValue(":carrera", self.carrera) q.bindValue(":anio", self.anio) q.bindValue(":lunac", self.lunac) q.bindValue(":hijos", self.hijos) q.bindValue(":flia", self.familia) q.bindValue(":mail", self.mail) q.bindValue(":egreso", self.egreso) institutos = self.insti1 + ", " + self.insti2 q.bindValue(":insti", institutos) q.bindValue(":escuela", self.escuela) q.bindValue(":distri", self.distrito) print(self.fotoDni) q.bindValue(":doc_dni", self.fotoDni) q.bindValue(":doc_Tit", self.fotoTit) q.bindValue(":doc_reg", self.numReg) q.bindValue(":doc_fot", self.fotos) q.bindValue(":doc_cert", self.certif) q.bindValue(":hora", self.horario) q.bindValue(":selfdni", self.dni) if self.db.database('inscripciones').isOpen(): print("Damned world") else: print(self.db.connectionName() + " esta abierta") q.prepare(sql) estado = q.exec_() pipi = q.executedQuery() if estado is True: print("tudobom") self.close() else: print("DNI " + str(self.dni)) print(pipi) print((self.db.database('inscripciones').lastError()))
def add_new_tab( self, tab_name, model, new=False ): #теперь этот метод более универсален, так как тип модели передаём в параметрах print('in add new tab', tab_name) tab_names = [] if new: for t in self.tab_data.tables(): query = QtSql.QSqlQuery(self.tab_data) query.exec('select name from {0}'.format(t)) if query.isActive(): query.first() while query.isValid(): tab_names.append(query.value('name')) query.next() query.finish() print('tab names', tab_names) # режим выделения с Ctrl if tab_name not in tab_names: # проверяем, что нет вкладки с таким же именем self.table_count += 1 #строка ввода line_add_tag = QW.QLineEdit() validator = QtGui.QRegExpValidator( QtCore.QRegExp('\w{1,}.{0,}')) # обязательна буква или цифра # от ноля и больше вхождения любого символа, но минимум одна буква или цифра line_add_tag.setValidator( validator ) #добавили валидатор по созданному регулярному выражению line_add_tag.setPlaceholderText( "<Enter tag's name here>") # замещающий текст #тэги будем представлять в виде списка tag_list = QW.QListView() #model = QtGui.QStandardItemModel()#модель задаём в параметрах tag_list.setModel(model) tag_list.setSelectionMode( QW.QAbstractItemView.ExtendedSelection ) #режим множественного выделения, с ctrl и областью tag_list.setResizeMode( QW.QListView.Adjust ) #подгоняем размещение элементов под размер списка tag_list.setFlow(QW.QListView.LeftToRight) #направление вывода tag_list.setWrapping( True) #перенос элементов на новую строку разрешён tag_list.setWordWrap( True) #перенос текста элементов на новую строку разрешён #tag_list.setUniformItemSizes(True) width_size = QtCore.QSize(200, 30) tag_list.setGridSize( width_size ) #задаём размеры таблицы размещения, 200 - макс. длина строки до #обрезки текста, 30 - отступ между строками по вертикали #скрыть первую строку #tag_list.setMovement(QW.QListView.Free)#почему-то дублирует перетаскиваемый объект #model.itemChanged.connect(lambda:print('asdasd'))#сигнал о том, что какой-то элемент был изменён #надо установить валидатор... #слой для строки ввода и тэгов vb = QW.QVBoxLayout() vb.setAlignment(QtCore.Qt.AlignTop) #vb.addLayout(hb) vb.addWidget(line_add_tag) vb.addWidget(tag_list) #btn_plus.clicked.connect(lambda: self.valid_checkbox_name(line_add_tag.text(), line_add_tag, model)) #btn_delete.clicked.connect(lambda: self.delete_checkbox_by_name(model)) #btn_appoint.clicked.connect(lambda: QtCore.QCoreApplication.sendEvent(item_list.Item_List(), Mid())) #контейнер - обязательно виджет, гроупбокс или подобное tag_group = QW.QWidget() tag_group.setLayout(vb) #не нужна в связи с переходом на представление в виде списка #scrollArea = QW.QScrollArea() #scrollArea.setWidget(tag_group)#вставили контейнер с сеткой #scrollArea.setWidgetResizable(True)#без этого сетка с множеством компонентов тупо сжимается #scrollArea.ensureWidgetVisible(line_add_tag) #сигналы line_add_tag.returnPressed.connect( lambda: self.valid_checkbox_name(line_add_tag.text( ), line_add_tag, model)) # вызывается при нажатии Enter self.addTab(tag_group, tab_name) # self.setCurrentIndex( self.count() - 1) # автоматически переключаемся на созданную вкладку t_name = '_' + str(self.table_count) + '_' self.tab_model_dict[tab_name] = ( model, tag_list.selectionModel() ) #для того, чтобы можно было удалять теги из модели во вкладке #print(self.tab_model_dict) #будем удалять из model тот чекбокс, который выделен в selectionModel #записываем вкладку в базу данных: if new: print("write_tab_sql from add tab") self.write_tab_sql(tab_name) else: print( 'вкладка с таким именем уже существует! добавить диалог с ошибкой' )
def __init__(self, parent=None): QWidget.__init__(self, parent) self.interface_lng_val = parent.interface_lng_val self.con = parent.con self.full_dir = parent.full_dir self.par = parent if self.con.open(): self.table = QTableWidget(19, 2) self.table.setColumnWidth(0, 150) self.table.setColumnWidth(1, 230) self.table.setFixedSize(674, 480) if self.interface_lng_val == 'Russian': self.table.setHorizontalHeaderLabels(["Параметр", "Значение"]) elif self.interface_lng_val == 'English': self.table.setHorizontalHeaderLabels(["Parameter", "Value"]) # application application_lbl = QLabel('application') self.application = QComboBox() application_list = [ "compressibleInterFoam", "rhoCentralFoam", "sonicFoam", "icoFoam", "pisoFoam" ] self.application.addItems(application_list) self.table.setCellWidget(0, 1, self.application) self.table.setCellWidget(0, 0, application_lbl) # startFrom startFrom_lbl = QLabel('startFrom') self.startFrom = QComboBox() startFrom_list = ["startTime", "latestTime"] self.startFrom.addItems(startFrom_list) self.table.setCellWidget(1, 1, self.startFrom) self.table.setCellWidget(1, 0, startFrom_lbl) # startTime startTime_lbl = QLabel('startTime') self.startTime = QSpinBox() self.table.setCellWidget(2, 1, self.startTime) self.table.setCellWidget(2, 0, startTime_lbl) # stopAt stopAt_lbl = QLabel('stopAt') self.stopAt = QComboBox() stopAt_list = ["endTime"] self.stopAt.addItems(stopAt_list) self.table.setCellWidget(3, 1, self.stopAt) self.table.setCellWidget(3, 0, stopAt_lbl) # endTime endTime_lbl = QLabel('endTime') self.endTime = QDoubleSpinBox() self.endTime.setRange(0, 10000) self.table.setCellWidget(4, 1, self.endTime) self.table.setCellWidget(4, 0, endTime_lbl) # deltaT deltaT_lbl = QLabel('deltaT') self.deltaT = QLineEdit() self.deltaT.setFixedSize(100, 25) #self.deltaT.setRange(0, 10000) self.table.setCellWidget(5, 1, self.deltaT) self.table.setCellWidget(5, 0, deltaT_lbl) # writeControl writeControl_lbl = QLabel('writeControl') self.writeControl = QComboBox() writeControl_list = ["timeStep", "adjustableRunTime"] self.writeControl.addItems(writeControl_list) self.table.setCellWidget(6, 1, self.writeControl) self.table.setCellWidget(6, 0, writeControl_lbl) # writeInterval writeInterval_lbl = QLabel('writeInterval') self.writeInterval = QDoubleSpinBox() self.writeInterval.setRange(0, 10000) self.table.setCellWidget(7, 1, self.writeInterval) self.table.setCellWidget(7, 0, writeInterval_lbl) # purgeWrite purgeWrite_lbl = QLabel('purgeWrite') self.purgeWrite = QSpinBox() self.purgeWrite.setRange(0, 10000) self.table.setCellWidget(8, 1, self.purgeWrite) self.table.setCellWidget(8, 0, purgeWrite_lbl) # writeFormat writeFormat_lbl = QLabel('writeFormat') self.writeFormat = QComboBox() writeFormat_list = ["ascii", "binary"] self.writeFormat.addItems(writeFormat_list) self.table.setCellWidget(9, 1, self.writeFormat) self.table.setCellWidget(9, 0, writeFormat_lbl) # writePrecision writePrecision_lbl = QLabel('writePrecision') self.writePrecision = QSpinBox() self.writePrecision.setRange(0, 10000) self.table.setCellWidget(10, 1, self.writePrecision) self.table.setCellWidget(10, 0, writePrecision_lbl) # writeCompression writeCompression_lbl = QLabel('writeCompression') self.writeCompression = QComboBox() writeCompression_list = ["off"] self.writeCompression.addItems(writeCompression_list) self.table.setCellWidget(11, 1, self.writeCompression) self.table.setCellWidget(11, 0, writeCompression_lbl) # timeFormat timeFormat_lbl = QLabel('timeFormat') self.timeFormat = QComboBox() timeFormat_list = ["general"] self.timeFormat.addItems(timeFormat_list) self.table.setCellWidget(12, 1, self.timeFormat) self.table.setCellWidget(12, 0, timeFormat_lbl) # timePrecision timePrecision_lbl = QLabel('timePrecision') self.timePrecision = QSpinBox() self.timePrecision.setRange(0, 10000) self.table.setCellWidget(13, 1, self.timePrecision) self.table.setCellWidget(13, 0, timePrecision_lbl) # runTimeModifiable runTimeModifiable_lbl = QLabel('runTimeModifiable') self.runTimeModifiable = QComboBox() runTimeModifiable_list = ["yes", "no"] self.runTimeModifiable.addItems(runTimeModifiable_list) self.table.setCellWidget(14, 1, self.runTimeModifiable) self.table.setCellWidget(14, 0, runTimeModifiable_lbl) # adjustTimeStep adjustTimeStep_lbl = QLabel('adjustTimeStep') self.adjustTimeStep = QComboBox() adjustTimeStep_list = ["yes", "no"] self.adjustTimeStep.addItems(adjustTimeStep_list) self.table.setCellWidget(15, 1, self.adjustTimeStep) self.table.setCellWidget(15, 0, adjustTimeStep_lbl) # maxCo maxCo_lbl = QLabel('maxCo') self.maxCo = QDoubleSpinBox() self.maxCo.setRange(0, 10000) self.table.setCellWidget(16, 1, self.maxCo) self.table.setCellWidget(16, 0, maxCo_lbl) # maxAlphaCo maxAlphaCo_lbl = QLabel('maxAlphaCo') self.maxAlphaCo = QDoubleSpinBox() self.maxAlphaCo.setRange(0, 10000) self.table.setCellWidget(17, 1, self.maxAlphaCo) self.table.setCellWidget(17, 0, maxAlphaCo_lbl) # maxDeltaT maxDeltaT_lbl = QLabel('maxDeltaT') self.maxDeltaT = QSpinBox() self.maxDeltaT.setRange(0, 10000) self.table.setCellWidget(18, 1, self.maxDeltaT) self.table.setCellWidget(18, 0, maxDeltaT_lbl) # вывод значений параметров if 'controlDict' in self.con.tables(): query = QtSql.QSqlQuery() query.exec("SELECT * FROM controlDict") if query.isActive(): query.first() value_list = [] while query.isValid(): value_res = query.value('value') value_list.append(value_res) query.next() # application application_mas = self.application.count() for i in range(application_mas): if self.application.itemText(i) == value_list[0]: self.application.setCurrentIndex(i) # startFrom startFrom_mas = self.startFrom.count() for i in range(startFrom_mas): if self.startFrom.itemText(i) == value_list[1]: self.startFrom.setCurrentIndex(i) # startTime self.startTime.setValue(value_list[2]) # stopAt stopAt_mas = self.stopAt.count() for i in range(stopAt_mas): if self.stopAt.itemText(i) == value_list[3]: self.stopAt.setCurrentIndex(i) # endTime self.endTime.setValue(value_list[4]) # deltaT self.deltaT.setText(str(value_list[5])) # writeControl writeControl_mas = self.writeControl.count() for i in range(writeControl_mas): if self.writeControl.itemText(i) == value_list[6]: self.writeControl.setCurrentIndex(i) # writeInterval self.writeInterval.setValue(value_list[7]) # purgeWrite self.purgeWrite.setValue(value_list[8]) # writeFormat writeFormat_mas = self.writeFormat.count() for i in range(writeFormat_mas): if self.writeFormat.itemText(i) == value_list[9]: self.writeFormat.setCurrentIndex(i) # writePrecision self.writePrecision.setValue(value_list[10]) # writeCompression writeCompression_mas = self.writeCompression.count() for i in range(writeCompression_mas): if self.writeCompression.itemText(i) == value_list[11]: self.writeCompression.setCurrentIndex(i) # timeFormat timeFormat_mas = self.timeFormat.count() for i in range(timeFormat_mas): if self.timeFormat.itemText(i) == value_list[12]: self.timeFormat.setCurrentIndex(i) # timePrecision self.timePrecision.setValue(value_list[13]) # runTimeModifiable runTimeModifiable_mas = self.runTimeModifiable.count() for i in range(runTimeModifiable_mas): if self.runTimeModifiable.itemText( i) == value_list[14]: self.runTimeModifiable.setCurrentIndex(i) # adjustTimeStep adjustTimeStep_mas = self.adjustTimeStep.count() for i in range(adjustTimeStep_mas): if self.adjustTimeStep.itemText(i) == value_list[15]: self.adjustTimeStep.setCurrentIndex(i) # maxCo self.maxCo.setValue(value_list[16]) # maxAlphaCo self.maxAlphaCo.setValue(value_list[17]) # maxDeltaT self.maxDeltaT.setValue(value_list[18]) btnSave = QPushButton() btnSave.setFixedSize(80, 25) btnSave.clicked.connect(self.on_btnSave_clicked) if self.interface_lng_val == 'Russian': btnSave.setText("Сохранить") elif self.interface_lng_val == 'English': btnSave.setText("Save") vbox = QVBoxLayout() vbox.addWidget(self.table) vbox.addWidget(btnSave) # ---------------------Размещение на форме всех компонентов------------------------- form = QFormLayout() form.addRow(vbox) self.setLayout(form)
def t09_patient_remove(self, id): self.__execute( '''delete from patients where patients.idpatients = ''' + id) model = QtSql.QSqlQueryModel() model.setQuery(QtSql.QSqlQuery('select * from patients')) return model
def t09_services(self): model = QtSql.QSqlQueryModel() model.setQuery(QtSql.QSqlQuery('select * from services')) return model
def Ingresos(self): tipo = self.ventanahotel.cBIngresos.currentText() dia = time.strftime("%d/%m/%y") mes = time.strftime("%m/%y") anio = time.strftime("/%y") self.EGIG = "Ingreso" self.ventanahotel.tablaCuentas.setHorizontalHeaderLabels( ['N°', 'Fecha', self.EGIG]) for i in range(self.ventanahotel.tablaCuentas.rowCount()): self.ventanahotel.tablaCuentas.removeRow(i) if tipo == "Dia": self.db.open() consulta = QtSql.QSqlQuery() consulta.exec_( "SELECT * FROM Ingresos WHERE Fecha BETWEEN'%s' and '%s'" % (dia, dia)) row = 0 for i in range(self.ventanahotel.tablaCuentas.rowCount()): self.ventanahotel.tablaCuentas.removeRow(i) while consulta.next(): self.ventanahotel.tablaCuentas.insertRow(row) Numero = QTableWidgetItem(str(consulta.value(0))) Fecha = QTableWidgetItem(str(consulta.value(1))) Ingreso = QTableWidgetItem(str(consulta.value(2))) self.ventanahotel.tablaCuentas.setItem(row, 0, Numero) self.ventanahotel.tablaCuentas.setItem(row, 1, Fecha) self.ventanahotel.tablaCuentas.setItem(row, 2, Ingreso) row = row + 1 self.db.close() elif tipo == "Mes": self.db.open() consulta = QtSql.QSqlQuery() consulta.exec_( "SELECT * FROM Ingresos WHERE Fecha BETWEEN '%s' and '%s'" % ('1/' + mes, '31/' + mes)) row = 0 for i in range(self.ventanahotel.tablaCuentas.rowCount()): self.ventanahotel.tablaCuentas.removeRow(i) while consulta.next(): self.ventanahotel.tablaCuentas.insertRow(row) Numero = QTableWidgetItem(str(consulta.value(0))) Fecha = QTableWidgetItem(str(consulta.value(1))) Ingreso = QTableWidgetItem(str(consulta.value(2))) self.ventanahotel.tablaCuentas.setItem(row, 0, Numero) self.ventanahotel.tablaCuentas.setItem(row, 1, Fecha) self.ventanahotel.tablaCuentas.setItem(row, 2, Ingreso) row = row + 1 self.db.close() elif tipo == "Año": self.db.open() consulta = QtSql.QSqlQuery() consulta.exec_( "SELECT * FROM Ingresos WHERE Fecha BETWEEN '%s' and '%s'" % ('1/1' + anio, '31/12' + anio)) row = 0 for i in range(self.ventanahotel.tablaCuentas.rowCount()): self.ventanahotel.tablaCuentas.removeRow(i) while consulta.next(): self.ventanahotel.tablaCuentas.insertRow(row) Numero = QTableWidgetItem(str(consulta.value(0))) Fecha = QTableWidgetItem(str(consulta.value(1))) Ingreso = QTableWidgetItem(str(consulta.value(2))) self.ventanahotel.tablaCuentas.setItem(row, 0, Numero) self.ventanahotel.tablaCuentas.setItem(row, 1, Fecha) self.ventanahotel.tablaCuentas.setItem(row, 2, Ingreso) row = row + 1 self.db.close() else: for i in range(self.ventanahotel.tablaCuentas.rowCount()): self.ventanahotel.tablaCuentas.removeRow(i)
def t09_patients(self): model = QtSql.QSqlQueryModel() model.setQuery(QtSql.QSqlQuery('select * from patients')) return model
def Ver_Clientes(self): tipo = self.ventanahotel.cBClientes.currentText() dia = time.strftime("%d/%m/%y") mes = time.strftime("%m/%y") anio = time.strftime("/%y") for i in range(self.ventanahotel.tablaClientes.rowCount()): self.ventanahotel.tablaClientes.removeRow(i) if tipo == "Dia": self.db.open() consulta = QtSql.QSqlQuery() consulta.exec_( "SELECT * FROM CantClientes WHERE Fecha BETWEEN '%s' and '%s'" % (dia, dia)) row = 0 for i in range(self.ventanahotel.tablaClientes.rowCount()): self.ventanahotel.tablaClientes.removeRow(i) while consulta.next(): self.ventanahotel.tablaClientes.insertRow(row) Numero = QTableWidgetItem(str(consulta.value(0))) Fecha = QTableWidgetItem(str(consulta.value(1))) Cantidad = QTableWidgetItem(str(consulta.value(2))) self.ventanahotel.tablaClientes.setItem(row, 0, Numero) self.ventanahotel.tablaClientes.setItem(row, 1, Fecha) self.ventanahotel.tablaClientes.setItem(row, 2, Cantidad) row = row + 1 self.db.close() elif tipo == "Mes": self.db.open() consulta = QtSql.QSqlQuery() consulta.exec_( "SELECT * FROM CantClientes WHERE Fecha BETWEEN '%s' and '%s'" % ('1/' + mes, '31/' + mes)) row = 0 for i in range(self.ventanahotel.tablaClientes.rowCount()): self.ventanahotel.tablaClientes.removeRow(i) while consulta.next(): self.ventanahotel.tablaClientes.insertRow(row) Numero = QTableWidgetItem(str(consulta.value(0))) Fecha = QTableWidgetItem(str(consulta.value(1))) Cantidad = QTableWidgetItem(str(consulta.value(2))) self.ventanahotel.tablaClientes.setItem(row, 0, Numero) self.ventanahotel.tablaClientes.setItem(row, 1, Fecha) self.ventanahotel.tablaClientes.setItem(row, 2, Cantidad) row = row + 1 self.db.close() elif tipo == "Año": self.db.open() consulta = QtSql.QSqlQuery() consulta.exec_( "SELECT * FROM CantClientes WHERE Fecha BETWEEN '%s' and '%s'" % ('1/1' + anio, '31/12' + anio)) row = 0 for i in range(self.ventanahotel.tablaClientes.rowCount()): self.ventanahotel.tablaClientes.removeRow(i) while consulta.next(): self.ventanahotel.tablaClientes.insertRow(row) Numero = QTableWidgetItem(str(consulta.value(0))) Fecha = QTableWidgetItem(str(consulta.value(1))) Cantidad = QTableWidgetItem(str(consulta.value(2))) self.ventanahotel.tablaClientes.setItem(row, 0, Numero) self.ventanahotel.tablaClientes.setItem(row, 1, Fecha) self.ventanahotel.tablaClientes.setItem(row, 2, Cantidad) row = row + 1 self.db.close() else: for i in range(self.ventanahotel.tablaClientes.rowCount()): self.ventanahotel.tablaClientes.removeRow(i)
def imprimir(conexion, obra, documento, propiedades=None): consulta = QtSql.QSqlQuery(conexion) Autor = "" Obra = "" Listado = u"RESUMEN DE PRESUPUESTO" Instancia = modulo.Estilo() s = documento.styles d = Instancia.ListaEstilos() for key in d: s.addElement(d[key]) precision = "%.2f" ############### ###Contenido### ############### #Titulo consulta.exec_( "SELECT resumen FROM \"" + obra + "_Conceptos\" AS C, \"" + obra + "_Relacion\" AS R WHERE C.codigo = R.codhijo AND R.codpadre IS NULL") resumen = "" while consulta.next(): resumen = consulta.value(0) linea = Listado parrafo = P(stylename=Instancia.Estilos("Heading 1")) teletype.addTextToElement(parrafo, linea) documento.text.addElement(parrafo) titulo = P(stylename=Instancia.Estilos("Heading 2")) teletype.addTextToElement(titulo, resumen) documento.text.addElement(titulo) #linea horizontal linea = " " lineahorizontal = P(stylename=Instancia.Estilos("Linea horizontal gruesa")) teletype.addTextToElement(lineahorizontal, linea) documento.text.addElement(lineahorizontal) #consulta consulta.exec_("SELECT * FROM ver_resumen_capitulos('" + obra + "')") #datos de la consulta rec = consulta.record() codigo = rec.indexOf("codigo") resumen = rec.indexOf("resumen") cantidad = rec.indexOf("cantidad") euros = rec.indexOf("total") porcentaje = rec.indexOf("porcentaje") EM = 0.0 while consulta.next(): linea = consulta.value( codigo) + "\t" + consulta.value(resumen) + "\t" + formatear( consulta.value(euros)) + "\t" + formatear( consulta.value(porcentaje)) + " %" print(linea) tabp = P( stylename=Instancia.Estilos("Normal con tabuladores capitulos")) teletype.addTextToElement(tabp, linea) documento.text.addElement(tabp) EM = EM + consulta.value(euros) #EM salto = P() lb = LineBreak() salto.addElement(lb) documento.text.addElement(salto) lineaEM = "\tTotal Ejecución Material:\t" + formatear(EM) parrafo = P( stylename=Instancia.Estilos("Normal con tabuladores resumen negritas")) teletype.addTextToElement(parrafo, lineaEM) documento.text.addElement(parrafo) #GG GG = 0.0 consulta.exec_( "SELECT datos->>'Valor' FROM (SELECT jsonb_array_elements(propiedades->'Valor') AS datos \ FROM \"" + obra + "_Propiedades\" \ WHERE propiedades->>'Propiedad' = 'Porcentajes') AS subdatos WHERE datos->>'Variable' = 'zPorGastosGenerales'" ) while consulta.next(): GG = float(consulta.value(0)) print("Gastos generales " + str(GG) + "\t") GastosGenerales = EM * GG / 100 lineaGG = "\t\t" + str(GG) + "% Gastos generales\t" + formatear( GastosGenerales) parrafo = P(stylename=Instancia.Estilos("Normal con tabuladores resumen")) teletype.addTextToElement(parrafo, lineaGG) documento.text.addElement(parrafo) #BI BI = 0.0 consulta.exec_( "SELECT datos->>'Valor' FROM (SELECT jsonb_array_elements(propiedades->'Valor') AS datos \ FROM \"" + obra + "_Propiedades\" \ WHERE propiedades->>'Propiedad' = 'Porcentajes') AS subdatos WHERE datos->>'Variable' = 'zPorBenIndustrial'" ) while consulta.next(): BI = float(consulta.value(0)) print("Gastos generales " + str(BI) + "\t") BeneficioIndustrial = EM * BI / 100 lineaBI = "\t\t" + str(BI) + "%Beneficio Industrial\t" + formatear( BeneficioIndustrial) parrafo = P(stylename=Instancia.Estilos("Normal con tabuladores resumen")) teletype.addTextToElement(parrafo, lineaBI) documento.text.addElement(parrafo) #suma de GG+BI lineaGGBI = "\t\tSuma de G.G. + B.I.: \t" + formatear(GastosGenerales + BeneficioIndustrial) parrafo = P(stylename=Instancia.Estilos("Normal con tabuladores resumen")) teletype.addTextToElement(parrafo, lineaGGBI) documento.text.addElement(parrafo) #PContrata importeTPC = EM + GastosGenerales + BeneficioIndustrial lineaTPC = "\tTOTAL PRESUPUESTO DE CONTRATA: \t" + formatear(importeTPC) parrafo = P( stylename=Instancia.Estilos("Normal con tabuladores resumen negritas")) teletype.addTextToElement(parrafo, lineaTPC) documento.text.addElement(parrafo) #IVA IVA = 0 consulta.exec_( "SELECT datos->>'Valor' FROM (SELECT jsonb_array_elements(propiedades->'Valor') AS datos \ FROM \"" + obra + "_Propiedades\" \ WHERE propiedades->>'Propiedad' = 'Porcentajes') AS subdatos WHERE datos->>'Variable' = 'zPorIVAEjecucion'" ) while consulta.next(): IVA = float(consulta.value(0)) importeIVA = importeTPC * IVA / 100 lineaIVA = "\t\t" + str(IVA) + "% IVA\t" + formatear(importeIVA) parrafo = P(stylename=Instancia.Estilos("Normal con tabuladores resumen")) teletype.addTextToElement(parrafo, lineaIVA) documento.text.addElement(parrafo) #PGeneral importeTPG = importeTPC + (importeTPC * IVA / 100) lineaTPC = "\tTOTAL PRESUPUESTO GENERAL: \t" + formatear(importeTPG) parrafo = P( stylename=Instancia.Estilos("Normal con tabuladores resumen negritas")) teletype.addTextToElement(parrafo, lineaTPC) documento.text.addElement(parrafo) #salto salto = P() lb = LineBreak() salto.addElement(lb) documento.text.addElement(salto) #cantidad en letra consulta.exec_("SELECT numero_en_euro(" + str(importeTPG) + ")") print(consulta.lastError().text()) cantidadenletra = "" while consulta.next(): cantidadenletra = consulta.value(0) print("cantidad en letras " + cantidadenletra) resumen = P() texto_resumen = Span( stylename=Instancia.Estilos("Normal"), text="Asciende el presupuesto general a la expresada cantidad de ") resumen.addElement(texto_resumen) texto_cantidad_letra = Span(stylename=Instancia.Estilos("Negritas"), text=cantidadenletra) resumen.addElement(texto_cantidad_letra) documento.text.addElement(resumen) #firmas-datos encabezado_firma_proyectista = "" nombre_proyectista1 = "" nombre_proyectista2 = "" encabezado_firma_promotor = "" nombre_promotor1 = "" nombre_promotor2 = "" ciudad = "" consulta.exec_( "SELECT datos->>'Valor' FROM (SELECT jsonb_array_elements(propiedades->'Valor') AS datos \ FROM \"" + obra + "_Propiedades\" \ WHERE propiedades->>'Propiedad' = 'Proyectista') AS subdatos WHERE datos->>'Variable' = 'zPryEncabezamiento'" ) while consulta.next(): encabezado_firma_proyectista = consulta.value(0) consulta.exec_( "SELECT datos->>'Valor' FROM (SELECT jsonb_array_elements(propiedades->'Valor') AS datos \ FROM \"" + obra + "_Propiedades\" \ WHERE propiedades->>'Propiedad' = 'Proyectista') AS subdatos WHERE datos->>'Variable' = 'zPryNombre1'" ) while consulta.next(): nombre_proyectista1 = consulta.value(0) consulta.exec_( "SELECT datos->>'Valor' FROM (SELECT jsonb_array_elements(propiedades->'Valor') AS datos \ FROM \"" + obra + "_Propiedades\" \ WHERE propiedades->>'Propiedad' = 'Proyectista') AS subdatos WHERE datos->>'Variable' = 'zPryNombre2'" ) while consulta.next(): nombre_proyectista2 = consulta.value(0) consulta.exec_( "SELECT datos->>'Valor' FROM (SELECT jsonb_array_elements(propiedades->'Valor') AS datos \ FROM \"" + obra + "_Propiedades\" \ WHERE propiedades->>'Propiedad' = 'El promotor') AS subdatos WHERE datos->>'Variable' = 'zProEncabezamiento'" ) while consulta.next(): encabezado_firma_promotor = consulta.value(0) consulta.exec_( "SELECT datos->>'Valor' FROM (SELECT jsonb_array_elements(propiedades->'Valor') AS datos \ FROM \"" + obra + "_Propiedades\" \ WHERE propiedades->>'Propiedad' = 'El promotor') AS subdatos WHERE datos->>'Variable' = 'zProNombre1'" ) while consulta.next(): nombre_promotor1 = consulta.value(0) consulta.exec_( "SELECT datos->>'Valor' FROM (SELECT jsonb_array_elements(propiedades->'Valor') AS datos \ FROM \"" + obra + "_Propiedades\" \ WHERE propiedades->>'Propiedad' = 'El promotor') AS subdatos WHERE datos->>'Variable' = 'zProNombre2'" ) while consulta.next(): nombre_promotor2 = consulta.value(0) consulta.exec_( "SELECT datos->>'Valor' FROM (SELECT jsonb_array_elements(propiedades->'Valor') AS datos \ FROM \"" + obra + "_Propiedades\" \ WHERE propiedades->>'Propiedad' = 'Datos generales') AS subdatos WHERE datos->>'Variable' = 'zCiudad'" ) while consulta.next(): ciudad = consulta.value(0) #Linea ciudad y fecha #salto salto = P() lb = LineBreak() salto.addElement(lb) documento.text.addElement(salto) fecha = datetime.now() dia = fecha.strftime("%d") mes = fecha.strftime("%B") anno = fecha.strftime("%Y") lineaciudadfecha = "En " + ciudad + ", a " + dia + " de " + mes + " de " + anno parrafo = P(stylename=Instancia.Estilos("NormalP")) teletype.addTextToElement(parrafo, lineaciudadfecha) documento.text.addElement(parrafo) #salto salto = P() lb = LineBreak() salto.addElement(lb) documento.text.addElement(salto) #linea 1 firmas linea1 = encabezado_firma_proyectista + "\t\t\t" + encabezado_firma_promotor parrafo = P(stylename=Instancia.Estilos("NegritasP")) teletype.addTextToElement(parrafo, linea1) documento.text.addElement(parrafo) #saltos de linea for n in range(0, 2): salto = P() lb = LineBreak() salto.addElement(lb) documento.text.addElement(salto) #linea 2 firmas linea2 = nombre_proyectista1 + "\t\t\t" + nombre_promotor1 parrafo = P(stylename=Instancia.Estilos("NormalP")) teletype.addTextToElement(parrafo, linea2) documento.text.addElement(parrafo) #linea 2 firmas linea3 = nombre_proyectista2 + "\t\t\t" + nombre_promotor2 parrafo = P(stylename=Instancia.Estilos("NormalP")) teletype.addTextToElement(parrafo, linea3) documento.text.addElement(parrafo) return documento
def create_tables(self): query = QtSql.QSqlQuery() query.exec_(sql_queries.CREATE_TRACKER_TABLE) query.exec_(sql_queries.CREATE_TASK_TABLE)
def __init__(self, parent=None): QWidget.__init__(self, parent) self.interface_lng_val = parent.interface_lng_val self.con = parent.con self.full_dir = parent.full_dir self.par = parent if self.con.open(): if 'patches' in self.con.tables(): self.patches_lst = [] query = QtSql.QSqlQuery('SELECT * FROM patches') query.exec_() while query.next(): rec = query.value('patch_name') self.patches_lst.append(rec) # print(patches_lst) self.table = QTableWidget(len(self.patches_lst) + 3, 2) self.table.setColumnWidth(0, 150) self.table.setColumnWidth(1, 460) self.table.setFixedSize(674, 480) self.table.setHorizontalHeaderLabels(["Параметр", "Значение"]) # dimensions dimensions_lbl = QLabel('dimensions') self.d_1 = QLineEdit() self.d_1.setFixedSize(40, 25) self.d_2 = QLineEdit() self.d_2.setFixedSize(40, 25) self.d_3 = QLineEdit() self.d_3.setFixedSize(40, 25) self.d_4 = QLineEdit() self.d_4.setFixedSize(40, 25) self.d_5 = QLineEdit() self.d_5.setFixedSize(40, 25) self.d_6 = QLineEdit() self.d_6.setFixedSize(40, 25) self.d_7 = QLineEdit() self.d_7.setFixedSize(40, 25) self.dimensions_hbox = QHBoxLayout() self.dimensions_hbox.addWidget(self.d_1) self.dimensions_hbox.addWidget(self.d_2) self.dimensions_hbox.addWidget(self.d_3) self.dimensions_hbox.addWidget(self.d_4) self.dimensions_hbox.addWidget(self.d_5) self.dimensions_hbox.addWidget(self.d_6) self.dimensions_hbox.addWidget(self.d_7) self.dimensions_w = QWidget() self.dimensions_w.setLayout(self.dimensions_hbox) self.table.setCellWidget(0, 1, self.dimensions_w) self.table.setCellWidget(0, 0, dimensions_lbl) self.table.setRowHeight(0, 40) # internalField internalField_lbl = QLabel('internalField') self.internalField = QComboBox() self.internalField.setFixedSize(100, 25) internalField_list = ["uniform"] self.internalField.addItems(internalField_list) self.x = QLineEdit() self.x.setFixedSize(40, 25) self.y = QLineEdit() self.y.setFixedSize(40, 25) self.z = QLineEdit() self.z.setFixedSize(40, 25) self.internalField_hbox = QHBoxLayout() self.internalField_hbox.addWidget(self.internalField) self.internalField_hbox.addWidget(self.x) self.internalField_hbox.addWidget(self.y) self.internalField_hbox.addWidget(self.z) self.internalField_w = QWidget() self.internalField_w.setLayout(self.internalField_hbox) self.table.setCellWidget(1, 1, self.internalField_w) self.table.setCellWidget(1, 0, internalField_lbl) self.table.setRowHeight(1, 40) # вывод значений параметров if 'D' in self.con.tables(): query = QtSql.QSqlQuery() query.exec("SELECT * FROM D") if query.isActive(): query.first() value_list = [] while query.isValid(): value_res = query.value('value') value_list.append(value_res) query.next() # dimensions self.d_1.setText(value_list[0].split(' ')[0]) self.d_2.setText(value_list[0].split(' ')[1]) self.d_3.setText(value_list[0].split(' ')[2]) self.d_4.setText(value_list[0].split(' ')[3]) self.d_5.setText(value_list[0].split(' ')[4]) self.d_6.setText(value_list[0].split(' ')[5]) self.d_7.setText(value_list[0].split(' ')[6]) # internalField internalField_mas = self.internalField.count() for i in range(internalField_mas): if self.internalField.itemText(i) == value_list[1].split(', ')[0]: self.internalField.setCurrentIndex(i) self.x.setText(value_list[1].split(', ')[1]) self.y.setText(value_list[1].split(', ')[2]) self.z.setText(value_list[1].split(', ')[3]) # boundaryField boundaryField_lbl = QLabel('boundaryField') self.table.setCellWidget(2, 0, boundaryField_lbl) # patches k = 3 self.type_list_main = [] self.main_grid_list = [] self.traction_list = [] self.xyz_1_list_main = [] self.pressure_list = [] self.koord_list = [] self.value_list = [] self.xyz_2_list_main = [] self.traction_lbl_list = [] self.pressure_lbl_list = [] self.value_lbl_list = [] j = 2 bvc = 0 for el_p in self.patches_lst: el_p_lbl = QLabel(el_p) # type self.type_lbl = QLabel('type:') self.type = QComboBox() self.type.setFixedSize(150, 25) self.type_list = ["symmetryPlane", "tractionDisplacement", "empty"] self.type.addItems(self.type_list) self.main_grid = QGridLayout() self.main_grid.addWidget(self.type_lbl, 0, 0, alignment=QtCore.Qt.AlignLeft) self.main_grid.addWidget(self.type, 0, 1, alignment=QtCore.Qt.AlignLeft) self.main_grid.setRowStretch(0, 6500) self.table.setRowHeight(k, 40) self.type_list_main.append(self.type) self.main_grid_list.append(self.main_grid) # traction traction_lbl = QLabel('traction:') self.traction_lbl_list.append(traction_lbl) traction = QComboBox() traction_list = ["uniform", "demo"] traction.addItems(traction_list) x_1 = QLineEdit() x_1.setFixedSize(40, 25) y_1 = QLineEdit() y_1.setFixedSize(40, 25) z_1 = QLineEdit() z_1.setFixedSize(40, 25) xyz_1_list = [x_1, y_1, z_1] self.traction_list.append(traction) self.xyz_1_list_main.append(xyz_1_list) # pressure pressure_lbl = QLabel('pressure:') self.pressure_lbl_list.append(pressure_lbl) pressure = QComboBox() pressure_list = ["uniform", "demo"] pressure.addItems(pressure_list) koord = QLineEdit() koord.setFixedSize(40, 25) self.pressure_list.append(pressure) self.koord_list.append(koord) # value value_lbl = QLabel('value:') self.value_lbl_list.append(value_lbl) value = QComboBox() value_list = ["uniform", "demo"] value.addItems(value_list) x_2 = QLineEdit() x_2.setFixedSize(40, 25) y_2 = QLineEdit() y_2.setFixedSize(40, 25) z_2 = QLineEdit() z_2.setFixedSize(40, 25) xyz_2_list = [x_2, y_2, z_2] self.value_list.append(value) self.xyz_2_list_main.append(xyz_2_list) # вывод значений параметров if 'D' in self.con.tables(): query = QtSql.QSqlQuery() query.exec("SELECT * FROM D") if query.isActive(): query.first() value_list = [] while query.isValid(): value_res = query.value('value') value_list.append(value_res) query.next() if ',' not in value_list[j]: type_mas = self.main_grid_list[bvc].itemAtPosition(0, 1).widget().count() for i in range(type_mas): if self.main_grid_list[bvc].itemAtPosition(0, 1).widget().itemText(i) == value_list[j]: self.main_grid_list[bvc].itemAtPosition(0, 1).widget().setCurrentIndex(i) elif ',' in value_list[j]: type_mas = self.main_grid_list[bvc].itemAtPosition(0, 1).widget().count() for i in range(type_mas): if self.main_grid_list[bvc].itemAtPosition(0, 1).widget().itemText(i) == value_list[j].split(', ')[0]: self.main_grid_list[bvc].itemAtPosition(0, 1).widget().setCurrentIndex(i) self.main_grid_list[bvc].addWidget(self.traction_lbl_list[bvc], 1, 0, alignment=QtCore.Qt.AlignLeft) self.main_grid_list[bvc].addWidget(self.traction_list[bvc], 1, 1, alignment=QtCore.Qt.AlignLeft) self.main_grid_list[bvc].addWidget(self.xyz_1_list_main[bvc][0], 1, 2, alignment=QtCore.Qt.AlignLeft) self.main_grid_list[bvc].addWidget(self.xyz_1_list_main[bvc][1], 1, 3, alignment=QtCore.Qt.AlignLeft) self.main_grid_list[bvc].addWidget(self.xyz_1_list_main[bvc][2], 1, 4, alignment=QtCore.Qt.AlignLeft) self.main_grid_list[bvc].addWidget(self.pressure_lbl_list[bvc], 2, 0, alignment=QtCore.Qt.AlignLeft) self.main_grid_list[bvc].addWidget(self.pressure_list[bvc], 2, 1, alignment=QtCore.Qt.AlignLeft) self.main_grid_list[bvc].addWidget(self.koord_list[bvc], 2, 2, alignment=QtCore.Qt.AlignLeft) self.main_grid_list[bvc].addWidget(self.value_lbl_list[bvc], 3, 0, alignment=QtCore.Qt.AlignLeft) self.main_grid_list[bvc].addWidget(self.value_list[bvc], 3, 1, alignment=QtCore.Qt.AlignLeft) self.main_grid_list[bvc].addWidget(self.xyz_2_list_main[bvc][0], 3, 2, alignment=QtCore.Qt.AlignLeft) self.main_grid_list[bvc].addWidget(self.xyz_2_list_main[bvc][1], 3, 3, alignment=QtCore.Qt.AlignLeft) self.main_grid_list[bvc].addWidget(self.xyz_2_list_main[bvc][2], 3, 4, alignment=QtCore.Qt.AlignLeft) self.table.setRowHeight(bvc + 3, 120) # traction traction_mas = self.main_grid_list[bvc].itemAtPosition(1, 1).widget().count() for i in range(traction_mas): if self.main_grid_list[bvc].itemAtPosition(1, 1).widget().itemText(i) == value_list[j].split(', ')[1]: self.main_grid_list[bvc].itemAtPosition(1, 1).widget().setCurrentIndex(i) self.main_grid_list[bvc].itemAtPosition(1, 2).widget().setText(value_list[j].split(', ')[2]) self.main_grid_list[bvc].itemAtPosition(1, 3).widget().setText(value_list[j].split(', ')[3]) self.main_grid_list[bvc].itemAtPosition(1, 4).widget().setText(value_list[j].split(', ')[4]) # pressure pressure_mas = self.main_grid_list[bvc].itemAtPosition(2, 1).widget().count() for i in range(pressure_mas): if self.main_grid_list[bvc].itemAtPosition(2, 1).widget().itemText(i) == value_list[j].split(', ')[5]: self.main_grid_list[bvc].itemAtPosition(2, 1).widget().setCurrentIndex(i) self.main_grid_list[bvc].itemAtPosition(2, 2).widget().setText(value_list[j].split(', ')[6]) # value value_mas = self.main_grid_list[bvc].itemAtPosition(3, 1).widget().count() for i in range(value_mas): if self.main_grid_list[bvc].itemAtPosition(3, 1).widget().itemText(i) == value_list[j].split(', ')[7]: self.main_grid_list[bvc].itemAtPosition(3, 1).widget().setCurrentIndex(i) self.main_grid_list[bvc].itemAtPosition(3, 2).widget().setText(value_list[j].split(', ')[8]) self.main_grid_list[bvc].itemAtPosition(3, 3).widget().setText(value_list[j].split(', ')[9]) self.main_grid_list[bvc].itemAtPosition(3, 4).widget().setText(value_list[j].split(', ')[10]) self.main_w = QWidget() self.main_w.setLayout(self.main_grid) self.table.setCellWidget(k, 0, el_p_lbl) self.table.setCellWidget(k, 1, self.main_w) k = k + 1 j = j + 1 bvc = bvc + 1 btnSave = QPushButton() btnSave.setFixedSize(80, 25) btnSave.clicked.connect(self.on_btnSave_clicked) if self.interface_lng_val == 'Russian': btnSave.setText("Сохранить") elif self.interface_lng_val == 'English': btnSave.setText("Save") vbox = QVBoxLayout() vbox.addWidget(self.table) vbox.addWidget(btnSave) for bvc in range(len(self.type_list_main)): self.type_chng(self.type_list_main, bvc) # ---------------------Размещение на форме всех компонентов------------------------- form = QFormLayout() form.addRow(vbox) self.setLayout(form)
def t09_services_remove(self, id): self.__execute( '''delete from services where services.idservices = ''' + id) model = QtSql.QSqlQueryModel() model.setQuery(QtSql.QSqlQuery('select * from services')) return model
def on_btnSave_clicked(self): # создаем таблицу D if 'D' not in self.par.con.tables(): query = QtSql.QSqlQuery() query.exec("CREATE TABLE D(param, value)") dimensions_perem = [self.d_1.text(), self.d_2.text(), self.d_3.text(), self.d_4.text(), self.d_5.text(), self.d_6.text(), self.d_7.text()] dimensions_str = ' '.join(dimensions_perem) internalField_perem = [self.internalField.currentText(), self.x.text(), self.y.text(), self.z.text()] internalField_str = ', '.join(internalField_perem) query = QtSql.QSqlQuery() query.exec("INSERT INTO D(param, value) VALUES ('%s','%s')" % ('dimensions', dimensions_str)) query.exec("INSERT INTO D(param, value) VALUES ('%s','%s')" % ('internalField', internalField_str)) # записываем файл D if os.path.exists(self.full_dir + '/0/D'): os.remove(self.full_dir + '/0/D') shutil.copyfile("./matches/Shablon/0/D", self.full_dir + '/0/D') D = open(self.full_dir + '/0/D', 'a') ###dimensions### dimensions_bl = '\n' + 'dimensions ' + '[' + dimensions_str + ']' + ';' + '\n' ###internalField### internalField_bl = '\n' + 'internalField ' + self.internalField.currentText() + ' ' + '(' + self.x.text() + ' ' + self.y.text() + ' ' + self.z.text() + ')' + ';' + '\n' ###boundaryField### boundaryField_bl_start = '\n' + 'boundaryField' + '\n' + '{' + '\n' D.write(dimensions_bl + internalField_bl + boundaryField_bl_start) i = 0 for el_p in self.patches_lst: if self.type_list_main[i].currentText() == "symmetryPlane" or self.type_list_main[i].currentText() == "empty": type_txt = self.main_grid_list[i].itemAtPosition(0, 1).widget().currentText() query.exec("INSERT INTO D(param, value) VALUES ('%s','%s')" % (el_p, type_txt)) type_bl = ' ' + el_p + '\n' + ' ' + '{' + '\n' + ' ' + 'type' + ' ' + type_txt + ';' + '\n' + ' ' + '}' + '\n' D.write(type_bl) elif self.type_list_main[i].currentText() == "tractionDisplacement": type_txt = self.main_grid_list[i].itemAtPosition(0, 1).widget().currentText() traction_txt = self.main_grid_list[i].itemAtPosition(1, 1).widget().currentText() x_1_txt = self.main_grid_list[i].itemAtPosition(1, 2).widget().text() y_1_txt = self.main_grid_list[i].itemAtPosition(1, 3).widget().text() z_1_txt = self.main_grid_list[i].itemAtPosition(1, 4).widget().text() pressure_txt = self.main_grid_list[i].itemAtPosition(2, 1).widget().currentText() koord_txt = self.main_grid_list[i].itemAtPosition(2, 2).widget().text() value_txt = self.main_grid_list[i].itemAtPosition(3, 1).widget().currentText() x_2_txt = self.main_grid_list[i].itemAtPosition(3, 2).widget().text() y_2_txt = self.main_grid_list[i].itemAtPosition(3, 3).widget().text() z_2_txt = self.main_grid_list[i].itemAtPosition(3, 4).widget().text() complex_list = [type_txt, traction_txt, x_1_txt, y_1_txt, z_1_txt, pressure_txt, koord_txt, value_txt, x_2_txt, y_2_txt, z_2_txt] complex_str = ', '.join(complex_list) query.exec("INSERT INTO D(param, value) VALUES ('%s','%s')" % (el_p, complex_str)) complex_bl = ' ' + el_p + '\n' + ' ' + '{' + '\n' + \ ' ' + 'type' + ' ' + type_txt + ';' + '\n' + \ ' ' + 'traction' + ' ' + traction_txt + ' ' + '(' + x_1_txt + ' ' + y_1_txt + ' ' + z_1_txt + ')' + ';' + '\n' + \ ' ' + 'pressure' + ' ' + pressure_txt + ' ' + koord_txt + ';' + '\n' + \ ' ' + 'value' + ' ' + value_txt + ' ' + '(' + x_2_txt + ' ' + y_2_txt + ' ' + z_2_txt + ')' + ';' + '\n' + \ ' ' + '}' + '\n' D.write(complex_bl) i = i + 1 boundaryField_bl_start = '}' + '\n\n' D.write(boundaryField_bl_start) close_str = '// ************************************************************************* //' D.write(close_str) D.close() if 'D' in self.par.con.tables(): dimensions_perem = [self.d_1.text(), self.d_2.text(), self.d_3.text(), self.d_4.text(), self.d_5.text(), self.d_6.text(), self.d_7.text()] dimensions_str = ' '.join(dimensions_perem) internalField_perem = [self.internalField.currentText(), self.x.text(), self.y.text(), self.z.text()] internalField_str = ', '.join(internalField_perem) query = QtSql.QSqlQuery() query.exec("REPLACE INTO D(param, value) VALUES ('%s','%s')" % ('dimensions', dimensions_str)) query.exec("REPLACE INTO D(param, value) VALUES ('%s','%s')" % ('internalField', internalField_str)) # записываем файл D if os.path.exists(self.full_dir + '/0/D'): os.remove(self.full_dir + '/0/D') shutil.copyfile("./matches/Shablon/0/D", self.full_dir + '/0/D') D = open(self.full_dir + '/0/D', 'a') ###dimensions### dimensions_bl = '\n' + 'dimensions ' + '[' + dimensions_str + ']' + ';' + '\n' ###internalField### internalField_bl = '\n' + 'internalField ' + self.internalField.currentText() + ' ' + '(' + self.x.text() + ' ' + self.y.text() + ' ' + self.z.text() + ')' + ';' + '\n' ###boundaryField### boundaryField_bl_start = '\n' + 'boundaryField' + '\n' + '{' + '\n' D.write(dimensions_bl + internalField_bl + boundaryField_bl_start) i = 0 for el_p in self.patches_lst: if self.type_list_main[i].currentText() == "symmetryPlane" or self.type_list_main[i].currentText() == "empty": type_txt = self.main_grid_list[i].itemAtPosition(0, 1).widget().currentText() query.exec("REPLACE INTO D(param, value) VALUES ('%s','%s')" % (el_p, type_txt)) type_bl = ' ' + el_p + '\n' + ' ' + '{' + '\n' + ' ' + 'type' + ' ' + type_txt + ';' + '\n' + ' ' + '}' + '\n' D.write(type_bl) elif self.type_list_main[i].currentText() == "tractionDisplacement": type_txt = self.main_grid_list[i].itemAtPosition(0, 1).widget().currentText() traction_txt = self.main_grid_list[i].itemAtPosition(1, 1).widget().currentText() x_1_txt = self.main_grid_list[i].itemAtPosition(1, 2).widget().text() y_1_txt = self.main_grid_list[i].itemAtPosition(1, 3).widget().text() z_1_txt = self.main_grid_list[i].itemAtPosition(1, 4).widget().text() pressure_txt = self.main_grid_list[i].itemAtPosition(2, 1).widget().currentText() koord_txt = self.main_grid_list[i].itemAtPosition(2, 2).widget().text() value_txt = self.main_grid_list[i].itemAtPosition(3, 1).widget().currentText() x_2_txt = self.main_grid_list[i].itemAtPosition(3, 2).widget().text() y_2_txt = self.main_grid_list[i].itemAtPosition(3, 3).widget().text() z_2_txt = self.main_grid_list[i].itemAtPosition(3, 4).widget().text() complex_list = [type_txt, traction_txt, x_1_txt, y_1_txt, z_1_txt, pressure_txt, koord_txt, value_txt, x_2_txt, y_2_txt, z_2_txt] complex_str = ', '.join(complex_list) query.exec("REPLACE INTO D(param, value) VALUES ('%s','%s')" % (el_p, complex_str)) complex_bl = ' ' + el_p + '\n' + ' ' + '{' + '\n' + \ ' ' + 'type' + ' ' + type_txt + ';' + '\n' + \ ' ' + 'traction' + ' ' + traction_txt + ' ' + '(' + x_1_txt + ' ' + y_1_txt + ' ' + z_1_txt + ')' + ';' + '\n' + \ ' ' + 'pressure' + ' ' + pressure_txt + ' ' + koord_txt + ';' + '\n' + \ ' ' + 'value' + ' ' + value_txt + ' ' + '(' + x_2_txt + ' ' + y_2_txt + ' ' + z_2_txt + ')' + ';' + '\n' + \ ' ' + '}' + '\n' D.write(complex_bl) i = i + 1 boundaryField_bl_start = '}' + '\n\n' D.write(boundaryField_bl_start) close_str = '// ************************************************************************* //' D.write(close_str) D.close() self.par.cdw.setWidget(self.par.outf_scroll) outf = open(self.full_dir + '/0/D') if self.interface_lng_val == 'Russian': msg_lbl = QLabel( '<span style="color:green">Файл D сохранен</span>') elif self.interface_lng_val == 'English': msg_lbl = QLabel( '<span style="color:green">The D file was saved</span>') self.par.listWidget.clear() self.par.item = QListWidgetItem() self.par.listWidget.addItem(self.par.item) self.par.listWidget.setItemWidget(self.par.item, msg_lbl) data = outf.read() if self.interface_lng_val == 'Russian': self.par.outf_lbl.setText("Файл " + "<font color='peru'>" + 'D' + "</font>") elif self.interface_lng_val == 'English': self.par.outf_lbl.setText("<font color='peru'>" + 'D' + "</font>" + " file") self.par.outf_edit.setText(data) self.par.cdw.setTitleBarWidget(self.par.cdw_frame) outf.close()
def t09_spec(self): model = QtSql.QSqlQueryModel() model.setQuery(QtSql.QSqlQuery('select * from specializations')) return model
# -*- coding: utf-8 -*- from PyQt5 import QtSql, QtWidgets import sys, os dbPath = r'./DB/Cert2.db3' if os.path.exists(dbPath): print ("Файл найден") else: print ("Файл не найден") app = QtWidgets.QApplication(sys.argv) con = QtSql.QSqlDatabase.addDatabase('QSQLITE') a = con.setDatabaseName('Cert2.db') print(a) con.open() query = QtSql.QSqlQuery() query.exec_("SELECT * FROM Unit") lst = [] #if query.isActive(): # query.first() # while query.isValid(): # lst.append(query.value('id')+':'+ str(query.value('Name'))) # query.next() # for p in lst: print(p) con.close()
def t09_workers(self): model = QtSql.QSqlQueryModel() model.setQuery(QtSql.QSqlQuery('select * from workers')) return model
def on_btnSave_clicked(self): application_txt = self.application.currentText() startFrom_txt = self.startFrom.currentText() startTime_txt = self.startTime.value() stopAt_txt = self.stopAt.currentText() endTime_txt = self.endTime.value() deltaT_txt = self.deltaT.text() writeControl_txt = self.writeControl.currentText() writeInterval_txt = self.writeInterval.value() purgeWrite_txt = self.purgeWrite.value() writeFormat_txt = self.writeFormat.currentText() writePrecision_txt = self.writePrecision.value() writeCompression_txt = self.writeCompression.currentText() timeFormat_txt = self.timeFormat.currentText() timePrecision_txt = self.timePrecision.value() runTimeModifiable_txt = self.runTimeModifiable.currentText() adjustTimeStep_txt = self.adjustTimeStep.currentText() maxCo_txt = self.maxCo.value() maxAlphaCo_txt = self.maxAlphaCo.value() maxDeltaT_txt = self.maxDeltaT.value() self.par.application = application_txt if 'controlDict' not in self.con.tables(): query = QtSql.QSqlQuery() query.exec("CREATE TABLE controlDict(param, value)") query.exec( "INSERT INTO controlDict(param, value) VALUES ('%s','%s')" % ('application', '')) query.exec( "INSERT INTO controlDict(param, value) VALUES ('%s','%s')" % ('startFrom', '')) query.exec( "INSERT INTO controlDict(param, value) VALUES ('%s','%s')" % ('startTime', '')) query.exec( "INSERT INTO controlDict(param, value) VALUES ('%s','%s')" % ('stopAt', '')) query.exec( "INSERT INTO controlDict(param, value) VALUES ('%s','%s')" % ('endTime', '')) query.exec( "INSERT INTO controlDict(param, value) VALUES ('%s','%s')" % ('deltaT', '')) query.exec( "INSERT INTO controlDict(param, value) VALUES ('%s','%s')" % ('writeControl', '')) query.exec( "INSERT INTO controlDict(param, value) VALUES ('%s','%s')" % ('writeInterval', '')) query.exec( "INSERT INTO controlDict(param, value) VALUES ('%s','%s')" % ('purgeWrite', '')) query.exec( "INSERT INTO controlDict(param, value) VALUES ('%s','%s')" % ('writeFormat', '')) query.exec( "INSERT INTO controlDict(param, value) VALUES ('%s','%s')" % ('writePrecision', '')) query.exec( "INSERT INTO controlDict(param, value) VALUES ('%s','%s')" % ('writeCompression', '')) query.exec( "INSERT INTO controlDict(param, value) VALUES ('%s','%s')" % ('timeFormat', '')) query.exec( "INSERT INTO controlDict(param, value) VALUES ('%s','%s')" % ('timePrecision', '')) query.exec( "INSERT INTO controlDict(param, value) VALUES ('%s','%s')" % ('runTimeModifiable', '')) query.exec( "INSERT INTO controlDict(param, value) VALUES ('%s','%s')" % ('adjustTimeStep', '')) query.exec( "INSERT INTO controlDict(param, value) VALUES ('%s','%s')" % ('maxCo', '')) query.exec( "INSERT INTO controlDict(param, value) VALUES ('%s','%s')" % ('maxAlphaCo', '')) query.exec( "INSERT INTO controlDict(param, value) VALUES ('%s','%s')" % ('maxDeltaT', '')) if 'controlDict' in self.con.tables(): query = QtSql.QSqlQuery() query.prepare( "UPDATE controlDict SET value=? WHERE param='application'") query.bindValue(0, application_txt) query.exec_() query.prepare( "UPDATE controlDict SET value=? WHERE param='startFrom'") query.bindValue(0, startFrom_txt) query.exec_() query.prepare( "UPDATE controlDict SET value=? WHERE param='startTime'") query.bindValue(0, startTime_txt) query.exec_() query.prepare( "UPDATE controlDict SET value=? WHERE param='stopAt'") query.bindValue(0, stopAt_txt) query.exec_() query.prepare( "UPDATE controlDict SET value=? WHERE param='endTime'") query.bindValue(0, endTime_txt) query.exec_() query.prepare( "UPDATE controlDict SET value=? WHERE param='deltaT'") query.bindValue(0, deltaT_txt) query.exec_() query.prepare( "UPDATE controlDict SET value=? WHERE param='writeControl'") query.bindValue(0, writeControl_txt) query.exec_() query.prepare( "UPDATE controlDict SET value=? WHERE param='writeInterval'") query.bindValue(0, writeInterval_txt) query.exec_() query.prepare( "UPDATE controlDict SET value=? WHERE param='purgeWrite'") query.bindValue(0, purgeWrite_txt) query.exec_() query.prepare( "UPDATE controlDict SET value=? WHERE param='purgeWrite'") query.bindValue(0, purgeWrite_txt) query.exec_() query.prepare( "UPDATE controlDict SET value=? WHERE param='writeFormat'") query.bindValue(0, writeFormat_txt) query.exec_() query.prepare( "UPDATE controlDict SET value=? WHERE param='writePrecision'") query.bindValue(0, writePrecision_txt) query.exec_() query.prepare( "UPDATE controlDict SET value=? WHERE param='writeCompression'" ) query.bindValue(0, writeCompression_txt) query.exec_() query.prepare( "UPDATE controlDict SET value=? WHERE param='timeFormat'") query.bindValue(0, timeFormat_txt) query.exec_() query.prepare( "UPDATE controlDict SET value=? WHERE param='timePrecision'") query.bindValue(0, timePrecision_txt) query.exec_() query.prepare( "UPDATE controlDict SET value=? WHERE param='runTimeModifiable'" ) query.bindValue(0, runTimeModifiable_txt) query.exec_() query.prepare( "UPDATE controlDict SET value=? WHERE param='adjustTimeStep'") query.bindValue(0, adjustTimeStep_txt) query.exec_() query.prepare("UPDATE controlDict SET value=? WHERE param='maxCo'") query.bindValue(0, maxCo_txt) query.exec_() query.prepare( "UPDATE controlDict SET value=? WHERE param='maxAlphaCo'") query.bindValue(0, maxAlphaCo_txt) query.exec_() query.prepare( "UPDATE controlDict SET value=? WHERE param='maxDeltaT'") query.bindValue(0, maxDeltaT_txt) query.exec_() # записываем файл controlDict if os.path.exists(self.full_dir + '/system/controlDict'): os.remove(self.full_dir + '/system/controlDict') shutil.copyfile("./matches/Shablon/system/controlDict", self.full_dir + '/system/controlDict') cD = open(self.full_dir + '/system/controlDict', 'a') ###application### a_bl = '\n' + 'application ' + application_txt + ';' + '\n\n' ###startFrom### sF_bl = 'startFrom ' + startFrom_txt + ';' + '\n\n' ###startTime### sT_bl = 'startTime ' + str(startTime_txt) + ';' + '\n\n' ###stopAt### sA_bl = 'stopAt ' + stopAt_txt + ';' + '\n\n' ###endTime### sTi_bl = 'endTime ' + str(endTime_txt) + ';' + '\n\n' ###deltaT### dT_bl = 'deltaT ' + str(deltaT_txt) + ';' + '\n\n' ###writeControl### wC_bl = 'writeControl ' + writeControl_txt + ';' + '\n\n' ###writeInterval### wI_bl = 'writeInterval ' + str(writeInterval_txt) + ';' + '\n\n' ###purgeWrite### pW_bl = 'purgeWrite ' + str(purgeWrite_txt) + ';' + '\n\n' ###writeFormat### wF_bl = 'writeFormat ' + writeFormat_txt + ';' + '\n\n' ###writePrecision### wP_bl = 'writePrecision ' + str(writePrecision_txt) + ';' + '\n\n' ###writeCompression### wCo_bl = 'writeCompression ' + writeCompression_txt + ';' + '\n\n' ###timeFormat### tF_bl = 'timeFormat ' + timeFormat_txt + ';' + '\n\n' ###timePrecision### tP_bl = 'timePrecision ' + str(timePrecision_txt) + ';' + '\n\n' ###runTimeModifiable### rTM_bl = 'runTimeModifiable ' + runTimeModifiable_txt + ';' + '\n\n' ###adjustTimeStep### aTS_bl = 'adjustTimeStep ' + adjustTimeStep_txt + ';' + '\n\n' ###maxCo### mC_bl = 'maxCo ' + str(maxCo_txt) + ';' + '\n\n' ###maxAlphaCo### mAC_bl = 'maxAlphaCo ' + str(maxAlphaCo_txt) + ';' + '\n\n' ###maxDeltaT### mDT_bl = 'maxDeltaT ' + str(maxDeltaT_txt) + ';' + '\n\n' if deltaT_txt != '': cD.write(a_bl + sF_bl + sT_bl + sA_bl + sTi_bl + dT_bl + wC_bl + wI_bl + pW_bl + wF_bl + wP_bl + wCo_bl + tF_bl + tP_bl + rTM_bl + aTS_bl + mC_bl + mAC_bl + mDT_bl) close_str = '// ************************************************************************* //' cD.write(close_str) cD.close() self.par.cdw.setWidget(self.par.outf_scroll) outf = open(self.full_dir + '/system/controlDict') if self.interface_lng_val == 'Russian': msg_lbl = QLabel( '<span style="color:green">Файл controlDict сохранен</span>' ) elif self.interface_lng_val == 'English': msg_lbl = QLabel( '<span style="color:green">The controlDict file saved</span>' ) data = outf.read() if self.interface_lng_val == 'Russian': self.par.outf_lbl.setText("Файл " + "<font color='peru'>" + 'controlDict' + "</font>") elif self.interface_lng_val == 'English': self.par.outf_lbl.setText("<font color='peru'>" + 'controlDict' + "</font>" + " file") self.par.outf_edit.setText(data) self.par.cdw.setTitleBarWidget(self.par.cdw_frame) outf.close() else: if self.interface_lng_val == 'Russian': msg_lbl = QLabel( '<span style="color:green">Укажите значение параметра deltaT</span>' ) elif self.interface_lng_val == 'English': msg_lbl = QLabel( '<span style="color:green">Specify deltaT value</span>') self.par.listWidget.clear() self.par.item = QListWidgetItem() self.par.listWidget.addItem(self.par.item) self.par.listWidget.setItemWidget(self.par.item, msg_lbl)
def t09_workers_remove(self, id): self.__execute('''delete from workers where workers.idworker = ''' + id) model = QtSql.QSqlQueryModel() model.setQuery(QtSql.QSqlQuery('select * from workers')) return model
def setupUi(self, Contacts): Contacts.setObjectName("Contacts") Contacts.resize(723, 591) Contacts.setMaximumSize(QtCore.QSize(723, 591)) self.groupBox_3 = QtWidgets.QGroupBox(Contacts) self.groupBox_3.setGeometry(QtCore.QRect(20, 0, 681, 76)) self.groupBox_3.setStyleSheet("border:1px solid #ccc;") self.groupBox_3.setTitle("") self.groupBox_3.setObjectName("groupBox_3") self.groupBox_5 = QtWidgets.QGroupBox(self.groupBox_3) self.groupBox_5.setGeometry(QtCore.QRect(0, 30, 171, 51)) self.groupBox_5.setStyleSheet("border:0;") self.groupBox_5.setTitle("") self.groupBox_5.setObjectName("groupBox_5") self.label_5 = QtWidgets.QLabel(self.groupBox_3) self.label_5.setGeometry(QtCore.QRect(20, 10, 68, 17)) self.label_5.setStyleSheet("border:0;") self.label_5.setObjectName("label_5") self.label_6 = QtWidgets.QLabel(self.groupBox_3) self.label_6.setGeometry(QtCore.QRect(310, 10, 31, 20)) self.label_6.setStyleSheet("border:0;") self.label_6.setObjectName("label_6") self.startDate = QtWidgets.QLineEdit(self.groupBox_3) self.startDate.setGeometry(QtCore.QRect(20, 30, 520, 31)) self.startDate.setStyleSheet("border:1px solid #999; border-radius:3px;") self.startDate.setObjectName("startDate") self.btnGetData = QtWidgets.QPushButton(self.groupBox_3) self.btnGetData.setGeometry(QtCore.QRect(580, 30, 81, 31)) self.btnGetData.setStyleSheet("") self.btnGetData.setObjectName("btnGetData") self.logsView = QtWidgets.QTableView(Contacts) self.logsView.setGeometry(QtCore.QRect(20, 170, 681, 371)) self.logsView.setGridStyle(QtCore.Qt.NoPen) self.logsView.setObjectName("logsView") self.logsView.horizontalHeader().setDefaultSectionSize(130) self.logsView.horizontalHeader().setMinimumSectionSize(100) self.logsView.horizontalHeader().setSortIndicatorShown(True) self.logsView.horizontalHeader().setStretchLastSection(True) self.logsView.verticalHeader().setMinimumSectionSize(30) self.groupBox_2 = QtWidgets.QGroupBox(Contacts) self.groupBox_2.setGeometry(QtCore.QRect(20, 90, 371, 71)) self.groupBox_2.setStyleSheet("border:1px solid #ccc;") self.groupBox_2.setObjectName("groupBox_2") self.usernameFilter = QtWidgets.QComboBox(self.groupBox_2) self.usernameFilter.setGeometry(QtCore.QRect(20, 23, 251, 31)) self.usernameFilter.setObjectName("usernameFilter") self.btnLoad = QtWidgets.QPushButton(self.groupBox_2) self.btnLoad.setGeometry(QtCore.QRect(280, 23, 71, 31)) self.btnLoad.setObjectName("btnLoad") self.groupBox_4 = QtWidgets.QGroupBox(Contacts) self.groupBox_4.setGeometry(QtCore.QRect(410, 90, 291, 81)) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(10) self.groupBox_4.setFont(font) self.groupBox_4.setStyleSheet("border:1px solid #ccc;") self.groupBox_4.setTitle("") self.groupBox_4.setObjectName("groupBox_4") self.btnDelete = QtWidgets.QPushButton(self.groupBox_4) self.btnDelete.setGeometry(QtCore.QRect(20, 43, 121, 31)) self.btnDelete.setObjectName("btnDelete") self.selectLog = QtWidgets.QComboBox(self.groupBox_4) self.selectLog.setGeometry(QtCore.QRect(20, 10, 251, 27)) self.selectLog.setObjectName("selectLog") self.btnDeleteAll = QtWidgets.QPushButton(self.groupBox_4) self.btnDeleteAll.setGeometry(QtCore.QRect(150, 43, 121, 31)) self.btnDeleteAll.setObjectName("btnDeleteAll") self.btnClose = QtWidgets.QPushButton(Contacts) self.btnClose.setGeometry(QtCore.QRect(618, 550, 81, 31)) self.btnClose.setObjectName("btnClose") self.btnDeleteAll.clicked.connect(lambda: self.delete_all()) self.btnDelete.clicked.connect(lambda: self.delete_log()) self.btnGetData.clicked.connect(lambda: self.get_data()) self.btnLoad.clicked.connect(lambda: self.get_user_logs()) self.retranslateUi(Contacts) self.btnClose.clicked.connect(Contacts.close) QtCore.QMetaObject.connectSlotsByName(Contacts) Contacts.setTabOrder(self.startDate, self.btnGetData) Contacts.setTabOrder(self.btnGetData, self.usernameFilter) Contacts.setTabOrder(self.usernameFilter, self.btnLoad) Contacts.setTabOrder(self.btnLoad, self.selectLog) Contacts.setTabOrder(self.selectLog, self.btnDelete) Contacts.setTabOrder(self.btnDelete, self.btnDeleteAll) Contacts.setTabOrder(self.btnDeleteAll, self.logsView) Contacts.setTabOrder(self.logsView, self.btnClose) sql.connectDB() model = QtSql.QSqlQueryModel() q = QtSql.QSqlQuery() q.exec_("select operation from logs") model.setQuery(q) self.selectLog.setModel(model) qry = QtSql.QSqlQuery() qry.prepare("select distinct name from logs") qry.exec_() modal = QtSql.QSqlQueryModel() modal.setQuery(qry) self.usernameFilter.setModel(modal) self.get_logs()
def t10_activity(self): model = QtSql.QSqlQueryModel() model.setQuery(QtSql.QSqlQuery('select * from activity')) return model
def Cargo_Datos_Alumno(self, dni): print("entro") self.dni = dni print(self.dni) '''Obtengo datos del alumno a modificar''' sql = "SELECT * FROM alumnos WHERE DNI = :dni" q = QtSql.QSqlQuery(self.db.database("inscripciones")) print("pase el query") q.prepare(sql) q.bindValue(":dni", self.dni) ej = Utilidades() q = ej.ejecuto(q, "inscripciones") while q.next(): self.lnNombre.setText(q.value(1)) self.cBCarrera.setCurrentText(q.value(23)) self.lnCiclo.setText(str(q.value(24))) self.cBSexo.setCurrentText(q.value(22)) self.sBEdad.setValue(q.value(5)) self.lnDni.setText(str(q.value(2))) self.dENac.setDate(q.value(4)) self.lnLugar.setText(q.value(3)) self.ui.lnNac.setText(q.value(26)) self.cBCivil.setCurrentText(q.value(10)) self.cBHijos.setCurrentText(str(q.value(27))) self.lnFamiliar.setText(q.value(28)) self.lnCalle.setText(q.value(6)) self.lnNum.setText(str(q.value(7))) self.lnPiso.setText(q.value(8)) self.lnDepto.setText(q.value(9)) self.lnLocal.setText(q.value(11)) self.lnPartido.setText(q.value(12)) self.lnCP.setText(q.value(13)) self.lnTel.setText(str(q.value(14))) self.lnMov.setText(str(q.value(15))) self.lnMail.setText(q.value(29)) self.lntitulo.setText(q.value(16)) print("Tipe linea 73 " + str(type( q.value(30)))) # fecha = ej.convierte_Fechas(q.value(30)) # print(type(fecha) date = QDate.fromString(str(q.value(30)), "yyyy") self.dEEgr.setDate(QDate.fromString(str(q.value(30)), "yyyy")) self.lnEscuela.setText(q.value(32)) self.lnDistrito.setText(q.value(33)) self.lnOtros.setText(q.value(31)) if (q.value(18) == 0): self.rBtnNo.setChecked(True) self.rBtnSi.setChecked(False) else: self.rBtnSi.setChecked(True) self.rBtnNo.setChecked(False) self.lnAct.setText(q.value(19)) self.lnHorario.setText(q.value(25)) self.lnOS.setText(q.value(21)) self.lnTelEmer.setText(q.value(20)) diccio = { self.cBDni: q.value(34), self.cBTit: q.value(35), self.cBReg: q.value(36), self.cBCert: q.value(38), self.cBFoto: q.value(37) } for k in diccio: print(str(diccio.get(k))) if diccio.get(k) == b'\x01': k.setChecked(True) else: k.setChecked(False)
def __init__(self, parent=None): QWidget.__init__(self, parent) self.interface_lng_val = parent.interface_lng_val self.con = parent.con self.full_dir = parent.full_dir self.par = parent flag = False if 'mirrorMeshDict_x' in self.con.tables(): flag = True query = QtSql.QSqlQuery() query.exec("SELECT * FROM mirrorMeshDict_x") if query.isActive(): query.first() name_list = [] value_list = [] while query.isValid(): name_res = query.value('name') value_res = query.value('value') name_list.append(name_res) value_list.append(value_res) query.next() self.data_reprint() main_lbl = QLabel() # planeType planeType_lbl = QLabel() planeType_hbox = QHBoxLayout() self.planeType_edit = QComboBox() self.planeType_edit.setFixedSize(150, 25) planeType_list = ["pointAndNormal", "demo"] self.planeType_edit.addItems(planeType_list) planeType_hbox.addWidget(planeType_lbl) planeType_hbox.addWidget(self.planeType_edit) #pointAndNormalDict pAND_lbl = QLabel() #point point_lbl = QLabel() self.x1 = QLineEdit() self.x1.setFixedSize(50, 25) self.y1 = QLineEdit() self.y1.setFixedSize(50, 25) self.z1 = QLineEdit() self.z1.setFixedSize(50, 25) point_hbox = QHBoxLayout() point_hbox.addWidget(point_lbl) point_hbox.addWidget(self.x1) point_hbox.addWidget(self.y1) point_hbox.addWidget(self.z1) #normal normal_lbl = QLabel() self.x2 = QLineEdit() self.x2.setFixedSize(50, 25) self.y2 = QLineEdit() self.y2.setFixedSize(50, 25) self.z2 = QLineEdit() self.z2.setFixedSize(50, 25) normal_hbox = QHBoxLayout() normal_hbox.addWidget(normal_lbl) normal_hbox.addWidget(self.x2) normal_hbox.addWidget(self.y2) normal_hbox.addWidget(self.z2) pAND_grid = QGridLayout() pAND_grid.addLayout(point_hbox, 0, 0, alignment=QtCore.Qt.AlignCenter) pAND_grid.addLayout(normal_hbox, 1, 0, alignment=QtCore.Qt.AlignCenter) pAND_frame = QFrame() pAND_frame.setFixedSize(250, 100) pAND_frame.setStyleSheet( open("./styles/properties_form_style.qss", "r").read()) pAND_frame.setFrameShape(QFrame.Panel) pAND_frame.setFrameShadow(QFrame.Sunken) pAND_frame.setLayout(pAND_grid) # planeTolerance planeTolerance_lbl = QLabel() self.planeTolerance_edit = QLineEdit() self.planeTolerance_edit.setFixedSize(150, 25) if flag == True: planeType_mas = self.planeType_edit.count() for i in range(planeType_mas): if self.planeType_edit.itemText(i) == value_list[0]: self.planeType_edit.setCurrentIndex(i) self.x1.setText(value_list[1].split()[0]) self.y1.setText(value_list[1].split()[1]) self.z1.setText(value_list[1].split()[2]) self.x2.setText(value_list[2].split()[0]) self.y2.setText(value_list[2].split()[1]) self.z2.setText(value_list[2].split()[2]) self.planeTolerance_edit.setText(value_list[3]) planeTolerance_grid = QGridLayout() planeTolerance_grid.addWidget(planeTolerance_lbl, 0, 0, alignment=QtCore.Qt.AlignCenter) planeTolerance_grid.addWidget(self.planeTolerance_edit, 0, 1, alignment=QtCore.Qt.AlignCenter) btnSave = QPushButton() btnSave.setFixedSize(80, 25) btnSave.clicked.connect(self.on_btnSave_clicked) buttons_hbox = QHBoxLayout() buttons_hbox.addWidget(btnSave) if self.interface_lng_val == 'Russian': btnSave.setText("Сохранить") main_lbl.setText("Укажите параметры плоскости") planeType_lbl.setText("planeType:") pAND_lbl.setText("pointAndNormalDict") point_lbl.setText("point:") normal_lbl.setText("normal:") planeTolerance_lbl.setText("planeTolerance:") elif self.interface_lng_val == 'English': btnSave.setText("Save") main_lbl.setText("Specify the parameters of the plane") planeType_lbl.setText("planeType:") pAND_lbl.setText("pointAndNormalDict") point_lbl.setText("point:") normal_lbl.setText("normal:") planeTolerance_lbl.setText("planeTolerance:") mMD_grid = QGridLayout() mMD_grid.addWidget(main_lbl, 0, 0, alignment=QtCore.Qt.AlignCenter) mMD_grid.addLayout(planeType_hbox, 1, 0, alignment=QtCore.Qt.AlignCenter) mMD_grid.addWidget(pAND_lbl, 2, 0, alignment=QtCore.Qt.AlignCenter) mMD_grid.addWidget(pAND_frame, 3, 0, alignment=QtCore.Qt.AlignCenter) mMD_grid.addLayout(planeTolerance_grid, 4, 0, alignment=QtCore.Qt.AlignCenter) mMD_grid.addLayout(buttons_hbox, 5, 0, alignment=QtCore.Qt.AlignCenter) mMD_grid.setRowStretch(6, 2) mMD_frame = QFrame() mMD_frame.setFixedSize(670, 510) mMD_frame.setStyleSheet( open("./styles/properties_form_style.qss", "r").read()) mMD_frame.setFrameShape(QFrame.Panel) mMD_frame.setFrameShadow(QFrame.Sunken) mMD_frame.setLayout(mMD_grid) mMD_vbox = QVBoxLayout() mMD_vbox.addWidget(mMD_frame) # ---------------------Размещение на форме всех компонентов-------------------------# form = QFormLayout() form.addRow(mMD_vbox) self.setLayout(form)
def editingFinished(self): # first try to update info about device if self.serNum != '' and self.type != '': qryInfo = "SELECT * FROM allDevices WHERE `serialNumber` = '%s' AND `type` = '%s';" % ( self.serNum, self.type) infoQry = QtSql.QSqlQuery() updateQry = QtSql.QSqlQuery() ok = infoQry.exec(qryInfo) #if there is no such device, add it if not infoQry.first(): qryAddDevice = "INSERT INTO allDevices(serialNumber,type) VALUES (%s,'%s');" % ( self.serNum, self.type) ok = updateQry.exec(qryAddDevice) ok = infoQry.exec(qryInfo) ok = infoQry.first() if ok: if infoQry.value(7) != self.ipEdit.text(): qryIP = "UPDATE allDevices SET ipAddress = '%s' WHERE `serialNumber` = '%s' AND `type` = '%s';" % ( self.ipEdit.text(), self.serNum, self.type) ok = updateQry.exec(qryIP) if infoQry.value(8) != self.gatewayEdit.text(): qryIP = "UPDATE allDevices SET ipGateway = '%s' WHERE `serialNumber` = '%s' AND `type` = '%s';" % ( self.gatewayEdit.text(), self.serNum, self.type) ok = updateQry.exec(qryIP) if infoQry.value(9) != self.netmaskEdit.text(): qryIP = "UPDATE allDevices SET ipNetmask = '%s' WHERE `serialNumber` = '%s' AND `type` = '%s';" % ( self.netmaskEdit.text(), self.serNum, self.type) ok = updateQry.exec(qryIP) try: comSet = int(infoQry.value(10)) except: comSet = 0 if comSet != self.comEdit.value(): qryIP = "UPDATE allDevices SET COM = '%s' WHERE `serialNumber` = '%s' AND `type` = '%s';" % ( str(self.comEdit.value()), self.serNum, self.type) ok = updateQry.exec(qryIP) if infoQry.value(11) != self.locationComboBox.currentText(): qryLoc = "UPDATE allDevices SET location = '%s' WHERE `serialNumber` = '%s' AND `type` = '%s';" % ( self.locationComboBox.currentText(), self.serNum, self.type) ok = updateQry.exec(qryLoc) # adding info to incidents # get id of device idGet = "SELECT id FROM allDevices WHERE `serialNumber` = '%s' AND `type` = '%s';" % ( self.serNum, self.type) idQry = QtSql.QSqlQuery() ok = idQry.exec(idGet) idQry.first() # TODO: disable adding similar incidents (for same id and date), instead of it edit existing incident # insert basic info about incident # if it's new incident if ok and self.id == None: id = idQry.value(0) values = [ str(id), self.operator, self.brigade, self.dateCreationEdit.date().toString("yyyy-MM-dd"), self.desiredFinishDateCalendar.selectedDate().toString( "yyyy-MM-dd") ] addIncidentQryTxt = "INSERT INTO incidents(idDevice,operator,brigadeEngineer,takeoffDate,desiredFinishDate) VALUES(%s,'%s','%s','%s','%s');" % ( str(id), self.operator, self.brigade, self.dateCreationEdit.date().toString("yyyy-MM-dd"), self.desiredFinishDateCalendar.selectedDate().toString( "yyyy-MM-dd")) addIncidentQry = QtSql.QSqlQuery() ok = addIncidentQry.exec(addIncidentQryTxt) if ok: idIncident = QtSql.QSqlQuery() ok = idIncident.exec("SELECT LAST_INSERT_ID();") idIncident.first() self.id = idIncident.value(0) #or if incident already exists elif ok: id = idQry.value(0) values = [ str(id), self.brigade, self.dateCreationEdit.date().toString("yyyy-MM-dd"), self.desiredFinishDateCalendar.selectedDate().toString( "yyyy-MM-dd"), self.id ] updateQryTxt = "UPDATE incidents SET `idDevice`='{}', `brigadeEngineer`='{}', `takeoffDate`='{}', `desiredFinishDate`='{}' WHERE `idIncident`='{}';".format( values[0], values[1], values[2], values[3], values[4]) ok = updateQry.exec(updateQryTxt) #get problems if exists in db getProblemsQryTxt = "SELECT typicalProblem FROM problems WHERE incident=%d;" % self.id ok = idQry.exec(getProblemsQryTxt) #get selected problems problems = [] problemsToRemove = [] textProblems = "" if ok: while self.typicalProblemsLayout.count(): item = self.typicalProblemsLayout.takeAt(0) widget = item.widget() if widget is not None: if widget.isChecked(): problems.append(widget.text()) textProblems += "%s, " % widget.text() addProblemQry = QtSql.QSqlQuery() #write problems to base #first check if some removed while idQry.next(): if idQry.value(0) not in problems: problemsToRemove.append(idQry.value(0)) #if already in db, excluding from list to add else: problems.remove(idQry.value(0)) for i in problemsToRemove: removeProblemQryTxt = "DELETE FROM problems WHERE id=%d AND typicalProblem='%s';" % ( self.id, i) ok = addProblemQry.exec(removeProblemQryTxt) for i in problems: addProblemQryTxt = "INSERT INTO problems(typicalProblem,incident) VALUES('%s',%d);" % ( i, self.id) ok = addProblemQry.exec(addProblemQryTxt) if self.moreButton.isChecked(): addOtherProblemQryTxt = "INSERT INTO problems(incident,otherProblem) VALUES(%d,'%s');" % ( self.id, self.moreButton.text()) ok = addProblemQry.exec(addOtherProblemQryTxt) if textProblems != "": ok = addProblemQry.exec( "UPDATE incidents SET textProblems='%s' WHERE idIncident='%s';" % (textProblems, self.id)) self.accept()
def on_btnSave_clicked(self): planeType_txt = self.planeType_edit.currentText() msg_list = [] x1_txt = self.x1.text() y1_txt = self.y1.text() z1_txt = self.z1.text() x2_txt = self.x2.text() y2_txt = self.y2.text() z2_txt = self.z2.text() xyz1_list = [] xyz1_list.append(x1_txt) xyz1_list.append(y1_txt) xyz1_list.append(z1_txt) xyz2_list = [] xyz2_list.append(x2_txt) xyz2_list.append(y2_txt) xyz2_list.append(z2_txt) planeTolerance_txt = self.planeTolerance_edit.text() if x1_txt == '': if self.interface_lng_val == 'Russian': msg = 'Укажите значение x для параметра point' elif self.interface_lng_val == 'English': msg = 'Specify the x value for the point parameter' msg_list.append(msg) if y1_txt == '': if self.interface_lng_val == 'Russian': msg = 'Укажите значение y для параметра point' elif self.interface_lng_val == 'English': msg = 'Specify the y value for the point parameter' msg_list.append(msg) if z1_txt == '': if self.interface_lng_val == 'Russian': msg = 'Укажите значение z для параметра point' elif self.interface_lng_val == 'English': msg = 'Specify the z value for the point parameter' msg_list.append(msg) if x2_txt == '': if self.interface_lng_val == 'Russian': msg = 'Укажите значение x для параметра normal' elif self.interface_lng_val == 'English': msg = 'Specify the x value for the normal parameter' msg_list.append(msg) if y2_txt == '': if self.interface_lng_val == 'Russian': msg = 'Укажите значение y для параметра normal' elif self.interface_lng_val == 'English': msg = 'Specify the y value for the normal parameter' msg_list.append(msg) if z2_txt == '': if self.interface_lng_val == 'Russian': msg = 'Укажите значение z для параметра normal' elif self.interface_lng_val == 'English': msg = 'Specify the z value for the normal parameter' msg_list.append(msg) if planeTolerance_txt == '': if self.interface_lng_val == 'Russian': msg = 'Укажите значение для параметра planeTolerance' elif self.interface_lng_val == 'English': msg = 'Specify the value for the planeTolerance parameter' msg_list.append(msg) for msg in msg_list: msg_lbl = QLabel('<span style="color:red">' + msg + '</span>') self.par.item = QListWidgetItem() self.par.listWidget.addItem(self.par.item) self.par.listWidget.setItemWidget(self.par.item, msg_lbl) if '' not in xyz1_list and '' not in xyz2_list and planeTolerance_txt != '': if 'mirrorMeshDict_x' not in self.con.tables(): query = QtSql.QSqlQuery() xyz1_str = x1_txt + ' ' + y1_txt + ' ' + z1_txt xyz2_str = x2_txt + ' ' + y2_txt + ' ' + z2_txt query.exec("CREATE TABLE mirrorMeshDict_x(name, value)") query.exec( "INSERT INTO mirrorMeshDict_x(name, value) VALUES ('%s', '%s')" % ('planeType', planeType_txt)) query.exec( "INSERT INTO mirrorMeshDict_x(name, value) VALUES ('%s', '%s')" % ('point', xyz1_str)) query.exec( "INSERT INTO mirrorMeshDict_x(name, value) VALUES ('%s', '%s')" % ('point', xyz2_str)) query.exec( "INSERT INTO mirrorMeshDict_x(name, value) VALUES ('%s', '%s')" % ('planeTolerance', planeTolerance_txt)) else: query = QtSql.QSqlQuery() xyz1_str = x1_txt + ' ' + y1_txt + ' ' + z1_txt xyz2_str = x2_txt + ' ' + y2_txt + ' ' + z2_txt query.prepare("DROP TABLE mirrorMeshDict_x") query.exec_() query.exec("CREATE TABLE mirrorMeshDict_x(name, value)") query.exec( "INSERT INTO mirrorMeshDict_x(name, value) VALUES ('%s', '%s')" % ('planeType', planeType_txt)) query.exec( "INSERT INTO mirrorMeshDict_x(name, value) VALUES ('%s', '%s')" % ('point', xyz1_str)) query.exec( "INSERT INTO mirrorMeshDict_x(name, value) VALUES ('%s', '%s')" % ('point', xyz2_str)) query.exec( "INSERT INTO mirrorMeshDict_x(name, value) VALUES ('%s', '%s')" % ('planeTolerance', planeTolerance_txt)) # записываем файл mirrorMeshDict.x if os.path.exists(self.full_dir + '/system/mirrorMeshDict.x'): os.remove(self.full_dir + '/system/mirrorMeshDict.x') shutil.copyfile("./matches/Shablon/system/mirrorMeshDict.x", self.full_dir + '/system/mirrorMeshDict.x') mMD_x = open(self.full_dir + '/system/mirrorMeshDict.x', 'a') planeType_bl = '\n' + 'planeType' + ' ' + planeType_txt + ';' + '\n' pAND_bl = '\n' + 'pointAndNormalDict' + '\n' + '{' + '\n' + ' ' + 'point' + ' ' + '(' + x1_txt + ' ' + y1_txt + ' ' + z1_txt + ');' + '\n' + \ ' ' + 'normal' + ' ' + '(' + x2_txt + ' ' + y2_txt + ' ' + z2_txt + ');' + '\n' + '}' + '\n\n' planeTolerance_bl = 'planeTolerance' + ' ' + planeTolerance_txt + ';' + '\n\n' mMD_x.write(planeType_bl + pAND_bl + planeTolerance_bl) close_str = '// ************************************************************************* //' mMD_x.write(close_str) mMD_x.close() if self.interface_lng_val == 'Russian': msg = 'Файл mirrorMeshDict.x сохранен' elif self.interface_lng_val == 'English': msg = 'The mirrorMeshDict.x file saved</span>' self.par.listWidget.clear() msg_lbl = QLabel('<span style="color:green">' + msg + '</span>') self.par.item = QListWidgetItem() self.par.listWidget.addItem(self.par.item) self.par.listWidget.setItemWidget(self.par.item, msg_lbl) self.data_reprint()
def querys(self, sql): q = QtSql.QSqlQuery(self.db.database('asignaturas')) q.prepare(sql) return q
def setupUi(self, DialogCreditor): DialogCreditor.setObjectName("DialogCreditor") DialogCreditor.resize(474, 432) self.label_2 = QtWidgets.QLabel(DialogCreditor) self.label_2.setGeometry(QtCore.QRect(30, 56, 44, 27)) self.label_2.setObjectName("label_2") self.name = QtWidgets.QLineEdit(DialogCreditor) self.name.setGeometry(QtCore.QRect(80, 56, 146, 27)) self.name.setObjectName("name") self.lblPhone = QtWidgets.QLabel(DialogCreditor) self.lblPhone.setGeometry(QtCore.QRect(240, 56, 48, 27)) self.lblPhone.setObjectName("lblPhone") self.phone = QtWidgets.QLineEdit(DialogCreditor) self.phone.setGeometry(QtCore.QRect(290, 56, 151, 27)) self.phone.setObjectName("phone") self.productName = QtWidgets.QLineEdit(DialogCreditor) self.productName.setGeometry(QtCore.QRect(140, 110, 301, 27)) self.productName.setInputMethodHints(QtCore.Qt.ImhPreferNumbers) self.productName.setObjectName("productName") self.lblAmountPaid = QtWidgets.QLabel(DialogCreditor) self.lblAmountPaid.setGeometry(QtCore.QRect(30, 170, 92, 27)) self.lblAmountPaid.setToolTip("") self.lblAmountPaid.setProperty("toolTipDuration", 2) self.lblAmountPaid.setObjectName("lblAmountPaid") self.amountPaid = QtWidgets.QLineEdit(DialogCreditor) self.amountPaid.setGeometry(QtCore.QRect(130, 170, 311, 27)) self.amountPaid.setObjectName("amountPaid") self.lblAmount = QtWidgets.QLabel(DialogCreditor) self.lblAmount.setGeometry(QtCore.QRect(30, 230, 103, 27)) self.lblAmount.setObjectName("lblAmount") self.amountOwed = QtWidgets.QLineEdit(DialogCreditor) self.amountOwed.setGeometry(QtCore.QRect(160, 230, 281, 27)) self.amountOwed.setObjectName("amountOwed") self.lblTotal = QtWidgets.QLabel(DialogCreditor) self.lblTotal.setGeometry(QtCore.QRect(30, 286, 38, 27)) self.lblTotal.setObjectName("lblTotal") self.total = QtWidgets.QLineEdit(DialogCreditor) self.total.setGeometry(QtCore.QRect(80, 286, 145, 27)) self.total.setObjectName("total") self.quantity = QtWidgets.QLineEdit(DialogCreditor) self.quantity.setGeometry(QtCore.QRect(320, 286, 119, 27)) self.quantity.setInputMethodHints(QtCore.Qt.ImhPreferNumbers) self.quantity.setObjectName("quantity") self.dueDate = QtWidgets.QDateEdit(DialogCreditor) self.dueDate.setGeometry(QtCore.QRect(100, 340, 341, 27)) self.dueDate.setInputMethodHints(QtCore.Qt.ImhNone) self.dueDate.setCorrectionMode( QtWidgets.QAbstractSpinBox.CorrectToNearestValue) self.dueDate.setMinimumDate(QtCore.QDate(2018, 6, 20)) self.dueDate.setCalendarPopup(True) self.dueDate.setObjectName("dueDate") self.label = QtWidgets.QLabel(DialogCreditor) self.label.setGeometry(QtCore.QRect(-10, -4, 491, 41)) font = QtGui.QFont() font.setFamily("Times New Roman") font.setPointSize(14) font.setBold(True) font.setItalic(False) font.setWeight(75) self.label.setFont(font) self.label.setStyleSheet("background-color: rgb(0, 85, 127);\n" "color: rgb(255, 255, 255);") self.label.setAlignment(QtCore.Qt.AlignCenter) self.label.setObjectName("label") self.label_3 = QtWidgets.QLabel(DialogCreditor) self.label_3.setGeometry(QtCore.QRect(30, 110, 102, 27)) self.label_3.setObjectName("label_3") self.lblQuantity_2 = QtWidgets.QLabel(DialogCreditor) self.lblQuantity_2.setGeometry(QtCore.QRect(240, 286, 64, 27)) self.lblQuantity_2.setObjectName("lblQuantity_2") self.btnCancel = QtWidgets.QPushButton(DialogCreditor) self.btnCancel.setGeometry(QtCore.QRect(50, 381, 99, 31)) self.btnCancel.setStyleSheet("background-color: rgb(0, 0, 0);\n" "color: rgb(255, 255, 255);") self.btnCancel.setObjectName("btnCancel") self.lblDueDate = QtWidgets.QLabel(DialogCreditor) self.lblDueDate.setGeometry(QtCore.QRect(30, 336, 53, 27)) self.lblDueDate.setObjectName("lblDueDate") self.btnSave = QtWidgets.QPushButton(DialogCreditor) self.btnSave.setGeometry(QtCore.QRect(360, 381, 81, 31)) self.btnSave.setStyleSheet( "background-color: rgb(0, 0, 175);\n" "color: rgb(255, 255, 255);\n" "alternate-background-color: rgb(0, 0, 255);\n" "selection-background-color: rgb(0, 0, 232);") self.btnSave.setObjectName("btnSave") sql.connectDB() complet = QtWidgets.QCompleter() complet.setFilterMode(QtCore.Qt.MatchContains) complet.setCaseSensitivity(QtCore.Qt.CaseInsensitive) complet.setCompletionMode(QtWidgets.QCompleter.PopupCompletion) qery = QtSql.QSqlQuery() qery.exec_("select product_name from products") modal = QtSql.QSqlQueryModel() modal.setQuery(qery) self.productName.setCompleter(complet) complet.setModel(modal) completer = QtWidgets.QCompleter() completer.setFilterMode(QtCore.Qt.MatchContains) completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive) completer.setCompletionMode(QtWidgets.QCompleter.PopupCompletion) query = QtSql.QSqlQuery() query.exec_("select name, phone from customers") modl = QtSql.QSqlQueryModel() modl.setQuery(query) self.name.setCompleter(completer) completer.setModel(modl) completer.setCompletionColumn(0) completor = QtWidgets.QCompleter() completor.setFilterMode(QtCore.Qt.MatchContains) completor.setCaseSensitivity(QtCore.Qt.CaseInsensitive) completor.setCompletionMode(QtWidgets.QCompleter.PopupCompletion) self.phone.setCompleter(completor) completor.setModel(modl) completor.setCompletionColumn(1) self.retranslateUi(DialogCreditor) QtCore.QMetaObject.connectSlotsByName(DialogCreditor)