PyQt5チュートリアル(サンプル付き):作成 Python Qtを使用したGUI

⚡ スマートサマリー

PyQt is a Python binding for the cross-platform Qt widget toolkit, letting developers build native desktop GUIs. It wraps more than six hundred C++ classes covering windows, buttons, layouts, signals, slots, and themes for Windows, macOS、およびLinux。

  • 🔘 What is PyQt: A Python binding for the Qt C++ framework, maintained by Riverbank Computing.
  • ☑️ バージョン: PyQt4 binds Qt 4.x and 5.x; PyQt5 targets only the Qt 5.x series.
  • インストール: The pip package manager installs PyQt5 from a wheel with a single command.
  • 🧪 First app: QApplication and QWidget create and display a basic window on screen.
  • 🛠️ Signals and slots: Widget events raise signals that connect to Python slot functions.
  • 🤖 AI対応準備完了: PyQt builds desktop front-ends that run and visualize machine learning models.

PyQt5 チュートリアル

The sections below take you from PyQt basics through installation, core widgets, layouts, and themes with runnable examples.

PyQtとは何ですか?

PyQt   Python binding of the open-source widget-toolkit Qt, which also functions as a cross-platform application development framework. Qt is a popular C++ framework for writing GUI applications for all major desktop, mobile, and embedded platforms (it supports Linux, Windows, macOS, Android、iOS、Raspberry Piなど)。

PyQt is free software developed and maintained by Riverbank Computing, a company based in England, whereas Qt is developed by a Finnish firm called The Qt Company.

Features of PyQt

PyQt の重要な機能は次のとおりです。

PyQt consists of more than six hundred classes covering a range of features such as:

  • グラフィカルユーザーインターフェイス
  • SQLデータベース
  • ウェブツールキット
  • XML処理
  • Networking

These features can be combined to create advanced UIs as well as standalone applications. A lot of major companies across all industries use Qt. Some examples are LG, Mercedes, AMD, Panasonic, and Harman.

PyQt のバージョン

PyQt is available in two editions, PyQt4 and PyQt5. PyQt4 provides glue code for binding 4.x and 5.x versions of the Qt framework while PyQt5 provides a binding for only the 5.x versions. As a result, PyQt5 is not backward compatible with the deprecated modules of the older version. In this PyQt GUI tutorial, PyQt5 will be used for the demonstration of examples. Apart from these two versions, Riverbank Computing also provides PyQt3D—the Python bindings for the Qt3D framework. Qt3D is an application framework used to create real-time simulation systems with 2D/3D rendering.

PyQt5のインストール方法

この PyQt5 チュートリアルでは、PyQt をインストールする XNUMX つの方法について説明します。

  • Wheel ファイルの使用
  • ソースからのビルドとインストール

Qt(キュートと発音)は複雑なシステムであり、PyQtのコードベースにはコンパイルされた C++ (NAIST) と Python code under the hood. As a result, it is a complicated process to build and install it from the source compared to other Python libraries. However, you can easily install PyQt5 using wheels.

車輪付きの設置

ホイールは新しい標準です Python パッケージングおよび配布形式。簡単に言えば、ホイールは特別な名前と .うーん ファイル拡張子。ホイールはpip(Pythonのパッケージマネージャ)は、最近のバージョンの Python.

だから、あなたが持っているなら Python 3.4以降がインストールされている場合は、すでにpipがインストールされています。ただし、古いバージョンを使用している場合は、 Python, you must download and install pip before going forward. You can search for instructions at this link: https://pypi.org/project/pip/.

To install PyQt5:

ステップ1) コマンドプロンプトを開きます。
コマンド プロンプトまたは PowerShell を開きます。 Windows 機械。

PyQt5をインストールする

ステップ2) 以下を入力してください。

 pip install PyQt5

ステップ3) インストールに成功。
この PyQt5 チュートリアルのこのステップでは、PyQt5 whl パッケージ (約 50 MB) をダウンロードし、システムにインストールします。

PyQt5をインストールする

あるいは、 Windows binary for the version of Python あなたのコンピュータにインストールされます。

完了したら、この PyQt5 チュートリアルの次のセクションに進み、最初の GUI アプリを作成します。

