テキスト検索
QUiLoader を使用して .ui ファイルを動的に読み込む。
TextFinderのサンプルでは、QUiLoader クラスを用いて.ui ファイルを動的に読み込み、設定する方法を示しています。このクラスは Qt UI Tools ライブラリの一部であるxml-ph-0001@deepl.internalクラスを使用して、xml-ph-0000@deepl.internalファイルを動的に読み込み、設定する方法を示しています。
このプログラムでは、ユーザーがテキストの内容の中から特定の単語を検索することができます。ユーザーインターフェースの視覚的要素とレイアウトは、実行時にプログラムのリソースから読み込まれます。
![]() | ![]() |
リソースファイルの設定
このサンプルに必要なリソースは以下の通りです:
textfinder.ui- 以下のディレクトリに作成されたユーザーインターフェースファイル Qt Widgets Designerinput.txt- に表示されるテキストを含むテキストファイルQTextEdit
textfinder.ui には、Text Finderに必要なすべてのQWidget オブジェクトが含まれています。ユーザー入力にはQLineEdit が、input.txt の内容を表示するにはQTextEdit が、テキスト「Keyword」を表示するにはQLabel が、Find ボタンにはQPushButton が使用されています。なお、すべてのウィジェットには、識別しやすいobjectName が割り当てられています。これらはコード内で各ウィジェットを識別するために使用されます。
以下のスクリーンショットは、 Qt Widgets Designerで取得されたプレビューを示しています。

