Esempio n. 1
0
    def __init__( self ):
        '''
        Constructor
        '''
        super( tbFactura, self ).__init__(  )

# ESTABLECER LA INTERFAZ AL FORMULARIO
        self.setupUi(self)
# VALIDADOR DE MODO DE EDICION
        self.readOnly = True
        self.editmodel = None
#ESTABLECER LA FECHA INICIAL , (establecida al dia de mañana)
        self.categoriesview.headers = ["Descripcion", "Precio", "Unidades","Existencia","","",""]

# Crear el modelo para cargar catalogo de clientes
        self.clientesModel = QSqlQueryModel()
# Crear lista de autocompletado para el combo de clientes
        self.clienteCompleter = QCompleter()     
# Modelo que carga el catalogo de productos
        self.existenciaModel = QSqlQueryModel()

# Establecer todos los controles en modo de edicion
        self.setControls( False )
# Crear la conexion a la base de datos
        self.database = QSqlDatabase.database()

        
        
        self.vistaprevia = False
        
# Cargar los modelos del modo de edicion
        self.updateEditModels()
        self.parent = self.parent()
Esempio n. 2
0
    def __init__(self):
        '''
        Constructor
        '''
        super(tbFactura, self).__init__()

        # ESTABLECER LA INTERFAZ AL FORMULARIO
        self.setupUi(self)
        # VALIDADOR DE MODO DE EDICION
        self.readOnly = True
        self.editmodel = None
        #ESTABLECER LA FECHA INICIAL , (establecida al dia de mañana)
        self.categoriesview.headers = [
            "Descripcion", "Precio", "Unidades", "Existencia", "", "", ""
        ]

        # Crear el modelo para cargar catalogo de clientes
        self.clientesModel = QSqlQueryModel()
        # Crear lista de autocompletado para el combo de clientes
        self.clienteCompleter = QCompleter()
        # Modelo que carga el catalogo de productos
        self.existenciaModel = QSqlQueryModel()

        # Establecer todos los controles en modo de edicion
        self.setControls(False)
        # Crear la conexion a la base de datos
        self.database = QSqlDatabase.database()

        self.vistaprevia = False

        # Cargar los modelos del modo de edicion
        self.updateEditModels()
        self.parent = self.parent()
Esempio n. 3
0
 def tabChangedSlot(self,argTabIndex):
     
     if argTabIndex==1:
         db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
         self.tableView.setWindowTitle("Connect to QSQLITE Database Example")                          
         db.setHostName("localhost")
         db.setDatabaseName("serm_shadow.db")
         db.setUserName("")
         db.setPassword("")
                     
         if (db.open()==False): 
             message = "Database Error"
             msg = QMessageBox()
             msg.setIcon(QMessageBox.Information)
             msg.setText("Error at opening database")
             msg.setInformativeText(message)
             msg.setWindowTitle("Informative Message")
             msg.setStandardButtons(QMessageBox.Close)
             msg.exec_()  
             
         projectModel = QSqlQueryModel()
         projectModel.setQuery("SELECT datetime,temperature,humidity,smoke,lpg,co,windspeed,winddir,ffwi,risk FROM data_means ORDER BY recid DESC",db)
         self.tableView.setModel(projectModel)
         self.tableView.adjustSize
         self.tableView.setColumnWidth(0,168)
         self.tableView.show()
         
     elif argTabIndex==3:      
         conn = sqlite3.connect('serm.db')                 
         ds = pd.read_sql("SELECT timestamp,datetime,risk,smoke,temperature,humidity,windspeed,ffwi from data_means", conn);
         conn.close()
         ds.to_csv("serm.csv")
         self.show_predictions_table()
Esempio n. 4
0
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.ui = sm.Ui_Dialog()
        self.ui.setupUi(self)
        self.ui.table_studentList

        # Call DB
        self.db = QSqlDatabase.addDatabase("QSQLITE")
        self.db.setDatabaseName("studentInformation001.db")
        self.db.open()
        # End of call DB

        # student info into table view
        projectModel = QSqlQueryModel()
        projectModel.setQuery("SELECT schoolNumber, Name FROM Student ORDER BY schoolNumber ASC",self.db)

        projectView = self.ui.table_studentList
        projectView.setModel(projectModel)
        projectView.show()
        #end of student info into table view

        # QTableView Click Event
        self.qTableView = self.ui.table_studentList
        self.qTableView.clicked.connect(self.showInfo)
        
        # click and connection update
        self.ui.Btn_Update.clicked.connect(self.cont)
        
        # click and connection grade
        self.ui.Btn_Grade.clicked.connect(self.contGrade)
Esempio n. 5
0
    def __init__( self, tiposdoc, parent = None, edit = True ):
        '''
        Constructor
        '''
        super( FrmKardex, self ).__init__( parent )
        self.tiposdoc = ",".join( [str( item ) for item in tiposdoc] )

        self.edit = edit



        self.navigationmodel = QSqlQueryModel()

        self.detailsModel = QSqlQueryModel()


        self.navproxymodel = QSortFilterProxyModel()
        self.navproxymodel.setSourceModel( self.navigationmodel )

        self.detailsproxymodel = QSortFilterProxyModel()
        self.detailsproxymodel.setSourceModel( self.detailsModel )


        self.tabledetails.setModel( self.detailsproxymodel )
        self.tablenavigation.setModel( self.navproxymodel )

        self.editmodel = None

        QTimer.singleShot( 0, self.loadModels )
Esempio n. 6
0
    def __init__(self, parent):
        """
        Constructor
        """
        super(FrmCheques, self).__init__(parent)

        self.navmodel = QSqlQueryModel(self)
        self.navproxymodel = QSortFilterProxyModel(self)
        self.navproxymodel.setSourceModel(self.navmodel)

        self.accountsModel = QSqlQueryModel()
        self.accountsProxyModel = ROAccountsModel(self)
        self.accountsProxyModel.setSourceModel(self.accountsModel)

        #        El modelo que filtra a self.navmodel
        self.navproxymodel.setFilterKeyColumn(-1)
        self.navproxymodel.setFilterCaseSensitivity(Qt.CaseInsensitive)
        self.editmodel = None

        self.status = True
        # las acciones deberian de estar ocultas

        # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

        QTimer.singleShot(0, self.loadModels)
Esempio n. 7
0
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = sm.Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.table_studentList

        # Call DB
        db = QSqlDatabase.addDatabase("QSQLITE")
        db.setDatabaseName("studentInformation001.db")
        db.open()
        # End of call DB

        # student info into table view
        projectModel = QSqlQueryModel()
        projectModel.setQuery(
            "SELECT schoolNumber, Name FROM Student ORDER BY schoolNumber ASC",
            db)

        projectView = self.ui.table_studentList
        projectView.setModel(projectModel)
        projectView.show()
        #end of student info into table view

        # QTableView Click Event
        self.qTableView = self.ui.table_studentList
        self.qTableView.clicked.connect(self.showInfo)
Esempio n. 8
0
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.ui = sm.Ui_Dialog()
        self.ui.setupUi(self)
        self.ui.table_studentList

        # Call DB
        self.db = QSqlDatabase.addDatabase("QSQLITE")
        self.db.setDatabaseName("studentInformation001.db")
        self.db.open()
        # End of call DB

        # student info into table view
        projectModel = QSqlQueryModel()
        projectModel.setQuery(
            "SELECT schoolNumber, Name FROM Student ORDER BY schoolNumber ASC",
            self.db)

        projectView = self.ui.table_studentList
        projectView.setModel(projectModel)
        projectView.show()
        #end of student info into table view

        # QTableView Click Event
        self.qTableView = self.ui.table_studentList
        self.qTableView.clicked.connect(self.showInfo)

        # click and connection update
        self.ui.Btn_Update.clicked.connect(self.cont)

        # click and connection grade
        self.ui.Btn_Grade.clicked.connect(self.contGrade)
