Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the tab size in QML TextEdit?

Tags:

qt

qml

qtquick2

I use a TextEdit component for a code editor in my Qt 5.5 application. When pressing Tab or pasting snippets from other editors, a default tab size is applied (which is huge) and I just can't find a way to change that value.

My workaround is to forward key events to a C++ controller where I do stuff like inserting myCustomTabSize times spaceCharacter for each Qt::Key_Tab event. Or manually prepare strings from the clipboard before pasting them.

The QTextEdit class provides a setTabStopWidth method. Is there a QML equivalent for that?

like image 972
qCring Avatar asked Oct 07 '15 21:10

qCring


1 Answers

To change the tab size in QML TextEdit follow next steps:

1) Set objectName to TextEdit.

TextEdit {
    objectName: "myTextEdit"
}

2) Get access to TextEdit from c++.

QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

QObject *root = engine.rootObjects().at(0);
QObject *textEdit = root->findChild<QObject*>(QStringLiteral("myTextEdit"));

3) Get QTextDocument, associated with TextEdit.

QQuickTextDocument *quickTextDocument = textEdit->property("textDocument").value<QQuickTextDocument*>();
QTextDocument *document = quickTextDocument->textDocument();

4) Get default QTextOption.

QTextOption textOptions = document->defaultTextOption();

5) Sets the distance in device units between tab stops

textOptions.setTabStop(10);

6) Set options to document.

document->setDefaultTextOption(textOptions);
like image 59
Meefte Avatar answered Sep 23 '22 13:09

Meefte