QPlainTextEdit获得当前光标行的行号

QTextDocument的结构之复杂是不用不知道, 一用吓一跳。 连获得光标行号这么个简单问题都要拐上七八个弯。
下面是一个比较标准的解决方案:
//get the current line number
QTextCursor tc = edit->textCursor();//当前行的光标
QTextLayout* lo = tc.block().layout();
//get the relative position in the block
int pos = tc.position() – tc.block().position();//当前光标在本block内的相对位置
int line = lo->lineForTextPosition(pos).lineNumber() + tc.block().firstLineNumber();//用block的text layout计算光标在本block的行号, 需要传入光标相对于block的位置
qWarning() << line;

还有一个有点土的方法, 但代码稍微少点, 就是计算"\n"出现的次数代替行数, 当然有可能某些情况下会出bug, 请酌情使用:
int position = edit->textCursor().position();

qDebug() << edit->toPlainText().left(position).count(“\n”);

感觉这部分API设计得很乱, 非常不符合Qt的API设计intuitive的理念, 很需要改进。

Tags: , , ,
This entry was posted on Thursday, July 8th, 2010 at 11:14 PM and is filed under C++, Qt技术. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

One Response to “QPlainTextEdit获得当前光标行的行号”

  1. sol says:

    …没这么复杂:
    int line = edit->textCursor().blockNumber(); // zero based

Leave a Reply