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

时间:2014-12-25 16:46:55

标签: c++ qt qtgui qtextedit qtextcursor

我正在尝试创建一个按钮,用于强调我QTextEdit实例的选定文本。

在构造函数中,我正在激活游标并为稍后使用的setFontUnderline方法设置bool变量。

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)时再没有选择去下划线。

1 个答案:

答案 0 :(得分:2)

使用QTextCursor副本

文档需要更多阅读:

  

QTextCursor QTextEdit::​textCursor() const

     

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

它写道您获得了副本,因此当您尝试更改文本光标功能时,您正在复制而不是原始文件。

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

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

直接移动QTextEdit的光标

然而,

There is another way to solve this issue

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)
相关问题