基本的な PyQt Concepts とプログラム

Now that you have successfully installed PyQt5 on your computer, you are ready to write Python GUI applications.

Let us start with a simple app in this PyQt5 tutorial which will display an empty window on your screen.

火をつけろ Python IDLE 次のように入力します。

プログラム1

import sys
from PyQt5.QtWidgets import QApplication, QWidget
if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = QWidget()
    w.resize(300,300)
    w.setWindowTitle("Guru99")
    w.show()
    sys.exit(app.exec_())

app.py という名前で保存し(名前は問いません)、F5 キーを押してプログラムを実行します。または、保存したファイルをダブルクリックしてアプリケーションを起動することもできます。すべて正しく操作していれば、タイトルが表示された新しいウィンドウが開きます。 Guru下記に示すように99。

基本的な PyQt Concepts

Great! It is working. It is not much, but it is enough to grasp the basics. Now in this PyQt tutorial, let us see in detail what each of the lines in your program does.

from PyQt5.QtWidgets import QApplication, QWidget

このステートメントは、GUIを作成するために必要なすべてのモジュールを現在の名前空間にインポートします。QtWidgetsモジュールには、このチュートリアルで使用するすべての主要なウィジェットが含まれています。 Python Qt チュートリアル。

app = QApplication(sys.argv)

ここでは、QApplication クラスのオブジェクトを作成しています。 このステップは PyQt5 では必須です。 すべての UI アプリは、アプリへの一種のエントリ ポイントとして、QApplication のインスタンスを作成する必要があります。 作成しないとエラーが表示されます。

sys.argv は、シェル経由でアプリケーションを起動するとき、またはインターフェイスを自動化するときにアプリケーションに渡すことができるコマンドライン パラメーターのリストです。

In this PyQt5 example, you did not pass any arguments to QApplication. Therefore, you can also replace it with the code below and not even have to import the sys module.

app = QApplication([])
w = QWidget()

次に、QWidget クラスのオブジェクトを作成します。QWidget は Qt のすべての UI オブジェクトの基本クラスであり、アプリに表示されるほぼすべてのものがウィジェットです。これには、ダイアログ、テキスト、ボタン、バーなどが含まれます。複雑なユーザー インターフェイスを設計できる機能は、ウィジェットをネストできることです。つまり、ウィジェットの中にウィジェットを配置し、そのウィジェットの中にさらに別のウィジェットを配置することができます。次のセクションでは、この動作を確認します。

w.resize(300,300)

QWidget クラスのsizeメソッドを使用すると、任意のウィジェットの寸法を設定できます。 この場合、ウィンドウのサイズを 300 ピクセル x 300 ピクセルに変更しました。

Here, you should remember that widgets could be nested together; the outermost widget (i.e., the widget with no parent) is called a Window.

w.setWindowTitle("Guru99")

setWindowTitle() メソッドでは、引数として文字列を渡すことで、ウィンドウのタイトルをその文字列に設定できます。PyQt5 の例では、タイトルバーには次のように表示されます。 Guru99.

w.show()

show() は単にウィジェットをモニター画面に表示するだけです。

sys.exit(app.exec_())

app.exec_() メソッドは Qt/ を起動しますC++ イベントループ。ご存知のとおり、PyQtは主に C++ and uses the event loop mechanism to implement parallel execution. app.exec_() passes the control over to Qt, which will exit the application only when the user closes it from the GUI. That is why ctrl+c will not exit the application as in other Python programs. Since Qt has control over the app, Python events are not processed unless we set them up inside the application. Also, note that the exec method has an underscore in its name; this is because exec() was already a keyword in Python and the underscore resolves the naming conflict.

空っぽの窓の向こう側

In the previous section, you saw how to make a basic widget in Qt. It is now time to make some more involved interfaces with which the users can truly interact. Again, fire up your IDLE 次のように書いてください。

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QMessageBox

