summaryrefslogtreecommitdiffstats
path: root/src/gui/doc/snippets/textdocument-find/main.cpp
blob: 4b3948b114108ffa1661f2b0992fd5c1da14f239 (plain)
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
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QApplication>
#include <QTextEdit>

QString tr(const char *text)
{
    return QApplication::translate(text, text);
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QTextEdit *editor = new QTextEdit();

    QTextCursor cursor(editor->textCursor());
    cursor.movePosition(QTextCursor::Start);

    QTextCharFormat plainFormat(cursor.charFormat());
    QTextCharFormat colorFormat = plainFormat;
    colorFormat.setForeground(Qt::red);

    cursor.insertText(tr("Text can be displayed in a variety of "
                                  "different character "
                                  "formats. "), plainFormat);
    cursor.insertText(tr("We can emphasize text by making it "));
    cursor.insertText(tr("italic, give it a different color "));
    cursor.insertText(tr("to the default text color, underline it, "));
    cursor.insertText(tr("and use many other effects."));

    QString searchString = tr("text");

    QTextDocument *document = editor->document();
//! [0]
    QTextCursor newCursor(document);

    while (!newCursor.isNull() && !newCursor.atEnd()) {
        newCursor = document->find(searchString, newCursor);

        if (!newCursor.isNull()) {
            newCursor.movePosition(QTextCursor::WordRight,
                                   QTextCursor::KeepAnchor);

            newCursor.mergeCharFormat(colorFormat);
        }
//! [0] //! [1]
    }
//! [1]

    editor->setWindowTitle(tr("Text Document Find"));
    editor->resize(320, 480);
    editor->show();
    return app.exec();
}