【问题标题】:Retain the cursor position in QTextEdit在 QTextEdit 中保留光标位置
【发布时间】:2013-06-19 04:35:10
【问题描述】:

我有一个 QTextEdit 控件。它有一个最大限制(它可以容纳的最大字符数)。为了实现这一点,我将一个插槽连接到 textChanged() 信号,当字符总数超过允许的最大值时,它会删除多余的字符。

有了这个,我在处理光标位置时遇到了一些问题。谁能告诉我如何在 QTextEdit 中保留光标位置?

【问题讨论】:

    标签: c++ qt qlineedit


    【解决方案1】:

    在你的位置上:

    如果字符数超过最大值:

    向 QTextEdit 询问光标:

    QTextCursor QTextEdit::textCursor() const

    将返回值设置为您的 textEdit 光标(因为它返回一个副本)。来自文档:

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

    void QTextEdit::setTextCursor(const QTextCursor & cursor)

    要求光标删除最后一个字符

    void QTextCursor::deletePreviousChar()

    (编辑)代码:

    QTextCursor  cursor = ui->textEdit->textCursor();
    ui->textEdit->setTextCursor( cursor );
    cursor.deletePreviousChar();
    

    【讨论】:

    • QTextCursor cursor = ui->textEdit->textCursor(); ui->textEdit->setTextCursor( cursor );
      写上面两行有什么意义?它只是获取光标位置并设置它。
    • 文档:Returns a copy of the QTextCursor that represents the currently visible cursor. Note that changes on the returned cursor do not affect QTextEdit's cursor; use setTextCursor() to update the visible cursor.
    【解决方案2】:

    如果数字超过限制或输入错误的字符,我正在使用:

    ui->textEdit->textCursor().deletePreviousChar();
    

    【讨论】:

      猜你喜欢
      • 2014-07-18
      • 2015-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-16
      • 2019-01-04
      相关资源
      最近更新 更多