def update_visuals(self): """ Moves text editor's cursor to match currently highlighted `find` word, performs `find` highlighting, indicates index on dialog. """ # x of y words indicator idx = self.found_cursors.index(self.current_cursor) + 1 self.found_info_label.setText("{} of {} matches".format( idx, len(self.found_cursors))) self.found_info_label.repaint() # move along text editor's viewport next_pte_cursor = QTextCursor(self.current_cursor) next_pte_cursor.clearSelection() self.plain_text_edit.setTextCursor(next_pte_cursor) #highlighting normal_color = QColor(Qt.yellow).lighter() current_color = QColor(Qt.magenta).lighter() extra_selections: List[QTextEdit.ExtraSelection] = [] for cur in self.found_cursors: selection = QTextEdit.ExtraSelection() selection.cursor = cur if cur == self.current_cursor: selection.format.setBackground(current_color) else: selection.format.setBackground(normal_color) extra_selections.append(selection) self.plain_text_edit.setExtraSelections(extra_selections)
def goto_line(self, line_nb): """ Sets the cursor position at the end of the specified line :param line_nb: line number to go to """ cursor = QTextCursor(self.document().findBlockByLineNumber(line_nb - 1)) # Line numbers starts at 0 cursor.movePosition(QTextCursor.EndOfLine) self.setTextCursor(cursor)
def start_editing(self): """Starts editing.""" self.setTextInteractionFlags(Qt.TextEditorInteraction) self.setFocus() cursor = QTextCursor(self._cursor) cursor.select(QTextCursor.Document) self.setTextCursor(cursor) self._text_backup = self.toPlainText()
def set_line_number(self, lineno): if self._current_lineno == lineno: return self._current_lineno = lineno doc = self.text_edit.document() # FIXME: complexity in O(number of lines)? block = doc.findBlockByLineNumber(lineno - 1) cursor = QTextCursor(block) cursor.select(QTextCursor.BlockUnderCursor) # FIXME: complexity in O(number of lines)? self.text_edit.setTextCursor(cursor)
def scrollToLine(self, lineIndex): try: index = lineIndex - 10 if lineIndex >= 10 else 0 newCursor = QTextCursor( self.document().findBlockByLineNumber(index)) self.moveCursor(QTextCursor.End) self.setTextCursor(newCursor) newerCursor = QTextCursor( self.document().findBlockByLineNumber(lineIndex)) self.setTextCursor(newerCursor) except: self.labelVisitStack.clear()
def build_invoice(self, data): document = QTextDocument() self.setDocument(document) document.setPageSize(QSizeF(self.doc_width, self.doc_height)) document.setDefaultFont(font) cursor = QTextCursor(document) cursor.insertText(f"Customer Name: {data['c_name']}\n") cursor.insertText(f"Customer Address: {data['c_addr']}\n") cursor.insertText(f"Date: {data['i_date']}\n") cursor.insertText(f"Total Due: {data['total_due']}\n") # + return document # +++
def on_log_filter(self): log_lvl_name = str(self.sender().iconText()).upper() self.log_lvl = log_levels[log_lvl_name] cursor = QTextCursor(self.document()) current_block = cursor.block() while current_block.isValid() and current_block.userData(): block_log_lvl = current_block.userData().log_lvl if block_log_lvl <= self.log_lvl: current_block.setVisible(True) else: current_block.setVisible(False) current_block = next(current_block) self.viewport().update()
def __init__(self, result, type, parent=None): super(ResultBlock, self).__init__(parent) self.result = result self.text_font = QFont('monospace', 16) if type == 'plain': self.result_block = QTextEdit() self.result_block.setFont(self.text_font) self.result_block.insertPlainText(result) self.result_block.setMinimumHeight(600) # Make sure scrollbar is always at the top self.result_block.moveCursor(QTextCursor().Start) self.result_block.ensureCursorVisible() self.result_block.setReadOnly(True) elif type == 'html': self.result_block = QTextEdit() self.result_block.setFont(self.text_font) self.result_block.insertHtml(result) self.result_block.setMinimumHeight(600) # Make sure scrollbar is always at the top self.result_block.moveCursor(QTextCursor().Start) self.result_block.ensureCursorVisible() self.result_block.setReadOnly(True) elif type == 'image': self.result_block = QScrollArea() self.image_preview = QWidget() image_preview_layout = QVBoxLayout() image_preview_layout.addWidget(result) print(result) self.image_preview.setLayout(image_preview_layout) self.result_block.setWidget(self.image_preview) self.result_block.setWidgetResizable(True) self.result_block.setMinimumHeight(600) # Create layout and add widgets layout = QVBoxLayout() layout.addWidget(self.result_block) # Set layout self.setLayout(layout)
def set_cursor(self, line_number): doc = self.textbox.document() cursor = QTextCursor(doc) cursor.movePosition(QTextCursor.Start) for _ in range(line_number - 1): cursor.movePosition(QTextCursor.Down) cursor.movePosition(QTextCursor.EndOfLine, QTextCursor.KeepAnchor) self.textbox.setTextCursor(cursor) self.textbox.centerCursor()
def __init__(self, parent=None): super(Form, self).__init__(parent) self.setWindowTitle('RetroUFO') # Create widgets self.chkboxPlatformDetect = QCheckBox('Platform Auto-Detect') self.chkboxPlatformDetect.setChecked(True) self.chkboxPlatformDetect.stateChanged.connect(self.auto_detect) self.cmbboxPlatform = QComboBox() self.cmbboxPlatform.setEnabled(False) self.cmbboxPlatform.setEditable(False) self.cmbboxPlatform.addItem('Linux') self.cmbboxPlatform.addItem('macOS') self.cmbboxPlatform.addItem('Windows') self.cmbboxArchitecture = QComboBox() self.cmbboxArchitecture.setEnabled(False) self.cmbboxArchitecture.setEditable(False) self.cmbboxArchitecture.addItem('x86') self.cmbboxArchitecture.addItem('x86_64') self.chkboxLocationDetect = QCheckBox('Core Location Auto-Detect') self.chkboxLocationDetect.setChecked(True) self.chkboxLocationDetect.stateChanged.connect(self.auto_location) self.leditCoreLocation = QLineEdit('') self.leditCoreLocation.setEnabled(False) self.btnCoreLocation = QPushButton('...') self.btnCoreLocation.setEnabled(False) self.btnCoreLocation.clicked.connect(self.choose_location) self.teditLog = QTextEdit() self.teditLog.setReadOnly(True) self.tcsrLog = QTextCursor(self.teditLog.document()) self.chkboxKeepDownload = QCheckBox('Keep Downloaded Cores') self.chkboxKeepDownload.setChecked(False) self.btnGrabCores = QPushButton('Grab Cores') self.btnGrabCores.clicked.connect(self.grab_cores) # Create layout and add widgets self.formLayout = QVBoxLayout() self.formLayout.addWidget(self.chkboxPlatformDetect) self.formLayout.addWidget(self.cmbboxPlatform) self.formLayout.addWidget(self.cmbboxArchitecture) self.formLayout.addWidget(self.chkboxLocationDetect) self.formLayout.addWidget(self.leditCoreLocation) self.formLayout.addWidget(self.btnCoreLocation) self.formLayout.addWidget(self.teditLog) self.formLayout.addWidget(self.chkboxKeepDownload) self.formLayout.addWidget(self.btnGrabCores) # Set dialog layout self.setLayout(self.formLayout)
def getFirstVisibleBlockId(self): """ Detect the first block for which bounding rect - once translated in absolute coordinated - is contained by the editor's text area :return: the first visible block """ if self.verticalScrollBar().sliderPosition() == 0: return 0 cursor = QTextCursor(self.document()) cursor.movePosition(QTextCursor.Start) for i in range(self.document().blockCount()): block = cursor.block() r1 = self.viewport().geometry() r2 = self.document().documentLayout().blockBoundingRect(block).translated( self.viewport().geometry().x(), self.viewport().geometry().y() - self.verticalScrollBar().sliderPosition() ).toRect() if r1.contains(r2, True): return i cursor.movePosition(QTextCursor.NextBlock) return 0
def init_ui(self): layout = QVBoxLayout(self.central_widget) layout.addWidget(self.text_editor) help_button = QPushButton('Помощь по синтаксису') help_button.clicked.connect(self.help_syntax) layout.addWidget(help_button) save_button = QPushButton('Сохранить изменения') save_button.setStyleSheet('font-weight: bold;') save_button.clicked.connect(self.save_module) layout.addWidget(save_button) save_as_button = QPushButton('Сохранить как ...') save_as_button.setStyleSheet('font-style: italic;') save_as_button.clicked.connect(self.save_as_module) layout.addWidget(save_as_button) cursor = QTextCursor(self.text_editor.document()) cursor.movePosition(QTextCursor.End) self.text_editor.setTextCursor(cursor) self.setCentralWidget(self.central_widget)
def get_word_under_cursor(self, cursor: QTextCursor): """ A word is ~ r'[A-Za-z\'-]+', where leading / trailing `'` are stripped or blocking e.g. "'h'i'" w/ cursor at 0 returns ("", ""), cursor at 1 returns ("", "h'i") :param cursor: :return: Tuple(front part, back part) """ front_text = cursor.block().text()[:cursor.positionInBlock()] back_text = cursor.block().text()[cursor.positionInBlock():] # strip leading quotes raw_front_match = re.search( r'(?P<junk>\'*)(?P<raw_front>[A-Za-z\'-]*?)$', front_text) raw_front_word = raw_front_match.group('raw_front') # strip trailing quotes raw_back_match = re.search(r'^(?P<raw_back>[A-Za-z\'-]*)', back_text) raw_back_word = raw_back_match.group('raw_back') pre_back_match = re.search( r'^(?P<pre_back>[A-Za-z\'-]*?)(?P<junk>\'*)$', raw_back_word) pre_back_word = pre_back_match.group('pre_back') if len(pre_back_word) == 0: end_quotes_match = re.search(r'(?P<end_quotes>\'*)$', raw_front_word) if len(end_quotes_match.group( 'end_quotes')) > 0: # Not inside a word. front_word = '' else: front_word = raw_front_word else: front_word = raw_front_word if len(front_word) == 0: lead_quotes_match = re.search(r'^(?P<lead_quotes>\'*)', pre_back_word) if len(lead_quotes_match.group( 'lead_quotes')) > 0: # Not inside a word. back_word = '' else: back_word = pre_back_word else: back_word = pre_back_word return (front_word, back_word)
def find_all( text: str, document: QTextDocument, flags=QTextDocument.FindFlags() ) -> List[QTextCursor]: """ Finds all occurrences of `text` in `document`, in order. :param text: Text to find. :param document: Document to search. :param flags: Conditions to set on the search: none or (whole word and/or match case) :return: Ordered list of all found instances. """ cursor = QTextCursor(document) # default pos == 0 found: List[QTextCursor] = [] while True: cursor = document.find(text, cursor, flags) if cursor.isNull(): return found else: found.append(cursor)
def _update_ui_for_error(self, error: TranspilerError): self.statusBar().showMessage(str(error)) self.player.clear() line_number = error.source_position.line_number - 1 block = self.text_area.document().findBlockByLineNumber(line_number) self.highlighter.error_line = line_number self.highlighter.rehighlightBlock(block) scroll_line = line_number - 5 if line_number >= 5 else line_number cursor = QTextCursor( self.text_area.document().findBlockByNumber(scroll_line)) self.text_area.moveCursor(QTextCursor.End) self.text_area.setTextCursor(cursor)
def init_ui(self): layout = QVBoxLayout(self.central_widget) layout.addWidget(self.text_editor) help_button = QPushButton('Помощь по синтаксису') help_button.clicked.connect(self.help_syntax) layout.addWidget(help_button) crypto_label = QLabel('Алгоритм шифрования') crypto_label.setStyleSheet('font-style: italic;') crypto_label.setAlignment(Qt.AlignCenter) layout.addWidget(crypto_label) self.type_of_crypto.addItem('XOR') self.type_of_crypto.addItem('AES-256') layout.addWidget(self.type_of_crypto) create_button = QPushButton('Сохранить модуль') create_button.setStyleSheet('font-weight: bold;') create_button.clicked.connect(self.save_module) layout.addWidget(create_button) self.text_editor.setText(create_basic_text()) cursor = QTextCursor(self.text_editor.document()) cursor.movePosition(QTextCursor.End) self.text_editor.setTextCursor(cursor) self.setCentralWidget(self.central_widget)
def add_message_to_document(document, message): """Adds a message to a document and return the cursor. Args: document (QTextDocument) message (str) Returns: QTextCursor """ cursor = QTextCursor(document) cursor.movePosition(QTextCursor.End) cursor.insertBlock() cursor.insertHtml(message) return cursor
def _highlight(self, editor: QTextEdit, text: str, fmt: QTextCharFormat, fmt_chg: QTextCharFormat): cursor = QTextCursor(editor.textCursor()) if text.endswith('\n'): text = text[:-1] elif text.endswith('\n\1'): text = text[:-2] + '\1' pos_list = self._get_pos_list(text) text = text.replace('\0+', '').replace('\0-', '').replace('\0^', '').replace('\1', '') editor.setPlainText(text) n = 0 for tag, start, end in pos_list: if not end == start + 2: cursor.setPosition(start - n) cursor.setPosition(end - n - 2, QTextCursor.KeepAnchor) if tag == '^': cursor.mergeCharFormat(fmt_chg) else: cursor.mergeCharFormat(fmt) n += 3
def highlight_word(self, cursor: QTextCursor, entry: Optional[Entry]): selection = QTextEdit.ExtraSelection() normal_color = QColor(Qt.yellow).lighter() missing_color = QColor(Qt.magenta).lighter() default_color = QColor(Qt.green).lighter() if entry is None: selection.format.setBackground(missing_color) elif entry['default'] == cursor.selection().toPlainText(): selection.format.setBackground(default_color) else: selection.format.setBackground(normal_color) selection.cursor = cursor self.setExtraSelections([selection])
def testRefcount(self): textedit = QTextEdit() textedit.setReadOnly(True) doc = textedit.document() cursor = QTextCursor(doc) cursor.insertText("PySide Rocks") ud = TestUserData({"Life": 42}) self.assertEqual(sys.getrefcount(ud), 2) cursor.block().setUserData(ud) self.assertEqual(sys.getrefcount(ud), 3) ud2 = cursor.block().userData() self.assertEqual(sys.getrefcount(ud), 4) self.udata = weakref.ref(ud, None) del ud, ud2 self.assertEqual(sys.getrefcount(self.udata()), 2)
def textUnderCursor(self): tc = self.textCursor() tc.select(QTextCursor.WordUnderCursor) selected_text = tc.selectedText() if selected_text == "(": cursor_pos = tc.position() if cursor_pos - 2 > 0: cursor_prev = QTextCursor(self.document()) cursor_prev.setPosition(cursor_pos - 2) cursor_prev.select(QTextCursor.WordUnderCursor) selected_text = cursor_prev.selectedText() #print(selected_text) return selected_text
def testUndoRedo(self): text = 'foobar' doc = QTextDocument(text) self.assertFalse(doc.isRedoAvailable()) self.assertTrue(doc.isUndoAvailable()) self.assertEqual(doc.toPlainText(), text) cursor = QTextCursor(doc) doc.undo(cursor) self.assertTrue(doc.isRedoAvailable()) self.assertFalse(doc.isUndoAvailable()) self.assertEqual(doc.toPlainText(), '') doc.redo(cursor) self.assertFalse(doc.isRedoAvailable()) self.assertTrue(doc.isUndoAvailable()) self.assertEqual(doc.toPlainText(), text)
def testQTextCursorSelectedTableCells(self): obj = QTextCursor() self.assertEqual(obj.selectedTableCells(), (-1, -1, -1, -1))
def testCase(self): editor = QTextEdit() cursor = QTextCursor(editor.textCursor()) cursor.movePosition(QTextCursor.Start) mainFrame = cursor.currentFrame() plainCharFormat = QTextCharFormat() boldCharFormat = QTextCharFormat() boldCharFormat.setFontWeight(QFont.Bold); cursor.insertText(""" Text documents are represented by the QTextDocument class, rather than by QString objects. Each QTextDocument object contains information about the document's internal representation, its structure, and keeps track of modifications to provide undo/redo facilities. This approach allows features such as the layout management to be delegated to specialized classes, but also provides a focus for the framework.""", plainCharFormat) frameFormat = QTextFrameFormat() frameFormat.setMargin(32) frameFormat.setPadding(8) frameFormat.setBorder(4) cursor.insertFrame(frameFormat) cursor.insertText(""" Documents are either converted from external sources or created from scratch using Qt. The creation process can done by an editor widget, such as QTextEdit, or by explicit calls to the Scribe API.""", boldCharFormat) cursor = mainFrame.lastCursorPosition() cursor.insertText(""" There are two complementary ways to visualize the contents of a document: as a linear buffer that is used by editors to modify the contents, and as an object hierarchy containing structural information that is useful to layout engines. In the hierarchical model, the objects generally correspond to visual elements such as frames, tables, and lists. At a lower level, these elements describe properties such as the style of text used and its alignment. The linear representation of the document is used for editing and manipulation of the document's contents.""", plainCharFormat) frame = cursor.currentFrame() items = [] #test iterator for i in frame: items.append(i) #test __iadd__ b = frame.begin() i = 0 while not b.atEnd(): self.assertEqual(b, items[i]) self.assert_(b.parentFrame(), items[i].parentFrame()) b.__iadd__(1) i += 1 #test __isub__ b = frame.end() i = 0 while i > 0: self.assertEqual(b, items[i]) self.assert_(b.parentFrame(), items[i].parentFrame()) b.__isub__(1) i -= 1
def qt_util_reset_text_edit_cursor(qw_text_edit): first_row_block = qw_text_edit.document().findBlockByLineNumber( 0) # 1行目のblockを取得 qg_text_cursor = QTextCursor(first_row_block) qw_text_edit.setTextCursor(qg_text_cursor) # cursorを1行目に設定
def testQTextCursorSelectedTableCells(self): obj = QTextCursor() self.assertEquals(obj.selectedTableCells(), (-1, -1, -1, -1))
def on_log_received(self, data): time_info = datetime.fromtimestamp((data['time'] / 1000)).isoformat() log_message = '%s: %s : %s' % (time_info, data['level'], data['message']) message_document = self.document() cursor_to_add = QTextCursor(message_document) cursor_to_add.movePosition(cursor_to_add.End) cursor_to_add.insertText(log_message + '\n') if data['level'] in COLORS: fmt = QTextCharFormat() fmt.setForeground(COLORS[data['level']]) cursor_to_add.movePosition(cursor_to_add.PreviousBlock) log_lvl_data = LogLevelData(log_levels[data['level'].upper()]) cursor_to_add.block().setUserData(log_lvl_data) cursor_to_add_fmt = message_document.find(data['level'], cursor_to_add.position()) cursor_to_add_fmt.mergeCharFormat(fmt) if log_levels[data['level']] > self.log_lvl: cursor_to_add.block().setVisible(False) self.ensureCursorVisible()
def initUI(self): grid_layout = QGridLayout() grid_layout.setSpacing(10) self.setLayout(grid_layout) #Tutorial self.tutorialLabel = QLabel() self.tutorialLabel.setText( "Welcome to DeepCreamPy!\n\nIf you're new to DCP, please read the README.\nThis program does nothing without the proper setup of your images.\n\nReport any bugs you encounter to me on Github or Twitter @deeppomf." ) self.tutorialLabel.setAlignment(Qt.AlignCenter) self.tutorialLabel.setFont(QFont('Sans Serif', 13)) #Censor type group self.censorTypeGroupBox = QGroupBox('Censor Type') barButton = QRadioButton('Bar censor') mosaicButton = QRadioButton('Mosaic censor') barButton.setChecked(True) censorLayout = QVBoxLayout() censorLayout.addWidget(barButton) censorLayout.addWidget(mosaicButton) # censorLayout.addStretch(1) self.censorTypeGroupBox.setLayout(censorLayout) #Variation count group self.variationsGroupBox = QGroupBox('Number of Decensor Variations') var1Button = QRadioButton('1') var2Button = QRadioButton('2') var3Button = QRadioButton('4') var1Button.setChecked(True) varLayout = QVBoxLayout() varLayout.addWidget(var1Button) varLayout.addWidget(var2Button) varLayout.addWidget(var3Button) # varLayout.addStretch(1) self.variationsGroupBox.setLayout(varLayout) #Decensor button self.decensorButton = QPushButton('Decensor Your Images') self.decensorButton.clicked.connect(self.decensorClicked) self.decensorButton.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) #Progress message # self.progressGroupBox = QGroupBox('Progress') self.progressMessage = QTextEdit() self.progressCursor = QTextCursor(self.progressMessage.document()) self.progressMessage.setTextCursor(self.progressCursor) self.progressMessage.setReadOnly(True) self.progressCursor.insertText( "After you prepared your images, click on the decensor button once to begin decensoring.\nPlease be patient.\nDecensoring will take time.\n" ) # Progress Bar self.statusBar = QStatusBar(self) self.progressBar = QProgressBar() self.progressBar.setMinimum(0) self.progressBar.setMaximum(100) self.progressBar.setValue(0) self.statusLabel = QLabel("Showing Progress") self.statusBar.addWidget(self.statusLabel, 1) self.statusBar.addWidget(self.progressBar, 2) #put all groups into grid # addWidget(row, column, rowSpan, columnSpan) grid_layout.addWidget(self.tutorialLabel, 0, 0, 1, 2) grid_layout.addWidget(self.censorTypeGroupBox, 1, 0, 1, 1) grid_layout.addWidget(self.variationsGroupBox, 1, 1, 1, 1) grid_layout.addWidget(self.decensorButton, 2, 0, 1, 2) grid_layout.addWidget(self.progressMessage, 3, 0, 1, 2) grid_layout.addWidget(self.statusBar, 4, 0, 1, 2) #window size settings self.resize(900, 600) self.center() self.setWindowTitle('DeepCreamPy v2.2.0-beta') self.show()
class MainWindow(QWidget): def __init__(self): super().__init__() self.signals = Signals() self.initUI() self.setSignals() self.decensor = Decensor(self) self.load_model() def initUI(self): grid_layout = QGridLayout() grid_layout.setSpacing(10) self.setLayout(grid_layout) #Tutorial self.tutorialLabel = QLabel() self.tutorialLabel.setText( "Welcome to DeepCreamPy!\n\nIf you're new to DCP, please read the README.\nThis program does nothing without the proper setup of your images.\n\nReport any bugs you encounter to me on Github or Twitter @deeppomf." ) self.tutorialLabel.setAlignment(Qt.AlignCenter) self.tutorialLabel.setFont(QFont('Sans Serif', 13)) #Censor type group self.censorTypeGroupBox = QGroupBox('Censor Type') barButton = QRadioButton('Bar censor') mosaicButton = QRadioButton('Mosaic censor') barButton.setChecked(True) censorLayout = QVBoxLayout() censorLayout.addWidget(barButton) censorLayout.addWidget(mosaicButton) # censorLayout.addStretch(1) self.censorTypeGroupBox.setLayout(censorLayout) #Variation count group self.variationsGroupBox = QGroupBox('Number of Decensor Variations') var1Button = QRadioButton('1') var2Button = QRadioButton('2') var3Button = QRadioButton('4') var1Button.setChecked(True) varLayout = QVBoxLayout() varLayout.addWidget(var1Button) varLayout.addWidget(var2Button) varLayout.addWidget(var3Button) # varLayout.addStretch(1) self.variationsGroupBox.setLayout(varLayout) #Decensor button self.decensorButton = QPushButton('Decensor Your Images') self.decensorButton.clicked.connect(self.decensorClicked) self.decensorButton.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) #Progress message # self.progressGroupBox = QGroupBox('Progress') self.progressMessage = QTextEdit() self.progressCursor = QTextCursor(self.progressMessage.document()) self.progressMessage.setTextCursor(self.progressCursor) self.progressMessage.setReadOnly(True) self.progressCursor.insertText( "After you prepared your images, click on the decensor button once to begin decensoring.\nPlease be patient.\nDecensoring will take time.\n" ) # Progress Bar self.statusBar = QStatusBar(self) self.progressBar = QProgressBar() self.progressBar.setMinimum(0) self.progressBar.setMaximum(100) self.progressBar.setValue(0) self.statusLabel = QLabel("Showing Progress") self.statusBar.addWidget(self.statusLabel, 1) self.statusBar.addWidget(self.progressBar, 2) #put all groups into grid # addWidget(row, column, rowSpan, columnSpan) grid_layout.addWidget(self.tutorialLabel, 0, 0, 1, 2) grid_layout.addWidget(self.censorTypeGroupBox, 1, 0, 1, 1) grid_layout.addWidget(self.variationsGroupBox, 1, 1, 1, 1) grid_layout.addWidget(self.decensorButton, 2, 0, 1, 2) grid_layout.addWidget(self.progressMessage, 3, 0, 1, 2) grid_layout.addWidget(self.statusBar, 4, 0, 1, 2) #window size settings self.resize(900, 600) self.center() self.setWindowTitle('DeepCreamPy v2.2.0-beta') self.show() def load_model(self): # load model to make able to decensor several times self.decensorButton.setEnabled(False) self.decensorButton.setText( "Loading Machine Learning Model (Please Wait...)") self.decensor.start() self.decensor.signals = self.signals self.progressCursor.insertText( "Loading Decensor app consumes 6 GB memory at maximum") def setSignals(self): self.signals.update_decensorButton_Text.connect( self.decensorButton.setText) self.signals.update_decensorButton_Enabled.connect( self.decensorButton.setEnabled) self.signals.update_statusLabel_Text.connect(self.statusLabel.setText) self.signals.update_ProgressBar_SET_VALUE.connect( self.progressBar.setValue) self.signals.update_ProgressBar_MAX_VALUE.connect( self.progressBar.setMaximum) self.signals.update_ProgressBar_MIN_VALUE.connect( self.progressBar.setMinimum) # self.signals.insertText_progressCursor.connect(self.progressCursor.insertText) self.signals.insertText_progressCursor.connect( self.progressMessage.append) self.signals.clear_progressMessage.connect(self.progressMessage.clear) self.signals.appendText_progressMessage.connect( self.progressMessage.append) def decensorClicked(self): self.decensorButton.setEnabled(False) self.progressMessage.clear() self.progressCursor.insertText("Decensoring has begun!\n") # for now, decensor is initiated when this app is started # self.decensor = Decensor(text_edit = self.progressMessage, text_cursor = self.progressCursor, ui_mode = True) #https://stackoverflow.com/questions/42349470/pyqt-find-checked-radiobutton-in-a-group #set decensor to right settings #censor type censorTypeElements = self.censorTypeGroupBox.children() censorButtons = [ elem for elem in censorTypeElements if isinstance(elem, QRadioButton) ] for cb in censorButtons: if cb.isChecked(): censorType = cb.text() if censorType == 'Bar censor': self.decensor.is_mosaic = False else: self.decensor.is_mosaic = True #variations count variationsElements = self.variationsGroupBox.children() variationsButtons = [ elem for elem in variationsElements if isinstance(elem, QRadioButton) ] for vb in variationsButtons: if vb.isChecked(): variations = int(vb.text()) self.decensor.variations = variations self.decensorButton.setEnabled(False) self.decensor.start() # decensor.decensor_all_images_in_folder() # #centers the main window def center(self): qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft())
def testCase(self): editor = QTextEdit() cursor = QTextCursor(editor.textCursor()) cursor.movePosition(QTextCursor.Start) mainFrame = cursor.currentFrame() plainCharFormat = QTextCharFormat() boldCharFormat = QTextCharFormat() boldCharFormat.setFontWeight(QFont.Bold) cursor.insertText( """ Text documents are represented by the QTextDocument class, rather than by QString objects. Each QTextDocument object contains information about the document's internal representation, its structure, and keeps track of modifications to provide undo/redo facilities. This approach allows features such as the layout management to be delegated to specialized classes, but also provides a focus for the framework.""", plainCharFormat) frameFormat = QTextFrameFormat() frameFormat.setMargin(32) frameFormat.setPadding(8) frameFormat.setBorder(4) cursor.insertFrame(frameFormat) cursor.insertText( """ Documents are either converted from external sources or created from scratch using Qt. The creation process can done by an editor widget, such as QTextEdit, or by explicit calls to the Scribe API.""", boldCharFormat) cursor = mainFrame.lastCursorPosition() cursor.insertText( """ There are two complementary ways to visualize the contents of a document: as a linear buffer that is used by editors to modify the contents, and as an object hierarchy containing structural information that is useful to layout engines. In the hierarchical model, the objects generally correspond to visual elements such as frames, tables, and lists. At a lower level, these elements describe properties such as the style of text used and its alignment. The linear representation of the document is used for editing and manipulation of the document's contents.""", plainCharFormat) frame = cursor.currentFrame() items = [] #test iterator for i in frame: items.append(i) #test __iadd__ b = frame.begin() i = 0 while not b.atEnd(): self.assertEqual(b, items[i]) self.assertTrue(b.parentFrame(), items[i].parentFrame()) b.__iadd__(1) i += 1 #test __isub__ b = frame.end() i = 0 while i > 0: self.assertEqual(b, items[i]) self.assertTrue(b.parentFrame(), items[i].parentFrame()) b.__isub__(1) i -= 1
def update_document(self): self._qtextdoc.clear() cur = QTextCursor(self._qtextdoc) self.obj.render_to_doc(cur)
class MainWindow(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): grid_layout = QGridLayout() grid_layout.setSpacing(10) self.setLayout(grid_layout) #Tutorial self.tutorialLabel = QLabel() self.tutorialLabel.setText( "Welcome to DeepCreamPy!\n\nIf you're new to DCP, please read the README.\nThis program does nothing without the proper setup of your images.\n\nReport any bugs you encounter to me on Github or Twitter @deeppomf." ) self.tutorialLabel.setAlignment(Qt.AlignCenter) self.tutorialLabel.setFont(QFont('Sans Serif', 13)) #Censor type group self.censorTypeGroupBox = QGroupBox('Censor Type') barButton = QRadioButton('Bar censor') mosaicButton = QRadioButton('Mosaic censor') barButton.setChecked(True) censorLayout = QVBoxLayout() censorLayout.addWidget(barButton) censorLayout.addWidget(mosaicButton) # censorLayout.addStretch(1) self.censorTypeGroupBox.setLayout(censorLayout) #Variation count group self.variationsGroupBox = QGroupBox('Number of Decensor Variations') var1Button = QRadioButton('1') var2Button = QRadioButton('2') var3Button = QRadioButton('4') var1Button.setChecked(True) varLayout = QVBoxLayout() varLayout.addWidget(var1Button) varLayout.addWidget(var2Button) varLayout.addWidget(var3Button) # varLayout.addStretch(1) self.variationsGroupBox.setLayout(varLayout) #Decensor button self.decensorButton = QPushButton('Decensor Your Images') self.decensorButton.clicked.connect(self.decensorClicked) self.decensorButton.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) #Progress message # self.progressGroupBox = QGroupBox('Progress') self.progressMessage = QTextEdit() self.progressCursor = QTextCursor(self.progressMessage.document()) self.progressMessage.setTextCursor(self.progressCursor) self.progressMessage.setReadOnly(True) self.progressCursor.insertText( "After you prepared your images, click on the decensor button once to begin decensoring.\nPlease be patient.\nDecensoring will take time.\n" ) #put all groups into grid grid_layout.addWidget(self.tutorialLabel, 0, 0, 1, 2) grid_layout.addWidget(self.censorTypeGroupBox, 1, 0, 1, 1) grid_layout.addWidget(self.variationsGroupBox, 1, 1, 1, 1) grid_layout.addWidget(self.decensorButton, 2, 0, 1, 2) grid_layout.addWidget(self.progressMessage, 3, 0, 4, 2) #window size settings self.resize(500, 500) self.center() self.setWindowTitle('DeepCreamPy v2.2.0-beta') self.show() def decensorClicked(self): self.decensorButton.setEnabled(False) self.progressMessage.clear() self.progressCursor.insertText("Decensoring has begun!\n") decensor = Decensor(text_edit=self.progressMessage, text_cursor=self.progressCursor, ui_mode=True) #https://stackoverflow.com/questions/42349470/pyqt-find-checked-radiobutton-in-a-group #set decensor to right settings #censor type censorTypeElements = self.censorTypeGroupBox.children() censorButtons = [ elem for elem in censorTypeElements if isinstance(elem, QRadioButton) ] for cb in censorButtons: if cb.isChecked(): censorType = cb.text() if censorType == 'Bar censor': decensor.is_mosaic = False else: decensor.is_mosaic = True #variations count variationsElements = self.variationsGroupBox.children() variationsButtons = [ elem for elem in variationsElements if isinstance(elem, QRadioButton) ] for vb in variationsButtons: if vb.isChecked(): variations = int(vb.text()) decensor.variations = variations self.decensorButton.setEnabled(True) self.hide() self.progress = ProgressWindow(self, decensor=decensor) # decensor.decensor_all_images_in_folder() # self.progress.hide() # self.show() # def showAbout(self): # QMessageBox.about(self, 'About', "DeepCreamPy v2.2.0 \n Developed by deeppomf") # #centers the main window def center(self): qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft())