Ejemplo n.º 1
0
class NewTaskDialog(QDialog):

    def __init__(self, parent=None):
        super(NewTaskDialog, self).__init__(parent)
        # task name
        nameLabel = QLabel(self.tr("Name:"))
        self.name = QLineEdit()
        nameLabel.setBuddy(self.name)
        # priority
        priorityLabel = QLabel(self.tr("Priority:"))
        self.priority = QComboBox()
        priorityLabel.setBuddy(self.priority)

        dateLabel = QLabel(self.tr("Deadline:"))
        self.deadline = QDateEdit()
        dateLabel.setBuddy(self.deadline)

        self.deadline.setCalendarPopup(True)
        self.deadline.calendarWidget().setFirstDayOfWeek(Qt.Monday)
        self.deadline.setDate(QDate(date.today()))

        createButton = QPushButton(self.tr("Save"))
        cancelButton = QPushButton(self.tr("Cancel"))

        buttonLayout = QHBoxLayout()
        buttonLayout.addStretch()
        buttonLayout.addWidget(createButton)
        buttonLayout.addWidget(cancelButton)

        layout = QGridLayout()
        layout.addWidget(nameLabel, 0, 0)
        layout.addWidget(self.name, 0, 1)

        layout.addWidget(priorityLabel, 1, 0)
        layout.addWidget(self.priority, 1, 1)

        layout.addWidget(dateLabel, 2, 0)
        layout.addWidget(self.deadline, 2, 1)
        layout.addLayout(buttonLayout, 3, 0, 3, 2)
        self.setLayout(layout)

        self.connect(self.deadline, SIGNAL("dateChanged(const QDate&)"), self, SLOT("changed()"))
        self.connect(createButton, SIGNAL("clicked()"), self, SLOT("accept()"))
        self.connect(cancelButton, SIGNAL("clicked()"), self, SLOT("reject()"))
        self.setWindowTitle(self.tr("Task"))
        self.resize(350, 120)
        self.setMinimumSize(QSize(250, 120))
        self.setMaximumSize(QSize(450, 120))


    @pyqtSlot()
    def changed(self):
        print(self.deadline.text())
Ejemplo n.º 2
0
    def _create_widget(cls, c, parent, host=None):
        dt = QDateEdit(parent)
        dt.setObjectName(u'{0}_{1}'.format(cls._TYPE_PREFIX, c.name))
        dt.setCalendarPopup(True)

        # Set ranges
        if c.min_use_current_date:
            dt.setMinimumDate(date.today())
        else:
            dt.setMinimumDate(c.minimum)

        if c.max_use_current_date:
            dt.setMaximumDate(date.today())
        else:
            dt.setMaximumDate(c.maximum)

        # Set maximum date as current date
        dt.setDate(date.today())

        return dt
class DlgMagneticVariationParameters(QDialog):
    def __init__(self, parent = None):
        QDialog.__init__(self, parent)
        
        self.resize(290, 136);
        self.setWindowTitle("Reference Positions")
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed);
        sizePolicy.setHorizontalStretch(0);
        sizePolicy.setVerticalStretch(0);
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth());
        self.setSizePolicy(sizePolicy);
        verticalLayoutDlg = QVBoxLayout(self)
        verticalLayoutDlg.setObjectName(("verticalLayoutDlg"));
        frameDate = QFrame(self);
        frameDate.setObjectName(("frameDate"));
        frameDate.setFrameShape(QFrame.StyledPanel);
        frameDate.setFrameShadow(QFrame.Raised);
        horizontalLayoutDate = QHBoxLayout(frameDate);
        horizontalLayoutDate.setObjectName(("horizontalLayoutDate"));
        labelDate = QLabel(frameDate);
        labelDate.setObjectName(("labelDate"));
        labelDate.setMinimumSize(QSize(70, 0));
        labelDate.setMaximumSize(QSize(70, 16777215));
        labelDate.setText("Date:")

        horizontalLayoutDate.addWidget(labelDate);

        self.dtpDate = QDateEdit(frameDate);
        self.dtpDate.setObjectName(("dtpDate"));

        horizontalLayoutDate.addWidget(self.dtpDate);

        self.btnDtpDate =  QToolButton(frameDate);
        self.btnDtpDate.setObjectName(("btnDtpDate"));
        sizePolicy.setHeightForWidth(self.btnDtpDate.sizePolicy().hasHeightForWidth());
        self.btnDtpDate.setSizePolicy(sizePolicy);
        self.btnDtpDate.setMinimumSize(QSize(25, 0));
        self.btnDtpDate.setMaximumSize(QSize(25, 16777215));
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/calender.png")), QIcon.Normal, QIcon.Off)
        self.btnDtpDate.setIcon(icon)

        horizontalLayoutDate.addWidget(self.btnDtpDate);


        verticalLayoutDlg.addWidget(frameDate);

        frameModel = QFrame(self);
        frameModel.setObjectName(("frameModel"));
        frameModel.setFrameShape(QFrame.StyledPanel);
        frameModel.setFrameShadow(QFrame.Raised);
        horizontalLayoutModel = QHBoxLayout(frameModel);
        horizontalLayoutModel.setObjectName(("horizontalLayoutModel"));
        labelModel = QLabel(frameModel);
        labelModel.setObjectName(("labelModel"));
        labelModel.setMinimumSize(QSize(70, 0));
        labelModel.setMaximumSize(QSize(70, 16777215));
        labelModel.setText("Model:")

        horizontalLayoutModel.addWidget(labelModel);

        self.cmbModel = QComboBox(frameModel);
        self.cmbModel.setObjectName(("cmbModel"));

        horizontalLayoutModel.addWidget(self.cmbModel);


        verticalLayoutDlg.addWidget(frameModel);

        self.buttonBox = QDialogButtonBox(self);
        self.buttonBox.setObjectName(("buttonBox"));
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok);
        self.connect(self.buttonBox, SIGNAL("accepted()"), self.accept)
        self.connect(self.buttonBox, SIGNAL("rejected()"), self.reject)


        verticalLayoutDlg.addWidget(self.buttonBox);

        self.calendar = QCalendarWidget()
        self.calendar.clicked.connect(self.calendar_clicked)
        self.menu = QMenu()
        layout = QVBoxLayout(self.menu)
        layout.addWidget(self.calendar)

        self.btnDtpDate.clicked.connect(self.btnDtpDate_clicked)
        self.cmbModel.addItems(["WMM2015", "WMM2010" , "WMM2005", "WMM2000", "WMM95", "WMM90", "WMM85", "IGRF2000", "IGRF95", "IGRF90"])

    def btnDtpDate_clicked(self):
        rcRect = self.btnDtpDate.geometry()
        ptPoint = rcRect.bottomLeft()

        self.menu.exec_( self.mapToGlobal(ptPoint) )

    def calendar_clicked(self, date):
        self.dtpDate.setDate(date)

    def get_Date(self):
        return self.dtpDate.date()
    def setDate(self, date):
        if date != None:
            self.dtpDate.setDate(date)
    Date = property(get_Date, setDate, None, None)

    def get_Model(self):
        return self.cmbModel.currentIndex()
    def set_Model(self, index):
        if index == None:
            self.cmbModel.setCurrentIndex(1)
            return
        self.cmbModel.setCurrentIndex(index)
    Model = property(get_Model, set_Model, None, None)

    @staticmethod
    def smethod_0(date_0, magneticModelIndex_0):

        dlgMagneticVariationParameters = DlgMagneticVariationParameters()
        dlgMagneticVariationParameters.Date = date_0
        dlgMagneticVariationParameters.Model = magneticModelIndex_0
        dialogResult = dlgMagneticVariationParameters.exec_()
        if dialogResult != QDialog.Accepted:
            return (False, None, None)
        else:
            date  = dlgMagneticVariationParameters.Date;
            magneticIndex = dlgMagneticVariationParameters.Model;
            return (True, date, magneticIndex)
Ejemplo n.º 4
0
class LDSControls(QFrame):
        
    STATIC_IMG = ('error_static.png','linz_static.png','busy_static.png','clean_static.png')
    ANIM_IMG   = ('error.gif','linz.gif','layer.gif','clean.gif')
    
    IMG_SPEED  = 100
    IMG_WIDTH  = 64
    IMG_HEIGHT = 64
    
    MAX_WD = 450
    
    GD_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../../bin/gdal/gdal-data'))
    STATUS = LU.enum('ERROR','IDLE','BUSY','CLEAN')
    
    def __init__(self,parent):
        super(LDSControls, self).__init__()
        self.parent = parent
        self.initConf()
        self.initEPSG()
        self.initUI()
        
    def initConf(self):
        '''Read files in conf dir ending in conf'''
        self.cflist = ConfigInitialiser.getConfFiles()
        #self.imgset = self.STATIC_IMG if ConfigWrapper().readDSProperty('Misc','indicator')=='static' else self.ANIM_IMG
        #self.imgset = self.STATIC_IMG if self.parent.confconn.tp.src.confwrap.readDSProperty('Misc','indicator')=='static' else self.ANIM_IMG
        sep = self.parent.confconn.reg.openEndPoint(self.parent.confconn.SRCNAME,self.parent.confconn.uconf)
        self.imgset = self.STATIC_IMG if sep.confwrap.readDSProperty('Misc','indicator')=='static' else self.ANIM_IMG
        self.parent.confconn.reg.closeEndPoint(self.parent.confconn.SRCNAME)
        
    def initEPSG(self):
        '''Read GDAL EPSG files, splitting by NZ(RSR) and RestOfTheWorld'''

        gcsf = gdal.FindFile('gdal','gcs.csv') 
        if not gcsf:
            gcsf = os.path.join(self.GD_PATH,'gcs.csv')
        pcsf = gdal.FindFile('gdal','pcs.csv') 
        if not pcsf: 
            pcsf = os.path.join(self.GD_PATH,'pcs.csv')
        gcs = ConfigInitialiser.readCSV(gcsf)
        pcs = ConfigInitialiser.readCSV(pcsf)

        self.nzlsr = [(e[0],e[0]+' - '+e[3]) for e in gcs if 'NZGD'     in e[1] or  'RSRGD'     in e[1]] \
                   + [(e[0],e[0]+' - '+e[1]) for e in pcs if 'NZGD'     in e[1] or  'RSRGD'     in e[1]]
        self.rowsr = [(e[0],e[0]+' - '+e[3]) for e in gcs if 'NZGD' not in e[1] and 'RSRGD' not in e[1]] \
                   + [(e[0],e[0]+' - '+e[1]) for e in pcs if 'NZGD' not in e[1] and 'RSRGD' not in e[1]]
                   
                   
    def initUI(self):
        
        # 0      1          2       3       4       5      6    7    8
        #'destname','lgselect','layer','uconf','group','epsg','fd','td','int'
        
        #self.rdest,rlgselect,self.rlayer,ruconf,self.rgroup,repsg,rfd,rtd,rint = readlist 
        
        QToolTip.setFont(QFont('SansSerif', 10))
        
        #labels
        destLabel = QLabel('Destination')
        lgLabel = QLabel('Group/Layer')
        epsgLabel = QLabel('EPSG')
        fromDateLabel = QLabel('From Date')
        toDateLabel = QLabel('To Date')
        confLabel = QLabel('User Config')
        
        self.view = QLabel() 
        self.view.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.view.setAlignment(Qt.AlignCenter)

        self.confcombo = QComboBox(self)
        self.confcombo.setToolTip('Enter your user config name (file) here')
        self.confcombo.addItems(self.cflist)
        self.confcombo.setEditable(False)
        #self.confcombo.currentIndexChanged.connect(self.doLGEditUpdate)
        
        #combos
        self.lgcombo = QComboBox(self)
        self.lgcombo.setMaximumWidth(self.MAX_WD)
        self.lgcombo.setDuplicatesEnabled(False)
        #self.lgcombo.setInsertPolicy(QComboBox.InsertAlphabetically)#?doesnt seem to work
        self.lgcombo.setToolTip('Select either Layer or Group entry')
        self.lgcombo.setEditable(False)
        self.sepindex = None
        #self.updateLGValues()
        
        self.epsgcombo = QComboBox(self)
        self.epsgcombo.setMaximumWidth(self.MAX_WD)
        self.epsgcombo.setToolTip('Setting an EPSG number here determines the output SR of the layer')  
        self.epsgcombo.addItems([i[1] for i in self.nzlsr])
        self.epsgcombo.insertSeparator(len(self.nzlsr))
        self.epsgcombo.addItems([i[1] for i in self.rowsr])
        self.epsgcombo.setEditable(True)
        self.epsgcombo.setEnabled(False)
        
        self.destlist = self.getConfiguredDestinations()
        self.destcombo = QComboBox(self)
        self.destcombo.setToolTip('Choose the desired output type')   
        self.destcombo.setEditable(False)
        self.destcombo.addItems(self.destlist)

        #date selection
        self.fromdateedit = QDateEdit()
        self.fromdateedit.setCalendarPopup(True)
        self.fromdateedit.setEnabled(False)
        
        self.todateedit = QDateEdit()
        self.todateedit.setCalendarPopup(True)
        self.todateedit.setEnabled(False)
        
        #check boxes
        self.epsgenable = QCheckBox()
        self.epsgenable.setCheckState(False)
        self.epsgenable.clicked.connect(self.doEPSGEnable)       
        
        self.fromdateenable = QCheckBox()
        self.fromdateenable.setCheckState(False)
        self.fromdateenable.clicked.connect(self.doFromDateEnable)
        
        self.todateenable = QCheckBox()
        self.todateenable.setCheckState(False) 
        self.todateenable.clicked.connect(self.doToDateEnable)
        
        self.progressbar = QProgressBar()
        self.progressbar.setRange(0,100)
        self.progressbar.setVisible(True)
        self.progressbar.setMinimumWidth(self.MAX_WD)
        
        
        #buttons        
        self.initbutton = QPushButton("waiting")
        self.initbutton.setToolTip('Initialise the Layer Configuration')
        self.initbutton.clicked.connect(self.doInitClickAction)
        
        self.cleanbutton = QPushButton("Clean")
        self.cleanbutton.setToolTip('Clean the selected layer/group from local storage')
        self.cleanbutton.clicked.connect(self.doCleanClickAction)
        
        self.replicatebutton = QPushButton("Replicate")
        self.replicatebutton.setToolTip('Execute selected replication')
        self.replicatebutton.clicked.connect(self.doReplicateClickAction)
        
        self.cancelbutton = QPushButton("Close")
        self.cancelbutton.setToolTip('Close the LDS Replicate application')       
        self.cancelbutton.clicked.connect(self.parent.close)


        #set dialog values using GPR
        self.updateGUIValues(self.parent.gvs)
        
        #set onchange here otherwise we get circular initialisation
        self.destcombo.currentIndexChanged.connect(self.doDestChanged)
        self.confcombo.currentIndexChanged.connect(self.doConfChanged)
        self.lgcombo.currentIndexChanged.connect(self.doLGComboChanged)

        self.setStatus(self.STATUS.IDLE)
        
        #grid
        grid = QGridLayout()
        grid.setSpacing(10)
        
        
        #placement section ------------------------------------
        #---------+---------+--------+---------+--------
        # dest LB |         | dest DD
        # grp LB  |         | grp DD
        # conf LB |         | conf DD
        # epsg L  | epsg CB | epsg DD
        # f dt L  | f dt CB | f dt DD
        # t td L  | t td CB | t td DD
        # icon    |       <- progress ->
        # layer B | <- . -> |repl B  | clean B | close B 
        #---------+---------+--------+---------+--------

        grid.addWidget(destLabel, 1, 0)
        grid.addWidget(self.destcombo, 1, 2)

        #grid.addWidget(layerLabel, 2, 0)
        grid.addWidget(lgLabel, 2, 0)
        grid.addWidget(self.lgcombo, 2, 2)
        
        grid.addWidget(confLabel, 3, 0)
        grid.addWidget(self.confcombo, 3, 2)
        
        #grid.addWidget(groupLabel, 4, 0)
        #grid.addWidget(self.groupEdit, 4, 2)
        
        grid.addWidget(epsgLabel, 5, 0)
        grid.addWidget(self.epsgenable, 5, 1)
        grid.addWidget(self.epsgcombo, 5, 2)

        grid.addWidget(fromDateLabel, 6, 0)
        grid.addWidget(self.fromdateenable, 6, 1)
        grid.addWidget(self.fromdateedit, 6, 2)
        
        grid.addWidget(toDateLabel, 7, 0)
        grid.addWidget(self.todateenable, 7, 1)
        grid.addWidget(self.todateedit, 7, 2)
        
        hbox3 = QHBoxLayout()
        hbox3.addWidget(self.view) 
        hbox3.addStretch(1)
        hbox3.addWidget(self.progressbar)

        #hbox3.addLayout(vbox2)
        #hbox3.addLayout(vbox3)
        
        hbox4 = QHBoxLayout()
        hbox4.addWidget(self.initbutton)
        hbox4.addStretch(1)
        hbox4.addWidget(self.replicatebutton)
        hbox4.addWidget(self.cleanbutton)
        hbox4.addWidget(self.cancelbutton)
        

        vbox = QVBoxLayout()
        #vbox.addStretch(1)
        vbox.addLayout(grid)
        vbox.addLayout(hbox3)
        vbox.addLayout(hbox4)
        
        self.setLayout(vbox)  
       
    #def setProgress(self,pct):
    #    self.progressbar.setValue(pct)
        
    def setStatus(self,status,message='',tooltip=None):
        '''Sets indicator icon and statusbar message'''
        self.parent.statusbar.showMessage(message)
        self.parent.statusbar.setToolTip(tooltip if tooltip else '')

        #progress
        loc = os.path.abspath(os.path.join(IMG_LOC,self.imgset[status]))
        #loc = os.path.abspath(os.path.join(os.path.dirname(__file__),self.parent.IMG_LOC,self.imgset[status]))
        self.progressbar.setVisible(status in (self.STATUS.BUSY, self.STATUS.CLEAN))
        
        #icon
        anim = QMovie(loc, QByteArray(), self)
        anim.setScaledSize(QSize(self.IMG_WIDTH,self.IMG_HEIGHT))
        anim.setCacheMode(QMovie.CacheAll)
        anim.setSpeed(self.IMG_SPEED)
        self.view.clear()
        self.view.setMovie(anim)
        anim.start()

        self.view.repaint()
        QApplication.processEvents(QEventLoop.AllEvents)

    def mainWindowEnable(self,enable=True):
        cons = (self.lgcombo, self.confcombo, self.destcombo, 
                self.initbutton, self.replicatebutton, self.cleanbutton, self.cancelbutton,
                self.epsgenable,self.fromdateenable,self.todateenable,
                self.parent.menubar)
        for c in cons:
            c.setEnabled(enable)
            
        if enable:
            self.epsgcombo.setEnabled(self.epsgenable.checkState())
            self.fromdateedit.setEnabled(self.fromdateenable.checkState())
            self.todateedit.setEnabled(self.todateenable.checkState())
        else:
            self.epsgcombo.setEnabled(False)
            self.fromdateedit.setEnabled(False)
            self.todateedit.setEnabled(False)
   
        QApplication.restoreOverrideCursor() if enable else QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) 

    def refreshLGCombo(self):
        '''Re index LG combobox since a refreshLG call (new dest?) will usually mean new groups'''
        self.lgcombo.clear()
        self.lgcombo.addItems([i[2] for i in self.parent.confconn.lglist])
        #NOTE the separator consumes an index, if not clearing the combobox selectively remove the old sepindex (assumes g preceeds l)
        #if self.sepindex:
        #    self.lgcombo.removeItem(self.sepindex)
        self.sepindex = [i[0] for i in self.parent.confconn.lglist].count(LORG.GROUP)
        self.lgcombo.insertSeparator(self.sepindex)
        
    def updateLGValues(self,uconf,lgval,dest):
        '''Sets the values displayed in the Layer/Group combo'''
        #because we cant seem to sort combobox entries and want groups at the top, clear and re-add
        #TRACE#        
        #pdb.set_trace()
        sf = None
        try:
            self.parent.confconn.initConnections(uconf,lgval,dest)
        except Exception as e:
            sf=1
            ldslog.error('Error Updating UC Values. '+str(e))
            
        if sf:
            self.setStatus(self.STATUS.ERROR,'Error Updating UC Values', str(e))
        else:
            self.setStatus(self.STATUS.IDLE)
            
        self.refreshLGCombo()
        
    def centre(self):
        
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
        
    
    def gprParameters(self,rdest):
        '''Zip default and GPR values'''
        return [x if LU.assessNone(x) else y for x,y in zip(self.parent.gpr.readsec(rdest),self.parent.DEF_RVALS[1:])]
    
    def getLCE(self,ln):
        '''Read layer parameters'''
        dep = self.parent.confconn.reg.openEndPoint(self.parent.confconn.destname,self.parent.confconn.uconf)
        #sep = self.parent.confconn.reg.openEndPoint('WFS',self.parent.confconn.uconf)
        self.parent.confconn.reg.setupLayerConfig(self.parent.confconn.tp,None,dep,initlc=False)
        lce = dep.getLayerConf().readLayerParameters(ln)
        #self.parent.confconn.reg.closeEndPoint('WFS')
        self.parent.confconn.reg.closeEndPoint(self.parent.confconn.destname)
        sep,dep = None,None
        return lce
    
    
    def doDestChanged(self):
        '''Read the destname parameter and fill dialog with matching GPR values'''
        rdest = str(self.destlist[self.destcombo.currentIndex()])
        rvals = self.gprParameters(rdest)
        self.updateGUIValues([rdest]+rvals)    
        
        
    def doConfChanged(self):
        '''Read the user conf parameter and fill dialog with matching GPR values'''
        rdest = str(self.destlist[self.destcombo.currentIndex()])
        rlg,_,rep,rfd,rtd = self.gprParameters(rdest)
        ruc = str(self.cflist[self.confcombo.currentIndex()])
        self.updateGUIValues((rdest,rlg,ruc,rep,rfd,rtd))
        
        
    def doLGComboChanged(self):
        '''Read the layer/group value and change epsg to layer or gpr match'''
        #get a matching LG entry and test whether its a layer or group
        #lgi = self.parent.confconn.getLayerGroupIndex(self.lgcombo.currentText().toUtf8().data())
        lgi = self.parent.confconn.getLayerGroupIndex(LQ.readWidgetText(self.lgcombo.currentText()))
        #lgi can be none if we init a new group, in which case we use the GPR value
        if lgi:
            lge = self.parent.confconn.lglist[lgi]
            lce = self.getLCE(lge[1]) if lge[0]==LORG.LAYER else None
        else:
            lce = None
        
        #look for filled layer conf epsg OR use prefs stored in gpr
        if lce and LU.assessNone(lce.epsg):
            epsgval = lce.epsg
        else:
            rdest = str(self.destlist[self.destcombo.currentIndex()])
            _,_,epsgval,_,_ = self.gprParameters(rdest)
        epsgindex = [i[0] for i in self.nzlsr+[(0,0)]+self.rowsr].index(epsgval)
        if self.epsgcombo.currentIndex() != epsgindex:
            self.epsgcombo.setCurrentIndex(int(epsgindex))

        
    def updateGUIValues(self,readlist):
        '''Fill dialog values from provided list'''
        #TODO. Remove circular references when setCurrentIndex() triggers do###Changed()
        #Read user input
        rdest,self.rlgval,ruconf,repsg,rfd,rtd = readlist
        
        #--------------------------------------------------------------------
        
        #Destination Menu
        selecteddest = LU.standardiseDriverNames(rdest)
        if selecteddest not in self.destlist:
            self.destlist = self.getConfiguredDestinations()
            self.destcombo.addItem(selecteddest)
        destindex = self.destlist.index(selecteddest) if selecteddest else 0
        
        if self.destcombo.currentIndex() != destindex:
            self.destcombo.setCurrentIndex(destindex)
        
        #InitButton
        self.initbutton.setText('Layer Select')
        
        #Config File
        confindex = 0
        if LU.assessNone(ruconf):
            ruconf = ruconf.split('.')[0]
            if ruconf not in self.cflist:
                self.cflist += [ruconf,]
                self.confcombo.addItem(ruconf)
            confindex = self.cflist.index(ruconf)
            
        if self.confcombo.currentIndex() != confindex:
            self.confcombo.setCurrentIndex(confindex)
        #self.confEdit.setText(ruconf if LU.assessNone(ruconf) else '')
        
        #Layer/Group Selection
        self.updateLGValues(ruconf,self.rlgval,rdest)
        lgindex = None
        if LU.assessNone(self.rlgval):
            #index of list value
            lgindex = self.parent.confconn.getLayerGroupIndex(self.rlgval,col=1)
            
        if LU.assessNone(lgindex):
            #advance by 1 for sep
            lgindex += 1 if lgindex>self.sepindex else 0 
        else:
            #using the separator index sets the combo to blank
            lgindex = self.sepindex
        if self.lgcombo.currentIndex() != lgindex:
            self.lgcombo.setCurrentIndex(lgindex)
        #self.doLGEditUpdate()
        
        #EPSG
        #                                user > layerconf
        #useepsg = LU.precedence(repsg, lce.epsg if lce else None, None)
        epsgindex = [i[0] for i in self.nzlsr+[(None,None)]+self.rowsr].index(repsg)
        if self.epsgcombo.currentIndex() != epsgindex:
            self.epsgcombo.setCurrentIndex(epsgindex)
            
        #epsgedit = self.epsgcombo.lineEdit()
        #epsgedit.setText([e[1] for e in self.nzlsr+self.rowsr if e[0]==repsg][0])
        
        #epsgedit.setText([e for e in self.nzlsr+self.rowsr if re.match('^\s*(\d+).*',e).group(1)==repsg][0])
        
        #To/From Dates
        if LU.assessNone(rfd):
            self.fromdateedit.setDate(QDate(int(rfd[0:4]),int(rfd[5:7]),int(rfd[8:10])))
        else:
            early = DataStore.EARLIEST_INIT_DATE
            self.fromdateedit.setDate(QDate(int(early[0:4]),int(early[5:7]),int(early[8:10])))
            
        if LU.assessNone(rtd):
            self.todateedit.setDate(QDate(int(rtd[0:4]),int(rtd[5:7]),int(rtd[8:10]))) 
        else:
            today = DataStore.getCurrent()
            self.todateedit.setDate(QDate(int(today[0:4]),int(today[5:7]),int(today[8:10])))
            
        #Internal/External CheckBox