Esempio n. 9
0
    def __init__( self, parent = None ):
        '''
        Constructor
        '''
        super( FrmKardexOther, self ).__init__( parent )
        self.actionNew.setEnabled( False )
        self.navmodel = QSqlQueryModel()

        self.detailsModel = QSqlQueryModel()


        self.navproxymodel = QSortFilterProxyModel()
        self.navproxymodel.setSourceModel( self.navmodel )

        self.detailsproxymodel = QSortFilterProxyModel()
        self.detailsproxymodel.setSourceModel( self.detailsModel )

        self.accountsnavmodel = QSqlQueryModel()
        self.accountsproxymodel = QSortFilterProxyModel()
        self.accountsproxymodel.setSourceModel( self.accountsnavmodel )



        self.editmodel = None

        if not self.user.hasRole( "contabilidad" ):
            self.tableaccounts.setVisible( False )
            self.lblaccounts.setVisible( False )

        QTimer.singleShot( 0, self.loadModels )
Esempio n. 10
0
    def show_predictions_table(self):
        db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
        self.tableView_PM.setWindowTitle("Connect to QSQLITE Database Example")                          
        db.setHostName("localhost")
        db.setDatabaseName("serm.db")
        db.setUserName("")
        db.setPassword("")

        if (db.open()==False): 
            message = "Database Error"
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Information)
            msg.setText("Error at opening database")
            msg.setInformativeText(message)
            msg.setWindowTitle("Informative Message")
            msg.setStandardButtons(QMessageBox.Close)
            msg.exec_()               
        
        projectModel = QSqlQueryModel()
        projectModel.setQuery("SELECT datetime,smoke,temperature,humidity,windspeed,fri,ffwi FROM predictions ORDER BY recid DESC",db)
        
        self.tableView_PM.setModel(projectModel)
        self.tableView_PM.adjustSize
        self.tableView_PM.setColumnWidth(0,160)
        self.tableView_PM.show()  
Esempio n. 11
0
    def __init__( self, parent = None ):
        super( ReciboDelegate, self ).__init__( parent )

        query = QSqlQuery( """
            SELECT
                idtipomovimiento,
                CONCAT(descripcion, ' ' , moneda) as tipopago,
                idtipomoneda,
                m.simbolo
                FROM tiposmoneda m
            JOIN tiposmovimientocaja p
            ;
        """ )
        self.filtrados = []
        query.exec_()
        while query.next():
            self.filtrados.append( query.value( 1 ).toString() )

        self.abonosmodel = QSqlQueryModel()
        self.abonosmodel.setQuery( query )
        self.proxymodel = QSortFilterProxyModel()
        self.proxymodel.setSourceModel( self.abonosmodel )
        self.proxymodel.setFilterKeyColumn( 1 )
        self.completer = QCompleter()
        self.completer.setModel( self.proxymodel )

        self.completer.setCompletionColumn( 1 )
        self.completer.setCaseSensitivity( Qt.CaseInsensitive )
        self.completer.setCompletionMode( QCompleter.UnfilteredPopupCompletion )

        query = QSqlQuery( """
            SELECT idbanco,descripcion FROM bancos;
            """ )
        self.bancosmodel = QSqlQueryModel()
        self.bancosmodel.setQuery( query )
Esempio n. 12
0
 def querymodel(self, sql, **mappings):
     query = self._query(sql, **mappings)
     if query.exec_():
         model = QSqlQueryModel()
         model.setQuery(query)
         return model
     else:
        raise DatabaseException(query.lastError().text()) 
Esempio n. 13
0
 def querymodel(self, sql, **mappings):
     query = self._query(sql, **mappings)
     if query.exec_():
         model = QSqlQueryModel()
         model.setQuery(query)
         return model
     else:
         raise DatabaseException(query.lastError().text())
Esempio n. 14
0
 def __init__(self, parent=None):
     """
     Constructor
     """
     QSqlQueryModel.__init__(self, parent)
     self.data = []
     self.rCount = 0
     self.cCount = 0
Esempio n. 15
0
 def __init__(self, parent = None):
     """
     Constructor
     """
     QSqlQueryModel.__init__(self, parent)
     self.data = []
     self.rCount = 0
     self.cCount = 0
    def __init__(self, connectionName='', parent=None):
        """

        :type connectionName:str
        :type parent: QObject
        :return:
        """
        QSqlQueryModel.__init__(self, parent)

        self.__mConnectionName = connectionName
Esempio n. 17
0
 def querymodel(self, sql, **mappings):
     sql = sql.replace(r"\r\n", " ")
     query = self._query(sql, **mappings)
     print sql, mappings
     if query.exec_():
         model = QSqlQueryModel()
         model.setQuery(query)
         return model
     else:
         raise DatabaseException(query.lastError().text()) 
Esempio n. 18
0
 def data( self, index, role = Qt.DisplayRole ):
     """
     Esta funcion redefine data en la clase base, es el metodo que se utiliza para mostrar los datos del modelo
     """
     value = QSqlQueryModel.data( self, index, role )
     exchangeRate = Decimal( QSqlQueryModel.data( self, index.model().index( index.row(), TASA ) ).toString() )
     if value.isValid() and role in ( Qt.DisplayRole, Qt.EditRole ):
         if index.column() in ( TOTAL, SUBTOTAL, COSTO, IMPUESTOS ):
             return moneyfmt( Decimal( value.toString() ), 2, "US$" ) + " / " + moneyfmt( Decimal( value.toString() ) * exchangeRate, 2 , "C$" )
     return value
    def __init__(self, connectionName='', parent=None):
        """

        :type connectionName:str
        :type parent: QObject
        :return:
        """
        QSqlQueryModel.__init__(self, parent)

        self.__mConnectionName = connectionName
Esempio n. 20
0
 def querymodel(self, sql, **mappings):
     sql = sql.replace(r"\r\n", " ")
     query = self._query(sql, **mappings)
     print sql, mappings
     if query.exec_():
         model = QSqlQueryModel()
         model.setQuery(query)
         return model
     else:
         raise DatabaseException(query.lastError().text())
 def get_linked_esu_list(self, usrn):
     """
     function that selects all esus for a determined street
     :param usrn: the unique identifier of a certain street
     :return: list[esu_ids] all esu ids linked to a certain street or
     void in case a street does not have any linked esu
     """
     # executing the query
     esus_query_model = QSqlQueryModel()
     esus_query_model.setQuery(self.queries[9].format(usrn))
     while esus_query_model.canFetchMore():
         esus_query_model.fetchMore()
     n_rows = esus_query_model.rowCount()
     # skip if no esus are linked
     if n_rows == 0:
         return
     else:
         i = 0
         esus_list = []
         # creating a list of ESUs Ids that are linked to the street
         while i <= n_rows - 1:
             model_index = esus_query_model.createIndex(i, 0)
             esu = model_index.data()
             esus_list.append(esu)
             i += 1
         return esus_list
Esempio n. 22
0
    def __init__(self):
        super(MainWindow, self).__init__(None)

        self.model = QSqlQueryModel(self)
        self.model.setQuery("select * from student")
        self.model.setHeaderData(0, Qt.Horizontal, self.tr("学号"))
        self.model.setHeaderData(1, Qt.Horizontal, self.tr("姓名"))
        self.model.setHeaderData(2, Qt.Horizontal, self.tr("课程"))
        self.view = QTableView(self)
        self.view.setModel(self.model)
        self.setCentralWidget(self.view)
