为什么 cursor.clearselection() 在这个例子中不起作用

Why does cursor.clearselection() does not work in this example?

本文关键字:不起作用 cursor clearselection 为什么      更新时间:2023-10-16

我正在尝试创建一个按钮,该按钮为我的QTextEdit实例的选定文本添加下划线。

在构造函数中,我正在激活光标并为稍后使用的 setFontUnderline 方法设置一个布尔变量。

QTextCursor cursor1 = ui.myQTextfield->textCursor();
ui.myQTextfield->ensureCursorVisible();
test1 = false;

下面的第一种方法是通过按下下划线按钮来执行的,第二种方法是通过释放它来执行。

void Hauptfenster::pressed_underlinebutton()
{
    test1 = true;
    ui.myQTextfield->setFontUnderline(test1);   
}
void Hauptfenster::released_underlinebutton()
{
    cursor.clearSelection();
    test1 = false;
    ui.myQTextfield->setFontUnderline(test1);
}

问题是,使用此代码,所选文本首先由 pressed_underlinebutton() 方法下划线,然后立即使用 released_underlinebutton 方法取消下划线。

使用 released_underlinebutton() 方法,我想证明在再次设置 setfontunderline(false) 时没有更多的选择来取消下划线。

使用 QTextCursor 副本

文档需要更多阅读:

QTextCursor QTextEdit::textCursor() const

返回表示当前可见游标的 QTextCursor 的副本。请注意,对返回的游标所做的更改不会影响 QTextEdit 的游标;使用 setTextCursor() 更新可见光标。

它写道,您获得一个副本,因此当您尝试更改文本光标功能时,您是在对副本而不是原始副本进行操作。

因此,您应该确保如果希望更改在文本编辑控件上生效,则需要按如下方式设置文本光标:

cursor.clearSelection();
ui.myQTextfield->setTextCursor(cursor); // o/

直接移动QTextEdit的光标

但是,还有另一种方法可以解决此问题。

QTextCursor::Left   9   Move left one character.
QTextCursor::End    11  Move to the end of the document.

所以,你会写这样的东西:

ui.myQTextfield->moveCursor(QTextCursor::End)
ui.myQTextfield->moveCursor(QTextCursor::Left)