Bonsoir,

J'ai créer une fonction du type Ctrl+F, qui à partir d'un mot entré dans une lineEdit et un bouton "find", recherche toutes occurrences du mot entré dans un textEdit.

Plus précisément, j'ai un champ (lineEdit) qui me permet d'entré le mot que je souhaites recherché et un champ (textEdit) qui contient du texte.
Lorsqu'on clique sur le bouton "find", tous les mots trouvés sont surlignés en jaune.

Ce que je souhaites faire, c'est de stocké les positions du curseur de tout les mots trouvés dans un tableau par exemple. Le but c'est qu'à chaque fois que je cliquerais sur le bouton "find", le curseur se déplace automatiquement à l'occurrence suivante dans le textEdit.

Voici le code :

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
void TextFinder::on_findButton_clicked()
{
    initText();
 
    QString searchString = ui->lineEdit->text();
 
    QTextDocument *document = ui->textEdit->document();
    QTextCursor highlightCursor(document);
    QTextCursor cursor(document);
 
    cursor.beginEditBlock();
 
    QTextCharFormat plainFormat(highlightCursor.charFormat());
    QTextCharFormat colorFormat = plainFormat;
    colorFormat.setBackground(Qt::yellow);
    QTextCharFormat colorFormat2 = plainFormat;
    colorFormat2.setBackground(Qt::white);
 
    while(!highlightCursor.isNull() && !highlightCursor.atEnd()){
        highlightCursor = document->find(searchString, highlightCursor, QTextDocument::FindWholeWords);
        if(!highlightCursor.isNull()){
            highlightCursor.movePosition(QTextCursor::EndOfWord,QTextCursor::KeepAnchor);
            highlightCursor.mergeCharFormat(colorFormat);
        }
    }
 
    cursor.endEditBlock();
}
Merci