Esempio n. 23
0
 def fill_tables(self, qtable, table_name):
     """
     :param qtable: QTableView to show
     :param table_name: view or table name wich we want to charge
     """
     sql = "SELECT * FROM " + self.controller.schema_name + "." + table_name
     sql += " WHERE node_id = '" + self.id + "'"
     model = QSqlQueryModel()
     model.setQuery(sql)
     qtable.setModel(model)
     qtable.show()
Esempio n. 24
0
    def data( self, index, role = Qt.DisplayRole ):
        """
        Esta funcion redefine data en la clase base, es el metodo 
        que se utiliza para mostrar los datos del modelo
        """

        if not index.isValid():
            return None

        column = index.column()

        value = QSqlQueryModel.data( self, index, role )

        if column == CONCILIADO:
            if role == Qt.CheckStateRole and index.row() > 0:
                value = QSqlQueryModel.data( self, self.index( index.row(), 4 ), Qt.DisplayRole ).toInt()[0]
                return QVariant( Qt.Checked ) if value == 1 else QVariant( Qt.Unchecked )
            elif role == Qt.EditRole:
                return QSqlQueryModel.data( self, self.index( index.row(), 4 ), Qt.DisplayRole ).toInt()[0]
            else:
                return None
        elif column == SALDO:
            if role == Qt.DisplayRole:
                value = QSqlQueryModel.data( self, self.index( index.row(), 3 ), Qt.DisplayRole )
                value = Decimal( value.toString() )
                return moneyfmt( value, 4, "C$" )
        elif column == DEBE:
            if role == Qt.DisplayRole:
                value = Decimal( value.toString() )
                return moneyfmt( value, 4, "C$" ) if value > 0 else ""
            elif role == Qt.EditRole:
                return value
        elif column == HABER:
            if role == Qt.DisplayRole:
                value = Decimal( QSqlQueryModel.data( self, self.index( index.row(), DEBE ), role ).toString() )
                return moneyfmt( value * -1, 4, "C$" ) if value < 0 else ""
        elif column == CONCEPTO:
            if role == Qt.ToolTipRole:
                value = QSqlQueryModel.data( self, self.index( index.row(), 7 ), Qt.DisplayRole )
                return value
            elif role == Qt.DisplayRole:
                return value
            else:
                return None
        elif column == DELBANCO:
            if role == Qt.EditRole:
                value = QSqlQueryModel.data( self, self.index( index.row(), 5 ), Qt.DisplayRole )
                return value
            elif role == Qt.DisplayRole and index.row() > 0:
                value = QSqlQueryModel.data( self, self.index( index.row(), 5 ), Qt.DisplayRole )
                return "Si" if value == 1 else "No"
        elif column == IDTIPODOC:
            if role == Qt.EditRole:
                value = QSqlQueryModel.data( self, self.index( index.row(), 6 ), Qt.DisplayRole )
                return value
        elif column == FECHA:
            return value
        return None
Esempio n. 25
0
 def loadAllData(self):
     self.items = []
     model = QSqlQueryModel()
     model.setQuery('''SELECT s.code, s.name
             FROM services s
             ''')
     for i in xrange(model.rowCount()):
         code = model.record(i).value("code").toString()
         name = model.record(i).value("name").toString()
         item = [code + u": " + name]
         self.items.append(item)
     self.reset()
Esempio n. 26
0
    def __init__( self, datos_sesion, parent, edit = False ):
        u'''
        @param datos_sesion: La información de la sesion de caja
        '''
        super( FrmArqueo, self ).__init__( parent, True )
        self.sesion = datos_sesion
        self.setWindowModality( Qt.WindowModal )
        self.setWindowFlags( Qt.Dialog )
#        self.status = False 

        self.__dolar_proxy = ArqueoProxyModel()
        self.__cordoba_proxy = ArqueoProxyModel()
                    
        
        self.editmodel = None

#        El modelo principal
        self.navmodel = QSqlQueryModel( self )
    #        El modelo que filtra a self.navmodel
        self.navproxymodel = QSortFilterProxyModel( self )
        self.__details_proxymodel_d = QSortFilterProxyModel( self )
        self.__details_proxymodel_c = QSortFilterProxyModel( self )
        
        
        self.navproxymodel.setSourceModel( self.navmodel )
#        Este es el modelo con los datos de la tabla con los detalles
        self.detailsModel = QSqlQueryModel( self )
#        Este es el filtro del modelo anterior
        self.detailsproxymodel = QSortFilterProxyModel( self )
        self.detailsproxymodel.setSourceModel( self.detailsModel )

        #filtrar en dolares y en cordobas
        
        self.__details_proxymodel_d.setSourceModel( self.detailsproxymodel )
        self.__details_proxymodel_d.setFilterKeyColumn( MONEDA )
        self.__details_proxymodel_d.setFilterRegExp( "^%d$" % constantes.IDDOLARES )

    
        self.__details_proxymodel_c.setSourceModel( self.detailsproxymodel )
        self.__details_proxymodel_c.setFilterKeyColumn( MONEDA )
        self.__details_proxymodel_c.setFilterRegExp( "^%d$" % constantes.IDCORDOBAS )
           
        
        
        if edit:
            self.status = False
            self.newDocument()
            self.actionCancel.setVisible(False)
            self.tabWidget.setTabEnabled(1,False)
        else:
            self.status = True
            QTimer.singleShot( 0, self.loadModels )
    def loading(self):
        db = QSqlDatabase.addDatabase("QSQLITE")
        save_path='database/'
        complete = os.path.join(save_path,"user.sqlite")

        db.setDatabaseName(complete)
        db.open()

        View = QSqlQueryModel()
        View.setQuery("select * from users",db)
        self.tableView = QtGui.QTableView()
        self.tableView.setModel(View)
        self.tableView.show()
Esempio n. 28
0
    def updateArticles( self ):
        """
        Actualizar la lista de articulos
        """
        query = QSqlQuery()
        try:
            if not self.database.isOpen():
                if not self.database.open():
                    raise UserWarning( u"No se pudo conectar con la "
                                       + "base de datos" )



            self.updateArticleList( query )
            self.editmodel.updateLines( query )


            providers_model = QSqlQueryModel()
            providers_model.setQuery( """
            SELECT idpersona, nombre 
            FROM personas p 
            WHERE tipopersona = 2 AND activo = 1
            """ )
            if not providers_model.rowCount() > 0:
                raise UserWarning( "No existen proveedores en el sistema" )
            self.cbProvider.setModel( providers_model )
            self.cbProvider.setModelColumn( 1 )

            warehouse_model = QSqlQueryModel()
            warehouse_model.setQuery( """
            SELECT idbodega, nombrebodega
            FROM bodegas b
            ORDER BY idbodega
            """ )
            if not warehouse_model.rowCount() > 0:
                raise UserWarning( "No existen bodegas en el sistema" )
            self.cbWarehouse.setModel( warehouse_model )
            self.cbWarehouse.setModelColumn( 1 )

            self.cbWarehouse.setCurrentIndex( -1 )
            self.cbProvider.setCurrentIndex( -1 )



        except UserWarning as inst:
            QMessageBox.warning( self, qApp.organizationName(),
                                  unicode( inst ) )
            logging.error( query.lastError().text() )
            logging.error( unicode( inst ) )
            self.cancel()
        except Exception as inst:
            QMessageBox.critical( self, qApp.organizationName(),
                "Hubo un error fatal al tratar de actualizar la lista " \
                + "de articulos, el sistema no puede recuperarse" \
                + " y sus cambios se han perdido" )
            logging.error( query.lastError().text() )
            logging.critical( unicode( inst ) )
            self.cancel()