#        if LU.assessNone(rint):
#            self.internalTrigger.setChecked(rint.lower()==DataStore.CONF_INT)
#        else:
#            self.internalTrigger.setChecked(DataStore.DEFAULT_CONF==DataStore.CONF_INT)
        
        
    def getConfiguredDestinations(self):
        defml = ['',]+DataStore.DRIVER_NAMES.values()
        return [d for d in self.parent.gpr.getDestinations() if d in defml]
        
    def doEPSGEnable(self):
        self.epsgcombo.setEnabled(self.epsgenable.isChecked())
        
    def doFromDateEnable(self):
        self.fromdateedit.setEnabled(self.fromdateenable.isChecked())
          
    def doToDateEnable(self):
        self.todateedit.setEnabled(self.todateenable.isChecked())  
          
    def readParameters(self):
        '''Read values out of dialogs'''
        destination = LU.assessNone(str(self.destlist[self.destcombo.currentIndex()]))
        #lgindex = self.parent.confconn.getLayerGroupIndex(self.lgcombo.currentText().toUtf8().data())
        lgindex = self.parent.confconn.getLayerGroupIndex(LQ.readWidgetText(self.lgcombo.currentText()))
        #NB need to test for None explicitly since zero is a valid index
        lgval = self.parent.confconn.lglist[lgindex][1] if LU.assessNone(lgindex) else None       
        #uconf = LU.standardiseUserConfigName(str(self.confcombo.lineEdit().text()))
        #uconf = str(self.confcombo.lineEdit().text())
        uconf = str(self.cflist[self.confcombo.currentIndex()])
        ee = self.epsgenable.isChecked()
        epsg = None if ee is False else re.match('^\s*(\d+).*',str(self.epsgcombo.lineEdit().text())).group(1)
        fe = self.fromdateenable.isChecked()
        te = self.todateenable.isChecked()
        fd = None if fe is False else str(self.fromdateedit.date().toString('yyyy-MM-dd'))
        td = None if te is False else str(self.todateedit.date().toString('yyyy-MM-dd'))
        
        return destination,lgval,uconf,epsg,fe,te,fd,td
    
    def doInitClickAction(self):
        '''Initialise the LC on LC-button-click, action'''
        try:
            try:
                self.setStatus(self.STATUS.BUSY,'Opening Layer-Config Editor')  
                self.progressbar.setValue(0)
                self.parent.runLayerConfigAction()
            finally:
                self.setStatus(self.STATUS.IDLE,'Ready')
        except Exception as e:
            self.setStatus(self.STATUS.ERROR,'Error in Layer-Config',str(sys.exc_info()))#e))
        
    def doCleanClickAction(self):
        '''Set clean anim and run clean'''
        #lgo = self.lgcombo.currentText().toUtf8().data()
        lgo = LQ.readWidgetText(self.lgcombo.currentText())
        
        try:
            self.setStatus(self.STATUS.CLEAN,'Running Clean '+lgo)
            self.progressbar.setValue(0)
            self.runReplicationScript(True)
        except Exception as e:
            self.setStatus(self.STATUS.ERROR,'Failed Clean of '+lgo,str(sys.exc_info()))#e))
        
    def doReplicateClickAction(self):
        '''Set busy anim and run repl'''
        lgo = self.lgcombo.currentText()#.toUtf8().data()#only used for error messages
        try:
            self.setStatus(self.STATUS.BUSY,'Running Replicate '+lgo)
            self.progressbar.setValue(0)
            self.runReplicationScript(False)
        except Exception as e:
            self.setStatus(self.STATUS.ERROR,'Failed Replication of '+lgo,str(sys.exc_info()))#e))

    def runReplicationScript(self,clean=False):
        '''Run the layer/group repliction script'''
        destination,lgval,uconf,epsg,fe,te,fd,td = self.readParameters()
        uconf_path = LU.standardiseUserConfigName(uconf)
        destination_path = LU.standardiseLayerConfigName(destination)
        destination_driver = LU.standardiseDriverNames(destination)

        if not os.path.exists(uconf_path):
            self.userConfMessage(uconf_path)
            return
        elif not MainFileReader(uconf_path).hasSection(destination_driver):
            self.userConfMessage(uconf_path,destination_driver)
            return
        #-----------------------------------------------------
        #'destname','layer','uconf','group','epsg','fd','td','int'
     
        self.parent.gpr.write((destination_driver,lgval,uconf,epsg,fd,td))        
        ldslog.info(u'dest={0}, lg={1}, conf={2}, epsg={3}'.format(destination_driver,lgval,uconf,epsg))
        ldslog.info('fd={0}, td={1}, fe={2}, te={3}'.format(fd,td,fe,te))
        lgindex = self.parent.confconn.getLayerGroupIndex(lgval,col=1)
        #lorg = self.parent.confconn.lglist[lgindex][0]
        #----------don't need lorg in TP anymore but it is useful for sorting/counting groups
        #self.parent.confconn.tp.setLayerOrGroup(lorg)
        self.parent.confconn.tp.setLayerGroupValue(lgval)
        if self.fromdateenable.isChecked(): self.parent.confconn.tp.setFromDate(fd)
        if self.todateenable.isChecked(): self.parent.confconn.tp.setToDate(td)
        self.parent.confconn.tp.setUserConf(uconf)
        if self.epsgenable: self.parent.confconn.tp.setEPSG(epsg)
        
        #because clean state persists in TP
        if clean:
            self.parent.confconn.tp.setCleanConfig()
        else:
            self.parent.confconn.tp.clearCleanConfig()
        #(re)initialise the data source since uconf may have changed
        #>>#self.parent.confconn.tp.src = self.parent.confconn.initSourceWrapper()
        #--------------------------
        ###ep = self.parent.confconn.reg.openEndPoint(self.parent.confconn.destname,self.parent.confconn.uconf)
        
        ###self.parent.confconn.reg.closeEndPoint(self.parent.confconn.destname)
        ###ep = None
        #Open ProcessRunner and run with TP(proc)/self(gui) instances
        #HACK temp add of dest_drv to PR call
        try:
            #TODO. Test for valid LC first
            self.tpr = ProcessRunner(self,destination_driver)
        except Exception as e:
            ldslog.error('Cannot create ProcessRunner {}. NB Possible missing Layer Config {}'.format(str(e),destination_path))
            self.layerConfMessage(destination_path)
            return
        #If PR has been successfully created we must vave a valid dst    
        self.tpr.start()
        
    def quitProcessRunner(self):
        self.tpr.join()
        self.tpr.quit()
        self.trp = None

        
    def userConfMessage(self,uconf,secname=None):
        ucans = QMessageBox.warning(self, 'User Config Missing/Incomplete', 
                                'Specified User-Config file, '+str(uconf)+' does not exist' if secname is None else 'User-Config file does not contain '+str(secname)+' section', 
                                'Back','Initialise User Config')
        if not ucans:
            #Retry
            ldslog.warn('Retry specifying UC')
            #self.confcombo.setCurrentIndex(0)
            return
        #Init
        ldslog.warn('Reset User Config Wizard')
        self.parent.runWizardAction()


    def layerConfMessage(self,dest):
        lcans = QMessageBox.warning(self, 'Layer Config Missing', 
                                'Required Layer-Config file, '+str(dest)+' does not exist', 
                                'Back','Run Layer Select')
        if not lcans:
            #Retry
            ldslog.warn('Retry specifying LC')
            #self.destcombo.setCurrentIndex(0)
            return
        #Init
        ldslog.warn('Reset Layer Config')
        self.doInitClickAction()
Ejemplo n.º 5
0
class sub_canvas(MyMplCanvas):
    def __init__(self, *args, **kwargs):
        MyMplCanvas.__init__(self, *args, **kwargs)
        # 初始化变量,以控制图表的显示
        self.control = {"basic":True,
                        "extreme":True,
                        "slope":True,
                        "star":True}

        self.widget = QWidget(self)
        self.horizontalLayout = QHBoxLayout(self.widget)
        self.label_1 = QLabel(self.widget)
        self.horizontalLayout.addWidget(self.label_1)
        self.lineEdit = QLineEdit(self.widget)
        self.horizontalLayout.addWidget(self.lineEdit)
        self.label_2 = QLabel(self.widget)
        self.horizontalLayout.addWidget(self.label_2)
        self.dateEdit = QDateEdit(self.widget)
        self.horizontalLayout.addWidget(self.dateEdit)
        self.label_3 = QLabel(self.widget)
        self.horizontalLayout.addWidget(self.label_3)
        self.dateEdit_2 = QDateEdit(self.widget)
        self.horizontalLayout.addWidget(self.dateEdit_2)
        self.button1 = QPushButton(self.widget)
        self.horizontalLayout.addWidget(self.button1)
        self.button2 = QPushButton(self.widget)
        self.horizontalLayout.addWidget(self.button2)
        self.button3 = QPushButton(self.widget)
        self.horizontalLayout.addWidget(self.button3)
        self.button4 = QPushButton(self.widget)
        self.horizontalLayout.addWidget(self.button4)
        self.button5 = QPushButton(self.widget)
        self.horizontalLayout.addWidget(self.button5)
        self.lineEdit.setText(QtCore.QString('002594'))
        three_month = QtCore.QDate.currentDate().toJulianDay() - 150
        self.dateEdit.setDate(QtCore.QDate.fromJulianDay(three_month))
        self.dateEdit_2.setDate(QtCore.QDate.currentDate())
        self.label_1.setText(_translate("MainWindow", "股票代码", None))
        self.label_2.setText(_translate("MainWindow", "起始时间", None))
        self.label_3.setText(_translate("MainWindow", "终止时间", None))
        self.button1.setText(_translate("MainWindow", "所有", None))
        self.button2.setText(_translate("MainWindow", "极端", None))
        self.button3.setText(_translate("MainWindow", "斜率", None))
        self.button4.setText(_translate("MainWindow", "趋势", None))
        self.button5.setText(_translate("MainWindow", "清除", None))

        self.button1.clicked.connect(self.draw_all)
        self.button2.clicked.connect(self.draw_extreme)
        self.button3.clicked.connect(self.draw_slope)
        self.button4.clicked.connect(self.draw_trend)
        self.button5.clicked.connect(self.clear)

    def keyPressEvent(self, event):
        keyEvent = QKeyEvent(event)
        if keyEvent.key() == QtCore.Qt.Key_Enter or keyEvent.key() == QtCore.Qt.Key_Return:
            self.draw_all()
        if keyEvent.key() == QtCore.Qt.Key_0:
            self.draw_all()

    # 定义横坐标格式的回调函数
    def my_major_formatter(self, x, pos):
        for i in range(self.num):
            if (x == i):
                return self.str_date[i]

    # 控制图表的显示信息
    # basic 为基本图标,extreme为极端情景,slope为斜率,star为选股星数,trend为趋势线
    def set_control_all(self):
        self.control = {"basic": True, "extreme": True, "slope": True,"star":True,"trend":False}

    def set_control_extreme(self):
        self.control = {"basic": True, "extreme": True, "slope": False, "star": True,"trend":False}

    def set_control_slope(self):
        self.control = {"basic": True, "extreme": False, "slope": True, "star": True,"trend":False}

    def set_control_star(self):
        self.control = {"basic": True, "extreme": False, "slope": False, "star": True,"trend":False}

    def set_control_trend(self):
        self.control = {"basic": True, "extreme": False, "slope": False, "star": False, "trend": True}

    def draw_all(self):
        self.get_value()
        self.set_control_all()
        self.update_figure()

    def draw_extreme(self):
        self.get_value()
        self.set_control_extreme()
        self.update_figure()

    def draw_slope(self):
        self.get_value()
        self.set_control_slope()
        self.update_figure()

    def draw_star(self):
        self.get_value()
        self.set_control_star()
        self.update_figure()

    def draw_trend(self):
        self.get_value()
        self.set_control_trend()
        self.update_figure()
    def get_value(self):
        # 从qt中读取数据并进行格式转化,然后将这个读入到已有的软件中
        code = QtCore.QString(self.lineEdit.text())
        start = QtCore.QString(self.dateEdit.text())
        end = QtCore.QString(self.dateEdit_2.text())
        code = unicode(code)
        start = datetime.date(int(start.split("/")[0]), int(start.split("/")[1]), int(start.split("/")[2])).isoformat()
        end = datetime.date(int(end.split("/")[0]), int(end.split("/")[1]), int(end.split("/")[2])).isoformat()
        # K线图和EMA等
        self.num, self.kbar, self.str_date, self.ema, self.name= source(code, start, end)
        # 星图
        self.star_date, self.star_value = star(col, code, start, end)


    def update_figure(self):

        self.fig.clf()
        self.ax1 = self.fig.add_subplot(111)
        self.ax2 = self.ax1.twinx()  # 创建第二个坐标轴,为同图

        # 万得的接口
        WindPy.w.start()
        self.ax1.set_xticks(range(self.num))
        xmajorLocator = MultipleLocator(5)  # 将x主刻度标签设置为5的倍数
        xminorLocator = MultipleLocator(1)  # 将x副刻度标签设置为1的倍数
        self.ax1.xaxis.set_major_locator(xmajorLocator)
        self.ax1.xaxis.set_minor_locator(xminorLocator)
        self.ax1.xaxis.set_major_formatter(FuncFormatter(self.my_major_formatter))
        # 设置网格
        self.ax1.grid()

        self.ax1.plot(range(self.num),self.ema,linewidth = 0.5,color = "blue")
        if self.control["star"]:
            self.ax2.bar(range(len(self.star_date)), self.star_value, picker=True, color='#FFFF00', width = 0.5,edgecolor = 'black')
        from matplotlib.font_manager import FontProperties
        font = FontProperties(size=14)  # 设置字体
        self.ax1.set_title(self.name)
        self.ax1.set_ylabel(u'价格')
        self.ax2.set_ylabel(u'星数')
        # 极端情况
        high_1 = self.kbar[0][2]
        low_1 = self.kbar[0][3]
        ema_1 = self.ema[0]
        deviate_1 = max(abs(high_1 - ema_1),abs(low_1 - ema_1))
        high_2 = self.kbar[1][2]
        low_2 = self.kbar[1][3]
        ema_2 = self.ema[1]
        deviate_2 = max(abs(high_2 - ema_2),abs(low_2 - ema_2))
        high_3 = self.kbar[2][2]
        low_3 = self.kbar[2][3]
        ema_3 = self.ema[2]
        deviate_3 = max(abs(high_3 - ema_3),abs(low_3 - ema_3))
        high_4 = self.kbar[3][2]
        low_4 = self.kbar[3][3]
        ema_4 = self.ema[3]
        deviate_4 = max(abs(high_4 - ema_4), abs(low_4 - ema_4))
        high_5 = self.kbar[3][2]
        low_5 = self.kbar[3][3]
        ema_5 = self.ema[3]
        deviate_5 = max(abs(high_5 - ema_5), abs(low_5 - ema_5))
        lim = self.ax1.get_ylim()
        distance = (lim[1] - lim[0])/9
        mark_1 = {'Buy':False,'Sell':False}
        mark_2 = {'Buy':False,'Sell':False}
        mark_3 = {'Buy':False,'Sell':False}
        mark_4 = {'Buy':False,'Sell':False}
        mark_5 = {'Buy':False,'Sell':False}
        mark_6 = {'Buy':False,'Sell':False}
        for i in range(5,self.num):
            alpha = 1.11
            beta = 0.88
            high_6 = self.kbar[i][2]
            low_6 = self.kbar[i][3]
            ema_6 = self.ema[i]
            deviate_6 = max(abs(high_6 - ema_6),abs(low_6 - ema_6))
            condition1 = deviate_4 > deviate_3 > deviate_2 or deviate_4 > deviate_3 > deviate_1 or deviate_4 > deviate_2 > deviate_1
            condition2 = ema_4 > ema_3 > ema_2 or ema_2 > ema_3 > ema_4
            condition3 = deviate_4 > deviate_5 * beta and deviate_4 > deviate_6
            top = high_4 - ema_4
            bottom = ema_4 - low_4
            condition4 = (low_4 < low_5 * alpha and low_4 < low_6 and top < bottom) or (high_4 > high_5 * beta and high_4 > high_6 and top > bottom)
            condition5 = top < bottom
            condition6 = top > bottom
            condition7 = high_3 < ema_3 and high_4 < ema_4 and high_5 < ema_5 and high_6 > ema_6 * alpha
            condition8 = low_3 > ema_3 and low_4 > ema_4 and low_5 > ema_5 and low_6 < ema_6 * beta
            max_ema = max(ema_3,ema_4,ema_5)
            min_ema = min(ema_3,ema_4,ema_5)
            condition9 = (ema_3 > ema_4 > ema_5) and ema_6 > ema_5
            condition10 = (ema_3 < ema_4 < ema_5) and ema_6 < ema_5
            condition11 = max_ema < (min_ema * 1.1)
            condition12 = (mark_5['Buy'] == False)
            condition13 = (mark_5['Sell'] == False)
            matplotlib.rcParams.update({'font.size': 9})
            highest = max(high_1, high_2, high_3, high_4, high_5, high_6)
            lowest = max(low_1, low_2, low_3, low_4, low_5, low_6)
            if self.control["extreme"]:
                if condition1 and condition2 and condition3 and condition4 and condition5 and condition12 or condition7 :
                    # self.ax1.annotate(u'多', xy=(i, low_6), xytext=(i-0.5, low_6 - distance), arrowprops=dict(arrowstyle="-"))
                    self.ax1.text(i-0.7, low_6 - distance * 1, u'多',size=5)
                    mark_6['Buy'] = True
                if condition1 and condition2 and condition3 and condition4 and condition6 and condition13 or condition8 :
                    # self.ax1.annotate(u'空', xy=(i, high_6), xytext=(i-0.5, high_6 + distance), arrowprops=dict(arrowstyle="-"))
                    self.ax1.text(i-0.7, high_6 + distance * 1, u'空', size=5)
                    mark_6['Sell'] = True
            if self.control["slope"]:
                if condition9 and condition11:
                    # self.ax1.annotate(u'B', xy=(i - 0.5, low_6 - distance * 3), xytext=(i - 0.5, low_6 - distance * 3),arrowprops=dict(arrowstyle="-"))
                    self.ax1.text(i - 0.5, low_6 - distance * 1.8, u'B', size=8)
                if condition10 and condition11:
                    # self.ax1.annotate(u'S', xy=(i - 0.5, high_6 + distance * 3), xytext=(i - 0.5, high_6 + distance * 3),arrowprops=dict(arrowstyle="-"))
                    self.ax1.text(i - 0.5, high_6 + distance * 1.8, u'S', size=8)
            if self.control["trend"]:
                if i%6 == 0:
                    self.trend_x = [i-6,i]
                    self.trend_y = [high_1,highest]
                    self.ax1.plot(self.trend_x,self.trend_y)
            deviate_1 = deviate_2
            deviate_2 = deviate_3
            deviate_3 = deviate_4
            deviate_4 = deviate_5
            deviate_5 = deviate_6
            ema_1 = ema_2
            ema_2 = ema_3
            ema_3 = ema_4
            ema_4 = ema_5
            ema_5 = ema_6
            low_1 = low_2
            low_2 = low_3
            low_3 = low_4
            low_4 = low_5
            low_5 = low_6
            high_1 = high_2
            high_2 = high_3
            high_3 = high_4
            high_4 = high_5
            high_5 = high_6
            mark_1 = mark_2
            mark_2 = mark_3
            mark_3 = mark_4
            mark_4 = mark_5
            mark_5 = mark_6
            mark_6 = {'Buy':False,'Sell':False}

        # self.ax1.annotate('extreme', xy=(18, 16.8), xytext=(20, 16), arrowprops=dict(arrowstyle="->"))
        self.ax2.set_ylim(0, 80)
        candlestick_ohlc(self.ax1, self.kbar, width=0.5, colorup='r', colordown='g')
        # self.ax1.hold(False)
        # self.ax2.hold(False)
        lim = self.ax1.get_ylim()
        self.ax1.set_ylim(lim[0] * 0.9, lim[1]*0.98)
        for tick in self.ax1.xaxis.get_major_ticks():
            tick.label1.set_fontsize(8)
            tick.label1.set_rotation(75)
        for tick in self.ax1.yaxis.get_major_ticks():
            tick.label1.set_fontsize(8)
            tick.label1.set_rotation(30)
        for tick in self.ax2.xaxis.get_major_ticks():
            tick.label1.set_fontsize(8)
            tick.label1.set_rotation(75)
        for tick in self.ax2.yaxis.get_major_ticks():
            tick.label1.set_fontsize(8)
            tick.label1.set_rotation(30)
        # 子图二

        # self.ax2.set_xticks(range(self.num))
        # self.ax2.xaxis.set_major_locator(xmajorLocator)
        # self.ax2.xaxis.set_minor_locator(xminorLocator)
        # self.ax2.grid()
        # self.ax2.set_xticklabels(self.str_date, rotation=25, horizontalalignment='right')

        # self.ax2.bar(range(len(self.star_date)), self.star_value, picker=True, color='#FFFF00')
        # #self.ax2.xaxis.set_major_locator(xmajorLocator)
        # self.ax2.xaxis.set_major_formatter(FuncFormatter(self.my_major_formatter))
        # for label in self.ax2.get_xticklabels():
        #     label.set_picker(True)
        # for tick in self.ax2.xaxis.get_major_ticks():
        #     tick.label1.set_fontsize(5)
        #     tick.label1.set_rotation(90)
        # for tick in self.ax2.yaxis.get_major_ticks():
        #     tick.label1.set_fontsize(5)
        #     tick.label1.set_rotation(30)
        #
        self.draw()
        # self.fig.clf()


    def clear(self):
        self.fig.clf()
        self.ax1 = self.fig.add_subplot(111)
        # self.ax1 = self.fig.add_axes([0.1, 0.35, 0.8, 0.58])
        # self.ax2 = self.fig.add_axes([0.1, 0.07, 0.8, 0.2])
        self.draw()
Ejemplo n.º 6
0
        def initGui():
            def setData():
                buttonPath.setText(self.data["path"])
                radioVisual.setChecked(self.data["isVisual"])
                radioAnalytic.setChecked(not self.data["isVisual"])
                chkBoxSquare.setChecked(self.data["isSquare"])
                d1 = self.data["date1"]
                d2 = self.data["date2"]
                date1.setDate(d1)
                date2.setDate(d2)
                date1.setMaximumDate(d2.addDays(-1))
                date2.setMinimumDate(d1.addDays(+1))
                spinDay.setValue(d1.daysTo(d2))

            def connect():
                buttonOK.clicked.connect(self.onOK)
                buttonPath.clicked.connect(self.onPath)
                date1.dateChanged.connect(self.onDateChanged1)
                date2.dateChanged.connect(self.onDateChanged2)
                spinDay.valueChanged.connect(self.onValueChanged)

            windowTitle = "Setting download images Planet Labs"
            self.setWindowTitle(windowTitle)
            self.setWindowIcon(icon)

            grpImage = QGroupBox("Images", self)
            radioVisual = QRadioButton("Visual", grpImage)
            radioVisual.setObjectName("rbVisual")
            radioAnalytic = QRadioButton("Analytic", grpImage)
            chkBoxSquare = QCheckBox("Square thumbnail", grpImage)
            chkBoxSquare.setObjectName("cbBoxSquare")
            buttonPath = QPushButton(self.titleSelectDirectory, grpImage)
            buttonPath.setObjectName("pbPath")

            layoutRadioButtons = QHBoxLayout()
            for item in (radioVisual, radioAnalytic):
                layoutRadioButtons.addWidget(item)

            layoutImage = QVBoxLayout(grpImage)
            layoutImage.addLayout(layoutRadioButtons)
            layoutImage.addWidget(chkBoxSquare)
            layoutImage.addWidget(buttonPath)

            grpDateSearch = QGroupBox("Dates for search", self)
            date1 = QDateEdit(grpDateSearch)
            date1.setObjectName("deDate1")
            date2 = QDateEdit(grpDateSearch)
            date2.setObjectName("deDate2")
            for item in [date1, date2]:
                item.setCalendarPopup(True)
                format = item.displayFormat().replace("yy", "yyyy")
                item.setDisplayFormat(format)
            spinDay = QSpinBox(grpDateSearch)
            spinDay.setObjectName("sbDay")
            spinDay.setSingleStep(1)
            spinDay.setSuffix(" Days")
            spinDay.setRange(1, 1000 * 360)

            layoutDate = QHBoxLayout(grpDateSearch)
            layoutDate.addWidget(QLabel("From", grpDateSearch))
            layoutDate.addWidget(date1)
            layoutDate.addWidget(QLabel("To", grpDateSearch))
            layoutDate.addWidget(date2)
            layoutDate.addWidget(spinDay)

            buttonOK = QPushButton("OK", self)

            layout = QVBoxLayout(self)
            layout.addWidget(grpImage)
            layout.addWidget(grpDateSearch)
            layout.addWidget(buttonOK)

            self.resize(5 * len(windowTitle) + 200, 30)

            if not self.data is None:
                setData()
            else:
                radioVisual.setChecked(True)
                radioAnalytic.setChecked(False)
                chkBoxSquare.setChecked(False)
                d2 = QDate.currentDate()
                d1 = d2.addMonths(-1)
                date1.setDate(d1)
                date2.setDate(d2)
                date1.setMaximumDate(d2.addDays(-1))
                date2.setMinimumDate(d1.addDays(+1))
                spinDay.setValue(d1.daysTo(d2))

            connect()
Ejemplo n.º 7
0
class QtDateSelector(QtBoundedDate, ProxyDateSelector):
    """ A Qt implementation of an Enaml ProxyDateSelector.

    """

    #: A reference to the widget created by the proxy.
    widget = Typed(QDateEdit)

    # --------------------------------------------------------------------------
    # Initialization API
    # --------------------------------------------------------------------------
    def create_widget(self):
        """ Create the QDateEdit widget.

        """
        self.widget = QDateEdit(self.parent_widget())

    def init_widget(self):
        """ Initialize the widget.

        """
        super(QtDateSelector, self).init_widget()
        d = self.declaration
        self.set_date_format(d.date_format)
        self.set_calendar_popup(d.calendar_popup)
        self.widget.dateChanged.connect(self.on_date_changed)

    # --------------------------------------------------------------------------
    # Abstract API Implementation
    # --------------------------------------------------------------------------
    def get_date(self):
        """ Return the current date in the control.

        Returns
        -------
        result : date
            The current control date as a date object.

        """
        return self.widget.date().toPyDate()

    def set_minimum(self, date):
        """ Set the widget's minimum date.

        Parameters
        ----------
        date : date
            The date object to use for setting the minimum date.

        """
        self.widget.setMinimumDate(date)

    def set_maximum(self, date):
        """ Set the widget's maximum date.

        Parameters
        ----------
        date : date
            The date object to use for setting the maximum date.

        """
        self.widget.setMaximumDate(date)

    def set_date(self, date):
        """ Set the widget's current date.

        Parameters
        ----------
        date : date
            The date object to use for setting the date.

        """
        self._guard |= CHANGED_GUARD
        try:
            self.widget.setDate(date)
        finally:
            self._guard &= ~CHANGED_GUARD

    def set_date_format(self, format):
        """ Set the widget's date format.

        Parameters
        ----------
        format : str
            A Python time formatting string.

        """
        # XXX make sure Python's and Qt's format strings are the
        # same, or convert between the two.
        self.widget.setDisplayFormat(format)

    def set_calendar_popup(self, popup):
        """ Set whether a calendar popup is available on the widget.

        Parameters
        ----------
        popup : bool
            Whether the calendar popup is enabled.

        """
        self.widget.setCalendarPopup(popup)
Ejemplo n.º 8
0
class sub_canvas(MyMplCanvas):
    def __init__(self, *args, **kwargs):
        MyMplCanvas.__init__(self, *args, **kwargs)


        self.widget = QWidget(self)
        self.horizontalLayout = QHBoxLayout(self.widget)
        self.label_1 = QLabel(self.widget)
        self.horizontalLayout.addWidget(self.label_1)
        self.lineEdit = QLineEdit(self.widget)
        self.horizontalLayout.addWidget(self.lineEdit)
        self.label_2 = QLabel(self.widget)
        self.horizontalLayout.addWidget(self.label_2)
        self.dateEdit = QDateEdit(self.widget)
        self.horizontalLayout.addWidget(self.dateEdit)
        self.label_3 = QLabel(self.widget)
        self.horizontalLayout.addWidget(self.label_3)
        self.dateEdit_2 = QDateEdit(self.widget)
        self.horizontalLayout.addWidget(self.dateEdit_2)
        self.button1 = QPushButton(self.widget)
        self.horizontalLayout.addWidget(self.button1)
        self.button2 = QPushButton(self.widget)
        self.horizontalLayout.addWidget(self.button2)
        self.lineEdit.setText(QtCore.QString('600198'))
        three_month = QtCore.QDate.currentDate().toJulianDay() - 40
        self.dateEdit.setDate(QtCore.QDate.fromJulianDay(three_month))
        self.dateEdit_2.setDate(QtCore.QDate.currentDate())
        self.label_1.setText(_translate("MainWindow", "股票代码", None))
        self.label_2.setText(_translate("MainWindow", "起始时间", None))
        self.label_3.setText(_translate("MainWindow", "终止时间", None))
        self.button1.setText(_translate("MainWindow", "提交", None))
        self.button2.setText(_translate("MainWindow", "清除", None))

        self.button1.clicked.connect(self.get_value)
        self.button2.clicked.connect(self.clear)

    # 定义横坐标格式的回调函数
    def my_major_formatter(self, x, pos):
        for i in range(self.num):
            if (x == i):
                return self.str_date[i]

    def get_value(self):
        code = QtCore.QString(self.lineEdit.text())
        start = QtCore.QString(self.dateEdit.text())
        end = QtCore.QString(self.dateEdit_2.text())
        code = unicode(code)
        start = datetime.date(int(start.split("/")[0]), int(start.split("/")[1]), int(start.split("/")[2])).isoformat()
        end = datetime.date(int(end.split("/")[0]), int(end.split("/")[1]), int(end.split("/")[2])).isoformat()

        self.num, self.kbar, self.str_date, self.ema, = source(code, start, end)
        self.star_date, self.star_value = star(col, code, start, end)
        self.update_figure()
    def update_figure(self):

        self.fig.clf()
        self.ax1 = self.fig.add_subplot(111)
        self.ax2 = self.ax1.twinx()  # 创建第二个坐标轴,为同图
        # 子图一
        self.ax1.set_xticks(range(self.num))
        xmajorLocator = MultipleLocator(5)  # 将x主刻度标签设置为3的倍数
        xminorLocator = MultipleLocator(1)  # 将x副刻度标签设置为1的倍数
        self.ax1.xaxis.set_major_locator(xmajorLocator)
        self.ax1.xaxis.set_minor_locator(xminorLocator)
        self.ax1.xaxis.set_major_formatter(FuncFormatter(self.my_major_formatter))
        self.ax1.grid()
        self.ax2.bar(range(len(self.star_date)), self.star_value, picker=True, color='#FFFF00', width = 0.5,edgecolor = 'black')

        self.ax1.plot(range(self.num),self.ema,linewidth = 0.5,color = "blue")

        #极端情况
        high_1 = self.kbar[0][2]
        low_1 = self.kbar[0][3]
        ema_1 = self.ema[0]
        deviate_1 = max(abs(high_1 - ema_1),abs(low_1 - ema_1))
        high_2 = self.kbar[1][2]
        low_2 = self.kbar[1][3]
        ema_2 = self.ema[1]
        deviate_2 = max(abs(high_2 - ema_2),abs(low_2 - ema_2))
        high_3 = self.kbar[2][2]
        low_3 = self.kbar[2][3]
        ema_3 = self.ema[2]
        deviate_3 = max(abs(high_3 - ema_3),abs(low_3 - ema_3))
        high_4 = self.kbar[3][2]
        low_4 = self.kbar[3][3]
        ema_4 = self.ema[3]
        deviate_4 = max(abs(high_4 - ema_4),abs(low_4 - ema_4))
        high_5 = self.kbar[4][2]
        low_5 = self.kbar[4][3]
        ema_5 = self.ema[4]
        deviate_5 = max(abs(high_5 - ema_5),abs(low_5 - ema_5))
        high_6 = self.kbar[5][2]
        low_6 = self.kbar[5][3]
        ema_6 = self.ema[5]
        deviate_6 = max(abs(high_6 - ema_6),abs(low_6 - ema_6))
        for i in range(6,self.num):
            high_7 = self.kbar[i][2]
            low_7 = self.kbar[i][3]
            ema_7 = self.ema[i]
            deviate_7 = max(abs(high_7 - ema_7),abs(low_7 - ema_7))
            condition1 = deviate_5 > deviate_3 > deviate_2 > deviate_1 or deviate_4 > deviate_3 > deviate_2 > deviate_1
            condition2 = ema_5 > ema_4 > ema_3 > ema_2 > ema_1 or ema_1 > ema_2 > ema_3 > ema_4 > ema_5
            condition3 = deviate_5 > deviate_6 > deviate_7
            if condition1 and condition2 and condition3 :
                self.ax1.annotate('E', xy=(i, low_7), xytext=(i+ 1, low_7+0.5), arrowprops=dict(arrowstyle="->"))
            deviate_1 = deviate_2
            deviate_2 = deviate_3
            deviate_3 = deviate_4
            deviate_4 = deviate_5
            deviate_5 = deviate_6
            deviate_6 = deviate_7
            ema_1 = ema_2
            ema_2 = ema_3
            ema_3 = ema_4
            ema_4 = ema_5
            ema_5 = ema_6
            ema_6 = ema_7
        # self.ax1.annotate('extreme', xy=(18, 16.8), xytext=(20, 16), arrowprops=dict(arrowstyle="->"))
        self.ax2.set_ylim(0, 80)
        candlestick_ohlc(self.ax1, self.kbar, width=0.5, colorup='r', colordown='g')
        lim = self.ax1.get_ylim()
        # self.ax1.hold(False)
        # self.ax2.hold(False)
        self.ax1.set_ylim(lim[0] * 0.95, lim[1])
        for tick in self.ax1.xaxis.get_major_ticks():
            tick.label1.set_fontsize(8)
            tick.label1.set_rotation(75)
        for tick in self.ax1.yaxis.get_major_ticks():
            tick.label1.set_fontsize(8)
            tick.label1.set_rotation(30)
        for tick in self.ax2.xaxis.get_major_ticks():
            tick.label1.set_fontsize(8)
            tick.label1.set_rotation(75)
        for tick in self.ax2.yaxis.get_major_ticks():
            tick.label1.set_fontsize(8)
            tick.label1.set_rotation(30)
        # 子图二

        # self.ax2.set_xticks(range(self.num))
        # self.ax2.xaxis.set_major_locator(xmajorLocator)
        # self.ax2.xaxis.set_minor_locator(xminorLocator)
        # self.ax2.grid()
        # self.ax2.set_xticklabels(self.str_date, rotation=25, horizontalalignment='right')

        # self.ax2.bar(range(len(self.star_date)), self.star_value, picker=True, color='#FFFF00')
        # #self.ax2.xaxis.set_major_locator(xmajorLocator)
        # self.ax2.xaxis.set_major_formatter(FuncFormatter(self.my_major_formatter))
        # for label in self.ax2.get_xticklabels():
        #     label.set_picker(True)
        # for tick in self.ax2.xaxis.get_major_ticks():
        #     tick.label1.set_fontsize(5)
        #     tick.label1.set_rotation(90)
        # for tick in self.ax2.yaxis.get_major_ticks():
        #     tick.label1.set_fontsize(5)
        #     tick.label1.set_rotation(30)
        #
        self.draw()
        # self.fig.clf()


    def clear(self):
        self.fig.clf()
        self.ax1 = self.fig.add_subplot(111)
        # self.ax1 = self.fig.add_axes([0.1, 0.35, 0.8, 0.58])
        # self.ax2 = self.fig.add_axes([0.1, 0.07, 0.8, 0.2])
        self.draw()
