【问题标题】:Qt QTextBrowser/QTextEdit: Tab key changes bullet/ordered list indentationQt QTextBrowser/QTextEdit:Tab 键更改项目符号/有序列表缩进
【发布时间】:2021-09-15 00:31:11
【问题描述】:

我正在使用 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);
}

有没有一种方法可以改变 Tab 键在焦点 QTextEdit 中按下时的作用?

【问题讨论】:

    标签: c++ qt qt5 desktop-application qt6


    【解决方案1】:

    我已经解决了!

    我为继承 QMainWindow 的类实例重新实现了 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 Key”连接到我自己在 OP 中实现的插槽。

    最后:

    ui->textEditor->installEventFilter(this);
    

    【讨论】:

    • 代码不是很干净,但我想了解这个概念。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    相关资源
    最近更新 更多