Изменение текста в QTextEdit

Привет, я пытаюсь создать функцию для сканирования QTextEdit, поиска адресов электронной почты и номеров телефонов и выделения их жирным шрифтом. Когда я запускаю его, моя программа вылетает с ошибкой "QTextCursor::setPosition: Position '-1' out of range", вот код:

void MakeDisplay::processDoc(){
    QString doc = text->toPlainText();
    QTextCursor cursor = text->textCursor();
    QTextCharFormat format;
    format.setFontWeight(75);
    QRegExp emails("*.@.*");
    QRegExp phoneNums
    ("(\\d{3}-\\d{3}-\\d{4})(\\d{3}-\\d{7})(\\d{10})(\\(\\d{3}\\)\\d{3}-\\d{4})(\\(\\d{3}\\)\\d{7})");
    int i, j;
    i = 0;
    j = 0;
    while (!cursor.atEnd() || (i != doc.size())){
        i = doc.indexOf(emails);
        j = doc.indexOf(phoneNums);
        cursor.setPosition(i,QTextCursor::MoveAnchor);
        cursor.setPosition(i, QTextCursor::KeepAnchor);
        cursor.mergeCharFormat(format);
        cursor.setPosition(j,QTextCursor::MoveAnchor);
        cursor.setPosition(j, QTextCursor::KeepAnchor);
        cursor.mergeCharFormat(format);
        i++;
        j++;
    }

}

person Dmon    schedule 02.03.2014    source источник
comment
Проверьте возврат функций doc.indexOf().   -  person elephant    schedule 02.03.2014


Ответы (1)


Искать нужно до тех пор, пока ничего более интересного не будет найдено:

void MakeDisplay::processDoc(){
    QString doc = text->toPlainText();
    QTextCursor cursor = text->textCursor();
    QTextCharFormat format;
    format.setFontWeight(75);
    QRegExp emails("*.@.*");
    QRegExp phoneNums
    ("(\\d{3}-\\d{3}-\\d{4})(\\d{3}-\\d{7})(\\d{10})(\\(\\d{3}\\)\\d{3}-\\d{4})(\\(\\d{3}\\)\\d{7})");
    int i, j;
    i = 0;
    j = 0;
    while (!cursor.atEnd()&& (i!=-1||j!=-1))
    {
        if(i!=-1)
        {
           i = doc.indexOf(emails);
           if(i!=-1)
           {       
              cursor.setPosition(i,QTextCursor::MoveAnchor);
              cursor.setPosition(i, QTextCursor::KeepAnchor);
              cursor.mergeCharFormat(format);
              ++i;
           }
        }
        if(j!=-1)
        {
           j = doc.indexOf(phoneNums);
           if(j!=-1)
           {
              cursor.setPosition(j,QTextCursor::MoveAnchor);
              cursor.setPosition(j, QTextCursor::KeepAnchor);
              cursor.mergeCharFormat(format);
              ++j;
           }
    }
}
person user2672165    schedule 02.03.2014