Merge pull request #19924 from benj5378/codeDupEditor

Gui: avoid code duplication in PythonEditor
This commit is contained in:
Chris Hennes
2025-03-17 00:02:03 -05:00
committed by GitHub
3 changed files with 32 additions and 38 deletions

View File

@@ -238,25 +238,7 @@ void PythonEditor::keyPressEvent(QKeyEvent* e)
void PythonEditor::onComment()
{
QTextCursor cursor = textCursor();
int selStart = cursor.selectionStart();
int selEnd = cursor.selectionEnd();
QTextBlock block;
cursor.beginEditBlock();
for (block = document()->begin(); block.isValid(); block = block.next()) {
int pos = block.position();
int off = block.length()-1;
// at least one char of the block is part of the selection
if ( pos >= selStart || pos+off >= selStart) {
if ( pos+1 > selEnd )
break; // end of selection reached
cursor.setPosition(block.position());
cursor.insertText(QLatin1String("#"));
selEnd++;
}
}
cursor.endEditBlock();
prepend(QStringLiteral("#"));
}
void PythonEditor::onUncomment()

View File

@@ -495,6 +495,30 @@ PythonTextEditor::PythonTextEditor(QWidget *parent)
PythonTextEditor::~PythonTextEditor() = default;
void PythonTextEditor::prepend(const QString& str)
{
QTextCursor cursor = textCursor();
// for each selected block insert a tab or spaces
int selStart = cursor.selectionStart();
int selEnd = cursor.selectionEnd();
QTextBlock block;
cursor.beginEditBlock();
for (block = document()->begin(); block.isValid(); block = block.next()) {
int pos = block.position();
int off = block.length()-1;
// at least one char of the block is part of the selection
if ( pos >= selStart || pos+off >= selStart) {
if ( pos+1 > selEnd )
break; // end of selection reached
cursor.setPosition(block.position());
cursor.insertText(str);
selEnd += str.length();
}
}
cursor.endEditBlock();
}
void PythonTextEditor::keyPressEvent (QKeyEvent * e)
{
if ( e->key() == Qt::Key_Tab ) {
@@ -511,25 +535,7 @@ void PythonTextEditor::keyPressEvent (QKeyEvent * e)
cursor.insertText(ch);
cursor.endEditBlock();
} else {
// for each selected block insert a tab or spaces
int selStart = cursor.selectionStart();
int selEnd = cursor.selectionEnd();
QTextBlock block;
cursor.beginEditBlock();
for (block = document()->begin(); block.isValid(); block = block.next()) {
int pos = block.position();
int off = block.length()-1;
// at least one char of the block is part of the selection
if ( pos >= selStart || pos+off >= selStart) {
if ( pos+1 > selEnd )
break; // end of selection reached
cursor.setPosition(block.position());
cursor.insertText(ch);
selEnd += ch.length();
}
}
cursor.endEditBlock();
prepend(ch);
}
return;

View File

@@ -139,6 +139,12 @@ public:
explicit PythonTextEditor(QWidget *parent = nullptr);
~PythonTextEditor() override;
public Q_SLOTS:
/** Inserts \a str at the beginning of each selected line or the current line if
* nothing is selected
*/
void prepend(const QString& str);
protected:
void keyPressEvent(QKeyEvent *) override;
};