PDA

View Full Version : indent selection in QPlainTextEdit



qt_gotcha
24th August 2010, 15:56
I do this to increase the indent of a selection of lines in a plainTextEdit, but nothing happens:


QTextCursor cur = plainEdit->textCursor(); // contains the selection
QTextBlockFormat tbf = cur.blockFormat(); //selection format
tbf.setIndent(10); // change indent
cur.setBlockFormat(tbf); // put it all back
plainEdit->setTextCursor(cur);

wordwrap is off so a block is a line. This doesn't work, somebody has some pointers? thanks

qt_gotcha
24th August 2010, 19:06
This is my code to do this, I add a space instead of doing a real indent, but it is fine for me. If anyone can make this more efficient, I am all ears!

QTextCursor cur = ETEditor->textCursor();
int a = cur.anchor();
int p = cur.position();

cur.setPosition(a);
cur.movePosition(QTextCursor::StartOfBlock,QTextCu rsor::MoveAnchor);
a = cur.position();
// save a new anchor at the beginning of the line of the selected text
cur.setPosition(a);
cur.setPosition(p, QTextCursor::KeepAnchor);
// set a new selection with the new beginning
QString str = cur.selection().toPlainText();
QStringList list = str.split("\n");
// get the selected text and split into lines

for (int i = 0; i < list.count(); i++)
list[i].insert(0," ");
//insert a space at the beginning of each line

str=list.join("\n");
cur.removeSelectedText();
cur.insertText(str);
// put the new text back
cur.setPosition(a);
cur.setPosition(p, QTextCursor::KeepAnchor);
// reselect the text for more indents

ETEditor->setTextCursor(cur);
// put the whole thing back into the main text