コード例 #1
0
ファイル: ofertas.py プロジェクト: dravix/pyventa
    def __init__(self,parent,ide=-1):
    		QDialog.__init__(self)
		self.setupUi(self)
		self.cursor=parent.cursor
		self.curser=parent.curser
		self.parent=parent
		self.ide=ide
		self.banderas={'edicion':False}
		self.matriz={'productos':[],'familias':[],'departamentos':[]}
		self.lista=[]
		self.menuAdd = QMenu(self)
		#Menu contextual de tipos de impresion
		self.menuAdd.addAction("Productos",self.listarProds)
		self.menuAdd.addAction("Familias",self.listarFams)
		self.menuAdd.addAction("Departamentos",self.listarDeps)
		self.tbMas.setMenu(self.menuAdd)
		self.tbMas.setPopupMode(2)
		self.CP=CalculaPrecio(self)

		#self.connect(self.rbDepa, SIGNAL("clicked ()"), self.listarDeps)
		#self.connect(self.rbFam, SIGNAL("clicked ()"), self.listarFams)
		#self.connect(self.rbProd, SIGNAL("clicked ()"), self.listarProds)

		self.connect(self.tbPublicar, SIGNAL("clicked ( )"), self.terminar)
		self.connect(self.tbCerrar, SIGNAL("clicked ()"), self.close)
		self.connect(self.tbMenos, SIGNAL("clicked ()"), self.quitar)
		self.connect(self.tbCalcDes, SIGNAL("clicked ()"), self.calcularPrecio)
		self.connect(self.sbMinimo,SIGNAL("editingFinished ()"),self.checkMaximo)		
		self.connect(self.CP.dsbDescuento,SIGNAL("valueChanged ( double )"),lambda:self.dsDescuento.setValue(self.CP.dsbDescuento.value()))		
		
        	self.deInicio.setDate(QDate.currentDate())
        	self.deFin.setDate(QDate.currentDate())
        	self.promo={'nombre':'','descuento':'','inicio':'','fin':'','minimo':''}
        	self.iniciar()
コード例 #2
0
    def __init__(self, ganttWidget):
        super(XGanttWidgetItem, self).__init__()

        # set default properties
        self.setFixedHeight(ganttWidget.cellHeight())
        for i in range(1, 20):
            self.setTextAlignment(i, Qt.AlignCenter)

        # define custom properties
        self._blockedAdjustments = {}
        self._viewItem = self.createViewItem()
        self._dateStart = QDate.currentDate()
        self._dateEnd = QDate.currentDate()
        self._allDay = True
        self._timeStart = QTime(0, 0, 0)
        self._timeEnd = QTime(23, 59, 59)
        self._name = "NONE"
        self._properties = {}
        self._itemStyle = XGanttWidgetItem.ItemStyle.Normal
        self._useGroupStyleWithChildren = True
        self._dependencies = {}
        self._reverseDependencies = {}
        self._dbEntry = None
        self._workdays = 0
        self._ganttWidget = ganttWidget
        #self._calculateWeekdays         = 0
        #self._dbDepartmentAssignment    = ''

        self.setPrivelages()
コード例 #3
0
    def __init__(self, parent=0, *args, **kwargs):
        super(InventoryViewWidget, self).__init__(parent=parent,
                                                  *args,
                                                  **kwargs)

        self.parentWidget().setWindowTitle(Config.APP_NAME +
                                           u"     INVENTAIRE")

        self.parent = parent

        self.title = u"Inventaire"

        self.on_date = FormatDate(QDate(date.today().year, 1, 1))
        self.end_date = FormatDate(QDate.currentDate())
        self.button = Button(u"Ok")
        self.button.clicked.connect(self.rapport_filter)
        self.btt_export = BttExportXLSX(u"Exporter")
        self.btt_export.clicked.connect(self.export_xls)

        self.invent_table = InventaireTableWidget(parent=self)
        # Grid
        gridbox = QGridLayout()
        gridbox.addWidget(FormLabel(u"Date debut"), 0, 1)
        gridbox.addWidget(self.on_date, 0, 2)
        gridbox.addWidget(FormLabel(u"Date fin"), 1, 1)
        gridbox.addWidget(self.end_date, 1, 2)
        gridbox.addWidget(self.button, 1, 3)
        gridbox.addWidget(self.btt_export, 1, 6)
        gridbox.setColumnStretch(4, 5)
        vbox = QVBoxLayout()
        vbox.addWidget(FPageTitle(self.title))
        vbox.addLayout(gridbox)
        vbox.addWidget(self.invent_table)
        self.setLayout(vbox)
        self.refresh()
コード例 #4
0
    def run(self):
        """Run method that performs all the real work"""

        # show the dialog
        self.dlg.show()

        sCalPopup = QCalendarWidget()
        eCalPopup = QCalendarWidget()
        self.dlg.startDate.setCalendarPopup(True)
        self.dlg.startDate.setCalendarWidget(sCalPopup)
        self.dlg.endDate.setCalendarPopup(True)
        self.dlg.endDate.setCalendarWidget(eCalPopup)

        self.dlg.startDate.setDate(QDate(2016, 11, 11))
        self.dlg.endDate.setDate(QDate(2016, 11, 18))

        # self.dlg.queryTable.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.dlg.queryTable.setHorizontalHeaderLabels([
            'providername', 'type', 'satellitename', 'instrumentname',
            'sensortype', 'sensorband', 'sensorresolution', 'date',
            'cloudcover', 'price'
        ])
        self.mapExtentsChanged()
        self.iface.mapCanvas().extentsChanged.connect(self.mapExtentsChanged)
        self.dlg.queryButton.clicked.connect(self.mapExtentsChanged)
        self.dlg.queryTable.cellClicked.connect(self.tableClicked)

        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            print("Goodbye")
コード例 #5
0
ファイル: print_dlg.py プロジェクト: SergioLaime/txscada
 def __init__(self, parent = None):
     QDialog.__init__(self, parent)
     self.setupUi(self)
     # Inicializacion de fechas
     hasta = date.today()
     desde = hasta - relativedelta(months = 1)
     self.dateTimeEdit_desde.setDate(QDate(desde.year, desde.month, desde.day))
     self.dateTimeEdit_hasta.setDate(QDate(hasta.year, hasta.month, hasta.day))
     
     self.model_co = QSqlQueryModel(self)
     self.model_uc = QSqlQueryModel(self)
     self.comboBox_CO.setModel(self.model_co)
     self.comboBox_UC.setModel(self.model_uc)
     self.model_co.setQuery(QUERY_ALL_CO)
     
     for i in range(0, 4):
         self.comboBox_tipo.addItem("Tipo %d" % i, QVariant(i))
         
     self._template = None
     
     if self.comboBox_CO.model().query().size() == 0:
         # Si no hay concentradores no se pueden imprimir reportes
         self.comboBox_CO.setEnabled(False)
         self.comboBox_UC.setEnabled(False)
         self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
コード例 #6
0
    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()
コード例 #7
0
    def __init__(self, iface, parent=None):
        """
        Constructor
        """
        QDialog.__init__(self, parent)
        self.setupUi(self)
        self.iface = iface

        self.tools = PgVersionTools(parent)

        self.dateEditRev1.setDate(QDate.currentDate())
        self.dateEditRev2.setDate(QDate.currentDate())

        canvas = self.iface.mapCanvas()
        theLayer = self.iface.activeLayer()
        provider = theLayer.dataProvider()
        uri = provider.dataSourceUri()
        myDb = self.tools.layerDB('logview', theLayer)
        mySchema = QgsDataSourceURI(uri).schema()
        myTable = QgsDataSourceURI(uri).table()

        if len(mySchema) == 0:
            mySchema = 'public'

        sql = "select revision from versions.pgvslogview('" + mySchema + "." + myTable.replace(
            '_version', '') + "') order by revision desc"
        result = myDb.read(sql)

        for i in range(len(result['REVISION'])):
            self.cmbRevision1.addItem(result['REVISION'][i])
            self.cmbRevision2.addItem(result['REVISION'][i])
