QTextEdit - 获取选择行号

Joh*_*ing 5 c++ qt text qt4 qtextedit

我有以下代码(在mouseReleaseEvent中实现)来检测用户何时选择了文本行:

    QTextCursor cursor = this->textCursor();
    int start = cursor.selectionStart();
    int end = cursor.selectionEnd();

    if(!cursor.hasSelection())
        return; // No selection available

    qWarning() << "start: " << start << " end: " << end << endl;
Run Code Online (Sandbox Code Playgroud)

问题是:我需要选择开始和结束的行号.我一直在努力解决问题并且什么也没解决,你能不能给我一个线索?

Bal*_*des 5

有可能,它不是最好的解决方案,但似乎对我有用.变量selectedLines将包含选择的行数.

QTextCursor cursor = ui->plainTextEdit->textCursor();
int selectedLines = 0; //<--- this is it 
if(!cursor.selection().isEmpty())
{
    QString str = cursor.selection().toPlainText();
    selectedLines = str.count("\n")+1;
}
Run Code Online (Sandbox Code Playgroud)

我希望,它会有所帮助:)