def dialog():
    mbox = QMessageBox()

    mbox.setText("Your allegiance has been noted")
    mbox.setDetailedText("You are now a disciple and subject of the all-knowing Guru")
    mbox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
            
    mbox.exec_()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = QWidget()
    w.resize(300,300)
    w.setWindowTitle("Guru99")
    
    label = QLabel(w)
    label.setText("Behold the Guru, Guru99")
    label.move(100,130)
    label.show()

    btn = QPushButton(w)
    btn.setText('Beheld')
    btn.move(110,150)
    btn.show()
    btn.clicked.connect(dialog)

    
    w.show()
    sys.exit(app.exec_())

Save the file as appone.py or anything you like and press F5 to run the program. If you have not made any mistakes, the IDLE 以下に示すように、テキストとボタンを含む新しいウィンドウが開きます。

空を超えて Windows

  1. 最初のウィンドウのボタンをクリックすると、書き込んだテキストを含む新しいメッセージ ボックスが開きます。
  2. 「詳細を非表示/詳細を表示」ボタンをクリックして、追加テキストの表示を切り替えることができるようになりました。

As you can see, since we had not set any window title in the message box, a default title was provided by Python そのもの。

Now that it is working, let us take a look at the extra code that you have added to the previous PyQt5 example.

from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QMessageBox

これにより、PyQt5 の例で使用したさらにいくつかのウィジェット (QLabel、QPushButton、QMessage) がインポートされます。Box.

def dialog():
    mbox = QMessageBox()

    mbox.setText("Your allegiance has been noted")
    mbox.setDetailedText("You are now a disciple and subject of the all-knowing Guru")
    mbox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
            
    mbox.exec_()

ここでは、メッセージ ボックス ウィジェットを作成し、ボタンやその他のフィールドにテキストを設定する dialog というメソッドを定義しました。

特定のウィジェット (この場合はボタン PushButton) でボタンが押されると、ダイアログ メソッドがプログラムのメイン ブロックから呼び出されます。 そのボタンでトリガーされたクリック イベントにより、この関数が実行されます。 このような関数は Qt ではスロットと呼ばれます。詳しくは、 信号 (NAIST) と スロット 次の段落で説明します。

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = QWidget()
    w.resize(300,300)
    w.setWindowTitle("Guru99")

This is the main section of the app and, as in the previous example, you start by creating an instance of QApplication followed by a simple widget, i.e. an instance of QWidget.

label = QLabel(w)
    btn = QPushButton(w)

このアプリケーションには、QLabel と QPushButton という XNUMX つの新しいウィジェットが追加されました。 QLabel はウィジェット内の編集不可能なテキストまたはプレースホルダーを印刷するために使用され、QPushButton はクリック可能なボタンを作成するために使用されます。

ここで注意すべき重要な点は、label オブジェクトと btn オブジェクトを作成するときに、ウィンドウ オブジェクト (w) を QLabel と QPushButton のコンストラクターに渡していることです。 これは、PyQt5 でのネストの仕組みです。 別のウィジェット内にウィジェットを作成するには、親ウィジェットの参照を子のコンストラクターに渡します。

label.move(100,130)
btn.move(110,150)

move() は、親ウィジェットに対するウィジェットの位置を設定するために使用されます。 最初のケースでは、ラベルはウィンドウの左から 100 ピクセル、上から 130 ピクセル移動します。

同様に、ボタンはウィンドウの左から 110 ピクセル、上から 150 ピクセルの位置に配置されます。 この例はレイアウトを実現するための粗雑な方法であり、通常は運用環境では使用されません。 ここでは学習目的でのみ含まれています。 Qt は、この PyQt チュートリアルの次のセクションで詳しく説明するさまざまなレイアウトをサポートしています。

btn.clicked.connect(dialog)

Finally, this is an example of signals and slots in Qt. In GUI-based applications, functions are executed based on the actions performed by the user, like hovering over an element or clicking a button. These actions are called イベント。 app.exec_() メソッドが制御を Qt に転送することを思い出してください。 イベント ループ。 イベント ループは、イベントをリッスンし、それに応じてアクションを実行するために存在します。

ユーザーがボタンをクリックするなどのイベントが発生すると、対応する Qt ウィジェットが 信号。 これらの信号を接続できるのは、 Python 機能 (この例のダイアログ関数のように) 信号がトリガーされたときに関数が実行されるようにします。 これらの関数は呼び出されます スロット Qt 言語で。