コード例 #8
0
 def __init__( self, ganttWidget ):
     super(XGanttWidgetItem, self).__init__()
     
     # set default properties
     self.setFixedHeight(ganttWidget.cellHeight())
     for i in range(1, 20):
         self.setTextAlignment(i, Qt.AlignCenter)
     
     # define custom properties
     self._blockedAdjustments        = {}
     self._viewItem                  = self.createViewItem()
     self._dateStart                 = QDate.currentDate()
     self._dateEnd                   = QDate.currentDate()
     self._allDay                    = True
     self._timeStart                 = QTime(0, 0, 0)
     self._timeEnd                   = QTime(23, 59, 59)
     self._name                      = "NONE"
     self._properties                = {}
     self._itemStyle                 = XGanttWidgetItem.ItemStyle.Normal
     self._useGroupStyleWithChildren = True
     self._dependencies              = {}
     self._reverseDependencies       = {}
     self._dbEntry                   = None
     self._workdays                  = 0
     self._ganttWidget               = ganttWidget
     #self._calculateWeekdays         = 0
     #self._dbDepartmentAssignment    = ''
 
     self.setPrivelages()
コード例 #9
0
    def test_reset_button(self):
        self.test_browser.lowerDate.setDate(QDate(2013, 3, 3))
        self.test_browser.upperDate.setDate(QDate(2013, 5, 5))
        self.test_browser.upperCount.setValue(0.5)
        self.test_browser.lowerCount.setValue(0.5)
        self.test_browser.lowerZoom.setValue(60)
        self.test_browser.upperZoom.setValue(60)
        self.test_browser.slideID.setText('Test!')
        self.test_browser.otherComments.setText('')
        self.test_browser.saveLocation.setText('Something')
        self.test_browser.dropdowns[0].setCurrentIndex(1)
        self.test_browser.dropdowns[1].setCurrentIndex(1)
        self.test_browser.dropdowns[2].setCurrentIndex(1)
        self.test_browser.dropdowns[3].setCurrentIndex(1)
        self.assertTrue(self.test_browser.imageSearch())
        self.test_browser.resetFields()

        self.assertEqual(QDate.toString(self.test_browser.lowerDate.date(), "dd-MM-yyyy"), "01-01-2013")
        self.assertEqual(QDate.toString(self.test_browser.upperDate.date(), "dd-MM-yyyy"), "13-03-2014")
        self.assertEqual(self.test_browser.dropdowns[0].currentText(), '<Please select one>')
        self.assertEqual(self.test_browser.dropdowns[1].currentText(), '<Please select one>')
        self.assertEqual(self.test_browser.dropdowns[2].currentText(), '<Please select one>')
        self.assertEqual(self.test_browser.dropdowns[3].currentText(), '<Please select one>')
        self.assertEqual(self.test_browser.upperCount.value(), 1.0)
        self.assertEqual(self.test_browser.lowerCount.value(), 0.0)
        self.assertEqual(self.test_browser.lowerZoom.value(), 0)
        self.assertEqual(self.test_browser.upperZoom.value(), 1000000)
        self.assertEqual(self.test_browser.slideID.text(), '')
        self.assertEqual(self.test_browser.otherComments.toPlainText(), '')
        self.assertEqual(self.test_browser.saveLocation.text(), '<Download Location>')
コード例 #10
0
    def validateDate(self, item):
        """
        Does a two-stage check if user gives a new date as input. 
        First, QRegExpValidator checks if the input matches the regular
        expression '\d{1,2}\.', i.e. a one- or two-digit number followed by a
        dot. If this is accepted, a QDate with the new day is created. If this
        is valid (depends on the month, internally handled by QDate), the new
        date is assigned to the item.
        If any of those validations fails, the user is prompted with a warning
        and the date is reset.

        :param      item | DateItem 
        :return     valid | bool
        """
        state = _DATEVALIDATOR_.validate(item.text(), 0)[0]
        if state == QtGui.QValidator.Acceptable:
            newDay = unicode(item.text())  #str 'dd.
            year, month, _ = item.data().toDate().getDate()
            date = QDate(year, month,
                         int(newDay[:-1]))  #skip trailing . of day
            if date.isValid():
                item.setData(date)
                return True
        QtGui.QMessageBox.warning(
            None, 'Invalid input!',
            'Please enter a valid day of the format \'dd.\'')
        item.setText(str(item.data().toDate().day()) + '.')
コード例 #11
0
    def test_value_date(self):
        test_property = DateProperty("test name", QDate.currentDate(), "gco:Date")

        test_property.value = QDate.fromString("2015-06-07")

        with self.assertRaises(TypeError):
            test_property.value = 20150607
コード例 #12
0
    def setup_ui(self):
        # json file selector
        self.json_groupbox = QGroupBox("Export ODK Aggregate")
        layout = QGridLayout()
        self.json_select_button = PushButton("", self)
        self.json_select_button.clicked.connect(self.json_selector_clicked)
        layout.addWidget(self.json_select_button, 1, 0)
        self.json_groupbox.setLayout(layout)

        # destination folder selector
        self.destination_groupbox = QGroupBox("Destination")
        layout = QGridLayout()
        self.destination_select_button = PushButton(self.destination_folder,
                                                    self)
        self.destination_select_button.clicked.connect(
            self.destination_selector_clicked)
        layout.addWidget(self.destination_select_button, 1, 0)
        self.destination_groupbox.setLayout(layout)

        # period calendars
        today = datetime.date.today()
        self.period_groupbox = QGroupBox("Période")
        layout = QGridLayout()
        self.from_date_selector = DateTimeEdit(QDate(self.from_date))
        self.from_date_selector.dateChanged.connect(self.from_date_changed)
        self.from_date_selector.setMaximumDate(self.to_date)
        self.to_date_selector = DateTimeEdit(QDate(self.to_date))
        self.to_date_selector.dateChanged.connect(self.to_date_changed)
        self.to_date_selector.setMinimumDate(self.from_date)
        self.to_date_selector.setMaximumDate(today)
        layout.addWidget(Label("Du"), 2, 0)
        layout.addWidget(self.from_date_selector, 3, 0)
        layout.addWidget(Label("Au"), 2, 1)
        layout.addWidget(self.to_date_selector, 3, 1)
        self.period_groupbox.setLayout(layout)

        # start button
        self.start_button = PushButton("Démarrer")
        self.start_button.setEnabled(False)
        self.start_button.setDefault(True)
        self.start_button.clicked.connect(self.export_requested)

        # cancel button
        self.cancel_button = CancelPushButton("Annuler")
        self.cancel_button.setEnabled(False)
        self.cancel_button.clicked.connect(self.cancel_export)

        # grid
        self.gridBox = QGridLayout()
        self.gridBox.addWidget(self.json_groupbox, 0, 0, 1, 2)
        self.gridBox.addWidget(self.destination_groupbox, 1, 0, 1, 2)
        self.gridBox.addWidget(self.period_groupbox, 2, 0, 1, 2)
        self.gridBox.addWidget(self.start_button, 3, 0)
        self.gridBox.addWidget(self.cancel_button, 3, 1)

        vBox = QVBoxLayout()
        vBox.addLayout(self.gridBox)
        self.setLayout(vBox)

        self.json_fpath = None
コード例 #13
0
    def __init__(self):
        self.today = Days()

        self.yesterday = Days(QDate.currentDate().addDays(-1))

        self.tomorrow = Days(QDate.currentDate().addDays(1))

        self.this_week = Days(
            QDate.currentDate().addDays(-(QDate.currentDate().dayOfWeek() -
                                          1)))
        self.this_week.period = self.this_week.date.addDays(6)

        self.last_week = Days(self.this_week.date.addDays(-7))
        self.last_week.period = self.this_week.period.addDays(-7)

        self.next_week = Days(self.this_week.date.addDays(7))
        self.next_week.period = self.this_week.period.addDays(7)

        self.this_month = Days(
            QDate.currentDate().addDays(-(self.today.date.day() - 1)))
        self.this_month.period = self.this_month.date.addDays(
            self.this_month.date.daysInMonth() - 1)

        self.last_month = Days(self.this_month.date.addMonths(-1))
        self.last_month.period = self.last_month.date.addDays(
            self.last_month.date.daysInMonth() - 1)

        self.next_month = Days(self.this_month.date.addMonths(1))
        self.next_month.period = self.next_month.date.addDays(
            self.next_month.date.daysInMonth() - 1)
