Solved QTextEdit: press Ctrl+/ to add // to each line of selection
-
It is a common operation to commented out code in IDE
-
Are you asking how to implement that or... ?
-
@sonichy
You will write code to recognize the Ctrl+/ key press on yourQTextEdit
, then get the currently selected lines and go through them line-by-line inserting the//
at the start of each line. -
void MdiChild::keyPressEvent(QKeyEvent *e) { if ((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_Slash) { QString s = textCursor().selection().toPlainText(); QStringList SL = s.split("\n"); for(int i=0; i<SL.length(); i++){ if(SL.at(i).trimmed().startsWith("//")){ s = SL.at(i); s.replace("//",""); }else{ s = "//" + SL.at(i); } if(i<SL.length()-1) s.append("\n"); textCursor().insertText(s); } } else { return QPlainTextEdit::keyPressEvent(e); } }
-
@sonichy
In principle what you have written looks about right to me. However, depending on what you want, I think this is missing a couple of facilities from what I would expect a "comment/uncomment" to do having used it in other editors:-
If your start position is in the middle of a line, or there is no selection just where the text caret is, I think your code inserts a
//
in the middle of a line. That's not right. They tend to go backwards from the start point to find the beginning of that line, and comment the whole line that way. -
Your code decides whether to insert/remove a
//
("toggle") from each line depending on what each line starts with. When you have a block like:
code // a comment some code // another comment some more code
you will come out with
//code a comment //some code another comment //some more code
which is not great. I think others look at whether the first line is or is not presently commented, and then apply (the reverse) of that to every line from then on, rather than "toggle* each line individually, so it would come out more like:
//code //// a comment //some code //// another comment //some more code
ready to be uncommented on a second key press. Have a play and see what you think.
-