Subsequently, the basic syntax to trigger a slot function in response to the signal from an event is as follows:

 widget.signal.connect(slot)

This means that whenever a 信号 によってトリガーされます ウィジェット、接続された スロット 関数が実行されます。 要約すると、シグナルとスロットは、オブジェクト間で通信し、コンポーネントの再利用性と対話性を促進するために Qt によって使用されます。

ウィジェットをネストし、シグナルとスロットを使用してインタラクションを実装する方法がわかったので、ここでは、PyQt アプリで使用できる便利なウィジェットとその他のクラスのリストを示します。

コンポーネントとウィジェット

PyQt には、GUI アプリの作成に使用できるウィジェットが多数あります。 ただし、PyQt5 では、クラスがさまざまなモジュールに再編成され、ライセンスが改訂されました。

Therefore, it is crucial to have a high-level view of the structure of PyQt5. In this section, you will see how PyQt5 is organized internally and learn about the different modules, libraries, and API classes provided by PyQt5.

PyQt5 ディレクトリ構造

PyQt5 ディレクトリ構造

これらは、 Pythonの Qt バインディング、具体的には PyQt5 です。

  • Qt: It combines all the classes/modules mentioned below into a single module. It considerably increases the memory used by the application. However, it is easier to manage the framework by only importing one module.
  • Qtコア: 他のモジュールで使用されるコアの非グラフィカル クラスが含まれます。 ここに、Qt イベント ループ、シグナル、スロット接続などが実装されます。
  • Qtウィジェット: Contains most of the widgets available in PyQt5.
  • QtGui: GUI コンポーネントが含まれており、QtCore モジュールを拡張します。
  • Qtネットワーク: Qt を介してネットワーク プログラミングを実装するために使用されるクラスが含まれています。 TCP サーバー、TCP ソケット、UDP ソケット、SSL 処理、ネットワーク セッション、および DNS ルックアップをサポートします。
  • Qtマルチメディア: provides low-level multimedia functionality.
  • QtSQL: SQL データベースのデータベース統合を実装します。 ODBCをサポート、 MySQL, Oracle, SQLite, PostgreSQL.

PyQt5 ウィジェット

Here is a list of the most frequently used widgets in PyQt5:

  • QLine編集: これは、ユーザーが XNUMX 行のテキストを入力できる入力フィールドです。
line = QLineEdit()
  • Qラジオボタン: This is an input field with a selectable button, similar to the radio buttons in HTML.
rad = QRadioButton("button title")
rad.setChecked(True)  #to select the button by default.
  • QコンボBox: 選択可能な項目のリストを含むドロップダウン メニューを表示するために使用されます。
drop = QComboBox(w)
drop.addItems(["item one", "item two", "item three"])
  • QチェックBox: ラジオ ボタンと同様に、ラベルの前に選択可能な四角いボックスが表示され、選択するとチェックマークが付きます。
check = QCheckBox("button title")
  • Qメニューバー: It displays a horizontal menu bar at the top of a window. You can only add objects of the QMenu class to this bar. Those QMenu objects can further contain strings, QAction objects or other QMenu objects.
  • Qツールバー: ウィンドウ内で移動できる水平バーまたはペインです。 ボタンやその他のウィジェットが含まれる場合があります。
  • Qタブ: It is used to break down the contents of a window into multiple pages that can be accessed through different tabs on top of the widget. It consists of two sections: the tab bar and the tab page.
  • Qスクロールバー: これは、ユーザーがウィンドウ内で上下にスクロールできるようにするスクロールバーを作成するために使用されます。可動スライダー、スライダーで構成されています。 trackボタンと、スライダーを上下にスクロールするための2つのボタンがあります。
scroll = QScrollBar()
  • Qスプリッター: スプリッターは、ウィジェットが適切にグループ化され、乱雑に表示されないように、ウィンドウのコンテンツを分離するために使用されます。 QSplitter は、PyQt5 で使用できる主要なレイアウト ハンドラーの XNUMX つで、コンテンツを水平方向と垂直方向の両方に分割するために使用されます。
  • Qドック: A dock widget is a sub-window with two properties: it can be moved within the main window, and it can be docked outside the parent window to another location on the screen.

