PyQt4中如何获取QTextEdit光标旁文本?实现注释切换功能
Toggle Comment Functionality for QTextEdit (Bash IDE)
Great question! Toggling comments with the same shortcut is a must-have for any IDE, and I’ve got you covered. Let’s fix this step by step—your core issue of accessing the cursor’s line text is easier to solve than you might think.
Here’s a complete, tested implementation that adds toggle comment support using Ctrl+/:
def commentShortcut(self): cursor = self.textCursor() current_block = cursor.block() # Get the full line text, preserving leading whitespace line_text = current_block.text() if not line_text.strip(): # Skip empty lines (optional, remove if needed) return # Calculate leading whitespace to maintain proper indentation leading_whitespace = line_text[:len(line_text) - len(line_text.lstrip())] content = line_text.lstrip() # Check if the line is already commented (Bash uses #) is_commented = content.startswith('#') if is_commented: # Remove comment: handle both "# comment" and "#comment" formats if content.startswith('# '): new_content = content[2:] else: new_content = content[1:] new_line = leading_whitespace + new_content else: # Add comment: insert # with a space after leading indentation new_line = leading_whitespace + '# ' + content # Replace the line with modified text (undo-friendly) cursor.beginEditBlock() cursor.movePosition(QtGui.QTextCursor.StartOfBlock) cursor.movePosition(QtGui.QTextCursor.EndOfBlock, QtGui.QTextCursor.KeepAnchor) cursor.insertText(new_line) cursor.endEditBlock() # Restore cursor position after edit self.setTextCursor(cursor)
Key Details & Improvements:
- Accessing Line Text:
current_block.text()directly grabs the entire line’s content—no need for the block number juggling in your original snippet. - Indentation Preservation: We calculate leading whitespace so comments align with your code’s indentation (e.g.,
echo "hello"becomes# echo "hello"instead of# echo "hello"), keeping your Bash scripts clean. - Smart Toggle Logic: Detects if the line is already commented (ignoring leading spaces) and adjusts accordingly. Handles both spaced and unspaced comment formats.
- Undo Support: Wrapping edits in
beginEditBlock()/endEditBlock()makes the toggle action undoable with Ctrl+Z—critical for an IDE experience. - Empty Line Handling: Skips empty lines to avoid adding unnecessary comments (remove the
if not line_text.strip()check if you want to toggle comments on empty lines).
Quick Tip for Your IDE:
If you want to extend this to multi-line comment toggling later, just loop over all selected blocks instead of only current_block.
内容的提问来源于stack exchange,提问作者Dušan Atanacković
相关产品推荐
相关产品推荐

