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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QTextEdit>
#include <QSyntaxHighlighter>
class MyHighlighter : public QSyntaxHighlighter
{
public:
MyHighlighter(QTextDocument *document)
: QSyntaxHighlighter(document)
{
}
void setPattern(const QString &pattern)
{
_pattern = pattern; // Change la chaîne recherchée
rehighlight(); // Permet d'effacer tout le style et de recolorer le tout (cela appelle highlightBlock, ci-dessous)
}
void highlightBlock(const QString &text)
{
if (_pattern.isEmpty()) // On ne fait rien si on n'a pas de sélection
return;
QTextCharFormat format; // Format du texte sélectionné
format.setFontItalic(true);
format.setForeground(Qt::red);
QRegExp expression(_pattern); // Pattern, comme dans l'exemple de la doc
int index = text.indexOf(expression); // On cherche la première occurrence du texte cherché
while (index >= 0) // Tant qu'on a des occurrences du texte cherché
{
int length = expression.matchedLength(); // Récupération de la taille de la sélection (on peut remplacer ça par _pattern.lenght() si on veut)
setFormat(index, length, format); // Application du style au texte trouvé
index = text.indexOf(expression, index + length); // On cherche l'occurrence suivante du texte cherché pour repartir sur un tour de boucle
}
}
private:
QString _pattern; // Le texte cherché
};
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow() : QMainWindow()
{
_edit = new QTextEdit; // Création d'un textEdit
_highlighter = new MyHighlighter(_edit->document()); // Création d'un Highlighter
setCentralWidget(_edit); // Le textEdit prend la taille de la fenêtre
connect(_edit, SIGNAL(selectionChanged()), this, SLOT(rehighlightText())); // Slot à appeler à chaque changement de sélection
}
private slots:
void rehighlightText()
{
disconnect(_edit, SIGNAL(selectionChanged()), this, SLOT(rehighlightText())); // Déconnexion pour éviter une récursion infinie vu que le syntax highlighter mène le signal selectionChanged() a être ré-appelé
_highlighter->setPattern(_edit->textCursor().selectedText()); // Changement de la chaîne à colorer
connect(_edit, SIGNAL(selectionChanged()), this, SLOT(rehighlightText())); // Reconnexion pour rétablir les appels
}
private:
QTextEdit *_edit;
MyHighlighter *_highlighter;
};
#endif // MAINWINDOW_H |
Partager