レイアウトとテーマ

前の PyQt5 の例では、GUI 内のウィジェットの位置を設定するために move() メソッドとsize() メソッドのみを使用していました。

ただし、PyQt には、アプリケーションの高度なユーザー インターフェイスの作成に使用できる堅牢なレイアウト管理エンジンがあります。 このセクションでは、Qt でレイアウトの作成と管理に使用される XNUMX つの重要なクラスについて学びます。

  1. QBoxレイアウト
  2. QGridLayout

QBoxレイアウト

QBoxレイアウトは、レイアウトの子ウィジェットを水平または垂直の行に配置するために使用されます。 Q から継承する XNUMX つの対象クラスBoxレイアウトは次のとおりです。

  • QHBoxレイアウト: 子ウィジェットを水平に並べるために使用されます。
  • QVBoxレイアウト: 子ウィジェットを垂直に並べるために使用されます。

たとえば、QH に XNUMX つのボタンを並べると、次のようになります。Boxレイアウトが見えてきます。

QBoxレイアウト

import sys
from PyQt5.QtWidgets import *

if __name__ == "__main__":

    app = QApplication([])
    w = QWidget()
    w.setWindowTitle("Musketeers")

    btn1 = QPushButton("Athos")
    btn2 = QPushButton("Porthos")
    btn3 = QPushButton("Aramis")

    hbox = QHBoxLayout(w)

    hbox.addWidget(btn1)
    hbox.addWidget(btn2)
    hbox.addWidget(btn3)

    w.show()

    sys.exit(app.exec_())

QV ではこのように表示されますBoxレイアウト。

QBoxレイアウト

import sys
from PyQt5.QtWidgets import *

if __name__ == "__main__":

    app = QApplication([])
    w = QWidget()
    w.setWindowTitle("Musketeers")

    btn1 = QPushButton("Athos")
    btn2 = QPushButton("Porthos")
    btn3 = QPushButton("Aramis")

    vb = QVBoxLayout(w)

    vb.addWidget(btn1)
    vb.addWidget(btn2)
    vb.addWidget(btn3)

    w.show()

    sys.exit(app.exec_())

この時点で説明が必要な唯一の関数は、addWidget() メソッドです。 H にウィジェットを挿入するために使用されます。Box またはVBox レイアウト。 次のセクションで説明するように、異なる数のパラメータを取る他のレイアウトでも使用されます。 ウィジェットは、挿入した順序でレイアウト内に表示されます。

QGridLayout

QGridLayout は、ウィジェットがグリッド (行列や 2D 配列など) の形式でレイアウトされるインターフェイスを作成するために使用されます。 グリッド レイアウトに要素を挿入するには、行列表現を使用して、グリッド内の行と列の数、およびそれらの要素の位置を定義できます。

たとえば、3*3 グリッド (つまり、XNUMX 行 XNUMX 列のグリッド) を作成するには、次のコードを記述します。

Import sys
from PyQt5.QtWidgets import *

if __name__ == "__main__":
    app = QApplication([])

    w = QWidget()

    grid = QGridLayout(w)

    for i in range(3):
        for j in range(3):
            grid.addWidget(QPushButton("Button"),i,j)


    w.show()
    sys.exit(app.exec_())

これが出力になります:

QGridLayout

The addWidget() method in the grid layout takes these arguments:

  • グリッドに追加するウィジェット オブジェクト
  • オブジェクトの x 座標
  • オブジェクトの y 座標
  • The row-span (default = 0)
  • The col-span (default = 0)

To understand it better, you can manually insert each widget as shown below.

import sys
from PyQt5.QtWidgets import *

if __name__ == "__main__":
    app = QApplication([])

    w = QWidget()

    grid = QGridLayout(w)
    grid.addWidget(QPushButton("Button one"),0,0)
    grid.addWidget(QPushButton("Button two"),0,1)
    grid.addWidget(QPushButton("Button three"),1,0)
    grid.addWidget(QPushButton("Button four"),1,1)


    w.show()
    sys.exit(app.exec_())