コード例 #14
0
    def update_time_bounds(self):
        # State and performance depend only on NDVI data
        # TODO: need to also account for GAEZ and/or CCI data dates for
        # stratification
        start_year = QDate(self.start_year_ndvi, 1, 1)
        end_year = QDate(self.end_year_ndvi, 12, 31)

        # State
        self.perf_year_start.setMinimumDate(start_year)
        self.perf_year_start.setMaximumDate(end_year)
        self.perf_year_end.setMinimumDate(start_year)
        self.perf_year_end.setMaximumDate(end_year)

        # Performance
        self.state_year_bl_start.setMinimumDate(start_year)
        self.state_year_bl_start.setMaximumDate(end_year)
        self.state_year_bl_end.setMinimumDate(start_year)
        self.state_year_bl_end.setMaximumDate(end_year)
        self.state_year_tg_start.setMinimumDate(start_year)
        self.state_year_tg_start.setMaximumDate(end_year)
        self.state_year_tg_end.setMinimumDate(start_year)
        self.state_year_tg_end.setMaximumDate(end_year)

        # Trajectory - needs to also account for climate data
        start_year_traj = QDate(
            max(self.start_year_ndvi, self.start_year_climate), 1, 1)
        end_year_traj = QDate(min(self.end_year_ndvi, self.end_year_climate),
                              12, 31)

        self.traj_year_start.setMinimumDate(start_year_traj)
        self.traj_year_start.setMaximumDate(end_year_traj)
        self.traj_year_end.setMinimumDate(start_year_traj)
        self.traj_year_end.setMaximumDate(end_year_traj)
コード例 #15
0
    def _getCalendar(self, display_format, value=None):
        '''
        Get a combobox filled with the given values
        
        :param values: The values as key = value, value = description or text
        :type values: Dict
        
        :returns: A combobox
        :rtype: QWidget
        '''

        widget = QWidget()
        calendar = QDateTimeEdit()
        calendar.setCalendarPopup(True)
        calendar.setDisplayFormat(display_format)
        if value is not None:
            calendar.setDate(QDate.fromString(value, display_format))
        else:
            calendar.setDate(QDate.currentDate())
        layout = QHBoxLayout(widget)
        layout.addWidget(calendar, 1)
        layout.setAlignment(Qt.AlignCenter)
        layout.setContentsMargins(5, 0, 5, 0)
        widget.setLayout(layout)

        return widget
コード例 #16
0
 def setDateEnd( self, date, ignoreDuration = False ):
     """
     Sets the date start value for this item.
     
     :param      dateStart | <QDate>
     """
     date = QDate(date)
     
     delta = self._dateEnd.daysTo(date)
     if ( not delta ):
         return
     
     if ( self.itemStyle() != self.ItemStyle.Group ):
         self._dateEnd = date
     else:
         duration        = self.duration()
         if ignoreDuration is False:
             self._dateStart = date.addDays(-duration)
         self._dateEnd   = date
         
     self.adjustChildren(delta)
     self.adjustRange()
     
     # sync the tree
     self.sync()
コード例 #17
0
    def setDateEnd(self, date, ignoreDuration=False):
        """
        Sets the date start value for this item.
        
        :param      dateStart | <QDate>
        """
        date = QDate(date)

        delta = self._dateEnd.daysTo(date)
        if (not delta):
            return

        if (self.itemStyle() != self.ItemStyle.Group):
            self._dateEnd = date
        else:
            duration = self.duration()
            if ignoreDuration is False:
                self._dateStart = date.addDays(-duration)
            self._dateEnd = date

        self.adjustChildren(delta)
        self.adjustRange()

        # sync the tree
        self.sync()
コード例 #18
0
ファイル: export_poly.py プロジェクト: virtualadrian/Roadnet
    def create_feature_from_record(self, record):
        """
        Create feature in temporary layer from record returned from query.
        :param record: QSqlQuery record describing feature
        """
        feature = QgsFeature()
        wkb = record.value('geom')
        if type(wkb) == QByteArray:
            geometry = QgsGeometry()
            geometry.fromWkb(wkb)
            feature.setGeometry(geometry)
        else:
            "NOT a byte"

        feature.setAttributes([
            record.value('poly_id'),
            record.value('RefNo'),
            record.value('rec_type'),
            record.value('desctxt'),
            record.value('locality'),
            record.value('town'),
            record.value('LocTxt'),
            record.value('RdStatus'),
            record.value('Swa_org'),
            QDate().fromString(str(record.value('Adopt_Date')), 'yyyyMMdd'),
            QDate().fromString(str(record.value('Entry_Date')), 'yyyyMMdd'),
            record.value('lor_no'),
            record.value('route'),
            record.value('symbol'),
            record.value('element'),
            record.value('hierarchy')
        ])
        return feature
コード例 #19
0
ファイル: conciliacion.py プロジェクト: armonge/EsquipulasPy
 def aceptar( self ):
     fecha = QDate.currentDate()
     fecha = QDate( fecha.year(), fecha.month(), fecha.daysInMonth() )
     if self.dtPicker.date() > fecha:
         QMessageBox.information( None, "Cuentas Bancarias", "La cuenta seleccionada ya fue conciliada" )
     else:
         return self.accept()
コード例 #20
0
    def testDateTimeTypes(self):
        vl = QgsVectorLayer(
            '%s table="qgis_test"."date_times" sql=' % (self.dbconn),
            "testdatetimes", "postgres")
        assert (vl.isValid())

        fields = vl.dataProvider().fields()
        self.assertEqual(
            fields.at(fields.indexFromName('date_field')).type(),
            QVariant.Date)
        self.assertEqual(
            fields.at(fields.indexFromName('time_field')).type(),
            QVariant.Time)
        self.assertEqual(
            fields.at(fields.indexFromName('datetime_field')).type(),
            QVariant.DateTime)

        f = vl.getFeatures(QgsFeatureRequest()).next()

        date_idx = vl.fieldNameIndex('date_field')
        assert isinstance(f.attributes()[date_idx], QDate)
        self.assertEqual(f.attributes()[date_idx], QDate(2004, 3, 4))
        time_idx = vl.fieldNameIndex('time_field')
        assert isinstance(f.attributes()[time_idx], QTime)
        self.assertEqual(f.attributes()[time_idx], QTime(13, 41, 52))
        datetime_idx = vl.fieldNameIndex('datetime_field')
        assert isinstance(f.attributes()[datetime_idx], QDateTime)
        self.assertEqual(f.attributes()[datetime_idx],
                         QDateTime(QDate(2004, 3, 4), QTime(13, 41, 52)))
コード例 #21
0
ファイル: dbhandler.py プロジェクト: ZeeD/calendar
 def setData(self, index, value, role=None):
     if not index.isValid() or role not in (Qt.EditRole, Qt.CheckStateRole):
         return False
     expected_datepayd = QDate.fromString(index.data().toString(),
                                          'd MMMM yyyy')
     if role == Qt.EditRole:
         effective_datepayd = value.toDate()
     elif value.toInt()[0] == Qt.Checked:
         effective_datepayd = expected_datepayd
     else:
         print 'Error: Non puoi annullare i pagamenti'
         return False
     query = QSqlQuery(
         'UPDATE payments SET effective_datepayd = '
         ':effective_datepayd WHERE clients_client = :clients_client '
         'AND clients_machine = :clients_machine AND clients_selldate = '
         ':clients_selldate AND expected_datepayd = :expected_datepayd',
         self._db)
     # TODO: trovare client, machine, selldate
     header_data = self.headerData(index.column(), Qt.Horizontal,
                                   Qt.DisplayRole).toString().split('\n')
     client = header_data[0]
     machine = header_data[1]
     selldate = QDate.fromString(header_data[2], 'd MMMM yyyy')
     query.bindValue(':effective_datepayd', QVariant(effective_datepayd))
     query.bindValue(':clients_client', QVariant(client))
     query.bindValue(':clients_machine', QVariant(machine))
     query.bindValue(':clients_selldate', QVariant(selldate))
     query.bindValue(':expected_datepayd', QVariant(expected_datepayd))
     if not query.exec_():
         raise StandardError('SYNTAX ERROR')
     self.emit(SIGNAL("dataChanged()"), index, index)
     return True
