在插槽断开连接时清除ExtraSelections Qt

Clear ExtraSelections Qt on slot disconnect

本文关键字:清除 ExtraSelections Qt 连接 插槽 断开      更新时间:2023-10-16

我在QT QTextEdit中实现了一个聚焦模式,在该模式中,我高亮显示光标所在的单行。到目前为止,我可以启用对焦模式,但当我禁用对焦模式时,我希望状态恢复到原来的状态。

调用连接和断开连接的功能是:

void MainWindow::onFocus_Mode_triggered()
{
    QTextEdit *texed = qobject_cast<QTextEdit*>(ui->tabWidget->currentWidget());
    if(ui->actionFocus_Mode->isChecked()){
        connect(texed, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine()));
    } 
    else {
        disconnect(texed, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine())); //First disconnect and then call method to clear ExtraSelections
        BacktoNormal(); //Help needed in implementing this
    }
}

现在,当菜单项actionFocus_Mode被选中时,光标当前所在的行将通过下面给出的函数以黄色突出显示。

void MainWindow::highlightCurrentLine() {
    QTextEdit *texed = qobject_cast<QTextEdit*>(ui->tabWidget->currentWidget());
    QList<QTextEdit::ExtraSelection> extraSelections;
    QTextEdit::ExtraSelection selection;
    QColor lineColor = QColor(Qt::yellow).lighter(160);
    selection.format.setBackground(lineColor);
    selection.format.setProperty(QTextFormat::FullWidthSelection, true);
    selection.cursor = texed->textCursor();
    selection.cursor.clearSelection();
    extraSelections.append(selection);
    texed->setExtraSelections(extraSelections);
}

所以我可以用黄色突出显示它,但如果(!ui->actionFocus_Mode->isChecked()),即如果菜单项(焦点模式)未选中,那么我希望恢复到正常模式。如何实现BacktoNormal()函数。

我现在的想法是,我应该将lineColor设置为透明或其他什么,以使其恢复正常(如果可能的话)。我找不到与此相关的任何信息。任何帮助都是有用的,因为我完全陷入了困境。

BackNormal中,尽量不将任何内容设置为额外选择。

    QTextEdit *texed = qobject_cast<QTextEdit*>(ui->textEdit);
    QList<QTextEdit::ExtraSelection> extraSelections;
    QTextEdit::ExtraSelection selection;
    QColor lineColor = QColor(Qt::yellow).lighter(160);
    selection.format.setBackground(lineColor);
    selection.format.setProperty(QTextFormat::FullWidthSelection, true);
    selection.cursor = texed->textCursor();
    selection.cursor.clearSelection();
    extraSelections.append(selection);
    extraSelections.clear();//nothing
    texed->setExtraSelections(extraSelections);

我什么时候在我的计算机上尝试过这个(使用另一个代码),这个选择被成功删除了。

较小版本:

    QTextEdit *texed = qobject_cast<QTextEdit*>(ui->textEdit);
    QList<QTextEdit::ExtraSelection> extraSelections;//empty list
    texed->setExtraSelections(extraSelections);