Ejemplo n.º 9
0
class UserDialog(QDialog):

    holdc = {}

    def __init__(self, parent=None):
        super(UserDialog, self).__init__(parent)
        self.pagetitle = self.sessionname
        self.tableFont = QFont('Century Gothic', 8)
        self.table = QTableWidget()
        self.cols = [
            'SN', 'ITEM', 'QUANTITY', 'UNIT AMOUNT', 'TOTAL AMOUNT', 'DATE'
        ]
        self.h1_pull_box = QVBoxLayout()

        #self.tableFont.setFamily('Century Gothic')
        self.tableHeaderStyle = "::section {" "background-color: teal; color:white}"
        #pull all CA
        self.editID = 0
        self.hold_unit = {}
        self.hold_store = {}
        self.hold_storeGroup = {}
        self.hold_borrowed = {}

        from_label = QLabel('From:')
        to_label = QLabel('To:')
        self.fromData = QDateEdit()
        self.toData = QDateEdit()
        currentDate = QDate()
        self.fromData.setDate(currentDate.currentDate())
        self.fromData.setCalendarPopup(True)
        self.toData.setDate(currentDate.currentDate())
        self.toData.setCalendarPopup(True)
        menu = QMenu()
        menu.addAction('All', lambda: self.reloadTable(0))
        menu.addAction('In-Stock', lambda: self.reloadTable(1))
        menu.addAction('Out-Stock', lambda: self.reloadTable(2))
        menu.addAction('Damaged', lambda: self.reloadTable(3))
        menu.addAction('Borrowed', lambda: self.reloadTable(4))
        self.pull_btn = QPushButton()
        self.pull_btn.setText("Load")
        self.pull_btn.setMenu(menu)
        h_pull_box = QHBoxLayout()
        h_pull_box.addWidget(from_label)
        h_pull_box.addWidget(self.fromData)
        h_pull_box.addWidget(to_label)
        h_pull_box.addWidget(self.toData)
        h_pull_box.addWidget(self.pull_btn)

        storeGroup = self.pullGroupStore()
        unit = self.pullUnit()

        self.storeGroupText = QLabel('Category')
        self.storeGroupData = QComboBox()
        self.storeGroupData.currentIndexChanged.connect(self.reloadStore)
        self.storeText = QLabel('Items')
        self.storeData = QComboBox()

        self.amountText = QLabel('Total Cost')
        self.amountData = QLineEdit()
        self.amountData.setPlaceholderText('0000.00')
        self.tellerText = QLabel('Reciept No.')
        self.tellerData = QLineEdit()
        self.tellerData.setPlaceholderText('xxxxxxxxx')
        self.quantityText = QLabel('Quantity.')
        self.quantityData = QLineEdit()
        self.quantityData.setPlaceholderText('00.0')
        self.periodText = QLabel('Period (days)')
        self.periodData = QLineEdit()
        self.periodData.setPlaceholderText('00.0')
        self.personText = QLabel('Recieved By:')
        self.personData = QLineEdit()
        self.personData.setPlaceholderText('00.0')
        self.unitText = QLabel('Unit')
        self.unitData = QComboBox()
        self.borrowedText = QLabel('Borrowed')
        self.borrowedData = QComboBox()
        self.dateText = QLabel('Date')
        self.dateData = QDateEdit()
        self.dateData.setDate(currentDate.currentDate())
        self.dateData.setCalendarPopup(True)
        self.descriptionText = QLabel('Description')
        self.descriptionData = QPlainTextEdit()
        self.descriptionData.move(200, 100)
        self.borrowedText.hide()
        self.borrowedData.hide()

        mboz = QVBoxLayout()
        hboz = QHBoxLayout()
        self.state = QLabel('')
        self.r1 = QRadioButton('In-stock')
        self.r1.setChecked(True)
        self.r1.toggled.connect(lambda: self.changeStates())
        self.r2 = QRadioButton('Out-stock')
        self.r2.toggled.connect(lambda: self.changeStates())
        self.r3 = QRadioButton('Damaged')
        self.r3.toggled.connect(lambda: self.changeStates())
        self.r4 = QRadioButton('Borrowed')
        self.r4.toggled.connect(lambda: self.changeStates())
        self.r5 = QRadioButton('Returned')
        self.r5.toggled.connect(lambda: self.changeStates())
        hboz.addWidget(self.r1)
        hboz.addWidget(self.r2)
        hboz.addWidget(self.r3)
        hboz.addWidget(self.r4)
        hboz.addWidget(self.r5)

        i = 0
        for a in storeGroup:
            self.hold_storeGroup[i] = a['id']
            tex = str(a['name']).upper()
            self.storeGroupData.addItem(tex)
            i += 1

        i = 0
        str_key = self.hold_storeGroup[self.storeGroupData.currentIndex()]
        store = self.pullStore(str_key)
        for a in store:
            self.hold_store[i] = a['id']
            tex = str(a['name']).upper()
            self.storeData.addItem(tex)
            i += 1

        i = 0
        for a in unit:
            self.hold_unit[i] = a['id']
            tex = str(a['name']).upper()
            self.unitData.addItem(tex)
            i += 1

        self.reloadBorrowed()
        self.FormLayout = QFormLayout()
        self.FormLayout.addRow(self.storeGroupText, self.storeGroupData)
        self.FormLayout.addRow(self.storeText, self.storeData)
        self.FormLayout.addRow(self.tellerText, self.tellerData)
        self.FormLayout.addRow(self.quantityText, self.quantityData)
        self.FormLayout.addRow(self.amountText, self.amountData)
        self.FormLayout.addRow(self.dateText, self.dateData)
        self.FormLayout.addRow(self.periodText, self.periodData)
        self.FormLayout.addRow(self.borrowedText, self.borrowedData)
        self.FormLayout.addRow(self.personText, self.personData)
        self.FormLayout.addRow(self.descriptionText, self.descriptionData)
        self.periodText.hide()
        self.periodData.hide()

        mboz.addLayout(hboz)
        mboz.addLayout(self.FormLayout)
        mboz.addWidget(self.state)

        groupBox1 = QGroupBox('Add Store Item')
        groupBox1.setLayout(mboz)

        self.pb = QPushButton()
        self.pb.setObjectName("Add")
        self.pb.setText("Add Store Item")

        self.pb1 = QPushButton()
        self.pb1.setObjectName("Edit")
        self.pb1.setText("Edit Row")
        self.pb1.setEnabled(False)

        self.pb2 = QPushButton()
        self.pb2.setObjectName("Close")
        self.pb2.setText("Close")

        self.pb3 = QPushButton()
        self.pb3.setObjectName("Delete")
        self.pb3.setText("Delete Row")
        self.pb3.setEnabled(False)

        self.pb4 = QPushButton()
        self.pb4.setObjectName("Reset")
        self.pb4.setText("Reset")
        self.pb4.hide()

        self.pb5 = QPushButton()
        self.pb5.setObjectName("Change")
        self.pb5.setText("Change Store")
        self.pb5.hide()

        self.pb6 = QPushButton()
        self.pb6.setObjectName("Clear")
        self.pb6.setText("Clear Selection")
        self.pb6.setEnabled(False)

        hbo = QHBoxLayout()
        hbo.addWidget(self.pb)
        hbo.addWidget(self.pb5)
        hbo.addWidget(self.pb4)
        hbo.addWidget(self.pb2)
        groupBox2 = QGroupBox('Store Data')
        groupBox2.setLayout(hbo)

        al = self.pullStoreData(0)
        if al and len(al) > 0:
            al = al
        else:
            al = {}

        self.storeData.currentIndexChanged.connect(
            lambda: self.reloadBorrowed())

        header = self.table.horizontalHeader()
        header.setResizeMode(QHeaderView.ResizeToContents)
        header.setStretchLastSection(True)
        header.setStyleSheet(self.tableHeaderStyle)
        vheader = self.table.verticalHeader()
        vheader.setStyleSheet(self.tableHeaderStyle)
        # Body
        self.table.setWindowTitle("Store")
        self.table.setStyleSheet("color:white")
        self.table.resize(300, 250)
        self.table.setFont(self.tableFont)
        self.table.setSortingEnabled(2)
        #self.table.resizeColumnsToContents()
        self.table.setRowCount(len(al))
        self.table.setColumnCount(len(self.cols))
        self.table.setHorizontalHeaderLabels(self.cols)
        self.table.setContextMenuPolicy(Qt.CustomContextMenu)
        self.table.customContextMenuRequested.connect(self.handleHeaderMenu)
        self.table.hideColumn(0)
        self.table.setSelectionMode(QAbstractItemView.MultiSelection)
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)

        i = 0
        for q in al:
            #row id
            if q['state'] == 1:
                color = QColor(100, 0, 0)
            elif q['state'] == 2:
                color = QColor(100, 100, 0)
            elif q['state'] == 3:
                color = QColor(100, 0, 100)
            elif q['state'] == 4:
                color = QColor(0, 100, 100)
            else:
                color = QColor(0, 50, 150)

            self.table.setItem(i, 0, QTableWidgetItem(str(q['id'])))
            self.table.item(i, 0).setBackground(color)
            self.table.setItem(i, 1,
                               QTableWidgetItem(str(q['itemname']).upper()))
            self.table.item(i, 1).setBackground(color)
            self.table.setItem(i, 2,
                               QTableWidgetItem(str(q['quantity']).upper()))
            self.table.item(i, 2).setBackground(color)
            try:
                zamt = str("{:,}".format(float(q['amount'])))
            except:
                zamt = ''
            self.table.setItem(i, 3, QTableWidgetItem(zamt))
            self.table.item(i, 3).setBackground(color)
            try:
                if len(q['amount']) > 0 and float(q['amount']) > 0:
                    tot = float(q['amount']) * float(q['quantity'])
                else:
                    tot = 0
            except:
                tot = 0
            self.table.setItem(i, 4, QTableWidgetItem(str(tot).upper()))
            self.table.item(i, 4).setBackground(color)
            damz = float(q['datepaid'])
            damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y')
            self.table.setItem(i, 5, QTableWidgetItem(str(damt)))
            self.table.item(i, 5).setBackground(color)
            i += 1
        self.table.itemSelectionChanged.connect(self.confirmSelection)
        self.table.resizeRowsToContents()
        v_pull_box = QVBoxLayout()

        self.h1_pull_box.addWidget(self.table)
        v_pull_box.addLayout(h_pull_box)
        v_pull_box.addLayout(self.h1_pull_box)
        h2_pull_box = QHBoxLayout()
        h2_pull_box.addWidget(self.pb1)
        h2_pull_box.addWidget(self.pb3)
        h2_pull_box.addWidget(self.pb6)
        v_pull_box.addLayout(h2_pull_box)

        groupBox3 = QGroupBox()
        groupBox3.setLayout(hbo)
        groupBox2.setLayout(v_pull_box)

        grid = QGridLayout()
        grid.addWidget(groupBox1, 0, 0)
        grid.addWidget(groupBox2, 0, 1, 2, 1)
        grid.addWidget(groupBox3, 1, 0)

        self.setLayout(grid)
        self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click())
        self.connect(self.pb1, SIGNAL("clicked()"),
                     lambda: self.button_editshow())
        self.connect(self.pb2, SIGNAL("clicked()"),
                     lambda: self.button_close(self))
        self.connect(self.pb3, SIGNAL("clicked()"),
                     lambda: self.button_delete())
        self.connect(self.pb4, SIGNAL("clicked()"),
                     lambda: self.button_reset())
        self.connect(self.pb5, SIGNAL("clicked()"), lambda: self.button_edit())
        self.connect(self.pb6, SIGNAL("clicked()"),
                     lambda: self.button_clear())
        #self.connect(self.pull_btn, SIGNAL("clicked()"), lambda x =1: self.reloadTable(x))

        self.setWindowTitle(self.pagetitle)

    def stateReciept(self):
        self.amountText.show()
        self.amountData.show()
        self.tellerText.show()
        self.tellerData.show()
        self.tellerText.setText('Reciept No.')
        self.periodText.hide()
        self.periodData.hide()
        self.personText.setText('Recieved By:')
        self.personData.setPlaceholderText('Fullname or department')
        self.borrowedText.hide()
        self.borrowedData.hide()
        self.reloadTable(1)

    def stateIssue(self):
        self.amountText.hide()
        self.amountData.hide()
        self.tellerText.show()
        self.tellerData.show()
        self.tellerText.setText('Issue No.')
        self.periodText.hide()
        self.periodData.hide()
        self.personText.setText('Issued to:')
        self.personData.setPlaceholderText('Fullname or department issued to')
        self.borrowedText.hide()
        self.borrowedData.hide()
        self.reloadTable(2)

    def stateDamage(self):
        self.amountText.hide()
        self.amountData.hide()
        self.tellerText.hide()
        self.tellerData.hide()
        self.periodText.hide()
        self.periodData.hide()
        self.personText.setText('Reported By:')
        self.personData.setPlaceholderText('Fullname or department')
        self.borrowedText.hide()
        self.borrowedData.hide()
        self.reloadTable(3)

    def stateBorrowed(self):
        self.amountText.hide()
        self.amountData.hide()
        self.tellerText.hide()
        self.tellerData.hide()
        self.periodText.show()
        self.periodData.show()
        self.personText.setText('Given to:')
        self.personData.setPlaceholderText(
            'Fullname or department borrowed to')
        self.borrowedText.hide()
        self.borrowedData.hide()
        self.reloadTable(4)

    def stateReturned(self):
        self.amountText.hide()
        self.amountData.hide()
        self.tellerText.hide()
        self.tellerData.hide()
        self.periodText.hide()
        self.periodData.hide()
        self.personText.setText('Returned By:')
        self.personData.setPlaceholderText(
            'Fullname or department borrowed to')
        self.borrowedText.show()
        self.borrowedData.show()
        self.reloadBorrowed()
        self.reloadTable(5)

    def changeStates(self):
        self.getQuantity()
        if self.r1.isChecked():
            self.stateReciept()
        elif self.r2.isChecked():
            self.stateIssue()
        elif self.r3.isChecked():
            self.stateDamage()
        elif self.r4.isChecked():
            self.stateBorrowed()
        elif self.r5.isChecked():
            self.stateReturned()

    def handleHeaderMenu(self, pos):
        print('column(%d)' % self.table.horizontalHeader().logicalIndexAt(pos))
        menu = QMenu()
        menu.addAction('Add')
        menu.addAction('Delete')
        menu.exec_(QCursor.pos())

    def pullGroupStore(self):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"pubID": 23, "active": 0})
        return arr

    def pullStore(self, a):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"subID": a})
        return arr

    def pullUnit(self):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"pubID": 20, "active": 0})
        return arr

    def pullStoreData(self, a=None):
        st_date = self.fromData.date().toPyDate()
        en_date = self.toData.date().toPyDate()
        st_date = time.mktime(st_date.timetuple())
        en_date = time.mktime(en_date.timetuple())

        db = 'school_stores' + str(self.session)
        cn = Db()
        arr = cn.selectStoreDate(db, st_date, en_date, a)
        return arr

    def mySelectTable(self):
        '''
        get the selected rpws in a table
        returns list or row ids
        '''
        sels = self.table.selectedIndexes()
        sels = self.table.selectionModel().selectedRows()

        park = []
        park1 = []
        for j in sels:
            park.append(j.row())

        for i in set(park):
            selected = self.table.item(i, 0).text()
            park1.append(selected)

        return park1

    def editRow(self, a):
        _session = self.session
        g = Db()
        db = 'school_stores' + str(_session)
        data = g.selectn(db, '', 1, {'id': a})
        if len(data) > 0:
            try:
                amt = float(data['amount'])
                qty = float(data['quantity'])
                if amt > 0 and qty > 0:
                    cost = amt * qty
                else:
                    cost = 0
            except:
                cost = 0
                amt = 0
                qty = 0

            if data['state'] == 1:
                self.r1.setChecked(True)
            elif data['state'] == 2:
                self.r2.setChecked(True)
            elif data['state'] == 3:
                self.r3.setChecked(True)
            elif data['state'] == 4:
                self.r4.setChecked(True)
            elif data['state'] == 5:
                self.r5.setChecked(True)

            self.amountData.setText(str(cost))
            self.descriptionData.clear()
            self.descriptionData.insertPlainText(str(data['description']))
            self.tellerData.setText(str(data['teller']))
            self.periodData.setText(str(data['period']))
            self.personData.setText(str(data['person']))
            self.quantityData.setText(str(qty))
            stID = self.hold_store.keys()[self.hold_store.values().index(
                data['itemID'])]
            self.storeData.setCurrentIndex(stID)

    def reloadBorrowed(self):
        self.getQuantity()
        _store = self.hold_store[self.storeData.currentIndex()]
        _session = self.session
        g = Db()
        db = 'school_stores' + str(_session)
        data = g.selectn(db, '', '', {'itemID': _store, 'state': 4})
        fig = 0
        self.borrowedData.clear()
        self.hold_borrowed = {}
        i = 0
        for a in data:
            ret = g.selectStoreReturned(db, a['id'])

            if ret:
                retu = ret['qty']
            else:
                retu = 0

            fig = float(a['quantity']) - float(retu)
            damz = float(a['datepaid'])
            if float(fig) > 0:
                self.hold_borrowed[i] = a['id']
                damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y')
                tex = str(damt) + " " + str(
                    a['person']).upper() + " (" + str(fig).upper() + ")"
                self.borrowedData.addItem(tex)
                i += 1

    def reloadStore(self):
        self.getQuantity()
        cat = self.hold_storeGroup[self.storeGroupData.currentIndex()]
        store = self.pullStore(cat)
        self.storeData.clear()
        self.hold_store = {}
        i = 0
        for a in store:
            self.hold_store[i] = a['id']
            tex = str(a['name']).upper()
            self.storeData.addItem(tex)
            i += 1

    def getQuantity(self):
        if self.storeData.currentIndex() > -1:
            s = self.hold_store[self.storeData.currentIndex()]
            _session = self.session
            g = Db()
            db = 'school_stores' + str(_session)
            fi = g.selectStoreQuantity(db, s)
            remain = 0
            arr = {}
            for a in fi:
                arr[a['state']] = a['qty']

            if 1 in arr:
                re = arr[1]
            else:
                re = 0

            if 2 in arr:
                isu = arr[2]
            else:
                isu = 0

            if 3 in arr:
                dam = arr[3]
            else:
                dam = 0

            if 4 in arr:
                bor = arr[4]
            else:
                bor = 0

            if 5 in arr:
                ret = arr[5]
            else:
                ret = 0

            borrowed = float(bor) - float(ret)
            issued = float(isu) + float(borrowed) + float(dam)
            remain = float(re) - float(issued)
            self.quantityText.setText('QTY: ' + str(remain))
            if remain == 0 and (self.r2.isChecked() or self.r3.isChecked()
                                or self.r4.isChecked()):
                self.quantityData.setEnabled(False)
            else:
                self.quantityData.setEnabled(True)
            return remain

    def reloadTable(self, a):
        self.getQuantity()
        if not a == 0:
            data = self.pullStoreData(a)
        else:
            data = self.pullStoreData()

        self.table.close()
        self.table = QTableWidget()
        header = self.table.horizontalHeader()
        header.setResizeMode(QHeaderView.ResizeToContents)
        header.setStretchLastSection(True)
        header.setStyleSheet(self.tableHeaderStyle)
        vheader = self.table.verticalHeader()
        vheader.setStyleSheet(self.tableHeaderStyle)
        # Body
        self.table.setWindowTitle("Stores")
        self.table.setStyleSheet("color:white")
        self.table.resize(300, 250)
        self.table.setFont(self.tableFont)
        self.table.setSortingEnabled(2)
        self.table.resizeColumnsToContents()
        self.table.setRowCount(len(data))
        self.table.setColumnCount(len(self.cols))
        self.table.setHorizontalHeaderLabels(self.cols)
        self.table.setContextMenuPolicy(Qt.CustomContextMenu)
        self.table.customContextMenuRequested.connect(self.handleHeaderMenu)
        self.table.hideColumn(0)
        self.table.setSelectionMode(QAbstractItemView.MultiSelection)
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        i = 0
        for q in data:
            #row id

            if q['state'] == 1:
                color = QColor(100, 0, 0)
            elif q['state'] == 2:
                color = QColor(100, 100, 0)
            elif q['state'] == 3:
                color = QColor(100, 0, 100)
            elif q['state'] == 4:
                color = QColor(0, 100, 100)
            else:
                color = QColor(0, 50, 150)

            self.table.setItem(i, 0, QTableWidgetItem(str(q['id'])))
            self.table.item(i, 0).setBackground(color)
            self.table.setItem(i, 1,
                               QTableWidgetItem(str(q['itemname']).upper()))
            self.table.item(i, 1).setBackground(color)
            self.table.setItem(i, 2,
                               QTableWidgetItem(str(q['quantity']).upper()))
            self.table.item(i, 2).setBackground(color)
            try:
                zamt = str("{:,}".format(float(q['amount'])))
            except:
                zamt = ''
            self.table.setItem(i, 3, QTableWidgetItem(zamt))
            self.table.item(i, 3).setBackground(color)
            try:
                if len(q['amount']) > 0 and float(q['amount']) > 0:
                    tot = float(q['amount']) * float(q['quantity'])
                else:
                    tot = 0
            except:
                tot = 0
            self.table.setItem(i, 4, QTableWidgetItem(str(tot).upper()))
            self.table.item(i, 4).setBackground(color)
            damz = float(q['datepaid'])
            damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y')
            self.table.setItem(i, 5, QTableWidgetItem(str(damt)))
            self.table.item(i, 5).setBackground(color)
            i += 1
        self.table.itemSelectionChanged.connect(self.confirmSelection)
        self.table.resizeRowsToContents()
        self.h1_pull_box.addWidget(self.table)
        self.table.show()

    def pullOnes(self, a, b):
        cn = Db()
        arr = cn.selectn(a, '', 1, {'id': b})
        return arr

    def confirmSelection(self):
        item = self.mySelectTable()
        if len(item) == 1:
            self.pb1.setEnabled(True)
            self.pb3.setEnabled(True)
            self.pb6.setEnabled(True)
        elif len(item) > 1:
            self.pb1.setEnabled(False)
            self.pb3.setEnabled(True)
            self.pb6.setEnabled(True)
        else:
            self.pb1.setEnabled(False)
            self.pb3.setEnabled(False)
            self.pb6.setEnabled(False)

    def button_close(self, b):
        b.close()

    def button_editshow(self):
        item = self.mySelectTable()
        self.editRow(item[0])
        self.pb.hide()
        self.pb4.show()
        self.pb5.show()

    def button_delete(self):
        item = self.mySelectTable()
        _session = self.session
        g = Db()
        db = 'school_stores' + str(_session)
        for j in item:
            g.delete(db, {'id': j})
        self.reloadTable(1)

    def button_edit(self):
        _session = self.session
        _amounts = self.amountData.text()
        _teller = self.tellerData.text()
        _quantity = self.quantityData.text()
        _person = self.personData.text()
        _period = self.periodData.text()
        _date = self.dateData.date().toPyDate()
        _date = time.mktime(_date.timetuple())
        _description = self.descriptionData.toPlainText()
        _store = self.hold_store[self.storeData.currentIndex()]
        _borrowed = self.hold_borrowed[self.borrowedData.currentIndex()]

        arr = {}
        #recieved
        if self.r1.isChecked() and _amounts and not (
                _amounts == 0) and int(_store) > 0 and int(_quantity) > 0:
            _amount = float(_amounts) / float(_quantity)
            arr['amount'] = _amount
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['teller'] = _teller
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['state'] = 1
        #issued
        elif self.r2.isChecked() and int(_store) > 0 and int(_quantity) > 0:
            _amount = float(_amounts) / float(_quantity)
            arr['amount'] = _amount
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['teller'] = _teller
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['state'] = 2
        #damaged
        elif self.r3.isChecked() and int(_store) > 0 and int(_quantity) > 0:
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['teller'] = _teller
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['state'] = 3

        elif self.r4.isChecked() and int(_store) > 0 and int(_quantity) > 0:
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['period'] = _period
            arr['state'] = 4

        elif self.r5.isChecked() and int(_store) > 0 and int(_quantity) > 0:
            _borrowed = self.hold_borrowed[self.borrowedData.currentIndex()]
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['period'] = _period
            arr['active'] = _borrowed
            arr['state'] = 5

        ups = {}
        ups['id'] = self.editID
        if int(self.editID) > 0 and len(arr) > 0:
            db = 'school_stores' + str(_session)
            g = Db()
            g.update(db, arr, ups)
            if int(self.editID) > 0:
                self.button_reset()

    def button_reset(self):
        self.getQuantity()
        self.reloadTable(1)
        self.amountData.setText('')
        self.descriptionData.clear()
        self.tellerData.setText('')
        self.personData.setText('')
        self.periodData.setText('')
        self.quantityData.setText('')
        self.pb4.hide()
        self.pb5.hide()
        self.pb.show()
        self.editID = 0
        self.button_clear()
        self.confirmSelection()
        self.reloadBorrowed()

    def button_clear(self):
        self.table.selectionModel().clearSelection()

    def button_click(self):
        _session = self.session
        _amounts = self.amountData.text()
        _teller = self.tellerData.text()
        _quantity = self.quantityData.text()
        _person = self.personData.text()
        _period = self.periodData.text()
        _date = self.dateData.date().toPyDate()
        _date = time.mktime(_date.timetuple())
        _description = self.descriptionData.toPlainText()
        _store = self.hold_store[self.storeData.currentIndex()]

        arr = {}
        #recieved
        if self.r1.isChecked() and _amounts and not (
                _amounts == 0) and int(_store) > 0 and int(_quantity) > 0:
            _amount = float(_amounts) / float(_quantity)
            arr['amount'] = _amount
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['teller'] = _teller
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['state'] = 1
        #issued
        elif self.r2.isChecked() and _amounts and not (
                _amounts == 0) and int(_store) > 0 and int(_quantity) > 0:
            _amount = float(_amounts) / float(_quantity)
            arr['amount'] = _amount
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['teller'] = _teller
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['state'] = 2
        #damaged
        elif self.r3.isChecked() and int(_store) > 0 and int(
                float(_quantity)) > 0:
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['teller'] = _teller
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['state'] = 3

        elif self.r4.isChecked() and int(_store) > 0 and int(
                float(_quantity)) > 0:
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['period'] = _period
            arr['state'] = 4

        elif self.r5.isChecked() and int(_store) > 0 and int(
                float(_quantity)) > 0 and self.borrowedData.currentIndex() > 0:
            _borrowed = self.hold_borrowed[self.borrowedData.currentIndex()]
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['period'] = _period
            arr['active'] = _borrowed
            arr['state'] = 5

        if len(arr) > 0:
            db = 'school_stores' + str(_session)
            g = Db()
            ins = g.insert(db, arr)
            if int(ins) > 0:
                self.button_reset()