Esempio n. 29
0
    def __init__(self, numero, parent=None):
        super(Anular, self).__init__(parent)

        self.setupUi()

        # QtCore.QMetaObject.connectSlotsByName(self)

        self.conceptosmodel = QSqlQueryModel()
        self.conceptosmodel.setQuery(
            """
        SELECT idconcepto,descripcion
        FROM conceptos c
        WHERE idtipodoc = %d
        ;
        """
            % constantes.IDANULACION
        )
        self.cboConceptos.setModel(self.conceptosmodel)
        self.cboConceptos.setCurrentIndex(-1)
        self.cboConceptos.setModelColumn(1)
        self.numero = numero

        self.lblnCheque2.setText(str(self.numero))
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
Esempio n. 30
0
    def __init__( self , numero, parent = None ):
        super( DlgAnular, self ).__init__( parent )

        self.cboConceptos = QComboBox( self )
        self.cboConceptos.setObjectName( "cboConceptos" )

        self.txtObservaciones = QPlainTextEdit( self )
        self.txtObservaciones.setObjectName( "txtObservaciones" )
        self.setupUi()


        #QtCore.QMetaObject.connectSlotsByName(self)

        self.conceptosmodel = QSqlQueryModel()
        self.conceptosmodel.setQuery( """
        SELECT idconcepto,descripcion
        FROM conceptos c
        WHERE idtipodoc = %d
        ;
        """ % constantes.IDANULACION )
        self.cboConceptos.setModel( self.conceptosmodel )
        self.cboConceptos.setCurrentIndex( -1 )
        self.cboConceptos.setModelColumn( 1 )
        self.numero = numero

        self.lblnfactura2.setText( str( self.numero ) )
Esempio n. 31
0
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.clientId = None

        self.modelClients = CSqlQueryModel()
        self.modelClients.setQuery(
            "SELECT ID, Deleted, Surname, Name, MidName, BirthDate, Sex, SNILS, Growth, Weight, birthPlace, notes FROM Client WHERE deleted = 0 ORDER BY Surname, Name, MidName")
        self.ui.tableView.setModel(self.modelClients)
        self.modelServices = QSqlQueryModel()

        self.installEventFilter(self)
        self.ui.btnClear.clicked.connect(self.clear)
        self.ui.btnSearch.clicked.connect(self.search)
        self.ui.btnPrint.clicked.connect(self.createReport)
        self.ui.tableView.setColumnHidden(0, True)
        self.ui.tableView.setColumnHidden(1, True)
        self.ui.tableView_2.setColumnHidden(0, True)
        QtCore.QObject.connect(self.ui.tableView.selectionModel(),
                               QtCore.SIGNAL('currentRowChanged(QModelIndex, QModelIndex)'), self.getClientId)
        self.ui.leAge.setValidator(
            QtGui.QRegExpValidator(QtCore.QRegExp("0[0-9][1-9]|1[12][0-9]|[1-9][1-9]|[1-9]"), self))
        self.ui.leAge.textChanged.connect(self.updateBirthDate)
        self.ui.leBirthDay.textChanged.connect(self.updateYear)
        self.ui.tableView.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.tableView.customContextMenuRequested.connect(self.popup)
Esempio n. 32
0
    def __init__( self, parent = None ):
        """
        Constructor
        """
        super( FrmDevolucion, self ).__init__( parent )



        self.editmodel = None

        self.status = True

#        las acciones deberian de estar ocultas


#        El modelo principal
        self.navmodel = RONavigationModel( self )
#        El modelo que filtra a self.navmodel
        self.navproxymodel = QSortFilterProxyModel( self )
        self.navproxymodel.setSourceModel( self.navmodel )
#        Este es el modelo con los datos de la tabla para navegar
        self.detailsmodel = QSqlQueryModel( self )
#        Este es el filtro del modelo anterior
        self.detailsproxymodel = QSortFilterProxyModel( self )
        self.detailsproxymodel.setSourceModel( self.detailsmodel )



#        Cargar los modelos en un hilo aparte
        QTimer.singleShot( 0, self.loadModels )
Esempio n. 33
0
 def __init__(self, parent=None, datamodel=None):
     """
     Constructor
     """
     QDialog.__init__(self, parent)
     self.setupUi(self)
     self.model = QSqlQueryModel()
     self.selTableView.setModel(self.model)
     self.database = datamodel.getQSqlDatabase()
     self.updateModel()
     self.selTableView.hideColumn(0)
     self.selTableView.hideColumn(5)
     self.selTableView.hideColumn(6)
     # Change status and keep the column.
     QObject.connect(datamodel, SIGNAL("modelInstalled()"),
                     self.on_datamodel_modelInstalled)
Esempio n. 34
0
    def __init__( self, tipo, rol, parent ):
        super( FrmPersona, self ).__init__( parent, True )

        self.tabledetails = None
        self.setWindowModality( Qt.WindowModal )
        self.setWindowFlags( Qt.Dialog )

        self.tipo = tipo
        self.rol = rol
        self.lbltitulo.setText( u"<B>Datos del %s</B>" % rol )

        self.editmodel = None
#        self.parent = parent

        self.navmodel = QSqlQueryModel()

        self.navproxymodel = QSortFilterProxyModel()
        self.navproxymodel.setFilterKeyColumn( -1 )
        self.navproxymodel.setSourceModel( self.navmodel )
        self.navproxymodel.setFilterCaseSensitivity( Qt.CaseInsensitive )
        self.tablenavigation.setModel( self.navproxymodel )

        self.actionPreview.setVisible( False )
        self.actionPrint.setVisible( False )
        self.updateModels()
        self.status = True
Esempio n. 35
0
 def data( self, index, role = Qt.DisplayRole ):
     if role == Qt.CheckStateRole and index.column() == ACTIVO:
         if index.column() == ACTIVO:
             return  QVariant( Qt.Checked ) if index.data( Qt.EditRole ).toBool() else QVariant( Qt.Unchecked )
     elif role == Qt.DisplayRole and index.column() == ACTIVO:
         return None
     return QSqlQueryModel.data( self, index, role )
Esempio n. 36
0
 def loadData(self, clientId):
     self.items = []
     if clientId:
         model = QSqlQueryModel()
         model.setQuery('''SELECT s.code, s.name
             FROM Client c
             INNER JOIN cure cr on cr.Client_ID = c.id
             INNER JOIN services s on s.id = cr.Services_ID
             WHERE c.id = {0}
             '''.format(clientId))
         for i in xrange(model.rowCount()):
             code = model.record(i).value("code").toString()
             name = model.record(i).value("name").toString()
             item = [code + u": " + name]
             self.items.append(item)
     self.items.append([u""])
     self.reset()
Esempio n. 37
0
 def __init__( self, query, showTable = False ):
     QStyledItemDelegate.__init__( self )
     self.accounts = QSqlQueryModel()
     self.accounts.setQuery( query )
     self.proxymodel = QSortFilterProxyModel()
     self.proxymodel.setFilterKeyColumn( 0 )
     self.proxymodel.setSourceModel( self.accounts )
     self.showTable = showTable
     self.filtrados = []
Esempio n. 38
0
 def clear_xref_and_esu_tables(self):
     """
     Blank model clears the xref table
     """
     # Set xref to empty model
     empty_model = QSqlQueryModel()
     self.street_browser.ui.crossReferenceTableView.setModel(empty_model)
     # Clear list widget
     self.street_browser.ui.linkEsuListWidget.clear()
Esempio n. 39
0
 def populate_list(self, table_id):
     """
     populate the list view on initialisation and when radio buttons are toggled,
     this view is just for show because QSqlQueryModel class does not handle editing
     but data need to be displayed as concatenated strings, this is not allowed in a
     QSqlTableModel class
     :param table_id: the id passed from the radio button
     :return: void
     """
     self.srwr_lu_dia.ui.typeDescLineEdit.clear()
     self.items_model = QSqlQueryModel()
     self.items_model.setQuery(self.queries[table_id], self.db)
     while self.items_model.canFetchMore():
         self.items_model.fetchMore()
     self.srwr_lu_dia.ui.typeNoSpinBox.setValue(0)
     self.srwr_lu_dia.ui.itemsListView.setModel(self.items_model)
     self.srwr_lu_dia.ui.itemsListView.setModelColumn(1)
     self.create_data_model(table_id)
