更改QTextEdit中的文本

时间:2014-03-02 15:28:12

标签: c++ qt qtextedit qregexp qtextcursor

您好我正在尝试创建一个功能来扫描QTextEdit,搜索电子邮件地址和电话号码并将其更改为粗体。当我运行它时,它崩溃了我的程序,错误“QTextCursor :: setPosition:Position'-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 != 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++;
    }

}

1 个答案:

答案 0 :(得分: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;
           }
    }
}