Search code examples
c++qttabsqt5desktop-application

QTextEdit: Tab key changes bullet list indentation


I am using C++ and Qt6. I have a QTextEdit that accepts rich text. When I press the tab key, formatting changes to this:

enter image description here

The result I want is the 3rd bullet, but what I am getting is the second bullet. Any ideas?

I already implemented a slot that gets called when my "Increase Indentation" button gets called and its the functionality I want pressing the tab key to achieve:

void SummaryWindow::changeListIndentation(int increment)
{
QTextCursor cursor = ui->textEditor->textCursor();
QTextList *currentList = cursor.currentList();

if(currentList)
{
    QTextListFormat listFormat;
    QTextListFormat::Style currentStyle = currentList->format().style();
    listFormat.setIndent(cursor.currentList()->format().indent() + increment);
    if (currentStyle == QTextListFormat::ListDisc || currentStyle == QTextListFormat::ListCircle || currentStyle == QTextListFormat::ListSquare)
    {
        if (listFormat.indent() == 1){listFormat.setStyle(QTextListFormat::ListDisc);}
        if (listFormat.indent() == 2){listFormat.setStyle(QTextListFormat::ListCircle);}
        if (listFormat.indent() >= 3){listFormat.setStyle(QTextListFormat::ListSquare);}
    }
    if (currentStyle == QTextListFormat::ListDecimal || currentStyle == QTextListFormat::ListUpperAlpha || currentStyle == QTextListFormat::ListLowerAlpha)
    {
        if (listFormat.indent() == 1){listFormat.setStyle(QTextListFormat::ListDecimal);}
        if (listFormat.indent() == 2){listFormat.setStyle(QTextListFormat::ListUpperAlpha);}
        if (listFormat.indent() >= 3){listFormat.setStyle(QTextListFormat::ListLowerAlpha);}
    }
    currentList->setFormat(listFormat);
}
else
{
    QTextBlockFormat blockFormat = cursor.block().blockFormat();
    blockFormat.setIndent( increment == 1 ? blockFormat.indent() + 1 : (blockFormat.indent() == 0 ? 0 : blockFormat.indent() - 1));
    cursor.setBlockFormat(blockFormat);
}
}

Solution

  • bool SummaryWindow::eventFilter(QObject *obj, QEvent *event)
    {
        if (obj == ui->textEditor && event->type() == QEvent::KeyPress)
        {
    
            QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
            if (keyEvent->key() == Qt::Key_Tab)
            {
                this->changeListIndentation(1);
                return true;
            }
            else if (keyEvent->key() == Qt::Key_Backtab)
            {
                this->changeListIndentation(-1);
                return true;
            }
        }
            return QMainWindow::eventFilter(obj, event);
    }