Esempio n. 40
0
    def __init__( self, parent  ):
        super( dlgmovimientosbancarios, self ).__init__( parent ) 
        self.conceptosModel = QSqlQueryModel() 
        self.setupUi( self )
        self.database = QSqlDatabase.database()
        self.proxymodel = QSortFilterProxyModel()
        self.editmodel = MovimientosBancariosModel()
        
        
        fecha = self.parent().editmodel.fechaConciliacion
        self.dtPicker.setMaximumDate(fecha)
        self.dtPicker.setMinimumDate(QDate(fecha.year(),fecha.month(),1))
        self.cbtipodoc.addItem(u"Nota de Crédito")
        self.cbtipodoc.addItem(u"Nota de Débito")
        
        self.conceptosModel.setQuery( """
               SELECT idconcepto, descripcion,idtipodoc FROM conceptos c WHERE idtipodoc in (%d,%d );
            """ %(constantes.IDNOTACREDITO,constantes.IDND) )
        
        
        self.proxymodel.setSourceModel(self.conceptosModel)
        self.proxymodel.setFilterKeyColumn(2)
        self.proxymodel.setFilterCaseSensitivity(Qt.CaseInsensitive)
        self.cbconcepto.setModel(self.proxymodel)
        self.cbconcepto.setModelColumn(1)
        self.buttonBox.rejected.connect( self.reject )
        self.buttonBox.accepted.connect( self.aceptar )
        
        self.editmodel.tipoDoc = constantes.IDDEPOSITO 

        
        self.cuentasDelegate = AccountsSelectorDelegate( QSqlQuery( """
            SELECT c.idcuenta, c.codigo, c.descripcion
            FROM cuentascontables c
            JOIN cuentasxdocumento cd ON c.idcuenta = cd.idcuenta
            WHERE c.idcuenta in (%d,%d,%d)
            """ %(constantes.CAJAGENERAL,constantes.CAJACHICA, constantes.CAPITAL) ) )


        self.editmodel.insertRow( 1 )
        self.editmodel.lines[0].itemId = parent.editmodel.idCuentaContable
        self.editmodel.lines[0].code = parent.txtcuenta.text()
        self.editmodel.lines[0].name = parent.txtcuenta.toolTip()
        

        self.editmodel.insertRow( 1 )
        self.editmodel.fechaDoc = QDateTime.currentDateTime()
        self.editmodel.autorId = parent.user.uid
            #        Crea un edit delegate para las cuentas
        self.tabledetails.setItemDelegate( self.cuentasDelegate )
        self.tabledetails.setModel( self.editmodel )
        self.tabledetails.setEditTriggers( 
                          QAbstractItemView.EditKeyPressed |
                          QAbstractItemView.AnyKeyPressed |
                          QAbstractItemView.DoubleClicked )

        self.tabledetails.setColumnHidden(0,False)
Esempio n. 41
0
    def __init__(self, netmanager, clipboard, parent=None):
        super(MainWin, self).__init__(parent)
        self.setWindowTitle("Eilat Browser " + netmanager.name)

        self.netmanager = netmanager
        self.clipboard = clipboard

        self.tab_widget = QTabWidget(self)
        self.tab_widget.tabBar().setMovable(True)
        self.setCentralWidget(self.tab_widget)
        self.tab_widget.setTabsClosable(True)

        database = QSqlDatabase("QPSQL")
        database.open("pguser", "pguser")

        query = QSqlQuery(
            "select concat(host, path) h, count(*) c from reply " +
            "where status between 200 and 399 " +
            "and is_bookmarkable(path) " +
            "and host not in (select host from filtro) " + "group by h " +
            "order by c desc", database)

        self.model = QSqlQueryModel()
        self.model.setQuery(query)

        self.tab_widget.tabCloseRequested.connect(self.del_tab)

        def new_tab_from_clipboard():
            """ One-use callback for QShortcut.
            Reads the content of the PRIMARY clipboard and navigates to it
            on a new tab.

            """
            url = unicode(self.clipboard.text(QClipboard.Selection)).strip()
            self.add_tab(url)

        set_shortcuts([("Ctrl+T", self, self.add_tab),
                       ("Y", self, new_tab_from_clipboard),
                       ("Ctrl+W", self, self.del_tab),
                       ("N", self, partial(self.inc_tab, -1)),
                       ("Ctrl+PgUp", self, partial(self.inc_tab, -1)),
                       ("M", self, self.inc_tab),
                       ("Ctrl+PgDown", self, self.inc_tab),
                       ("Ctrl+Q", self, QApplication.closeAllWindows)])
Esempio n. 42
0
class Cuenta( object ):
    def __init__( self, parent, fecha, account_id = 0 ,
                  code = "", description = "", monto = Decimal( 0 ),
                  esdebe = 0 ):
        self.parentItem = parent
        self.id = account_id
        self.code = code
        self.description = description
        self.monto = monto
        self.esdebe = esdebe

        self.childItems = []

        if self.id != 0:
            self.model = QSqlQueryModel()
            q = "CALL spBalance( %s )" % fecha.toString( "yyyyMMdd" )
            self.model.setQuery( q )

            modelo = self.model
            agregados = []

            for i in range( modelo.rowCount() ):
                if modelo.index( i, IDCUENTA ).data().toInt()[0] not in agregados:
                    c = CuentaPadre( self, modelo, modelo, i, agregados )
                    self.appendChild( c )

    def appendChild( self, item ):
        self.childItems.append( item )

    def child( self, row ):
        return self.childItems[row]

    def childCount( self ):
        return len( self.childItems )

    def columnCount( self ):
        return 8

    @property
    def acumulado( self ):
        total = self.monto
        for child in self.childItems:
            total += child.acumulado
        return total
Esempio n. 43
0
class Users(QObject):
    def __init__(self, parent=None):
        super(Users, self).__init__(parent)
        self.model = QSqlQueryModel()
        self.sortProxyModels = {}
        self.init_model()
        self.init_proxy_models()


    def init_model(self):
        self.model.setQuery(u"SELECT concat_ws(' ', firstname, lastname, patrname) "
                            u"AS FIO, "
                            u"CONCAT_WS(', ', birthdate, TIMESTAMPDIFF(YEAR, birthdate, CURDATE())) "
                            u"AS \"Birth date, age\", "
                            u"(CASE WHEN sex=1 THEN 'М' WHEN sex=2 THEN 'Ж' ELSE 'Неопределен' END)  "
                            u"AS sex , "
                            u"concat_ws(' ', test.ClientPolicy.serial, test.ClientPolicy.number) "
                            u"AS 'Policy serial and number', "
                            u"(SELECT name FROM test.rbDocumentType WHERE id = test.ClientDocument.documentType_id) "
                            u"AS \"Document type\", "
                            u"concat_ws(' ', test.ClientDocument.serial, test.ClientDocument.number) "
                            u"AS \"Document serial and number\""

                            u"FROM test.Client "
                            u"LEFT JOIN test.ClientPolicy ON test.Client.id=test.ClientPolicy.client_id "
                            u"LEFT JOIN test.ClientDocument ON test.Client.id=test.ClientDocument.client_id")


    def init_proxy_model(self, name, column):
        proxy = QSortFilterProxyModel()
        proxy.setSourceModel(self.model)
        proxy.setFilterKeyColumn(column)
        proxy.setFilterCaseSensitivity(Qt.CaseInsensitive)
        self.model = proxy
        self.sortProxyModels[name] = proxy
        return proxy

    def init_proxy_models(self):
        for (name, settings) in config["filter_fields"].items():
            self.init_proxy_model(name, settings["column"])

    def apply_filer(self, text, filter_name):
        self.sortProxyModels[filter_name].setFilterFixedString(text)