Ejemplo n.º 10
0
class AddTalkWidget(QWidget):
    '''
    classdocs
    '''
    def __init__(self, parent=None):
        '''
        Constructor
        '''
        QWidget.__init__(self, parent)
        self.mainLayout = QVBoxLayout()
        self.setLayout(self.mainLayout)

        self.addTalkGroupBox = QGroupBox("Add Talk")
        self.mainLayout.addWidget(self.addTalkGroupBox)

        self.addTalkLayout = QFormLayout()
        self.addTalkGroupBox.setLayout(self.addTalkLayout)

        # Title
        self.titleLabel = QLabel("Title")
        self.titleLineEdit = QLineEdit()
        if hasattr(QLineEdit(), 'setPlaceholderText'):
            self.titleLineEdit.setPlaceholderText("Title of the presentation")
        self.titleLabel.setBuddy(self.titleLineEdit)
        self.addTalkLayout.addRow(self.titleLabel, self.titleLineEdit)

        # Presenter
        self.presenterLabel = QLabel("Presenter")
        self.presenterLineEdit = QLineEdit()
        if hasattr(QLineEdit(), 'setPlaceholderText'):
            self.presenterLineEdit.setPlaceholderText(
                "Name person or people presenting (comma separated)")
        self.presenterLabel.setBuddy(self.presenterLineEdit)
        self.addTalkLayout.addRow(self.presenterLabel, self.presenterLineEdit)

        # Event
        self.eventLabel = QLabel("Event")
        self.eventLineEdit = QLineEdit()
        if hasattr(QLineEdit(), 'setPlaceholderText'):
            self.eventLineEdit.setPlaceholderText(
                "The name of the Event this talk is being presented at")
        self.eventLabel.setBuddy(self.eventLineEdit)
        self.addTalkLayout.addRow(self.eventLabel, self.eventLineEdit)

        # Room
        self.roomLabel = QLabel("Room")
        self.roomLineEdit = QLineEdit()
        if hasattr(QLineEdit(), 'setPlaceholderText'):
            self.roomLineEdit.setPlaceholderText(
                "The Room in which the presentation is taking place")
        self.roomLabel.setBuddy(self.roomLineEdit)
        self.addTalkLayout.addRow(self.roomLabel, self.roomLineEdit)

        # Date
        current_date = QDate()
        self.dateLabel = QLabel("Date")
        self.dateEdit = QDateEdit()
        self.dateEdit.setDate(current_date.currentDate())
        self.dateLabel.setBuddy(self.dateEdit)
        self.addTalkLayout.addRow(self.dateLabel, self.dateEdit)

        self.dateEdit.setCalendarPopup(True)

        # Time
        current_time = QTime()
        self.timeLabel = QLabel("Time")
        self.timeEdit = QTimeEdit()
        self.timeEdit.setTime(current_time.currentTime())
        self.timeLabel.setBuddy(self.dateEdit)
        self.addTalkLayout.addRow(self.timeLabel, self.timeEdit)

        # Buttons
        addIcon = QIcon.fromTheme("list-add")
        cancelIcon = QIcon.fromTheme("edit-clear")

        self.buttonsWidget = QHBoxLayout()
        self.addButton = QPushButton("Add")
        self.addButton.setIcon(addIcon)
        self.cancelButton = QPushButton("Cancel")
        self.cancelButton.setIcon(cancelIcon)
        self.buttonsWidget.addWidget(self.addButton)
        self.buttonsWidget.addWidget(self.cancelButton)
        self.addTalkLayout.addRow(None, self.buttonsWidget)
Ejemplo n.º 11
0
class FormStudentMisconduct(QDialog):
    def __init__(self, student, term, edit=None, parent=None):
        super(FormStudentMisconduct, self).__init__(parent)
        self.student = student
        self.term = term

        self.db_class = 'student_class' + str(self.term)
        self.db_subject = 'student_subject' + str(self.term)

        student = self.pullData('students', 1, {'id': self.student})
        term = self.pullData('terms', 1, {'id': self.term})
        session = self.pullData('session', 1, {'id': term['sessionID']})

        self.session = str(
            str(session['name']) + " " + str(term['name'] + " Term")).title()
        self.fullname = str(
            str(student['surname']) + " " + str(student['firstname'])).title()
        self.sessionID = session['id']

        fullnameLbl = QLabel(self.fullname)
        fullnameLbl.setFont(QFont("Candara", 14, QFont.Bold))
        termLbl = QLabel(self.session)
        termLbl.setFont(QFont("Candara", 12, QFont.Bold))

        actionLbl = QLabel('Action')
        reactionLbl = QLabel('Corrective/Punitive Measure')
        issuerLbl = QLabel('Issuer')
        self.actionData = QPlainTextEdit()
        self.reactionData = QPlainTextEdit()
        self.staffData = QLineEdit()
        self.staffData.setPlaceholderText(
            'Staff Name or  Deparment or Organisation')

        self.pb = QPushButton()
        self.pb.setObjectName("close")
        self.pb.setText("Close")

        self.pb1 = QPushButton()
        self.pb1.setObjectName("Add")
        self.pb1.setText("Add")

        self.pb2 = QPushButton()
        self.pb2.setObjectName("Edit")
        self.pb2.setText("Edit")

        self.connect(self.pb1, SIGNAL("clicked()"),
                     lambda: self.button_click())
        self.connect(self.pb2, SIGNAL("clicked()"), lambda: self.button_edit())
        self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_close())

        self.dateLbl = QLabel('Choose Date:')
        currentDate = QDate()
        self.dateData = QDateEdit()
        self.dateData.setDate(currentDate.currentDate())
        self.dateData.setCalendarPopup(True)

        h_box = QHBoxLayout()
        h_box.addWidget(self.dateLbl)
        h_box.addWidget(self.dateData)

        h_box2 = QHBoxLayout()
        h_box2.addWidget(issuerLbl)
        h_box2.addWidget(self.staffData)

        h_box1 = QHBoxLayout()
        h_box1.addWidget(self.pb)
        h_box1.addWidget(self.pb1)
        h_box1.addWidget(self.pb2)

        self.v_box = QVBoxLayout()
        self.v_box.addWidget(fullnameLbl)
        self.v_box.addWidget(termLbl)
        self.v_box.addLayout(h_box)
        self.v_box.addWidget(actionLbl)
        self.v_box.addWidget(self.actionData)
        self.v_box.addWidget(reactionLbl)
        self.v_box.addWidget(self.reactionData)
        self.v_box.addLayout(h_box2)
        self.v_box.addLayout(h_box1)

        if edit and len(edit) > 0:
            self.edit = edit
            self.editRow(edit)
            self.pb1.hide()
            self.pb2.show()
        else:
            self.edit = None
            self.pb1.show()
            self.pb2.hide()

        self.setLayout(self.v_box)
        self.setWindowTitle("Misconduct Report Form")

    def pullData(self, db, sid, arr):
        g = Db()
        data = g.selectn(db, '', sid, arr)
        return data

    def convert_arr(self, arr):
        ar = []
        for a in arr:
            ar.append(a['subjectID'])

        return ar

    def editrow(self, a):
        e = a.split('_')
        g = Db()
        self.mainrow = e[1]
        self.mainses = e[0]
        db = 'school_conducts' + str(self.mainses)
        data = g.selectn(db, '', 1, {'id': self.mainrow})
        if data and len(data) > 0:
            self.ailmentData.clear()
            self.ailmentData.insertPlainText(str(data['action']))
            self.staffData.setText(str(data['staffname']))
            self.treatmentData.clear()
            self.treatmentData.insertPlainText(str(data['reaction']))

    def button_close(self):
        self.reject()

    def button_click(self):
        action = self.actionData.toPlainText()
        reaction = self.reactionData.toPlainText()
        staff = self.staffData.text()
        _date = self.dateData.date().toPyDate()
        _date = time.mktime(_date.timetuple())

        db = 'school_conducts' + str(self.sessionID)

        if len(action) > 0 and len(reaction) > 0:
            arr = {}
            arr['studentID'] = self.student
            arr['action'] = action
            arr['reaction'] = reaction
            arr['datepaid'] = _date
            arr['staffname'] = staff
            arr['state'] = 1
            g = Db()
            g.insert(db, arr)

        ## set subject
        self.getValue()

    def button_edit(self):
        action = self.actionData.toPlainText()
        reaction = self.reactionData.toPlainText()
        staff = self.staffData.text()
        _date = self.dateData.date().toPyDate()
        _date = time.mktime(_date.timetuple())

        db = 'school_conducts' + str(self.sessionID)

        if len(action) > 0 and len(reaction) > 0:
            arr = {}
            arr['action'] = action
            arr['reaction'] = reaction
            arr['datepaid'] = _date
            arr['staffname'] = staff

            g = Db()
            g.update(db, arr, {'id': self.edit})

        ## set subject
        self.getValue()

    def getValue(self):
        self.accept()
Ejemplo n.º 12
0
class SessionsManager(QDialog):
    def __init__(self, n, parent=None):
        super(SessionsManager, self).__init__(parent)
        self.par = n
        #main
        title = Settingz().positions(30)
        self.titleID = title['id']
        self.titlePage = title['page']
        self.titleName = title['name']
        self.titleSub = title['subID']
        self.titleIcon = title['icon']
        self.pagetitle = self.titlePage
        #stylesheet
        stylesheet = Valid().background() + Valid().font()
        treeStyleSheet = Valid().treez()

        self.groupBox1 = QGroupBox(self.titleName)
        self.groupBox2 = QGroupBox('Add')

        #items
        self.tree = QTreeWidget()
        self.tree.setHeaderLabel("Choose " + self.titleName)
        #tree.setItemDelegate(Delegate())
        self.tree.setItemDelegate(Delegates())
        self.tree.headerItem().setText(0, 'Name')
        self.tree.setStyleSheet(treeStyleSheet)
        self.makeTree()
        self.tree.setMinimumHeight(250)
        self.tree.clicked.connect(lambda: self.getSelection())
        self.tree.itemClicked.connect(lambda state: self.getChecked(state))
        #buttons
        #add
        nImg = Buttons().addButton()
        self.pb = QPushButton()
        self.pb.setFlat(True)
        self.pb.setIcon(QIcon(nImg))
        self.pb.setMaximumHeight(30)
        self.pb.setMaximumWidth(30)

        nImg1 = Buttons().closeButton()
        self.pb1 = QPushButton()
        self.pb1.setFlat(True)
        self.pb1.setIcon(QIcon(nImg1))
        self.pb1.setMaximumHeight(30)
        self.pb1.setMaximumWidth(30)

        nImg2 = Buttons().editButton()
        self.pb2 = QPushButton()
        self.pb2.setFlat(True)
        self.pb2.setIcon(QIcon(nImg2))
        self.pb2.setMaximumHeight(30)
        self.pb2.setMaximumWidth(30)

        nImg3 = Buttons().deleteButton()
        self.pb3 = QPushButton()
        self.pb3.setFlat(True)
        self.pb3.setIcon(QIcon(nImg3))
        self.pb3.setMaximumHeight(30)
        self.pb3.setMaximumWidth(30)

        nImg4 = Buttons().saveButton()
        self.pb4 = QPushButton()
        self.pb4.setFlat(True)
        self.pb4.setIcon(QIcon(nImg4))
        self.pb4.setMaximumHeight(30)
        self.pb4.setMaximumWidth(30)

        nImg5 = Buttons().resetButton()
        self.pb5 = QPushButton()
        self.pb5.setFlat(True)
        self.pb5.setIcon(QIcon(nImg5))
        self.pb5.setMaximumHeight(30)
        self.pb5.setMaximumWidth(30)

        nImg6 = Buttons().closeButton()
        self.pb6 = QPushButton()
        self.pb6.setFlat(True)
        self.pb6.setIcon(QIcon(nImg6))
        self.pb6.setMaximumHeight(30)
        self.pb6.setMaximumWidth(30)

        nImg7 = Buttons().addButton()
        self.pb7 = QPushButton()
        self.pb7.setFlat(True)
        self.pb7.setIcon(QIcon(nImg7))
        self.pb7.setMaximumHeight(30)
        self.pb7.setMaximumWidth(30)

        hbo = QHBoxLayout()
        hbo.addStretch()
        hbo.addWidget(self.pb1)
        hbo.addWidget(self.pb3)
        hbo.addWidget(self.pb2)
        hbo.addWidget(self.pb7)

        vbo = QVBoxLayout()
        vbo.addWidget(self.tree)
        vbo.addLayout(hbo)

        self.l1 = QLabel("Name")
        self.le1 = QLineEdit()
        self.le1.setObjectName("name")
        vals1 = Valid().fullNum()
        self.le1.setValidator(vals1)
        self.le1.setPlaceholderText("Lowercase max 25 letters")

        self.fromLbl = QLabel("Starts")
        self.toLbl = QLabel("Ends")
        self.fromData = QDateEdit()
        self.toData = QDateEdit()
        currentDate = QDate()
        self.fromData.setDate(currentDate.currentDate())
        self.fromData.setCalendarPopup(True)
        self.toData.setDate(currentDate.currentDate())
        self.toData.setCalendarPopup(True)

        FormLayout = QFormLayout()
        FormLayout.addRow(self.l1, self.le1)
        FormLayout.addRow(self.fromLbl, self.fromData)
        FormLayout.addRow(self.toLbl, self.toData)

        Hlayout1 = QHBoxLayout()
        Hlayout1.addStretch()
        Hlayout1.addWidget(self.pb6)
        Hlayout1.addWidget(self.pb5)
        Hlayout1.addWidget(self.pb4)
        Hlayout1.addWidget(self.pb)

        Vlayout1 = QVBoxLayout()
        Vlayout1.addLayout(FormLayout)
        Vlayout1.addLayout(Hlayout1)

        self.groupBox1.setLayout(vbo)
        self.groupBox2.setLayout(Vlayout1)
        self.groupBox2.hide()

        self.connect(self.pb, SIGNAL("clicked()"),
                     lambda: self.button_add())  #add
        self.connect(self.pb1, SIGNAL("clicked()"),
                     lambda: self.button_close())  #close
        self.connect(self.pb2, SIGNAL("clicked()"),
                     lambda: self.button_edit())  #edit
        self.connect(self.pb3, SIGNAL("clicked()"),
                     lambda: self.button_delete())  #delete
        self.connect(self.pb4, SIGNAL("clicked()"),
                     lambda: self.button_save())  #save
        self.connect(self.pb5, SIGNAL("clicked()"),
                     lambda: self.button_reset())  #reset

        self.pb4.hide()
        self.pb7.hide()

        grid = QGridLayout()
        grid.addWidget(self.groupBox1, 0, 0)
        grid.addWidget(self.groupBox2, 1, 0)

        self.setLayout(grid)
        self.setStyleSheet(stylesheet)
        self.setWindowIcon(QIcon(self.titleIcon))
        self.setWindowTitle(self.pagetitle)

    def makeTree(self):
        self.tree.clear()
        arr = Db().selectn('session', '', 5)
        self.hold_data = {}
        self.hold_mdata = {}
        self.hold_data_add = {}
        self.hold_data_add_item = {}
        current = time.time()

        if self.titleSub and self.titleSub > 0:
            if arr and len(arr) > 0:
                for val in arr:
                    ch = Valid().pullData('terms', '',
                                          {'sessionID': val['id']})
                    child = QTreeWidgetItem(self.tree)
                    child.setIcon(0, QIcon('icons.cfolder.png'))
                    try:
                        ts = int(float(val['start_date']))
                    except:
                        ts = int(current)
                    ts = datetime.utcfromtimestamp(ts).strftime('%d-%m-%Y')

                    try:
                        ts1 = int(float(val['end_date']))
                    except:
                        ts1 = int(current)
                    ts1 = datetime.utcfromtimestamp(ts1).strftime('%d-%m-%Y')

                    child.setText(
                        0,
                        str(val['name']).upper() + " - " + ts + " " + ts1)
                    self.hold_mdata[val['id']] = child

                    for va in ch:
                        child1 = QTreeWidgetItem(child)
                        child1.setFlags(child1.flags()
                                        | Qt.ItemIsUserCheckable)

                        try:
                            ts2 = int(float(va['start_date']))
                        except:
                            ts2 = int(current)
                        ts2 = datetime.utcfromtimestamp(ts2).strftime(
                            '%d-%m-%Y')
                        try:
                            ts3 = int(float(va['end_date']))
                        except:
                            ts3 = int(current)
                        ts3 = datetime.utcfromtimestamp(ts3).strftime(
                            '%d-%m-%Y')

                        child1.setText(
                            0,
                            str(va['name']).upper() + " " + ts2 + " " + ts3)
                        self.hold_data[va['id']] = child1
                        if (va['active'] == 1):
                            child1.setCheckState(0, Qt.Checked)
                        else:
                            child1.setCheckState(0, Qt.Unchecked)

                    child1 = QTreeWidgetItem(child)
                    child1.setFlags(child1.flags() | Qt.ItemIsUserCheckable)
                    child1.setText(0, 'Add New Term')
                    self.hold_data_add_item[val['id']] = child1
        else:
            if arr and len(arr) > 0:
                for val in arr:
                    child = QTreeWidgetItem(self.tree)
                    child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
                    child.setText(0, str(val['name']).upper())
                    child.setText(1, str(val['abbrv']).upper())
                    self.hold_data[val['id']] = child
                    if (val['active'] == 0):
                        child.setCheckState(0, Qt.Checked)
                    else:
                        child.setCheckState(0, Qt.Unchecked)

        child = QTreeWidgetItem(self.tree)
        child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
        child.setText(0, 'Add New Session')
        self.hold_data_add['addnew'] = child

    def getChecked(self, a):
        arr_hold = []
        g = Db()
        for i in self.hold_data:
            if self.hold_data[i].checkState(0) == Qt.Checked:
                arr_hold.append(i)
                self.hold_data[i].setCheckState(0, Qt.Checked)
                g.update('terms', {'active': 0}, {'active': 1})
                g.update('terms', {'active': 1}, {'id': i})
                tt = g.selectn('terms', '', 1, {'id': i})
                g.update('session', {'active': 0}, {'active': 1})
                g.update('session', {'active': 1}, {'id': tt['sessionID']})
                g.selectn('session', '', 1, {'id': tt['sessionID']})
            else:
                self.hold_data[i].setCheckState(0, Qt.Unchecked)

        self.reloadTerm()

    def reloadTerm(self):
        session = self.par.activeTerm()
        activeTerm = str(session[1]) + ' SESSION ' + str(session[3]) + ' TERM'
        self.par.majorSession = session[2]
        self.par.lbl.setText(activeTerm)

    def getSelected(self):
        r = False
        self.sessionMain = False
        for i in self.hold_mdata:
            if self.hold_mdata[i].isSelected():
                r = i

        if r and r > 0:
            self.groupBox2.show()
            self.sessionMain = True
            return r
        else:
            for i in self.hold_data:
                if self.hold_data[i].isSelected():
                    r = i
            if r and r > 0:
                self.sessionMain = False
                self.groupBox2.show()
                return r
            else:
                self.groupBox2.hide()

    def getSession(self):
        self.sessionID = None
        for i in self.hold_data_session:
            if self.hold_data_session[i].isSelected():
                r = i
        if r and r > 0:
            self.sessionID = r

    def getSelection(self):
        self.le1.clear()
        currentDate = QDate()
        self.fromData.setDate(currentDate.currentDate())
        self.toData.setDate(currentDate.currentDate())
        self.sessionMain = False

        if self.hold_data_add['addnew'].isSelected():
            self.groupBox2.setTitle('Add New')
            self.groupBox2.show()
            self.sessionMain = True
            self.sessionID = False
        else:
            self.sessionMain = False
            r = None
            for i in self.hold_data_add_item:
                if self.hold_data_add_item[i].isSelected():
                    r = i
            if r:
                g = Db()
                v = g.selectn('session', '', 1, {'id': r})
                vname = str(v['name']).upper() + ' Session'
                self.groupBox2.setTitle('ADD ' + str(vname) + ' Term')
                self.sessionID = r
                self.groupBox2.show()
            else:
                self.groupBox2.setTitle('Add')
                self.sessionID = False
                self.groupBox2.hide()

    def setActive(self):
        g = Db()
        for i in self.hold_data:
            if self.hold_data[i].checkState(0) == Qt.Checked:
                g.update('datas', {'active': 0}, {'id': i})
            else:
                g.update('datas', {'active': 1}, {'id': i})

    def button_add(self):
        s1 = self.le1.text()
        _datef = self.fromData.date().toPyDate()
        _datef = time.mktime(_datef.timetuple())
        _datee = self.toData.date().toPyDate()
        _datee = time.mktime(_datee.timetuple())
        g = Db()

        if self.sessionID and self.sessionID > 0:
            try:
                if (len(s1) > 0):
                    y = {
                        'name': s1.lower(),
                        'start_date': _datef,
                        'sessionID': self.sessionID,
                        'end_date': _datee,
                        'active': 0
                    }
                    z = g.insert('terms', y)
                    if z and z > 0:
                        g.createClass(z)
                        g.createSubject(z)
                        g.createFee(z)
                        g.createPay(z)
                        g.createResult(z)
                        g.createAffective(z)
                        g.createPsychomoto(z)
                    self.makeTree()
                    self.button_reset()
                    self.par.menuSession()
                    self.par.dropdownSession()
                else:
                    pass
            except:
                pass
        else:
            try:
                if (len(s1) > 0):
                    y = {
                        'name': s1.lower(),
                        'start_date': _datef,
                        'end_date': _datee,
                        'active': 0
                    }
                    z = g.insert('session', y)
                    if z and z > 0:
                        g.createExpenses(z)
                        g.createStores(z)
                        g.createAwards(z)
                        g.createConducts(z)
                        g.createMails(z)
                        g.createMedicals(z)
                    self.makeTree()
                    self.button_reset()
                    self.par.menuSession()
                    self.par.dropdownSession()
                else:
                    pass
            except:
                pass

    def button_save(self):
        row = self.editrow
        s1 = self.le1.text()
        _datef = self.fromData.date().toPyDate()
        _datef = time.mktime(_datef.timetuple())
        _datee = self.toData.date().toPyDate()
        _datee = time.mktime(_datee.timetuple())

        g = Db()

        if (len(s1) > 0) and row and row > 0:
            if self.sessionID and self.sessionID > 0:
                try:
                    if (len(s1) > 0):
                        y = {
                            'name': s1.lower(),
                            'start_date': _datef,
                            'sessionID': self.sessionID,
                            'end_date': _datee,
                            'active': 0
                        }
                        k = {'id': row}
                        g.update('terms', y, k)
                        z = row
                        if z and z > 0:
                            g.createClass(z)
                            g.createSubject(z)
                            g.createFee(z)
                            g.createPay(z)
                            g.createResult(z)
                            g.createAffective(z)
                            g.createPsychomoto(z)
                        self.makeTree()
                        self.button_reset()
                        self.par.menuSession()
                        self.par.dropdownSession()
                    else:
                        pass
                except:
                    pass
            else:
                try:
                    if (len(s1) > 0):
                        y = {
                            'name': s1.lower(),
                            'start_date': _datef,
                            'end_date': _datee,
                            'active': 0
                        }
                        k = {'id': row}
                        g.update('session', y, k)
                        z = row
                        if z and z > 0:
                            g.createExpenses(z)
                            g.createStores(z)
                            g.createAwards(z)
                            g.createConducts(z)
                            g.createMails(z)
                            g.createMedicals(z)
                        self.makeTree()
                        self.button_reset()
                        self.par.menuSession()
                        self.par.dropdownSession()
                    else:
                        pass
                except:
                    pass

    def button_delete(self):
        row = self.getSelected()
        g = Db()
        try:
            if row and row > 0:
                y = {'abbrv': '', 'active': 2}
                z = {'id': row}
                g.update('datas', y, z)
                self.makeTree()
            else:
                pass
        except:
            pass

    def button_reset(self):
        self.le1.clear()
        currentDate = QDate()
        self.fromData.setDate(currentDate.currentDate())
        self.toData.setDate(currentDate.currentDate())
        self.groupBox2.setTitle('Add')
        self.groupBox2.hide()
        self.pb.show()
        self.pb4.hide()

    def button_edit(self):
        row = self.getSelected()
        currentDate = QDate()
        if row:
            self.editrow = row
            g = Db()
            if self.sessionMain:
                data = g.selectn('session', '', 1, {'id': row})
                data_name = str(data['name'])
                self.groupBox2.setTitle('Edit')
                self.sessionID = False
            else:
                data = g.selectn('terms', '', 1, {'id': row})
                data_sess = g.selectn('session', '', 1,
                                      {'id': data['sessionID']})
                data_name = str(data['name'])
                self.sessionID = data['sessionID']
                self.groupBox2.setTitle('Edit ' + str(data_sess['name']))
            try:
                self.le1.setText(data_name)
            except:
                self.le1.setText('')
            try:
                self.fromData.setDate(data['start_date'])
            except:
                self.fromData.setDate(currentDate.currentDate())
            try:
                self.toData.setDate(data['end_date'])
            except:
                self.toData.setDate(currentDate.currentDate())
            self.pb.hide()
            self.pb4.show()

    def button_close(self):
        self.close()
