PyQt5 チュートリアル - 基本ウィンドウ
胡金庫
2023年1月30日

PyQt5 基本ウィンドウ
PyQt5 で基本的なウィンドウを作成します。
import sys
from PyQt5 import QtWidgets
def basicWindow():
app = QtWidgets.QApplication(sys.argv)
windowExample = QtWidgets.QWidget()
windowExample.setWindowTitle("Basic Window Example")
windowExample.show()
sys.exit(app.exec_())
basicWindow()
from PyQt5 import QtWidgets
QtWidgets
モジュールをインポートして、グラフィカルユーザーインターフェイスにアクセスできるようにします。
app = QtWidgets.QApplication(sys.argv)
イベントループにアクセスできるアプリケーションオブジェクトを作成します。
windowExample = QtWidgets.QWidget()
次に、QtWidget
を作成する必要があります。これをトップレベルウィンドウとして使用し、必要なものをすべて備えているためです。
windowExample.setWindowTitle("Basic Window Example")
setWindowTitle
はウィンドウのタイトルを設定し、必要なときにいつでも呼び出すことができます。
windowExample.show()
このステートメントは、ウィンドウを表示します。ために必要です。
sys.exit(app.exec_())
app.exec_()
関数を使用して、イベントループを開始する必要があります。
これを行わない場合、プログラムはそれ自体で実行し続けることができないため、プログラムはまっすぐに実行されます。このイベントループは、ここからのイベントが実行されるのを待っています。
basicWindow()
次に、ウィンドウの実行を開始するために呼び出すことができる関数にすべてを入れます。
PyQt5 ウィンドウサイズの変更
ウィンドウのサイズを変更したい場合は、ウィンドウウィジェットの setGeometry()
メソッドを使用できます。
import sys
from PyQt5 import QtWidgets
def basicWindow():
app = QtWidgets.QApplication(sys.argv)
windowExample = QtWidgets.QWidget()
windowExample.setGeometry(0, 0, 400, 400)
windowExample.setWindowTitle("Basic Window Example")
windowExample.show()
sys.exit(app.exec_())
basicWindow()
windowExample.setGeometry(0, 0, 400, 400)
setGeometry()
メソッドは、4つの整数を入力引数として受け取ります。
- X 座標
- Y 座標
- フレームの幅
- フレームの高さ
したがって、ウィンドウサイズの例は 400 x 400
ピクセルです。
PyQt5 ウィンドウの追加アイコン
import sys
from PyQt5 import QtWidgets, QtGui
def basicWindow():
app = QtWidgets.QApplication(sys.argv)
windowExample = QtWidgets.QWidget()
windowExample.setWindowTitle("Basic Window Example")
windowExample.setWindowIcon(QtGui.QIcon("python.jpg"))
windowExample.show()
sys.exit(app.exec_())
basicWindow()
windowExample.setWindowIcon(QtGui.QIcon("python.jpg"))
ウィンドウアイコンを python.jpg
に設定します。setWindowIcon
メソッドのパラメーターは QtGui
モジュールの QIcon
オブジェクトです。
チュートリアルを楽しんでいますか? <a href="https://www.youtube.com/@delftstack/?sub_confirmation=1" style="color: #a94442; font-weight: bold; text-decoration: underline;">DelftStackをチャンネル登録</a> して、高品質な動画ガイドをさらに制作するためのサポートをお願いします。 Subscribe