How to indent multiline text behind lists in QMLs TextEdit - list

In QML Im using a TextEdit item for a text editor with highlighter code running behind it (QSyntaxHighlighter). When the user types a dash (-), it will be recognised by the highlighter code and formatted (like Markdown). But additionally I want the text to be indented behind the dash, when it is multiline. Just like it behaves with HTML lists.
This is how it looks like right now:
This is how I want it (the text aligns properly behind the dash):
I know this can indent the text:
QTextCursor cursor(currentBlock());
QTextBlockFormat textBlockFormat = currentBlock().blockFormat();
textBlockFormat.setIndent(1);
cursor.setBlockFormat(textBlockFormat);
An idea is to indent all the text by default and un-indent the lines with a dash or similar, but couldn't quite figure out yet how to achieve it.
Any other ideas?

Ok apparently there is also a list styling option. This is how you can change the style of a block:
QTextBlock block = textDoc->findBlockByNumber(i);
QTextCursor cursor(block);
cursor.beginEditBlock();
QTextListFormat::Style style = QTextListFormat::ListDecimal;
QTextBlockFormat blockFmt = cursor.blockFormat();
QTextListFormat listFmt;
if (cursor.currentList()) {
listFmt = cursor.currentList()->format();
} else {
listFmt.setIndent(blockFmt.indent() + 1);
blockFmt.setIndent(0);
cursor.setBlockFormat(blockFmt);
}
listFmt.setStyle(style);
cursor.createList(listFmt);
cursor.endEditBlock();
This could be used in a slot linking to the contentsChange signal from QTextDocument or in a highlighter.

Related

QLineEdit: how to put cursor at the end of typed text?

There is a QLineEdit in which you need to enter a phone number. Gave him a mask
ui->lineEdit_4->setInputMask("+7\\(999\\)999\\-99\\-99;_");
Further, when saving the data, the entered string is checked by the validator:
QRegularExpression numberRegex ("^\\+\\d{1,1}\\(\\d{3,3}\\)\\d{3,3}\\-\\d{2,2}\\-\\d{2,2}$");
QRegularExpressionValidator *numberValidator = new QRegularExpressionValidator (numberRegex);
QString a = ui->lineEdit_4->text();
int b = ui->lineEdit_4->cursorPosition();
if(numberValidator->validate(a, b) == QValidator::Acceptable){
....
}
Above I described everything that is, and now the very essence of the problem. Typing is extremely inconvenient, since the cursor is not attached to anything. Wherever you click, the cursor will appear there. How to make the cursor appear where you need to type text? So far, in ideas there is only a check for the cursor position, and every time it changes, put it on the first "_" in the line. But something sounds crazy
Connect this signal: https://doc.qt.io/qt-5/qlineedit.html#cursorPositionChanged
In the target method, move cursor to the end of the field with this: https://doc.qt.io/qt-5/qlineedit.html#end
Something like this:
QObject::connect(
ui->lineEdit_4,
&QLineEdit::cursorPositionChanged,
this,
[this](){
ui->lineEdit_4->end(false);
});

Write on the same line in TextEdit in Qt

When we use ui->TextEdit->append("...") the text entered will be shown in a new line in the TextEdit section. What I want to do is to write on the same line... I've tried this code:
ui->textEdit->append("My name is:");
ui->textEdit->append("\b bla");
but it seems that "\b" isn't recognised by Qt
Maybe an option is to do the append outside of the QTextEdit to avoid having a new paragraph created:
QString text = ui->textEdit->text();
text.append("bla");
ui->textEdit->setText(text);

Qt/QML: Text with inline QML elements

We are building a graphical user interface with QtQuick/QML. We have some dynamic, multi-line text coming from a database, which should be displayed in the application. Currently, we are using the Text element to display the text. However, we need some QML components inline embedded into the text. For this, the text coming from the database contains placeholders such as ::checkbox|1:: which should then be replaced and displayed by the program.
In HTML, this is easy, you can simply mix inline elements with text to produce a result like this:
but in QML, this seems to be more difficult, as Text elements cannot be word-wrapped into two halves if there is not enough space (both the text and the container size should be dynamic).
The best solution we could come up with, is creating a Flow layout with one Text element for each word, but this seems too hacky.
Using RichText with HTML is not enogh, since we really need our custom QML elements in the text.
Also, we want to avoid using a WebView due to performance reasons.
Is there a sophisticated way to implement this with QML/C++ only?
You can create custom widgets and embed them into QML:
Writing QML Extensions with C++
I haven't tried placing something in the middle, but I did try adding a tag to the beginning (and I might try adding a tag at the end).
QML's Text has a lineLaidOut signal that let's you indent the first line of text.
http://doc.qt.io/qt-5/qml-qtquick-text.html#lineLaidOut-signal
Here's what I did:
Text {
text: issue.summary
onLineLaidOut: {
if (line.number == 0) {
var indent = tagRect.width + tagRect.rightMargin
line.x += indent
line.width -= indent
}
}
Rectangle {
id: tagRect
implicitWidth: padding + tagText.implicitWidth + padding
implicitHeight: padding + tagText.implicitHeight + padding
color: "#400"
property int padding: 2
property int rightMargin: 8
radius: 3
Text {
id: tagText
anchors.centerIn: parent
text: issue.product
color: "#fff"
}
}
}