コード例 #22
0
ファイル: period_by.py プロジェクト: Ciwara/GCiss
    def __init__(self, parent=0, *args, **kwargs):
        super(PeriodByViewWidget, self).__init__(parent=parent,
                                                 *args,
                                                 **kwargs)
        self.parent = parent
        self.title = FPageTitle(_(u"Periodic report"))

        self.on_date = FormatDate(QDate(date.today().year, 1, 1))
        self.end_date = FormatDate(QDate.currentDate())
        self.Button = Button(u"OK")
        self.Button.clicked.connect(self.rapport_filter)
        self.current_period = FLabel(
            self.format_period(self.on_date.text(), self.end_date.text()))
        vbox = QVBoxLayout()
        # Grid
        gridbox = QGridLayout()
        gridbox.addWidget(FormLabel(u"Date debut"), 0, 0)
        gridbox.addWidget(self.on_date, 0, 1)
        gridbox.addWidget(FormLabel(u"Date fin"), 1, 0)
        gridbox.addWidget(self.end_date, 1, 1)
        gridbox.addWidget(self.Button, 1, 2)
        gridbox.setColumnStretch(3, 1)

        gridbox.addWidget(self.current_period, 1, 4)

        self.table = By_periodTableWidget(parent=self)

        vbox.addWidget(self.title)
        vbox.addLayout(gridbox)
        vbox.addWidget(self.table)
        self.setLayout(vbox)
コード例 #23
0
 def __init__(self, minimum=QDate(),
              maximum=QDate.currentDate(),
              format="yyyy-MM-dd", parent=None):
     super(DateColumnDelegate, self).__init__(parent)
     self.minimum = minimum
     self.maximum = maximum
     self.format = QString(format)
コード例 #24
0
 def _getCalendar(self, display_format, value = None):
     '''
     Get a combobox filled with the given values
     
     :param values: The values as key = value, value = description or text
     :type values: Dict
     
     :returns: A combobox
     :rtype: QWidget
     '''
     
     
     widget = QWidget()
     calendar = QDateTimeEdit()
     calendar.setCalendarPopup(True)
     calendar.setDisplayFormat(display_format)
     if value is not None:
         calendar.setDate(QDate.fromString(value, display_format))
     else:
         calendar.setDate(QDate.currentDate())
     layout = QHBoxLayout(widget)
     layout.addWidget(calendar, 1);
     layout.setAlignment(Qt.AlignCenter);
     layout.setContentsMargins(5,0,5,0);
     widget.setLayout(layout);
             
     return widget
コード例 #25
0
 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()
コード例 #26
0
    def testDateTimeWriteShapefile(self):
        """Check writing date and time fields to an ESRI shapefile."""
        ml = QgsVectorLayer(
            ('Point?crs=epsg:4326&field=id:int&'
             'field=date_f:date&field=time_f:time&field=dt_f:datetime'),
            'test', 'memory')

        assert ml is not None, 'Provider not initialised'
        assert ml.isValid(), 'Source layer not valid'
        provider = ml.dataProvider()
        assert provider is not None

        ft = QgsFeature()
        ft.setGeometry(QgsGeometry.fromPoint(QgsPoint(10, 10)))
        ft.setAttributes([
            1,
            QDate(2014, 3, 5),
            QTime(13, 45, 22),
            QDateTime(QDate(2014, 3, 5), QTime(13, 45, 22))
        ])
        res, features = provider.addFeatures([ft])
        assert res
        assert len(features) > 0

        dest_file_name = os.path.join(str(QDir.tempPath()), 'datetime.shp')
        print(dest_file_name)
        crs = QgsCoordinateReferenceSystem()
        crs.createFromId(4326, QgsCoordinateReferenceSystem.EpsgCrsId)
        write_result = QgsVectorFileWriter.writeAsVectorFormat(
            ml, dest_file_name, 'utf-8', crs, 'ESRI Shapefile')
        self.assertEqual(write_result, QgsVectorFileWriter.NoError)

        # Open result and check
        created_layer = QgsVectorLayer(u'{}|layerid=0'.format(dest_file_name),
                                       u'test', u'ogr')

        fields = created_layer.dataProvider().fields()
        self.assertEqual(
            fields.at(fields.indexFromName('date_f')).type(), QVariant.Date)
        #shapefiles do not support time types, result should be string
        self.assertEqual(
            fields.at(fields.indexFromName('time_f')).type(), QVariant.String)
        #shapefiles do not support datetime types, result should be date
        self.assertEqual(
            fields.at(fields.indexFromName('dt_f')).type(), QVariant.Date)

        f = created_layer.getFeatures(QgsFeatureRequest()).next()

        date_idx = created_layer.fieldNameIndex('date_f')
        assert isinstance(f.attributes()[date_idx], QDate)
        self.assertEqual(f.attributes()[date_idx], QDate(2014, 3, 5))
        time_idx = created_layer.fieldNameIndex('time_f')
        #shapefiles do not support time types
        assert isinstance(f.attributes()[time_idx], basestring)
        self.assertEqual(f.attributes()[time_idx], '13:45:22')
        #shapefiles do not support datetime types
        datetime_idx = created_layer.fieldNameIndex('dt_f')
        assert isinstance(f.attributes()[datetime_idx], QDate)
        self.assertEqual(f.attributes()[datetime_idx], QDate(2014, 3, 5))
コード例 #27
0
ファイル: custom_date_edit.py プロジェクト: nathangeology/ert
    def setDate(self, date):
        if isinstance(date, datetime.date):
            date = QDate(date.year, date.month, date.day)

        if date is not None and date.isValid():
            self._line_edit.setText(str(date.toString("yyyy-MM-dd")))
        else:
            self._line_edit.setText("")
コード例 #28
0
    def test_value_date(self):
        test_property = DateProperty('test name', QDate.currentDate(),
                                     'gco:Date')

        test_property.value = QDate.fromString('2015-06-07')

        with self.assertRaises(TypeError):
            test_property.value = 20150607
コード例 #29
0
ファイル: custom_date_edit.py プロジェクト: Ensembles/ert
    def setDate(self, date):
        if isinstance(date, datetime.date):
            date = QDate(date.year, date.month, date.day)

        if date is not None and date.isValid():
            self._line_edit.setText(str(date.toString("yyyy-MM-dd")))
        else:
            self._line_edit.setText("")
コード例 #30
0
ファイル: scheme_lodgement.py プロジェクト: cb-flts/stdm
 def _configure_date_controls(self):
     """
     Set the configuration of the date widget controls.
     """
     self.date_apprv.setMaximumDate(QDate.currentDate())
     self.date_establish.setMaximumDate(QDate.currentDate())
     self.date_establish.setDate(QDate.currentDate())
     self.date_apprv.setDate((QDate.currentDate()))
コード例 #31
0
    def firstShow(self):
        lc_start_year = QDate(self.datasets['Land cover']['ESA CCI']['Start year'], 1, 1)
        lc_end_year = QDate(self.datasets['Land cover']['ESA CCI']['End year'], 12, 31)
        self.year_start.setMinimumDate(lc_start_year)
        self.year_start.setMaximumDate(lc_end_year)
        self.year_end.setMinimumDate(lc_start_year)
        self.year_end.setMaximumDate(lc_end_year)

        super(DlgCalculateSOC, self).firstShow()
コード例 #32
0
 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()
コード例 #33
0
	def readDates(self, tree):
		"""
		Lese die Daten aus (Geburtsdatum, Verwandlungsdatum, aktuelles Datum im Spiel).
		"""

		dates = tree.find("dates")
		self.__character.dateBirth = QDate.fromString(dates.attrib["birth"], Config.DATE_FORMAT)
		self.__character.dateBecoming = QDate.fromString(dates.attrib["becoming"], Config.DATE_FORMAT)
		self.__character.dateGame = QDate.fromString(dates.attrib["game"], Config.DATE_FORMAT)
