PyQt でボタンに背景画像を設定の方法
PyQtのボタンに背景画像を設定するにはQPushButtonクラスのsetStyleSheet()メソッドを使用して、CSSスタイルで背景画像を設定します。具体的な手順は次のとおりです。
- 必要なモジュールをインポートする
from PyQt5.QtWidgets import QApplication, QPushButton
from PyQt5.QtGui import QPixmap
- QPushButtonオブジェクトを生成します。
button = QPushButton()
- バックグラウンドイメージのロード:
background_img = QPixmap("path_to_image.jpg") # 替换为你的图片路径
- 背景画像のサイズを設定する
background_img = background_img.scaled(button.size(), aspectRatioMode=Qt.IgnoreAspectRatio)
- ボタンに背景画像を適用する:
button.setStyleSheet("border-image: url(%s);" % background_img)
上述のステップは以下のように1つの関数にまとめられます。
def set_button_background(button, image_path):
button.setStyleSheet("border-image: url(%s);" % image_path)
ボタンの背景画像を設定するにはset_button_background()関数を呼び出します。
button = QPushButton()
set_button_background(button, "path_to_image.jpg") # 替换为你的图片路径
これでボタンの背景画像の設定は完了です。