Qt QTextBrowser/QTextEdit: Tab键改变bullet/ordered列表缩进

Qt QTextBrowser/QTextEdit: Tab key changes bullet/ordered list indentation

我正在使用 C++ 和 Qt6,我正在创建一个文本编辑器,它可以为使用它的人模仿 Word 或 Evernote 的基本功能。 我希望当用户按下按键选项卡时发生这种情况:

第二颗子弹是我得到的,第三颗子弹是我想要的。

我已准备好此代码:

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);
}

有没有一种方法可以更改在聚焦的 QTextEdit 中按下 Tab 键时的功能?

我已经解决了!

我为继承 QMainWindow 的 class 实例重新实现了 QMainWindow eventFilter。

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

使用这种方法,我能够将“Tab 键”连接到我自己在 OP 中实现的插槽。

最后:

ui->textEditor->installEventFilter(this);