コード例 #34
0
ファイル: utils.py プロジェクト: jeroendierckx/Camelot
def date_from_string(s):
    s = s.strip()
    if not s:
        return None
    from PyQt4.QtCore import QDate
    import string
    f = local_date_format()
    dt = QDate.fromString(s, f)
    if not dt.isValid():
        #
        # if there is a mismatch of 1 in length between format and
        # string, prepend a 0, to handle the case of 1/11/2011
        #
        if len(f) == len(s) + 1:
            s = '0' + s
            dt = QDate.fromString(s, f)
    if not dt.isValid():
        #
        # try alternative separators
        #
        separators = u''.join([c for c in f if c not in string.ascii_letters])
        if separators:
            alternative_string = u''.join([
                (c if c in string.digits else separators[0]) for c in s
            ])
            dt = QDate.fromString(alternative_string, f)
    if not dt.isValid():
        # try parsing without separators
        # attention : using non ascii letters will fail on windows
        # string.letters then contains non ascii letters of which we don't know the
        # encoding, so we cannot convert them to unicode to compare them
        only_letters_format = u''.join(
            [c for c in f if c in string.ascii_letters])
        only_letters_string = u''.join(
            [c for c in s if c in (string.ascii_letters + string.digits)])
        dt = QDate.fromString(only_letters_string, only_letters_format)
        if not dt.isValid():
            # try parsing without the year, and take the current year by default
            only_letters_format = u''.join(
                [c for c in only_letters_format if c not in ['y']])
            dt = QDate.fromString(only_letters_string, only_letters_format)
            if not dt.isValid():
                raise ParsingError()


#                # try parsing without year and month, and take the current year and month by default
#                only_letters_format = u''.join([c for c in only_letters_format if c not in ['M']])
#                dt = QDate.fromString(only_letters_string, only_letters_format)
#                if not dt.isValid():
#                    raise ParsingError()
#                else:
#                    today = date.today()
#                    return date(today.year, today.month, dt.day())
            else:
                return date(date.today().year, dt.month(), dt.day())
    return date(dt.year(), dt.month(), dt.day())
コード例 #35
0
ファイル: payment.py プロジェクト: Ciwara/GCiss
    def __init__(self, parent=0, *args, **kwargs):

        super(PaymentViewWidget, self).__init__(parent=parent, *args, **kwargs)
        FPeriodHolder.__init__(self, *args, **kwargs)

        self.parentWidget().setWindowTitle(Config.APP_NAME + u"   Movements")
        self.parent = parent

        self.title = u"Movements"

        self.on_date = FormatDate(
            QDate(date.today().year,
                  date.today().month, 1))
        self.end_date = FormatDate(QDate.currentDate())
        self.now = datetime.now().strftime("%x")
        self.soldeField = FormLabel("0")
        self.label_balance = FormLabel(u"Solde au {} ".format(self.now))
        balanceBox = QGridLayout()
        balanceBox.addWidget(self.label_balance, 0, 2)
        balanceBox.addWidget(self.soldeField, 0, 3)
        balanceBox.setColumnStretch(0, 1)

        self.table = RapportTableWidget(parent=self)
        self.button = Button(u"Ok")
        self.button.clicked.connect(self.table.refresh_)

        self.btt_export = BttExportXLSX(u"Exporter")
        self.btt_export.clicked.connect(self.export_xls)
        self.add_btt = Button("Créditer")
        self.add_btt.setIcon(
            QIcon(u"{img_media}{img}".format(img_media=Config.img_media,
                                             img="in.png")))
        self.add_btt.clicked.connect(self.add_payment)
        self.sub_btt = Button("Débiter")
        self.sub_btt.setIcon(
            QIcon(u"{img_media}{img}".format(img_media=Config.img_media,
                                             img="out.png")))
        self.sub_btt.clicked.connect(self.sub_payment)

        editbox = QGridLayout()
        editbox.addWidget(FormLabel(u"Date debut"), 0, 1)
        editbox.addWidget(self.on_date, 0, 2)
        editbox.addWidget(FormLabel(u"Date fin"), 1, 1)
        editbox.addWidget(self.end_date, 1, 2)
        editbox.addWidget(self.button, 1, 3)

        editbox.addWidget(self.sub_btt, 1, 5)
        editbox.addWidget(self.add_btt, 1, 6)
        editbox.addWidget(self.btt_export, 1, 7)
        editbox.setColumnStretch(4, 2)
        vbox = QVBoxLayout()
        vbox.addWidget(FPageTitle(self.title))
        vbox.addLayout(editbox)
        vbox.addWidget(self.table)
        vbox.addLayout(balanceBox)
        self.setLayout(vbox)
コード例 #36
0
	def fill_data(self, id=None):				
				#id.model().record(id.row()).value('id').toInt()		
		#if id !=None:			
		#	id = id.model().record(id.row()).value('id').toInt()
		#	id = id[0]		#solo para enteros para string cambia		
		
		if self.datos.check_havedata('cf_empleado')==True	:
			self.botonera.btnModificar.setEnabled(True)
			self.botonera.btnEliminar.setEnabled(True)
			self.botonera.btnSearch.setEnabled(True)
			self.botonera.btnPrint.setEnabled(True)				
			self.emp = self.datos.get_data('cf_empleado', id)		
			#algunas tanformaciones para las fechas para usar el control dateedit		
			
			self.empid=self.emp[0]
			self.lncodigo.setText(self.emp[1])
			self.lnsexo.setText(self.emp[2])
			self.lnnombres.setText(self.emp[3])
			self.lnapellidos.setText(self.emp[4])		
			self.lncedula.setText(str(self.emp[5]))
			self.lnrif.setText(self.emp[6])
			self.lntlfhab.setText(self.emp[7])
			self.lntlfcel.setText(self.emp[8])
			if self.emp[9] == None:
				self.lnfecnac.setDate(QDate(1, 1, 1900))
			else:
				self.lnfecnac.setDate(self.emp[9])
				
			self.txtdir1.setPlainText(self.emp[10])
			self.txtdir2.setPlainText(self.emp[11])
			self.lnemail.setText(self.emp[12])			
			if self.emp[13] == None:
				self.lnfecingreso.setDate(QDate(1, 1, 1900))
			else:
				self.lnfecingreso.setDate(self.emp[13])
				
			self.lncuenta.setText(self.emp[14])
			
			if self.emp[16] == None:
				self.lnfecegreso.setDate(QDate(1, 1, 1900))
			else:
				self.lnfecegreso.setDate(self.emp[16])
			self.lnfoto.setText(self.emp[17])
			self.idcargo=self.emp[18]
			self.tipemp=self.emp[19]
			self.iddpto=self.emp[20]
			self.idtiponom=self.emp[21]
			self.idbanco=self.emp[22]					
			
			self.fillcombos()
			self.fillgrid()
			self.lblfoto.setPixmap(QPixmap('fotos/'+self.lnfoto.text()))
		else:			
			self.botonera.btnModificar.setEnabled(False)
			self.botonera.btnEliminar.setEnabled(False)
			self.clear_fields()