この例では、textfinder.qrc ファイルをインクルードすることで、両方のリソースをアプリケーションの実行ファイル内に格納しています。あるいは、ファイルシステムから、または外部バイナリリソース.rcc ファイルから、実行時にこれらのファイルを読み込むことも可能です。リソースファイルの詳細については、『The Qt Resource System』を参照してください。
textfinder.qrc ファイルには、リソースとして含めるべきすべてのファイルが列挙されています:
<!DOCTYPE RCC><RCC version="1.0">
<qresource>
<file>forms/textfinder.ui</file>
<file>forms/input.txt</file>
</qresource>
</RCC>実行時にフォームを生成するために、このサンプルはQt UI Toolsライブラリに対してリンクされています。これはtextfinder.pro ファイル内で次のように行われます:
QT += widgets uitools
HEADERS = textfinder.h
SOURCES = textfinder.cpp main.cpp
RESOURCES = textfinder.qrcTextFinderクラスの定義
TextFinder クラスには、メインのユーザーインターフェースが含まれています。このクラスでは、前述のQPushButton 、QTextEdit 、QLineEdit 要素へのポインタが宣言されています。ユーザーインターフェース内のQLabel については、コードからアクセスする必要がないため、ここでは宣言されていません。
class TextFinder : public QWidget
{
Q_OBJECT
public:
explicit TextFinder(QWidget *parent = nullptr);
private slots:
void on_findButton_clicked();
private:
QPushButton *ui_findButton;
QTextEdit *ui_textEdit;
QLineEdit *ui_lineEdit;
};スロット `on_findButton_clicked() ` は、uic で要求される「自動接続(Automatic Connection)」の命名規則に従って命名されたスロットです。
リソースの読み込み
QFile を使用して、実行時にプログラムリソースからデータを読み込みます。この処理を行うコードは、textfinder.cpp の最上部に定義されている 2 つのメソッド、loadUiFile およびloadTextFile にあります。
loadUiFile 関数は、以前に作成されたユーザーインターフェースファイルを Qt Widgets Designer。まず、リソースシステムからtextfinder.ui ファイルが検索され、開かれます。次に、QUiLoader インスタンスが作成され、QUiLoader::load()関数が呼び出されます。この際、第1引数には開かれたファイルが、第2引数には親として設定すべきウィジェットのポインタが渡されます。作成されたQWidget が返されます。
staticQWidget*loadUiFile(QWidget*parent)
{
QFile file(u":/forms/textfinder.ui"_s);
if(!file.open(QIODevice::ReadOnly))
qFatal("Cannot open resource file");
returnQUiLoader().load(&file,parent);
}同様に、loadTextFile 関数は、resourcesからinput.txt を検索して開きます。その後、QTextStream::readAll()関数を使用して、そのファイルの内容を返します。
staticQString loadTextFile()
{
QFile inputFile(u":/forms/input.txt"_s);
if(!inputFile.open(QIODevice::ReadOnly))
qFatal("Cannot open resource file");
returnQTextStream(&inputFile).readAll();
}TextFinderクラスの実装
TextFinder クラスのコンストラクタは、子ウィジェットを直接インスタンス化しません。代わりに、loadUiFile() 関数を呼び出し、その後QObject::findChild()を使用して、作成されたQWidgetをオブジェクト名で特定します。
TextFinder::TextFinder(QWidget *parent)
: QWidget(parent)
{
QWidget *formWidget = loadUiFile(this);
ui_findButton = findChild<QPushButton*>("findButton");
ui_textEdit = findChild<QTextEdit*>("textEdit");
ui_lineEdit = findChild<QLineEdit*>("lineEdit");その後、QMetaObject::connectSlotsByName() を使用して、on_findButton_clicked() スロットが自動的に呼び出されるようにします。
QMetaObject::connectSlotsByName(this);loadTextFile 関数は、QTextEdit に表示するテキストを取得するために呼び出されます。
ui_textEdit->setText(loadTextFile());formWidget 内の動的に読み込まれるユーザーインターフェースが、これで正しく設定されました。次に、QVBoxLayout を通じてformWidget を埋め込みます。
auto *layout = new QVBoxLayout(this);
layout->addWidget(formWidget);コンストラクタの最後に、ウィンドウのタイトルを設定しています。
setWindowTitle(tr("Text Finder"));
}on_findButton_clicked() 関数は、ui_findButton のclicked() シグナルに接続されたスロットです。searchString はui_lineEdit から抽出され、document はui_textEdit から抽出されます。searchString が空の場合、QMessageBox が使用され、ユーザーに単語の入力を求めます。 それ以外の場合は、ui_textEdit 内の単語を順に処理し、searchString の出現箇所をすべてハイライトします。2つのQTextCursorオブジェクトが使用されます。1つはline 内の単語を順に処理するため、もう1つは編集ブロックを追跡するために使用されます。
void TextFinder::on_findButton_clicked()
{
QString searchString = ui_lineEdit->text();
QTextDocument *document = ui_textEdit->document();
bool found = false;
// undo previous change (if any)
document->undo();
if (searchString.isEmpty()) {
QMessageBox::information(this, tr("Empty Search Field"),
tr("The search field is empty. "
"Please enter a word and click Find."));
} else {
QTextCursor highlightCursor(document);
QTextCursor cursor(document);
cursor.beginEditBlock();
QTextCharFormat plainFormat(highlightCursor.charFormat());
QTextCharFormat colorFormat = plainFormat;
colorFormat.setForeground(Qt::red);
while (!highlightCursor.isNull() && !highlightCursor.atEnd()) {
highlightCursor = document->find(searchString, highlightCursor,
QTextDocument::FindWholeWords);
if (!highlightCursor.isNull()) {
found = true;
highlightCursor.movePosition(QTextCursor::WordRight,
QTextCursor::KeepAnchor);
highlightCursor.mergeCharFormat(colorFormat);
}
}
cursor.endEditBlock();found フラグは、searchString がui_textEdit の内容内で見つかったかどうかを示すために使用されます。見つからなかった場合は、QMessageBox を使用してユーザーに通知します。
if (found == false) {
QMessageBox::information(this, tr("Word Not Found"),
tr("Sorry, the word cannot be found."));
}
}
}main() 関数
main() 関数は、TextFinder をインスタンス化して表示します。
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
TextFinder textFinder;
textFinder.show();
return app.exec();
}アプリケーションにフォームを組み込むには、さまざまな方法があります。QUiLoader を使用するのは、そのうちの 1 つにすぎません。利用可能な他の方法の詳細については、「アプリケーションでのQt Widgets Designer UI ファイルの使用」を参照してください。
「Calculator Builder」も参照してください 。
© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.

