def createEditor(self, parent, option, index): """QWidget * QStyledItemDelegate::createEditor ( QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index )""" editor = QDateTimeEdit(parent) editor.setCalendarPopup(True) editor.setDisplayFormat(self.edit_pattern) editor.dateTimeChanged.connect(self._commitAndClose) return editor
class DateRequest(Request): def __init__(self, parent): Request.__init__(self, parent) self.setOperators() self.setDateTime() def setOperators(self): self.operatorCombo = OperatorCombo(self) self.hlayout.addWidget(self.operatorCombo) self.connect(self.operatorCombo, SIGNAL("currentIndexChanged ( int )"), self.updateQuery) self.connect(self.operatorCombo, SIGNAL("currentIndexChanged ( const QString &)"), self.updateQuery) def updateQuery(self, data): self.emit(SIGNAL("queryUpdated")) def setDateTime(self): self.datetime = QDateTimeEdit(self) self.datetime.setCalendarPopup(True) self.hlayout.addWidget(self.datetime, 50) self.connect(self.datetime, SIGNAL("dateChanged ( const QDate &)"), self.updateQuery) self.connect(self.datetime, SIGNAL("dateTimeChanged ( const QDateTime &)"), self.updateQuery) self.connect(self.datetime, SIGNAL("timeChanged ( const QTime &)"), self.updateQuery) def request(self): res = "(time " + str(self.operatorCombo.currentText()) date_time = self.datetime.dateTime() res += str(date_time.toString("yyyy-MM-ddThh:mm:ss")) + ")" return res
class DateDialog(QDialog): def __init__(self, parent=None): super(DateDialog, self).__init__(parent) layout = QVBoxLayout(self) # nice widget for editing the date self.datetime = QDateTimeEdit(self) self.datetime.setCalendarPopup(True) self.datetime.setDateTime(QDateTime.currentDateTime()) layout.addWidget(self.datetime) # OK and Cancel buttons self.buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self) layout.addWidget(self.buttons) self.buttons.accepted.connect(self.accept) self.buttons.rejected.connect(self.reject) # get current date and time from the dialog def dateTime(self): return self.datetime.dateTime() # static method to create the dialog and return (date, time, accepted) @staticmethod def getDateTime(parent=None): dialog = DateDialog(parent) result = dialog.exec_() date = dialog.dateTime() return (date.date(), date.time(), result == QDialog.Accepted)
def __init__(self, parent=None): QDialog.__init__(self, parent) self.resize(290, 136) self.setWindowTitle("Effective Date") 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")) self.groupBox = GroupBox(self) verticalLayoutDlg.addWidget(self.groupBox) self.dtpDate = QDateTimeEdit(self.groupBox) self.dtpDate.setObjectName(("dtpDate")) self.dtpDate.setDateTime(QDateTime.currentDateTime()) self.groupBox.Add = self.dtpDate self.calendar = QCalendarWidget(self.groupBox) self.groupBox.Add = self.calendar self.calendar.clicked.connect(self.calendar_clicked) self.btnBoxOkCancel = QDialogButtonBox(self) self.btnBoxOkCancel.setObjectName(("btnBoxOkCancel")) self.btnBoxOkCancel.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) # btnOK = self.btnBoxOkCancel.button(QDialogButtonBox.Ok) # btnOK.setText("Create") self.connect(self.btnBoxOkCancel, SIGNAL("accepted()"), self.acceptDlg) self.connect(self.btnBoxOkCancel, SIGNAL("rejected()"), self.reject) verticalLayoutDlg.addWidget(self.btnBoxOkCancel)
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
def __init__(self, parent = None, _id = 0): super(TplRow, self).__init__(parent) self.id = _id self.setLayout(QHBoxLayout()) self.idLabel = QLabel(self) self.beginEdit = QDateTimeEdit(self) self.beginEdit.setCalendarPopup(True) self.endEdit = QDateTimeEdit(self) self.endEdit.setCalendarPopup(True) self.timeDiff = ClickLabel(self) self.descriptionEdit = QLineEdit(self) self.noteEdit = QLineEdit(self) self.delButton = QPushButton(self) self.delButton.setText('X') self.layout().addWidget(self.idLabel) self.layout().addWidget(self.beginEdit) self.layout().addWidget(self.endEdit) self.layout().addWidget(self.timeDiff) self.layout().addWidget(self.descriptionEdit) self.layout().addWidget(self.noteEdit) self.layout().addWidget(self.delButton) self.layout().setContentsMargins(2,2,2,2) self.connect(self.descriptionEdit, SIGNAL('editingFinished ()'), self.notify) self.connect(self.noteEdit, SIGNAL('editingFinished ()'), self.notify) self.connect(self.beginEdit, SIGNAL('editingFinished ()'), self.notify) self.connect(self.endEdit, SIGNAL('editingFinished ()'), self.notify) self.connect(self.delButton, SIGNAL('clicked()'), self.delete) self.connect(self.timeDiff, SIGNAL('clicked()'), self.onTimeDiff)
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
def setDateTime(self): self.datetime = QDateTimeEdit(self) self.datetime.setCalendarPopup(True) self.hlayout.addWidget(self.datetime, 50) self.connect(self.datetime, SIGNAL("dateChanged ( const QDate &)"), self.updateQuery) self.connect(self.datetime, SIGNAL("dateTimeChanged ( const QDateTime &)"), self.updateQuery) self.connect(self.datetime, SIGNAL("timeChanged ( const QTime &)"), self.updateQuery)
def __init__(self, client, arg, value, compatibility=None): ArgFilterBase.__init__(self, client, arg, value, compatibility=compatibility) QDateTimeEdit.__init__(self) datevalue = QDateTime() try: datevalue.setTime_t(int(value)) self.setDateTime(datevalue) except (TypeError, ValueError): self.setDateTime(QDateTime.currentDateTime()) self.setCalendarPopup(True)
def setup(self): for label, value in self.data: if DEBUG: print "value:", value if label is None and value is None: # Separator: (None, None) self.formlayout.addRow(QLabel(" "), QLabel(" ")) self.widgets.append(None) continue elif label is None: # Comment self.formlayout.addRow(QLabel(value)) self.widgets.append(None) continue elif tuple_to_qfont(value) is not None: field = FontLayout(value, self) elif text_to_qcolor(value).isValid(): field = ColorLayout(QColor(value), self) elif isinstance(value, (str, unicode)): field = QLineEdit(value, self) elif isinstance(value, (list, tuple)): selindex = value.pop(0) field = QComboBox(self) if isinstance(value[0], (list, tuple)): keys = [key for key, _val in value] value = [val for _key, val in value] else: keys = value field.addItems(value) if selindex in value: selindex = value.index(selindex) elif selindex in keys: selindex = keys.index(selindex) elif not isinstance(selindex, int): print >>STDERR, "Warning: '%s' index is invalid (label: " \ "%s, value: %s)" % (selindex, label, value) selindex = 0 field.setCurrentIndex(selindex) elif isinstance(value, bool): field = QCheckBox(self) if value: field.setCheckState(Qt.Checked) else: field.setCheckState(Qt.Unchecked) elif isinstance(value, float): field = QLineEdit(repr(value), self) elif isinstance(value, int): field = QSpinBox(self) field.setRange(-1e9, 1e9) field.setValue(value) elif isinstance(value, datetime.datetime): field = QDateTimeEdit(self) field.setDateTime(value) elif isinstance(value, datetime.date): field = QDateEdit(self) field.setDate(value) else: field = QLineEdit(repr(value), self) self.formlayout.addRow(label, field) self.widgets.append(field)
def createEditor(self, parent, option, index): """Overriding method createEditor""" if index.column() < 3: return None value = self.get_value(index) key = index.model().get_key(index) readonly = isinstance(value, tuple) or self.parent().readonly #---editor = DictEditor if isinstance(value, (list, tuple, dict)) and not self.inplace: editor = DictEditor(value, key, icon=self.parent().windowIcon(), readonly=readonly) if editor.exec_() and not readonly: self.set_value(index, editor.get_copy()) return None #---editor = ArrayEditor elif isinstance(value, ndarray) and ndarray is not FakeObject \ and not self.inplace: if value.size == 0: return None editor = ArrayEditor(parent) if editor.setup_and_check(value, title=key, readonly=readonly): if editor.exec_(): # Only necessary for child class RemoteDictDelegate: # (ArrayEditor does not make a copy of value) self.set_value(index, value) return None #---editor = QDateTimeEdit elif isinstance(value, datetime.datetime) and not self.inplace: editor = QDateTimeEdit(value, parent) editor.setCalendarPopup(True) editor.setFont(get_font('dicteditor')) self.connect(editor, SIGNAL("returnPressed()"), self.commitAndCloseEditor) return editor #---editor = QDateEdit elif isinstance(value, datetime.date) and not self.inplace: editor = QDateEdit(value, parent) editor.setCalendarPopup(True) editor.setFont(get_font('dicteditor')) self.connect(editor, SIGNAL("returnPressed()"), self.commitAndCloseEditor) return editor #---editor = QTextEdit elif isinstance(value, (str, unicode)) and len(value) > 40: editor = TextEditor(value, key) if editor.exec_() and not readonly: conv = str if isinstance(value, str) else unicode self.set_value(index, conv(editor.get_copy())) return None #---editor = QLineEdit else: editor = QLineEdit(parent) editor.setFont(get_font('dicteditor')) editor.setAlignment(Qt.AlignLeft) self.connect(editor, SIGNAL("returnPressed()"), self.commitAndCloseEditor) return editor
def createEditor(self,parent,option,index): """create widgets to edit values""" if index.isValid(): model = index.model() column = index.column() if (column == model.position_for_header('date')) or \ (column == model.position_for_header('expected_date')) : data = model.data(index,Qt.DisplayRole) if data.toString() == "": data = datetime.today() editor = QDateTimeEdit(data) editor.setCalendarPopup(True) self.updateEditorGeometry(editor, option,index ) # by default it's a bit too small editor.setFixedWidth(option.rect.width() + 50) # FIXME: resulting position is still wrong return editor return QStyledItemDelegate.createEditor(self,parent,option,index)
class DateRequest(Request): def __init__(self, parent): Request.__init__(self, parent) self.setOperators() self.setDateTime() def setOperators(self): self.operatorCombo = OperatorCombo(self) self.hlayout.addWidget(self.operatorCombo) def setDateTime(self): self.datetime = QDateTimeEdit(self) self.datetime.setCalendarPopup(True) self.hlayout.addWidget(self.datetime, 50) def request(self): res = "(time " + str(self.operatorCombo.currentText()) date_time = self.datetime.dateTime() res += str(date_time.toString("yyyy-MM-ddThh:mm:ss")) + ")" return res
def extra_keywords_to_widgets(extra_keyword_definition): """Create widgets for extra keyword. :param extra_keyword_definition: An extra keyword definition. :type extra_keyword_definition: dict :return: QCheckBox and The input widget :rtype: (QCheckBox, QWidget) """ # Check box check_box = QCheckBox(extra_keyword_definition['name']) check_box.setToolTip(extra_keyword_definition['description']) check_box.setChecked(True) # Input widget if extra_keyword_definition['type'] == float: input_widget = QDoubleSpinBox() input_widget.setMinimum(extra_keyword_definition['minimum']) input_widget.setMaximum(extra_keyword_definition['maximum']) input_widget.setSuffix(extra_keyword_definition['unit_string']) elif extra_keyword_definition['type'] == int: input_widget = QSpinBox() input_widget.setMinimum(extra_keyword_definition['minimum']) input_widget.setMaximum(extra_keyword_definition['maximum']) input_widget.setSuffix(extra_keyword_definition['unit_string']) elif extra_keyword_definition['type'] == unicode: if extra_keyword_definition.get('options'): input_widget = QComboBox() options = extra_keyword_definition['options'] for option in options: input_widget.addItem( option['name'], option['key'], ) default_option_index = input_widget.findData( extra_keyword_definition['default_option']) input_widget.setCurrentIndex(default_option_index) else: input_widget = QLineEdit() elif extra_keyword_definition['type'] == datetime: input_widget = QDateTimeEdit() input_widget.setCalendarPopup(True) input_widget.setDisplayFormat('hh:mm:ss, d MMM yyyy') input_widget.setDateTime(datetime.now()) else: raise Exception input_widget.setToolTip(extra_keyword_definition['description']) # Signal # noinspection PyUnresolvedReferences check_box.stateChanged.connect(input_widget.setEnabled) return check_box, input_widget
def createEditor(self, parent, styleOption, index): if index.column() == 1: editor = QDateTimeEdit(parent) editor.setDisplayFormat(self.parent().currentDateFormat) editor.setCalendarPopup(True) return editor editor = QLineEdit(parent) # create a completer with the strings in the column as model allStrings = [] for i in range(1, index.model().rowCount()): strItem = index.model().data(index.sibling(i, index.column()), Qt.EditRole) if strItem not in allStrings: allStrings.append(strItem) aS = [str(x.toString()) for x in allStrings] autoComplete = QCompleter(QStringList(",".join(aS))) editor.setCompleter(autoComplete) editor.editingFinished.connect(self.commitAndCloseEditor) return editor
def __init__(self, parent=None): super(DateDialog, self).__init__(parent) layout = QVBoxLayout(self) # nice widget for editing the date self.datetime = QDateTimeEdit(self) self.datetime.setCalendarPopup(True) self.datetime.setDateTime(QDateTime.currentDateTime()) layout.addWidget(self.datetime) # OK and Cancel buttons self.buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self) layout.addWidget(self.buttons) self.buttons.accepted.connect(self.accept) self.buttons.rejected.connect(self.reject)
class RunsDialog(QtHelper.EnhancedQDialog): """ Runs several dialog """ RefreshRepository = pyqtSignal(str) def __init__(self, dialogName, parent = None, iRepo=None, lRepo=None, rRepo=None): """ Constructor """ QtHelper.EnhancedQDialog.__init__(self, parent) self.name = self.tr("Prepare a group of runs") self.projectReady = False self.iRepo = iRepo self.lRepo = lRepo self.rRepo = rRepo self.createDialog() self.createConnections() def createDialog(self): """ Create qt dialog """ self.setWindowTitle( self.name ) mainLayout = QHBoxLayout() layoutTests = QHBoxLayout() layoutRepoTest = QVBoxLayout() self.prjCombo = QComboBox(self) self.prjCombo.setEnabled(False) self.repoTests = QTreeWidget(self) self.repoTests.setFrameShape(QFrame.NoFrame) if USE_PYQT5: self.repoTests.header().setSectionResizeMode(QHeaderView.Stretch) else: self.repoTests.header().setResizeMode(QHeaderView.Stretch) self.repoTests.setHeaderHidden(True) self.repoTests.setContextMenuPolicy(Qt.CustomContextMenu) self.repoTests.setIndentation(10) layoutRepoTest.addWidget(self.prjCombo) layoutRepoTest.addWidget(self.repoTests) self.testsList = QListWidget(self) layoutTests.addLayout( layoutRepoTest ) layoutTests.addWidget( self.testsList ) mainLayout.addLayout( layoutTests ) buttonLayout = QVBoxLayout() self.okButton = QPushButton(self.tr("Execute All"), self) self.okButton.setEnabled(False) self.cancelButton = QPushButton(self.tr("Cancel"), self) self.upButton = QPushButton(self.tr("UP"), self) self.upButton.setEnabled(False) self.downButton = QPushButton(self.tr("DOWN"), self) self.downButton.setEnabled(False) self.clearButton = QPushButton(self.tr("Remove All"), self) self.delButton = QPushButton(self.tr("Remove"), self) self.delButton.setEnabled(False) self.runSimultaneous = QCheckBox(self.tr("Simultaneous Run")) self.schedImmed = QRadioButton(self.tr("Run Immediately")) self.schedImmed.setChecked(True) self.schedAt = QRadioButton(self.tr("Run At:")) self.schedAtDateTimeEdit = QDateTimeEdit(QDateTime.currentDateTime()) self.schedAtDateTimeEdit.setEnabled(False) buttonLayout.addWidget(self.okButton) buttonLayout.addWidget(self.runSimultaneous) buttonLayout.addWidget(self.schedImmed) buttonLayout.addWidget(self.schedAt) buttonLayout.addWidget(self.schedAtDateTimeEdit) buttonLayout.addWidget( self.upButton ) buttonLayout.addWidget( self.downButton ) buttonLayout.addWidget( self.delButton ) buttonLayout.addWidget( self.clearButton ) buttonLayout.addWidget(self.cancelButton) mainLayout.addLayout(buttonLayout) self.setMinimumHeight(400) self.setMinimumWidth(750) self.setLayout(mainLayout) def initProjects(self, projects=[], defaultProject=1): """ Initialize projects """ # init date and time self.schedAtDateTimeEdit.setDateTime(QDateTime.currentDateTime()) self.projectReady = False self.repoTests.clear() self.prjCombo.clear() self.testsList.clear() self.prjCombo.setEnabled(True) # insert data pname = '' for p in projects: self.prjCombo.addItem ( p['name'] ) if defaultProject == p['project_id']: pname = p['name'] for i in xrange(self.prjCombo.count()): item_text = self.prjCombo.itemText(i) if str(pname) == str(item_text): self.prjCombo.setCurrentIndex(i) self.projectReady = True self.RefreshRepository.emit(pname) def initializeTests(self, listing): """ Initialize tests """ self.repoTests.clear() self.testRoot = self.rRepo.Item(repo = self.iRepo.remote(), parent = self.repoTests, txt = "Root", type = QTreeWidgetItem.UserType+10, isRoot = True ) self.testRoot.setSelected(True) self.createRepository(listing=listing, parent=self.testRoot,fileincluded=True) self.repoTests.sortItems(0, Qt.AscendingOrder) self.hideItems(hideTsx=False, hideTpx=False, hideTcx=True, hideTdx=True, hideTxt=True, hidePy=True, hideTux=False, hidePng=True, hideTgx=False, hideTax=False) def createRepository(self, listing, parent, fileincluded=True): """ Create repository @param listing: @type listing: list @param parent: @type parent: @param fileincluded: @type fileincluded: boolean """ try: for dct in listing: if dct["type"] == "folder": item = self.rRepo.Item(repo = self.iRepo.remote(), parent = parent, txt = dct["name"], propertiesFile=dct ) self.createRepository( dct["content"] , item, fileincluded ) else: if fileincluded: if dct["type"] == "file": pname = self.iRepo.remote().getProjectName(dct["project"]) # {'modification': 1342259500, 'type': 'file', 'name': '__init__.py', 'size': '562 } item = self.rRepo.Item(repo = self.iRepo.remote(), parent = parent, txt = dct["name"] , propertiesFile=dct, type = QTreeWidgetItem.UserType+0, projectId=dct["project"], projectName=pname ) except Exception as e: self.error( "unable to create tree for runs: %s" % e ) def onProjectChanged(self, projectItem): """ Called when the project changed on the combo box """ if self.projectReady: item_text = self.prjCombo.itemText(projectItem) self.RefreshRepository.emit(item_text) def createConnections (self): """ create qt connections * ok * cancel """ self.prjCombo.currentIndexChanged.connect(self.onProjectChanged) self.okButton.clicked.connect( self.acceptClicked ) self.cancelButton.clicked.connect( self.reject ) self.upButton.clicked.connect(self.upTest) self.downButton.clicked.connect(self.downTest) self.clearButton.clicked.connect(self.clearList) self.delButton.clicked.connect(self.delTest) self.testsList.itemClicked.connect(self.onItemSelected) self.testsList.itemSelectionChanged.connect(self.onItemSelectionChanged) self.schedAt.toggled.connect(self.onSchedAtActivated) self.repoTests.itemDoubleClicked.connect( self.onTestDoucleClicked ) def onSchedAtActivated(self, toggled): """ On sched at button activated """ if toggled: self.schedAtDateTimeEdit.setEnabled(True) else: self.schedAtDateTimeEdit.setEnabled(False) def onItemSelectionChanged(self): """ Called on item selection changed """ self.onItemSelected(itm=None) def onItemSelected(self, itm): """ Call on item selected """ selectedItems = self.testsList.selectedItems() if len(selectedItems): self.delButton.setEnabled(True) self.upButton.setEnabled(True) self.downButton.setEnabled(True) else: self.delButton.setEnabled(False) self.upButton.setEnabled(False) self.downButton.setEnabled(False) if not self.testsList.count(): self.okButton.setEnabled(False) def upTest(self): """ Up test """ currentRow = self.testsList.currentRow() currentItem = self.testsList.takeItem(currentRow) self.testsList.insertItem(currentRow - 1, currentItem) def downTest(self): """ Down test """ currentRow = self.testsList.currentRow() currentItem = self.testsList.takeItem(currentRow) self.testsList.insertItem(currentRow + 1, currentItem) def delTest(self): """ Del test """ currentRow = self.testsList.currentRow() currentItem = self.testsList.takeItem(currentRow) def clearList(self): """ Clear test """ self.testsList.clear() self.delButton.setEnabled(False) self.upButton.setEnabled(False) self.downButton.setEnabled(False) self.okButton.setEnabled(False) def iterateTree(self, item, hideTsx, hideTpx, hideTcx, hideTdx, hideTxt, hidePy, hideTux, hidePng, hideTgx, hideTax): """ Iterate tree """ child_count = item.childCount() for i in range(child_count): subitem = item.child(i) subchild_count = subitem.childCount() if subchild_count > 0: self.iterateTree(item=subitem, hideTsx=hideTsx, hideTpx=hideTpx, hideTcx=hideTcx, hideTdx=hideTdx, hideTxt=hideTxt, hidePy=hidePy, hideTux=hideTux, hidePng=hidePng, hideTgx=hideTgx, hideTax=hideTax) else: if hideTux and subitem.getExtension() == self.rRepo.EXTENSION_TUX: subitem.setHidden (True) elif hideTpx and subitem.getExtension() == self.rRepo.EXTENSION_TPX: subitem.setHidden (True) elif hideTgx and subitem.getExtension() == self.rRepo.EXTENSION_TGX: subitem.setHidden (True) elif hideTcx and subitem.getExtension() == self.rRepo.EXTENSION_TCX: subitem.setHidden (True) elif hideTsx and subitem.getExtension() == self.rRepo.EXTENSION_TSX: subitem.setHidden (True) elif hideTdx and subitem.getExtension() == self.rRepo.EXTENSION_TDX: subitem.setHidden (True) elif hideTxt and subitem.getExtension() == self.rRepo.EXTENSION_TXT: subitem.setHidden (True) elif hidePy and subitem.getExtension() == self.rRepo.EXTENSION_PY: subitem.setHidden (True) elif hidePng and subitem.getExtension() == self.rRepo.EXTENSION_PNG: subitem.setHidden (True) elif hideTax and subitem.getExtension() == self.rRepo.EXTENSION_TAx: subitem.setHidden (True) else: subitem.setHidden(False) def hideItems(self, hideTsx=False, hideTpx=False, hideTcx=False, hideTdx=False, hideTxt=False, hidePy=False, hideTux=False, hidePng=False, hideTgx=False, hideTax=False): """ Hide items """ root = self.repoTests.invisibleRootItem() self.iterateTree(item=root, hideTsx=hideTsx, hideTpx=hideTpx, hideTcx=hideTcx, hideTdx=hideTdx, hideTxt=hideTxt, hidePy=hidePy, hideTux=hideTux, hidePng=hidePng, hideTgx=hideTgx, hideTax=hideTax) def onTestDoucleClicked(self, testItem): """ On tests double clicked """ if testItem.type() != QTreeWidgetItem.UserType+0: return self.okButton.setEnabled(True) currentProject = self.prjCombo.currentText() testName = "%s:%s" % (str(currentProject),testItem.getPath(withFileName = True)) testItem = QListWidgetItem(testName ) if testName.endswith(self.rRepo.EXTENSION_TUX): testItem.setIcon(QIcon(":/tux.png")) if testName.endswith(self.rRepo.EXTENSION_TSX): testItem.setIcon(QIcon(":/tsx.png")) if testName.endswith(self.rRepo.EXTENSION_TPX): testItem.setIcon(QIcon(":/tpx.png")) if testName.endswith(self.rRepo.EXTENSION_TGX): testItem.setIcon(QIcon(":/tgx.png")) if testName.endswith(self.rRepo.EXTENSION_TAX): testItem.setIcon(QIcon(":/tax.png")) self.testsList.addItem( testItem ) def acceptClicked (self): """ Called on accept button """ self.accept() def getTests(self): """ Returns all tests in the list """ tests = [] for i in xrange(self.testsList.count()): testItem = self.testsList.item(i) tests.append( str(testItem.text()) ) runSimultaneous = False if self.runSimultaneous.isChecked(): runSimultaneous = True if self.schedImmed.isChecked(): runAt = (0,0,0,0,0,0) return (tests, False, runAt, runSimultaneous) else: pydt = self.schedAtDateTimeEdit.dateTime().toPyDateTime() runAt = (pydt.year, pydt.month, pydt.day, pydt.hour, pydt.minute, pydt.second) return (tests, True, runAt, runSimultaneous)
def __init__(self, evt_widget, parent=None): QWidget.__init__(self, parent) self.evt_widget = evt_widget self.verticalLayout = QVBoxLayout(self) spacerItem = QSpacerItem(20, 259, QSizePolicy.Minimum, QSizePolicy.Expanding) tmp_widget = QWidget() self.verticalLayout.addWidget(tmp_widget) hor_layout = QHBoxLayout(tmp_widget) hor_layout.addWidget(QLabel("Display :")) self.admin_events = QPushButton(QIcon(":/green_configure.png"), "Admin. events") self.choose_event_type = QComboBox() self.choose_event_type.addItem(QIcon(":/internet_explorer"), "All", 42) self.choose_event_type.addItem(QIcon(":/audit_success"), "Audit success", EVENTLOG_AUDIT_SUCCESS) self.choose_event_type.addItem(QIcon(":/audit_failure"), "Audit failure", EVENTLOG_AUDIT_FAILURE) self.choose_event_type.addItem(QIcon(":/error"), "Error", EVENTLOG_ERROR_TYPE) self.choose_event_type.addItem(QIcon(":/warning"), "Warning", EVENTLOG_WARNING_TYPE) self.choose_event_type.addItem(QIcon(":/info"), "Information", EVENTLOG_INFORMATION_TYPE) self.choose_event_type.addItem(QIcon(":/chat.png"), "Comment", 5) hor_layout.addWidget(self.choose_event_type) tmp_widget = QWidget() self.verticalLayout.addWidget(tmp_widget) hor_layout = QHBoxLayout(tmp_widget) self.id = QLineEdit() hor_layout.addWidget(QLabel("Id :")) self.cb = QComboBox() self.cbs = QComboBox() self.init() hor_layout.addWidget(self.cb) tmp_widget = QWidget() self.verticalLayout.addWidget(tmp_widget) hor_layout = QHBoxLayout(tmp_widget) self.source = QLineEdit() hor_layout.addWidget(QLabel("Source :")) hor_layout.addWidget(self.cbs) self.verticalLayout.addWidget(QLabel("Start date :")) self.select_date_b = QDateTimeEdit() self.select_date_b.setDisplayFormat("MMM dd yyyy hh:mm AP") self.verticalLayout.addWidget(self.select_date_b) self.verticalLayout.addWidget(QLabel("End date:")) self.select_date_e = QDateTimeEdit() self.select_date_e.setDisplayFormat("MMM dd yyyy hh:mm AP") self.verticalLayout.addWidget(self.select_date_e) self.search_date = QPushButton("Go") self.verticalLayout.addWidget(self.search_date) self.verticalLayout.addItem(spacerItem) self.search_date.clicked.connect(self.filterByDate) self.cb.activated.connect(self.filterById) self.cbs.activated.connect(self.filterBySource) self.choose_event_type.activated.connect(self.filterByLvl)
def _create_widget(cls, c, parent, host=None): dtt = QDateTimeEdit(parent) dtt.setObjectName(u'{0}_{1}'.format(cls._TYPE_PREFIX, c.name)) dtt.setCalendarPopup(True) # Set ranges if c.min_use_current_datetime: dtt.setMinimumDateTime(datetime.today()) else: dtt.setMinimumDateTime(c.minimum) if c.max_use_current_datetime: dtt.setMaximumDateTime(datetime.today()) else: dtt.setMaximumDateTime(c.maximum) # Set maximum datetime as current datetime dtt.setDateTime(dtt.maximumDateTime()) return dtt
def createWidget(self, parent): wid = QDateTimeEdit(parent) wid.setCalendarPopup(True) wid.setFrame(False) return wid
def updateParamsAndTemplates(self, templateIndex): #Удаление всех виджетов для ввода параметров шаблона (QLabel и QWidget) for widget in self.scrollAreaWidgetContents.children(): if not isinstance(widget, QLayout): self.paramNamesLayout.removeWidget(widget) self.paramValuesLayout.removeWidget(widget) self._templateParamsWidgets.clear() self._templateNameWithPathList = [] self._templateStmts = {} codecName = forceString(self.cmbCodec.currentText()) templateDirectory = CExportToDbfDialog.getTemplatesDirectory() templateNameWithPath = forceString(self.cmbExportTemplates.itemData(templateIndex)) # Если выбран режим работы с группой шаблонов if self.rbTemplateGroups.isChecked(): #Подгружается файл группы шаблонов (текстовый документ, где построчно указываются пути к файлам с шаблонами группы) templateGroupNameWithPath = templateNameWithPath + self.groupExt if not os.path.exists(templateGroupNameWithPath): return with codecs.open(templateGroupNameWithPath, 'r', encoding = codecName) as groupFile: lineList = groupFile.readlines() for fileLine in lineList: fileLine = fileLine.strip() if fileLine.startswith('..'): templateNameWithPath = fileLine.replace('..', os.path.dirname(templateDirectory), 1) elif fileLine.startswith('.'): templateNameWithPath = fileLine.replace('.', templateDirectory, 1) elif os.path.basename(fileLine) == fileLine: templateNameWithPath = os.path.join(templateDirectory, fileLine) else: templateNameWithPath = os.path.abspath(fileLine) if not CExportToDbfDialog.isCorrectTemplateName(templateNameWithPath): templateNameWithPath = os.path.splitext(templateNameWithPath)[0] if not CExportToDbfDialog.isCorrectTemplateName(templateNameWithPath): continue self._templateNameWithPathList.append(os.path.abspath(templateNameWithPath)) else: if CExportToDbfDialog.isCorrectTemplateName(templateNameWithPath): self._templateNameWithPathList.append(os.path.abspath(templateNameWithPath)) for templateNameWithPath in self._templateNameWithPathList: with codecs.open(templateNameWithPath + self.sqlExt, 'r', encoding = codecName) as templateFile: matches = [] try: self._templateStmts[templateNameWithPath] = templateFile.read() matches = self._pattern.findall(self._templateStmts[templateNameWithPath]) except: QtGui.qApp.logCurrentException() self.markTemplateAsIncorrect(templateIndex) for match in matches: paramName = match[0] paramType = match[1] if not self._templateParamsWidgets.has_key((paramName, paramType)): if paramType == 'b': self._templateParamsWidgets[(paramName, paramType)] = QCheckBox() elif paramType == 'f': self._templateParamsWidgets[(paramName, paramType)] = QDoubleSpinBox() self._templateParamsWidgets[(paramName, paramType)].setRange(-999.999, 999.999) elif paramType == 'd': self._templateParamsWidgets[(paramName, paramType)] = QDateEdit() self._templateParamsWidgets[(paramName, paramType)].setCalendarPopup(True) self._templateParamsWidgets[(paramName, paramType)].setDate(QDate.currentDate()) elif paramType == 't': self._templateParamsWidgets[(paramName, paramType)] = QDateTimeEdit() self._templateParamsWidgets[(paramName, paramType)].setCalendarPopup(True) self._templateParamsWidgets[(paramName, paramType)].setDate(QDate.currentDate()) elif paramType == 's': self._templateParamsWidgets[(paramName, paramType)] = QLineEdit() elif paramType == 'i': self._templateParamsWidgets[(paramName, paramType)] = QSpinBox() self._templateParamsWidgets[(paramName, paramType)].setRange(-999999, 999999) #end for match in matches #end with codecs.open(templateNameWithPath #end for templateNameWithPath for item in self._templateParamsWidgets.items(): self.paramNamesLayout.addWidget(QLabel('%s:' % item[0][0].replace('_', ' ')), alignment = Qt.AlignRight) self.paramValuesLayout.addWidget(item[1]) item[1].setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
class DlgAixmEffectiveDate(QDialog): def __init__(self, parent=None): QDialog.__init__(self, parent) self.resize(290, 136) self.setWindowTitle("Effective Date") 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")) self.groupBox = GroupBox(self) verticalLayoutDlg.addWidget(self.groupBox) self.dtpDate = QDateTimeEdit(self.groupBox) self.dtpDate.setObjectName(("dtpDate")) self.dtpDate.setDateTime(QDateTime.currentDateTime()) self.groupBox.Add = self.dtpDate self.calendar = QCalendarWidget(self.groupBox) self.groupBox.Add = self.calendar self.calendar.clicked.connect(self.calendar_clicked) self.btnBoxOkCancel = QDialogButtonBox(self) self.btnBoxOkCancel.setObjectName(("btnBoxOkCancel")) self.btnBoxOkCancel.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) # btnOK = self.btnBoxOkCancel.button(QDialogButtonBox.Ok) # btnOK.setText("Create") self.connect(self.btnBoxOkCancel, SIGNAL("accepted()"), self.acceptDlg) self.connect(self.btnBoxOkCancel, SIGNAL("rejected()"), self.reject) verticalLayoutDlg.addWidget(self.btnBoxOkCancel) def calendar_clicked(self, date): self.dtpDate.setDate(date) def get_DateTime(self): return self.dtpDate.dateTime() def set_DateTime(self, dateTime): if dateTime != None: self.dtpDate.setDateTime(dateTime) self.calendar.setCurrentPage(dateTime.date().year(), dateTime.date().month()) DateTime = property(get_DateTime, set_DateTime, None, None) def acceptDlg(self): self.accept() @staticmethod def smethod_0(dateTime_0): flag = False dlgAixmEffectiveDate = DlgAixmEffectiveDate() dlgAixmEffectiveDate.dtpDate.setDateTime(dateTime_0) resultDlg = dlgAixmEffectiveDate.exec_() if (resultDlg != 1): return False, dateTime_0 else: dateTime_0 = dlgAixmEffectiveDate.DateTime flag = True return flag, dateTime_0
class dlgSelectCuenta( QDialog ): def __init__( self, parent = None ): super( dlgSelectCuenta, self ).__init__( parent ) self.padre = parent self.ctaBancomodel = QSqlQueryModel() self.ctaBancomodel.setQuery( """ SELECT b.descripcion as Banco, cb.ctabancaria as 'No. Cuenta', tm.simbolo as Moneda, c.codigo as 'Codigo Contable', c.idcuenta as Id, c.descripcion as 'Cuenta Contable', IF( con.fecha IS NULL, LAST_DAY(MIN(d.fechacreacion)), (MAX(con.fecha) + INTERVAL 1 MONTH)) AS conciliar FROM cuentasbancarias cb JOIN bancos b ON cb.idbanco=b.idbanco JOIN cuentascontables c ON c.idcuenta=cb.idcuentacontable JOIN tiposmoneda tm ON tm.idtipomoneda=cb.idtipomoneda LEFT JOIN conciliaciones con ON con.idcuentabancaria=cb.idcuentacontable LEFT JOIN cuentasxdocumento cd ON cd.idcuenta=c.idcuenta LEFT JOIN documentos d ON cd.iddocumento = d.iddocumento WHERE d.iddocumento IS NOT NULL GROUP BY c.idcuenta ; """ ) # # if self.ctaBancomodel.rowCount() == 0 : # QMessageBox.critical(self,"Cuentas Bancarias","No existe ninguna cuenta bancaria") # self.destroy() self.setWindowTitle( u"Elija fecha y cuenta bancaria para la conciliación" ) self.filtermodel = QSortFilterProxyModel() self.filtermodel.setSourceModel( self.ctaBancomodel ) self.filtermodel.setFilterCaseSensitivity( Qt.CaseInsensitive ) self.filtermodel.setFilterKeyColumn( -1 ) self.tblCuenta = QTableView() self.tblCuenta.setSelectionMode( QAbstractItemView.SingleSelection ) self.tblCuenta.setSelectionBehavior( QAbstractItemView.SelectRows ) self.tblCuenta.setModel( self.filtermodel ) buttonbox = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel ) self.txtSearch = QLineEdit() formlayout = QFormLayout() formlayout.addRow( "&Buscar", self.txtSearch ) self.dtPicker = QDateTimeEdit() self.dtPicker.setReadOnly( True ) # self.dtPicker.setCalendarPopup(True) self.dtPicker.setAlignment( Qt.AlignHCenter ) self.dtPicker.setDisplayFormat( "MMMM 'd'el yyyy" ) # self.dtPicker.setMinimumDate(QDate(2009,1,1)) fecha = QDate.currentDate() self.dtPicker.setDate( QDate( fecha.year(), fecha.month(), fecha.daysInMonth() ) ) fechalayout = QFormLayout() fechalayout.addRow( "&Fecha", self.dtPicker ) layout = QVBoxLayout() layout.addLayout( fechalayout ) layout.addWidget( self.tblCuenta ) layout.addLayout( formlayout ) layout.addWidget( buttonbox ) self.setLayout( layout ) self.setMinimumWidth( 400 ) buttonbox.accepted.connect( self.aceptar ) buttonbox.rejected.connect( self.reject ) self.txtSearch.textChanged[unicode].connect( self.updateFilter ) self.tblCuenta.selectionModel().currentChanged[QModelIndex, QModelIndex].connect( self.on_tblCuenta_currentChanged ) self.setModal( True ) self.setWindowFlags( Qt.Dialog | Qt.MSWindowsFixedSizeDialogHint | Qt.WindowTitleHint ) self.show() self.tblCuenta.setFocus() self.tblCuenta.selectRow( 0 ) self.tblCuenta.setColumnHidden( 4, True ) self.tblCuenta.setColumnHidden( 5, True ) self.tblCuenta.setColumnHidden( 6, True ) self.tblCuenta.horizontalHeader().setStretchLastSection( True ) self.tblCuenta.resizeColumnsToContents() @property def data( self ): data = {} fila = self.tblCuenta.selectionModel().currentIndex().row() fecha = self.dtPicker.date() data['banco'] = self.filtermodel.index( fila, 0 ).data().toString() data['id_cuenta_contable'] = self.filtermodel.index( fila, 4 ).data().toInt()[0] data['codigo_cuenta_contable'] = self.filtermodel.index( fila, 3 ).data().toString() data['cuenta_bancaria'] = self.filtermodel.index( fila, 5 ).data().toString() data['fecha'] = QDate( fecha.year(), fecha.month(), fecha.daysInMonth() ) data['moneda'] = self.filtermodel.index( fila, 2 ).data().toString() if not QSqlDatabase.database().isOpen() and not QSqlDatabase.open(): raise Exception( QSqlDatabase.lastError() ) query = QSqlQuery() if not query.exec_( "CALL spSaldoCuenta( %d, %s )" % ( data['id_cuenta_contable'], QDate( data['fecha'].year(), data['fecha'].month(), data['fecha'].daysInMonth() ).toString( "yyyyMMdd" ) ) ): raise Exception( query.lastError().text() ) query.first() data['saldo_inicial_libro'] = Decimal( query.value( 0 ).toString() ) return data 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() def exec_( self ): if self.ctaBancomodel.rowCount() == 0: QMessageBox.critical( self.padre, "Cuentas Bancarias", "No existe ninguna cuenta bancaria con movimientos en este mes" ) return self.reject() else: return QDialog.exec_( self ) def updateFilter( self, str ): self.filtermodel.setFilterWildcard( str ) # @pyqtSlot( "QModelIndex" ) # def on_tblCuenta_clicked(self, index): 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()
class TplRow(QWidget): def __init__(self, parent = None, _id = 0): super(TplRow, self).__init__(parent) self.id = _id self.setLayout(QHBoxLayout()) self.idLabel = QLabel(self) self.beginEdit = QDateTimeEdit(self) self.beginEdit.setCalendarPopup(True) self.endEdit = QDateTimeEdit(self) self.endEdit.setCalendarPopup(True) self.timeDiff = ClickLabel(self) self.descriptionEdit = QLineEdit(self) self.noteEdit = QLineEdit(self) self.delButton = QPushButton(self) self.delButton.setText('X') self.layout().addWidget(self.idLabel) self.layout().addWidget(self.beginEdit) self.layout().addWidget(self.endEdit) self.layout().addWidget(self.timeDiff) self.layout().addWidget(self.descriptionEdit) self.layout().addWidget(self.noteEdit) self.layout().addWidget(self.delButton) self.layout().setContentsMargins(2,2,2,2) self.connect(self.descriptionEdit, SIGNAL('editingFinished ()'), self.notify) self.connect(self.noteEdit, SIGNAL('editingFinished ()'), self.notify) self.connect(self.beginEdit, SIGNAL('editingFinished ()'), self.notify) self.connect(self.endEdit, SIGNAL('editingFinished ()'), self.notify) self.connect(self.delButton, SIGNAL('clicked()'), self.delete) self.connect(self.timeDiff, SIGNAL('clicked()'), self.onTimeDiff) def set(self, tpl): self.idLabel.setText(str(tpl[0])) self.beginEdit.setDateTime(QDateTime.fromTime_t(tpl[1])) self.endEdit.setDateTime(QDateTime.fromTime_t(tpl[2])) self.timeDiff.setText( self.mkDiff( tpl[1], tpl[2] ) ) self.descriptionEdit.setText(str(tpl[3])) self.noteEdit.setText(str(tpl[4])) def get(self): tpl = [] tpl.append(int(self.idLabel.text())) tpl.append(self.beginEdit.dateTime().toTime_t()) tpl.append(self.endEdit.dateTime().toTime_t()) tpl.append(self.descriptionEdit.text()) tpl.append(self.noteEdit.text()) return tpl def clear(self): self.beginEdit.clear() self.endEdit.clear() self.timeDiff.clear() self.descriptionEdit.clear() self.noteEdit.clear() self.idLabel.clear() def mkDiff(self, begin, end): return '%4d' % ceil( float( end - begin ) / 60 ) @pyqtSlot() def onTimeDiff(self): self.parent().parent().parent().statusBar.showMessage( '%s copied to clipboard.' % self.timeDiff.text() ) self.parent().clipboard.setText( str(self.timeDiff.text()).strip() ) @pyqtSlot() def delete(self): if self.idLabel.text(): if QMessageBox.question(self, 'delete ?', 'really delete id %s ?' % self.idLabel.text(), QMessageBox.Yes|QMessageBox.No, QMessageBox.No) == QMessageBox.Yes: self.emit(SIGNAL('del(int)'), self.id) @pyqtSlot() def notify(self): if self.idLabel.text(): self.timeDiff.setText( self.mkDiff( self.beginEdit.dateTime().toTime_t(), self.endEdit.dateTime().toTime_t() ) ) self.emit(SIGNAL('valueChanged(int)'), self.id)
class EvtxAdminPannel(QWidget): def __init__(self, parent=None, chunks=[]): super(EvtxAdminPannel, self).__init__(parent) self.verticalLayout = QVBoxLayout(self) spacerItem = QSpacerItem(20, 259, QSizePolicy.Minimum, QSizePolicy.Expanding) self.verticalLayout.setMargin(3) self.verticalLayout.addWidget( QLabel("Number of chunk(s) : " + str(len(chunks)))) nb_rec = 0 for i in chunks: nb_rec += i.nbRecord() self.nb_rec = nb_rec self.verticalLayout.addWidget( QLabel("Number of record(s) : " + str(nb_rec))) tmp_widget = QWidget() self.verticalLayout.addWidget(tmp_widget) hor_layout = QHBoxLayout(tmp_widget) hor_layout.addWidget(QLabel("Display :")) self.admin_events = QPushButton(QIcon(":/green_configure.png"), "Admin. events") hor_layout.addWidget(self.admin_events) self.choose_event_type = QComboBox() self.choose_event_type.addItem(QIcon(":/internet_explorer"), "All", 42) self.choose_event_type.addItem(QIcon(":/audit_success"), "Audit success", 0) self.choose_event_type.addItem(QIcon(":/audit_failure"), "Audit failure", 1) self.choose_event_type.addItem(QIcon(":/error"), "Error", 2) self.choose_event_type.addItem(QIcon(":/warning"), "Warning", 3) self.choose_event_type.addItem(QIcon(":/info"), "Information", 4) self.choose_event_type.addItem(QIcon(":/chat.png"), "Comment", 5) hor_layout.addWidget(self.choose_event_type) tmp_widget = QWidget() self.verticalLayout.addWidget(tmp_widget) hor_layout = QHBoxLayout(tmp_widget) self.id = QLineEdit() hor_layout.addWidget(QLabel("Id :")) self.cb = self.initId(chunks, 'id') self.cb.setMaxVisibleItems(15) hor_layout.addWidget(self.cb) hor_layout.addWidget(self.id) self.search_id = QPushButton("Go") hor_layout.addWidget(self.search_id) tmp_widget = QWidget() self.verticalLayout.addWidget(tmp_widget) hor_layout = QHBoxLayout(tmp_widget) self.source = QLineEdit() hor_layout.addWidget(QLabel("Source :")) self.cbs = self.initId(chunks, 'source') hor_layout.addWidget(self.cbs) hor_layout.addWidget(self.source) self.search_source = QPushButton("Go") hor_layout.addWidget(self.search_source) self.verticalLayout.addWidget(QLabel("Date debut :")) self.select_date_b = QDateTimeEdit() self.select_date_b.setDisplayFormat("MMM dd yyyy hh:mm AP") self.verticalLayout.addWidget(self.select_date_b) self.verticalLayout.addWidget(QLabel("date fin:")) self.select_date_e = QDateTimeEdit() self.select_date_e.setDisplayFormat("MMM dd yyyy hh:mm AP") self.verticalLayout.addWidget(self.select_date_e) self.search_date = QPushButton("Go") self.verticalLayout.addWidget(self.search_date) self.verticalLayout.addItem(spacerItem) def initId(self, chunks, param): cb = QComboBox() tmp_list = [] for chunk in chunks: events = chunk.events() for event in events: tmp_list.append(str(events[event][param])) tmp_list = self.unique(tmp_list) cb.addItems(tmp_list) return cb def unique(self, seq, idfun=None): # order preserving if idfun is None: def idfun(x): return x seen = {} result = [] for item in seq: marker = idfun(item) if marker in seen: continue seen[marker] = 1 if item is not None: result.append(item) return sorted(result)
def __init__(self, parent=None, chunks=[]): super(EvtxAdminPannel, self).__init__(parent) self.verticalLayout = QVBoxLayout(self) spacerItem = QSpacerItem(20, 259, QSizePolicy.Minimum, QSizePolicy.Expanding) self.verticalLayout.setMargin(3) self.verticalLayout.addWidget( QLabel("Number of chunk(s) : " + str(len(chunks)))) nb_rec = 0 for i in chunks: nb_rec += i.nbRecord() self.nb_rec = nb_rec self.verticalLayout.addWidget( QLabel("Number of record(s) : " + str(nb_rec))) tmp_widget = QWidget() self.verticalLayout.addWidget(tmp_widget) hor_layout = QHBoxLayout(tmp_widget) hor_layout.addWidget(QLabel("Display :")) self.admin_events = QPushButton(QIcon(":/green_configure.png"), "Admin. events") hor_layout.addWidget(self.admin_events) self.choose_event_type = QComboBox() self.choose_event_type.addItem(QIcon(":/internet_explorer"), "All", 42) self.choose_event_type.addItem(QIcon(":/audit_success"), "Audit success", 0) self.choose_event_type.addItem(QIcon(":/audit_failure"), "Audit failure", 1) self.choose_event_type.addItem(QIcon(":/error"), "Error", 2) self.choose_event_type.addItem(QIcon(":/warning"), "Warning", 3) self.choose_event_type.addItem(QIcon(":/info"), "Information", 4) self.choose_event_type.addItem(QIcon(":/chat.png"), "Comment", 5) hor_layout.addWidget(self.choose_event_type) tmp_widget = QWidget() self.verticalLayout.addWidget(tmp_widget) hor_layout = QHBoxLayout(tmp_widget) self.id = QLineEdit() hor_layout.addWidget(QLabel("Id :")) self.cb = self.initId(chunks, 'id') self.cb.setMaxVisibleItems(15) hor_layout.addWidget(self.cb) hor_layout.addWidget(self.id) self.search_id = QPushButton("Go") hor_layout.addWidget(self.search_id) tmp_widget = QWidget() self.verticalLayout.addWidget(tmp_widget) hor_layout = QHBoxLayout(tmp_widget) self.source = QLineEdit() hor_layout.addWidget(QLabel("Source :")) self.cbs = self.initId(chunks, 'source') hor_layout.addWidget(self.cbs) hor_layout.addWidget(self.source) self.search_source = QPushButton("Go") hor_layout.addWidget(self.search_source) self.verticalLayout.addWidget(QLabel("Date debut :")) self.select_date_b = QDateTimeEdit() self.select_date_b.setDisplayFormat("MMM dd yyyy hh:mm AP") self.verticalLayout.addWidget(self.select_date_b) self.verticalLayout.addWidget(QLabel("date fin:")) self.select_date_e = QDateTimeEdit() self.select_date_e.setDisplayFormat("MMM dd yyyy hh:mm AP") self.verticalLayout.addWidget(self.select_date_e) self.search_date = QPushButton("Go") self.verticalLayout.addWidget(self.search_date) self.verticalLayout.addItem(spacerItem)
def setDateTime(self): self.datetime = QDateTimeEdit(self) self.datetime.setCalendarPopup(True) self.hlayout.addWidget(self.datetime, 50)
def createEditor(self, parent, option, index): editor = QDateTimeEdit(parent) editor.setCalendarPopup(True) return editor
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.agreement1ID = 'AG01' self.agreement2ID = 'AG02' self.dbNameInit = 'test1' self.calculate1 = '+' self.c1 = '1' self.c3 = '1' self.threads = [] self.onInit() def onInit(self): self.resize(450, 300) self.center() self.setMenu() self.setWindowTitle(u'MainWindow') self.setWindowIcon(QIcon('learning.ico')) self.agreement1 = QLabel('Contract1', self) self.agreement11 = QLabel(' Contract1 *', self) self.agreement2 = QLabel('Contract2', self) self.agreement22 = QLabel('Contract2 *', self) self.calculate = QLabel('Formula', self) self.startTime = QLabel('Start Time', self) self.endTime = QLabel('End Time', self) self.agreement1Edit = QLineEdit() self.agreement2Edit = QLineEdit() self.calculate1Edit = QLineEdit() self.calculate2Combo = QComboBox() self.calculate2Combo.addItem('+') self.calculate2Combo.addItem('-') self.calculate2Combo.addItem('*') self.calculate2Combo.addItem('/') self.calculate2Combo.activated[str].connect(self.onActivated) self.calculate2Edit = QLineEdit() self.calculate3Edit = QLineEdit() self.startTimeEdit = QDateTimeEdit( datetime.strptime('20150101 00:00:00', '%Y%m%d %H:%M:%S'), self) self.startTimeEdit.setDisplayFormat('yyyy-MM-dd') self.startTimeEdit.setCalendarPopup(True) self.endTimeEdit = QDateTimeEdit(QDateTime.currentDateTime(), self) self.endTimeEdit.setDisplayFormat('yyyy-MM-dd') self.endTimeEdit.setCalendarPopup(True) self.stateEdit = QTextEdit() self.run = QPushButton('Run', self) self.run.clicked.connect(self.runMain) #self.setAgreementBtn = QPushButton('Setting', self) #self.setAgreementBtn.clicked.connect(self.setAgreement) grid = QGridLayout() #grid.setSpacing(10) grid.addWidget(self.agreement1, 1, 0) grid.addWidget(self.agreement1Edit, 1, 1) grid.addWidget(self.agreement2, 2, 0) grid.addWidget(self.agreement2Edit, 2, 1) #grid.addWidget(self.setAgreementBtn, 2, 2) grid.addWidget(self.startTime, 3, 0) grid.addWidget(self.startTimeEdit, 3, 1) grid.addWidget(self.endTime, 4, 0) grid.addWidget(self.endTimeEdit, 4, 1) grid.addWidget(self.calculate, 5, 0) grid.addWidget(self.agreement11, 5, 1) grid.addWidget(self.calculate1Edit, 5, 2) grid.addWidget(self.calculate2Combo, 5, 3) grid.addWidget(self.agreement22, 5, 4) grid.addWidget(self.calculate3Edit, 5, 5) grid.addWidget(self.stateEdit, 6, 1, 1, 5) grid.addWidget(self.run, 7, 1) gridWidget = QWidget() gridWidget.setLayout(grid) self.agreement11.move(200, 100) self.setCentralWidget(gridWidget) self.show() def onActivated(self, text): self.calculate1 = text def setMenu(self): exitAction = QAction(u'Quit', self) exitAction.triggered.connect(qApp.quit) menubar = self.menuBar() fileMenu = menubar.addMenu(u'Menu') fileMenu.addAction(exitAction) def center(self): qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) def done(self, ls): self.stateEdit.append(u'Maximum:%f' % ls[1]) self.stateEdit.append(u'Minimum:%f' % ls[2]) self.stateEdit.append(u'Average:%f' % ls[3]) show(ls[0]) self.run.setEnabled(True) self.stateEdit.append('End time: %s' % time.ctime()) def runMain(self): self.run.setEnabled(False) agreementt1 = self.agreement1Edit.text() agreementt2 = self.agreement2Edit.text() if agreementt1 == '': self.stateEdit.append('Settings of contract1 have error!') elif agreementt2 == '': self.stateEdit.append('Settings of contract2 have error!') else: self.agreement1ID = agreementt1 self.agreement2ID = agreementt2 startTime = self.startTimeEdit.dateTime() endTime = self.endTimeEdit.dateTime() self.c1 = self.calculate1Edit.text() self.c3 = self.calculate3Edit.text() self.stateEdit.append('Formula: ' + self.c1 + '*' + self.agreement1ID + self.calculate1 + self.c3 + '*' + self.agreement2ID + ' have set') self.stateEdit.append('Start time: %s' % time.ctime()) self.workThread = WorkThread(self.agreement1ID, self.agreement2ID, startTime, endTime, self.c1, self.c3, self.calculate1) self.workThread.finishSignal.connect(self.done) self.workThread.start()
def createDialog(self): """ Create qt dialog """ self.setWindowTitle( self.name ) mainLayout = QHBoxLayout() layoutTests = QHBoxLayout() layoutRepoTest = QVBoxLayout() self.prjCombo = QComboBox(self) self.prjCombo.setEnabled(False) self.repoTests = QTreeWidget(self) self.repoTests.setFrameShape(QFrame.NoFrame) if USE_PYQT5: self.repoTests.header().setSectionResizeMode(QHeaderView.Stretch) else: self.repoTests.header().setResizeMode(QHeaderView.Stretch) self.repoTests.setHeaderHidden(True) self.repoTests.setContextMenuPolicy(Qt.CustomContextMenu) self.repoTests.setIndentation(10) layoutRepoTest.addWidget(self.prjCombo) layoutRepoTest.addWidget(self.repoTests) self.testsList = QListWidget(self) layoutTests.addLayout( layoutRepoTest ) layoutTests.addWidget( self.testsList ) mainLayout.addLayout( layoutTests ) buttonLayout = QVBoxLayout() self.okButton = QPushButton(self.tr("Execute All"), self) self.okButton.setEnabled(False) self.cancelButton = QPushButton(self.tr("Cancel"), self) self.upButton = QPushButton(self.tr("UP"), self) self.upButton.setEnabled(False) self.downButton = QPushButton(self.tr("DOWN"), self) self.downButton.setEnabled(False) self.clearButton = QPushButton(self.tr("Remove All"), self) self.delButton = QPushButton(self.tr("Remove"), self) self.delButton.setEnabled(False) self.runSimultaneous = QCheckBox(self.tr("Simultaneous Run")) self.schedImmed = QRadioButton(self.tr("Run Immediately")) self.schedImmed.setChecked(True) self.schedAt = QRadioButton(self.tr("Run At:")) self.schedAtDateTimeEdit = QDateTimeEdit(QDateTime.currentDateTime()) self.schedAtDateTimeEdit.setEnabled(False) buttonLayout.addWidget(self.okButton) buttonLayout.addWidget(self.runSimultaneous) buttonLayout.addWidget(self.schedImmed) buttonLayout.addWidget(self.schedAt) buttonLayout.addWidget(self.schedAtDateTimeEdit) buttonLayout.addWidget( self.upButton ) buttonLayout.addWidget( self.downButton ) buttonLayout.addWidget( self.delButton ) buttonLayout.addWidget( self.clearButton ) buttonLayout.addWidget(self.cancelButton) mainLayout.addLayout(buttonLayout) self.setMinimumHeight(400) self.setMinimumWidth(750) self.setLayout(mainLayout)
class EvtControlPannel(QWidget): def __init__(self, evt_widget, parent=None): QWidget.__init__(self, parent) self.evt_widget = evt_widget self.verticalLayout = QVBoxLayout(self) spacerItem = QSpacerItem(20, 259, QSizePolicy.Minimum, QSizePolicy.Expanding) tmp_widget = QWidget() self.verticalLayout.addWidget(tmp_widget) hor_layout = QHBoxLayout(tmp_widget) hor_layout.addWidget(QLabel("Display :")) self.admin_events = QPushButton(QIcon(":/green_configure.png"), "Admin. events") self.choose_event_type = QComboBox() self.choose_event_type.addItem(QIcon(":/internet_explorer"), "All", 42) self.choose_event_type.addItem(QIcon(":/audit_success"), "Audit success", EVENTLOG_AUDIT_SUCCESS) self.choose_event_type.addItem(QIcon(":/audit_failure"), "Audit failure", EVENTLOG_AUDIT_FAILURE) self.choose_event_type.addItem(QIcon(":/error"), "Error", EVENTLOG_ERROR_TYPE) self.choose_event_type.addItem(QIcon(":/warning"), "Warning", EVENTLOG_WARNING_TYPE) self.choose_event_type.addItem(QIcon(":/info"), "Information", EVENTLOG_INFORMATION_TYPE) self.choose_event_type.addItem(QIcon(":/chat.png"), "Comment", 5) hor_layout.addWidget(self.choose_event_type) tmp_widget = QWidget() self.verticalLayout.addWidget(tmp_widget) hor_layout = QHBoxLayout(tmp_widget) self.id = QLineEdit() hor_layout.addWidget(QLabel("Id :")) self.cb = QComboBox() self.cbs = QComboBox() self.init() hor_layout.addWidget(self.cb) tmp_widget = QWidget() self.verticalLayout.addWidget(tmp_widget) hor_layout = QHBoxLayout(tmp_widget) self.source = QLineEdit() hor_layout.addWidget(QLabel("Source :")) hor_layout.addWidget(self.cbs) self.verticalLayout.addWidget(QLabel("Start date :")) self.select_date_b = QDateTimeEdit() self.select_date_b.setDisplayFormat("MMM dd yyyy hh:mm AP") self.verticalLayout.addWidget(self.select_date_b) self.verticalLayout.addWidget(QLabel("End date:")) self.select_date_e = QDateTimeEdit() self.select_date_e.setDisplayFormat("MMM dd yyyy hh:mm AP") self.verticalLayout.addWidget(self.select_date_e) self.search_date = QPushButton("Go") self.verticalLayout.addWidget(self.search_date) self.verticalLayout.addItem(spacerItem) self.search_date.clicked.connect(self.filterByDate) self.cb.activated.connect(self.filterById) self.cbs.activated.connect(self.filterBySource) self.choose_event_type.activated.connect(self.filterByLvl) def filterByDate(self, checked): date_begin = self.select_date_b.dateTime() date_end = self.select_date_e.dateTime() date_begin_str = str(date_begin.toString('yyyy-MM-dd hh:mm:ss')) date_end_str = str(date_end.toString('yyyy-MM-dd hh:mm:ss')) if date_begin > date_end: message = QMessageBox() message.setText('Date mismatch.') message.exec_() else: for i in range(self.evt_widget.rowCount()): data = self.evt_widget.item(i, 2) if data.text() >= date_begin_str and data.text( ) <= date_end_str: self.evt_widget.showRow(i) else: self.evt_widget.hideRow(i) def filterById(self, index): lvl = self.cb.currentText() for i in range(self.evt_widget.rowCount()): item = self.evt_widget.item(i, 1) data = item.text() if data != lvl: self.evt_widget.hideRow(i) else: self.evt_widget.showRow(i) def dispAll(self): for i in range(self.evt_widget.rowCount()): self.evt_widget.showRow(i) def filterByLvl(self, index): type_e = self.choose_event_type.currentText() if type_e == 'All': self.dispAll() else: for i in range(self.evt_widget.rowCount()): item = self.evt_widget.item(i, 0) data = item.text() if data != type_e: self.evt_widget.hideRow(i) else: self.evt_widget.showRow(i) def reload(self, item): self.init() def filterBySource(self, index): lvl = self.cbs.currentText() for i in range(self.evt_widget.rowCount()): item = self.evt_widget.item(i, 3) data = item.text() if data != lvl: self.evt_widget.hideRow(i) else: self.evt_widget.showRow(i) def init(self): tmp_list = [] tmp_list2 = [] self.cb.clear() self.cbs.clear() for i in range(self.evt_widget.rowCount()): item = self.evt_widget.item(i, 1).text() tmp_list.append(item) item = self.evt_widget.item(i, 3).text() tmp_list2.append(item) tmp_list = self.unique(tmp_list) tmp_list2 = self.unique(tmp_list2) self.cb.addItems(tmp_list) self.cbs.addItems(tmp_list2) def unique(self, seq, idfun=None): # order preserving if idfun is None: def idfun(x): return x seen = {} result = [] for item in seq: marker = idfun(item) if marker in seen: continue seen[marker] = 1 if item is not None: result.append(item) return sorted(result)
def setup(self): for key, value in self.data: # Separate parameter attribute's name and help description label = key[0] help = key[1] if DEBUG: print "value:", value if label is None and value is None: # Separator: (None, None) self.formlayout.addRow(QLabel(" "), QLabel(" ")) self.widgets[None] = None continue elif label is None: # Comment self.formlayout.addRow(QLabel(value)) self.widgets[None] = value continue elif tuple_to_qfont(value) is not None: field = FontLayout(value, self) elif text_to_qcolor(value).isValid(): field = ColorLayout(QColor(value), self) elif isinstance(value, (str, unicode)): if (label == 'Help'): self.help.insert(0, value) continue else: field = QLineEdit(value, self) elif isinstance(value, (list, tuple)): selindex = value.pop(0) field = QComboBox(self) if isinstance(value[0], (list, tuple)): keys = [key for key, _val in value] value = [val for _key, val in value] else: keys = value field.addItems(value) if selindex in value: selindex = value.index(selindex) elif selindex in keys: selindex = keys.index(selindex) elif not isinstance(selindex, int): print >>STDERR, "Warning: '%s' index is invalid (label: " \ "%s, value: %s)" % (selindex, label, value) selindex = 0 field.setCurrentIndex(selindex) elif isinstance(value, bool): field = QCheckBox(self) field.setCheckState(Qt.Checked if value else Qt.Unchecked) elif isinstance(value, float): field = QLineEdit(repr(value), self) elif isinstance(value, int): field = QSpinBox(self) field.setRange(-1e9, 1e9) field.setValue(value) elif isinstance(value, datetime.datetime): field = QDateTimeEdit(self) field.setDateTime(value) elif isinstance(value, datetime.date): field = QDateEdit(self) field.setDate(value) else: field = QLineEdit(repr(value), self) field.setToolTip(QString(help)) self.help.append(label + ' -- ' + help) self.formlayout.addRow(label, field) # Add close button self.widgets[label] = field
def __init__( self, parent = None ): super( dlgSelectCuenta, self ).__init__( parent ) self.padre = parent self.ctaBancomodel = QSqlQueryModel() self.ctaBancomodel.setQuery( """ SELECT b.descripcion as Banco, cb.ctabancaria as 'No. Cuenta', tm.simbolo as Moneda, c.codigo as 'Codigo Contable', c.idcuenta as Id, c.descripcion as 'Cuenta Contable', IF( con.fecha IS NULL, LAST_DAY(MIN(d.fechacreacion)), (MAX(con.fecha) + INTERVAL 1 MONTH)) AS conciliar FROM cuentasbancarias cb JOIN bancos b ON cb.idbanco=b.idbanco JOIN cuentascontables c ON c.idcuenta=cb.idcuentacontable JOIN tiposmoneda tm ON tm.idtipomoneda=cb.idtipomoneda LEFT JOIN conciliaciones con ON con.idcuentabancaria=cb.idcuentacontable LEFT JOIN cuentasxdocumento cd ON cd.idcuenta=c.idcuenta LEFT JOIN documentos d ON cd.iddocumento = d.iddocumento WHERE d.iddocumento IS NOT NULL GROUP BY c.idcuenta ; """ ) # # if self.ctaBancomodel.rowCount() == 0 : # QMessageBox.critical(self,"Cuentas Bancarias","No existe ninguna cuenta bancaria") # self.destroy() self.setWindowTitle( u"Elija fecha y cuenta bancaria para la conciliación" ) self.filtermodel = QSortFilterProxyModel() self.filtermodel.setSourceModel( self.ctaBancomodel ) self.filtermodel.setFilterCaseSensitivity( Qt.CaseInsensitive ) self.filtermodel.setFilterKeyColumn( -1 ) self.tblCuenta = QTableView() self.tblCuenta.setSelectionMode( QAbstractItemView.SingleSelection ) self.tblCuenta.setSelectionBehavior( QAbstractItemView.SelectRows ) self.tblCuenta.setModel( self.filtermodel ) buttonbox = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel ) self.txtSearch = QLineEdit() formlayout = QFormLayout() formlayout.addRow( "&Buscar", self.txtSearch ) self.dtPicker = QDateTimeEdit() self.dtPicker.setReadOnly( True ) # self.dtPicker.setCalendarPopup(True) self.dtPicker.setAlignment( Qt.AlignHCenter ) self.dtPicker.setDisplayFormat( "MMMM 'd'el yyyy" ) # self.dtPicker.setMinimumDate(QDate(2009,1,1)) fecha = QDate.currentDate() self.dtPicker.setDate( QDate( fecha.year(), fecha.month(), fecha.daysInMonth() ) ) fechalayout = QFormLayout() fechalayout.addRow( "&Fecha", self.dtPicker ) layout = QVBoxLayout() layout.addLayout( fechalayout ) layout.addWidget( self.tblCuenta ) layout.addLayout( formlayout ) layout.addWidget( buttonbox ) self.setLayout( layout ) self.setMinimumWidth( 400 ) buttonbox.accepted.connect( self.aceptar ) buttonbox.rejected.connect( self.reject ) self.txtSearch.textChanged[unicode].connect( self.updateFilter ) self.tblCuenta.selectionModel().currentChanged[QModelIndex, QModelIndex].connect( self.on_tblCuenta_currentChanged ) self.setModal( True ) self.setWindowFlags( Qt.Dialog | Qt.MSWindowsFixedSizeDialogHint | Qt.WindowTitleHint ) self.show() self.tblCuenta.setFocus() self.tblCuenta.selectRow( 0 ) self.tblCuenta.setColumnHidden( 4, True ) self.tblCuenta.setColumnHidden( 5, True ) self.tblCuenta.setColumnHidden( 6, True ) self.tblCuenta.horizontalHeader().setStretchLastSection( True ) self.tblCuenta.resizeColumnsToContents()
def onInit(self): self.resize(450, 300) self.center() self.setMenu() self.setWindowTitle(u'MainWindow') self.setWindowIcon(QIcon('learning.ico')) self.agreement1 = QLabel('Contract1', self) self.agreement11 = QLabel(' Contract1 *', self) self.agreement2 = QLabel('Contract2', self) self.agreement22 = QLabel('Contract2 *', self) self.calculate = QLabel('Formula', self) self.startTime = QLabel('Start Time', self) self.endTime = QLabel('End Time', self) self.agreement1Edit = QLineEdit() self.agreement2Edit = QLineEdit() self.calculate1Edit = QLineEdit() self.calculate2Combo = QComboBox() self.calculate2Combo.addItem('+') self.calculate2Combo.addItem('-') self.calculate2Combo.addItem('*') self.calculate2Combo.addItem('/') self.calculate2Combo.activated[str].connect(self.onActivated) self.calculate2Edit = QLineEdit() self.calculate3Edit = QLineEdit() self.startTimeEdit = QDateTimeEdit( datetime.strptime('20150101 00:00:00', '%Y%m%d %H:%M:%S'), self) self.startTimeEdit.setDisplayFormat('yyyy-MM-dd') self.startTimeEdit.setCalendarPopup(True) self.endTimeEdit = QDateTimeEdit(QDateTime.currentDateTime(), self) self.endTimeEdit.setDisplayFormat('yyyy-MM-dd') self.endTimeEdit.setCalendarPopup(True) self.stateEdit = QTextEdit() self.run = QPushButton('Run', self) self.run.clicked.connect(self.runMain) #self.setAgreementBtn = QPushButton('Setting', self) #self.setAgreementBtn.clicked.connect(self.setAgreement) grid = QGridLayout() #grid.setSpacing(10) grid.addWidget(self.agreement1, 1, 0) grid.addWidget(self.agreement1Edit, 1, 1) grid.addWidget(self.agreement2, 2, 0) grid.addWidget(self.agreement2Edit, 2, 1) #grid.addWidget(self.setAgreementBtn, 2, 2) grid.addWidget(self.startTime, 3, 0) grid.addWidget(self.startTimeEdit, 3, 1) grid.addWidget(self.endTime, 4, 0) grid.addWidget(self.endTimeEdit, 4, 1) grid.addWidget(self.calculate, 5, 0) grid.addWidget(self.agreement11, 5, 1) grid.addWidget(self.calculate1Edit, 5, 2) grid.addWidget(self.calculate2Combo, 5, 3) grid.addWidget(self.agreement22, 5, 4) grid.addWidget(self.calculate3Edit, 5, 5) grid.addWidget(self.stateEdit, 6, 1, 1, 5) grid.addWidget(self.run, 7, 1) gridWidget = QWidget() gridWidget.setLayout(grid) self.agreement11.move(200, 100) self.setCentralWidget(gridWidget) self.show()
class QtDatetimeSelector(QtBoundedDatetime, ProxyDatetimeSelector): """ A Qt implementation of an Enaml ProxyDatetimeSelector. """ #: A reference to the widget created by the proxy. widget = Typed(QDateTimeEdit) #-------------------------------------------------------------------------- # Initialization API #-------------------------------------------------------------------------- def create_widget(self): """ Create the QDateTimeEdit widget. """ self.widget = QDateTimeEdit(self.parent_widget()) def init_widget(self): """ Initialize the widget. """ super(QtDatetimeSelector, self).init_widget() d = self.declaration self.set_datetime_format(d.datetime_format) self.set_calendar_popup(d.calendar_popup) self.widget.dateTimeChanged.connect(self.on_datetime_changed) #-------------------------------------------------------------------------- # Abstract API Implementation #-------------------------------------------------------------------------- def get_datetime(self): """ Return the current datetime in the control. Returns ------- result : datetime The current control datetime as a datetime object. """ return self.widget.dateTime().toPyDateTime() def set_minimum(self, datetime): """ Set the widget's minimum datetime. Parameters ---------- datetime : datetime The datetime object to use for setting the minimum datetime. """ self.widget.setMinimumDateTime(datetime) def set_maximum(self, datetime): """ Set the widget's maximum datetime. Parameters ---------- datetime : datetime The datetime object to use for setting the maximum datetime. """ self.widget.setMaximumDateTime(datetime) def set_datetime(self, datetime): """ Set the widget's current datetime. Parameters ---------- datetime : datetime The datetime object to use for setting the datetime. """ self._guard |= CHANGED_GUARD try: self.widget.setDateTime(datetime) finally: self._guard &= ~CHANGED_GUARD def set_datetime_format(self, format): """ Set the widget's datetime 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)
def setup(self): for label, value in self.data: if DEBUG_FORMLAYOUT: print("value:", value) if label is None and value is None: # Separator: (None, None) self.formlayout.addRow(QLabel(" "), QLabel(" ")) self.widgets.append(None) continue elif label is None: # Comment self.formlayout.addRow(QLabel(value)) self.widgets.append(None) continue elif tuple_to_qfont(value) is not None: field = FontLayout(value, self) elif text_to_qcolor(value).isValid(): field = ColorLayout(QColor(value), self) elif is_text_string(value): if '\n' in value: for linesep in (os.linesep, '\n'): if linesep in value: value = value.replace(linesep, u("\u2029")) field = QTextEdit(value, self) else: field = QLineEdit(value, self) elif isinstance(value, (list, tuple)): value = list(value) # in case this is a tuple selindex = value.pop(0) field = QComboBox(self) if isinstance(value[0], (list, tuple)): keys = [key for key, _val in value] value = [val for _key, val in value] else: keys = value field.addItems(value) if selindex in value: selindex = value.index(selindex) elif selindex in keys: selindex = keys.index(selindex) elif not isinstance(selindex, int): print("Warning: '%s' index is invalid (label: "\ "%s, value: %s)" % (selindex, label, value), file=STDERR) selindex = 0 field.setCurrentIndex(selindex) elif isinstance(value, bool): field = QCheckBox(self) field.setCheckState(Qt.Checked if value else Qt.Unchecked) elif isinstance(value, float): field = QLineEdit(repr(value), self) field.setValidator(QDoubleValidator(field)) dialog = self.get_dialog() dialog.register_float_field(field) self.connect(field, SIGNAL('textChanged(QString)'), lambda text: dialog.update_buttons()) elif isinstance(value, int): field = QSpinBox(self) field.setRange(-1e9, 1e9) field.setValue(value) elif isinstance(value, datetime.datetime): field = QDateTimeEdit(self) field.setDateTime(value) elif isinstance(value, datetime.date): field = QDateEdit(self) field.setDate(value) else: field = QLineEdit(repr(value), self) self.formlayout.addRow(label, field) self.widgets.append(field)
def create_widget(self): """ Create the QDateTimeEdit widget. """ self.widget = QDateTimeEdit(self.parent_widget())