コード例 #37
0
ファイル: editParticipantDialog.py プロジェクト: diana134/afs
    def __init__(self, parent=None, testing=False, participantId=None):
        # Initialize object using ui_addParticipant
        super(EditParticipantDialog, self).__init__(parent)
        self.ui = Ui_AddParticipantDialog()
        self.ui.setupUi(self)

        # Initialize class variables
        self.testing = testing
        if participantId is None:
            QMessageBox.critical(self, 'Invalid Participant', "An invalid participant was chosen.", QMessageBox.Ok)
            self.reject()
        # if participantId[0] == 's':
        #     self.participantId = participantId[1:]
        # else:
        #     self.participantId = participantId
        self.participantId = participantId
        self.participant = dbInteractionInstance.getParticipantFromId(participantId)

        # Set up the contact
        self.contactId = self.participant.contact
        if self.contactId:
            c = dbInteractionInstance.getTeacherFromId(self.contactId)
            if c is not None:
                self.ui.contactPersonLineEdit.setText("{0} {1}".format(c.first, c.last))

        # Initialize ui with variables
        self.ui.addParticipantBtn.setText("&Update Participant")
        self.setWindowTitle("Edit Participant")
        self.ui.firstNameLineEdit.setText(self.participant.first)
        self.ui.lastNameLineEdit.setText(self.participant.last)
        self.ui.addressLineEdit.setText(self.participant.address)
        self.ui.cityLineEdit.setText(self.participant.city)
        self.ui.postalCodeLineEdit.setText(humanPostalCodeFormat(self.participant.postal))
        self.ui.homePhoneLineEdit.setText(humanPhoneNumberFormat(self.participant.home))
        self.ui.cellPhoneLineEdit.setText(humanPhoneNumberFormat(self.participant.cell))
        self.ui.emailLineEdit.setText(self.participant.email)
        self.ui.dateOfBirthDateEdit.setDate(QDate.fromString(self.participant.dob, "yyyy-MM-dd"))
        self.ui.ageLabel.setText("Age as of Jan. 1 {0}".format(QDate.currentDate().year()))
        self.ui.schoolAttendingLineEdit.setText(self.participant.schoolAttending)
        self.ui.parentLineEdit.setText(self.participant.parent)
        self.ui.schoolGradeLineEdit.setText(self.participant.schoolGrade)
        self.ui.groupNameLineEdit.setText(self.participant.groupName)
        self.ui.numberParticipantsLineEdit.setText(self.participant.numberParticipants)
        self.ui.schoolGradeLineEdit.setText(self.participant.schoolGrade)
        self.ui.averageAgeLineEdit.setText(self.participant.averageAge)
        if self.participant.earliestPerformanceTime != "":
            self.ui.timeConstraintsGroupBox.setChecked(True)
            self.ui.earliestPerformanceTimeTimeEdit.setTime(QTime.fromString(self.participant.earliestPerformanceTime, "h:mm A"))
            self.ui.latestPerformanceTimeTimeEdit.setTime(QTime.fromString(self.participant.latestPerformanceTime, "h:mm A"))
        self.ui.participantsTextEdit.setText(self.participant.participants)

        # Set the age display
        self.dob_changed()

        # Make the buttons do things
        self.connectSlots()
コード例 #38
0
 def RefreshFromDB(self):
     if self._dbEntry is not None:
         startDate = self._dbEntry._startdate
         endDate = self._dbEntry._enddate
         self.setDateStart(
             QDate(startDate.year, startDate.month, startDate.day), True)
         self.setDateEnd(QDate(endDate.year, endDate.month, endDate.day),
                         True)
         self.setName(self._dbEntry._name)
         self.sync()
コード例 #39
0
def forceDate(val):
    if isinstance(val, QVariant):
        return val.toDate()
    if isinstance(val, QDate):
        return val
    if isinstance(val, QDateTime):
        return val.date()
    if val is None:
        return QDate()
    return QDate(val)
コード例 #40
0
    def test_value_date(self):
        test_property = DateProperty(
            'test name',
            QDate.currentDate(),
            'gco:Date'
        )

        test_property.value = QDate.fromString('2015-06-07')

        with self.assertRaises(TypeError):
            test_property.value = 20150607
コード例 #41
0
    def __init__( self, parent = None ):
        """
        Constructor
        """

        super( FrmEstadoResultado, self ).__init__( parent )
        self.setupUi( self )
        self.parentWindow = parent
#        self.editmodel = None
        self.user = user.LoggedUser
        self.status = True
        self.dtPicker.setMaximumDate( QDate.currentDate() )
        self.dtPicker.setDate( QDate.currentDate() )
コード例 #42
0
	def AddProject(self):
		self._myXGanttWidgetItem = XGanttWidgetItem(self._myXGanttWidget)
		#self._myXGanttViewItem = self._myXGanttWidgetItem.createViewItem()
		self._myXGanttWidgetItem.setName("test")
		self._myXGanttWidgetItem.setDateEnd(QDate.currentDate().addMonths(+1))
		self._myXGanttWidgetItem.setDateStart(QDate.currentDate().addDays(+1))
		
		self._myXGanttWidgetItem.setProperty("Start",QDate(2014,10,1))
		self._myXGanttWidgetItem.setProperty("End",QDate(2014,10,2))
		self._myXGanttWidgetItem.setProperty("Calendar Days",2)
		self._myXGanttWidgetItem.setProperty("Work Days",2)
		
		self._myXGanttWidget.addTopLevelItem(self._myXGanttWidgetItem)
		self._myXGanttWidget.show()
コード例 #43
0
ファイル: factura.py プロジェクト: joseanm/pyqt_billing
    def printDocument1(self):
        html = u""

        date = QDate.currentDate().toString(self.DATE_FORMAT)
        
        address = Qt.escape("Bario francisco mesa").replace(",","<br>")
        contact = Qt.escape("Luis Mejia")
        balance = 5000
        html += ("<p align=right><img src=':/logo.png'></p>"
                 "<p> align = right>Greasy hands ltd."
                 "<br>New Lombard Street"
                 "<br>London<br>WC13 4PX<br>%s</p>"
                 "<p>%s</p><p>Dear %s, </p>"
                 "<p>The balance of your account is %s.")% (
                   date, address, contact, QString("$ %L1").arg(float(balance),0,"f",2))
                 
        if balance <0 :
            html += ("<p><font color =red><b> Please remit the amount owing immediately.</b></font>")
        else:
            html += "We are delighted to have done business with you."
        
        html += ("</p><p>&nbsp;</p><p>"
                "<table border=1 cellpadding=2 cellspacing=2><tr><td colspan=3>Transaction</td></tr>")
        transactions = [
                        (QDate.currentDate(),500),
                        (QDate.currentDate(),500),
                        (QDate.currentDate(),-500),
                        (QDate.currentDate(),500)
                        ]
        for date, amount in transactions:
            color, status = "black", "Credit"
            if amount <0:
                color, status = "red", "Debid"
            
            html += ("<tr>"
                        "<td align= right>%s</td>"
                        "<td>%s</td><td align=right><font color=%s>%s</font></td></tr>" % (
                        date.toString(self.DATE_FORMAT), status,color, QString("$ %L1").arg(float(abs(amount)), 0, "f",2)))
            
        html += ("</table></p><p style='page-break-after=always;'>"
                 "We hope to continue doing business with you</p>")
                 
        
        pdialog = QPrintDialog() 
        if pdialog.exec_() == QDialog.Accepted:
            printer = pdialog.printer()
            document = QTextDocument()
            document.setHtml(html)
            document.print_(printer)
コード例 #44
0
ファイル: utils.py プロジェクト: maurodoglio/Camelot
def date_from_string(s):
    s = s.strip()
    if not s:
        return None
    from PyQt4.QtCore import QDate
    import string
    f = local_date_format()
    dt = QDate.fromString(s, f)
    if not dt.isValid():
        #
        # if there is a mismatch of 1 in length between format and
        # string, prepend a 0, to handle the case of 1/11/2011
        #
        if len(f) == len(s) + 1:
            s = '0' + s
            dt = QDate.fromString(s, f)
    if not dt.isValid():
        #
	# try alternative separators
        #
        separators = u''.join([c for c in f if c not in string.ascii_letters])
        if separators:
            alternative_string = u''.join([(c if c in string.digits else separators[0]) for c in s])
            dt = QDate.fromString(alternative_string, f)
    if not dt.isValid():
        # try parsing without separators
        # attention : using non ascii letters will fail on windows
        # string.letters then contains non ascii letters of which we don't know the
        # encoding, so we cannot convert them to unicode to compare them
        only_letters_format = u''.join([c for c in f if c in string.ascii_letters])
        only_letters_string = u''.join([c for c in s if c in (string.ascii_letters+string.digits)])
        dt = QDate.fromString(only_letters_string, only_letters_format)
        if not dt.isValid():
            # try parsing without the year, and take the current year by default
            only_letters_format = u''.join([c for c in only_letters_format if c not in ['y']])
            dt = QDate.fromString(only_letters_string, only_letters_format)
            if not dt.isValid():
                raise ParsingError()