Ejemplo n.º 13
0
class sub_canvas(MyMplCanvas):
    def __init__(self, *args, **kwargs):
        MyMplCanvas.__init__(self, *args, **kwargs)


        self.widget = QWidget(self)
        self.horizontalLayout = QHBoxLayout(self.widget)
        self.treeWidget = QTreeWidget(self.widget)
        self.horizontalLayout.addWidget(self.treeWidget)
        self.label_1 = QLabel(self.widget)
        self.horizontalLayout.addWidget(self.label_1)
        self.label_2 = QLabel(self.widget )
        self.lineEdit = QLineEdit(self.widget)
        self.horizontalLayout.addWidget(self.lineEdit)
        self.horizontalLayout.addWidget(self.label_2)
        self.dateEdit = QDateEdit(self.widget)
        self.horizontalLayout.addWidget(self.dateEdit)
        self.label_3 = QLabel(self.widget)
        self.horizontalLayout.addWidget(self.label_3)
        self.dateEdit_2 = QDateEdit(self.widget)
        self.horizontalLayout.addWidget(self.dateEdit_2)
        self.button1 = QPushButton(self.widget)
        self.horizontalLayout.addWidget(self.button1)
        self.button2 = QPushButton(self.widget)
        self.horizontalLayout.addWidget(self.button2)
        self.lineEdit.setText(QtCore.QString('M'))
        three_month = QtCore.QDate.currentDate().toJulianDay() - 60
        self.dateEdit.setDate(QtCore.QDate.fromJulianDay(three_month))
        self.dateEdit_2.setDate(QtCore.QDate.currentDate())
        self.button1.clicked.connect(self.get_value)
        self.button2.clicked.connect(self.clear)

        self.treeWidget.headerItem().setText(0, _translate("MainWindow", "期货品种", None))
        self.root1 = QTreeWidgetItem(self.treeWidget)
        self.root1.setText(0, _translate("MainWindow", "中金所", None))
        self.root2 = QTreeWidgetItem(self.treeWidget)
        self.root2.setText(0, _translate("MainWindow", "上海期货", None))
        self.root3 = QTreeWidgetItem(self.treeWidget)
        self.root3.setText(0, _translate("MainWindow", "大连商品", None))
        self.root4 = QTreeWidgetItem(self.treeWidget)
        self.root4.setText(0, _translate("MainWindow", "郑州商品", None))
        self.child11 = QTreeWidgetItem(self.root1)
        self.child12 = QTreeWidgetItem(self.root1)
        self.child13 = QTreeWidgetItem(self.root1)
        self.child14 = QTreeWidgetItem(self.root1)
        self.child15 = QTreeWidgetItem(self.root1)
        self.child16 = QTreeWidgetItem(self.root1)
        self.child17 = QTreeWidgetItem(self.root1)
        self.child18 = QTreeWidgetItem(self.root1)
        self.child11.setText(0, _translate("MainWindow", "CFFEX 沪深300指数期货(IF)", None))
        self.child12.setText(0, _translate("MainWindow", "CFFEX 上证50指数期货(IH)", None))
        self.child13.setText(0, _translate("MainWindow", "CFFEX 中证500指数期货(IC)", None))
        self.child14.setText(0, _translate("MainWindow", "CFFEX 5年期国债期货(TF)", None))
        self.child15.setText(0, _translate("MainWindow", "CFFEX 10年期国债期货(T)", None))
        self.child16.setText(0, _translate("MainWindow", "CFFEX 3年期国债期货(仿真)(TT)", None))
        self.child17.setText(0, _translate("MainWindow", "CFFEX 澳元兑美元(AUDUSD)期货(仿真)(AF)", None))
        self.child18.setText(0, _translate("MainWindow", "CFFEX 欧元兑美元(EURUSD)期货(仿真)(EF)", None))
        self.child21 = QTreeWidgetItem(self.root2)
        self.child22 = QTreeWidgetItem(self.root2)
        self.child23 = QTreeWidgetItem(self.root2)
        self.child24 = QTreeWidgetItem(self.root2)
        self.child25 = QTreeWidgetItem(self.root2)
        self.child26 = QTreeWidgetItem(self.root2)
        self.child27 = QTreeWidgetItem(self.root2)
        self.child28 = QTreeWidgetItem(self.root2)
        self.child29 = QTreeWidgetItem(self.root2)
        self.child210 = QTreeWidgetItem(self.root2)
        self.child211 = QTreeWidgetItem(self.root2)
        self.child212 = QTreeWidgetItem(self.root2)
        self.child213 = QTreeWidgetItem(self.root2)
        self.child214 = QTreeWidgetItem(self.root2)
        self.child21.setText(0, _translate("MainWindow", "SHFE 铜(CU)", None))
        self.child22.setText(0, _translate("MainWindow", "SHFE 铝(AL)", None))
        self.child23.setText(0, _translate("MainWindow", "SHFE 铅(ZN)", None))
        self.child24.setText(0, _translate("MainWindow", "SHFE 黄金(AU)", None))
        self.child25.setText(0, _translate("MainWindow", "SHFE 白银(AG)", None))
        self.child26.setText(0, _translate("MainWindow", "SHFE 螺纹钢(RB)", None))
        self.child27.setText(0, _translate("MainWindow", "SHFE 橡胶(RU)", None))
        self.child28.setText(0, _translate("MainWindow", "SHFE 燃油(FU)", None))
        self.child29.setText(0, _translate("MainWindow", "SHFE 线材(WR)", None))
        self.child210.setText(0, _translate("MainWindow", "SHFE 石油沥青(BU)", None))
        self.child211.setText(0, _translate("MainWindow", "SHFE 热轧卷板(HC)", None))
        self.child212.setText(0, _translate("MainWindow", "SHFE 镍(NI)", None))
        self.child213.setText(0, _translate("MainWindow", "SHFE 锡(SN)", None))
        self.child214.setText(0, _translate("MainWindow", "SHFE 上期有色金属指数期货(仿真)(IM)", None))
        self.child31 = QTreeWidgetItem(self.root3)
        self.child32 = QTreeWidgetItem(self.root3)
        self.child33 = QTreeWidgetItem(self.root3)
        self.child34 = QTreeWidgetItem(self.root3)
        self.child35 = QTreeWidgetItem(self.root3)
        self.child36 = QTreeWidgetItem(self.root3)
        self.child37 = QTreeWidgetItem(self.root3)
        self.child38 = QTreeWidgetItem(self.root3)
        self.child39 = QTreeWidgetItem(self.root3)
        self.child310 = QTreeWidgetItem(self.root3)
        self.child311 = QTreeWidgetItem(self.root3)
        self.child312 = QTreeWidgetItem(self.root3)
        self.child313 = QTreeWidgetItem(self.root3)
        self.child314 = QTreeWidgetItem(self.root3)
        self.child31.setText(0, _translate("MainWindow", "DCE 豆一(A)", None))
        self.child32.setText(0, _translate("MainWindow", "DCE 豆粕(M)", None))
        self.child33.setText(0, _translate("MainWindow", "DCE 豆油(Y)", None))
        self.child34.setText(0, _translate("MainWindow", "DCE 棕榈油(P)", None))
        self.child35.setText(0, _translate("MainWindow", "DCE 玉米(C)", None))
        self.child36.setText(0, _translate("MainWindow", "DCE 铁矿石(I)", None))
        self.child37.setText(0, _translate("MainWindow", "DCE 焦炭(JM)", None))
        self.child38.setText(0, _translate("MainWindow", "DCE PVC(V)", None))
        self.child39.setText(0, _translate("MainWindow", "DCE 豆二(B)", None))
        self.child310.setText(0, _translate("MainWindow", "DCE 鸡蛋(JD)", None))
        self.child311.setText(0, _translate("MainWindow", "DCE 纤维板(FB)", None))
        self.child312.setText(0, _translate("MainWindow", "DCE 胶合板(BB)", None))
        self.child313.setText(0, _translate("MainWindow", "DCE 聚丙烯(PP)", None))
        self.child314.setText(0, _translate("MainWindow", "DCE 玉米淀粉(CS)", None))
        self.child41 = QTreeWidgetItem(self.root4)
        self.child42 = QTreeWidgetItem(self.root4)
        self.child43 = QTreeWidgetItem(self.root4)
        self.child44 = QTreeWidgetItem(self.root4)
        self.child45 = QTreeWidgetItem(self.root4)
        self.child46 = QTreeWidgetItem(self.root4)
        self.child47 = QTreeWidgetItem(self.root4)
        self.child48 = QTreeWidgetItem(self.root4)
        self.child49 = QTreeWidgetItem(self.root4)
        self.child410 = QTreeWidgetItem(self.root4)
        self.child411 = QTreeWidgetItem(self.root4)
        self.child412 = QTreeWidgetItem(self.root4)
        self.child413 = QTreeWidgetItem(self.root4)
        self.child414 = QTreeWidgetItem(self.root4)
        self.child415 = QTreeWidgetItem(self.root4)
        self.child416 = QTreeWidgetItem(self.root4)
        self.child41.setText(0, _translate("MainWindow", "CZCE 强麦(WH)", None))
        self.child42.setText(0, _translate("MainWindow", "CZCE 菜油(OI)", None))
        self.child43.setText(0, _translate("MainWindow", "CZCE 棉花(CF)", None))
        self.child44.setText(0, _translate("MainWindow", "CZCE 白糖(SR)", None))
        self.child45.setText(0, _translate("MainWindow", "CZCE 早籼稻(RI)", None))
        self.child46.setText(0, _translate("MainWindow", "CZCE 动力煤(ZC)", None))
        self.child47.setText(0, _translate("MainWindow", "CZCE PTA(TA)", None))
        self.child48.setText(0, _translate("MainWindow", "CZCE 玻璃(FG)", None))
        self.child49.setText(0, _translate("MainWindow", "CZCE 甲醇(MA)", None))
        self.child410.setText(0, _translate("MainWindow", "CZCE 菜籽油(RM)", None))
        self.child411.setText(0, _translate("MainWindow", "CZCE 油菜籽(RS)", None))
        self.child412.setText(0, _translate("MainWindow", "CZCE 普麦(PM)", None))
        self.child413.setText(0, _translate("MainWindow", "CZCE 粳稻(JR)", None))
        self.child414.setText(0, _translate("MainWindow", "CZCE 晚籼稻(LR)", None))
        self.child415.setText(0, _translate("MainWindow", "CZCE 锰硅(SM)", None))
        self.child416.setText(0, _translate("MainWindow", "CZCE 硅铁(LR)", None))
        # self.treeWidget.addTopLevelItem(self.root)
        # self.treeWidget.addTopLevelItem(self.root)
        self.label_1.setText(_translate("MainWindow", "期货品种", None))
        self.label_2.setText(_translate("MainWindow", "起始时间", None))
        self.label_3.setText(_translate("MainWindow", "终止时间", None))
        self.button1.setText(_translate("MainWindow", "提交", None))
        self.button2.setText(_translate("MainWindow", "清除", None))
    def keyPressEvent(self, event):
        keyEvent = QKeyEvent(event)
        if keyEvent.key() == QtCore.Qt.Key_Enter or keyEvent.key() == QtCore.Qt.Key_Return:
            self.get_value()
        if keyEvent.key() == QtCore.Qt.Key_0:
            self.get_value()

    # 定义横坐标格式的回调函数
    def my_major_formatter(self, x, pos):
        for i in range(self.num):
            if (x == i):
                return self.str_date[i]

    def get_value(self):
        code = QtCore.QString(self.lineEdit.text())
        start = QtCore.QString(self.dateEdit.text())
        end = QtCore.QString(self.dateEdit_2.text())
        code = unicode(code)
        start = datetime.date(int(start.split("/")[0]), int(start.split("/")[1]), int(start.split("/")[2])).isoformat()
        end = datetime.date(int(end.split("/")[0]), int(end.split("/")[1]), int(end.split("/")[2])).isoformat()

        self.num, self.kbar, self.str_date, self.ema, self.name= source(code, start, end)
        self.star_date, self.star_value = star(col, code, start, end)
        self.update_figure()
    def update_figure(self):

        self.fig.clf()
        self.ax1 = self.fig.add_axes([0.22, 0.1, 0.7, 0.7])
        # self.ax2 = self.ax1.twinx()  # 创建第二个坐标轴,为同图
        # 子图一
        WindPy.w.start()
        self.ax1.set_xticks(range(self.num))
        xmajorLocator = MultipleLocator(5)  # 将x主刻度标签设置为3的倍数
        xminorLocator = MultipleLocator(1)  # 将x副刻度标签设置为1的倍数
        self.ax1.xaxis.set_major_locator(xmajorLocator)
        self.ax1.xaxis.set_minor_locator(xminorLocator)
        self.ax1.xaxis.set_major_formatter(FuncFormatter(self.my_major_formatter))
        self.ax1.grid()

        # self.ax2.bar(range(len(self.star_date)), self.star_value, picker=True, color='#FFFF00', width = 0.5,edgecolor = 'black')
        self.ax1.plot(range(self.num),self.ema,linewidth = 0.5,color = "blue")
        from matplotlib.font_manager import FontProperties
        font = FontProperties(size=14)  # 设置字体
        self.ax1.set_title(self.name)
        self.ax1.set_ylabel(u'价格')
        # self.ax2.set_ylabel(u'星数')
        #极端情况1
        # high_1 = self.kbar[0][2]
        # low_1 = self.kbar[0][3]
        # ema_1 = self.ema[0]
        # deviate_1 = max(abs(high_1 - ema_1),abs(low_1 - ema_1))
        # high_2 = self.kbar[1][2]
        # low_2 = self.kbar[1][3]
        # ema_2 = self.ema[1]
        # deviate_2 = max(abs(high_2 - ema_2),abs(low_2 - ema_2))
        # high_3 = self.kbar[2][2]
        # low_3 = self.kbar[2][3]
        # ema_3 = self.ema[2]
        # deviate_3 = max(abs(high_3 - ema_3),abs(low_3 - ema_3))
        # high_4 = self.kbar[3][2]
        # low_4 = self.kbar[3][3]
        # ema_4 = self.ema[3]
        # deviate_4 = max(abs(high_4 - ema_4),abs(low_4 - ema_4))
        # high_5 = self.kbar[4][2]
        # low_5 = self.kbar[4][3]
        # ema_5 = self.ema[4]
        # deviate_5 = max(abs(high_5 - ema_5),abs(low_5 - ema_5))
        # high_6 = self.kbar[5][2]
        # low_6 = self.kbar[5][3]
        # ema_6 = self.ema[5]
        # deviate_6 = max(abs(high_6 - ema_6),abs(low_6 - ema_6))
        # for i in range(6,self.num):
        #     high_7 = self.kbar[i][2]
        #     low_7 = self.kbar[i][3]
        #     ema_7 = self.ema[i]
        #     deviate_7 = max(abs(high_7 - ema_7),abs(low_7 - ema_7))
        #     condition1 = deviate_5 > deviate_3 > deviate_2 > deviate_1 or deviate_4 > deviate_3 > deviate_2 > deviate_1
        #     condition2 = ema_5 > ema_4 > ema_3 > ema_2 > ema_1 or ema_1 > ema_2 > ema_3 > ema_4 > ema_5
        #     condition3 = deviate_5 > deviate_6 > deviate_7
        #     if condition1 and condition2 and condition3 :
        #         self.ax1.annotate('E', xy=(i, low_7), xytext=(i+ 1, low_7+0.5), arrowprops=dict(arrowstyle="->"))
        #     deviate_1 = deviate_2
        #     deviate_2 = deviate_3
        #     deviate_3 = deviate_4
        #     deviate_4 = deviate_5
        #     deviate_5 = deviate_6
        #     deviate_6 = deviate_7
        #     ema_1 = ema_2
        #     ema_2 = ema_3
        #     ema_3 = ema_4
        #     ema_4 = ema_5
        #     ema_5 = ema_6
        #     ema_6 = ema_7
        # 极端情况2
        high_1 = self.kbar[0][2]
        low_1 = self.kbar[0][3]
        ema_1 = self.ema[0]
        deviate_1 = max(abs(high_1 - ema_1),abs(low_1 - ema_1))
        high_2 = self.kbar[1][2]
        low_2 = self.kbar[1][3]
        ema_2 = self.ema[1]
        deviate_2 = max(abs(high_2 - ema_2),abs(low_2 - ema_2))
        high_3 = self.kbar[2][2]
        low_3 = self.kbar[2][3]
        ema_3 = self.ema[2]
        deviate_3 = max(abs(high_3 - ema_3),abs(low_3 - ema_3))
        high_4 = self.kbar[3][2]
        low_4 = self.kbar[3][3]
        ema_4 = self.ema[3]
        deviate_4 = max(abs(high_4 - ema_4), abs(low_4 - ema_4))
        high_5 = self.kbar[3][2]
        low_5 = self.kbar[3][3]
        ema_5 = self.ema[3]
        deviate_5 = max(abs(high_5 - ema_5), abs(low_5 - ema_5))
        lim = self.ax1.get_ylim()
        # distance = 0.3
        distance = (lim[1] - lim[0])/9
        for i in range(5,self.num):
            alpha = 1.10
            beta = 0.90
            high_6 = self.kbar[i][2]
            low_6 = self.kbar[i][3]
            ema_6 = self.ema[i]
            deviate_6 = max(abs(high_6 - ema_6),abs(low_6 - ema_6))
            condition1 = deviate_4 > deviate_3 > deviate_2 or deviate_4 > deviate_3 > deviate_1 or deviate_4 > deviate_2 > deviate_1
            condition2 = ema_4 > ema_3 > ema_2 or ema_2 > ema_3 > ema_4
            condition3 = deviate_4 > deviate_5 * beta and deviate_4 > deviate_6
            top = high_4 - ema_4
            bottom = ema_4 - low_4
            condition4 = (low_4 < low_5 * alpha and low_4 < low_6 and top < bottom) or (high_4 > high_5 * beta and high_4 > high_6 and top > bottom)
            condition5 = top < bottom
            condition6 = top > bottom
            condition7 = high_3 < ema_3 and high_4 < ema_4 and high_5 < ema_5 and high_6 > ema_6 * alpha
            condition8 = low_3 > ema_3 and low_4 > ema_4 and low_5 > ema_5 and low_6 < ema_6 * beta
            matplotlib.rcParams.update({'font.size': 9})
            if condition1 and condition2 and condition3 and condition4 and condition5 or condition7:
                self.ax1.annotate(u'多', xy=(i, low_6), xytext=(i-0.5, low_6 - distance), arrowprops=dict(arrowstyle="-"))
            if condition1 and condition2 and condition3 and condition4 and condition6 or condition8:
                self.ax1.annotate(u'空', xy=(i, high_6), xytext=(i-0.5, high_6 + distance), arrowprops=dict(arrowstyle="-"))
            deviate_1 = deviate_2
            deviate_2 = deviate_3
            deviate_3 = deviate_4
            deviate_4 = deviate_5
            deviate_5 = deviate_6
            ema_1 = ema_2
            ema_2 = ema_3
            ema_3 = ema_4
            ema_4 = ema_5
            ema_5 = ema_6
            low_1 = low_2
            low_2 = low_3
            low_3 = low_4
            low_4 = low_5
            low_5 = low_6
            high_1 = high_2
            high_2 = high_3
            high_3 = high_4
            high_4 = high_5
            high_5 = high_6
        # self.ax1.annotate('extreme', xy=(18, 16.8), xytext=(20, 16), arrowprops=dict(arrowstyle="->"))
        # self.ax2.set_ylim(0, 80)
        candlestick_ohlc(self.ax1, self.kbar, width=0.5, colorup='r', colordown='g')
        # self.ax1.hold(False)
        # self.ax2.hold(False)
        lim = self.ax1.get_ylim()
        self.ax1.set_ylim(lim[0] * 0.95, lim[1])
        for tick in self.ax1.xaxis.get_major_ticks():
            tick.label1.set_fontsize(8)
            tick.label1.set_rotation(75)
        for tick in self.ax1.yaxis.get_major_ticks():
            tick.label1.set_fontsize(8)
            tick.label1.set_rotation(30)
        # for tick in self.ax2.xaxis.get_major_ticks():
        #     tick.label1.set_fontsize(8)
        #     tick.label1.set_rotation(75)
        # for tick in self.ax2.yaxis.get_major_ticks():
        #     tick.label1.set_fontsize(8)
        #     tick.label1.set_rotation(30)
        # 子图二

        # self.ax2.set_xticks(range(self.num))
        # self.ax2.xaxis.set_major_locator(xmajorLocator)
        # self.ax2.xaxis.set_minor_locator(xminorLocator)
        # self.ax2.grid()
        # self.ax2.set_xticklabels(self.str_date, rotation=25, horizontalalignment='right')

        # self.ax2.bar(range(len(self.star_date)), self.star_value, picker=True, color='#FFFF00')
        # #self.ax2.xaxis.set_major_locator(xmajorLocator)
        # self.ax2.xaxis.set_major_formatter(FuncFormatter(self.my_major_formatter))
        # for label in self.ax2.get_xticklabels():
        #     label.set_picker(True)
        # for tick in self.ax2.xaxis.get_major_ticks():
        #     tick.label1.set_fontsize(5)
        #     tick.label1.set_rotation(90)
        # for tick in self.ax2.yaxis.get_major_ticks():
        #     tick.label1.set_fontsize(5)
        #     tick.label1.set_rotation(30)
        #
        self.draw()
        # self.fig.clf()


    def clear(self):
        self.fig.clf()
        self.ax1 = self.fig.add_axes([0.22, 0.1, 0.7, 0.7])
        # self.ax1 = self.fig.add_axes([0.1, 0.35, 0.8, 0.58])
        # self.ax2 = self.fig.add_axes([0.1, 0.07, 0.8, 0.2])
        self.draw()
