1

嗨,我正在尝试创建一个功能来扫描 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++;
    }

}
4

1 回答 1

2

您需要搜索,直到没有找到更有趣的东西:

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;
           }
    }
}
于 2014-03-02T19:56:51.870 回答