#                # try parsing without year and month, and take the current year and month by default
#                only_letters_format = u''.join([c for c in only_letters_format if c not in ['M']])
#                dt = QDate.fromString(only_letters_string, only_letters_format)
#                if not dt.isValid():
#                    raise ParsingError()
#                else:
#                    today = date.today()
#                    return date(today.year, today.month, dt.day())
            else:
                return date(date.today().year, dt.month(), dt.day())
    return date(dt.year(), dt.month(), dt.day())
コード例 #45
0
    def __init__(self, id):
        super(CatalogFilterDate, self).__init__(id)
        self.label = QLabel(TEXT_LABEL_BETWEEN)

        self.datetime_begin_edit = QDateEdit(QDate.currentDate())
        self.datetime_end_edit = QDateEdit(QDate.currentDate())
        self.datetime_begin_edit.setCalendarPopup(True)
        self.datetime_end_edit.setCalendarPopup(True)
        self.expand_widget(self.datetime_begin_edit)
        self.expand_widget(self.datetime_end_edit)

        value_item = QGridLayout()
        value_item.addWidget(self.datetime_begin_edit, 0, 0)
        value_item.addWidget(QLabel(TEXT_LABEL_AND), 0, 1)
        value_item.addWidget(self.datetime_end_edit, 0, 2)
        self.value_item = value_item
コード例 #46
0
ファイル: test_wizard.py プロジェクト: mozilla/mozregression
def test_wizard(mocker, qtbot, os, bits, wizard_class, pages):
    mozinfo = mocker.patch('mozregui.wizard.mozinfo')
    mozinfo.os = os
    mozinfo.bits = bits

    wizard = wizard_class()
    qtbot.addWidget(wizard)
    wizard.show()
    qtbot.waitForWindowShown(wizard)

    for page_class in pages:
        assert isinstance(wizard.currentPage(), page_class)
        wizard.next()

    # everything has been visited
    assert wizard.visitedPages() == wizard.pageIds()

    fetch_config, options = wizard.options()

    now = QDate.currentDate()

    assert isinstance(fetch_config, CommonConfig)
    assert fetch_config.app_name == 'firefox'  # this is the default
    assert fetch_config.os == os
    assert fetch_config.bits == bits
    assert fetch_config.build_type == 'shippable'
    assert not fetch_config.repo

    assert options['profile'] == ''
    if isinstance(wizard, SingleRunWizard):
        assert options['launch'] == now.addDays(-3).toPyDate()
    else:
        assert options['good'] == now.addYears(-1).toPyDate()
        assert options['bad'] == now.toPyDate()
コード例 #47
0
ファイル: order_view.py プロジェクト: Ciwara/GCiss
    def __init__(self, parent=0, *args, **kwargs):
        super(OrderViewWidget, self).__init__(parent=parent, *args, **kwargs)

        self.order_table = OrederTableWidget(parent=self)
        self.parentWidget().setWindowTitle(Config.NAME_ORGA + u"    COMMANDE")

        self.title = FPageTitle(u"Faire une Commande")

        self.com_date = FormatDate(QDate.currentDate())
        vbox = QVBoxLayout()

        self.export_xls_btt = BttExportXLS(u"Exporter")
        self.connect(self.export_xls_btt, SIGNAL('clicked()'),
                     self.export_xls_order)

        # self.save_order_btt = Button_save(u"enregistre")
        # self.connect(self.save_order_btt, SIGNAL('clicked()'),
        #              self.save_order)

        self.restor_order_btt = Deleted_btt(u"vider")
        self.connect(self.restor_order_btt, SIGNAL('clicked()'),
                     self.remove_save)

        # Grid
        gridbox = QGridLayout()
        gridbox.addWidget(FormLabel(u"Date"), 0, 0)
        gridbox.addWidget(self.com_date, 0, 1)
        gridbox.setColumnStretch(1, 5)
        gridbox.addWidget(self.restor_order_btt, 2, 2)
        # gridbox.addWidget(self.save_order_btt, 2, 3)
        gridbox.addWidget(self.export_xls_btt, 2, 4)
        vbox.addWidget(self.title)
        vbox.addLayout(gridbox)
        vbox.addWidget(self.order_table)
        self.setLayout(vbox)
コード例 #48
0
ファイル: printer.py プロジェクト: maximerobin/Ufwi
def interval_previous_week():
    date = QDate.currentDate()
    end = QDateTime(date.addDays(-(date.dayOfWeek() - 1)))
    begin = QDateTime(date.addDays(-(date.dayOfWeek() - 1) - 7))
    return {'start_time': begin.toTime_t(),
            'end_time':   end.toTime_t()
           }
コード例 #49
0
    def __init__(self, iface, dbm):
        QDialog.__init__(self)
        self.iface = iface
        self.dbm = dbm
        self.setupUi(self)

        self.accepted.connect(self.onAccepted)

        now = QDate.currentDate()
        self.uiSearchDate.setDate(now)
        self.uiSearchDate.setMaximumDate(now)
        self.uiToDate.setDate(now)
        self.uiToDate.setMaximumDate(now)
        # FIXME next two lines into def => update on change of one of the two Date edits
        # FIXME next two lines into def => update on change of one of the two Date edits
        self.uiFromDate.setMaximumDate(self.uiToDate.date())
        self.uiToDate.setMinimumDate(self.uiFromDate.date())

        # Signals
        self.uiVerticalChk.stateChanged.connect(self.onFilmModeChange)
        self.uiObliqueChk.stateChanged.connect(self.onFilmModeChange)

        #self.uiSearchDate.dateChanged.connect()

        #self.uiMilitaryNumberEdit.textChanged()
        self.setupMilitaryCombo()

        self.uiFromDate.dateChanged.connect(self.timeSpanChanged)
        self.uiToDate.dateChanged.connect(self.timeSpanChanged)
        self.uiFromChk.stateChanged.connect(self.timeSpanConstraints)
        self.uiToChk.stateChanged.connect(self.timeSpanConstraints)
コード例 #50
0
def dow(values, feature, parent):
    """
        Returns an integer representing the day of week for a given date. Returned 
        values range from 0-6, where 0 is Sunday.
        
        <p><h4>Syntax</h4>
        dow(<i>date</i>)</p>

        <p><h4>Arguments</h4>
        <i>  date</i> &rarr; a date value. Must be a valid date or datetime field, or a 
        string in the format 'yyyy-mm-dd'.<br></p>
        
        <p><h4>Example</h4>
        <!-- Show example of function.-->
             dow('2013-07-01') &rarr; 1</p>
    """
    input_date = values[0]

    # Return dayOfWeek() % 7 so that values range from 0 (sun) to 6 (sat)
    # to match Postgresql behaviour
    if type(input_date) == QDateTime:
        return input_date.date().dayOfWeek() % 7
    elif type(input_date) == QDate:
        return input_date.dayOfWeek() % 7
    elif type(input_date) in (str, unicode):
        # Convert string to qdate
        input_qdate = QDate.fromString(input_date, "yyyy-MM-dd")
        if input_qdate.isValid():
            return input_qdate.dayOfWeek() % 7
        else:
            return None
コード例 #51
0
ファイル: genericdelegates.py プロジェクト: DaoQiu/VimProject
 def __init__(self, minimum=QDate(),
              maximum=QDate.currentDate(),
              format="yyyy-MM-dd", parent=None):
     super(DateColumnDelegate, self).__init__(parent)
     self.minimum = minimum
     self.maximum = maximum
     self.format = QString(format)