グリッドは次のようになります。

QGridLayout

複数の行または列にまたがるには、rowspan パラメーターと Colspan パラメーターを addWidget() に渡すこともできます。

たとえば、

grid.addWidget(QPushButton("Button five"),2,0,1,0)

これにより、両方の列にまたがるボタンが作成されます。

QGridLayout

部門

PyQt5 には、アプリで使用できるいくつかの組み込みテーマが付属しています。 の setStyle() QApplication インスタンスで呼び出されるメソッドは、アプリケーションに特定のテーマを設定するために使用されます。

For example, adding the following line of code will change the theme of your application from default to Fusion.

app.setStyle("Fusion")

This is how the previous example will look in the Fusion Theme.

部門

Another useful function for theming your apps is the setPalette() method. Here is the code for changing the color of different widgets using setPalette().

import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QPalette

if __name__ == "__main__":
    app = QApplication([])
    app.setStyle("Fusion")
    
    qp = QPalette()
    qp.setColor(QPalette.ButtonText, Qt.black)
    qp.setColor(QPalette.Window, Qt.black)
    qp.setColor(QPalette.Button, Qt.gray)
    app.setPalette(qp)

    w = QWidget()

    grid = QGridLayout(w)
    grid.addWidget(QPushButton("Button one"),0,0)
    grid.addWidget(QPushButton("Button two"),0,1)
    grid.addWidget(QPushButton("Button three"),1,0)
    grid.addWidget(QPushButton("Button four"),1,1)


    w.show()
    sys.exit(app.exec_())

ここに結果があります。

部門

setPalette() メソッドを使用するには、まずパレットを定義する必要があります。 これは、QPalette クラスのオブジェクトを作成することによって行われます。

 qp = QPalette()

Notice that the QPalette class belongs to the QtGui module and you will need to import it for this to work. Once you have created the QPalette object, use the setColor() method to pass the name of a widget whose color you want to change and the color you want to be set.

 qp.setColor(QPalette.Window, Qt.black)

This will change the color of the window to black. After you have defined your color scheme, use the setPalette() function to apply the palette to your application.

app.setPalette(qp)

アプリの基本的なテーマを作成する場合に行う必要があるのはこれだけです。 PyQt では、スタイルシートを使用してウィジェットの外観を定義することもできます。 CSS に精通している場合は、Qt スタイル シートを使用してアプリの高度なスタイルを簡単に定義できます。

よくあるご質問

Tkinter ships with Python and suits small, simple tools. PyQt offers far more widgets, a visual designer, and a native look, making it better for large, professional desktop applications — at the cost of a steeper learning curve and GPL licensing.

Both bind the same Qt libraries and share almost identical APIs. The key difference is licensing: PyQt uses GPL or a paid commercial license, while PySide (Qt for Python) uses the LGPL, allowing closed-source distribution for free.

Qt Designer is a drag-and-drop tool that saves your layout as an XML .ui file. Convert it to Python with the pyuic5 utility, or load it at runtime using uic.loadUi().

PyQt6 binds the newer Qt 6 framework and requires fully scoped enums, such as Qt.AlignmentFlag.AlignLeft. PyQt5 targets Qt 5 and remains the most widely used version. PyQt6 also drops some deprecated modules and adds better high-DPI support.

Use PyInstaller: run pyinstaller –onefile –windowed app.py to bundle your script, PyQt5, and the Qt libraries into a single executable. The –windowed flag hides the console. fbs and cx_Freeze are popular alternatives.

PyQt5 is beginner-friendly if you know basic Python. Understanding classes, objects, and the signals-and-slots pattern helps most. Qt Designer lets you build layouts visually, so you can create working windows before mastering every widget by hand.

PyQt builds desktop front-ends for machine learning models — dashboards that load data, trigger training or inference, and display predictions, charts, or images. It pairs well with NumPy, pandas, and Matplotlib, wrapping a trained model in a friendly GUI.

Yes. GitHub Copilot autocompletes common PyQt5 patterns like QApplication setup, widget creation, and signal-slot connections from a comment or function name. Always run the generated window to confirm layouts and event handlers behave as intended.