Esempio n. 44
0
    def __init__( self, parent = None ):
        '''
        Constructor
        '''
        super( FrmRecibo, self ).__init__( parent )



#       las acciones deberian de estar ocultas
        self.frbotones.setVisible( False )
        self.actionSave.setVisible( False )
        self.actionCancel.setVisible( False )

#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#        El modelo principal
        self.navmodel = QSqlQueryModel( self )
#        El modelo que filtra a self.navmodel
        self.navproxymodel = RONavigationModel( self )
        self.navproxymodel.setSourceModel( self.navmodel )
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++        

#        Este es el modelo con los datos de la con los detalles
        self.detailsmodel = QSqlQueryModel( self )
#        Este es el filtro del modelo anterior
        self.detailsproxymodel = QSortFilterProxyModel( self )
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#        Este es el modelo con los datos de la con los detalles
        self.abonosmodel = QSqlQueryModel( self )
#        Este es el filtro del modelo anterior
        self.abonosproxymodel = QSortFilterProxyModel( self )
        self.abonosproxymodel.setSourceModel( self.abonosmodel )
        self.facturasmodel = QSqlQueryModel( self )
        self.facturasproxymodel = ROFacturasModel( self )
        self.facturasproxymodel.setSourceModel( self.facturasmodel )

        #inicializando el documento
        self.editmodel = None
        self.datosRecibo = None

        self.status = True

        QTimer.singleShot( 0, self.loadModels )
Esempio n. 45
0
 def data( self, index, role = Qt.DisplayRole ):
     """
     Esta funcion redefine data en la clase base, es el metodo 
     que se utiliza para mostrar los datos del modelo
     """
     if not index.isValid():
         return None
     value = QSqlQueryModel.data( self, index, role )
     if index.column() == FECHA and role == Qt.DisplayRole:
         value = value.toDate().toString( "MMMM yyyy" )
     return value
Esempio n. 46
0
    def __init__(self, parent=None):
        super(FrmOperations, self).__init__(parent)
        self.setupUi(self)
        self.__status = False
        self.database = QSqlDatabase.database()

        self.navmodel = QSqlQueryModel()
        self.navproxymodel = QSortFilterProxyModel()
        self.navproxymodel.setFilterKeyColumn(-1)
        self.navproxymodel.setFilterCaseSensitivity(Qt.CaseInsensitive)
        self.navproxymodel.setSourceModel(self.navmodel)

        self.detailsmodel = QSqlQueryModel()
        self.detailsproxymodel = QSortFilterProxyModel()
        self.detailsproxymodel.setSourceModel(self.detailsmodel)

        self.navproxymodel.setDynamicSortFilter(True)
        self.detailsproxymodel.setDynamicSortFilter(True)

        self.mapper = QDataWidgetMapper(self)
        self.mapper.setModel(self.navproxymodel)

        self.user = user.LoggedUser

        self.editModel = None

        self.tableNavigation.setModel(self.navproxymodel)
        self.tableDetails.setModel(self.detailsproxymodel)

        self.tableDetails.setColumnHidden(IDCUENTA, True)
        self.tableDetails.setColumnHidden(IDDOCUMENTOC, True)

        self.actionCancelar.setVisible(False)
        self.actionGuardar.setVisible(False)

        #        self.actionGuardar.activated.connect( self.save )
        self.tableNavigation.selectionModel().selectionChanged[QItemSelection, QItemSelection].connect(
            self.updateDetails
        )

        QTimer.singleShot(0, self.updateModels)
Esempio n. 47
0
 def data(self, index, int_role=None):
     """
     Reimplementation of data method if is col 1 (street type)
     :param index: model index
     :param int_role: Display role/User role etc
     :return: Modified value with Type prefix
     """
     value = QSqlQueryModel.data(self, index, int_role)
     if value and int_role == Qt.DisplayRole:
         if index.column() == 1:
             value = "Type " + str(value)
     return value
Esempio n. 48
0
    def __init__(self, parent):
        '''
        Constructor
        '''
        super(DlgPais, self).__init__(parent)
        self.setupUi(self)

        self.table = ""
        self.backmodel = QSqlQueryModel()
        self.database = parent.database

        self.filtermodel = QSortFilterProxyModel(self)
        self.filtermodel.setSourceModel(self.backmodel)
        self.filtermodel.setDynamicSortFilter(True)
        self.filtermodel.setFilterKeyColumn(-1)
        self.filtermodel.setFilterCaseSensitivity(Qt.CaseInsensitive)

        #        self.tableview.setModel(self.filtermodel)

        self.setReadOnly(True)
        QTimer.singleShot(0, self.updateModels)
Esempio n. 49
0
    def __init__( self , sesion, parent ):
        '''
        Constructor
        @param sesion: Los datos de la sesión actual de caja
        @param parent: La ventana padre del formulario
        @type sesion: DatosSesion
        '''
        super( FrmPago, self ).__init__( parent, True )
        self.setWindowModality( Qt.WindowModal )
        self.setWindowFlags( Qt.Dialog )
        self.sesion = sesion
        self.tabledetails = None


        self.editmodel = None

        self.groupcuentas.setVisible( False )

        self.actionSave.setVisible( False )
        self.actionCancel.setVisible( False )

#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#        El modelo principal
        self.navmodel = QSqlQueryModel( self )
#        El modelo que filtra a self.navmodel
        self.navproxymodel = QSortFilterProxyModel( self )
        self.navproxymodel.setSourceModel( self.navmodel )
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++        

#        Este es el modelo con los datos de la con los detalles
        self.detailsmodel = QSqlQueryModel( self )
#        Este es el filtro del modelo anterior
        self.detailsproxymodel = QSortFilterProxyModel( self )

        self.sbtotalc.setValue( 0 )
        self.sbtotald.setValue( 0 )

        self.conceptosModel = QSqlQueryModel()

        QTimer.singleShot( 0, self.loadModels )
