def __init__(self, *args, **kwargs): super(NewIntegerSequenceDateTimeConvertSpecDialog, self).__init__(*args, **kwargs) self.setWindowTitle("New integer sequence datetime") QBtn = QDialogButtonBox.Ok | QDialogButtonBox.Cancel self.buttonBox = QDialogButtonBox(QBtn) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) self.datetime = QDateTimeEdit() self.start_integer = QSpinBox() self.duration = QLineEdit("1h") self.duration.textChanged.connect(self._validate) self.layout = QVBoxLayout() self.form = QFormLayout() self.form.addRow("Initial datetime", self.datetime) self.form.addRow("Initial integer", self.start_integer) self.form.addRow("Timestep duration", self.duration) self.layout.addLayout(self.form) self.layout.addWidget(self.buttonBox) self.setLayout(self.layout) self._validate()
def createBottomRightGroupBox(self): self.bottomRightGroupBox = QGroupBox("Group 3") self.bottomRightGroupBox.setCheckable(True) self.bottomRightGroupBox.setChecked(True) lineEdit = QLineEdit('s3cRe7') lineEdit.setEchoMode(QLineEdit.Password) spinBox = QSpinBox(self.bottomRightGroupBox) spinBox.setValue(50) dateTimeEdit = QDateTimeEdit(self.bottomRightGroupBox) dateTimeEdit.setDateTime(QDateTime.currentDateTime()) slider = QSlider(Qt.Horizontal, self.bottomRightGroupBox) slider.setValue(40) scrollBar = QScrollBar(Qt.Horizontal, self.bottomRightGroupBox) scrollBar.setValue(60) dial = QDial(self.bottomRightGroupBox) dial.setValue(30) dial.setNotchesVisible(True) layout = QGridLayout() layout.addWidget(lineEdit, 0, 0, 1, 2) layout.addWidget(spinBox, 1, 0, 1, 2) layout.addWidget(dateTimeEdit, 2, 0, 1, 2) layout.addWidget(slider, 3, 0) layout.addWidget(scrollBar, 4, 0) layout.addWidget(dial, 3, 1, 2, 1) layout.setRowStretch(5, 1) self.bottomRightGroupBox.setLayout(layout)
def widgets(self): self.scroll = QScrollArea() self.scroll.setWidgetResizable(True) # Top layout widgets self.addIssueImg = QLabel() self.img = QPixmap('assets/icons/create-issue.png') self.addIssueImg.setPixmap(self.img) self.addIssueImg.setAlignment(Qt.AlignCenter) self.titleText = QLabel("Add issue") self.titleText.setAlignment(Qt.AlignCenter) # Middle layout widgets self.issueInfoTitleText = QLabel("Issue info") self.issueInfoTitleText.setAlignment(Qt.AlignCenter) self.dateEntry = QDateTimeEdit() self.dateEntry.setDateTime(QDateTime.currentDateTime()) self.priorityEntry = QComboBox() self.priorityEntry.setEditable(True) self.observerEntry = QComboBox() self.observerEntry.setEditable(True) self.revisionTeamEntry = QComboBox() self.revisionTeamEntry.setEditable(True) self.inspectionNameEntry = QComboBox() self.inspectionNameEntry.setEditable(True) self.observationThemeEntry = QComboBox() self.observationThemeEntry.setEditable(True) self.facilityEntry = QComboBox() self.facilityEntry.setEditable(True) self.facilitySupervisorEntry = QComboBox() self.facilitySupervisorEntry.setEditable(True) self.specificLocationEntry = QTextEdit() self.inspectedDepartmentEntry = QComboBox() self.inspectedDepartmentEntry.setEditable(True) self.inspectedContractorEntry = QComboBox() self.inspectedContractorEntry.setEditable(True) self.inspectedSubcontractorEntry = QComboBox() self.inspectedSubcontractorEntry.setEditable(True) self.deadlineEntry = QDateTimeEdit() self.deadlineEntry.setDateTime(QDateTime.currentDateTime()) # Bottom layout widgets self.attachFilesBtn = QPushButton("Attach files") self.addActionBtn = QPushButton("Add action") self.rootCauseEntry = QComboBox() self.rootCauseEntry.setEditable(True) self.rootCauseDetailsEntry = QTextEdit() self.rootCauseActionPartyEntry = QComboBox() self.rootCauseActionPartyEntry.setEditable(True) self.addRootCauseBtn = QPushButton("Add root cause") self.submitObservationBtn = QPushButton("Add issue") self.submitObservationBtn.clicked.connect(self.addIssue)
def addIssue(self): date = self.dateEntry.text() priority = self.priorityEntry.currentText() observer = self.observerEntry.currentText() revisionTeam = self.revisionTeamEntry.currentText() inspectionName = self.inspectionNameEntry.currentText() observationTheme = self.observationThemeEntry.currentText() facility = self.facilityEntry.currentText() facilitySupervisor = self.facilitySupervisorEntry.currentText() specificLocation = self.specificLocationEntry.toPlainText() inspectedDept = self.inspectedDepartmentEntry.currentText() inspectedContr = self.inspectedContractorEntry.currentText() inspectedSubcontr = self.inspectedSubcontractorEntry.currentText() deadline = self.deadlineEntry.text() if date and priority and observer and revisionTeam and inspectionName and observationTheme and facility\ and facilitySupervisor and specificLocation and inspectedDept and inspectedContr \ and inspectedSubcontr and deadline != "": try: query = "INSERT INTO issues (issue_date, issue_priority, issue_observer, issue_team," \ "issue_inspection, issue_theme, issue_facility, issue_fac_supervisor," \ "issue_spec_loc, issue_insp_dept, issue_insp_contr, issue_insp_subcontr, issue_deadline, created_on) " \ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" # The purpose of this block is to make created_on timestamp the same format as other dates currentTime = QDateTimeEdit() currentTime.setDateTime(QDateTime.currentDateTime()) now = currentTime.text() db.cur.execute( query, (date, priority, observer, revisionTeam, inspectionName, observationTheme, facility, facilitySupervisor, specificLocation, inspectedDept, inspectedContr, inspectedSubcontr, deadline, now)) db.conn.commit() QMessageBox.information(self, "Info", "Issue has been added") self.Parent.displayIssues() self.close() except: QMessageBox.information(self, "Info", "Issue has not been added") else: QMessageBox.information(self, "Info", "Fields cannot be empty")
class NewIntegerSequenceDateTimeConvertSpecDialog(QDialog): def __init__(self, *args, **kwargs): super(NewIntegerSequenceDateTimeConvertSpecDialog, self).__init__(*args, **kwargs) self.setWindowTitle("New integer sequence datetime") QBtn = QDialogButtonBox.Ok | QDialogButtonBox.Cancel self.buttonBox = QDialogButtonBox(QBtn) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) self.datetime = QDateTimeEdit() self.start_integer = QSpinBox() self.duration = QLineEdit("1h") self.duration.textChanged.connect(self._validate) self.layout = QVBoxLayout() self.form = QFormLayout() self.form.addRow("Initial datetime", self.datetime) self.form.addRow("Initial integer", self.start_integer) self.form.addRow("Timestep duration", self.duration) self.layout.addLayout(self.form) self.layout.addWidget(self.buttonBox) self.setLayout(self.layout) self._validate() def _validate(self): try: Duration(self.duration.text()) except ParameterValueFormatError: self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False) return self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True) def get_spec(self): start_datetime = DateTime(self.datetime.dateTime().toString( Qt.ISODate)) duration = Duration(self.duration.text()) start_int = self.start_integer.value() return IntegerSequenceDateTimeConvertSpec(start_datetime, start_int, duration)
def __init__(self, parent=None): super(application, self).__init__(parent) self.bot = None self.db = sqlite3.connect('database') # tabs self.tab1 = QWidget() self.tab2 = QWidget() self.tab3 = QWidget() self.tab4 = QWidget() self.tab5 = QWidget() self.resize(640, 400) self.addTab(self.tab1, "Tab 1") self.addTab(self.tab2, "Tab 2") self.addTab(self.tab3, "Tab 3") self.addTab(self.tab4, "Tab 4") self.addTab(self.tab5, "Tab 5") # tab set keys self.h_box_key = QHBoxLayout() self.change_key_b = QPushButton("Edit keys") self.edit_1 = QLineEdit() self.edit_2 = QLineEdit() self.edit_3 = QLineEdit() self.edit_4 = QLineEdit() self.result = QLabel() self.set_button = QPushButton("Set keys") self.handle_info = QLabel() self.follower_info = QLabel() self.ready_lab = QLabel() # tab follow self.box_label = QLabel("Link to tweet") self.combo_label = QLabel("Mode") self.spin_label = QLabel("Limit before sleep") self.prog_bar = QProgressBar() self.combo_box = QComboBox() self.h_box = QHBoxLayout() self.spin_box = QSpinBox() self.link_box = QLineEdit() self.link_result = QLabel() self.follow_button = QPushButton("Follow Retweeters") self.cancel_button = QPushButton("Cancel") self.logger = QPlainTextEdit() self.h_box2 = QHBoxLayout() self.max_box = QSpinBox() self.max_label = QLabel("Max follows before stop") # tab unfollow self.unfollow_button = QPushButton("Unfollow Auto followers") self.unf_logger = QPlainTextEdit() self.unfollow_res = QLabel() self.prog_bar_unf = QProgressBar() self.unfollow_cancel = QPushButton("Cancel") self.unf_confirm = QMessageBox() # tab help self.help_box = QPlainTextEdit() self.help_label = QLabel( "<a href='http://Optumsense.com/'>http://Optumsense.com/</a>") #tab schedule self.tweet_box = QPlainTextEdit() self.date_time = QDateTimeEdit(QDateTime.currentDateTime()) self.schedule_but = QPushButton("Schedule Tweet") self.schedule_info = QLabel() self.schedule_table = QTableView() # threads self.follow_thread = None self.unfollow_thread = None self.schedule_thread = None # tabs self.tab1UI() self.tab2UI() self.tab3UI() self.tab4UI() self.tab5UI() self.setWindowTitle("Optumize") self.setWindowIcon(QtGui.QIcon('assets/oo.png')) # db cursor = self.db.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS keys(one TEXT, two TEXT, three TEXT, four TEXT)''' ) self.db.commit()
class AddIssue(QWidget): def __init__(self, parent): QWidget.__init__(self) self.setWindowTitle("Add issue") self.setWindowIcon(QIcon("assets/icons/icon.ico")) self.setGeometry(450, 150, 750, 950) # self.setFixedSize(self.size()) self.Parent = parent self.UI() self.show() def UI(self): self.widgets() self.layouts() def widgets(self): self.scroll = QScrollArea() self.scroll.setWidgetResizable(True) # Top layout widgets self.addIssueImg = QLabel() self.img = QPixmap('assets/icons/create-issue.png') self.addIssueImg.setPixmap(self.img) self.addIssueImg.setAlignment(Qt.AlignCenter) self.titleText = QLabel("Add issue") self.titleText.setAlignment(Qt.AlignCenter) # Middle layout widgets self.issueInfoTitleText = QLabel("Issue info") self.issueInfoTitleText.setAlignment(Qt.AlignCenter) self.dateEntry = QDateTimeEdit() self.dateEntry.setDateTime(QDateTime.currentDateTime()) self.priorityEntry = QComboBox() self.priorityEntry.setEditable(True) self.observerEntry = QComboBox() self.observerEntry.setEditable(True) self.revisionTeamEntry = QComboBox() self.revisionTeamEntry.setEditable(True) self.inspectionNameEntry = QComboBox() self.inspectionNameEntry.setEditable(True) self.observationThemeEntry = QComboBox() self.observationThemeEntry.setEditable(True) self.facilityEntry = QComboBox() self.facilityEntry.setEditable(True) self.facilitySupervisorEntry = QComboBox() self.facilitySupervisorEntry.setEditable(True) self.specificLocationEntry = QTextEdit() self.inspectedDepartmentEntry = QComboBox() self.inspectedDepartmentEntry.setEditable(True) self.inspectedContractorEntry = QComboBox() self.inspectedContractorEntry.setEditable(True) self.inspectedSubcontractorEntry = QComboBox() self.inspectedSubcontractorEntry.setEditable(True) self.deadlineEntry = QDateTimeEdit() self.deadlineEntry.setDateTime(QDateTime.currentDateTime()) # Bottom layout widgets self.attachFilesBtn = QPushButton("Attach files") self.addActionBtn = QPushButton("Add action") self.rootCauseEntry = QComboBox() self.rootCauseEntry.setEditable(True) self.rootCauseDetailsEntry = QTextEdit() self.rootCauseActionPartyEntry = QComboBox() self.rootCauseActionPartyEntry.setEditable(True) self.addRootCauseBtn = QPushButton("Add root cause") self.submitObservationBtn = QPushButton("Add issue") self.submitObservationBtn.clicked.connect(self.addIssue) def layouts(self): self.mainLayout = QVBoxLayout() self.topLayout = QHBoxLayout() self.bottomLayout = QFormLayout() # Put elements into frames for visual distinction self.topFrame = QFrame() self.bottomFrame = QFrame() # Add widgets to top layout self.topLayout.addWidget(self.addIssueImg) self.topLayout.addWidget(self.titleText) self.topFrame.setLayout(self.topLayout) # Add widgets to middle layout self.bottomLayout.addRow(self.issueInfoTitleText) self.bottomLayout.addRow(QLabel("Inspection Date: "), self.dateEntry) self.bottomLayout.addRow(QLabel("Priority: "), self.priorityEntry) self.bottomLayout.addRow(QLabel("Observer: "), self.observerEntry) self.bottomLayout.addRow(QLabel("Revision Team: "), self.revisionTeamEntry) self.bottomLayout.addRow(QLabel("Inspection Name: "), self.inspectionNameEntry) self.bottomLayout.addRow(QLabel("HSE Theme: "), self.observationThemeEntry) self.bottomLayout.addRow(QLabel("Facility: "), self.facilityEntry) self.bottomLayout.addRow(QLabel("Facility supervisor: "), self.facilitySupervisorEntry) self.bottomLayout.addRow(QLabel("Specific location: "), self.specificLocationEntry) self.bottomLayout.addRow(QLabel("Inspected department: "), self.inspectedDepartmentEntry) self.bottomLayout.addRow(QLabel("Inspected contractor: "), self.inspectedContractorEntry) self.bottomLayout.addRow(QLabel("Inspected subcontractor: "), self.inspectedSubcontractorEntry) self.bottomLayout.addRow(QLabel("Deadline: "), self.deadlineEntry) self.bottomLayout.addRow(QLabel(""), self.attachFilesBtn) self.bottomLayout.addRow(QLabel(""), self.addActionBtn) self.bottomLayout.addRow(QLabel(""), self.addRootCauseBtn) self.bottomLayout.addRow(QLabel(""), self.submitObservationBtn) self.bottomFrame.setLayout(self.bottomLayout) # Make bottom frame scollable self.scroll.setWidget(self.bottomFrame) # Add frames to main layout self.mainLayout.addWidget(self.topFrame) self.mainLayout.addWidget(self.scroll) self.setLayout(self.mainLayout) def addIssue(self): date = self.dateEntry.text() priority = self.priorityEntry.currentText() observer = self.observerEntry.currentText() revisionTeam = self.revisionTeamEntry.currentText() inspectionName = self.inspectionNameEntry.currentText() observationTheme = self.observationThemeEntry.currentText() facility = self.facilityEntry.currentText() facilitySupervisor = self.facilitySupervisorEntry.currentText() specificLocation = self.specificLocationEntry.toPlainText() inspectedDept = self.inspectedDepartmentEntry.currentText() inspectedContr = self.inspectedContractorEntry.currentText() inspectedSubcontr = self.inspectedSubcontractorEntry.currentText() deadline = self.deadlineEntry.text() if date and priority and observer and revisionTeam and inspectionName and observationTheme and facility\ and facilitySupervisor and specificLocation and inspectedDept and inspectedContr \ and inspectedSubcontr and deadline != "": try: query = "INSERT INTO issues (issue_date, issue_priority, issue_observer, issue_team," \ "issue_inspection, issue_theme, issue_facility, issue_fac_supervisor," \ "issue_spec_loc, issue_insp_dept, issue_insp_contr, issue_insp_subcontr, issue_deadline, created_on) " \ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" # The purpose of this block is to make created_on timestamp the same format as other dates currentTime = QDateTimeEdit() currentTime.setDateTime(QDateTime.currentDateTime()) now = currentTime.text() db.cur.execute( query, (date, priority, observer, revisionTeam, inspectionName, observationTheme, facility, facilitySupervisor, specificLocation, inspectedDept, inspectedContr, inspectedSubcontr, deadline, now)) db.conn.commit() QMessageBox.information(self, "Info", "Issue has been added") self.Parent.displayIssues() self.close() except: QMessageBox.information(self, "Info", "Issue has not been added") else: QMessageBox.information(self, "Info", "Fields cannot be empty")
def init_ui(self): self.setFixedWidth(500) self.setWindowTitle(_('Event properties')) self.setWindowIcon(QIcon(config.ICON)) self.setSizeGripEnabled(False) self.setModal(True) self.layout = QFormLayout(self) self.label_main_title = QLabel(_('Main title')) self.item_main_title = QLineEdit() self.layout.addRow(self.label_main_title, self.item_main_title) self.label_sub_title = QLabel(_('Sub title')) self.item_sub_title = QTextEdit() self.item_sub_title.setMaximumHeight(100) self.layout.addRow(self.label_sub_title, self.item_sub_title) self.label_start_date = QLabel(_('Start date')) self.item_start_date = QDateTimeEdit() self.item_start_date.setDisplayFormat('yyyy.MM.dd HH:mm:ss') self.layout.addRow(self.label_start_date, self.item_start_date) self.label_end_date = QLabel(_('End date')) # self.item_end_date = QCalendarWidget() self.item_end_date = QDateTimeEdit() self.item_end_date.setDisplayFormat('yyyy.MM.dd HH:mm:ss') self.layout.addRow(self.label_end_date, self.item_end_date) self.label_location = QLabel(_('Location')) self.item_location = QLineEdit() self.layout.addRow(self.label_location, self.item_location) self.label_type = QLabel(_('Event type')) self.item_type = AdvComboBox() self.item_type.addItems(RaceType.get_titles()) self.layout.addRow(self.label_type, self.item_type) self.label_relay_legs = QLabel(_('Relay legs')) self.item_relay_legs = QSpinBox() self.item_relay_legs.setMinimum(1) self.item_relay_legs.setMaximum(20) self.item_relay_legs.setValue(3) self.layout.addRow(self.label_relay_legs, self.item_relay_legs) self.item_type.currentTextChanged.connect(self.change_type) self.label_refery = QLabel(_('Chief referee')) self.item_refery = QLineEdit() self.layout.addRow(self.label_refery, self.item_refery) self.label_secretary = QLabel(_('Secretary')) self.item_secretary = QLineEdit() self.layout.addRow(self.label_secretary, self.item_secretary) self.label_url = QLabel(_('URL')) self.item_url = QLineEdit() self.layout.addRow(self.label_url, self.item_url) def cancel_changes(): self.close() def apply_changes(): try: self.apply_changes_impl() except Exception as e: logging.error(str(e)) self.close() button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.button_ok = button_box.button(QDialogButtonBox.Ok) self.button_ok.setText(_('OK')) self.button_ok.clicked.connect(apply_changes) self.button_cancel = button_box.button(QDialogButtonBox.Cancel) self.button_cancel.setText(_('Cancel')) self.button_cancel.clicked.connect(cancel_changes) self.layout.addRow(button_box) self.set_values_from_model() self.show()
class TransferWidget(AbstractOperationDetails): def __init__(self, parent=None): AbstractOperationDetails.__init__(self, parent) self.name = "Transfer" self.from_date_label = QLabel(self) self.from_account_label = QLabel(self) self.from_amount_label = QLabel(self) self.to_date_label = QLabel(self) self.to_account_label = QLabel(self) self.to_amount_label = QLabel(self) self.fee_account_label = QLabel(self) self.fee_amount_label = QLabel(self) self.comment_label = QLabel(self) self.arrow_account = QLabel(self) self.copy_date_btn = QPushButton(self) self.copy_amount_btn = QPushButton(self) self.main_label.setText(g_tr("TransferWidget", "Transfer")) self.from_date_label.setText(g_tr("TransferWidget", "Date/Time")) self.from_account_label.setText(g_tr("TransferWidget", "From")) self.from_amount_label.setText(g_tr("TransferWidget", "Amount")) self.to_date_label.setText(g_tr("TransferWidget", "Date/Time")) self.to_account_label.setText(g_tr("TransferWidget", "To")) self.to_amount_label.setText(g_tr("TransferWidget", "Amount")) self.fee_account_label.setText(g_tr("TransferWidget", "Fee from")) self.fee_amount_label.setText(g_tr("TransferWidget", "Fee amount")) self.comment_label.setText(g_tr("TransferWidget", "Note")) self.arrow_account.setText(" ➜ ") self.copy_date_btn.setText("➜") self.copy_date_btn.setFixedWidth( self.copy_date_btn.fontMetrics().width("XXXX")) self.copy_amount_btn.setText("➜") self.copy_amount_btn.setFixedWidth( self.copy_amount_btn.fontMetrics().width("XXXX")) self.withdrawal_timestamp = QDateTimeEdit(self) self.withdrawal_timestamp.setCalendarPopup(True) self.withdrawal_timestamp.setTimeSpec(Qt.UTC) self.withdrawal_timestamp.setFixedWidth( self.withdrawal_timestamp.fontMetrics().width( "00/00/0000 00:00:00") * 1.25) self.withdrawal_timestamp.setDisplayFormat("dd/MM/yyyy hh:mm:ss") self.deposit_timestamp = QDateTimeEdit(self) self.deposit_timestamp.setCalendarPopup(True) self.deposit_timestamp.setTimeSpec(Qt.UTC) self.deposit_timestamp.setFixedWidth( self.deposit_timestamp.fontMetrics().width("00/00/0000 00:00:00") * 1.25) self.deposit_timestamp.setDisplayFormat("dd/MM/yyyy hh:mm:ss") self.from_account_widget = AccountSelector(self) self.to_account_widget = AccountSelector(self) self.fee_account_widget = AccountSelector(self) self.withdrawal = AmountEdit(self) self.withdrawal.setAlignment(Qt.AlignRight) self.deposit = AmountEdit(self) self.deposit.setAlignment(Qt.AlignRight) self.fee = AmountEdit(self) self.fee.setAlignment(Qt.AlignRight) self.comment = QLineEdit(self) self.layout.addWidget(self.from_date_label, 1, 0, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.from_account_label, 2, 0, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.from_amount_label, 3, 0, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.comment_label, 5, 0, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.withdrawal_timestamp, 1, 1, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.from_account_widget, 2, 1, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.withdrawal, 3, 1, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.comment, 5, 1, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.copy_date_btn, 1, 2, 1, 1) self.layout.addWidget(self.arrow_account, 2, 2, 1, 1, Qt.AlignCenter) self.layout.addWidget(self.copy_amount_btn, 3, 2, 1, 1) self.layout.addWidget(self.to_date_label, 1, 3, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.to_account_label, 2, 3, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.to_amount_label, 3, 3, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.fee_account_label, 4, 3, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.fee_amount_label, 5, 3, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.deposit_timestamp, 1, 4, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.to_account_widget, 2, 4, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.deposit, 3, 4, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.fee_account_widget, 4, 4, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.fee, 5, 4, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.commit_button, 0, 6, 1, 1) self.layout.addWidget(self.revert_button, 0, 7, 1, 1) self.layout.addItem(self.verticalSpacer, 6, 0, 1, 1) self.layout.addItem(self.horizontalSpacer, 1, 5, 1, 1) self.copy_date_btn.clicked.connect(self.onCopyDate) self.copy_amount_btn.clicked.connect(self.onCopyAmount) super()._init_db("transfers") self.mapper.setItemDelegate(TransferWidgetDelegate(self.mapper)) self.from_account_widget.changed.connect(self.mapper.submit) self.to_account_widget.changed.connect(self.mapper.submit) self.fee_account_widget.changed.connect(self.mapper.submit) self.mapper.addMapping(self.withdrawal_timestamp, self.model.fieldIndex("withdrawal_timestamp")) self.mapper.addMapping(self.from_account_widget, self.model.fieldIndex("withdrawal_account")) self.mapper.addMapping(self.withdrawal, self.model.fieldIndex("withdrawal")) self.mapper.addMapping(self.deposit_timestamp, self.model.fieldIndex("deposit_timestamp")) self.mapper.addMapping(self.to_account_widget, self.model.fieldIndex("deposit_account")) self.mapper.addMapping(self.deposit, self.model.fieldIndex("deposit")) self.mapper.addMapping(self.fee_account_widget, self.model.fieldIndex("fee_account")) self.mapper.addMapping(self.fee, self.model.fieldIndex("fee")) self.mapper.addMapping(self.comment, self.model.fieldIndex("note")) self.model.select() @Slot() def saveChanges(self): record = self.model.record(0) note = record.value(self.model.fieldIndex("note")) if not note: # If we don't have note - set it to NULL value # TODO - is it really needed? self.model.setData( self.model.index(0, self.model.fieldIndex("note")), None) # Set related fields NULL if we don't have fee. This is required for correct transfer processing fee_amount = record.value(self.model.fieldIndex("fee")) if not fee_amount: fee_amount = 0 if abs(float(fee_amount)) < Setup.CALC_TOLERANCE: self.model.setData( self.model.index(0, self.model.fieldIndex("fee_account")), None) self.model.setData( self.model.index(0, self.model.fieldIndex("fee")), None) super().saveChanges() def prepareNew(self, account_id): new_record = self.model.record() new_record.setNull("id") new_record.setValue( "withdrawal_timestamp", int(datetime.now().replace(tzinfo=tz.tzutc()).timestamp())) new_record.setValue("withdrawal_account", account_id) new_record.setValue("withdrawal", 0) new_record.setValue( "deposit_timestamp", int(datetime.now().replace(tzinfo=tz.tzutc()).timestamp())) new_record.setValue("deposit_account", 0) new_record.setValue("deposit", 0) new_record.setValue("fee_account", 0) new_record.setValue("fee", 0) new_record.setValue("asset", None) new_record.setValue("note", None) return new_record def copyToNew(self, row): new_record = self.model.record(row) new_record.setNull("id") new_record.setValue( "withdrawal_timestamp", int(datetime.now().replace(tzinfo=tz.tzutc()).timestamp())) new_record.setValue( "deposit_timestamp", int(datetime.now().replace(tzinfo=tz.tzutc()).timestamp())) return new_record @Slot() def onCopyDate(self): self.deposit_timestamp.setDateTime( self.withdrawal_timestamp.dateTime()) @Slot() def onCopyAmount(self): self.deposit.setText(self.withdrawal.text())
def widgets(self): self.dropdownData = IssuesDropdownData() # Top layout widgets self.issueImg = QLabel() self.img = QPixmap('assets/icons/logo-dark.png') self.issueImg.setPixmap(self.img) self.issueImg.setAlignment(Qt.AlignCenter) self.titleText = QLabel("Display issue") self.titleText.setAlignment(Qt.AlignCenter) # Bottom layout widgets self.idEntry = QLabel(str(self.id)) self.dateEntry = QDateTimeEdit(calendarPopup=True) self.dateEntry.setDateTime( QDateTime.fromString(self.date, "yyyy-MM-dd h:mm AP")) self.priorityEntry = QComboBox() self.priorityEntry.addItems(self.dropdownData.priorityItems()) self.priorityEntry.setCurrentText(self.priority) self.observerEntry = QComboBox() self.observerEntry.addItems(self.dropdownData.observerItems()) self.observerEntry.setCurrentText(self.observer) self.revTeamEntry = QComboBox() self.revTeamEntry.addItems(self.dropdownData.revTeamItems()) self.revTeamEntry.setCurrentText(self.revTeam) self.inspectionNameEntry = QComboBox() self.inspectionNameEntry.addItems(self.dropdownData.inspNameItems()) self.inspectionNameEntry.setCurrentText(self.inspectorName) self.themeEntry = QComboBox() self.themeEntry.addItems(self.dropdownData.hseThemeItems()) self.themeEntry.setCurrentText(self.theme) self.facilityEntry = QComboBox() self.facilityEntry.addItems(self.dropdownData.facilityItems()) self.facilityEntry.setCurrentText(self.facility) self.facilitySupervisorEntry = QComboBox() self.facilitySupervisorEntry.addItems( self.dropdownData.facSupervisorItems()) self.facilitySupervisorEntry.setCurrentText(self.facilitySupervisor) self.specLocationEntry = QTextEdit() self.specLocationEntry.setText(self.specLocation) self.inspectedDeptEntry = QComboBox() self.inspectedDeptEntry.addItems(self.dropdownData.inspDeptItems()) self.inspectedDeptEntry.setCurrentText(self.inspectedDept) self.inspectedContrEntry = QComboBox() self.inspectedContrEntry.addItems(self.dropdownData.inspContrItems()) self.inspectedContrEntry.setCurrentText(self.inspectedContr) self.inspectedSubcontrEntry = QComboBox() self.inspectedSubcontrEntry.addItems( self.dropdownData.inspSubcontrItems()) self.inspectedSubcontrEntry.setCurrentText(self.inspectedSubcontr) self.statusEntry = QComboBox() self.statusEntry.addItems(self.dropdownData.statusItems()) self.statusEntry.setCurrentText(self.status) self.deadlineEntry = QDateTimeEdit(calendarPopup=True) self.deadlineEntry.setDateTime( QDateTime.fromString(self.deadline, "yyyy-MM-dd h:mm AP")) self.updateBtn = QPushButton("Update") self.updateBtn.clicked.connect(self.updateIssue) self.deleteBtn = QPushButton("Delete") self.deleteBtn.clicked.connect(self.Parent.funcDeleteIssue) self.cancelBtn = QPushButton("Cancel") self.cancelBtn.clicked.connect(self.closeWindow)
class IncomeSpendingWidget(AbstractOperationDetails): def __init__(self, parent=None): AbstractOperationDetails.__init__(self, parent) self.name = "Income/Spending" self.details_model = None self.category_delegate = CategorySelectorDelegate() self.tag_delegate = TagSelectorDelegate() self.float_delegate = FloatDelegate(2) self.date_label = QLabel(self) self.details_label = QLabel(self) self.account_label = QLabel(self) self.peer_label = QLabel(self) self.main_label.setText(g_tr("IncomeSpendingWidget", "Income / Spending")) self.date_label.setText(g_tr("IncomeSpendingWidget", "Date/Time")) self.details_label.setText(g_tr("IncomeSpendingWidget", "Details")) self.account_label.setText(g_tr("IncomeSpendingWidget", "Account")) self.peer_label.setText(g_tr("IncomeSpendingWidget", "Peer")) self.timestamp_editor = QDateTimeEdit(self) self.timestamp_editor.setCalendarPopup(True) self.timestamp_editor.setTimeSpec(Qt.UTC) self.timestamp_editor.setFixedWidth(self.timestamp_editor.fontMetrics().width("00/00/0000 00:00:00") * 1.25) self.timestamp_editor.setDisplayFormat("dd/MM/yyyy hh:mm:ss") self.account_widget = AccountSelector(self) self.peer_widget = PeerSelector(self) self.a_currency = OptionalCurrencyComboBox(self) self.a_currency.setText(g_tr("IncomeSpendingWidget", "Paid in foreign currency:")) self.add_button = QPushButton(self) self.add_button.setText(" +️ ") self.add_button.setFont(self.bold_font) self.add_button.setFixedWidth(self.add_button.fontMetrics().width("XXX")) self.del_button = QPushButton(self) self.del_button.setText(" — ️") self.del_button.setFont(self.bold_font) self.del_button.setFixedWidth(self.del_button.fontMetrics().width("XXX")) self.copy_button = QPushButton(self) self.copy_button.setText(" >> ️") self.copy_button.setFont(self.bold_font) self.copy_button.setFixedWidth(self.copy_button.fontMetrics().width("XXX")) self.details_table = QTableView(self) self.details_table.horizontalHeader().setFont(self.bold_font) self.details_table.setAlternatingRowColors(True) self.details_table.verticalHeader().setVisible(False) self.details_table.verticalHeader().setMinimumSectionSize(20) self.details_table.verticalHeader().setDefaultSectionSize(20) self.layout.addWidget(self.date_label, 1, 0, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.details_label, 2, 0, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.timestamp_editor, 1, 1, 1, 4) self.layout.addWidget(self.add_button, 2, 1, 1, 1) self.layout.addWidget(self.copy_button, 2, 2, 1, 1) self.layout.addWidget(self.del_button, 2, 3, 1, 1) self.layout.addWidget(self.account_label, 1, 5, 1, 1, Qt.AlignRight) self.layout.addWidget(self.peer_label, 2, 5, 1, 1, Qt.AlignRight) self.layout.addWidget(self.account_widget, 1, 6, 1, 1) self.layout.addWidget(self.peer_widget, 2, 6, 1, 1) self.layout.addWidget(self.a_currency, 1, 7, 1, 1) self.layout.addWidget(self.commit_button, 0, 9, 1, 1) self.layout.addWidget(self.revert_button, 0, 10, 1, 1) self.layout.addWidget(self.details_table, 4, 0, 1, 11) self.layout.addItem(self.horizontalSpacer, 1, 8, 1, 1) self.add_button.clicked.connect(self.addChild) self.del_button.clicked.connect(self.delChild) super()._init_db("actions") self.mapper.setItemDelegate(IncomeSpendingWidgetDelegate(self.mapper)) self.details_model = DetailsModel(self.details_table, db_connection()) self.details_model.setTable("action_details") self.details_model.setEditStrategy(QSqlTableModel.OnManualSubmit) self.details_table.setModel(self.details_model) self.details_model.dataChanged.connect(self.onDataChange) self.account_widget.changed.connect(self.mapper.submit) self.peer_widget.changed.connect(self.mapper.submit) self.a_currency.changed.connect(self.mapper.submit) self.a_currency.updated.connect(self.details_model.setAltCurrency) self.mapper.addMapping(self.timestamp_editor, self.model.fieldIndex("timestamp")) self.mapper.addMapping(self.account_widget, self.model.fieldIndex("account_id")) self.mapper.addMapping(self.peer_widget, self.model.fieldIndex("peer_id")) self.mapper.addMapping(self.a_currency, self.model.fieldIndex("alt_currency_id")) self.details_table.setItemDelegateForColumn(2, self.category_delegate) self.details_table.setItemDelegateForColumn(3, self.tag_delegate) self.details_table.setItemDelegateForColumn(4, self.float_delegate) self.details_table.setItemDelegateForColumn(5, self.float_delegate) self.model.select() self.details_model.select() self.details_model.configureView() def setId(self, id): super().setId(id) self.details_model.setFilter(f"action_details.pid = {id}") @Slot() def addChild(self): new_record = self.details_model.record() new_record.setNull("tag_id") new_record.setValue("amount", 0) new_record.setValue("amount_alt", 0) if not self.details_model.insertRecord(-1, new_record): logging.fatal( g_tr('AbstractOperationDetails', "Failed to add new record: ") + self.details_model.lastError().text()) return @Slot() def delChild(self): idx = self.details_table.selectionModel().selection().indexes() selected_row = idx[0].row() self.details_model.removeRow(selected_row) self.details_table.setRowHidden(selected_row, True) @Slot() def saveChanges(self): if not self.model.submitAll(): logging.fatal( g_tr('AbstractOperationDetails', "Operation submit failed: ") + self.model.lastError().text()) return pid = self.model.data(self.model.index(0, self.model.fieldIndex("id"))) if pid is None: # we just have saved new action record and need last inserted id pid = self.model.query().lastInsertId() for row in range(self.details_model.rowCount()): self.details_model.setData(self.details_model.index(row, self.details_model.fieldIndex("pid")), pid) if not self.details_model.submitAll(): logging.fatal(g_tr('AbstractOperationDetails', "Operation details submit failed: ") + self.details_model.lastError().text()) return self.modified = False self.commit_button.setEnabled(False) self.revert_button.setEnabled(False) self.dbUpdated.emit() return def createNew(self, account_id=0): super().createNew(account_id) self.details_model.setFilter(f"action_details.pid = 0") def prepareNew(self, account_id): new_record = self.model.record() new_record.setNull("id") new_record.setValue("timestamp", int(datetime.now().replace(tzinfo=tz.tzutc()).timestamp())) new_record.setValue("account_id", account_id) new_record.setValue("peer_id", 0) new_record.setValue("alt_currency_id", None) return new_record def copyNew(self): old_id = self.model.record(self.mapper.currentIndex()).value(0) super().copyNew() self.details_model.setFilter(f"action_details.pid = 0") query = executeSQL("SELECT * FROM action_details WHERE pid = :pid ORDER BY id DESC", [(":pid", old_id)]) while query.next(): new_record = query.record() new_record.setNull("id") new_record.setNull("pid") assert self.details_model.insertRows(0, 1) self.details_model.setRecord(0, new_record) def copyToNew(self, row): new_record = self.model.record(row) new_record.setNull("id") new_record.setValue("timestamp", int(datetime.now().replace(tzinfo=tz.tzutc()).timestamp())) return new_record
def widgets(self): self.scroll = QScrollArea() self.scroll.setWidgetResizable(True) self.dropdownData = IssuesDropdownData() # Top layout widgets self.addIssueImg = QLabel() self.img = QPixmap('assets/icons/create-issue.png') self.addIssueImg.setPixmap(self.img) self.addIssueImg.setAlignment(Qt.AlignCenter) self.titleText = QLabel("ADD ISSUE") self.titleText.setObjectName("add_issue_title_txt") self.titleText.setAlignment(Qt.AlignCenter) # Middle layout widgets self.dateEntry = QDateTimeEdit(calendarPopup=True) self.dateEntry.setDateTime(QDateTime.currentDateTime()) self.priorityEntry = QComboBox() self.priorityEntry.addItems(self.dropdownData.priorityItems()) self.observerEntry = QComboBox() self.observerEntry.addItems(self.dropdownData.observerItems()) self.revisionTeamEntry = QComboBox() self.revisionTeamEntry.addItems(self.dropdownData.revTeamItems()) self.inspectionNameEntry = QComboBox() self.inspectionNameEntry.addItems(self.dropdownData.inspNameItems()) self.observationThemeEntry = QComboBox() self.observationThemeEntry.addItems(self.dropdownData.hseThemeItems()) self.facilityEntry = QComboBox() self.facilityEntry.addItems(self.dropdownData.facilityItems()) self.facilitySupervisorEntry = QComboBox() self.facilitySupervisorEntry.addItems( self.dropdownData.facSupervisorItems()) self.specificLocationEntry = QTextEdit() self.inspectedDepartmentEntry = QComboBox() self.inspectedDepartmentEntry.addItems( self.dropdownData.inspDeptItems()) self.inspectedContractorEntry = QComboBox() self.inspectedContractorEntry.addItems( self.dropdownData.inspContrItems()) self.inspectedSubcontractorEntry = QComboBox() self.inspectedSubcontractorEntry.addItems( self.dropdownData.inspSubcontrItems()) self.deadlineEntry = QDateTimeEdit(calendarPopup=True) self.deadlineEntry.setDateTime(QDateTime.currentDateTime().addDays(14)) # Bottom layout widgets self.attachFilesBtn = QPushButton("Attach files") self.attachFilesBtn.clicked.connect(self.funcAttachFiles) self.addActionBtn = QPushButton("Add action") self.rootCauseEntry = QComboBox() self.rootCauseEntry.setEditable(True) self.rootCauseDetailsEntry = QTextEdit() self.rootCauseActionPartyEntry = QComboBox() self.rootCauseActionPartyEntry.setEditable(True) self.addRootCauseBtn = QPushButton("Add root cause") self.submitObservationBtn = QPushButton("Add issue") self.submitObservationBtn.clicked.connect(self.addIssue) self.cancelBtn = QPushButton("Cancel") self.cancelBtn.clicked.connect(self.closeWindow)
class AddIssue(QWidget): def __init__(self, parent): QWidget.__init__(self) self.setWindowTitle("Add issue") self.setWindowIcon(QIcon("assets/icons/icon.ico")) self.setGeometry(450, 150, 750, 950) # self.setFixedSize(self.size()) self.Parent = parent self.filePathName = "" self.UI() self.show() def UI(self): self.widgets() self.layouts() def widgets(self): self.scroll = QScrollArea() self.scroll.setWidgetResizable(True) self.dropdownData = IssuesDropdownData() # Top layout widgets self.addIssueImg = QLabel() self.img = QPixmap('assets/icons/create-issue.png') self.addIssueImg.setPixmap(self.img) self.addIssueImg.setAlignment(Qt.AlignCenter) self.titleText = QLabel("ADD ISSUE") self.titleText.setObjectName("add_issue_title_txt") self.titleText.setAlignment(Qt.AlignCenter) # Middle layout widgets self.dateEntry = QDateTimeEdit(calendarPopup=True) self.dateEntry.setDateTime(QDateTime.currentDateTime()) self.priorityEntry = QComboBox() self.priorityEntry.addItems(self.dropdownData.priorityItems()) self.observerEntry = QComboBox() self.observerEntry.addItems(self.dropdownData.observerItems()) self.revisionTeamEntry = QComboBox() self.revisionTeamEntry.addItems(self.dropdownData.revTeamItems()) self.inspectionNameEntry = QComboBox() self.inspectionNameEntry.addItems(self.dropdownData.inspNameItems()) self.observationThemeEntry = QComboBox() self.observationThemeEntry.addItems(self.dropdownData.hseThemeItems()) self.facilityEntry = QComboBox() self.facilityEntry.addItems(self.dropdownData.facilityItems()) self.facilitySupervisorEntry = QComboBox() self.facilitySupervisorEntry.addItems( self.dropdownData.facSupervisorItems()) self.specificLocationEntry = QTextEdit() self.inspectedDepartmentEntry = QComboBox() self.inspectedDepartmentEntry.addItems( self.dropdownData.inspDeptItems()) self.inspectedContractorEntry = QComboBox() self.inspectedContractorEntry.addItems( self.dropdownData.inspContrItems()) self.inspectedSubcontractorEntry = QComboBox() self.inspectedSubcontractorEntry.addItems( self.dropdownData.inspSubcontrItems()) self.deadlineEntry = QDateTimeEdit(calendarPopup=True) self.deadlineEntry.setDateTime(QDateTime.currentDateTime().addDays(14)) # Bottom layout widgets self.attachFilesBtn = QPushButton("Attach files") self.attachFilesBtn.clicked.connect(self.funcAttachFiles) self.addActionBtn = QPushButton("Add action") self.rootCauseEntry = QComboBox() self.rootCauseEntry.setEditable(True) self.rootCauseDetailsEntry = QTextEdit() self.rootCauseActionPartyEntry = QComboBox() self.rootCauseActionPartyEntry.setEditable(True) self.addRootCauseBtn = QPushButton("Add root cause") self.submitObservationBtn = QPushButton("Add issue") self.submitObservationBtn.clicked.connect(self.addIssue) self.cancelBtn = QPushButton("Cancel") self.cancelBtn.clicked.connect(self.closeWindow) def layouts(self): self.mainLayout = QVBoxLayout() self.topLayout = QHBoxLayout() self.bottomLayout = QFormLayout() self.bottomLayout.setVerticalSpacing(20) self.bottomBtnLayout = QHBoxLayout() # Put elements into frames for visual distinction self.topFrame = QFrame() self.bottomFrame = QFrame() # Add widgets to top layout # self.topLayout.addWidget(self.addIssueImg) self.topLayout.addWidget(self.titleText) self.topFrame.setLayout(self.topLayout) # Add widgets to middle layout # self.bottomLayout.addRow(self.issueInfoTitleText) self.bottomLayout.addRow(QLabel("Inspection Date: "), self.dateEntry) self.bottomLayout.addRow(QLabel("Priority: "), self.priorityEntry) self.bottomLayout.addRow(QLabel("Observer: "), self.observerEntry) self.bottomLayout.addRow(QLabel("Revision Team: "), self.revisionTeamEntry) self.bottomLayout.addRow(QLabel("Inspection Name: "), self.inspectionNameEntry) self.bottomLayout.addRow(QLabel("HSE Theme: "), self.observationThemeEntry) self.bottomLayout.addRow(QLabel("Facility: "), self.facilityEntry) self.bottomLayout.addRow(QLabel("Facility supervisor: "), self.facilitySupervisorEntry) self.bottomLayout.addRow(QLabel("Specific location: "), self.specificLocationEntry) self.bottomLayout.addRow(QLabel("Inspected department: "), self.inspectedDepartmentEntry) self.bottomLayout.addRow(QLabel("Inspected contractor: "), self.inspectedContractorEntry) self.bottomLayout.addRow(QLabel("Inspected subcontractor: "), self.inspectedSubcontractorEntry) self.bottomLayout.addRow(QLabel("Deadline: "), self.deadlineEntry) self.bottomLayout.addRow(QLabel(""), self.attachFilesBtn) # self.bottomLayout.addRow(QLabel(""), self.addActionBtn) # self.bottomLayout.addRow(QLabel(""), self.addRootCauseBtn) # self.bottomLayout.addRow(QLabel(""), self.submitObservationBtn) self.bottomBtnLayout.addWidget(self.cancelBtn) self.bottomBtnLayout.addItem( QSpacerItem(200, 5, QSizePolicy.Minimum, QSizePolicy.Expanding)) self.bottomBtnLayout.addWidget(self.submitObservationBtn) self.bottomBtnLayout.setAlignment(Qt.AlignBottom) self.bottomLayout.addRow(self.bottomBtnLayout) self.bottomFrame.setLayout(self.bottomLayout) # Make bottom frame scollable self.scroll.setWidget(self.bottomFrame) # Add frames to main layout self.mainLayout.addWidget(self.topFrame) self.mainLayout.addWidget(self.scroll) self.setLayout(self.mainLayout) @Slot() def closeWindow(self): self.close() @Slot() def addIssue(self): date = self.dateEntry.text() priority = self.priorityEntry.currentText() observer = self.observerEntry.currentText() revisionTeam = self.revisionTeamEntry.currentText() inspectionName = self.inspectionNameEntry.currentText() observationTheme = self.observationThemeEntry.currentText() facility = self.facilityEntry.currentText() facilitySupervisor = self.facilitySupervisorEntry.currentText() specificLocation = self.specificLocationEntry.toPlainText() inspectedDept = self.inspectedDepartmentEntry.currentText() inspectedContr = self.inspectedContractorEntry.currentText() inspectedSubcontr = self.inspectedSubcontractorEntry.currentText() deadline = self.deadlineEntry.text() # If user selected a file to attach, rename the file and copy it to media folder if self.filePathName != "": self.newFilePath = ShCopy2(self.filePathName, self.attachedFilePath) im = Image.open(self.filePathName) im_resized = self.crop_max_square(im).resize((800, 800), Image.LANCZOS) im_resized.save(self.attachedResizedFilePath) else: self.attachedFilePath = "" self.attachedResizedFilePath = "" if date and priority and observer and revisionTeam and inspectionName and observationTheme and facility \ and facilitySupervisor and specificLocation and inspectedDept and inspectedContr \ and inspectedSubcontr and deadline != "": try: query = "INSERT INTO issues (issue_date, issue_priority, issue_observer, issue_team," \ "issue_inspection, issue_theme, issue_facility, issue_fac_supervisor," \ "issue_spec_loc, issue_insp_dept, issue_insp_contr, issue_insp_subcontr, issue_deadline, " \ "created_on, photo_original_path, photo_resized_path) " \ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" # The purpose of this block is to make created_on timestamp the same format as other dates currentTime = QDateTimeEdit() currentTime.setDateTime(QDateTime.currentDateTime()) now = currentTime.text() db.cur.execute( query, (date, priority, observer, revisionTeam, inspectionName, observationTheme, facility, facilitySupervisor, specificLocation, inspectedDept, inspectedContr, inspectedSubcontr, deadline, now, self.attachedFilePath, self.attachedResizedFilePath)) db.conn.commit() QMessageBox.information(self, "Info", "Issue has been added") self.Parent.funcDisplayIssues() self.close() except: QMessageBox.information(self, "Info", "Issue has not been added") else: QMessageBox.information(self, "Info", "Fields cannot be empty") # Need to figure out how attach files to items in db @Slot() def funcAttachFiles(self): self.filePathName = QFileDialog.getOpenFileName( self, "Attach file...", "/", "Image files (*.jpg *.jpeg *.png)")[0] if osPath.isfile(self.filePathName): fileName, fileExt = osPath.splitext(self.filePathName) if fileExt == '.jpg' or fileExt == '.jpeg' or fileExt == '.png': date = datetime.now() randomSuffix = "".join( random.choice(string.ascii_lowercase) for i in range(15)) self.attachedFilePath = osPath.join( "assets", "media", "issues-media", "photos", ("{:%d%b%Y_%Hh%Mm}".format(date) + randomSuffix + fileExt)) self.attachedResizedFilePath = osPath.join( "assets", "media", "issues-media", "photos_resized", ("{:%d%b%Y_%Hh%Mm}".format(date) + randomSuffix + "_resized" + fileExt)) QMessageBox.information(self, "Info", "File attached successfully") else: QMessageBox.information(self, "Info", "Wrong file type!") else: QMessageBox.information(self, "Info", "No file selected") # Image processing functions @Slot() def crop_center(self, pil_img, crop_width, crop_height): img_width, img_height = pil_img.size fill_color = 'rgba(255, 255, 255, 1)' if pil_img.mode in ('RGBA', 'LA'): background = Image.new(pil_img.mode[:-1], pil_img.size, fill_color) background.paste(pil_img, pil_img.split()[-1]) image = background return pil_img.crop( ((img_width - crop_width) // 2, (img_height - crop_height) // 2, (img_width + crop_width) // 2, (img_height + crop_height) // 2)) # Crop the largest possible square from a rectangle @Slot() def crop_max_square(self, pil_img): return self.crop_center(pil_img, min(pil_img.size), min(pil_img.size))
def addIssue(self): date = self.dateEntry.text() priority = self.priorityEntry.currentText() observer = self.observerEntry.currentText() revisionTeam = self.revisionTeamEntry.currentText() inspectionName = self.inspectionNameEntry.currentText() observationTheme = self.observationThemeEntry.currentText() facility = self.facilityEntry.currentText() facilitySupervisor = self.facilitySupervisorEntry.currentText() specificLocation = self.specificLocationEntry.toPlainText() inspectedDept = self.inspectedDepartmentEntry.currentText() inspectedContr = self.inspectedContractorEntry.currentText() inspectedSubcontr = self.inspectedSubcontractorEntry.currentText() deadline = self.deadlineEntry.text() # If user selected a file to attach, rename the file and copy it to media folder if self.filePathName != "": self.newFilePath = ShCopy2(self.filePathName, self.attachedFilePath) im = Image.open(self.filePathName) im_resized = self.crop_max_square(im).resize((800, 800), Image.LANCZOS) im_resized.save(self.attachedResizedFilePath) else: self.attachedFilePath = "" self.attachedResizedFilePath = "" if date and priority and observer and revisionTeam and inspectionName and observationTheme and facility \ and facilitySupervisor and specificLocation and inspectedDept and inspectedContr \ and inspectedSubcontr and deadline != "": try: query = "INSERT INTO issues (issue_date, issue_priority, issue_observer, issue_team," \ "issue_inspection, issue_theme, issue_facility, issue_fac_supervisor," \ "issue_spec_loc, issue_insp_dept, issue_insp_contr, issue_insp_subcontr, issue_deadline, " \ "created_on, photo_original_path, photo_resized_path) " \ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" # The purpose of this block is to make created_on timestamp the same format as other dates currentTime = QDateTimeEdit() currentTime.setDateTime(QDateTime.currentDateTime()) now = currentTime.text() db.cur.execute( query, (date, priority, observer, revisionTeam, inspectionName, observationTheme, facility, facilitySupervisor, specificLocation, inspectedDept, inspectedContr, inspectedSubcontr, deadline, now, self.attachedFilePath, self.attachedResizedFilePath)) db.conn.commit() QMessageBox.information(self, "Info", "Issue has been added") self.Parent.funcDisplayIssues() self.close() except: QMessageBox.information(self, "Info", "Issue has not been added") else: QMessageBox.information(self, "Info", "Fields cannot be empty")
def setup(self): for label, value in self.data: if label is None and value is None: # Separator: (None, None) separator = QFrame() separator.setFrameShape(QFrame.HLine) separator.setFrameShadow(QFrame.Sunken) self.formlayout.addRow(separator) self.widgets.append(None) continue if label is None: if isinstance(value, (list, tuple)): field = PushLayout(value, self) self.formlayout.addRow(field) else: img_fmt = tuple(['.'+str(bytes(ext).decode()) for ext in QImageReader.supportedImageFormats()]) if value.endswith(img_fmt): # Image pixmap = QPixmap(value) lab = QLabel() lab.setPixmap(pixmap) self.formlayout.addRow(lab) else: # Comment self.formlayout.addRow(QLabel(value)) self.widgets.append(None) continue if 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 value in ['file', 'dir'] or value.startswith('file:'): field = FileLayout(value, self) elif value == 'slider' or value.startswith('slider:') \ or value.startswith('slider@'): field = SliderLayout(value, self) elif value == 'password': field = QLineEdit(self) field.setEchoMode(QLineEdit.Password) elif value in ['calendar', 'calendarM'] \ or value.startswith(('calendar:', 'calendarM:')) \ or value.startswith(('calendar@', 'calendarM@')): index = value.find('@') if index != -1: value, date = value[:index], value[index+1:] else: date = False field = QCalendarWidget(self) field.setVerticalHeaderFormat(field.NoVerticalHeader) parsed = value.split(':') if parsed[-1] == '': field.setGridVisible(True) parsed.pop(-1) if parsed[0] == 'calendarM': field.setFirstDayOfWeek(Qt.Monday) if len(parsed) == 2: field.setMaximumDate(datetime.date(*eval(parsed[1]))) elif len(parsed) == 3: field.setMinimumDate(datetime.date(*eval(parsed[1]))) field.setMaximumDate(datetime.date(*eval(parsed[2]))) if date: field.setSelectedDate(datetime.date(*eval(date))) elif '\n' in value: if value == '\n': value = '' for linesep in (os.linesep, '\n'): if linesep in value: value = value.replace(linesep, "\u2029") # paragraph separator field = QTextEdit(value, self) else: field = QLineEdit(value, self) elif isinstance(value, (list, tuple)) and is_text_string(value[0])\ and (value[0].startswith('0v') or value[0].startswith('0h') or value[0].startswith('1v') or value[0].startswith('1h')): if value[0][2:]: binary = value[0][2:] else: binary = value[0][0] * len(value[1:]) if value[0][1] == 'v': field = CheckVLayout(value[1:], binary, self) elif value[0][1] == 'h': field = CheckHLayout(value[1:], binary, self) elif isinstance(value, (list, tuple)): save_value = value value = list(value) # always needed to protect self.data selindex = value.pop(0) if isinstance(selindex, int): selindex = selindex - 1 if isinstance(value[0], (list, tuple)): keys = [ key for key, _val in value ] value = [ val for _key, val in value ] else: keys = value if selindex in value: selindex = value.index(selindex) elif selindex in keys: selindex = keys.index(selindex) elif not isinstance(selindex, int): print(f"Warning: '{selindex}' index is invalid (label: {label}, value: {value})" ,file=sys.stderr) selindex = -1 if isinstance(save_value, list): field = QComboBox(self) field.addItems(value) field.setCurrentIndex(selindex) elif isinstance(save_value, tuple): field = RadioLayout(value, selindex, self) elif isinstance(value, bool): field = QCheckBox(self) field.setChecked(value) elif isinstance(value, float): field = QLineEdit(QLocale().toString(value), self) field.setValidator(QDoubleValidator(field)) dialog = self.get_dialog() dialog.register_float_field(field) if SIGNAL is None: field.textChanged.connect(dialog.float_valid) else: self.connect(field, SIGNAL('textChanged(QString)'), dialog.float_valid) 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) elif isinstance(value, datetime.time): field = QTimeEdit(self) field.setTime(value) else: field = QLineEdit(repr(value), self) # Eventually catching the 'countfield' feature and processing it if label.startswith('n '): label = label[2:] if isinstance(field, QLineEdit) and is_text_string(value) or isinstance(field, QComboBox): field = CountLayout(field) else: print(f"Warning: '{label}' doesn't support 'nfield' feature", file=sys.stderr) # Eventually extracting tooltip from label and processing it index = label.find('::') if index != -1: label, tooltip = label[:index], label[index+2:] field.setToolTip(tooltip) # Eventually catching the 'required' feature and processing it if label.endswith(' *'): label = label[:-1] + '<font color="red">*</font>' if isinstance(field, (QLineEdit, QTextEdit, QComboBox, FileLayout, RadioLayout)): dialog = self.get_dialog() dialog.register_required_field(field) else: print(f"Warning: '{type(field)}' doesn't support 'required' feature", file=sys.stderr) if isinstance(field, QLineEdit): if SIGNAL is None: field.textChanged.connect(dialog.required_valid) else: self.connect(field, SIGNAL('textChanged(QString)'),dialog.required_valid) elif isinstance(field, QTextEdit): if SIGNAL is None: field.textChanged.connect(dialog.required_valid) else: self.connect(field, SIGNAL('textChanged()'),dialog.required_valid) elif isinstance(field, QComboBox): if SIGNAL is None: field.currentIndexChanged.connect(dialog.required_valid) else: self.connect(field,SIGNAL('currentIndexChanged(QString)'),dialog.required_valid) elif isinstance(field, FileLayout): if SIGNAL is None: field.lineedit.textChanged.connect(dialog.required_valid) else: self.connect(field.lineedit,SIGNAL('textChanged(QString)'),dialog.required_valid) elif isinstance(field, RadioLayout): if SIGNAL is None: field.group.buttonClicked.connect(dialog.required_valid) else: self.connect(field.group, SIGNAL('buttonClicked(int)'),dialog.required_valid) # Eventually setting the widget_color if self.widget_color: style = "background-color:" + self.widget_color + ";" field.setStyleSheet(style) if self.type == 'form': self.formlayout.addRow(label, field) elif self.type == 'questions': self.formlayout.addRow(QLabel(label)) self.formlayout.addRow(field) self.widgets.append(field)
class DisplayIssue(QWidget): def __init__(self, parent): QWidget.__init__(self) self.setWindowTitle("View issue") self.setWindowIcon(QIcon("assets/icons/logo-dark.png")) self.setGeometry(450, 150, 750, 950) self.Parent = parent self.setStyleSheet(styles.mainStyle()) self.UI() self.show() def UI(self): self.issueDetails() self.widgets() self.layouts() def issueDetails(self): row = self.Parent.issuesTable.currentRow() issueId = self.Parent.issuesTable.item(row, 2).text() # Strip the ISS# from the id issueId = issueId.lstrip("ISS#") query = "SELECT * FROM issues WHERE issue_id=?" cur = db.cur issue = cur.execute(query, (issueId, )).fetchone() self.id = issue[0] self.date = issue[1] self.priority = issue[2] self.observer = issue[3] self.revTeam = issue[4] self.inspectorName = issue[5] self.theme = issue[6] self.facility = issue[7] self.facilitySupervisor = issue[8] self.specLocation = issue[9] self.inspectedDept = issue[10] self.inspectedContr = issue[11] self.inspectedSubcontr = issue[12] self.deadline = issue[13] self.status = issue[14] def widgets(self): self.dropdownData = IssuesDropdownData() # Top layout widgets self.issueImg = QLabel() self.img = QPixmap('assets/icons/logo-dark.png') self.issueImg.setPixmap(self.img) self.issueImg.setAlignment(Qt.AlignCenter) self.titleText = QLabel("Display issue") self.titleText.setAlignment(Qt.AlignCenter) # Bottom layout widgets self.idEntry = QLabel(str(self.id)) self.dateEntry = QDateTimeEdit(calendarPopup=True) self.dateEntry.setDateTime( QDateTime.fromString(self.date, "yyyy-MM-dd h:mm AP")) self.priorityEntry = QComboBox() self.priorityEntry.addItems(self.dropdownData.priorityItems()) self.priorityEntry.setCurrentText(self.priority) self.observerEntry = QComboBox() self.observerEntry.addItems(self.dropdownData.observerItems()) self.observerEntry.setCurrentText(self.observer) self.revTeamEntry = QComboBox() self.revTeamEntry.addItems(self.dropdownData.revTeamItems()) self.revTeamEntry.setCurrentText(self.revTeam) self.inspectionNameEntry = QComboBox() self.inspectionNameEntry.addItems(self.dropdownData.inspNameItems()) self.inspectionNameEntry.setCurrentText(self.inspectorName) self.themeEntry = QComboBox() self.themeEntry.addItems(self.dropdownData.hseThemeItems()) self.themeEntry.setCurrentText(self.theme) self.facilityEntry = QComboBox() self.facilityEntry.addItems(self.dropdownData.facilityItems()) self.facilityEntry.setCurrentText(self.facility) self.facilitySupervisorEntry = QComboBox() self.facilitySupervisorEntry.addItems( self.dropdownData.facSupervisorItems()) self.facilitySupervisorEntry.setCurrentText(self.facilitySupervisor) self.specLocationEntry = QTextEdit() self.specLocationEntry.setText(self.specLocation) self.inspectedDeptEntry = QComboBox() self.inspectedDeptEntry.addItems(self.dropdownData.inspDeptItems()) self.inspectedDeptEntry.setCurrentText(self.inspectedDept) self.inspectedContrEntry = QComboBox() self.inspectedContrEntry.addItems(self.dropdownData.inspContrItems()) self.inspectedContrEntry.setCurrentText(self.inspectedContr) self.inspectedSubcontrEntry = QComboBox() self.inspectedSubcontrEntry.addItems( self.dropdownData.inspSubcontrItems()) self.inspectedSubcontrEntry.setCurrentText(self.inspectedSubcontr) self.statusEntry = QComboBox() self.statusEntry.addItems(self.dropdownData.statusItems()) self.statusEntry.setCurrentText(self.status) self.deadlineEntry = QDateTimeEdit(calendarPopup=True) self.deadlineEntry.setDateTime( QDateTime.fromString(self.deadline, "yyyy-MM-dd h:mm AP")) self.updateBtn = QPushButton("Update") self.updateBtn.clicked.connect(self.updateIssue) self.deleteBtn = QPushButton("Delete") self.deleteBtn.clicked.connect(self.Parent.funcDeleteIssue) self.cancelBtn = QPushButton("Cancel") self.cancelBtn.clicked.connect(self.closeWindow) def layouts(self): self.mainLayout = QVBoxLayout() self.topLayout = QVBoxLayout() self.bottomLayout = QFormLayout() self.bottomBtnLayout = QHBoxLayout() self.topFrame = QFrame() self.bottomFrame = QFrame() # Add widgets self.topLayout.addWidget(self.titleText) self.topLayout.addWidget(self.issueImg) self.topFrame.setLayout(self.topLayout) self.bottomLayout.addRow("ID: ", self.idEntry) self.bottomLayout.addRow("Date: ", self.dateEntry) self.bottomLayout.addRow("Priority: ", self.priorityEntry) self.bottomLayout.addRow("Observer: ", self.observerEntry) self.bottomLayout.addRow("Revision Team: ", self.revTeamEntry) self.bottomLayout.addRow("Inspector name: ", self.inspectionNameEntry) self.bottomLayout.addRow("HSE theme: ", self.themeEntry) self.bottomLayout.addRow("Facility: ", self.facilityEntry) self.bottomLayout.addRow("Facility supervisor: ", self.facilitySupervisorEntry) self.bottomLayout.addRow("Specific location: ", self.specLocationEntry) self.bottomLayout.addRow("Inspected department: ", self.inspectedDeptEntry) self.bottomLayout.addRow("Inspected contractor: ", self.inspectedContrEntry) self.bottomLayout.addRow("Inspected subcontractor: ", self.inspectedSubcontrEntry) self.bottomLayout.addRow("Deadline: ", self.deadlineEntry) self.bottomLayout.addRow("Status: ", self.statusEntry) self.bottomBtnLayout.addWidget(self.cancelBtn) self.bottomBtnLayout.addItem( QSpacerItem(60, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)) self.bottomBtnLayout.addWidget(self.deleteBtn) self.bottomBtnLayout.addWidget(self.updateBtn) self.bottomLayout.addRow(self.bottomBtnLayout) self.bottomFrame.setLayout(self.bottomLayout) self.mainLayout.addWidget(self.topFrame) self.mainLayout.addWidget(self.bottomFrame) self.setLayout(self.mainLayout) @Slot() def closeWindow(self): self.close() @Slot() def updateIssue(self): row = self.Parent.issuesTable.currentRow() issueId = self.Parent.issuesTable.item(row, 2).text() issueId = issueId.lstrip("ISS#") date = self.dateEntry.text() priority = self.priorityEntry.currentText() observer = self.observerEntry.currentText() revTeam = self.revTeamEntry.currentText() inspectionName = self.inspectionNameEntry.currentText() theme = self.themeEntry.currentText() facility = self.facilityEntry.currentText() facilitySupervisor = self.facilitySupervisorEntry.currentText() specLocation = self.specLocationEntry.toPlainText() inspDept = self.inspectedDeptEntry.currentText() inspContr = self.inspectedContrEntry.currentText() inspSubcontr = self.inspectedSubcontrEntry.currentText() status = self.statusEntry.currentText() print(status) deadline = self.deadlineEntry.text() if (date and priority and observer and revTeam and inspectionName and theme and facility and facilitySupervisor and specLocation and inspDept and deadline != ""): try: query = "UPDATE issues SET " \ "issue_date=?, " \ "issue_priority=?, " \ "issue_observer=?, " \ "issue_team=?," \ "issue_inspection=?, " \ "issue_theme=?, " \ "issue_facility=?, " \ "issue_fac_supervisor=?," \ "issue_spec_loc=?, " \ "issue_insp_dept=?, " \ "issue_insp_contr=?, " \ "issue_insp_subcontr=?," \ "issue_deadline=?, " \ "status=? " \ "WHERE issue_id=? " db.cur.execute( query, (date, priority, observer, revTeam, inspectionName, theme, facility, facilitySupervisor, specLocation, inspDept, inspContr, inspSubcontr, deadline, status, issueId)) db.conn.commit() QMessageBox.information(self, "Info", "Issue info updated") except: QMessageBox.information(self, "Info", "No changes made") else: QMessageBox.information(self, "Info", "Fields cannot be empty") self.Parent.funcDisplayIssues() self.close()
def __init__(self, parent=None): AbstractOperationDetails.__init__(self, parent) self.name = "Income/Spending" self.details_model = None self.category_delegate = CategorySelectorDelegate() self.tag_delegate = TagSelectorDelegate() self.float_delegate = FloatDelegate(2) self.date_label = QLabel(self) self.details_label = QLabel(self) self.account_label = QLabel(self) self.peer_label = QLabel(self) self.main_label.setText(g_tr("IncomeSpendingWidget", "Income / Spending")) self.date_label.setText(g_tr("IncomeSpendingWidget", "Date/Time")) self.details_label.setText(g_tr("IncomeSpendingWidget", "Details")) self.account_label.setText(g_tr("IncomeSpendingWidget", "Account")) self.peer_label.setText(g_tr("IncomeSpendingWidget", "Peer")) self.timestamp_editor = QDateTimeEdit(self) self.timestamp_editor.setCalendarPopup(True) self.timestamp_editor.setTimeSpec(Qt.UTC) self.timestamp_editor.setFixedWidth(self.timestamp_editor.fontMetrics().width("00/00/0000 00:00:00") * 1.25) self.timestamp_editor.setDisplayFormat("dd/MM/yyyy hh:mm:ss") self.account_widget = AccountSelector(self) self.peer_widget = PeerSelector(self) self.a_currency = OptionalCurrencyComboBox(self) self.a_currency.setText(g_tr("IncomeSpendingWidget", "Paid in foreign currency:")) self.add_button = QPushButton(self) self.add_button.setText(" +️ ") self.add_button.setFont(self.bold_font) self.add_button.setFixedWidth(self.add_button.fontMetrics().width("XXX")) self.del_button = QPushButton(self) self.del_button.setText(" — ️") self.del_button.setFont(self.bold_font) self.del_button.setFixedWidth(self.del_button.fontMetrics().width("XXX")) self.copy_button = QPushButton(self) self.copy_button.setText(" >> ️") self.copy_button.setFont(self.bold_font) self.copy_button.setFixedWidth(self.copy_button.fontMetrics().width("XXX")) self.details_table = QTableView(self) self.details_table.horizontalHeader().setFont(self.bold_font) self.details_table.setAlternatingRowColors(True) self.details_table.verticalHeader().setVisible(False) self.details_table.verticalHeader().setMinimumSectionSize(20) self.details_table.verticalHeader().setDefaultSectionSize(20) self.layout.addWidget(self.date_label, 1, 0, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.details_label, 2, 0, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.timestamp_editor, 1, 1, 1, 4) self.layout.addWidget(self.add_button, 2, 1, 1, 1) self.layout.addWidget(self.copy_button, 2, 2, 1, 1) self.layout.addWidget(self.del_button, 2, 3, 1, 1) self.layout.addWidget(self.account_label, 1, 5, 1, 1, Qt.AlignRight) self.layout.addWidget(self.peer_label, 2, 5, 1, 1, Qt.AlignRight) self.layout.addWidget(self.account_widget, 1, 6, 1, 1) self.layout.addWidget(self.peer_widget, 2, 6, 1, 1) self.layout.addWidget(self.a_currency, 1, 7, 1, 1) self.layout.addWidget(self.commit_button, 0, 9, 1, 1) self.layout.addWidget(self.revert_button, 0, 10, 1, 1) self.layout.addWidget(self.details_table, 4, 0, 1, 11) self.layout.addItem(self.horizontalSpacer, 1, 8, 1, 1) self.add_button.clicked.connect(self.addChild) self.del_button.clicked.connect(self.delChild) super()._init_db("actions") self.mapper.setItemDelegate(IncomeSpendingWidgetDelegate(self.mapper)) self.details_model = DetailsModel(self.details_table, db_connection()) self.details_model.setTable("action_details") self.details_model.setEditStrategy(QSqlTableModel.OnManualSubmit) self.details_table.setModel(self.details_model) self.details_model.dataChanged.connect(self.onDataChange) self.account_widget.changed.connect(self.mapper.submit) self.peer_widget.changed.connect(self.mapper.submit) self.a_currency.changed.connect(self.mapper.submit) self.a_currency.updated.connect(self.details_model.setAltCurrency) self.mapper.addMapping(self.timestamp_editor, self.model.fieldIndex("timestamp")) self.mapper.addMapping(self.account_widget, self.model.fieldIndex("account_id")) self.mapper.addMapping(self.peer_widget, self.model.fieldIndex("peer_id")) self.mapper.addMapping(self.a_currency, self.model.fieldIndex("alt_currency_id")) self.details_table.setItemDelegateForColumn(2, self.category_delegate) self.details_table.setItemDelegateForColumn(3, self.tag_delegate) self.details_table.setItemDelegateForColumn(4, self.float_delegate) self.details_table.setItemDelegateForColumn(5, self.float_delegate) self.model.select() self.details_model.select() self.details_model.configureView()
def create_date_picker(self, index): tmp_time = self.uniqueDates[index] time_QFormat = tmp_time.split("-") # date is parsed and converted to int to comply with required format of QDate date_picker = QDateTimeEdit( QDate(int(time_QFormat[0]), int(time_QFormat[1]), int(time_QFormat[2])), self) date_picker.setDisplayFormat("yyyy.MM.dd") date_picker.setCalendarPopup(True) date_picker.setCalendarWidget(QCalendarWidget()) date_picker.resize(date_picker.width() + 20, date_picker.height()) return date_picker
class FilewriterCommandWidget(QWidget): """ Used for the required and optional fields when saving a filewriter command JSON file. """ def __init__(self, parent=None): super(FilewriterCommandWidget, self).__init__() self.setParent(parent) self.setLayout(QFormLayout()) self.nexus_file_name_edit = QLineEdit() self.ok_button = QPushButton("Ok") if parent is not None: self.ok_button.clicked.connect(parent.close) self.broker_line_edit = QLineEdit() self.broker_line_edit.setPlaceholderText("broker:port") self.ok_validator = CommandDialogOKValidator() self.ok_validator.is_valid.connect(self.ok_button.setEnabled) filename_validator = CommandDialogFileNameValidator() self.nexus_file_name_edit.setValidator(filename_validator) filename_validator.is_valid.connect( partial( validate_line_edit, self.nexus_file_name_edit, tooltip_on_reject= f"Invalid NeXus file name - Should end with {HDF_FILE_EXTENSIONS}", )) filename_validator.is_valid.connect( self.ok_validator.set_filename_valid) filename_validator.is_valid.emit(False) broker_validator = NameValidator([]) self.broker_line_edit.setValidator(broker_validator) broker_validator.is_valid.connect( partial( validate_line_edit, self.broker_line_edit, tooltip_on_reject="Broker is required", )) broker_validator.is_valid.connect(self.ok_validator.set_broker_valid) broker_validator.is_valid.emit(False) self.start_time_enabled = QCheckBox() self.start_time_picker = QDateTimeEdit(QDateTime.currentDateTime()) self.start_time_picker.setDisplayFormat(TIME_FORMAT) self.start_time_enabled.stateChanged.connect( partial(self.state_changed, True)) self.start_time_enabled.setChecked(True) self.stop_time_enabled = QCheckBox() self.stop_time_picker = QDateTimeEdit(QDateTime.currentDateTime()) self.stop_time_picker.setDisplayFormat(TIME_FORMAT) self.stop_time_enabled.stateChanged.connect( partial(self.state_changed, False)) self.stop_time_enabled.setChecked(False) self.state_changed(False, Qt.CheckState.Unchecked) self.service_id_lineedit = QLineEdit() self.service_id_lineedit.setPlaceholderText("(Optional)") self.abort_on_uninitialised_stream_checkbox = QCheckBox() self.use_swmr_checkbox = QCheckBox() self.use_swmr_checkbox.setChecked(True) self.layout().addRow("nexus_file_name", self.nexus_file_name_edit) self.layout().addRow("broker", self.broker_line_edit) self.layout().addRow("specify start time?", self.start_time_enabled) self.layout().addRow("start_time", self.start_time_picker) self.layout().addRow("specify stop time?", self.stop_time_enabled) self.layout().addRow("stop_time", self.stop_time_picker) self.layout().addRow("service_id", self.service_id_lineedit) self.layout().addRow("abort_on_uninitialised_stream", self.abort_on_uninitialised_stream_checkbox) self.layout().addRow("use_hdf_swmr", self.use_swmr_checkbox) self.layout().addRow(self.ok_button) def state_changed(self, is_start_time: bool, state: Qt.CheckState): if state != Qt.CheckState.Checked: self.start_time_picker.setEnabled( False) if is_start_time else self.stop_time_picker.setEnabled( False) else: self.start_time_picker.setEnabled( True) if is_start_time else self.stop_time_picker.setEnabled( True) def get_arguments( self, ) -> Tuple[str, str, Union[str, None], Union[str, None], str, bool, bool]: """ gets the arguments of required and optional fields for the filewriter command. :return: Tuple containing all of the fields. """ return ( self.nexus_file_name_edit.text(), self.broker_line_edit.text(), self.start_time_picker.dateTime().toMSecsSinceEpoch() if self.start_time_enabled.checkState() == Qt.CheckState.Checked else None, self.stop_time_picker.dateTime().toMSecsSinceEpoch() if self.stop_time_enabled.checkState() == Qt.CheckState.Checked else None, self.service_id_lineedit.text(), self.abort_on_uninitialised_stream_checkbox.checkState() == Qt.CheckState.Checked, self.use_swmr_checkbox.checkState() == Qt.CheckState.Checked, )
def __init__(self, parent=None): AbstractOperationDetails.__init__(self, parent) self.name = "Transfer" self.from_date_label = QLabel(self) self.from_account_label = QLabel(self) self.from_amount_label = QLabel(self) self.to_date_label = QLabel(self) self.to_account_label = QLabel(self) self.to_amount_label = QLabel(self) self.fee_account_label = QLabel(self) self.fee_amount_label = QLabel(self) self.comment_label = QLabel(self) self.arrow_account = QLabel(self) self.copy_date_btn = QPushButton(self) self.copy_amount_btn = QPushButton(self) self.main_label.setText(g_tr("TransferWidget", "Transfer")) self.from_date_label.setText(g_tr("TransferWidget", "Date/Time")) self.from_account_label.setText(g_tr("TransferWidget", "From")) self.from_amount_label.setText(g_tr("TransferWidget", "Amount")) self.to_date_label.setText(g_tr("TransferWidget", "Date/Time")) self.to_account_label.setText(g_tr("TransferWidget", "To")) self.to_amount_label.setText(g_tr("TransferWidget", "Amount")) self.fee_account_label.setText(g_tr("TransferWidget", "Fee from")) self.fee_amount_label.setText(g_tr("TransferWidget", "Fee amount")) self.comment_label.setText(g_tr("TransferWidget", "Note")) self.arrow_account.setText(" ➜ ") self.copy_date_btn.setText("➜") self.copy_date_btn.setFixedWidth( self.copy_date_btn.fontMetrics().width("XXXX")) self.copy_amount_btn.setText("➜") self.copy_amount_btn.setFixedWidth( self.copy_amount_btn.fontMetrics().width("XXXX")) self.withdrawal_timestamp = QDateTimeEdit(self) self.withdrawal_timestamp.setCalendarPopup(True) self.withdrawal_timestamp.setTimeSpec(Qt.UTC) self.withdrawal_timestamp.setFixedWidth( self.withdrawal_timestamp.fontMetrics().width( "00/00/0000 00:00:00") * 1.25) self.withdrawal_timestamp.setDisplayFormat("dd/MM/yyyy hh:mm:ss") self.deposit_timestamp = QDateTimeEdit(self) self.deposit_timestamp.setCalendarPopup(True) self.deposit_timestamp.setTimeSpec(Qt.UTC) self.deposit_timestamp.setFixedWidth( self.deposit_timestamp.fontMetrics().width("00/00/0000 00:00:00") * 1.25) self.deposit_timestamp.setDisplayFormat("dd/MM/yyyy hh:mm:ss") self.from_account_widget = AccountSelector(self) self.to_account_widget = AccountSelector(self) self.fee_account_widget = AccountSelector(self) self.withdrawal = AmountEdit(self) self.withdrawal.setAlignment(Qt.AlignRight) self.deposit = AmountEdit(self) self.deposit.setAlignment(Qt.AlignRight) self.fee = AmountEdit(self) self.fee.setAlignment(Qt.AlignRight) self.comment = QLineEdit(self) self.layout.addWidget(self.from_date_label, 1, 0, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.from_account_label, 2, 0, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.from_amount_label, 3, 0, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.comment_label, 5, 0, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.withdrawal_timestamp, 1, 1, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.from_account_widget, 2, 1, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.withdrawal, 3, 1, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.comment, 5, 1, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.copy_date_btn, 1, 2, 1, 1) self.layout.addWidget(self.arrow_account, 2, 2, 1, 1, Qt.AlignCenter) self.layout.addWidget(self.copy_amount_btn, 3, 2, 1, 1) self.layout.addWidget(self.to_date_label, 1, 3, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.to_account_label, 2, 3, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.to_amount_label, 3, 3, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.fee_account_label, 4, 3, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.fee_amount_label, 5, 3, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.deposit_timestamp, 1, 4, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.to_account_widget, 2, 4, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.deposit, 3, 4, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.fee_account_widget, 4, 4, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.fee, 5, 4, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.commit_button, 0, 6, 1, 1) self.layout.addWidget(self.revert_button, 0, 7, 1, 1) self.layout.addItem(self.verticalSpacer, 6, 0, 1, 1) self.layout.addItem(self.horizontalSpacer, 1, 5, 1, 1) self.copy_date_btn.clicked.connect(self.onCopyDate) self.copy_amount_btn.clicked.connect(self.onCopyAmount) super()._init_db("transfers") self.mapper.setItemDelegate(TransferWidgetDelegate(self.mapper)) self.from_account_widget.changed.connect(self.mapper.submit) self.to_account_widget.changed.connect(self.mapper.submit) self.fee_account_widget.changed.connect(self.mapper.submit) self.mapper.addMapping(self.withdrawal_timestamp, self.model.fieldIndex("withdrawal_timestamp")) self.mapper.addMapping(self.from_account_widget, self.model.fieldIndex("withdrawal_account")) self.mapper.addMapping(self.withdrawal, self.model.fieldIndex("withdrawal")) self.mapper.addMapping(self.deposit_timestamp, self.model.fieldIndex("deposit_timestamp")) self.mapper.addMapping(self.to_account_widget, self.model.fieldIndex("deposit_account")) self.mapper.addMapping(self.deposit, self.model.fieldIndex("deposit")) self.mapper.addMapping(self.fee_account_widget, self.model.fieldIndex("fee_account")) self.mapper.addMapping(self.fee, self.model.fieldIndex("fee")) self.mapper.addMapping(self.comment, self.model.fieldIndex("note")) self.model.select()
def __init__(self, parent=None): super(FilewriterCommandWidget, self).__init__() self.setParent(parent) self.setLayout(QFormLayout()) self.nexus_file_name_edit = QLineEdit() self.ok_button = QPushButton("Ok") if parent is not None: self.ok_button.clicked.connect(parent.close) self.broker_line_edit = QLineEdit() self.broker_line_edit.setPlaceholderText("broker:port") self.ok_validator = CommandDialogOKValidator() self.ok_validator.is_valid.connect(self.ok_button.setEnabled) filename_validator = CommandDialogFileNameValidator() self.nexus_file_name_edit.setValidator(filename_validator) filename_validator.is_valid.connect( partial( validate_line_edit, self.nexus_file_name_edit, tooltip_on_reject= f"Invalid NeXus file name - Should end with {HDF_FILE_EXTENSIONS}", )) filename_validator.is_valid.connect( self.ok_validator.set_filename_valid) filename_validator.is_valid.emit(False) broker_validator = NameValidator([]) self.broker_line_edit.setValidator(broker_validator) broker_validator.is_valid.connect( partial( validate_line_edit, self.broker_line_edit, tooltip_on_reject="Broker is required", )) broker_validator.is_valid.connect(self.ok_validator.set_broker_valid) broker_validator.is_valid.emit(False) self.start_time_enabled = QCheckBox() self.start_time_picker = QDateTimeEdit(QDateTime.currentDateTime()) self.start_time_picker.setDisplayFormat(TIME_FORMAT) self.start_time_enabled.stateChanged.connect( partial(self.state_changed, True)) self.start_time_enabled.setChecked(True) self.stop_time_enabled = QCheckBox() self.stop_time_picker = QDateTimeEdit(QDateTime.currentDateTime()) self.stop_time_picker.setDisplayFormat(TIME_FORMAT) self.stop_time_enabled.stateChanged.connect( partial(self.state_changed, False)) self.stop_time_enabled.setChecked(False) self.state_changed(False, Qt.CheckState.Unchecked) self.service_id_lineedit = QLineEdit() self.service_id_lineedit.setPlaceholderText("(Optional)") self.abort_on_uninitialised_stream_checkbox = QCheckBox() self.use_swmr_checkbox = QCheckBox() self.use_swmr_checkbox.setChecked(True) self.layout().addRow("nexus_file_name", self.nexus_file_name_edit) self.layout().addRow("broker", self.broker_line_edit) self.layout().addRow("specify start time?", self.start_time_enabled) self.layout().addRow("start_time", self.start_time_picker) self.layout().addRow("specify stop time?", self.stop_time_enabled) self.layout().addRow("stop_time", self.stop_time_picker) self.layout().addRow("service_id", self.service_id_lineedit) self.layout().addRow("abort_on_uninitialised_stream", self.abort_on_uninitialised_stream_checkbox) self.layout().addRow("use_hdf_swmr", self.use_swmr_checkbox) self.layout().addRow(self.ok_button)
class EventPropertiesDialog(QDialog): def __init__(self): super().__init__(GlobalAccess().get_main_window()) def exec_(self): self.init_ui() return super().exec_() def init_ui(self): self.setFixedWidth(500) self.setWindowTitle(_('Event properties')) self.setWindowIcon(QIcon(config.ICON)) self.setSizeGripEnabled(False) self.setModal(True) self.layout = QFormLayout(self) self.label_main_title = QLabel(_('Main title')) self.item_main_title = QLineEdit() self.layout.addRow(self.label_main_title, self.item_main_title) self.label_sub_title = QLabel(_('Sub title')) self.item_sub_title = QTextEdit() self.item_sub_title.setMaximumHeight(100) self.layout.addRow(self.label_sub_title, self.item_sub_title) self.label_start_date = QLabel(_('Start date')) self.item_start_date = QDateTimeEdit() self.item_start_date.setDisplayFormat('yyyy.MM.dd HH:mm:ss') self.layout.addRow(self.label_start_date, self.item_start_date) self.label_end_date = QLabel(_('End date')) # self.item_end_date = QCalendarWidget() self.item_end_date = QDateTimeEdit() self.item_end_date.setDisplayFormat('yyyy.MM.dd HH:mm:ss') self.layout.addRow(self.label_end_date, self.item_end_date) self.label_location = QLabel(_('Location')) self.item_location = QLineEdit() self.layout.addRow(self.label_location, self.item_location) self.label_type = QLabel(_('Event type')) self.item_type = AdvComboBox() self.item_type.addItems(RaceType.get_titles()) self.layout.addRow(self.label_type, self.item_type) self.label_relay_legs = QLabel(_('Relay legs')) self.item_relay_legs = QSpinBox() self.item_relay_legs.setMinimum(1) self.item_relay_legs.setMaximum(20) self.item_relay_legs.setValue(3) self.layout.addRow(self.label_relay_legs, self.item_relay_legs) self.item_type.currentTextChanged.connect(self.change_type) self.label_refery = QLabel(_('Chief referee')) self.item_refery = QLineEdit() self.layout.addRow(self.label_refery, self.item_refery) self.label_secretary = QLabel(_('Secretary')) self.item_secretary = QLineEdit() self.layout.addRow(self.label_secretary, self.item_secretary) self.label_url = QLabel(_('URL')) self.item_url = QLineEdit() self.layout.addRow(self.label_url, self.item_url) def cancel_changes(): self.close() def apply_changes(): try: self.apply_changes_impl() except Exception as e: logging.error(str(e)) self.close() button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.button_ok = button_box.button(QDialogButtonBox.Ok) self.button_ok.setText(_('OK')) self.button_ok.clicked.connect(apply_changes) self.button_cancel = button_box.button(QDialogButtonBox.Cancel) self.button_cancel.setText(_('Cancel')) self.button_cancel.clicked.connect(cancel_changes) self.layout.addRow(button_box) self.set_values_from_model() self.show() def change_type(self): flag = self.item_type.currentText() == RaceType.RELAY.get_title() self.label_relay_legs.setVisible(flag) self.item_relay_legs.setVisible(flag) def set_values_from_model(self): obj = race() self.item_main_title.setText(str(obj.data.title)) self.item_sub_title.setText(str(obj.data.description)) self.item_location.setText(str(obj.data.location)) self.item_url.setText(str(obj.data.url)) self.item_refery.setText(str(obj.data.chief_referee)) self.item_secretary.setText(str(obj.data.secretary)) self.item_start_date.setDateTime(obj.data.get_start_datetime()) self.item_end_date.setDateTime(obj.data.get_end_datetime()) self.item_type.setCurrentText(obj.data.race_type.get_title()) self.item_relay_legs.setValue(obj.data.relay_leg_count) self.change_type() def apply_changes_impl(self): obj = race() start_date = self.item_start_date.dateTime().toPython() end_date = self.item_end_date.dateTime().toPython() obj.data.title = self.item_main_title.text() obj.data.description = self.item_sub_title.toPlainText() obj.data.description = obj.data.description.replace('\n', '<br>\n') obj.data.location = self.item_location.text() obj.data.url = self.item_url.text() obj.data.chief_referee = self.item_refery.text() obj.data.secretary = self.item_secretary.text() obj.data.start_datetime = start_date obj.data.end_datetime = end_date t = RaceType.get_by_name(self.item_type.currentText()) if t is not None: obj.data.race_type = t obj.data.relay_leg_count = self.item_relay_legs.value() obj.set_setting('system_zero_time', (start_date.hour, start_date.minute, 0)) ResultCalculation(race()).process_results() GlobalAccess().get_main_window().set_title()
class Ui_MainWindow(object): def setupUi(self, MainWindow): if not MainWindow.objectName(): MainWindow.setObjectName("MainWindow") MainWindow.resize(1121, 770) self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.scrollArea = QScrollArea(MainWindow) self.scrollArea.setObjectName("scrollArea") self.scrollArea.setGeometry(QRect(10, 10, 1101, 531)) self.scrollArea.setWidgetResizable(True) self.scrollAreaWidgetContents = QWidget() self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents") self.scrollAreaWidgetContents.setGeometry(QRect(0, 0, 1099, 529)) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.tableWidget = QTableWidget(self.scrollAreaWidgetContents) self.tableWidget.setObjectName("tableWidget") self.tableWidget.setGeometry(QRect(0, 0, 1099, 529)) self.tableWidget.setAutoFillBackground(True) self.tableWidget.horizontalHeader().setCascadingSectionResizes(False) self.tableWidget.setColumnCount(24) self.column_label = ['begin', 'end', 'time interval', 'login', 'mac ab', 'ULSK1', 'BRAS ip', 'start count', 'alive count', 'stop count', 'incoming', 'outcoming', 'error_count', 'code 0', 'code 1011', 'code 1100', 'code -3', 'code -52', 'code -42', 'code -21', 'code -40', ' code -44', 'code -46', ' code -38'] self.tableWidget.setHorizontalHeaderLabels(self.column_label) self.PathFile = QLineEdit(self.centralwidget) self.PathFile.setGeometry(QRect(200, 10, 831, 90)) self.PathFile.setObjectName("PathFile") self.progressBar_2 = QProgressBar(MainWindow) self.progressBar_2.setObjectName("progressBar_2") self.progressBar_2.setGeometry(QRect(400, 590, 651, 23)) self.progressBar_2.setProperty("value", 0) self.progressBar = QProgressBar(MainWindow) self.progressBar.setObjectName("progressBar") self.progressBar.setGeometry(QRect(400, 650, 651, 23)) self.progressBar.setProperty("value", 0) self.comboBox = QComboBox(MainWindow) self.comboBox.addItem("") self.comboBox.addItem("") self.comboBox.addItem("") self.comboBox.setObjectName("comboBox") self.comboBox.setGeometry(QRect(20, 690, 161, 28)) self.comboBox.setEditable(False) self.comboBox.setDuplicatesEnabled(False) self.dateTimeEdit = QDateTimeEdit(MainWindow) self.dateTimeEdit.setObjectName("dateTimeEdit") self.dateTimeEdit.setGeometry(QRect(190, 690, 151, 28)) self.dateTimeEdit.setCurrentSection(QDateTimeEdit.DaySection) self.saveButt = QPushButton(self.centralwidget) self.saveButt.setGeometry(QRect(20, 610, 321, 28)) self.saveButt.setObjectName("saveButt") self.AnalizButt = QPushButton(self.centralwidget) self.AnalizButt.setGeometry(QRect(20, 570, 321, 28)) self.AnalizButt.setObjectName("AnalizButt") self.OpenButt = QPushButton(self.centralwidget) self.OpenButt.setGeometry(QRect(400, 710, 615, 40)) self.OpenButt.setObjectName("OpenButt") self.change_cbButt = QPushButton(self.centralwidget) self.change_cbButt.setObjectName("change_cbButt") self.change_cbButt.setGeometry(QRect(20, 730, 321, 28)) self.change_sizeButt = QPushButton(self.centralwidget) self.change_sizeButt.setObjectName(u"change_sizeButt") self.change_sizeButt.setGeometry(QRect(20, 650, 161, 28)) self.change_sizeLine = QLineEdit(self.centralwidget) self.change_sizeLine.setObjectName("change_sizeLine") self.change_sizeLine.setGeometry(QRect(190, 650, 151, 28)) self.OpenButt.raise_() self.AnalizButt.raise_() self.change_cbButt.raise_() self.progressBar.raise_() self.PathFile.raise_() self.tableWidget.raise_() self.saveButt.raise_() self.comboBox.raise_() self.dateTimeEdit.raise_() self.change_sizeButt.raise_() MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QMetaObject.connectSlotsByName(MainWindow) # setupUi def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QCoreApplication.translate("MainWindow", "MainWindow", None)) #if QT_CONFIG(accessibility) self.tableWidget.setAccessibleName("") #endif // QT_CONFIG(accessibility) self.comboBox.setItemText(0, QCoreApplication.translate("MainWindow", "Парамметры выборки", None)) self.comboBox.setItemText(1, QCoreApplication.translate("MainWindow", "Выборка по логину", None)) self.comboBox.setItemText(2, QCoreApplication.translate("MainWindow", "Выборка по дате", None)) self.comboBox.setCurrentText(QCoreApplication.translate("MainWindow", "\u041f\u043e\u043b\u043d\u044b\u0439 \u0441\u043f\u0438\u0441\u043e\u043a", None)) self.comboBox.setPlaceholderText("") self.dateTimeEdit.setDisplayFormat(QCoreApplication.translate("MainWindow", "dd.MM.yyyy H:mm:ss")) self.saveButt.setText(QCoreApplication.translate("MainWindow", "Сохранить данные", None)) self.OpenButt.setText(QCoreApplication.translate("MainWindow", "Выбрать папку", None)) self.change_cbButt.setText(QCoreApplication.translate("MainWindow", "Изменить парамметры", None)) self.AnalizButt.setText(QCoreApplication.translate("MainWindow", "Анализировать", None)) self.change_sizeLine.setPlaceholderText(QCoreApplication.translate("MainWindow", "1-1000", None)) self.change_sizeButt.setText(QCoreApplication.translate("MainWindow", u"Изменить выборку", None))
class EditView: widget = QWidget() layout = QVBoxLayout() grid_widget = QWidget() grid_layout = QGridLayout() buttons_widget = QWidget() buttons_layout = QHBoxLayout() lbl_timestamp = QLabel("Timestamp") cal_timestamp = QDateTimeEdit() lbl_duration = QLabel("Duration") lbl_hour = QLabel("Hours") spn_hour = QSpinBox() lbl_min = QLabel("Minutes") spn_min = QSpinBox() lbl_sec = QLabel("Seconds") spn_sec = QSpinBox() lbl_activity = QLabel("Activity") txt_activity = QLineEdit() btn_done = QPushButton(QIcon.fromTheme('cancel'), "Done") btn_revert = QPushButton(QIcon.fromTheme('edit-undo'), "Revert") btn_save = QPushButton(QIcon.fromTheme('document-save'), "Save") index = None entry = None done_callback = None @classmethod def build(cls): """Build the interface.""" cls.lbl_timestamp.setWhatsThis("The timestamp for the entry.") cls.cal_timestamp.setWhatsThis("The timestamp for the entry.") cls.cal_timestamp.setDisplayFormat("yyyy MMM dd hh:mm:ss") cls.cal_timestamp.dateTimeChanged.connect(cls.edited) cls.lbl_hour.setWhatsThis("The hour part of the entry duration.") cls.spn_hour.setWhatsThis("The hour part of the entry duration.") cls.spn_hour.valueChanged.connect(cls.edited) cls.lbl_min.setWhatsThis("The minute part of the entry duration.") cls.spn_min.setWhatsThis("The minute part of the entry duration.") cls.spn_min.valueChanged.connect(cls.edited) cls.lbl_sec.setWhatsThis("The second part of the entry duration.") cls.spn_sec.setWhatsThis("The second part of the entry duration.") cls.spn_sec.valueChanged.connect(cls.edited) cls.lbl_activity.setWhatsThis("The activity notes for the entry.") cls.txt_activity.setWhatsThis("The activity notes for the entry.") cls.txt_activity.textChanged.connect(cls.edited) cls.grid_layout.addWidget(cls.lbl_timestamp, 0, 0, 1, 1) cls.grid_layout.addWidget(cls.cal_timestamp, 0, 1, 1, 1) cls.grid_layout.addWidget(cls.lbl_duration, 2, 0, 1, 2) cls.grid_layout.addWidget(cls.lbl_hour, 3, 0, 1, 1) cls.grid_layout.addWidget(cls.spn_hour, 3, 1, 1, 1) cls.grid_layout.addWidget(cls.lbl_min, 4, 0, 1, 1) cls.grid_layout.addWidget(cls.spn_min, 4, 1, 1, 1) cls.grid_layout.addWidget(cls.lbl_sec, 5, 0, 1, 1) cls.grid_layout.addWidget(cls.spn_sec, 5, 1, 1, 1) cls.grid_layout.addWidget(cls.lbl_activity, 6, 0, 1, 1) cls.grid_layout.addWidget(cls.txt_activity, 6, 1, 1, 1) cls.grid_widget.setLayout(cls.grid_layout) cls.btn_done.clicked.connect(cls.done) cls.btn_done.setWhatsThis("Return to time log.") cls.buttons_layout.addWidget(cls.btn_done) cls.buttons_layout.addWidget(cls.btn_revert) cls.buttons_layout.addWidget(cls.btn_save) cls.btn_save.clicked.connect(cls.save) cls.btn_save.setWhatsThis("Save the settings.") cls.btn_revert.clicked.connect(cls.refresh) cls.btn_revert.setWhatsThis("Discard changes to settings.") cls.buttons_widget.setLayout(cls.buttons_layout) cls.layout.addWidget(cls.grid_widget) cls.layout.addWidget(cls.buttons_widget) cls.widget.setLayout(cls.layout) cls.refresh() return cls.widget @classmethod def connect(cls, done=None): if done: cls.done_callback = done @classmethod def done(cls): if cls.done_callback: cls.done_callback() @classmethod def load_item(cls, timestamp): cls.entry = TimeLog.retrieve_from_log(timestamp) cls.refresh() @classmethod def edited(cls): cls.btn_done.setEnabled(False) cls.btn_revert.setEnabled(True) cls.btn_save.setEnabled(True) @classmethod def not_edited(cls): cls.btn_done.setEnabled(True) cls.btn_revert.setEnabled(False) cls.btn_save.setEnabled(False) @classmethod def refresh(cls): if cls.entry is None: return timestamp = cls.entry.timestamp datetime = QDateTime() datetime.setDate(QDate(timestamp.year, timestamp.month, timestamp.day)) datetime.setTime( QTime(timestamp.hour, timestamp.minute, timestamp.second)) cls.cal_timestamp.setDateTime(datetime) hours, minutes, seconds = cls.entry.duration cls.spn_hour.setValue(hours) cls.spn_min.setValue(minutes) cls.spn_sec.setValue(seconds) cls.txt_activity.setText(cls.entry.notes) cls.not_edited() @classmethod def save(cls): TimeLog.remove_from_log(cls.entry.timestamp) timestamp = datetime(cls.cal_timestamp.date().year(), cls.cal_timestamp.date().month(), cls.cal_timestamp.date().day(), cls.cal_timestamp.time().hour(), cls.cal_timestamp.time().minute(), cls.cal_timestamp.time().second()) new_timestamp = TimeLog.add_to_log(timestamp, cls.spn_hour.value(), cls.spn_min.value(), cls.spn_sec.value(), cls.txt_activity.text()) cls.not_edited() cls.entry = TimeLog.retrieve_from_log(new_timestamp) # Display the revised data. cls.refresh()
def setupUi(self, MainWindow): if not MainWindow.objectName(): MainWindow.setObjectName("MainWindow") MainWindow.resize(1121, 770) self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.scrollArea = QScrollArea(MainWindow) self.scrollArea.setObjectName("scrollArea") self.scrollArea.setGeometry(QRect(10, 10, 1101, 531)) self.scrollArea.setWidgetResizable(True) self.scrollAreaWidgetContents = QWidget() self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents") self.scrollAreaWidgetContents.setGeometry(QRect(0, 0, 1099, 529)) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.tableWidget = QTableWidget(self.scrollAreaWidgetContents) self.tableWidget.setObjectName("tableWidget") self.tableWidget.setGeometry(QRect(0, 0, 1099, 529)) self.tableWidget.setAutoFillBackground(True) self.tableWidget.horizontalHeader().setCascadingSectionResizes(False) self.tableWidget.setColumnCount(24) self.column_label = ['begin', 'end', 'time interval', 'login', 'mac ab', 'ULSK1', 'BRAS ip', 'start count', 'alive count', 'stop count', 'incoming', 'outcoming', 'error_count', 'code 0', 'code 1011', 'code 1100', 'code -3', 'code -52', 'code -42', 'code -21', 'code -40', ' code -44', 'code -46', ' code -38'] self.tableWidget.setHorizontalHeaderLabels(self.column_label) self.PathFile = QLineEdit(self.centralwidget) self.PathFile.setGeometry(QRect(200, 10, 831, 90)) self.PathFile.setObjectName("PathFile") self.progressBar_2 = QProgressBar(MainWindow) self.progressBar_2.setObjectName("progressBar_2") self.progressBar_2.setGeometry(QRect(400, 590, 651, 23)) self.progressBar_2.setProperty("value", 0) self.progressBar = QProgressBar(MainWindow) self.progressBar.setObjectName("progressBar") self.progressBar.setGeometry(QRect(400, 650, 651, 23)) self.progressBar.setProperty("value", 0) self.comboBox = QComboBox(MainWindow) self.comboBox.addItem("") self.comboBox.addItem("") self.comboBox.addItem("") self.comboBox.setObjectName("comboBox") self.comboBox.setGeometry(QRect(20, 690, 161, 28)) self.comboBox.setEditable(False) self.comboBox.setDuplicatesEnabled(False) self.dateTimeEdit = QDateTimeEdit(MainWindow) self.dateTimeEdit.setObjectName("dateTimeEdit") self.dateTimeEdit.setGeometry(QRect(190, 690, 151, 28)) self.dateTimeEdit.setCurrentSection(QDateTimeEdit.DaySection) self.saveButt = QPushButton(self.centralwidget) self.saveButt.setGeometry(QRect(20, 610, 321, 28)) self.saveButt.setObjectName("saveButt") self.AnalizButt = QPushButton(self.centralwidget) self.AnalizButt.setGeometry(QRect(20, 570, 321, 28)) self.AnalizButt.setObjectName("AnalizButt") self.OpenButt = QPushButton(self.centralwidget) self.OpenButt.setGeometry(QRect(400, 710, 615, 40)) self.OpenButt.setObjectName("OpenButt") self.change_cbButt = QPushButton(self.centralwidget) self.change_cbButt.setObjectName("change_cbButt") self.change_cbButt.setGeometry(QRect(20, 730, 321, 28)) self.change_sizeButt = QPushButton(self.centralwidget) self.change_sizeButt.setObjectName(u"change_sizeButt") self.change_sizeButt.setGeometry(QRect(20, 650, 161, 28)) self.change_sizeLine = QLineEdit(self.centralwidget) self.change_sizeLine.setObjectName("change_sizeLine") self.change_sizeLine.setGeometry(QRect(190, 650, 151, 28)) self.OpenButt.raise_() self.AnalizButt.raise_() self.change_cbButt.raise_() self.progressBar.raise_() self.PathFile.raise_() self.tableWidget.raise_() self.saveButt.raise_() self.comboBox.raise_() self.dateTimeEdit.raise_() self.change_sizeButt.raise_() MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QMetaObject.connectSlotsByName(MainWindow)
def __init__(self, parent=None): AbstractOperationDetails.__init__(self, parent) self.name = "Trade" self.date_label = QLabel(self) self.settlement_label = QLabel() self.number_label = QLabel(self) self.account_label = QLabel(self) self.symbol_label = QLabel(self) self.qty_label = QLabel(self) self.price_label = QLabel(self) self.fee_label = QLabel(self) self.comment_label = QLabel(self) self.main_label.setText(g_tr("TradeWidget", "Buy / Sell")) self.date_label.setText(g_tr("TradeWidget", "Date/Time")) self.settlement_label.setText(g_tr("TradeWidget", "Settlement")) self.number_label.setText(g_tr("TradeWidget", "#")) self.account_label.setText(g_tr("TradeWidget", "Account")) self.symbol_label.setText(g_tr("TradeWidget", "Asset")) self.qty_label.setText(g_tr("TradeWidget", "Qty")) self.price_label.setText(g_tr("TradeWidget", "Price")) self.fee_label.setText(g_tr("TradeWidget", "Fee")) self.comment_label.setText(g_tr("TradeWidget", "Note")) self.timestamp_editor = QDateTimeEdit(self) self.timestamp_editor.setCalendarPopup(True) self.timestamp_editor.setTimeSpec(Qt.UTC) self.timestamp_editor.setFixedWidth(self.timestamp_editor.fontMetrics().width("00/00/0000 00:00:00") * 1.25) self.timestamp_editor.setDisplayFormat("dd/MM/yyyy hh:mm:ss") self.settlement_editor = QDateEdit(self) self.settlement_editor.setCalendarPopup(True) self.settlement_editor.setTimeSpec(Qt.UTC) self.settlement_editor.setFixedWidth(self.settlement_editor.fontMetrics().width("00/00/0000") * 1.5) self.settlement_editor.setDisplayFormat("dd/MM/yyyy") self.account_widget = AccountSelector(self) self.asset_widget = AssetSelector(self) self.qty_edit = AmountEdit(self) self.qty_edit.setAlignment(Qt.AlignRight) self.price_edit = AmountEdit(self) self.price_edit.setAlignment(Qt.AlignRight) self.fee_edit = AmountEdit(self) self.fee_edit.setAlignment(Qt.AlignRight) self.number = QLineEdit(self) self.comment = QLineEdit(self) self.layout.addWidget(self.date_label, 1, 0, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.account_label, 2, 0, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.symbol_label, 3, 0, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.comment_label, 4, 0, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.timestamp_editor, 1, 1, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.account_widget, 2, 1, 1, 4) self.layout.addWidget(self.asset_widget, 3, 1, 1, 4) self.layout.addWidget(self.comment, 4, 1, 1, 4) self.layout.addWidget(self.settlement_label, 1, 2, 1, 1, Qt.AlignRight) self.layout.addWidget(self.settlement_editor, 1, 3, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.number_label, 1, 5, 1, 1, Qt.AlignRight) self.layout.addWidget(self.qty_label, 2, 5, 1, 1, Qt.AlignRight) self.layout.addWidget(self.price_label, 3, 5, 1, 1, Qt.AlignRight) self.layout.addWidget(self.fee_label, 4, 5, 1, 1, Qt.AlignRight) self.layout.addWidget(self.number, 1, 6, 1, 1) self.layout.addWidget(self.qty_edit, 2, 6, 1, 1) self.layout.addWidget(self.price_edit, 3, 6, 1, 1) self.layout.addWidget(self.fee_edit, 4, 6, 1, 1) self.layout.addWidget(self.commit_button, 0, 8, 1, 1) self.layout.addWidget(self.revert_button, 0, 9, 1, 1) self.layout.addItem(self.verticalSpacer, 6, 6, 1, 1) self.layout.addItem(self.horizontalSpacer, 1, 6, 1, 1) super()._init_db("trades") self.mapper.setItemDelegate(TradeWidgetDelegate(self.mapper)) self.account_widget.changed.connect(self.mapper.submit) self.asset_widget.changed.connect(self.mapper.submit) self.mapper.addMapping(self.timestamp_editor, self.model.fieldIndex("timestamp")) self.mapper.addMapping(self.settlement_editor, self.model.fieldIndex("settlement")) self.mapper.addMapping(self.account_widget, self.model.fieldIndex("account_id")) self.mapper.addMapping(self.asset_widget, self.model.fieldIndex("asset_id")) self.mapper.addMapping(self.number, self.model.fieldIndex("number")) self.mapper.addMapping(self.qty_edit, self.model.fieldIndex("qty")) self.mapper.addMapping(self.price_edit, self.model.fieldIndex("price")) self.mapper.addMapping(self.fee_edit, self.model.fieldIndex("fee")) self.mapper.addMapping(self.comment, self.model.fieldIndex("note")) self.model.select()
def createEditor(self, aParent, option, index): return QDateTimeEdit(aParent)
def __init__(self, parent=None): AbstractOperationDetails.__init__(self, parent) self.name = "Corporate action" self.combo_model = None self.date_label = QLabel(self) self.account_label = QLabel(self) self.type_label = QLabel(self) self.number_label = QLabel(self) self.before_label = QLabel(self) self.asset_b_label = QLabel(self) self.qty_b_label = QLabel(self) self.after_label = QLabel(self) self.asset_a_label = QLabel(self) self.qty_a_label = QLabel(self) self.ratio_label = QLabel(self) self.comment_label = QLabel(self) self.arrow_asset = QLabel(self) self.arrow_amount = QLabel(self) self.main_label.setText(g_tr("CorpActionWidget", "Corporate Action")) self.date_label.setText(g_tr("CorpActionWidget", "Date/Time")) self.account_label.setText(g_tr("CorpActionWidget", "Account")) self.type_label.setText(g_tr("CorpActionWidget", "Type")) self.number_label.setText(g_tr("CorpActionWidget", "#")) self.asset_b_label.setText(g_tr("CorpActionWidget", "Asset")) self.qty_b_label.setText(g_tr("CorpActionWidget", "Qty")) self.asset_a_label.setText(g_tr("CorpActionWidget", "Asset")) self.qty_a_label.setText(g_tr("CorpActionWidget", "Qty")) self.ratio_label.setText(g_tr("CorpActionWidget", "% of basis")) self.comment_label.setText(g_tr("CorpActionWidget", "Note")) self.arrow_asset.setText(" ➜ ") self.arrow_amount.setText(" ➜ ") self.timestamp_editor = QDateTimeEdit(self) self.timestamp_editor.setCalendarPopup(True) self.timestamp_editor.setTimeSpec(Qt.UTC) self.timestamp_editor.setFixedWidth(self.timestamp_editor.fontMetrics().width("00/00/0000 00:00:00") * 1.25) self.timestamp_editor.setDisplayFormat("dd/MM/yyyy hh:mm:ss") self.type = QComboBox(self) self.account_widget = AccountSelector(self) self.asset_b_widget = AssetSelector(self) self.asset_a_widget = AssetSelector(self) self.qty_b_edit = AmountEdit(self) self.qty_a_edit = AmountEdit(self) self.ratio_edit = AmountEdit(self) self.number = QLineEdit(self) self.comment = QLineEdit(self) self.layout.addWidget(self.date_label, 1, 0, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.type_label, 2, 0, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.number_label, 3, 0, 1, 1, Qt.AlignRight) self.layout.addWidget(self.comment_label, 5, 0, 1, 6, Qt.AlignLeft) self.layout.addWidget(self.timestamp_editor, 1, 1, 1, 1) self.layout.addWidget(self.type, 2, 1, 1, 1) self.layout.addWidget(self.number, 3, 1, 1, 1) self.layout.addWidget(self.comment, 5, 1, 1, 6) self.layout.addWidget(self.account_label, 1, 2, 1, 1, Qt.AlignRight) self.layout.addWidget(self.asset_b_label, 2, 2, 1, 1, Qt.AlignRight) self.layout.addWidget(self.qty_b_label, 3, 2, 1, 1, Qt.AlignRight) self.layout.addWidget(self.account_widget, 1, 3, 1, 4) self.layout.addWidget(self.asset_b_widget, 2, 3, 1, 1) self.layout.addWidget(self.qty_b_edit, 3, 3, 1, 1) self.layout.addWidget(self.arrow_asset, 2, 4, 1, 1) self.layout.addWidget(self.arrow_amount, 3, 4, 1, 1) self.layout.addWidget(self.asset_a_label, 2, 5, 1, 1, Qt.AlignRight) self.layout.addWidget(self.qty_a_label, 3, 5, 1, 1, Qt.AlignRight) self.layout.addWidget(self.ratio_label, 4, 5, 1, 1, Qt.AlignRight) self.layout.addWidget(self.asset_a_widget, 2, 6, 1, 1) self.layout.addWidget(self.qty_a_edit, 3, 6, 1, 1) self.layout.addWidget(self.ratio_edit, 4, 6, 1, 1) self.layout.addWidget(self.commit_button, 0, 8, 1, 1) self.layout.addWidget(self.revert_button, 0, 9, 1, 1) self.layout.addItem(self.verticalSpacer, 6, 0, 1, 1) self.layout.addItem(self.horizontalSpacer, 1, 7, 1, 1) super()._init_db("corp_actions") self.combo_model = QStringListModel([g_tr("CorpActionWidget", "N/A"), g_tr("CorpActionWidget", "Merger"), g_tr("CorpActionWidget", "Spin-Off"), g_tr("CorpActionWidget", "Symbol change"), g_tr("CorpActionWidget", "Split"), g_tr("CorpActionWidget", "Stock dividend")]) self.type.setModel(self.combo_model) self.mapper.setItemDelegate(CorporateActionWidgetDelegate(self.mapper)) self.account_widget.changed.connect(self.mapper.submit) self.asset_b_widget.changed.connect(self.mapper.submit) self.asset_a_widget.changed.connect(self.mapper.submit) self.mapper.addMapping(self.timestamp_editor, self.model.fieldIndex("timestamp")) self.mapper.addMapping(self.account_widget, self.model.fieldIndex("account_id")) self.mapper.addMapping(self.asset_b_widget, self.model.fieldIndex("asset_id")) self.mapper.addMapping(self.asset_a_widget, self.model.fieldIndex("asset_id_new")) self.mapper.addMapping(self.number, self.model.fieldIndex("number")) self.mapper.addMapping(self.qty_b_edit, self.model.fieldIndex("qty")) self.mapper.addMapping(self.qty_a_edit, self.model.fieldIndex("qty_new")) self.mapper.addMapping(self.ratio_edit, self.model.fieldIndex("basis_ratio")) self.mapper.addMapping(self.comment, self.model.fieldIndex("note")) self.mapper.addMapping(self.type, self.model.fieldIndex("type"), QByteArray().setRawData("currentIndex", 12)) self.model.select()
class application(QTabWidget): bot = 0 def __init__(self, parent=None): super(application, self).__init__(parent) self.bot = None self.db = sqlite3.connect('database') # tabs self.tab1 = QWidget() self.tab2 = QWidget() self.tab3 = QWidget() self.tab4 = QWidget() self.tab5 = QWidget() self.resize(640, 400) self.addTab(self.tab1, "Tab 1") self.addTab(self.tab2, "Tab 2") self.addTab(self.tab3, "Tab 3") self.addTab(self.tab4, "Tab 4") self.addTab(self.tab5, "Tab 5") # tab set keys self.h_box_key = QHBoxLayout() self.change_key_b = QPushButton("Edit keys") self.edit_1 = QLineEdit() self.edit_2 = QLineEdit() self.edit_3 = QLineEdit() self.edit_4 = QLineEdit() self.result = QLabel() self.set_button = QPushButton("Set keys") self.handle_info = QLabel() self.follower_info = QLabel() self.ready_lab = QLabel() # tab follow self.box_label = QLabel("Link to tweet") self.combo_label = QLabel("Mode") self.spin_label = QLabel("Limit before sleep") self.prog_bar = QProgressBar() self.combo_box = QComboBox() self.h_box = QHBoxLayout() self.spin_box = QSpinBox() self.link_box = QLineEdit() self.link_result = QLabel() self.follow_button = QPushButton("Follow Retweeters") self.cancel_button = QPushButton("Cancel") self.logger = QPlainTextEdit() self.h_box2 = QHBoxLayout() self.max_box = QSpinBox() self.max_label = QLabel("Max follows before stop") # tab unfollow self.unfollow_button = QPushButton("Unfollow Auto followers") self.unf_logger = QPlainTextEdit() self.unfollow_res = QLabel() self.prog_bar_unf = QProgressBar() self.unfollow_cancel = QPushButton("Cancel") self.unf_confirm = QMessageBox() # tab help self.help_box = QPlainTextEdit() self.help_label = QLabel( "<a href='http://Optumsense.com/'>http://Optumsense.com/</a>") #tab schedule self.tweet_box = QPlainTextEdit() self.date_time = QDateTimeEdit(QDateTime.currentDateTime()) self.schedule_but = QPushButton("Schedule Tweet") self.schedule_info = QLabel() self.schedule_table = QTableView() # threads self.follow_thread = None self.unfollow_thread = None self.schedule_thread = None # tabs self.tab1UI() self.tab2UI() self.tab3UI() self.tab4UI() self.tab5UI() self.setWindowTitle("Optumize") self.setWindowIcon(QtGui.QIcon('assets/oo.png')) # db cursor = self.db.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS keys(one TEXT, two TEXT, three TEXT, four TEXT)''' ) self.db.commit() def tab1UI(self): layout = QFormLayout() layout.addRow(self.h_box) self.h_box.addWidget(self.combo_label) self.combo_label.setAlignment(Qt.AlignRight) self.h_box.addWidget(self.combo_box) self.combo_box.addItem("Follow Retweeters") self.combo_box.addItem("Follow Followers") self.combo_box.currentIndexChanged.connect(self.selection_change) self.h_box.addWidget(self.spin_label) self.spin_label.setAlignment(Qt.AlignRight) self.h_box.addWidget(self.spin_box) self.spin_box.setMinimum(1) self.spin_box.setValue(30) layout.addRow(self.box_label, self.link_box) self.link_result.setAlignment(Qt.AlignCenter) layout.addRow(self.link_result) layout.addRow(self.follow_button) self.follow_button.clicked.connect(self.follow_ret) layout.addRow(self.cancel_button) self.cancel_button.clicked.connect(self.cancel_onclick) layout.addRow(self.h_box2) self.h_box2.addWidget(self.max_label) self.h_box2.addWidget(self.max_box) self.max_box.setFixedWidth(100) self.max_label.setAlignment(Qt.AlignRight) self.max_box.setMaximum(1000000) self.max_box.setValue(100) self.max_label.hide() self.max_box.hide() layout.addRow(self.logger) self.logger.setReadOnly(True) layout.addRow(self.prog_bar) self.prog_bar.setAlignment(Qt.AlignCenter) self.setTabText(0, "Follow") self.setTabIcon(0, QtGui.QIcon('assets/check_mark.png')) self.tab1.setLayout(layout) def selection_change(self, i): if i == 0: self.box_label.setText("Link to tweet") self.follow_button.setText("Follow Retweeters") self.link_result.setText("") self.max_label.hide() self.max_box.hide() self.follow_button.clicked.connect(self.follow_ret) else: self.box_label.setText("Handle of user") self.follow_button.setText("Follow Followers") self.link_result.setText("") self.max_label.show() self.max_box.show() self.max_label.setText("Max follows before stop") self.follow_button.clicked.connect(self.follow_fol) def cancel_onclick(self): if self.follow_thread is None: pass elif self.follow_thread.isRunning(): self.prog_bar.setValue(0) self.logger.appendPlainText("Cancelled script") self.follow_thread.terminate() self.follow_thread = None def follow_ret(self): self.prog_bar.setValue(0) self.follow_button.setEnabled(False) self.link_result.setText("") self.logger.clear() limit = self.spin_box.value() if self.bot is None: self.link_result.setText( "<font color='red'>Configure access keys in set keys tab</font>" ) return if self.follow_thread is not None: return link = self.link_box.text() id_tweet = link.split("/")[-1] try: tweet = self.bot.api.get_status(id_tweet) self.logger.appendPlainText( f"following retweeters from link: {link}...") self.follow_thread = FollowThread(self.bot, id_tweet, limit, 1, 0) self.follow_thread.start() self.connect(self.follow_thread, SIGNAL("finished()"), self.done) self.connect(self.follow_thread, SIGNAL("setup_prog(QString)"), self.setup_prog) self.connect(self.follow_thread, SIGNAL("post_follow(QString)"), self.post_follow) except tweepy.error.TweepError: self.follow_button.setEnabled(True) self.link_result.setText( "<font color='red'>Could not find tweet</font>") def setup_prog(self, msg): self.prog_bar.setMaximum(int(msg)) def follow_fol(self): self.prog_bar.setValue(0) self.follow_button.setEnabled(False) self.link_result.setText("") self.logger.clear() limit = self.spin_box.value() if self.bot is None: self.link_result.setText( "<font color='red'>Configure access keys in set keys tab</font>" ) return if self.follow_thread is not None: return handle = self.link_box.text() if handle == '': self.link_result.setText( "<font color='red'>Enter a handle above</font>") return elif handle[0] == '@': id_user = handle[1:] else: id_user = handle try: man = self.bot.api.get_user(id_user) self.logger.appendPlainText( f"following followers of {man.screen_name}...") self.logger.appendPlainText(f"Collecting") self.follow_thread = FollowThread(self.bot, id_user, limit, 2, self.max_box.value()) self.follow_thread.start() self.connect(self.follow_thread, SIGNAL("finished()"), self.done) self.connect(self.follow_thread, SIGNAL("setup_prog(QString)"), self.setup_prog) self.connect(self.follow_thread, SIGNAL("post_follow(QString)"), self.post_follow) except tweepy.error.TweepError: self.follow_button.setEnabled(True) self.link_result.setText( "<font color='red'>Could not find user</font>") def post_follow(self, message): if message == "bad": self.logger.appendPlainText( "Rate limit exceeded... sleeping for cooldown") else: self.logger.appendPlainText(message) self.prog_bar.setValue(self.prog_bar.value() + 1) def done(self): self.follow_thread = None self.follow_button.setEnabled(True) def tab2UI(self): layout = QFormLayout() layout.addRow(self.unfollow_button) layout.addRow(self.unfollow_cancel) layout.addRow(self.unfollow_res) self.unfollow_res.setAlignment(Qt.AlignCenter) self.unfollow_button.clicked.connect(self.unfollow_fol) self.unfollow_cancel.clicked.connect(self.unfollow_can) layout.addWidget(self.unf_logger) self.unf_logger.setReadOnly(True) layout.addRow(self.prog_bar_unf) self.prog_bar_unf.setAlignment(Qt.AlignCenter) self.setTabText(1, "Unfollow") self.setTabIcon(1, QtGui.QIcon('assets/cross.png')) self.tab2.setLayout(layout) def unfollow_fol(self): self.unfollow_button.setEnabled(False) self.unfollow_thread = UnfollowThread(self.bot) self.unfollow_thread.start() self.connect(self.unfollow_thread, SIGNAL("post_unfol(QString)"), self.post_unfol) self.connect(self.unfollow_thread, SIGNAL("finished()"), self.done_unf) def done_unf(self): self.unfollow_thread = None self.unf_logger.appendPlainText("Done") self.unfollow_button.setEnabled(True) def post_unfol(self, msg): if msg == "bad": self.unf_logger.appendPlainText( "rate limit exceeded, resting for 15 minutes") else: self.unf_logger.appendPlainText(f"Unfollowing {msg}") def unfollow_can(self): if self.unfollow_thread is None: pass elif self.unfollow_thread.isRunning(): self.unf_logger.appendPlainText("Cancelled script") self.unfollow_thread.terminate() self.unfollow_thread = None def tab3UI(self): layout = QFormLayout() layout.addWidget(self.tweet_box) self.tweet_box.setMaximumHeight(150) self.tweet_box.setPlaceholderText("Tweet contents") layout.addRow(self.date_time) self.date_time.setCalendarPopup(True) layout.addRow(self.schedule_info) layout.addRow(self.schedule_but) self.schedule_but.clicked.connect(self.schedule_tweet) layout.addWidget(self.schedule_table) self.setTabText(2, "Schedule Tweet") self.setTabIcon(2, QtGui.QIcon('assets/calendar.png')) self.tab3.setLayout(layout) def schedule_tweet(self): tweet_contents = self.tweet_box.toPlainText() if (len(tweet_contents) == 0): print("length of tweet is 0") self.schedule_info.setText("length of tweet is 0") return elif (len(tweet_contents) >= 280): self.schedule_info.setText("Tweet char limit exceeded") return if self.bot is None: self.schedule_info.setText( "<font color='red'>Configure access keys in set keys tab</font>" ) return datetime = self.date_time.text() try: print("done") self.schedule_thread.start() self.schedule_thread.add_tweet(tweet_contents, datetime) except: self.follow_button.setEnabled(True) self.link_result.setText( "<font color='red'>Could not find user</font>") def done_schedule(self): print("done scheduler") def tab4UI(self): layout = QFormLayout() layout.addRow("API key", self.edit_1) layout.addRow("API key secret", self.edit_2) layout.addRow("Auth token", self.edit_3) layout.addRow("Auth token secret", self.edit_4) self.set_button.clicked.connect(self.set_keys) l = self.read_file() if l is not None: if len(l) == 4: self.edit_1.setText(l[0]) self.edit_2.setText(l[1]) self.edit_3.setText(l[2]) self.edit_4.setText(l[3]) self.set_keys() layout.addRow(self.result) self.result.setAlignment(Qt.AlignCenter) layout.addRow(self.h_box_key) self.h_box_key.addWidget(self.change_key_b) self.h_box_key.addWidget(self.set_button) self.change_key_b.clicked.connect(self.change_keys) layout.addRow(self.handle_info) self.handle_info.setAlignment(Qt.AlignCenter) layout.addRow(self.follower_info) self.follower_info.setAlignment(Qt.AlignCenter) layout.addRow(self.ready_lab) self.ready_lab.setAlignment(Qt.AlignCenter) self.setTabText(3, "Settings") self.setTabIcon(3, QtGui.QIcon('assets/settings.png')) self.tab4.setLayout(layout) def change_keys(self): self.set_button.setEnabled(True) def set_keys(self): self.set_button.setEnabled(False) self.result.setText("") one = self.edit_1.text() two = self.edit_2.text() three = self.edit_3.text() four = self.edit_4.text() try: self.bot = apiconnector.ApiConnector(one, two, three, four) me = self.bot.add_keys(one, two, three, four) self.handle_info.setText("Handle: @" + me.screen_name) self.follower_info.setText("Followers: " + str(me.followers_count)) self.ready_lab.setText("<font color='green'>Ready!</font>") cursor = self.db.cursor() cursor.execute('DELETE FROM keys;', ) cursor.execute( '''INSERT INTO keys(one, two, three, four) VALUES(?,?,?,?)''', (one, two, three, four)) self.db.commit() self.schedule_thread = ScheduleThread(self.bot) except: print("Could not authenticate you") self.result.setText( "<font color='red'>Could not authenticate you</font>") def read_file(self): result = [] try: cursor = self.db.cursor() cursor.execute('''SELECT one, two, three, four FROM keys''') all_rows = cursor.fetchall() for row in all_rows: result.append(row[0]) result.append(row[1]) result.append(row[2]) result.append(row[3]) return result except: return None def tab5UI(self): layout = QFormLayout() layout.addRow("Website", self.help_label) self.help_label.setOpenExternalLinks(True) self.setTabText(4, "Help") self.setTabIcon(4, QtGui.QIcon('assets/help.png')) self.tab5.setLayout(layout)