Ejemplo n.º 14
0
class StudentForm(QDialog):
    def __init__(self, parent=None):
        super(StudentForm, self).__init__(parent)
        #self.setGeometry(50, 50, 820, 530)
        self.resize(530, 430)

        self.tabz = QTabWidget(self)
        self.tab1 = QWidget(self)
        self.tab2 = QWidget(self)
        self.tab3 = QWidget(self)
        self.tab4 = QWidget(self)

        #main form
        self.schno = QLabel("School Number")
        self.schnoData = QLineEdit()
        self.schnoData.setObjectName("schno")
        self.schnoData.setPlaceholderText("00000000")

        self.surname = QLabel("Surname")
        self.surnameData = QLineEdit()
        self.surnameData.setObjectName("surname")
        self.surnameData.setPlaceholderText("Surname")

        self.firstname = QLabel("Firstname")
        self.firstnameData = QLineEdit()
        self.firstnameData.setObjectName("firstname")
        self.firstnameData.setPlaceholderText("Firstname")

        self.middlename = QLabel("Middlename")
        self.middlenameData = QLineEdit()
        self.middlenameData.setObjectName("middlename")
        self.middlenameData.setPlaceholderText("middlename")

        self.soo = QLabel("State/Region of Origin")
        self.sooData = QLineEdit()
        self.sooData.setObjectName("soo")
        self.sooData.setPlaceholderText("Lagos")

        self.lga = QLabel("LGA/District")
        self.lgaData = QLineEdit()
        self.lgaData.setObjectName("lga")
        self.lgaData.setPlaceholderText("Ikeja")

        self.addr = QLabel("House Address")
        self.addrData = QTextEdit()
        self.addrData.setObjectName("addr")
        #self.addrData.setPlaceholderText("No. 12 Harrrison For Str., Ney York")

        self.dob = QLabel("Date of Birth")
        self.dobData = QDateEdit()
        self.dobData.setObjectName("dob")

        self.admit = QLabel("Date Admitted")
        self.admitData = QDateEdit()
        self.admitData.setObjectName("admit")

        self.pb = QPushButton()
        self.pb.setObjectName("Submit")
        self.pb.setText("Submit")

        self.pb1 = QPushButton()
        self.pb1.setObjectName("Cancel")
        self.pb1.setText("Cancel")

        hbo = QHBoxLayout()
        self.gender = QLabel('Gender')
        self.r1 = QRadioButton('Male')
        self.r2 = QRadioButton('Female')
        hbo.addWidget(self.r1)
        hbo.addWidget(self.r2)

        Formlayout = QFormLayout()
        Formlayout.addRow(self.schno, self.schnoData)
        Formlayout.addRow(self.surname, self.surnameData)
        Formlayout.addRow(self.firstname, self.firstnameData)
        Formlayout.addRow(self.middlename, self.middlenameData)
        Formlayout.addRow(self.gender, hbo)
        Formlayout.addRow(self.dob, self.dobData)
        Formlayout.addRow(self.admit, self.admitData)
        Formlayout.addRow(self.soo, self.sooData)
        Formlayout.addRow(self.lga, self.lgaData)
        Formlayout.addRow(self.addr, self.addrData)

        grid = QGridLayout()
        grid.addWidget(self.pb1, 0, 1)
        grid.addWidget(self.pb, 0, 0)

        groupBox = QGroupBox('BIODATA')
        groupBox.setLayout(Formlayout)

        vbox = QVBoxLayout()
        vbox.addWidget(groupBox)
        vbox.addStretch()
        vbox.addLayout(grid)

        #self.setLayout(vbox)
        self.connect(self.pb, SIGNAL("clicked()"),
                     lambda: self.button_click(1))
        self.connect(self.pb1, SIGNAL("clicked()"), self.close)
        self.setWindowTitle("Student Data")
        #self.setTabText(0, 'BioData')
        self.tab1.setLayout(vbox)

        #guardian data
        relations = [
            'Father', 'Mother', 'Aunt', 'Uncle', 'Grand Parent', 'Guardian',
            'Others'
        ]

        #first guardian details
        self.g1name = QLabel("First Guardian")
        self.g1Data = QLineEdit()
        self.g1Data.setObjectName("g1name")
        self.g1Data.setPlaceholderText("Fullname")

        self.g1rel = QLabel('Relationship')
        self.g1relData = QComboBox()
        self.g1relData.addItems(relations)

        self.g1p1 = QLabel("Phone Number")
        self.g1p1Data = QLineEdit()
        self.g1p1Data.setObjectName("g1p1")
        self.g1p1Data.setPlaceholderText("08000000000")

        self.g1p2 = QLabel("Alt. Phone Number")
        self.g1p2Data = QLineEdit()
        self.g1p2Data.setObjectName("g1p2")
        self.g1p2Data.setPlaceholderText("08000000000")

        self.g1email = QLabel("Email")
        self.g1emailData = QLineEdit()
        self.g1emailData.setObjectName("g1email")
        self.g1emailData.setPlaceholderText("*****@*****.**")

        self.g1addr = QLabel("Address")
        self.g1addrData = QTextEdit()
        self.g1addrData.setObjectName("g1add")
        #self.g1addrData.setPlaceholderText("No. 12 Harrrison For Str., Ney York")
        #second guardian details
        self.g2name = QLabel("Second Guardian")
        self.g2Data = QLineEdit()
        self.g2Data.setObjectName("g2name")
        self.g2Data.setPlaceholderText("Mr. Surname Lastname")

        self.g2rel = QLabel('Relationship')
        self.g2relData = QComboBox()
        self.g2relData.addItems(relations)

        self.g2p1 = QLabel("Phone Number")
        self.g2p1Data = QLineEdit()
        self.g2p1Data.setObjectName("g2p1")
        self.g2p1Data.setPlaceholderText("08000000000")

        self.g2p2 = QLabel("Alt. Phone Number")
        self.g2p2Data = QLineEdit()
        self.g2p2Data.setObjectName("g2p2")
        self.g2p2Data.setPlaceholderText("08000000000")

        self.g2email = QLabel("Email")
        self.g2emailData = QLineEdit()
        self.g2emailData.setObjectName("g2email")
        self.g2emailData.setPlaceholderText("*****@*****.**")

        self.g2addr = QLabel("Address")
        self.g2addrData = QTextEdit()
        self.g2addrData.setObjectName("g2add")
        #self.g2addrData.setPlaceholderText("No. 12 Harrrison For Str., Ney York")

        self.pb = QPushButton()
        self.pb.setObjectName("Submit")
        self.pb.setText("Submit")

        self.pb1 = QPushButton()
        self.pb1.setObjectName("Cancel")
        self.pb1.setText("Cancel")

        hbo = QHBoxLayout()

        self.gender = QLabel('Gender')
        self.r1 = QRadioButton('Male')
        self.r2 = QRadioButton('Female')
        hbo.addWidget(self.r1)
        hbo.addWidget(self.r2)

        Formlayout1 = QFormLayout()
        Formlayout1.addRow(self.g1name, self.g1Data)
        Formlayout1.addRow(self.g1rel, self.g1relData)
        Formlayout1.addRow(self.g1p1, self.g1p1Data)
        Formlayout1.addRow(self.g1p2, self.g1p2Data)
        Formlayout1.addRow(self.g1email, self.g1emailData)
        Formlayout1.addRow(self.g1addr, self.g1addrData)

        Formlayout2 = QFormLayout()
        Formlayout2.addRow(self.g2name, self.g2Data)
        Formlayout2.addRow(self.g2rel, self.g2relData)
        Formlayout2.addRow(self.g2p1, self.g2p1Data)
        Formlayout2.addRow(self.g2p2, self.g2p2Data)
        Formlayout2.addRow(self.g2email, self.g2emailData)
        Formlayout2.addRow(self.g2addr, self.g2addrData)

        grid1 = QGridLayout()
        grid1.addWidget(self.pb, 0, 0)
        grid1.addWidget(self.pb1, 0, 1)

        hbox1 = QHBoxLayout()
        hbox1.addLayout(Formlayout1)
        hbox1.addLayout(Formlayout2)

        groupBox2 = QGroupBox('GUARDIAN')
        groupBox2.setLayout(hbox1)

        vbox1 = QVBoxLayout()
        vbox1.addWidget(groupBox2)
        vbox1.addStretch()
        vbox1.addLayout(grid1)

        #photo
        self.pic1 = QLabel()
        image1 = Image.open('img/studentz.png')
        self.pic1.resize(100, 150)
        self.pic1.setLabel(image1)

        self.pic2 = QLabel()
        image2 = Image.open('img/studentz.png')
        self.pic2.resize(100, 150)
        self.pic2.setPixmap(image2)

        self.pic3 = QLabel()
        image3 = Image.open('img/studentz.png')
        self.pic3.resize(100, 150)
        self.pic3.setPixmap(image3)

        self.picBtn1 = QPushButton('Select Image')
        self.picBtn1.clicked.connect(self.getFilez)

        self.picBtn2 = QPushButton('Select Image')
        self.picBtn2.clicked.connect(self.getFilez)

        self.picBtn3 = QPushButton('Select Image')
        self.picBtn3.clicked.connect(self.getFilez)

        picGrid = QGridLayout()

        picGrid.addWidget(self.pic1, 0, 1)
        picGrid.addWidget(self.pic2, 0, 2)
        picGrid.addWidget(self.pic3, 0, 3)

        picGrid.addWidget(self.picBtn1, 1, 1)
        picGrid.addWidget(self.picBtn2, 2, 2)
        picGrid.addWidget(self.picBtn3, 3, 3)

        self.tabz.addTab(self.tab1, 'Bio-Data')
        self.tabz.addTab(self.tab2, 'Contact Details')
        self.tabz.addTab(self.tab3, 'Passports')

        #self.tabz.setTabEnabled(1, False)
        #self.tabz.setTabEnabled(2, False)

        self.setWindowTitle("Add Student Data")
        self.show()

    def getFile(self, a):
        fname = QFileDialog.getOpenFileName(self, 'Open', 'c:\\',
                                            "Image File (*.jpg *.png)")
        if a == 1:
            self.pic1.setPixmap(QPixmap(fname))
        elif a == 2:
            self.pic2.setPixmap(QPixmap(fname))
        elif a == 2:
            self.pic3.setPixmap(QPixmap(fname))

    def getFilez(self):
        fname = QFileDialog.getOpenFileName(self, 'Open', 'c:\\',
                                            "Image File (*.jpg *.png)")
        self.pic1.setPixmap(QPixmap(fname))

    def contFill(self, a):

        sid = a
        data = self.pullStudents(a)
        self.resize(430, 530)

        #self.tabz = QTabWidget(self)
        self.tabz.clear()

        self.tab1 = QWidget(self)
        self.tab2 = QWidget(self)
        self.tab3 = QWidget(self)

        self.schno = QLabel("School Number")
        self.schnoData = QLineEdit()
        self.schnoData.setObjectName("schno")
        if (data['schno'] and len(data['schno']) > 1):
            self.schnoData.setText(data['schno'])
        else:
            self.schnoData.setPlaceholderText("00000000")

        self.surname = QLabel("Surname")
        self.surnameData = QLineEdit()
        self.surnameData.setObjectName("surname")
        if (data['surname'] and len(data['surname']) > 1):
            tx = data['surname']
            self.surnameData.setText(tx.title())
        else:
            self.surnameData.setPlaceholderText("Surname")

        self.firstname = QLabel("Firstname")
        self.firstnameData = QLineEdit()
        self.firstnameData.setObjectName("firstname")
        if (data['firstname'] and len(data['firstname'])):
            tx = data['firstname']
            self.firstnameData.setText(tx.title())
        else:
            self.firstnameData.setPlaceholderText("Firstname")

        self.middlename = QLabel("Middlename")
        self.middlenameData = QLineEdit()
        self.middlenameData.setObjectName("middlename")
        if (data['othername'] and len(data['othername']) > 1):
            tx = data['othername']
            self.middlenameData.setText(tx.title())
        else:
            self.middlenameData.setPlaceholderText("othername")

        self.soo = QLabel("State/Region of Origin")
        self.sooData = QLineEdit()
        self.sooData.setObjectName("soo")
        if (data['soo'] and len(data['soo']) > 1):
            tx = data['soo']
            self.sooData.setText(tx.title())
        else:
            self.sooData.setPlaceholderText("Lagos")

        self.lga = QLabel("LGA/District")
        self.lgaData = QLineEdit()
        self.lgaData.setObjectName("lga")
        if (data['lga'] and len(data['lga'])):
            tx = data['lga']
            self.lgaData.setText(tx.title())
        else:
            self.lgaData.setPlaceholderText("Ikeja")

        self.addr = QLabel("House Address")
        self.addrData = QTextEdit()
        self.addrData.setObjectName("addr")
        if (data['addr'] and len(data['addr'])):
            tx = data['addr']
            self.addrData.setText(tx)
        else:
            pass

        self.dob = QLabel("Date of Birth")
        self.dobData = QDateEdit()
        self.dobData.setObjectName("dob")
        tx = QDate.fromString(data['dob'], 'yyyy-MM-dd')
        self.dobData.setDate(QDate(tx.year(), tx.month(), tx.day()))

        self.admit = QLabel("Date Admitted")
        self.admitData = QDateEdit()
        self.admitData.setObjectName("admit")
        tx = QDate.fromString(data['admit'], 'yyyy-MM-dd')
        self.admitData.setDate(QDate(tx.year(), tx.month(), tx.day()))

        self.pb4 = QPushButton()
        self.pb4.setObjectName("Submit")
        self.pb4.setText("Submit")

        self.pb5 = QPushButton()
        self.pb5.setObjectName("Cancel")
        self.pb5.setText("Cancel")

        hbo = QHBoxLayout()
        self.gender = QLabel('Gender')
        self.r1 = QRadioButton('Male')
        self.r2 = QRadioButton('Female')
        if (data['gender'] == 'Male'):
            self.r1.setChecked(True)
        elif (data['gender'] == 'Female'):
            self.r2.setChecked(True)

        hbo.addWidget(self.r1)
        hbo.addWidget(self.r2)

        Formlayout = QFormLayout()
        Formlayout.addRow(self.schno, self.schnoData)
        Formlayout.addRow(self.surname, self.surnameData)
        Formlayout.addRow(self.firstname, self.firstnameData)
        Formlayout.addRow(self.middlename, self.middlenameData)
        Formlayout.addRow(self.gender, hbo)
        Formlayout.addRow(self.dob, self.dobData)
        Formlayout.addRow(self.admit, self.admitData)
        Formlayout.addRow(self.soo, self.sooData)
        Formlayout.addRow(self.lga, self.lgaData)
        Formlayout.addRow(self.addr, self.addrData)

        grid = QGridLayout()
        grid.addWidget(self.pb1, 0, 1)
        grid.addWidget(self.pb, 0, 0)

        groupBox = QGroupBox('BIODATA')
        groupBox.setLayout(Formlayout)

        vbox = QVBoxLayout()
        vbox.addWidget(groupBox)
        vbox.addStretch()
        vbox.addLayout(grid)

        #self.setLayout(vbox)
        self.connect(self.pb4, SIGNAL("clicked()"),
                     lambda: self.button1_click(sid))
        self.connect(self.pb5, SIGNAL("clicked()"), self.close)
        self.tab1.setLayout(vbox)

        relations = [
            'Father', 'Mother', 'Aunt', 'Uncle', 'Grand Parent', 'Guardian',
            'Others'
        ]

        #first guardian details
        self.g1name = QLabel("First Guardian")
        self.g1Data = QLineEdit()
        self.g1Data.setObjectName("g1name")
        if (data['g1'] and len(data['g1']) > 1):
            tx = data['g1']
            self.g1Data.setText(tx.title())
        else:
            self.g1Data.setPlaceholderText("Mr. Surname Lastname")

        self.g1rel = QLabel('Relationship')
        self.g1relData = QComboBox()
        self.g1relData.addItems(relations)
        if data['g1rel'] and len(data['g1rel']) > 0:
            index1 = self.g1relData.findText(data['g1rel'],
                                             Qt.QtMatchFixedString)
            if index1 >= 0:
                self.g1relData.setCurrentIndex(index1)

        self.g1p1 = QLabel("Phone Number")
        self.g1p1Data = QLineEdit()
        self.g1p1Data.setObjectName("g1p1")
        if (data['g1p1'] and len(data['g1p1']) > 1):
            tx = data['g1p1']
            self.g1p1Data.setText(tx.title())
        else:
            self.g1p1Data.setPlaceholderText("08000000000")

        self.g1p2 = QLabel("Alt. Phone Number")
        self.g1p2Data = QLineEdit()
        self.g1p2Data.setObjectName("g1p2")
        if (data['g1p2'] and len(data['g1p2']) > 1):
            tx = data['g1p2']
            self.g1p2Data.setText(tx.title())
        else:
            self.g1p2Data.setPlaceholderText("08000000000")

        self.g1email = QLabel("Email")
        self.g1emailData = QLineEdit()
        self.g1emailData.setObjectName("g1email")
        if (data['g1email'] and len(data['g1email']) > 1):
            tx = data['g1email']
            self.g1Data.setText(tx.title())
        else:
            self.g1Data.setPlaceholderText("*****@*****.**")

        self.g1addr = QLabel("Address")
        self.g1addrData = QTextEdit()
        self.g1addrData.setObjectName("g1add")
        if (data['g1addr'] and len(data['g1addr']) > 1):
            tx = data['g1addr']
            self.g1Data.setText(tx.title())
        else:
            pass

        #second guardian details
        self.g2name = QLabel("Second Guardian")
        self.g2Data = QLineEdit()
        self.g2Data.setObjectName("g2name")
        if (data['g2'] and len(data['g2']) > 1):
            tx = data['g2']
            self.g2Data.setText(tx.title())
        else:
            self.g2Data.setPlaceholderText("Title. Surname Lastname")

        self.g2rel = QLabel('Relationship')
        self.g2relData = QComboBox()
        self.g2relData.addItems(relations)
        if data['g2rel'] and len(data['g2rel']) > 0:
            index2 = self.g2relData.findText(data['g2rel'],
                                             Qt.QtMatchFixedString)
            if index2 >= 0:
                self.g2relData.setCurrentIndex(index2)

        self.g2p1 = QLabel("Phone Number")
        self.g2p1Data = QLineEdit()
        self.g2p1Data.setObjectName("g2p1")
        if (data['g2p1'] and len(data['g2p1']) > 1):
            tx = data['g2p1']
            self.g2p1Data.setText(tx.title())
        else:
            self.g2p1Data.setPlaceholderText("08000000000")

        self.g2p2 = QLabel("Alt. Phone Number")
        self.g2p2Data = QLineEdit()
        self.g2p2Data.setObjectName("g2p2")
        if (data['g2p2'] and len(data['g2p2']) > 1):
            tx = data['g2p2']
            self.g2p2Data.setText(tx.title())
        else:
            self.g2p2Data.setPlaceholderText("0800000000")

        self.g2email = QLabel("Email")
        self.g2emailData = QLineEdit()
        self.g2emailData.setObjectName("g2email")
        if (data['g2email'] and len(data['g2email']) > 1):
            tx = data['g2email']
            self.g2emailData.setText(tx.title())
        else:
            self.g2emailData.setPlaceholderText("*****@*****.**")

        self.g2addr = QLabel("Address")
        self.g2addrData = QTextEdit()
        self.g2addrData.setObjectName("g2add")
        if (data['g2addr'] and len(data['g2addr']) > 1):
            tx = data['g2addr']
            self.g2Data.setText(tx.title())
        else:
            pass

        self.pb = QPushButton()
        self.pb.setObjectName("Submit")
        self.pb.setText("Submit")

        self.pb1 = QPushButton()
        self.pb1.setObjectName("Cancel")
        self.pb1.setText("Cancel")

        hbo = QHBoxLayout()

        self.gender = QLabel('Gender')
        self.r1 = QRadioButton('Male')
        self.r2 = QRadioButton('Female')
        hbo.addWidget(self.r1)
        hbo.addWidget(self.r2)

        Formlayout1 = QFormLayout()
        Formlayout1.addRow(self.g1name, self.g1Data)
        Formlayout1.addRow(self.g1rel, self.g1relData)
        Formlayout1.addRow(self.g1p1, self.g1p1Data)
        Formlayout1.addRow(self.g1p2, self.g1p2Data)
        Formlayout1.addRow(self.g1email, self.g1emailData)
        Formlayout1.addRow(self.g1addr, self.g1addrData)

        Formlayout2 = QFormLayout()
        Formlayout2.addRow(self.g2name, self.g2Data)
        Formlayout2.addRow(self.g2rel, self.g2relData)
        Formlayout2.addRow(self.g2p1, self.g2p1Data)
        Formlayout2.addRow(self.g2p2, self.g2p2Data)
        Formlayout2.addRow(self.g2email, self.g2emailData)
        Formlayout2.addRow(self.g2addr, self.g2addrData)

        grid1 = QGridLayout()
        grid1.addWidget(self.pb, 0, 0)
        grid1.addWidget(self.pb1, 0, 1)

        hbox1 = QHBoxLayout()
        hbox1.addLayout(Formlayout1)
        hbox1.addStretch()
        hbox1.addLayout(Formlayout2)

        groupBox2 = QGroupBox('GUARDIAN')
        groupBox2.setLayout(hbox1)

        vbox1 = QVBoxLayout()
        vbox1.addWidget(groupBox2)
        vbox1.addStretch()
        vbox1.addLayout(grid1)

        self.tab2.setLayout(vbox1)

        #photo
        picstyle = QSize(120, 180)
        picstyle1 = Qt.KeepAspectRatio

        self.pic1Lbl = QLabel('YEAR 1 & 2')
        self.pic2Lbl = QLabel('YEAR 3 & 4')
        self.pic3Lbl = QLabel('YEAR 5 & 6')

        self.pic1 = QLabel()
        pixmap1 = QPixmap('img/studentz.png').scaled(picstyle, picstyle1)
        self.pic1.setPixmap(pixmap1)

        self.pic2 = QLabel()
        pixmap2 = QPixmap('img/studentz.png').scaled(picstyle, picstyle1)
        self.pic2.setPixmap(pixmap2)

        self.pic3 = QLabel()
        pixmap3 = QPixmap('img/studentz.png').scaled(picstyle, picstyle1)
        self.pic3.setPixmap(pixmap3)

        self.picBtn1 = QPushButton('Select Image')
        self.picBtn1.clicked.connect(self.getFilez)

        self.picBtn2 = QPushButton('Select Image')
        self.picBtn2.clicked.connect(self.getFilez)

        self.picBtn3 = QPushButton('Select Image')
        self.picBtn3.clicked.connect(self.getFilez)

        self.pic1Lbl.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        self.pic2Lbl.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        self.pic3Lbl.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)

        self.picBtn1.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        self.picBtn2.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        self.picBtn3.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)

        h1pic = QVBoxLayout()
        h2pic = QVBoxLayout()
        h3pic = QVBoxLayout()
        vpic = QHBoxLayout()

        h1pic.addWidget(self.pic1Lbl)
        h1pic.addStretch(0)
        h1pic.addWidget(self.pic1)
        h1pic.addStretch(0)
        h1pic.addWidget(self.picBtn1)
        h1pic.setContentsMargins(0, 0, 0, 0)
        h1pic.setSpacing(0)
        h1pic.setMargin(0)

        h2pic.addWidget(self.pic2Lbl)
        h2pic.addStretch(0)
        h2pic.addWidget(self.pic2)
        h2pic.addStretch(0)
        h2pic.addWidget(self.picBtn2)
        h2pic.setContentsMargins(0, 0, 0, 0)
        h2pic.setSpacing(0)
        h2pic.setMargin(0)

        h3pic.addWidget(self.pic3Lbl)
        h3pic.addStretch(0)
        h3pic.addWidget(self.pic3)
        h3pic.addStretch(0)
        h3pic.addWidget(self.picBtn3)
        h3pic.setContentsMargins(0, 0, 0, 0)
        h3pic.setSpacing(0)
        h3pic.setMargin(0)

        vpic.addLayout(h1pic)
        vpic.addStretch(0)
        vpic.addLayout(h2pic)
        vpic.addStretch(0)
        vpic.addLayout(h3pic)
        vpic.setSpacing(0)
        vpic.setMargin(0)
        vpic.setContentsMargins(0, 0, 0, 0)

        self.tab3.setLayout(vpic)
        self.tab3.resize(100, 100)
        #self.tab3.setStyleSheet("background-color: red; margin:5px; border:1px solid red;")

        self.tabz.addTab(self.tab1, 'Bio-Data')
        self.tabz.addTab(self.tab2, 'Contact Details')
        self.tabz.addTab(self.tab3, 'Passports')

        self.setWindowTitle("Add Student Data")
        self.show()

    def eContFill(self, a):

        sid = 23
        data = self.pullStudents(a)
        self.resize(430, 530)

        #self.tabz = QTabWidget(self)
        self.tabz.clear()

        self.tab1 = QWidget(self)
        self.tab2 = QWidget(self)
        self.tab3 = QWidget(self)

        self.schno = QLabel("School Number")
        self.schnoData = QLineEdit()
        self.schnoData.setObjectName("schno")
        if (data['schno'] and len(data['schno']) > 1):
            self.schnoData.setText(data['schno'])
        else:
            self.schnoData.setPlaceholderText("00000000")

        self.surname = QLabel("Surname")
        self.surnameData = QLineEdit()
        self.surnameData.setObjectName("surname")
        if (data['surname'] and len(data['surname']) > 1):
            tx = data['surname']
            self.surnameData.setText(tx.title())
        else:
            self.surnameData.setPlaceholderText("Surname")

        self.firstname = QLabel("Firstname")
        self.firstnameData = QLineEdit()
        self.firstnameData.setObjectName("firstname")
        if (data['firstname'] and len(data['firstname'])):
            tx = data['firstname']
            self.firstnameData.setText(tx.title())
        else:
            self.firstnameData.setPlaceholderText("Firstname")

        self.middlename = QLabel("Middlename")
        self.middlenameData = QLineEdit()
        self.middlenameData.setObjectName("middlename")
        if (data['othername'] and len(data['othername']) > 1):
            tx = data['othername']
            self.middlenameData.setText(tx.title())
        else:
            self.middlenameData.setPlaceholderText("othername")

        self.soo = QLabel("State/Region of Origin")
        self.sooData = QLineEdit()
        self.sooData.setObjectName("soo")
        if (data['soo'] and len(data['soo']) > 1):
            tx = data['soo']
            self.sooData.setText(tx.title())
        else:
            self.sooData.setPlaceholderText("Lagos")

        self.lga = QLabel("LGA/District")
        self.lgaData = QLineEdit()
        self.lgaData.setObjectName("lga")
        if (data['lga'] and len(data['lga'])):
            tx = data['lga']
            self.lgaData.setText(tx.title())
        else:
            self.lgaData.setPlaceholderText("Ikeja")

        self.addr = QLabel("House Address")
        self.addrData = QTextEdit()
        self.addrData.setObjectName("addr")
        if (data['addr'] and len(data['addr'])):
            tx = data['addr']
            self.addrData.setText(tx)
        else:
            pass

        self.dob = QLabel("Date of Birth")
        self.dobData = QDateEdit()
        self.dobData.setObjectName("dob")
        tx = QDate.fromString(data['dob'], 'yyyy-MM-dd')
        self.dobData.setDate(QDate(tx.year(), tx.month(), tx.day()))

        self.admit = QLabel("Date Admitted")
        self.admitData = QDateEdit()
        self.admitData.setObjectName("admit")
        tx = QDate.fromString(data['admit'], 'yyyy-MM-dd')
        self.admitData.setDate(QDate(tx.year(), tx.month(), tx.day()))

        self.pb4 = QPushButton()
        self.pb4.setObjectName("Submit")
        self.pb4.setText("Submit")

        self.pb5 = QPushButton()
        self.pb5.setObjectName("Cancel")
        self.pb5.setText("Cancel")

        hbo = QHBoxLayout()
        self.gender = QLabel('Gender')
        self.r1 = QRadioButton('Male')
        self.r2 = QRadioButton('Female')
        if (data['gender'] == 'Male'):
            self.r1.setChecked(True)
        elif (data['gender'] == 'Female'):
            self.r2.setChecked(True)

        hbo.addWidget(self.r1)
        hbo.addWidget(self.r2)

        Formlayout = QFormLayout()
        Formlayout.addRow(self.schno, self.schnoData)
        Formlayout.addRow(self.surname, self.surnameData)
        Formlayout.addRow(self.firstname, self.firstnameData)
        Formlayout.addRow(self.middlename, self.middlenameData)
        Formlayout.addRow(self.gender, hbo)
        Formlayout.addRow(self.dob, self.dobData)
        Formlayout.addRow(self.admit, self.admitData)
        Formlayout.addRow(self.soo, self.sooData)
        Formlayout.addRow(self.lga, self.lgaData)
        Formlayout.addRow(self.addr, self.addrData)

        grid = QGridLayout()
        grid.addWidget(self.pb1, 0, 1)
        grid.addWidget(self.pb, 0, 0)

        groupBox = QGroupBox('BIODATA')
        groupBox.setLayout(Formlayout)

        vbox = QVBoxLayout()
        vbox.addWidget(groupBox)
        vbox.addStretch()
        vbox.addLayout(grid)

        #self.setLayout(vbox)
        self.connect(self.pb4, SIGNAL("clicked()"),
                     lambda: self.button1_click(sid))
        self.connect(self.pb5, SIGNAL("clicked()"), self.close)
        self.tab1.setLayout(vbox)

        relations = [
            'Father', 'Mother', 'Aunt', 'Uncle', 'Grand Parent', 'Guardian',
            'Others'
        ]

        #first guardian details
        self.g1name = QLabel("First Guardian")
        self.g1Data = QLineEdit()
        self.g1Data.setObjectName("g1name")
        if (data['g1'] and len(data['g1']) > 1):
            tx = data['g1']
            self.g1Data.setText(tx.title())
        else:
            self.g1Data.setPlaceholderText("Mr. Surname Lastname")

        self.g1rel = QLabel('Relationship')
        self.g1relData = QComboBox()
        self.g1relData.addItems(relations)
        if data['g1rel'] and len(data['g1rel']) > 0:
            index1 = self.g1relData.findText(data['g1rel'],
                                             Qt.QtMatchFixedString)
            if index1 >= 0:
                self.g1relData.setCurrentIndex(index1)

        self.g1p1 = QLabel("Phone Number")
        self.g1p1Data = QLineEdit()
        self.g1p1Data.setObjectName("g1p1")
        if (data['g1p1'] and len(data['g1p1']) > 1):
            tx = data['g1p1']
            self.g1p1Data.setText(tx.title())
        else:
            self.g1p1Data.setPlaceholderText("08000000000")

        self.g1p2 = QLabel("Alt. Phone Number")
        self.g1p2Data = QLineEdit()
        self.g1p2Data.setObjectName("g1p2")
        if (data['g1p2'] and len(data['g1p2']) > 1):
            tx = data['g1p2']
            self.g1p2Data.setText(tx.title())
        else:
            self.g1p2Data.setPlaceholderText("08000000000")

        self.g1email = QLabel("Email")
        self.g1emailData = QLineEdit()
        self.g1emailData.setObjectName("g1email")
        if (data['g1email'] and len(data['g1email']) > 1):
            tx = data['g1email']
            self.g1Data.setText(tx.title())
        else:
            self.g1Data.setPlaceholderText("*****@*****.**")

        self.g1addr = QLabel("Address")
        self.g1addrData = QTextEdit()
        self.g1addrData.setObjectName("g1add")
        if (data['g1addr'] and len(data['g1addr']) > 1):
            tx = data['g1addr']
            self.g1Data.setText(tx.title())
        else:
            pass

        #second guardian details
        self.g2name = QLabel("Second Guardian")
        self.g2Data = QLineEdit()
        self.g2Data.setObjectName("g2name")
        if (data['g2'] and len(data['g2']) > 1):
            tx = data['g2']
            self.g2Data.setText(tx.title())
        else:
            self.g2Data.setPlaceholderText("Title. Surname Lastname")

        self.g2rel = QLabel('Relationship')
        self.g2relData = QComboBox()
        self.g2relData.addItems(relations)
        if data['g2rel'] and len(data['g2rel']) > 0:
            index2 = self.g2relData.findText(data['g2rel'],
                                             Qt.QtMatchFixedString)
            if index2 >= 0:
                self.g2relData.setCurrentIndex(index2)

        self.g2p1 = QLabel("Phone Number")
        self.g2p1Data = QLineEdit()
        self.g2p1Data.setObjectName("g2p1")
        if (data['g2p1'] and len(data['g2p1']) > 1):
            tx = data['g2p1']
            self.g2p1Data.setText(tx.title())
        else:
            self.g2p1Data.setPlaceholderText("08000000000")

        self.g2p2 = QLabel("Alt. Phone Number")
        self.g2p2Data = QLineEdit()
        self.g2p2Data.setObjectName("g2p2")
        if (data['g2p2'] and len(data['g2p2']) > 1):
            tx = data['g2p2']
            self.g2p2Data.setText(tx.title())
        else:
            self.g2p2Data.setPlaceholderText("0800000000")

        self.g2email = QLabel("Email")
        self.g2emailData = QLineEdit()
        self.g2emailData.setObjectName("g2email")
        if (data['g2email'] and len(data['g2email']) > 1):
            tx = data['g2email']
            self.g2emailData.setText(tx.title())
        else:
            self.g2emailData.setPlaceholderText("*****@*****.**")

        self.g2addr = QLabel("Address")
        self.g2addrData = QTextEdit()
        self.g2addrData.setObjectName("g2add")
        if (data['g2addr'] and len(data['g2addr']) > 1):
            tx = data['g2addr']
            self.g2Data.setText(tx.title())
        else:
            pass

        self.pb = QPushButton()
        self.pb.setObjectName("Submit")
        self.pb.setText("Submit")

        self.pb1 = QPushButton()
        self.pb1.setObjectName("Cancel")
        self.pb1.setText("Cancel")

        hbo = QHBoxLayout()

        self.gender = QLabel('Gender')
        self.r1 = QRadioButton('Male')
        self.r2 = QRadioButton('Female')
        hbo.addWidget(self.r1)
        hbo.addWidget(self.r2)

        Formlayout1 = QFormLayout()
        Formlayout1.addRow(self.g1name, self.g1Data)
        Formlayout1.addRow(self.g1rel, self.g1relData)
        Formlayout1.addRow(self.g1p1, self.g1p1Data)
        Formlayout1.addRow(self.g1p2, self.g1p2Data)
        Formlayout1.addRow(self.g1email, self.g1emailData)
        Formlayout1.addRow(self.g1addr, self.g1addrData)

        Formlayout2 = QFormLayout()
        Formlayout2.addRow(self.g2name, self.g2Data)
        Formlayout2.addRow(self.g2rel, self.g2relData)
        Formlayout2.addRow(self.g2p1, self.g2p1Data)
        Formlayout2.addRow(self.g2p2, self.g2p2Data)
        Formlayout2.addRow(self.g2email, self.g2emailData)
        Formlayout2.addRow(self.g2addr, self.g2addrData)

        grid1 = QGridLayout()
        grid1.addWidget(self.pb, 0, 0)
        grid1.addWidget(self.pb1, 0, 1)

        hbox1 = QHBoxLayout()
        hbox1.addLayout(Formlayout1)
        hbox1.addStretch()
        hbox1.addLayout(Formlayout2)

        groupBox2 = QGroupBox('GUARDIAN')
        groupBox2.setLayout(hbox1)

        vbox1 = QVBoxLayout()
        vbox1.addWidget(groupBox2)
        vbox1.addStretch()
        vbox1.addLayout(grid1)

        self.tab2.setLayout(vbox1)

        #photo
        picstyle = QSize(120, 180)
        picstyle1 = Qt.KeepAspectRatio

        self.pic1Lbl = QLabel('YEAR 1 & 2')
        self.pic2Lbl = QLabel('YEAR 3 & 4')
        self.pic3Lbl = QLabel('YEAR 5 & 6')

        self.pic1 = QLabel()
        pixmap1 = QPixmap('img/studentz.png').scaled(picstyle, picstyle1)
        self.pic1.setPixmap(pixmap1)

        self.pic2 = QLabel()
        pixmap2 = QPixmap('img/studentz.png').scaled(picstyle, picstyle1)
        self.pic2.setPixmap(pixmap2)

        self.pic3 = QLabel()
        pixmap3 = QPixmap('img/studentz.png').scaled(picstyle, picstyle1)
        self.pic3.setPixmap(pixmap3)

        self.picBtn1 = QPushButton('Select Image')
        self.picBtn1.clicked.connect(self.getFilez)

        self.picBtn2 = QPushButton('Select Image')
        self.picBtn2.clicked.connect(self.getFilez)

        self.picBtn3 = QPushButton('Select Image')
        self.picBtn3.clicked.connect(self.getFilez)

        self.pic1Lbl.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        self.pic2Lbl.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        self.pic3Lbl.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)

        self.picBtn1.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        self.picBtn2.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        self.picBtn3.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)

        h1pic = QVBoxLayout()
        h2pic = QVBoxLayout()
        h3pic = QVBoxLayout()
        vpic = QHBoxLayout()

        h1pic.addWidget(self.pic1Lbl)
        h1pic.addStretch(0)
        h1pic.addWidget(self.pic1)
        h1pic.addStretch(0)
        h1pic.addWidget(self.picBtn1)
        h1pic.setContentsMargins(0, 0, 0, 0)
        h1pic.setSpacing(0)
        h1pic.setMargin(0)

        h2pic.addWidget(self.pic2Lbl)
        h2pic.addStretch(0)
        h2pic.addWidget(self.pic2)
        h2pic.addStretch(0)
        h2pic.addWidget(self.picBtn2)
        h2pic.setContentsMargins(0, 0, 0, 0)
        h2pic.setSpacing(0)
        h2pic.setMargin(0)

        h3pic.addWidget(self.pic3Lbl)
        h3pic.addStretch(0)
        h3pic.addWidget(self.pic3)
        h3pic.addStretch(0)
        h3pic.addWidget(self.picBtn3)
        h3pic.setContentsMargins(0, 0, 0, 0)
        h3pic.setSpacing(0)
        h3pic.setMargin(0)

        vpic.addLayout(h1pic)
        vpic.addStretch(0)
        vpic.addLayout(h2pic)
        vpic.addStretch(0)
        vpic.addLayout(h3pic)
        vpic.setSpacing(0)
        vpic.setMargin(0)
        vpic.setContentsMargins(0, 0, 0, 0)

        self.tab3.setLayout(vpic)
        self.tab3.resize(100, 100)
        self.tab3.setStyleSheet(
            "background-color: red; margin:5px; border:1px solid red;")

        self.tabz.addTab(self.tab1, 'Bio-Data')
        self.tabz.addTab(self.tab2, 'Contact Details')
        self.tabz.addTab(self.tab3, 'Passports')

        self.setWindowTitle("Add Student Data")
        self.show()

    def button_click(self, a):
        # shost is a QString object
        arr = {}
        arr['schno'] = self.schnoData.text()
        arr['surname'] = self.surnameData.text()
        arr['firstname'] = self.firstnameData.text()
        arr['othername'] = self.middlenameData.text()
        arr['soo'] = self.sooData.text()
        arr['lga'] = self.lgaData.text()
        arr['addr'] = self.addrData.toPlainText()
        dob = self.dobData.date()
        arr['dob'] = dob.toPyDate()
        admit = self.admitData.date()
        arr['admit'] = admit.toPyDate()
        arr['active'] = 0
        if self.r1.isChecked():
            arr['gender'] = 0
        else:
            arr['gender'] = 1

        self.a = a

        g = Db()
        if ((arr['surname']) and (arr['firstname']) and (arr['schno'])):
            h = g.insert('students', arr)

        self.contFill(h)

    def button1_click(self, a):
        # shost is a QString object
        arr = {}
        arr['schno'] = self.schnoData.text()
        arr['surname'] = self.surnameData.text()
        arr['firstname'] = self.firstnameData.text()
        arr['othername'] = self.middlenameData.text()
        arr['soo'] = self.sooData.text()
        arr['lga'] = self.lgaData.text()
        arr['addr'] = self.addrData.toPlainText()
        dob = self.dobData.date()
        arr['dob'] = dob.toPyDate()
        admit = self.admitData.date()
        arr['admit'] = admit.toPyDate()
        arr['active'] = 0

        arr['g1'] = self.g1Data.text()
        arr['g1rel'] = self.g1relData.itemData(self.g1relData.currentIndex())
        arr['g1p1'] = self.g1p1Data.text()
        arr['g1p2'] = self.g1p2Data.text()
        arr['g1email'] = self.g1emailData.text()
        arr['g1addr'] = self.g1addData.text()
        arr['g2'] = self.g2Data.text()
        arr['g2rel'] = self.g2relData.itemData(self.g2relData.currentIndex())
        arr['g2p1'] = self.g2p1Data.text()
        arr['g2p2'] = self.g2p2Data.text()
        arr['g2email'] = self.g2emailData.text()
        arr['g2addr'] = self.g2addData.text()

        self.a = a
        print(arr)
        g = Db()
        if ((arr['surname']) and (arr['firstname']) and (arr['schno'])):
            r = g.update('students', arr, {'id': self.a})
        print(r)
        self.close()

    def button_click1(self, a):
        # shost is a QString object
        s1 = self.le.text()
        s2 = self.le2.text()
        self.a = a
        g = Db()
        if (len(s1) > 0):
            y = {'name': s1, 'subID': self.a, 'abbrv': s2}
            j = g.insert('datas', y)
            return j

    def pullClass(self, a):
        self.a = a
        cn = Db()
        students = cn.select('datas', '', '', {'subID': self.a})
        arr = {}

        for j in students:
            arr[j[0]] = j[2]
        return arr

    def pullStudents(self, a):
        self.a = a
        cn = Db()
        students = cn.selectn('students', '', 1, {'id': self.a})
        return students

    def lunchUnitForm(self, a):
        self.a = a

        self.form = UnitForm(self.a)
        self.form.show()