Esempio n. 50
0
    def workcat_fill_table(self, workcat_id):
        """ Fill table @widget filtering query by @workcat_id """
        
        result_select = utils_giswater.getWidgetText(self.items_dialog.txt_name)
        if result_select != 'null':
            expr = " feature_id LIKE '%" + result_select + "%'"
            # Refresh model with selected filter
            self.controller.log_info(expr)            
            self.tbl_psm.model().setFilter(expr)
            self.tbl_psm.model().select()
            return
                
        # Define SQL
        sql = ("SELECT 'NODE' as feature_type, nodecat_id AS featurecat_id, node_id AS feature_id, code, name as state"
            " FROM " + self.schema_name + ".v_edit_node JOIN " + self.schema_name + ".value_state ON id = state"
            " WHERE workcat_id = '" + str(workcat_id) + "'"
            " UNION"
            " SELECT 'ARC', arccat_id, arc_id, code, name"
            " FROM " + self.schema_name + ".v_edit_arc JOIN " + self.schema_name + ".value_state ON id = state"
            " WHERE workcat_id = '" + str(workcat_id) + "'"
            " UNION"
            " SELECT 'ELEMENT', elementcat_id, element_id, code, name"
            " FROM " + self.schema_name + ".v_edit_element JOIN " + self.schema_name + ".value_state ON id = state"
            " WHERE workcat_id = '" + str(workcat_id) + "'"
            " UNION" 
            " SELECT 'CONNEC', connecat_id, connec_id, code, name"
            " FROM " + self.schema_name + ".v_edit_connec JOIN " + self.schema_name + ".value_state ON id = state"
            " WHERE workcat_id = '" + str(workcat_id) + "'")
        
        # Set model        
        self.model = QSqlQueryModel()     
        self.model.setQuery(sql)    

        # Check for errors
        if self.model.lastError().isValid():
            self.controller.show_warning(self.model.lastError().text())        
              
        # Attach model to table view
        self.tbl_psm.setModel(self.model)     
    def loading(self):
        save_path = 'database/'
        complete = os.path.join(save_path, "user")
        f = open(complete, "r")
        creator = f.read()
        f.close()

        print(creator)
        save_path = 'database/'
        comp = os.path.join(save_path, "user.sqlite")
        db = sqlite3.connect(comp)
        cur = db.cursor()
        f = unicode(
            cur.execute('SELECT Role FROM users where Username=(?)',
                        (creator, )).fetchone()[0])
        db.close()

        if (f == "Admin"):
            save_path = 'database/'
            complete = os.path.join(save_path, "user.sqlite")
            db = QSqlDatabase.addDatabase("QSQLITE")
            db.setDatabaseName(complete)
            db.open()
            View = QSqlQueryModel()
            View.setQuery("select * from Files", db)
            self.tableView = QtGui.QTableView()
            self.tableView.setModel(View)
            self.tableView.show()
        elif (f == 'User'):
            save_path = 'database/'
            save = os.path.join(save_path, "user.sqlite")
            db = sqlite3.connect(save)
            cur = db.cursor()
            f = """SELECT * FROM Files where File_creator=('%s')""" % (
                creator)  #This shit cost me a lot i will never forget

            complete = os.path.join(save_path, "user.sqlite")
            db = QSqlDatabase.addDatabase("QSQLITE")
            db.setDatabaseName(complete)
            db.open()
            View = QSqlQueryModel()
            View.setQuery(f, db)
            self.tableView = QtGui.QTableView()
            self.tableView.setModel(View)
            self.tableView.show()
 def write_content(self,
                   query_id,
                   header_id,
                   header_no_content_id,
                   columns_name_id,
                   include_footpaths=True,
                   include_subtitle=False):
     """
     format the content of the data coming from the db either in text or dialog format
     :param query_id: int reference to the query dictionary
     :param header_id: int reference to the header dictionary
     :param header_no_content_id: int reference to the header no content dictionary
     :param columns_name_id: int reference to the list of columns of the required table
     :param include_footpaths: bool value to include footpaths in type 3 streets query
     :param include_subtitle: bool indicates if the header has a subtitle
     :return: void
     """
     # build a query model object
     query_model = QSqlQueryModel()
     if not include_footpaths:
         filtered_query = self.queries[2].replace(
             "AND (lnkESU_STREET.Currency_flag = 0)",
             "AND (lnkESU_STREET.Currency_flag = 0) AND "
             "(tblStreet.Description not like '%Footpath%')")
         query_model.setQuery(filtered_query)
     else:
         query_model.setQuery(self.queries[query_id])
     while query_model.canFetchMore():
         query_model.fetchMore()
     parent_model_index = QModelIndex()
     # if the path is not specified sends data to function creating a list
     if self.file_path is None:
         assert isinstance(columns_name_id, object)
         items_list = self.content_to_screen(
             content_list=None,
             query_model=query_model,
             columns_name_id=columns_name_id,
             no_content_id=header_no_content_id)
         return items_list
Esempio n. 53
0
 def data(self, index, role=None):
     """get score table from view"""
     if role is None:
         role = Qt.DisplayRole
     if role == Qt.DisplayRole:
         unformatted = unicode(
             self.record(index.row()).value(index.column()).toString())
         if index.column() == 2:
             # we do not yet use this for listing remote games but if we do
             # this translation is needed for robot players
             names = [m18n(name) for name in unformatted.split('///')]
             return QVariant(', '.join(names))
         elif index.column() == 1:
             dateVal = datetime.datetime.strptime(unformatted,
                                                  '%Y-%m-%dT%H:%M:%S')
             return QVariant(dateVal.strftime('%c').decode('utf-8'))
     return QSqlQueryModel.data(self, index, role)
Esempio n. 54
0
    def fill_table_by_query(self, qtable, query):
        """
        :param qtable: QTableView to show
        :param query: query to set model
        """
        model = QSqlQueryModel()
        model.setQuery(query)
        qtable.setModel(model)
        qtable.show()

        # Check for errors
        if model.lastError().isValid():
            self.controller.show_warning(model.lastError().text())
Esempio n. 55
0
    def __init__( self ,tipopersona, parent ):
        '''
        Constructor
        '''
        super( dlgPersona, self ).__init__( parent )
        self.setupUi(self)

#        self.tableview.addActions( ( self.actionEdit, self.actionNew ) )
        self.idtipopersona = tipopersona
        self.table = ""
        self.backmodel = QSqlQueryModel()
        self.database = parent.database

        self.filtermodel = QSortFilterProxyModel( self )
        self.filtermodel.setSourceModel( self.backmodel )
        self.filtermodel.setDynamicSortFilter( True )
        self.filtermodel.setFilterKeyColumn( -1 )
        self.filtermodel.setFilterCaseSensitivity( Qt.CaseInsensitive )
        
        self.paisesModel = QSqlQueryModel()
        self.cbpais.setModel( self.paisesModel )
        self.cbpais.setCurrentIndex( -1 )
        self.cbpais.setFocus()
        self.cbpais.setModelColumn( 1 )
        self.paisescompleter = QCompleter()
        self.paisescompleter.setCaseSensitivity( Qt.CaseInsensitive )
        self.paisescompleter.setModel( self.paisesModel )
        self.paisescompleter.setCompletionColumn( 1 )
        self.cbpais.setCompleter( self.paisescompleter )      


        self.proveedoresModel = QSqlQueryModel()
        self.cbproveedor.setModel( self.proveedoresModel )
        self.cbproveedor.setCurrentIndex( -1 )
        self.cbproveedor.setFocus()
        self.cbproveedor.setModelColumn( 1 )
        self.proveedorcompleter = QCompleter()
        self.proveedorcompleter.setCaseSensitivity( Qt.CaseInsensitive )
        self.proveedorcompleter.setModel( self.proveedoresModel )
        self.proveedorcompleter.setCompletionColumn( 1 )
        self.cbproveedor.setCompleter( self.proveedorcompleter ) 


#        self.tableview.setModel(self.filtermodel)
        self.cbsexo.setCurrentIndex(-1)
        self.txtnombre.setFocus()
        self.setReadOnly(True)
        QTimer.singleShot( 0, self.updateModels )
Esempio n. 56
0
 def setQuery(self, str, db=None):
     if db == None:
         self.query = QSqlQuery(str)
     else:
         self.query = str
     QSqlQueryModel.setQuery(self, str)
     del self.data
     self.data = []
     self.rCount = QSqlQueryModel.rowCount(self)
     if self.rCount > 10000:
         self.rCount = 10000
     self.cCount = QSqlQueryModel.columnCount(self)
     for i in range(self.rCount):
         row = []
         for j in range(self.cCount):
             row.append(
                 QSqlQueryModel.data(self, QSqlQueryModel.index(self, i,
                                                                j)))
         self.data.append(row)
     self.clear()
     print self.rowCount(), self.columnCount()
Esempio n. 57
0
from PyQt4.QtSql import QSqlQueryModel, QSqlDatabase
from PyQt4.QtGui import QApplication, QListView, QTableView
import sys

app = QApplication(sys.argv)

db = QSqlDatabase.addDatabase("QMYSQL")
db.setHostName("localhost")
db.setDatabaseName("app")
db.setUserName("root")
db.setPassword("")
db.open()

projectModel = QSqlQueryModel()
projectModel.setQuery("select name from customers", db)

projectView = QTableView()
projectView.setModel(projectModel)

projectView.show()