コード例 #52
0
ファイル: start.py プロジェクト: kjpolaszek/js_python
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
	self.text = 'Wybierz wpis \n <----'	
	self.setWindowIcon(QtGui.QIcon('./Icon/diary-no2.png'))        
	self.ui = Ui_editor()
        self.ui.setupUi(self)
	self.index = 0
	self.ui.textEdit.setText(self.text)
	self.ui.actionClear.triggered.connect(self.clear)
	self.ui.actionOpen.triggered.connect(self.file_open)
	self.ui.actionSave.triggered.connect(self.file_save)
	self.ui.actionSave_as.triggered.connect(self.file_save_as)		
	self.ui.actionInfo.triggered.connect(self.ShowAboutPopup)	
	self.ui.actionRemove.triggered.connect(self.remove_file)
	self.ui.actionnew_day.triggered.connect(self.next_day)
	self.ui.actionHelp.triggered.connect(self.Help)	
	self.currentDate = QDate.currentDate()	
	self.today = datetime.date.today().strftime('%d-%m-%Y')
	self.today_full = datetime.date.today().strftime('%A %d %B %Y')
	self.ui.label_date.setText('Dzisiaj jest: '+self.today_full.decode('utf-8'))	
    	self.filemodel = QtGui.QFileSystemModel()
	self.filemodel.setFilter(QtCore.QDir.NoDotAndDotDot | QtCore.QDir.Files)
	self.filemodel.sort(3,1)	
	self.ui.listView.setModel(self.filemodel)	
        root_index = self.filemodel.setRootPath('./Data')	
	self.ui.listView.setRootIndex(root_index)
	self.ui.listView.clicked.connect(self.clicked)
	self.ui.listView.activated.connect(self.clicked) 		
コード例 #53
0
ファイル: period_by.py プロジェクト: Ciwara/GCiss
    def __init__(self, parent=0, *args, **kwargs):
        super(PeriodByViewWidget, self).__init__(
            parent=parent, *args, **kwargs)
        self.parent = parent
        self.title = FPageTitle(_(u"Periodic report"))

        self.on_date = FormatDate(QDate(date.today().year, 1, 1))
        self.end_date = FormatDate(QDate.currentDate())
        self.Button = Button(u"OK")
        self.Button.clicked.connect(self.rapport_filter)
        self.current_period = FLabel(self.format_period(self.on_date.text(),
                                                        self.end_date.text()))
        vbox = QVBoxLayout()
        # Grid
        gridbox = QGridLayout()
        gridbox.addWidget(FormLabel(u"Date debut"), 0, 0)
        gridbox.addWidget(self.on_date, 0, 1)
        gridbox.addWidget(FormLabel(u"Date fin"), 1, 0)
        gridbox.addWidget(self.end_date, 1, 1)
        gridbox.addWidget(self.Button, 1, 2)
        gridbox.setColumnStretch(3, 1)

        gridbox.addWidget(self.current_period, 1, 4)

        self.table = By_periodTableWidget(parent=self)

        vbox.addWidget(self.title)
        vbox.addLayout(gridbox)
        vbox.addWidget(self.table)
        self.setLayout(vbox)
コード例 #54
0
ファイル: database.py プロジェクト: Blakstar26/freeseer
 def get_talks_by_room_and_time(self, room):
     """Returns the talks hosted in a specified room, starting from the current date and time"""
     current_date = QDate.currentDate().toString(1)  # yyyy-mm-dd
     current_time = QTime.currentTime().toString()  # hh:mm:ss
     return QtSql.QSqlQuery('''SELECT * FROM presentations
                               WHERE Room='{}' AND Date='{}'
                               AND StartTime >= '{}' ORDER BY StartTime ASC'''.format(room, current_date, current_time))
コード例 #55
0
ファイル: rkdOperate.py プロジェクト: hedge31/ColdStoreSystem
def clearRkd(rkdForm):
    rkdForm.rkdDocNoText.setText(u'自动编号')
    rkdForm.CustomText.clear()
    rkdForm.ItemText.clear()
    rkdForm.weightText.clear()
    rkdForm.inDateEdit.setDate(QDate.currentDate())
    rkdForm.stockText.clear()
コード例 #56
0
ファイル: conciliacion.py プロジェクト: armonge/EsquipulasPy
 def on_tblCuenta_currentChanged( self, _current, _previous ):
     fila = self.tblCuenta.selectionModel().currentIndex().row()
     fecha = self.filtermodel.index( fila, 6 ).data().toDate()
     if fecha.toString() != "":
         self.dtPicker.setDate( fecha )
     else:
         fecha = QDate.currentDate()
コード例 #57
0
ファイル: printer.py プロジェクト: maximerobin/Ufwi
def interval_previous_month():
    date = QDate.currentDate()
    end = QDateTime(date.addDays(-date.day() + 1))
    begin = QDateTime(end.date().addDays(-end.date().addDays(-1).daysInMonth()))
    return {'start_time': begin.toTime_t(),
            'end_time':   end.toTime_t()
           }
コード例 #58
0
    def __init__(self, movies, movie=None, parent=None):
        super(AddEditMovieDlg, self).__init__(parent)
        self.setupUi(self)

        self.movies = movies
        self.movie = movie
        self.acquiredDateEdit.setDisplayFormat(moviedata.DATEFORMAT)
        if movie is not None:
            self.titleLineEdit.setText(movie.title)
            self.yearSpinBox.setValue(movie.year)
            self.minutesSpinBox.setValue(movie.minutes)
            self.acquiredDateEdit.setDate(movie.acquired)
            self.acquiredDateEdit.setEnabled(False)
            self.locationLineEdit.setText(movie.location)
            self.notesTextEdit.setPlainText(movie.notes)
            self.notesTextEdit.setFocus()
            self.buttonBox.button(QDialogButtonBox.Ok).setText(
                                  "&Accept")
            self.setWindowTitle("My Movies - Edit Movie")
        else:
            today = QDate.currentDate()
            self.acquiredDateEdit.setDateRange(today.addDays(-5),
                                               today)
            self.acquiredDateEdit.setDate(today)
            self.titleLineEdit.setFocus()
        self.on_titleLineEdit_textEdited(QString())
コード例 #59
0
ファイル: refund_edit_add.py プロジェクト: Ciwara/GCiss
    def __init__(self, table_p, parent, provid_clt=None, type_=None, refund=None, *args, **kwargs):
        QDialog.__init__(self, parent, *args, **kwargs)

        self.type_ = type_
        self.refund = refund
        self.parent = parent
        self.table_p = table_p
        self.provid_clt = provid_clt
        self.new = True
        if self.refund:
            self.new = False
            self.last_r = self.refund
            self.type_ = refund.type_
            self.refund_date_field = FormatDate(self.refund.date)
            self.refund_date_field.setEnabled(False)
            self.title = u"Modification de {} {}".format(self.refund.type_,
                                                         self.refund.invoice.client)
            self.succes_msg = u"{} a été bien mise à jour".format(
                self.refund.type_)
            self.amount = refund.amount
            self.provid_clt = refund.provider_client
        else:
            self.refund_date_field = FormatDate(QDate.currentDate())
            self.succes_msg = u"Client a été bien enregistré"
            self.title = u"Création d'un nouvel client"
            self.amount = ""
            self.refund = Refund()
            self.last_r = Refund.select().where(
                Refund.provider_client == provid_clt).order_by(Refund.date.desc()).get()

        self.setWindowTitle(self.title)
        self.amount_field = IntLineEdit(unicode(self.amount))

        vbox = QVBoxLayout()
        self.last_remaining = self.last_r.refund_remaing()
        print(self.last_remaining)
        # try:
        #     self.last_r.refund_remaing()
        # self.remaining = self.last_r.remaining
        # except Exception as e:
        #     self
        #     print("last_r except ", e)
        #     self.last_r = None
        # self.close()

        formbox = QFormLayout()
        formbox.addRow(FormLabel("Client :"),
                       FormLabel(self.provid_clt.name))
        formbox.addRow(FormLabel("Dette restante :"),
                       FormLabel(str(formatted_number(self.last_remaining)) + Config.DEVISE))
        formbox.addRow(FormLabel(u"Date : *"), self.refund_date_field)
        formbox.addRow(FormLabel(u"Montant : *"), self.amount_field)

        butt = Button_save(u"Enregistrer")
        butt.clicked.connect(self.save_edit)
        formbox.addRow("", butt)
        # formbox.addRow("", "Le client {} n'est pas endetté")

        vbox.addLayout(formbox)
        self.setLayout(vbox)