Ejemplo n.º 15
0
class TalkDetailsWidget(QWidget):

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

        self.layout = QGridLayout()
        self.setLayout(self.layout)

        self.buttonLayout = QHBoxLayout()

        saveIcon = QIcon.fromTheme("document-save")
        self.saveButton = QPushButton('Save Talk')
        self.saveButton.setIcon(saveIcon)
        self.buttonLayout.addWidget(self.saveButton)

        self.layout.addLayout(self.buttonLayout, 0, 1, 1, 1)

        self.titleLabel = QLabel('Title')
        self.titleLineEdit = QLineEdit()
        self.presenterLabel = QLabel('Presenter')
        self.presenterLineEdit = QLineEdit()
        self.layout.addWidget(self.titleLabel, 1, 0, 1, 1)
        self.layout.addWidget(self.titleLineEdit, 1, 1, 1, 1)
        self.layout.addWidget(self.presenterLabel, 1, 2, 1, 1)
        self.layout.addWidget(self.presenterLineEdit, 1, 3, 1, 1)

        self.eventLabel = QLabel('Event')
        self.eventLineEdit = QLineEdit()
        self.categoryLabel = QLabel('Category')
        self.categoryLineEdit = QLineEdit()

        self.layout.addWidget(self.eventLabel, 2, 0, 1, 1)
        self.layout.addWidget(self.eventLineEdit, 2, 1, 1, 1)
        self.layout.addWidget(self.categoryLabel, 2, 2, 1, 1)
        self.layout.addWidget(self.categoryLineEdit, 2, 3, 1, 1)

        self.roomLabel = QLabel('Room')
        self.roomLineEdit = QLineEdit()
        self.dateLayout = QHBoxLayout()
        self.dateLabel = QLabel('Date')
        self.dateEdit = QDateEdit()
        currentDate = QDate()
        self.dateEdit.setDate(currentDate.currentDate())
        self.dateEdit.setCalendarPopup(True)

        self.layout.addWidget(self.roomLabel, 3, 0, 1, 1)
        self.layout.addWidget(self.roomLineEdit, 3, 1, 1, 1)
        self.dateLayout.addWidget(self.dateEdit)
        self.layout.addWidget(self.dateLabel, 3, 2, 1, 1)
        self.layout.addLayout(self.dateLayout, 3, 3, 1, 1)

        self.startTimeLayout = QHBoxLayout()
        self.startTimeLabel = QLabel('Start Time')
        self.startTimeEdit = QTimeEdit()
        self.startTimeLayout.addWidget(self.startTimeEdit)
        self.endTimeLayout = QHBoxLayout()
        self.endTimeLabel = QLabel('End Time')
        self.endTimeEdit = QTimeEdit()
        self.endTimeLayout.addWidget(self.endTimeEdit)

        self.layout.addWidget(self.startTimeLabel, 4, 0, 1, 1)
        self.layout.addLayout(self.startTimeLayout, 4, 1, 1, 1)
        self.layout.addWidget(self.endTimeLabel, 4, 2, 1, 1)
        self.layout.addLayout(self.endTimeLayout, 4, 3, 1, 1)

        self.descriptionLabel = QLabel('Description')
        self.descriptionLabel.setAlignment(Qt.AlignTop)
        self.descriptionTextEdit = QPlainTextEdit()
        self.layout.addWidget(self.descriptionLabel, 5, 0, 1, 1)
        self.layout.addWidget(self.descriptionTextEdit, 5, 1, 1, 3)

    def enable_input_fields(self):
            self.titleLineEdit.setPlaceholderText("Enter Talk Title")
            self.presenterLineEdit.setPlaceholderText("Enter Presenter Name")
            self.categoryLineEdit.setPlaceholderText("Enter Category Type")
            self.eventLineEdit.setPlaceholderText("Enter Event Name")
            self.roomLineEdit.setPlaceholderText("Enter Room Location")
            self.titleLineEdit.setEnabled(True)
            self.presenterLineEdit.setEnabled(True)
            self.categoryLineEdit.setEnabled(True)
            self.eventLineEdit.setEnabled(True)
            self.roomLineEdit.setEnabled(True)
            self.dateEdit.setEnabled(True)
            self.startTimeEdit.setEnabled(True)
            self.endTimeEdit.setEnabled(True)
            self.descriptionTextEdit.setEnabled(True)

    def disable_input_fields(self):
            self.titleLineEdit.setPlaceholderText("")
            self.presenterLineEdit.setPlaceholderText("")
            self.categoryLineEdit.setPlaceholderText("")
            self.eventLineEdit.setPlaceholderText("")
            self.roomLineEdit.setPlaceholderText("")
            self.titleLineEdit.setEnabled(False)
            self.presenterLineEdit.setEnabled(False)
            self.categoryLineEdit.setEnabled(False)
            self.eventLineEdit.setEnabled(False)
            self.roomLineEdit.setEnabled(False)
            self.dateEdit.setEnabled(False)
            self.startTimeEdit.setEnabled(False)
            self.endTimeEdit.setEnabled(False)
            self.descriptionTextEdit.setEnabled(False)
Ejemplo n.º 16
0
class QtDateSelector(QtBoundedDate, ProxyDateSelector):
    """ A Qt implementation of an Enaml ProxyDateSelector.

    """
    #: A reference to the widget created by the proxy.
    widget = Typed(QDateEdit)

    #--------------------------------------------------------------------------
    # Initialization API
    #--------------------------------------------------------------------------
    def create_widget(self):
        """ Create the QDateEdit widget.

        """
        self.widget = QDateEdit(self.parent_widget())

    def init_widget(self):
        """ Initialize the widget.

        """
        super(QtDateSelector, self).init_widget()
        d = self.declaration
        self.set_date_format(d.date_format)
        self.set_calendar_popup(d.calendar_popup)
        self.widget.dateChanged.connect(self.on_date_changed)

    #--------------------------------------------------------------------------
    # Abstract API Implementation
    #--------------------------------------------------------------------------
    def get_date(self):
        """ Return the current date in the control.

        Returns
        -------
        result : date
            The current control date as a date object.

        """
        return self.widget.date().toPyDate()

    def set_minimum(self, date):
        """ Set the widget's minimum date.

        Parameters
        ----------
        date : date
            The date object to use for setting the minimum date.

        """
        self.widget.setMinimumDate(date)

    def set_maximum(self, date):
        """ Set the widget's maximum date.

        Parameters
        ----------
        date : date
            The date object to use for setting the maximum date.

        """
        self.widget.setMaximumDate(date)

    def set_date(self, date):
        """ Set the widget's current date.

        Parameters
        ----------
        date : date
            The date object to use for setting the date.

        """
        self._guard |= CHANGED_GUARD
        try:
            self.widget.setDate(date)
        finally:
            self._guard &= ~CHANGED_GUARD

    def set_date_format(self, format):
        """ Set the widget's date format.

        Parameters
        ----------
        format : str
            A Python time formatting string.

        """
        # XXX make sure Python's and Qt's format strings are the
        # same, or convert between the two.
        self.widget.setDisplayFormat(format)

    def set_calendar_popup(self, popup):
        """ Set whether a calendar popup is available on the widget.

        Parameters
        ----------
        popup : bool
            Whether the calendar popup is enabled.

        """
        self.widget.setCalendarPopup(popup)
Ejemplo n.º 17
0
class TalkDetailsWidget(QWidget):
    def __init__(self, parent=None):
        super(TalkDetailsWidget, self).__init__(parent)

        self.layout = QGridLayout()
        self.setLayout(self.layout)

        self.buttonLayout = QHBoxLayout()

        saveIcon = QIcon.fromTheme("document-save")
        self.saveButton = QPushButton('Save Talk')
        self.saveButton.setIcon(saveIcon)
        self.buttonLayout.addWidget(self.saveButton)

        self.layout.addLayout(self.buttonLayout, 0, 1, 1, 1)

        self.titleLabel = QLabel('Title')
        self.titleLineEdit = QLineEdit()
        self.presenterLabel = QLabel('Presenter')
        self.presenterLineEdit = QLineEdit()
        self.layout.addWidget(self.titleLabel, 1, 0, 1, 1)
        self.layout.addWidget(self.titleLineEdit, 1, 1, 1, 1)
        self.layout.addWidget(self.presenterLabel, 1, 2, 1, 1)
        self.layout.addWidget(self.presenterLineEdit, 1, 3, 1, 1)

        self.eventLabel = QLabel('Event')
        self.eventLineEdit = QLineEdit()
        self.categoryLabel = QLabel('Category')
        self.categoryLineEdit = QLineEdit()

        self.layout.addWidget(self.eventLabel, 2, 0, 1, 1)
        self.layout.addWidget(self.eventLineEdit, 2, 1, 1, 1)
        self.layout.addWidget(self.categoryLabel, 2, 2, 1, 1)
        self.layout.addWidget(self.categoryLineEdit, 2, 3, 1, 1)

        self.roomLabel = QLabel('Room')
        self.roomLineEdit = QLineEdit()
        self.dateLayout = QHBoxLayout()
        self.dateLabel = QLabel('Date')
        self.dateEdit = QDateEdit()
        currentDate = QDate()
        self.dateEdit.setDate(currentDate.currentDate())
        self.dateEdit.setCalendarPopup(True)

        self.layout.addWidget(self.roomLabel, 3, 0, 1, 1)
        self.layout.addWidget(self.roomLineEdit, 3, 1, 1, 1)
        self.dateLayout.addWidget(self.dateEdit)
        self.layout.addWidget(self.dateLabel, 3, 2, 1, 1)
        self.layout.addLayout(self.dateLayout, 3, 3, 1, 1)

        self.startTimeLayout = QHBoxLayout()
        self.startTimeLabel = QLabel('Start Time')
        self.startTimeEdit = QTimeEdit()
        self.startTimeLayout.addWidget(self.startTimeEdit)
        self.endTimeLayout = QHBoxLayout()
        self.endTimeLabel = QLabel('End Time')
        self.endTimeEdit = QTimeEdit()
        self.endTimeLayout.addWidget(self.endTimeEdit)

        self.layout.addWidget(self.startTimeLabel, 4, 0, 1, 1)
        self.layout.addLayout(self.startTimeLayout, 4, 1, 1, 1)
        self.layout.addWidget(self.endTimeLabel, 4, 2, 1, 1)
        self.layout.addLayout(self.endTimeLayout, 4, 3, 1, 1)

        self.descriptionLabel = QLabel('Description')
        self.descriptionLabel.setAlignment(Qt.AlignTop)
        self.descriptionTextEdit = QPlainTextEdit()
        self.layout.addWidget(self.descriptionLabel, 5, 0, 1, 1)
        self.layout.addWidget(self.descriptionTextEdit, 5, 1, 1, 3)

    def enable_input_fields(self):
        self.titleLineEdit.setPlaceholderText("Enter Talk Title")
        self.presenterLineEdit.setPlaceholderText("Enter Presenter Name")
        self.categoryLineEdit.setPlaceholderText("Enter Category Type")
        self.eventLineEdit.setPlaceholderText("Enter Event Name")
        self.roomLineEdit.setPlaceholderText("Enter Room Location")
        self.titleLineEdit.setEnabled(True)
        self.presenterLineEdit.setEnabled(True)
        self.categoryLineEdit.setEnabled(True)
        self.eventLineEdit.setEnabled(True)
        self.roomLineEdit.setEnabled(True)
        self.dateEdit.setEnabled(True)
        self.startTimeEdit.setEnabled(True)
        self.endTimeEdit.setEnabled(True)
        self.descriptionTextEdit.setEnabled(True)

    def disable_input_fields(self):
        self.titleLineEdit.setPlaceholderText("")
        self.presenterLineEdit.setPlaceholderText("")
        self.categoryLineEdit.setPlaceholderText("")
        self.eventLineEdit.setPlaceholderText("")
        self.roomLineEdit.setPlaceholderText("")
        self.titleLineEdit.setEnabled(False)
        self.presenterLineEdit.setEnabled(False)
        self.categoryLineEdit.setEnabled(False)
        self.eventLineEdit.setEnabled(False)
        self.roomLineEdit.setEnabled(False)
        self.dateEdit.setEnabled(False)
        self.startTimeEdit.setEnabled(False)
        self.endTimeEdit.setEnabled(False)
        self.descriptionTextEdit.setEnabled(False)
Ejemplo n.º 18
0
class ExpensesDialog(QDialog):

    holdc = {}

    def __init__(self, session, parent=None):
        super(ExpensesDialog, self).__init__(parent)
        self.session = session
        session = self.pullOnes('session', session)
        self.sessionname = str(session['name']) + ' Session'
        self.pagetitle = self.sessionname
        self.tableFont = QFont('Century Gothic', 8)
        #self.tableFont.setFamily('Century Gothic')
        self.tableHeaderStyle = "::section {" "background-color: teal; color:white}"
        #pull all CA
        self.editID = 0
        self.hold_account = {}
        self.hold_expenses = {}
        self.hold_expensesGroup = {}

        from_label = QLabel('From:')
        to_label = QLabel('To:')
        self.fromData = QDateEdit()
        self.toData = QDateEdit()
        currentDate = QDate()
        self.fromData.setDate(currentDate.currentDate())
        self.fromData.setCalendarPopup(True)
        self.toData.setDate(currentDate.currentDate())
        self.toData.setCalendarPopup(True)
        self.pull_btn = QPushButton()
        self.pull_btn.setText("Load")
        h_pull_box = QHBoxLayout()
        h_pull_box.addWidget(from_label)
        h_pull_box.addWidget(self.fromData)
        h_pull_box.addWidget(to_label)
        h_pull_box.addWidget(self.toData)
        h_pull_box.addWidget(self.pull_btn)

        expensesGroup = self.pullGroupExpenses()
        account = self.pullAccount()

        self.expenseGroupText = QLabel('Category')
        self.expenseGroupData = QComboBox()
        self.expenseGroupData.currentIndexChanged.connect(self.reloadExpenses)
        self.expenseText = QLabel('Expenses')
        self.expenseData = QComboBox()
        self.amountText = QLabel('Amount')
        self.amountData = QLineEdit()
        self.amountData.setPlaceholderText('0000.00')
        self.tellerText = QLabel('Teller/Reciept No.')
        self.tellerData = QLineEdit()
        self.tellerData.setPlaceholderText('xxxxxxxxx')
        self.accountText = QLabel('Account')
        self.accountData = QComboBox()
        self.dateText = QLabel('Date')
        self.dateData = QDateEdit()
        self.dateData.setDate(currentDate.currentDate())
        self.dateData.setCalendarPopup(True)
        self.descriptionText = QLabel('Brief Description')
        self.descriptionData = QPlainTextEdit()
        self.descriptionData.move(200, 100)
        hboz = QHBoxLayout()
        self.gender = QLabel('State')
        self.r1 = QRadioButton('Expenses')
        self.r1.setChecked(True)
        self.r2 = QRadioButton('Refund')
        hboz.addWidget(self.r1)
        hboz.addWidget(self.r2)

        i = 0
        for a in expensesGroup:
            self.hold_expensesGroup[i] = a['id']
            tex = str(a['name']).upper()
            self.expenseGroupData.addItem(tex)
            i += 1

        i = 0
        exp_key = self.hold_expensesGroup[self.expenseGroupData.currentIndex()]
        expenses = self.pullExpenses(exp_key)
        for a in expenses:
            self.hold_expenses[i] = a['id']
            tex = str(a['name']).upper()
            self.expenseData.addItem(tex)
            i += 1

        i = 0
        for a in account:
            self.hold_account[i] = a['id']
            tex = str(a['name']).upper()
            self.accountData.addItem(tex)
            i += 1

        self.FormLayout = QFormLayout()
        self.FormLayout.addRow(self.expenseGroupText, self.expenseGroupData)
        self.FormLayout.addRow(self.expenseText, self.expenseData)
        self.FormLayout.addRow(self.accountText, self.accountData)
        self.FormLayout.addRow(self.tellerText, self.tellerData)
        self.FormLayout.addRow(self.amountText, self.amountData)
        self.FormLayout.addRow(self.gender, hboz)
        self.FormLayout.addRow(self.dateText, self.dateData)
        self.FormLayout.addRow(self.descriptionText, self.descriptionData)

        groupBox1 = QGroupBox('Add Expenses')
        groupBox1.setLayout(self.FormLayout)

        self.pb = QPushButton()
        self.pb.setObjectName("Add")
        self.pb.setText("Add Expenses")

        self.pb1 = QPushButton()
        self.pb1.setObjectName("Edit")
        self.pb1.setText("Edit Row")
        self.pb1.setEnabled(False)

        self.pb2 = QPushButton()
        self.pb2.setObjectName("Close")
        self.pb2.setText("Close")

        self.pb3 = QPushButton()
        self.pb3.setObjectName("Delete")
        self.pb3.setText("Delete Row")
        self.pb3.setEnabled(False)

        self.pb4 = QPushButton()
        self.pb4.setObjectName("Reset")
        self.pb4.setText("Reset")
        self.pb4.hide()

        self.pb5 = QPushButton()
        self.pb5.setObjectName("Change")
        self.pb5.setText("Change Expenses")
        self.pb5.hide()

        self.pb6 = QPushButton()
        self.pb6.setObjectName("Clear")
        self.pb6.setText("Clear Selection")
        self.pb6.setEnabled(False)

        hbo = QHBoxLayout()
        hbo.addWidget(self.pb)
        hbo.addWidget(self.pb5)
        hbo.addWidget(self.pb4)
        hbo.addWidget(self.pb2)
        groupBox2 = QGroupBox('Expenses Data')
        groupBox2.setLayout(hbo)

        self.cols = ['SN', 'EXPENSES', 'ACCOUNT', 'AMOUNT', 'DATE']
        al = self.pullExpensesData()
        if len(al) > 0:
            al = al
        else:
            al = {}

        self.table = QTableWidget()
        header = self.table.horizontalHeader()
        header.setResizeMode(QHeaderView.ResizeToContents)
        header.setStretchLastSection(True)
        header.setStyleSheet(self.tableHeaderStyle)
        vheader = self.table.verticalHeader()
        vheader.setStyleSheet(self.tableHeaderStyle)
        # Body
        self.table.setWindowTitle("Expenses")
        self.table.resize(300, 250)
        self.table.setFont(self.tableFont)
        self.table.setSortingEnabled(2)
        #self.table.resizeColumnsToContents()
        self.table.setRowCount(len(al))
        self.table.setColumnCount(len(self.cols))
        self.table.setHorizontalHeaderLabels(self.cols)
        self.table.setContextMenuPolicy(Qt.CustomContextMenu)
        self.table.customContextMenuRequested.connect(self.handleHeaderMenu)
        self.table.hideColumn(0)
        self.table.setSelectionMode(QAbstractItemView.MultiSelection)
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)

        i = 0
        for q in al:
            #row id
            self.table.setItem(i, 0, QTableWidgetItem(str(q['id'])))
            self.table.setItem(i, 1,
                               QTableWidgetItem(str(q['expensename']).upper()))
            self.table.setItem(i, 2,
                               QTableWidgetItem(str(q['accountname']).upper()))
            zamt = str("{:,}".format(float(q['amount'])))
            self.table.setItem(i, 3, QTableWidgetItem(zamt))
            damz = float(q['datepaid'])
            damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y')
            self.table.setItem(i, 4, QTableWidgetItem(str(damt)))
            i += 1
        self.table.itemSelectionChanged.connect(self.confirmSelection)
        self.table.resizeRowsToContents()
        v_pull_box = QVBoxLayout()
        self.h1_pull_box = QVBoxLayout()
        self.h1_pull_box.addWidget(self.table)
        v_pull_box.addLayout(h_pull_box)
        v_pull_box.addLayout(self.h1_pull_box)
        h2_pull_box = QHBoxLayout()
        h2_pull_box.addWidget(self.pb1)
        h2_pull_box.addWidget(self.pb3)
        h2_pull_box.addWidget(self.pb6)
        v_pull_box.addLayout(h2_pull_box)

        groupBox3 = QGroupBox()
        groupBox3.setLayout(hbo)
        groupBox2.setLayout(v_pull_box)

        grid = QGridLayout()
        grid.addWidget(groupBox1, 0, 0)
        grid.addWidget(groupBox2, 0, 1, 2, 1)
        grid.addWidget(groupBox3, 1, 0)

        self.setLayout(grid)
        self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click())
        self.connect(self.pb1, SIGNAL("clicked()"),
                     lambda: self.button_editshow())
        self.connect(self.pb2, SIGNAL("clicked()"),
                     lambda: self.button_close(self))
        self.connect(self.pb3, SIGNAL("clicked()"),
                     lambda: self.button_delete())
        self.connect(self.pb4, SIGNAL("clicked()"),
                     lambda: self.button_reset())
        self.connect(self.pb5, SIGNAL("clicked()"), lambda: self.button_edit())
        self.connect(self.pb6, SIGNAL("clicked()"),
                     lambda: self.button_clear())
        self.connect(self.pull_btn,
                     SIGNAL("clicked()"),
                     lambda x=1: self.reloadTable(x))

        self.setWindowTitle(self.pagetitle)

    def handleHeaderMenu(self, pos):
        print('column(%d)' % self.table.horizontalHeader().logicalIndexAt(pos))
        menu = QMenu()
        menu.addAction('Add')
        menu.addAction('Delete')
        menu.exec_(QCursor.pos())

    def pullGroupExpenses(self):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"pubID": 15, "active": 0})
        return arr

    def pullExpenses(self, a):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"subID": a})
        return arr

    def pullAccount(self):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"pubID": 20, "active": 0})
        return arr

    def pullExpensesData(self):
        st_date = self.fromData.date().toPyDate()
        en_date = self.toData.date().toPyDate()
        st_date = time.mktime(st_date.timetuple())
        en_date = time.mktime(en_date.timetuple())

        db = 'school_expenses' + str(self.session)
        cn = Db()
        arr = cn.selectExpenseDate(db, st_date, en_date)
        return arr

    def mySelectTable(self):
        '''
        get the selected rpws in a table
        returns list or row ids
        '''
        sels = self.table.selectedIndexes()
        sels = self.table.selectionModel().selectedRows()

        park = []
        park1 = []
        for j in sels:
            park.append(j.row())

        for i in set(park):
            selected = self.table.item(i, 0).text()
            park1.append(selected)

        return park1

    def editRow(self, a):
        _session = self.session
        g = Db()
        db = 'school_expenses' + str(_session)
        data = g.selectn(db, '', 1, {'id': a})
        if len(data) > 0:
            self.editID = int(data['id'])
            if float(data['amount']) < 0:
                amt = float(data['amount']) * -1
                self.amountData.setText(str(amt))
                self.r1.setChecked(True)
            else:
                amt = float(data['amount'])
                self.amountData.setText(str(amt))
                self.r2.setChecked(True)

            self.descriptionData.clear()
            self.descriptionData.insertPlainText(str(data['description']))
            self.tellerData.setText(str(data['teller']))
            acID = self.hold_account.keys()[self.hold_account.values().index(
                data['accountID'])]
            self.accountData.setCurrentIndex(acID)
            exID = self.hold_expenses.keys()[self.hold_expenses.values().index(
                data['expenseID'])]
            self.expenseData.setCurrentIndex(exID)

    def reloadExpenses(self):
        cat = self.hold_expensesGroup[self.expenseGroupData.currentIndex()]
        expenses = self.pullExpenses(cat)
        self.expenseData.clear()
        self.hold_expenses = {}
        i = 0
        for a in expenses:
            self.hold_expenses[i] = a['id']
            tex = str(a['name']).upper()
            self.expenseData.addItem(tex)
            i += 1

    def reloadTable(self, a):
        data = self.pullExpensesData()
        self.table.close()
        self.table = QTableWidget()
        header = self.table.horizontalHeader()
        header.setResizeMode(QHeaderView.ResizeToContents)
        header.setStretchLastSection(True)
        header.setStyleSheet(self.tableHeaderStyle)
        vheader = self.table.verticalHeader()
        vheader.setStyleSheet(self.tableHeaderStyle)
        # Body
        self.table.setWindowTitle("Expenses")
        self.table.resize(300, 250)
        self.table.setFont(self.tableFont)
        self.table.setSortingEnabled(2)
        self.table.resizeColumnsToContents()
        self.table.setRowCount(len(data))
        self.table.setColumnCount(len(self.cols))
        self.table.setHorizontalHeaderLabels(self.cols)
        self.table.setContextMenuPolicy(Qt.CustomContextMenu)
        self.table.customContextMenuRequested.connect(self.handleHeaderMenu)
        self.table.hideColumn(0)
        self.table.setSelectionMode(QAbstractItemView.MultiSelection)
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        i = 0
        for q in data:
            #row id
            self.table.setItem(i, 0, QTableWidgetItem(str(q['id'])))
            self.table.setItem(i, 1,
                               QTableWidgetItem(str(q['expensename']).upper()))
            self.table.setItem(i, 2,
                               QTableWidgetItem(str(q['accountname']).upper()))
            zamt = str("{:,}".format(float(q['amount'])))
            self.table.setItem(i, 3, QTableWidgetItem(zamt))
            damz = float(q['datepaid'])
            damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y')
            self.table.setItem(i, 4, QTableWidgetItem(str(damt)))
            i += 1
        self.table.itemSelectionChanged.connect(self.confirmSelection)
        self.table.resizeRowsToContents()
        self.h1_pull_box.addWidget(self.table)
        self.table.show()

    def pullOnes(self, a, b):
        cn = Db()
        arr = cn.selectn(a, '', 1, {'id': b})
        return arr

    def confirmSelection(self):
        item = self.mySelectTable()
        if len(item) == 1:
            self.pb1.setEnabled(True)
            self.pb3.setEnabled(True)
            self.pb6.setEnabled(True)
        elif len(item) > 1:
            self.pb1.setEnabled(False)
            self.pb3.setEnabled(True)
            self.pb6.setEnabled(True)
        else:
            self.pb1.setEnabled(False)
            self.pb3.setEnabled(False)
            self.pb6.setEnabled(False)

    def button_close(self, b):
        b.close()

    def button_editshow(self):
        item = self.mySelectTable()
        self.editRow(item[0])
        self.pb.hide()
        self.pb4.show()
        self.pb5.show()

    def button_delete(self):
        item = self.mySelectTable()
        _session = self.session
        g = Db()
        db = 'school_expenses' + str(_session)
        for j in item:
            g.delete(db, {'id': j})

        self.reloadTable(1)

    def button_edit(self):
        _session = self.session
        _amount = self.amountData.text()
        _teller = self.tellerData.text()
        _date = self.dateData.date().toPyDate()
        _date = time.mktime(_date.timetuple())
        _description = self.descriptionData.toPlainText()
        _account = self.hold_account[self.accountData.currentIndex()]
        _expense = self.hold_expenses[self.expenseData.currentIndex()]
        if self.r1.isChecked():
            _amount = float(_amount)
        else:
            _amount = float(_amount) * -1

        arr = {}
        if _amount and not (_amount
                            == 0) and int(_expense) > 0 and int(_account) > 0:
            arr['amount'] = _amount
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['accountID'] = _account
            arr['expenseID'] = _expense
            arr['teller'] = _teller

            ups = {}
            ups['id'] = self.editID
            if int(self.editID) > 0:
                db = 'school_expenses' + str(_session)
                g = Db()
                g.update(db, arr, ups)
                if int(self.editID) > 0:
                    self.button_reset()

    def button_reset(self):
        self.reloadTable(1)
        self.amountData.setText('')
        self.descriptionData.clear()
        self.tellerData.setText('')
        self.pb4.hide()
        self.pb5.hide()
        self.pb.show()
        self.editID = 0
        self.button_clear()
        self.confirmSelection()

    def button_clear(self):
        self.table.selectionModel().clearSelection()

    def button_click(self):
        _session = self.session
        _amount = self.amountData.text()
        _teller = self.tellerData.text()
        _date = self.dateData.date().toPyDate()
        _date = time.mktime(_date.timetuple())
        _description = self.descriptionData.toPlainText()
        _account = self.hold_account[self.accountData.currentIndex()]
        _expense = self.hold_expenses[self.expenseData.currentIndex()]
        if self.r1.isChecked():
            _amount = float(_amount)
        else:
            _amount = float(_amount) * -1

        arr = {}
        if _amount and not (_amount
                            == 0) and int(_expense) > 0 and int(_account) > 0:
            arr['amount'] = _amount
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['accountID'] = _account
            arr['expenseID'] = _expense
            arr['teller'] = _teller

            db = 'school_expenses' + str(_session)
            g = Db()
            ins = g.insert(db, arr)
            if int(ins) > 0:
                self.button_reset()