model = projectView.model()
indexes = projectView.selectionModel().currentIndex().row()

app.exec_()
Esempio n. 58
0
class MainWin(QMainWindow):
    """ Esta ventana guarda las tabs """
    def __init__(self, netmanager, clipboard, parent=None):
        super(MainWin, self).__init__(parent)
        self.setWindowTitle("Eilat Browser " + netmanager.name)

        self.netmanager = netmanager
        self.clipboard = clipboard

        self.tab_widget = QTabWidget(self)
        self.tab_widget.tabBar().setMovable(True)
        self.setCentralWidget(self.tab_widget)
        self.tab_widget.setTabsClosable(True)

        database = QSqlDatabase("QPSQL")
        database.open("pguser", "pguser")

        query = QSqlQuery(
            "select concat(host, path) h, count(*) c from reply " +
            "where status between 200 and 399 " +
            "and is_bookmarkable(path) " +
            "and host not in (select host from filtro) " + "group by h " +
            "order by c desc", database)

        self.model = QSqlQueryModel()
        self.model.setQuery(query)

        self.tab_widget.tabCloseRequested.connect(self.del_tab)

        def new_tab_from_clipboard():
            """ One-use callback for QShortcut.
            Reads the content of the PRIMARY clipboard and navigates to it
            on a new tab.

            """
            url = unicode(self.clipboard.text(QClipboard.Selection)).strip()
            self.add_tab(url)

        set_shortcuts([("Ctrl+T", self, self.add_tab),
                       ("Y", self, new_tab_from_clipboard),
                       ("Ctrl+W", self, self.del_tab),
                       ("N", self, partial(self.inc_tab, -1)),
                       ("Ctrl+PgUp", self, partial(self.inc_tab, -1)),
                       ("M", self, self.inc_tab),
                       ("Ctrl+PgDown", self, self.inc_tab),
                       ("Ctrl+Q", self, QApplication.closeAllWindows)])

    # aux. action (en register_actions)
    def inc_tab(self, incby=1):
        """ Takes the current tab index, modifies wrapping around,
        and sets as current.

        Afterwards the active tab has focus on its webkit area.

        """
        if self.tab_widget.count() < 2:
            return
        idx = self.tab_widget.currentIndex()
        idx += incby
        if idx < 0:
            idx = self.tab_widget.count() - 1
        elif idx >= self.tab_widget.count():
            idx = 0
        self.tab_widget.setCurrentIndex(idx)
        self.tab_widget.currentWidget().webkit.setFocus()

    # action y connect en llamada en constructor
    def del_tab(self, idx=None):
        """ Closes a tab. If 'idx' is set, it was called by a
        tabCloseRequested signal. If not, it was called by a keyboard
        action and closes the currently active tab.

        Afterwards the active tab has focus on its webkit area.

        It closes the window when deleting the last active tab.

        """
        if idx is None:
            idx = self.tab_widget.currentIndex()
        self.tab_widget.widget(idx).webkit.stop()
        self.tab_widget.widget(idx).deleteLater()
        self.tab_widget.removeTab(idx)
        if len(self.tab_widget) == 0:
            self.close()
        else:
            self.tab_widget.currentWidget().webkit.setFocus()

    # action (en register_actions)
    # externo en eilat.py, crea la primera tab
    def add_tab(self, url=None):
        """ Creates a new tab, either empty or navegating to the url.
        Sets itself as the active tab.

        If navegating to an url it gives focus to the webkit area. Otherwise,
        the address bar is focused.

        """
        tab = WebTab(browser=self, parent=self.tab_widget)

        self.tab_widget.addTab(tab, "New tab")
        self.tab_widget.setCurrentWidget(tab)
        if url:
            tab.navigate(url)
        else:
            tab.address_bar.setFocus()
Esempio n. 59
0
    def loading(self):
        save_path='database/'
        complete = os.path.join(save_path,"user")
        f=open(complete,"r")
        creator=f.read()
        f.close()
        ############so finally i came up with something###########
        #TOPSECRET=4
        #SECRET=3
        #CONFIDENTIAL=2
        #UNCLASSIFIED=1
        ############never under estimate your opponent###############

        print(creator)
        save_path='database/'
        comp = os.path.join(save_path,"user.sqlite")
        db = sqlite3.connect(comp)
        cur= db.cursor()
        f=unicode(cur.execute('SELECT Role FROM users where Username=(?)',(creator,)).fetchone()[0])
        cl=unicode(cur.execute('SELECT Clearance  FROM users where Username=(?)',(creator,)).fetchone()[0])
        allow=unicode(cur.execute('SELECT access_auth FROM users where Username=(?)',(creator,)).fetchone()[0])
        db.close()
        if(f=="Admin"):
            save_path='database/'
            complete = os.path.join(save_path,"user.sqlite")
            db = QSqlDatabase.addDatabase("QSQLITE")
            db.setDatabaseName(complete)
            db.open()
            View = QSqlQueryModel()
            View.setQuery("select * from Files",db)
            self.tableView = QtGui.QTableView()
            self.tableView.setModel(View)
            self.tableView.show()
        elif(f=='User'):
            if(allow=="Yes"):
                if(cl =="TOPSECRET"):
                    save_path='database/'
                    save = os.path.join(save_path,"user.sqlite")
                    db = sqlite3.connect(save)
                    cur= db.cursor()

                    complete = os.path.join(save_path,"user.sqlite")
                    db = QSqlDatabase.addDatabase("QSQLITE")
                    db.setDatabaseName(complete)
                    db.open()
                    View = QSqlQueryModel()
                    View.setQuery("SELECT * FROM files where Clearance in('TOPSECRET','SECRET','CONFIDENTIAL','UNCLASSIFIED')",db)
                    self.tableView = QtGui.QTableView()
                    self.tableView.setModel(View)
                    self.tableView.show()
                elif(cl =="SECRET"):
                    save_path='database/'
                    save = os.path.join(save_path,"user.sqlite")
                    db = sqlite3.connect(save)
                    cur= db.cursor()

                    complete = os.path.join(save_path,"user.sqlite")
                    db = QSqlDatabase.addDatabase("QSQLITE")
                    db.setDatabaseName(complete)
                    db.open()
                    View = QSqlQueryModel()
                    View.setQuery("SELECT * FROM files where Clearance in('SECRET','CONFIDENTIAL','UNCLASSIFIED')",db)
                    self.tableView = QtGui.QTableView()
                    self.tableView.setModel(View)
                    self.tableView.show()
                elif(cl =="CONFIDENTIAL"):
                    save_path='database/'
                    save = os.path.join(save_path,"user.sqlite")
                    db = sqlite3.connect(save)
                    cur= db.cursor()

                    complete = os.path.join(save_path,"user.sqlite")
                    db = QSqlDatabase.addDatabase("QSQLITE")
                    db.setDatabaseName(complete)
                    db.open()
                    View = QSqlQueryModel()
                    View.setQuery("SELECT * FROM files where Clearance in('CONFIDENTIAL','UNCLASSIFIED')",db)
                    self.tableView = QtGui.QTableView()
                    self.tableView.setModel(View)
                    self.tableView.show()
                elif(cl =="UNCLASSIFIED"):
                    save_path='database/'
                    save = os.path.join(save_path,"user.sqlite")
                    db = sqlite3.connect(save)
                    cur= db.cursor()

                    complete = os.path.join(save_path,"user.sqlite")
                    db = QSqlDatabase.addDatabase("QSQLITE")
                    db.setDatabaseName(complete)
                    db.open()
                    View = QSqlQueryModel()
                    View.setQuery("SELECT * FROM files where Clearance in('UNCLASSIFIED')",db)
                    self.tableView = QtGui.QTableView()
                    self.tableView.setModel(View)
                    self.tableView.show()