def __init__(self, parent, object_name): self.parent = parent self.prefs = parent.prefs self.elements = self.prefs.get('appearance_css', None) debug_print("AnnotationElementsTable::__init__ - self.elements", self.elements) if not self.elements: self.elements = default_elements debug_print("AnnotationElementsTable::__init__ - self.elements", self.elements) QTableWidget.__init__(self) self.setObjectName(object_name) self.layout = parent.elements_hl.layout() # Add ourselves to the layout sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) #sizePolicy.setVerticalStretch(0) #sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth()) self.setSizePolicy(sizePolicy) #self.setMaximumSize(QSize(16777215, self.MAXIMUM_TABLE_HEIGHT)) self.setColumnCount(0) self.setRowCount(0) self.layout.addWidget(self)
def __create_ui(self): self.l = QGridLayout() self.t = QTableWidget(0, 3) self.t.setHorizontalHeaderLabels( ('№ дела (обращения)', 'Дата приёма', 'Дата отправки в СМЭВ')) self.t.resizeColumnsToContents() self.l.addWidget(self.t, 0, 0, 1, 2) w = QWidget() hl = QHBoxLayout(w) hl.setDirection(QHBoxLayout.LeftToRight) hl.addWidget(QWidget()) ok_b = QPushButton(tr('Добавить запрос')) ok_b.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Minimum) ok_b.clicked.connect(self.__show_form) hl.addWidget(ok_b) w.setLayout(hl) self.l.addWidget(w, 1, 0, 1, 2) w = QWidget() w.setLayout(self.l) self.cw.setWidget(w) # self.cw.setLayout(self.l) # self.w.setCentralWidget(self.cw) w = QWidget() l = QVBoxLayout() l.addWidget(self.cw) w.setLayout(l) self.w.setCentralWidget(w)
def setupUi(self): self.setWindowTitle('Dictionary') layout = QGridLayout(self) self.setLayout(layout) self.edit = QLineEdit(self) self.edit.textChanged.connect(self.onTextChanged) self.edit.returnPressed.connect(self.onReturnPressed) searchButton = QPushButton('&Search', self) searchButton.clicked.connect(self.onSearchButtonClicked) addButton = QPushButton('Add', self) addButton.clicked.connect(self.onAddButtonClicked) header = ('Short', 'Long', "Translate") self.table = QTableWidget(self) self.table.setColumnCount(3) self.table.setHorizontalHeaderLabels(header) self.table.setColumnWidth(0, 50) self.table.setColumnWidth(1, 200) self.edit.setCompleter( QCompleter(self.updateTable(self.dictionary.words))) layout.addWidget(self.edit, 0, 0) layout.addWidget(searchButton, 0, 1) layout.addWidget(addButton, 0, 2) layout.addWidget(self.table, 1, 0, 1, 3)
def __init__(self, *args, **kwargs): super(GUIapp, self).__init__(*args, **kwargs) self.setWindowTitle("TEST 1.0") self.resize(800, 600) self.button1 = QPushButton("Input File") self.button1.clicked.connect(self.getFile) self.label1 = QLabel("Prediction") self.table = QTableWidget() self.label2 = QLabel("Insert CSV File") self.textEditor = QTextEdit() #self.setCentralWidget(self.graphWidget) #https: // stackoverflow.com / questions / 31775468 / show - string - values - on - x - axis - in -pyqtgraph # plot data: x, y values layout = QVBoxLayout() layout.addWidget(self.button1) layout.addWidget(self.label2) layout.addWidget(self.textEditor) layout.addWidget(self.label1) layout.addWidget(self.table) self.setLayout(layout)
def focusInEvent(self, *args, **kwargs): """ Reimplemented in order to set flag if cursor was moved by focus. """ self.in_foc_as = True QTableWidget.focusInEvent(self, *args, **kwargs) self.in_foc_as = False
def __layout(self): self.container = QWidget() self.tableWidget = QTableWidget() self.layout = QVBoxLayout() self.layout.addWidget(self.tableWidget) self.setLayout(self.layout)
def initUI(self): self.file_number = 2 self._score = 0 self.setMouseTracking(True) self.resize(500, 500) self.center() self.setWindowTitle('Игра') self.main_pic = QLabel(self) self.main_pic.setPixmap( QPixmap(resource_path("PIC/running_rabbit.jpg"))) self.main_pic.resize(500, 500) self.button_start_game = QPushButton("НАЧАТЬ ИГРУ", self) self.button_start_game.resize(140, 50) self.button_start_game.move(70, 300) self.button_start_game.clicked.connect(self.start_game) self.button_edit_map = QPushButton("СОЗДАТЬ КАРТУ", self) self.button_edit_map.resize(140, 50) self.button_edit_map.move(70, 360) self.button_edit_map.clicked.connect(self.edit_map_menu) self.button_exit = QPushButton("ЗАКОНЧИТЬ СЕАНС", self) self.button_exit.resize(140, 50) self.button_exit.move(70, 420) self.button_exit.clicked.connect(self.exit) self.timer_game = QTimer() self.timer_game.timeout.connect(self.updateValues) self.timer_game.start(200) self.setFocusPolicy(Qt.StrongFocus) self.lable_score = QLabel(self) self.lable_score.resize(200, 35) self.lable_score.setFont( QFont("RetroComputer[RUS by Daymarius]", 26, QFont.Bold)) self.lable_score.setVisible(False) self.button_menu = QPushButton("НАЗАД", self) self.button_menu.resize(120, 40) self.button_menu.clicked.connect(self.show_menu) self.button_menu.setVisible(False) self.lable_name = QLabel("ВВЕДИТЕ ВАШЕ ИМЯ:", self) self.lable_name.sizeHint() self.lable_name.setFont( QFont("RetroComputer[RUS by Daymarius]", 10, QFont.Bold)) self.lable_name.move(230, 300) self.input_name = QLineEdit("Без имени", self) self.input_name.resize(200, 20) self.input_name.move(230, 325) self.table_score = QTableWidget(self) self.table_score.resize(200, 120) self.table_score.move(230, 350)
def __init__(self): ''' Constructor ''' QTableWidget.__init__(self) self.horizontal_headers = self.horizontalHeader() self.vertical_headers = self.verticalHeader() self.vertical_headers.setContextMenuPolicy(Qt.CustomContextMenu) self.vertical_headers.customContextMenuRequested.connect( self.show_header_right_click_menu)
def __init__(self, parent=None): super(CustomsQWidget, self).__init__(parent) self.setStyleSheet(settings.css_style) self.setWindowFlags(Qt.FramelessWindowHint) self.setObjectName('dialog') self.setMinimumSize(420, 330) # Fields self.customs_table = QTableWidget() self.table_headers = ['Variable', 'Value'] self.offset = None
def __init__(self, parent=None): super(HistoryQWidget, self).__init__(parent) self.setStyleSheet(settings.css_style) self.setWindowFlags(Qt.FramelessWindowHint) self.setObjectName('dialog') self.setMinimumSize(800, 670) # Fields self.history_table = QTableWidget() self.table_headers = [_('Events')] self.history_title = QLabel() self.offset = None
def __init__(self, parent): QTableWidget.__init__(self, parent) self.create_context_menu() self.setSelectionBehavior(QAbstractItemView.SelectRows) self.setDragEnabled(True) self.setAcceptDrops(True) self.setDragDropMode(QAbstractItemView.InternalMove) self.setDropIndicatorShown(True) self.fmt = tweaks['gui_pubdate_display_format'] if self.fmt is None: self.fmt = 'MMM yyyy'
class ResultTable(QWidget): def __init__(self): super(ResultTable, self).__init__() self.__layout() def __layout(self): self.container = QWidget() self.tableWidget = QTableWidget() self.layout = QVBoxLayout() self.layout.addWidget(self.tableWidget) self.setLayout(self.layout) def setContent(self, astroTable): self.tableWidget.setRowCount(len(astroTable)) self.tableWidget.setColumnCount(len(astroTable.colnames)) self.tableWidget.setHorizontalHeaderLabels(astroTable.colnames) rowIdx = 0 colIdx = 0 for row in astroTable: for header in astroTable.colnames: self.tableWidget.setItem( rowIdx, colIdx, QTableWidgetItem(str(astroTable[rowIdx][header]))) colIdx = colIdx + 1 rowIdx = rowIdx + 1 colIdx = 0
def setup_ui(self): self.l = l = QVBoxLayout(self) self.la = la = QLabel(_( 'Create rules to convert identifiers into links.')) la.setWordWrap(True) l.addWidget(la) items = [] for k, lx in iteritems(msprefs['id_link_rules']): for n, t in lx: items.append((k, n, t)) items.sort(key=lambda x:sort_key(x[1])) self.table = t = QTableWidget(len(items), 3, self) t.setHorizontalHeaderLabels([_('Key'), _('Name'), _('Template')]) for r, (key, val, template) in enumerate(items): t.setItem(r, 0, QTableWidgetItem(key)) t.setItem(r, 1, QTableWidgetItem(val)) t.setItem(r, 2, QTableWidgetItem(template)) l.addWidget(t) t.horizontalHeader().setSectionResizeMode(2, t.horizontalHeader().Stretch) self.cb = b = QPushButton(QIcon(I('plus.png')), _('&Add rule'), self) connect_lambda(b.clicked, self, lambda self: self.edit_rule()) self.bb.addButton(b, self.bb.ActionRole) self.rb = b = QPushButton(QIcon(I('minus.png')), _('&Remove rule'), self) connect_lambda(b.clicked, self, lambda self: self.remove_rule()) self.bb.addButton(b, self.bb.ActionRole) self.eb = b = QPushButton(QIcon(I('modified.png')), _('&Edit rule'), self) connect_lambda(b.clicked, self, lambda self: self.edit_rule(self.table.currentRow())) self.bb.addButton(b, self.bb.ActionRole) l.addWidget(self.bb)
def mousePressEvent(self, event): ep = event.pos() if self.indexAt(ep) not in self.selectionModel().selectedIndexes() and \ event.button() == Qt.LeftButton and not self.event_has_mods(): self.setDragEnabled(False) else: self.setDragEnabled(True) return QTableWidget.mousePressEvent(self, event)
class ViewIssuedBooks(QWidget): session=Session() def __init__(self,id): super().__init__() self.id=id self.title="Admin Panel" self.width = 640 self.height = 400 self.top = 100 self.left = 100 self.initUI() def initUI(self): self.createTable() self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.layout=QVBoxLayout() self.layout.addWidget(self.tableWidget) self.setLayout(self.layout) self.show() def createTable(self): # Create table self.tableWidget = QTableWidget() self.populateTable(self.tableWidget) self.tableWidget.move(0,0) # table selection change #self.tableWidget.doubleClicked.connect(self.on_click) def populateTable(self,table): issue=self.session.query(Issue).filter(Issue.issued_to==self.id).all() try: table.setRowCount(len(issue)+1) self.tableWidget.setColumnCount(3) self.tableWidget.setItem(0,0, QTableWidgetItem("Id")) self.tableWidget.setItem(0,1, QTableWidgetItem("Book")) self.tableWidget.setItem(0,2, QTableWidgetItem("Author")) for i in range(len(issue)): table.setItem(i+1,0,QTableWidgetItem(str(issue[i].id))) table.setItem(i+1,1,QTableWidgetItem(issue[i].book.name)) table.setItem(i+1,2,QTableWidgetItem(issue[i].book.author)) except: print("An error has occured")
def __init__(self, parent, *args): QWidget.__init__(self, parent, *args) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) lo = QVBoxLayout(self) lo.setContentsMargins(0, 0, 0, 0) lo1 = QHBoxLayout() lo.addLayout(lo1) lo1.setContentsMargins(0, 0, 0, 0) lbl = QLabel(QString("<nobr><b>Source groupings:</b></nobr>"), self) lo1.addWidget(lbl, 0) lo1.addStretch(1) # add show/hide button self._showattrbtn = QPushButton(self) self._showattrbtn.setMinimumWidth(256) lo1.addWidget(self._showattrbtn, 0) lo1.addStretch() self._showattrbtn.clicked.connect(self._togglePlotControlsVisibility) # add table self.table = QTableWidget(self) lo.addWidget(self.table) self.table.cellChanged[int, int].connect(self._valueChanged) self.table.setSelectionMode(QTableWidget.NoSelection) # setup basic columns self.table.setColumnCount(6 + len(self.EditableAttrs)) for i, label in enumerate( ("grouping", "total", "selection", "list", "plot", "style")): self.table.setHorizontalHeaderItem(i, QTableWidgetItem(label)) self.table.horizontalHeader().setSectionHidden(self.ColApply, True) # setup columns for editable grouping attributes for i, attr in self.AttrByCol.items(): self.table.setHorizontalHeaderItem( i, QTableWidgetItem(PlotStyles.StyleAttributeLabels[attr])) self.table.horizontalHeader().setSectionHidden(i, True) self.table.verticalHeader().hide() # other internal init self._attrs_shown = False self._togglePlotControlsVisibility() self.model = None self._setting_model = False self._currier = PersistentCurrier() # row of 'selected' grouping self._irow_selgroup = 0
def __init__(self): super().__init__() self.iDList = [] self.packetCount = 0 self.counter = 0 self.statsTableIndex = 0 self.setWindowTitle('SnifferStats') self.snifferAPI = SnifferAPI() self.contentBox = QLabel() self.statsTable = QTableWidget() self.tabs = QTabWidget() self.tabBasic = QWidget() self.tabAdvanced = QWidget() self.layout = QVBoxLayout() self.tabs.addTab(self.tabBasic, "Basic") self.tabs.addTab(self.tabAdvanced, "Advanced") self.tabBasic.layout = QVBoxLayout() self.tabAdvanced.layout = QVBoxLayout()
class GUIapp(QWidget): def __init__(self, *args, **kwargs): super(GUIapp, self).__init__(*args, **kwargs) self.setWindowTitle("TEST 1.0") self.resize(800, 600) self.button1 = QPushButton("Input File") self.button1.clicked.connect(self.getFile) self.label1 = QLabel("Prediction") self.table = QTableWidget() self.label2 = QLabel("Insert CSV File") self.textEditor = QTextEdit() #self.setCentralWidget(self.graphWidget) #https: // stackoverflow.com / questions / 31775468 / show - string - values - on - x - axis - in -pyqtgraph # plot data: x, y values layout = QVBoxLayout() layout.addWidget(self.button1) layout.addWidget(self.label2) layout.addWidget(self.textEditor) layout.addWidget(self.label1) layout.addWidget(self.table) self.setLayout(layout) def getFile(self): dialg = QFileDialog() dialg.setFileMode(QFileDialog.AnyFile) dialg.setNameFilter("CSV Files (*.csv)") if dialg.exec_(): fileName = dialg.selectedFiles() f = open(fileName[0], 'r') ml = machineLearning(f) with open(fileName[0], 'r') as f: data = f.read() self.textEditor.setPlainText(data) self.table.setRowCount(len(ml)) self.table.setColumnCount(1) x = -1 while x <= len(ml) - 2: x += 1 self.table.setItem(x, 0, QTableWidgetItem(ml[x])) header = self.table.horizontalHeader() header.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch) f.close() else: pass
def __init__(self, parent, object_name): self.parent = parent self.prefs = parent.prefs self.elements = self.prefs.get('appearance_css', None) if not self.elements: self.elements = default_elements QTableWidget.__init__(self) self.setObjectName(object_name) self.layout = parent.elements_hl.layout() # Add ourselves to the layout sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) #sizePolicy.setVerticalStretch(0) #sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth()) self.setSizePolicy(sizePolicy) #self.setMaximumSize(QSize(16777215, self.MAXIMUM_TABLE_HEIGHT)) self.setColumnCount(0) self.setRowCount(0) self.layout.addWidget(self)
def moveCursor(self, cursor_action, modifiers): """ Reimplemented in order to create a new row by <Tab> if last cell. Returns: index (QModelIndex): index to move cursor. """ if not self.in_foc_as and \ cursor_action == QAbstractItemView.MoveNext and \ self.currentRow() == self.rowCount() - 1 and \ self.currentColumn() == self.columnCount() - 1: self.insertRow(self.rowCount()) for j in xrange(self.columnCount()): newitem = QTableWidgetItem("") self.setItem(self.rowCount() - 1, j, newitem) index = self.indexFromItem(self.item(self.rowCount() - 1, 0)) else: index = QTableWidget.moveCursor(self, cursor_action, modifiers) return index
def __init__(self, parent=None): QTableWidget.__init__(self, parent=parent)
class SyncWidget(QWidget): def __init__(self, gui, do_user_config, selected_book_ids, is_sync_selected): QWidget.__init__(self, gui) api.build_request('/limits') self.logger = Logger( path.join(gui.current_db.library_path, 'bookfusion_sync.log')) self.logger.info( 'Open sync dialog: selected_book_ids={}; is_sync_selected={}'. format(selected_book_ids, is_sync_selected)) if len(selected_book_ids) == 0: is_sync_selected = False self.worker_thread = None self.do_user_config = do_user_config self.db = gui.current_db.new_api self.selected_book_ids = selected_book_ids self.l = QVBoxLayout() self.l.setContentsMargins(0, 0, 0, 0) self.setLayout(self.l) self.radio_layout = QVBoxLayout() self.l.addLayout(self.radio_layout) self.sync_all_radio = QRadioButton('Sync all books') self.sync_all_radio.setChecked(not is_sync_selected) self.radio_layout.addWidget(self.sync_all_radio) sync_selected_radio_label = 'Sync selected books' if len(selected_book_ids) > 0: sync_selected_radio_label = 'Sync {} selected {}'.format( len(selected_book_ids), 'book' if len(selected_book_ids) == 1 else 'books') self.sync_selected_radio = QRadioButton(sync_selected_radio_label) self.sync_selected_radio.toggled.connect(self.toggle_sync_selected) self.sync_selected_radio.setChecked(is_sync_selected) self.sync_selected_radio.setEnabled(len(selected_book_ids) > 0) self.radio_layout.addWidget(self.sync_selected_radio) self.reupload_possible = len(selected_book_ids) > 0 and len( selected_book_ids) <= 100 if self.reupload_possible: for book_id in selected_book_ids: identifiers = self.db.get_proxy_metadata(book_id).identifiers if not identifiers.get('bookfusion'): self.reupload_possible = False self.reupload_checkbox = QCheckBox('Re-upload book files', self) self.reupload_checkbox.setVisible(is_sync_selected and self.reupload_possible) self.radio_layout.addWidget(self.reupload_checkbox) self.btn_layout = QHBoxLayout() self.l.addLayout(self.btn_layout) self.config_btn = QPushButton('Configure') self.config_btn.clicked.connect(self.config) self.btn_layout.addWidget(self.config_btn) self.btn_layout.addStretch() self.start_btn = QPushButton('Start') self.start_btn.clicked.connect(self.start) self.btn_layout.addWidget(self.start_btn) self.cancel_btn = QPushButton('Cancel') self.cancel_btn.clicked.connect(self.cancel) self.cancel_btn.hide() self.btn_layout.addWidget(self.cancel_btn) self.info = QHBoxLayout() self.info.setContentsMargins(0, 0, 0, 0) self.l.addLayout(self.info) self.msg = QLabel() self.info.addWidget(self.msg) self.info.addStretch() self.log_btn = QLabel('<a href="#">Log</a>') self.log_btn.linkActivated.connect(self.toggle_log) self.log_btn.hide() self.info.addWidget(self.log_btn) self.log = QTableWidget(0, 2) self.log.setHorizontalHeaderLabels(['Book', 'Message']) self.log.horizontalHeader().setStretchLastSection(True) self.log.hide() self.l.addWidget(self.log) self.apply_config() def __del__(self): if self.worker_thread: self.worker_thread.quit() self.worker_thread.terminate() def config(self): self.do_user_config(parent=self) self.apply_config() def apply_config(self): configured = bool(prefs['api_key']) self.start_btn.setEnabled(configured) def toggle_sync_selected(self, is_sync_selected): if hasattr(self, 'reupload_checkbox'): self.reupload_checkbox.setVisible(is_sync_selected and self.reupload_possible) def start(self): if self.sync_selected_radio.isChecked( ) and self.reupload_checkbox.isChecked(): reply = QMessageBox.question( self, 'BookFusion Sync', 'Re-uploading book files can potentially result in previous highlights or bookmarks no longer working.\n\nPreviously uploaded files will be overwritten. Are you sure you want to re-upload?', QMessageBox.No | QMessageBox.Yes, QMessageBox.Yes) if reply != QMessageBox.Yes: return self.worker = None self.valid_book_ids = None self.book_log_map = {} self.book_progress_map = {} if self.sync_selected_radio.isChecked(): book_ids = list(self.selected_book_ids) else: book_ids = list(self.db.all_book_ids()) self.logger.info('Start sync: sync_selected={}; book_ids={}'.format( self.sync_selected_radio.isChecked(), book_ids)) self.in_progress = True self.total = len(book_ids) self.update_progress(None) self.start_btn.hide() self.cancel_btn.show() self.config_btn.setEnabled(False) self.sync_all_radio.setEnabled(False) self.sync_selected_radio.setEnabled(False) self.worker_thread = QThread(self) self.worker = CheckWorker(self.db, self.logger, book_ids) self.worker.finished.connect(self.finish_check) self.worker.finished.connect(self.worker_thread.quit) self.worker.progress.connect(self.update_progress) self.worker.limitsAvailable.connect(self.apply_limits) self.worker.resultsAvailable.connect(self.apply_results) self.worker.aborted.connect(self.abort) self.worker.moveToThread(self.worker_thread) self.worker_thread.started.connect(self.worker.start) self.worker_thread.start() def apply_limits(self, limits): self.logger.info('Limits: {}'.format(limits)) self.limits = limits def apply_results(self, books_count, valid_ids): self.logger.info('Check results: books_count={}; valid_ids={}'.format( books_count, valid_ids)) self.valid_book_ids = valid_ids self.books_count = books_count def finish_check(self): if self.valid_book_ids: is_filesize_exceeded = len(self.valid_book_ids) < self.books_count is_total_books_exceeded = self.limits[ 'total_books'] and self.books_count > self.limits['total_books'] if is_filesize_exceeded or is_total_books_exceeded: if self.limits['message']: msg_box = QMessageBox(self) msg_box.setWindowTitle('BookFusion Sync') msg_box.addButton(QMessageBox.No) msg_box.addButton(QMessageBox.Yes) msg_box.setText(self.limits['message']) msg_box.setDefaultButton(QMessageBox.Yes) reply = msg_box.exec_() if reply == QMessageBox.Yes: self.start_sync() else: self.in_progress = False self.msg.setText('Canceled.') self.finish_sync() else: self.start_sync() else: self.start_sync() else: if self.in_progress: self.in_progress = False self.msg.setText('No supported books selected.') self.finish_sync() def start_sync(self): self.log_btn.show() self.log.setRowCount(0) self.log.show() self.worker_thread = QThread(self) book_ids = self.valid_book_ids if self.limits['total_books']: book_ids = book_ids[:self.limits['total_books']] self.total = len(book_ids) self.worker = UploadManager( self.db, self.logger, book_ids, self.sync_selected_radio.isChecked() and self.reupload_checkbox.isChecked()) self.worker.finished.connect(self.finish_sync) self.worker.finished.connect(self.worker_thread.quit) self.worker.progress.connect(self.update_progress) self.worker.uploadProgress.connect(self.update_upload_progress) self.worker.started.connect(self.log_start) self.worker.skipped.connect(self.log_skip) self.worker.failed.connect(self.log_fail) self.worker.uploaded.connect(self.log_upload) self.worker.updated.connect(self.log_update) self.worker.aborted.connect(self.abort) self.worker.moveToThread(self.worker_thread) self.worker_thread.started.connect(self.worker.start) self.worker_thread.start() def finish_sync(self): if self.in_progress: self.msg.setText('Done.') self.cancel_btn.hide() self.cancel_btn.setEnabled(True) self.start_btn.show() self.config_btn.setEnabled(True) self.sync_all_radio.setEnabled(True) self.sync_selected_radio.setEnabled(len(self.selected_book_ids) > 0) def abort(self, error): self.in_progress = False self.msg.setText(error) def cancel(self): self.in_progress = False self.msg.setText('Canceled.') self.cancel_btn.setEnabled(False) self.worker.cancel() def update_progress(self, progress): if self.in_progress: if isinstance(self.worker, UploadManager): msg = 'Synchronizing...' else: msg = 'Preparing...' if progress: msg += ' {} of {}'.format(progress + 1, self.total) self.msg.setText(msg) def update_upload_progress(self, book_id, sent, total): if not book_id in self.book_progress_map: return progress = self.book_progress_map[book_id] if sent < total: progress.setValue(sent) progress.setMaximum(total) else: progress.setMaximum(0) def log_start(self, book_id): self.update_log(book_id, None) def log_fail(self, book_id, msg): self.update_log(book_id, msg) def log_skip(self, book_id): self.update_log(book_id, 'skipped') def log_upload(self, book_id): self.update_log(book_id, 'uploaded') def log_update(self, book_id): self.update_log(book_id, 'updated') def toggle_log(self, _): self.log.setVisible(not self.log.isVisible()) def update_log(self, book_id, msg): if book_id in self.book_log_map: index = self.book_log_map[book_id] else: index = self.log.rowCount() self.book_log_map[book_id] = index self.log.insertRow(index) title = self.db.get_proxy_metadata(book_id).title title_item = QTableWidgetItem(title) title_item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemNeverHasChildren) self.log.setItem(index, 0, title_item) progress = QProgressBar() progress.setMaximum(0) self.log.setCellWidget(index, 1, progress) self.book_progress_map[book_id] = progress if not msg is None: del (self.book_progress_map[book_id]) self.log.setCellWidget(index, 1, None) msg_item = QTableWidgetItem(msg) msg_item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemNeverHasChildren) self.log.setItem(index, 1, msg_item) def maybe_cancel(self): if self.worker_thread and self.worker_thread.isRunning(): reply = QMessageBox.question( self, 'BookFusion Sync', 'Are you sure you want to cancel the currently running process?', QMessageBox.No | QMessageBox.Yes, QMessageBox.Yes) if reply == QMessageBox.Yes: self.cancel() else: return False return True
def __init__(self, gui, do_user_config, selected_book_ids, is_sync_selected): QWidget.__init__(self, gui) api.build_request('/limits') self.logger = Logger( path.join(gui.current_db.library_path, 'bookfusion_sync.log')) self.logger.info( 'Open sync dialog: selected_book_ids={}; is_sync_selected={}'. format(selected_book_ids, is_sync_selected)) if len(selected_book_ids) == 0: is_sync_selected = False self.worker_thread = None self.do_user_config = do_user_config self.db = gui.current_db.new_api self.selected_book_ids = selected_book_ids self.l = QVBoxLayout() self.l.setContentsMargins(0, 0, 0, 0) self.setLayout(self.l) self.radio_layout = QVBoxLayout() self.l.addLayout(self.radio_layout) self.sync_all_radio = QRadioButton('Sync all books') self.sync_all_radio.setChecked(not is_sync_selected) self.radio_layout.addWidget(self.sync_all_radio) sync_selected_radio_label = 'Sync selected books' if len(selected_book_ids) > 0: sync_selected_radio_label = 'Sync {} selected {}'.format( len(selected_book_ids), 'book' if len(selected_book_ids) == 1 else 'books') self.sync_selected_radio = QRadioButton(sync_selected_radio_label) self.sync_selected_radio.toggled.connect(self.toggle_sync_selected) self.sync_selected_radio.setChecked(is_sync_selected) self.sync_selected_radio.setEnabled(len(selected_book_ids) > 0) self.radio_layout.addWidget(self.sync_selected_radio) self.reupload_possible = len(selected_book_ids) > 0 and len( selected_book_ids) <= 100 if self.reupload_possible: for book_id in selected_book_ids: identifiers = self.db.get_proxy_metadata(book_id).identifiers if not identifiers.get('bookfusion'): self.reupload_possible = False self.reupload_checkbox = QCheckBox('Re-upload book files', self) self.reupload_checkbox.setVisible(is_sync_selected and self.reupload_possible) self.radio_layout.addWidget(self.reupload_checkbox) self.btn_layout = QHBoxLayout() self.l.addLayout(self.btn_layout) self.config_btn = QPushButton('Configure') self.config_btn.clicked.connect(self.config) self.btn_layout.addWidget(self.config_btn) self.btn_layout.addStretch() self.start_btn = QPushButton('Start') self.start_btn.clicked.connect(self.start) self.btn_layout.addWidget(self.start_btn) self.cancel_btn = QPushButton('Cancel') self.cancel_btn.clicked.connect(self.cancel) self.cancel_btn.hide() self.btn_layout.addWidget(self.cancel_btn) self.info = QHBoxLayout() self.info.setContentsMargins(0, 0, 0, 0) self.l.addLayout(self.info) self.msg = QLabel() self.info.addWidget(self.msg) self.info.addStretch() self.log_btn = QLabel('<a href="#">Log</a>') self.log_btn.linkActivated.connect(self.toggle_log) self.log_btn.hide() self.info.addWidget(self.log_btn) self.log = QTableWidget(0, 2) self.log.setHorizontalHeaderLabels(['Book', 'Message']) self.log.horizontalHeader().setStretchLastSection(True) self.log.hide() self.l.addWidget(self.log) self.apply_config()
def __init__(self, parent): QTableWidget.__init__(self, parent) self.setSelectionBehavior(QAbstractItemView.SelectRows)
def initRewardsForm(self): self.collateralHidden = True self.rewardsForm = QGroupBox() self.rewardsForm.setTitle("Transfer Rewards") layout = QFormLayout() layout.setContentsMargins(10, 10, 10, 10) layout.setSpacing(13) layout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow) ##--- ROW 1 hBox = QHBoxLayout() self.mnSelect = QComboBox() self.mnSelect.setToolTip("Select Masternode") hBox.addWidget(self.mnSelect) label = QLabel("Total Address Balance") label.setAlignment(Qt.AlignRight | Qt.AlignVCenter) hBox.addWidget(label) self.addrAvailLine = QLabel() self.addrAvailLine.setToolTip("PIVX Address total balance") self.addrAvailLine.setText("--") hBox.addWidget(self.addrAvailLine) self.btn_toggleCollateral = QPushButton("Show Collateral") hBox.addWidget(self.btn_toggleCollateral) hBox.setStretch(0, 1) hBox.setStretch(1, 0) hBox.setStretch(2, 0) layout.addRow(QLabel("Masternode"), hBox) ## --- ROW 2: REWARDS self.rewardsList = QVBoxLayout() self.rewardsList.statusLabel = QLabel( '<b style="color:purple">Checking explorer...</b>') self.rewardsList.statusLabel.setVisible(True) self.rewardsList.addWidget(self.rewardsList.statusLabel) self.rewardsList.box = QTableWidget() self.rewardsList.box.setMinimumHeight(140) self.rewardsList.box.setMaximumHeight(140) self.rewardsList.box.setHorizontalScrollBarPolicy( Qt.ScrollBarAlwaysOff) self.rewardsList.box.setSelectionMode(QAbstractItemView.MultiSelection) self.rewardsList.box.setSelectionBehavior(QAbstractItemView.SelectRows) self.rewardsList.box.setShowGrid(True) self.rewardsList.box.setColumnCount(4) self.rewardsList.box.setRowCount(0) self.rewardsList.box.horizontalHeader().setSectionResizeMode( 2, QHeaderView.Stretch) self.rewardsList.box.verticalHeader().hide() item = QTableWidgetItem() item.setText("PIVs") item.setTextAlignment(Qt.AlignCenter) self.rewardsList.box.setHorizontalHeaderItem(0, item) item = QTableWidgetItem() item.setText("Confirmations") item.setTextAlignment(Qt.AlignCenter) self.rewardsList.box.setHorizontalHeaderItem(1, item) item = QTableWidgetItem() item.setText("TX Hash") item.setTextAlignment(Qt.AlignCenter) self.rewardsList.box.setHorizontalHeaderItem(2, item) item = QTableWidgetItem() item.setText("TX Output N") item.setTextAlignment(Qt.AlignCenter) self.rewardsList.box.setHorizontalHeaderItem(3, item) item = QTableWidgetItem() self.rewardsList.addWidget(self.rewardsList.box) layout.addRow(self.rewardsList) ##--- ROW 3 hBox2 = QHBoxLayout() self.btn_selectAllRewards = QPushButton("Select All") self.btn_selectAllRewards.setToolTip("Select all available UTXOs") hBox2.addWidget(self.btn_selectAllRewards) self.btn_deselectAllRewards = QPushButton("Deselect all") self.btn_deselectAllRewards.setToolTip("Deselect current selection") hBox2.addWidget(self.btn_deselectAllRewards) hBox2.addWidget(QLabel("Selected rewards")) self.selectedRewardsLine = QLabel() self.selectedRewardsLine.setMinimumWidth(200) self.selectedRewardsLine.setStyleSheet("color: purple") self.selectedRewardsLine.setToolTip("PIVX to move away") hBox2.addWidget(self.selectedRewardsLine) hBox2.addStretch(1) self.swiftxCheck = QCheckBox() self.swiftxCheck.setToolTip( "check for SwiftX instant transaction (flat fee rate of 0.01 PIV)") hBox2.addWidget(QLabel("Use SwiftX")) hBox2.addWidget(self.swiftxCheck) layout.addRow(hBox2) ##--- ROW 4 hBox3 = QHBoxLayout() self.destinationLine = QLineEdit() self.destinationLine.setToolTip("PIVX address to transfer rewards to") hBox3.addWidget(self.destinationLine) hBox3.addWidget(QLabel("Fee")) self.feeLine = QDoubleSpinBox() self.feeLine.setDecimals(8) self.feeLine.setPrefix("PIV ") self.feeLine.setToolTip("Insert a small fee amount") self.feeLine.setFixedWidth(150) self.feeLine.setSingleStep(0.001) hBox3.addWidget(self.feeLine) self.btn_sendRewards = QPushButton("Send") hBox3.addWidget(self.btn_sendRewards) layout.addRow(QLabel("Destination Address"), hBox3) ##--- ROW 5 hBox4 = QHBoxLayout() hBox4.addStretch(1) self.loadingLine = QLabel( "<b style='color:red'>Preparing TX.</b> Completed: ") self.loadingLinePercent = QProgressBar() self.loadingLinePercent.setMaximumWidth(200) self.loadingLinePercent.setMaximumHeight(10) self.loadingLinePercent.setRange(0, 100) hBox4.addWidget(self.loadingLine) hBox4.addWidget(self.loadingLinePercent) self.loadingLine.hide() self.loadingLinePercent.hide() layout.addRow(hBox4) #--- Set Layout self.rewardsForm.setLayout(layout) #--- ROW 5 self.btn_Cancel = QPushButton("Clear/Reload")
class ModelGroupsTable(QWidget): EditableAttrs = [ attr for attr in PlotStyles.StyleAttributes if attr in PlotStyles.StyleAttributeOptions ] ColList = 3 ColPlot = 4 ColApply = 5 AttrByCol = dict([(i + 6, attr) for i, attr in enumerate(EditableAttrs)]) def __init__(self, parent, *args): QWidget.__init__(self, parent, *args) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) lo = QVBoxLayout(self) lo.setContentsMargins(0, 0, 0, 0) lo1 = QHBoxLayout() lo.addLayout(lo1) lo1.setContentsMargins(0, 0, 0, 0) lbl = QLabel(QString("<nobr><b>Source groupings:</b></nobr>"), self) lo1.addWidget(lbl, 0) lo1.addStretch(1) # add show/hide button self._showattrbtn = QPushButton(self) self._showattrbtn.setMinimumWidth(256) lo1.addWidget(self._showattrbtn, 0) lo1.addStretch() self._showattrbtn.clicked.connect(self._togglePlotControlsVisibility) # add table self.table = QTableWidget(self) lo.addWidget(self.table) self.table.cellChanged[int, int].connect(self._valueChanged) self.table.setSelectionMode(QTableWidget.NoSelection) # setup basic columns self.table.setColumnCount(6 + len(self.EditableAttrs)) for i, label in enumerate( ("grouping", "total", "selection", "list", "plot", "style")): self.table.setHorizontalHeaderItem(i, QTableWidgetItem(label)) self.table.horizontalHeader().setSectionHidden(self.ColApply, True) # setup columns for editable grouping attributes for i, attr in self.AttrByCol.items(): self.table.setHorizontalHeaderItem( i, QTableWidgetItem(PlotStyles.StyleAttributeLabels[attr])) self.table.horizontalHeader().setSectionHidden(i, True) self.table.verticalHeader().hide() # other internal init self._attrs_shown = False self._togglePlotControlsVisibility() self.model = None self._setting_model = False self._currier = PersistentCurrier() # row of 'selected' grouping self._irow_selgroup = 0 def clear(self): self.table.setRowCount(0) self.model = None # setup mappings from the group.show_plot attribute to check state ShowAttrToCheckState = { PlotStyles.ShowNot: Qt.Unchecked, PlotStyles.ShowDefault: Qt.PartiallyChecked, PlotStyles.ShowAlways: Qt.Checked } CheckStateToShowAttr = dict([(val, key) for key, val in ShowAttrToCheckState.items()]) def _makeCheckItem(self, name, group, attr): item = QTableWidgetItem(name) if group is self.model.defgroup: item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable) item.setCheckState( Qt.Checked if getattr(group.style, attr) else Qt.Unchecked) else: item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsTristate) item.setCheckState(self.ShowAttrToCheckState[getattr( group.style, attr)]) return item def _updateModel(self, what=SkyModel.UpdateAll, origin=None): if origin is self or not what & (SkyModel.UpdateTags | SkyModel.UpdateGroupStyle): return model = self.model self._setting_model = True # to ignore cellChanged() signals (in valueChanged()) # _item_cb is a dict (with row,col keys) containing the widgets (CheckBoxes ComboBoxes) per each cell self._item_cb = {} # lists of "list" and "plot" checkboxes per each grouping (excepting the default grouping); each entry is an (row,col,item) tuple. # used as argument to self._showControls() self._list_controls = [] self._plot_controls = [] # list of selection callbacks (to which signals are connected) self._callbacks = [] # set requisite number of rows,and start filling self.table.setRowCount(len(model.groupings)) for irow, group in enumerate(model.groupings): self.table.setItem(irow, 0, QTableWidgetItem(group.name)) if group is model.selgroup: self._irow_selgroup = irow # total # source in group: skip for "current" if group is not model.curgroup: self.table.setItem(irow, 1, QTableWidgetItem(str(group.total))) # selection controls: skip for current and selection if group not in (model.curgroup, model.selgroup): btns = QWidget() lo = QHBoxLayout(btns) lo.setContentsMargins(0, 0, 0, 0) lo.setSpacing(0) # make selector buttons (depending on which group we're in) if group is model.defgroup: Buttons = (("+", lambda src, grp=group: True, "select all sources"), ("-", lambda src, grp=group: False, "unselect all sources")) else: Buttons = ( ("=", lambda src, grp=group: grp.func(src), "select only this grouping"), ("+", lambda src, grp=group: src.selected or grp.func(src), "add grouping to selection"), ("-", lambda src, grp=group: src.selected and not grp. func(src), "remove grouping from selection"), ("&&", lambda src, grp=group: src.selected and grp.func(src), "intersect selection with grouping")) lo.addStretch(1) for label, predicate, tooltip in Buttons: btn = QToolButton(btns) btn.setText(label) btn.setMinimumWidth(24) btn.setMaximumWidth(24) btn.setToolTip(tooltip) lo.addWidget(btn) # add callback btn.clicked.connect( self._currier.curry(self.selectSources, predicate)) lo.addStretch(1) self.table.setCellWidget(irow, 2, btns) # "list" checkbox (not for current and selected groupings: these are always listed) if group not in (model.curgroup, model.selgroup): item = self._makeCheckItem("", group, "show_list") self.table.setItem(irow, self.ColList, item) item.setToolTip( """<P>If checked, sources in this grouping will be listed in the source table. If un-checked, sources will be excluded from the table. If partially checked, then the default list/no list setting of "all sources" will be in effect. </P>""") # "plot" checkbox (not for the current grouping, since that's always plotted) if group is not model.curgroup: item = self._makeCheckItem("", group, "show_plot") self.table.setItem(irow, self.ColPlot, item) item.setToolTip( """<P>If checked, sources in this grouping will be included in the plot. If un-checked, sources will be excluded from the plot. If partially checked, then the default plot/no plot setting of "all sources" will be in effect. </P>""") # custom style control # for default, current and selected, this is just a text label if group is model.defgroup: item = QTableWidgetItem("default:") item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter) item.setToolTip( """<P>This is the default plot style used for all sources for which a custom grouping style is not selected.</P>""" ) self.table.setItem(irow, self.ColApply, item) elif group is model.curgroup: item = QTableWidgetItem("") item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter) item.setToolTip( """<P>This is the plot style used for the highlighted source, if any.</P>""" ) self.table.setItem(irow, self.ColApply, item) elif group is model.selgroup: item = QTableWidgetItem("") item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter) item.setToolTip( """<P>This is the plot style used for the currently selected sources.</P>""" ) self.table.setItem(irow, self.ColApply, item) # for the rest, a combobox with custom priorities else: cb = QComboBox() cb.addItems(["default"] + ["custom %d" % p for p in range(1, 10)]) index = max(0, min(group.style.apply, 9)) # dprint(0,group.name,"apply",index) cb.setCurrentIndex(index) cb.activated[int].connect( self._currier.xcurry(self._valueChanged, (irow, self.ColApply))) self.table.setCellWidget(irow, self.ColApply, cb) cb.setToolTip( """<P>This controls whether sources within this group are plotted with a customized plot style. Customized styles have numeric priority; if a source belongs to multiple groups, then the style with the lowest priority takes precedence.<P>""") # attribute comboboxes for icol, attr in self.AttrByCol.items(): # get list of options for this style attribute. If dealing with first grouping (i==0), which is # the "all sources" grouping, then remove the "default" option (which is always first in the list) options = PlotStyles.StyleAttributeOptions[attr] if irow == 0: options = options[1:] # make combobox cb = QComboBox() cb.addItems(list(map(str, options))) # the "label" option is also editable if attr == "label": cb.setEditable(True) try: index = options.index(getattr(group.style, attr)) cb.setCurrentIndex(index) except ValueError: cb.setEditText(str(getattr(group.style, attr))) slot = self._currier.xcurry(self._valueChanged, (irow, icol)) cb.activated[int].connect(slot) cb.editTextChanged['QString'].connect(slot) cb.setEnabled(group is model.defgroup or group.style.apply) self.table.setCellWidget(irow, icol, cb) label = attr if irow: cb.setToolTip( """<P>This is the %s used to plot sources in this group, when a "custom" style for the group is enabled via the style control.<P>""" % label) else: cb.setToolTip( "<P>This is the default %s used for all sources for which a custom style is not specified below.<P>" % label) self.table.resizeColumnsToContents() # re-enable processing of cellChanged() signals self._setting_model = False def setModel(self, model): self.model = model self.model.connect("updated", self._updateModel) self.model.connect("selected", self.updateModelSelection) self._updateModel(SkyModel.UpdateAll) def _valueChanged(self, row, col): """Called when a cell has been edited""" if self._setting_model: return group = self.model.groupings[row] item = self.table.item(row, col) if col == self.ColList: if group is not self.model.defgroup: # tri-state items go from unchecked to checked when user clicks them. Make them partially checked instead. if group.style.show_list == PlotStyles.ShowNot and item.checkState( ) == Qt.Checked: item.setCheckState(Qt.PartiallyChecked) group.style.show_list = self.CheckStateToShowAttr[ item.checkState()] self.model.emitChangeGroupingVisibility(group, origin=self) return elif col == self.ColPlot: if group is not self.model.defgroup: # tri-state items go from unchecked to checked by default. Make them partially checked instead. if group.style.show_plot == PlotStyles.ShowNot and item.checkState( ) == Qt.Checked: item.setCheckState(Qt.PartiallyChecked) group.style.show_plot = self.CheckStateToShowAttr[ item.checkState()] elif col == self.ColApply: group.style.apply = self.table.cellWidget(row, col).currentIndex() # enable/disable editable cells for j in list(self.AttrByCol.keys()): item1 = self.table.item(row, j) if item1: fl = item1.flags() & ~Qt.ItemIsEnabled if group.style.apply: fl |= Qt.ItemIsEnabled item1.setFlags(fl) cw = self.table.cellWidget(row, j) cw and cw.setEnabled(group.style.apply) elif col in self.AttrByCol: cb = self.table.cellWidget(row, col) txt = str(cb.currentText()) attr = self.AttrByCol[col] if txt == "default": setattr(group.style, attr, PlotStyles.DefaultValue) else: setattr(group.style, attr, PlotStyles.StyleAttributeTypes.get(attr, str)(txt)) # all other columns: return so we don't emit a signal else: return # in all cases emit a signal self.model.emitChangeGroupingStyle(group, origin=self) def selectSources(self, predicate, curry=False): """Selects sources according to predicate(src)""" busy = BusyIndicator() for src in self.model.sources: src.selected = predicate(src) self.model.emitSelection(origin=self) busy.reset_cursor() def updateModelSelection(self, nsel, origin=None): """This is called when some other widget changes the set of selected model sources""" self.table.clearSelection() if self.model: self.table.item(self._irow_selgroup, 1).setText(str(nsel)) def _togglePlotControlsVisibility(self): if self._attrs_shown: self._attrs_shown = False self.table.hideColumn(self.ColApply) for col in self.AttrByCol.keys(): self.table.hideColumn(col) self._showattrbtn.setText("Show plot styles >>") else: self._attrs_shown = True self.table.showColumn(self.ColApply) for col in self.AttrByCol.keys(): self.table.showColumn(col) self._showattrbtn.setText("<< Hide plot styles")
class HistoryQWidget(QWidget): """ Class who create the History QWidget for host """ def __init__(self, parent=None): super(HistoryQWidget, self).__init__(parent) self.setStyleSheet(settings.css_style) self.setWindowFlags(Qt.FramelessWindowHint) self.setObjectName('dialog') self.setMinimumSize(800, 670) # Fields self.history_table = QTableWidget() self.table_headers = [_('Events')] self.history_title = QLabel() self.offset = None def initialize(self): """ Initialize History QWidget """ main_layout = QVBoxLayout(self) main_layout.setContentsMargins(0, 0, 0, 0) # Title Window main_layout.addWidget(get_logo_widget(self, _('History'))) # History QWidget history_widget = QWidget() history_layout = QVBoxLayout(history_widget) # History QTableWidget self.history_table.setObjectName('history') self.history_table.verticalHeader().hide() self.history_table.verticalHeader().setDefaultSectionSize(100) self.history_table.setColumnCount(len(self.table_headers)) self.history_table.setColumnWidth(0, 600) self.history_table.setSortingEnabled(True) self.history_table.setHorizontalScrollMode(QAbstractItemView.ScrollPerItem) self.history_table.setHorizontalHeaderLabels(self.table_headers) self.history_table.setEditTriggers(QAbstractItemView.NoEditTriggers) self.history_table.horizontalHeader().setStretchLastSection(True) self.history_table.horizontalHeader().setMinimumHeight(30) history_layout.addWidget(self.history_table) main_layout.addWidget(history_widget) center_widget(self) def update_history_data(self, hostname, host_history): """ Update data of history QTableWidget :param hostname: name of the host :type hostname: str :param host_history: history of host :type host_history: History """ logger.debug('Open History for %s', hostname) self.history_table.setRowCount(len(host_history.data)) self.history_table.setHorizontalHeaderLabels( [_("The last 25 events for %s") % hostname.capitalize()] ) row = 0 for event in host_history.data: event_widget = self.get_event_widget(hostname, event) self.history_table.setCellWidget(row, 0, event_widget) row += 1 def get_event_widget(self, hostname, event): """ Return event QWidget with icon, event text and event message :param hostname: name of host attached to event :type hostname: str :param event: data of an event :type event: dict :return: widget of event :rtype: QWidget """ event_widget = QWidget() event_widget.setObjectName('history') event_widget.setToolTip(event['type']) event_layout = QGridLayout(event_widget) # Event icon icon_pixmap = self.get_icon_label(event) event_layout.addWidget(icon_pixmap, 0, 0, 2, 1) # Event type (with date) event_title = QLabel() event_title.setObjectName( History.get_history_icon_name(event['message'], event['type']) ) local_timestamp = get_local_datetime_from_date(event['_updated']) created_since = get_diff_since_last_timestamp(local_timestamp.timestamp()) event_type = self.get_event_type(event, hostname) event_type_dated = '%s (%s)' % (event_type, created_since) event_title.setText(event_type_dated) event_layout.addWidget(event_title, 0, 1, 1, 1) # Event message event_msg = QLabel() event_msg.setWordWrap(True) event_msg.setText(event['message']) event_layout.addWidget(event_msg, 1, 1, 1, 1) return event_widget @staticmethod def get_icon_label(event): """ Return QWidget with corresponding icon to item state :param event: data of an event :type event: dict :return: icon QWidget :rtype: QWidget """ icon_label = QLabel() icon = QPixmap( settings.get_image( History.get_history_icon_name(event['message'], event['type']) ) ) icon_label.setPixmap(icon) icon_label.setFixedSize(32, 32) icon_label.setScaledContents(True) return icon_label @staticmethod def get_event_type(event, hostname): """ Return event type for history :param event: event of history :type event: dict :param hostname: name of host attached to event :type hostname: str :return: the event type :rtype: str """ event_type = '' if 'service_name' in event: if event['service_name']: event_type = _('Service: %s') % event['service_name'].capitalize() if not event_type: event_type = _('Host: %s') % hostname.capitalize() return event_type def paintEvent(self, _): # pragma: no cover """Override to apply "background-color" property of QWidget""" opt = QStyleOption() opt.initFrom(self) painter = QPainter(self) self.style().drawPrimitive(QStyle.PE_Widget, opt, painter, self) def mousePressEvent(self, event): # pragma: no cover """ QWidget.mousePressEvent(QMouseEvent) """ self.offset = event.pos() def mouseMoveEvent(self, event): # pragma: no cover """ QWidget.mousePressEvent(QMouseEvent) """ try: x = event.globalX() y = event.globalY() x_w = self.offset.x() y_w = self.offset.y() self.move(x - x_w, y - y_w) except AttributeError as e: logger.warning('Move Event %s: %s', self.objectName(), str(e))
def keyPressEvent(self, event): if event.key() == Qt.Key_Delete: self.delete_pressed.emit() event.accept() return return QTableWidget.keyPressEvent(self, event)
def __init__(self, parent, all_tags): QTableWidget.__init__(self, parent) self.setSelectionBehavior(QAbstractItemView.SelectRows) self.tags_values = all_tags
class Ui(QApplication): def __init__(self): super().__init__(argv) self.w = QMainWindow() self.w.setMinimumWidth(300) self.w.setMinimumHeight(300) # self.w.setWindowTitle(tr("Отправка запросов на ВС АУГО")) self.cw = QScrollArea() # self.__create_ui() self.__showed = False self.__wgts = {} self.cb = QComboBox() self.individuals = [] self.entities = [] self.documents = [] self.doc_files = [] self.__setupUi(self.w) self.w.showMaximized() def report_error(self, msg=None): if not msg: etype, value, tb = exc_info() trace = ''.join(format_exception(etype, value, tb)) delim_len = 40 msg = ("*" * delim_len + "\n%s\n" + "*" * delim_len) % trace error(msg) mb = QMessageBox(QMessageBox.Critical, tr('Ошибка'), str(exc_info()[1])) mb.setDetailedText(msg) mb.exec() def __create_ui(self): self.l = QGridLayout() self.t = QTableWidget(0, 3) self.t.setHorizontalHeaderLabels( ('№ дела (обращения)', 'Дата приёма', 'Дата отправки в СМЭВ')) self.t.resizeColumnsToContents() self.l.addWidget(self.t, 0, 0, 1, 2) w = QWidget() hl = QHBoxLayout(w) hl.setDirection(QHBoxLayout.LeftToRight) hl.addWidget(QWidget()) ok_b = QPushButton(tr('Добавить запрос')) ok_b.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Minimum) ok_b.clicked.connect(self.__show_form) hl.addWidget(ok_b) w.setLayout(hl) self.l.addWidget(w, 1, 0, 1, 2) w = QWidget() w.setLayout(self.l) self.cw.setWidget(w) # self.cw.setLayout(self.l) # self.w.setCentralWidget(self.cw) w = QWidget() l = QVBoxLayout() l.addWidget(self.cw) w.setLayout(l) self.w.setCentralWidget(w) def __setupUi(self, mainWindow): mainWindow.setObjectName("MainWindow") self.centralwidget = QWidget(mainWindow) self.centralwidget.setObjectName("centralwidget") self.horizontalLayout = QHBoxLayout(self.centralwidget) self.horizontalLayout.setObjectName("horizontalLayout") self.scrollArea = QScrollArea(self.centralwidget) self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName("scrollArea") self.scrollAreaWidgetContents = QWidget() self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents") self.gridLayout = QGridLayout(self.scrollAreaWidgetContents) self.gridLayout.setObjectName("gridLayout") self.__show_form() self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.horizontalLayout.addWidget(self.scrollArea) mainWindow.setCentralWidget(self.centralwidget) self.menubar = QMenuBar(mainWindow) self.menubar.setObjectName("menubar") self.menu = QMenu(self.menubar) self.menu.setObjectName("menu") mainWindow.setMenuBar(self.menubar) self.statusbar = QStatusBar(mainWindow) self.statusbar.setObjectName("statusbar") mainWindow.setStatusBar(self.statusbar) self.action_1 = QAction(mainWindow) self.action_1.setObjectName("action") self.action_1.triggered.connect(self.send) self.action = QAction(mainWindow) self.action.setObjectName("action") self.action.triggered.connect(self.on_action_triggered) self.action_2 = QAction(mainWindow) self.action_2.setObjectName("action_2") self.action_3 = QAction(mainWindow) self.action_3.setObjectName("action_3") self.action_3.triggered.connect(self.get_response) self.menu.addAction(self.action) self.menubar.addAction(self.action_1) self.menubar.addAction(self.action_2) self.menubar.addAction(self.action_3) self.menubar.addAction(self.menu.menuAction()) self.__retranslateUi(mainWindow) QMetaObject.connectSlotsByName(mainWindow) @pyqtSlot(bool) def get_response(self): try: from dmsic import Integration i = Integration(self) res = i.get_response()[0] if res: QMessageBox.information(self.w, tr("Получен ответ"), str(res)) except: self.report_error() @pyqtSlot(bool) def send(self): try: from dmsic import Integration i = Integration(self) declar = {} for k, v in self.__wgts.items(): if k in ('object_address', 'AppliedDocument', 'legal_entity', 'person'): a = {} for key, val in v.items(): if val.metaObject().className() == 'QDateEdit': a[key] = datetime.strptime(val.text(), '%d.%m.%Y') else: a[key] = val.text() declar[k] = a else: if v.metaObject().className() == 'QDateEdit': declar[k] = datetime.strptime(v.text(), '%d.%m.%Y') else: declar[k] = v.text() a = declar[ 'AppliedDocument'] if 'AppliedDocument' in declar else [] for v in self.documents: d = {} for key, val in v.items(): if val.metaObject().className() == 'QDateEdit': d[key] = datetime.strptime(val.text(), '%d.%m.%Y') else: d[key] = val.text() if not self.doc_files: raise Exception('Добавте файл документа') d['file_name'] = self.doc_files[self.documents.index(v)] a.append(d) declar['AppliedDocument'] = a a = declar['person'] if 'person' in declar else [] for v in self.individuals: ind = {} for key, val in v.items(): if key in ('address', 'fact_address'): adr = {} for k, vl in val.items(): adr[k] = vl.text() ind[key] = adr else: if val.metaObject().className() == 'QDateEdit': ind[key] = datetime.strptime( val.text(), '%d.%m.%Y') else: ind[key] = val.text() a.append(ind) declar['person'] = a a = declar['legal_entity'] if 'legal_entity' in declar else [] for v in self.entities: ent = {} for key, val in v.items(): if key == 'address': adr = {} for k, vl in val.items(): adr[k] = vl.text() ent[key] = adr else: if val.metaObject().className() == 'QDateEdit': ent[key] = datetime.strptime( val.text(), '%d.%m.%Y') else: ent[key] = val.text() a.append(ent) declar['legal_entity'] = a i.send(declar) mb = QMessageBox(self.w) mb.information(self.w, tr('Готово'), tr('Запрос отправлен')) except: self.report_error() @pyqtSlot(bool) def on_action_triggered(self): a = Ui_Dialog() d = QDialog() a.setupUi(d) d.exec() def __retranslateUi(self, MainWindow): _translate = QCoreApplication.translate MainWindow.setWindowTitle( _translate("MainWindow", "Отправка запросов на ВС АУГО")) # self.pushButton.setText(_translate("MainWindow", "Добавить")) self.menu.setTitle(_translate("MainWindow", "Справка")) self.action_1.setText(_translate("MainWindow", "Отправить")) self.action_2.setText(_translate("MainWindow", "Настройка")) self.action.setText(_translate("MainWindow", "О программе")) self.action_3.setText(_translate("MainWindow", "Получить ответ")) @pyqtSlot(bool) def __show_form(self): if self.__showed: return self.gridLayout.addWidget( QLabel(tr('№ дела (обращения) <em style="color: red">*</em>'))) w = QLineEdit() self.gridLayout.addWidget(w) w.setFocus() self.__wgts['declar_number'] = w self.gridLayout.addWidget( QLabel( tr('Услуга (код или номер, или наименование)<em style="color: red">*</em>' ))) w = QLineEdit() self.gridLayout.addWidget(w) self.__wgts['service'] = w self.gridLayout.addWidget( QLabel( tr('Дата регистрации запроса <em style="color: red">*</em>'))) de = QDateEdit(QDate().currentDate()) de.setCalendarPopup(True) self.gridLayout.addWidget(de) self.__wgts['register_date'] = de self.gridLayout.addWidget( QLabel( tr('Плановый срок предоставления услуги <em style="color: red">*</em>' ))) de = QDateEdit() self.__wgts['register_date'].dateChanged.connect(de.setMinimumDate) de.setCalendarPopup(True) de.setMinimumDate(self.__wgts['register_date'].date()) self.gridLayout.addWidget(de) self.__wgts['end_date'] = de gb = QGroupBox(tr('Место нахождения объекта услуги')) gb_l = QGridLayout() self.__wgts['object_address'] = self.__add_address(gb_l) gb.setLayout(gb_l) self.gridLayout.addWidget(gb, self.gridLayout.rowCount() + 1, 0, 1, 2) doc = {} gb = QGroupBox(tr('Приложенный документ *')) gb_l = QGridLayout() gb_l.addWidget( QLabel(tr('Наименование документа <em style="color: red">*</em>'))) w = QLineEdit() w.setMaxLength(1024) gb_l.addWidget(w, 0, 1, 1, 1) doc['title'] = w gb_l.addWidget( QLabel(tr('Номер документа <em style="color: red">*</em>'))) w = QLineEdit() w.setMaxLength(50) gb_l.addWidget(w) doc['number'] = w gb_l.addWidget( QLabel(tr('Дата документа <em style="color: red">*</em>'))) w = QDateEdit() w.setCalendarPopup(True) gb_l.addWidget(w) doc['date'] = w gb_l.addWidget( QLabel( tr('Прямая ссылка на файл. Поддерживаются только пртоколы ' 'HTTP, FTP <em style="color: red">*</em>'))) w = QLineEdit() gb_l.addWidget(w) doc['url'] = w gb.setLayout(gb_l) self.gridLayout.addWidget(gb, self.gridLayout.rowCount() + 1, 0, 1, 2) self.documents.append(doc) gb = QGroupBox(tr('Заявители *')) self.dec_layout = QGridLayout() self.cb = QComboBox() self.cb.addItems(('Физическое лицо', 'Юридическое лицо/Индивидуальный предприниматель')) self.dec_layout.addWidget(self.cb) b = QPushButton(tr('Добавить')) b.clicked.connect(self.add_declarant) self.dec_layout.addWidget(b, 0, 1, 1, 1) gb.setLayout(self.dec_layout) self.gridLayout.addWidget(gb, self.gridLayout.rowCount() + 1, 0, 1, 2) b = QPushButton(tr('Добавить файл документа')) b.clicked.connect(self.__add_doc_file) self.gridLayout.addWidget(b) self.file_label = QLabel() self.gridLayout.addWidget(self.file_label) self.warn_label = QLabel(tr("Не удаляйте файл до отправки запроса")) self.warn_label.setStyleSheet('color: red') self.warn_label.setVisible(False) self.gridLayout.addWidget(self.warn_label, self.gridLayout.rowCount() + 1, 0, 1, 2) self.__showed = True @pyqtSlot(bool) def __add_doc_file(self): file_name = QFileDialog.getOpenFileName( caption=tr('Выбурите файл'), filter=tr('Файлы pdf (*.pdf);;Все файлы (*.*)'))[0] self.file_label.setText(file_name) if self.doc_files: self.doc_files = [] self.doc_files.append(file_name) self.warn_label.setVisible(True) def __add_address(self, gb_l): wgts = {} gb_l.addWidget(QLabel(tr('Почтовый индекс'))) w = QLineEdit() gb_l.addWidget(w, 0, 1, 1, 1) wgts['Postal_Code'] = w gb_l.addWidget(QLabel(tr('Регион'))) w = QLineEdit() gb_l.addWidget(w) wgts['Region'] = w gb_l.addWidget(QLabel(tr('Район'))) w = QLineEdit() gb_l.addWidget(w) wgts['District'] = w gb_l.addWidget(QLabel(tr('Муниципальное образование'))) w = QLineEdit() gb_l.addWidget(w) wgts['City'] = w gb_l.addWidget(QLabel(tr('Городской район'))) w = QLineEdit() gb_l.addWidget(w) wgts['Urban_District'] = w gb_l.addWidget(QLabel(tr('Сельсовет'))) w = QLineEdit() gb_l.addWidget(w) wgts['Soviet_Village'] = w gb_l.addWidget( QLabel(tr('Населенный пункт <em style="color: red">*</em>'))) w = QLineEdit() gb_l.addWidget(w) wgts['Locality'] = w cb = QComboBox() cb.addItems(('Вариант 1', 'Вариант 2')) gb_l.addWidget(cb) st = QStackedWidget() p1 = QWidget() l = QGridLayout() l.setSpacing(3) l.addWidget(QLabel(tr('Улица <em style="color: red">*</em>'))) w = QLineEdit() l.addWidget(w, 0, 1, 1, 1) wgts["Street"] = w l.addWidget(QLabel(tr('Дом <em style="color: red">*</em>'))) w = QLineEdit() l.addWidget(w) wgts["House"] = w p1.setLayout(l) st.addWidget(p1) p2 = QWidget() l = QGridLayout() l.setSpacing(3) l.addWidget(QLabel(tr('Ориентир'))) w = QLineEdit() l.addWidget(w, 0, 1, 1, 1) wgts["Reference_point"] = w p2.setLayout(l) st.addWidget(p2) gb_l.addWidget(st, 9, 0, 1, 2) cb.activated.connect(st.setCurrentIndex) gb_l.addWidget(QLabel(tr('Корпус'))) w = QLineEdit() gb_l.addWidget(w) wgts['Housing'] = w gb_l.addWidget(QLabel(tr('Строение'))) w = QLineEdit() gb_l.addWidget(w) wgts['Building'] = w gb_l.addWidget(QLabel(tr('Квартира'))) w = QLineEdit() gb_l.addWidget(w) wgts['Apartment'] = w return wgts @pyqtSlot(bool) def add_declarant(self, var=True, gl=None): if not gl: gl = self.dec_layout dc = {} gb_l = QGridLayout() if self.cb.currentIndex() == 0 or gl != self.dec_layout: # Add Individual gb = QGroupBox(tr('Физическое лицо *')) gb_l.addWidget(QLabel(tr('Фамилия <em style="color: red">*</em>'))) w = QLineEdit() gb_l.addWidget(w, 0, 1, 1, 1) dc['surname'] = w gb_l.addWidget(QLabel(tr('Имя <em style="color: red">*</em>'))) w = QLineEdit() gb_l.addWidget(w) dc['first_name'] = w gb_l.addWidget(QLabel(tr('Отчество'))) w = QLineEdit() gb_l.addWidget(w) dc['patronymic'] = w adr = QGroupBox(tr('Адрес регистрации *')) adr_l = QGridLayout() dc['address'] = self.__add_address(adr_l) adr.setLayout(adr_l) gb_l.addWidget(adr, gb_l.rowCount() + 1, 0, 1, 2) gb.setLayout(gb_l) gl.addWidget(gb, gl.rowCount() + 1, 0, 1, 2) self.individuals.append(dc) else: # Add LegalEntity gb = QGroupBox( tr('Юридическое лицо/Индивидуальный предприниматель *')) gb_l.addWidget( QLabel( tr('Краткое наименование ЮЛ <em style="color: red">*</em>') )) w = QLineEdit() gb_l.addWidget(w, 0, 1, 1, 1) dc['name'] = w adr = QGroupBox(tr('Юридический адрес *')) adr_l = QGridLayout() dc['address'] = self.__add_address(adr_l) adr.setLayout(adr_l) gb_l.addWidget(adr, gb_l.rowCount() + 1, 0, 1, 2) gb.setLayout(gb_l) gl.addWidget(gb, gl.rowCount() + 1, 0, 1, 2) self.entities.append(dc)
class TableTab(TraceDocks): ## The constructor # initialize the super-class, assign a name and first configItems def __init__(self,parent): super(TableTab, self).__init__(parent,'TableTab') self.tabName = 'TableTab' self.parent = parent self.logger.logEvent('Creating Tab now: '+ self.tabName) # Set a couple of default-values, in case the configParser does not work self.snifferConfig.configAutoClearCheck = 1 self.snifferConfig.configFilterState = 'Local' self.snifferConfig.configFilterList = self.snifferFilter.filteredIdList # By parsing the config now, we assure that we re-load everything # the way we left it self.snifferConfig.parseConfigFromFile() self.lastSearchedText = 'nullthiswillneverbefound' self.lastMatch = 'purge' self.lastIndex = 0 ## Create the visible UI def setTableTabLayout(self): # Create Table Tab --------------------### # Create Layouts self.Vlayout = QVBoxLayout() self.H1layout = QHBoxLayout() self.H11layout = QHBoxLayout() self.H12layout = QHBoxLayout() self.H21layout = QHBoxLayout() self.V11layout = QVBoxLayout() self.V21layout = QVBoxLayout() # Create Widgets for H1layout # First buttons self.clearTableButt = QPushButton('Clear Table') self.clearTableButt.clicked.connect(self.clearTable) self.autoClearCheck = QCheckBox('Auto Clear') self.autoClearCheck.stateChanged.connect(self.checkAutoClearChanged) self.searchInputField = QLineEdit() self.searchInputField.setPlaceholderText('Enter search term, then click search') self.searchButt = QPushButton('Search Table') self.searchButt.clicked.connect(lambda: self.searchInTable(self.searchInputField.text(),2)) self.showSummaryButt = QPushButton('Show Summary') self.showSummaryButt.clicked.connect(self.showSummary) self.filterGroup = QButtonGroup() self.localFilterRadio = QRadioButton('Local',self) self.globalFilterRadio = QRadioButton('Global', self) self.configureFilterButt = QPushButton('Configure Filter') self.configureFilterButt.clicked.connect(self.configureFilter) self.localFilterRadio.clicked.connect(self.localRadioSelected) self.globalFilterRadio.clicked.connect(self.globalRadioSelected) self.H21layout.addWidget(self.localFilterRadio) self.H21layout.addWidget(self.globalFilterRadio) self.H21layout.addWidget(self.showSummaryButt) self.V21layout.addLayout(self.H21layout) self.V21layout.addWidget(self.configureFilterButt) # Add Widgets to H11layout self.H11layout.addWidget(self.clearTableButt) self.H11layout.addWidget(self.autoClearCheck) # Add Widgets to H12layout self.H12layout.addWidget(self.searchInputField) self.H12layout.addWidget(self.searchButt) self.H12layout.addStretch() self.V11layout.addLayout(self.H11layout) self.V11layout.addLayout(self.H12layout) self.H1layout.addLayout(self.V11layout) self.H1layout.addLayout(self.V21layout) self.syncUiToConfig() #------------------------------------ # Create Table self.detailTableIndex = 0 self.detailTable = QTableWidget() self.detailTableItem = QTableWidgetItem() self.detailTable.setRowCount(0) self.detailTable.setColumnCount(6) self.detailTable.setHorizontalHeaderLabels('packID;Tick;Timer;Type;Message;Length'.split(';')) self.detailTable.resizeColumnsToContents() self.detailTableHeader = self.detailTable.horizontalHeader() self.detailTableHeader.setSectionResizeMode(0, QHeaderView.ResizeToContents) self.detailTableHeader.setSectionResizeMode(1, QHeaderView.ResizeToContents) self.detailTableHeader.setSectionResizeMode(2, QHeaderView.ResizeToContents) self.detailTableHeader.setSectionResizeMode(3, QHeaderView.ResizeToContents) self.detailTableHeader.setSectionResizeMode(4, QHeaderView.Stretch) self.detailTableHeader.setSectionResizeMode(5, QHeaderView.ResizeToContents) #------------------------------------ self.Vlayout.addLayout(self.H1layout) self.Vlayout.addWidget(self.detailTable) self.dockContents.setLayout(self.Vlayout) ## Fill the main table with the entries from the given list # @param fillTableList the list which is to be parsed into the table def fillTable(self,fillTableList): print('Filling Table with all items in PayloadList') self.detailTable.scrollToTop() # Scrolls to the top of the table self.configAutoClearCheck = True if self.configAutoClearCheck == True: self.detailTable.setRowCount(0) self.detailTableIndex = 0 Globals.dockDict['dockStart'].progressShotBar.setMaximum(len(Globals.payloadList)) for self.tablePayload in fillTableList: self.detailTable.insertRow(self.detailTableIndex) self.detailTable.setItem(self.detailTableIndex,0,QTableWidgetItem(str(self.tablePayload.payloadHead.packetID))) self.detailTable.setItem(self.detailTableIndex,1,QTableWidgetItem(str(self.tablePayload.payloadHead.tickCountHigh << 8 | self.tablePayload.payloadHead.tickCountLow))) self.detailTable.setItem(self.detailTableIndex,2,QTableWidgetItem(str(self.tablePayload.payloadHead.timerByteHigh << 8 | self.tablePayload.payloadHead.timerByteLow))) self.detailTable.setItem(self.detailTableIndex,3,QTableWidgetItem(Globals.tspDict[self.tablePayload.payloadHead.informationID][0])) testPayload = self.tablePayload.toDict() # This a little messy: We check whether an objectDict is available, and if it is # we check for the different DataTypes there might be, since the message section is unified. # Basically, we need to handle all the different cases there can be, payload0-payload3 and the actual objectType if Globals.objectDict: if getDataType(self.tablePayload) == 1: if getObjectType(self.tablePayload) == 5: try: self.detailTable.setItem(self.detailTableIndex,4,QTableWidgetItem(str(self.tablePayload.data1)+': '+Globals.objectDict['TASK'][str(self.tablePayload.data1)])) except: self.detailTable.setItem(self.detailTableIndex,4,QTableWidgetItem('FAILED WITH KEYERROR - see printOutput')) print('KEYERROR DETAILS:') print(testPayload) elif getDataType(self.tablePayload) == 2: try: self.detailTable.setItem(self.detailTableIndex,4,QTableWidgetItem(str(self.tablePayload.data1)+': '+Globals.objectDict[Globals.objectTypeDict[self.tablePayload.data1]][str(self.tablePayload.data2)])) except: self.detailTable.setItem(self.detailTableIndex,4,QTableWidgetItem('FAILED WITH KEYERROR - see printOutput')) print('KEYERROR DETAILS:') print(testPayload) # If the objectDict does not exist, we can just dump the raw information into the message-section -> no lookup will be happening # and it is up to the user to interpret the data else: if getDataType(self.tablePayload) == 1: self.detailTable.setItem(self.detailTableIndex,4,QTableWidgetItem(str(self.tablePayload.data1))) elif getDataType(self.tablePayload) == 2: self.detailTable.setItem(self.detailTableIndex,4,QTableWidgetItem(str(self.tablePayload.data1)+';'+str(self.tablePayload.data2))) elif getDataType(self.tablePayload) == 3: self.detailTable.setItem(self.detailTableIndex,4,QTableWidgetItem(str(self.tablePayload.data1)+';'+str(self.tablePayload.data2)+';'+str(self.tablePayload.data3))) self.detailTable.setItem(self.detailTableIndex,5,QTableWidgetItem('payload'+str(getDataType(self.tablePayload)))) self.detailTableIndex+=1 Globals.dockDict['dockStart'].progressShotBar.setValue(self.detailTableIndex) Globals.dockDict['dockStart'].progressShotBar.setValue(len(Globals.payloadList)) Globals.dockDict['dockStart'].displayStatusMessage('Table filled completely, check the tab') self.lastSearchedText = 'thisisAWorkAround' # No idea why this is there... # --- DOCK-SPECIFIC UI FUNCTIONS --- # # -----------------------------------# ## Disable all UI-buttons belonging to the tab. This is implementation specific def disableButtons(self): self.clearTableButt.setEnabled(False) self.autoClearCheck.setEnabled(False) print('Disable TabTable Buttons') ## CB: clearTableButton // Clear the main table def clearTable(self): self.logger.logEvent('clear Table clicked') self.detailTable.setRowCount(0) self.detailTableIndex = 0 ## CB: autoClearCheckbox // set the configAutoClearCheck state according to the checkbox def checkAutoClearChanged(self): self.snifferConfig.configAutoClearCheck ^= 1 self.logger.logEvent('changed Auto Clear Checkbox to - '+ str(self.snifferConfig.configAutoClearCheck)) ## CB: localRadioButt // set the configFilterState to 'Local' def localRadioSelected(self): self.snifferConfig.configFilterState = 'Local' self.logger.logEvent('changed Filter Radio to - '+ str(self.snifferConfig.configFilterState)) ## CB: globalRadioButt // set the configFilterState to 'Global' def globalRadioSelected(self): self.snifferConfig.configFilterState = 'Global' self.logger.logEvent('changed Filter Radio to - '+ str(self.snifferConfig.configFilterState)) ## CB: Show Stats // opens the Stat-Dialog to show misc. information about the measurement def showSummary(self): self.snifferStats.show() self.snifferStats.showStats() ## Searches the table for a string and scrolls to the found item. # @param textToSearch the string that needs to be found in the table # @param column the column where the search needs to take place def searchInTable(self, textToSearch, column): if textToSearch not in Globals.IDList: QMessageBox.about(self,'Not Found','SearchText not Found!') return if self.lastSearchedText == textToSearch: self.detailTable.setCurrentItem(self.lastFound[self.lastIndex]) self.detailTable.scrollToItem(self.lastFound[self.lastIndex]) self.lastIndex = self.lastIndex + 1 if self.lastIndex == len(self.lastFound): self.lastIndex = 0 else: foundItems = self.detailTable.findItems(textToSearch, Qt.MatchExactly) self.lastSearchedText = textToSearch if len(foundItems) != 0: self.lastFound = foundItems self.lastIndex = 1 self.detailTable.setCurrentItem(foundItems[0]) self.detailTable.scrollToItem(self.lastFound[self.lastIndex]) # --- MANDATORY UI FUNCTIONS --- # # -------------------------------# ## Read out all components of snifferConfig and set the UI elements according to # the saved values. def syncUiToConfig(self): self.autoClearCheck.setChecked(self.snifferConfig.configAutoClearCheck) if self.snifferConfig.configFilterState == 'Local': self.localFilterRadio.click() elif self.snifferConfig.configFilterState == 'Global': self.globalFilterRadio.click() else: print('Error, neither local nor global in config') ## Open the correct filter based on the radioButton. If the Global-filter is checked # we assign its calledby variable in order to execute the right callback after the filter is saved. def configureFilter(self): if self.localFilterRadio.isChecked(): self.snifferFilter.show() elif self.globalFilterRadio.isChecked(): Globals.globalFilter.show() Globals.globalFilter.calledBy = 'dockTable' else: print('neither radios checked. Error!') ## CB: // Updates the UI-contents with after filtering has taken place. # This function should not be called by the tab itself, but by the filter # @param filteredIDs the IDs that are to be kept in the payloadList (obsolete) # @param filteredPayloads the new payloadList, which only contains the payloads filtered by the SnifferFilter def filterUpdated(self, filteredIDs, filteredPayloads): print('we arrive from SnifferFilter') self.clearTable() self.fillTable(filteredPayloads)
class Game(QWidget): def __init__(self): super().__init__() self._flag_1 = False self.media = QtCore.QUrl.fromLocalFile("MP3/music.mp3") content = QtMultimedia.QMediaContent(self.media) self.player = QtMultimedia.QMediaPlayer() self.player.setMedia(content) self.player.setVolume(50) self.initUI() def initUI(self): self.file_number = 2 self._score = 0 self.setMouseTracking(True) self.resize(500, 500) self.center() self.setWindowTitle('Игра') self.main_pic = QLabel(self) self.main_pic.setPixmap( QPixmap(resource_path("PIC/running_rabbit.jpg"))) self.main_pic.resize(500, 500) self.button_start_game = QPushButton("НАЧАТЬ ИГРУ", self) self.button_start_game.resize(140, 50) self.button_start_game.move(70, 300) self.button_start_game.clicked.connect(self.start_game) self.button_edit_map = QPushButton("СОЗДАТЬ КАРТУ", self) self.button_edit_map.resize(140, 50) self.button_edit_map.move(70, 360) self.button_edit_map.clicked.connect(self.edit_map_menu) self.button_exit = QPushButton("ЗАКОНЧИТЬ СЕАНС", self) self.button_exit.resize(140, 50) self.button_exit.move(70, 420) self.button_exit.clicked.connect(self.exit) self.timer_game = QTimer() self.timer_game.timeout.connect(self.updateValues) self.timer_game.start(200) self.setFocusPolicy(Qt.StrongFocus) self.lable_score = QLabel(self) self.lable_score.resize(200, 35) self.lable_score.setFont( QFont("RetroComputer[RUS by Daymarius]", 26, QFont.Bold)) self.lable_score.setVisible(False) self.button_menu = QPushButton("НАЗАД", self) self.button_menu.resize(120, 40) self.button_menu.clicked.connect(self.show_menu) self.button_menu.setVisible(False) self.lable_name = QLabel("ВВЕДИТЕ ВАШЕ ИМЯ:", self) self.lable_name.sizeHint() self.lable_name.setFont( QFont("RetroComputer[RUS by Daymarius]", 10, QFont.Bold)) self.lable_name.move(230, 300) self.input_name = QLineEdit("Без имени", self) self.input_name.resize(200, 20) self.input_name.move(230, 325) self.table_score = QTableWidget(self) self.table_score.resize(200, 120) self.table_score.move(230, 350) def bd_score(self): con = sqlite3.connect(resource_path("DB/score.db")) # Создание курсора cur = con.cursor() # Выполнение запроса и получение всех результатов result = cur.execute( "SELECT * FROM main ORDER BY score DESC;").fetchmany(5) cur.execute("DROP TABLE main") cur.execute("CREATE TABLE main (name STRING, score INTEGER)") for item in result: cur.execute("INSERT INTO main VALUES(?, ?)", (item[0], item[1])) con.commit() # Вывод результатов на экран if result != []: self.table_score.setColumnCount(len(result[0])) self.table_score.setRowCount(0) for i, row in enumerate(result): self.table_score.setRowCount(self.table_score.rowCount() + 1) for j, elem in enumerate(row): item = QTableWidgetItem(str(elem)) self.table_score.setItem(i, j, item) item.setFlags(QtCore.Qt.ItemIsEnabled) self.table_score.setHorizontalHeaderItem( 0, QTableWidgetItem("Имя игрока")) self.table_score.setHorizontalHeaderItem(1, QTableWidgetItem("Счет")) self.table_score.setColumnWidth(0, 127) self.table_score.setColumnWidth(1, 20) con.close() def append_bd_score_and_name(self): con = sqlite3.connect("DB/score.db") # Создание курсора cur = con.cursor() cur.execute("INSERT INTO main VALUES(?, ?)", (self.input_name.text(), self.get_score())) con.commit() self.bd_score() con.close() def get_score(self): return self._score def set_score(self, score): self._score = score def keyPressEvent(self, event): if event.key() == Qt.Key_Right: self.hero.go_right() elif event.key() == Qt.Key_Left: self.hero.go_left() elif event.key() == Qt.Key_Up: self.hero.go_up() elif event.key() == Qt.Key_Down: self.hero.go_down() elif event.key() == Qt.Key_Space: self.hero.go_dig() def keyReleaseEvent(self, QKeyEvent): if self._flag_1 and not QKeyEvent.isAutoRepeat(): self.hero.stop() def edit_map_menu(self): game.setVisible(False) edit_map.create_map() edit_map.show() def exit(self): sys.exit(app.exec()) def center(self): qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) def reload_game(self): score = self.get_score() lifes = self.hero.get_lifes() self.start_game() self.set_score(score) self.hero.set_lifes(lifes) def start_game(self): self.player.play() self.set_score(0) self.map = Map(resource_path("MAP/" + str(self.file_number) + ".map")) for enemy in self.enemies: enemy.create_labirint() self.button_menu.setVisible(True) self.button_menu.setFocusPolicy(False) self.lable_score.setVisible(True) self.lable_score.move(0, 0) self.button_menu.move(self.map.get_col() * 40 - 120, 0) self.lable_score.setText("00000") sp_0_1 = [] for j in range(self.map.get_row()): for i in range(self.map.get_col()): if type(self.map.get_elem_xy(i, j)) == Empty and ( self.map.get_row() - 1 == j or type(self.map.get_elem_xy( i, j + 1)) in [Stairs, Brick]): sp_0_1.append((i, j)) zerro = Zerro() one = One() for i in range(int(round(len(sp_0_1) * 0.2))): t = randrange(0, len(sp_0_1)) x, y = sp_0_1[t] self.map.set_elem_xy(x, y, choice([zerro, one])) del sp_0_1[t] self.hide_menu() def show_menu(self): self.append_bd_score_and_name() game.player.pause() self.hero.timer.stop() for enemy in self.enemies: enemy.timer.stop() self.timer_game.stop() self.main_pic.show() self.table_score.show() self.input_name.show() self.lable_name.show() self.button_menu.setVisible(False) self.lable_score.setVisible(False) self.button_edit_map.setVisible(True) self.button_exit.setVisible(True) self.button_start_game.setVisible(True) self.resize(500, 500) self.center() self._flag_1 = False def hide_menu(self): game.player.play() self.hero.timer.start(200) for enemy in self.enemies: enemy.timer.start(200) game.timer_game.start(200) self.main_pic.hide() self.table_score.hide() self.input_name.hide() self.lable_name.hide() self.button_menu.setVisible(True) self.lable_score.setVisible(True) self.button_edit_map.setVisible(False) self.button_exit.setVisible(False) self.button_start_game.setVisible(False) self.resize(self.map.get_col() * 40, self.map.get_row() * 40 + 40) self.center() self._flag_1 = True def paintEvent(self, event): qp = QPainter() qp.begin(self) if self._flag_1: for i in range(self.map.get_col()): for j in range(self.map.get_row()): qp.drawPixmap( i * 40, j * 40 + 40, self.map.get_elem_xy( i, j).get_pic()) # рисуем картинками из elem_map qp.drawPixmap(self.hero.get_x() * 40, self.hero.get_y() * 40 + 40, self.hero.get_pic()) for enemy in self.enemies: qp.drawPixmap(enemy.get_x() * 40, enemy.get_y() * 40 + 40, enemy.get_pic()) for i in range(game.hero.get_lifes()): qp.drawPixmap(280 + i * 40, 0, self.hero._pic[self.hero._STOP][0]) txt = "00000" + str(self._score) self.lable_score.setText(txt[len(txt) - 5:len(txt)]) qp.end() def updateValues(self): self.update() def you_lose(self): self.player.pause() self.hero.timer.stop() for enemy in self.enemies: enemy.timer.stop() self.timer_game.stop() if self.hero.get_lifes() > 1: game.player.pause() buttonReply = QMessageBox.question( self, 'ВЫ ПРОИГРАЛИ', "Продолжить игру?", QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if buttonReply == QMessageBox.Yes: self.hero.set_lifes(self.hero.get_lifes() - 1) self.reload_game() self.timer_game.start(200) else: self.set_score(0) self.show_menu() else: game.player.pause() buttonReply = QMessageBox.information(self, 'ИГРА ОКОНЧЕНА', "Вы проиграли.") self.append_bd_score_and_name() self.show_menu()
def initRewardsForm(self): self.rewardsForm = QGroupBox() self.rewardsForm.setTitle("Transfer UTXOs") layout = QFormLayout() layout.setContentsMargins(10, 10, 10, 10) layout.setSpacing(13) layout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow) ##--- ROW 1 line1 = QHBoxLayout() line1.addWidget(QLabel("Account HW")) self.edt_hwAccount = QSpinBox() self.edt_hwAccount.setMaximum(9999) self.edt_hwAccount.setFixedWidth(50) self.edt_hwAccount.setToolTip( "account number of the hardware wallet.\nIf unsure put 0") self.edt_hwAccount.setValue(0) line1.addWidget(self.edt_hwAccount) line1.addWidget(QLabel("spath from")) self.edt_spathFrom = QSpinBox() self.edt_spathFrom.setMaximum(9999) self.edt_spathFrom.setFixedWidth(50) self.edt_spathFrom.setToolTip("starting address n.") self.edt_spathFrom.setValue(0) line1.addWidget(self.edt_spathFrom) line1.addWidget(QLabel("spath to")) self.edt_spathTo = QSpinBox() self.edt_spathTo.setMaximum(9999) self.edt_spathTo.setFixedWidth(50) self.edt_spathTo.setToolTip("ending address n.") self.edt_spathTo.setValue(10) line1.addWidget(self.edt_spathTo) line1.addWidget(QLabel("internal/external")) self.edt_internalExternal = QSpinBox() self.edt_internalExternal.setFixedWidth(50) self.edt_internalExternal.setToolTip("ending address n.") self.edt_internalExternal.setValue(0) self.edt_internalExternal.setMaximum(1) line1.addWidget(self.edt_internalExternal) line1.addStretch(1) self.btn_reload = QPushButton("Scan Ledger device") self.btn_reload.setToolTip("Reload data from ledger device") line1.addWidget(self.btn_reload) layout.addRow(line1) hBox = QHBoxLayout() self.addySelect = QComboBox() self.addySelect.setToolTip("Select Address") hBox.addWidget(self.addySelect) layout.addRow(hBox) ## --- ROW 2: UTXOs self.rewardsList = QVBoxLayout() self.rewardsList.statusLabel = QLabel( '<b style="color:red">Reload Rewards</b>') self.rewardsList.statusLabel.setVisible(True) self.rewardsList.addWidget(self.rewardsList.statusLabel) self.rewardsList.box = QTableWidget() self.rewardsList.box.setMinimumHeight(200) #self.rewardsList.box.setMaximumHeight(140) self.rewardsList.box.setHorizontalScrollBarPolicy( Qt.ScrollBarAlwaysOff) self.rewardsList.box.setSelectionMode(QAbstractItemView.MultiSelection) self.rewardsList.box.setSelectionBehavior(QAbstractItemView.SelectRows) self.rewardsList.box.setShowGrid(True) self.rewardsList.box.setColumnCount(4) self.rewardsList.box.setRowCount(0) self.rewardsList.box.horizontalHeader().setSectionResizeMode( 2, QHeaderView.Stretch) self.rewardsList.box.verticalHeader().hide() item = QTableWidgetItem() item.setText("PIVs") item.setTextAlignment(Qt.AlignCenter) self.rewardsList.box.setHorizontalHeaderItem(0, item) item = QTableWidgetItem() item.setText("Confirmations") item.setTextAlignment(Qt.AlignCenter) self.rewardsList.box.setHorizontalHeaderItem(1, item) item = QTableWidgetItem() item.setText("TX Hash") item.setTextAlignment(Qt.AlignCenter) self.rewardsList.box.setHorizontalHeaderItem(2, item) item = QTableWidgetItem() item.setText("TX Output N") item.setTextAlignment(Qt.AlignCenter) self.rewardsList.box.setHorizontalHeaderItem(3, item) item = QTableWidgetItem() self.rewardsList.addWidget(self.rewardsList.box) layout.addRow(self.rewardsList) ##--- ROW 3 hBox2 = QHBoxLayout() self.btn_selectAllRewards = QPushButton("Select All") self.btn_selectAllRewards.setToolTip("Select all available UTXOs") hBox2.addWidget(self.btn_selectAllRewards) self.btn_deselectAllRewards = QPushButton("Deselect All") self.btn_deselectAllRewards.setToolTip("Deselect current selection") hBox2.addWidget(self.btn_deselectAllRewards) hBox2.addWidget(QLabel("Selected UTXOs")) self.selectedRewardsLine = QLabel() self.selectedRewardsLine.setMinimumWidth(200) self.selectedRewardsLine.setStyleSheet("color: purple") self.selectedRewardsLine.setToolTip("PIVX to move away") hBox2.addWidget(self.selectedRewardsLine) hBox2.addStretch(1) self.swiftxCheck = QCheckBox() self.swiftxCheck.setToolTip( "check for SwiftX instant transaction (flat fee rate of 0.01 PIV)") hBox2.addWidget(QLabel("Use SwiftX")) hBox2.addWidget(self.swiftxCheck) layout.addRow(hBox2) ##--- ROW 4 hBox3 = QHBoxLayout() self.destinationLine = QLineEdit() self.destinationLine.setToolTip("PIVX address to send PIV to") hBox3.addWidget(self.destinationLine) hBox3.addWidget(QLabel("Fee")) self.feeLine = QDoubleSpinBox() self.feeLine.setDecimals(8) self.feeLine.setPrefix("PIV ") self.feeLine.setToolTip("Insert a small fee amount") self.feeLine.setFixedWidth(150) self.feeLine.setSingleStep(0.001) hBox3.addWidget(self.feeLine) self.btn_sendRewards = QPushButton("Send") hBox3.addWidget(self.btn_sendRewards) layout.addRow(QLabel("Destination Address"), hBox3) hBox4 = QHBoxLayout() hBox4.addStretch(1) self.loadingLine = QLabel( "<b style='color:red'>Preparing TX.</b> Completed: ") self.loadingLinePercent = QProgressBar() self.loadingLinePercent.setMaximumWidth(200) self.loadingLinePercent.setMaximumHeight(10) self.loadingLinePercent.setRange(0, 100) hBox4.addWidget(self.loadingLine) hBox4.addWidget(self.loadingLinePercent) self.loadingLine.hide() self.loadingLinePercent.hide() layout.addRow(hBox4) #--- Set Layout self.rewardsForm.setLayout(layout) #--- ROW 5 self.btn_Cancel = QPushButton("Clear")
def setTableTabLayout(self): # Create Table Tab --------------------### # Create Layouts self.Vlayout = QVBoxLayout() self.H1layout = QHBoxLayout() self.H11layout = QHBoxLayout() self.H12layout = QHBoxLayout() self.H21layout = QHBoxLayout() self.V11layout = QVBoxLayout() self.V21layout = QVBoxLayout() # Create Widgets for H1layout # First buttons self.clearTableButt = QPushButton('Clear Table') self.clearTableButt.clicked.connect(self.clearTable) self.autoClearCheck = QCheckBox('Auto Clear') self.autoClearCheck.stateChanged.connect(self.checkAutoClearChanged) self.searchInputField = QLineEdit() self.searchInputField.setPlaceholderText('Enter search term, then click search') self.searchButt = QPushButton('Search Table') self.searchButt.clicked.connect(lambda: self.searchInTable(self.searchInputField.text(),2)) self.showSummaryButt = QPushButton('Show Summary') self.showSummaryButt.clicked.connect(self.showSummary) self.filterGroup = QButtonGroup() self.localFilterRadio = QRadioButton('Local',self) self.globalFilterRadio = QRadioButton('Global', self) self.configureFilterButt = QPushButton('Configure Filter') self.configureFilterButt.clicked.connect(self.configureFilter) self.localFilterRadio.clicked.connect(self.localRadioSelected) self.globalFilterRadio.clicked.connect(self.globalRadioSelected) self.H21layout.addWidget(self.localFilterRadio) self.H21layout.addWidget(self.globalFilterRadio) self.H21layout.addWidget(self.showSummaryButt) self.V21layout.addLayout(self.H21layout) self.V21layout.addWidget(self.configureFilterButt) # Add Widgets to H11layout self.H11layout.addWidget(self.clearTableButt) self.H11layout.addWidget(self.autoClearCheck) # Add Widgets to H12layout self.H12layout.addWidget(self.searchInputField) self.H12layout.addWidget(self.searchButt) self.H12layout.addStretch() self.V11layout.addLayout(self.H11layout) self.V11layout.addLayout(self.H12layout) self.H1layout.addLayout(self.V11layout) self.H1layout.addLayout(self.V21layout) self.syncUiToConfig() #------------------------------------ # Create Table self.detailTableIndex = 0 self.detailTable = QTableWidget() self.detailTableItem = QTableWidgetItem() self.detailTable.setRowCount(0) self.detailTable.setColumnCount(6) self.detailTable.setHorizontalHeaderLabels('packID;Tick;Timer;Type;Message;Length'.split(';')) self.detailTable.resizeColumnsToContents() self.detailTableHeader = self.detailTable.horizontalHeader() self.detailTableHeader.setSectionResizeMode(0, QHeaderView.ResizeToContents) self.detailTableHeader.setSectionResizeMode(1, QHeaderView.ResizeToContents) self.detailTableHeader.setSectionResizeMode(2, QHeaderView.ResizeToContents) self.detailTableHeader.setSectionResizeMode(3, QHeaderView.ResizeToContents) self.detailTableHeader.setSectionResizeMode(4, QHeaderView.Stretch) self.detailTableHeader.setSectionResizeMode(5, QHeaderView.ResizeToContents) #------------------------------------ self.Vlayout.addLayout(self.H1layout) self.Vlayout.addWidget(self.detailTable) self.dockContents.setLayout(self.Vlayout)