Ejemplo n.º 19
0
class AddTalkWidget(QWidget):
    '''
    classdocs
    '''

    def __init__(self, parent=None):
        '''
        Constructor
        '''
        QWidget.__init__(self, parent)
        self.mainLayout = QVBoxLayout()
        self.setLayout(self.mainLayout)

        self.addTalkGroupBox = QGroupBox("Add Talk")
        self.mainLayout.addWidget(self.addTalkGroupBox)

        self.addTalkLayout = QFormLayout()
        self.addTalkGroupBox.setLayout(self.addTalkLayout)

        # Title
        self.titleLabel = QLabel("Title")
        self.titleLineEdit = QLineEdit()
        if hasattr(QLineEdit(), 'setPlaceholderText'):
            self.titleLineEdit.setPlaceholderText("Title of the presentation")
        self.titleLabel.setBuddy(self.titleLineEdit)
        self.addTalkLayout.addRow(self.titleLabel, self.titleLineEdit)

        # Presenter
        self.presenterLabel = QLabel("Presenter")
        self.presenterLineEdit = QLineEdit()
        if hasattr(QLineEdit(), 'setPlaceholderText'):
            self.presenterLineEdit.setPlaceholderText("Name person or people presenting (comma separated)")
        self.presenterLabel.setBuddy(self.presenterLineEdit)
        self.addTalkLayout.addRow(self.presenterLabel, self.presenterLineEdit)

        # Event
        self.eventLabel = QLabel("Event")
        self.eventLineEdit = QLineEdit()
        if hasattr(QLineEdit(), 'setPlaceholderText'):
            self.eventLineEdit.setPlaceholderText("The name of the Event this talk is being presented at")
        self.eventLabel.setBuddy(self.eventLineEdit)
        self.addTalkLayout.addRow(self.eventLabel, self.eventLineEdit)

        # Room
        self.roomLabel = QLabel("Room")
        self.roomLineEdit = QLineEdit()
        if hasattr(QLineEdit(), 'setPlaceholderText'):
            self.roomLineEdit.setPlaceholderText("The Room in which the presentation is taking place")
        self.roomLabel.setBuddy(self.roomLineEdit)
        self.addTalkLayout.addRow(self.roomLabel, self.roomLineEdit)

        # Date
        current_date = QDate()
        self.dateLabel = QLabel("Date")
        self.dateEdit = QDateEdit()
        self.dateEdit.setDate(current_date.currentDate())
        self.dateLabel.setBuddy(self.dateEdit)
        self.addTalkLayout.addRow(self.dateLabel, self.dateEdit)

        self.dateEdit.setCalendarPopup(True)

        # Time
        current_time = QTime()
        self.timeLabel = QLabel("Time")
        self.timeEdit = QTimeEdit()
        self.timeEdit.setTime(current_time.currentTime())
        self.timeLabel.setBuddy(self.dateEdit)
        self.addTalkLayout.addRow(self.timeLabel, self.timeEdit)

        # Buttons
        addIcon = QIcon.fromTheme("list-add")
        cancelIcon = QIcon.fromTheme("edit-clear")

        self.buttonsWidget = QHBoxLayout()
        self.addButton = QPushButton("Add")
        self.addButton.setIcon(addIcon)
        self.cancelButton = QPushButton("Cancel")
        self.cancelButton.setIcon(cancelIcon)
        self.buttonsWidget.addWidget(self.addButton)
        self.buttonsWidget.addWidget(self.cancelButton)
        self.addTalkLayout.addRow(None, self.buttonsWidget)
Ejemplo n.º 20
0
class LDSControls(QFrame):
        
    STATIC_IMG = ('error_static.png','linz_static.png','busy_static.png','clean_static.png')
    ANIM_IMG   = ('error.gif','linz.gif','layer.gif','clean.gif')
    
    IMG_SPEED  = 100
    IMG_WIDTH  = 64
    IMG_HEIGHT = 64
    
    MAX_WD = 450
    
    GD_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../../bin/gdal/gdal-data'))
    STATUS = LU.enum('ERROR','IDLE','BUSY','CLEAN')
    
    def __init__(self,parent):
        super(LDSControls, self).__init__()
        self.parent = parent
        self.initConf()
        self.initEPSG()
        self.initUI()
        
    def initConf(self):
        '''Read files in conf dir ending in conf'''
        self.cflist = ConfigInitialiser.getConfFiles()
        #self.imgset = self.STATIC_IMG if ConfigWrapper().readDSProperty('Misc','indicator')=='static' else self.ANIM_IMG
        #self.imgset = self.STATIC_IMG if self.parent.confconn.tp.src.confwrap.readDSProperty('Misc','indicator')=='static' else self.ANIM_IMG
        sep = self.parent.confconn.reg.openEndPoint(self.parent.confconn.SRCNAME,self.parent.confconn.uconf)
        self.imgset = self.STATIC_IMG if sep.confwrap.readDSProperty('Misc','indicator')=='static' else self.ANIM_IMG
        self.parent.confconn.reg.closeEndPoint(self.parent.confconn.SRCNAME)
        
    def initEPSG(self):
        '''Read GDAL EPSG files, splitting by NZ(RSR) and RestOfTheWorld'''

        gcsf = gdal.FindFile('gdal','gcs.csv') 
        if not gcsf:
            gcsf = os.path.join(self.GD_PATH,'gcs.csv')
        pcsf = gdal.FindFile('gdal','pcs.csv') 
        if not pcsf: 
            pcsf = os.path.join(self.GD_PATH,'pcs.csv')
        gcs = ConfigInitialiser.readCSV(gcsf)
        pcs = ConfigInitialiser.readCSV(pcsf)

        self.nzlsr = [(e[0],e[0]+' - '+e[3]) for e in gcs if 'NZGD'     in e[1] or  'RSRGD'     in e[1]] \
                   + [(e[0],e[0]+' - '+e[1]) for e in pcs if 'NZGD'     in e[1] or  'RSRGD'     in e[1]]
        self.rowsr = [(e[0],e[0]+' - '+e[3]) for e in gcs if 'NZGD' not in e[1] and 'RSRGD' not in e[1]] \
                   + [(e[0],e[0]+' - '+e[1]) for e in pcs if 'NZGD' not in e[1] and 'RSRGD' not in e[1]]
                   
                   
    def initUI(self):
        
        # 0      1          2       3       4       5      6    7    8
        #'destname','lgselect','layer','uconf','group','epsg','fd','td','int'
        
        #self.rdest,rlgselect,self.rlayer,ruconf,self.rgroup,repsg,rfd,rtd,rint = readlist 
        
        QToolTip.setFont(QFont('SansSerif', 10))
        
        #labels
        destLabel = QLabel('Destination')
        lgLabel = QLabel('Group/Layer')
        epsgLabel = QLabel('EPSG')
        fromDateLabel = QLabel('From Date')
        toDateLabel = QLabel('To Date')
        confLabel = QLabel('User Config')
        
        self.view = QLabel() 
        self.view.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.view.setAlignment(Qt.AlignCenter)

        self.confcombo = QComboBox(self)
        self.confcombo.setToolTip('Enter your user config name (file) here')
        self.confcombo.addItems(self.cflist)
        self.confcombo.setEditable(False)
        #self.confcombo.currentIndexChanged.connect(self.doLGEditUpdate)
        
        #combos
        self.lgcombo = QComboBox(self)
        self.lgcombo.setMaximumWidth(self.MAX_WD)
        self.lgcombo.setDuplicatesEnabled(False)
        #self.lgcombo.setInsertPolicy(QComboBox.InsertAlphabetically)#?doesnt seem to work
        self.lgcombo.setToolTip('Select either Layer or Group entry')
        self.lgcombo.setEditable(False)
        self.sepindex = None
        #self.updateLGValues()
        
        self.epsgcombo = QComboBox(self)
        self.epsgcombo.setMaximumWidth(self.MAX_WD)
        self.epsgcombo.setToolTip('Setting an EPSG number here determines the output SR of the layer')  
        self.epsgcombo.addItems([i[1] for i in self.nzlsr])
        self.epsgcombo.insertSeparator(len(self.nzlsr))
        self.epsgcombo.addItems([i[1] for i in self.rowsr])
        self.epsgcombo.setEditable(True)
        self.epsgcombo.setEnabled(False)
        
        self.destlist = self.getConfiguredDestinations()
        self.destcombo = QComboBox(self)
        self.destcombo.setToolTip('Choose the desired output type')   
        self.destcombo.setEditable(False)
        self.destcombo.addItems(self.destlist)

        #date selection
        self.fromdateedit = QDateEdit()
        self.fromdateedit.setCalendarPopup(True)
        self.fromdateedit.setEnabled(False)
        
        self.todateedit = QDateEdit()
        self.todateedit.setCalendarPopup(True)
        self.todateedit.setEnabled(False)
        
        #check boxes
        self.epsgenable = QCheckBox()
        self.epsgenable.setCheckState(False)
        self.epsgenable.clicked.connect(self.doEPSGEnable)       
        
        self.fromdateenable = QCheckBox()
        self.fromdateenable.setCheckState(False)
        self.fromdateenable.clicked.connect(self.doFromDateEnable)
        
        self.todateenable = QCheckBox()
        self.todateenable.setCheckState(False) 
        self.todateenable.clicked.connect(self.doToDateEnable)
        
        self.progressbar = QProgressBar()
        self.progressbar.setRange(0,100)
        self.progressbar.setVisible(True)
        self.progressbar.setMinimumWidth(self.MAX_WD)
        
        
        #buttons        
        self.initbutton = QPushButton("waiting")
        self.initbutton.setToolTip('Initialise the Layer Configuration')
        self.initbutton.clicked.connect(self.doInitClickAction)
        
        self.cleanbutton = QPushButton("Clean")
        self.cleanbutton.setToolTip('Clean the selected layer/group from local storage')
        self.cleanbutton.clicked.connect(self.doCleanClickAction)
        
        self.replicatebutton = QPushButton("Replicate")
        self.replicatebutton.setToolTip('Execute selected replication')
        self.replicatebutton.clicked.connect(self.doReplicateClickAction)
        
        self.cancelbutton = QPushButton("Close")
        self.cancelbutton.setToolTip('Close the LDS Replicate application')       
        self.cancelbutton.clicked.connect(self.parent.close)


        #set dialog values using GPR
        self.updateGUIValues(self.parent.gvs)
        
        #set onchange here otherwise we get circular initialisation
        self.destcombo.currentIndexChanged.connect(self.doDestChanged)
        self.confcombo.currentIndexChanged.connect(self.doConfChanged)
        self.lgcombo.currentIndexChanged.connect(self.doLGComboChanged)

        self.setStatus(self.STATUS.IDLE)
        
        #grid
        grid = QGridLayout()
        grid.setSpacing(10)
        
        
        #placement section ------------------------------------
        #---------+---------+--------+---------+--------
        # dest LB |         | dest DD
        # grp LB  |         | grp DD
        # conf LB |         | conf DD
        # epsg L  | epsg CB | epsg DD
        # f dt L  | f dt CB | f dt DD
        # t td L  | t td CB | t td DD
        # icon    |       <- progress ->
        # layer B | <- . -> |repl B  | clean B | close B 
        #---------+---------+--------+---------+--------

        grid.addWidget(destLabel, 1, 0)
        grid.addWidget(self.destcombo, 1, 2)

        #grid.addWidget(layerLabel, 2, 0)
        grid.addWidget(lgLabel, 2, 0)
        grid.addWidget(self.lgcombo, 2, 2)
        
        grid.addWidget(confLabel, 3, 0)
        grid.addWidget(self.confcombo, 3, 2)
        
        #grid.addWidget(groupLabel, 4, 0)
        #grid.addWidget(self.groupEdit, 4, 2)
        
        grid.addWidget(epsgLabel, 5, 0)
        grid.addWidget(self.epsgenable, 5, 1)
        grid.addWidget(self.epsgcombo, 5, 2)

        grid.addWidget(fromDateLabel, 6, 0)
        grid.addWidget(self.fromdateenable, 6, 1)
        grid.addWidget(self.fromdateedit, 6, 2)
        
        grid.addWidget(toDateLabel, 7, 0)
        grid.addWidget(self.todateenable, 7, 1)
        grid.addWidget(self.todateedit, 7, 2)
        
        hbox3 = QHBoxLayout()
        hbox3.addWidget(self.view) 
        hbox3.addStretch(1)
        hbox3.addWidget(self.progressbar)

        #hbox3.addLayout(vbox2)
        #hbox3.addLayout(vbox3)
        
        hbox4 = QHBoxLayout()
        hbox4.addWidget(self.initbutton)
        hbox4.addStretch(1)
        hbox4.addWidget(self.replicatebutton)
        hbox4.addWidget(self.cleanbutton)
        hbox4.addWidget(self.cancelbutton)
        

        vbox = QVBoxLayout()
        #vbox.addStretch(1)
        vbox.addLayout(grid)
        vbox.addLayout(hbox3)
        vbox.addLayout(hbox4)
        
        self.setLayout(vbox)  
       
    #def setProgress(self,pct):
    #    self.progressbar.setValue(pct)
        
    def setStatus(self,status,message='',tooltip=None):
        '''Sets indicator icon and statusbar message'''
        self.parent.statusbar.showMessage(message)
        self.parent.statusbar.setToolTip(tooltip if tooltip else '')

        #progress
        loc = os.path.abspath(os.path.join(IMG_LOC,self.imgset[status]))
        #loc = os.path.abspath(os.path.join(os.path.dirname(__file__),self.parent.IMG_LOC,self.imgset[status]))
        self.progressbar.setVisible(status in (self.STATUS.BUSY, self.STATUS.CLEAN))
        
        #icon
        anim = QMovie(loc, QByteArray(), self)
        anim.setScaledSize(QSize(self.IMG_WIDTH,self.IMG_HEIGHT))
        anim.setCacheMode(QMovie.CacheAll)
        anim.setSpeed(self.IMG_SPEED)
        self.view.clear()
        self.view.setMovie(anim)
        anim.start()

        self.view.repaint()
        QApplication.processEvents(QEventLoop.AllEvents)

    def mainWindowEnable(self,enable=True):
        cons = (self.lgcombo, self.confcombo, self.destcombo, 
                self.initbutton, self.replicatebutton, self.cleanbutton, self.cancelbutton,
                self.epsgenable,self.fromdateenable,self.todateenable,
                self.parent.menubar)
        for c in cons:
            c.setEnabled(enable)
            
        if enable:
            self.epsgcombo.setEnabled(self.epsgenable.checkState())
            self.fromdateedit.setEnabled(self.fromdateenable.checkState())
            self.todateedit.setEnabled(self.todateenable.checkState())
        else:
            self.epsgcombo.setEnabled(False)
            self.fromdateedit.setEnabled(False)
            self.todateedit.setEnabled(False)
   
        QApplication.restoreOverrideCursor() if enable else QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) 

    def refreshLGCombo(self):
        '''Re index LG combobox since a refreshLG call (new dest?) will usually mean new groups'''
        self.lgcombo.clear()
        self.lgcombo.addItems([i[2] for i in self.parent.confconn.lglist])
        #NOTE the separator consumes an index, if not clearing the combobox selectively remove the old sepindex (assumes g preceeds l)
        #if self.sepindex:
        #    self.lgcombo.removeItem(self.sepindex)
        self.sepindex = [i[0] for i in self.parent.confconn.lglist].count(LORG.GROUP)
        self.lgcombo.insertSeparator(self.sepindex)
        
    def updateLGValues(self,uconf,lgval,dest):
        '''Sets the values displayed in the Layer/Group combo'''
        #because we cant seem to sort combobox entries and want groups at the top, clear and re-add
        #TRACE#        
        #pdb.set_trace()
        sf = None
        try:
            self.parent.confconn.initConnections(uconf,lgval,dest)
        except Exception as e:
            sf=1
            ldslog.error('Error Updating UC Values. '+str(e))
            
        if sf:
            self.setStatus(self.STATUS.ERROR,'Error Updating UC Values', str(e))
        else:
            self.setStatus(self.STATUS.IDLE)
            
        self.refreshLGCombo()
        
    def centre(self):
        
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
        
    
    def gprParameters(self,rdest):
        '''Zip default and GPR values'''
        return [x if LU.assessNone(x) else y for x,y in zip(self.parent.gpr.readsec(rdest),self.parent.DEF_RVALS[1:])]
    
    def getLCE(self,ln):
        '''Read layer parameters'''
        dep = self.parent.confconn.reg.openEndPoint(self.parent.confconn.destname,self.parent.confconn.uconf)
        #sep = self.parent.confconn.reg.openEndPoint('WFS',self.parent.confconn.uconf)
        self.parent.confconn.reg.setupLayerConfig(self.parent.confconn.tp,None,dep,initlc=False)
        lce = dep.getLayerConf().readLayerParameters(ln)
        #self.parent.confconn.reg.closeEndPoint('WFS')
        self.parent.confconn.reg.closeEndPoint(self.parent.confconn.destname)
        sep,dep = None,None
        return lce
    
    
    def doDestChanged(self):
        '''Read the destname parameter and fill dialog with matching GPR values'''
        rdest = str(self.destlist[self.destcombo.currentIndex()])
        rvals = self.gprParameters(rdest)
        self.updateGUIValues([rdest]+rvals)    
        
        
    def doConfChanged(self):
        '''Read the user conf parameter and fill dialog with matching GPR values'''
        rdest = str(self.destlist[self.destcombo.currentIndex()])
        rlg,_,rep,rfd,rtd = self.gprParameters(rdest)
        ruc = str(self.cflist[self.confcombo.currentIndex()])
        self.updateGUIValues((rdest,rlg,ruc,rep,rfd,rtd))
        
        
    def doLGComboChanged(self):
        '''Read the layer/group value and change epsg to layer or gpr match'''
        #get a matching LG entry and test whether its a layer or group
        #lgi = self.parent.confconn.getLayerGroupIndex(self.lgcombo.currentText().toUtf8().data())
        lgi = self.parent.confconn.getLayerGroupIndex(LQ.readWidgetText(self.lgcombo.currentText()))
        #lgi can be none if we init a new group, in which case we use the GPR value
        if lgi:
            lge = self.parent.confconn.lglist[lgi]
            lce = self.getLCE(lge[1]) if lge[0]==LORG.LAYER else None
        else:
            lce = None
        
        #look for filled layer conf epsg OR use prefs stored in gpr
        if lce and LU.assessNone(lce.epsg):
            epsgval = lce.epsg
        else:
            rdest = str(self.destlist[self.destcombo.currentIndex()])
            _,_,epsgval,_,_ = self.gprParameters(rdest)
        epsgindex = [i[0] for i in self.nzlsr+[(0,0)]+self.rowsr].index(epsgval)
        if self.epsgcombo.currentIndex() != epsgindex:
            self.epsgcombo.setCurrentIndex(int(epsgindex))

        
    def updateGUIValues(self,readlist):
        '''Fill dialog values from provided list'''
        #TODO. Remove circular references when setCurrentIndex() triggers do###Changed()
        #Read user input
        rdest,self.rlgval,ruconf,repsg,rfd,rtd = readlist
        
        #--------------------------------------------------------------------
        
        #Destination Menu
        selecteddest = LU.standardiseDriverNames(rdest)
        if selecteddest not in self.destlist:
            self.destlist = self.getConfiguredDestinations()
            self.destcombo.addItem(selecteddest)
        destindex = self.destlist.index(selecteddest) if selecteddest else 0
        
        if self.destcombo.currentIndex() != destindex:
            self.destcombo.setCurrentIndex(destindex)
        
        #InitButton
        self.initbutton.setText('Layer Select')
        
        #Config File
        confindex = 0
        if LU.assessNone(ruconf):
            ruconf = ruconf.split('.')[0]
            if ruconf not in self.cflist:
                self.cflist += [ruconf,]
                self.confcombo.addItem(ruconf)
            confindex = self.cflist.index(ruconf)
            
        if self.confcombo.currentIndex() != confindex:
            self.confcombo.setCurrentIndex(confindex)
        #self.confEdit.setText(ruconf if LU.assessNone(ruconf) else '')
        
        #Layer/Group Selection
        self.updateLGValues(ruconf,self.rlgval,rdest)
        lgindex = None
        if LU.assessNone(self.rlgval):
            #index of list value
            lgindex = self.parent.confconn.getLayerGroupIndex(self.rlgval,col=1)
            
        if LU.assessNone(lgindex):
            #advance by 1 for sep
            lgindex += 1 if lgindex>self.sepindex else 0 
        else:
            #using the separator index sets the combo to blank
            lgindex = self.sepindex
        if self.lgcombo.currentIndex() != lgindex:
            self.lgcombo.setCurrentIndex(lgindex)
        #self.doLGEditUpdate()
        
        #EPSG
        #                                user > layerconf
        #useepsg = LU.precedence(repsg, lce.epsg if lce else None, None)
        epsgindex = [i[0] for i in self.nzlsr+[(None,None)]+self.rowsr].index(repsg)
        if self.epsgcombo.currentIndex() != epsgindex:
            self.epsgcombo.setCurrentIndex(epsgindex)
            
        #epsgedit = self.epsgcombo.lineEdit()
        #epsgedit.setText([e[1] for e in self.nzlsr+self.rowsr if e[0]==repsg][0])
        
        #epsgedit.setText([e for e in self.nzlsr+self.rowsr if re.match('^\s*(\d+).*',e).group(1)==repsg][0])
        
        #To/From Dates
        if LU.assessNone(rfd):
            self.fromdateedit.setDate(QDate(int(rfd[0:4]),int(rfd[5:7]),int(rfd[8:10])))
        else:
            early = DataStore.EARLIEST_INIT_DATE
            self.fromdateedit.setDate(QDate(int(early[0:4]),int(early[5:7]),int(early[8:10])))
            
        if LU.assessNone(rtd):
            self.todateedit.setDate(QDate(int(rtd[0:4]),int(rtd[5:7]),int(rtd[8:10]))) 
        else:
            today = DataStore.getCurrent()
            self.todateedit.setDate(QDate(int(today[0:4]),int(today[5:7]),int(today[8:10])))
            
        #Internal/External CheckBox
#        if LU.assessNone(rint):
#            self.internalTrigger.setChecked(rint.lower()==DataStore.CONF_INT)
#        else:
#            self.internalTrigger.setChecked(DataStore.DEFAULT_CONF==DataStore.CONF_INT)
        
        
    def getConfiguredDestinations(self):
        defml = ['',]+DataStore.DRIVER_NAMES.values()
        return [d for d in self.parent.gpr.getDestinations() if d in defml]
        
    def doEPSGEnable(self):
        self.epsgcombo.setEnabled(self.epsgenable.isChecked())
        
    def doFromDateEnable(self):
        self.fromdateedit.setEnabled(self.fromdateenable.isChecked())
          
    def doToDateEnable(self):
        self.todateedit.setEnabled(self.todateenable.isChecked())  
          
    def readParameters(self):
        '''Read values out of dialogs'''
        destination = LU.assessNone(str(self.destlist[self.destcombo.currentIndex()]))
        #lgindex = self.parent.confconn.getLayerGroupIndex(self.lgcombo.currentText().toUtf8().data())
        lgindex = self.parent.confconn.getLayerGroupIndex(LQ.readWidgetText(self.lgcombo.currentText()))
        #NB need to test for None explicitly since zero is a valid index
        lgval = self.parent.confconn.lglist[lgindex][1] if LU.assessNone(lgindex) else None       
        #uconf = LU.standardiseUserConfigName(str(self.confcombo.lineEdit().text()))
        #uconf = str(self.confcombo.lineEdit().text())
        uconf = str(self.cflist[self.confcombo.currentIndex()])
        ee = self.epsgenable.isChecked()
        epsg = None if ee is False else re.match('^\s*(\d+).*',str(self.epsgcombo.lineEdit().text())).group(1)
        fe = self.fromdateenable.isChecked()
        te = self.todateenable.isChecked()
        fd = None if fe is False else str(self.fromdateedit.date().toString('yyyy-MM-dd'))
        td = None if te is False else str(self.todateedit.date().toString('yyyy-MM-dd'))
        
        return destination,lgval,uconf,epsg,fe,te,fd,td
    
    def doInitClickAction(self):
        '''Initialise the LC on LC-button-click, action'''
        try:
            try:
                self.setStatus(self.STATUS.BUSY,'Opening Layer-Config Editor')  
                self.progressbar.setValue(0)
                self.parent.runLayerConfigAction()
            finally:
                self.setStatus(self.STATUS.IDLE,'Ready')
        except Exception as e:
            self.setStatus(self.STATUS.ERROR,'Error in Layer-Config',str(sys.exc_info()))#e))
        
    def doCleanClickAction(self):
        '''Set clean anim and run clean'''
        #lgo = self.lgcombo.currentText().toUtf8().data()
        lgo = LQ.readWidgetText(self.lgcombo.currentText())
        
        try:
            self.setStatus(self.STATUS.CLEAN,'Running Clean '+lgo)
            self.progressbar.setValue(0)
            self.runReplicationScript(True)
        except Exception as e:
            self.setStatus(self.STATUS.ERROR,'Failed Clean of '+lgo,str(sys.exc_info()))#e))
        
    def doReplicateClickAction(self):
        '''Set busy anim and run repl'''
        lgo = self.lgcombo.currentText()#.toUtf8().data()#only used for error messages
        try:
            self.setStatus(self.STATUS.BUSY,'Running Replicate '+lgo)
            self.progressbar.setValue(0)
            self.runReplicationScript(False)
            ldslog.debug('TRPfinish')
        except Exception as e:
            self.setStatus(self.STATUS.ERROR,'Failed Replication of '+lgo,str(sys.exc_info()))#e))

    def runReplicationScript(self,clean=False):
        '''Run the layer/group repliction script'''
        destination,lgval,uconf,epsg,fe,te,fd,td = self.readParameters()
        uconf_path = LU.standardiseUserConfigName(uconf)
        destination_path = LU.standardiseLayerConfigName(destination)
        destination_driver = LU.standardiseDriverNames(destination)

        if not os.path.exists(uconf_path):
            self.userConfMessage(uconf_path)
            return
        elif not MainFileReader(uconf_path).hasSection(destination_driver):
            self.userConfMessage(uconf_path,destination_driver)
            return
        #-----------------------------------------------------
        #'destname','layer','uconf','group','epsg','fd','td','int'
     
        self.parent.gpr.write((destination_driver,lgval,uconf,epsg,fd,td))        
        ldslog.info(u'dest={0}, lg={1}, conf={2}, epsg={3}'.format(destination_driver,lgval,uconf,epsg))
        ldslog.info('fd={0}, td={1}, fe={2}, te={3}'.format(fd,td,fe,te))
        lgindex = self.parent.confconn.getLayerGroupIndex(lgval,col=1)
        #lorg = self.parent.confconn.lglist[lgindex][0]
        #----------don't need lorg in TP anymore but it is useful for sorting/counting groups
        #self.parent.confconn.tp.setLayerOrGroup(lorg)
        self.parent.confconn.tp.setLayerGroupValue(lgval)
        if self.fromdateenable.isChecked(): self.parent.confconn.tp.setFromDate(fd)
        if self.todateenable.isChecked(): self.parent.confconn.tp.setToDate(td)
        self.parent.confconn.tp.setUserConf(uconf)
        if self.epsgenable: self.parent.confconn.tp.setEPSG(epsg)
        
        #because clean state persists in TP
        if clean:
            self.parent.confconn.tp.setCleanConfig()
        else:
            self.parent.confconn.tp.clearCleanConfig()
        #(re)initialise the data source since uconf may have changed
        #>>#self.parent.confconn.tp.src = self.parent.confconn.initSourceWrapper()
        #--------------------------
        ###ep = self.parent.confconn.reg.openEndPoint(self.parent.confconn.destname,self.parent.confconn.uconf)
        
        ###self.parent.confconn.reg.closeEndPoint(self.parent.confconn.destname)
        ###ep = None
        #Open ProcessRunner and run with TP(proc)/self(gui) instances
        #HACK temp add of dest_drv to PR call
        try:
            #TODO. Test for valid LC first
            self.tpr = ProcessRunner(self,destination_driver)
        except Exception as e:
            ldslog.error('Cannot create ProcessRunner {}. NB Possible missing Layer Config {}'.format(str(e),destination_path))
            self.layerConfMessage(destination_path)
            return
        #If PR has been successfully created we must vave a valid dst    
        ldslog.debug('TRPstart')
        self.tpr.start()
        
#     def quitProcessRunner(self):
#         self.tpr.join()
#         self.tpr.quit()
#         self.trp = None

        
    def userConfMessage(self,uconf,secname=None):
        ucans = QMessageBox.warning(self, 'User Config Missing/Incomplete', 
                                'Specified User-Config file, '+str(uconf)+' does not exist' if secname is None else 'User-Config file does not contain '+str(secname)+' section', 
                                'Back','Initialise User Config')
        if not ucans:
            #Retry
            ldslog.warn('Retry specifying UC')
            #self.confcombo.setCurrentIndex(0)
            return
        #Init
        ldslog.warn('Reset User Config Wizard')
        self.parent.runWizardAction()


    def layerConfMessage(self,dest):
        lcans = QMessageBox.warning(self, 'Layer Config Missing', 
                                'Required Layer-Config file, '+str(dest)+' does not exist', 
                                'Back','Run Layer Select')
        if not lcans:
            #Retry
            ldslog.warn('Retry specifying LC')
            #self.destcombo.setCurrentIndex(0)
            return
        #Init
        ldslog.warn('Reset Layer Config')
        self.doInitClickAction()