Set line spacing in QTextEdit

I want to set the line spacing of a QTextEdit.
It's no problem to get that information with
QFontMetrics::lineSpacing();
But how to set that?
I tried with StyleSheets, but that didn't work:
this->setStyleSheet("QTextEdit{ height: 200%; }");
or
this->setStyleSheet("QTextEdit{ line-height: 200%; }");
Partial solution:
Well, I've found a solution - not the way I wanted it, but at least it's simple and it gives nearly my intended behavior, enough for my proof of concept.
On every new line there's some linespacing. But if you just type until the text is automatically wrapped to a new line you wont have line-spacing between this two lines. This hack only works with text blocks, see the code.
Just keep in mind it's brute force and a ugly hack. But it provides some kind of line-spacing to your beautiful QTextEdit. Call it everytime your text changes.
void setLineSpacing(int lineSpacing) {
int lineCount = 0;
for (QTextBlock block = this->document()->begin(); block.isValid();
block = block.next(), ++lineCount) {
QTextCursor tc = QTextCursor(block);
QTextBlockFormat fmt = block.blockFormat();
if (fmt.topMargin() != lineSpacing
|| fmt.bottomMargin() != lineSpacing) {
fmt.setTopMargin(lineSpacing);
//fmt.setBottomMargin(lineSpacing);
tc.setBlockFormat(fmt);
}
}
}
The QFontMetrics contains (per the name) static properties that come from the font file. How wide a capital "C" is, etc. lineSpacing() gets you the natural distance in single-spacing that the person who designed the font encoded into the font itself. If you actually wanted to change that (you don't)...the somewhat complicated story of how is told here:
http://fontforge.sourceforge.net/faq.html#linespace
As for the line spacing in a QTextEdit...it looks (to me) like that is seen as one of the things that falls under Qt's extensibility model for specifying text "layouts":
http://doc.qt.io/qt-4.8/richtext-layouts.html
You would supply your own layout class to the QTextDocument instead of using the default. Someone tried it here but did not post their completed code:
http://www.qtcentre.org/threads/4198-QTextEdit-with-custom-space-between-lines
I know this is an old question, but I've spent a lot of time today trying to solve this for PyQt5 5.15.2. I'm posting my solution in case it is useful to others. The solution is for Python, but should be easily transferable.
The following code will change the line height to 150% for a populated QTextEdit widget in one go. Further editing will pick up the current block format, and continue applying it. I've found it to be very slow for large documents though.
textEdit = QTextEdit()
# ... load text into widget here ...
blockFmt = QTextBlockFormat()
blockFmt.setLineHeight(150, QTextBlockFormat.ProportionalHeight)
theCursor = textEdit.textCursor()
theCursor.clearSelection()
theCursor.select(QTextCursor.Document)
theCursor.mergeBlockFormat(blockFmt)
Applying blockformat to entire document rather than each line works.
QTextBlockFormat bf = this->textCursor().blockFormat();
bf.setLineHeight(lineSpacing, QTextBlockFormat::LineDistanceHeight) ;
this->textCursor().setBlockFormat(bf);
I have translated Jadzia626's code to C++ and it works. Here is the information about setLineHeight()
qreal lineSpacing = 35;
QTextCursor textCursor = ui->textBrowser->textCursor();
QTextBlockFormat * newFormat = new QTextBlockFormat();
textCursor.clearSelection();
textCursor.select(QTextCursor::Document);
newFormat->setLineHeight(lineSpacing, QTextBlockFormat::ProportionalHeight);
textCursor.setBlockFormat(*newFormat);

How to format the selected text in a QTextEdit by pressing a button

I want to format a selected text in a QTextEdit by clicking a button. For axample I want to make it bold if it is not-bold, or not-bold if it is bold. Please help me with an example.
EDIT:
Actually I have found already a code - qt demo for text editor which does what I need:
void
MyTextEdit::boldText(bool isBold) //this is the SLOT for the button trigger(bool)
{
QTextCharFormat fmt;
fmt.setFontWeight(isBold ? QFont::Bold : QFont::Normal);
mergeFormatOnWordOrSelection(fmt);
}
void
MyTextEdit::mergeFormatOnWordOrSelection(const QTextCharFormat &format)
{
QTextCursor cursor = m_textEdit->textCursor();
if (!cursor.hasSelection())
cursor.select(QTextCursor::WordUnderCursor);
cursor.mergeCharFormat(format);
m_textEdit->mergeCurrentCharFormat(format);
}
But I can't understand what returnes the textCursor() method, and how the merging of properties is being done? Just some formats are being changed, some of them stay constant. How mergeCharFormat function understands what to change and what to leave as is. Please explain me just these 2 things.
Thanks.
The textCursor() returns a textCursor that contains the position of the cursor you use in the textEdit, see QTextCursor in Qt classes. So by selecting the text that is contained by the cursor start and end position, you have the text that is currently highlited.
As for the mergeCharFormat, I guess that it is used to apply a new state (bold, italic, underlined) and to keep the existing ones. Say your text is already underlined and you apply bold, you would want to keep both.
Hope this helps.